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
50,669,200
![enter image description here](https://i.stack.imgur.com/B0NS3.png) I need your help in understanding the distribution plot. I was going through tutorial on [this link](http://devarea.com/python-machine-learning-example-linear-regression/#.WxQmilMvxsN). At the end of the post they have mentioned: > > We can see from the graph that most of the times the predictions were correct (difference = 0). > > > So I am not able to understand how are they analyzing the graph.
2018/06/03
[ "https://Stackoverflow.com/questions/50669200", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8285020/" ]
Reading through your comments, it is difficult to understand where exactly you are having a problem. I'm going to assume it's because you did not know how to write the other initializer due to your first comment: ``` `my object is simple "stuct" and I could not make "(dictionary: data)" -call.` ``` Here's the initializer you could use: ``` extension User { init?(dictionary: [String: Any]){ guard let firstName = dictionary["firstName"] as? String else { return nil } guard let lastName = dictionary["lastName"] as? String else { return nil } } self.init(firstName: firstName, lastName: lastName) } ```
I finally found that simply swift firestore sdk still missing that function but it seams like it is in works and you can find discussion about that in [here](https://github.com/firebase/firebase-ios-sdk/issues/627) > > ...We've had something like this on our radar for a bit. Essentially we want to provide an equivalent to the Android DocumentSnapshot.toObject. > > > , hopefully it's done soon...
21,611,328
I'm trying to unzip a file with `7z.exe` and the password contains special characters on it EX. `&)kra932(lk0¤23` By executing the following command: ``` subprocess.call(['7z.exe', 'x', '-y', '-ps^&)kratsaslkd932(lkasdf930¤23', 'file.zip']) ``` `7z.exe` launches fine but it says the password is wrong. This is a file I created and it is driving me nuts. If I run the command on the windows command line it runs fine ``` 7z.exe x -y -ps^&)kratsaslkd932(lkasdf930¤23 file.zip ``` How can I make python escape the `&` character? --- @Wim the issue occurs & on the password, because when i execute ``` 7z.exe x -y -ps^&)kratsaslkd932(lkasdf930¤23 file.zip ``` it says invalid command `')kratsaslkd932(lkasdf930¤23'` im using python 2.76, cant upgrade to 3.x due to company tools that only run on 2.76
2014/02/06
[ "https://Stackoverflow.com/questions/21611328", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2065094/" ]
There is a big security risk in passing the password on the command line. With administrative rights, it is possible to retrieve that information (startup info object) and extract the password. A better solution is to open 7zip as a process, and feed the password into its standard input. Here is an example of a command line that compresses "source.txt" into "dest.7z": ``` CMD = ['c:\\Program Files\\7-Zip\\7z.exe', 'a', '-t7z', '-p', 'c:\\source.txt', 'd:\\dest.7z'] PASSWORD = "Nj@8G86Tuj#a" ``` First you need to convert the password into an input string. Please note that 7-zip expects the password to by typed into the terminal. You can use special characters as long as they can be represented in your terminal. The encoding of the terminal matters! For example, on Hungarian Windows, you might want to use "cp1250" encoding. In all cases, the standard input is a binary file, and it expects a binary string ("bytes" in Python 3). If you want to be on the safe side, you can restrict passwords to plain ascii and create your input like this: ``` input = (PASSWORD + "\r\n").encode("ascii") ``` If you know the encoding of your terminal, then you can convert the password to that encoding. You will also be able to detect if the password cannot be used with the system's encoding. (And by the way, it also means that it cannot be used interactively either.) (Last time I checked, the terminal encoding was different for different regional settings on Windows. Maybe there is a trick to change that to UTF-8, but I'm not sure how.) This is how you execute a command: ``` import subprocess import typing def execute(cmd : typing.List[str], input: typing.Optional[bytes] = None, verbose=False, debug=False, normal_priority=False): if verbose: print(cmd) creationflags = subprocess.CREATE_NO_WINDOW if normal_priority: creationflags |= subprocess.NORMAL_PRIORITY_CLASS else: creationflags |= subprocess.BELOW_NORMAL_PRIORITY_CLASS if debug: process = subprocess.Popen(cmd, shell=False, stdout=sys.stdout, stderr=sys.stderr, stdin=subprocess.PIPE, creationflags=creationflags) else: process = subprocess.Popen(cmd, shell=False, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, stdin=subprocess.PIPE, creationflags=creationflags) if input: process.stdin.write(input) process.stdin.flush() returncode = process.wait() if returncode: raise OSError(returncode) CMD = ['c:\\Program Files\\7-Zip\\7z.exe', 'a', '-t7z', '-p', 'c:\\source.txt', 'd:\\dest.7z'] PASSWORD = "Nj@8G86Tuj#a" input = (PASSWORD + "\r\n").encode("ascii") execute(CMD, input) ``` This also shows how to lower process priority (which is usually a good idea when compressing large amounts of data), and it also shows how to forward standard output and standard error to the console. The absolute correct solution would be to load 7-zip DLL and use its API. (I did not check but that can probably use 8 bit binary strings for passwords.) Note: this example is for Python 3 but the same can be done with Python 2.
I'd suggest using a raw string and the shlex module (esp. on Windows) and NOT supporting any encoding other than ASCII. ``` import shlex import subprocess cmd = r'7z.exe x -y -p^&moreASCIIpasswordchars file.zip' subprocess.call(shlex.split(cmd)) ``` Back to the non-ASCII character issue... I'm pretty sure in Python versions < 3 you simply can't use non-ASCII characters. I'm no C expert, but notice the difference between [2.7](http://hg.python.org/cpython/file/712b4665955d/PC/_subprocess.c#l420) and [3.3](http://hg.python.org/cpython/file/b5ad525076eb/Modules/_winapi.c#l579). The former uses a "standard" char while the later uses a wide char.
21,611,328
I'm trying to unzip a file with `7z.exe` and the password contains special characters on it EX. `&)kra932(lk0¤23` By executing the following command: ``` subprocess.call(['7z.exe', 'x', '-y', '-ps^&)kratsaslkd932(lkasdf930¤23', 'file.zip']) ``` `7z.exe` launches fine but it says the password is wrong. This is a file I created and it is driving me nuts. If I run the command on the windows command line it runs fine ``` 7z.exe x -y -ps^&)kratsaslkd932(lkasdf930¤23 file.zip ``` How can I make python escape the `&` character? --- @Wim the issue occurs & on the password, because when i execute ``` 7z.exe x -y -ps^&)kratsaslkd932(lkasdf930¤23 file.zip ``` it says invalid command `')kratsaslkd932(lkasdf930¤23'` im using python 2.76, cant upgrade to 3.x due to company tools that only run on 2.76
2014/02/06
[ "https://Stackoverflow.com/questions/21611328", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2065094/" ]
There is a big security risk in passing the password on the command line. With administrative rights, it is possible to retrieve that information (startup info object) and extract the password. A better solution is to open 7zip as a process, and feed the password into its standard input. Here is an example of a command line that compresses "source.txt" into "dest.7z": ``` CMD = ['c:\\Program Files\\7-Zip\\7z.exe', 'a', '-t7z', '-p', 'c:\\source.txt', 'd:\\dest.7z'] PASSWORD = "Nj@8G86Tuj#a" ``` First you need to convert the password into an input string. Please note that 7-zip expects the password to by typed into the terminal. You can use special characters as long as they can be represented in your terminal. The encoding of the terminal matters! For example, on Hungarian Windows, you might want to use "cp1250" encoding. In all cases, the standard input is a binary file, and it expects a binary string ("bytes" in Python 3). If you want to be on the safe side, you can restrict passwords to plain ascii and create your input like this: ``` input = (PASSWORD + "\r\n").encode("ascii") ``` If you know the encoding of your terminal, then you can convert the password to that encoding. You will also be able to detect if the password cannot be used with the system's encoding. (And by the way, it also means that it cannot be used interactively either.) (Last time I checked, the terminal encoding was different for different regional settings on Windows. Maybe there is a trick to change that to UTF-8, but I'm not sure how.) This is how you execute a command: ``` import subprocess import typing def execute(cmd : typing.List[str], input: typing.Optional[bytes] = None, verbose=False, debug=False, normal_priority=False): if verbose: print(cmd) creationflags = subprocess.CREATE_NO_WINDOW if normal_priority: creationflags |= subprocess.NORMAL_PRIORITY_CLASS else: creationflags |= subprocess.BELOW_NORMAL_PRIORITY_CLASS if debug: process = subprocess.Popen(cmd, shell=False, stdout=sys.stdout, stderr=sys.stderr, stdin=subprocess.PIPE, creationflags=creationflags) else: process = subprocess.Popen(cmd, shell=False, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, stdin=subprocess.PIPE, creationflags=creationflags) if input: process.stdin.write(input) process.stdin.flush() returncode = process.wait() if returncode: raise OSError(returncode) CMD = ['c:\\Program Files\\7-Zip\\7z.exe', 'a', '-t7z', '-p', 'c:\\source.txt', 'd:\\dest.7z'] PASSWORD = "Nj@8G86Tuj#a" input = (PASSWORD + "\r\n").encode("ascii") execute(CMD, input) ``` This also shows how to lower process priority (which is usually a good idea when compressing large amounts of data), and it also shows how to forward standard output and standard error to the console. The absolute correct solution would be to load 7-zip DLL and use its API. (I did not check but that can probably use 8 bit binary strings for passwords.) Note: this example is for Python 3 but the same can be done with Python 2.
Try to put double quotes between your password, otherwise the cmd parser would any parse special character as is instead of taking it as part of the password. For example, `7z.exe x -y -ps^&)kratsaslkd932(lkasdf930¤23 file.zip` won't work. But `7z.exe x -y -p"s^&)kratsaslkd932(lkasdf930¤23" file.zip` would definitely work.
74,611,463
I have this code ``` import numpy a=numpy.pad(numpy.empty([8,8]), 1, constant_values=1) print(a) ``` 50% of the times I execute it it prints a normal array, 50% of times it prints this ``` [[ 1.00000000e+000 1.00000000e+000 1.00000000e+000 1.00000000e+000 1.00000000e+000 1.00000000e+000 1.00000000e+000 1.00000000e+000 1.00000000e+000 1.00000000e+000] [ 1.00000000e+000 3.25639960e-265 2.03709399e-231 -7.49281680e-111 9.57832017e-299 8.17611616e-093 9.57832017e-299 1.31887592e+066 -2.29724802e+236 1.00000000e+000] [ 1.00000000e+000 5.11889256e-014 -2.29724802e+236 2.19853714e-004 -2.29724802e+236 -9.20964279e+232 2.37057719e+043 1.48921177e+048 5.29583156e-235 1.00000000e+000] [ 1.00000000e+000 6.37391724e+057 5.68896808e-235 2.73626021e+067 6.08210460e-235 1.17578020e+077 6.66029790e-235 7.05235822e-235 2.13106310e-308 1.00000000e+000] [ 1.00000000e+000 7.83852638e-235 2.13214956e-308 8.62479942e-235 2.13323602e-308 9.41107246e-235 2.13432248e-308 1.61214828e+063 1.35001671e-284 1.00000000e+000] [ 1.00000000e+000 7.20990215e-264 9.57831969e-299 5.06352214e+139 3.18093720e+144 1.21642092e-234 1.25562635e-234 2.13866833e-308 1.41045067e-234 1.00000000e+000] [ 1.00000000e+000 2.13975479e-308 1.56770528e-234 2.14084125e-308 1.72495988e-234 2.14192771e-308 1.88221449e-234 2.14301418e-308 2.03946910e-234 1.00000000e+000] [ 1.00000000e+000 2.14410064e-308 2.19672371e-234 2.14518710e-308 2.35397832e-234 2.14627356e-308 1.61656736e+063 1.35004493e-284 7.20998544e-264 1.00000000e+000] [ 1.00000000e+000 3.93674833e-241 7.20999301e-264 6.00700127e-246 2.03709519e-231 -5.20176578e-111 9.57832021e-299 5.66452894e+075 -2.29724802e+236 1.00000000e+000] [ 1.00000000e+000 1.00000000e+000 1.00000000e+000 1.00000000e+000 1.00000000e+000 1.00000000e+000 1.00000000e+000 1.00000000e+000 1.00000000e+000 1.00000000e+000]] ``` what is worse, when i do .astype(int) it keeps doing this ``` [[ 1 1 1 1 1 1 1 1 1 1] [ 1 0 0 0 -2147483648 0 -2147483648 0 0 1] [ 1 0 0 -2147483648 0 0 0 0 -2147483648 1] [ 1 0 0 0 0 -2147483648 0 0 0 1] [ 1 0 0 0 0 0 -2147483648 0 0 1] [ 1 0 0 -2147483648 0 0 0 0 0 1] [ 1 0 -2147483648 0 0 0 -2147483648 0 -2147483648 1] [ 1 0 -2147483648 -2147483648 0 -2147483648 0 0 -2147483648 1] [ 1 0 0 0 0 0 0 0 0 1] [ 1 1 1 1 1 1 1 1 1 1]] ``` tried on normal python 3.11 and anaconda 3.9. I googled but I couldn't find a way to fix this, so any help would be much appreciated. The post needs to have more text so that it isn't "mostly code" and it lets me post it. I would like to know if there are any good ways to solve the issue I've described. As I wrote, I tested it on two different versions of python. Unfortunately, both lead to the same issue.
2022/11/29
[ "https://Stackoverflow.com/questions/74611463", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15673832/" ]
You can use [apache\_beam.io.jdbc](https://beam.apache.org/releases/pydoc/current/apache_beam.io.jdbc.html) to read from your MySQL database, and the [BigQuery I/O](https://beam.apache.org/documentation/io/built-in/google-bigquery/) to write on BigQuery. Beam knowledge is expected, so I recommend looking at [Apache Beam Programming Guide](https://beam.apache.org/documentation/programming-guide/) first. If you are looking for something pre-built, we have the [JDBC to BigQuery Google-provided template](https://cloud.google.com/dataflow/docs/guides/templates/provided-batch#java-database-connectivity-jdbc-to-bigquery), which is open-source ([here](https://github.com/GoogleCloudPlatform/DataflowTemplates/blob/main/v2/googlecloud-to-googlecloud/src/main/java/com/google/cloud/teleport/v2/templates/JdbcToBigQuery.java)), but it is written in Java.
If you only want to copy data from `MySQL` to `BigQuery`, you can firstly export your `MySql` data to `Cloud Storage`, then load this file to a `BigQuery` table. I think no need using `Dataflow` in this case because you don't have complex transformations and business logics. It only corresponds to a copy. [Export](https://cloud.google.com/sql/docs/mysql/import-export/import-export-csv#customize-csv-format) the `MySQL` data to `Cloud Storage` via a `sql` query and `gcloud` cli : ```bash gcloud sql export csv INSTANCE_NAME gs://BUCKET_NAME/FILE_NAME \ --database=DATABASE_NAME \ --offload \ --query=SELECT_QUERY \ --quote="22" \ --escape="5C" \ --fields-terminated-by="2C" \ --lines-terminated-by="0A" ``` [Load](https://cloud.google.com/bigquery/docs/loading-data-cloud-storage-csv#loading_csv_data_into_a_table) the `csv` file to a `BigQuery` table via `gcloud` cli and `bq` : ```bash bq load \ --source_format=CSV \ mydataset.mytable \ gs://mybucket/mydata.csv \ ./myschema.json ``` `./myschema.json` is the `BigQuery` table schema.
62,482,387
I have done everything the documentation says to. * I added pip path and it is working but the python command is not working. [Image of path to my python38 DLL](https://i.stack.imgur.com/HSGzo.png) * The pip path which I added: `C:\Users\Harshal\AppData\Local\Programs\Python\Python38\Scripts python path : C:\Users\Harshal\AppData\Local\Programs\Python\Python38` * python command is not working .pip works
2020/06/20
[ "https://Stackoverflow.com/questions/62482387", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10537108/" ]
In some cases, `py` command works as well as `python` command, so you can try `py`: ``` py -V py -m pip # this is for pip, exactly for this python version ```
Add your python to system environment variables like your path. or Reinstall python and check the Add to path Checkbox while installing ``` Add to path ```
64,652,322
I'm currently struggling with python's bit operations as in python3 there is no difference anymore between 32bit integers (int) and 64bit integers (long). What I want is an **efficient** function that takes any integer and cuts the most significant 32 bits and then converts these 32 bits back to an integer with the correct sign. Example 1: ``` >>> bin_string = bin(3293670138 & 0b11111111111111111111111111111111) >>> print(bin_string) 0b11000100010100010110101011111010 >>> print(int(bin_string,2)) 3293670138 ``` But the result should have been -1001297158 since converting '11000100010100010110101011111010' in a 32 bits integer is a negative number. I already have my own solution: ``` def int32(val): if val >= -2**31 and val <= 2**31-1: return val bin_string = bin(val & 0b11111111111111111111111111111111) int_val = int(bin_string,2) if int_val > 2147483647: return -(~(int_val-1)%2**32) return int_val ``` However, I would like to know if someone has a more elegant and performant idea. Thank you in advance!
2020/11/02
[ "https://Stackoverflow.com/questions/64652322", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10684977/" ]
Significantly simpler solution: Let [`ctypes`](https://docs.python.org/3/library/ctypes.html) do the work for you. ``` from ctypes import c_int32 def int32(val): return c_int32(val).value ``` That just constructs a `c_int32` type from the provided Python `int`, which truncates as you desire, then extracts the value back out as a normal Python `int` type. The time taken is less than that of your existing function for values that actually require trimming. On my machine, it takes about 155-175 ns reliably, where your function is more variable, taking around 310-320 ns for positive values, and 405-415 ns for negative values. It *is* slower for values that don't require trimming though; your code excludes them relatively cheaply (I improved it slightly by changing the test to `if -2 ** 31 <= val < 2 ** 31:`), taking ~75 ns, but this code does the conversion no matter what, taking the same roughly fixed amount of time. If numbers usually fit, and performance is critical, you can short cut out the way your original code (with slightly modification from me) did: ``` def int32(val): if -2 ** 31 <= val < 2 ** 31: return val return c_int32(val).value ``` That makes the "must truncate" case slightly slower (just under 200 ns) in exchange for making the "no truncation needed" case faster (below 80 ns). Importantly, either way, it's fairly simple. It doesn't involve maintaining complicated code, and it's largely self-documenting; you tell it to make a signed 32 bit int, and it does so.
use bitstring library which is excellent. ``` from bitstring import BitArray x = BitArray(bin='11000100010100010110101011111010') print(x.int) ```
20,534,999
Here is an example of failure from a shell. ``` >>> from traits.api import Dict >>> d=Dict() >>> d['Foo']='BAR' Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'Dict' object does not support item assignment ``` I have been searching all over the web, and there is no indication of how to use Dict. I am trying to write a simple app that displays the contents of a python dictionary. This link ([Defining view elements from dictionary elements in TraitsUI](https://stackoverflow.com/questions/19228631/defining-view-elements-from-dictionary-elements-in-traitsui)) was moderately helpful except for the fact that the dictionary gets updated on some poll\_interval and if I use the solution there (wrapping a normal python dict in a class derived from HasTraits) the display does not update when the underlying dictionary gets updated. Here are the relevant parts of what I have right now. The last class can pretty much be ignored, the only reason I included it is to help understand how I intend to use the Dict. pyNetObjDisplay.run\_ext() gets called once per loop from the base classes run() method ``` class DictContainer(HasTraits): _dict = {} def __getattr__(self, key): return self._dict[key] def __getitem__(self, key): return self._dict[key] def __setitem__(self, key, value): self._dict[key] = value def __delitem__(self, key, value): del self._dict[key] def __str__(self): return self._dict.__str__() def __repr__(self): return self._dict.__repr__() def has_key(self, key): return self._dict.has_key(key) class displayWindow(HasTraits): _remote_data = Instance(DictContainer) _messages = Str('', desc='Field to display messages to the user.', label='Messages', multi_line=True) def __remote_data_default(self): tempDict = DictContainer() tempDict._dict = Dict #tempDict['FOO'] = 'BAR' sys.stderr.write('SETTING DEFAULT DICTIONARY:\t%s\n' % tempDict) return tempDict def __messages_default(self): tempStr = Str() tempStr = '' return tempStr def traits_view(self): return View( Item('object._remote_data', editor=ValueEditor()), Item('object._messages'), resizable=True ) class pyNetObjDisplay(pyNetObject.pyNetObjPubClient): '''A derived pyNetObjPubClient that stores remote data in a dictionary and displays it using traitsui.''' def __init__(self, hostname='localhost', port=54322, service='pyNetObject', poll_int=10.0): self._display = displayWindow() self.poll_int = poll_int super(pyNetObjDisplay, self).__init__(hostname, port, service) self._ui_running = False self._ui_pid = 0 ### For Testing Only, REMOVE THESE LINES ### self.connect() self.ns_subscribe(service, 'FOO', poll_int) self.ns_subscribe(service, 'BAR', poll_int) self.ns_subscribe(service, 'BAZ', poll_int) ############################################ def run_ext(self): if not self._ui_running: self._ui_running = True self._ui_pid = os.fork() if not self._ui_pid: time.sleep(1.25*self.poll_int) self._display.configure_traits() for ((service, namespace, key), value) in self._object_buffer: sys.stderr.write('TEST:\t' + str(self._display._remote_data) + '\n') if not self._display._remote_data.has_key(service): self._display._remote_data[service] = {} if not self._display._remote_data[service].has_key(namespace): #self._remote_data[service][namespace] = {} self._display._remote_data[service][namespace] = {} self._display._remote_data[service][namespace][key] = value msg = 'Got Published ((service, namespace, key), value) pair:\t((%s, %s, %s), %s)\n' % (service, namespace, key, value) sys.stderr.write(msg) self._display._messages += msg sys.stderr.write('REMOTE DATA:\n' + str(self._display._remote_data) self._object_buffer = [] ```
2013/12/12
[ "https://Stackoverflow.com/questions/20534999", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2121874/" ]
I think your basic problem has to do with notification issues for traits that live outside the model object, and not with "how to access those objects" per se [edit: actually no this is not your problem at all! But it is what I thought you were trying to do when I read your question with my biased mentality towards problems I have seen before and in any case my suggested solution will still work]. I have run into this sort of problem recently because of how I decided to design my program (with code describing a GUI separated modularly from the very complex sets of data that it can contain). You may have found my other questions, as you found the first one. Having lots of data live in a complex data hierarchy away from the GUI is not the design that traitsui has in mind for your application and it causes all kinds of problems with notifications. Having a flatter design where GUI information is integrated into the different parts of your program more directly is the design solution. I think that various workarounds might be possible for this in general (I have used some for instance in [enabled\_when listening outside model object](https://stackoverflow.com/questions/20409629/enabled-when-listening-outside-model-object)) that don't involve dictionaries. I'm not sure what the most design friendly solution to your problem with dictionaries is, but one thing that works and doesn't interfere a lot with your design (but it is still a "somewhat annoying" solution) is to make everything in a dictionary be a HasTraits and thus tag it as listenable. Like so: ``` from traits.api import * from traitsui.api import * from traitsui.ui_editors.array_view_editor import ArrayViewEditor import numpy as np class DContainer(HasTraits): _dict=Dict def __getattr__(self, k): if k in self._dict: return self._dict[k] class DItem(HasTraits): _item=Any def __init__(self,item): super(DItem,self).__init__() self._item=item def setitem(self,val): self._item=val def getitem(self): return self._item def traits_view(self): return View(Item('_item',editor=ArrayViewEditor())) class LargeApplication(HasTraits): d=Instance(DContainer) stupid_listener=Any bn=Button('CLICKME') def _d_default(self): d=DContainer() d._dict={'a_stat':DItem(np.random.random((10,1))), 'b_stat':DItem(np.random.random((10,10)))} return d def traits_view(self): v=View( Item('object.d.a_stat',editor=InstanceEditor(),style='custom'), Item('bn'), height=500,width=500) return v def _bn_fired(self): self.d.a_stat.setitem(np.random.random((10,1))) LargeApplication().configure_traits() ```
Okay, I found the answer (kindof) in this question: [Traits List not reporting items added or removed](https://stackoverflow.com/questions/19041426/traits-list-not-reporting-items-added-or-removed) when including Dict or List objects as attributes in a class one should NOT do it this way: ``` class Foo(HasTraits): def __init__(self): ### This will not work as expected! self.bar = Dict(desc='Description.', label='Name', value={}) ``` Instead do this: ``` class Foo(HasTraits): def __init__(self): self.add_trait('bar', Dict(desc='Description.', label='Name', value={}) ) ``` Now the following will work: ``` >>> f = Foo() >>> f.bar['baz']='boo' >>> f.bar['baz'] 'boo' ``` Unfortunately for some reason the GUI generated with configure\_traits() does not update it's view when the underlying data changes. Here is some test code that demonstrates the problem: ``` import os import time import sys from traits.api import HasTraits, Str, Dict from traitsui.api import View, Item, ValueEditor class displayWindow(HasTraits): def __init__(self, **traits): super(displayWindow, self).__init__(**traits) self.add_trait('_remote_data', Dict(desc='Dictionary to store remote data in.', label='Data', value={}) ) self.add_trait('_messages', Str(desc='Field to display messages to the user.', label='Messages', multi_line=True, value='') ) def traits_view(self): return View( Item('object._remote_data', editor=ValueEditor()), Item('object._messages'), resizable=True ) class testObj(object): def __init__(self): super(testObj, self).__init__() self._display = displayWindow() self._ui_pid = 0 def run(self): ### Run the GUI in the background self._ui_pid = os.fork() if not self._ui_pid: self._display.configure_traits() i = 0 while True: self._display._remote_data[str(i)] = i msg = 'Added (key,value):\t("%s", %s)\n' % (str(i), i, ) self._display._messages += msg sys.stderr.write(msg) time.sleep(5.0) i+=1 if __name__ == '__main__': f = testObj() f.run() ```
66,047,199
So what i am basically trying to do is groups a set of mongo docs having the same `key:value` pair and return them in the form of a list of list. EX: ``` {"client":"abp","product":"a"},{"client":"aaj","product":"b"},{"client":"abp","product":"c"} ``` Output: ``` {"result": [ [{"client":"abp","product":"a"},{"client":"abp","product":"c"}], [{"client":"aaj","product":"b"}] ] } ``` Mongo query or any other logic in python would help. Thanks in advance.
2021/02/04
[ "https://Stackoverflow.com/questions/66047199", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12408855/" ]
I would group by client and then create and array of product using $push. $push allows you to insert each grouped object in an array. ``` db.yourcollection.aggregate([ { $group: { _id: '$client', products: {$push: {client: '$client', product: '$product'}} } }]) ```
``` from operator import itemgetter from itertools import groupby x=[{"client":"abp","product":"a"},{"client":"aaj","product":"b"},{"client":"abp","product":"c"}] x.sort(key=itemgetter('client'),reverse=True) d=[list(g) for (k,g) in groupby(x,itemgetter('client'))] final = {} final['result']=d Output: {'result': [[{'client': 'abp', 'product': 'a'}, {'client': 'abp', 'product': 'c'}], [{'client': 'aaj', 'product': 'b'}]] ```
34,651,824
Currently `--resize` flag that I created is boolean, and means that all my objects will be resized: ``` parser.add_argument("--resize", action="store_true", help="Do dictionary resize") # ... # if resize flag is true I'm re-sizing all objects if args.resize: for object in my_obects: object.do_resize() ``` Is there a way implement argparse argument that if passed as boolean flag (`--resize`) will return true, but if passed with value (`--resize 10`), will contain value. Example: 1. `python ./my_script.py --resize # Will contain True that means, resize all the objects` 2. `python ./my_script.py --resize <index> # Will contain index, that means resize only specific object`
2016/01/07
[ "https://Stackoverflow.com/questions/34651824", "https://Stackoverflow.com", "https://Stackoverflow.com/users/524743/" ]
In order to optionally accept a value, you need to set [`nargs`](https://docs.python.org/2/library/argparse.html#nargs) to `'?'`. This will make the argument consume one value if it is specified. If the argument is specified but without value, then the argument will be assigned the argument’s [`const`](https://docs.python.org/3/library/argparse.html#const) value, so that’s what you need to specify too: ``` parser = argparse.ArgumentParser() parser.add_argument('--resize', nargs='?', const=True) ``` There are now three cases for this argument: 1. Not specified: The argument will get its [default value](https://docs.python.org/3/library/argparse.html#default) (`None` by default): ``` >>> parser.parse_args(''.split()) Namespace(resize=None) ``` 2. Specified without a value: The argument will get its const value: ``` >>> parser.parse_args('--resize'.split()) Namespace(resize=True) ``` 3. Specified with a value: The argument will get the specified value: ``` >>> parser.parse_args('--resize 123'.split()) Namespace(resize='123') ``` Since you are looking for an index, you can also specify `type=int` so that the argument value will be automatically parsed as an integer. This will not affect the default or const case, so you still get `None` or `True` in those cases: ``` >>> parser = argparse.ArgumentParser() >>> parser.add_argument('--resize', nargs='?', type=int, const=True) >>> parser.parse_args('--resize 123'.split()) Namespace(resize=123) ``` --- Your usage would then look something like this: ``` if args.resize is True: for object in my_objects: object.do_resize() elif args.resize: my_objects[args.resize].do_resize() ```
You can add `default=False`, `const=True` and `nargs='?'` to the argument definition and remove `action`. This way if you don't pass `--resize` it will store False, if you pass `--resize` with no argument will store `True` and otherwise the passed argument. Still you will have to refactor the code a bit to know if you have index to delete or delete all objects.
34,651,824
Currently `--resize` flag that I created is boolean, and means that all my objects will be resized: ``` parser.add_argument("--resize", action="store_true", help="Do dictionary resize") # ... # if resize flag is true I'm re-sizing all objects if args.resize: for object in my_obects: object.do_resize() ``` Is there a way implement argparse argument that if passed as boolean flag (`--resize`) will return true, but if passed with value (`--resize 10`), will contain value. Example: 1. `python ./my_script.py --resize # Will contain True that means, resize all the objects` 2. `python ./my_script.py --resize <index> # Will contain index, that means resize only specific object`
2016/01/07
[ "https://Stackoverflow.com/questions/34651824", "https://Stackoverflow.com", "https://Stackoverflow.com/users/524743/" ]
In order to optionally accept a value, you need to set [`nargs`](https://docs.python.org/2/library/argparse.html#nargs) to `'?'`. This will make the argument consume one value if it is specified. If the argument is specified but without value, then the argument will be assigned the argument’s [`const`](https://docs.python.org/3/library/argparse.html#const) value, so that’s what you need to specify too: ``` parser = argparse.ArgumentParser() parser.add_argument('--resize', nargs='?', const=True) ``` There are now three cases for this argument: 1. Not specified: The argument will get its [default value](https://docs.python.org/3/library/argparse.html#default) (`None` by default): ``` >>> parser.parse_args(''.split()) Namespace(resize=None) ``` 2. Specified without a value: The argument will get its const value: ``` >>> parser.parse_args('--resize'.split()) Namespace(resize=True) ``` 3. Specified with a value: The argument will get the specified value: ``` >>> parser.parse_args('--resize 123'.split()) Namespace(resize='123') ``` Since you are looking for an index, you can also specify `type=int` so that the argument value will be automatically parsed as an integer. This will not affect the default or const case, so you still get `None` or `True` in those cases: ``` >>> parser = argparse.ArgumentParser() >>> parser.add_argument('--resize', nargs='?', type=int, const=True) >>> parser.parse_args('--resize 123'.split()) Namespace(resize=123) ``` --- Your usage would then look something like this: ``` if args.resize is True: for object in my_objects: object.do_resize() elif args.resize: my_objects[args.resize].do_resize() ```
Use `nargs` to accept different number of command-line arguments Use `default` and `const` to set the default value of resize see here for details: <https://docs.python.org/3/library/argparse.html#nargs> ``` parser.add_argument('-resize', dest='resize', type=int, nargs='?', default=False, const=True) >>tmp.py -resize 1 args.resize: 1 >>tmp.py -resize args.resize: True >>tmp.py args.resize: False ```
24,818,096
I am new to python app development. When I tried a code I'm not able to see its output. My sample code is: ``` class name: def __init__(self): x = '' y = '' print x,y ``` When i called the above function like ``` some = name() some.x = 'yeah' some.x.y = 'hell' ``` When i called `some.x` it works fine but when i called `some.x.y = 'hell'` it shows error like ``` Traceback (most recent call last): File "<pyshell#5>", line 1, in <module> some.x.y = 'hell' AttributeError: 'str' object has no attribute 'y' ``` Hope you guys can help me out.
2014/07/18
[ "https://Stackoverflow.com/questions/24818096", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3843420/" ]
First of all, you are defining the class with the wrong way, you should; ``` class name: def __init__(self): self.x = '' self.y = '' print x,y ``` Then, you are calling the wrong way, you should; ``` some = name() some.x = 'yeah' some.y = 'hell' ``` The problem is, `x` and `y` are `strings`. If you want to `some.x.y` for some reason, you should define `x` on your own.In other words, you can't use `some.x.y` for now. Ok, you still need for `some.x.y`; ``` class name: def __init__(self): pass some = name() some.x = name() some.x.y = "foo" print some.x.y >>> foo ```
`x` and `y` are two different variables on your instance `some`. When you call `some.x`, you are returning the string `'yeah'`. And then you call `.y`, you are actually trying to do `'yeah'.y`, which is why it says string object has no attribute `y`. So what you want to do is: ``` some = name() some.x = 'hell' some.y = 'yeah' print some.x, some.y ```
24,818,096
I am new to python app development. When I tried a code I'm not able to see its output. My sample code is: ``` class name: def __init__(self): x = '' y = '' print x,y ``` When i called the above function like ``` some = name() some.x = 'yeah' some.x.y = 'hell' ``` When i called `some.x` it works fine but when i called `some.x.y = 'hell'` it shows error like ``` Traceback (most recent call last): File "<pyshell#5>", line 1, in <module> some.x.y = 'hell' AttributeError: 'str' object has no attribute 'y' ``` Hope you guys can help me out.
2014/07/18
[ "https://Stackoverflow.com/questions/24818096", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3843420/" ]
`x` and `y` are two different variables on your instance `some`. When you call `some.x`, you are returning the string `'yeah'`. And then you call `.y`, you are actually trying to do `'yeah'.y`, which is why it says string object has no attribute `y`. So what you want to do is: ``` some = name() some.x = 'hell' some.y = 'yeah' print some.x, some.y ```
These are different variables. So when you do chain .y onto some.x you are looking for a member variable y of a string which does not exist ``` some = name() some.x = 'yeah' some.y = 'hell' ``` if you want to make a single string out of both x and y you can use + to concatenate them together as follows ``` s = some.x + ' ' + some.y print s # prints out "yeah hell" class name: def __init__(self): x = '' y = '' def ___str__(self): print x + ' ' y ``` now you can print the class and get ``` print some # prints "yeah hell" ```
24,818,096
I am new to python app development. When I tried a code I'm not able to see its output. My sample code is: ``` class name: def __init__(self): x = '' y = '' print x,y ``` When i called the above function like ``` some = name() some.x = 'yeah' some.x.y = 'hell' ``` When i called `some.x` it works fine but when i called `some.x.y = 'hell'` it shows error like ``` Traceback (most recent call last): File "<pyshell#5>", line 1, in <module> some.x.y = 'hell' AttributeError: 'str' object has no attribute 'y' ``` Hope you guys can help me out.
2014/07/18
[ "https://Stackoverflow.com/questions/24818096", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3843420/" ]
`x` and `y` are two different variables on your instance `some`. When you call `some.x`, you are returning the string `'yeah'`. And then you call `.y`, you are actually trying to do `'yeah'.y`, which is why it says string object has no attribute `y`. So what you want to do is: ``` some = name() some.x = 'hell' some.y = 'yeah' print some.x, some.y ```
When you perform `some.x` you are no longer dealing with the `some`, you are dealing with the type that `some.x` is. Since `'foo'.y` doesn't make sense, you cannot do it with `some.x` either since it is of the same type as `'foo'`.
24,818,096
I am new to python app development. When I tried a code I'm not able to see its output. My sample code is: ``` class name: def __init__(self): x = '' y = '' print x,y ``` When i called the above function like ``` some = name() some.x = 'yeah' some.x.y = 'hell' ``` When i called `some.x` it works fine but when i called `some.x.y = 'hell'` it shows error like ``` Traceback (most recent call last): File "<pyshell#5>", line 1, in <module> some.x.y = 'hell' AttributeError: 'str' object has no attribute 'y' ``` Hope you guys can help me out.
2014/07/18
[ "https://Stackoverflow.com/questions/24818096", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3843420/" ]
First of all, you are defining the class with the wrong way, you should; ``` class name: def __init__(self): self.x = '' self.y = '' print x,y ``` Then, you are calling the wrong way, you should; ``` some = name() some.x = 'yeah' some.y = 'hell' ``` The problem is, `x` and `y` are `strings`. If you want to `some.x.y` for some reason, you should define `x` on your own.In other words, you can't use `some.x.y` for now. Ok, you still need for `some.x.y`; ``` class name: def __init__(self): pass some = name() some.x = name() some.x.y = "foo" print some.x.y >>> foo ```
These are different variables. So when you do chain .y onto some.x you are looking for a member variable y of a string which does not exist ``` some = name() some.x = 'yeah' some.y = 'hell' ``` if you want to make a single string out of both x and y you can use + to concatenate them together as follows ``` s = some.x + ' ' + some.y print s # prints out "yeah hell" class name: def __init__(self): x = '' y = '' def ___str__(self): print x + ' ' y ``` now you can print the class and get ``` print some # prints "yeah hell" ```
24,818,096
I am new to python app development. When I tried a code I'm not able to see its output. My sample code is: ``` class name: def __init__(self): x = '' y = '' print x,y ``` When i called the above function like ``` some = name() some.x = 'yeah' some.x.y = 'hell' ``` When i called `some.x` it works fine but when i called `some.x.y = 'hell'` it shows error like ``` Traceback (most recent call last): File "<pyshell#5>", line 1, in <module> some.x.y = 'hell' AttributeError: 'str' object has no attribute 'y' ``` Hope you guys can help me out.
2014/07/18
[ "https://Stackoverflow.com/questions/24818096", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3843420/" ]
First of all, you are defining the class with the wrong way, you should; ``` class name: def __init__(self): self.x = '' self.y = '' print x,y ``` Then, you are calling the wrong way, you should; ``` some = name() some.x = 'yeah' some.y = 'hell' ``` The problem is, `x` and `y` are `strings`. If you want to `some.x.y` for some reason, you should define `x` on your own.In other words, you can't use `some.x.y` for now. Ok, you still need for `some.x.y`; ``` class name: def __init__(self): pass some = name() some.x = name() some.x.y = "foo" print some.x.y >>> foo ```
When you perform `some.x` you are no longer dealing with the `some`, you are dealing with the type that `some.x` is. Since `'foo'.y` doesn't make sense, you cannot do it with `some.x` either since it is of the same type as `'foo'`.
72,462,419
Given a website (for example stackoverflow.com) I want to download all the files under: ``` (Right Click) -> Inspect -> Sources -> Page ``` Please Try it yourself and see the files you get. **How can I do that in python?** I know how to retrive page source but not the source files. I tried searching this multiple times with no success and there is a confusion between sources (files) and page source. Please Note, I'm looking for a an approach or example rather than ready-to-use code. For example, I want to gather all of these files under `top`: ![enter image description here](https://i.stack.imgur.com/BeJEZ.jpg)
2022/06/01
[ "https://Stackoverflow.com/questions/72462419", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19248696/" ]
To download website source files (mirroring websites / copy source files from websites) you may try [`PyWebCopy`](https://github.com/rajatomar788/pywebcopy/) library. To save any single page - ``` from pywebcopy import save_webpage save_webpage( url="https://httpbin.org/", project_folder="E://savedpages//", project_name="my_site", bypass_robots=True, debug=True, open_in_browser=True, delay=None, threaded=False, ) ``` To save full website - ``` from pywebcopy import save_website save_website( url="https://httpbin.org/", project_folder="E://savedpages//", project_name="my_site", bypass_robots=True, debug=True, open_in_browser=True, delay=None, threaded=False, ) ``` You can also check tools like [httrack](https://www.httrack.com/) which comes with a GUI to download website files (mirror). On the other hand to download web-page source code (HTML pages) - ``` import requests url = 'https://stackoverflow.com/questions/72462419/how-to-download-website-source-files-in-python' html_output_name = 'test2.html' req = requests.get(url, 'html.parser', headers={ 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.67 Safari/537.36'}) with open(html_output_name, 'w') as f: f.write(req.text) f.close() ```
The easiest way to do this is definitely not with Python. As you seem to know, you can download code to a single site w/ Command click > View Page Source or the sources tab of inspect element. To download all the files in a website's structure, you should use a web-scraper. For Mac, SiteSucker is your best option if you don’t care about having all of the site assets (videos, images, etc. hosted on the website) downloaded locally on your computer. Videos especially could take up a lot of space, so this sometimes helpful. (Site Sucker is not free, but pretty cheap). The GUI in SiteSucker is self-explanatory, so there's no learning curve. If you do want all assets to be downloaded locally on your computer (you may want to do this if you want to access a site’s content offline, for example), HTTrack is the best option, in my opinion, for Mac and Windows. (Free). HTTrack is harder to use than SiteSucker, but allows more options about which files to grab, and again will download things locally. There are many good tutorials/pages about how to use the GUI for HTTrack, like this one: <http://www.httrack.com/html/shelldoc.html> You could also use wget (Free) to download content, but wget does not have a GUI and has less flexibility, so I prefer HTTrack.
63,158,692
**Summarize the problem:** The Python package basically opens PDFs in batch folder, reads the first page of each PDF, matches keywords, and dumps compatible PDFs in source folder for OCR scripts to kick in. The first script to take all PDFs are **MainBankClass.py**. I am trying to use a docker-compose file to include all these python scripts under the same *network* and *volume* so that each OCR script starts to scan bank statements when the pre-processing is done. [This link](https://stackoverflow.com/questions/53920742/how-to-run-multiple-python-scripts-and-an-executable-files-using-docker/53921177) is the closest so far to accomplish the goal but it seems that I missed some parts of it. The process to call different OCR scripts is achieved by `runpy.run_path(path_name='ChaseOCR.py')`, thus these scripts are in the same directory of `__init__.py`. Here is the filesystem structure: ``` BankStatements ┣ BankofAmericaOCR ┃ ┣ BancAmericaOCR.py ┃ ┗ Dockerfile.bankofamerica ┣ ChaseBankStatementOCR ┃ ┣ ChaseOCR.py ┃ ┗ Dockerfile.chase ┣ WellsFargoStatementOCR ┃ ┣ Dockerfile.wellsfargo ┃ ┗ WellsFargoOCR.py ┣ BancAmericaOCR.py ┣ ChaseOCR.py ┣ Dockerfile ┣ WellsFargoOCR.py ┣ __init__.py ┗ docker-compose.yml ``` **What I've tried so far:** In docker-compose.yml: ``` version: '3' services: mainbankclass_container: build: context: '.' dockerfile: Dockerfile volumes: - /Users:/Users #links: # - "chase_container" # - "wellsfargo_container" # - "bankofamerica_container" chase_container: build: . working_dir: /app/ChaseBankStatementOCR command: ./ChaseOCR.py volumes: - /Users:/Users bankofamerica_container: build: . working_dir: /app/BankofAmericaOCR command: ./BancAmericaOCR.py volumes: - /Users:/Users wellsfargo_container: build: . working_dir: /app/WellsFargoStatementOCR command: ./WellsFargoOCR.py volumes: - /Users:/Users ``` And each dockerfile under each bank folder is similar except `CMD` would be changed accordingly. For example, in ChaseBankStatementOCR folder: ``` FROM python:3.7-stretch WORKDIR /app COPY . /app CMD ["python3", "ChaseOCR.py"] <---- changes are made here for the other two bank scripts ``` The last element is for Dockerfile outside of each folder: ``` FROM python:3.7-stretch WORKDIR /app COPY ./requirements.txt ./ RUN pip3 install --upgrade pip RUN pip3 install -r requirements.txt RUN pip3 install --upgrade PyMuPDF COPY . /app COPY ./ChaseOCR.py /app COPY ./BancAmericaOCR.py /app COPY ./WellsFargoOCR.py /app EXPOSE 8080 CMD ["python3", "MainBankClass.py"] ``` After running `docker-compose build`, containers and network are successfully built. Error occurs when I run `docker run -v /Users:/Users: python3 python3 ~/BankStatementsDemoOCR/BankStatements/MainBankClass.py` and the error message is *FileNotFoundError: [Errno 2] No such file or directory: 'BancAmericaOCR.py'* I am assuming that the container doesn't have BancAmericaOCR.py but I have composed each .py file under the same network and I don't think `links` is a good practice since docker recommended to use `networks` [here](https://docs.docker.com/compose/networking/). What am I missing here? Any help is much appreciated. Thanks in advance.
2020/07/29
[ "https://Stackoverflow.com/questions/63158692", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12961386/" ]
> > single application in a single container ... need networks for different py files to communicate > > > You only have one container. Docker networks are for multiple containers to talk to one another. And Docker Compose has a default bridge network defined for all services, so you shouldn't need that if you were still using docker-compose Here's a cleaned up Dockerfile with all the scripts copied in, with the addition of an entrypoint file ``` FROM python:3.7-stretch WORKDIR /app COPY ./requirements.txt ./ RUN pip3 install --upgrade pip PyMuPDF && pip3 install -r requirements.txt COPY . /app COPY ./docker-entrypoint.sh / ENTRYPOINT /docker-entrypoint.sh ``` In your entrypoint, you can loop over every file ``` #!/bin/bash for b in Chase WellsFargo BofA ; do python3 /app/$b.py done exec python3 /app/MainBankClass.py ```
So after days of searching regarding my case, I am closing this thread with an implementation of **single application in a single container** suggested on [this link](https://forums.docker.com/t/is-it-possible-to-run-python-package-with-multiple-py-scripts-in-docker-compose-yml/97094/8) from docker forum. Instead of going with docker-compose, the suggested approach is to use 1 container with dockerfile for this application and it's working as expected. On top of the dockerfile, we also need *networks* for different py files to communicate. For example: ``` docker network create my_net docker run -it --network my_net -v /Users:/Users --rm my_awesome_app ``` **EDIT:** No network is needed since we are only running one container. **EDIT 2:** Please see the accepted answer for future reference Any answers are welcomed if anyone has better ideas on the case.
378,811
I'm trying to get Python scripts, called from a web browser, to work. I keep getting the error: ``` 500 Internal Server Error ``` When I check my error logs I see the message ``` Premature end of script headers ``` The only documentation of this error online says that it can be the result of having improper line return characters in your script, but I wrote my test script right from the shell with pico. Also, when I run the file from the command line it executes just fine. " So far the only change I have made to apache is to add the .py to the "AddHandler cgi-script" line. Thanks! --- Thanks for the quick responses. Here is the latest version of the test code. I added a couple new lines before the output as suggested but still get the same error: ``` #!/usr/local/bin/python print "Content-type: text/html\n" print "\n\n" print "<HTML>" print "<HEAD>" print "<TITLE>Test</TITLE>" print "</HEAD>" print "<BODY>" print "<H2>Hi there.</h2>" print "</BODY>" print "</HTML>" ``` Some other details: I am running Apache 1.3 and don't have mod\_python. I set apache to recognize .py as mentioned above. I am running the script from the main public\_html folder. --- An update. It doesn't seem to matter what I put in the shebang line. I tried all of the suggestions and even if I leave it blank the same error is showing up in the errors log and I'm getting a 500 error. I'm running Apache/1.3.41 on linux (red hat 3.4) with WHM/Cpanel installed.
2008/12/18
[ "https://Stackoverflow.com/questions/378811", "https://Stackoverflow.com", "https://Stackoverflow.com/users/47514/" ]
One common error is the wrong path. I my case it was usr/bin/python. The other common error is not transferring the file in ASCII mode. I am using WinSCP where you can set it easily: Go to Options->Preferences->Transfers->click Edit and change the mode to Text. This code should work: ``` #!/usr/bin/python print "Content-type: text/html\n\n"; print "<html><head>"; print "<title>CGI Test</title>"; print "</head><body>"; print "<p>Test page using Python</p>"; print "</body></html>"; ```
Sounds to me like you're using a script written in Windows on a Unix machine, without first converting the line-endings from 0d0a to 0a. It should be easy to convert it. One way is with your ftp program; transfer the file in ASCII mode. The way I use with Metapad is to use File->FileFormat before saving.
378,811
I'm trying to get Python scripts, called from a web browser, to work. I keep getting the error: ``` 500 Internal Server Error ``` When I check my error logs I see the message ``` Premature end of script headers ``` The only documentation of this error online says that it can be the result of having improper line return characters in your script, but I wrote my test script right from the shell with pico. Also, when I run the file from the command line it executes just fine. " So far the only change I have made to apache is to add the .py to the "AddHandler cgi-script" line. Thanks! --- Thanks for the quick responses. Here is the latest version of the test code. I added a couple new lines before the output as suggested but still get the same error: ``` #!/usr/local/bin/python print "Content-type: text/html\n" print "\n\n" print "<HTML>" print "<HEAD>" print "<TITLE>Test</TITLE>" print "</HEAD>" print "<BODY>" print "<H2>Hi there.</h2>" print "</BODY>" print "</HTML>" ``` Some other details: I am running Apache 1.3 and don't have mod\_python. I set apache to recognize .py as mentioned above. I am running the script from the main public\_html folder. --- An update. It doesn't seem to matter what I put in the shebang line. I tried all of the suggestions and even if I leave it blank the same error is showing up in the errors log and I'm getting a 500 error. I'm running Apache/1.3.41 on linux (red hat 3.4) with WHM/Cpanel installed.
2008/12/18
[ "https://Stackoverflow.com/questions/378811", "https://Stackoverflow.com", "https://Stackoverflow.com/users/47514/" ]
OK last guess: Trying changing that shebang line to: ``` #!/usr/bin/env python ``` or ``` #!/usr/bin/local/env python ``` It would also be helpful to know your platform / hosting provider.
If you have configured Apaches httpd file correctly then you might be getting this error for following two reasons.Make sure these are correct. 1. Include '#!/usr/bin/python' or '#!C:/Python27/python' or accordingly in your script as first line. 2. Make sure there is space after print "Content-type: text/html" ie. print "Content-type: text/html\n\n"; Hope this helps!!
378,811
I'm trying to get Python scripts, called from a web browser, to work. I keep getting the error: ``` 500 Internal Server Error ``` When I check my error logs I see the message ``` Premature end of script headers ``` The only documentation of this error online says that it can be the result of having improper line return characters in your script, but I wrote my test script right from the shell with pico. Also, when I run the file from the command line it executes just fine. " So far the only change I have made to apache is to add the .py to the "AddHandler cgi-script" line. Thanks! --- Thanks for the quick responses. Here is the latest version of the test code. I added a couple new lines before the output as suggested but still get the same error: ``` #!/usr/local/bin/python print "Content-type: text/html\n" print "\n\n" print "<HTML>" print "<HEAD>" print "<TITLE>Test</TITLE>" print "</HEAD>" print "<BODY>" print "<H2>Hi there.</h2>" print "</BODY>" print "</HTML>" ``` Some other details: I am running Apache 1.3 and don't have mod\_python. I set apache to recognize .py as mentioned above. I am running the script from the main public\_html folder. --- An update. It doesn't seem to matter what I put in the shebang line. I tried all of the suggestions and even if I leave it blank the same error is showing up in the errors log and I'm getting a 500 error. I'm running Apache/1.3.41 on linux (red hat 3.4) with WHM/Cpanel installed.
2008/12/18
[ "https://Stackoverflow.com/questions/378811", "https://Stackoverflow.com", "https://Stackoverflow.com/users/47514/" ]
This is the exact behavior you would get if your Python script does not have the executable permission set. Try: ``` chmod a+x foo.py ``` (where foo.py is your script name). See the [Apache tutorial](http://httpd.apache.org/docs/1.3/howto/cgi.html#filepermissions) for more information.
One common error is the wrong path. I my case it was usr/bin/python. The other common error is not transferring the file in ASCII mode. I am using WinSCP where you can set it easily: Go to Options->Preferences->Transfers->click Edit and change the mode to Text. This code should work: ``` #!/usr/bin/python print "Content-type: text/html\n\n"; print "<html><head>"; print "<title>CGI Test</title>"; print "</head><body>"; print "<p>Test page using Python</p>"; print "</body></html>"; ```
378,811
I'm trying to get Python scripts, called from a web browser, to work. I keep getting the error: ``` 500 Internal Server Error ``` When I check my error logs I see the message ``` Premature end of script headers ``` The only documentation of this error online says that it can be the result of having improper line return characters in your script, but I wrote my test script right from the shell with pico. Also, when I run the file from the command line it executes just fine. " So far the only change I have made to apache is to add the .py to the "AddHandler cgi-script" line. Thanks! --- Thanks for the quick responses. Here is the latest version of the test code. I added a couple new lines before the output as suggested but still get the same error: ``` #!/usr/local/bin/python print "Content-type: text/html\n" print "\n\n" print "<HTML>" print "<HEAD>" print "<TITLE>Test</TITLE>" print "</HEAD>" print "<BODY>" print "<H2>Hi there.</h2>" print "</BODY>" print "</HTML>" ``` Some other details: I am running Apache 1.3 and don't have mod\_python. I set apache to recognize .py as mentioned above. I am running the script from the main public\_html folder. --- An update. It doesn't seem to matter what I put in the shebang line. I tried all of the suggestions and even if I leave it blank the same error is showing up in the errors log and I'm getting a 500 error. I'm running Apache/1.3.41 on linux (red hat 3.4) with WHM/Cpanel installed.
2008/12/18
[ "https://Stackoverflow.com/questions/378811", "https://Stackoverflow.com", "https://Stackoverflow.com/users/47514/" ]
If you have configured Apaches httpd file correctly then you might be getting this error for following two reasons.Make sure these are correct. 1. Include '#!/usr/bin/python' or '#!C:/Python27/python' or accordingly in your script as first line. 2. Make sure there is space after print "Content-type: text/html" ie. print "Content-type: text/html\n\n"; Hope this helps!!
I tried many approaches to get Python working with Apache properly and finally settled with using **Apache + mod\_WSGI + [web.py](http://webpy.org/cookbook/mod_wsgi-apache)** . It sounds like a lot, but it is much simpler than using the complicated frameworks like Django out there. (You're right, don't bother with mod\_python) Note, I am using Apache2 , but mod\_wsgi works on 1.3 as well, based on the [modwsgi page](http://code.google.com/p/modwsgi/). If you are on Redhat, I believe you have yum, so make sure to get the apache wsgi module and other python packages: ``` $ yum update $ yum install gcc gcc-c++ python-setuptools python-devel $ yum install httpd mod_wsgi ``` And get web.py for your version of python. For example, using easy\_install. I have v2.6. ``` $ easy_install-2.6 web.py ``` Create a directory for your python scripts : `/opt/local/apache2/wsgi-scripts/` In your httpd.conf : ``` LoadModule wsgi_module modules/mod_wsgi.so # note foo.py is the python file to get executed # and /opt/local/apache2/wsgi-scripts/ is the dedicated directory for wsgi scripts WSGIScriptAlias /myapp /opt/local/apache2/wsgi-scripts/foo.py/ AddType text/html .py <Directory /opt/local/apache2/wsgi-scripts/> Order allow,deny Allow from all </Directory> ``` Note that web.py uses a "templates directory". Put that into the wsgi directory , `/opt/local/apache2/wsgi-scripts/templates/` . Create a file `/opt/local/apache2/wsgi-scripts/templates/mytemplate.html` : ``` $def with (text) <html> <body> Hello $text. </body> </html> ``` Add appropriate permissions. ``` $ chown -R root:httpd /opt/local/apache2/wsgi-scripts/ $ chmod -R 770 /opt/local/apache2/wsgi-scripts/ ``` In your python file, foo.py : ``` import web urls = ( '/', 'broker',) render = web.template.render('/opt/local/apache2/wsgi-scripts/templates/') application = web.application(urls, globals()).wsgifunc() class broker: def GET(self): return render.mytemplate("World") ``` The above will replace the special web.py $text variable in the mytemplate with the word "World" before returning the result . <http://ivory.idyll.org/articles/wsgi-intro/what-is-wsgi.html>
378,811
I'm trying to get Python scripts, called from a web browser, to work. I keep getting the error: ``` 500 Internal Server Error ``` When I check my error logs I see the message ``` Premature end of script headers ``` The only documentation of this error online says that it can be the result of having improper line return characters in your script, but I wrote my test script right from the shell with pico. Also, when I run the file from the command line it executes just fine. " So far the only change I have made to apache is to add the .py to the "AddHandler cgi-script" line. Thanks! --- Thanks for the quick responses. Here is the latest version of the test code. I added a couple new lines before the output as suggested but still get the same error: ``` #!/usr/local/bin/python print "Content-type: text/html\n" print "\n\n" print "<HTML>" print "<HEAD>" print "<TITLE>Test</TITLE>" print "</HEAD>" print "<BODY>" print "<H2>Hi there.</h2>" print "</BODY>" print "</HTML>" ``` Some other details: I am running Apache 1.3 and don't have mod\_python. I set apache to recognize .py as mentioned above. I am running the script from the main public\_html folder. --- An update. It doesn't seem to matter what I put in the shebang line. I tried all of the suggestions and even if I leave it blank the same error is showing up in the errors log and I'm getting a 500 error. I'm running Apache/1.3.41 on linux (red hat 3.4) with WHM/Cpanel installed.
2008/12/18
[ "https://Stackoverflow.com/questions/378811", "https://Stackoverflow.com", "https://Stackoverflow.com/users/47514/" ]
This is the exact behavior you would get if your Python script does not have the executable permission set. Try: ``` chmod a+x foo.py ``` (where foo.py is your script name). See the [Apache tutorial](http://httpd.apache.org/docs/1.3/howto/cgi.html#filepermissions) for more information.
I tried many approaches to get Python working with Apache properly and finally settled with using **Apache + mod\_WSGI + [web.py](http://webpy.org/cookbook/mod_wsgi-apache)** . It sounds like a lot, but it is much simpler than using the complicated frameworks like Django out there. (You're right, don't bother with mod\_python) Note, I am using Apache2 , but mod\_wsgi works on 1.3 as well, based on the [modwsgi page](http://code.google.com/p/modwsgi/). If you are on Redhat, I believe you have yum, so make sure to get the apache wsgi module and other python packages: ``` $ yum update $ yum install gcc gcc-c++ python-setuptools python-devel $ yum install httpd mod_wsgi ``` And get web.py for your version of python. For example, using easy\_install. I have v2.6. ``` $ easy_install-2.6 web.py ``` Create a directory for your python scripts : `/opt/local/apache2/wsgi-scripts/` In your httpd.conf : ``` LoadModule wsgi_module modules/mod_wsgi.so # note foo.py is the python file to get executed # and /opt/local/apache2/wsgi-scripts/ is the dedicated directory for wsgi scripts WSGIScriptAlias /myapp /opt/local/apache2/wsgi-scripts/foo.py/ AddType text/html .py <Directory /opt/local/apache2/wsgi-scripts/> Order allow,deny Allow from all </Directory> ``` Note that web.py uses a "templates directory". Put that into the wsgi directory , `/opt/local/apache2/wsgi-scripts/templates/` . Create a file `/opt/local/apache2/wsgi-scripts/templates/mytemplate.html` : ``` $def with (text) <html> <body> Hello $text. </body> </html> ``` Add appropriate permissions. ``` $ chown -R root:httpd /opt/local/apache2/wsgi-scripts/ $ chmod -R 770 /opt/local/apache2/wsgi-scripts/ ``` In your python file, foo.py : ``` import web urls = ( '/', 'broker',) render = web.template.render('/opt/local/apache2/wsgi-scripts/templates/') application = web.application(urls, globals()).wsgifunc() class broker: def GET(self): return render.mytemplate("World") ``` The above will replace the special web.py $text variable in the mytemplate with the word "World" before returning the result . <http://ivory.idyll.org/articles/wsgi-intro/what-is-wsgi.html>
378,811
I'm trying to get Python scripts, called from a web browser, to work. I keep getting the error: ``` 500 Internal Server Error ``` When I check my error logs I see the message ``` Premature end of script headers ``` The only documentation of this error online says that it can be the result of having improper line return characters in your script, but I wrote my test script right from the shell with pico. Also, when I run the file from the command line it executes just fine. " So far the only change I have made to apache is to add the .py to the "AddHandler cgi-script" line. Thanks! --- Thanks for the quick responses. Here is the latest version of the test code. I added a couple new lines before the output as suggested but still get the same error: ``` #!/usr/local/bin/python print "Content-type: text/html\n" print "\n\n" print "<HTML>" print "<HEAD>" print "<TITLE>Test</TITLE>" print "</HEAD>" print "<BODY>" print "<H2>Hi there.</h2>" print "</BODY>" print "</HTML>" ``` Some other details: I am running Apache 1.3 and don't have mod\_python. I set apache to recognize .py as mentioned above. I am running the script from the main public\_html folder. --- An update. It doesn't seem to matter what I put in the shebang line. I tried all of the suggestions and even if I leave it blank the same error is showing up in the errors log and I'm getting a 500 error. I'm running Apache/1.3.41 on linux (red hat 3.4) with WHM/Cpanel installed.
2008/12/18
[ "https://Stackoverflow.com/questions/378811", "https://Stackoverflow.com", "https://Stackoverflow.com/users/47514/" ]
You may also get a better error message by adding this line at the top of your Python script: `import cgitb; cgitb.enable()` Also, the header should be capitalized `Content-Type`, not `Content-type`, although I doubt that that is breaking anything.
This ended up being a `dos2unix` issue for me. Ran `dos2unix test.py test.py` and it worked. The `\r\n` combinations were the problem. Had to `yum install dos2unix` to get it installed.
378,811
I'm trying to get Python scripts, called from a web browser, to work. I keep getting the error: ``` 500 Internal Server Error ``` When I check my error logs I see the message ``` Premature end of script headers ``` The only documentation of this error online says that it can be the result of having improper line return characters in your script, but I wrote my test script right from the shell with pico. Also, when I run the file from the command line it executes just fine. " So far the only change I have made to apache is to add the .py to the "AddHandler cgi-script" line. Thanks! --- Thanks for the quick responses. Here is the latest version of the test code. I added a couple new lines before the output as suggested but still get the same error: ``` #!/usr/local/bin/python print "Content-type: text/html\n" print "\n\n" print "<HTML>" print "<HEAD>" print "<TITLE>Test</TITLE>" print "</HEAD>" print "<BODY>" print "<H2>Hi there.</h2>" print "</BODY>" print "</HTML>" ``` Some other details: I am running Apache 1.3 and don't have mod\_python. I set apache to recognize .py as mentioned above. I am running the script from the main public\_html folder. --- An update. It doesn't seem to matter what I put in the shebang line. I tried all of the suggestions and even if I leave it blank the same error is showing up in the errors log and I'm getting a 500 error. I'm running Apache/1.3.41 on linux (red hat 3.4) with WHM/Cpanel installed.
2008/12/18
[ "https://Stackoverflow.com/questions/378811", "https://Stackoverflow.com", "https://Stackoverflow.com/users/47514/" ]
do you have something like this at the top before you print anything else? ``` print "Content-type: text/html\n" ``` If you already have this, then post your code.
You can also get some of this same foolishness if you have DOS style end of lines on a linux web server. (That just chewed up about two hours of my morning today.) Off to update my vim.rc on this windows box that I need to use.
378,811
I'm trying to get Python scripts, called from a web browser, to work. I keep getting the error: ``` 500 Internal Server Error ``` When I check my error logs I see the message ``` Premature end of script headers ``` The only documentation of this error online says that it can be the result of having improper line return characters in your script, but I wrote my test script right from the shell with pico. Also, when I run the file from the command line it executes just fine. " So far the only change I have made to apache is to add the .py to the "AddHandler cgi-script" line. Thanks! --- Thanks for the quick responses. Here is the latest version of the test code. I added a couple new lines before the output as suggested but still get the same error: ``` #!/usr/local/bin/python print "Content-type: text/html\n" print "\n\n" print "<HTML>" print "<HEAD>" print "<TITLE>Test</TITLE>" print "</HEAD>" print "<BODY>" print "<H2>Hi there.</h2>" print "</BODY>" print "</HTML>" ``` Some other details: I am running Apache 1.3 and don't have mod\_python. I set apache to recognize .py as mentioned above. I am running the script from the main public\_html folder. --- An update. It doesn't seem to matter what I put in the shebang line. I tried all of the suggestions and even if I leave it blank the same error is showing up in the errors log and I'm getting a 500 error. I'm running Apache/1.3.41 on linux (red hat 3.4) with WHM/Cpanel installed.
2008/12/18
[ "https://Stackoverflow.com/questions/378811", "https://Stackoverflow.com", "https://Stackoverflow.com/users/47514/" ]
do you have something like this at the top before you print anything else? ``` print "Content-type: text/html\n" ``` If you already have this, then post your code.
If you have configured Apaches httpd file correctly then you might be getting this error for following two reasons.Make sure these are correct. 1. Include '#!/usr/bin/python' or '#!C:/Python27/python' or accordingly in your script as first line. 2. Make sure there is space after print "Content-type: text/html" ie. print "Content-type: text/html\n\n"; Hope this helps!!
378,811
I'm trying to get Python scripts, called from a web browser, to work. I keep getting the error: ``` 500 Internal Server Error ``` When I check my error logs I see the message ``` Premature end of script headers ``` The only documentation of this error online says that it can be the result of having improper line return characters in your script, but I wrote my test script right from the shell with pico. Also, when I run the file from the command line it executes just fine. " So far the only change I have made to apache is to add the .py to the "AddHandler cgi-script" line. Thanks! --- Thanks for the quick responses. Here is the latest version of the test code. I added a couple new lines before the output as suggested but still get the same error: ``` #!/usr/local/bin/python print "Content-type: text/html\n" print "\n\n" print "<HTML>" print "<HEAD>" print "<TITLE>Test</TITLE>" print "</HEAD>" print "<BODY>" print "<H2>Hi there.</h2>" print "</BODY>" print "</HTML>" ``` Some other details: I am running Apache 1.3 and don't have mod\_python. I set apache to recognize .py as mentioned above. I am running the script from the main public\_html folder. --- An update. It doesn't seem to matter what I put in the shebang line. I tried all of the suggestions and even if I leave it blank the same error is showing up in the errors log and I'm getting a 500 error. I'm running Apache/1.3.41 on linux (red hat 3.4) with WHM/Cpanel installed.
2008/12/18
[ "https://Stackoverflow.com/questions/378811", "https://Stackoverflow.com", "https://Stackoverflow.com/users/47514/" ]
This is the exact behavior you would get if your Python script does not have the executable permission set. Try: ``` chmod a+x foo.py ``` (where foo.py is your script name). See the [Apache tutorial](http://httpd.apache.org/docs/1.3/howto/cgi.html#filepermissions) for more information.
Sounds to me like you're using a script written in Windows on a Unix machine, without first converting the line-endings from 0d0a to 0a. It should be easy to convert it. One way is with your ftp program; transfer the file in ASCII mode. The way I use with Metapad is to use File->FileFormat before saving.
378,811
I'm trying to get Python scripts, called from a web browser, to work. I keep getting the error: ``` 500 Internal Server Error ``` When I check my error logs I see the message ``` Premature end of script headers ``` The only documentation of this error online says that it can be the result of having improper line return characters in your script, but I wrote my test script right from the shell with pico. Also, when I run the file from the command line it executes just fine. " So far the only change I have made to apache is to add the .py to the "AddHandler cgi-script" line. Thanks! --- Thanks for the quick responses. Here is the latest version of the test code. I added a couple new lines before the output as suggested but still get the same error: ``` #!/usr/local/bin/python print "Content-type: text/html\n" print "\n\n" print "<HTML>" print "<HEAD>" print "<TITLE>Test</TITLE>" print "</HEAD>" print "<BODY>" print "<H2>Hi there.</h2>" print "</BODY>" print "</HTML>" ``` Some other details: I am running Apache 1.3 and don't have mod\_python. I set apache to recognize .py as mentioned above. I am running the script from the main public\_html folder. --- An update. It doesn't seem to matter what I put in the shebang line. I tried all of the suggestions and even if I leave it blank the same error is showing up in the errors log and I'm getting a 500 error. I'm running Apache/1.3.41 on linux (red hat 3.4) with WHM/Cpanel installed.
2008/12/18
[ "https://Stackoverflow.com/questions/378811", "https://Stackoverflow.com", "https://Stackoverflow.com/users/47514/" ]
Two things spring immediately to mind. 1. Make sure you are outputting the `Content-Type: text/html` header 2. Make sure you are adding two newlines ("\n") after the headers before you output "Hello, world" or whatever.
You can also get some of this same foolishness if you have DOS style end of lines on a linux web server. (That just chewed up about two hours of my morning today.) Off to update my vim.rc on this windows box that I need to use.
58,604,645
I want to get all the installed patches on an `AWS EC2 instance`, So I run this code in `boto3`: ``` response = client.describe_instance_patches(InstanceId=instance_id, Filters=[{'Key': 'State','Values': ['Installed',]} ]) ``` My instance has a patch with a negative timestamp : ``` { "Patches": [ { "KBId": "KB3178539", "Severity": "Important", "Classification": "SecurityUpdates", "Title": "Security Update for Windows 8.1 (KB3178539)", "State": "Installed", "InstalledTime": 1483574400.0 }, { "KBId": "KB4493446", "Severity": "Critical", "Classification": "SecurityUpdates", "Title": "2019-04 Security Monthly Quality Rollup for Windows 8.1 for x64-based Systems (KB4493446)", "State": "Installed", "InstalledTime": 1555804800.0 }, { "KBId": "KB4487080", "Severity": "Important", "Classification": "SecurityUpdates", "Title": "2019-02 Security and Quality Rollup for .NET Framework 3.5, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2 for Windows 8.1 (KB4487080)", "State": "Installed", "InstalledTime": -62135596800.0 } ] } ``` So my boto3 snippet gives me this error: ``` response = client.describe_instance_patches(InstanceId=instance_id, Filters=[{'Key': 'State','Values': ['Installed',]}, ]) File "/usr/local/lib/python2.7/dist-packages/botocore/client.py", line 357, in _api_call return self._make_api_call(operation_name, kwargs) File "/usr/local/lib/python2.7/dist-packages/botocore/client.py", line 648, in _make_api_call operation_model, request_dict, request_context) File "/usr/local/lib/python2.7/dist-packages/botocore/client.py", line 667, in _make_request return self._endpoint.make_request(operation_model, request_dict) File "/usr/local/lib/python2.7/dist-packages/botocore/endpoint.py", line 102, in make_request return self._send_request(request_dict, operation_model) File "/usr/local/lib/python2.7/dist-packages/botocore/endpoint.py", line 135, in _send_request request, operation_model, context) File "/usr/local/lib/python2.7/dist-packages/botocore/endpoint.py", line 167, in _get_response request, operation_model) File "/usr/local/lib/python2.7/dist-packages/botocore/endpoint.py", line 218, in _do_get_response response_dict, operation_model.output_shape) File "/usr/local/lib/python2.7/dist-packages/botocore/parsers.py", line 242, in parse parsed = self._do_parse(response, shape) File "/usr/local/lib/python2.7/dist-packages/botocore/parsers.py", line 740, in _do_parse parsed = self._handle_json_body(response['body'], shape) File "/usr/local/lib/python2.7/dist-packages/botocore/parsers.py", line 761, in _handle_json_body return self._parse_shape(shape, parsed_json) File "/usr/local/lib/python2.7/dist-packages/botocore/parsers.py", line 302, in _parse_shape return handler(shape, node) File "/usr/local/lib/python2.7/dist-packages/botocore/parsers.py", line 572, in _handle_structure raw_value) File "/usr/local/lib/python2.7/dist-packages/botocore/parsers.py", line 302, in _parse_shape return handler(shape, node) File "/usr/local/lib/python2.7/dist-packages/botocore/parsers.py", line 310, in _handle_list parsed.append(self._parse_shape(member_shape, item)) File "/usr/local/lib/python2.7/dist-packages/botocore/parsers.py", line 302, in _parse_shape return handler(shape, node) File "/usr/local/lib/python2.7/dist-packages/botocore/parsers.py", line 572, in _handle_structure raw_value) File "/usr/local/lib/python2.7/dist-packages/botocore/parsers.py", line 302, in _parse_shape return handler(shape, node) File "/usr/local/lib/python2.7/dist-packages/botocore/parsers.py", line 589, in _handle_timestamp return self._timestamp_parser(value) File "/usr/local/lib/python2.7/dist-packages/botocore/utils.py", line 558, in parse_timestamp return datetime.datetime.fromtimestamp(value, tzlocal()) File "/usr/local/lib/python2.7/dist-packages/dateutil/tz/_common.py", line 144, in fromutc return f(self, dt) File "/usr/local/lib/python2.7/dist-packages/dateutil/tz/_common.py", line 258, in fromutc dt_wall = self._fromutc(dt) File "/usr/local/lib/python2.7/dist-packages/dateutil/tz/_common.py", line 222, in _fromutc dtoff = dt.utcoffset() File "/usr/local/lib/python2.7/dist-packages/dateutil/tz/tz.py", line 216, in utcoffset if self._isdst(dt): File "/usr/local/lib/python2.7/dist-packages/dateutil/tz/tz.py", line 288, in _isdst if self.is_ambiguous(dt): File "/usr/local/lib/python2.7/dist-packages/dateutil/tz/tz.py", line 250, in is_ambiguous (naive_dst != self._naive_is_dst(dt - self._dst_saved))) OverflowError: date value out of range ``` I need to get the installed patches of several instances and I don't want the script to break when it finds a negative timestamp. How can workaround this ? How can I use the filters to get only valid timestamps ?
2019/10/29
[ "https://Stackoverflow.com/questions/58604645", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2337243/" ]
Assuming this is nothing to with service worker/PWA, the solution could be implemented by returning the front end version by letting the server return the current version of the Vue App everytime. `axiosConfig.js` ``` axios.interceptors.response.use( (resp) => { let fe_version = resp.headers['fe-version'] || 'default' if(fe_version !== localStorage.getItem('fe-version') && resp.config.method == 'get'){ localStorage.setItem('fe-version', fe_version) window.location.reload() // For new version, simply reload on any get } return Promise.resolve(resp) }, ) ``` Full Article here: <https://blog.francium.tech/vue-js-cache-not-getting-cleared-in-production-on-deploy-656fcc5a85fe>
A possible problem could be that the browser is caching the `index.html` file. Try to disable cache for `index.html` like this: ``` <meta http-equiv="cache-control" content="max-age=0" /> <meta http-equiv="cache-control" content="no-cache" /> <meta http-equiv="expires" content="0" /> <meta http-equiv="expires" content="Tue, 01 Jan 1980 1:00:00 GMT" /> <meta http-equiv="pragma" content="no-cache" /> ``` Or if you are using a .htaccess file, add this code to the bottom of the file: ``` <Files index.html> FileETag None Header unset ETag Header set Cache-Control "max-age=0, no-cache, no-store, must-revalidate" Header set Pragma "no-cache" Header set Expires "Wed, 11 Jan 1984 05:00:00 GMT" </Files> ```
49,604,025
I'm trying to translate code that generates a Voronoi Diagram from Javascript into Python. This is a struggle because I don't know Javascript. I think I can sort-of make it out, but I'm still running into issues with things I don't understand. Please help me figure out what is wrong with my code. The code I've written simply give a blank window. Please help me generate a Voronoi Diagram. In order, I have my code, then the original code. Here's a link to the website I found it at: [Procedural Generation Wiki](http://pcg.wikidot.com/pcg-algorithm:voronoi-diagram) My Code: ``` """ Translated from javascript example at http://pcg.wikidot.com/pcg-algorithm:voronoi-diagram I have included the original comments. My own comments are preceded by two hash-tags/pound-signs. IE # Original Javascript comments here ## My comments here """ import random import pygame from pygame import gfxdraw # specify an empty points array ## I will use a list. points = [] lines = [] # get a random number in range min, max -1 ## No need for our own random number function. ## Just, import random, instead. def definePoints(numPoints, mapSize): # we want to take a group of points that will fit on our map at random for typ in range(numPoints): # here's the random points x = random.randrange(0, mapSize) y = random.randrange(0, mapSize) # "type:" decides what point it is # x, y: location # citizens: the cells in our grid that belong to this point ## Can't use "type:" (without quotes) in python comments ## Since I don't know Javascript, I dunno what he's doing here. ## I'm just going to append lists inside points. ## order is: type, x, y, citizens points.append([typ, x, y, []]) # brute force-y but it works # for each cell in the grid for x in range(mapSize): for y in range(mapSize): # find the nearest point lowestDelta = (0, mapSize * mapSize) for p in range(len(points)): # for each point get the difference in distance # between our point and the current cell ## I split the above comment into two so ## it would be less than 80 characters. delta = abs(points[p][1] - x) + abs(points[p][2] - y) # store the point nearest if it's closer than the last one if delta < lowestDelta[1]: lowestDelta = (p, delta) # push the cell to the nearest point ## Okay, here's where I start getting confused. ## I dunno how to do whatever he's doing in Python. for point in points: if lowestDelta[0] == point[0]: activePoint = point dx = x - activePoint[1] dy = y - activePoint[2] # log delta in cell for drawing ## Again, not sure what he's doing here. for point in points: if activePoint == point: point[3].append(dx) point[3].append(dy) return points ## all comments and code from here on are mine. def main(): # Get points points = definePoints(20, 400) print("lines: ", lines) # Setup pygame screens. pygame.init() size = (400, 400) screen = pygame.display.set_mode(size) white = (255, 255, 255) done = False # Control fps of window. clock = pygame.time.Clock() fps = 40 while not done: for event in pygame.event.get(): if event.type == pygame.QUIT: done = True for point in points: for p in point[3]: # draw white wherever there's a point. # pygame windows are black by default gfxdraw.pixel(screen, point[1], point[2], white) # controls FPS clock.tick(fps) if __name__ == "__main__": main() ``` Original Example Code: ``` //specify an empty points array var points = []; //get a random number in range min, max - 1 function randRange(min, max) { return Math.floor(Math.random() * ((max) - min) + min); } function definePoints(numPoints, mapSize) { //we want to take a group of points that will fit on our map at random for(var i = 0; i < numPoints; i++) { //here's the random points var x = randRange(0, mapSize); var y = randRange(0, mapSize); //type: decides which point it is //x, y: location //citizens: the cells in our grid that belong to this point points.push({type: i, x: x, y: y, citizens: []}); } //brute force-y but it works //for each cell in the grid for(var x = 0; x < mapSize; x++) { for(var y = 0; y < mapSize; y++) { //find the nearest point var lowestDelta = {pointId: 0, delta: mapSize * mapSize}; for(var p = 0; p < points.length; p++) { //for each point get the difference in distance between our point and the current cell var delta = Math.abs(points[p].x - x) + Math.abs(points[p].y - y); //store the point as nearest if it's closer than the last one if(delta < lowestDelta.delta) { lowestDelta = {pointId: p, delta: delta}; } } //push the cell to the nearest point var activePoint = points[lowestDelta.pointId]; var dx = x - activePoint.x; var dy = y - activePoint.y; //log delta in cell for drawing activePoint.citizens.push({ dx: dx, dy: dy }); } } } definePoints(20, 40); for(var point of points) { for(var citizen of point.citizens) { //set color of cell based on point //draw cell at (point.x + citizen.dx) * cellSize, (point.y + citizen.dy) * cellSize } } ```
2018/04/02
[ "https://Stackoverflow.com/questions/49604025", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7944978/" ]
This seems a little bit like homework, so lets try to get you on the right track over outright providing the code to accomplish this. You're going to want to create a loop that performs your code a certain number of times. Let's say we just want to output a certain string 5 times. As an example, here's some really simple code: ``` def testPrint(): print('I am text!') for i in range(5): testPrint() ``` This will create a function called testPrint() that prints text "I am Text!", then run that function 5 times in a loop. If you can apply this to the section of code you need to run 5 times, it should solve the problem you are facing.
This worked for me. It creates a table using the .messagebox module. You can enter your name into the entry label. Then, when you click the button it returns "Hello (name)". ``` from tkinter import * from tkinter.messagebox import * master = Tk() label1 = Label(master, text = 'Name:', relief = 'groove', width = 19) entry1 = Entry(master, relief = 'groove', width = 20) blank1 = Entry(master, relief = 'groove', width = 20) def show_answer(): a = entry1.get() b = "Hello",a blank1.insert(0, b) button1 = Button(master, text = 'Output Name', relief = 'groove', width = 20, command =show_answer) #Geometry label1.grid( row = 1, column = 1, padx = 10 ) entry1.grid( row = 1, column = 2, padx = 10 ) blank1.grid( row = 1, column = 3, padx = 10 ) button1.grid( row = 2, column = 2, columnspan = 2) #Static Properties master.title('Hello') ```
55,927,009
I'm trying to write a script that creates a playlist on my spotify account in python, from scratch and not using a module like *spotipy*. My question is how do I authenticate with my client id and client secret key using the *requests* module or grab an access token using those credentials?
2019/04/30
[ "https://Stackoverflow.com/questions/55927009", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9128668/" ]
Try this full Client Credentials Authorization flow. First step – get an authorization token with your credentials: ``` CLIENT_ID = " < your client id here... > " CLIENT_SECRET = " < your client secret here... > " grant_type = 'client_credentials' body_params = {'grant_type' : grant_type} url='https://accounts.spotify.com/api/token' response = requests.post(url, data=body_params, auth = (CLIENT_ID, CLIENT_SECRET)) token_raw = json.loads(response.text) token = token_raw["access_token"] ``` Second step – make a request to any of the playlists endpoint. Make sure to set a valid value for `<spotify_user>`. ``` headers = {"Authorization": "Bearer {}".format(token)} r = requests.get(url="https://api.spotify.com/v1/users/<spotify_user>/playlists", headers=headers) print(r.text) ```
As it is referenced [here](https://developer.spotify.com/documentation/web-api/reference/playlists/create-playlist/), you have to give the Bearer token to the Authorization header, and using requests it is done by declaring the "headers" optional: ```py r = requests.post(url="https://api.spotify.com/v1/users/{your-user}/playlists", headers={"Authorization": <token>, ...}) ``` The details of how can you get the Bearer token of your users can be found [here](https://developer.spotify.com/documentation/general/guides/authorization-guide/)
72,230,877
So I had created a python web scraper for my college capstone project that scraped around the web and followed links based on a random selection from the page. I utilized Python's request module to return links from a get request. I had it working flawlessly along with a graphing program that showed the program working in real time. I fired it up to show my professor and now the `.links` returns an empty dictionary for every single website. Originally I had added a skip for any site that returned no links, but now all of them are returning empty. I've reinstalled Python, reinstalled the requests module, and tried feeding the program websites manually and I cannot seem to find a reason for the change. For reference, I have been using *Portswigger.net* as a baseline to test the `.links` to see if I get them returned. It worked before, and now it does not. Here is the get request sample: ``` import requests Url = "https://portswigger.net" def GetRequest(url): with requests.get(url=Url) as response: try: links = response.links if links: return links else: return False except Exception as error: return error print(GetRequest(Url)) ``` **UPDATE** So out of the 200 sites I tested this morning, the only one to return links was *kite.com*. It returned the links no problem and my program was able to follow them and collect the data. Literally a week ago the whole program would run fine and return page links from almost every single website.
2022/05/13
[ "https://Stackoverflow.com/questions/72230877", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13450139/" ]
`Requests.Response.links` doesn't work like that [1]. It looks for [Links in the Header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Link), not link elements in the Response body. What you want is to extract link *elements* from the Response body, so I would recommend something like `lxml` or `beautifulsoup`. Seeing as this is fairly common and straight forward and this is a school project, I'll leave that task up to the reader. [1] - <https://docs.python-requests.org/en/latest/api/#requests.Response.links>
Parsing links with `beautifulsoup4` is a possible solution: ```py import requests from bs4 import BeautifulSoup def get_links(url: str) -> list[str]: with requests.get(url) as response: soup = BeautifulSoup(response.text, features='html.parser') links = [] for link in soup.find_all('a'): target = link.get('href') if target.startswith('http'): links.append(target) return links links = get_links('https://portswigger.com') print(*links, sep='\n') # https://forum.portswigger.net/ # https://portswigger.net/web-security # https://portswigger.net/research # https://portswigger.net/daily-swig # ... ```
62,556,358
Sometimes when I run the code it gives me the correct output, other times it says "List index out of range" and other times it just continues following code. I found the code on: <https://www.codeproject.com/articles/873060/python-search-youtube-for-video> How can I fix this? ``` searchM = input("Enter the movie you would like to search: ") def watch_trailer(): query_string = urllib.parse.urlencode({"search_query" : searchM}) html_content = urllib.request.urlopen("http://www.youtube.com/results?" + query_string) search_results = re.findall(r'href=\"\/watch\?v=(.{11})', html_content.read().decode()) print("Click on the link to watch the trailer: ","http://www.youtube.com/watch?v="+search_results[0]) watch_trailer() ```
2020/06/24
[ "https://Stackoverflow.com/questions/62556358", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13757098/" ]
The error occurs when no 'search results' have been obtained, such that search\_results[0] cannot be found. I would suggest you use an 'if/else' statement, something like: ``` if len(search_results) == 0: print("No search results obtained. Please try again.") else: print("Click on the link to watch the trailer: ","http://www.youtube.com/watch?v="+search_results[0]) ```
search[0] will return the first element of the list. However, if there are no elements in the list, there will not be a first element in the list, and "List index out of range". I recommend adding an if statement to check if the length of search\_results is greater than 0 and then printing search[0]. Hope this helps! ``` if len(search_results) > 0: print(search_results[0]) else: print("There are no results for this search") ```
51,140,417
For the past 4 days I have been working to get taskwarrior and taskwarrior server running on windows 10. It has proven quite a challenge for me. I followed the steps written below: "Building the Stable Version" on <https://taskwarrior.org/docs/build.html> and created a folder: ``` C:\taskwarrior ``` Opened Developer Command Prompt for VC 2017 ``` cd /d C:/taskwarrior git clone https://github.com/GothenburgBitFactory/taskwarrior.git taskwarrior.git cd taskwarrior.git git checkout master ``` And then depending on whether I try to build taskwarrior with Sync enabled (automatically unless manually disabled): ``` cmake -DCMAKE_BUILD_TYPE=release . ``` > > GNUTLS\_library is missing > > > or: ``` cmake -DCMAKE_BUILD_TYPE=release . -DENABLE_SYNC=OFF ``` > > -- libuuid not found. > > > **A short summary of steps followed and attempts so far:** 1. Downloaded and installed Microsoft Visual C++ 2017 Redistributable (x64 and x86) from: <https://visualstudio.microsoft.com/vs/features/cplusplus/> 2. Ensured cl was available as suggested in the documentation of microsoft: <https://msdn.microsoft.com/en-us/library/cyz1h6zd.aspx> 3. Downloaded MinGW installation Manager and installed the base package as was suggested on <http://www.mingw.org/wiki/Getting_Started>: > > If you do wish to install mingw-get-inst.exe's obligatory set, > (including the GNU C Compiler, the GNU Debugger (GDB), and the GNU > make tool), you should select the mingw-base package for installation. > > > 4. Installing Cmake from <https://cmake.org/download/> 5. Running the commands described above from cmd in administrator mode 6. Opening Cmake selecting the source folder: `C:/taskwarrior/taskwarrior.git` With build folder: ``` C:/taskwarrior ``` This gave the exact same errors as when I tried the it through the Developer Command Prompt for VC 2017 described above, from which I conclude that I do not have a typo in my commands described above. 7. Even though it should be installed with Mingw already, GNU is still not found (even after reboot). So I tried downloading it manually from: 8. <http://gnuwin32.sourceforge.net/packages/make.htm> 9. <https://sourceforge.net/projects/gnuwin32/> 10. And I tried the following commands from Command prompt: `install libgnutlsxx28 gnutls-dev` `install gnutls-dev` 11. As suggested in the install file in taskwarrior for Debian based distributions, I tried: `libgnutls-dev` Which opens the IncrediBuild Version 9.2.1 Setup, I currently do not know what that does. 12. I tried downloading the libuuid library from: <https://sourceforge.net/projects/libuuid/> but I currently do not know how to build and install it. 13. I tried installing it through python in cmd with: `easy_install python-libuuid` 14. Learning building programs from source code from: <https://msdn.microsoft.com/en-us/library/cyz1h6zd.aspx> 15. Learning and practicing from <https://github.com/codebox/bitmeteros/wiki/How-to-build-on-Windows>. 16. At the end I learned I had [Cygwin](https://cygwin.com/install.html) installed already and that I could simply install an old version of taskwarrior by reinstalling cygwin and checking/marking the task package. So I have the taskwarrior running, but not the taskwarrior server. And moreover I am trying to learn how to build code/projects from source, so I am trying to make a succesfull build to increase my skillset and hence toolset. 17. The explenation to install GNU TLS 3.6.2 on <https://www.gnutls.org/manual/gnutls.html#Downloading-and-installing> is limited to: > > The package is then extracted, configured and built like many other packages that use Autoconf. For detailed information on configuring and building it, refer to the INSTALL file that is part of the distribution archive. Typically you invoke ./configure and then make check install. > > > However, the latest GNUTLS for Windows x64 download file: Latest w64 version on gitlab on: <https://www.gnutls.org/download.html> named artifacts.zip contains no file named `INSTALL`. So I am currently working on understanding how to configure and built using autoconf. **Question:** *Do you know how I could install the GNU library and/or libuuid library on windows 10?*
2018/07/02
[ "https://Stackoverflow.com/questions/51140417", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7437143/" ]
I'm not sure that it is still relevant to your problem, but I was able to build taskwarrior v2.5.1 under 64-bit cygwin (on Win7), using the `cmake` line from here: [TW-1845 Cygwin build fails, missing get\_current\_dir\_name](https://github.com/GothenburgBitFactory/taskwarrior/issues/1861) Namely, this `cmake` line followed by `make`: ``` cmake -DHAVE_GET_CURRENT_DIR_NAME=0 ```
I am likely to have misunderstood the context. GnuTLS Appears to be a program that works/is made for a linux/debian operating system. Nevertheless, the following two solutions were effective in: 1. Finding and using the UUID library in Windows. 2. Solving the XY-problem and using GnuTLS on a "windows pc" (with Linux on it).: For the missing UUID missing library error: 1. Open explorer>go to C: (or other system disc)>search for: `uuid.lib`>Memorize the path to the/any `uuid.lib` file. (For me `C:/Program Files (x86)/Microsoft SDKs/Windows/v7.1A/Lib worked`) 2. Open Cmake and in UUID\_LIBRARY\_DIR enter: 3. `C:/Program Files (x86)/Microsoft SDKs/Windows/v7.1A/Lib` 4. Then in UUID\_LIBRARY enter: `C:/Program Files (x86)/Microsoft SDKs/Windows/v7.1A/Lib/Uuid.Lib` Where you substitute `C:/Program Files (x86)/Microsoft SDKs/Windows/v7.1A/Lib` with the path you found yourself for your own UUID.lib at step 1. That made CMake overcome the UUID error in windows. Now for the GnuTLS I could not find a solution in windows itself. But when I read the taskserver installation guide on: <https://gitpitch.com/GothenburgBitFactory/taskserver-setup#/4/4> I learned that Taskwarrior is not intended to run on Windows itself/natively, but in a linux environment (To be specific, the linux distribution Ubuntu is recommended to be installed on windows as is specified here: <https://taskwarrior.org/download/>) it takes 1 click to completely download and install the linux distribution (which currently looks like an emulator to me). In the windows store one can download Ubuntu and other Linux distributions as Debian GNU/Linux: <https://learn.microsoft.com/en-us/windows/wsl/install-win10>. Since I had quite a bit of difficulties installing GnuTLS I tried the debian GNU/Linux distribution, hoping it would be pre-installed in the distribution. The following commands successfully installed taskwarrior and GnuTLS and Taskserver on the debian GNU/Linux: 1. `sudo apt-get update` 2. `sudo apt-get install taskwarrior` 3. `cd /home/a/` 4. then create new directory 'taskwarrior' 5. `mkdir taskwarrior` 6. `cd /home/a/taskwarrior` Task Server installation in Debian: 7. `sudo apt install g++` 8. `sudo apt install libgnutls28-dev` 9. `sudo apt install uuid-dev` 10. `sudo apt install cmake` 11. `**sudo apt install gnutls-utils**` gnutls failed so: 12. `**sudo apt-get update**` 13. `**sudo apt install gnutls-utils**` 14. `sudo apt-get update` 15. `sudo apt-get install git-core` Source: <https://gitpitch.com/GothenburgBitFactory/taskserver-setup#/6/1> suggests you enter: `git clone --recurse-submodules=yes https://github.com/GothenburgBitFactory/taskserver.git taskserver.git` that gave the following error: `option`recurse-submodules`takes no value`, so rewrite it to: 16. `git clone https://github.com/GothenburgBitFactory/taskserver.git taskserver.git` 17. `cd taskserver.git/` 18. `git checkout master` 19. `cmake -DCMAKE_BUILD_TYPE=release .` 20. `make` Now you can test the build as described in: <https://gitpitch.com/GothenburgBitFactory/taskserver-setup#/6/8> Note: the SOURCEDIR now is home/a/taskwarrior/taskserver.git (/test I currently do not know whether /test is a subfolder of the source or the actual source directory) 21. `sudo make install` Note: You can Verify GnuTLS installation with: 22. `task diagnostics | grep libgnutls` 23. `sudo apt install taskd` **Remaining unanswered** The above only answers half of my question (and solves the [XY-problem](https://en.wikipedia.org/wiki/XY_problem)). The installation of GnuTLS on windows itself is still not solved. I currently am unsure about the download > > GNU for windows > > > Latest w64 version on gitlab gnutls\_3\_6\_0\_1:mingw64 > > > on <https://gnutls.org/download.html>. 1. It contains a lib and a bin folder, which seems to indicate that even the files listed under "windows" are intended for a Linux Operating System(OS) (since I think those type of folders are not used conventionally used in windows/I do not know what to do with them/how to install them). 2. That would imply that GnuTLS assumes that the only application of GnuTLS, even on a Windows operating system happens in a Linux system. It could also just be my lack of knowledge/work/understanding in how to use/install those files in windows. So if anyone can still answer how GnuTLS on windows is intended to be applied, I would greatly appreciate the insight!
33,355,299
I've already searched SO for how to flatten a list of lists (i.e. here:[Making a flat list out of list of lists in Python](https://stackoverflow.com/questions/952914/making-a-flat-list-out-of-list-of-lists-in-python)) but none of the solutions I find addresses flattening a list of lists of lists to just a list of lists. I have: ``` my_list = [ [ [1,2,3],[4,5] ], [ [9],[8,9,10],[3,4,6] ], [ [1] ] ] ``` I want: ``` my_list = [ [1,2,3,4,5], [9,8,9,10,3,4,6], [1] ] ``` The solution should work for a list of floats as well. Any suggestions?
2015/10/26
[ "https://Stackoverflow.com/questions/33355299", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2483176/" ]
If we apply the logic from [this answer](https://stackoverflow.com/a/952952/771848), should not it be just: ``` In [2]: [[item for subsublist in sublist for item in subsublist] for sublist in my_list] Out[2]: [[1, 2, 3, 4, 5], [9, 8, 9, 10, 3, 4, 6], [1]] ``` And, similarly via [`itertools.chain()`](https://stackoverflow.com/a/953097/771848): ``` In [3]: [list(itertools.chain(*sublist)) for sublist in my_list] Out[3]: [[1, 2, 3, 4, 5], [9, 8, 9, 10, 3, 4, 6], [1]] ```
You could use this recursive subroutine ``` def flatten(lst, n): if n == 0: return lst return flatten([j for i in lst for j in i], n - 1) mylist = [ [ [1,2,3],[4,5] ], [ [9],[8,9,10],[3,4,6] ], [ [1] ] ] flatten(mylist, 1) #=> [[1, 2, 3], [4, 5], [9], [8, 9, 10], [3, 4, 6], [1]] flatten(mylist, 2) #=> [1, 2, 3, 4, 5, 9, 8, 9, 10, 3, 4, 6, 1] ```
33,355,299
I've already searched SO for how to flatten a list of lists (i.e. here:[Making a flat list out of list of lists in Python](https://stackoverflow.com/questions/952914/making-a-flat-list-out-of-list-of-lists-in-python)) but none of the solutions I find addresses flattening a list of lists of lists to just a list of lists. I have: ``` my_list = [ [ [1,2,3],[4,5] ], [ [9],[8,9,10],[3,4,6] ], [ [1] ] ] ``` I want: ``` my_list = [ [1,2,3,4,5], [9,8,9,10,3,4,6], [1] ] ``` The solution should work for a list of floats as well. Any suggestions?
2015/10/26
[ "https://Stackoverflow.com/questions/33355299", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2483176/" ]
If we apply the logic from [this answer](https://stackoverflow.com/a/952952/771848), should not it be just: ``` In [2]: [[item for subsublist in sublist for item in subsublist] for sublist in my_list] Out[2]: [[1, 2, 3, 4, 5], [9, 8, 9, 10, 3, 4, 6], [1]] ``` And, similarly via [`itertools.chain()`](https://stackoverflow.com/a/953097/771848): ``` In [3]: [list(itertools.chain(*sublist)) for sublist in my_list] Out[3]: [[1, 2, 3, 4, 5], [9, 8, 9, 10, 3, 4, 6], [1]] ```
This is an inside-out version of fl00r's recursive answer which coincides more with what OP was after: ``` def flatten(lists,n): if n == 1: return [x for xs in lists for x in xs] else: return [flatten(xs,n-1) for xs in lists] >>> flatten(my_list,1) [[1, 2, 3], [4, 5], [9], [8, 9, 10], [3, 4, 6], [1]] >>> flatten(my_list,2) [[1, 2, 3, 4, 5], [9, 8, 9, 10, 3, 4, 6], [1]] ```
33,355,299
I've already searched SO for how to flatten a list of lists (i.e. here:[Making a flat list out of list of lists in Python](https://stackoverflow.com/questions/952914/making-a-flat-list-out-of-list-of-lists-in-python)) but none of the solutions I find addresses flattening a list of lists of lists to just a list of lists. I have: ``` my_list = [ [ [1,2,3],[4,5] ], [ [9],[8,9,10],[3,4,6] ], [ [1] ] ] ``` I want: ``` my_list = [ [1,2,3,4,5], [9,8,9,10,3,4,6], [1] ] ``` The solution should work for a list of floats as well. Any suggestions?
2015/10/26
[ "https://Stackoverflow.com/questions/33355299", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2483176/" ]
If we apply the logic from [this answer](https://stackoverflow.com/a/952952/771848), should not it be just: ``` In [2]: [[item for subsublist in sublist for item in subsublist] for sublist in my_list] Out[2]: [[1, 2, 3, 4, 5], [9, 8, 9, 10, 3, 4, 6], [1]] ``` And, similarly via [`itertools.chain()`](https://stackoverflow.com/a/953097/771848): ``` In [3]: [list(itertools.chain(*sublist)) for sublist in my_list] Out[3]: [[1, 2, 3, 4, 5], [9, 8, 9, 10, 3, 4, 6], [1]] ```
For this particular case, ``` In [1]: [sum(x,[]) for x in my_list] Out[1]: [[1, 2, 3, 4, 5], [9, 8, 9, 10, 3, 4, 6], [1]] ``` is the shortest and the fastest method: ``` In [7]: %timeit [sum(x,[]) for x in my_list] 100000 loops, best of 3: 5.93 µs per loop ```
33,355,299
I've already searched SO for how to flatten a list of lists (i.e. here:[Making a flat list out of list of lists in Python](https://stackoverflow.com/questions/952914/making-a-flat-list-out-of-list-of-lists-in-python)) but none of the solutions I find addresses flattening a list of lists of lists to just a list of lists. I have: ``` my_list = [ [ [1,2,3],[4,5] ], [ [9],[8,9,10],[3,4,6] ], [ [1] ] ] ``` I want: ``` my_list = [ [1,2,3,4,5], [9,8,9,10,3,4,6], [1] ] ``` The solution should work for a list of floats as well. Any suggestions?
2015/10/26
[ "https://Stackoverflow.com/questions/33355299", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2483176/" ]
This is an inside-out version of fl00r's recursive answer which coincides more with what OP was after: ``` def flatten(lists,n): if n == 1: return [x for xs in lists for x in xs] else: return [flatten(xs,n-1) for xs in lists] >>> flatten(my_list,1) [[1, 2, 3], [4, 5], [9], [8, 9, 10], [3, 4, 6], [1]] >>> flatten(my_list,2) [[1, 2, 3, 4, 5], [9, 8, 9, 10, 3, 4, 6], [1]] ```
You could use this recursive subroutine ``` def flatten(lst, n): if n == 0: return lst return flatten([j for i in lst for j in i], n - 1) mylist = [ [ [1,2,3],[4,5] ], [ [9],[8,9,10],[3,4,6] ], [ [1] ] ] flatten(mylist, 1) #=> [[1, 2, 3], [4, 5], [9], [8, 9, 10], [3, 4, 6], [1]] flatten(mylist, 2) #=> [1, 2, 3, 4, 5, 9, 8, 9, 10, 3, 4, 6, 1] ```
33,355,299
I've already searched SO for how to flatten a list of lists (i.e. here:[Making a flat list out of list of lists in Python](https://stackoverflow.com/questions/952914/making-a-flat-list-out-of-list-of-lists-in-python)) but none of the solutions I find addresses flattening a list of lists of lists to just a list of lists. I have: ``` my_list = [ [ [1,2,3],[4,5] ], [ [9],[8,9,10],[3,4,6] ], [ [1] ] ] ``` I want: ``` my_list = [ [1,2,3,4,5], [9,8,9,10,3,4,6], [1] ] ``` The solution should work for a list of floats as well. Any suggestions?
2015/10/26
[ "https://Stackoverflow.com/questions/33355299", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2483176/" ]
This is an inside-out version of fl00r's recursive answer which coincides more with what OP was after: ``` def flatten(lists,n): if n == 1: return [x for xs in lists for x in xs] else: return [flatten(xs,n-1) for xs in lists] >>> flatten(my_list,1) [[1, 2, 3], [4, 5], [9], [8, 9, 10], [3, 4, 6], [1]] >>> flatten(my_list,2) [[1, 2, 3, 4, 5], [9, 8, 9, 10, 3, 4, 6], [1]] ```
For this particular case, ``` In [1]: [sum(x,[]) for x in my_list] Out[1]: [[1, 2, 3, 4, 5], [9, 8, 9, 10, 3, 4, 6], [1]] ``` is the shortest and the fastest method: ``` In [7]: %timeit [sum(x,[]) for x in my_list] 100000 loops, best of 3: 5.93 µs per loop ```
35,494,331
How can I get generics to work in Python.NET with CPython. I get an error when using the subscript syntax from [Python.NET Using Generics](http://pythonnet.sourceforge.net/readme.html#generics) ``` TypeError: unsubscriptable object ``` With Python 2.7.11 + pythonnet==2.1.0.dev1 ``` >python.exe Python 2.7.11 (v2.7.11:6d1b6a68f775, Dec 5 2015, 20:32:19) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import clr >>> from System import EventHandler >>> from System import EventArgs >>> EventHandler[EventArgs] Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unsubscriptable object ``` I've also tried pythonnet==2.0.0 and building form github ca15fe8 with ReleaseWin x86 and got the same error. With IronPython-2.7.5: ``` >ipy.exe IronPython 2.7.5 (2.7.5.0) on .NET 4.0.30319.0 (32-bit) Type "help", "copyright", "credits" or "license" for more information. >>> import clr >>> from System import EventHandler >>> from System import EventArgs >>> EventHandler[EventArgs] <type 'EventHandler[EventArgs]'> ```
2016/02/18
[ "https://Stackoverflow.com/questions/35494331", "https://Stackoverflow.com", "https://Stackoverflow.com/users/742745/" ]
You can get the generic class object explicitly: ``` EventHandler = getattr(System, 'EventHandler`1') ``` The number indicates the number of generic arguments.
That doesn't work because there are both generic and non-generic versions of the `EventHandler` class that exist in the `System` namespace. The name is overloaded. You need to indicate that you want the generic version. I'm not sure how exactly Python.NET handles overloaded classes/functions but it seems like it has an `Overloads` property. Try something like this and see how that goes: ``` EventHandler_EventArgs = EventHandler.Overloads[EventArgs] ``` (this doesn't work) It doesn't seem like Python.NET has ways to resolve the overloaded class name, each overload is treated as separate distinct types (using their clr names). It doesn't do the same thing as IronPython and lump them into a single containing type. In this particular case, the `EventArgs` name corresponds to the non-generic `EventArgs` type. You'll need to get the appropriate type directly from the System module as filmor illustrates.
30,189,013
is the code he wants me to enter that fails ``` from sys import argv script, user_name = argv prompt = '> ' print "Hi %s, I'm the %s script." % (user_name, script) print "I'd like to ask you a few questions." print "Do you like me %s?" % user_name likes = raw_input(prompt) ``` is the code I modified after seeing errors and knowing he uses python 2, I've just been making corrections to his code as I find them online. ``` from sys import argv script, user_name = argv prompt = '> ' print ("Hi" user_name: %s, "I/'m the", %s: script.) print ("I;d like tok ask you a few questions") print ("Do you like me %s") % (user_name) likes = input(prompt) ``` --- All `%s`, `%d` `%r` have failed for me. Is this a python 2 convention? Should I be using something else? for example ``` foo = bar print ("the variable foo %s is a fundamental programming issue.) ``` I have tried using tuples? as in: ``` print ("the variable foo", %s: foo, "is a fundamental programming issue.") ``` with no success
2015/05/12
[ "https://Stackoverflow.com/questions/30189013", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4891078/" ]
Here is one method: ``` select v.* from vusearch as v where v.JobId = (select max(v2.JobId) from vusearch as v2 where v2.AddressId = v.AddressId ); ```
Managed to get it fixed - I probably hadn't provided enough information as I was trying to keep my explanation simple. Many thanks for your help Gordon ((vuSearch.PDID) IN ( (SELECT Max(v2.PDID) FROM vuSearch AS v2 GROUP BY v2.PAID)))
51,947,819
I have a pandas dataframe with 5 years daily time series data. I want to make a monthly plot from whole datasets so that the plot should shows variation (std or something else) within monthly data. Simillar figure I tried to create but did not found a way to do that: [![enter image description here](https://i.stack.imgur.com/wVxxx.png)](https://i.stack.imgur.com/wVxxx.png) for example, I have a sudo daily precipitation data: ``` date = pd.to_datetime("1st of Dec, 1999") dates = date+pd.to_timedelta(np.arange(1900), 'D') ppt = np.random.normal(loc=0.0, scale=1.0, size=1900).cumsum() df = pd.DataFrame({'pre':ppt},index=dates) ``` Manually I can do it like: ``` one = df['pre']['1999-12-01':'2000-11-29'].values two = df['pre']['2000-12-01':'2001-11-30'].values three = df['pre']['2001-12-01':'2002-11-30'].values four = df['pre']['2002-12-01':'2003-11-30'].values five = df['pre']['2003-12-01':'2004-11-29'].values df = pd.DataFrame({'2000':one,'2001':two,'2002':three,'2003':four,'2004':five}) std = df.std(axis=1) lw = df.mean(axis=1)-std up = df.mean(axis=1)+std plt.fill_between(np.arange(365), up, lw, alpha=.4) ``` I am looking for the more pythonic way to do that instead of doing it manually! Any helps will be highly appreciated
2018/08/21
[ "https://Stackoverflow.com/questions/51947819", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5111380/" ]
If I'm understanding you correctly you'd like to plot your daily observations against a monthly periodic mean +/- 1 standard deviation. And that's what you get in my screenshot below. Nevermind the lackluster design and color choice. We'll get to that if this is something you can use. And please notice that I've replaced your `ppt = np.random.rand(1900)` with `ppt = np.random.normal(loc=0.0, scale=1.0, size=1900).cumsum()` just to make the data look a bit more like your screenshot. [![enter image description here](https://i.stack.imgur.com/WgmOA.png)](https://i.stack.imgur.com/WgmOA.png) Here I've aggregated the daily data by month, and retrieved mean and standard deviation for each month. Then I've merged that data with the original dataframe so that you're able to plot both the source and the grouped data like this: ``` # imports import matplotlib.pyplot as plt import pandas as pd import matplotlib.dates as mdates import numpy as np # Data that matches your setup, but with a random # seed to make it reproducible np.random.seed(42) date = pd.to_datetime("1st of Dec, 1999") dates = date+pd.to_timedelta(np.arange(1900), 'D') #ppt = np.random.rand(1900) ppt = np.random.normal(loc=0.0, scale=1.0, size=1900).cumsum() df = pd.DataFrame({'ppt':ppt},index=dates) # A subset df = df.tail(200) # Add a yearmonth column df['YearMonth'] = df.index.map(lambda x: 100*x.year + x.month) # Create aggregated dataframe df2 = df.groupby('YearMonth').agg(['mean', 'std']).reset_index() df2.columns = ['YearMonth', 'mean', 'std'] # Merge original data and aggregated data df3 = pd.merge(df,df2,how='left',on=['YearMonth']) df3 = df3.set_index(df.index) df3 = df3[['ppt', 'mean', 'std']] # Function to make your plot def monthplot(): fig, ax = plt.subplots(1) ax.set_facecolor('white') # Define upper and lower bounds for shaded variation lower_bound = df3['mean'] + df3['std']*-1 upper_bound = df3['mean'] + df3['std'] fig, ax = plt.subplots(1) ax.set_facecolor('white') # Source data and mean ax.plot(df3.index,df3['mean'], lw=0.5, color = 'red') ax.plot(df3.index, df3['ppt'], lw=0.1, color = 'blue') # Variation and shaded area ax.fill_between(df3.index, lower_bound, upper_bound, facecolor='grey', alpha=0.5) fig = ax.get_figure() # Assign months to X axis locator = mdates.MonthLocator() # every month # Specify the format - %b gives us Jan, Feb... fmt = mdates.DateFormatter('%b') X = plt.gca().xaxis X.set_major_locator(locator) X.set_major_formatter(fmt) fig.show() monthplot() ``` Check out [this post](https://stackoverflow.com/questions/46555819/months-as-axis-ticks) for more on axis formatting and [this post](https://stackoverflow.com/questions/25146121/extracting-just-month-and-year-from-pandas-datetime-column-python) on how to add a YearMonth column.
In your example, you have a few mistakes, but I think it isn't important. Do you want all years to be on the same graphic (like in your example)? If you do, this may help you: ``` df['month'] = df.index.strftime("%m-%d") df['year'] = df.index.year df.set_index(['month']).drop(['year'],1).plot() ```
67,010,037
I am not an expert in python. When I run this code, I get an error stating that the source is empty. It occurs in the statement that converts bgr to rgb from a live video feed. I also attached some of the error code below. I did try to resolve it changing some of it, but it did not work out. So, if you have any ideas, please share. ``` import cv2 import mediapipe as mp import time class handDetector(): def __init__(self, mode = False, maxHands=2, detectionCon=0.5, trackCon=0.5): self.mode = mode self.maxHands = maxHands self.detectionCon = detectionCon self.trackCon = trackCon self.mpHands = mp.solutions.hands self.hands = self.mpHands.Hands(self.mode, self.maxHands, self.detectionCon, self.trackCon) self.mpDraw = mp.solutions.drawing_utils def findhands(self, img, draw=True): imgRGB = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) self.results = self.hands.process(imgRGB) if self.results.multi_hand_landmarks: for handLms in self.results.multi_hand_landmarks: if draw: self.mpDraw.draw_landmarks(img, handLms, self.mpHands.HAND_CONNECTIONS) return img # for id, lm in enumerate(handLms.landmark): # # print(id,lm) # h, w, c = img.shape # cx, cy = int(lm.x * w), int(lm.y * h) # print(id, cx, cy) # # if id==4: # cv2.circle(img, (cx, cy), 15, (255, 0, 255), cv2.FILLED) def findPosition(self, img, handNo=0, draw=True): lmList = [] if self.results.multi_hand_landmarks: myHand = self.results.multi_hand_landmarks[handNo] for id, lm in enumerate(myHand.landmark): # print(id, lm) h, w, c = img.shape cx, cy = int(lm.x * w), int(lm.y * h) # print(id, cx, cy) lmList.append([id, cx, cy]) if draw: cv2.circle(img, (cx, cy), 10, (255, 0, 0), cv2.FILLED) return lmList def main(): pTime = 0 cTime = 0 cap = cv2.VideoCapture(0) detector = handDetector() while True: success,img = cap.read() img = detector.findhands(img) lmList = detector.findPosition(img) if len(lmList) != 0: print(lmList[4]) cTime = time.time() fps = 1/(cTime-pTime) pTime = cTime cv2.putText(img, str(int(fps)), (10, 70), cv2.FONT_HERSHEY_PLAIN, 3, (255, 0, 255), 3) cv2.imshow("Image", img) cv2.waitKey(1) if __name__=="__main__": main() ``` Error code is : ``` cv2.cvtColor(img, cv2.COLOR_BGR2RGB) cv2.error: OpenCV(4.5.1) error: (-215:Assertion failed) !_src.empty() in function 'cv::cvtColor' ``` Thank You
2021/04/08
[ "https://Stackoverflow.com/questions/67010037", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14020038/" ]
You can use `Series.isin`: ``` In [1998]: res = df1[df1.id_number.isin(df2.id_number) & df1.accuracy.ge(85)] In [1999]: res Out[1999]: Name Contact_number id_number accuracy 0 Eric 9786543628 AZ256hy 90 1 Jack 9786543628 AZ98kds 85 ``` **EDIT:** If you want only certain columns: ``` In [2089]: res = df1[df1.id_number.isin(df2.id_number) & df1.accuracy.ge(85)][['Name', 'Contact_number']] In [2090]: res Out[2090]: Name Contact_number 0 Eric 9786543628 1 Jack 9786543628 ```
Edit: I made changes to the conditions. This should work ``` df = pd.read_excel(open(r'input.xlsx', 'rb'), sheet_name='sheet1') df2 = pd.read_excel(open(r'input.xlsx', 'rb'), sheet_name='sheet2') df.loc[(df['id_number'] == df2['id_number']) & (df['accuracy']>= 85),['Name','Contact_number', 'id_number']] ```
28,458,785
How can I pass a `sed` command to `popen` without using a raw string? When I pass an sed command to `popen` in the list form I get an error: `unterminated address regex` (see first example) ```python >>> COMMAND = ['sed', '-i', '-e', "\$amystring", '/home/map/myfile'] >>> subprocess.Popen(COMMAND).communicate(input=None) sed: -e expression #1, char 11: unterminated address regex ``` using the raw string form it works as expected: ```python >>> COMMAND = r"""sed -i -e "\$amystring" /home/map/myfile""" >>> subprocess.Popen(COMMAND, shell=True).communicate(input=None) ``` I'm really interested in passing `"\$amystring"` as an element of the list. Please avoid answers like ```python >>> COMMAND = r" ".join(['sed', '-i', '-e', "\$amystring", '/home/map/myfile'] >>> subprocess.Popen(COMMAND, shell=True).communicate(input=None) ```
2015/02/11
[ "https://Stackoverflow.com/questions/28458785", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1659599/" ]
The difference between the two forms is that with `shell=True` as an argument, the string gets passed as is to the shell, which then interprets it. This results in (with bash): ``` sed -i -e \$amystring /home/map/myfile ``` being run. With the list args and the default `shell=False`, python calls the executable directly with the arguments in the list. In this case, the literal string is passed to sed, ``` sed -i -e '\$amystring' /home/map/myfile ``` and `'\$amystring'` is not a valid `sed` expression. In this case, you'd need to call ``` >>> COMMAND = ['sed', '-i', '-e', "$amystring", '/home/map/myfile'] >>> subprocess.Popen(COMMAND).communicate(input=None) ``` since the string does not need to be escaped for the shell.
There is not such thing as a raw string. There are only raw string *literals*. A literal -- it is something that you type in the Python source code. `r'\$amystring'` and `'\\$amystring'` are the same *strings objects* despite being represented using different string *string literals*. As [@Jonathan Villemaire-Krajden said](https://stackoverflow.com/a/28460565/4279): if there is no `shell=True` then you don't need to escape `$` shell metacharacter. You only need it if you run the command in the shell: ``` $ python -c 'import sys; print(sys.argv)' "\$amystring" ['-c', '$amystring'] ``` Note: there is no backslash in the output. Don't use `.communicate()` unless you redirect standard streams using `PIPE`, you could use `call()`, `check_call()` instead: ``` import subprocess rc = subprocess.call(['sed', '-i', '-e', '$amystring', '/home/map/myfile']) ``` To emulate the `$amystring` sed command in Python (± newlines): ``` with open('/home/map/myfile', 'a') as file: print('mystring', file=file) ```
65,354,710
I was trying to Connect and Fetch data from BigQuery Dataset to Local Pycharm Using Pyspark. I ran this below Script in Pycharm: ``` from pyspark.sql import SparkSession spark = SparkSession.builder\ .config('spark.jars', "C:/Users/PycharmProjects/pythonProject/spark-bigquery-latest.jar")\ .getOrCreate() conn = spark.read.format("bigquery")\ .option("credentialsFile", "C:/Users/PycharmProjects/pythonProject/google-bq-api.json")\ .option("parentProject", "Google-Project-ID")\ .option("project", "Dataset-Name")\ .option("table", "dataset.schema.tablename")\ .load() conn.show() ``` For this I got the below error: ``` Exception in thread "main" java.io.IOException: No FileSystem for scheme: C at org.apache.hadoop.fs.FileSystem.getFileSystemClass(FileSystem.java:2660) at org.apache.hadoop.fs.FileSystem.createFileSystem(FileSystem.java:2667) at org.apache.hadoop.fs.FileSystem.access$200(FileSystem.java:94) at org.apache.hadoop.fs.FileSystem$Cache.getInternal(FileSystem.java:2703) at org.apache.hadoop.fs.FileSystem$Cache.get(FileSystem.java:2685) at org.apache.hadoop.fs.FileSystem.get(FileSystem.java:373) at org.apache.spark.deploy.DependencyUtils$.resolveGlobPath(DependencyUtils.scala:191) at org.apache.spark.deploy.DependencyUtils$.$anonfun$resolveGlobPaths$2(DependencyUtils.scala:147) at org.apache.spark.deploy.DependencyUtils$.$anonfun$resolveGlobPaths$2$adapted(DependencyUtils.scala:145) at scala.collection.TraversableLike.$anonfun$flatMap$1(TraversableLike.scala:245) at scala.collection.IndexedSeqOptimized.foreach(IndexedSeqOptimized.scala:36) at scala.collection.IndexedSeqOptimized.foreach$(IndexedSeqOptimized.scala:33) at scala.collection.mutable.WrappedArray.foreach(WrappedArray.scala:38) at scala.collection.TraversableLike.flatMap(TraversableLike.scala:245) at scala.collection.TraversableLike.flatMap$(TraversableLike.scala:242) at scala.collection.AbstractTraversable.flatMap(Traversable.scala:108) at org.apache.spark.deploy.DependencyUtils$.resolveGlobPaths(DependencyUtils.scala:145) at org.apache.spark.deploy.SparkSubmit.$anonfun$prepareSubmitEnvironment$4(SparkSubmit.scala:363) at scala.Option.map(Option.scala:230) at org.apache.spark.deploy.SparkSubmit.prepareSubmitEnvironment(SparkSubmit.scala:363) at org.apache.spark.deploy.SparkSubmit.org$apache$spark$deploy$SparkSubmit$$runMain(SparkSubmit.scala:871) at org.apache.spark.deploy.SparkSubmit.doRunMain$1(SparkSubmit.scala:180) at org.apache.spark.deploy.SparkSubmit.submit(SparkSubmit.scala:203) at org.apache.spark.deploy.SparkSubmit.doSubmit(SparkSubmit.scala:90) at org.apache.spark.deploy.SparkSubmit$$anon$2.doSubmit(SparkSubmit.scala:1007) at org.apache.spark.deploy.SparkSubmit$.main(SparkSubmit.scala:1016) at org.apache.spark.deploy.SparkSubmit.main(SparkSubmit.scala) Traceback (most recent call last): File "C:\Users\naveen.chandar\PycharmProjects\pythonProject\BigQueryConnector.py", line 4, in <module> spark = SparkSession.builder.config('spark.jars', 'C:/Users/naveen.chandar/PycharmProjects/pythonProject/spark-bigquery-latest.jar').getOrCreate() File "C:\Users\naveen.chandar\AppData\Local\Programs\Python\Python39\lib\site-packages\pyspark\sql\session.py", line 186, in getOrCreate sc = SparkContext.getOrCreate(sparkConf) File "C:\Users\naveen.chandar\AppData\Local\Programs\Python\Python39\lib\site-packages\pyspark\context.py", line 376, in getOrCreate SparkContext(conf=conf or SparkConf()) File "C:\Users\naveen.chandar\AppData\Local\Programs\Python\Python39\lib\site-packages\pyspark\context.py", line 133, in __init__ SparkContext._ensure_initialized(self, gateway=gateway, conf=conf) File "C:\Users\naveen.chandar\AppData\Local\Programs\Python\Python39\lib\site-packages\pyspark\context.py", line 325, in _ensure_initialized SparkContext._gateway = gateway or launch_gateway(conf) File "C:\Users\naveen.chandar\AppData\Local\Programs\Python\Python39\lib\site-packages\pyspark\java_gateway.py", line 105, in launch_gateway raise Exception("Java gateway process exited before sending its port number") Exception: Java gateway process exited before sending its port number ``` So, I researched and tried it from different Diecrtory like "D-drive" and also tried to fix a static port with `set PYSPARK_SUBMIT_ARGS="--master spark://<IP_Address>:<Port>"`, but still I got the same error in Pycharm. Then I thought of trying the same script in local Command Prompt under Pyspark and I got this error: ``` failed to find class org/conscrypt/CryptoUpcalls ERROR:root:Exception while sending command. Traceback (most recent call last): File "D:\spark-2.4.7-bin-hadoop2.7\python\lib\py4j-0.10.7-src.zip\py4j\java_gateway.py", line 1152, in send_command answer = smart_decode(self.stream.readline()[:-1]) File "C:\Users\naveen.chandar\AppData\Local\Programs\Python\Python37\lib\socket.py", line 589, in readinto return self._sock.recv_into(b) ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host During handling of the above exception, another exception occurred: Traceback (most recent call last): File "D:\spark-2.4.7-bin-hadoop2.7\python\lib\py4j-0.10.7-src.zip\py4j\java_gateway.py", line 985, in send_command response = connection.send_command(command) File "D:\spark-2.4.7-bin-hadoop2.7\python\lib\py4j-0.10.7-src.zip\py4j\java_gateway.py", line 1164, in send_command "Error while receiving", e, proto.ERROR_ON_RECEIVE) py4j.protocol.Py4JNetworkError: Error while receiving Traceback (most recent call last): File "<stdin>", line 1, in <module> File "D:\spark-2.4.7-bin-hadoop2.7\python\pyspark\sql\dataframe.py", line 381, in show print(self._jdf.showString(n, 20, vertical)) File "D:\spark-2.4.7-bin-hadoop2.7\python\lib\py4j-0.10.7-src.zip\py4j\java_gateway.py", line 1257, in __call__ File "D:\spark-2.4.7-bin-hadoop2.7\python\pyspark\sql\utils.py", line 63, in deco return f(*a, **kw) File "D:\spark-2.4.7-bin-hadoop2.7\python\lib\py4j-0.10.7-src.zip\py4j\protocol.py", line 336, in get_return_value py4j.protocol.Py4JError: An error occurred while calling o42.showString ``` My Python Version is 3.7.9 and Spark Version is 2.4.7 So either way I ran out of idea's and I appreciate some help on any one of the situation I facing... Thanks In Advance!!
2020/12/18
[ "https://Stackoverflow.com/questions/65354710", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10030455/" ]
Start your file system references with `file:///c:/...`
You need to replace `/` with `\` for the path to work
29,580,828
I'm starting with Docker. I have started with a Hello World script in Python 3. This is my Dockerfile: ``` FROM ubuntu:latest RUN apt-get update RUN apt-get install python3 COPY . hello.py CMD python3 hello.py ``` In the same directory, I have this python script: ``` if __name__ == "__main__": print("Hello World!"); ``` I have built the image with this command: ``` docker build -t home/ubuntu-python-hello . ``` So far, so good. But when I try to run the script with this command: ``` docker run home/ubuntu-python-hello ``` I get this error: ``` /usr/bin/python3: can't find '__main__' module in 'hello.py' ``` What am I doing wrong? Any advice or suggestion is accepted, I'm just a newbie. Thanks.
2015/04/11
[ "https://Stackoverflow.com/questions/29580828", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3026283/" ]
Thanks to Gerrat, I solved it this way: ``` COPY hello.py hello.py ``` instead of ``` COPY . hello.py ```
You need to install python this way and confirm it with the -y. RUN apt-get update && apt-get install python3-dev -y
25,561,020
Below are the snippets of my code regarding file upload. Here is my HTML code where I will choose and upload the file: ```html <form ng-click="addImportFile()" enctype="multipart/form-data"> <label for="importfile">Import Time Events File:</label><br><br> <label for="select_import_file">SELECT FILE:</label><br> <input id="import_file" type="file" class="file btn btn-default" ng-disabled="CutOffListTemp.id== Null" data-show-preview="false"> <input class="btn btn-primary" type="submit" name="submit" value="Upload" ng-disabled="CutOffListTemp.id== Null"/><br/><br/> </form> ``` This is my controller that will link both html and my python file: ```javascript angular.module('hrisWebappApp').controller('ImportPayrollCtrl', function ($scope, $state, $stateParams, $http, ngTableParams, $modal, $filter) { $scope.addImportFile = function() { $http.post('http://127.0.0.1:5000/api/v1.0/upload_file/' + $scope.CutOffListTemp.id, {}) .success(function(data, status, headers, config) { console.log(data); if (data.success) { console.log('import success!'); } else { console.log('importing of file failed' ); } }) .error(function(data, status, headers, config) {}); }; ``` This is my python file: ```python @api.route('/upload_file/<int:id>', methods=['GET','POST']) @cross_origin(headers=['Content-Type']) def upload_file(id): print "hello" try: os.stat('UPLOAD_FOLDER') except: os.mkdir('UPLOAD_FOLDER') file = request.files['file'] print 'filename: ' + file.filename if file and allowed_file(file.filename): print 'allowing file' filename = secure_filename(file.filename) path=(os.path.join(current_app.config['UPLOAD_FOLDER'], filename)) file.save(path) #The end of the line which save the file you uploaded. return redirect(url_for('uploaded_file', filename=filename)) return ''' <!doctype html> <title>Upload new File</title> <h1>Upload new File</h1> <p>opsss it seems you uploaded an invalid filename please use .csv only</p> <form action="" method=post enctype=multipart/form-data> <p><input type=file name=file> <input type=submit value=Upload> </form> ''' ``` And the result in the console gave me this even if I select the correct format of file: ```html <!doctype html> <title>Upload new File</title> <h1>Upload new File</h1> <p>opsss it seems you uploaded an invalid filename please use .csv only</p> <form action="" method=post enctype=multipart/form-data> <p><input type=file name=file> <input type=submit value=Upload> </form> ``` This is not returning to my HTML and I cannot upload the file.
2014/08/29
[ "https://Stackoverflow.com/questions/25561020", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3988760/" ]
Hi I can finally upload the file, I change the angular part, I change it by this: ``` $scope.addImportFile = function() { var f = document.getElementById('file').files[0]; console.log(f); var formData = new FormData(); formData.append('file', f); $http({method: 'POST', url: 'http://127.0.0.1:5000/api/v1.0/upload_file/' +$scope.CutOffListTemp.id, data: formData, headers: {'Content-Type': undefined}, transformRequest: angular.identity}) .success(function(data, status, headers, config) {console.log(data); if (data.success) { console.log('import success!'); } }) .error(function(data, status, headers, config) { }); // } }; ```
The first thing is about the post request. Without ng-click="addImportFile()", the browser will usually take care of serializing form data and sending it to the server. So if you try: ``` <form method="put" enctype="multipart/form-data" action="http://127.0.0.1:5000/api/v1.0/upload_file"> <label for="importfile">Import Time Events File:</label><br><br> <label for="select_import_file">SELECT FILE:</label><br> <input id="import_file" type="file" name="file" class="file btn btn-default" ng-disabled="CutOffListTemp.id== Null" data-show-preview="false"> <input class="btn btn-primary" type="submit" name="submit" value="Upload" ng-disabled="CutOffListTemp.id== Null"/><br/><br/> </form> ``` and then in python, make your request url independent of scope.CutOffListTemp.id: @api.route('/upload\_file', methods=['GET','POST']) It probably will work. Alternatively, if you want to use your custom function to send post request, the browser will not take care of the serialization stuff any more, you will need to do it yourself. In angular, the API for $http.post is: $http.post('/someUrl', data).success(successCallback); If we use "{}" for the data parameter, which means empty, the server will not find the data named "file" (file = request.files['file']). Thus you will see Bad Request To fix it, we need to use formData to make file upload which requires your browser supports HTML5: ``` $scope.addImportFile = function() { var f = document.getElementById('file').files[0] var fd = new FormData(); fd.append("file", f); $http.post('http://127.0.0.1:5000/api/v1.0/upload_file/'+$scope.CutOffListTemp.id, fd, headers: {'Content-Type': undefined}) .success...... ``` Other than using the native javascript code above, there are plenty great angular file upload libraries which can make file upload much easier for angular, you may probably want to have a look at one of them (reference: [File Upload using AngularJS](https://stackoverflow.com/questions/18571001/file-upload-using-angularjs)): * <https://github.com/nervgh/angular-file-upload> * <https://github.com/leon/angular-upload> * ......
62,497,777
Can't start server using Apache + Django OS: MacOS Catalina Apache: 2.4.43 Python: 3.8 Django: 3.0.7 Used by Apache from Brew. mod\_wsgi installed via pip. The application is created through the standard command ``` django-admin startproject project_temp ``` The application starts when the command is called ``` python manage.py runserver ``` At start for mod\_wsgi - everything is OK ``` mod_wsgi-express start-server ``` When I start Apache, the server is not accessible. Checked at "localhost: 80". Tell me, what do I need to do to start the server? Httpd settings: ``` ServerRoot "/usr/local/opt/httpd" ServerName localhost Listen 80 LoadModule mpm_prefork_module lib/httpd/modules/mod_mpm_prefork.so LoadModule authn_file_module lib/httpd/modules/mod_authn_file.so LoadModule authn_core_module lib/httpd/modules/mod_authn_core.so LoadModule authz_host_module lib/httpd/modules/mod_authz_host.so LoadModule authz_groupfile_module lib/httpd/modules/mod_authz_groupfile.so LoadModule authz_user_module lib/httpd/modules/mod_authz_user.so LoadModule authz_core_module lib/httpd/modules/mod_authz_core.so LoadModule access_compat_module lib/httpd/modules/mod_access_compat.so LoadModule auth_basic_module lib/httpd/modules/mod_auth_basic.so LoadModule reqtimeout_module lib/httpd/modules/mod_reqtimeout.so LoadModule filter_module lib/httpd/modules/mod_filter.so LoadModule mime_module lib/httpd/modules/mod_mime.so LoadModule log_config_module lib/httpd/modules/mod_log_config.so LoadModule env_module lib/httpd/modules/mod_env.so LoadModule headers_module lib/httpd/modules/mod_headers.so LoadModule setenvif_module lib/httpd/modules/mod_setenvif.so LoadModule version_module lib/httpd/modules/mod_version.so LoadModule unixd_module lib/httpd/modules/mod_unixd.so LoadModule status_module lib/httpd/modules/mod_status.so LoadModule autoindex_module lib/httpd/modules/mod_autoindex.so LoadModule alias_module lib/httpd/modules/mod_alias.so LoadModule rewrite_module lib/httpd/modules/mod_rewrite.so LoadModule wsgi_module /Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/mod_wsgi/server/mod_wsgi-py38.cpython-38-darwin.so <Directory /> AllowOverride All </Directory> <Files ".ht*"> Require all denied </Files> <IfModule log_config_module> LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined LogFormat "%h %l %u %t \"%r\" %>s %b" common <IfModule logio_module> LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %I %O" combinedio </IfModule> CustomLog "/usr/local/var/log/httpd/access_log" common </IfModule> <IfModule headers_module> RequestHeader unset Proxy early </IfModule> <IfModule mime_module> TypesConfig /usr/local/etc/httpd/mime.types AddType application/x-compress .Z AddType application/x-gzip .gz .tgz </IfModule> <IfModule proxy_html_module> Include /usr/local/etc/httpd/extra/proxy-html.conf </IfModule> <IfModule ssl_module> SSLRandomSeed startup builtin SSLRandomSeed connect builtin </IfModule> WSGIScriptAlias / /Users/r/Projects/project_temp/project_temp/wsgi.py WSGIPythonHome /Library/Frameworks/Python.framework/Versions/3.8 <VirtualHost localhost:80> LogLevel warn ErrorLog /Users/r/Projects/project_temp/log/error.log CustomLog /Users/r/Projects/project_temp/log/access.log combined <Directory /Users/r/Projects/project_temp/project_temp> <Files wsgi.py> Require all granted </Files> </Directory> </VirtualHost> ```
2020/06/21
[ "https://Stackoverflow.com/questions/62497777", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7060063/" ]
`&str` is an immutable slice, it somewhat similar to [`std::string_view`](https://en.cppreference.com/w/cpp/string/basic_string_view), so you cannot modify it. Instead, you may use iterator and collect a new [`String`](https://doc.rust-lang.org/std/string/struct.String.html): ```rust let removed: String = foo .chars() .take(start) .chain(foo.chars().skip(stop)) .collect(); ``` the other way would be an in-place `String` modifying: ```rust let mut foo: String = "hello".to_string(); // ... foo.replace_range((start..stop), ""); ``` Keep in mind, however, that the last example semantically different, because it operates on byte indicies, rather than char ones. Therefore it may panic at wrong usage (e.g. when `start` offset lay at the middle of multi-byte char).
Kitsu's solution w/o lambda ``` fn remove(start: usize, stop: usize, s: &str) -> String { let mut rslt = "".to_string(); for (i, c) in s.chars().enumerate() { if start > i || stop < i + 1 { rslt.push(c); } } rslt } ``` …as fast as `replace_range` but can handle unicode character [Playground](https://play.rust-lang.org/?version=stable&mode=release&edition=2021&gist=bf4b8b0f1d9ad886ac0702238177b11d)
9,511,825
I have a pythonscript run.py that I currently run in the command line. However, I want a start.py script either in python (preferably) or .bat, php, or some other means that allows me to make it such that once run.py finishes running, the start.py script will reexecute the run.py script indefinitely, but ONLY after the run.py finishes executing and exits. Sample Steps: - Start.py is run that starts Run.py - Run.py prints "hello" for 3 times after 5 seconds and exits normally or abnormally - Start.py knows Run.py finished/closed and reexecutes run.py How do I accomplish this?
2012/03/01
[ "https://Stackoverflow.com/questions/9511825", "https://Stackoverflow.com", "https://Stackoverflow.com/users/971888/" ]
Your problem is that you're using -INFINITY and +INFINITY as win/loss scores. You should have scores for win/loss that are higher/lower than any other positional evaluation score, but not equal to your infinity values. This will guarantee that a move will be chosen even in positions that are hopelessly lost.
It's been a long time since i implemented minimax so I might be wrong, but it seems to me that your code, if you encounter a winning or losing move, does not update the best variable (this happens in the (board.checkEnd()) statement at the top of your method). Also, if you want your algorithm to try to win with as much as possible, or lose with as little as possible if it can't win, I suggest you update your eval function. In a win situation, it should return a large value (larger that any non-win situation), the more you win with the laregr the value. In a lose situation, it should return a large negative value (less than in any non-lose situation), the more you lose by the less the value. It seems to me (without trying it out) that if you update your eval function that way and skip the check if (board.checkEnd()) altogether, your algorithm should work fine (unless there's other problems with it). Good luck!
9,511,825
I have a pythonscript run.py that I currently run in the command line. However, I want a start.py script either in python (preferably) or .bat, php, or some other means that allows me to make it such that once run.py finishes running, the start.py script will reexecute the run.py script indefinitely, but ONLY after the run.py finishes executing and exits. Sample Steps: - Start.py is run that starts Run.py - Run.py prints "hello" for 3 times after 5 seconds and exits normally or abnormally - Start.py knows Run.py finished/closed and reexecutes run.py How do I accomplish this?
2012/03/01
[ "https://Stackoverflow.com/questions/9511825", "https://Stackoverflow.com", "https://Stackoverflow.com/users/971888/" ]
It's been a long time since i implemented minimax so I might be wrong, but it seems to me that your code, if you encounter a winning or losing move, does not update the best variable (this happens in the (board.checkEnd()) statement at the top of your method). Also, if you want your algorithm to try to win with as much as possible, or lose with as little as possible if it can't win, I suggest you update your eval function. In a win situation, it should return a large value (larger that any non-win situation), the more you win with the laregr the value. In a lose situation, it should return a large negative value (less than in any non-lose situation), the more you lose by the less the value. It seems to me (without trying it out) that if you update your eval function that way and skip the check if (board.checkEnd()) altogether, your algorithm should work fine (unless there's other problems with it). Good luck!
If you can detect that a position is truly won or lost, then that implies you are solving the endgame. In this case, your evaluation function should be returning the final score of the game (e.g. 64 for a total victory, 31 for a narrow loss), since this can be calculated accurately, unlike the estimates that you will evaluate in the midgame.
9,511,825
I have a pythonscript run.py that I currently run in the command line. However, I want a start.py script either in python (preferably) or .bat, php, or some other means that allows me to make it such that once run.py finishes running, the start.py script will reexecute the run.py script indefinitely, but ONLY after the run.py finishes executing and exits. Sample Steps: - Start.py is run that starts Run.py - Run.py prints "hello" for 3 times after 5 seconds and exits normally or abnormally - Start.py knows Run.py finished/closed and reexecutes run.py How do I accomplish this?
2012/03/01
[ "https://Stackoverflow.com/questions/9511825", "https://Stackoverflow.com", "https://Stackoverflow.com/users/971888/" ]
Your problem is that you're using -INFINITY and +INFINITY as win/loss scores. You should have scores for win/loss that are higher/lower than any other positional evaluation score, but not equal to your infinity values. This will guarantee that a move will be chosen even in positions that are hopelessly lost.
If you can detect that a position is truly won or lost, then that implies you are solving the endgame. In this case, your evaluation function should be returning the final score of the game (e.g. 64 for a total victory, 31 for a narrow loss), since this can be calculated accurately, unlike the estimates that you will evaluate in the midgame.
6,539,267
I started coding an RPG engine in python and I want it to be very scripted(buffs, events). I am experimenting with events and hooking. I would appreciate if you could tell me some matured opensource projects(so i can inspect the code) to learn from. Not necessarily python, but it would be ideal. Thanks in advance.
2011/06/30
[ "https://Stackoverflow.com/questions/6539267", "https://Stackoverflow.com", "https://Stackoverflow.com/users/492162/" ]
As Daenyth suggested, [pygame](http://pygame.org/) is a great place to start. There are plenty of projects linked to on their page. The other library that is quite lovely for this type of thing is [Panda3D.](http://www.panda3d.org/) Though I haven't yet used it, the library comes with samples, and it looks like there is a list of projects using it somewhere. Have fun.
You might have a look at `pygame`, it's pretty common for this sort of thing.
63,129,698
I'm using subprocess to spawn a `conda create` command and capture the resulting `stdout` for later use. I also immediately print the `stdout` to the console so the user can still see the progress of the subprocess: ``` p = subprocess.Popen('conda create -n env1 python', stdout=subprocess.PIPE, stderr=subprocess.STDOUT) for line in iter(p.stdout.readline, b''): sys.stdout.write(line.decode(sys.stdout.encoding)) ``` This works fine until half way through the execution when the `conda create` requires user input: it prompts `Proceed (n/y)?` and waits for the user to input an option. However, the code above doesn't print the prompt and instead just waits for input "on a blank screen". Once an input is received the prompt is printed *afterwards* and then execution continues as expected. I assume this is because the input somehow blocks the prompt being written to `stdout` and so the `readline` doesn't receive new data until after the input block has been lifted. Is there a way I can ensure the input prompt is printed before the subprocess waits for user input? Note I'm running on Windows.
2020/07/28
[ "https://Stackoverflow.com/questions/63129698", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1963945/" ]
Although I'm sure pexpect would have worked in this case, I decided it would be overkill. Instead I used MisterMiyagi's insight and replaced `readline` with `read`. The final code is as so: ``` p = subprocess.Popen('conda create -n env1 python', stdout=subprocess.PIPE, stderr=subprocess.STDOUT) while p.poll() is None: sys.stdout.write(p.stdout.read(1).decode(sys.stdout.encoding)) sys.stdout.flush() ``` Note the `read(1)` as just using `read()` would block the while loop until an EOF is found. Given no EOF is found before the input prompt, nothing will be printed at all! In addition, `flush` is called which ensures the text written to `sys.stdout` is actually visible on screen.
For this use case I recommend using [pexpect](https://pypi.org/project/pexpect/). *stdin != stdout* Example use case where it conditionally sends to *stdin* on prompts on *stdout* ``` def expectgit(alog): TMPLOG = "/tmp/pexpect.log" cmd = f''' ssh -T git@github.com ;\ echo "alldone" ; ''' with open(TMPLOG, "w") as log: ch = pexpect.spawn(f"/bin/bash -c \"{cmd}\"", encoding='utf-8', logfile=log) while True: i = ch.expect(["successfully authenticated", "Are you sure you want to continue connecting"]) if i == 0: alog.info("Git all good") break elif i == 1: alog.info("Fingerprint verification") ch.send("yes\r") ch.expect("alldone") i = ch.expect([pexpect.EOF], timeout=5) ch.close() alog.info("expect done - EOF") with open(TMPLOG) as log: for l in log.readlines(): alog.debug(l.strip()) ```
49,830,562
Let the two lists be ``` x = [0,1,2,2,5,2,1,0,1,2] y = [0,1,3,2,1,4,1,3,1,2] ``` How to find the similar elements in these two lists in python and print them. What I am doing- ``` for i, j in x, y: if x[i] == y[j]: print(x[i], y[j]) ``` I want to find elements like x[0], y[0] and x[1], y[1] etc. This does not work, I am new to python. I want to find the exact index at which the elements are common. I want to find the index 0, 1, 3, 6, 8, 9; because the elements at these indices are equal
2018/04/14
[ "https://Stackoverflow.com/questions/49830562", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9645192/" ]
Two problems: First, you should initiate `smallest` with the last element if you want to search from the end of array: ``` int result = findMinAux(arr,arr.length-1,arr[arr.length - 1]); ``` Secondly, you should reassign `smallest`: ``` if(startIndex>=0) { smallest = findMinAux(arr,startIndex,smallest); } ```
See this code. In every iteration, elements are compared with current element and index in increased on the basis of comparison. This is tail recursive as well. So it can be used in large arrays as well. ``` public class Q1 { public static void main(String[] args) { int[] testArr = {12, 32, 45, 435, -1, 345, 0, 564, -10, 234, 25}; System.out.println(); System.out.println(find(testArr, 0, testArr.length - 1, testArr[0])); } public static int find(int[] arr, int currPos, int lastPos, int elem) { if (currPos == lastPos) { return elem; } else { if (elem < arr[currPos]) { return find(arr, currPos + 1, lastPos, elem); } else { return find(arr, currPos + 1, lastPos, arr[currPos]); } } } } ```
49,830,562
Let the two lists be ``` x = [0,1,2,2,5,2,1,0,1,2] y = [0,1,3,2,1,4,1,3,1,2] ``` How to find the similar elements in these two lists in python and print them. What I am doing- ``` for i, j in x, y: if x[i] == y[j]: print(x[i], y[j]) ``` I want to find elements like x[0], y[0] and x[1], y[1] etc. This does not work, I am new to python. I want to find the exact index at which the elements are common. I want to find the index 0, 1, 3, 6, 8, 9; because the elements at these indices are equal
2018/04/14
[ "https://Stackoverflow.com/questions/49830562", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9645192/" ]
Two problems: First, you should initiate `smallest` with the last element if you want to search from the end of array: ``` int result = findMinAux(arr,arr.length-1,arr[arr.length - 1]); ``` Secondly, you should reassign `smallest`: ``` if(startIndex>=0) { smallest = findMinAux(arr,startIndex,smallest); } ```
Actually, this implementation works fine ``` public static int findMinAux(int[] arr, int startIndex, int smallest) { if(startIndex < 0) return smallest; if(arr[startIndex] < smallest){ smallest = arr[startIndex]; } return findMinAux(arr, startIndex - 1, smallest); } ``` And also you has a typo in calling this funtion, the last parameter must be an value from array, in your case the last value, not the last index. ``` int result = findMinAux(arr,arr.length-1, arr.length - 1); ``` change to ``` int result = findMinAux(arr,arr.length-2, arr[arr.length - 1]); ```
49,830,562
Let the two lists be ``` x = [0,1,2,2,5,2,1,0,1,2] y = [0,1,3,2,1,4,1,3,1,2] ``` How to find the similar elements in these two lists in python and print them. What I am doing- ``` for i, j in x, y: if x[i] == y[j]: print(x[i], y[j]) ``` I want to find elements like x[0], y[0] and x[1], y[1] etc. This does not work, I am new to python. I want to find the exact index at which the elements are common. I want to find the index 0, 1, 3, 6, 8, 9; because the elements at these indices are equal
2018/04/14
[ "https://Stackoverflow.com/questions/49830562", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9645192/" ]
Two problems: First, you should initiate `smallest` with the last element if you want to search from the end of array: ``` int result = findMinAux(arr,arr.length-1,arr[arr.length - 1]); ``` Secondly, you should reassign `smallest`: ``` if(startIndex>=0) { smallest = findMinAux(arr,startIndex,smallest); } ```
This approach works with a single method and an overloaded version so you don't have to pass the initial values ``` public static int findMin(int[] arr) { int index = 0; int min = Integer.MAX_VALUE; min = Math.min(arr[index], min); return findMin(arr,index+1,min); } private static int findMin(int[] arr, int index, int min) { if(index < arr.length) { min = Math.min(arr[index], min); return findMin(arr,index+1,min); } System.out.println(min); return min; } ``` The second method is private so from outside the class, only the first/default method can be called.
49,830,562
Let the two lists be ``` x = [0,1,2,2,5,2,1,0,1,2] y = [0,1,3,2,1,4,1,3,1,2] ``` How to find the similar elements in these two lists in python and print them. What I am doing- ``` for i, j in x, y: if x[i] == y[j]: print(x[i], y[j]) ``` I want to find elements like x[0], y[0] and x[1], y[1] etc. This does not work, I am new to python. I want to find the exact index at which the elements are common. I want to find the index 0, 1, 3, 6, 8, 9; because the elements at these indices are equal
2018/04/14
[ "https://Stackoverflow.com/questions/49830562", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9645192/" ]
Two problems: First, you should initiate `smallest` with the last element if you want to search from the end of array: ``` int result = findMinAux(arr,arr.length-1,arr[arr.length - 1]); ``` Secondly, you should reassign `smallest`: ``` if(startIndex>=0) { smallest = findMinAux(arr,startIndex,smallest); } ```
``` class Minimum { int minelem; int minindex; Minimum() { minelem = Integer.MAX_VALUE; minindex = -1; } } public class Q1 { public static void main(String[] args) { int[] testArr = {12,32,45,435,-1,345,0,564,-10,234,25}; findMin(testArr); } public static int findMin(int[] arr) { Minimum m = new Minimum(); m = findMinAux(arr,arr.length-1,m); System.out.println(m.minindex); return m.minindex; } public static Minimum findMinAux(int[] arr, int lastindex, Minimum m) { if(lastindex < 0) { return m; } if(m.minelem > arr[lastindex]) { m.minelem = arr[lastindex]; m.minindex = lastindex; } return findMinAux(arr,lastindex - 1, m); } } ``` I have used another class here for simplification. Please check if this solved your problem meanwhile I am explaining why and how it is working.
49,830,562
Let the two lists be ``` x = [0,1,2,2,5,2,1,0,1,2] y = [0,1,3,2,1,4,1,3,1,2] ``` How to find the similar elements in these two lists in python and print them. What I am doing- ``` for i, j in x, y: if x[i] == y[j]: print(x[i], y[j]) ``` I want to find elements like x[0], y[0] and x[1], y[1] etc. This does not work, I am new to python. I want to find the exact index at which the elements are common. I want to find the index 0, 1, 3, 6, 8, 9; because the elements at these indices are equal
2018/04/14
[ "https://Stackoverflow.com/questions/49830562", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9645192/" ]
Actually, this implementation works fine ``` public static int findMinAux(int[] arr, int startIndex, int smallest) { if(startIndex < 0) return smallest; if(arr[startIndex] < smallest){ smallest = arr[startIndex]; } return findMinAux(arr, startIndex - 1, smallest); } ``` And also you has a typo in calling this funtion, the last parameter must be an value from array, in your case the last value, not the last index. ``` int result = findMinAux(arr,arr.length-1, arr.length - 1); ``` change to ``` int result = findMinAux(arr,arr.length-2, arr[arr.length - 1]); ```
See this code. In every iteration, elements are compared with current element and index in increased on the basis of comparison. This is tail recursive as well. So it can be used in large arrays as well. ``` public class Q1 { public static void main(String[] args) { int[] testArr = {12, 32, 45, 435, -1, 345, 0, 564, -10, 234, 25}; System.out.println(); System.out.println(find(testArr, 0, testArr.length - 1, testArr[0])); } public static int find(int[] arr, int currPos, int lastPos, int elem) { if (currPos == lastPos) { return elem; } else { if (elem < arr[currPos]) { return find(arr, currPos + 1, lastPos, elem); } else { return find(arr, currPos + 1, lastPos, arr[currPos]); } } } } ```
49,830,562
Let the two lists be ``` x = [0,1,2,2,5,2,1,0,1,2] y = [0,1,3,2,1,4,1,3,1,2] ``` How to find the similar elements in these two lists in python and print them. What I am doing- ``` for i, j in x, y: if x[i] == y[j]: print(x[i], y[j]) ``` I want to find elements like x[0], y[0] and x[1], y[1] etc. This does not work, I am new to python. I want to find the exact index at which the elements are common. I want to find the index 0, 1, 3, 6, 8, 9; because the elements at these indices are equal
2018/04/14
[ "https://Stackoverflow.com/questions/49830562", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9645192/" ]
This approach works with a single method and an overloaded version so you don't have to pass the initial values ``` public static int findMin(int[] arr) { int index = 0; int min = Integer.MAX_VALUE; min = Math.min(arr[index], min); return findMin(arr,index+1,min); } private static int findMin(int[] arr, int index, int min) { if(index < arr.length) { min = Math.min(arr[index], min); return findMin(arr,index+1,min); } System.out.println(min); return min; } ``` The second method is private so from outside the class, only the first/default method can be called.
See this code. In every iteration, elements are compared with current element and index in increased on the basis of comparison. This is tail recursive as well. So it can be used in large arrays as well. ``` public class Q1 { public static void main(String[] args) { int[] testArr = {12, 32, 45, 435, -1, 345, 0, 564, -10, 234, 25}; System.out.println(); System.out.println(find(testArr, 0, testArr.length - 1, testArr[0])); } public static int find(int[] arr, int currPos, int lastPos, int elem) { if (currPos == lastPos) { return elem; } else { if (elem < arr[currPos]) { return find(arr, currPos + 1, lastPos, elem); } else { return find(arr, currPos + 1, lastPos, arr[currPos]); } } } } ```
49,830,562
Let the two lists be ``` x = [0,1,2,2,5,2,1,0,1,2] y = [0,1,3,2,1,4,1,3,1,2] ``` How to find the similar elements in these two lists in python and print them. What I am doing- ``` for i, j in x, y: if x[i] == y[j]: print(x[i], y[j]) ``` I want to find elements like x[0], y[0] and x[1], y[1] etc. This does not work, I am new to python. I want to find the exact index at which the elements are common. I want to find the index 0, 1, 3, 6, 8, 9; because the elements at these indices are equal
2018/04/14
[ "https://Stackoverflow.com/questions/49830562", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9645192/" ]
``` class Minimum { int minelem; int minindex; Minimum() { minelem = Integer.MAX_VALUE; minindex = -1; } } public class Q1 { public static void main(String[] args) { int[] testArr = {12,32,45,435,-1,345,0,564,-10,234,25}; findMin(testArr); } public static int findMin(int[] arr) { Minimum m = new Minimum(); m = findMinAux(arr,arr.length-1,m); System.out.println(m.minindex); return m.minindex; } public static Minimum findMinAux(int[] arr, int lastindex, Minimum m) { if(lastindex < 0) { return m; } if(m.minelem > arr[lastindex]) { m.minelem = arr[lastindex]; m.minindex = lastindex; } return findMinAux(arr,lastindex - 1, m); } } ``` I have used another class here for simplification. Please check if this solved your problem meanwhile I am explaining why and how it is working.
See this code. In every iteration, elements are compared with current element and index in increased on the basis of comparison. This is tail recursive as well. So it can be used in large arrays as well. ``` public class Q1 { public static void main(String[] args) { int[] testArr = {12, 32, 45, 435, -1, 345, 0, 564, -10, 234, 25}; System.out.println(); System.out.println(find(testArr, 0, testArr.length - 1, testArr[0])); } public static int find(int[] arr, int currPos, int lastPos, int elem) { if (currPos == lastPos) { return elem; } else { if (elem < arr[currPos]) { return find(arr, currPos + 1, lastPos, elem); } else { return find(arr, currPos + 1, lastPos, arr[currPos]); } } } } ```
49,830,562
Let the two lists be ``` x = [0,1,2,2,5,2,1,0,1,2] y = [0,1,3,2,1,4,1,3,1,2] ``` How to find the similar elements in these two lists in python and print them. What I am doing- ``` for i, j in x, y: if x[i] == y[j]: print(x[i], y[j]) ``` I want to find elements like x[0], y[0] and x[1], y[1] etc. This does not work, I am new to python. I want to find the exact index at which the elements are common. I want to find the index 0, 1, 3, 6, 8, 9; because the elements at these indices are equal
2018/04/14
[ "https://Stackoverflow.com/questions/49830562", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9645192/" ]
``` class Minimum { int minelem; int minindex; Minimum() { minelem = Integer.MAX_VALUE; minindex = -1; } } public class Q1 { public static void main(String[] args) { int[] testArr = {12,32,45,435,-1,345,0,564,-10,234,25}; findMin(testArr); } public static int findMin(int[] arr) { Minimum m = new Minimum(); m = findMinAux(arr,arr.length-1,m); System.out.println(m.minindex); return m.minindex; } public static Minimum findMinAux(int[] arr, int lastindex, Minimum m) { if(lastindex < 0) { return m; } if(m.minelem > arr[lastindex]) { m.minelem = arr[lastindex]; m.minindex = lastindex; } return findMinAux(arr,lastindex - 1, m); } } ``` I have used another class here for simplification. Please check if this solved your problem meanwhile I am explaining why and how it is working.
Actually, this implementation works fine ``` public static int findMinAux(int[] arr, int startIndex, int smallest) { if(startIndex < 0) return smallest; if(arr[startIndex] < smallest){ smallest = arr[startIndex]; } return findMinAux(arr, startIndex - 1, smallest); } ``` And also you has a typo in calling this funtion, the last parameter must be an value from array, in your case the last value, not the last index. ``` int result = findMinAux(arr,arr.length-1, arr.length - 1); ``` change to ``` int result = findMinAux(arr,arr.length-2, arr[arr.length - 1]); ```
49,830,562
Let the two lists be ``` x = [0,1,2,2,5,2,1,0,1,2] y = [0,1,3,2,1,4,1,3,1,2] ``` How to find the similar elements in these two lists in python and print them. What I am doing- ``` for i, j in x, y: if x[i] == y[j]: print(x[i], y[j]) ``` I want to find elements like x[0], y[0] and x[1], y[1] etc. This does not work, I am new to python. I want to find the exact index at which the elements are common. I want to find the index 0, 1, 3, 6, 8, 9; because the elements at these indices are equal
2018/04/14
[ "https://Stackoverflow.com/questions/49830562", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9645192/" ]
``` class Minimum { int minelem; int minindex; Minimum() { minelem = Integer.MAX_VALUE; minindex = -1; } } public class Q1 { public static void main(String[] args) { int[] testArr = {12,32,45,435,-1,345,0,564,-10,234,25}; findMin(testArr); } public static int findMin(int[] arr) { Minimum m = new Minimum(); m = findMinAux(arr,arr.length-1,m); System.out.println(m.minindex); return m.minindex; } public static Minimum findMinAux(int[] arr, int lastindex, Minimum m) { if(lastindex < 0) { return m; } if(m.minelem > arr[lastindex]) { m.minelem = arr[lastindex]; m.minindex = lastindex; } return findMinAux(arr,lastindex - 1, m); } } ``` I have used another class here for simplification. Please check if this solved your problem meanwhile I am explaining why and how it is working.
This approach works with a single method and an overloaded version so you don't have to pass the initial values ``` public static int findMin(int[] arr) { int index = 0; int min = Integer.MAX_VALUE; min = Math.min(arr[index], min); return findMin(arr,index+1,min); } private static int findMin(int[] arr, int index, int min) { if(index < arr.length) { min = Math.min(arr[index], min); return findMin(arr,index+1,min); } System.out.println(min); return min; } ``` The second method is private so from outside the class, only the first/default method can be called.
73,818,926
I am trying to send 2 params to the backend through a get request that returns some query based on the params I send to the backend. I am using React.js front end and flask python backend. My get request looks like this: ``` async function getStatsData() { const req = axios.get('http://127.0.0.1:5000/stat/', { params: { user: 0, flashcard_id: 1 }, headers: {'Access-Control-Allow-Origin': '*', 'X-Requested-With': 'XMLHttpRequest'}, }) const res = await req; return res.data.results.map((statsItem, index) => { return { stat1: statsItem.stat1, stat2: statsItem.stat2, stat3: statsItem.stat3, stat4: statsItem.user, key: statsItem.key } }) } ``` and then my route in the backend is this: ``` @app.route('/stat/<user>/<flashcard_id>', methods=['GET', 'POST', 'OPTIONS']) def stats(user, flashcard_id): def get_total_percent_correct(user): correct = d.db_query('SELECT COUNT(*) FROM cards.responses WHERE guess = answer AND user_id = %s' % user)[0][0] total = d.db_query('SELECT COUNT(*) FROM cards.responses WHERE user_id = %s' % user)[0][0] try: return round(float(correct)/float(total),3)*100 except: print('0') def get_percent_correct_for_flashcard(user,flashcard_id): total = d.db_query('SELECT COUNT(*) FROM cards.responses WHERE user_id = %s AND flashcard_id = %s' % (user, flashcard_id))[0][0] correct = d.db_query('SELECT COUNT(*) FROM cards.responses WHERE flashcard_id = %s AND guess = answer AND user_id = %s' % (flashcard_id, user))[0][0] try: return round(float(correct)/float(total),3)*100 except: print('0') def get_stats_for_flashcard(user_id, flashcard_id): attempts = d.db_query('SELECT COUNT(*) FROM cards.responses WHERE user_id = %s AND flashcard_id = %s' % (user_id, flashcard_id))[0][0] correct = d.db_query('SELECT COUNT(*) FROM cards.responses WHERE flashcard_id = %s AND guess = answer AND user_id = %s' % (flashcard_id, user_id))[0][0] missed = attempts - correct return attempts, correct, missed data = [{ "stat1": get_total_percent_correct(user), "stat2": get_percent_correct_for_flashcard(user, flashcard_id), 'stat3': get_stats_for_flashcard(user, flashcard_id), 'user': user, 'key':999 }] return {"response_code" : 200, "results" : data} ``` When I go to <http://127.0.0.1:5000/stat/0/1> in my browser, the stats are shown correctly but the get request is not working because it says xhr.js:210 GET <http://127.0.0.1:5000/stat/?user=0&flashcard_id=1> 404 (NOT FOUND) . So clearly I'm not sending or receiving the params correctly. Does anyone know how to solve this? Thank you for your time
2022/09/22
[ "https://Stackoverflow.com/questions/73818926", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19603491/" ]
In your backend route you are expecting the values in url as dynamic segment, but from axios you are sending it as [query sring](https://en.wikipedia.org/wiki/Query_string). **Solution:** You can modify the axios request like this to send the values as dynamic segment: ``` const user = 0; const flashcard_id = 1; const req = axios.get(`http://127.0.0.1:5000/stat/${user}/${flashcard_id}`,{ headers: {'Access-Control-Allow-Origin': '*', 'X-Requested-With': 'XMLHttpRequest'}, }) ``` **or** you can modify flask route like this if you need to recieve values from query params: ``` from flask import request @app.route('/stat/', methods=['GET', 'POST', 'OPTIONS']) def stats(): user = request.args.get('user') flashcard_id = request.args.get('flashcard_id') ```
Send the parameters like this: ``` const req = axios.get(`http://127.0.0.1:5000/stat/${user}/${flashcard_id}`) ``` and in Flask you receive the parameters like this: ``` @app.route('/stat/<user>/<flashcard_id>', methods=['GET', 'POST', 'OPTIONS']) def stats(user, flashcard_id): ```
52,154,682
After installing python 3.7 from python.org, running the Install Certificate.command resulted in the below error. Please, can you provide some guidance? Why does Install Certificate.command result in error? [Some background] Tried to install python via anaconda, brew and python.org, even installing version 3.6.6, hoping I could get one of them to work. Each installation resulted in ssl certification errors when I tried to install a package. See further below for example error from current python 3.7 installation. I read every page with any reference to openssl errors and followed every instruction. That last one probably has done more damage to my machine tbh. I installed, uninstalled and reinstalled from each of anaconda, brew and python.org, deleting and cleaning a bunch of folders along the way, trying to make a clean installation. Along the way, I even managed to delete pip, wheel and setuptools from site-directories folder of the apple preinstalled python version. So all in all, after a week of python installation hell, I am totally stuck. ``` Collecting certifi Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate in certificate chain (_ssl.c:1045)'))': /simple/certifi/ Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate in certificate chain (_ssl.c:1045)'))': /simple/certifi/ Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate in certificate chain (_ssl.c:1045)'))': /simple/certifi/ Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate in certificate chain (_ssl.c:1045)'))': /simple/certifi/ Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate in certificate chain (_ssl.c:1045)'))': /simple/certifi/ Could not fetch URL https://pypi.org/simple/certifi/: There was a problem confirming the ssl certificate: HTTPSConnectionPool(host='pypi.org', port=443): Max retries exceeded with url: /simple/certifi/ (Caused by SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate in certificate chain (_ssl.c:1045)'))) - skipping Could not find a version that satisfies the requirement certifi (from versions: ) No matching distribution found for certifi Traceback (most recent call last): File "<stdin>", line 44, in <module> File "<stdin>", line 25, in main File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/subprocess.py", line 328, in check_call raise CalledProcessError(retcode, cmd) subprocess.CalledProcessError: Command '['/Library/Frameworks/Python.framework/Versions/3.7/bin/python3.7', '-E', '-s', '-m', 'pip', 'install', '--upgrade', 'certifi']' returned non-zero exit status 1. logout Saving session... ...copying shared history... ...saving history...truncating history files... ...completed. [Process completed] ``` `pip3 install numpy` results in the below error ``` Collecting numpy Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate in certificate chain (_ssl.c:1045)'))': /simple/numpy/ Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate in certificate chain (_ssl.c:1045)'))': /simple/numpy/ Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate in certificate chain (_ssl.c:1045)'))': /simple/numpy/ Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate in certificate chain (_ssl.c:1045)'))': /simple/numpy/ Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate in certificate chain (_ssl.c:1045)'))': /simple/numpy/ Could not fetch URL https://pypi.org/simple/numpy/: There was a problem confirming the ssl certificate: HTTPSConnectionPool(host='pypi.org', port=443): Max retries exceeded with url: /simple/numpy/ (Caused by SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate in certificate chain (_ssl.c:1045)'))) - skipping Could not find a version that satisfies the requirement numpy (from versions: ) No matching distribution found for numpy ``` --- EDIT post @newbie comment Based on the most upvoted answer in that post, I tried the following: ``` $ curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py % Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed 100 1604k 100 1604k 0 0 188k 0 0:00:08 0:00:08 --:--:-- 148k $ python3 get-pip.py Collecting pip Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate in certificate chain (_ssl.c:1045)'))': /simple/pip/ Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate in certificate chain (_ssl.c:1045)'))': /simple/pip/ Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate in certificate chain (_ssl.c:1045)'))': /simple/pip/ Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate in certificate chain (_ssl.c:1045)'))': /simple/pip/ Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate in certificate chain (_ssl.c:1045)'))': /simple/pip/ Could not fetch URL https://pypi.org/simple/pip/: There was a problem confirming the ssl certificate: HTTPSConnectionPool(host='pypi.org', port=443): Max retries exceeded with url: /simple/pip/ (Caused by SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate in certificate chain (_ssl.c:1045)'))) - skipping Could not find a version that satisfies the requirement pip (from versions: ) No matching distribution found for pip $ pip3 search numpy Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate in certificate chain (_ssl.c:1045)'))': /pypi Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate in certificate chain (_ssl.c:1045)'))': /pypi Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate in certificate chain (_ssl.c:1045)'))': /pypi Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate in certificate chain (_ssl.c:1045)'))': /pypi Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate in certificate chain (_ssl.c:1045)'))': /pypi Exception: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/urllib3/connectionpool.py", line 600, in urlopen chunked=chunked) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/urllib3/connectionpool.py", line 343, in _make_request self._validate_conn(conn) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/urllib3/connectionpool.py", line 849, in _validate_conn conn.connect() File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/urllib3/connection.py", line 356, in connect ssl_context=context) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/urllib3/util/ssl_.py", line 359, in ssl_wrap_socket return context.wrap_socket(sock, server_hostname=server_hostname) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/ssl.py", line 412, in wrap_socket session=session File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/ssl.py", line 850, in _create self.do_handshake() File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/ssl.py", line 1108, in do_handshake self._sslobj.do_handshake() ssl.SSLCertVerificationError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate in certificate chain (_ssl.c:1045) During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/requests/adapters.py", line 445, in send timeout=timeout File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/urllib3/connectionpool.py", line 667, in urlopen **response_kw) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/urllib3/connectionpool.py", line 667, in urlopen **response_kw) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/urllib3/connectionpool.py", line 667, in urlopen **response_kw) [Previous line repeated 1 more times] File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/urllib3/connectionpool.py", line 638, in urlopen _stacktrace=sys.exc_info()[2]) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/urllib3/util/retry.py", line 398, in increment raise MaxRetryError(_pool, url, error or ResponseError(cause)) pip._vendor.urllib3.exceptions.MaxRetryError: HTTPSConnectionPool(host='pypi.org', port=443): Max retries exceeded with url: /pypi (Caused by SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate in certificate chain (_ssl.c:1045)'))) During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_internal/basecommand.py", line 141, in main status = self.run(options, args) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_internal/commands/search.py", line 48, in run pypi_hits = self.search(query, options) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_internal/commands/search.py", line 65, in search hits = pypi.search({'name': query, 'summary': query}, 'or') File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/xmlrpc/client.py", line 1112, in __call__ return self.__send(self.__name, args) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/xmlrpc/client.py", line 1452, in __request verbose=self.__verbose File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_internal/download.py", line 788, in request headers=headers, stream=True) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/requests/sessions.py", line 559, in post return self.request('POST', url, data=data, json=json, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_internal/download.py", line 396, in request return super(PipSession, self).request(method, url, *args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/requests/sessions.py", line 512, in request resp = self.send(prep, **send_kwargs) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/requests/sessions.py", line 622, in send r = adapter.send(request, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/cachecontrol/adapter.py", line 53, in send resp = super(CacheControlAdapter, self).send(request, **kw) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/pip/_vendor/requests/adapters.py", line 511, in send raise SSLError(e, request=request) pip._vendor.requests.exceptions.SSLError: HTTPSConnectionPool(host='pypi.org', port=443): Max retries exceeded with url: /pypi (Caused by SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate in certificate chain (_ssl.c:1045)'))) ``` =========== EDIT2 : searched for all locations where copies of openssl.cnf file exists. Does this seem right? ``` $ mdfind openssl.cnf /usr/local/etc/openssl/openssl.cnf /opt/vagrant/embedded/ssl/openssl.cnf /opt/vagrant/embedded/ssl/openssl.cnf.dist /private/etc/ssl/openssl.cnf /System/Library/OpenSSL/openssl.cnf /opt/vagrant/embedded/ssl/misc/CA.pl ```
2018/09/03
[ "https://Stackoverflow.com/questions/52154682", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10297557/" ]
wanted to answer my own question as I seem to have fixed most of the issues. The solution: 1. Created a pip directory and then a pip.conf file in $HOME/Library/Application Support 2. To the pip.conf added code [global] trusted-host = pypi.python.org pypi.org files.pythonhosted.org 3. Started installing using $ pip install --trusted-host pypi.org --trusted-host files.pythonhosted.org pip 4. Then tried pip install which worked, so used that to install numpy, pandas, geopy etc. 5. Successfully ran the Install CertificateCommand file in Applications/Python 3.7 Results: 1. Installation via pip is working. 2. Spyder3 is working 3. Python 3.7 is working 4. numpy, pandas, matplotlib, geopy are working 5. Jupyter notebook is working Outstanding: Still getting GeocoderServiceError and Brew doctor says vim missing python. Will raise separate questions for these.
You don't need to run Install Certificate.command. You should reinstall Xcode command line tools that contains Python. ```sh pip3 uninstall -y -r <(pip requests certifi) brew uninstall --ignore-dependencies python3 sudo rm -rf /Library/Developer/CommandLineTools xcode-select --install sudo xcode-select -r python3 -m pip install --user certifi python3 -m pip install --user requests ```
39,739,195
I have a JSON object that I'd like to transform using jq from one form to another (of course, I could use javascript or python and iterate, but jq would be preferable). The issue is that the input contains long arrays that needs to be broken into multiple smaller arrays whenever data stops repeating within the first array. I'm not really sure how to describe this problem so I'll just put an example out here which is hopefully more explanatory. The one safe assumption-- if it is of any help-- is that the input data is always pre-sorted on the first two elements (e.g. "row\_x" and "col\_y"): input: ``` { "headers": [ "col1", "col2", "col3" ], "data": [ [ "row1","col1","b","src2" ], [ "row1","col1","b","src1" ], [ "row1","col1","b","src3" ], [ "row1","col2","d","src4" ], [ "row1","col2","e","src5" ], [ "row1","col2","f","src6" ], [ "row1","col3","j","src7" ], [ "row1","col3","g","src8" ], [ "row1","col3","h","src9" ], [ "row1","col3","i","src10" ], [ "row2","col1","l","src13" ], [ "row2","col1","j","src11" ], [ "row2","col1","k","src12" ], [ "row2","col3","o","src15" ] ] } ``` desired output: ``` { "headers": [ "col1", "col2", "col3" ], "values": [ [["b","b","b"],["d","e","f"],["g","h","i","j"]], [["j","k","l"],null,["o"]] ], "sources": [ [["src1","src2","src3"],["src4","src5","src6"],["src7","src8","src9","src10"]], [["src11","src12","src13"],null,["src15"]] ] } ``` Is this doable at all in jq? UPDATE: a variant of this is to retain the original data order, so the output is as follows: ``` { "headers": [ "col1", "col2", "col3" ], "values": [ [["b","b","b"],["d","e","f"],["j","g","h","i"]], [["l","j","k"],null,["o"]] ], "sources": [ [["src2","src1","src3"],["src4","src5","src6"],["src7","src8","src9","src10"]], [["src13","src11","src12"],null,["src15"]] ] } ```
2016/09/28
[ "https://Stackoverflow.com/questions/39739195", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3160967/" ]
Is it doable? Of course! First you'll want to group the data by rows then columns. Then with the groups, build your values/sources arrays. ``` .headers as $headers | .data # make the data easier to access | map({ row: .[0], col: .[1], val: .[2], src: .[3] }) # keep it sorted so they are in expected order in the end | sort_by([.row,.col,.src]) # group by rows | group_by(.row) # create a map to each of the cols for easier access | map(group_by(.col) | reduce .[] as $col ({}; .[$col[0].col] = [$col[] | {val,src}] ) ) # build the result | { headers: $headers, values: map([.[$headers[]] | [.[]?.val]]), sources: map([.[$headers[]] | [.[]?.src]]) } ``` This will produce the following result: ``` { "headers": [ "col1", "col2", "col3" ], "values": [ [ [ "b", "b", "b" ], [ "d", "e", "f" ], [ "i", "j", "g", "h" ] ], [ [ "j", "k", "l" ], [], [ "o" ] ] ], "sources": [ [ [ "src1", "src2", "src3" ], [ "src4", "src5", "src6" ], [ "src10", "src7", "src8", "src9" ] ], [ [ "src11", "src12", "src13" ], [], [ "src15" ] ] ] } ```
Since the primary data source here can be thought of as a two-dimensional matrix, it may be worth considering a matrix-oriented approach to the problem, especially if it is intended that empty rows in the input matrix are not simply omitted, or if the number of columns in the matrix is not initially known. To spice things up a little, let's choose to represent an m x n matrix, M, as a JSON array of the form [m, n, a] where a is an array of arrays, such that a[i][j] is the element of M in row i, column j. First, let's define some basic matrix-oriented operations: ``` def ij(i;j): .[2][i][j]; def set_ij(i;j;value): def max(a;b): if a < b then b else a end; .[0] as $m | .[1] as $n | [max(i+1;$m), max(j+1;$n), (.[2] | setpath([i,j];value)) ]; ``` The data source uses strings of the form "rowI" for row i and "colJ" for row j, so we define a matrix-update function accordingly: ``` def update_row_col( row; col; value): ((row|sub("^row";"")|tonumber) - 1) as $r | ((col|sub("^col";"")|tonumber) - 1) as $c | ij($r;$c) as $v | set_ij($r; $c; if $v == null then [value] else $v + [value] end) ; ``` Given an array of items of the form ["rowI","colJ", V, S], generate a matrix with the value {"source": S, "value": V} at row I and column J: ``` def generate: reduce .[] as $x ([0,0,null]; update_row_col( $x[0]; $x[1]; { "source": $x[3], "value": $x[2] }) ); ``` Now we turn to the desired output. The following filter will extract f from the input matrix, producing an array of arrays, replacing [] with null: ``` def extract(f): . as $m | (reduce range(0; $m[0]) as $i ([]; . + ( reduce range(0; $m[1]) as $j ([]; . + [ $m | ij($i;$j) // [] | map(f) ]) ) )) | map( if length == 0 then null else . end ); ``` Putting it all together (generating the headers dynamically is left as an exercise for the interested reader): ``` {headers} + (.data | generate | { "values": extract(.value), "sources": extract(.source) } ) ``` Output: `{ "headers": [ "col1", "col2", "col3" ], "values": [ [ "b", "b", "b" ], [ "d", "e", "f" ], [ "j", "g", "h", "i" ], [ "l", "j", "k" ], null, [ "o" ] ], "sources": [ [ "src2", "src1", "src3" ], [ "src4", "src5", "src6" ], [ "src7", "src8", "src9", "src10" ], [ "src13", "src11", "src12" ], null, [ "src15" ] ] }`
39,739,195
I have a JSON object that I'd like to transform using jq from one form to another (of course, I could use javascript or python and iterate, but jq would be preferable). The issue is that the input contains long arrays that needs to be broken into multiple smaller arrays whenever data stops repeating within the first array. I'm not really sure how to describe this problem so I'll just put an example out here which is hopefully more explanatory. The one safe assumption-- if it is of any help-- is that the input data is always pre-sorted on the first two elements (e.g. "row\_x" and "col\_y"): input: ``` { "headers": [ "col1", "col2", "col3" ], "data": [ [ "row1","col1","b","src2" ], [ "row1","col1","b","src1" ], [ "row1","col1","b","src3" ], [ "row1","col2","d","src4" ], [ "row1","col2","e","src5" ], [ "row1","col2","f","src6" ], [ "row1","col3","j","src7" ], [ "row1","col3","g","src8" ], [ "row1","col3","h","src9" ], [ "row1","col3","i","src10" ], [ "row2","col1","l","src13" ], [ "row2","col1","j","src11" ], [ "row2","col1","k","src12" ], [ "row2","col3","o","src15" ] ] } ``` desired output: ``` { "headers": [ "col1", "col2", "col3" ], "values": [ [["b","b","b"],["d","e","f"],["g","h","i","j"]], [["j","k","l"],null,["o"]] ], "sources": [ [["src1","src2","src3"],["src4","src5","src6"],["src7","src8","src9","src10"]], [["src11","src12","src13"],null,["src15"]] ] } ``` Is this doable at all in jq? UPDATE: a variant of this is to retain the original data order, so the output is as follows: ``` { "headers": [ "col1", "col2", "col3" ], "values": [ [["b","b","b"],["d","e","f"],["j","g","h","i"]], [["l","j","k"],null,["o"]] ], "sources": [ [["src2","src1","src3"],["src4","src5","src6"],["src7","src8","src9","src10"]], [["src13","src11","src12"],null,["src15"]] ] } ```
2016/09/28
[ "https://Stackoverflow.com/questions/39739195", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3160967/" ]
Is it doable? Of course! First you'll want to group the data by rows then columns. Then with the groups, build your values/sources arrays. ``` .headers as $headers | .data # make the data easier to access | map({ row: .[0], col: .[1], val: .[2], src: .[3] }) # keep it sorted so they are in expected order in the end | sort_by([.row,.col,.src]) # group by rows | group_by(.row) # create a map to each of the cols for easier access | map(group_by(.col) | reduce .[] as $col ({}; .[$col[0].col] = [$col[] | {val,src}] ) ) # build the result | { headers: $headers, values: map([.[$headers[]] | [.[]?.val]]), sources: map([.[$headers[]] | [.[]?.src]]) } ``` This will produce the following result: ``` { "headers": [ "col1", "col2", "col3" ], "values": [ [ [ "b", "b", "b" ], [ "d", "e", "f" ], [ "i", "j", "g", "h" ] ], [ [ "j", "k", "l" ], [], [ "o" ] ] ], "sources": [ [ [ "src1", "src2", "src3" ], [ "src4", "src5", "src6" ], [ "src10", "src7", "src8", "src9" ] ], [ [ "src11", "src12", "src13" ], [], [ "src15" ] ] ] } ```
Here is a solution that uses **reduce**, **getpath** and **setpath** ``` .headers as $headers | reduce .data[] as [$r,$c,$v,$s] ( {headers:$headers, values:{}, sources:{}} ; setpath(["values", $r, $c]; (getpath(["values", $r, $c]) // []) + [$v]) | setpath(["sources", $r, $c]; (getpath(["sources", $r, $c]) // []) + [$s]) ) | .values = [ .values[] | [ .[ $headers[] ] ] ] | .sources = [ .sources[] | [ .[ $headers[] ] ] ] ``` Sample output (manually reformatted for readability) ``` { "headers":["col1","col2","col3"], "values":[[["b","b","b"],["d","e","f"],["j","g","h","i"]], [["l","j","k"],null,["o"]]], "sources":[[["src2","src1","src3"],["src4","src5","src6"],["src7","src8","src9","src10"]], [["src13","src11","src12"],null,["src15"]]] } ```
50,967,329
I am trying to create a script that will * look at each word in a text document and store in a list (WordList) * Look at a second text document and store each word in a list (RandomText) * Print out the words that appear in both lists I have come up with the below which stores the text in a file, however I can't seem to get the function to compare the lists and print similarities. ``` KeyWords = open("wordlist.txt").readlines() # Opens WordList text file, Reads each line and stores in a list named "KeyWords". RanText = open("RandomText.txt").readlines() # Opens RandomText text file, reads each line and stores in a list named "RanText" def Check(): for x in KeyWords: if x in RanText: print(x) print(KeyWords) print(RanText) print(Check) ``` Output: ``` C:\Scripts>python Search.py ['Word1\n', 'Word2\n', 'Word3\n', 'Word4\n', 'Word5'] ['Lorem ipsum dolor sit amet, Word1 consectetur adipiscing elit. Nunc fringilla arcu congue metus aliquam mollis.\n', 'Mauris nec maximus purus. Maecenas sit amet pretium tellus. Praesent Word3 sed rhoncus eo. Duis id commodo orci.\n', 'Quisque at dignissim lacus.'] <function Check at 0x00A9B618> ```
2018/06/21
[ "https://Stackoverflow.com/questions/50967329", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7276704/" ]
Add `tools:replace="android:label"` to your `<application>` tag in AndroidManifest.xml as suggested in error logs. This error might have occurred because AndroidManifest.xml of some jar file or library might also be having the `android:label` attribute defined in its `<application>` tag which is causing merger conflict as manifest merging process could not understand which `android:label` to continue with.
add uses-SDK tools in the Manifest file ``` <uses-sdk tools:replace="android:label" /> ```
5,217,513
i am looking to start learning. people have told me it is juts as capable. though i haven't really seen any good looking games available. some decent ones on pygame, but none really stand out. i would like to know if python really is as capable as other languages. EDIT: thanks guys, is python good for game development?
2011/03/07
[ "https://Stackoverflow.com/questions/5217513", "https://Stackoverflow.com", "https://Stackoverflow.com/users/647813/" ]
Short answer: Yes, it is. But this heavily depends on your problem :)
This [article](http://www.python.org/doc/essays/comparisons.html) has very good comparison of Python with other languages like C++, Java etc.
5,217,513
i am looking to start learning. people have told me it is juts as capable. though i haven't really seen any good looking games available. some decent ones on pygame, but none really stand out. i would like to know if python really is as capable as other languages. EDIT: thanks guys, is python good for game development?
2011/03/07
[ "https://Stackoverflow.com/questions/5217513", "https://Stackoverflow.com", "https://Stackoverflow.com/users/647813/" ]
Each language has strengths and weaknesses. Also, each implementation of a language has strengths and weaknesses. [CPython](http://en.wikipedia.org/wiki/CPython) is not the same as [Jython](http://en.wikipedia.org/wiki/Jython) and [PyPy](http://en.wikipedia.org/wiki/PyPy) is different again. Python is very good in the "business logic-to-lines of code" ratio: it has a pretty succinct way of putting things. C++ is good at lower-level functionality, but given good code can also express high-level functionality with clean code. Performance of well-written C++ code will *usually* be better than equivalent Python code, but performance is not always an important measurement of code. When big-budget games use Python (or other dynamic languages), then they usually don't write their whole project in that language. Instead they use a base engine written in some lower-level language (C, C++) and implement some (or most or all) of the "business logic" in the dynamic language. That provides the best of both worlds.
Short answer: Yes, it is. But this heavily depends on your problem :)
5,217,513
i am looking to start learning. people have told me it is juts as capable. though i haven't really seen any good looking games available. some decent ones on pygame, but none really stand out. i would like to know if python really is as capable as other languages. EDIT: thanks guys, is python good for game development?
2011/03/07
[ "https://Stackoverflow.com/questions/5217513", "https://Stackoverflow.com", "https://Stackoverflow.com/users/647813/" ]
Each language has strengths and weaknesses. Also, each implementation of a language has strengths and weaknesses. [CPython](http://en.wikipedia.org/wiki/CPython) is not the same as [Jython](http://en.wikipedia.org/wiki/Jython) and [PyPy](http://en.wikipedia.org/wiki/PyPy) is different again. Python is very good in the "business logic-to-lines of code" ratio: it has a pretty succinct way of putting things. C++ is good at lower-level functionality, but given good code can also express high-level functionality with clean code. Performance of well-written C++ code will *usually* be better than equivalent Python code, but performance is not always an important measurement of code. When big-budget games use Python (or other dynamic languages), then they usually don't write their whole project in that language. Instead they use a base engine written in some lower-level language (C, C++) and implement some (or most or all) of the "business logic" in the dynamic language. That provides the best of both worlds.
This [article](http://www.python.org/doc/essays/comparisons.html) has very good comparison of Python with other languages like C++, Java etc.
5,217,513
i am looking to start learning. people have told me it is juts as capable. though i haven't really seen any good looking games available. some decent ones on pygame, but none really stand out. i would like to know if python really is as capable as other languages. EDIT: thanks guys, is python good for game development?
2011/03/07
[ "https://Stackoverflow.com/questions/5217513", "https://Stackoverflow.com", "https://Stackoverflow.com/users/647813/" ]
Yes, Yes and Yes. Python is for Real Programmers. Must Read <http://www.paulgraham.com/pypar.html> Refer For More. <http://wiki.python.org/moin/LanguageComparisons>
This [article](http://www.python.org/doc/essays/comparisons.html) has very good comparison of Python with other languages like C++, Java etc.
5,217,513
i am looking to start learning. people have told me it is juts as capable. though i haven't really seen any good looking games available. some decent ones on pygame, but none really stand out. i would like to know if python really is as capable as other languages. EDIT: thanks guys, is python good for game development?
2011/03/07
[ "https://Stackoverflow.com/questions/5217513", "https://Stackoverflow.com", "https://Stackoverflow.com/users/647813/" ]
Each language has strengths and weaknesses. Also, each implementation of a language has strengths and weaknesses. [CPython](http://en.wikipedia.org/wiki/CPython) is not the same as [Jython](http://en.wikipedia.org/wiki/Jython) and [PyPy](http://en.wikipedia.org/wiki/PyPy) is different again. Python is very good in the "business logic-to-lines of code" ratio: it has a pretty succinct way of putting things. C++ is good at lower-level functionality, but given good code can also express high-level functionality with clean code. Performance of well-written C++ code will *usually* be better than equivalent Python code, but performance is not always an important measurement of code. When big-budget games use Python (or other dynamic languages), then they usually don't write their whole project in that language. Instead they use a base engine written in some lower-level language (C, C++) and implement some (or most or all) of the "business logic" in the dynamic language. That provides the best of both worlds.
Yes, Yes and Yes. Python is for Real Programmers. Must Read <http://www.paulgraham.com/pypar.html> Refer For More. <http://wiki.python.org/moin/LanguageComparisons>
28,865,785
I am using python to take a very large string (DNA sequences) and try to make a suffix tree out of it. My program gave a memory error after a long while of making nested objects, so I thought in order to increase performance, it might be useful to create buffers from the string instead of actually slicing the string. Both version are below, with their relevant issues described. **First (non-buffer) version** - After about a minute of processing a large string a *MemoryError* occurs for currNode.out[substring[0]] = self.Node(pos, substring[1:]) ``` class SuffixTree(object): class Node(object): def __init__(self, position, suffix): self.position = position self.suffix = suffix self.out = {} def __init__(self, text): self.text = text self.max_repeat = 2 self.repeats = {} self.root = self.Node(None, '') L = len(self.text) for i in xrange(L): substring = self.text[-1*(i+1):] + "$" currNode = self.root self.branch(currNode, substring, L-i-1, 0) max_repeat = max(self.repeats.iterkeys(), key=len) print "Max repeat is", len(max_repeat), ":", max_repeat, "at locations:", self.repeats[max_repeat] def branch(self, currNode, substring, pos, repeat): if currNode.suffix != '': currNode.out[currNode.suffix[0]] = self.Node(currNode.position, currNode.suffix[1:]) currNode.suffix = '' currNode.position = None if substring[0] not in currNode.out: currNode.out[substring[0]] = self.Node(pos, substring[1:]) if repeat >= self.max_repeat: for node in currNode.out: self.repeats.setdefault(self.text[pos:pos+repeat], []).append(currNode.out[node].position) self.max_repeat = repeat else: newNode = currNode.out[substring[0]] self.branch(newNode, substring[1:], pos, repeat+1) ``` \*\*Second Version \*\* - Thinking that the constant saving of large string slices was probably the issue, I implemented all of the slices using buffers of strings instead. However, this version almost immediately gives a *MemoryError* for substring = buffer(self.text, i-1) + "$" ``` class SuffixTree(object): class Node(object): def __init__(self, position, suffix): self.position = position self.suffix = suffix self.out = {} def __init__(self, text): self.text = text self.max_repeat = 2 self.repeats = {} self.root = self.Node(None, '') L = len(self.text) for i in xrange(L,0,-1): substring = buffer(self.text, i-1) + "$" #print substring currNode = self.root self.branch(currNode, substring, i-1, 0) max_repeat = max(self.repeats.iterkeys(), key=len) print "Max repeat is", len(max_repeat), ":", max_repeat, "at locations:", self.repeats[max_repeat] #print self.repeats def branch(self, currNode, substring, pos, repeat): if currNode.suffix != '': currNode.out[currNode.suffix[0]] = self.Node(currNode.position, buffer(currNode.suffix,1)) currNode.suffix = '' currNode.position = None if substring[0] not in currNode.out: currNode.out[substring[0]] = self.Node(pos, buffer(substring,1)) if repeat >= self.max_repeat: for node in currNode.out: self.repeats.setdefault(buffer(self.text,pos,repeat), []).append(currNode.out[node].position) self.max_repeat = repeat else: newNode = currNode.out[substring[0]] self.branch(newNode, buffer(substring,1), pos, repeat+1) ``` Is my understanding of buffers mistaken in someway? I thought using them would help the memory issue my program was having, not make it worse.
2015/03/04
[ "https://Stackoverflow.com/questions/28865785", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
The result makes sense. The check inside your ifs is truey in both cases (probably because both BL1, BN1 exist). What you need to do in your code is retrieve the selected index and then use it. Give an id to your dropdown list: ``` <select id="dropdownList"> .... ``` And then use it in your code to retrieve the selected value: ``` var dropdownList = document.getElementById("dropdownList"); var price = dropdownList.options[dropdownList.selectedIndex].value; //rest of code ``` Take a look on a similar question [here](https://stackoverflow.com/questions/1085801/get-selected-value-of-dropdownlist-using-javascript). You can also find a relative tutorial [here](http://www.javascript-coder.com/javascript-form/javascript-get-select.phtml).
1st: You are defining the variable *price* multiple times. 2nd: Your code checks for 'value' and of cause, it always has a value. I guess, what you really want to check is, whether an option is selected or not annd then use its value. ```js function BookingFare() { var price = 0; var BN1 = document.getElementById('BN1'); var BL1 = document.getElementById('BL1'); if (BL1.selected) { price = BL1.value; } if (BN1.selected) { price = BN1.value; } document.getElementById('priceBox').innerHTML = price; } ``` ```html <form> <select> <option name="Bristol " value="40.0" id="BN1">Bristol - Newcastle</option> <option name="London " value="35.0" id="BL1">Bristol - London</option> </select> <button type="button" onclick="BookingFare(); return false;">Submit</button> <br> <label id='priceBox'></label> </form> ```
28,865,785
I am using python to take a very large string (DNA sequences) and try to make a suffix tree out of it. My program gave a memory error after a long while of making nested objects, so I thought in order to increase performance, it might be useful to create buffers from the string instead of actually slicing the string. Both version are below, with their relevant issues described. **First (non-buffer) version** - After about a minute of processing a large string a *MemoryError* occurs for currNode.out[substring[0]] = self.Node(pos, substring[1:]) ``` class SuffixTree(object): class Node(object): def __init__(self, position, suffix): self.position = position self.suffix = suffix self.out = {} def __init__(self, text): self.text = text self.max_repeat = 2 self.repeats = {} self.root = self.Node(None, '') L = len(self.text) for i in xrange(L): substring = self.text[-1*(i+1):] + "$" currNode = self.root self.branch(currNode, substring, L-i-1, 0) max_repeat = max(self.repeats.iterkeys(), key=len) print "Max repeat is", len(max_repeat), ":", max_repeat, "at locations:", self.repeats[max_repeat] def branch(self, currNode, substring, pos, repeat): if currNode.suffix != '': currNode.out[currNode.suffix[0]] = self.Node(currNode.position, currNode.suffix[1:]) currNode.suffix = '' currNode.position = None if substring[0] not in currNode.out: currNode.out[substring[0]] = self.Node(pos, substring[1:]) if repeat >= self.max_repeat: for node in currNode.out: self.repeats.setdefault(self.text[pos:pos+repeat], []).append(currNode.out[node].position) self.max_repeat = repeat else: newNode = currNode.out[substring[0]] self.branch(newNode, substring[1:], pos, repeat+1) ``` \*\*Second Version \*\* - Thinking that the constant saving of large string slices was probably the issue, I implemented all of the slices using buffers of strings instead. However, this version almost immediately gives a *MemoryError* for substring = buffer(self.text, i-1) + "$" ``` class SuffixTree(object): class Node(object): def __init__(self, position, suffix): self.position = position self.suffix = suffix self.out = {} def __init__(self, text): self.text = text self.max_repeat = 2 self.repeats = {} self.root = self.Node(None, '') L = len(self.text) for i in xrange(L,0,-1): substring = buffer(self.text, i-1) + "$" #print substring currNode = self.root self.branch(currNode, substring, i-1, 0) max_repeat = max(self.repeats.iterkeys(), key=len) print "Max repeat is", len(max_repeat), ":", max_repeat, "at locations:", self.repeats[max_repeat] #print self.repeats def branch(self, currNode, substring, pos, repeat): if currNode.suffix != '': currNode.out[currNode.suffix[0]] = self.Node(currNode.position, buffer(currNode.suffix,1)) currNode.suffix = '' currNode.position = None if substring[0] not in currNode.out: currNode.out[substring[0]] = self.Node(pos, buffer(substring,1)) if repeat >= self.max_repeat: for node in currNode.out: self.repeats.setdefault(buffer(self.text,pos,repeat), []).append(currNode.out[node].position) self.max_repeat = repeat else: newNode = currNode.out[substring[0]] self.branch(newNode, buffer(substring,1), pos, repeat+1) ``` Is my understanding of buffers mistaken in someway? I thought using them would help the memory issue my program was having, not make it worse.
2015/03/04
[ "https://Stackoverflow.com/questions/28865785", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
The result makes sense. The check inside your ifs is truey in both cases (probably because both BL1, BN1 exist). What you need to do in your code is retrieve the selected index and then use it. Give an id to your dropdown list: ``` <select id="dropdownList"> .... ``` And then use it in your code to retrieve the selected value: ``` var dropdownList = document.getElementById("dropdownList"); var price = dropdownList.options[dropdownList.selectedIndex].value; //rest of code ``` Take a look on a similar question [here](https://stackoverflow.com/questions/1085801/get-selected-value-of-dropdownlist-using-javascript). You can also find a relative tutorial [here](http://www.javascript-coder.com/javascript-form/javascript-get-select.phtml).
I think this is what you are looking for. ```html <script> function BookingFare() { var price = 0; //var ofAdults = getElementById('adults').value; //var ofChildren = getElementById('children').value; var bristol = document.getElementById('bristol').value; console.log(bristol); if (bristol == 35.0) { var price = bristol; } if (bristol == 40.0) { var price = bristol; } document.getElementById('priceBox').innerHTML = price; } </script> <form> <select id="bristol"> <option name ="Bristol "value="40.0" id ="BN1">Bristol - Newcastle</option> <option name ="London "value="35.0" id ="BL1">Bristol - London</option> </select> <button type="button" onclick="BookingFare(); return false;">Submit</button> </form> <label id='priceBox'></label> ```
49,883,623
Am trying to solve project euler question : > > 2520 is the smallest number that can be divided by each of the numbers > from 1 to 10 without any remainder. What is the smallest positive > number that is evenly divisible by all of the numbers from 1 to 20? > > > I've come up with the python solution below, but is there any way to loop the number in the `if` instead of having to write all of them. ``` def smallest_m(): start=1 while True: if start%2==0 and start%3==0 and start%4==0 and start%5==0 and start%5==0 and start%6==0 and start%7==0 and start%8==0 and start%9==0 and start%10==0 and start%11==0 and start%12==0 and start%13==0 and start%14==0 and start%15==0 and start%16==0 and start%17==0 and start%18==0 and start%19==0 and start%20==0: print(start) break else: start+=1 smallest_m() ```
2018/04/17
[ "https://Stackoverflow.com/questions/49883623", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5126615/" ]
You can use a generator expression and the all function: ``` def smallest_m(): start = 1 while True: if all(start % i == 0 for i in range(2, 20+1)): print(start) break else: start+=1 smallest_m() ```
Try this ``` n = 2520 result = True for i in range(1, 11): if (n % i != 0): result = False print(result) ```
49,883,623
Am trying to solve project euler question : > > 2520 is the smallest number that can be divided by each of the numbers > from 1 to 10 without any remainder. What is the smallest positive > number that is evenly divisible by all of the numbers from 1 to 20? > > > I've come up with the python solution below, but is there any way to loop the number in the `if` instead of having to write all of them. ``` def smallest_m(): start=1 while True: if start%2==0 and start%3==0 and start%4==0 and start%5==0 and start%5==0 and start%6==0 and start%7==0 and start%8==0 and start%9==0 and start%10==0 and start%11==0 and start%12==0 and start%13==0 and start%14==0 and start%15==0 and start%16==0 and start%17==0 and start%18==0 and start%19==0 and start%20==0: print(start) break else: start+=1 smallest_m() ```
2018/04/17
[ "https://Stackoverflow.com/questions/49883623", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5126615/" ]
Here is one solution which utilizes a generator. The smallest number I see is 232792560. ``` def smallest_m(n): for k in range(20, n, 20): match = True for i in range(1, 21): if k % i != 0: match = False break else: if match: yield k res = next(smallest_m(2432902008176640001)) # 232792560 ```
Try this ``` n = 2520 result = True for i in range(1, 11): if (n % i != 0): result = False print(result) ```
49,883,623
Am trying to solve project euler question : > > 2520 is the smallest number that can be divided by each of the numbers > from 1 to 10 without any remainder. What is the smallest positive > number that is evenly divisible by all of the numbers from 1 to 20? > > > I've come up with the python solution below, but is there any way to loop the number in the `if` instead of having to write all of them. ``` def smallest_m(): start=1 while True: if start%2==0 and start%3==0 and start%4==0 and start%5==0 and start%5==0 and start%6==0 and start%7==0 and start%8==0 and start%9==0 and start%10==0 and start%11==0 and start%12==0 and start%13==0 and start%14==0 and start%15==0 and start%16==0 and start%17==0 and start%18==0 and start%19==0 and start%20==0: print(start) break else: start+=1 smallest_m() ```
2018/04/17
[ "https://Stackoverflow.com/questions/49883623", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5126615/" ]
You can use a generator expression and the all function: ``` def smallest_m(): start = 1 while True: if all(start % i == 0 for i in range(2, 20+1)): print(start) break else: start+=1 smallest_m() ```
Here is one solution which utilizes a generator. The smallest number I see is 232792560. ``` def smallest_m(n): for k in range(20, n, 20): match = True for i in range(1, 21): if k % i != 0: match = False break else: if match: yield k res = next(smallest_m(2432902008176640001)) # 232792560 ```
21,735,023
I am a python newb so please forgive me. I have searched on Google and SA but couldn't find anything. Anyway, I am using the python library [Wordpress XMLRPC](http://python-wordpress-xmlrpc.readthedocs.org/en/latest/overview.html). `myblog`, `myusername`, and `mypassword` are just placeholders to hide my real website, username and password. When I run the code I use my real data. My Code: ``` from wordpress_xmlrpc import * wp = Client('http://www.myblog.wordpress.com/xmlrpc.php', 'myusername', 'mypassword') ``` The Error: ``` Traceback (most recent call last): File "C:/Python27/wordpress_bro", line 2, in <module> wp = Client('http://www.myblog.wordpress.com/xmlrpc.php', 'myusername', 'mypassword') File "build\bdist.win32\egg\wordpress_xmlrpc\base.py", line 27, in __init__ raise ServerConnectionError(repr(e)) ServerConnectionError: <ProtocolError for www.myblog.wordpress.com/xmlrpc.php: 301 Moved Permanently> ``` When I go to `http://www.myblog.wordpress.com/xmlrpc.php` in my browser I get: ``` XML-RPC server accepts POST requests only. ``` Could somebody please help me? Thanks!
2014/02/12
[ "https://Stackoverflow.com/questions/21735023", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3302735/" ]
Variant 3 is ok (but I'd rather use a loop instead of hard-coded options). Your mistake is that you compare 'option1', 'option2' and so one when your real values are '1', '2', '3'. Also as @ElefantPhace said, don't forget about spaces before **selected**, or you'll get invalid html instead. So it would be this: ``` <select name="up_opt"> <option value="1" <?php if ($_GET['up_opt'] == 1) { echo ' selected="selected"'; } ?>>Opt1</option> <option value="2" <?php if ($_GET['up_opt'] == 2) { echo ' selected="selected"'; } ?>>Opt2</option> <option value="3" <?php if ($_GET['up_opt'] == 3) { echo ' selected="selected"'; } ?>>Opt3</option> </select> ``` With loop: ``` <?php $options = array( 1 => 'Opt1', 2 => 'Opt2', 3 => 'Opt3', ); ?> <select name="up_opt"> <?php foreach ($options as $value => $label): ?> <option value="<?php echo $value; ?>" <?php if ($_GET['up_opt'] == 1) { echo ' selected="selected"'; } ?>><?php echo $label; ?></option> <?php endforeach ?> </select> ```
Here is all three of your variants, tested and working as expected. They are all basically the same, you were just using the wrong variable names, and different ones from example to example 1) ``` <?php $opt= array('1' => 'opt1', '2' => 'opt2', '3' => 'opt3') ; echo '<select name="up_opt">'; foreach ($opt as $i => $value) { echo "<option value=\"$i\""; if ($_POST['up_opt'] == $i){ echo " selected"; } echo ">$value</option>"; } echo '</select>'; ?> ``` 2) uses same array as above ``` $edu = $_POST['up_opt']; echo '<select name="up_opt">'; foreach ( $opt as $i => $value ){ echo "<option value=\"$i\"", ($i == $edu) ? ' selected' : ''; echo ">$value</option>"; } echo "</select>"; ``` 3) ``` echo '<select name="up_opt">'; echo '<option value="1"', ($_POST['up_opt'] == '1') ? 'selected':'' ,'>Opt1</option>'; echo '<option value="2"', ($_POST['up_opt'] == '2') ? 'selected':'' ,'>Opt2</option>'; echo '<option value="3"', ($_POST['up_opt'] == '3') ? 'selected':'' ,'>Opt3</option>'; echo '</select>'; ```
15,260,558
Here is my code to run the server: ``` class MyRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler): #.... PORT = 8089 httpd = SocketServer.TCPServer(("", PORT), MyRequestHandler) httpd.allow_reuse_address = True print "Serving forever at port", PORT try: httpd.serve_forever() except: print "Closing the server." httpd.server_close() raise ``` Yet this is what happens: ``` ^CClosing the server. Traceback (most recent call last): File "server.py", line 118, in <module> self.send_error(400, "Unimplemented GET command: %s" % (self.path,)) File "/home/claudiu/local/lib/python2.6/SocketServer.py", line 224, in serve_forever r, w, e = select.select([self], [], [], poll_interval) KeyboardInterrupt (.virtualenv)claudiu@xxx:~/xxx$ python server.py Traceback (most recent call last): File "server.py", line 122, in <module> httpd = SocketServer.TCPServer(("", PORT), MyRequestHandler) File "/home/claudiu/local/lib/python2.6/SocketServer.py", line 402, in __init__ self.server_bind() File "/home/claudiu/local/lib/python2.6/SocketServer.py", line 413, in server_bind self.socket.bind(self.server_address) File "<string>", line 1, in bind socket.error: [Errno 98] Address already in use ``` Why? I close the server and set `allow_reuse_address` to True... Using python 2.6.8.
2013/03/06
[ "https://Stackoverflow.com/questions/15260558", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15055/" ]
It is because TCP [TIME\_WAIT](http://dev.fyicenter.com/Interview-Questions/Socket-4/Explain_the_TIME_WAIT_state_.html). [Somebody discovered this exact problem.](http://brokenbad.com/2012/01/address-reuse-in-pythons-socketserver/) > > However, if I try to stop and start the server again to test any modifications, I get a random “socket.error: [Errno 98] Address > already in use” error. This happens only if a client has already > connected to the server. > > > Checking with netstat and ps, I found that although the process it > self is no longer running, the socket is still listening on the port > with status “TIME\_WAIT”. Basically the OS waits for a while to make > sure this connection has no remaining packets on the way. > > >
It is because you have to set SO\_REUSEADDRESS *before* you bind the socket. As you are creating and binding the socket all in one step and then setting it, it is already too late.
15,260,558
Here is my code to run the server: ``` class MyRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler): #.... PORT = 8089 httpd = SocketServer.TCPServer(("", PORT), MyRequestHandler) httpd.allow_reuse_address = True print "Serving forever at port", PORT try: httpd.serve_forever() except: print "Closing the server." httpd.server_close() raise ``` Yet this is what happens: ``` ^CClosing the server. Traceback (most recent call last): File "server.py", line 118, in <module> self.send_error(400, "Unimplemented GET command: %s" % (self.path,)) File "/home/claudiu/local/lib/python2.6/SocketServer.py", line 224, in serve_forever r, w, e = select.select([self], [], [], poll_interval) KeyboardInterrupt (.virtualenv)claudiu@xxx:~/xxx$ python server.py Traceback (most recent call last): File "server.py", line 122, in <module> httpd = SocketServer.TCPServer(("", PORT), MyRequestHandler) File "/home/claudiu/local/lib/python2.6/SocketServer.py", line 402, in __init__ self.server_bind() File "/home/claudiu/local/lib/python2.6/SocketServer.py", line 413, in server_bind self.socket.bind(self.server_address) File "<string>", line 1, in bind socket.error: [Errno 98] Address already in use ``` Why? I close the server and set `allow_reuse_address` to True... Using python 2.6.8.
2013/03/06
[ "https://Stackoverflow.com/questions/15260558", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15055/" ]
Thanks to the other answers, I figured it out. `allow_reuse_address` should be on the class, not on the instance: ``` SocketServer.TCPServer.allow_reuse_address = True httpd = SocketServer.TCPServer(("", PORT), MyRequestHandler) ``` I'm still not sure why closing the socket didn't free it up for the next run of the server, though.
It is because TCP [TIME\_WAIT](http://dev.fyicenter.com/Interview-Questions/Socket-4/Explain_the_TIME_WAIT_state_.html). [Somebody discovered this exact problem.](http://brokenbad.com/2012/01/address-reuse-in-pythons-socketserver/) > > However, if I try to stop and start the server again to test any modifications, I get a random “socket.error: [Errno 98] Address > already in use” error. This happens only if a client has already > connected to the server. > > > Checking with netstat and ps, I found that although the process it > self is no longer running, the socket is still listening on the port > with status “TIME\_WAIT”. Basically the OS waits for a while to make > sure this connection has no remaining packets on the way. > > >
15,260,558
Here is my code to run the server: ``` class MyRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler): #.... PORT = 8089 httpd = SocketServer.TCPServer(("", PORT), MyRequestHandler) httpd.allow_reuse_address = True print "Serving forever at port", PORT try: httpd.serve_forever() except: print "Closing the server." httpd.server_close() raise ``` Yet this is what happens: ``` ^CClosing the server. Traceback (most recent call last): File "server.py", line 118, in <module> self.send_error(400, "Unimplemented GET command: %s" % (self.path,)) File "/home/claudiu/local/lib/python2.6/SocketServer.py", line 224, in serve_forever r, w, e = select.select([self], [], [], poll_interval) KeyboardInterrupt (.virtualenv)claudiu@xxx:~/xxx$ python server.py Traceback (most recent call last): File "server.py", line 122, in <module> httpd = SocketServer.TCPServer(("", PORT), MyRequestHandler) File "/home/claudiu/local/lib/python2.6/SocketServer.py", line 402, in __init__ self.server_bind() File "/home/claudiu/local/lib/python2.6/SocketServer.py", line 413, in server_bind self.socket.bind(self.server_address) File "<string>", line 1, in bind socket.error: [Errno 98] Address already in use ``` Why? I close the server and set `allow_reuse_address` to True... Using python 2.6.8.
2013/03/06
[ "https://Stackoverflow.com/questions/15260558", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15055/" ]
The `[Err 98] Address already in use` is due to the fact the socket was `.close()` but it's still waiting for enough time to pass to be sure the remote TCP received the acknowledgment of its connection termination request (see [TIME\_WAIT](https://en.wikipedia.org/wiki/Transmission_Control_Protocol)). By default you are not allowed to bind a socket if there a socket bound to that port but you can override that with `allow_reuse_address` (SO\_REUSEADDR) Although is possible to mutate `TCPServer.allow_reuse_addr` (as proposed in [this other answer](https://stackoverflow.com/a/15278302/90580)), I think is more clean to your own subclass of `TCPServer` where `allow_reuse_address` is set to `True`: ``` import SocketServer import SimpleHTTPServer import time class MyRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler): def do_GET(): time.sleep(60) self.request.sendall("I'm here!") class ReuseAddrTCPServer(SocketServer.TCPServer): allow_reuse_address = True PORT = 8089 httpd = ReuseAddrTCPServer(("", PORT), MyRequestHandler) httpd.daemon_threads = True print "Serving forever at port", PORT try: httpd.serve_forever() except: print "Closing the server." httpd.server_close() raise ``` You can use definitely set `allow_reuse_address` on the instance itself (without messing with classes) but you need to use `TCPServer(..., bind_and_activate=False)`, otherwise the socket will be bound before you have a chance to change the `allow_reuse_address` setting. Then you need to manually call `.server_bind()` and `.server_activate()` before `serve_forever()`: ``` ... httpd = SocketServer.TCPServer(("", PORT), MyRequestHandler, bind_and_activate=False) httpd.allow_reuse_address = True httpd.daemon_threads = True ... httpd.server_bind() httpd.server_activate() httpd.serve_forever() ```
It is because TCP [TIME\_WAIT](http://dev.fyicenter.com/Interview-Questions/Socket-4/Explain_the_TIME_WAIT_state_.html). [Somebody discovered this exact problem.](http://brokenbad.com/2012/01/address-reuse-in-pythons-socketserver/) > > However, if I try to stop and start the server again to test any modifications, I get a random “socket.error: [Errno 98] Address > already in use” error. This happens only if a client has already > connected to the server. > > > Checking with netstat and ps, I found that although the process it > self is no longer running, the socket is still listening on the port > with status “TIME\_WAIT”. Basically the OS waits for a while to make > sure this connection has no remaining packets on the way. > > >
15,260,558
Here is my code to run the server: ``` class MyRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler): #.... PORT = 8089 httpd = SocketServer.TCPServer(("", PORT), MyRequestHandler) httpd.allow_reuse_address = True print "Serving forever at port", PORT try: httpd.serve_forever() except: print "Closing the server." httpd.server_close() raise ``` Yet this is what happens: ``` ^CClosing the server. Traceback (most recent call last): File "server.py", line 118, in <module> self.send_error(400, "Unimplemented GET command: %s" % (self.path,)) File "/home/claudiu/local/lib/python2.6/SocketServer.py", line 224, in serve_forever r, w, e = select.select([self], [], [], poll_interval) KeyboardInterrupt (.virtualenv)claudiu@xxx:~/xxx$ python server.py Traceback (most recent call last): File "server.py", line 122, in <module> httpd = SocketServer.TCPServer(("", PORT), MyRequestHandler) File "/home/claudiu/local/lib/python2.6/SocketServer.py", line 402, in __init__ self.server_bind() File "/home/claudiu/local/lib/python2.6/SocketServer.py", line 413, in server_bind self.socket.bind(self.server_address) File "<string>", line 1, in bind socket.error: [Errno 98] Address already in use ``` Why? I close the server and set `allow_reuse_address` to True... Using python 2.6.8.
2013/03/06
[ "https://Stackoverflow.com/questions/15260558", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15055/" ]
Thanks to the other answers, I figured it out. `allow_reuse_address` should be on the class, not on the instance: ``` SocketServer.TCPServer.allow_reuse_address = True httpd = SocketServer.TCPServer(("", PORT), MyRequestHandler) ``` I'm still not sure why closing the socket didn't free it up for the next run of the server, though.
It is because you have to set SO\_REUSEADDRESS *before* you bind the socket. As you are creating and binding the socket all in one step and then setting it, it is already too late.
15,260,558
Here is my code to run the server: ``` class MyRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler): #.... PORT = 8089 httpd = SocketServer.TCPServer(("", PORT), MyRequestHandler) httpd.allow_reuse_address = True print "Serving forever at port", PORT try: httpd.serve_forever() except: print "Closing the server." httpd.server_close() raise ``` Yet this is what happens: ``` ^CClosing the server. Traceback (most recent call last): File "server.py", line 118, in <module> self.send_error(400, "Unimplemented GET command: %s" % (self.path,)) File "/home/claudiu/local/lib/python2.6/SocketServer.py", line 224, in serve_forever r, w, e = select.select([self], [], [], poll_interval) KeyboardInterrupt (.virtualenv)claudiu@xxx:~/xxx$ python server.py Traceback (most recent call last): File "server.py", line 122, in <module> httpd = SocketServer.TCPServer(("", PORT), MyRequestHandler) File "/home/claudiu/local/lib/python2.6/SocketServer.py", line 402, in __init__ self.server_bind() File "/home/claudiu/local/lib/python2.6/SocketServer.py", line 413, in server_bind self.socket.bind(self.server_address) File "<string>", line 1, in bind socket.error: [Errno 98] Address already in use ``` Why? I close the server and set `allow_reuse_address` to True... Using python 2.6.8.
2013/03/06
[ "https://Stackoverflow.com/questions/15260558", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15055/" ]
The `[Err 98] Address already in use` is due to the fact the socket was `.close()` but it's still waiting for enough time to pass to be sure the remote TCP received the acknowledgment of its connection termination request (see [TIME\_WAIT](https://en.wikipedia.org/wiki/Transmission_Control_Protocol)). By default you are not allowed to bind a socket if there a socket bound to that port but you can override that with `allow_reuse_address` (SO\_REUSEADDR) Although is possible to mutate `TCPServer.allow_reuse_addr` (as proposed in [this other answer](https://stackoverflow.com/a/15278302/90580)), I think is more clean to your own subclass of `TCPServer` where `allow_reuse_address` is set to `True`: ``` import SocketServer import SimpleHTTPServer import time class MyRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler): def do_GET(): time.sleep(60) self.request.sendall("I'm here!") class ReuseAddrTCPServer(SocketServer.TCPServer): allow_reuse_address = True PORT = 8089 httpd = ReuseAddrTCPServer(("", PORT), MyRequestHandler) httpd.daemon_threads = True print "Serving forever at port", PORT try: httpd.serve_forever() except: print "Closing the server." httpd.server_close() raise ``` You can use definitely set `allow_reuse_address` on the instance itself (without messing with classes) but you need to use `TCPServer(..., bind_and_activate=False)`, otherwise the socket will be bound before you have a chance to change the `allow_reuse_address` setting. Then you need to manually call `.server_bind()` and `.server_activate()` before `serve_forever()`: ``` ... httpd = SocketServer.TCPServer(("", PORT), MyRequestHandler, bind_and_activate=False) httpd.allow_reuse_address = True httpd.daemon_threads = True ... httpd.server_bind() httpd.server_activate() httpd.serve_forever() ```
It is because you have to set SO\_REUSEADDRESS *before* you bind the socket. As you are creating and binding the socket all in one step and then setting it, it is already too late.
15,260,558
Here is my code to run the server: ``` class MyRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler): #.... PORT = 8089 httpd = SocketServer.TCPServer(("", PORT), MyRequestHandler) httpd.allow_reuse_address = True print "Serving forever at port", PORT try: httpd.serve_forever() except: print "Closing the server." httpd.server_close() raise ``` Yet this is what happens: ``` ^CClosing the server. Traceback (most recent call last): File "server.py", line 118, in <module> self.send_error(400, "Unimplemented GET command: %s" % (self.path,)) File "/home/claudiu/local/lib/python2.6/SocketServer.py", line 224, in serve_forever r, w, e = select.select([self], [], [], poll_interval) KeyboardInterrupt (.virtualenv)claudiu@xxx:~/xxx$ python server.py Traceback (most recent call last): File "server.py", line 122, in <module> httpd = SocketServer.TCPServer(("", PORT), MyRequestHandler) File "/home/claudiu/local/lib/python2.6/SocketServer.py", line 402, in __init__ self.server_bind() File "/home/claudiu/local/lib/python2.6/SocketServer.py", line 413, in server_bind self.socket.bind(self.server_address) File "<string>", line 1, in bind socket.error: [Errno 98] Address already in use ``` Why? I close the server and set `allow_reuse_address` to True... Using python 2.6.8.
2013/03/06
[ "https://Stackoverflow.com/questions/15260558", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15055/" ]
Thanks to the other answers, I figured it out. `allow_reuse_address` should be on the class, not on the instance: ``` SocketServer.TCPServer.allow_reuse_address = True httpd = SocketServer.TCPServer(("", PORT), MyRequestHandler) ``` I'm still not sure why closing the socket didn't free it up for the next run of the server, though.
The `[Err 98] Address already in use` is due to the fact the socket was `.close()` but it's still waiting for enough time to pass to be sure the remote TCP received the acknowledgment of its connection termination request (see [TIME\_WAIT](https://en.wikipedia.org/wiki/Transmission_Control_Protocol)). By default you are not allowed to bind a socket if there a socket bound to that port but you can override that with `allow_reuse_address` (SO\_REUSEADDR) Although is possible to mutate `TCPServer.allow_reuse_addr` (as proposed in [this other answer](https://stackoverflow.com/a/15278302/90580)), I think is more clean to your own subclass of `TCPServer` where `allow_reuse_address` is set to `True`: ``` import SocketServer import SimpleHTTPServer import time class MyRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler): def do_GET(): time.sleep(60) self.request.sendall("I'm here!") class ReuseAddrTCPServer(SocketServer.TCPServer): allow_reuse_address = True PORT = 8089 httpd = ReuseAddrTCPServer(("", PORT), MyRequestHandler) httpd.daemon_threads = True print "Serving forever at port", PORT try: httpd.serve_forever() except: print "Closing the server." httpd.server_close() raise ``` You can use definitely set `allow_reuse_address` on the instance itself (without messing with classes) but you need to use `TCPServer(..., bind_and_activate=False)`, otherwise the socket will be bound before you have a chance to change the `allow_reuse_address` setting. Then you need to manually call `.server_bind()` and `.server_activate()` before `serve_forever()`: ``` ... httpd = SocketServer.TCPServer(("", PORT), MyRequestHandler, bind_and_activate=False) httpd.allow_reuse_address = True httpd.daemon_threads = True ... httpd.server_bind() httpd.server_activate() httpd.serve_forever() ```
5,988,617
According to the python doc, vertical bars literal are used as an 'or' operator. It matches A|B,where A and B can be arbitrary REs. For example, if the regular expression is as following: ABC|DEF,it matches strings like these: "ABC", "DEF" But what if I want to match strings as following: "ABCF", "ADEF" Perhaps what I want is something like **A(BC)|(DE)F** which means: * match "A" first, * then string "BC" or "DE", * then char "F". I know the above expression is not right since brackets have other meanings in regular expression, just to express my idea. Thanks!
2011/05/13
[ "https://Stackoverflow.com/questions/5988617", "https://Stackoverflow.com", "https://Stackoverflow.com/users/166482/" ]
These will work: ``` A(BC|DE)F A(?:BC|DE)F ``` The difference is the number of groups generated: 1 with the first, 0 with the second. Yours will match either `ABC` or `DEF`, with 2 groups, one containing nothing and the other containing the matched fragment (`BC` or `DE`).
The only difference between parentheses in Python regexps (and perl-compatible regexps in general), and parentheses in formal regular expressions, is that in Python, parens store their result. Everything matched by a regular expression inside parentheses is stored as a "submatch" or "group" that you can access using the `group` method on the match object returned by `re.match`, `re.search`, or `re.finditer`. They are also used in backreferences, a feature of Python RE/PCRE that violates normal regular expression rules, and that you probably don't care about. If you don't care about the whole submatch extraction deal, it's fine to use parens like this. If you do care, there is a non-capturing version of parens that are exactly the same as formal regular expressions: `(?:...)` instead of `(...)`. This, and more, is described in the [official docs](http://docs.python.org/library/re.html#regular-expression-syntax)
8,340,372
> > **Note:** this question is tagged both **language-agnostic** and **python** as my primary concern is finding out the algorithm to implement the solution to the problem, but information on how to implement it *efficiently* (=executing fast!) in python are a plus. > > > **Rules of the game:** * Imagine two teams one of *A agents* (`An`) and one of *B agents* (`Bn`). * In the game space there are a certain number of available *slots* (`Sn`) that can be occupied. * At each turn each agent is given a subset of slots he/she can occupy. * One agent can occupy *only one slot at at time*, however each slot can be occupied by two different agents, provided they are *each from a different team*. **The question:** I am trying to find an ***efficient* way to compute the best possible move** for `A` agents, where "best possible move" means either maximising or minimising the chances to occupy the same slots occupied by team `B`. The moves of team `B` are not known in advance. **Example scenario:** This scenario is deliberately trivial. It is just meant to illustrate the game mechanics. ``` A1 can occupy S1, S2 A2 can occupy S2, S3 B1 can occupy S1, S2 ``` In this case the solution is obvious: `A1 → S1` and `A2 → S2` is the option that will guarantee meeting with `B1` [as `B1` cannot avoid to occupy either `S1` or `S2`], while `A2 → S3` and `A1 → random(S1, S2)` is the one that will maximise the chances to avoid `B1`. **Real-life scenarios:** In real-life scenarios, the slots can be hundreds and the agents in each team various dozens. The difficulty in the naïve implementation I tried so far is that I basically consider every single possible set of moves for the team `B`, and score each of the possible alternative set of moves for `A`. So, my computation time increases exponentially. Still, I'm not sure this is a problem that can be solved only by "brute force". And even if this is the case I wonder: 1. If the optimal brute force solution necessarily grows exponentially (time-wise). 2. If there is a way to compute an non-optimal, locally-best solution. Thank you!
2011/12/01
[ "https://Stackoverflow.com/questions/8340372", "https://Stackoverflow.com", "https://Stackoverflow.com/users/146792/" ]
If I understand correctly, the problem of finding an optimal strategy for A once you know the positions for B is the same as finding a [maximum matching](http://en.wikipedia.org/wiki/Matching_%28graph_theory%29) in a bipartite graph. The first set of vertices represent the A agents, the second set of vertices represent the slots ocupyed by the B agents and there is an edge if an agent can choose the occupy the slot. The problem is then finding the maximum number of edges you can ocupy without a vertex touching more then one edge. There are simple polynomial algorithms to solve this problem. One of the most classic is the one based on [augmenting paths](https://en.wikipedia.org/wiki/Maximum_flow_problem#Maximum_cardinality_bipartite_matching). ``` while you can find a path, augment the path a path is a sequence of vertices a1, b1, a2, b2, ... an, bn such that ai -> bi is an unmatched edge bi -> a(i+1) is a matched edge a1 and bn are unmatched to augment a path match all the unmatched edges (ai -> bi) unmatch all the matched edges (bi -> a(i+1)) (this results in one aditional matched edge after the iteration) ``` A naïve implementation of this algorithm is O(V\*E) but you can probably find more efficient python implementations of bipartite matching somewhere.
This is not really a question of programming as much as it is a game theory question. What follows is a sketch of a game-theoretic analysis of the problem. We have a game of two players (A and B). A two-player game is always a zero-sum game, i.e. the gain of one player is loss for the other. Even if game payoffs are not zero-sum (i.e. there are results that give positive payoffs to both players), payoffs can be always normalized (taking their difference), so we can assume without loss of generality that the game here is also a zero-sum game. From this we deduce that if it is the goal of A to maximize [minimize] the number of meetings with agents of B, then it is the goal of B to minimize [maximize] the number of meetings with agents of A. Based on the description it is further assumed that A and B choose their moves simultaneously, i.e. A picks the slots for A's agents without knowing which slots B's agents are going to take and vice versa. Without this assumption, i.e. if B can see A's moves, it's very easy for B to "win". Let X be the set of all possible assignments of A's agents to the available slots (obeying the constraints for the current round or turn), i.e. X is a set of subsets of the slots; every subset denoting an assignment of agents to exactly those slots in the subset. Similarly, let Y be the set of all possible assignment of B's agents to the available slots (similarly obeying the constraints for B's agents). There are now four games. In each game A chooses an alement x of X and b chooses an element y of Y, after which: * In game I.a, A wins if x and y share a slot, otherwise B wins (in this game, A tries to force at least one meeting) * In game I.b, A receives a positive payoff equivalent to the number of common slots in x and y (in this game, A tries to maximize the number of meetings) * In game II.a, A wins if x and y do not share a slot, otherwise B wins (in this game, A tries to avoid any meetings) * In game II.b, A receives a negative payoff equivalent to the number of common slots in x and y (in this game, A tries to minimize the number of meetings) All these games can be analyzed using standard game-theoretic techniques. We focus on game I.a and leave the rest as an exercise to the reader. If there is an element y of Y available such that no x in X shares a slot with y, B chooses y and wins; so assume not, i.e. assume that every y in Y corresponds to at least one x in X such that x and y share a slot. A cannot play by any deterministic strategy, because B can counter it by choosing an y that does not share a slot with the deterministically chosen x; therefore A has to play by a mixed strategy, i.e. a randomized strategy exactly in the same way as the mixed strategy 1/3 - 1/3 - 1/3 is optimal for Roshambo (rock-paper-scissors). B will be also playing a mixed strategy in response. The probabilities of different elements of X and Y are dictated by the number of matching sets, i.e. an elements x of X that has common slots with many Y's is going to have a higher probability in the mixed strategy than those that have common slots with only a few Y's. Calculating the stable mixed strategies (a Nash equilibrium for this game) is in theory straightforward and any basic reference on game theory can be consulted.
8,340,372
> > **Note:** this question is tagged both **language-agnostic** and **python** as my primary concern is finding out the algorithm to implement the solution to the problem, but information on how to implement it *efficiently* (=executing fast!) in python are a plus. > > > **Rules of the game:** * Imagine two teams one of *A agents* (`An`) and one of *B agents* (`Bn`). * In the game space there are a certain number of available *slots* (`Sn`) that can be occupied. * At each turn each agent is given a subset of slots he/she can occupy. * One agent can occupy *only one slot at at time*, however each slot can be occupied by two different agents, provided they are *each from a different team*. **The question:** I am trying to find an ***efficient* way to compute the best possible move** for `A` agents, where "best possible move" means either maximising or minimising the chances to occupy the same slots occupied by team `B`. The moves of team `B` are not known in advance. **Example scenario:** This scenario is deliberately trivial. It is just meant to illustrate the game mechanics. ``` A1 can occupy S1, S2 A2 can occupy S2, S3 B1 can occupy S1, S2 ``` In this case the solution is obvious: `A1 → S1` and `A2 → S2` is the option that will guarantee meeting with `B1` [as `B1` cannot avoid to occupy either `S1` or `S2`], while `A2 → S3` and `A1 → random(S1, S2)` is the one that will maximise the chances to avoid `B1`. **Real-life scenarios:** In real-life scenarios, the slots can be hundreds and the agents in each team various dozens. The difficulty in the naïve implementation I tried so far is that I basically consider every single possible set of moves for the team `B`, and score each of the possible alternative set of moves for `A`. So, my computation time increases exponentially. Still, I'm not sure this is a problem that can be solved only by "brute force". And even if this is the case I wonder: 1. If the optimal brute force solution necessarily grows exponentially (time-wise). 2. If there is a way to compute an non-optimal, locally-best solution. Thank you!
2011/12/01
[ "https://Stackoverflow.com/questions/8340372", "https://Stackoverflow.com", "https://Stackoverflow.com/users/146792/" ]
The members of the two teams and the slots define a tripartite graph `A-S-B`, with edges given by the possible moves. The bipartite subgraphs consisting of the slots and members of just one team are of interest; call these `A-S` for the graph with team A members and `S-B` for team B members. You can use the `S-B` graph to assign values to the slots, and then the `S-A` graph to select moves that maximize or minimize the value for team A. An appropriate choice for the value of a slot is the likelihood of finding a member of team B in that slot. With that, the value for a set of moves for team A is the sum of the slot values, i.e., the expected number of slots where a team B member will be found. Note that the moves of the members of a team are not independent, so both stages present some challenge. Given the values for the slots, choosing the moves for team A becomes a standard problem: the [assignment problem](http://en.wikipedia.org/wiki/Assignment_problem). This is related to the maximal bipartite matching suggested in missingno's answer, but the value of the slots needs to be accounted for; the edges can be given weight equal to the value of the slot on which the edge is incident, with a maximum weighted bipartite matching equivalent to the assignment problem. Use standard algorithms to solve (or approximate) this part of the problem. So how can we assign values to the slots? I'd suggest just generating random moves for the members of team B, counting how often the slots are occupied, and dividing the counts by the number of sample moves you consider. It's not really clear from the question how hard it will be to generate a random set of moves; assuming that each team member has the option to stay in place, it is easy to do just by randomly selecting moves for each member in random order. A simplifying factor in both stages is that there is an easy way to decompose the problem into independent sub-problems. The connected components of the bipartite graphs show which team members can move in a way that interferes with which others, e.g., if the team members are split into two groups on different parts of the board, the groups can be treated independently. This applies in both stages, both probabilistically evaluating the slots with the `S-B` graph and optimizing the assignment in the `A-S` graph. Of course, if any component is small enough, you could always enumerate the possibilities and solve the subproblem exactly.
This is not really a question of programming as much as it is a game theory question. What follows is a sketch of a game-theoretic analysis of the problem. We have a game of two players (A and B). A two-player game is always a zero-sum game, i.e. the gain of one player is loss for the other. Even if game payoffs are not zero-sum (i.e. there are results that give positive payoffs to both players), payoffs can be always normalized (taking their difference), so we can assume without loss of generality that the game here is also a zero-sum game. From this we deduce that if it is the goal of A to maximize [minimize] the number of meetings with agents of B, then it is the goal of B to minimize [maximize] the number of meetings with agents of A. Based on the description it is further assumed that A and B choose their moves simultaneously, i.e. A picks the slots for A's agents without knowing which slots B's agents are going to take and vice versa. Without this assumption, i.e. if B can see A's moves, it's very easy for B to "win". Let X be the set of all possible assignments of A's agents to the available slots (obeying the constraints for the current round or turn), i.e. X is a set of subsets of the slots; every subset denoting an assignment of agents to exactly those slots in the subset. Similarly, let Y be the set of all possible assignment of B's agents to the available slots (similarly obeying the constraints for B's agents). There are now four games. In each game A chooses an alement x of X and b chooses an element y of Y, after which: * In game I.a, A wins if x and y share a slot, otherwise B wins (in this game, A tries to force at least one meeting) * In game I.b, A receives a positive payoff equivalent to the number of common slots in x and y (in this game, A tries to maximize the number of meetings) * In game II.a, A wins if x and y do not share a slot, otherwise B wins (in this game, A tries to avoid any meetings) * In game II.b, A receives a negative payoff equivalent to the number of common slots in x and y (in this game, A tries to minimize the number of meetings) All these games can be analyzed using standard game-theoretic techniques. We focus on game I.a and leave the rest as an exercise to the reader. If there is an element y of Y available such that no x in X shares a slot with y, B chooses y and wins; so assume not, i.e. assume that every y in Y corresponds to at least one x in X such that x and y share a slot. A cannot play by any deterministic strategy, because B can counter it by choosing an y that does not share a slot with the deterministically chosen x; therefore A has to play by a mixed strategy, i.e. a randomized strategy exactly in the same way as the mixed strategy 1/3 - 1/3 - 1/3 is optimal for Roshambo (rock-paper-scissors). B will be also playing a mixed strategy in response. The probabilities of different elements of X and Y are dictated by the number of matching sets, i.e. an elements x of X that has common slots with many Y's is going to have a higher probability in the mixed strategy than those that have common slots with only a few Y's. Calculating the stable mixed strategies (a Nash equilibrium for this game) is in theory straightforward and any basic reference on game theory can be consulted.
8,340,372
> > **Note:** this question is tagged both **language-agnostic** and **python** as my primary concern is finding out the algorithm to implement the solution to the problem, but information on how to implement it *efficiently* (=executing fast!) in python are a plus. > > > **Rules of the game:** * Imagine two teams one of *A agents* (`An`) and one of *B agents* (`Bn`). * In the game space there are a certain number of available *slots* (`Sn`) that can be occupied. * At each turn each agent is given a subset of slots he/she can occupy. * One agent can occupy *only one slot at at time*, however each slot can be occupied by two different agents, provided they are *each from a different team*. **The question:** I am trying to find an ***efficient* way to compute the best possible move** for `A` agents, where "best possible move" means either maximising or minimising the chances to occupy the same slots occupied by team `B`. The moves of team `B` are not known in advance. **Example scenario:** This scenario is deliberately trivial. It is just meant to illustrate the game mechanics. ``` A1 can occupy S1, S2 A2 can occupy S2, S3 B1 can occupy S1, S2 ``` In this case the solution is obvious: `A1 → S1` and `A2 → S2` is the option that will guarantee meeting with `B1` [as `B1` cannot avoid to occupy either `S1` or `S2`], while `A2 → S3` and `A1 → random(S1, S2)` is the one that will maximise the chances to avoid `B1`. **Real-life scenarios:** In real-life scenarios, the slots can be hundreds and the agents in each team various dozens. The difficulty in the naïve implementation I tried so far is that I basically consider every single possible set of moves for the team `B`, and score each of the possible alternative set of moves for `A`. So, my computation time increases exponentially. Still, I'm not sure this is a problem that can be solved only by "brute force". And even if this is the case I wonder: 1. If the optimal brute force solution necessarily grows exponentially (time-wise). 2. If there is a way to compute an non-optimal, locally-best solution. Thank you!
2011/12/01
[ "https://Stackoverflow.com/questions/8340372", "https://Stackoverflow.com", "https://Stackoverflow.com/users/146792/" ]
This is a brute force solution, but perhaps less brute than the obvious one of enumerating all possibilities. As noted by the other solutions, this problem has to do with [matchings](http://en.wikipedia.org/wiki/Matching_%28graph_theory%29) on a [bipartite graph](http://en.wikipedia.org/wiki/Bipartite_graph). **Step 1: Compute the probability of each site being occupied by a *B* agent** Construct the following bipartite graph. The vertices are the *B* agents `B1,B2,...,BK` and the sites `S1,S2,...,SN`, and there is an edge between `Bi` and `Sj` if agent `Bi` can occupy site `Sj`. Find all maximal matchings (or maximum matchings if that's your algorithm for *B* agents) on this graph, say there are `M` of them. For each site `Si`, the probability of the site being occupied by a *B* agent is ``` Pi = #(matchings using Si) / M ``` *Algorithms to consider*: * [Hopcroft–Karp algorithm](http://en.wikipedia.org/wiki/Hopcroft-Karp_algorithm) **Step 2: Find the highest weight matching for *A* agents** Construct the following edge-weighted bipartite graph. The vertices are the *A* agents `A1,A2,...,AL` and the sites `S1,S2,...,SN`, and there is an edge between `Ai` and `Sj` if agent `Ai` can occupy site `Sj` and this edge has weight `Pi`. Find a maximum matching with maximal or minimal weight. *Algorithms to consider*: * [Bellman–Ford algorithm](http://en.wikipedia.org/wiki/Bellman-Ford_algorithm) * [Dijkstra's algorithm](http://en.wikipedia.org/wiki/Dijkstra_algorithm) * [Fibonacci heap](http://en.wikipedia.org/wiki/Fibonacci_heap) * [Hungarian algorithm](http://en.wikipedia.org/wiki/Hungarian_algorithm) Right now this is nothing more than a restatement of the problem, but perhaps thinking about it in this way will lead to a less brutish brute force approach. For example, once Step 1 is done, you can take a greedy algorithm to choose a play for *A* agents by including those `Si` with highest/lowest probability. Though finding matchings can be difficult, knowing whether or not one exists isn't. You can use [Hall's marriage theorem](http://en.wikipedia.org/wiki/Marriage_theorem) to determine whether a perfect matching exists once you choose the most/least likely `Si`s.
This is not really a question of programming as much as it is a game theory question. What follows is a sketch of a game-theoretic analysis of the problem. We have a game of two players (A and B). A two-player game is always a zero-sum game, i.e. the gain of one player is loss for the other. Even if game payoffs are not zero-sum (i.e. there are results that give positive payoffs to both players), payoffs can be always normalized (taking their difference), so we can assume without loss of generality that the game here is also a zero-sum game. From this we deduce that if it is the goal of A to maximize [minimize] the number of meetings with agents of B, then it is the goal of B to minimize [maximize] the number of meetings with agents of A. Based on the description it is further assumed that A and B choose their moves simultaneously, i.e. A picks the slots for A's agents without knowing which slots B's agents are going to take and vice versa. Without this assumption, i.e. if B can see A's moves, it's very easy for B to "win". Let X be the set of all possible assignments of A's agents to the available slots (obeying the constraints for the current round or turn), i.e. X is a set of subsets of the slots; every subset denoting an assignment of agents to exactly those slots in the subset. Similarly, let Y be the set of all possible assignment of B's agents to the available slots (similarly obeying the constraints for B's agents). There are now four games. In each game A chooses an alement x of X and b chooses an element y of Y, after which: * In game I.a, A wins if x and y share a slot, otherwise B wins (in this game, A tries to force at least one meeting) * In game I.b, A receives a positive payoff equivalent to the number of common slots in x and y (in this game, A tries to maximize the number of meetings) * In game II.a, A wins if x and y do not share a slot, otherwise B wins (in this game, A tries to avoid any meetings) * In game II.b, A receives a negative payoff equivalent to the number of common slots in x and y (in this game, A tries to minimize the number of meetings) All these games can be analyzed using standard game-theoretic techniques. We focus on game I.a and leave the rest as an exercise to the reader. If there is an element y of Y available such that no x in X shares a slot with y, B chooses y and wins; so assume not, i.e. assume that every y in Y corresponds to at least one x in X such that x and y share a slot. A cannot play by any deterministic strategy, because B can counter it by choosing an y that does not share a slot with the deterministically chosen x; therefore A has to play by a mixed strategy, i.e. a randomized strategy exactly in the same way as the mixed strategy 1/3 - 1/3 - 1/3 is optimal for Roshambo (rock-paper-scissors). B will be also playing a mixed strategy in response. The probabilities of different elements of X and Y are dictated by the number of matching sets, i.e. an elements x of X that has common slots with many Y's is going to have a higher probability in the mixed strategy than those that have common slots with only a few Y's. Calculating the stable mixed strategies (a Nash equilibrium for this game) is in theory straightforward and any basic reference on game theory can be consulted.
8,340,372
> > **Note:** this question is tagged both **language-agnostic** and **python** as my primary concern is finding out the algorithm to implement the solution to the problem, but information on how to implement it *efficiently* (=executing fast!) in python are a plus. > > > **Rules of the game:** * Imagine two teams one of *A agents* (`An`) and one of *B agents* (`Bn`). * In the game space there are a certain number of available *slots* (`Sn`) that can be occupied. * At each turn each agent is given a subset of slots he/she can occupy. * One agent can occupy *only one slot at at time*, however each slot can be occupied by two different agents, provided they are *each from a different team*. **The question:** I am trying to find an ***efficient* way to compute the best possible move** for `A` agents, where "best possible move" means either maximising or minimising the chances to occupy the same slots occupied by team `B`. The moves of team `B` are not known in advance. **Example scenario:** This scenario is deliberately trivial. It is just meant to illustrate the game mechanics. ``` A1 can occupy S1, S2 A2 can occupy S2, S3 B1 can occupy S1, S2 ``` In this case the solution is obvious: `A1 → S1` and `A2 → S2` is the option that will guarantee meeting with `B1` [as `B1` cannot avoid to occupy either `S1` or `S2`], while `A2 → S3` and `A1 → random(S1, S2)` is the one that will maximise the chances to avoid `B1`. **Real-life scenarios:** In real-life scenarios, the slots can be hundreds and the agents in each team various dozens. The difficulty in the naïve implementation I tried so far is that I basically consider every single possible set of moves for the team `B`, and score each of the possible alternative set of moves for `A`. So, my computation time increases exponentially. Still, I'm not sure this is a problem that can be solved only by "brute force". And even if this is the case I wonder: 1. If the optimal brute force solution necessarily grows exponentially (time-wise). 2. If there is a way to compute an non-optimal, locally-best solution. Thank you!
2011/12/01
[ "https://Stackoverflow.com/questions/8340372", "https://Stackoverflow.com", "https://Stackoverflow.com/users/146792/" ]
The members of the two teams and the slots define a tripartite graph `A-S-B`, with edges given by the possible moves. The bipartite subgraphs consisting of the slots and members of just one team are of interest; call these `A-S` for the graph with team A members and `S-B` for team B members. You can use the `S-B` graph to assign values to the slots, and then the `S-A` graph to select moves that maximize or minimize the value for team A. An appropriate choice for the value of a slot is the likelihood of finding a member of team B in that slot. With that, the value for a set of moves for team A is the sum of the slot values, i.e., the expected number of slots where a team B member will be found. Note that the moves of the members of a team are not independent, so both stages present some challenge. Given the values for the slots, choosing the moves for team A becomes a standard problem: the [assignment problem](http://en.wikipedia.org/wiki/Assignment_problem). This is related to the maximal bipartite matching suggested in missingno's answer, but the value of the slots needs to be accounted for; the edges can be given weight equal to the value of the slot on which the edge is incident, with a maximum weighted bipartite matching equivalent to the assignment problem. Use standard algorithms to solve (or approximate) this part of the problem. So how can we assign values to the slots? I'd suggest just generating random moves for the members of team B, counting how often the slots are occupied, and dividing the counts by the number of sample moves you consider. It's not really clear from the question how hard it will be to generate a random set of moves; assuming that each team member has the option to stay in place, it is easy to do just by randomly selecting moves for each member in random order. A simplifying factor in both stages is that there is an easy way to decompose the problem into independent sub-problems. The connected components of the bipartite graphs show which team members can move in a way that interferes with which others, e.g., if the team members are split into two groups on different parts of the board, the groups can be treated independently. This applies in both stages, both probabilistically evaluating the slots with the `S-B` graph and optimizing the assignment in the `A-S` graph. Of course, if any component is small enough, you could always enumerate the possibilities and solve the subproblem exactly.
If I understand correctly, the problem of finding an optimal strategy for A once you know the positions for B is the same as finding a [maximum matching](http://en.wikipedia.org/wiki/Matching_%28graph_theory%29) in a bipartite graph. The first set of vertices represent the A agents, the second set of vertices represent the slots ocupyed by the B agents and there is an edge if an agent can choose the occupy the slot. The problem is then finding the maximum number of edges you can ocupy without a vertex touching more then one edge. There are simple polynomial algorithms to solve this problem. One of the most classic is the one based on [augmenting paths](https://en.wikipedia.org/wiki/Maximum_flow_problem#Maximum_cardinality_bipartite_matching). ``` while you can find a path, augment the path a path is a sequence of vertices a1, b1, a2, b2, ... an, bn such that ai -> bi is an unmatched edge bi -> a(i+1) is a matched edge a1 and bn are unmatched to augment a path match all the unmatched edges (ai -> bi) unmatch all the matched edges (bi -> a(i+1)) (this results in one aditional matched edge after the iteration) ``` A naïve implementation of this algorithm is O(V\*E) but you can probably find more efficient python implementations of bipartite matching somewhere.
8,340,372
> > **Note:** this question is tagged both **language-agnostic** and **python** as my primary concern is finding out the algorithm to implement the solution to the problem, but information on how to implement it *efficiently* (=executing fast!) in python are a plus. > > > **Rules of the game:** * Imagine two teams one of *A agents* (`An`) and one of *B agents* (`Bn`). * In the game space there are a certain number of available *slots* (`Sn`) that can be occupied. * At each turn each agent is given a subset of slots he/she can occupy. * One agent can occupy *only one slot at at time*, however each slot can be occupied by two different agents, provided they are *each from a different team*. **The question:** I am trying to find an ***efficient* way to compute the best possible move** for `A` agents, where "best possible move" means either maximising or minimising the chances to occupy the same slots occupied by team `B`. The moves of team `B` are not known in advance. **Example scenario:** This scenario is deliberately trivial. It is just meant to illustrate the game mechanics. ``` A1 can occupy S1, S2 A2 can occupy S2, S3 B1 can occupy S1, S2 ``` In this case the solution is obvious: `A1 → S1` and `A2 → S2` is the option that will guarantee meeting with `B1` [as `B1` cannot avoid to occupy either `S1` or `S2`], while `A2 → S3` and `A1 → random(S1, S2)` is the one that will maximise the chances to avoid `B1`. **Real-life scenarios:** In real-life scenarios, the slots can be hundreds and the agents in each team various dozens. The difficulty in the naïve implementation I tried so far is that I basically consider every single possible set of moves for the team `B`, and score each of the possible alternative set of moves for `A`. So, my computation time increases exponentially. Still, I'm not sure this is a problem that can be solved only by "brute force". And even if this is the case I wonder: 1. If the optimal brute force solution necessarily grows exponentially (time-wise). 2. If there is a way to compute an non-optimal, locally-best solution. Thank you!
2011/12/01
[ "https://Stackoverflow.com/questions/8340372", "https://Stackoverflow.com", "https://Stackoverflow.com/users/146792/" ]
This is a brute force solution, but perhaps less brute than the obvious one of enumerating all possibilities. As noted by the other solutions, this problem has to do with [matchings](http://en.wikipedia.org/wiki/Matching_%28graph_theory%29) on a [bipartite graph](http://en.wikipedia.org/wiki/Bipartite_graph). **Step 1: Compute the probability of each site being occupied by a *B* agent** Construct the following bipartite graph. The vertices are the *B* agents `B1,B2,...,BK` and the sites `S1,S2,...,SN`, and there is an edge between `Bi` and `Sj` if agent `Bi` can occupy site `Sj`. Find all maximal matchings (or maximum matchings if that's your algorithm for *B* agents) on this graph, say there are `M` of them. For each site `Si`, the probability of the site being occupied by a *B* agent is ``` Pi = #(matchings using Si) / M ``` *Algorithms to consider*: * [Hopcroft–Karp algorithm](http://en.wikipedia.org/wiki/Hopcroft-Karp_algorithm) **Step 2: Find the highest weight matching for *A* agents** Construct the following edge-weighted bipartite graph. The vertices are the *A* agents `A1,A2,...,AL` and the sites `S1,S2,...,SN`, and there is an edge between `Ai` and `Sj` if agent `Ai` can occupy site `Sj` and this edge has weight `Pi`. Find a maximum matching with maximal or minimal weight. *Algorithms to consider*: * [Bellman–Ford algorithm](http://en.wikipedia.org/wiki/Bellman-Ford_algorithm) * [Dijkstra's algorithm](http://en.wikipedia.org/wiki/Dijkstra_algorithm) * [Fibonacci heap](http://en.wikipedia.org/wiki/Fibonacci_heap) * [Hungarian algorithm](http://en.wikipedia.org/wiki/Hungarian_algorithm) Right now this is nothing more than a restatement of the problem, but perhaps thinking about it in this way will lead to a less brutish brute force approach. For example, once Step 1 is done, you can take a greedy algorithm to choose a play for *A* agents by including those `Si` with highest/lowest probability. Though finding matchings can be difficult, knowing whether or not one exists isn't. You can use [Hall's marriage theorem](http://en.wikipedia.org/wiki/Marriage_theorem) to determine whether a perfect matching exists once you choose the most/least likely `Si`s.
If I understand correctly, the problem of finding an optimal strategy for A once you know the positions for B is the same as finding a [maximum matching](http://en.wikipedia.org/wiki/Matching_%28graph_theory%29) in a bipartite graph. The first set of vertices represent the A agents, the second set of vertices represent the slots ocupyed by the B agents and there is an edge if an agent can choose the occupy the slot. The problem is then finding the maximum number of edges you can ocupy without a vertex touching more then one edge. There are simple polynomial algorithms to solve this problem. One of the most classic is the one based on [augmenting paths](https://en.wikipedia.org/wiki/Maximum_flow_problem#Maximum_cardinality_bipartite_matching). ``` while you can find a path, augment the path a path is a sequence of vertices a1, b1, a2, b2, ... an, bn such that ai -> bi is an unmatched edge bi -> a(i+1) is a matched edge a1 and bn are unmatched to augment a path match all the unmatched edges (ai -> bi) unmatch all the matched edges (bi -> a(i+1)) (this results in one aditional matched edge after the iteration) ``` A naïve implementation of this algorithm is O(V\*E) but you can probably find more efficient python implementations of bipartite matching somewhere.
8,340,372
> > **Note:** this question is tagged both **language-agnostic** and **python** as my primary concern is finding out the algorithm to implement the solution to the problem, but information on how to implement it *efficiently* (=executing fast!) in python are a plus. > > > **Rules of the game:** * Imagine two teams one of *A agents* (`An`) and one of *B agents* (`Bn`). * In the game space there are a certain number of available *slots* (`Sn`) that can be occupied. * At each turn each agent is given a subset of slots he/she can occupy. * One agent can occupy *only one slot at at time*, however each slot can be occupied by two different agents, provided they are *each from a different team*. **The question:** I am trying to find an ***efficient* way to compute the best possible move** for `A` agents, where "best possible move" means either maximising or minimising the chances to occupy the same slots occupied by team `B`. The moves of team `B` are not known in advance. **Example scenario:** This scenario is deliberately trivial. It is just meant to illustrate the game mechanics. ``` A1 can occupy S1, S2 A2 can occupy S2, S3 B1 can occupy S1, S2 ``` In this case the solution is obvious: `A1 → S1` and `A2 → S2` is the option that will guarantee meeting with `B1` [as `B1` cannot avoid to occupy either `S1` or `S2`], while `A2 → S3` and `A1 → random(S1, S2)` is the one that will maximise the chances to avoid `B1`. **Real-life scenarios:** In real-life scenarios, the slots can be hundreds and the agents in each team various dozens. The difficulty in the naïve implementation I tried so far is that I basically consider every single possible set of moves for the team `B`, and score each of the possible alternative set of moves for `A`. So, my computation time increases exponentially. Still, I'm not sure this is a problem that can be solved only by "brute force". And even if this is the case I wonder: 1. If the optimal brute force solution necessarily grows exponentially (time-wise). 2. If there is a way to compute an non-optimal, locally-best solution. Thank you!
2011/12/01
[ "https://Stackoverflow.com/questions/8340372", "https://Stackoverflow.com", "https://Stackoverflow.com/users/146792/" ]
The members of the two teams and the slots define a tripartite graph `A-S-B`, with edges given by the possible moves. The bipartite subgraphs consisting of the slots and members of just one team are of interest; call these `A-S` for the graph with team A members and `S-B` for team B members. You can use the `S-B` graph to assign values to the slots, and then the `S-A` graph to select moves that maximize or minimize the value for team A. An appropriate choice for the value of a slot is the likelihood of finding a member of team B in that slot. With that, the value for a set of moves for team A is the sum of the slot values, i.e., the expected number of slots where a team B member will be found. Note that the moves of the members of a team are not independent, so both stages present some challenge. Given the values for the slots, choosing the moves for team A becomes a standard problem: the [assignment problem](http://en.wikipedia.org/wiki/Assignment_problem). This is related to the maximal bipartite matching suggested in missingno's answer, but the value of the slots needs to be accounted for; the edges can be given weight equal to the value of the slot on which the edge is incident, with a maximum weighted bipartite matching equivalent to the assignment problem. Use standard algorithms to solve (or approximate) this part of the problem. So how can we assign values to the slots? I'd suggest just generating random moves for the members of team B, counting how often the slots are occupied, and dividing the counts by the number of sample moves you consider. It's not really clear from the question how hard it will be to generate a random set of moves; assuming that each team member has the option to stay in place, it is easy to do just by randomly selecting moves for each member in random order. A simplifying factor in both stages is that there is an easy way to decompose the problem into independent sub-problems. The connected components of the bipartite graphs show which team members can move in a way that interferes with which others, e.g., if the team members are split into two groups on different parts of the board, the groups can be treated independently. This applies in both stages, both probabilistically evaluating the slots with the `S-B` graph and optimizing the assignment in the `A-S` graph. Of course, if any component is small enough, you could always enumerate the possibilities and solve the subproblem exactly.
This is a brute force solution, but perhaps less brute than the obvious one of enumerating all possibilities. As noted by the other solutions, this problem has to do with [matchings](http://en.wikipedia.org/wiki/Matching_%28graph_theory%29) on a [bipartite graph](http://en.wikipedia.org/wiki/Bipartite_graph). **Step 1: Compute the probability of each site being occupied by a *B* agent** Construct the following bipartite graph. The vertices are the *B* agents `B1,B2,...,BK` and the sites `S1,S2,...,SN`, and there is an edge between `Bi` and `Sj` if agent `Bi` can occupy site `Sj`. Find all maximal matchings (or maximum matchings if that's your algorithm for *B* agents) on this graph, say there are `M` of them. For each site `Si`, the probability of the site being occupied by a *B* agent is ``` Pi = #(matchings using Si) / M ``` *Algorithms to consider*: * [Hopcroft–Karp algorithm](http://en.wikipedia.org/wiki/Hopcroft-Karp_algorithm) **Step 2: Find the highest weight matching for *A* agents** Construct the following edge-weighted bipartite graph. The vertices are the *A* agents `A1,A2,...,AL` and the sites `S1,S2,...,SN`, and there is an edge between `Ai` and `Sj` if agent `Ai` can occupy site `Sj` and this edge has weight `Pi`. Find a maximum matching with maximal or minimal weight. *Algorithms to consider*: * [Bellman–Ford algorithm](http://en.wikipedia.org/wiki/Bellman-Ford_algorithm) * [Dijkstra's algorithm](http://en.wikipedia.org/wiki/Dijkstra_algorithm) * [Fibonacci heap](http://en.wikipedia.org/wiki/Fibonacci_heap) * [Hungarian algorithm](http://en.wikipedia.org/wiki/Hungarian_algorithm) Right now this is nothing more than a restatement of the problem, but perhaps thinking about it in this way will lead to a less brutish brute force approach. For example, once Step 1 is done, you can take a greedy algorithm to choose a play for *A* agents by including those `Si` with highest/lowest probability. Though finding matchings can be difficult, knowing whether or not one exists isn't. You can use [Hall's marriage theorem](http://en.wikipedia.org/wiki/Marriage_theorem) to determine whether a perfect matching exists once you choose the most/least likely `Si`s.
53,557,240
I have an input, which is a word. if my input contains `python`, print `True`. if not, print `False`. for example: if the input is `puytrmhqoln` print `True`(because it contains python's letter, however, there is some letter between `python`) if the input is `pythno` print `False` (because in types o after n)
2018/11/30
[ "https://Stackoverflow.com/questions/53557240", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10688308/" ]
I found the answer. ``` import sys inputs = sys.stdin.readline().strip() word = "python" for i in range(len(inputs)): if word == "": break if inputs[i] == word[0]: word = word[1:] if word == "": print("YES") else: print("NO") ``` it works for words like `hello` with double letter, also `python`
Iterate over each character of your string. And see whether the current character is identical to the currently next one in your string you are looking for: ``` strg = "pythrno" lookfor = "python" longest_substr = "" index = 0 max_index = len(lookfor) for c in strg: if c == lookfor[index] and index < max_index: longest_substr += c index += 1 print(longest_substr) ``` will give you ``` pytho ``` You now can simply compare `longest_substr` and `lookfor` and wrap this in a dedicated function.
53,557,240
I have an input, which is a word. if my input contains `python`, print `True`. if not, print `False`. for example: if the input is `puytrmhqoln` print `True`(because it contains python's letter, however, there is some letter between `python`) if the input is `pythno` print `False` (because in types o after n)
2018/11/30
[ "https://Stackoverflow.com/questions/53557240", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10688308/" ]
I found the answer. ``` import sys inputs = sys.stdin.readline().strip() word = "python" for i in range(len(inputs)): if word == "": break if inputs[i] == word[0]: word = word[1:] if word == "": print("YES") else: print("NO") ``` it works for words like `hello` with double letter, also `python`
I hope this code will be useful: Variant 1 (looks for the whole word): ``` s_word = 'python' def check(word): filtered_word = "".join(filter(lambda x: x in tuple(s_word), tuple(word))) return filtered_word == s_word print(check('puytrmhqoln')) # returns True print(check('pythno')) # returns False ``` Variant 2 (seeking character by character, validates the order of the characters): ``` s_word = 'python' def check(word): for i in s_word: pre_sym = s_word[s_word.index(i) - 1] if s_word.index(i) > 0 else i if word.index(i) < word.index(pre_sym): return False return True print(check('pyttthorne')) # returns True print(check('puytrmhqoln')) # returns True print(check('pythno')) # returns False ``` Variant 3 (seeking character by character): ``` def check(word): w_slice = word for c in s_word: if w_slice.find(c) < 0: return False w_slice = word[word.index(c) + 1:] return True s_word = 'hello' print(check('helo')) # returns False print(check('helolo')) # returns True s_word = 'python' print(check('pyttthorne')) # returns True print(check('puytrmhqoln')) # returns True print(check('pythno')) # returns False ``` Variant 4 (with regexp): ``` import re s_word = _REFERENCE_WORD_ # convert the reference word to a regular expression re_expr = re.compile(r'.*%s{1}.*' % '{1}.*'.join(s_word)) ``` Usage: ``` print(True if re_expr.match(_ENTERED_WORD_) else False) ``` Example for 'hello': ``` s_word = 'hello' re_expr = re.compile(r'.*%s{1}.*' % '{1}.*'.join(s_word)) for w in ('helo', 'helolo', 'hlelo', 'ahhellllloou'): print(f'{s_word} in {w} -> {True if re_expr.match(w) else False}') # returns: # hello in helo -> False # hello in helolo -> True # hello in hlelo -> False # hello in ahhellllloou -> True ``` Example for 'python': ``` s_word = 'python' re_expr = re.compile(r'.*%s{1}.*' % '{1}.*'.join(s_word)) for w in ('pyttthorne', 'puytrmhqoln', 'pythno'): print(f'{s_word} in {w} -> {True if re_expr.match(w) else False}') # returns: # python in pyttthorne -> True # python in puytrmhqoln -> True # python in pythno -> False ```
52,911,232
I'm trying to install and import the Basemap library into my Jupyter Notebook, but this returns the following error: ``` KeyError: 'PROJ_LIB' ``` After some research online, I understand I'm to install Basemap on a separate environment in Anaconda. After creating a new environment and installing Basemap (as well as all other relevant libraries), I have activated the environment. But when importing Basemap I still receive the same KeyError. Here's what I did in my MacOS terminal: ``` conda create --name Py3.6 python=3.6 basemap source activate Py3.6 conda upgrade proj4 env | grep -i proj conda update --channel conda-forge proj4 ``` Then in Jupyter Notebook I run the following: ``` from mpl_toolkits.basemap import Basemap ``` Can anyone tell me why this results in a KeyError?
2018/10/21
[ "https://Stackoverflow.com/questions/52911232", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10534668/" ]
Need to set the PROJ\_LIB environment variable either before starting your notebook or in python with `os.environ['PROJ_LIB'] = '<path_to_anaconda>/share/proj'` Ref. [Basemap import error in PyCharm —— KeyError: 'PROJ\_LIB'](https://stackoverflow.com/questions/52295117/basemap-import-error-in-pycharm-keyerror-proj-lib)
The problem occurs as the file location of "epsg" and PROJ\_LIB has been changed for recent versions of python, but somehow they forgot to update the **init**.py for Basemap. If you have installed python using anaconda, this is a possible location for your espg file: `C:\Users\(xxxx)\AppData\Local\Continuum\anaconda3\pkgs\proj4-5.1.0-hfa6e2cd_1\Library\share` So you have to add this path at the start of your code in spyder or whatever field you are using. ```py import os os.environ['PROJ_LIB'] = r'C:\Users\(xxxx)\AppData\Local\Continuum\anaconda3\pkgs\proj4-5.1.0-hfa6e2cd_1\Library\share' from mpl_toolkits.basemap import Basemap ```
52,911,232
I'm trying to install and import the Basemap library into my Jupyter Notebook, but this returns the following error: ``` KeyError: 'PROJ_LIB' ``` After some research online, I understand I'm to install Basemap on a separate environment in Anaconda. After creating a new environment and installing Basemap (as well as all other relevant libraries), I have activated the environment. But when importing Basemap I still receive the same KeyError. Here's what I did in my MacOS terminal: ``` conda create --name Py3.6 python=3.6 basemap source activate Py3.6 conda upgrade proj4 env | grep -i proj conda update --channel conda-forge proj4 ``` Then in Jupyter Notebook I run the following: ``` from mpl_toolkits.basemap import Basemap ``` Can anyone tell me why this results in a KeyError?
2018/10/21
[ "https://Stackoverflow.com/questions/52911232", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10534668/" ]
Need to set the PROJ\_LIB environment variable either before starting your notebook or in python with `os.environ['PROJ_LIB'] = '<path_to_anaconda>/share/proj'` Ref. [Basemap import error in PyCharm —— KeyError: 'PROJ\_LIB'](https://stackoverflow.com/questions/52295117/basemap-import-error-in-pycharm-keyerror-proj-lib)
Launch Jupyter Notebook from command prompt and it won't throw the same error. It somehow works for me!
52,911,232
I'm trying to install and import the Basemap library into my Jupyter Notebook, but this returns the following error: ``` KeyError: 'PROJ_LIB' ``` After some research online, I understand I'm to install Basemap on a separate environment in Anaconda. After creating a new environment and installing Basemap (as well as all other relevant libraries), I have activated the environment. But when importing Basemap I still receive the same KeyError. Here's what I did in my MacOS terminal: ``` conda create --name Py3.6 python=3.6 basemap source activate Py3.6 conda upgrade proj4 env | grep -i proj conda update --channel conda-forge proj4 ``` Then in Jupyter Notebook I run the following: ``` from mpl_toolkits.basemap import Basemap ``` Can anyone tell me why this results in a KeyError?
2018/10/21
[ "https://Stackoverflow.com/questions/52911232", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10534668/" ]
Need to set the PROJ\_LIB environment variable either before starting your notebook or in python with `os.environ['PROJ_LIB'] = '<path_to_anaconda>/share/proj'` Ref. [Basemap import error in PyCharm —— KeyError: 'PROJ\_LIB'](https://stackoverflow.com/questions/52295117/basemap-import-error-in-pycharm-keyerror-proj-lib)
If you **can not locate epsg file** at all, you can download it here: <https://raw.githubusercontent.com/matplotlib/basemap/master/lib/mpl_toolkits/basemap/data/epsg> And copy this file to your PATH, e.g. to: os.environ['PROJ\_LIB'] = 'C:\Users\username\Anaconda3\pkgs\basemap-1.2.0-py37h4e5d7af\_0\Lib\site-packages\mpl\_toolkits\basemap\data\' This is the ONLY solution that worked for me on Windows 10 / Anaconda 3.
52,911,232
I'm trying to install and import the Basemap library into my Jupyter Notebook, but this returns the following error: ``` KeyError: 'PROJ_LIB' ``` After some research online, I understand I'm to install Basemap on a separate environment in Anaconda. After creating a new environment and installing Basemap (as well as all other relevant libraries), I have activated the environment. But when importing Basemap I still receive the same KeyError. Here's what I did in my MacOS terminal: ``` conda create --name Py3.6 python=3.6 basemap source activate Py3.6 conda upgrade proj4 env | grep -i proj conda update --channel conda-forge proj4 ``` Then in Jupyter Notebook I run the following: ``` from mpl_toolkits.basemap import Basemap ``` Can anyone tell me why this results in a KeyError?
2018/10/21
[ "https://Stackoverflow.com/questions/52911232", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10534668/" ]
The problem occurs as the file location of "epsg" and PROJ\_LIB has been changed for recent versions of python, but somehow they forgot to update the **init**.py for Basemap. If you have installed python using anaconda, this is a possible location for your espg file: `C:\Users\(xxxx)\AppData\Local\Continuum\anaconda3\pkgs\proj4-5.1.0-hfa6e2cd_1\Library\share` So you have to add this path at the start of your code in spyder or whatever field you are using. ```py import os os.environ['PROJ_LIB'] = r'C:\Users\(xxxx)\AppData\Local\Continuum\anaconda3\pkgs\proj4-5.1.0-hfa6e2cd_1\Library\share' from mpl_toolkits.basemap import Basemap ```
Launch Jupyter Notebook from command prompt and it won't throw the same error. It somehow works for me!
52,911,232
I'm trying to install and import the Basemap library into my Jupyter Notebook, but this returns the following error: ``` KeyError: 'PROJ_LIB' ``` After some research online, I understand I'm to install Basemap on a separate environment in Anaconda. After creating a new environment and installing Basemap (as well as all other relevant libraries), I have activated the environment. But when importing Basemap I still receive the same KeyError. Here's what I did in my MacOS terminal: ``` conda create --name Py3.6 python=3.6 basemap source activate Py3.6 conda upgrade proj4 env | grep -i proj conda update --channel conda-forge proj4 ``` Then in Jupyter Notebook I run the following: ``` from mpl_toolkits.basemap import Basemap ``` Can anyone tell me why this results in a KeyError?
2018/10/21
[ "https://Stackoverflow.com/questions/52911232", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10534668/" ]
In Windows 10 command line: first find the directory where the **epsg** file is stored: ``` where /r "c:\Users\username" epsg.* ``` ... **c:\Users\username\AppData\Local\conda\conda\envs\envname\Library\share**\epsg ... then either in command line: ``` activate envname SET PROJ_LIB=c:\Users\username\AppData\Local\conda\conda\envs\envname\Library\share ``` (make sure there are no leading on trailing spaces in the path!) and then ``` jupyter notebook ``` or add this to your jupyter notebook (as suggested by john ed): ``` import os os.environ['PROJ_LIB'] = r'c:\Users\username\AppData\Local\conda\conda\envs\envname\Library\share' ```
The problem occurs as the file location of "epsg" and PROJ\_LIB has been changed for recent versions of python, but somehow they forgot to update the **init**.py for Basemap. If you have installed python using anaconda, this is a possible location for your espg file: `C:\Users\(xxxx)\AppData\Local\Continuum\anaconda3\pkgs\proj4-5.1.0-hfa6e2cd_1\Library\share` So you have to add this path at the start of your code in spyder or whatever field you are using. ```py import os os.environ['PROJ_LIB'] = r'C:\Users\(xxxx)\AppData\Local\Continuum\anaconda3\pkgs\proj4-5.1.0-hfa6e2cd_1\Library\share' from mpl_toolkits.basemap import Basemap ```
52,911,232
I'm trying to install and import the Basemap library into my Jupyter Notebook, but this returns the following error: ``` KeyError: 'PROJ_LIB' ``` After some research online, I understand I'm to install Basemap on a separate environment in Anaconda. After creating a new environment and installing Basemap (as well as all other relevant libraries), I have activated the environment. But when importing Basemap I still receive the same KeyError. Here's what I did in my MacOS terminal: ``` conda create --name Py3.6 python=3.6 basemap source activate Py3.6 conda upgrade proj4 env | grep -i proj conda update --channel conda-forge proj4 ``` Then in Jupyter Notebook I run the following: ``` from mpl_toolkits.basemap import Basemap ``` Can anyone tell me why this results in a KeyError?
2018/10/21
[ "https://Stackoverflow.com/questions/52911232", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10534668/" ]
The problem occurs as the file location of "epsg" and PROJ\_LIB has been changed for recent versions of python, but somehow they forgot to update the **init**.py for Basemap. If you have installed python using anaconda, this is a possible location for your espg file: `C:\Users\(xxxx)\AppData\Local\Continuum\anaconda3\pkgs\proj4-5.1.0-hfa6e2cd_1\Library\share` So you have to add this path at the start of your code in spyder or whatever field you are using. ```py import os os.environ['PROJ_LIB'] = r'C:\Users\(xxxx)\AppData\Local\Continuum\anaconda3\pkgs\proj4-5.1.0-hfa6e2cd_1\Library\share' from mpl_toolkits.basemap import Basemap ```
If you **can not locate epsg file** at all, you can download it here: <https://raw.githubusercontent.com/matplotlib/basemap/master/lib/mpl_toolkits/basemap/data/epsg> And copy this file to your PATH, e.g. to: os.environ['PROJ\_LIB'] = 'C:\Users\username\Anaconda3\pkgs\basemap-1.2.0-py37h4e5d7af\_0\Lib\site-packages\mpl\_toolkits\basemap\data\' This is the ONLY solution that worked for me on Windows 10 / Anaconda 3.
52,911,232
I'm trying to install and import the Basemap library into my Jupyter Notebook, but this returns the following error: ``` KeyError: 'PROJ_LIB' ``` After some research online, I understand I'm to install Basemap on a separate environment in Anaconda. After creating a new environment and installing Basemap (as well as all other relevant libraries), I have activated the environment. But when importing Basemap I still receive the same KeyError. Here's what I did in my MacOS terminal: ``` conda create --name Py3.6 python=3.6 basemap source activate Py3.6 conda upgrade proj4 env | grep -i proj conda update --channel conda-forge proj4 ``` Then in Jupyter Notebook I run the following: ``` from mpl_toolkits.basemap import Basemap ``` Can anyone tell me why this results in a KeyError?
2018/10/21
[ "https://Stackoverflow.com/questions/52911232", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10534668/" ]
In Windows 10 command line: first find the directory where the **epsg** file is stored: ``` where /r "c:\Users\username" epsg.* ``` ... **c:\Users\username\AppData\Local\conda\conda\envs\envname\Library\share**\epsg ... then either in command line: ``` activate envname SET PROJ_LIB=c:\Users\username\AppData\Local\conda\conda\envs\envname\Library\share ``` (make sure there are no leading on trailing spaces in the path!) and then ``` jupyter notebook ``` or add this to your jupyter notebook (as suggested by john ed): ``` import os os.environ['PROJ_LIB'] = r'c:\Users\username\AppData\Local\conda\conda\envs\envname\Library\share' ```
Launch Jupyter Notebook from command prompt and it won't throw the same error. It somehow works for me!
52,911,232
I'm trying to install and import the Basemap library into my Jupyter Notebook, but this returns the following error: ``` KeyError: 'PROJ_LIB' ``` After some research online, I understand I'm to install Basemap on a separate environment in Anaconda. After creating a new environment and installing Basemap (as well as all other relevant libraries), I have activated the environment. But when importing Basemap I still receive the same KeyError. Here's what I did in my MacOS terminal: ``` conda create --name Py3.6 python=3.6 basemap source activate Py3.6 conda upgrade proj4 env | grep -i proj conda update --channel conda-forge proj4 ``` Then in Jupyter Notebook I run the following: ``` from mpl_toolkits.basemap import Basemap ``` Can anyone tell me why this results in a KeyError?
2018/10/21
[ "https://Stackoverflow.com/questions/52911232", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10534668/" ]
If you **can not locate epsg file** at all, you can download it here: <https://raw.githubusercontent.com/matplotlib/basemap/master/lib/mpl_toolkits/basemap/data/epsg> And copy this file to your PATH, e.g. to: os.environ['PROJ\_LIB'] = 'C:\Users\username\Anaconda3\pkgs\basemap-1.2.0-py37h4e5d7af\_0\Lib\site-packages\mpl\_toolkits\basemap\data\' This is the ONLY solution that worked for me on Windows 10 / Anaconda 3.
Launch Jupyter Notebook from command prompt and it won't throw the same error. It somehow works for me!