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
53,327,240
I have been trying to find a way to get python to ready my `csv`. Take the values that are in the date columns (`3months | 6months | 12months`) and plot it onto a graph however I have been struggling to find resources and have no previous experience with python. If anyone could point me in the right direction it would be much appreciated. I have already been able to get python to read a simple csv with little values in however **I cannot figure out a way to show a line for each of these shares over the look back dates**. Here is my csv format. ``` ticker, 3months, 6months, 12months appl, -12, 16, 24 tsla, 9, 10, 7 amzn, -7, 14, 36 ``` I am trying to read the csv and output it into a graph like this. ![Image](https://i.stack.imgur.com/JtsmT.png)
2018/11/15
[ "https://Stackoverflow.com/questions/53327240", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10471828/" ]
The pattern `(?!\S)` uses a negative lookahead to check what follows is not a non whitespace character. What you could so is replace the `(?!\S)` with a word boundary `\b` to let it not be part of a larger match: `(?i)(?<!\S)lending\s?qb\b` [Regex demo](https://regex101.com/r/nyHoT5/1) Another way could be to use a positive lookahead to check for a whitespace character or `.,` or the end of the string using [`(?=[\s,.]|$)`](https://regex101.com/r/nyHoT5/1/) For example: ``` str5 ="The best product is Lending qb." print(re.findall(r'(?<!\S)lending\s?qb(?=[\s,.]|$)', str5, re.IGNORECASE)) # ['Lending qb'] ```
This `(?!\S)` is a forward whitespace boundary. It is really this `(?![^\s])` a negative of a negative with the added benefit of it matching at the EOS (end of string). What that means is you can use the negative class form to add characters that qualify as a boundary. So, just put the period and comma in with the whitespace. `(?i)(?<![^\s,.])lending\s?qb(?![^\s,.])` <https://regex101.com/r/BrOj2J/1> As a tutorial point, this concept encapsulates multiple assertions and is basic engine Boolean class logic which speeds up the engine by a ten fold factor by comparison.
53,327,240
I have been trying to find a way to get python to ready my `csv`. Take the values that are in the date columns (`3months | 6months | 12months`) and plot it onto a graph however I have been struggling to find resources and have no previous experience with python. If anyone could point me in the right direction it would be much appreciated. I have already been able to get python to read a simple csv with little values in however **I cannot figure out a way to show a line for each of these shares over the look back dates**. Here is my csv format. ``` ticker, 3months, 6months, 12months appl, -12, 16, 24 tsla, 9, 10, 7 amzn, -7, 14, 36 ``` I am trying to read the csv and output it into a graph like this. ![Image](https://i.stack.imgur.com/JtsmT.png)
2018/11/15
[ "https://Stackoverflow.com/questions/53327240", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10471828/" ]
The pattern `(?!\S)` uses a negative lookahead to check what follows is not a non whitespace character. What you could so is replace the `(?!\S)` with a word boundary `\b` to let it not be part of a larger match: `(?i)(?<!\S)lending\s?qb\b` [Regex demo](https://regex101.com/r/nyHoT5/1) Another way could be to use a positive lookahead to check for a whitespace character or `.,` or the end of the string using [`(?=[\s,.]|$)`](https://regex101.com/r/nyHoT5/1/) For example: ``` str5 ="The best product is Lending qb." print(re.findall(r'(?<!\S)lending\s?qb(?=[\s,.]|$)', str5, re.IGNORECASE)) # ['Lending qb'] ```
You have correctly identified one issue in the regex (punctuation immediately after QB), but there is a second edge case to consider given that the input is messy -- what if there are multiple spaces in `Lending QB`?. I believe the most robust solution to your problem is: ``` (?i)(?<!\S)lending\s*qb\b ``` * `\b` enforces that `QB` occur at the end of a word, automatically considering punctuation. * `\s?` was replaced with `\s*` to allow any amount of whitespace to be a match, rather than just zero-to-one whitespaces. PS. Another point to consider is that `\b` terminates on all punctuation, `(?=\s|[,.])` will only terminate on the given punctuation: `,` or `.` in this case. Given the wide range of possible punctuation (colon, semicolon, dash, hyphen, emdash...) I would strongly recommend `\b` over `(?=\s|[,.])`. Unless you want precise control over allowable terminating punctuation of course... PPS. further test cases to illustrate my points ``` str6 ='Lending Qb: simply the best' str7 ='I'm a fan of lending QB' ```
53,327,240
I have been trying to find a way to get python to ready my `csv`. Take the values that are in the date columns (`3months | 6months | 12months`) and plot it onto a graph however I have been struggling to find resources and have no previous experience with python. If anyone could point me in the right direction it would be much appreciated. I have already been able to get python to read a simple csv with little values in however **I cannot figure out a way to show a line for each of these shares over the look back dates**. Here is my csv format. ``` ticker, 3months, 6months, 12months appl, -12, 16, 24 tsla, 9, 10, 7 amzn, -7, 14, 36 ``` I am trying to read the csv and output it into a graph like this. ![Image](https://i.stack.imgur.com/JtsmT.png)
2018/11/15
[ "https://Stackoverflow.com/questions/53327240", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10471828/" ]
The pattern `(?!\S)` uses a negative lookahead to check what follows is not a non whitespace character. What you could so is replace the `(?!\S)` with a word boundary `\b` to let it not be part of a larger match: `(?i)(?<!\S)lending\s?qb\b` [Regex demo](https://regex101.com/r/nyHoT5/1) Another way could be to use a positive lookahead to check for a whitespace character or `.,` or the end of the string using [`(?=[\s,.]|$)`](https://regex101.com/r/nyHoT5/1/) For example: ``` str5 ="The best product is Lending qb." print(re.findall(r'(?<!\S)lending\s?qb(?=[\s,.]|$)', str5, re.IGNORECASE)) # ['Lending qb'] ```
Thank you "The fourth bird", "sln", and "Mark\_Anderson". Your answers provided solutions and also were very educational. I went with Mark's answer since it seemed to be the most robust, which is where I'm trying to get to. Ideally, I do want to capture all cases when the product name is mentioned, no matter how messy it's typed. I changed my code to this: ``` df['lendingQB'] = df['Text'].str.findall(r'(?i)(?<!\S)lending\s*qb\b', re.IGNORECASE) ```
53,327,240
I have been trying to find a way to get python to ready my `csv`. Take the values that are in the date columns (`3months | 6months | 12months`) and plot it onto a graph however I have been struggling to find resources and have no previous experience with python. If anyone could point me in the right direction it would be much appreciated. I have already been able to get python to read a simple csv with little values in however **I cannot figure out a way to show a line for each of these shares over the look back dates**. Here is my csv format. ``` ticker, 3months, 6months, 12months appl, -12, 16, 24 tsla, 9, 10, 7 amzn, -7, 14, 36 ``` I am trying to read the csv and output it into a graph like this. ![Image](https://i.stack.imgur.com/JtsmT.png)
2018/11/15
[ "https://Stackoverflow.com/questions/53327240", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10471828/" ]
You have correctly identified one issue in the regex (punctuation immediately after QB), but there is a second edge case to consider given that the input is messy -- what if there are multiple spaces in `Lending QB`?. I believe the most robust solution to your problem is: ``` (?i)(?<!\S)lending\s*qb\b ``` * `\b` enforces that `QB` occur at the end of a word, automatically considering punctuation. * `\s?` was replaced with `\s*` to allow any amount of whitespace to be a match, rather than just zero-to-one whitespaces. PS. Another point to consider is that `\b` terminates on all punctuation, `(?=\s|[,.])` will only terminate on the given punctuation: `,` or `.` in this case. Given the wide range of possible punctuation (colon, semicolon, dash, hyphen, emdash...) I would strongly recommend `\b` over `(?=\s|[,.])`. Unless you want precise control over allowable terminating punctuation of course... PPS. further test cases to illustrate my points ``` str6 ='Lending Qb: simply the best' str7 ='I'm a fan of lending QB' ```
This `(?!\S)` is a forward whitespace boundary. It is really this `(?![^\s])` a negative of a negative with the added benefit of it matching at the EOS (end of string). What that means is you can use the negative class form to add characters that qualify as a boundary. So, just put the period and comma in with the whitespace. `(?i)(?<![^\s,.])lending\s?qb(?![^\s,.])` <https://regex101.com/r/BrOj2J/1> As a tutorial point, this concept encapsulates multiple assertions and is basic engine Boolean class logic which speeds up the engine by a ten fold factor by comparison.
53,327,240
I have been trying to find a way to get python to ready my `csv`. Take the values that are in the date columns (`3months | 6months | 12months`) and plot it onto a graph however I have been struggling to find resources and have no previous experience with python. If anyone could point me in the right direction it would be much appreciated. I have already been able to get python to read a simple csv with little values in however **I cannot figure out a way to show a line for each of these shares over the look back dates**. Here is my csv format. ``` ticker, 3months, 6months, 12months appl, -12, 16, 24 tsla, 9, 10, 7 amzn, -7, 14, 36 ``` I am trying to read the csv and output it into a graph like this. ![Image](https://i.stack.imgur.com/JtsmT.png)
2018/11/15
[ "https://Stackoverflow.com/questions/53327240", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10471828/" ]
You have correctly identified one issue in the regex (punctuation immediately after QB), but there is a second edge case to consider given that the input is messy -- what if there are multiple spaces in `Lending QB`?. I believe the most robust solution to your problem is: ``` (?i)(?<!\S)lending\s*qb\b ``` * `\b` enforces that `QB` occur at the end of a word, automatically considering punctuation. * `\s?` was replaced with `\s*` to allow any amount of whitespace to be a match, rather than just zero-to-one whitespaces. PS. Another point to consider is that `\b` terminates on all punctuation, `(?=\s|[,.])` will only terminate on the given punctuation: `,` or `.` in this case. Given the wide range of possible punctuation (colon, semicolon, dash, hyphen, emdash...) I would strongly recommend `\b` over `(?=\s|[,.])`. Unless you want precise control over allowable terminating punctuation of course... PPS. further test cases to illustrate my points ``` str6 ='Lending Qb: simply the best' str7 ='I'm a fan of lending QB' ```
Thank you "The fourth bird", "sln", and "Mark\_Anderson". Your answers provided solutions and also were very educational. I went with Mark's answer since it seemed to be the most robust, which is where I'm trying to get to. Ideally, I do want to capture all cases when the product name is mentioned, no matter how messy it's typed. I changed my code to this: ``` df['lendingQB'] = df['Text'].str.findall(r'(?i)(?<!\S)lending\s*qb\b', re.IGNORECASE) ```
42,358,433
I have a simple Python test code as under: **tmp.py** ``` import time while True: print "New val" time.sleep(1) ``` If I run it as below, I see the logs on terminal normally: ``` python tmp.py ``` But if I redirect the logs to a log file, it takes quite a while before the logs appear in the file: ``` python tmp.py >/tmp/logs.log 2>&1 ``` If I do a `cat /tmp/logs.log`, the output appears in that file quite late, or only when I quit the python application by pressing `Ctrl+C` Why do I not see the logs instantly in the redirected file? **Is it solvable by simple i/o redirection as I tried? (without doing code changes inside my Python code, by using modules like logging)**
2017/02/21
[ "https://Stackoverflow.com/questions/42358433", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2091948/" ]
The best option for your case is to set the environment variable `PYTHONUNBUFFERED`. This is a little more robust than calling `#/usr/bin/python -u`, as this may not work in some virtual envs. In your terminal: ``` export PYTHONUNBUFFERED=1 python tmp.py >/tmp/logs.log 2>&1 #or however else you want to call your script. ```
The issue is that the output is buffered, that means python saves the output in a buffer and flushes it every now and then, but not necessarily after each print. You could fix by forcing a flush after each print by explicitly calling `sys.stdout.flush()`. ``` import time import sys while True: print "New val" sys.stdout.flush() time.sleep(1) ```
65,700,886
My experience in python is close to 0, bear with me. I want to install <https://pypi.org/project/locuplot/> on an EC2 machine to create some plots after running Locust in headless mode. However, I do not manage to install it: ``` yum update -y yum install python3 -y yum install python3-devel -y yum install python3-pip -y yum install python-pip -y yum -y groupinstall 'Development Tools' pip3 install locust pip install locuplot ``` But the last command results in: ``` Collecting locuplot Could not find a version that satisfies the requirement locuplot (from versions: ) No matching distribution found for locuplot ``` What am I missing?
2021/01/13
[ "https://Stackoverflow.com/questions/65700886", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11868615/" ]
You have ``` pip install locuplot ``` in your last line, but `locuplot` does only work with python3 and, depending on your setup, `pip` might default to the python2 installation, so you should do ``` pip3 install locuplot ``` instead
Thanks to FlyingTeller found the issue. The reason is that it requires python>=3.8 ``` amazon-linux-extras install python3 python3.8 -m pip install locuplot pip install locuplot ```
29,166,538
From what I read about variable scopes and importing resource files in [robotframework doc](http://robotframework.org/robotframework/latest/RobotFrameworkUserGuide.html#id487) i would expect this to work (python 2.7, RF 2.8.7): Test file: ``` *** Settings *** Resource VarRes.txt Suite Setup Preconditions *** Variables *** *** Test Cases *** VarDemo Log To Console imported [${TODAY}] *** Keywords *** ``` Resource file: ``` *** Settings *** Library DateTime *** Variables *** ${TODAY} ${EMPTY} # Initialised during setup, see keyword Preconditions *** Keywords *** Format Local Date [Arguments] ${inc} ${format} ${date} = Get Current Date time_zone=local increment=${inc} day result_format=${format} [Return] ${date} # formatted date Preconditions ${TODAY} = Format Local Date 0 %Y-%m-%d Log To Console inited [${TODAY}] ``` However the output is: ``` inited [2015-03-20] imported [] ``` RF documentation states: > > Variables with the test suite scope are available anywhere in the test > suite where they are defined **or imported**. They can be created in > Variable tables, **imported from resource** and .... > > > which I think is done here.
2015/03/20
[ "https://Stackoverflow.com/questions/29166538", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4629534/" ]
The following works for me: JavaScript: ``` // Traian Băsescu encodes to VHJhaWFuIELEg3Nlc2N1 var base64 = btoa(unescape(encodeURIComponent( $("#Contact_description").val() ))); ``` PHP: ``` $utf8 = base64_decode($base64); ```
The problem is that Javascript strings are encoded in UTF-16, and browsers do not offer very many good tools to deal with encodings. A great resource specifically for dealing with Base64 encodings and Unicode can be found at MDN: <https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64/Base64_encoding_and_decoding> Their suggested solution for encoding strings **without using the often cited solution involving the deprecated `unescape` function** is: ``` function b64EncodeUnicode(str) { return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, function(match, p1) { return String.fromCharCode('0x' + p1); })); } ``` For further solutions and details I highly recommend you read the entire page.
26,013,487
I need to change the path of the python's core dump file, or completely disable it. I'm aware that it's possible to change the pattern and location of the core dumps in linux using: ``` /proc/sys/kernel/core_pattern ``` But this is not a suitable solution on a shared server and/or on a grid engine. So, how can I change the path of python's core dump, or how can I disable it's flush to the disk? Is it possible to change that pattern to `/dev/null` only for my user?
2014/09/24
[ "https://Stackoverflow.com/questions/26013487", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2536294/" ]
You can use shell command `ulimit` to control it: ``` ulimit -c 0 # Disable core file creation ``` Without the value, it will print current limit (the maximum size of core file will be created): ``` ulimit -c ```
I think, this page gives you what you are looking for: <http://sigquit.wordpress.com/2009/03/13/the-core-pattern/> Quoting from the page: > > "...the kernel configuration includes a file named “core\_pattern”: > > > > ``` /proc/sys/kernel/core_pattern ``` > > In my system, that file contains just this single word: > core > > > As expected, this pattern shows how the core file will be generated. Two things can be understood from the previous line: The filename of the core dump file generated will be “core”; and second, the current directory will be used to store it (as the path specified is completely relative to the current directory). > > > Now, if we change the contents of that file… (as root, of course) > > > ``` $> mkdir -p /tmp/cores $> chmod a+rwx /tmp/cores $> echo "/tmp/cores/core.%e.%p.%h.%t" > /proc/sys/kernel/core_pattern ``` > > You can use the following pattern elements in the core\_pattern file: > > > ``` %p: pid %: '%' is dropped %%: output one '%' %u: uid %g: gid %s: signal number %t: UNIX time of dump %h: hostname %e: executable filename %: both are dropped ``` Further on, this part touches the specific need of handling things when working on a cluster of nodes: > > Isn’t is great?! Imagine that you have a cluster of machines and you want to use a NFS directory to store all core files from all the nodes. You will be able to detect which node generated the core file (with the hostname), which program generated it (with the program name), and also when did it happen (with the unix time). > > > And configuring it for good, > > The changes done before are only applicable until the next reboot. In order to make the change in all future reboots, you will need to add the following in “/etc/sysctl.conf“: > > > ``` # Own core file pattern... kernel.core_pattern=/tmp/cores/core.%e.%p.%h.%t ``` > > sysctl.conf is the file controlling every configuration under /proc/sys > > >
56,863,556
I want to convert Binary Tree into Array using Python and i don't know how to give index to tree-node? I have done this using the formula left\_son=(2\*p)+1; and right\_son=(2\*p)+2; in java But i'm stuck in python. Is there any Function to give index to tree-node in python ?
2019/07/03
[ "https://Stackoverflow.com/questions/56863556", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8627333/" ]
You can represent a binary tree in python as a one-dimensional list the exact same way. For example if you have at tree represented as: ``` [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 14, 15] ``` `0` is the root `1` & `2` are the next level the children of `1` & `2` are `[3, 4]` and `[5, 6]` This corresponds to your formula. For a given node at index `i` the children of that node are `(2*i)+1` `(2*i)+2`. This is a common way to model a heap. You can read more about how Python uses this in its [heapq library].(<https://docs.python.org/3.0/library/heapq.html>) You can use this to traverse the tree in depths with something like: ``` a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 14, 15] def childNodes(i): return (2*i)+1, (2*i)+2 def traversed(a, i=0, d = 0): if i >= len(a): return l, r = childNodes(i) traversed(a, r, d = d+1) print(" "*d + str(a[i])) traversed(a, l, d = d+1) traversed(a) ``` **This Prints** ``` 15 6 14 2 13 5 11 0 10 4 9 1 8 3 7 ```
Incase of a binary tree, you'll have to perform a level order traversal. And as you keep traversing, you'll have to store the values in the array in the order they appear during the traversal. This will help you in restoring the properties of a binary tree and will also maintain the order of elements. Here is the code to perform level order traversal. ``` class Node: # A utility function to create a new node def __init__(self, key): self.data = key self.left = None self.right = None # Function to print level order traversal of tree def printLevelOrder(root): h = height(root) for i in range(1, h+1): printGivenLevel(root, i) # Print nodes at a given level def printGivenLevel(root , level): if root is None: return if level == 1: print "%d" %(root.data), elif level > 1 : printGivenLevel(root.left , level-1) printGivenLevel(root.right , level-1) """ Compute the height of a tree--the number of nodes along the longest path from the root node down to the farthest leaf node """ def height(node): if node is None: return 0 else : # Compute the height of each subtree lheight = height(node.left) rheight = height(node.right) #Use the larger one if lheight > rheight : return lheight+1 else: return rheight+1 # Driver program to test above function root = Node(1) root.left = Node(2) root.right = Node(3) root.left.left = Node(4) root.left.right = Node(5) print "Level order traversal of binary tree is -" printLevelOrder(root) ```
45,804,534
I'm trying to load Parquet data into `PySpark`, where a column has a space in the name: ``` df = spark.read.parquet('my_parquet_dump') df.select(df['Foo Bar'].alias('foobar')) ``` Even though I have aliased the column, I'm still getting this error and error propagating from the `JVM` side of `PySpark`. I've attached the stack trace below. Is there a way I can load this parquet file into `PySpark`, without pre-processing the data in Scala, and without modifying the source parquet file? ``` --------------------------------------------------------------------------- Py4JJavaError Traceback (most recent call last) /usr/local/python/pyspark/sql/utils.py in deco(*a, **kw) 62 try: ---> 63 return f(*a, **kw) 64 except py4j.protocol.Py4JJavaError as e: /usr/local/python/lib/py4j-0.10.4-src.zip/py4j/protocol.py in get_return_value(answer, gateway_client, target_id, name) 318 "An error occurred while calling {0}{1}{2}.\n". --> 319 format(target_id, ".", name), value) 320 else: Py4JJavaError: An error occurred while calling o864.collectToPython. : org.apache.spark.sql.AnalysisException: Attribute name "Foo Bar" contains invalid character(s) among " ,;{}()\n\t=". Please use alias to rename it.; at org.apache.spark.sql.execution.datasources.parquet.ParquetSchemaConverter$.checkConversionRequirement(ParquetSchemaConverter.scala:581) at org.apache.spark.sql.execution.datasources.parquet.ParquetSchemaConverter$.checkFieldName(ParquetSchemaConverter.scala:567) at org.apache.spark.sql.execution.datasources.parquet.ParquetSchemaConverter$$anonfun$checkFieldNames$1.apply(ParquetSchemaConverter.scala:575) at org.apache.spark.sql.execution.datasources.parquet.ParquetSchemaConverter$$anonfun$checkFieldNames$1.apply(ParquetSchemaConverter.scala:575) at scala.collection.IndexedSeqOptimized$class.foreach(IndexedSeqOptimized.scala:33) at scala.collection.mutable.ArrayOps$ofRef.foreach(ArrayOps.scala:186) at org.apache.spark.sql.execution.datasources.parquet.ParquetSchemaConverter$.checkFieldNames(ParquetSchemaConverter.scala:575) at org.apache.spark.sql.execution.datasources.parquet.ParquetFileFormat.buildReaderWithPartitionValues(ParquetFileFormat.scala:293) at org.apache.spark.sql.execution.FileSourceScanExec.inputRDD$lzycompute(DataSourceScanExec.scala:285) at org.apache.spark.sql.execution.FileSourceScanExec.inputRDD(DataSourceScanExec.scala:283) at org.apache.spark.sql.execution.FileSourceScanExec.inputRDDs(DataSourceScanExec.scala:303) at org.apache.spark.sql.execution.ProjectExec.inputRDDs(basicPhysicalOperators.scala:42) at org.apache.spark.sql.execution.WholeStageCodegenExec.doExecute(WholeStageCodegenExec.scala:386) at org.apache.spark.sql.execution.SparkPlan$$anonfun$execute$1.apply(SparkPlan.scala:117) at org.apache.spark.sql.execution.SparkPlan$$anonfun$execute$1.apply(SparkPlan.scala:117) at org.apache.spark.sql.execution.SparkPlan$$anonfun$executeQuery$1.apply(SparkPlan.scala:138) at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:151) at org.apache.spark.sql.execution.SparkPlan.executeQuery(SparkPlan.scala:135) at org.apache.spark.sql.execution.SparkPlan.execute(SparkPlan.scala:116) at org.apache.spark.sql.execution.SparkPlan.getByteArrayRdd(SparkPlan.scala:228) at org.apache.spark.sql.execution.SparkPlan.executeTake(SparkPlan.scala:311) at org.apache.spark.sql.execution.CollectLimitExec.executeCollect(limit.scala:38) at org.apache.spark.sql.Dataset$$anonfun$collectToPython$1.apply$mcI$sp(Dataset.scala:2803) at org.apache.spark.sql.Dataset$$anonfun$collectToPython$1.apply(Dataset.scala:2800) at org.apache.spark.sql.Dataset$$anonfun$collectToPython$1.apply(Dataset.scala:2800) at org.apache.spark.sql.execution.SQLExecution$.withNewExecutionId(SQLExecution.scala:65) at org.apache.spark.sql.Dataset.withNewExecutionId(Dataset.scala:2823) at org.apache.spark.sql.Dataset.collectToPython(Dataset.scala:2800) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:244) at py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:357) at py4j.Gateway.invoke(Gateway.java:280) at py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:132) at py4j.commands.CallCommand.execute(CallCommand.java:79) at py4j.GatewayConnection.run(GatewayConnection.java:214) at java.lang.Thread.run(Thread.java:748) During handling of the above exception, another exception occurred: AnalysisException Traceback (most recent call last) <ipython-input-37-9d7c55a5465c> in <module>() ----> 1 spark.sql("SELECT `Foo Bar` as hey FROM df limit 10").take(1) /usr/local/python/pyspark/sql/dataframe.py in take(self, num) 474 [Row(age=2, name=u'Alice'), Row(age=5, name=u'Bob')] 475 """ --> 476 return self.limit(num).collect() 477 478 @since(1.3) /usr/local/python/pyspark/sql/dataframe.py in collect(self) 436 """ 437 with SCCallSiteSync(self._sc) as css: --> 438 port = self._jdf.collectToPython() 439 return list(_load_from_socket(port, BatchedSerializer(PickleSerializer()))) 440 /usr/local/python/lib/py4j-0.10.4-src.zip/py4j/java_gateway.py in __call__(self, *args) 1131 answer = self.gateway_client.send_command(command) 1132 return_value = get_return_value( -> 1133 answer, self.gateway_client, self.target_id, self.name) 1134 1135 for temp_arg in temp_args: /usr/local/python/pyspark/sql/utils.py in deco(*a, **kw) 67 e.java_exception.getStackTrace())) 68 if s.startswith('org.apache.spark.sql.AnalysisException: '): ---> 69 raise AnalysisException(s.split(': ', 1)[1], stackTrace) 70 if s.startswith('org.apache.spark.sql.catalyst.analysis'): 71 raise AnalysisException(s.split(': ', 1)[1], stackTrace) AnalysisException: 'Attribute name "Foo Bar" contains invalid character(s) among " ,;{}()\\n\\t=". Please use alias to rename it.;' ```
2017/08/21
[ "https://Stackoverflow.com/questions/45804534", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1922392/" ]
Have you tried, ```py df = df.withColumnRenamed("Foo Bar", "foobar") ``` When you select the column with an alias you're still passing the wrong column name through a select clause.
I tried @ktang 's method and it worked for me as well. I'm working with SQL and Python, so it may be different for you, but it worked nonetheless. Ensure there are no spaces in your column names/headers. Despite the list of characters provided in the error message, space ( ) doesn't seem to be acceptable by Pyspark. I was initially using: ``` master_df = spark.sql(f''' SELECT occ.num, 'Occ Event' AS `Event Type`, ... ``` Changing the space ( ) in Event Type to an underscore (\_) worked: ``` master_df = spark.sql(f''' SELECT occ.num, 'Occ Event' AS `Event_Type`, ... ```
20,862,510
How do you determine if an incoming url Request to an Openshift app is 'http' or 'https'? I wrote an Openshift python 3.3 app back in June '13. I was able to tell if the incoming url to my Openshift app was 'http' or 'https' by the following code: ``` if request['HTTP_X_FORWARDED_PROTO'] == 'https': #do something ``` This code no longer works when I create new Openshift apps. I have posted on the Openshift forums without finding the solution. They suggested that I post here. Anybody know how to do this?
2013/12/31
[ "https://Stackoverflow.com/questions/20862510", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1924325/" ]
This is a bug and will be fixed. EDIT: Opened <https://bugzilla.redhat.com/show_bug.cgi?id=1048331> to track
In the meantime I found that this works. if request.environ['HTTP\_X\_FORWARDED\_PROTO'] == 'http': # or https
32,111,279
I want to read a pdf file in python. Tried some of the ways- PdfReader and pdfquery but not getting the result in string format. Want to have some of the content from that pdf file. is there any way to do that?
2015/08/20
[ "https://Stackoverflow.com/questions/32111279", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4075219/" ]
[PDFminer](http://www.unixuser.org/%7Eeuske/python/pdfminer/index.html) is a tool for extracting information from PDF documents.
Does it matter in your case if file is pdf or not. If you just want to read your file as string, just open it as you would open a normal file. E.g.- ``` with open('my_file.pdf') as file: content = file.read() ```
56,914,592
I have a lot of PNG images that I want to classify, using a trained CNN model. To speed up the process, I would like to use multiple-processing with CPUs (I have 72 available, here I'm just using 4). I don't have a GPU available at the moment, but if necessary, I could get one. **My workflow:** 1. read a figure with `openCV` 2. adapt shape and format 3. use `mymodel.predict(img)` to get the probability for each class When it comes to the prediction step, it never finishes the `mymodel.predict(img)` step. When I use the code without the multiprocessing module, it works fine. For the model, I'm using keras with a tensorflow backend. ``` # load model mymodel = load_model('190704_1_fcs_plotclassifier.h5') # use python library multiprocessing to use different CPUs import multiprocessing as mp pool = mp.Pool(4) # Define callback function to collect the output in 'outcomes' outcomes = [] def collect_result(result): global outcomes outcomes.append(result) # Define prediction function def prediction(img): img = cv2.resize(img,(49,49)) img = img.astype('float32') / 255 img = np.reshape(img,[1,49,49,3]) status = mymodel.predict(img) status = status[0][1] return(status) # Define evaluate function def evaluate(i,figure): # predict the propability of the picture to be in class 0 or 1 img = cv2.imread(figure) status = prediction(img) outcome = [figure, status] return(i,outcome) # execute multiprocessing for i, item in enumerate(listoffigurepaths): pool.apply_async(evaluate, args=(i, item), callback=collect_result) pool.close() pool.join() # get outcome print(outcomes) ``` It would be great if somebody knows how to predict several images at a time! I simplified my code here, but if somebody has an example how it could be done, I would highly appreciate it.
2019/07/06
[ "https://Stackoverflow.com/questions/56914592", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11124934/" ]
Does a processing-speed or a size-of-RAMor a number-of-CPU-coresor an introduced add-on processing latency matter most?[ALL OF THESE DO:](https://stackoverflow.com/revisions/18374629/3) ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- The python **`multiprocessing`** module is known ( and the **`joblib`** does the same ) to: > > The `multiprocessing` package offers both local and remote concurrency, **effectively side-stepping the Global Interpreter Lock** by using **subprocesses** instead of threads. > > > Yet, as everything in our Universe, this comes at cost: The wish, expressed by O/P as: > > *To speed up the process, I would like to **use multiple-processing with CPUs** (I have **72 available*** > > > will, for this kind of a similar application of a pre-trained **`mymodel.predict()`**-or, if sent into a `Pool( 72 )`-execution almost for sure suffocate almost any hardware RAM by swapping. Here is an example, where "just"-Do-Nothing worker was spawned by the **`n_jobs = 100`** directive - to see what happens ( time-wise ~ 532+ [ms] lost + memory-allocation-wise where XYZ [GB] or RAM have immediately been allocated by O/S ): [![enter image description here](https://i.stack.imgur.com/Oshjh.png)](https://i.stack.imgur.com/Oshjh.png) This comes from the fact, that each **`multiprocessing`** spawned sub-process ( not threads, as O/P has already experienced on her own ) is first instantiated ( after an adequate add-on latency due to O/S process/RAM-allocations-management ) as a ---**FULL-COPY**--- of the ecosystem present inside the original python process ( the complete **`python`** interpreter + all its **`import`**-ed modules + all its internal state and data-structures - used or not - ) so indeed huge amounts of RAM-allocations take place ( have you noticed the platform started to SWAP? notice how many sub-processes were spawned until that time and you have a ceiling of how many such can fit in-RAM and it makes devastating performance effects if trying ( or letting, by using the **`joblib`**-s `n_jobs = -1` auto-scaling directive ) to populate more sub-processes, that this SWAP-introducing number... So far good, we have paid some ( often for carefully designed code a reasonably negligible amount, if compared to fully train again the whole predictor, doesn't it? ) time to spawn some number of parallel processes. If the distributed workload next goes back, to one, common and performance-wise singular resource ( a disk directory-tree with files ), the performance of parallel-processes goes but in wreck havoc - it has to wait for such resource(!) to first get it free again. Finally, even the "right"-amount of **`Pool()`**-spawned sub-processes, such that prevents am O/S to start SWAPPING RAM to disk and back, the inter-process communication is extremely expensive -- here, serialising ( Pickling/unPickling ) + enQueueing + deQueueing all DATA-objects, one has to pass there and back ( yes, even for the **`callback`** fun ), so the less one sends, the way faster the `Pool`-processing will become. Here, all `Pool`-associated processes might benefit from independent logging of the results, which may reduce both the scales and latency of the inter-process communications, but will also consolidate the results, reported by any number of workers into the common log. --- How to ... ? First benchmark the costs of each step: ---------------------------------------------------- Without hard facts ( measured durations in `[us]` ), one remains with just an opinion. ``` def prediction( img ): img = cv2.resize( img, ( 49, 49 ) ) img = img.astype( 'float32' ) / 255 img = np.reshape( img, [1, 49, 49, 3] ) status = mymodel.predict( img ) status = status[0][1] return( status ) def evaluate( i, figure ): # predict the propability of the picture to be in class 0 or 1 img = cv2.imread( figure ) status = prediction( img ) outcome = [figure, status] return( i, outcome ) #-------------------------------------------------- from zmq import Stopwatch aClk = Stopwatch() #------------------------------------NOW THE COSTS OF ORIGINAL VERSION: aListOfRESULTs = [] for iii in range( 100 ): #-------------------------------------------------aClk-ed---------- SECTION aClk.start(); _ = evaluate( 1, aFigureNAME ); A = aClk.stop() #-------------------------------------------------aClk-ed---------- SECTION print( "as-is took {0:}[us]".format( A ) );aListOfRESULTs.append( A ) #---------------------------------------------------------------------- print( [ aFun( aListOfRESULTs ) for aFun in ( np.min, np.mean, np.max ) ] ) #---------------------------------------------------------------------- ``` --- Lets try something a bit else: ``` def eval_w_RAM_allocs_avoided( indexI, aFigureNAME ): return [ indexI, [ aFigureNAME, mymodel.predict( ( cv2.resize( cv2.imread( aFigureNAME ), ( 49, 49 ) ).astype( 'float32' ) / 255 ).reshape( [1, 49, 49, 3] ) )[0][1], ], ] #------------------------------------NOW THE COSTS OF MOD-ed VERSION: aListOfRESULTs = [] for iii in range( 100 ): #-------------------------------------------------aClk-ed---------- SECTION aClk.start() _ = eval_w_RAM_allocs_avoided( 1, aFigureNAME ) B = aClk.stop() #-------------------------------------------------aClk-ed---------- SECTION print( "MOD-ed took {0:}[us] ~ {1:} x".format( B, float( B ) / A ) ) aListOfRESULTs.append( B ) #---------------------------------------------------------------------- print( [ aFun( aListOfRESULTs ) for aFun in ( np.min, np.mean, np.max ) ] ) #---------------------------------------------------------------------- ``` --- And the actual `img` pre-processing pipeline overhead costs: ``` #------------------------------------NOW THE COSTS OF THE IMG-PREPROCESSING aListOfRESULTs = [] for iii in range( 100 ): #-------------------------------------------------aClk-ed---------- SECTION aClk.start() aPredictorSpecificFormatIMAGE = ( cv2.resize( cv2.imread( aFigureNAME ), ( 49, 49 ) ).astype( 'float32' ) / 255 ).reshape( [1, 49, 49, 3] ) C = aClk.stop() #-------------------------------------------------aClk-ed---------- SECTION print( "IMG setup took {0:}[us] ~ {1:} of A".format( C, float( C ) / A ) ) aListOfRESULTs.append( C ) #---------------------------------------------------------------------- print( [ aFun( aListOfRESULTs ) for aFun in ( np.min, np.mean, np.max ) ] ) #---------------------------------------------------------------------- ``` --- Actual fileI/O ops: ``` #------------------------------------NOW THE COSTS OF THE IMG-FILE-I/O-READ aListOfRESULTs = [] for iii in range( 100 ): #-------------------------------------------------aClk-ed---------- SECTION aFileNAME = listoffigurepaths[158 + iii * 172] aClk.start() _ = cv2.imread( aFileNAME ) F = aClk.stop() #-------------------------------------------------aClk-ed---------- SECTION print( "aFileIO took {0:}[us] ~ {1:} of A".format( F, float( F ) / A ) ) aListOfRESULTs.append( F ) #---------------------------------------------------------------------- print( [ aFun( aListOfRESULTs ) for aFun in ( np.min, np.mean, np.max ) ] ) #---------------------------------------------------------------------- ``` Without these hard-fact collected ( as a form of quantitative records-of-evidence ), one could hardly decide, what would be the best performance boosting step here for any massive-scale prediction-pipeline image processing. Having these items tested, post results and further steps ( be it for going via **`multiprocessing.Pool`** or using other strategy for larger performance scaling, to whatever higher performance ) may first get reasonably evaluated, as the hard facts were first collected to do so.
One python package I know that may help you is `joblib`. Hope it can solve your problem. ``` from joblib import Parallel, delayed ``` ``` # load model mymodel = load_model('190704_1_fcs_plotclassifier.h5') # Define callback function to collect the output in 'outcomes' outcomes = [] def collect_result(result): global outcomes outcomes.append(result) # Define prediction function def prediction(img): img = cv2.resize(img,(49,49)) img = img.astype('float32') / 255 img = np.reshape(img,[1,49,49,3]) status = mymodel.predict(img) status = status[0][1] return(status) # Define evaluate function def evaluate(i,figure): # predict the propability of the picture to be in class 0 or 1 img = cv2.imread(figure) status = prediction(img) outcome = [figure, status] return(i,outcome) outcomes = Parallel(n_jobs=72)(delayed(evaluate)(i,figure) for figure in listoffigurepaths) ```
56,914,592
I have a lot of PNG images that I want to classify, using a trained CNN model. To speed up the process, I would like to use multiple-processing with CPUs (I have 72 available, here I'm just using 4). I don't have a GPU available at the moment, but if necessary, I could get one. **My workflow:** 1. read a figure with `openCV` 2. adapt shape and format 3. use `mymodel.predict(img)` to get the probability for each class When it comes to the prediction step, it never finishes the `mymodel.predict(img)` step. When I use the code without the multiprocessing module, it works fine. For the model, I'm using keras with a tensorflow backend. ``` # load model mymodel = load_model('190704_1_fcs_plotclassifier.h5') # use python library multiprocessing to use different CPUs import multiprocessing as mp pool = mp.Pool(4) # Define callback function to collect the output in 'outcomes' outcomes = [] def collect_result(result): global outcomes outcomes.append(result) # Define prediction function def prediction(img): img = cv2.resize(img,(49,49)) img = img.astype('float32') / 255 img = np.reshape(img,[1,49,49,3]) status = mymodel.predict(img) status = status[0][1] return(status) # Define evaluate function def evaluate(i,figure): # predict the propability of the picture to be in class 0 or 1 img = cv2.imread(figure) status = prediction(img) outcome = [figure, status] return(i,outcome) # execute multiprocessing for i, item in enumerate(listoffigurepaths): pool.apply_async(evaluate, args=(i, item), callback=collect_result) pool.close() pool.join() # get outcome print(outcomes) ``` It would be great if somebody knows how to predict several images at a time! I simplified my code here, but if somebody has an example how it could be done, I would highly appreciate it.
2019/07/06
[ "https://Stackoverflow.com/questions/56914592", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11124934/" ]
Does a processing-speed or a size-of-RAMor a number-of-CPU-coresor an introduced add-on processing latency matter most?[ALL OF THESE DO:](https://stackoverflow.com/revisions/18374629/3) ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- The python **`multiprocessing`** module is known ( and the **`joblib`** does the same ) to: > > The `multiprocessing` package offers both local and remote concurrency, **effectively side-stepping the Global Interpreter Lock** by using **subprocesses** instead of threads. > > > Yet, as everything in our Universe, this comes at cost: The wish, expressed by O/P as: > > *To speed up the process, I would like to **use multiple-processing with CPUs** (I have **72 available*** > > > will, for this kind of a similar application of a pre-trained **`mymodel.predict()`**-or, if sent into a `Pool( 72 )`-execution almost for sure suffocate almost any hardware RAM by swapping. Here is an example, where "just"-Do-Nothing worker was spawned by the **`n_jobs = 100`** directive - to see what happens ( time-wise ~ 532+ [ms] lost + memory-allocation-wise where XYZ [GB] or RAM have immediately been allocated by O/S ): [![enter image description here](https://i.stack.imgur.com/Oshjh.png)](https://i.stack.imgur.com/Oshjh.png) This comes from the fact, that each **`multiprocessing`** spawned sub-process ( not threads, as O/P has already experienced on her own ) is first instantiated ( after an adequate add-on latency due to O/S process/RAM-allocations-management ) as a ---**FULL-COPY**--- of the ecosystem present inside the original python process ( the complete **`python`** interpreter + all its **`import`**-ed modules + all its internal state and data-structures - used or not - ) so indeed huge amounts of RAM-allocations take place ( have you noticed the platform started to SWAP? notice how many sub-processes were spawned until that time and you have a ceiling of how many such can fit in-RAM and it makes devastating performance effects if trying ( or letting, by using the **`joblib`**-s `n_jobs = -1` auto-scaling directive ) to populate more sub-processes, that this SWAP-introducing number... So far good, we have paid some ( often for carefully designed code a reasonably negligible amount, if compared to fully train again the whole predictor, doesn't it? ) time to spawn some number of parallel processes. If the distributed workload next goes back, to one, common and performance-wise singular resource ( a disk directory-tree with files ), the performance of parallel-processes goes but in wreck havoc - it has to wait for such resource(!) to first get it free again. Finally, even the "right"-amount of **`Pool()`**-spawned sub-processes, such that prevents am O/S to start SWAPPING RAM to disk and back, the inter-process communication is extremely expensive -- here, serialising ( Pickling/unPickling ) + enQueueing + deQueueing all DATA-objects, one has to pass there and back ( yes, even for the **`callback`** fun ), so the less one sends, the way faster the `Pool`-processing will become. Here, all `Pool`-associated processes might benefit from independent logging of the results, which may reduce both the scales and latency of the inter-process communications, but will also consolidate the results, reported by any number of workers into the common log. --- How to ... ? First benchmark the costs of each step: ---------------------------------------------------- Without hard facts ( measured durations in `[us]` ), one remains with just an opinion. ``` def prediction( img ): img = cv2.resize( img, ( 49, 49 ) ) img = img.astype( 'float32' ) / 255 img = np.reshape( img, [1, 49, 49, 3] ) status = mymodel.predict( img ) status = status[0][1] return( status ) def evaluate( i, figure ): # predict the propability of the picture to be in class 0 or 1 img = cv2.imread( figure ) status = prediction( img ) outcome = [figure, status] return( i, outcome ) #-------------------------------------------------- from zmq import Stopwatch aClk = Stopwatch() #------------------------------------NOW THE COSTS OF ORIGINAL VERSION: aListOfRESULTs = [] for iii in range( 100 ): #-------------------------------------------------aClk-ed---------- SECTION aClk.start(); _ = evaluate( 1, aFigureNAME ); A = aClk.stop() #-------------------------------------------------aClk-ed---------- SECTION print( "as-is took {0:}[us]".format( A ) );aListOfRESULTs.append( A ) #---------------------------------------------------------------------- print( [ aFun( aListOfRESULTs ) for aFun in ( np.min, np.mean, np.max ) ] ) #---------------------------------------------------------------------- ``` --- Lets try something a bit else: ``` def eval_w_RAM_allocs_avoided( indexI, aFigureNAME ): return [ indexI, [ aFigureNAME, mymodel.predict( ( cv2.resize( cv2.imread( aFigureNAME ), ( 49, 49 ) ).astype( 'float32' ) / 255 ).reshape( [1, 49, 49, 3] ) )[0][1], ], ] #------------------------------------NOW THE COSTS OF MOD-ed VERSION: aListOfRESULTs = [] for iii in range( 100 ): #-------------------------------------------------aClk-ed---------- SECTION aClk.start() _ = eval_w_RAM_allocs_avoided( 1, aFigureNAME ) B = aClk.stop() #-------------------------------------------------aClk-ed---------- SECTION print( "MOD-ed took {0:}[us] ~ {1:} x".format( B, float( B ) / A ) ) aListOfRESULTs.append( B ) #---------------------------------------------------------------------- print( [ aFun( aListOfRESULTs ) for aFun in ( np.min, np.mean, np.max ) ] ) #---------------------------------------------------------------------- ``` --- And the actual `img` pre-processing pipeline overhead costs: ``` #------------------------------------NOW THE COSTS OF THE IMG-PREPROCESSING aListOfRESULTs = [] for iii in range( 100 ): #-------------------------------------------------aClk-ed---------- SECTION aClk.start() aPredictorSpecificFormatIMAGE = ( cv2.resize( cv2.imread( aFigureNAME ), ( 49, 49 ) ).astype( 'float32' ) / 255 ).reshape( [1, 49, 49, 3] ) C = aClk.stop() #-------------------------------------------------aClk-ed---------- SECTION print( "IMG setup took {0:}[us] ~ {1:} of A".format( C, float( C ) / A ) ) aListOfRESULTs.append( C ) #---------------------------------------------------------------------- print( [ aFun( aListOfRESULTs ) for aFun in ( np.min, np.mean, np.max ) ] ) #---------------------------------------------------------------------- ``` --- Actual fileI/O ops: ``` #------------------------------------NOW THE COSTS OF THE IMG-FILE-I/O-READ aListOfRESULTs = [] for iii in range( 100 ): #-------------------------------------------------aClk-ed---------- SECTION aFileNAME = listoffigurepaths[158 + iii * 172] aClk.start() _ = cv2.imread( aFileNAME ) F = aClk.stop() #-------------------------------------------------aClk-ed---------- SECTION print( "aFileIO took {0:}[us] ~ {1:} of A".format( F, float( F ) / A ) ) aListOfRESULTs.append( F ) #---------------------------------------------------------------------- print( [ aFun( aListOfRESULTs ) for aFun in ( np.min, np.mean, np.max ) ] ) #---------------------------------------------------------------------- ``` Without these hard-fact collected ( as a form of quantitative records-of-evidence ), one could hardly decide, what would be the best performance boosting step here for any massive-scale prediction-pipeline image processing. Having these items tested, post results and further steps ( be it for going via **`multiprocessing.Pool`** or using other strategy for larger performance scaling, to whatever higher performance ) may first get reasonably evaluated, as the hard facts were first collected to do so.
img\_height = 512 # Height of the input images img\_width =512 # Width of the input images img\_channels = 3 # Number of color channels of the input images orig\_images = [] # Store the images here. batch\_holder = np.zeros((20, img\_height, img\_width, 3)) img\_dir = "path/to/image/" for i,img, in enumerate(os.listdir(img\_dir)): img = os.path.join(img\_dir, img) orig\_images.append(imread(img)) img =image.load\_img(img, target\_size=(img\_height, img\_width)) batch\_holder[i,:] =img y\_pred = model.predict(batch\_holder) y\_pred\_decoded = decode\_y(y\_pred,parameter) np.set\_printoptions(precision=2, suppress=True, linewidth=90) print("Predicted boxes:\n") print(' class conf xmin ymin xmax ymax') print(y\_pred\_decoded[i]) Display the image and draw the predicted boxes onto it. ======================================================= Set the colors for the bounding boxes ===================================== colors = plt.cm.hsv(np.linspace(0, 1, 21)).tolist() classes = ['background','class'] current\_axis = plt.gca() for box in y\_pred\_decoded[I]: xmin = box[-4] \* orig\_images[0].shape[1] / img\_width ymin = box[-3] \* orig\_images[0].shape[0] / img\_height xmax = box[-2] \* orig\_images[0].shape[1] / img\_width ymax = box[-1] \* orig\_images[0].shape[0] / img\_height color = colors[int(box[0])] label = '{}: {:.2f}'.format(classes[int(box[0])], box[1]) current\_axis.add\_patch(plt.Rectangle((xmin, ymin), xmax - xmin, ymax - ymin, color=color, fill=False, linewidth=2)) current\_axis.text(xmin, ymin, label, size='x-large', color='white', bbox={'facecolor': color, 'alpha': 1.0}) plt.imshow(orig\_images[i]) plt.show()
12,167,192
I want to create a dict which can be accessed as: ``` d[id_1][id_2][id_3] = amount ``` As of now I have a huge ugly function: ``` def parse_dict(id1,id2,id3,principal, data_dict): if data_dict.has_key(id1): values = data_dict[id1] if values.has_key[id2] .. else: inner_inner_dict = {} # and so on ``` What is the pythonic way to do this? note, that i input the principal.. but what i want is the amount.. So if all the three keys are there.. add principal to the previous amount! Thanks
2012/08/28
[ "https://Stackoverflow.com/questions/12167192", "https://Stackoverflow.com", "https://Stackoverflow.com/users/902885/" ]
You may want to consider using [`defaultdict`](http://docs.python.org/library/collections.html): For example: ``` json_dict = defaultdict(lambda: defaultdict(dict)) ``` will create a `defaultdict` of `defaultdict`s of `dict`s (I know..but it is right), to access it, you can simply do: ``` json_dict['context']['name']['id'] = '42' ``` without having to resort to using `if...else` to initialize.
Maybe you need to have a look at multi-dimensional arrays - for example in numpy: <http://docs.scipy.org/doc/numpy/reference/arrays.ndarray.html>
12,167,192
I want to create a dict which can be accessed as: ``` d[id_1][id_2][id_3] = amount ``` As of now I have a huge ugly function: ``` def parse_dict(id1,id2,id3,principal, data_dict): if data_dict.has_key(id1): values = data_dict[id1] if values.has_key[id2] .. else: inner_inner_dict = {} # and so on ``` What is the pythonic way to do this? note, that i input the principal.. but what i want is the amount.. So if all the three keys are there.. add principal to the previous amount! Thanks
2012/08/28
[ "https://Stackoverflow.com/questions/12167192", "https://Stackoverflow.com", "https://Stackoverflow.com/users/902885/" ]
You may want to consider using [`defaultdict`](http://docs.python.org/library/collections.html): For example: ``` json_dict = defaultdict(lambda: defaultdict(dict)) ``` will create a `defaultdict` of `defaultdict`s of `dict`s (I know..but it is right), to access it, you can simply do: ``` json_dict['context']['name']['id'] = '42' ``` without having to resort to using `if...else` to initialize.
``` from collections import defaultdict d = defaultdict(lambda : defaultdict(dict)) d[id_1][id_2][id_3] = amount ```
12,167,192
I want to create a dict which can be accessed as: ``` d[id_1][id_2][id_3] = amount ``` As of now I have a huge ugly function: ``` def parse_dict(id1,id2,id3,principal, data_dict): if data_dict.has_key(id1): values = data_dict[id1] if values.has_key[id2] .. else: inner_inner_dict = {} # and so on ``` What is the pythonic way to do this? note, that i input the principal.. but what i want is the amount.. So if all the three keys are there.. add principal to the previous amount! Thanks
2012/08/28
[ "https://Stackoverflow.com/questions/12167192", "https://Stackoverflow.com", "https://Stackoverflow.com/users/902885/" ]
You may want to consider using [`defaultdict`](http://docs.python.org/library/collections.html): For example: ``` json_dict = defaultdict(lambda: defaultdict(dict)) ``` will create a `defaultdict` of `defaultdict`s of `dict`s (I know..but it is right), to access it, you can simply do: ``` json_dict['context']['name']['id'] = '42' ``` without having to resort to using `if...else` to initialize.
You can make a simple dictionary that creates new ones (using [Autovivification](http://en.wikipedia.org/wiki/Autovivification)): ``` >>> class AutoDict(dict): def __missing__(self, key): x = AutoDict() self[key] = x return x >>> d = AutoDict() >>> d[1][2][3] = 4 >>> d {1: {2: {3: 4}}} ``` This will have no limit of dimensions as the defaultdict with dict has. Or a simpler version using `defaultdict` (from the above wiki link): ``` def auto_dict(): return defaultdict(auto_dict) ```
12,167,192
I want to create a dict which can be accessed as: ``` d[id_1][id_2][id_3] = amount ``` As of now I have a huge ugly function: ``` def parse_dict(id1,id2,id3,principal, data_dict): if data_dict.has_key(id1): values = data_dict[id1] if values.has_key[id2] .. else: inner_inner_dict = {} # and so on ``` What is the pythonic way to do this? note, that i input the principal.. but what i want is the amount.. So if all the three keys are there.. add principal to the previous amount! Thanks
2012/08/28
[ "https://Stackoverflow.com/questions/12167192", "https://Stackoverflow.com", "https://Stackoverflow.com/users/902885/" ]
You may want to consider using [`defaultdict`](http://docs.python.org/library/collections.html): For example: ``` json_dict = defaultdict(lambda: defaultdict(dict)) ``` will create a `defaultdict` of `defaultdict`s of `dict`s (I know..but it is right), to access it, you can simply do: ``` json_dict['context']['name']['id'] = '42' ``` without having to resort to using `if...else` to initialize.
``` >>> from collections import defaultdict >>> import json >>> def tree(): return defaultdict(tree) >>> t = tree() >>> t['a']['b']['c'] = 'foo' >>> t['a']['b']['d'] = 'bar' >>> json.dumps(t) '{"a": {"b": {"c": "foo", "d": "bar"}}}' ```
12,167,192
I want to create a dict which can be accessed as: ``` d[id_1][id_2][id_3] = amount ``` As of now I have a huge ugly function: ``` def parse_dict(id1,id2,id3,principal, data_dict): if data_dict.has_key(id1): values = data_dict[id1] if values.has_key[id2] .. else: inner_inner_dict = {} # and so on ``` What is the pythonic way to do this? note, that i input the principal.. but what i want is the amount.. So if all the three keys are there.. add principal to the previous amount! Thanks
2012/08/28
[ "https://Stackoverflow.com/questions/12167192", "https://Stackoverflow.com", "https://Stackoverflow.com/users/902885/" ]
``` from collections import defaultdict d = defaultdict(lambda : defaultdict(dict)) d[id_1][id_2][id_3] = amount ```
Maybe you need to have a look at multi-dimensional arrays - for example in numpy: <http://docs.scipy.org/doc/numpy/reference/arrays.ndarray.html>
12,167,192
I want to create a dict which can be accessed as: ``` d[id_1][id_2][id_3] = amount ``` As of now I have a huge ugly function: ``` def parse_dict(id1,id2,id3,principal, data_dict): if data_dict.has_key(id1): values = data_dict[id1] if values.has_key[id2] .. else: inner_inner_dict = {} # and so on ``` What is the pythonic way to do this? note, that i input the principal.. but what i want is the amount.. So if all the three keys are there.. add principal to the previous amount! Thanks
2012/08/28
[ "https://Stackoverflow.com/questions/12167192", "https://Stackoverflow.com", "https://Stackoverflow.com/users/902885/" ]
You can make a simple dictionary that creates new ones (using [Autovivification](http://en.wikipedia.org/wiki/Autovivification)): ``` >>> class AutoDict(dict): def __missing__(self, key): x = AutoDict() self[key] = x return x >>> d = AutoDict() >>> d[1][2][3] = 4 >>> d {1: {2: {3: 4}}} ``` This will have no limit of dimensions as the defaultdict with dict has. Or a simpler version using `defaultdict` (from the above wiki link): ``` def auto_dict(): return defaultdict(auto_dict) ```
Maybe you need to have a look at multi-dimensional arrays - for example in numpy: <http://docs.scipy.org/doc/numpy/reference/arrays.ndarray.html>
12,167,192
I want to create a dict which can be accessed as: ``` d[id_1][id_2][id_3] = amount ``` As of now I have a huge ugly function: ``` def parse_dict(id1,id2,id3,principal, data_dict): if data_dict.has_key(id1): values = data_dict[id1] if values.has_key[id2] .. else: inner_inner_dict = {} # and so on ``` What is the pythonic way to do this? note, that i input the principal.. but what i want is the amount.. So if all the three keys are there.. add principal to the previous amount! Thanks
2012/08/28
[ "https://Stackoverflow.com/questions/12167192", "https://Stackoverflow.com", "https://Stackoverflow.com/users/902885/" ]
``` >>> from collections import defaultdict >>> import json >>> def tree(): return defaultdict(tree) >>> t = tree() >>> t['a']['b']['c'] = 'foo' >>> t['a']['b']['d'] = 'bar' >>> json.dumps(t) '{"a": {"b": {"c": "foo", "d": "bar"}}}' ```
Maybe you need to have a look at multi-dimensional arrays - for example in numpy: <http://docs.scipy.org/doc/numpy/reference/arrays.ndarray.html>
50,552,153
I have used the following code to find the last digit of sum of fibonacci numbers ``` #using python3 def fibonacci_sum(n): if n < 2: print(n) else: a, b = 0, 1 sum=1 for i in range(1,n): a, b = b, (a+b) sum=sum+b lastdigit=(sum)%10 print(lastdigit) n = int(input("")); fibonacci_sum(n); ``` My code is working fine. But for a larger given input like 613455 it takes much more time. I need an efficient code. Can anyone help me with this.
2018/05/27
[ "https://Stackoverflow.com/questions/50552153", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5405806/" ]
Keeping track of the last digit only ==================================== Note that whenever you add integers, the last digit of the sum depends only on the last digits of the addents. This means we only have to keep the last digit on every iteration. The same applies to the sum, at all time we only need to keep its last digit. ``` def fibonacci_last_digit_sum(n): sum_, a, b = 0, 0, 1 for _ in range(n): a, b = b, (a + b) % 10 sum_ = (sum_ + b) % 10 return sum_ print(fibonacci_last_digit_sum(613455)) # 2 ``` The above yields a cyclic result ================================ Any triple `(a, b, sum_)` entirely defines the next elements in the sequence. But since we are keeping track solely of the last digit, then there are finitely many such triples. This means that the sequence of triples `(a, b, sum_)` must be cyclic, it comes back to the same value at some point. In particular, a gross upper bound for the length of this cycle is `1000`. This means we can easily check empirically what the length of that cycle is with this updated version of our code. ``` def fibonacci_last_digit_sum(n): sum_, a, b = 0, 0, 1 for _ in range(n): a, b = b, (a + b) % 10 sum_ = (sum_ + b) % 10 return a, b, sum_ seen = set() for x in range(1000): triple = fibonacci_last_digit_sum(x) if triple in seen: print('Back to start:', x) break seen.add(triple) ``` Output: ``` Back to start: 60 ``` In other words, the cycle is of length `60`. This means for any `n`, the answer will be the same as for `n % 60`. This allows to write a solution which run-time depends only on the modulo operation `n % 60`, [which is *O(log(n))*](https://math.stackexchange.com/questions/320420/time-complexity-of-a-modulo-operation). ``` def fibonacci_last_digit_sum(n): sum_, a, b = 0, 0, 1 for _ in range(n % 60): # We range over n % 60 instead of n a, b = b, (a + b) % 10 sum_ = (sum_ + b) % 10 return sum_ print(fibonacci_last_digit_sum(613455)) # 2 ``` One last improvement would be to hardcode the cycle in a list, as it is relatively short, and return the value at index `n % 60`.
You're asking for code that returns the last digit of the sum of the first n Fibonacci numbers. First thing to note is that fib(1) + fib(2) + ... + fib(n) = fib(n+2)-1. That's easily proved: Let S(n) be the sum of the first n Fibonacci numbers. Then S(1) = 1, S(2) = 2, and S(n) - S(n-1) = fib(n). The result follows by induction. Second, modulo 2, the Fibonacci numbers repeat on a cycle of length 3, and modulo 5, the Fibonacci numbers repeat on a cycle of length 20. [See the wikipedia page on the Pisano period](https://en.wikipedia.org/wiki/Pisano_period). This gives us an O(1) solution using the above and the [Chinese Remainder Theorem](https://en.wikipedia.org/wiki/Chinese_remainder_theorem) ``` f2 = [0,1,1] f5 = [0,1,1,2,3,0,3,3,1,4,0,4,4,3,2,0,2,2,4,1] def f1(n): y = f5[(n+2) % 20] return (y-1)%10 if y%2==f2[(n+2)%3] else y+4 cases = [1, 2, 100, 12334, 1234567] for i in cases: print(i, f1(i)) ```
63,559,190
I am trying to loop through the files in a folder with python. I have found different ways to do that such as using os package or glob. But for some reason, they don't maintain the order the files appear in the folder. For example, my folder has `img_10`, `img_20`, `img_30`... But when i loop through them, my code reads the files like: `img_30`, `img_10`, `img_50`... and so on. I would like my program to read the files as they appear in the folder, maintaining the sequence they are in.
2020/08/24
[ "https://Stackoverflow.com/questions/63559190", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11446390/" ]
You need to pass the data in an `array`(`->with()` method) or you can use `compact` method too. ```php return view('admin.faq.index', compact('faqs')); ``` Or ```php return view('admin.faq.index')->with(array('faqs'=>$faqs)); ```
try to use the `compact` method as below: ``` public function index(Request $request) { $faqs = Faq::all(); return view('admin.faq.index',compact('faqs')); } ```
63,559,190
I am trying to loop through the files in a folder with python. I have found different ways to do that such as using os package or glob. But for some reason, they don't maintain the order the files appear in the folder. For example, my folder has `img_10`, `img_20`, `img_30`... But when i loop through them, my code reads the files like: `img_30`, `img_10`, `img_50`... and so on. I would like my program to read the files as they appear in the folder, maintaining the sequence they are in.
2020/08/24
[ "https://Stackoverflow.com/questions/63559190", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11446390/" ]
try to use the `compact` method as below: ``` public function index(Request $request) { $faqs = Faq::all(); return view('admin.faq.index',compact('faqs')); } ```
Looks like $faqs is empty. You can check that with @isset(). <https://laravel.com/docs/7.x/blade#if-statements>
63,559,190
I am trying to loop through the files in a folder with python. I have found different ways to do that such as using os package or glob. But for some reason, they don't maintain the order the files appear in the folder. For example, my folder has `img_10`, `img_20`, `img_30`... But when i loop through them, my code reads the files like: `img_30`, `img_10`, `img_50`... and so on. I would like my program to read the files as they appear in the folder, maintaining the sequence they are in.
2020/08/24
[ "https://Stackoverflow.com/questions/63559190", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11446390/" ]
You need to pass the data in an `array`(`->with()` method) or you can use `compact` method too. ```php return view('admin.faq.index', compact('faqs')); ``` Or ```php return view('admin.faq.index')->with(array('faqs'=>$faqs)); ```
Looks like $faqs is empty. You can check that with @isset(). <https://laravel.com/docs/7.x/blade#if-statements>
36,177,019
Okays so I'm new to python and I just really need some help with this. This is my code so far. I keep getting a syntax error and I have no idea what im doing wrong ``` count = int(input("What number do you want the timer to start: ")) count == ">" -1: print("count") print("") count = count - 1 time.sleep(1) ```
2016/03/23
[ "https://Stackoverflow.com/questions/36177019", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5970976/" ]
You need to ensure you import the time library before you can access the time.sleep method. Also it may be more effective to a for use a loop to repeat code. The structure of your if statement is also incorrect and is not a correct expression. ``` IF <Expression> is TRUE: DO THIS. ``` Also consider using a range within your for loop see below; ``` import time count = int(input("What number do you want the timer to start: ")) for countdown in range(count,0,-1): print (countdown) time.sleep(1) ``` Explanation; ``` for countdown in range(count,0,-1): ``` range (starting point, end point, step) . Starts at your given integer, ends at 0, steps by -1 every iteration.
In the 2nd line, you can't deduct 1 from ">" which is a string. What you need here is apparently a for loop. EDIT: You forgot the import too! ``` import time count = int(input("What number do you want the timer to start: ")) for i in range(count): print("count") print(i) count = count - 1 time.sleep(1) ```
36,177,019
Okays so I'm new to python and I just really need some help with this. This is my code so far. I keep getting a syntax error and I have no idea what im doing wrong ``` count = int(input("What number do you want the timer to start: ")) count == ">" -1: print("count") print("") count = count - 1 time.sleep(1) ```
2016/03/23
[ "https://Stackoverflow.com/questions/36177019", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5970976/" ]
You need to ensure you import the time library before you can access the time.sleep method. Also it may be more effective to a for use a loop to repeat code. The structure of your if statement is also incorrect and is not a correct expression. ``` IF <Expression> is TRUE: DO THIS. ``` Also consider using a range within your for loop see below; ``` import time count = int(input("What number do you want the timer to start: ")) for countdown in range(count,0,-1): print (countdown) time.sleep(1) ``` Explanation; ``` for countdown in range(count,0,-1): ``` range (starting point, end point, step) . Starts at your given integer, ends at 0, steps by -1 every iteration.
The syntax error presumably comes from the line that reads ``` count == ">" -1: ``` I'm not sure where you got that from! What you need is a *loop* that stops when the counter runs out, and otherwise repeats the same code. ``` count = int(input("What number do you want the timer to start: ")) while count > 0: print("count", count) print("") count = count - 1 time.sleep(1) ``` You could also replace `count = count -1` with `count -= 1` but that won't make any difference to the operation of the code.
36,177,019
Okays so I'm new to python and I just really need some help with this. This is my code so far. I keep getting a syntax error and I have no idea what im doing wrong ``` count = int(input("What number do you want the timer to start: ")) count == ">" -1: print("count") print("") count = count - 1 time.sleep(1) ```
2016/03/23
[ "https://Stackoverflow.com/questions/36177019", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5970976/" ]
You need to ensure you import the time library before you can access the time.sleep method. Also it may be more effective to a for use a loop to repeat code. The structure of your if statement is also incorrect and is not a correct expression. ``` IF <Expression> is TRUE: DO THIS. ``` Also consider using a range within your for loop see below; ``` import time count = int(input("What number do you want the timer to start: ")) for countdown in range(count,0,-1): print (countdown) time.sleep(1) ``` Explanation; ``` for countdown in range(count,0,-1): ``` range (starting point, end point, step) . Starts at your given integer, ends at 0, steps by -1 every iteration.
First, you must `import time` in order to use the `time.sleep()` function Next, I'm not too sure what you mean by: > > `count == ">" -1:` > > > If you're creating a "stopwatch", then it would be logical to use some sort of a loop: ``` while count > 0: print(count,"seconds left") count -= 1 time.sleep(1) print ("Finished") ``` That should work fine.
36,177,019
Okays so I'm new to python and I just really need some help with this. This is my code so far. I keep getting a syntax error and I have no idea what im doing wrong ``` count = int(input("What number do you want the timer to start: ")) count == ">" -1: print("count") print("") count = count - 1 time.sleep(1) ```
2016/03/23
[ "https://Stackoverflow.com/questions/36177019", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5970976/" ]
You need to ensure you import the time library before you can access the time.sleep method. Also it may be more effective to a for use a loop to repeat code. The structure of your if statement is also incorrect and is not a correct expression. ``` IF <Expression> is TRUE: DO THIS. ``` Also consider using a range within your for loop see below; ``` import time count = int(input("What number do you want the timer to start: ")) for countdown in range(count,0,-1): print (countdown) time.sleep(1) ``` Explanation; ``` for countdown in range(count,0,-1): ``` range (starting point, end point, step) . Starts at your given integer, ends at 0, steps by -1 every iteration.
There is a syntax error in your second line. I am not sure what you are trying to achieve there. Probably you want to check if count>-1. do this: ``` import time count = int(input("What number do you want the timer to start: ")) if count>0: while(count): print(count) time.sleep(1) count = count -1 ```
52,008,168
I have this python code that should make a video: ``` import cv2 import numpy as np out = cv2.VideoWriter("/tmp/test.mp4", cv2.VideoWriter_fourcc(*'MP4V'), 25, (500, 500), True) data = np.zeros((500,500,3)) for i in xrange(500): out.write(data) out.release() ``` I expect a black video but the code throws an assertion error: ``` $ python test.py OpenCV(3.4.1) Error: Assertion failed (image->depth == 8) in writeFrame, file /io/opencv/modules/videoio/src/cap_ffmpeg.cpp, line 274 Traceback (most recent call last): File "test.py", line 11, in <module> out.write(data) cv2.error: OpenCV(3.4.1) /io/opencv/modules/videoio/src/cap_ffmpeg.cpp:274: error: (-215) image->depth == 8 in function writeFrame ``` I tried various fourcc values but none seem to work.
2018/08/24
[ "https://Stackoverflow.com/questions/52008168", "https://Stackoverflow.com", "https://Stackoverflow.com/users/325809/" ]
So it looks like you did a DBinspect on an existing database to generate this model. I'm guessing this is failing because Django ORM expects your table to have a primary key. "id" is the default name for a Django generated model primary key field. I suspect when you are trying to call `Characterweapons.objects.all()` it's trying to get the primary key field for some reason. There may be a workaround but unless you *really* know what your doing with your database, I would highly urge you to set a primary key on your tables.
The best solution that I found, in this case, was to perform my own query, for example: ``` fact = MyModelWithoutPK.objects.raw("SELECT * FROM my_model_without_pk WHERE my_search=some_search") ``` This way you don't have to implement or add another middleware. see more at [Django docs](https://docs.djangoproject.com/en/2.2/topics/db/sql/)
7,772,965
I'm trying to install the Python M2Crypto package into a virtualenv on an x86\_64 RHEL 6.1 machine. This process invokes swig, which fails with the following error: ``` $ virtualenv -q --no-site-packages venv $ pip install -E venv M2Crypto==0.20.2 Downloading/unpacking M2Crypto==0.20.2 Downloading M2Crypto-0.20.2.tar.gz (412Kb): 412Kb downloaded Running setup.py egg_info for package M2Crypto Installing collected packages: M2Crypto Running setup.py install for M2Crypto building 'M2Crypto.__m2crypto' extension swigging SWIG/_m2crypto.i to SWIG/_m2crypto_wrap.c swig -python -I/usr/include/python2.6 -I/usr/include -includeall -o SWIG/_m2crypto_wrap.c SWIG/_m2crypto.i /usr/include/openssl/opensslconf.h:31: Error: CPP #error ""This openssl-devel package does not work your architecture?"". Use the -cpperraswarn option to continue swig processing. error: command 'swig' failed with exit status 1 Complete output from command /home/lorin/venv/bin/python -c "import setuptools;__file__='/home/lorin/venv/build/M2Crypto/setup.py';exec(compile(open(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --single-version-externally-managed --record /tmp/pip-BFiNtU-record/install-record.txt --install-headers /home/lorin/venv/include/site/python2.6: ``` I've got OpenSSL 1.0.0 installed via RPM packages from RedHat. The part of /usr/include/openssl/opensslconf.h that causes the error looks like this: ``` #if defined(__i386__) #include "opensslconf-i386.h" #elif defined(__ia64__) #include "opensslconf-ia64.h" #elif defined(__powerpc64__) #include "opensslconf-ppc64.h" #elif defined(__powerpc__) #include "opensslconf-ppc.h" #elif defined(__s390x__) #include "opensslconf-s390x.h" #elif defined(__s390__) #include "opensslconf-s390.h" #elif defined(__sparc__) && defined(__arch64__) #include "opensslconf-sparc64.h" #elif defined(__sparc__) #include "opensslconf-sparc.h" #elif defined(__x86_64__) #include "opensslconf-x86_64.h" #else #error "This openssl-devel package does not work your architecture?" #endif ``` gcc has the right variable defined: ``` $ echo | gcc -E -dM - | grep x86_64 #define __x86_64 1 #define __x86_64__ 1 ``` But apparenty swig doesn't, since this is the line that's failing: ``` swig -python -I/usr/include/python2.6 -I/usr/include -includeall -o \ SWIG/_m2crypto_wrap.c SWIG/_m2crypto.i ``` Is there a way to fix this by changing something in my system configuration? M2Crypto gets installed in a virtualenv as part of a larger script I don't control, so avoiding mucking around with the M2Crypto files would be a good thing.
2011/10/14
[ "https://Stackoverflow.com/questions/7772965", "https://Stackoverflow.com", "https://Stackoverflow.com/users/742/" ]
You just don't have `swig` installed. **Try:** ``` sudo yum install swig ``` **And then:** ``` sudo easy_install M2crypto ```
``` sudo yum install m2crypto ``` worked for me to get around this problem.
7,772,965
I'm trying to install the Python M2Crypto package into a virtualenv on an x86\_64 RHEL 6.1 machine. This process invokes swig, which fails with the following error: ``` $ virtualenv -q --no-site-packages venv $ pip install -E venv M2Crypto==0.20.2 Downloading/unpacking M2Crypto==0.20.2 Downloading M2Crypto-0.20.2.tar.gz (412Kb): 412Kb downloaded Running setup.py egg_info for package M2Crypto Installing collected packages: M2Crypto Running setup.py install for M2Crypto building 'M2Crypto.__m2crypto' extension swigging SWIG/_m2crypto.i to SWIG/_m2crypto_wrap.c swig -python -I/usr/include/python2.6 -I/usr/include -includeall -o SWIG/_m2crypto_wrap.c SWIG/_m2crypto.i /usr/include/openssl/opensslconf.h:31: Error: CPP #error ""This openssl-devel package does not work your architecture?"". Use the -cpperraswarn option to continue swig processing. error: command 'swig' failed with exit status 1 Complete output from command /home/lorin/venv/bin/python -c "import setuptools;__file__='/home/lorin/venv/build/M2Crypto/setup.py';exec(compile(open(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --single-version-externally-managed --record /tmp/pip-BFiNtU-record/install-record.txt --install-headers /home/lorin/venv/include/site/python2.6: ``` I've got OpenSSL 1.0.0 installed via RPM packages from RedHat. The part of /usr/include/openssl/opensslconf.h that causes the error looks like this: ``` #if defined(__i386__) #include "opensslconf-i386.h" #elif defined(__ia64__) #include "opensslconf-ia64.h" #elif defined(__powerpc64__) #include "opensslconf-ppc64.h" #elif defined(__powerpc__) #include "opensslconf-ppc.h" #elif defined(__s390x__) #include "opensslconf-s390x.h" #elif defined(__s390__) #include "opensslconf-s390.h" #elif defined(__sparc__) && defined(__arch64__) #include "opensslconf-sparc64.h" #elif defined(__sparc__) #include "opensslconf-sparc.h" #elif defined(__x86_64__) #include "opensslconf-x86_64.h" #else #error "This openssl-devel package does not work your architecture?" #endif ``` gcc has the right variable defined: ``` $ echo | gcc -E -dM - | grep x86_64 #define __x86_64 1 #define __x86_64__ 1 ``` But apparenty swig doesn't, since this is the line that's failing: ``` swig -python -I/usr/include/python2.6 -I/usr/include -includeall -o \ SWIG/_m2crypto_wrap.c SWIG/_m2crypto.i ``` Is there a way to fix this by changing something in my system configuration? M2Crypto gets installed in a virtualenv as part of a larger script I don't control, so avoiding mucking around with the M2Crypto files would be a good thing.
2011/10/14
[ "https://Stackoverflow.com/questions/7772965", "https://Stackoverflow.com", "https://Stackoverflow.com/users/742/" ]
You just don't have `swig` installed. **Try:** ``` sudo yum install swig ``` **And then:** ``` sudo easy_install M2crypto ```
It seems like not having swig is the problem, as @LeoC said. For those on MacOS, I'd recommend downloading swig via a package manager like homebrew because it's cleaner. I.e. you'd run ```html brew install swig ```
7,772,965
I'm trying to install the Python M2Crypto package into a virtualenv on an x86\_64 RHEL 6.1 machine. This process invokes swig, which fails with the following error: ``` $ virtualenv -q --no-site-packages venv $ pip install -E venv M2Crypto==0.20.2 Downloading/unpacking M2Crypto==0.20.2 Downloading M2Crypto-0.20.2.tar.gz (412Kb): 412Kb downloaded Running setup.py egg_info for package M2Crypto Installing collected packages: M2Crypto Running setup.py install for M2Crypto building 'M2Crypto.__m2crypto' extension swigging SWIG/_m2crypto.i to SWIG/_m2crypto_wrap.c swig -python -I/usr/include/python2.6 -I/usr/include -includeall -o SWIG/_m2crypto_wrap.c SWIG/_m2crypto.i /usr/include/openssl/opensslconf.h:31: Error: CPP #error ""This openssl-devel package does not work your architecture?"". Use the -cpperraswarn option to continue swig processing. error: command 'swig' failed with exit status 1 Complete output from command /home/lorin/venv/bin/python -c "import setuptools;__file__='/home/lorin/venv/build/M2Crypto/setup.py';exec(compile(open(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --single-version-externally-managed --record /tmp/pip-BFiNtU-record/install-record.txt --install-headers /home/lorin/venv/include/site/python2.6: ``` I've got OpenSSL 1.0.0 installed via RPM packages from RedHat. The part of /usr/include/openssl/opensslconf.h that causes the error looks like this: ``` #if defined(__i386__) #include "opensslconf-i386.h" #elif defined(__ia64__) #include "opensslconf-ia64.h" #elif defined(__powerpc64__) #include "opensslconf-ppc64.h" #elif defined(__powerpc__) #include "opensslconf-ppc.h" #elif defined(__s390x__) #include "opensslconf-s390x.h" #elif defined(__s390__) #include "opensslconf-s390.h" #elif defined(__sparc__) && defined(__arch64__) #include "opensslconf-sparc64.h" #elif defined(__sparc__) #include "opensslconf-sparc.h" #elif defined(__x86_64__) #include "opensslconf-x86_64.h" #else #error "This openssl-devel package does not work your architecture?" #endif ``` gcc has the right variable defined: ``` $ echo | gcc -E -dM - | grep x86_64 #define __x86_64 1 #define __x86_64__ 1 ``` But apparenty swig doesn't, since this is the line that's failing: ``` swig -python -I/usr/include/python2.6 -I/usr/include -includeall -o \ SWIG/_m2crypto_wrap.c SWIG/_m2crypto.i ``` Is there a way to fix this by changing something in my system configuration? M2Crypto gets installed in a virtualenv as part of a larger script I don't control, so avoiding mucking around with the M2Crypto files would be a good thing.
2011/10/14
[ "https://Stackoverflow.com/questions/7772965", "https://Stackoverflow.com", "https://Stackoverflow.com/users/742/" ]
There's a repository where "pip install" works: <https://github.com/martinpaljak/M2Crypto>
It seems like not having swig is the problem, as @LeoC said. For those on MacOS, I'd recommend downloading swig via a package manager like homebrew because it's cleaner. I.e. you'd run ```html brew install swig ```
7,772,965
I'm trying to install the Python M2Crypto package into a virtualenv on an x86\_64 RHEL 6.1 machine. This process invokes swig, which fails with the following error: ``` $ virtualenv -q --no-site-packages venv $ pip install -E venv M2Crypto==0.20.2 Downloading/unpacking M2Crypto==0.20.2 Downloading M2Crypto-0.20.2.tar.gz (412Kb): 412Kb downloaded Running setup.py egg_info for package M2Crypto Installing collected packages: M2Crypto Running setup.py install for M2Crypto building 'M2Crypto.__m2crypto' extension swigging SWIG/_m2crypto.i to SWIG/_m2crypto_wrap.c swig -python -I/usr/include/python2.6 -I/usr/include -includeall -o SWIG/_m2crypto_wrap.c SWIG/_m2crypto.i /usr/include/openssl/opensslconf.h:31: Error: CPP #error ""This openssl-devel package does not work your architecture?"". Use the -cpperraswarn option to continue swig processing. error: command 'swig' failed with exit status 1 Complete output from command /home/lorin/venv/bin/python -c "import setuptools;__file__='/home/lorin/venv/build/M2Crypto/setup.py';exec(compile(open(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --single-version-externally-managed --record /tmp/pip-BFiNtU-record/install-record.txt --install-headers /home/lorin/venv/include/site/python2.6: ``` I've got OpenSSL 1.0.0 installed via RPM packages from RedHat. The part of /usr/include/openssl/opensslconf.h that causes the error looks like this: ``` #if defined(__i386__) #include "opensslconf-i386.h" #elif defined(__ia64__) #include "opensslconf-ia64.h" #elif defined(__powerpc64__) #include "opensslconf-ppc64.h" #elif defined(__powerpc__) #include "opensslconf-ppc.h" #elif defined(__s390x__) #include "opensslconf-s390x.h" #elif defined(__s390__) #include "opensslconf-s390.h" #elif defined(__sparc__) && defined(__arch64__) #include "opensslconf-sparc64.h" #elif defined(__sparc__) #include "opensslconf-sparc.h" #elif defined(__x86_64__) #include "opensslconf-x86_64.h" #else #error "This openssl-devel package does not work your architecture?" #endif ``` gcc has the right variable defined: ``` $ echo | gcc -E -dM - | grep x86_64 #define __x86_64 1 #define __x86_64__ 1 ``` But apparenty swig doesn't, since this is the line that's failing: ``` swig -python -I/usr/include/python2.6 -I/usr/include -includeall -o \ SWIG/_m2crypto_wrap.c SWIG/_m2crypto.i ``` Is there a way to fix this by changing something in my system configuration? M2Crypto gets installed in a virtualenv as part of a larger script I don't control, so avoiding mucking around with the M2Crypto files would be a good thing.
2011/10/14
[ "https://Stackoverflow.com/questions/7772965", "https://Stackoverflow.com", "https://Stackoverflow.com/users/742/" ]
I had a similar issue where `/usr/include/openssl` was missing `opensslconf.h` (source <https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=733644#10>) ```bash sudo ln -s /usr/include/x86_64-linux-gnu/openssl/opensslconf.h /usr/include/openssl ```
I found a new way to fix this problem in centos5.8, try it. `vim setup.py` ``` def finalize_options(self): ... self.swig_opts.append('-includeall') # after this line self.swig_opts.append('-I/usr/include/openssl') # add here ``` then `python setup.py install` will work.
7,772,965
I'm trying to install the Python M2Crypto package into a virtualenv on an x86\_64 RHEL 6.1 machine. This process invokes swig, which fails with the following error: ``` $ virtualenv -q --no-site-packages venv $ pip install -E venv M2Crypto==0.20.2 Downloading/unpacking M2Crypto==0.20.2 Downloading M2Crypto-0.20.2.tar.gz (412Kb): 412Kb downloaded Running setup.py egg_info for package M2Crypto Installing collected packages: M2Crypto Running setup.py install for M2Crypto building 'M2Crypto.__m2crypto' extension swigging SWIG/_m2crypto.i to SWIG/_m2crypto_wrap.c swig -python -I/usr/include/python2.6 -I/usr/include -includeall -o SWIG/_m2crypto_wrap.c SWIG/_m2crypto.i /usr/include/openssl/opensslconf.h:31: Error: CPP #error ""This openssl-devel package does not work your architecture?"". Use the -cpperraswarn option to continue swig processing. error: command 'swig' failed with exit status 1 Complete output from command /home/lorin/venv/bin/python -c "import setuptools;__file__='/home/lorin/venv/build/M2Crypto/setup.py';exec(compile(open(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --single-version-externally-managed --record /tmp/pip-BFiNtU-record/install-record.txt --install-headers /home/lorin/venv/include/site/python2.6: ``` I've got OpenSSL 1.0.0 installed via RPM packages from RedHat. The part of /usr/include/openssl/opensslconf.h that causes the error looks like this: ``` #if defined(__i386__) #include "opensslconf-i386.h" #elif defined(__ia64__) #include "opensslconf-ia64.h" #elif defined(__powerpc64__) #include "opensslconf-ppc64.h" #elif defined(__powerpc__) #include "opensslconf-ppc.h" #elif defined(__s390x__) #include "opensslconf-s390x.h" #elif defined(__s390__) #include "opensslconf-s390.h" #elif defined(__sparc__) && defined(__arch64__) #include "opensslconf-sparc64.h" #elif defined(__sparc__) #include "opensslconf-sparc.h" #elif defined(__x86_64__) #include "opensslconf-x86_64.h" #else #error "This openssl-devel package does not work your architecture?" #endif ``` gcc has the right variable defined: ``` $ echo | gcc -E -dM - | grep x86_64 #define __x86_64 1 #define __x86_64__ 1 ``` But apparenty swig doesn't, since this is the line that's failing: ``` swig -python -I/usr/include/python2.6 -I/usr/include -includeall -o \ SWIG/_m2crypto_wrap.c SWIG/_m2crypto.i ``` Is there a way to fix this by changing something in my system configuration? M2Crypto gets installed in a virtualenv as part of a larger script I don't control, so avoiding mucking around with the M2Crypto files would be a good thing.
2011/10/14
[ "https://Stackoverflow.com/questions/7772965", "https://Stackoverflow.com", "https://Stackoverflow.com/users/742/" ]
You just don't have `swig` installed. **Try:** ``` sudo yum install swig ``` **And then:** ``` sudo easy_install M2crypto ```
I had a similar issue where `/usr/include/openssl` was missing `opensslconf.h` (source <https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=733644#10>) ```bash sudo ln -s /usr/include/x86_64-linux-gnu/openssl/opensslconf.h /usr/include/openssl ```
7,772,965
I'm trying to install the Python M2Crypto package into a virtualenv on an x86\_64 RHEL 6.1 machine. This process invokes swig, which fails with the following error: ``` $ virtualenv -q --no-site-packages venv $ pip install -E venv M2Crypto==0.20.2 Downloading/unpacking M2Crypto==0.20.2 Downloading M2Crypto-0.20.2.tar.gz (412Kb): 412Kb downloaded Running setup.py egg_info for package M2Crypto Installing collected packages: M2Crypto Running setup.py install for M2Crypto building 'M2Crypto.__m2crypto' extension swigging SWIG/_m2crypto.i to SWIG/_m2crypto_wrap.c swig -python -I/usr/include/python2.6 -I/usr/include -includeall -o SWIG/_m2crypto_wrap.c SWIG/_m2crypto.i /usr/include/openssl/opensslconf.h:31: Error: CPP #error ""This openssl-devel package does not work your architecture?"". Use the -cpperraswarn option to continue swig processing. error: command 'swig' failed with exit status 1 Complete output from command /home/lorin/venv/bin/python -c "import setuptools;__file__='/home/lorin/venv/build/M2Crypto/setup.py';exec(compile(open(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --single-version-externally-managed --record /tmp/pip-BFiNtU-record/install-record.txt --install-headers /home/lorin/venv/include/site/python2.6: ``` I've got OpenSSL 1.0.0 installed via RPM packages from RedHat. The part of /usr/include/openssl/opensslconf.h that causes the error looks like this: ``` #if defined(__i386__) #include "opensslconf-i386.h" #elif defined(__ia64__) #include "opensslconf-ia64.h" #elif defined(__powerpc64__) #include "opensslconf-ppc64.h" #elif defined(__powerpc__) #include "opensslconf-ppc.h" #elif defined(__s390x__) #include "opensslconf-s390x.h" #elif defined(__s390__) #include "opensslconf-s390.h" #elif defined(__sparc__) && defined(__arch64__) #include "opensslconf-sparc64.h" #elif defined(__sparc__) #include "opensslconf-sparc.h" #elif defined(__x86_64__) #include "opensslconf-x86_64.h" #else #error "This openssl-devel package does not work your architecture?" #endif ``` gcc has the right variable defined: ``` $ echo | gcc -E -dM - | grep x86_64 #define __x86_64 1 #define __x86_64__ 1 ``` But apparenty swig doesn't, since this is the line that's failing: ``` swig -python -I/usr/include/python2.6 -I/usr/include -includeall -o \ SWIG/_m2crypto_wrap.c SWIG/_m2crypto.i ``` Is there a way to fix this by changing something in my system configuration? M2Crypto gets installed in a virtualenv as part of a larger script I don't control, so avoiding mucking around with the M2Crypto files would be a good thing.
2011/10/14
[ "https://Stackoverflow.com/questions/7772965", "https://Stackoverflow.com", "https://Stackoverflow.com/users/742/" ]
M2Crypto supplies a fedora\_setup.sh script to handle the problems with Fedora/RL/CentOs releases, but pip, of course, doesn't know anything about it. After the pip install fails, it leaves the downloaded stuff in the venv/build/M2Crypto directory. do this: ``` cd <path-to-your-venv>/venv/build/M2Crypto chmod u+x fedora_setup.sh ./fedora_setup.sh build ./fedora_setup.sh install ``` This has worked in my install process
I had a similar issue where `/usr/include/openssl` was missing `opensslconf.h` (source <https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=733644#10>) ```bash sudo ln -s /usr/include/x86_64-linux-gnu/openssl/opensslconf.h /usr/include/openssl ```
7,772,965
I'm trying to install the Python M2Crypto package into a virtualenv on an x86\_64 RHEL 6.1 machine. This process invokes swig, which fails with the following error: ``` $ virtualenv -q --no-site-packages venv $ pip install -E venv M2Crypto==0.20.2 Downloading/unpacking M2Crypto==0.20.2 Downloading M2Crypto-0.20.2.tar.gz (412Kb): 412Kb downloaded Running setup.py egg_info for package M2Crypto Installing collected packages: M2Crypto Running setup.py install for M2Crypto building 'M2Crypto.__m2crypto' extension swigging SWIG/_m2crypto.i to SWIG/_m2crypto_wrap.c swig -python -I/usr/include/python2.6 -I/usr/include -includeall -o SWIG/_m2crypto_wrap.c SWIG/_m2crypto.i /usr/include/openssl/opensslconf.h:31: Error: CPP #error ""This openssl-devel package does not work your architecture?"". Use the -cpperraswarn option to continue swig processing. error: command 'swig' failed with exit status 1 Complete output from command /home/lorin/venv/bin/python -c "import setuptools;__file__='/home/lorin/venv/build/M2Crypto/setup.py';exec(compile(open(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --single-version-externally-managed --record /tmp/pip-BFiNtU-record/install-record.txt --install-headers /home/lorin/venv/include/site/python2.6: ``` I've got OpenSSL 1.0.0 installed via RPM packages from RedHat. The part of /usr/include/openssl/opensslconf.h that causes the error looks like this: ``` #if defined(__i386__) #include "opensslconf-i386.h" #elif defined(__ia64__) #include "opensslconf-ia64.h" #elif defined(__powerpc64__) #include "opensslconf-ppc64.h" #elif defined(__powerpc__) #include "opensslconf-ppc.h" #elif defined(__s390x__) #include "opensslconf-s390x.h" #elif defined(__s390__) #include "opensslconf-s390.h" #elif defined(__sparc__) && defined(__arch64__) #include "opensslconf-sparc64.h" #elif defined(__sparc__) #include "opensslconf-sparc.h" #elif defined(__x86_64__) #include "opensslconf-x86_64.h" #else #error "This openssl-devel package does not work your architecture?" #endif ``` gcc has the right variable defined: ``` $ echo | gcc -E -dM - | grep x86_64 #define __x86_64 1 #define __x86_64__ 1 ``` But apparenty swig doesn't, since this is the line that's failing: ``` swig -python -I/usr/include/python2.6 -I/usr/include -includeall -o \ SWIG/_m2crypto_wrap.c SWIG/_m2crypto.i ``` Is there a way to fix this by changing something in my system configuration? M2Crypto gets installed in a virtualenv as part of a larger script I don't control, so avoiding mucking around with the M2Crypto files would be a good thing.
2011/10/14
[ "https://Stackoverflow.com/questions/7772965", "https://Stackoverflow.com", "https://Stackoverflow.com/users/742/" ]
I did this and it works very well : ``` env SWIG_FEATURES="-cpperraswarn -includeall -I/usr/include/openssl" pip install M2Crypto ``` Of course you have to install swigg with `sudo yum install swig` before
``` sudo yum install m2crypto ``` worked for me to get around this problem.
7,772,965
I'm trying to install the Python M2Crypto package into a virtualenv on an x86\_64 RHEL 6.1 machine. This process invokes swig, which fails with the following error: ``` $ virtualenv -q --no-site-packages venv $ pip install -E venv M2Crypto==0.20.2 Downloading/unpacking M2Crypto==0.20.2 Downloading M2Crypto-0.20.2.tar.gz (412Kb): 412Kb downloaded Running setup.py egg_info for package M2Crypto Installing collected packages: M2Crypto Running setup.py install for M2Crypto building 'M2Crypto.__m2crypto' extension swigging SWIG/_m2crypto.i to SWIG/_m2crypto_wrap.c swig -python -I/usr/include/python2.6 -I/usr/include -includeall -o SWIG/_m2crypto_wrap.c SWIG/_m2crypto.i /usr/include/openssl/opensslconf.h:31: Error: CPP #error ""This openssl-devel package does not work your architecture?"". Use the -cpperraswarn option to continue swig processing. error: command 'swig' failed with exit status 1 Complete output from command /home/lorin/venv/bin/python -c "import setuptools;__file__='/home/lorin/venv/build/M2Crypto/setup.py';exec(compile(open(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --single-version-externally-managed --record /tmp/pip-BFiNtU-record/install-record.txt --install-headers /home/lorin/venv/include/site/python2.6: ``` I've got OpenSSL 1.0.0 installed via RPM packages from RedHat. The part of /usr/include/openssl/opensslconf.h that causes the error looks like this: ``` #if defined(__i386__) #include "opensslconf-i386.h" #elif defined(__ia64__) #include "opensslconf-ia64.h" #elif defined(__powerpc64__) #include "opensslconf-ppc64.h" #elif defined(__powerpc__) #include "opensslconf-ppc.h" #elif defined(__s390x__) #include "opensslconf-s390x.h" #elif defined(__s390__) #include "opensslconf-s390.h" #elif defined(__sparc__) && defined(__arch64__) #include "opensslconf-sparc64.h" #elif defined(__sparc__) #include "opensslconf-sparc.h" #elif defined(__x86_64__) #include "opensslconf-x86_64.h" #else #error "This openssl-devel package does not work your architecture?" #endif ``` gcc has the right variable defined: ``` $ echo | gcc -E -dM - | grep x86_64 #define __x86_64 1 #define __x86_64__ 1 ``` But apparenty swig doesn't, since this is the line that's failing: ``` swig -python -I/usr/include/python2.6 -I/usr/include -includeall -o \ SWIG/_m2crypto_wrap.c SWIG/_m2crypto.i ``` Is there a way to fix this by changing something in my system configuration? M2Crypto gets installed in a virtualenv as part of a larger script I don't control, so avoiding mucking around with the M2Crypto files would be a good thing.
2011/10/14
[ "https://Stackoverflow.com/questions/7772965", "https://Stackoverflow.com", "https://Stackoverflow.com/users/742/" ]
M2Crypto supplies a fedora\_setup.sh script to handle the problems with Fedora/RL/CentOs releases, but pip, of course, doesn't know anything about it. After the pip install fails, it leaves the downloaded stuff in the venv/build/M2Crypto directory. do this: ``` cd <path-to-your-venv>/venv/build/M2Crypto chmod u+x fedora_setup.sh ./fedora_setup.sh build ./fedora_setup.sh install ``` This has worked in my install process
It seems like not having swig is the problem, as @LeoC said. For those on MacOS, I'd recommend downloading swig via a package manager like homebrew because it's cleaner. I.e. you'd run ```html brew install swig ```
7,772,965
I'm trying to install the Python M2Crypto package into a virtualenv on an x86\_64 RHEL 6.1 machine. This process invokes swig, which fails with the following error: ``` $ virtualenv -q --no-site-packages venv $ pip install -E venv M2Crypto==0.20.2 Downloading/unpacking M2Crypto==0.20.2 Downloading M2Crypto-0.20.2.tar.gz (412Kb): 412Kb downloaded Running setup.py egg_info for package M2Crypto Installing collected packages: M2Crypto Running setup.py install for M2Crypto building 'M2Crypto.__m2crypto' extension swigging SWIG/_m2crypto.i to SWIG/_m2crypto_wrap.c swig -python -I/usr/include/python2.6 -I/usr/include -includeall -o SWIG/_m2crypto_wrap.c SWIG/_m2crypto.i /usr/include/openssl/opensslconf.h:31: Error: CPP #error ""This openssl-devel package does not work your architecture?"". Use the -cpperraswarn option to continue swig processing. error: command 'swig' failed with exit status 1 Complete output from command /home/lorin/venv/bin/python -c "import setuptools;__file__='/home/lorin/venv/build/M2Crypto/setup.py';exec(compile(open(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --single-version-externally-managed --record /tmp/pip-BFiNtU-record/install-record.txt --install-headers /home/lorin/venv/include/site/python2.6: ``` I've got OpenSSL 1.0.0 installed via RPM packages from RedHat. The part of /usr/include/openssl/opensslconf.h that causes the error looks like this: ``` #if defined(__i386__) #include "opensslconf-i386.h" #elif defined(__ia64__) #include "opensslconf-ia64.h" #elif defined(__powerpc64__) #include "opensslconf-ppc64.h" #elif defined(__powerpc__) #include "opensslconf-ppc.h" #elif defined(__s390x__) #include "opensslconf-s390x.h" #elif defined(__s390__) #include "opensslconf-s390.h" #elif defined(__sparc__) && defined(__arch64__) #include "opensslconf-sparc64.h" #elif defined(__sparc__) #include "opensslconf-sparc.h" #elif defined(__x86_64__) #include "opensslconf-x86_64.h" #else #error "This openssl-devel package does not work your architecture?" #endif ``` gcc has the right variable defined: ``` $ echo | gcc -E -dM - | grep x86_64 #define __x86_64 1 #define __x86_64__ 1 ``` But apparenty swig doesn't, since this is the line that's failing: ``` swig -python -I/usr/include/python2.6 -I/usr/include -includeall -o \ SWIG/_m2crypto_wrap.c SWIG/_m2crypto.i ``` Is there a way to fix this by changing something in my system configuration? M2Crypto gets installed in a virtualenv as part of a larger script I don't control, so avoiding mucking around with the M2Crypto files would be a good thing.
2011/10/14
[ "https://Stackoverflow.com/questions/7772965", "https://Stackoverflow.com", "https://Stackoverflow.com/users/742/" ]
I did this and it works very well : ``` env SWIG_FEATURES="-cpperraswarn -includeall -I/usr/include/openssl" pip install M2Crypto ``` Of course you have to install swigg with `sudo yum install swig` before
It seems like not having swig is the problem, as @LeoC said. For those on MacOS, I'd recommend downloading swig via a package manager like homebrew because it's cleaner. I.e. you'd run ```html brew install swig ```
7,772,965
I'm trying to install the Python M2Crypto package into a virtualenv on an x86\_64 RHEL 6.1 machine. This process invokes swig, which fails with the following error: ``` $ virtualenv -q --no-site-packages venv $ pip install -E venv M2Crypto==0.20.2 Downloading/unpacking M2Crypto==0.20.2 Downloading M2Crypto-0.20.2.tar.gz (412Kb): 412Kb downloaded Running setup.py egg_info for package M2Crypto Installing collected packages: M2Crypto Running setup.py install for M2Crypto building 'M2Crypto.__m2crypto' extension swigging SWIG/_m2crypto.i to SWIG/_m2crypto_wrap.c swig -python -I/usr/include/python2.6 -I/usr/include -includeall -o SWIG/_m2crypto_wrap.c SWIG/_m2crypto.i /usr/include/openssl/opensslconf.h:31: Error: CPP #error ""This openssl-devel package does not work your architecture?"". Use the -cpperraswarn option to continue swig processing. error: command 'swig' failed with exit status 1 Complete output from command /home/lorin/venv/bin/python -c "import setuptools;__file__='/home/lorin/venv/build/M2Crypto/setup.py';exec(compile(open(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --single-version-externally-managed --record /tmp/pip-BFiNtU-record/install-record.txt --install-headers /home/lorin/venv/include/site/python2.6: ``` I've got OpenSSL 1.0.0 installed via RPM packages from RedHat. The part of /usr/include/openssl/opensslconf.h that causes the error looks like this: ``` #if defined(__i386__) #include "opensslconf-i386.h" #elif defined(__ia64__) #include "opensslconf-ia64.h" #elif defined(__powerpc64__) #include "opensslconf-ppc64.h" #elif defined(__powerpc__) #include "opensslconf-ppc.h" #elif defined(__s390x__) #include "opensslconf-s390x.h" #elif defined(__s390__) #include "opensslconf-s390.h" #elif defined(__sparc__) && defined(__arch64__) #include "opensslconf-sparc64.h" #elif defined(__sparc__) #include "opensslconf-sparc.h" #elif defined(__x86_64__) #include "opensslconf-x86_64.h" #else #error "This openssl-devel package does not work your architecture?" #endif ``` gcc has the right variable defined: ``` $ echo | gcc -E -dM - | grep x86_64 #define __x86_64 1 #define __x86_64__ 1 ``` But apparenty swig doesn't, since this is the line that's failing: ``` swig -python -I/usr/include/python2.6 -I/usr/include -includeall -o \ SWIG/_m2crypto_wrap.c SWIG/_m2crypto.i ``` Is there a way to fix this by changing something in my system configuration? M2Crypto gets installed in a virtualenv as part of a larger script I don't control, so avoiding mucking around with the M2Crypto files would be a good thing.
2011/10/14
[ "https://Stackoverflow.com/questions/7772965", "https://Stackoverflow.com", "https://Stackoverflow.com/users/742/" ]
If you are seeing this and are on Ubuntu, use apt-get instead of pip to avoid this issue. `apt-get install python-m2crypto`
On FreeBSD I had to install Swig (the obvious part) as well (by `sudo pkg install swig`), but Swig 2.0 executable was named `swig2.0` and handle `swig` resulted in `command not found`. Solution: symlink Swig 2.0 to handle `swig`: ``` ln -s /usr/local/bin/swig2.0 /usr/local/bin/swig ```
52,733,094
I am using Ubuntu 16.04 lts. My default python binary is python2.7. When I am trying to install ipykernel for hydrogen in atom editor, with the following command ``` python -m pip install ipykernel ``` It is giving the following errors ``` ERROR: ipykernel requires Python version 3.4 or above. ``` I am trying to install ipykernel for python2. I have already installed python3.7. Also ipython and jupyter notebook is installed.
2018/10/10
[ "https://Stackoverflow.com/questions/52733094", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8881054/" ]
Starting with version 5.0 of the [kernel](https://ipykernel.readthedocs.io/en/latest/changelog.html#id3), and version 6.0 of [IPython](https://ipython.readthedocs.io/en/stable/whatsnew/version6.html#ipython-6-0), compatibility with Python 2 was dropped. As far as I know, the only solution is to install an earlier release. In order to have Python 2.7 available in the Jupyter Notebook I installed IPython 5.7, and ipykernel 4.10. If you want to install earlier releases of IPython or ipykernel you can do the following: * Uninstall IPython `pip uninstall ipython` * Reinstall IPython `python2 -m pip install ipython==5.7 --user` * Install ipykernel `python2 -m pip install ipykernel==4.10 --user`
Try using `Anaconda` You can learn how to install Anaconda from [here](https://conda.io/docs/user-guide/install/linux.html) After that, try creating a virtual environment via: ``` conda create -n yourenvname python=2.7 anaconda ``` And activate it via: ``` source activate yourenvname ``` After that, try installing: ``` pip install ipython pip intall ipykernel ```
56,789,173
I have a simple class in which I want to generate methods based on inherited class fields: ``` class Parent: def __init__(self, *args, **kwargs): self.fields = getattr(self, 'TOGGLEABLE') self.generate_methods() def _toggle(self, instance): print(self, instance) # Prints correctly # Here I need to have the caller method, which is: # toggle_following() def generate_methods(self): for field_name in self.fields: setattr(self, f'toggle_{field_name}', self._toggle) class Child(Parent): following = ['a', 'b', 'c'] TOGGLEABLE = ('following',) ``` At this moment, there is a `toggle_following` function successfully generated in `Child`. Then I invoke it with a single parameter: ``` >>> child = Child() >>> child.toggle_following('b') <__main__.Child object at 0x104d21b70> b ``` And it prints out the expected result in the `print` statement. **But I need to receive the caller name `toggle_following` in my generic `_toggle` function.** I've tried using the [`inspect`](https://docs.python.org/3/library/inspect.html) module, but it seems that it has a different purpose regarding function inspection.
2019/06/27
[ "https://Stackoverflow.com/questions/56789173", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5729960/" ]
maybe this is too hackish, and maybe there's a more elegant (i.e. dedicated) way to achieve this, but: you can create a wrapper function that passes the func\_name to the inner `_toggle` func: ```py class Parent: def __init__(self, *args, **kwargs): self.fields = getattr(self, 'TOGGLEABLE') self.generate_methods() def _toggle(self, instance, func_name): print(self, instance) # Prints correctly print(func_name) def generate_methods(self): for field_name in self.fields: func_name = 'toggle_{}'.format(field_name) # I don't have python 3.7 on this computer :P setattr(self, func_name, lambda instance: self._toggle(instance, func_name)) class Child(Parent): following = ['a', 'b', 'c'] TOGGLEABLE = ('following',) child = Child() child.toggle_following('b') ``` Output: ``` <__main__.Child object at 0x7fbe566c0748> b toggle_following ```
Another approach to solve the same problem would be to use `__getattr__` in the following way: ``` class Parent: def _toggle(self, instance, func_name): print(self, instance) # Prints correctly print(func_name) def __getattr__(self, attr): if not attr.startswith("toggle_"): raise AttributeError("Attribute {} not found".format(attr)) tmp = attr.replace("toggle_", "") if tmp not in self.TOGGLEABLE: raise AttributeError( "You cannot toggle the untoggleable {}".format(attr) ) return lambda x: self._toggle(x, attr) class Child(Parent): following = ['a', 'b', 'c'] TOGGLEABLE = ('following',) child = Child() # This can toggle child.toggle_following('b') # This cannot toggle child.toggle_something('b') ``` which yields: ``` (<__main__.Child instance at 0x107a0e290>, 'b') toggle_following Traceback (most recent call last): File "/Users/urban/tmp/test.py", line 26, in <module> child.toggle_something('b') File "/Users/urban/tmp/test.py", line 13, in __getattr__ raise AttributeError("You cannot toggle the untoggleable {}".format(attr)) AttributeError: You cannot toggle the untoggleable toggle_something ```
39,400,319
My opinion of the Azure-Python SDK is not high for Azure RM. What takes 1 line in PowerShell takes 10 in Python. That is the opposite of what python is supposed to do. So, my idea is to create python package which comes with a directory containing a few template .ps1 scripts. You would define a few variables like vmname, resourcegroup, location, etc... inject these into the .ps1 templates, then call commands from the REPL. Right now I'm having trouble using the subprocess module to keep PS open until I tell it to close. As it stands now, I need to include ``` login-azurerm ``` and authenticate before running **any** command. This won't do. I'd like to fix this, but frankly right now I'm wondering whether or not the premise is a good idea to start with. Any input is much appreciated!
2016/09/08
[ "https://Stackoverflow.com/questions/39400319", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6293857/" ]
@RobTruxal, the new CLI for Azure will be in Python and will be released as a preview soon. You can already try it from the github account: <https://github.com/Azure/azure-cli> The Azure SDK for Python is not supposed to mimic the Powershell cmdlets, but to be a language SDK (like C#, Java, Ruby, etc.). If you have any suggestion/comments about the Python SDK itself, please do not hesitate to fill an issue on the issue tracker: <https://github.com/Azure/azure-sdk-for-python/issues> (FYI, I'm the owner of the Python SDK repo at MS)
@RobTruxal, It seems that a feasible way to call PowerShell in Python is using the module `subprocess`, such as the code below as reference. ``` import subprocess subprocess.call(["C:\\WINDOWS\\system32\\WindowsPowerShell\\v1.0\\powershell.exe", "your-script.ps1", "arguments"]) ``` You need to write your powershell script which includes `login-azurerm` command, and interaction with cmd that running python script. Or you can choose the AzureCLI for cross platform in node.js as the command line tool for managing Azure Resoure. Hope it helps.
62,295,329
I'm trying to play an mp3 file using python VLC but it seems like nothing is happening and there is no error message. Below is the code: ``` import vlc p = vlc.MediaPlayer(r"C:\Users\user\Desktop\python\projects\etc\lady_maria.mp3") p.play() ``` I tried below code as I've read from another post: ``` import vlc mp3 = "C:/Users/user/Desktop/python/projects/etc/lady_maria.mp3" instance = vlc.get_default_instance() media = instance.media_new(mp3) media_list = instance.media_list_new([mp3]) player = instance.media_player_new() player.set_media(media) list_player = instance.media_list_player_new() list_player.set_media_player(player) list_player.set_media_list(media_list) ``` I also tried to use pygame mixer but same reason, no sounds, and no error message. ``` from pygame import mixer mixer.init() mixer.music.load(r'C:\Users\user\Desktop\python\projects\etc\lady_maria.mp3') mixer.music.play() ``` All of these do not give an error message so I'm not sure what is going on.. Any advice will be greatly appreciated!
2020/06/10
[ "https://Stackoverflow.com/questions/62295329", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11639529/" ]
If audio files are playing fine on the system:- for pygame library adjust volume using: ``` mixer.music.set_volume(1.0) # float value from 0.0 to 1.0 for volume setting ```
I can't work out what the actual issue is given the code in the OP. Please try this test code. ``` import pygame WINDOW_WIDTH = 200 WINDOW_HEIGHT = 200 ### initialisation pygame.init() pygame.font.init() pygame.mixer.init() window = pygame.display.set_mode( ( WINDOW_WIDTH, WINDOW_HEIGHT ) ) # Rain sound from: https://www.freesoundslibrary.com/sound-of-rain-falling-mp3/ (CC BY 4.0) pygame.mixer.music.load( 'rain-falling.mp3' ) pygame.mixer.music.play( loops=-1 ) # loop forever ### Main Loop clock = pygame.time.Clock() font = pygame.font.SysFont(None, 40) done = False while not done: # Handle user-input for event in pygame.event.get(): if ( event.type == pygame.QUIT ): done = True # Draw some text window.fill( ( 0, 0, 50 ) ) ms = font.render( str( pygame.time.get_ticks() ), True, ( 255,255,255 ) ) window.blit( ms, ( 100, 100 ) ) pygame.display.flip() # Clamp FPS clock.tick_busy_loop(30) pygame.quit() ``` If you download the MP3 from the link in the source, and running this script produces no sound, the issue is with your local machine setup. In this case perhaps verify you are using a recent version of Python and PyGame. I've tested this with Python 3.8.2 and PyGame 1.9.6. I don't think installing [VLC Media Player](https://www.videolan.org/vlc/) would hurt anything. This is my daily "go-to" media player.
62,295,329
I'm trying to play an mp3 file using python VLC but it seems like nothing is happening and there is no error message. Below is the code: ``` import vlc p = vlc.MediaPlayer(r"C:\Users\user\Desktop\python\projects\etc\lady_maria.mp3") p.play() ``` I tried below code as I've read from another post: ``` import vlc mp3 = "C:/Users/user/Desktop/python/projects/etc/lady_maria.mp3" instance = vlc.get_default_instance() media = instance.media_new(mp3) media_list = instance.media_list_new([mp3]) player = instance.media_player_new() player.set_media(media) list_player = instance.media_list_player_new() list_player.set_media_player(player) list_player.set_media_list(media_list) ``` I also tried to use pygame mixer but same reason, no sounds, and no error message. ``` from pygame import mixer mixer.init() mixer.music.load(r'C:\Users\user\Desktop\python\projects\etc\lady_maria.mp3') mixer.music.play() ``` All of these do not give an error message so I'm not sure what is going on.. Any advice will be greatly appreciated!
2020/06/10
[ "https://Stackoverflow.com/questions/62295329", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11639529/" ]
So the problem was solved as: ``` from pygame import mixer mixer.init() mixer.music.load(r'C:\Users\user\Desktop\python\projects\etc\lady_maria.mp3') mixer.music.play() time.sleep(5) ``` adding `time.sleep(5)` fixed the problem! [Pygame, sounds don't play](https://stackoverflow.com/questions/2936914/pygame-sounds-dont-play)
I can't work out what the actual issue is given the code in the OP. Please try this test code. ``` import pygame WINDOW_WIDTH = 200 WINDOW_HEIGHT = 200 ### initialisation pygame.init() pygame.font.init() pygame.mixer.init() window = pygame.display.set_mode( ( WINDOW_WIDTH, WINDOW_HEIGHT ) ) # Rain sound from: https://www.freesoundslibrary.com/sound-of-rain-falling-mp3/ (CC BY 4.0) pygame.mixer.music.load( 'rain-falling.mp3' ) pygame.mixer.music.play( loops=-1 ) # loop forever ### Main Loop clock = pygame.time.Clock() font = pygame.font.SysFont(None, 40) done = False while not done: # Handle user-input for event in pygame.event.get(): if ( event.type == pygame.QUIT ): done = True # Draw some text window.fill( ( 0, 0, 50 ) ) ms = font.render( str( pygame.time.get_ticks() ), True, ( 255,255,255 ) ) window.blit( ms, ( 100, 100 ) ) pygame.display.flip() # Clamp FPS clock.tick_busy_loop(30) pygame.quit() ``` If you download the MP3 from the link in the source, and running this script produces no sound, the issue is with your local machine setup. In this case perhaps verify you are using a recent version of Python and PyGame. I've tested this with Python 3.8.2 and PyGame 1.9.6. I don't think installing [VLC Media Player](https://www.videolan.org/vlc/) would hurt anything. This is my daily "go-to" media player.
67,109,676
example1.py: ``` from tkinter import * root = Tk() filename = 'james' Lbl = Label(root,text="ciao") Lbl.pack() root.mainloop() ``` example2.py: ``` from example1 import filename print(filename) ``` Why python open tkinter window if I run only example2.py? It is necessary for me that filename is in the example1.py and called from example2.py. I called only filename variable and not a tkinter window in example2.
2021/04/15
[ "https://Stackoverflow.com/questions/67109676", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9811405/" ]
**This is because the standard rules of Python** yup! Python automatically excecutes the Python file which you imported.In Your Case its example1 file. **To prevent This Use this instance:** ``` if __name__ == '__main__': root.mainloop() ``` in your file [see](https://www.geeksforgeeks.org/what-does-the-if-__name__-__main__-do/%3Cbr%3E) **Edit:** And the rest problem is that, You cannot directly import a variable from a file. **You Will have to store it in an function like:** `yourFileName` **So your final code will be** **example1.py** ``` from tkinter import * root = Tk() filename = 'james' Lbl = Label(root,text="ciao") Lbl.pack() def filenamefunc(): return filename if __name__ == '__main__': root.mainloop() ``` **And your example2.py will be** ``` from example1 import filenamefunc print(filenamefunc) ``` **Thank-you**
First, I don't know how to solve your problem. but I know what you want to know. I understand you have two python file ('example 1' and 'example 2'). And you want to import 'filename' from 'example 1'. But Tkinter is worked and you want to know why. right? The import function is not pick-up tool. \*\*\* That's mean you can't get the 'filename' without other data-processing.\*\*\* When you call the import file 'example1', python is run the 'example1' code from beginning to end and get the filename. It's faster to try than to explain. ``` from tkinter import * filename = 'james' print(' before ') root = Tk() Lbl = Label(root,text="ciao") Lbl.pack() root.mainloop() print(' after ') ``` Fix your code like this and run 'example 2'. First,You can see 'before' text in your terminal. And tkinter will be ran and then when you close the tkinter, you can see 'after' text and work your code `print(filename)` example1[filename is saved 'james' >> print 'before' >> run the tkinter mainloop >> print 'after'] >> example2[get filename from example1 >> filename is 'james' >> print(filename)] Anyway, It's the answer about 'why' tkinter is run.
5,249,353
I'm learning python. I have a list of simple entries and I want to convert it in a dictionary where the first element of list is the key of the second element, the third is the key of the fourth, and so on. How can I do it? ``` list = ['first_key', 'first_value', 'second_key', 'second_value'] ``` Thanks in advance!
2011/03/09
[ "https://Stackoverflow.com/questions/5249353", "https://Stackoverflow.com", "https://Stackoverflow.com/users/619378/" ]
``` myDict = dict(zip(myList[::2], myList[1::2])) ``` Please do not use 'list' as a variable name, as it prevents you from accessing the list() function. If there is much data involved, we can do it more efficiently using iterator functions: ``` from itertools import izip, islice myList = ['first_key', 'first_value', 'second_key', 'second_value'] myDict = dict(izip(islice(myList,0,None,2), islice(myList,1,None,2))) ```
The most concise way is ``` some_list = ['first_key', 'first_value', 'second_key', 'second_value'] d = dict(zip(*[iter(some_list)] * 2)) ```
5,249,353
I'm learning python. I have a list of simple entries and I want to convert it in a dictionary where the first element of list is the key of the second element, the third is the key of the fourth, and so on. How can I do it? ``` list = ['first_key', 'first_value', 'second_key', 'second_value'] ``` Thanks in advance!
2011/03/09
[ "https://Stackoverflow.com/questions/5249353", "https://Stackoverflow.com", "https://Stackoverflow.com/users/619378/" ]
The most concise way is ``` some_list = ['first_key', 'first_value', 'second_key', 'second_value'] d = dict(zip(*[iter(some_list)] * 2)) ```
If the list is large, you end up wasting memory by building slices or eager zips. One way to convert the list more lazily is to (ab)use the list iterator and `izip`. ``` from itertools import izip lst = ['first_key', 'first_value', 'second_key', 'second_value'] i = iter(lst) d = dict(izip(i,i)) ```
5,249,353
I'm learning python. I have a list of simple entries and I want to convert it in a dictionary where the first element of list is the key of the second element, the third is the key of the fourth, and so on. How can I do it? ``` list = ['first_key', 'first_value', 'second_key', 'second_value'] ``` Thanks in advance!
2011/03/09
[ "https://Stackoverflow.com/questions/5249353", "https://Stackoverflow.com", "https://Stackoverflow.com/users/619378/" ]
The most concise way is ``` some_list = ['first_key', 'first_value', 'second_key', 'second_value'] d = dict(zip(*[iter(some_list)] * 2)) ```
The KISS way: Use exception and iterators ``` myDict = {} it = iter(list) for x in list: try: myDict[it.next()] = it.next() except: pass myDict ```
5,249,353
I'm learning python. I have a list of simple entries and I want to convert it in a dictionary where the first element of list is the key of the second element, the third is the key of the fourth, and so on. How can I do it? ``` list = ['first_key', 'first_value', 'second_key', 'second_value'] ``` Thanks in advance!
2011/03/09
[ "https://Stackoverflow.com/questions/5249353", "https://Stackoverflow.com", "https://Stackoverflow.com/users/619378/" ]
``` myDict = dict(zip(myList[::2], myList[1::2])) ``` Please do not use 'list' as a variable name, as it prevents you from accessing the list() function. If there is much data involved, we can do it more efficiently using iterator functions: ``` from itertools import izip, islice myList = ['first_key', 'first_value', 'second_key', 'second_value'] myDict = dict(izip(islice(myList,0,None,2), islice(myList,1,None,2))) ```
If the list is large, you end up wasting memory by building slices or eager zips. One way to convert the list more lazily is to (ab)use the list iterator and `izip`. ``` from itertools import izip lst = ['first_key', 'first_value', 'second_key', 'second_value'] i = iter(lst) d = dict(izip(i,i)) ```
5,249,353
I'm learning python. I have a list of simple entries and I want to convert it in a dictionary where the first element of list is the key of the second element, the third is the key of the fourth, and so on. How can I do it? ``` list = ['first_key', 'first_value', 'second_key', 'second_value'] ``` Thanks in advance!
2011/03/09
[ "https://Stackoverflow.com/questions/5249353", "https://Stackoverflow.com", "https://Stackoverflow.com/users/619378/" ]
``` myDict = dict(zip(myList[::2], myList[1::2])) ``` Please do not use 'list' as a variable name, as it prevents you from accessing the list() function. If there is much data involved, we can do it more efficiently using iterator functions: ``` from itertools import izip, islice myList = ['first_key', 'first_value', 'second_key', 'second_value'] myDict = dict(izip(islice(myList,0,None,2), islice(myList,1,None,2))) ```
The KISS way: Use exception and iterators ``` myDict = {} it = iter(list) for x in list: try: myDict[it.next()] = it.next() except: pass myDict ```
5,249,353
I'm learning python. I have a list of simple entries and I want to convert it in a dictionary where the first element of list is the key of the second element, the third is the key of the fourth, and so on. How can I do it? ``` list = ['first_key', 'first_value', 'second_key', 'second_value'] ``` Thanks in advance!
2011/03/09
[ "https://Stackoverflow.com/questions/5249353", "https://Stackoverflow.com", "https://Stackoverflow.com/users/619378/" ]
If the list is large, you end up wasting memory by building slices or eager zips. One way to convert the list more lazily is to (ab)use the list iterator and `izip`. ``` from itertools import izip lst = ['first_key', 'first_value', 'second_key', 'second_value'] i = iter(lst) d = dict(izip(i,i)) ```
The KISS way: Use exception and iterators ``` myDict = {} it = iter(list) for x in list: try: myDict[it.next()] = it.next() except: pass myDict ```
45,636,955
I've got the following python method, it gets a string and returns an integer. I'm looking for the correct `input` that will print "Great Success!" ``` input = "XXX" def enc(pwd): inc = 0 for i in range(1, len(pwd) + 1): _1337 = pwd[i - 1] _move = ord(_1337) - 47 if i == 1: inc += _move else: inc += _move * (42 ** (i - 1)) return inc if hex(enc(input)) == 0xEA9D1ED352B8: print "Great Success!" ```
2017/08/11
[ "https://Stackoverflow.com/questions/45636955", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8451227/" ]
It's encoding the input in base 42 (starting from `chr(47)` which is `'/'`), and easy to decode: ``` def dec(x): while x: yield chr(47 + x % 42) x //= 42 print ''.join(dec(0xEA9D1ED352B8)) ``` The output is: `?O95PIVII`
You can try to bruteforce it. Just make a while loop where the input is encrypted by the function until you have the same hash. But with no informations about the length of the input and so on it could take a while.
45,636,955
I've got the following python method, it gets a string and returns an integer. I'm looking for the correct `input` that will print "Great Success!" ``` input = "XXX" def enc(pwd): inc = 0 for i in range(1, len(pwd) + 1): _1337 = pwd[i - 1] _move = ord(_1337) - 47 if i == 1: inc += _move else: inc += _move * (42 ** (i - 1)) return inc if hex(enc(input)) == 0xEA9D1ED352B8: print "Great Success!" ```
2017/08/11
[ "https://Stackoverflow.com/questions/45636955", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8451227/" ]
It's encoding the input in base 42 (starting from `chr(47)` which is `'/'`), and easy to decode: ``` def dec(x): while x: yield chr(47 + x % 42) x //= 42 print ''.join(dec(0xEA9D1ED352B8)) ``` The output is: `?O95PIVII`
Yes it is easy to crack. The answer is "?O95PIVII". ``` >>> enc("?O95PIVII")==0xEA9D1ED352B8 True ``` The check in your example is invalid by the way, you need to drop the `hex` from it because the literal 0xEA9D1ED352B8 is parsed as an int. *edit* See Rawing's comment for a hint of how I got the answer. A bit more detail: because its summing powers of 42 based on the index of the char in the string, it's easy to figure out the required length of the input string: `math.ceil(math.log(target)/math.log(42))` which gives us 9. I then worked my way from the end to the start of the string, because the last character has the most effect on the sum.
38,697,820
I'm trying to run sqoop command inside Python script. I had no problem to do that trough shell command, but when I'm trying to execute python stript: ``` #!/usr/bin/python sqoopcom="sqoop import --direct --connect abcd --username abc --P --query "queryname" " exec (sqoopcom) ``` I got an error, Invalid syntax, how to solve it ?
2016/08/01
[ "https://Stackoverflow.com/questions/38697820", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5312431/" ]
The build in `exec` statement that you're using is for interpreting python code inside a python program. What you want is to execute an external (shell) command. For that you could use `call` from the **subprocess module** ``` import subprocess subprocess.call(["echo", "Hello", "World"]) ``` <https://docs.python.org/3/library/subprocess.html>
You need to skip " on --query param ``` sqoopcom="sqoop import --direct --connect abcd --username abc --P --query \"queryname\" --target-dir /pwd/dir --m 1 --fetch-size 1000 --verbose --fields-terminated-by , --escaped-by \\ --enclosed-by '\"'/dir/part-m-00000" ```
38,697,820
I'm trying to run sqoop command inside Python script. I had no problem to do that trough shell command, but when I'm trying to execute python stript: ``` #!/usr/bin/python sqoopcom="sqoop import --direct --connect abcd --username abc --P --query "queryname" " exec (sqoopcom) ``` I got an error, Invalid syntax, how to solve it ?
2016/08/01
[ "https://Stackoverflow.com/questions/38697820", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5312431/" ]
You need to skip " on --query param ``` sqoopcom="sqoop import --direct --connect abcd --username abc --P --query \"queryname\" --target-dir /pwd/dir --m 1 --fetch-size 1000 --verbose --fields-terminated-by , --escaped-by \\ --enclosed-by '\"'/dir/part-m-00000" ```
You can use: Invalid syntax error noted that you haven't backslashed \"queryname\" ``` #!/usr/bin/env python import os sqoopcom="sqoop import --direct --connect abcd --username abc --P --query \"queryname\" " os.system(sqoopcom) ```
38,697,820
I'm trying to run sqoop command inside Python script. I had no problem to do that trough shell command, but when I'm trying to execute python stript: ``` #!/usr/bin/python sqoopcom="sqoop import --direct --connect abcd --username abc --P --query "queryname" " exec (sqoopcom) ``` I got an error, Invalid syntax, how to solve it ?
2016/08/01
[ "https://Stackoverflow.com/questions/38697820", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5312431/" ]
The build in `exec` statement that you're using is for interpreting python code inside a python program. What you want is to execute an external (shell) command. For that you could use `call` from the **subprocess module** ``` import subprocess subprocess.call(["echo", "Hello", "World"]) ``` <https://docs.python.org/3/library/subprocess.html>
You can use: Invalid syntax error noted that you haven't backslashed \"queryname\" ``` #!/usr/bin/env python import os sqoopcom="sqoop import --direct --connect abcd --username abc --P --query \"queryname\" " os.system(sqoopcom) ```
46,225,871
``` x = open("file.txt",'w') s = chr(931) # 'Σ' x.write(s) ``` Error ``` Traceback (most recent call last): File "C:\Python34\lib\encodings\cp1252.py", line 19, in encode return codecs.charmap_encode(input,self.errors,encoding_table)[0] UnicodeEncodeError: 'charmap' codec can't encode character '\u03a3' in position 0: character maps to <undefined> ``` Even if I save the char 'Σ' in Windows txt-editor under code UTF-8 and then open in python the return will be 'Σ' and not what I expect Σ. I don't understand why python interpret the sign wrong because it's utf-8 or is this a problem in windows?
2017/09/14
[ "https://Stackoverflow.com/questions/46225871", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4772772/" ]
Your default encoding seems to be cp1252, not utf-8. You need to specify the encoding, to be sure it's utf-8. ### this works fine: ``` with open('outfile.txt', 'w', encoding='utf-8') as f: f.write('Σ') ``` ### this raises your error: ``` with open('outfile.txt', 'w', encoding='cp1252') as f: f.write('Σ') ```
I solve the problem by saving as bytes instead of string ``` def save_byte(): x = open("file.txt",'wb') s = chr(931) # 'Σ' s = s.encode() x.write(s) x.close() ``` outout: Σ
7,139,293
I'm currently building my android project from the project folder with ant like the following: ``` MyProject/ build.xml ``` The ant command that I use to build is: ``` $ MyProject/ant install ``` In my java code, I have some unused imports and variables, for instance: ``` import java.io.IOException; String doNothing = "Do Nothing"; ``` I'm not making used of the above in my code. Is there way to detect those from the command line with `ant`? If not, do I have to use a third party tool? In Python, I use [pyflakes](http://pypi.python.org/pypi/pyflakes) to cleanup my code. I'm looking for the equivalent in Java at the command line.
2011/08/21
[ "https://Stackoverflow.com/questions/7139293", "https://Stackoverflow.com", "https://Stackoverflow.com/users/117642/" ]
You can use [PMD](http://pmd.sourceforge.net/) to do this and much more. It includes checks for both unused local variables and unused imports. It can be [integrated with ant](https://pmd.github.io/pmd-6.17.0/pmd_userdocs_tools_ant.html) and you can configure it to fail the build if any errors are detected. If you are using the standard build structure that is created via the `android` command line tool you can tie the PMD target into the `-pre-compile` stage.
You do not have to do this if you have proguard enabled. <http://developer.android.com/guide/developing/tools/proguard.html>
3,032,519
When I was using the built-in simple server, everything is OK, the admin interface is beautiful: `python manage.py runserver` However, when I try to serve my application using a wsgi server with `django.core.handlers.wsgi.WSGIHandler`, Django seems to forget where the admin media files is, and the admin page is not styled at all: `gunicorn_django` How did this happen?
2010/06/13
[ "https://Stackoverflow.com/questions/3032519", "https://Stackoverflow.com", "https://Stackoverflow.com/users/225262/" ]
When I look into the source code of Django, I find out the reason. Somewhere in the `django.core.management.commands.runserver` module, a `WSGIHandler` object is wrapped inside an `AdminMediaHandler`. According to the document, `AdminMediaHandler` is a > > WSGI middleware that intercepts calls > to the admin media directory, as > defined by the ADMIN\_MEDIA\_PREFIX setting, and serves those images. > Use this ONLY LOCALLY, for development! This hasn't been tested > for > security and is not super efficient. > > > And that's why the admin media files can only be found automatically when I was using the test server. Now I just go ahead and set up the admin media url mapping manually :)
Django by default doesn't serve the media files since it usually is better to serve these static files on another server (for performance etc.). So, when deploying your application you have to make sure you setup another server (or virtual server) which serves the media (including the admin media). You can find the admin media in `django/contrib/admin/media`. You should setup your MEDIA\_URL and ADMIN\_MEDIA\_URL so that they point to the media files. See also <http://docs.djangoproject.com/en/dev/howto/static-files/#howto-static-files>.
3,032,519
When I was using the built-in simple server, everything is OK, the admin interface is beautiful: `python manage.py runserver` However, when I try to serve my application using a wsgi server with `django.core.handlers.wsgi.WSGIHandler`, Django seems to forget where the admin media files is, and the admin page is not styled at all: `gunicorn_django` How did this happen?
2010/06/13
[ "https://Stackoverflow.com/questions/3032519", "https://Stackoverflow.com", "https://Stackoverflow.com/users/225262/" ]
Django by default doesn't serve the media files since it usually is better to serve these static files on another server (for performance etc.). So, when deploying your application you have to make sure you setup another server (or virtual server) which serves the media (including the admin media). You can find the admin media in `django/contrib/admin/media`. You should setup your MEDIA\_URL and ADMIN\_MEDIA\_URL so that they point to the media files. See also <http://docs.djangoproject.com/en/dev/howto/static-files/#howto-static-files>.
I've run into this problem too (because I do some development against gunicorn), and here's how to remove the admin-media magic and serve admin media like any other media through urls.py: ``` import os import django ... admin_media_url = settings.ADMIN_MEDIA_PREFIX.lstrip('/') + '(?P<path>.*)$' admin_media_path = os.path.join(django.__path__[0], 'contrib', 'admin', 'media') urlpatterns = patterns('', url(r'^admin/', include(admin.site.urls)), url(r'^' + admin_media_url , 'django.views.static.serve', { 'document_root': admin_media_path, }, name='admin-media'), ... ) ``` Also: <http://djangosnippets.org/snippets/2547/> And, of course, `#include <production_disclaimer.h>`.
3,032,519
When I was using the built-in simple server, everything is OK, the admin interface is beautiful: `python manage.py runserver` However, when I try to serve my application using a wsgi server with `django.core.handlers.wsgi.WSGIHandler`, Django seems to forget where the admin media files is, and the admin page is not styled at all: `gunicorn_django` How did this happen?
2010/06/13
[ "https://Stackoverflow.com/questions/3032519", "https://Stackoverflow.com", "https://Stackoverflow.com/users/225262/" ]
When I look into the source code of Django, I find out the reason. Somewhere in the `django.core.management.commands.runserver` module, a `WSGIHandler` object is wrapped inside an `AdminMediaHandler`. According to the document, `AdminMediaHandler` is a > > WSGI middleware that intercepts calls > to the admin media directory, as > defined by the ADMIN\_MEDIA\_PREFIX setting, and serves those images. > Use this ONLY LOCALLY, for development! This hasn't been tested > for > security and is not super efficient. > > > And that's why the admin media files can only be found automatically when I was using the test server. Now I just go ahead and set up the admin media url mapping manually :)
I've run into this problem too (because I do some development against gunicorn), and here's how to remove the admin-media magic and serve admin media like any other media through urls.py: ``` import os import django ... admin_media_url = settings.ADMIN_MEDIA_PREFIX.lstrip('/') + '(?P<path>.*)$' admin_media_path = os.path.join(django.__path__[0], 'contrib', 'admin', 'media') urlpatterns = patterns('', url(r'^admin/', include(admin.site.urls)), url(r'^' + admin_media_url , 'django.views.static.serve', { 'document_root': admin_media_path, }, name='admin-media'), ... ) ``` Also: <http://djangosnippets.org/snippets/2547/> And, of course, `#include <production_disclaimer.h>`.
72,991,013
How can I get an input like this in python3 The first input is = 2 and based on this first input I want to get 2 get new inputs For example: ``` 2 # how many inputs? 1 2 # 2 numbers inputs ``` or ``` 3 # how many inputs? 3 5 8 # in one line getting 3 inputs ``` Here is another example: ``` 4 6 8 7 9 ``` How I can get in one line inputs based on the first input? I tried to use map but with no luck ``` n = int(input()) for i in range(n): x = map(int,input().split()) ``` But the output is ``` if n is 2 1 2 ``` Again asking for inputs because of `i = 0` getting `1 2` and `i = 1` again asking for input.
2022/07/15
[ "https://Stackoverflow.com/questions/72991013", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19312041/" ]
This might be an approach: ``` <?php $input = "1234-ABC 2345 rBC 9998DDD 9657 lJi"; preg_match_all('/(\d{4}[-\s]*[a-z]{3})/i', $input, $matches); $output = array_shift($matches); array_walk($output, function(&$value) { $value = strtoupper(str_replace(" ", "", $value)); }); print_r($output); ``` The output obviously is: ``` Array ( [0] => 1234ABC [1] => 2345RBC [2] => 9998DDD [3] => 9657LJI ) ```
You regular expression `(\d{4})( *)(-*)( *)([a-zA-Z]{3})` was correct but you needed to use `preg_match_all` to return multiple matches. This is a demo: <https://onlinephp.io/c/e5acb> ``` <?php function parsePlates($subject){ $plates = []; preg_match_all('/(\d{4})( *)(-*)( *)([a-zA-Z]{3})/sim', $subject, $result, PREG_PATTERN_ORDER); for ($i = 0; $i < count($result[0]); $i++) { $plate = $result[0][$i]; $plates[] = $plate; } return $plates; } $plates = parsePlates('1234 ABC 4567BCX'); var_dump($plates); ```
38,442,107
I tried the following: ``` #!/usr/bin/env python import keras from keras.models import model_from_yaml model_file_path = 'model-301.yaml' weights_file_path = 'model-301.hdf5' # Load network with open(model_file_path) as f: yaml_string = f.read() model = model_from_yaml(yaml_string) model.load_weights(weights_file_path) model.compile(optimizer='adagrad', loss='binary_crossentropy') # Visualize from keras.utils.visualize_util import plot ``` However, this gives an error: ``` Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/home/moose/.local/lib/python2.7/site-packages/keras/utils/visualize_util.py", line 7, in <module> if not pydot.find_graphviz(): AttributeError: 'module' object has no attribute 'find_graphviz' ``` How can I fix this? Note: The hdf5 and the YAML file can be found [on Github](https://github.com/TensorVision/MediSeg/tree/master/AP3/model-301).
2016/07/18
[ "https://Stackoverflow.com/questions/38442107", "https://Stackoverflow.com", "https://Stackoverflow.com/users/562769/" ]
The problem is also referenced on the [issues page](https://github.com/fchollet/keras/issues/3210) of the keras project. You need to install a version of `pydot` <= 1.1.0 because the function `find_graphviz` was [removed](https://github.com/erocarrera/pydot/commit/bc639e76b214b1795ebd6263680ee55d9d4fca9f#diff-44fda7721399b25e8cb06471016a3454) in version 1.2.0. Alternatively you could install [pydot-ng](https://github.com/pydot/pydot-ng) instead, which is [recommended](https://github.com/fchollet/keras/blob/master/keras/utils/visualize_util.py#L2) by the keras developers.
If you have not already installed `pydot` python package - try to install it. If you have `pydot` reinstallation should help with your problem.
10,782,285
> > **Possible Duplicate:** > > [How to generate all permutations of a list in Python](https://stackoverflow.com/questions/104420/how-to-generate-all-permutations-of-a-list-in-python) > > > I am given a list `[1,2,3]` and the task is to create all the possible permutations of this list. Expected output: ``` [[1, 2, 3], [1, 3, 2], [2, 3, 1], [2, 1, 3], [3, 1, 2], [3, 2, 1]] ``` I can't even think from where to begin. Can anyone help? Thanks
2012/05/28
[ "https://Stackoverflow.com/questions/10782285", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1407910/" ]
[itertools.permutations](http://docs.python.org/library/itertools.html#itertools.permutations) does this for you. Otherwise, a simple method consist in finding the permutations recursively: you successively select the first element of the output, then ask your function to find all the permutations of the remaining elements. A slightly different, but similar solution can be found at <https://stackoverflow.com/a/104436/42973>. It finds all the permutations of the remaining (non-first) elements, and then inserts the first element successively at all the possible locations.
this is a rudimentary solution... the idea is to use recursion to go through all permutation and reject the non valid permutations. ``` def perm(list_to_perm,perm_l,items,out): if len(perm_l) == items: out +=[perm_l] else: for i in list_to_perm: if i not in perm_l: perm(list_to_perm,perm_l +[i],items,out) a = [1,2,3] out = [] perm(a,[],len(a),out) print out ``` output: ``` [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]] ```
35,042,340
I am using [Backbone.LocalStorage](https://github.com/jeromegn/Backbone.localStorage) plugin with backbone app. It is working fine in chrome and safari however, it is giving me below error in firefox. > > DOMException [SecurityError: "The operation is insecure." > code: 18 > nsresult: 0x80530012 > location: <http://localhost:8000/js/libs/backbone.localStorage/backbone.localStorage.js?version=1453910702146:137]> > > > I am using python `simpleHttpServer` How can I resolve this error? **UPDATE** Here is my code. ``` paths: { 'jquery' : 'libs/jquery/dist/jquery', 'underscore' : 'libs/underscore/underscore', 'backbone' : 'libs/backbone/backbone', 'localStorage' : 'libs/backbone.localStorage/backbone.localStorage', 'text' : 'plugins/text' } ``` Here is collection where localStorage is used. ``` var Items = Backbone.Collection.extend({ model: SomeModel, localStorage: new Backbone.LocalStorage('items'), }); ``` **UPDATE 2** I am using firefox 36. **UPDATE 3** It seems like it is a CORS issue but my firefox version is 36. Which should be fine. **UPDATE 4** I am also getting this error in firefox nightly version 44. I also updated my firefox to version 44. Still same error.
2016/01/27
[ "https://Stackoverflow.com/questions/35042340", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1136062/" ]
Make sure Firefox has cookies enabled. The setting can be found under Menu/Options/Privacy/History In the dropdown, select either 'Remember History' or if You prefer use custom settings for history, but select option Accept cookies from sites Hope it helps.
Make sure your domains are same. verify [Same Origin Policy](http://en.wikipedia.org/wiki/Same_origin_policy) which means same domain, subdomain, protocol (http vs https) and same port. [What is Same Origin Policy?](http://en.wikipedia.org/wiki/Same_origin_policy) [How does pushState protect against potential content forgeries?](https://stackoverflow.com/questions/6193983/how-does-pushstate-protect-against-potential-content-forgeries)
35,042,340
I am using [Backbone.LocalStorage](https://github.com/jeromegn/Backbone.localStorage) plugin with backbone app. It is working fine in chrome and safari however, it is giving me below error in firefox. > > DOMException [SecurityError: "The operation is insecure." > code: 18 > nsresult: 0x80530012 > location: <http://localhost:8000/js/libs/backbone.localStorage/backbone.localStorage.js?version=1453910702146:137]> > > > I am using python `simpleHttpServer` How can I resolve this error? **UPDATE** Here is my code. ``` paths: { 'jquery' : 'libs/jquery/dist/jquery', 'underscore' : 'libs/underscore/underscore', 'backbone' : 'libs/backbone/backbone', 'localStorage' : 'libs/backbone.localStorage/backbone.localStorage', 'text' : 'plugins/text' } ``` Here is collection where localStorage is used. ``` var Items = Backbone.Collection.extend({ model: SomeModel, localStorage: new Backbone.LocalStorage('items'), }); ``` **UPDATE 2** I am using firefox 36. **UPDATE 3** It seems like it is a CORS issue but my firefox version is 36. Which should be fine. **UPDATE 4** I am also getting this error in firefox nightly version 44. I also updated my firefox to version 44. Still same error.
2016/01/27
[ "https://Stackoverflow.com/questions/35042340", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1136062/" ]
This happens when we try to access a resource (CSS...) that is located on a different domain. To deal with this error we can use this: ``` try { //your critical access to ressources ! //rules = document.styleSheets[i].cssRules; } catch(e) { if(e.name !== "SecurityError") { throw e; } ```
Make sure your domains are same. verify [Same Origin Policy](http://en.wikipedia.org/wiki/Same_origin_policy) which means same domain, subdomain, protocol (http vs https) and same port. [What is Same Origin Policy?](http://en.wikipedia.org/wiki/Same_origin_policy) [How does pushState protect against potential content forgeries?](https://stackoverflow.com/questions/6193983/how-does-pushstate-protect-against-potential-content-forgeries)
35,042,340
I am using [Backbone.LocalStorage](https://github.com/jeromegn/Backbone.localStorage) plugin with backbone app. It is working fine in chrome and safari however, it is giving me below error in firefox. > > DOMException [SecurityError: "The operation is insecure." > code: 18 > nsresult: 0x80530012 > location: <http://localhost:8000/js/libs/backbone.localStorage/backbone.localStorage.js?version=1453910702146:137]> > > > I am using python `simpleHttpServer` How can I resolve this error? **UPDATE** Here is my code. ``` paths: { 'jquery' : 'libs/jquery/dist/jquery', 'underscore' : 'libs/underscore/underscore', 'backbone' : 'libs/backbone/backbone', 'localStorage' : 'libs/backbone.localStorage/backbone.localStorage', 'text' : 'plugins/text' } ``` Here is collection where localStorage is used. ``` var Items = Backbone.Collection.extend({ model: SomeModel, localStorage: new Backbone.LocalStorage('items'), }); ``` **UPDATE 2** I am using firefox 36. **UPDATE 3** It seems like it is a CORS issue but my firefox version is 36. Which should be fine. **UPDATE 4** I am also getting this error in firefox nightly version 44. I also updated my firefox to version 44. Still same error.
2016/01/27
[ "https://Stackoverflow.com/questions/35042340", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1136062/" ]
Make sure your domains are same. verify [Same Origin Policy](http://en.wikipedia.org/wiki/Same_origin_policy) which means same domain, subdomain, protocol (http vs https) and same port. [What is Same Origin Policy?](http://en.wikipedia.org/wiki/Same_origin_policy) [How does pushState protect against potential content forgeries?](https://stackoverflow.com/questions/6193983/how-does-pushstate-protect-against-potential-content-forgeries)
I had similar issue with one script, I dig into error and found it required SSL websockets, so I started SSL and again checked, and It worked. Try enabling HTTPS and access website as <https://127.0.0.1/> It may solve error.
35,042,340
I am using [Backbone.LocalStorage](https://github.com/jeromegn/Backbone.localStorage) plugin with backbone app. It is working fine in chrome and safari however, it is giving me below error in firefox. > > DOMException [SecurityError: "The operation is insecure." > code: 18 > nsresult: 0x80530012 > location: <http://localhost:8000/js/libs/backbone.localStorage/backbone.localStorage.js?version=1453910702146:137]> > > > I am using python `simpleHttpServer` How can I resolve this error? **UPDATE** Here is my code. ``` paths: { 'jquery' : 'libs/jquery/dist/jquery', 'underscore' : 'libs/underscore/underscore', 'backbone' : 'libs/backbone/backbone', 'localStorage' : 'libs/backbone.localStorage/backbone.localStorage', 'text' : 'plugins/text' } ``` Here is collection where localStorage is used. ``` var Items = Backbone.Collection.extend({ model: SomeModel, localStorage: new Backbone.LocalStorage('items'), }); ``` **UPDATE 2** I am using firefox 36. **UPDATE 3** It seems like it is a CORS issue but my firefox version is 36. Which should be fine. **UPDATE 4** I am also getting this error in firefox nightly version 44. I also updated my firefox to version 44. Still same error.
2016/01/27
[ "https://Stackoverflow.com/questions/35042340", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1136062/" ]
Make sure Firefox has cookies enabled. The setting can be found under Menu/Options/Privacy/History In the dropdown, select either 'Remember History' or if You prefer use custom settings for history, but select option Accept cookies from sites Hope it helps.
This happens when we try to access a resource (CSS...) that is located on a different domain. To deal with this error we can use this: ``` try { //your critical access to ressources ! //rules = document.styleSheets[i].cssRules; } catch(e) { if(e.name !== "SecurityError") { throw e; } ```
35,042,340
I am using [Backbone.LocalStorage](https://github.com/jeromegn/Backbone.localStorage) plugin with backbone app. It is working fine in chrome and safari however, it is giving me below error in firefox. > > DOMException [SecurityError: "The operation is insecure." > code: 18 > nsresult: 0x80530012 > location: <http://localhost:8000/js/libs/backbone.localStorage/backbone.localStorage.js?version=1453910702146:137]> > > > I am using python `simpleHttpServer` How can I resolve this error? **UPDATE** Here is my code. ``` paths: { 'jquery' : 'libs/jquery/dist/jquery', 'underscore' : 'libs/underscore/underscore', 'backbone' : 'libs/backbone/backbone', 'localStorage' : 'libs/backbone.localStorage/backbone.localStorage', 'text' : 'plugins/text' } ``` Here is collection where localStorage is used. ``` var Items = Backbone.Collection.extend({ model: SomeModel, localStorage: new Backbone.LocalStorage('items'), }); ``` **UPDATE 2** I am using firefox 36. **UPDATE 3** It seems like it is a CORS issue but my firefox version is 36. Which should be fine. **UPDATE 4** I am also getting this error in firefox nightly version 44. I also updated my firefox to version 44. Still same error.
2016/01/27
[ "https://Stackoverflow.com/questions/35042340", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1136062/" ]
Make sure Firefox has cookies enabled. The setting can be found under Menu/Options/Privacy/History In the dropdown, select either 'Remember History' or if You prefer use custom settings for history, but select option Accept cookies from sites Hope it helps.
I had similar issue with one script, I dig into error and found it required SSL websockets, so I started SSL and again checked, and It worked. Try enabling HTTPS and access website as <https://127.0.0.1/> It may solve error.
35,042,340
I am using [Backbone.LocalStorage](https://github.com/jeromegn/Backbone.localStorage) plugin with backbone app. It is working fine in chrome and safari however, it is giving me below error in firefox. > > DOMException [SecurityError: "The operation is insecure." > code: 18 > nsresult: 0x80530012 > location: <http://localhost:8000/js/libs/backbone.localStorage/backbone.localStorage.js?version=1453910702146:137]> > > > I am using python `simpleHttpServer` How can I resolve this error? **UPDATE** Here is my code. ``` paths: { 'jquery' : 'libs/jquery/dist/jquery', 'underscore' : 'libs/underscore/underscore', 'backbone' : 'libs/backbone/backbone', 'localStorage' : 'libs/backbone.localStorage/backbone.localStorage', 'text' : 'plugins/text' } ``` Here is collection where localStorage is used. ``` var Items = Backbone.Collection.extend({ model: SomeModel, localStorage: new Backbone.LocalStorage('items'), }); ``` **UPDATE 2** I am using firefox 36. **UPDATE 3** It seems like it is a CORS issue but my firefox version is 36. Which should be fine. **UPDATE 4** I am also getting this error in firefox nightly version 44. I also updated my firefox to version 44. Still same error.
2016/01/27
[ "https://Stackoverflow.com/questions/35042340", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1136062/" ]
This happens when we try to access a resource (CSS...) that is located on a different domain. To deal with this error we can use this: ``` try { //your critical access to ressources ! //rules = document.styleSheets[i].cssRules; } catch(e) { if(e.name !== "SecurityError") { throw e; } ```
I had similar issue with one script, I dig into error and found it required SSL websockets, so I started SSL and again checked, and It worked. Try enabling HTTPS and access website as <https://127.0.0.1/> It may solve error.
54,204,181
I am trying to set the return value of a `get` request in python in order to do a unit test, which tests if the `post` request is called with the correct arguments. Assume I have the following code to test ``` # main.py import requests from django.contrib.auth.models import User def function_with_get(): client = requests.session() some_data = str(client.get('https://cool_site.com').content) return some_data def function_to_test(data): for user in User.objects.all(): if user.username in data: post_data = dict(data=user.username) else: post_data = dict(data='Not found') client.post('https://not_cool_site.com', data=post_data) #test.py from unittest import mock from unittest import TestCase from main import function_with_get, function_to_test class Testing(TestCase): @mock.patch('main.requests.session') def test_which_fails_because_of_get(self, mock_sess): mock_sess.get[0].return_value.content = 'User1' data = function_with_get() function_to_test(data) assertIn('Not Found', mock_sess.retrun_value.post.call_args_list[1]) ``` This, sadly, does not work and I have also tried to set it without `content`, however, I get an error **AttributeError: 'str' object has no attribute 'content'** What would be the correct way to set the `return_value` of the `get` request, so that I can test the arguments of the `post` request?
2019/01/15
[ "https://Stackoverflow.com/questions/54204181", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7226268/" ]
I think you almost have it, except you're missing the return value for `session()` - because `session` is instantiated to create the `client` instance. I think you can drop the `[0]` too. Try: ``` mock_sess**.return\_value.**get.return_value.content = 'User1' ```
Try with .text because this should work for strings. ``` s = requests.Session() s.get('https://httpbin.org/cookies/ set/sessioncookie/123456789') r = s.get('https://httpbin.org/ cookies') print(r.text) ``` <http://docs.python-requests.org/en/master/user/advanced/>
37,932,363
So I need to make this plot in python. I wish to remove my legend's border. However, when I tried the different solutions other posters made, they were unable to work with mine. Please help. **This doesn't work:** ``` plt.legend({'z$\sim$0.35', 'z$\sim$0.1','z$\sim$1.55'}) plt.legend(frameon=False) ``` --- ``` plt.legend({'z$\sim$0.35', 'z$\sim$0.1','z$\sim$1.55'}) plt.legend.get_frame().set_linewidth(0.0) ``` --- ``` plt.legend({'z$\sim$0.35', 'z$\sim$0.1','z$\sim$1.55'}, 'Box', 'off') ``` Additionally, when I plotted, I imported two different files and graphed them with a line and with circles respectively. How could I put a line or a circle within the legend key? The plot: [![enter image description here](https://i.stack.imgur.com/Axl8g.png)](https://i.stack.imgur.com/Axl8g.png)
2016/06/20
[ "https://Stackoverflow.com/questions/37932363", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6491230/" ]
It's very strange because the command : ``` plt.legend(frameon=False) ``` Should work very well. You can also try this command, to compare : ``` plt.legend(frameon=None) ``` You can also read the documentation on this page about [plt.legend](http://matplotlib.org/api/legend_api.html) I scripted something as example to you : ``` import numpy as np import matplotlib.pyplot as plt x = np.array([0,4,8,13]) y = np.array([0,1,2,3]) fig1, ((ax1, ax2)) = plt.subplots(1, 2) ax1.plot(x,y, label=u'test') ax1.legend(loc='upper left', frameon=False) ax2.plot(x,y, label=u'test2') ax2.legend(loc='upper left', frameon=None) plt.show() ``` [![enter image description here](https://i.stack.imgur.com/cxDcK.png)](https://i.stack.imgur.com/cxDcK.png)
Try this if you want to draw only one plot (without subplot) ``` plt.legend({'z$\sim$0.35', 'z$\sim$0.1','z$\sim$1.55'}, frameon=False) ``` It is enough one plt.legend. The second one rewrites the first one.
37,932,363
So I need to make this plot in python. I wish to remove my legend's border. However, when I tried the different solutions other posters made, they were unable to work with mine. Please help. **This doesn't work:** ``` plt.legend({'z$\sim$0.35', 'z$\sim$0.1','z$\sim$1.55'}) plt.legend(frameon=False) ``` --- ``` plt.legend({'z$\sim$0.35', 'z$\sim$0.1','z$\sim$1.55'}) plt.legend.get_frame().set_linewidth(0.0) ``` --- ``` plt.legend({'z$\sim$0.35', 'z$\sim$0.1','z$\sim$1.55'}, 'Box', 'off') ``` Additionally, when I plotted, I imported two different files and graphed them with a line and with circles respectively. How could I put a line or a circle within the legend key? The plot: [![enter image description here](https://i.stack.imgur.com/Axl8g.png)](https://i.stack.imgur.com/Axl8g.png)
2016/06/20
[ "https://Stackoverflow.com/questions/37932363", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6491230/" ]
It's very strange because the command : ``` plt.legend(frameon=False) ``` Should work very well. You can also try this command, to compare : ``` plt.legend(frameon=None) ``` You can also read the documentation on this page about [plt.legend](http://matplotlib.org/api/legend_api.html) I scripted something as example to you : ``` import numpy as np import matplotlib.pyplot as plt x = np.array([0,4,8,13]) y = np.array([0,1,2,3]) fig1, ((ax1, ax2)) = plt.subplots(1, 2) ax1.plot(x,y, label=u'test') ax1.legend(loc='upper left', frameon=False) ax2.plot(x,y, label=u'test2') ax2.legend(loc='upper left', frameon=None) plt.show() ``` [![enter image description here](https://i.stack.imgur.com/cxDcK.png)](https://i.stack.imgur.com/cxDcK.png)
Make sure frameon = False is together with the positional argument in plt.legend(...) if you want to specify the position as well as remove the border. If these arguments are written separately or in sequential, there's an issue of overwriting and the desired effect may not be achieved. Correct! `plt.legend(loc="lower right", frameon=False)` May not give desired effect when written like this! `plt.legend(loc="lower right")` & `plt.legend(frameon=False)`
69,364,940
The text is like "1-2years. 3years. 10years." I want get result `[(1,2),(3),(10)]`. I use python. I first tried `r"([0-9]?)[-]?([0-9])years"`. It works well except for the case of 10. I also tried `r"([0-9]?)[-]?([0-9]|10)years"` but the result is still `[(1,2),(3),(1,0)]`.
2021/09/28
[ "https://Stackoverflow.com/questions/69364940", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10490005/" ]
You need to listen for click event on newly added element. hence added a click listener on **newSpan** element after adding it into DOM. You are listening for event for removeLists element only but when you add a new element in the DOM, the newly doesn't have the click event. Hence, we have to listen for the event explicitly. I hope, it answers your question. :) ```js const toDoInput = document.querySelector("input"); const addButton = document.querySelector("button"); const listParent = document.querySelector("ul"); const removeLists = document.querySelectorAll(".remove-li"); const listItemMake = () => { if (toDoInput.value !== "") { const newDiv = document.createElement("div"); newDiv.classList.add("list-item"); const newListItem = document.createElement("li"); newListItem.append(toDoInput.value); newDiv.append(newListItem); toDoInput.value = ""; const newSpan = document.createElement("span"); newSpan.classList.add("remove-li"); newSpan.innerHTML = '(Remove Button)'; newDiv.append(newSpan); listParent.append(newDiv); newSpan.addEventListener("click", () => { newSpan.parentElement.remove(); }); } }; addButton.addEventListener("click", () => { listItemMake(); }); toDoInput.addEventListener("keydown", (event) => { if (event.code === "Enter") { listItemMake(); } }); for (const removeList of removeLists) { removeList.addEventListener("click", () => { removeList.parentElement.remove(); }) } ``` ```html <h1>ToDo Application</h1> <div class="container"> <div class="form-container"> <input type="text" placeholder="Add New Tasks"> <button>Add</button> </div> <div class="list-container"> <ul> <div class="list-item"> <li>Sample List Item</li> <span class="remove-li">(Remove Button)</span> </div> <div class="list-item"> <li>Sample List Item</li> <span class="remove-li">(Remove Button)</span> </div> <div class="list-item"> <li>Sample List Item</li> <span class="remove-li">(Remove Button)</span> </div> </ul> </div> </div> ```
Please change some code. Please add remove event function to listItemMake() function. ```js const toDoInput = document.querySelector("input"); const addButton = document.querySelector("button"); const listParent = document.querySelector("ul"); const listItemMake = () => { if (toDoInput.value !== "") { const newDiv = document.createElement("div"); newDiv.classList.add("list-item"); const newListItem = document.createElement("li"); newListItem.append(toDoInput.value); newDiv.append(newListItem); toDoInput.value = ""; const newSpan = document.createElement("span"); newSpan.classList.add("remove-li"); newSpan.innerHTML = '(Remove Button)'; newDiv.append(newSpan); listParent.append(newDiv); } addRemoveEvent(); }; addButton.addEventListener("click", () => { listItemMake(); }); toDoInput.addEventListener("keydown", (event) => { if (event.code === "Enter") { listItemMake(); } }); function addRemoveEvent() { const removeLists = document.querySelectorAll(".remove-li"); for (const removeList of removeLists) { removeList.addEventListener("click", () => { removeList.parentElement.remove(); }) } } addRemoveEvent(); ``` ```html <h1>ToDo Application</h1> <div class="container"> <div class="form-container"> <input type="text" placeholder="Add New Tasks"> <button>Add</button> </div> <div class="list-container"> <ul> <div class="list-item"> <li>Sample List Item</li> <span class="remove-li">(Remove Button)</span> </div> <div class="list-item"> <li>Sample List Item</li> <span class="remove-li">(Remove Button)</span> </div> <div class="list-item"> <li>Sample List Item</li> <span class="remove-li">(Remove Button)</span> </div> </ul> </div> </div> ```
69,364,940
The text is like "1-2years. 3years. 10years." I want get result `[(1,2),(3),(10)]`. I use python. I first tried `r"([0-9]?)[-]?([0-9])years"`. It works well except for the case of 10. I also tried `r"([0-9]?)[-]?([0-9]|10)years"` but the result is still `[(1,2),(3),(1,0)]`.
2021/09/28
[ "https://Stackoverflow.com/questions/69364940", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10490005/" ]
You need to listen for click event on newly added element. hence added a click listener on **newSpan** element after adding it into DOM. You are listening for event for removeLists element only but when you add a new element in the DOM, the newly doesn't have the click event. Hence, we have to listen for the event explicitly. I hope, it answers your question. :) ```js const toDoInput = document.querySelector("input"); const addButton = document.querySelector("button"); const listParent = document.querySelector("ul"); const removeLists = document.querySelectorAll(".remove-li"); const listItemMake = () => { if (toDoInput.value !== "") { const newDiv = document.createElement("div"); newDiv.classList.add("list-item"); const newListItem = document.createElement("li"); newListItem.append(toDoInput.value); newDiv.append(newListItem); toDoInput.value = ""; const newSpan = document.createElement("span"); newSpan.classList.add("remove-li"); newSpan.innerHTML = '(Remove Button)'; newDiv.append(newSpan); listParent.append(newDiv); newSpan.addEventListener("click", () => { newSpan.parentElement.remove(); }); } }; addButton.addEventListener("click", () => { listItemMake(); }); toDoInput.addEventListener("keydown", (event) => { if (event.code === "Enter") { listItemMake(); } }); for (const removeList of removeLists) { removeList.addEventListener("click", () => { removeList.parentElement.remove(); }) } ``` ```html <h1>ToDo Application</h1> <div class="container"> <div class="form-container"> <input type="text" placeholder="Add New Tasks"> <button>Add</button> </div> <div class="list-container"> <ul> <div class="list-item"> <li>Sample List Item</li> <span class="remove-li">(Remove Button)</span> </div> <div class="list-item"> <li>Sample List Item</li> <span class="remove-li">(Remove Button)</span> </div> <div class="list-item"> <li>Sample List Item</li> <span class="remove-li">(Remove Button)</span> </div> </ul> </div> </div> ```
Try to move const removeLists and removeList.addEventListener to listItemMake function, so when you add new item const removeLists can include new list item. ```js const listItemMake = () => { if (toDoInput.value !== "") { const newDiv = document.createElement("div"); newDiv.classList.add("list-item"); const newListItem = document.createElement("li"); newListItem.append(toDoInput.value); newDiv.append(newListItem); toDoInput.value = ""; const newSpan = document.createElement("span"); newSpan.classList.add("remove-li"); newSpan.innerHTML = '(Remove Button)'; newDiv.append(newSpan); listParent.append(newDiv); } const removeLists = document.querySelectorAll(".remove-li"); for (const removeList of removeLists) { removeList.addEventListener("click", () => { removeList.parentElement.remove(); }) } }; ```
69,364,940
The text is like "1-2years. 3years. 10years." I want get result `[(1,2),(3),(10)]`. I use python. I first tried `r"([0-9]?)[-]?([0-9])years"`. It works well except for the case of 10. I also tried `r"([0-9]?)[-]?([0-9]|10)years"` but the result is still `[(1,2),(3),(1,0)]`.
2021/09/28
[ "https://Stackoverflow.com/questions/69364940", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10490005/" ]
You need to listen for click event on newly added element. hence added a click listener on **newSpan** element after adding it into DOM. You are listening for event for removeLists element only but when you add a new element in the DOM, the newly doesn't have the click event. Hence, we have to listen for the event explicitly. I hope, it answers your question. :) ```js const toDoInput = document.querySelector("input"); const addButton = document.querySelector("button"); const listParent = document.querySelector("ul"); const removeLists = document.querySelectorAll(".remove-li"); const listItemMake = () => { if (toDoInput.value !== "") { const newDiv = document.createElement("div"); newDiv.classList.add("list-item"); const newListItem = document.createElement("li"); newListItem.append(toDoInput.value); newDiv.append(newListItem); toDoInput.value = ""; const newSpan = document.createElement("span"); newSpan.classList.add("remove-li"); newSpan.innerHTML = '(Remove Button)'; newDiv.append(newSpan); listParent.append(newDiv); newSpan.addEventListener("click", () => { newSpan.parentElement.remove(); }); } }; addButton.addEventListener("click", () => { listItemMake(); }); toDoInput.addEventListener("keydown", (event) => { if (event.code === "Enter") { listItemMake(); } }); for (const removeList of removeLists) { removeList.addEventListener("click", () => { removeList.parentElement.remove(); }) } ``` ```html <h1>ToDo Application</h1> <div class="container"> <div class="form-container"> <input type="text" placeholder="Add New Tasks"> <button>Add</button> </div> <div class="list-container"> <ul> <div class="list-item"> <li>Sample List Item</li> <span class="remove-li">(Remove Button)</span> </div> <div class="list-item"> <li>Sample List Item</li> <span class="remove-li">(Remove Button)</span> </div> <div class="list-item"> <li>Sample List Item</li> <span class="remove-li">(Remove Button)</span> </div> </ul> </div> </div> ```
```js const toDoInput = document.querySelector("input"); const addButton = document.querySelector("button"); const listParent = document.querySelector("ul"); const listItemMake = () => { if (toDoInput.value !== "") { const newDiv = document.createElement("div"); newDiv.classList.add("list-item"); const newListItem = document.createElement("li"); newListItem.append(toDoInput.value); newDiv.append(newListItem); toDoInput.value = ""; const newSpan = document.createElement("span"); newSpan.classList.add("remove-li"); newSpan.innerHTML = '(Remove Button)'; newDiv.append(newSpan); listParent.append(newDiv); } removeEvent() }; addButton.addEventListener("click", () => { listItemMake(); }); toDoInput.addEventListener("keydown", (event) => { if (event.code === "Enter") { listItemMake(); } }); const removeEvent = () => { const removeLists = document.querySelectorAll(".remove-li"); removeLists.forEach(item=>{ item.addEventListener("click", () => { item.parentElement.remove(); console.log('removed') }) })} ``` ```html <h1>ToDo Application</h1> <div class="container"> <div class="form-container"> <input type="text" placeholder="Add New Tasks"> <button>Add</button> </div> <div class="list-container"> <ul> <div class="list-item"> <li>Sample List Item</li> <span class="remove-li">(Remove Button)</span> </div> <div class="list-item"> <li>Sample List Item</li> <span class="remove-li">(Remove Button)</span> </div> <div class="list-item"> <li>Sample List Item</li> <span class="remove-li">(Remove Button)</span> </div> </ul> </div> </div> ```
69,364,940
The text is like "1-2years. 3years. 10years." I want get result `[(1,2),(3),(10)]`. I use python. I first tried `r"([0-9]?)[-]?([0-9])years"`. It works well except for the case of 10. I also tried `r"([0-9]?)[-]?([0-9]|10)years"` but the result is still `[(1,2),(3),(1,0)]`.
2021/09/28
[ "https://Stackoverflow.com/questions/69364940", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10490005/" ]
You need to listen for click event on newly added element. hence added a click listener on **newSpan** element after adding it into DOM. You are listening for event for removeLists element only but when you add a new element in the DOM, the newly doesn't have the click event. Hence, we have to listen for the event explicitly. I hope, it answers your question. :) ```js const toDoInput = document.querySelector("input"); const addButton = document.querySelector("button"); const listParent = document.querySelector("ul"); const removeLists = document.querySelectorAll(".remove-li"); const listItemMake = () => { if (toDoInput.value !== "") { const newDiv = document.createElement("div"); newDiv.classList.add("list-item"); const newListItem = document.createElement("li"); newListItem.append(toDoInput.value); newDiv.append(newListItem); toDoInput.value = ""; const newSpan = document.createElement("span"); newSpan.classList.add("remove-li"); newSpan.innerHTML = '(Remove Button)'; newDiv.append(newSpan); listParent.append(newDiv); newSpan.addEventListener("click", () => { newSpan.parentElement.remove(); }); } }; addButton.addEventListener("click", () => { listItemMake(); }); toDoInput.addEventListener("keydown", (event) => { if (event.code === "Enter") { listItemMake(); } }); for (const removeList of removeLists) { removeList.addEventListener("click", () => { removeList.parentElement.remove(); }) } ``` ```html <h1>ToDo Application</h1> <div class="container"> <div class="form-container"> <input type="text" placeholder="Add New Tasks"> <button>Add</button> </div> <div class="list-container"> <ul> <div class="list-item"> <li>Sample List Item</li> <span class="remove-li">(Remove Button)</span> </div> <div class="list-item"> <li>Sample List Item</li> <span class="remove-li">(Remove Button)</span> </div> <div class="list-item"> <li>Sample List Item</li> <span class="remove-li">(Remove Button)</span> </div> </ul> </div> </div> ```
You don't need the `removeLists` variable at all (just add event listeners to the static elements). The event listener to the `removeList` button/span should be added in the `listItemMake` function. The first three lines (`document.querySelector()`) return an [`Element DOM object`](https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector). The fourth line (`document.querySelectorAll()`) returns a static [`NodeList`](https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll) which can be iterated over similar to an array (but not all the same properties/methods). If you wanted to create an array from a `NodeList` so that you can use Array methods, you can use [`Array.from()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from) by passing in `document.querySelector()` (just one element) or `document.querySelectorAll()`. ```js const toDoInput = document.querySelector("input"); const addButton = document.querySelector("button"); const listParent = document.querySelector("ul"); // const removeLists = document.querySelectorAll(".remove-li"); const listItemMake = () => { if (toDoInput.value !== "") { const newDiv = document.createElement("div"); newDiv.classList.add("list-item"); const newListItem = document.createElement("li"); newListItem.append(toDoInput.value); newDiv.append(newListItem); toDoInput.value = ""; const newSpan = document.createElement("span"); newSpan.classList.add("remove-li"); newSpan.innerHTML = "(Remove Button)"; newDiv.append(newSpan); listParent.append(newDiv); newSpan.addEventListener("click", (event) => { event.target.parentElement.remove(); }); } }; addButton.addEventListener("click", () => { listItemMake(); }); toDoInput.addEventListener("keydown", (event) => { if (event.code === "Enter") { listItemMake(); } }); for (const removeList of document.querySelectorAll(".remove-li")) { removeList.addEventListener("click", () => { removeList.parentElement.remove(); }); } ``` ```html <h1>ToDo Application</h1> <div class="container"> <div class="form-container"> <input type="text" placeholder="Add New Tasks"> <button>Add</button> </div> <div class="list-container"> <ul> <div class="list-item"> <li>Sample List Item</li> <span class="remove-li">(Remove Button)</span> </div> <div class="list-item"> <li>Sample List Item</li> <span class="remove-li">(Remove Button)</span> </div> <div class="list-item"> <li>Sample List Item</li> <span class="remove-li">(Remove Button)</span> </div> </ul> </div> </div> ```
69,364,940
The text is like "1-2years. 3years. 10years." I want get result `[(1,2),(3),(10)]`. I use python. I first tried `r"([0-9]?)[-]?([0-9])years"`. It works well except for the case of 10. I also tried `r"([0-9]?)[-]?([0-9]|10)years"` but the result is still `[(1,2),(3),(1,0)]`.
2021/09/28
[ "https://Stackoverflow.com/questions/69364940", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10490005/" ]
Please change some code. Please add remove event function to listItemMake() function. ```js const toDoInput = document.querySelector("input"); const addButton = document.querySelector("button"); const listParent = document.querySelector("ul"); const listItemMake = () => { if (toDoInput.value !== "") { const newDiv = document.createElement("div"); newDiv.classList.add("list-item"); const newListItem = document.createElement("li"); newListItem.append(toDoInput.value); newDiv.append(newListItem); toDoInput.value = ""; const newSpan = document.createElement("span"); newSpan.classList.add("remove-li"); newSpan.innerHTML = '(Remove Button)'; newDiv.append(newSpan); listParent.append(newDiv); } addRemoveEvent(); }; addButton.addEventListener("click", () => { listItemMake(); }); toDoInput.addEventListener("keydown", (event) => { if (event.code === "Enter") { listItemMake(); } }); function addRemoveEvent() { const removeLists = document.querySelectorAll(".remove-li"); for (const removeList of removeLists) { removeList.addEventListener("click", () => { removeList.parentElement.remove(); }) } } addRemoveEvent(); ``` ```html <h1>ToDo Application</h1> <div class="container"> <div class="form-container"> <input type="text" placeholder="Add New Tasks"> <button>Add</button> </div> <div class="list-container"> <ul> <div class="list-item"> <li>Sample List Item</li> <span class="remove-li">(Remove Button)</span> </div> <div class="list-item"> <li>Sample List Item</li> <span class="remove-li">(Remove Button)</span> </div> <div class="list-item"> <li>Sample List Item</li> <span class="remove-li">(Remove Button)</span> </div> </ul> </div> </div> ```
```js const toDoInput = document.querySelector("input"); const addButton = document.querySelector("button"); const listParent = document.querySelector("ul"); const listItemMake = () => { if (toDoInput.value !== "") { const newDiv = document.createElement("div"); newDiv.classList.add("list-item"); const newListItem = document.createElement("li"); newListItem.append(toDoInput.value); newDiv.append(newListItem); toDoInput.value = ""; const newSpan = document.createElement("span"); newSpan.classList.add("remove-li"); newSpan.innerHTML = '(Remove Button)'; newDiv.append(newSpan); listParent.append(newDiv); } removeEvent() }; addButton.addEventListener("click", () => { listItemMake(); }); toDoInput.addEventListener("keydown", (event) => { if (event.code === "Enter") { listItemMake(); } }); const removeEvent = () => { const removeLists = document.querySelectorAll(".remove-li"); removeLists.forEach(item=>{ item.addEventListener("click", () => { item.parentElement.remove(); console.log('removed') }) })} ``` ```html <h1>ToDo Application</h1> <div class="container"> <div class="form-container"> <input type="text" placeholder="Add New Tasks"> <button>Add</button> </div> <div class="list-container"> <ul> <div class="list-item"> <li>Sample List Item</li> <span class="remove-li">(Remove Button)</span> </div> <div class="list-item"> <li>Sample List Item</li> <span class="remove-li">(Remove Button)</span> </div> <div class="list-item"> <li>Sample List Item</li> <span class="remove-li">(Remove Button)</span> </div> </ul> </div> </div> ```
69,364,940
The text is like "1-2years. 3years. 10years." I want get result `[(1,2),(3),(10)]`. I use python. I first tried `r"([0-9]?)[-]?([0-9])years"`. It works well except for the case of 10. I also tried `r"([0-9]?)[-]?([0-9]|10)years"` but the result is still `[(1,2),(3),(1,0)]`.
2021/09/28
[ "https://Stackoverflow.com/questions/69364940", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10490005/" ]
Please change some code. Please add remove event function to listItemMake() function. ```js const toDoInput = document.querySelector("input"); const addButton = document.querySelector("button"); const listParent = document.querySelector("ul"); const listItemMake = () => { if (toDoInput.value !== "") { const newDiv = document.createElement("div"); newDiv.classList.add("list-item"); const newListItem = document.createElement("li"); newListItem.append(toDoInput.value); newDiv.append(newListItem); toDoInput.value = ""; const newSpan = document.createElement("span"); newSpan.classList.add("remove-li"); newSpan.innerHTML = '(Remove Button)'; newDiv.append(newSpan); listParent.append(newDiv); } addRemoveEvent(); }; addButton.addEventListener("click", () => { listItemMake(); }); toDoInput.addEventListener("keydown", (event) => { if (event.code === "Enter") { listItemMake(); } }); function addRemoveEvent() { const removeLists = document.querySelectorAll(".remove-li"); for (const removeList of removeLists) { removeList.addEventListener("click", () => { removeList.parentElement.remove(); }) } } addRemoveEvent(); ``` ```html <h1>ToDo Application</h1> <div class="container"> <div class="form-container"> <input type="text" placeholder="Add New Tasks"> <button>Add</button> </div> <div class="list-container"> <ul> <div class="list-item"> <li>Sample List Item</li> <span class="remove-li">(Remove Button)</span> </div> <div class="list-item"> <li>Sample List Item</li> <span class="remove-li">(Remove Button)</span> </div> <div class="list-item"> <li>Sample List Item</li> <span class="remove-li">(Remove Button)</span> </div> </ul> </div> </div> ```
You don't need the `removeLists` variable at all (just add event listeners to the static elements). The event listener to the `removeList` button/span should be added in the `listItemMake` function. The first three lines (`document.querySelector()`) return an [`Element DOM object`](https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector). The fourth line (`document.querySelectorAll()`) returns a static [`NodeList`](https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll) which can be iterated over similar to an array (but not all the same properties/methods). If you wanted to create an array from a `NodeList` so that you can use Array methods, you can use [`Array.from()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from) by passing in `document.querySelector()` (just one element) or `document.querySelectorAll()`. ```js const toDoInput = document.querySelector("input"); const addButton = document.querySelector("button"); const listParent = document.querySelector("ul"); // const removeLists = document.querySelectorAll(".remove-li"); const listItemMake = () => { if (toDoInput.value !== "") { const newDiv = document.createElement("div"); newDiv.classList.add("list-item"); const newListItem = document.createElement("li"); newListItem.append(toDoInput.value); newDiv.append(newListItem); toDoInput.value = ""; const newSpan = document.createElement("span"); newSpan.classList.add("remove-li"); newSpan.innerHTML = "(Remove Button)"; newDiv.append(newSpan); listParent.append(newDiv); newSpan.addEventListener("click", (event) => { event.target.parentElement.remove(); }); } }; addButton.addEventListener("click", () => { listItemMake(); }); toDoInput.addEventListener("keydown", (event) => { if (event.code === "Enter") { listItemMake(); } }); for (const removeList of document.querySelectorAll(".remove-li")) { removeList.addEventListener("click", () => { removeList.parentElement.remove(); }); } ``` ```html <h1>ToDo Application</h1> <div class="container"> <div class="form-container"> <input type="text" placeholder="Add New Tasks"> <button>Add</button> </div> <div class="list-container"> <ul> <div class="list-item"> <li>Sample List Item</li> <span class="remove-li">(Remove Button)</span> </div> <div class="list-item"> <li>Sample List Item</li> <span class="remove-li">(Remove Button)</span> </div> <div class="list-item"> <li>Sample List Item</li> <span class="remove-li">(Remove Button)</span> </div> </ul> </div> </div> ```
69,364,940
The text is like "1-2years. 3years. 10years." I want get result `[(1,2),(3),(10)]`. I use python. I first tried `r"([0-9]?)[-]?([0-9])years"`. It works well except for the case of 10. I also tried `r"([0-9]?)[-]?([0-9]|10)years"` but the result is still `[(1,2),(3),(1,0)]`.
2021/09/28
[ "https://Stackoverflow.com/questions/69364940", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10490005/" ]
Try to move const removeLists and removeList.addEventListener to listItemMake function, so when you add new item const removeLists can include new list item. ```js const listItemMake = () => { if (toDoInput.value !== "") { const newDiv = document.createElement("div"); newDiv.classList.add("list-item"); const newListItem = document.createElement("li"); newListItem.append(toDoInput.value); newDiv.append(newListItem); toDoInput.value = ""; const newSpan = document.createElement("span"); newSpan.classList.add("remove-li"); newSpan.innerHTML = '(Remove Button)'; newDiv.append(newSpan); listParent.append(newDiv); } const removeLists = document.querySelectorAll(".remove-li"); for (const removeList of removeLists) { removeList.addEventListener("click", () => { removeList.parentElement.remove(); }) } }; ```
```js const toDoInput = document.querySelector("input"); const addButton = document.querySelector("button"); const listParent = document.querySelector("ul"); const listItemMake = () => { if (toDoInput.value !== "") { const newDiv = document.createElement("div"); newDiv.classList.add("list-item"); const newListItem = document.createElement("li"); newListItem.append(toDoInput.value); newDiv.append(newListItem); toDoInput.value = ""; const newSpan = document.createElement("span"); newSpan.classList.add("remove-li"); newSpan.innerHTML = '(Remove Button)'; newDiv.append(newSpan); listParent.append(newDiv); } removeEvent() }; addButton.addEventListener("click", () => { listItemMake(); }); toDoInput.addEventListener("keydown", (event) => { if (event.code === "Enter") { listItemMake(); } }); const removeEvent = () => { const removeLists = document.querySelectorAll(".remove-li"); removeLists.forEach(item=>{ item.addEventListener("click", () => { item.parentElement.remove(); console.log('removed') }) })} ``` ```html <h1>ToDo Application</h1> <div class="container"> <div class="form-container"> <input type="text" placeholder="Add New Tasks"> <button>Add</button> </div> <div class="list-container"> <ul> <div class="list-item"> <li>Sample List Item</li> <span class="remove-li">(Remove Button)</span> </div> <div class="list-item"> <li>Sample List Item</li> <span class="remove-li">(Remove Button)</span> </div> <div class="list-item"> <li>Sample List Item</li> <span class="remove-li">(Remove Button)</span> </div> </ul> </div> </div> ```
69,364,940
The text is like "1-2years. 3years. 10years." I want get result `[(1,2),(3),(10)]`. I use python. I first tried `r"([0-9]?)[-]?([0-9])years"`. It works well except for the case of 10. I also tried `r"([0-9]?)[-]?([0-9]|10)years"` but the result is still `[(1,2),(3),(1,0)]`.
2021/09/28
[ "https://Stackoverflow.com/questions/69364940", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10490005/" ]
Try to move const removeLists and removeList.addEventListener to listItemMake function, so when you add new item const removeLists can include new list item. ```js const listItemMake = () => { if (toDoInput.value !== "") { const newDiv = document.createElement("div"); newDiv.classList.add("list-item"); const newListItem = document.createElement("li"); newListItem.append(toDoInput.value); newDiv.append(newListItem); toDoInput.value = ""; const newSpan = document.createElement("span"); newSpan.classList.add("remove-li"); newSpan.innerHTML = '(Remove Button)'; newDiv.append(newSpan); listParent.append(newDiv); } const removeLists = document.querySelectorAll(".remove-li"); for (const removeList of removeLists) { removeList.addEventListener("click", () => { removeList.parentElement.remove(); }) } }; ```
You don't need the `removeLists` variable at all (just add event listeners to the static elements). The event listener to the `removeList` button/span should be added in the `listItemMake` function. The first three lines (`document.querySelector()`) return an [`Element DOM object`](https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector). The fourth line (`document.querySelectorAll()`) returns a static [`NodeList`](https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll) which can be iterated over similar to an array (but not all the same properties/methods). If you wanted to create an array from a `NodeList` so that you can use Array methods, you can use [`Array.from()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from) by passing in `document.querySelector()` (just one element) or `document.querySelectorAll()`. ```js const toDoInput = document.querySelector("input"); const addButton = document.querySelector("button"); const listParent = document.querySelector("ul"); // const removeLists = document.querySelectorAll(".remove-li"); const listItemMake = () => { if (toDoInput.value !== "") { const newDiv = document.createElement("div"); newDiv.classList.add("list-item"); const newListItem = document.createElement("li"); newListItem.append(toDoInput.value); newDiv.append(newListItem); toDoInput.value = ""; const newSpan = document.createElement("span"); newSpan.classList.add("remove-li"); newSpan.innerHTML = "(Remove Button)"; newDiv.append(newSpan); listParent.append(newDiv); newSpan.addEventListener("click", (event) => { event.target.parentElement.remove(); }); } }; addButton.addEventListener("click", () => { listItemMake(); }); toDoInput.addEventListener("keydown", (event) => { if (event.code === "Enter") { listItemMake(); } }); for (const removeList of document.querySelectorAll(".remove-li")) { removeList.addEventListener("click", () => { removeList.parentElement.remove(); }); } ``` ```html <h1>ToDo Application</h1> <div class="container"> <div class="form-container"> <input type="text" placeholder="Add New Tasks"> <button>Add</button> </div> <div class="list-container"> <ul> <div class="list-item"> <li>Sample List Item</li> <span class="remove-li">(Remove Button)</span> </div> <div class="list-item"> <li>Sample List Item</li> <span class="remove-li">(Remove Button)</span> </div> <div class="list-item"> <li>Sample List Item</li> <span class="remove-li">(Remove Button)</span> </div> </ul> </div> </div> ```
8,948,034
I want to retrieve and work with basic Vimeo data in python 3.2, given a video's URL. I'm a newcomer to JSON (and python), but it looked like the right fit for doing this. 1. Request Vimeo video data (via an API-formatted .json URL) 2. Convert returned JSON data into python dict 3. Display dict keys & data ("id", "title", "description", etc.) Another SO page [Get json data via url and use in python](https://stackoverflow.com/questions/1640715/get-json-data-via-url-and-use-in-python-simplejson) did something similar in python 2.x, but syntax changes (like integrating urllib2) led me to try this. ``` >>> import urllib >>> import json >>> req = urllib.request.urlopen("http://vimeo.com/api/v2/video/31161781.json") >>> opener = urllib.request.build_opener() >>> f = opener.open(req) Traceback (most recent call last): File "<pyshell#28>", line 1, in <module> f = opener.open(req) File "C:\Python32\lib\urllib\request.py", line 358, in open protocol = req.type AttributeError: 'HTTPResponse' object has no attribute 'type' ``` This code will integrate into an existing project, so I'm tied to using python. I know enough about HTTP queries to guess the data's within that response object, but not enough about python to understand why the open failed and how to reference it correctly. What should I try instead of `opener.open(req)`?
2012/01/20
[ "https://Stackoverflow.com/questions/8948034", "https://Stackoverflow.com", "https://Stackoverflow.com/users/73807/" ]
This works for me: ``` import urllib.request, json response = urllib.request.urlopen('http://vimeo.com/api/v2/video/31161781.json') content = response.read() data = json.loads(content.decode('utf8')) ``` Or with Requests: ``` import requests data = requests.get('http://vimeo.com/api/v2/video/31161781.json').json() ```
Check out: <http://www.voidspace.org.uk/python/articles/urllib2.shtml> ``` >>> import urllib2 >>> import json >>> req = urllib2.Request("http://vimeo.com/api/v2/video/31161781.json") >>> response = urllib2.urlopen(req) >>> content_string = response.read() >>> content_string '[{"id":31161781,"title":"Kevin Fanning talks about hiring for Boston startups","description":"CogoLabs.com talent developer and author Kevin Fanning talks about hiring for small teams in Boston, how job seekers can make themselves more attractive, and why recruiters should go the extra mile to attract talent.","url":"http:\\/\\/vimeo.com\\/31161781","upload_date":"2011-10-26 15:37:35","thumbnail_small":"http:\\/\\/b.vimeocdn.com\\/ts\\/209\\/777\\/209777866_100.jpg","thumbnail_medium":"http:\\/\\/b.vimeocdn.com\\/ts\\/209\\/777\\/209777866_200.jpg","thumbnail_large":"http:\\/\\/b.vimeocdn.com\\/ts\\/209\\/777\\/209777866_640.jpg","user_name":"Venture Cafe","user_url":"http:\\/\\/vimeo.com\\/venturecafe","user_portrait_small":"http:\\/\\/b.vimeocdn.com\\/ps\\/605\\/605070_30.jpg","user_portrait_medium":"http:\\/\\/b.vimeocdn.com\\/ps\\/605\\/605070_75.jpg","user_portrait_large":"http:\\/\\/b.vimeocdn.com\\/ps\\/605\\/605070_100.jpg","user_portrait_huge":"http:\\/\\/b.vimeocdn.com\\/ps\\/605\\/605070_300.jpg","stats_number_of_likes":0,"stats_number_of_plays":43,"stats_number_of_comments":0,"duration":531,"width":640,"height":360,"tags":"startup stories, entrepreneurship, interview, Venture Cafe, jobs","embed_privacy":"anywhere"}]' >>> loaded_content = json.loads(content_string) >>> type(content_string) <type 'str'> >>> type(loaded_content) <type 'list'> ```
8,948,034
I want to retrieve and work with basic Vimeo data in python 3.2, given a video's URL. I'm a newcomer to JSON (and python), but it looked like the right fit for doing this. 1. Request Vimeo video data (via an API-formatted .json URL) 2. Convert returned JSON data into python dict 3. Display dict keys & data ("id", "title", "description", etc.) Another SO page [Get json data via url and use in python](https://stackoverflow.com/questions/1640715/get-json-data-via-url-and-use-in-python-simplejson) did something similar in python 2.x, but syntax changes (like integrating urllib2) led me to try this. ``` >>> import urllib >>> import json >>> req = urllib.request.urlopen("http://vimeo.com/api/v2/video/31161781.json") >>> opener = urllib.request.build_opener() >>> f = opener.open(req) Traceback (most recent call last): File "<pyshell#28>", line 1, in <module> f = opener.open(req) File "C:\Python32\lib\urllib\request.py", line 358, in open protocol = req.type AttributeError: 'HTTPResponse' object has no attribute 'type' ``` This code will integrate into an existing project, so I'm tied to using python. I know enough about HTTP queries to guess the data's within that response object, but not enough about python to understand why the open failed and how to reference it correctly. What should I try instead of `opener.open(req)`?
2012/01/20
[ "https://Stackoverflow.com/questions/8948034", "https://Stackoverflow.com", "https://Stackoverflow.com/users/73807/" ]
Check out: <http://www.voidspace.org.uk/python/articles/urllib2.shtml> ``` >>> import urllib2 >>> import json >>> req = urllib2.Request("http://vimeo.com/api/v2/video/31161781.json") >>> response = urllib2.urlopen(req) >>> content_string = response.read() >>> content_string '[{"id":31161781,"title":"Kevin Fanning talks about hiring for Boston startups","description":"CogoLabs.com talent developer and author Kevin Fanning talks about hiring for small teams in Boston, how job seekers can make themselves more attractive, and why recruiters should go the extra mile to attract talent.","url":"http:\\/\\/vimeo.com\\/31161781","upload_date":"2011-10-26 15:37:35","thumbnail_small":"http:\\/\\/b.vimeocdn.com\\/ts\\/209\\/777\\/209777866_100.jpg","thumbnail_medium":"http:\\/\\/b.vimeocdn.com\\/ts\\/209\\/777\\/209777866_200.jpg","thumbnail_large":"http:\\/\\/b.vimeocdn.com\\/ts\\/209\\/777\\/209777866_640.jpg","user_name":"Venture Cafe","user_url":"http:\\/\\/vimeo.com\\/venturecafe","user_portrait_small":"http:\\/\\/b.vimeocdn.com\\/ps\\/605\\/605070_30.jpg","user_portrait_medium":"http:\\/\\/b.vimeocdn.com\\/ps\\/605\\/605070_75.jpg","user_portrait_large":"http:\\/\\/b.vimeocdn.com\\/ps\\/605\\/605070_100.jpg","user_portrait_huge":"http:\\/\\/b.vimeocdn.com\\/ps\\/605\\/605070_300.jpg","stats_number_of_likes":0,"stats_number_of_plays":43,"stats_number_of_comments":0,"duration":531,"width":640,"height":360,"tags":"startup stories, entrepreneurship, interview, Venture Cafe, jobs","embed_privacy":"anywhere"}]' >>> loaded_content = json.loads(content_string) >>> type(content_string) <type 'str'> >>> type(loaded_content) <type 'list'> ```
**you can try to like so:** ``` import requests url1 = 'http://vimeo.com/api/v2/video/31161781.json' html = requests.get(url1) html.encoding = html.apparent_encoding print(html.text) ```
8,948,034
I want to retrieve and work with basic Vimeo data in python 3.2, given a video's URL. I'm a newcomer to JSON (and python), but it looked like the right fit for doing this. 1. Request Vimeo video data (via an API-formatted .json URL) 2. Convert returned JSON data into python dict 3. Display dict keys & data ("id", "title", "description", etc.) Another SO page [Get json data via url and use in python](https://stackoverflow.com/questions/1640715/get-json-data-via-url-and-use-in-python-simplejson) did something similar in python 2.x, but syntax changes (like integrating urllib2) led me to try this. ``` >>> import urllib >>> import json >>> req = urllib.request.urlopen("http://vimeo.com/api/v2/video/31161781.json") >>> opener = urllib.request.build_opener() >>> f = opener.open(req) Traceback (most recent call last): File "<pyshell#28>", line 1, in <module> f = opener.open(req) File "C:\Python32\lib\urllib\request.py", line 358, in open protocol = req.type AttributeError: 'HTTPResponse' object has no attribute 'type' ``` This code will integrate into an existing project, so I'm tied to using python. I know enough about HTTP queries to guess the data's within that response object, but not enough about python to understand why the open failed and how to reference it correctly. What should I try instead of `opener.open(req)`?
2012/01/20
[ "https://Stackoverflow.com/questions/8948034", "https://Stackoverflow.com", "https://Stackoverflow.com/users/73807/" ]
This works for me: ``` import urllib.request, json response = urllib.request.urlopen('http://vimeo.com/api/v2/video/31161781.json') content = response.read() data = json.loads(content.decode('utf8')) ``` Or with Requests: ``` import requests data = requests.get('http://vimeo.com/api/v2/video/31161781.json').json() ```
Can you try to just request the url like so ``` response = urllib.urlopen('http://www.weather.com/weather/today/Ellicott+City+MD+21042') response_dict = json.loads(response.read()) ``` As you see python has a lot of libraries that share functionality, you shouldn't need to build an opener or anything to get this data.
8,948,034
I want to retrieve and work with basic Vimeo data in python 3.2, given a video's URL. I'm a newcomer to JSON (and python), but it looked like the right fit for doing this. 1. Request Vimeo video data (via an API-formatted .json URL) 2. Convert returned JSON data into python dict 3. Display dict keys & data ("id", "title", "description", etc.) Another SO page [Get json data via url and use in python](https://stackoverflow.com/questions/1640715/get-json-data-via-url-and-use-in-python-simplejson) did something similar in python 2.x, but syntax changes (like integrating urllib2) led me to try this. ``` >>> import urllib >>> import json >>> req = urllib.request.urlopen("http://vimeo.com/api/v2/video/31161781.json") >>> opener = urllib.request.build_opener() >>> f = opener.open(req) Traceback (most recent call last): File "<pyshell#28>", line 1, in <module> f = opener.open(req) File "C:\Python32\lib\urllib\request.py", line 358, in open protocol = req.type AttributeError: 'HTTPResponse' object has no attribute 'type' ``` This code will integrate into an existing project, so I'm tied to using python. I know enough about HTTP queries to guess the data's within that response object, but not enough about python to understand why the open failed and how to reference it correctly. What should I try instead of `opener.open(req)`?
2012/01/20
[ "https://Stackoverflow.com/questions/8948034", "https://Stackoverflow.com", "https://Stackoverflow.com/users/73807/" ]
Can you try to just request the url like so ``` response = urllib.urlopen('http://www.weather.com/weather/today/Ellicott+City+MD+21042') response_dict = json.loads(response.read()) ``` As you see python has a lot of libraries that share functionality, you shouldn't need to build an opener or anything to get this data.
**you can try to like so:** ``` import requests url1 = 'http://vimeo.com/api/v2/video/31161781.json' html = requests.get(url1) html.encoding = html.apparent_encoding print(html.text) ```
8,948,034
I want to retrieve and work with basic Vimeo data in python 3.2, given a video's URL. I'm a newcomer to JSON (and python), but it looked like the right fit for doing this. 1. Request Vimeo video data (via an API-formatted .json URL) 2. Convert returned JSON data into python dict 3. Display dict keys & data ("id", "title", "description", etc.) Another SO page [Get json data via url and use in python](https://stackoverflow.com/questions/1640715/get-json-data-via-url-and-use-in-python-simplejson) did something similar in python 2.x, but syntax changes (like integrating urllib2) led me to try this. ``` >>> import urllib >>> import json >>> req = urllib.request.urlopen("http://vimeo.com/api/v2/video/31161781.json") >>> opener = urllib.request.build_opener() >>> f = opener.open(req) Traceback (most recent call last): File "<pyshell#28>", line 1, in <module> f = opener.open(req) File "C:\Python32\lib\urllib\request.py", line 358, in open protocol = req.type AttributeError: 'HTTPResponse' object has no attribute 'type' ``` This code will integrate into an existing project, so I'm tied to using python. I know enough about HTTP queries to guess the data's within that response object, but not enough about python to understand why the open failed and how to reference it correctly. What should I try instead of `opener.open(req)`?
2012/01/20
[ "https://Stackoverflow.com/questions/8948034", "https://Stackoverflow.com", "https://Stackoverflow.com/users/73807/" ]
This works for me: ``` import urllib.request, json response = urllib.request.urlopen('http://vimeo.com/api/v2/video/31161781.json') content = response.read() data = json.loads(content.decode('utf8')) ``` Or with Requests: ``` import requests data = requests.get('http://vimeo.com/api/v2/video/31161781.json').json() ```
**you can try to like so:** ``` import requests url1 = 'http://vimeo.com/api/v2/video/31161781.json' html = requests.get(url1) html.encoding = html.apparent_encoding print(html.text) ```
48,117,638
I would like to know how to have setup.py install c modules locally. Locally as in not in `/usr/local/python..` and not in `~/local/python...`, but in `[where_all_my_code_is]/bin` and I can import it from scripts within the [where\_all\_my\_code\_is] folder. I have some c code. src/foo/foo.c ``` #include <Python.h> static PyObject * foo(PyObject* o) { PyObject* five = PyInt_FromLong(5); return PyNumber_Add(&o, &five); } static PyMethodDef funcs[] = { {"foo", (PyCFunction)foo, METH_VARARGS, "foo, foo and more foo"}, {NULL, NULL, 0, NULL} }; PyMODINIT_FUNC initaddList(void){ Py_InitModule3("foo", funcs, "do the foo"); } ``` setup.py ``` from distutils.core import setup, Extension setup(name='foo', version='1.0', ext_modules=[Extension('foo', ['src/foo/foo.c'])]) ``` Now, instead of installing this into my whatever /local/python folders or whatever, I want the code to be in a bin folder right there next to the module. e.g. ``` ~/My_python_project ./src ./foo ./foo.c ./some_code_that_imports_foo.py ./bin ./foo ./my_importable_foo.so ``` some\_code\_that\_imports\_foo.py: ``` import foo print(foo.foo(10)) # prints 15 ``` What is the appropriate/nicest way to accomplish this thing?
2018/01/05
[ "https://Stackoverflow.com/questions/48117638", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2886575/" ]
Here is one option: setup using ``` $ python3 setup.py install --root . --install-lib lib ``` add local `lib` path to the python path ``` $ export PYTHONPATH:$PYTHONPATH:./lib ``` Now python scripts in `.` can import the `c` modules we just compiled. Something fancier would need to be used for the exact scenario I suggested in the question, but the general procedure should apply. limitations? possible pitfalls? brittlenesses?
you would have to create custom package for the type of os you are using, deb or rpm or ebuild these system level tools install files into /usr/bin and /usr/lib instead of your local builds which go to /usr/local or user builds ~/local.
37,955,984
I don't have a clue what's causing this error. It appears to be a bug that there isn't a fix for. Could anyone tell give me a hint as to how I might get around this? It's frustrating me to no end. Thanks. ``` Operations to perform: Apply all migrations: admin, contenttypes, optilab, auth, sessions Running migrations: Rendering model states... DONE Applying optilab.0006_auto_20160621_1640...Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "C:\Python27\lib\site-packages\django\core\management\__init__.py", line 353, in execute_from_command_line utility.execute() File "C:\Python27\lib\site-packages\django\core\management\__init__.py", line 345, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Python27\lib\site-packages\django\core\management\base.py", line 348, in run_from_argv self.execute(*args, **cmd_options) File "C:\Python27\lib\site-packages\django\core\management\base.py", line 399, in execute output = self.handle(*args, **options) File "C:\Python27\lib\site-packages\django\core\management\commands\migrate.py", line 200, in handle executor.migrate(targets, plan, fake=fake, fake_initial=fake_initial) File "C:\Python27\lib\site-packages\django\db\migrations\executor.py", line 92, in migrate self._migrate_all_forwards(plan, full_plan, fake=fake, fake_initial=fake_initial) File "C:\Python27\lib\site-packages\django\db\migrations\executor.py", line 121, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "C:\Python27\lib\site-packages\django\db\migrations\executor.py", line 198, in apply_migration state = migration.apply(state, schema_editor) File "C:\Python27\lib\site-packages\django\db\migrations\migration.py", line 123, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "C:\Python27\lib\site-packages\django\db\migrations\operations\fields.py", line 121, in database_forwards schema_editor.remove_field(from_model, from_model._meta.get_field(self.name)) File "C:\Python27\lib\site-packages\django\db\backends\sqlite3\schema.py", line 247, in remove_field self._remake_table(model, delete_fields=[field]) File "C:\Python27\lib\site-packages\django\db\backends\sqlite3\schema.py", line 197, in _remake_table self.quote_name(model._meta.db_table), File "C:\Python27\lib\site-packages\django\db\backends\base\schema.py", line 110, in execute cursor.execute(sql, params) File "C:\Python27\lib\site-packages\django\db\backends\utils.py", line 79, in execute return super(CursorDebugWrapper, self).execute(sql, params) File "C:\Python27\lib\site-packages\django\db\backends\utils.py", line 64, in execute return self.cursor.execute(sql, params) File "C:\Python27\lib\site-packages\django\db\utils.py", line 95, in __exit__ six.reraise(dj_exc_type, dj_exc_value, traceback) File "C:\Python27\lib\site-packages\django\db\backends\utils.py", line 64, in execute return self.cursor.execute(sql, params) File "C:\Python27\lib\site-packages\django\db\backends\sqlite3\base.py", line 323, in execute return Database.Cursor.execute(self, query, params) django.db.utils.OperationalError: near ")": syntax error ``` Here's the contents of 0006\_auto\_20160621\_1640.py ``` # -*- coding: utf-8 -*- # Generated by Django 1.9.6 on 2016-06-21 22:40 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('optilab', '0005_test'), ] operations = [ migrations.RemoveField( model_name='lasersubstrate', name='substrate_ptr', ), migrations.RemoveField( model_name='waveguidesubstrate', name='substrate_ptr', ), migrations.DeleteModel( name='LaserSubstrate', ), migrations.DeleteModel( name='WaveguideSubstrate', ), ] ``` Here's the SQL produced from running 'python manage.py sqlmigrate optilab 0006' ``` BEGIN; -- -- Remove field substrate_ptr from lasersubstrate -- ALTER TABLE "optilab_lasersubstrate" RENAME TO "optilab_lasersubstrate__old"; CREATE TABLE "optilab_lasersubstrate" ("substrate_ptr_id" integer NOT NULL PRIMARY KEY REFERENCES "optilab_substrate" ("id")); INSERT INTO "optilab_lasersubstrate" () SELECT FROM "optilab_lasersubstrate__old"; DROP TABLE "optilab_lasersubstrate__old"; -- -- Remove field substrate_ptr from waveguidesubstrate -- ALTER TABLE "optilab_waveguidesubstrate" RENAME TO "optilab_waveguidesubstrate__old"; CREATE TABLE "optilab_waveguidesubstrate" ("substrate_ptr_id" integer NOT NULL PRIMARY KEY REFERENCES "optilab_substrate" ("id")); INSERT INTO "optilab_waveguidesubstrate" () SELECT FROM "optilab_waveguidesubstrate__old"; DROP TABLE "optilab_waveguidesubstrate__old"; -- -- Delete model LaserSubstrate -- DROP TABLE "optilab_lasersubstrate"; -- -- Delete model WaveguideSubstrate -- DROP TABLE "optilab_waveguidesubstrate"; COMMIT; ```
2016/06/21
[ "https://Stackoverflow.com/questions/37955984", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2075859/" ]
This appears to be the line that's causing the errror: ``` INSERT INTO "optilab_lasersubstrate" () SELECT FROM "optilab_lasersubstrate__old"; ``` You are usually expected to have a list of columns in those parenthesis. Eg `INSERT INTO "optilab_lasersubstrate" (col1,col2,etc)` however the migration has produced a blank set! Similarly the `SELECT FROM` portion should read as `SELECT col1,col2 FROM`. By some strange set of events you appear to have managed to create a table with no columns!! I see from your migration file that you are anyway dropping this table. So there isn't any reason to struggle with the `RemoveField` portion. It's code associated with the `RemoveField` that's causing the error. Change your migration as follows: ``` class Migration(migrations.Migration): dependencies = [ ('optilab', '0005_test'), ] operations = [ migrations.DeleteModel( name='LaserSubstrate', ), migrations.DeleteModel( name='WaveguideSubstrate', ), ] ```
Edit base.py in the lines that breaks and update it to: ``` def execute(self, query, params=None): if params is None: if '()' not in str(query): return Database.Cursor.execute(self, query) query = self.convert_query(query) if '()' not in str(query): return Database.Cursor.execute(self, query, params) ```
33,281,217
I'm crawling through a simple, but long HTML chunk, which is similar to this: ```html <table> <tbody> <tr> <td> Some text </td> <td> Some text </td> </tr> <tr> <td> Some text <br/> Some more text </td> </tr> </tbody> </table> ``` I'm collecting the data with following little python code (using lxml): ``` for element in root.iter(): if element == 'td': print element.text ``` Some of the texts are divided into two rows, but mostly they fit in a single row. The problem is within the divided rows. The root element is the 'table' tag. That little code can print out all the other texts, but not what comes after the 'br' tags. If I don't exclude non-td tags, the code tries to print possible text from inside the 'br' tags, but of course there's nothing in there and thus this prints just empty new line. However after this 'br', the code moves to the next tag on the line within the iteration, but ignores that data that's still inside the previous 'td' tag. How can I get also the data after those tags? Edit: It seems that some of the 'br' tags are self closing, but some are left open ```html <td> Some text <br> Some more text </td> ``` The element.tail method, suggested in the first answer, does not seem to be able to get the data after that open tag. Edit2: Actually it works. Was my own mistake. Forgot to mention that the "print element.text" part was encapsulated by try-except, which in case of the br tag caught an AttributeError, because there's nothing inside the br tags. I had set the exception to just pass and print out nothing. Inside the same try-except I tried also print out the tail, but printing out the tail was never reached, because of the exception that happened before it.
2015/10/22
[ "https://Stackoverflow.com/questions/33281217", "https://Stackoverflow.com", "https://Stackoverflow.com/users/256965/" ]
Because `<br/>` is a self-closing tag, it does not have any `text` content. Instead, you need to access it's `tail` content. The `tail` content is the content after the element's closing tag, but before the next opening tag. To access this content in your for loop you will need to use the following: ``` for element in root.iter(): element_text = element.text element_tail = element.tail ``` Even if the `br` tag is an opening tag, this method will still work: ``` from lxml import etree content = ''' <table> <tbody> <tr> <td> Some text </td> <td> Some text </td> </tr> <tr> <td> Some text <br> Some more text </td> </tr> </tbody> </table> ''' root = etree.HTML(content) for element in root.iter(): print(element.tail) ``` **Output** ``` Some more text ```
To me below is working to extract all the text after `br`- ``` normalize-space(//table//br/following::text()[1]) ``` **Working example is** [**at**](http://www.xpathtester.com/xpath/283dca20a024adbb5ece93de6c914531).
30,975,911
I have a python list of list as follows. I want to flatten it to a single list. ``` l = [u'[190215]'] ``` I am trying. ``` l = [item for value in l for item in value] ``` It turns the list to `[u'[', u'1', u'9', u'0', u'2', u'1', u'5', u']']` How to remove the `u` from the list.
2015/06/22
[ "https://Stackoverflow.com/questions/30975911", "https://Stackoverflow.com", "https://Stackoverflow.com/users/567797/" ]
The `u` means a [`unicode`](https://docs.python.org/2/howto/unicode.html) string which should be perfectly fine to use. But if you want to convert `unicode` to `str` (which just represents plain bytes in Python 2) then you may `encode` it using a character encoding such as `utf-8`. ``` >>> items = [u'[190215]'] >>> [item.encode('utf-8') for item in items] ['[190215]'] ```
You can convert your unicode to normal string with `str` : ``` >>> list(str(l[0])) ['[', '1', '9', '0', '2', '1', '5', ']'] ```
30,975,911
I have a python list of list as follows. I want to flatten it to a single list. ``` l = [u'[190215]'] ``` I am trying. ``` l = [item for value in l for item in value] ``` It turns the list to `[u'[', u'1', u'9', u'0', u'2', u'1', u'5', u']']` How to remove the `u` from the list.
2015/06/22
[ "https://Stackoverflow.com/questions/30975911", "https://Stackoverflow.com", "https://Stackoverflow.com/users/567797/" ]
The `u` means a [`unicode`](https://docs.python.org/2/howto/unicode.html) string which should be perfectly fine to use. But if you want to convert `unicode` to `str` (which just represents plain bytes in Python 2) then you may `encode` it using a character encoding such as `utf-8`. ``` >>> items = [u'[190215]'] >>> [item.encode('utf-8') for item in items] ['[190215]'] ```
In your current code, you are iterating on a string, which represents a list, hence you get the individual characters. ``` >>> from ast import literal_eval >>> l = [u'[190215]'] >>> l = [item for value in l for item in value] >>> l [u'[', u'1', u'9', u'0', u'2', u'1', u'5', u']'] ``` Seems to me, you want to convert the inner string representation of list, to a flattened list, so here you go: ``` >>> l = [u'[190215]'] >>> l = [item for value in l for item in literal_eval(value)] >>> l [190215] ``` --- The above will work only when all the inner lists are strings: ``` >>> l = [u'[190215]', u'[190216, 190217]'] >>> l = [item for value in l for item in literal_eval(value)] >>> l [190215, 190216, 190217] >>> l = [u'[190215]', u'[190216, 190217]', [12, 12]] >>> l = [item for value in l for item in literal_eval(value)] Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python2.7/ast.py", line 80, in literal_eval return _convert(node_or_string) File "/usr/lib/python2.7/ast.py", line 79, in _convert raise ValueError('malformed string') ValueError: malformed string ```
30,975,911
I have a python list of list as follows. I want to flatten it to a single list. ``` l = [u'[190215]'] ``` I am trying. ``` l = [item for value in l for item in value] ``` It turns the list to `[u'[', u'1', u'9', u'0', u'2', u'1', u'5', u']']` How to remove the `u` from the list.
2015/06/22
[ "https://Stackoverflow.com/questions/30975911", "https://Stackoverflow.com", "https://Stackoverflow.com/users/567797/" ]
The `u` means a [`unicode`](https://docs.python.org/2/howto/unicode.html) string which should be perfectly fine to use. But if you want to convert `unicode` to `str` (which just represents plain bytes in Python 2) then you may `encode` it using a character encoding such as `utf-8`. ``` >>> items = [u'[190215]'] >>> [item.encode('utf-8') for item in items] ['[190215]'] ```
use `[str(item) for item in list]` example ``` >>> li = [u'a', u'b', u'c', u'd'] >>> print li [u'a', u'b', u'c', u'd'] >>> li_u_removed = [str(i) for i in li] >>> print li_u_removed ['a', 'b', 'c', 'd'] ```
30,975,911
I have a python list of list as follows. I want to flatten it to a single list. ``` l = [u'[190215]'] ``` I am trying. ``` l = [item for value in l for item in value] ``` It turns the list to `[u'[', u'1', u'9', u'0', u'2', u'1', u'5', u']']` How to remove the `u` from the list.
2015/06/22
[ "https://Stackoverflow.com/questions/30975911", "https://Stackoverflow.com", "https://Stackoverflow.com/users/567797/" ]
The `u` means a [`unicode`](https://docs.python.org/2/howto/unicode.html) string which should be perfectly fine to use. But if you want to convert `unicode` to `str` (which just represents plain bytes in Python 2) then you may `encode` it using a character encoding such as `utf-8`. ``` >>> items = [u'[190215]'] >>> [item.encode('utf-8') for item in items] ['[190215]'] ```
I think this issue occurred in `python 2.7` but in latest python version **u** did not displayed when it run ``` l = [u'[190215]'] l = [item for value in l for item in value] print(l) ``` **output -:** `['[', '1', '9', '0', '2', '1', '5', ']']` If you want to **concatenate** string items in a list into a single string, you can try this code ``` l = [u'[190215]'] l = [item for value in l for item in value] l = ''.join(l) print(l) ``` **output -:** `[190215]`
30,975,911
I have a python list of list as follows. I want to flatten it to a single list. ``` l = [u'[190215]'] ``` I am trying. ``` l = [item for value in l for item in value] ``` It turns the list to `[u'[', u'1', u'9', u'0', u'2', u'1', u'5', u']']` How to remove the `u` from the list.
2015/06/22
[ "https://Stackoverflow.com/questions/30975911", "https://Stackoverflow.com", "https://Stackoverflow.com/users/567797/" ]
In your current code, you are iterating on a string, which represents a list, hence you get the individual characters. ``` >>> from ast import literal_eval >>> l = [u'[190215]'] >>> l = [item for value in l for item in value] >>> l [u'[', u'1', u'9', u'0', u'2', u'1', u'5', u']'] ``` Seems to me, you want to convert the inner string representation of list, to a flattened list, so here you go: ``` >>> l = [u'[190215]'] >>> l = [item for value in l for item in literal_eval(value)] >>> l [190215] ``` --- The above will work only when all the inner lists are strings: ``` >>> l = [u'[190215]', u'[190216, 190217]'] >>> l = [item for value in l for item in literal_eval(value)] >>> l [190215, 190216, 190217] >>> l = [u'[190215]', u'[190216, 190217]', [12, 12]] >>> l = [item for value in l for item in literal_eval(value)] Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python2.7/ast.py", line 80, in literal_eval return _convert(node_or_string) File "/usr/lib/python2.7/ast.py", line 79, in _convert raise ValueError('malformed string') ValueError: malformed string ```
You can convert your unicode to normal string with `str` : ``` >>> list(str(l[0])) ['[', '1', '9', '0', '2', '1', '5', ']'] ```
30,975,911
I have a python list of list as follows. I want to flatten it to a single list. ``` l = [u'[190215]'] ``` I am trying. ``` l = [item for value in l for item in value] ``` It turns the list to `[u'[', u'1', u'9', u'0', u'2', u'1', u'5', u']']` How to remove the `u` from the list.
2015/06/22
[ "https://Stackoverflow.com/questions/30975911", "https://Stackoverflow.com", "https://Stackoverflow.com/users/567797/" ]
use `[str(item) for item in list]` example ``` >>> li = [u'a', u'b', u'c', u'd'] >>> print li [u'a', u'b', u'c', u'd'] >>> li_u_removed = [str(i) for i in li] >>> print li_u_removed ['a', 'b', 'c', 'd'] ```
You can convert your unicode to normal string with `str` : ``` >>> list(str(l[0])) ['[', '1', '9', '0', '2', '1', '5', ']'] ```
30,975,911
I have a python list of list as follows. I want to flatten it to a single list. ``` l = [u'[190215]'] ``` I am trying. ``` l = [item for value in l for item in value] ``` It turns the list to `[u'[', u'1', u'9', u'0', u'2', u'1', u'5', u']']` How to remove the `u` from the list.
2015/06/22
[ "https://Stackoverflow.com/questions/30975911", "https://Stackoverflow.com", "https://Stackoverflow.com/users/567797/" ]
You can convert your unicode to normal string with `str` : ``` >>> list(str(l[0])) ['[', '1', '9', '0', '2', '1', '5', ']'] ```
I think this issue occurred in `python 2.7` but in latest python version **u** did not displayed when it run ``` l = [u'[190215]'] l = [item for value in l for item in value] print(l) ``` **output -:** `['[', '1', '9', '0', '2', '1', '5', ']']` If you want to **concatenate** string items in a list into a single string, you can try this code ``` l = [u'[190215]'] l = [item for value in l for item in value] l = ''.join(l) print(l) ``` **output -:** `[190215]`
30,975,911
I have a python list of list as follows. I want to flatten it to a single list. ``` l = [u'[190215]'] ``` I am trying. ``` l = [item for value in l for item in value] ``` It turns the list to `[u'[', u'1', u'9', u'0', u'2', u'1', u'5', u']']` How to remove the `u` from the list.
2015/06/22
[ "https://Stackoverflow.com/questions/30975911", "https://Stackoverflow.com", "https://Stackoverflow.com/users/567797/" ]
In your current code, you are iterating on a string, which represents a list, hence you get the individual characters. ``` >>> from ast import literal_eval >>> l = [u'[190215]'] >>> l = [item for value in l for item in value] >>> l [u'[', u'1', u'9', u'0', u'2', u'1', u'5', u']'] ``` Seems to me, you want to convert the inner string representation of list, to a flattened list, so here you go: ``` >>> l = [u'[190215]'] >>> l = [item for value in l for item in literal_eval(value)] >>> l [190215] ``` --- The above will work only when all the inner lists are strings: ``` >>> l = [u'[190215]', u'[190216, 190217]'] >>> l = [item for value in l for item in literal_eval(value)] >>> l [190215, 190216, 190217] >>> l = [u'[190215]', u'[190216, 190217]', [12, 12]] >>> l = [item for value in l for item in literal_eval(value)] Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/lib/python2.7/ast.py", line 80, in literal_eval return _convert(node_or_string) File "/usr/lib/python2.7/ast.py", line 79, in _convert raise ValueError('malformed string') ValueError: malformed string ```
I think this issue occurred in `python 2.7` but in latest python version **u** did not displayed when it run ``` l = [u'[190215]'] l = [item for value in l for item in value] print(l) ``` **output -:** `['[', '1', '9', '0', '2', '1', '5', ']']` If you want to **concatenate** string items in a list into a single string, you can try this code ``` l = [u'[190215]'] l = [item for value in l for item in value] l = ''.join(l) print(l) ``` **output -:** `[190215]`
30,975,911
I have a python list of list as follows. I want to flatten it to a single list. ``` l = [u'[190215]'] ``` I am trying. ``` l = [item for value in l for item in value] ``` It turns the list to `[u'[', u'1', u'9', u'0', u'2', u'1', u'5', u']']` How to remove the `u` from the list.
2015/06/22
[ "https://Stackoverflow.com/questions/30975911", "https://Stackoverflow.com", "https://Stackoverflow.com/users/567797/" ]
use `[str(item) for item in list]` example ``` >>> li = [u'a', u'b', u'c', u'd'] >>> print li [u'a', u'b', u'c', u'd'] >>> li_u_removed = [str(i) for i in li] >>> print li_u_removed ['a', 'b', 'c', 'd'] ```
I think this issue occurred in `python 2.7` but in latest python version **u** did not displayed when it run ``` l = [u'[190215]'] l = [item for value in l for item in value] print(l) ``` **output -:** `['[', '1', '9', '0', '2', '1', '5', ']']` If you want to **concatenate** string items in a list into a single string, you can try this code ``` l = [u'[190215]'] l = [item for value in l for item in value] l = ''.join(l) print(l) ``` **output -:** `[190215]`