qid
int64 46k
74.7M
| question
stringlengths 54
37.8k
| date
stringlengths 10
10
| metadata
sequencelengths 3
3
| response_j
stringlengths 17
26k
| response_k
stringlengths 26
26k
|
---|---|---|---|---|---|
17,219,675 | I am trying to use bash functions inside my python script to allow me to locate a specific directory and then grep a given file inside the directory. The catch is that I only have part of the directory name, so I need to use the bash function find to get the rest of the directory name (names are unique and will only ever return one folder)
The code I have so far is as follows:
```
def get_tag(part_of_foldername):
import subprocess
import os
p1 = subprocess.Popen(["find", "/path/to/directory", "-maxdepth", "1", "-name", "%s.*" % part_of_foldername, "-type", "d"], stdout=subprocess.PIPE)
directory = p1.communicate()[0].strip('\n')
os.chdir(directory)
p2 = subprocess.Popen(["grep", "STUFF_", ".hgtags"], stdout=subprocess.PIPE)
tag = p2.comminucate()[0].strip('\n')
return tag
```
Here is what's really strange. This code works when you enter it line by line into interactive, but not when it's run thru a script. It also works when you import the script file into interactive and call the function, but not when it's called by the main function. The traceback I get from running the script straight is as follows:
```
Traceback (most recent call last):
File "./integration.py", line 64, in <module>
main()
File "./integration.py", line 48, in main
tag = get_tag(folder)
File "./integration.py", line 9, in get_date
os.chdir(directory)
OSError: [Errno 2] No such file or directory: ''
```
And it's called in the main function like this:
```
if block_dict[block][0]=='0':
tag = get_tag(folder)
```
with "folder" being previously defined as a string.
Please note we use python 2.6 so I can't use the module check\_output unfortunately. | 2013/06/20 | [
"https://Stackoverflow.com/questions/17219675",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2506070/"
] | The right way is checking the `Value` property of the item selected on the list control.
You could use `SelectedValue` property, try something like this:
```
if(radioButtonList.SelectedValue == "Option 2")
{
Messagebox.Show("Warning: Selecting this option may release deadly neurotoxins")
}
```
You also can check using `SelectedItem.Text` property.
```
if(radioButtonList.SelectedItem.Text == "Option 2")
{
Messagebox.Show("Warning: Selecting this option may release deadly neurotoxins")
}
```
If you are on asp.net, you do not have Messagebox.Show, you should use a javascript alert. | Try this one.I hope it helps.
```
if(radioButtonList.SelectedValue == "Option 2")
{
string script = "alert('Warning: Selecting this option may release deadly neurotoxins');";
ClientScript.RegisterClientScriptBlock(this.GetType(), "Alert", script, true);
}
``` |
17,219,675 | I am trying to use bash functions inside my python script to allow me to locate a specific directory and then grep a given file inside the directory. The catch is that I only have part of the directory name, so I need to use the bash function find to get the rest of the directory name (names are unique and will only ever return one folder)
The code I have so far is as follows:
```
def get_tag(part_of_foldername):
import subprocess
import os
p1 = subprocess.Popen(["find", "/path/to/directory", "-maxdepth", "1", "-name", "%s.*" % part_of_foldername, "-type", "d"], stdout=subprocess.PIPE)
directory = p1.communicate()[0].strip('\n')
os.chdir(directory)
p2 = subprocess.Popen(["grep", "STUFF_", ".hgtags"], stdout=subprocess.PIPE)
tag = p2.comminucate()[0].strip('\n')
return tag
```
Here is what's really strange. This code works when you enter it line by line into interactive, but not when it's run thru a script. It also works when you import the script file into interactive and call the function, but not when it's called by the main function. The traceback I get from running the script straight is as follows:
```
Traceback (most recent call last):
File "./integration.py", line 64, in <module>
main()
File "./integration.py", line 48, in main
tag = get_tag(folder)
File "./integration.py", line 9, in get_date
os.chdir(directory)
OSError: [Errno 2] No such file or directory: ''
```
And it's called in the main function like this:
```
if block_dict[block][0]=='0':
tag = get_tag(folder)
```
with "folder" being previously defined as a string.
Please note we use python 2.6 so I can't use the module check\_output unfortunately. | 2013/06/20 | [
"https://Stackoverflow.com/questions/17219675",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2506070/"
] | The right way is checking the `Value` property of the item selected on the list control.
You could use `SelectedValue` property, try something like this:
```
if(radioButtonList.SelectedValue == "Option 2")
{
Messagebox.Show("Warning: Selecting this option may release deadly neurotoxins")
}
```
You also can check using `SelectedItem.Text` property.
```
if(radioButtonList.SelectedItem.Text == "Option 2")
{
Messagebox.Show("Warning: Selecting this option may release deadly neurotoxins")
}
```
If you are on asp.net, you do not have Messagebox.Show, you should use a javascript alert. | you can use jquery to solve this. it is much easier. here is a sample code.
```
$(document).ready(function () {
$("#<%=radioButtonList.ClientID%> input").change(function(){
alert('test');
});
});
``` |
39,175,648 | I am using `datetime` in some Python udfs that I use in my `pig` script. So far so good. I use pig 12.0 on Cloudera 5.5
However, I also need to use the `pytz` or `dateutil` packages as well and they dont seem to be part of a vanilla python install.
Can I use them in my `Pig` udfs in some ways? If so, how? I think `dateutil` is installed on my nodes (I am not admin, so how can I actually check that is the case?), but when I type:
```
import sys
#I append the path to dateutil on my local windows machine. Is that correct?
sys.path.append('C:/Users/me/AppData/Local/Continuum/Anaconda2/lib/site-packages')
from dateutil import tz
```
in my `udfs.py` script, I get:
```
2016-08-30 09:56:06,572 [main] ERROR org.apache.pig.tools.grunt.Grunt - ERROR 1121: Python Error. Traceback (most recent call last):
File "udfs.py", line 23, in <module>
from dateutil import tz
ImportError: No module named dateutil
```
when I run my pig script.
All my other python udfs (using `datetime` for instance) work just fine. Any idea how to fix that?
Many thanks!
**UPDATE**
after playing a bit with the python path, I am now able to
```
import dateutil
```
(at least Pig does not crash). But if I try:
```
from dateutil import tz
```
I get an error.
```
from dateutil import tz
File "/opt/python/lib/python2.7/site-packages/dateutil/tz.py", line 16, in <module>
from six import string_types, PY3
File "/opt/python/lib/python2.7/site-packages/six.py", line 604, in <module>
viewkeys = operator.methodcaller("viewkeys")
AttributeError: type object 'org.python.modules.operator' has no attribute 'methodcaller'
```
How to overcome that? I use tz in the following manner
```
to_zone = dateutil.tz.gettz('US/Eastern')
from_zone = dateutil.tz.gettz('UTC')
```
and then I change the timezone of my timestamps. Can I just import dateutil to do that? what is the proper syntax?
**UPDATE 2**
Following yakuza's suggestion, I am able to
```
import sys
sys.path.append('/opt/python/lib/python2.7/site-packages')
sys.path.append('/opt/python/lib/python2.7/site-packages/pytz/zoneinfo')
import pytz
```
but now I get and error again
```
Caused by: Traceback (most recent call last): File "udfs.py", line 158, in to_date_local File "__pyclasspath__/pytz/__init__.py", line 180, in timezone pytz.exceptions.UnknownTimeZoneError: 'America/New_York'
```
when I define
```
to_zone = pytz.timezone('America/New_York')
from_zone = pytz.timezone('UTC')
```
Found some hints here [UnknownTimezoneError Exception Raised with Python Application Compiled with Py2Exe](https://stackoverflow.com/questions/9158846/unknowntimezoneerror-exception-raised-with-python-application-compiled-with-py2e)
What to do? Awww, I just want to convert timezones in Pig :( | 2016/08/26 | [
"https://Stackoverflow.com/questions/39175648",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1609428/"
] | Well, as you probably know all Python UDF functions are not executed by Python interpreter, but Jython that is distributed with Pig. By default in 0.12.0 it should be [Jython 2.5.3](https://stackoverflow.com/questions/17711451/python-udf-version-with-jython-pig). Unfortunately `six` package supports Python starting from [Python 2.6](https://pypi.python.org/pypi/six) and it's package required by [`dateutil`](https://github.com/dateutil/dateutil/blob/master/setup.py). However `pytz` seems not to have such dependency, and should support Python versions starting from [Python 2.4](https://pypi.python.org/pypi/pytz).
So to achieve your goal you should distribute `pytz` package to all your nodes for version 2.5 and in your Pig UDF add it's path to `sys.path`. If you complete same steps you did for `dateutil` everything should work as you expect. We are using very same approach with `pygeoip` and it works like a charm.
How does it work
================
When you run Pig script that references some Python UDF (more precisely Jython UDF), you script gets compiled to map/reduce job, all `REGISTER`ed files are included in JAR file, and are distributed on nodes where code is actually executed. Now when your code is executed, Jython interpreter is started and executed from Java code. So now when Python code is executed on each node taking part in computation, all Python imports are resolved locally on node. Imports from standard libraries are taken from Jython implementation, but all "packages" have to be install otherwise, as there is no `pip` for it. So to make external packages available to Python UDF you have to install required packages manually using other `pip` or install from sources, but remember to download package **compatible with Python 2.5**! Then in every single UDF file, you have to append `site-packages` on each node, where you installed packages (it's important to use same directory on each node). For example:
```
import sys
sys.path.append('/path/to/site-packages')
# Imports of non-stdlib packages
```
Proof of concept
================
Let's assume some we have following files:
`/opt/pytz_test/test_pytz.pig`:
```
REGISTER '/opt/pytz_test/test_pytz_udf.py' using jython as test;
A = LOAD '/opt/pytz_test/test_pytz_data.csv' AS (timestamp:int);
B = FOREACH A GENERATE
test.to_date_local(timestamp);
STORE B INTO '/tmp/test_pytz_output.csv' using PigStorage(',');
```
`/opt/pytz_test/test_pytz_udf.py`:
```
from datetime import datetime
import sys
sys.path.append('/usr/lib/python2.6/site-packages/')
import pytz
@outputSchema('date:chararray')
def to_date_local(unix_timestamp):
"""
converts unix timestamp to a rounded date
"""
to_zone = pytz.timezone('America/New_York')
from_zone = pytz.timezone('UTC')
try :
as_datetime = datetime.utcfromtimestamp(unix_timestamp)
.replace(tzinfo=from_zone).astimezone(to_zone)
.date().strftime('%Y-%m-%d')
except:
as_datetime = unix_timestamp
return as_datetime
```
`/opt/pytz_test/test_pytz_data.csv`:
```
1294778181
1294778182
1294778183
1294778184
```
Now let's install `pytz` on our node (it has to be installed using Python version on which `pytz` is compatible with Python 2.5 (2.5-2.7), in my case I'll use Python 2.6):
`sudo pip2.6 install pytz`
**Please make sure, that file** `/opt/pytz_test/test_pytz_udf.py` **adds to `sys.path` reference to `site-packages` where `pytz` is installed.**
Now once we run Pig with our test script:
`pig -x local /opt/pytz_test/test_pytz.pig`
We should be able to read output from our job, which should list:
```
2011-01-11
2011-01-11
2011-01-11
2011-01-11
``` | From the answer to [a different but related question](https://stackoverflow.com/questions/7831649/how-do-i-make-hadoop-find-imported-python-modules-when-using-python-udfs-in-pig), it seems that you should be able to use resources as long as they are available on each of the nodes.
I think you can then add the path as described in [this answer regarding jython](https://stackoverflow.com/a/23807481/983722), and load the modules as usual.
>
> Append the location to the sys.path in the Python script:
>
>
>
> ```
> import sys
> sys.path.append('/usr/local/lib/python2.7/dist-packages')
> import happybase
>
> ```
>
> |
21,998,545 | I have code like:
```
While 1:
A = input()
print A
```
How long can I expect this to run? How many times?
Is there a way I can just throw away whatever I have in A once I have printed it?
How does python deal with it? Will the program crash after a while?
Thank you. | 2014/02/24 | [
"https://Stackoverflow.com/questions/21998545",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | When you reassign `A` to a new value, there is nothing left referring to the old value. [Garbage collection](https://stackoverflow.com/questions/4484167/details-how-python-garbage-collection-works) comes into play here, and the old object is automatically returned back to free memory.
Thus you should never run out of memory with a simple loop like this. | You change the value of A so memory wouldn't be an issue as python garbage collects the old value and returns the memory... so forever |
21,998,545 | I have code like:
```
While 1:
A = input()
print A
```
How long can I expect this to run? How many times?
Is there a way I can just throw away whatever I have in A once I have printed it?
How does python deal with it? Will the program crash after a while?
Thank you. | 2014/02/24 | [
"https://Stackoverflow.com/questions/21998545",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | This can literally run forever. The Python garbage collector will free the memory used by A when it's value is overwritten.
Side note: "While" must be lowercase "while" and it is considered more Pythonic to have "while True:" instead of "while 1:" | You change the value of A so memory wouldn't be an issue as python garbage collects the old value and returns the memory... so forever |
21,998,545 | I have code like:
```
While 1:
A = input()
print A
```
How long can I expect this to run? How many times?
Is there a way I can just throw away whatever I have in A once I have printed it?
How does python deal with it? Will the program crash after a while?
Thank you. | 2014/02/24 | [
"https://Stackoverflow.com/questions/21998545",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | When you reassign `A` to a new value, there is nothing left referring to the old value. [Garbage collection](https://stackoverflow.com/questions/4484167/details-how-python-garbage-collection-works) comes into play here, and the old object is automatically returned back to free memory.
Thus you should never run out of memory with a simple loop like this. | This can literally run forever. The Python garbage collector will free the memory used by A when it's value is overwritten.
Side note: "While" must be lowercase "while" and it is considered more Pythonic to have "while True:" instead of "while 1:" |
41,934,574 | I am new to C# programming, I migrated from python. I want to append two or more array (exact number is not known , depends on db entry) into a single array
like the list.append method in python does. Here the code example of what I want to do
```
int[] a = {1,2,3};
int[] b = {4,5,6};
int[] c = {7,8,9};
int[] d;
```
I don't want to add all the arrays at a time. I need somewhat like this
```
// I know this not correct
d += a;
d += b;
d += c;
```
And this is the final result I want
```
d = {{1,2,3},{4,5,6},{7,8,9}};
```
it would be too easy for you guys but then I am just starting with c#. | 2017/01/30 | [
"https://Stackoverflow.com/questions/41934574",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7268744/"
] | Well, if you want a simple **1D** array, try `SelectMany`:
```
int[] a = { 1, 2, 3 };
int[] b = { 4, 5, 6 };
int[] c = { 7, 8, 9 };
// d == {1, 2, 3, 4, 5, 6, 7, 8, 9}
int[] d = new[] { a, b, c } // initial jagged array
.SelectMany(item => item) // flattened
.ToArray(); // materialized as a array
```
if you want a *jagged* array (*array of arrays*)
```
// d == {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}
// notice the declaration - int[][] - array of arrays of int
int[][] d = new[] { a, b, c };
```
In case you want to append arrays conditionally, not in one go, *array* is not a collection type to choose for `d`; `List<int>` or `List<int[]>` will serve better:
```
// 1d array emulation
List<int> d = new List<int>();
...
d.AddRange(a);
d.AddRange(b);
d.AddRange(c);
```
Or
```
// jagged array emulation
List<int[]> d = new List<int[]>();
...
d.Add(a); //d.Add(a.ToArray()); if you want a copy of a
d.Add(b);
d.Add(c);
``` | It seems from your code that `d` is not a single-dimensional array, but it seems to be a jagged array (and array of arrays). If so, you can write this:
```
int[][] d = new int[][] { a, b, c };
```
If you instead want to concatenate all arrays to a new `d`, you can use:
```
int[] d = a.Concat(b).Concat(c).ToArray();
``` |
41,934,574 | I am new to C# programming, I migrated from python. I want to append two or more array (exact number is not known , depends on db entry) into a single array
like the list.append method in python does. Here the code example of what I want to do
```
int[] a = {1,2,3};
int[] b = {4,5,6};
int[] c = {7,8,9};
int[] d;
```
I don't want to add all the arrays at a time. I need somewhat like this
```
// I know this not correct
d += a;
d += b;
d += c;
```
And this is the final result I want
```
d = {{1,2,3},{4,5,6},{7,8,9}};
```
it would be too easy for you guys but then I am just starting with c#. | 2017/01/30 | [
"https://Stackoverflow.com/questions/41934574",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7268744/"
] | Well, if you want a simple **1D** array, try `SelectMany`:
```
int[] a = { 1, 2, 3 };
int[] b = { 4, 5, 6 };
int[] c = { 7, 8, 9 };
// d == {1, 2, 3, 4, 5, 6, 7, 8, 9}
int[] d = new[] { a, b, c } // initial jagged array
.SelectMany(item => item) // flattened
.ToArray(); // materialized as a array
```
if you want a *jagged* array (*array of arrays*)
```
// d == {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}
// notice the declaration - int[][] - array of arrays of int
int[][] d = new[] { a, b, c };
```
In case you want to append arrays conditionally, not in one go, *array* is not a collection type to choose for `d`; `List<int>` or `List<int[]>` will serve better:
```
// 1d array emulation
List<int> d = new List<int>();
...
d.AddRange(a);
d.AddRange(b);
d.AddRange(c);
```
Or
```
// jagged array emulation
List<int[]> d = new List<int[]>();
...
d.Add(a); //d.Add(a.ToArray()); if you want a copy of a
d.Add(b);
d.Add(c);
``` | ```
var z = new int[x.Length + y.Length];
x.CopyTo(z, 0);
y.CopyTo(z, x.Length);
``` |
41,934,574 | I am new to C# programming, I migrated from python. I want to append two or more array (exact number is not known , depends on db entry) into a single array
like the list.append method in python does. Here the code example of what I want to do
```
int[] a = {1,2,3};
int[] b = {4,5,6};
int[] c = {7,8,9};
int[] d;
```
I don't want to add all the arrays at a time. I need somewhat like this
```
// I know this not correct
d += a;
d += b;
d += c;
```
And this is the final result I want
```
d = {{1,2,3},{4,5,6},{7,8,9}};
```
it would be too easy for you guys but then I am just starting with c#. | 2017/01/30 | [
"https://Stackoverflow.com/questions/41934574",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7268744/"
] | Well, if you want a simple **1D** array, try `SelectMany`:
```
int[] a = { 1, 2, 3 };
int[] b = { 4, 5, 6 };
int[] c = { 7, 8, 9 };
// d == {1, 2, 3, 4, 5, 6, 7, 8, 9}
int[] d = new[] { a, b, c } // initial jagged array
.SelectMany(item => item) // flattened
.ToArray(); // materialized as a array
```
if you want a *jagged* array (*array of arrays*)
```
// d == {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}
// notice the declaration - int[][] - array of arrays of int
int[][] d = new[] { a, b, c };
```
In case you want to append arrays conditionally, not in one go, *array* is not a collection type to choose for `d`; `List<int>` or `List<int[]>` will serve better:
```
// 1d array emulation
List<int> d = new List<int>();
...
d.AddRange(a);
d.AddRange(b);
d.AddRange(c);
```
Or
```
// jagged array emulation
List<int[]> d = new List<int[]>();
...
d.Add(a); //d.Add(a.ToArray()); if you want a copy of a
d.Add(b);
d.Add(c);
``` | You can use `Array.Copy`. It copies a range of elements in one Array to another array. [Reference](https://msdn.microsoft.com/en-us/library/system.array.copy(v=vs.110).aspx)
```
int[] a = {1,2,3};
int[] b = {4,5,6};
int[] c = {7,8,9};
int[] combined = new int[a.Length + b.Length + c.Length];
Array.Copy(a, combined, a.Length);
Array.Copy(b, 0, combined, a.Length, b.Length);
Array.Copy(c, 0, combined, a.Length, b.Length, c.Length);
``` |
11,477,643 | So I'm contemplating what language to use in the development of an app that uses OpenCV. As a part of my decision, I'm interested in knowing how easy/difficult it is to include the opencv library in the final app. I'd really like to write this in python because the opencv bindings are great, python's easy, etc.
But I haven't been able to find a clear answer on stuff like "does py2app automatically bundle opencv when it sees the import cv line" (I think not) and if not, then is there a known way to do this?
In general, I would like to know the best way to distribute a python desktop app with opencv. | 2012/07/13 | [
"https://Stackoverflow.com/questions/11477643",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/132467/"
] | I've effectively packaged, deployed, and shipped a Python app using OpenCV with cxFreeze.
<http://cx-freeze.sourceforge.net/>
Yes, cxFreeze auto picked up the python extensions to OpenCV. I had to manually copy the OpenCV DLLs (Windows), but that was a minor issue that can be solved by a post-processing step in cxFreeze. It does pick up other DLL's, so I'm not sure what the issue was.
In fact, it worked so well I was surprised. The ONLY thing it didn't pick up properly was a QT library. Basically here were my steps (I'm using QT so ignore that part if you aren't):
1. cxfreeze App.py --target-dir App --base-name Win32GUI --include-modules PySide.QtNetwork
2. Copy over the opencv\build\x86\vc9\bin files to the App directory.
That's it. | You can have a look at
<http://www.pyinstaller.org/>
It's great and it packages the necessary dll for opencv.
For opencv to work it py2exe also package numpy. Make sure you add a dependency for it in case you are using py2exe. |
13,053,429 | I'm new to python. I am trying to create a script that gives me a different response when the same data is inputted more than once. The code goes like this :
```
def loop() :
Repeat = 0
response = raw_input("enter something : ")
if response == "hi"
Repeat += 1
print "hello"
loop()
if Repeat > 2 :
print "you have already said hi"
loop()
def main() :
loop()
raw_input()
main()
```
The above code doesn't work. preferably I would like a statement that checks both conditions, but i'm not quite sure how this could be done. | 2012/10/24 | [
"https://Stackoverflow.com/questions/13053429",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1636006/"
] | I would use a `dict` to store words/count. You can then inquire if the word is in the dictionary and update count ...
```
words = {}
while True:
word = raw_input("Say something:")
if word in words:
words[word] += 1
print "you already said ",words[word]
continue
else:
words[word] = 0
#...
```
You could also do this with `try`/`except`, but I thought I'd keep it simple to start out... | Your statement above is recursively calling itself. The new instance of loop does not have access to the calling value of Repeat and instead has its own local copy of Repeat. Also, you have if `Repeat > 2`. As written this means that it won't get your other print statement until they input "hello" three times to get the counter up to 3. You probably want to make that `Repeat >= 2`.
What you want is a while loop that tracks whether the input is repeated. In real life you probably want some condition to tell that while loop when to end, but you don't have whine here so you could use `while True:` to loop forever.
Finally, your code only checks if they put in "hello" more than once. You could make it more general by tracking what they have already said instead, and get rid of the need to have a counter in the process. For a fast sloppy version that I haven't tested, it might loop like:
```
alreadySaid = set() #sets are effecient and only store a specific element once
while True: #probably want an actual break condition here, but to do it forever this works
response = raw_input("enter something : ")
if response in alreadySaid:
print 'You already said {}'.format(response)
else:
print response
alreadySaid.add(response)
``` |
13,053,429 | I'm new to python. I am trying to create a script that gives me a different response when the same data is inputted more than once. The code goes like this :
```
def loop() :
Repeat = 0
response = raw_input("enter something : ")
if response == "hi"
Repeat += 1
print "hello"
loop()
if Repeat > 2 :
print "you have already said hi"
loop()
def main() :
loop()
raw_input()
main()
```
The above code doesn't work. preferably I would like a statement that checks both conditions, but i'm not quite sure how this could be done. | 2012/10/24 | [
"https://Stackoverflow.com/questions/13053429",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1636006/"
] | try something like this:
```
def loop(rep=None):
rep=rep if rep else set() #use a set or list to store the responses
response=raw_input("enter something : ")
if response not in rep: #if the response is not found in rep
rep.add(response) #store response in rep
print "hello"
loop(rep) #pass rep while calling loop()
else:
print "You've already said {0}".format(response) #if response is found
loop(rep)
loop()
```
**output:**
```
enter something : hi
hello
enter something : hi
You've already said hi
enter something : foo
hello
enter something : bar
hello
enter something : bar
You've already said bar
enter something :
```
PS: also add a breaking condition to `loop()` otherwise it'll be an infinite loop | Your statement above is recursively calling itself. The new instance of loop does not have access to the calling value of Repeat and instead has its own local copy of Repeat. Also, you have if `Repeat > 2`. As written this means that it won't get your other print statement until they input "hello" three times to get the counter up to 3. You probably want to make that `Repeat >= 2`.
What you want is a while loop that tracks whether the input is repeated. In real life you probably want some condition to tell that while loop when to end, but you don't have whine here so you could use `while True:` to loop forever.
Finally, your code only checks if they put in "hello" more than once. You could make it more general by tracking what they have already said instead, and get rid of the need to have a counter in the process. For a fast sloppy version that I haven't tested, it might loop like:
```
alreadySaid = set() #sets are effecient and only store a specific element once
while True: #probably want an actual break condition here, but to do it forever this works
response = raw_input("enter something : ")
if response in alreadySaid:
print 'You already said {}'.format(response)
else:
print response
alreadySaid.add(response)
``` |
34,543,513 | I'm looking for maximum absolute value out of chunked list.
For example, the list is:
```
[1, 2, 4, 5, 4, 5, 6, 7, 2, 6, -9, 6, 4, 2, 7, 8]
```
I want to find the maximum with lookahead = 4. For this case, it will return me:
```
[5, 7, 9, 8]
```
How can I do simply in Python?
```
for d in data[::4]:
if count < LIMIT:
count = count + 1
if abs(d) > maximum_item:
maximum_item = abs(d)
else:
max_array.append(maximum_item)
if maximum_item > highest_line:
highest_line = maximum_item
maximum_item = 0
count = 1
```
I know I can use for loop to check this. But I'm sure there is an easier way in python. | 2015/12/31 | [
"https://Stackoverflow.com/questions/34543513",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/517403/"
] | Using standard Python:
```
[max(abs(x) for x in arr[i:i+4]) for i in range(0, len(arr), 4)]
```
This works also if the array cannot be evenly divided. | Map the `list` to `abs()`, then [chunk the `list`](https://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks-in-python) and send it to `max()`:
```
array = [1,2,4,5,4,5,6,7,2,6,-9,6,4,2,7,8]
array = [abs(item) for item in array]
# use linked question's answer to chunk
# array = [[1,2,4,5], [4,5,6,7], [2,6,9,6], [4,2,7,8]] # chunked abs()'ed list
values = [max(item) for item in array]
```
Result:
```
>>> values
[5, 7, 9, 8]
``` |
34,543,513 | I'm looking for maximum absolute value out of chunked list.
For example, the list is:
```
[1, 2, 4, 5, 4, 5, 6, 7, 2, 6, -9, 6, 4, 2, 7, 8]
```
I want to find the maximum with lookahead = 4. For this case, it will return me:
```
[5, 7, 9, 8]
```
How can I do simply in Python?
```
for d in data[::4]:
if count < LIMIT:
count = count + 1
if abs(d) > maximum_item:
maximum_item = abs(d)
else:
max_array.append(maximum_item)
if maximum_item > highest_line:
highest_line = maximum_item
maximum_item = 0
count = 1
```
I know I can use for loop to check this. But I'm sure there is an easier way in python. | 2015/12/31 | [
"https://Stackoverflow.com/questions/34543513",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/517403/"
] | Map the `list` to `abs()`, then [chunk the `list`](https://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks-in-python) and send it to `max()`:
```
array = [1,2,4,5,4,5,6,7,2,6,-9,6,4,2,7,8]
array = [abs(item) for item in array]
# use linked question's answer to chunk
# array = [[1,2,4,5], [4,5,6,7], [2,6,9,6], [4,2,7,8]] # chunked abs()'ed list
values = [max(item) for item in array]
```
Result:
```
>>> values
[5, 7, 9, 8]
``` | Another way, is to use `islice` method from [`itertools`](https://docs.python.org/2.7/library/itertools.html?highlight=islice#itertools.islice) module:
```
>>> from itertools import islice
>>> [max(islice(map(abs,array),i,i+4)) for i in range(0,len(array),4)]
[5, 7, 9, 8]
```
To break it down:
1 - `map(abs, array)` returns a list of all absolute values of array elemets
2 - `islice(map(abs,array),i,i+4))` slices the array in chunks of four elements
3 - `i in range(0,len(array),4)` stepping range for `islice` to avoid overlapping
This can be wrapped in function as fellows:
```
def max_of_chunks(lst, chunk_size):
lst = map(abs, lst)
result = [max(islice(lst,i,i+chunk_size)) for i in range(0,len(lst),chunk_size)]
return result
``` |
34,543,513 | I'm looking for maximum absolute value out of chunked list.
For example, the list is:
```
[1, 2, 4, 5, 4, 5, 6, 7, 2, 6, -9, 6, 4, 2, 7, 8]
```
I want to find the maximum with lookahead = 4. For this case, it will return me:
```
[5, 7, 9, 8]
```
How can I do simply in Python?
```
for d in data[::4]:
if count < LIMIT:
count = count + 1
if abs(d) > maximum_item:
maximum_item = abs(d)
else:
max_array.append(maximum_item)
if maximum_item > highest_line:
highest_line = maximum_item
maximum_item = 0
count = 1
```
I know I can use for loop to check this. But I'm sure there is an easier way in python. | 2015/12/31 | [
"https://Stackoverflow.com/questions/34543513",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/517403/"
] | Map the `list` to `abs()`, then [chunk the `list`](https://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks-in-python) and send it to `max()`:
```
array = [1,2,4,5,4,5,6,7,2,6,-9,6,4,2,7,8]
array = [abs(item) for item in array]
# use linked question's answer to chunk
# array = [[1,2,4,5], [4,5,6,7], [2,6,9,6], [4,2,7,8]] # chunked abs()'ed list
values = [max(item) for item in array]
```
Result:
```
>>> values
[5, 7, 9, 8]
``` | **Upd:** Oh, I've just seen newest comments to task and answers. I wasn't get task properly, my bad :) Let my old answer stay here for history. Max numbers from list chunks you can find in the way like that:
```
largest = [max(abs(x) for x in l[i:i+n]) for i in xrange(0, len(l), n)]
```
or
```
largest = [max(abs(x) for x in l[i:i+n]) for i in range(0, len(l), n)]
```
if you're use Python3.
---
**Original answer just for history:** If you had to choice some numbers (once) from not a big list, you shouldn't install big libraries like `numpy` for such simple tasks. There are a lot of techniques to do it with built-in Python tools. Here they are (something of them).
So we have some list and count of maximum different elements:
```
In [1]: l = [1, 2, 4, 5, 4, 5, 6, 7, 2, 6, -9, 6, 4, 2, 7, 8]
In [2]: n = 4
```
**A.** First we getting only unique numbers from source list by converting it to **set**. Then we creating a **list** consist of these unique numbers, **sort** it and finally **get N** last (greatest) elements:
```
In [3]: sorted(list(set(l)))[-n:]
Out[3]: [5, 6, 7, 8]
```
**B.** You can use built-in `heapq` module:
```
In [7]: import heapq
In [8]: heapq.nlargest(n, set(l))
Out[8]: [8, 7, 6, 5]
```
Of course you can 'wrap' A or B technique into some human-friendly function like `def get_largest(seq, n): return sorted(list(set(l)))[-n:]`. Yes I've ommited some details like handling `IndexError`. You should remember about it when you'll writing the code.
**C.** If your list(s) is very long and you had to do many of these operations so fast as Python can, you should use special third-party libraries like `numpy` or `bottleneck`. |
34,543,513 | I'm looking for maximum absolute value out of chunked list.
For example, the list is:
```
[1, 2, 4, 5, 4, 5, 6, 7, 2, 6, -9, 6, 4, 2, 7, 8]
```
I want to find the maximum with lookahead = 4. For this case, it will return me:
```
[5, 7, 9, 8]
```
How can I do simply in Python?
```
for d in data[::4]:
if count < LIMIT:
count = count + 1
if abs(d) > maximum_item:
maximum_item = abs(d)
else:
max_array.append(maximum_item)
if maximum_item > highest_line:
highest_line = maximum_item
maximum_item = 0
count = 1
```
I know I can use for loop to check this. But I'm sure there is an easier way in python. | 2015/12/31 | [
"https://Stackoverflow.com/questions/34543513",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/517403/"
] | Using standard Python:
```
[max(abs(x) for x in arr[i:i+4]) for i in range(0, len(arr), 4)]
```
This works also if the array cannot be evenly divided. | Another way, is to use `islice` method from [`itertools`](https://docs.python.org/2.7/library/itertools.html?highlight=islice#itertools.islice) module:
```
>>> from itertools import islice
>>> [max(islice(map(abs,array),i,i+4)) for i in range(0,len(array),4)]
[5, 7, 9, 8]
```
To break it down:
1 - `map(abs, array)` returns a list of all absolute values of array elemets
2 - `islice(map(abs,array),i,i+4))` slices the array in chunks of four elements
3 - `i in range(0,len(array),4)` stepping range for `islice` to avoid overlapping
This can be wrapped in function as fellows:
```
def max_of_chunks(lst, chunk_size):
lst = map(abs, lst)
result = [max(islice(lst,i,i+chunk_size)) for i in range(0,len(lst),chunk_size)]
return result
``` |
34,543,513 | I'm looking for maximum absolute value out of chunked list.
For example, the list is:
```
[1, 2, 4, 5, 4, 5, 6, 7, 2, 6, -9, 6, 4, 2, 7, 8]
```
I want to find the maximum with lookahead = 4. For this case, it will return me:
```
[5, 7, 9, 8]
```
How can I do simply in Python?
```
for d in data[::4]:
if count < LIMIT:
count = count + 1
if abs(d) > maximum_item:
maximum_item = abs(d)
else:
max_array.append(maximum_item)
if maximum_item > highest_line:
highest_line = maximum_item
maximum_item = 0
count = 1
```
I know I can use for loop to check this. But I'm sure there is an easier way in python. | 2015/12/31 | [
"https://Stackoverflow.com/questions/34543513",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/517403/"
] | Using standard Python:
```
[max(abs(x) for x in arr[i:i+4]) for i in range(0, len(arr), 4)]
```
This works also if the array cannot be evenly divided. | **Upd:** Oh, I've just seen newest comments to task and answers. I wasn't get task properly, my bad :) Let my old answer stay here for history. Max numbers from list chunks you can find in the way like that:
```
largest = [max(abs(x) for x in l[i:i+n]) for i in xrange(0, len(l), n)]
```
or
```
largest = [max(abs(x) for x in l[i:i+n]) for i in range(0, len(l), n)]
```
if you're use Python3.
---
**Original answer just for history:** If you had to choice some numbers (once) from not a big list, you shouldn't install big libraries like `numpy` for such simple tasks. There are a lot of techniques to do it with built-in Python tools. Here they are (something of them).
So we have some list and count of maximum different elements:
```
In [1]: l = [1, 2, 4, 5, 4, 5, 6, 7, 2, 6, -9, 6, 4, 2, 7, 8]
In [2]: n = 4
```
**A.** First we getting only unique numbers from source list by converting it to **set**. Then we creating a **list** consist of these unique numbers, **sort** it and finally **get N** last (greatest) elements:
```
In [3]: sorted(list(set(l)))[-n:]
Out[3]: [5, 6, 7, 8]
```
**B.** You can use built-in `heapq` module:
```
In [7]: import heapq
In [8]: heapq.nlargest(n, set(l))
Out[8]: [8, 7, 6, 5]
```
Of course you can 'wrap' A or B technique into some human-friendly function like `def get_largest(seq, n): return sorted(list(set(l)))[-n:]`. Yes I've ommited some details like handling `IndexError`. You should remember about it when you'll writing the code.
**C.** If your list(s) is very long and you had to do many of these operations so fast as Python can, you should use special third-party libraries like `numpy` or `bottleneck`. |
57,673,070 | I am logging into gmail via python and deleting emails. However when I do a search for two emails I get no results to delete.
```
mail.select('Inbox')
result,data = mail.uid('search',None '(FROM target.com)')
```
The above works and will find and delete any email that had target.com in the from address. However when I send in another email address I get nothing.
```
result,data = mail.uid('search',None '(FROM "target.com" FROM "walmart.com")')
```
Yes I have both target.com and walmart.com emails in my inbox. | 2019/08/27 | [
"https://Stackoverflow.com/questions/57673070",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11951910/"
] | First of all I can confirm this behaviour for JavaFX 13 ea build 13. This was probably a very simplistic attempt to fix an old bug which the OP has already mentioned (image turning pink) which I reported a long time ago. The problem is that JPEGS cannot store alpha information and in the past the output was just garbled when an image with an alpha channel was written out as a JPEG. The fix now just refuses to write out the image at all instead of just ignoring the alpha channel.
A workaround is to make a copy of the image where you explicitly specify a color model without alpha channel.
Here is the original bug report which also contains the workaround: <https://bugs.openjdk.java.net/browse/JDK-8119048>
Here is some more info to simplify the conversion:
If you add this line to your code
```
BufferedImage awtImage = new BufferedImage((int)img.getWidth(), (int)img.getHeight(), BufferedImage.TYPE_INT_RGB);
```
and then call `SwingFXUtils.fromFXImage(img, awtImage)` with this as the second parameter instead of `null`, then the required conversion will be done automatically and the JPEG is written as expected. | Additionally to the answer of mipa and in the case that you do not have SwingFXUtils available, you could clone the BufferedImage into another BufferedImage without alpha channel:
```
BufferedImage withoutAlpha = new BufferedImage(
(int) originalWithAlpha.getWidth(),
(int) originalWithAlpha.getHeight(),
BufferedImage.TYPE_INT_RGB);
Graphics g = withoutAlpha.getGraphics();
g.drawImage(originalWithAlpha, 0, 0, null);
g.dispose();
``` |
52,753,613 | I have a dataframe say `df`. `df` has a column `'Ages'`
`>>> df['Age']`
[](https://i.stack.imgur.com/pcs2l.png)
I want to group this ages and create a new column something like this
```
If age >= 0 & age < 2 then AgeGroup = Infant
If age >= 2 & age < 4 then AgeGroup = Toddler
If age >= 4 & age < 13 then AgeGroup = Kid
If age >= 13 & age < 20 then AgeGroup = Teen
and so on .....
```
How can I achieve this using Pandas library.
I tried doing this something like this
```
X_train_data['AgeGroup'][ X_train_data.Age < 13 ] = 'Kid'
X_train_data['AgeGroup'][ X_train_data.Age < 3 ] = 'Toddler'
X_train_data['AgeGroup'][ X_train_data.Age < 1 ] = 'Infant'
```
but doing this i get this warning
>
> /Users/Anand/miniconda3/envs/learn/lib/python3.7/site-packages/ipykernel\_launcher.py:3: SettingWithCopyWarning:
> A value is trying to be set on a copy of a slice from a DataFrame
> See the caveats in the documentation: <http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy>
> This is separate from the ipykernel package so we can avoid doing imports until
> /Users/Anand/miniconda3/envs/learn/lib/python3.7/site-packages/ipykernel\_launcher.py:4: SettingWithCopyWarning:
> A value is trying to be set on a copy of a slice from a DataFrame
>
>
>
How to avoid this warning and do it in a better way. | 2018/10/11 | [
"https://Stackoverflow.com/questions/52753613",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4005417/"
] | Use [`pandas.cut`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.cut.html) with parameter `right=False` for not includes the rightmost edge of bins:
```
X_train_data = pd.DataFrame({'Age':[0,2,4,13,35,-1,54]})
bins= [0,2,4,13,20,110]
labels = ['Infant','Toddler','Kid','Teen','Adult']
X_train_data['AgeGroup'] = pd.cut(X_train_data['Age'], bins=bins, labels=labels, right=False)
print (X_train_data)
Age AgeGroup
0 0 Infant
1 2 Toddler
2 4 Kid
3 13 Teen
4 35 Adult
5 -1 NaN
6 54 Adult
```
Last for replace missing value use [`add_categories`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.cat.add_categories.html) with [`fillna`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.fillna.html):
```
X_train_data['AgeGroup'] = X_train_data['AgeGroup'].cat.add_categories('unknown')
.fillna('unknown')
print (X_train_data)
Age AgeGroup
0 0 Infant
1 2 Toddler
2 4 Kid
3 13 Teen
4 35 Adult
5 -1 unknown
6 54 Adult
```
---
```
bins= [-1,0,2,4,13,20, 110]
labels = ['unknown','Infant','Toddler','Kid','Teen', 'Adult']
X_train_data['AgeGroup'] = pd.cut(X_train_data['Age'], bins=bins, labels=labels, right=False)
print (X_train_data)
Age AgeGroup
0 0 Infant
1 2 Toddler
2 4 Kid
3 13 Teen
4 35 Adult
5 -1 unknown
6 54 Adult
``` | Just use:
```
X_train_data.loc[(X_train_data.Age < 13), 'AgeGroup'] = 'Kid'
``` |
65,513,452 | I am trying to display results in a table format (with borders) in a cgi script written in python.
How to display table boarders within python code.
```
check_list = elements.getvalue('check_list[]')
mydata=db.get_data(check_list)
print("_____________________________________")
print("<table><th>",check_list[0],"</th> <th>",check_list[1],"</th>")
i = 0 #here
for data in mydata:
print("<tr><td>",data[0],"</td> <td>",data[1],"</td></tr>")
i += 1 #here
if i == 2:#here
break#here
print("</table>")
```
the checklist elements represent columns names from a sqlite table. and based on the selected columns the data will be shown.
This code result is just showing two records result with no borders in a php page. | 2020/12/30 | [
"https://Stackoverflow.com/questions/65513452",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12888614/"
] | Digging through issues on vercel's github I found this alternative that doesn't use next-i18next or any other nextjs magic:
<https://github.com/Xairoo/nextjs-i18n-static-page-starter>
It's just basic i18n using i18next that bundles all locale together with JS, so there are obvious tradeoffs but at least it works with SSG. You can build upon that to come up with something more elaborate. That's what I will do. | You can't use `export` with next.js i18n implementation.
>
> Note that Internationalized Routing does not integrate with next export as next export does not leverage the Next.js routing layer. Hybrid Next.js applications that do not use next export are fully supported.
>
>
>
[Next.js docs](https://nextjs.org/docs/advanced-features/i18n-routing#how-does-this-work-with-static-generation) |
65,513,452 | I am trying to display results in a table format (with borders) in a cgi script written in python.
How to display table boarders within python code.
```
check_list = elements.getvalue('check_list[]')
mydata=db.get_data(check_list)
print("_____________________________________")
print("<table><th>",check_list[0],"</th> <th>",check_list[1],"</th>")
i = 0 #here
for data in mydata:
print("<tr><td>",data[0],"</td> <td>",data[1],"</td></tr>")
i += 1 #here
if i == 2:#here
break#here
print("</table>")
```
the checklist elements represent columns names from a sqlite table. and based on the selected columns the data will be shown.
This code result is just showing two records result with no borders in a php page. | 2020/12/30 | [
"https://Stackoverflow.com/questions/65513452",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12888614/"
] | You can't use `export` with next.js i18n implementation.
>
> Note that Internationalized Routing does not integrate with next export as next export does not leverage the Next.js routing layer. Hybrid Next.js applications that do not use next export are fully supported.
>
>
>
[Next.js docs](https://nextjs.org/docs/advanced-features/i18n-routing#how-does-this-work-with-static-generation) | Hello I show you my soluce with only i18n-js
```
// i18n.ts
import i18n from "i18n-js";
import en from "./en.json";
import fr from "./fr.json";
const localeEnable = ["fr", "en"];
const formatLocale = () => {
const { language } = window.navigator;
if (language.includes("en")) return "en";
if (language.includes("fr")) return "fr";
if (!localeEnable.includes(language)) return "en";
return "en";
};
// Set the key-value pairs for the different languages you want to support.
i18n.translations = {
en,
fr,
};
// Set the locale once at the beginning of your app.
i18n.locale = "en";
const useTranslate = () => {
return (t: string) => {
if (typeof window !== "undefined") {
i18n.locale = formatLocale();
}
return i18n.t(t);
};
};
export default useTranslate;
// home.tsx
import useTranslate from "../locales/i18n";
const t = useTranslate();
return (<p>{t("idstring")}</p>)
``` |
65,513,452 | I am trying to display results in a table format (with borders) in a cgi script written in python.
How to display table boarders within python code.
```
check_list = elements.getvalue('check_list[]')
mydata=db.get_data(check_list)
print("_____________________________________")
print("<table><th>",check_list[0],"</th> <th>",check_list[1],"</th>")
i = 0 #here
for data in mydata:
print("<tr><td>",data[0],"</td> <td>",data[1],"</td></tr>")
i += 1 #here
if i == 2:#here
break#here
print("</table>")
```
the checklist elements represent columns names from a sqlite table. and based on the selected columns the data will be shown.
This code result is just showing two records result with no borders in a php page. | 2020/12/30 | [
"https://Stackoverflow.com/questions/65513452",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12888614/"
] | Digging through issues on vercel's github I found this alternative that doesn't use next-i18next or any other nextjs magic:
<https://github.com/Xairoo/nextjs-i18n-static-page-starter>
It's just basic i18n using i18next that bundles all locale together with JS, so there are obvious tradeoffs but at least it works with SSG. You can build upon that to come up with something more elaborate. That's what I will do. | Hello I show you my soluce with only i18n-js
```
// i18n.ts
import i18n from "i18n-js";
import en from "./en.json";
import fr from "./fr.json";
const localeEnable = ["fr", "en"];
const formatLocale = () => {
const { language } = window.navigator;
if (language.includes("en")) return "en";
if (language.includes("fr")) return "fr";
if (!localeEnable.includes(language)) return "en";
return "en";
};
// Set the key-value pairs for the different languages you want to support.
i18n.translations = {
en,
fr,
};
// Set the locale once at the beginning of your app.
i18n.locale = "en";
const useTranslate = () => {
return (t: string) => {
if (typeof window !== "undefined") {
i18n.locale = formatLocale();
}
return i18n.t(t);
};
};
export default useTranslate;
// home.tsx
import useTranslate from "../locales/i18n";
const t = useTranslate();
return (<p>{t("idstring")}</p>)
``` |
65,513,452 | I am trying to display results in a table format (with borders) in a cgi script written in python.
How to display table boarders within python code.
```
check_list = elements.getvalue('check_list[]')
mydata=db.get_data(check_list)
print("_____________________________________")
print("<table><th>",check_list[0],"</th> <th>",check_list[1],"</th>")
i = 0 #here
for data in mydata:
print("<tr><td>",data[0],"</td> <td>",data[1],"</td></tr>")
i += 1 #here
if i == 2:#here
break#here
print("</table>")
```
the checklist elements represent columns names from a sqlite table. and based on the selected columns the data will be shown.
This code result is just showing two records result with no borders in a php page. | 2020/12/30 | [
"https://Stackoverflow.com/questions/65513452",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12888614/"
] | Digging through issues on vercel's github I found this alternative that doesn't use next-i18next or any other nextjs magic:
<https://github.com/Xairoo/nextjs-i18n-static-page-starter>
It's just basic i18n using i18next that bundles all locale together with JS, so there are obvious tradeoffs but at least it works with SSG. You can build upon that to come up with something more elaborate. That's what I will do. | There's an alternative, by not using the i18n feature of next.js completely and creating the i18n language detection yourself.
An example that uses the [next-language-detector](https://github.com/i18next/next-language-detector) module is described in [this blog post](https://locize.com/blog/next-i18n-static/) and may look like this:
```
// languageDetector.js
import languageDetector from 'next-language-detector'
import i18nextConfig from '../next-i18next.config'
export default languageDetector({
supportedLngs: i18nextConfig.i18n.locales,
fallbackLng: i18nextConfig.i18n.defaultLocale
})
```
---
```
// redirect.js
import { useEffect } from 'react'
import { useRouter } from 'next/router'
import languageDetector from './languageDetector'
export const useRedirect = (to) => {
const router = useRouter()
to = to || router.asPath
// language detection
useEffect(() => {
const detectedLng = languageDetector.detect()
if (to.startsWith('/' + detectedLng) && router.route === '/404') { // prevent endless loop
router.replace('/' + detectedLng + router.route)
return
}
languageDetector.cache(detectedLng)
router.replace('/' + detectedLng + to)
})
return <></>
};
export const Redirect = () => {
useRedirect()
return <></>
}
// eslint-disable-next-line react/display-name
export const getRedirect = (to) => () => {
useRedirect(to)
return <></>
}
```
The complete guide and the example code can be found here:
* [guide](https://locize.com/blog/next-i18n-static/)
* [example](https://github.com/i18next/next-language-detector/tree/main/examples/basic) |
65,513,452 | I am trying to display results in a table format (with borders) in a cgi script written in python.
How to display table boarders within python code.
```
check_list = elements.getvalue('check_list[]')
mydata=db.get_data(check_list)
print("_____________________________________")
print("<table><th>",check_list[0],"</th> <th>",check_list[1],"</th>")
i = 0 #here
for data in mydata:
print("<tr><td>",data[0],"</td> <td>",data[1],"</td></tr>")
i += 1 #here
if i == 2:#here
break#here
print("</table>")
```
the checklist elements represent columns names from a sqlite table. and based on the selected columns the data will be shown.
This code result is just showing two records result with no borders in a php page. | 2020/12/30 | [
"https://Stackoverflow.com/questions/65513452",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12888614/"
] | There's an alternative, by not using the i18n feature of next.js completely and creating the i18n language detection yourself.
An example that uses the [next-language-detector](https://github.com/i18next/next-language-detector) module is described in [this blog post](https://locize.com/blog/next-i18n-static/) and may look like this:
```
// languageDetector.js
import languageDetector from 'next-language-detector'
import i18nextConfig from '../next-i18next.config'
export default languageDetector({
supportedLngs: i18nextConfig.i18n.locales,
fallbackLng: i18nextConfig.i18n.defaultLocale
})
```
---
```
// redirect.js
import { useEffect } from 'react'
import { useRouter } from 'next/router'
import languageDetector from './languageDetector'
export const useRedirect = (to) => {
const router = useRouter()
to = to || router.asPath
// language detection
useEffect(() => {
const detectedLng = languageDetector.detect()
if (to.startsWith('/' + detectedLng) && router.route === '/404') { // prevent endless loop
router.replace('/' + detectedLng + router.route)
return
}
languageDetector.cache(detectedLng)
router.replace('/' + detectedLng + to)
})
return <></>
};
export const Redirect = () => {
useRedirect()
return <></>
}
// eslint-disable-next-line react/display-name
export const getRedirect = (to) => () => {
useRedirect(to)
return <></>
}
```
The complete guide and the example code can be found here:
* [guide](https://locize.com/blog/next-i18n-static/)
* [example](https://github.com/i18next/next-language-detector/tree/main/examples/basic) | Hello I show you my soluce with only i18n-js
```
// i18n.ts
import i18n from "i18n-js";
import en from "./en.json";
import fr from "./fr.json";
const localeEnable = ["fr", "en"];
const formatLocale = () => {
const { language } = window.navigator;
if (language.includes("en")) return "en";
if (language.includes("fr")) return "fr";
if (!localeEnable.includes(language)) return "en";
return "en";
};
// Set the key-value pairs for the different languages you want to support.
i18n.translations = {
en,
fr,
};
// Set the locale once at the beginning of your app.
i18n.locale = "en";
const useTranslate = () => {
return (t: string) => {
if (typeof window !== "undefined") {
i18n.locale = formatLocale();
}
return i18n.t(t);
};
};
export default useTranslate;
// home.tsx
import useTranslate from "../locales/i18n";
const t = useTranslate();
return (<p>{t("idstring")}</p>)
``` |
73,679,017 | I'm very new to python, so as one of the first projects I decided to a simple log-in menu, however, it gives me a mistake shown at the bottom.
The link to the tutorial I used:
>
> <https://www.youtube.com/watch?v=dR_cDapPWyY&ab_channel=techWithId>
>
>
>
This is the code to the log-in menu:
```
def welcome():
print("Welcome to your dashboard")
def gainAccess(Username=None, Password=None):
Username = input("Enter your username:")
Password = input("Enter your Password:")
if not len(Username or Password) < 1:
if True:
db = open("database.txt", "C:\Users\DeePak\OneDrive\Desktop\database.txt.txt")
d = []
f = []
for i in db:
a,b = i.split(",")
b = b.strip()
c = a,b
d.append(a)
f.append(b)
data = dict(zip(d, f))
try:
if Username in data:
hashed = data[Username].strip('b')
hashed = hashed.replace("'", "")
hashed = hashed.encode('utf-8')
try:
if bcrypt.checkpw(Password.encode(), hashed):
print("Login success!")
print("Hi", Username)
welcome()
else:
print("Wrong password")
except:
print("Incorrect passwords or username")
else:
print("Username doesn't exist")
except:
print("Password or username doesn't exist")
else:
print("Error logging into the system")
else:
print("Please attempt login again")
gainAccess()
# b = b.strip()
# accessDb()
def register(Username=None, Password1=None, Password2=None):
Username = input("Enter a username:")
Password1 = input("Create password:")
Password2 = input("Confirm Password:")
db = open("database.txt", "C:\Users\DeePak\OneDrive\Desktop\Name\database.txt")
d = []
for i in db:
a,b = i.split(",")
b = b.strip()
c = a,b
d.append(a)
if not len(Password1)<=8:
db = open("database.txt", "C:\Users\DeePak\OneDrive\Desktop\Name\database.txt")
if not Username ==None:
if len(Username) <1:
print("Please provide a username")
register()
elif Username in d:
print("Username exists")
register()
else:
if Password1 == Password2:
Password1 = Password1.encode('utf-8')
Password1 = bcrypt.hashpw(Password1, bcrypt.gensalt())
db = open("database.txt", "C:\Users\DeePak\OneDrive\Desktop\Name\database.txt")
db.write(Username+", "+str(Password1)+"\n")
print("User created successfully!")
print("Please login to proceed:")
# print(texts)
else:
print("Passwords do not match")
register()
else:
print("Password too short")
def home(option=None):
print("Welcome, please select an option")
option = input("Login | Signup:")
if option == "Login":
gainAccess()
elif option == "Signup":
register()
else:
print("Please enter a valid parameter, this is case-sensitive")
# register(Username, Password1, Password2)
# gainAccess(Username, Password1)
home()
```
**When I run it, I get this issue:**
```
db = open("database.txt", "C:\Users\DeePak\OneDrive\Desktop\Name\database.txt")
^
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape
``` | 2022/09/11 | [
"https://Stackoverflow.com/questions/73679017",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19810120/"
] | You can find the center of each region like this:
```py
markers = cv2.watershed(img, markers)
labels = np.unique(markers)
for label in labels:
y, x = np.nonzero(markers == label)
cx = int(np.mean(x))
cy = int(np.mean(y))
```
The result:
[](https://i.stack.imgur.com/O2INd.png)
Complete example:
```
import cv2
import numpy as np
img = cv2.imread("water_coins.jpg")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret, thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)
# noise removal
kernel = np.ones((3, 3), np.uint8)
opening = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel, iterations=2)
# sure background area
sure_bg = cv2.dilate(opening, kernel, iterations=3)
# Finding sure foreground area
dist_transform = cv2.distanceTransform(opening, cv2.DIST_L2, 5)
ret, sure_fg = cv2.threshold(dist_transform, 0.7 * dist_transform.max(), 255, 0)
# Finding unknown region
sure_fg = np.uint8(sure_fg)
unknown = cv2.subtract(sure_bg, sure_fg)
# Marker labelling
ret, markers = cv2.connectedComponents(sure_fg)
# Add one to all labels so that sure background is not 0, but 1
markers = markers + 1
# Now, mark the region of unknown with zero
markers[unknown == 255] = 0
markers = cv2.watershed(img, markers)
labels = np.unique(markers)
for label in labels:
y, x = np.nonzero(markers == label)
cx = int(np.mean(x))
cy = int(np.mean(y))
color = (255, 255, 255)
img[markers == label] = np.random.randint(0, 255, size=3)
cv2.circle(img, (cx, cy), 2, color=color, thickness=-1)
cv2.putText(img, f"{label}", (cx, cy), cv2.FONT_HERSHEY_SIMPLEX, 0.35, color, 1, cv2.LINE_AA)
cv2.imwrite("out.jpg", img)
``` | Erode every region independently with a structuring element that has the size of the region label. Then use any remaining pixel.
In some cases (tiny regions), no pixel at all will remain. You have two options
* use a pixel from the "ultimate eroded";
* use some location near the region and a leader line (but avoiding collisions is uneasy).
---
You can also work with the inner distances of the regions and pick pixels with maximum distance. |
54,768,539 | While I iterate within a for loop I continually receive the same warning, which I want to suppress. The warning reads:
`C:\Users\Nick Alexander\AppData\Local\Programs\Python\Python37\lib\site-packages\sklearn\preprocessing\data.py:193: UserWarning: Numerical issues were encountered when scaling the data and might not be solved. The standard deviation of the data is probably very close to 0. warnings.warn("Numerical issues were encountered "`
The code that is producing the warning is as follows:
```
def monthly_standardize(cols, df_train, df_train_grouped, df_val, df_val_grouped, df_test, df_test_grouped):
# Disable the SettingWithCopyWarning warning
pd.options.mode.chained_assignment = None
for c in cols:
df_train[c] = df_train_grouped[c].transform(lambda x: scale(x.astype(float)))
df_val[c] = df_val_grouped[c].transform(lambda x: scale(x.astype(float)))
df_test[c] = df_test_grouped[c].transform(lambda x: scale(x.astype(float)))
return df_train, df_val, df_test
```
I am already disabling one warning. I don't want to disable all warnings, I just want to disable this warning. I am using python 3.7 and sklearn version 0.0 | 2019/02/19 | [
"https://Stackoverflow.com/questions/54768539",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10973400/"
] | Try this at the beginning of the script to ignore specific warnings:
```
import warnings
warnings.filterwarnings("ignore", message="Numerical issues were encountered ")
``` | The python contextlib has a contextmamager for this: [suppress](https://docs.python.org/3/library/contextlib.html#contextlib.suppress)
```
from contextlib import suppress
with suppress(UserWarning):
for c in cols:
df_train[c] = df_train_grouped[c].transform(lambda x: scale(x.astype(float)))
df_val[c] = df_val_grouped[c].transform(lambda x: scale(x.astype(float)))
``` |
54,768,539 | While I iterate within a for loop I continually receive the same warning, which I want to suppress. The warning reads:
`C:\Users\Nick Alexander\AppData\Local\Programs\Python\Python37\lib\site-packages\sklearn\preprocessing\data.py:193: UserWarning: Numerical issues were encountered when scaling the data and might not be solved. The standard deviation of the data is probably very close to 0. warnings.warn("Numerical issues were encountered "`
The code that is producing the warning is as follows:
```
def monthly_standardize(cols, df_train, df_train_grouped, df_val, df_val_grouped, df_test, df_test_grouped):
# Disable the SettingWithCopyWarning warning
pd.options.mode.chained_assignment = None
for c in cols:
df_train[c] = df_train_grouped[c].transform(lambda x: scale(x.astype(float)))
df_val[c] = df_val_grouped[c].transform(lambda x: scale(x.astype(float)))
df_test[c] = df_test_grouped[c].transform(lambda x: scale(x.astype(float)))
return df_train, df_val, df_test
```
I am already disabling one warning. I don't want to disable all warnings, I just want to disable this warning. I am using python 3.7 and sklearn version 0.0 | 2019/02/19 | [
"https://Stackoverflow.com/questions/54768539",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10973400/"
] | Try this at the beginning of the script to ignore specific warnings:
```
import warnings
warnings.filterwarnings("ignore", message="Numerical issues were encountered ")
``` | To ignore for specific code blocks:
```py
import warnings
class IgnoreWarnings(object):
def __init__(self, message):
self.message = message
def __enter__(self):
warnings.filterwarnings("ignore", message=f".*{self.message}.*")
def __exit__(self, *_):
warnings.filterwarnings("default", message=f".*{self.message}.*")
with IgnoreWarnings("fish"):
warnings.warn("here be fish")
warnings.warn("here be dog")
warnings.warn("here were fish")
```
```
UserWarning: here be dog
UserWarning: here were fish
``` |
54,768,539 | While I iterate within a for loop I continually receive the same warning, which I want to suppress. The warning reads:
`C:\Users\Nick Alexander\AppData\Local\Programs\Python\Python37\lib\site-packages\sklearn\preprocessing\data.py:193: UserWarning: Numerical issues were encountered when scaling the data and might not be solved. The standard deviation of the data is probably very close to 0. warnings.warn("Numerical issues were encountered "`
The code that is producing the warning is as follows:
```
def monthly_standardize(cols, df_train, df_train_grouped, df_val, df_val_grouped, df_test, df_test_grouped):
# Disable the SettingWithCopyWarning warning
pd.options.mode.chained_assignment = None
for c in cols:
df_train[c] = df_train_grouped[c].transform(lambda x: scale(x.astype(float)))
df_val[c] = df_val_grouped[c].transform(lambda x: scale(x.astype(float)))
df_test[c] = df_test_grouped[c].transform(lambda x: scale(x.astype(float)))
return df_train, df_val, df_test
```
I am already disabling one warning. I don't want to disable all warnings, I just want to disable this warning. I am using python 3.7 and sklearn version 0.0 | 2019/02/19 | [
"https://Stackoverflow.com/questions/54768539",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10973400/"
] | ```
import warnings
with warnings.catch_warnings():
warnings.simplefilter('ignore')
# code that produces a warning
```
`warnings.catch_warnings()` means "whatever `warnings.` methods are run within this block, undo them when exiting the block". | The python contextlib has a contextmamager for this: [suppress](https://docs.python.org/3/library/contextlib.html#contextlib.suppress)
```
from contextlib import suppress
with suppress(UserWarning):
for c in cols:
df_train[c] = df_train_grouped[c].transform(lambda x: scale(x.astype(float)))
df_val[c] = df_val_grouped[c].transform(lambda x: scale(x.astype(float)))
``` |
54,768,539 | While I iterate within a for loop I continually receive the same warning, which I want to suppress. The warning reads:
`C:\Users\Nick Alexander\AppData\Local\Programs\Python\Python37\lib\site-packages\sklearn\preprocessing\data.py:193: UserWarning: Numerical issues were encountered when scaling the data and might not be solved. The standard deviation of the data is probably very close to 0. warnings.warn("Numerical issues were encountered "`
The code that is producing the warning is as follows:
```
def monthly_standardize(cols, df_train, df_train_grouped, df_val, df_val_grouped, df_test, df_test_grouped):
# Disable the SettingWithCopyWarning warning
pd.options.mode.chained_assignment = None
for c in cols:
df_train[c] = df_train_grouped[c].transform(lambda x: scale(x.astype(float)))
df_val[c] = df_val_grouped[c].transform(lambda x: scale(x.astype(float)))
df_test[c] = df_test_grouped[c].transform(lambda x: scale(x.astype(float)))
return df_train, df_val, df_test
```
I am already disabling one warning. I don't want to disable all warnings, I just want to disable this warning. I am using python 3.7 and sklearn version 0.0 | 2019/02/19 | [
"https://Stackoverflow.com/questions/54768539",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10973400/"
] | To ignore for specific code blocks:
```py
import warnings
class IgnoreWarnings(object):
def __init__(self, message):
self.message = message
def __enter__(self):
warnings.filterwarnings("ignore", message=f".*{self.message}.*")
def __exit__(self, *_):
warnings.filterwarnings("default", message=f".*{self.message}.*")
with IgnoreWarnings("fish"):
warnings.warn("here be fish")
warnings.warn("here be dog")
warnings.warn("here were fish")
```
```
UserWarning: here be dog
UserWarning: here were fish
``` | The python contextlib has a contextmamager for this: [suppress](https://docs.python.org/3/library/contextlib.html#contextlib.suppress)
```
from contextlib import suppress
with suppress(UserWarning):
for c in cols:
df_train[c] = df_train_grouped[c].transform(lambda x: scale(x.astype(float)))
df_val[c] = df_val_grouped[c].transform(lambda x: scale(x.astype(float)))
``` |
54,768,539 | While I iterate within a for loop I continually receive the same warning, which I want to suppress. The warning reads:
`C:\Users\Nick Alexander\AppData\Local\Programs\Python\Python37\lib\site-packages\sklearn\preprocessing\data.py:193: UserWarning: Numerical issues were encountered when scaling the data and might not be solved. The standard deviation of the data is probably very close to 0. warnings.warn("Numerical issues were encountered "`
The code that is producing the warning is as follows:
```
def monthly_standardize(cols, df_train, df_train_grouped, df_val, df_val_grouped, df_test, df_test_grouped):
# Disable the SettingWithCopyWarning warning
pd.options.mode.chained_assignment = None
for c in cols:
df_train[c] = df_train_grouped[c].transform(lambda x: scale(x.astype(float)))
df_val[c] = df_val_grouped[c].transform(lambda x: scale(x.astype(float)))
df_test[c] = df_test_grouped[c].transform(lambda x: scale(x.astype(float)))
return df_train, df_val, df_test
```
I am already disabling one warning. I don't want to disable all warnings, I just want to disable this warning. I am using python 3.7 and sklearn version 0.0 | 2019/02/19 | [
"https://Stackoverflow.com/questions/54768539",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10973400/"
] | ```
import warnings
with warnings.catch_warnings():
warnings.simplefilter('ignore')
# code that produces a warning
```
`warnings.catch_warnings()` means "whatever `warnings.` methods are run within this block, undo them when exiting the block". | To ignore for specific code blocks:
```py
import warnings
class IgnoreWarnings(object):
def __init__(self, message):
self.message = message
def __enter__(self):
warnings.filterwarnings("ignore", message=f".*{self.message}.*")
def __exit__(self, *_):
warnings.filterwarnings("default", message=f".*{self.message}.*")
with IgnoreWarnings("fish"):
warnings.warn("here be fish")
warnings.warn("here be dog")
warnings.warn("here were fish")
```
```
UserWarning: here be dog
UserWarning: here were fish
``` |
60,094,997 | Given a triangular matrix `m` in python how best to extract from it the value at row `i` column `j`?
```
m = [1,np.nan,np.nan,2,3,np.nan,4,5,6]
m = pd.DataFrame(np.array(x).reshape((3,3)))
```
Which looks like:
```
0 1 2
0 1.0 NaN NaN
1 2.0 3.0 NaN
2 4.0 5.0 6.0
```
I can get lower elements easily `m[2,0]` returns `4`.
But if I ask for `m[0,2]` i get `nan` when I would like `4` again.
What is the best way of accomplishing this with in python? | 2020/02/06 | [
"https://Stackoverflow.com/questions/60094997",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6948859/"
] | Use `pandas.DataFrame.fillna` with transpose:
```
m = m.fillna(m.T)
print(m)
```
Output:
```
0 1 2
0 1.0 2.0 4.0
1 2.0 3.0 5.0
2 4.0 5.0 6.0
m.loc[0,2] == m.loc[2,0] == 4
# True
```
---
In case there are column names (like `A`,`B`,`C`):
```
m.where(m.notna(), m.T.values)
```
Output:
```
A B C
0 1.0 2.0 4.0
1 2.0 3.0 5.0
2 4.0 5.0 6.0
``` | The easiest way I have found to solve this is to make the matrix symmetrical, I learnt how from [this](https://stackoverflow.com/a/2573982/6948859) answer.
There are a couple of steps:
1. Convert nan to 0
```
m0 = np.nan_to_num(m)
```
2. Add the transpose of the matrix to itself
```
m = m0 + m0.T
```
3. Subtract the diagonal
```
m = m - np.diag(m0.diagonal())
```
Then `m[0,2]` and `m[2,0]` will both give you `4`.
```
0 1 2
0 1.0 2.0 4.0
1 2.0 3.0 5.0
2 4.0 5.0 6.0
``` |
48,924,491 | Working in python 3.
So I have a dictionary like this;
`{"stripes": [1,0,5,3], "legs": [4,4,2,3], "colour": ['red', 'grey', 'blue', 'green']}`
I know all the lists in the dictionary have the same length, but the may not contain the same type of element. Some of them may even be lists of lists.
I want to return a dictionary like this;
`$>>> Get_element(2)
{"stripes": 5, "legs": 2, "colour": 'blue'}`
I know that dictionary comprehension is a thing, but I'm a bit confused on how to use it. I'm not sure if it's the most elegant way to achieve my goal either, can I slice a dictionary? | 2018/02/22 | [
"https://Stackoverflow.com/questions/48924491",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7690011/"
] | The answer to your question would be in this particular case to NOT use LINQ. My advice is to avoid abusing LINQ methods like `.ToList(), .ToArray()` etc, since it has a huge impact on performance. You iterate through the collection and creating a new collection. Very often simple `foreach` much more readable and understandable than a train of LINQ methods. | Linq is usually used to query and transform some data.
In case you can change how `persons` are created, this will be the best approach:
```
Person[] persons = nums.Select(n => new Person { Age = n }).ToArray();
```
If you already have the list of persons, go with the `foreach` loop. LinQ should be only used for querying, not modifying |
48,924,491 | Working in python 3.
So I have a dictionary like this;
`{"stripes": [1,0,5,3], "legs": [4,4,2,3], "colour": ['red', 'grey', 'blue', 'green']}`
I know all the lists in the dictionary have the same length, but the may not contain the same type of element. Some of them may even be lists of lists.
I want to return a dictionary like this;
`$>>> Get_element(2)
{"stripes": 5, "legs": 2, "colour": 'blue'}`
I know that dictionary comprehension is a thing, but I'm a bit confused on how to use it. I'm not sure if it's the most elegant way to achieve my goal either, can I slice a dictionary? | 2018/02/22 | [
"https://Stackoverflow.com/questions/48924491",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7690011/"
] | The answer to your question would be in this particular case to NOT use LINQ. My advice is to avoid abusing LINQ methods like `.ToList(), .ToArray()` etc, since it has a huge impact on performance. You iterate through the collection and creating a new collection. Very often simple `foreach` much more readable and understandable than a train of LINQ methods. | You could do it with linq but you're better of using a simple for loop.
Here's one (convoluted) way to do it:
```
persons
.Select((x, i) => new {Person = x, Id =i})
.ToList()
.ForEach(x=> x.Person.Age = nums[x.Id]);
``` |
48,924,491 | Working in python 3.
So I have a dictionary like this;
`{"stripes": [1,0,5,3], "legs": [4,4,2,3], "colour": ['red', 'grey', 'blue', 'green']}`
I know all the lists in the dictionary have the same length, but the may not contain the same type of element. Some of them may even be lists of lists.
I want to return a dictionary like this;
`$>>> Get_element(2)
{"stripes": 5, "legs": 2, "colour": 'blue'}`
I know that dictionary comprehension is a thing, but I'm a bit confused on how to use it. I'm not sure if it's the most elegant way to achieve my goal either, can I slice a dictionary? | 2018/02/22 | [
"https://Stackoverflow.com/questions/48924491",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7690011/"
] | The answer to your question would be in this particular case to NOT use LINQ. My advice is to avoid abusing LINQ methods like `.ToList(), .ToArray()` etc, since it has a huge impact on performance. You iterate through the collection and creating a new collection. Very often simple `foreach` much more readable and understandable than a train of LINQ methods. | Linq does not modify collections
Only one way to proceed
```
void Main()
{
int[] nums = { 1, 2, 3 };
var persons = nums.Select(n=>new Person{Age=n});
}
```
After that every person in persons will have provided Age. |
14,631,708 | I need to set up a private PyPI repository. I've realized there are a lot of them to choose from, and after surfing around, I chose [djangopypi2](http://djangopypi2.readthedocs.org/) since I found their installation instructions the clearest and the project is active.
I have never used Django before, so the question might really be a Django question. I followed the instructions and started up the application with this command:
```
$ gunicorn_django djangopypi2.website.settings
```
The repository is working as I want. After configuring '~/.pypirc', I can upload packages using:
```
$ python setup.py sdist upload -r local
```
And after configuring '~/.pip/pip.conf' with 'extra-index-url' I can install packages using:
```
$ pip install <package-name>
```
However, anyone can browse and download my packages. Authentication seems to only be needed for uploading packages. I tried using this example to require login to all pages:
[Best way to make Django's login\_required the default](https://stackoverflow.com/questions/2164069/best-way-to-make-djangos-login-required-the-default/2164224#2164224)
And set this:
```
LOGIN_REQUIRED_URLS = (
r'/(.*)$',
)
LOGIN_REQUIRED_URLS_EXCEPTIONS = (
r'/users/login(.*)$',
r'/users/logout(.*)$',
)
```
Now the webgui requires login on all pages, so that part works as expected, but I am not able to use the pip and upload utilities from the command-line anymore.
I tried 'pip install xxx' using the extra-index-url setting in 'pip.conf' like this:
```
extra-index-url = http://username:password@127.0.0.1:8000/simple/
```
but it says 'No distributions at all found for xxx'
'python setup.py sdist upload' gives:
```
Submitting dist/xxx-0.0.1.tar.gz to http://127.0.0.1:8000/
Upload failed (302): FOUND
```
So the question is, how do I enable authentication to work from 'pip' and 'python setup.py register/upload'? | 2013/01/31 | [
"https://Stackoverflow.com/questions/14631708",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1919913/"
] | You could declare, *and implement*, a pure virtual destructor:
```
class ShapeF
{
public:
virtual ~ShapeF() = 0;
...
};
ShapeF::~ShapeF() {}
```
It's a tiny step from what you already have, and will prevent `ShapeF` from being instantiated directly. The derived classes won't need to change. | Try using a protected constructor |
14,631,708 | I need to set up a private PyPI repository. I've realized there are a lot of them to choose from, and after surfing around, I chose [djangopypi2](http://djangopypi2.readthedocs.org/) since I found their installation instructions the clearest and the project is active.
I have never used Django before, so the question might really be a Django question. I followed the instructions and started up the application with this command:
```
$ gunicorn_django djangopypi2.website.settings
```
The repository is working as I want. After configuring '~/.pypirc', I can upload packages using:
```
$ python setup.py sdist upload -r local
```
And after configuring '~/.pip/pip.conf' with 'extra-index-url' I can install packages using:
```
$ pip install <package-name>
```
However, anyone can browse and download my packages. Authentication seems to only be needed for uploading packages. I tried using this example to require login to all pages:
[Best way to make Django's login\_required the default](https://stackoverflow.com/questions/2164069/best-way-to-make-djangos-login-required-the-default/2164224#2164224)
And set this:
```
LOGIN_REQUIRED_URLS = (
r'/(.*)$',
)
LOGIN_REQUIRED_URLS_EXCEPTIONS = (
r'/users/login(.*)$',
r'/users/logout(.*)$',
)
```
Now the webgui requires login on all pages, so that part works as expected, but I am not able to use the pip and upload utilities from the command-line anymore.
I tried 'pip install xxx' using the extra-index-url setting in 'pip.conf' like this:
```
extra-index-url = http://username:password@127.0.0.1:8000/simple/
```
but it says 'No distributions at all found for xxx'
'python setup.py sdist upload' gives:
```
Submitting dist/xxx-0.0.1.tar.gz to http://127.0.0.1:8000/
Upload failed (302): FOUND
```
So the question is, how do I enable authentication to work from 'pip' and 'python setup.py register/upload'? | 2013/01/31 | [
"https://Stackoverflow.com/questions/14631708",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1919913/"
] | You could declare, *and implement*, a pure virtual destructor:
```
class ShapeF
{
public:
virtual ~ShapeF() = 0;
...
};
ShapeF::~ShapeF() {}
```
It's a tiny step from what you already have, and will prevent `ShapeF` from being instantiated directly. The derived classes won't need to change. | If your compiler is Visual C++ then there is also an "abstract" keyword:
```
class MyClass abstract
{
// whatever...
};
```
Though AFAIK it will not compile on other compilers, it's one of Microsoft custom keywords. |
14,631,708 | I need to set up a private PyPI repository. I've realized there are a lot of them to choose from, and after surfing around, I chose [djangopypi2](http://djangopypi2.readthedocs.org/) since I found their installation instructions the clearest and the project is active.
I have never used Django before, so the question might really be a Django question. I followed the instructions and started up the application with this command:
```
$ gunicorn_django djangopypi2.website.settings
```
The repository is working as I want. After configuring '~/.pypirc', I can upload packages using:
```
$ python setup.py sdist upload -r local
```
And after configuring '~/.pip/pip.conf' with 'extra-index-url' I can install packages using:
```
$ pip install <package-name>
```
However, anyone can browse and download my packages. Authentication seems to only be needed for uploading packages. I tried using this example to require login to all pages:
[Best way to make Django's login\_required the default](https://stackoverflow.com/questions/2164069/best-way-to-make-djangos-login-required-the-default/2164224#2164224)
And set this:
```
LOGIN_REQUIRED_URLS = (
r'/(.*)$',
)
LOGIN_REQUIRED_URLS_EXCEPTIONS = (
r'/users/login(.*)$',
r'/users/logout(.*)$',
)
```
Now the webgui requires login on all pages, so that part works as expected, but I am not able to use the pip and upload utilities from the command-line anymore.
I tried 'pip install xxx' using the extra-index-url setting in 'pip.conf' like this:
```
extra-index-url = http://username:password@127.0.0.1:8000/simple/
```
but it says 'No distributions at all found for xxx'
'python setup.py sdist upload' gives:
```
Submitting dist/xxx-0.0.1.tar.gz to http://127.0.0.1:8000/
Upload failed (302): FOUND
```
So the question is, how do I enable authentication to work from 'pip' and 'python setup.py register/upload'? | 2013/01/31 | [
"https://Stackoverflow.com/questions/14631708",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1919913/"
] | Try using a protected constructor | If your compiler is Visual C++ then there is also an "abstract" keyword:
```
class MyClass abstract
{
// whatever...
};
```
Though AFAIK it will not compile on other compilers, it's one of Microsoft custom keywords. |
74,242,407 | I have a code that looks like:
```
#!/usr/bin/env python
'''Plot multiple DOS/PDOS in a single plot
run python dplot.py -h for more usage
'''
import argparse
import sys
import matplotlib.pyplot as plt
import numpy as np
parser = argparse.ArgumentParser()
# parser.add_argument('--dos', help='Plot the dos', required=True)
parser.add_argument('--dos', nargs='*', help='Files to plot')
parser.add_argument('--label', nargs='*', help='Label of the files')
parser.add_argument('--fermi', help='Fermi Energy')
args = parser.parse_args()
```
If I run this code with `python foo.py -h`, I get the output:
```
usage: foo.py [-h] [--dos [DOS ...]] [--label [LABEL ...]] [--fermi FERMI]
options:
-h, --help show this help message and exit
--dos [DOS ...] Files to plot
--label [LABEL ...] Label of the files
--fermi FERMI Fermi Energy
```
I know I can separately print the docstring using `print(__doc__)`.
But, I want the `python foo.py -h` to print both the docstring together with the present `-h` output. That is, `python foo.py -h` should give:
```
Plot multiple DOS/PDOS in a single plot
run python dplot.py -h for more usage
usage: foo.py [-h] [--dos [DOS ...]] [--label [LABEL ...]] [--fermi FERMI]
options:
-h, --help show this help message and exit
--dos [DOS ...] Files to plot
--label [LABEL ...] Label of the files
--fermi FERMI Fermi Energy
```
Is this possible? | 2022/10/29 | [
"https://Stackoverflow.com/questions/74242407",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2005559/"
] | Use `window` property `localStorage` to save the `theme` value across browser sessions.
Try the following code:
```
const theme = localStorage.getItem('theme')
if (!theme) localStorage.setItem('theme', 'light') // set the theme; by default 'light'
document.body.classList.add(theme)
``` | here is a way you could do it: Cookies.
```
function toggleDarkMode() {
let darkTheme= document.body;
darkTheme.classList.toggle("darkMode");
document.cookie = "theme=dark";
}
```
```
function toggleLightMode() {
let lightTheme= document.body;
lightTheme.classList.toggle("lightMode");
document.cookie = "theme=light";
}
```
and then to check:
```
let theme = document.cookie;
if(theme === 'theme=light'){
let lightTheme= document.body;
lightTheme.classList.toggle("lightMode");
} else if {
let darkTheme= document.body;
darkTheme.classList.toggle("darkMode");
}
``` |
38,571,667 | I'm trying to use Python to download an Excel file to my local drive from Box.
Using the boxsdk I was able to authenticate via OAuth2 and successfully get the file id on Box.
However when I use the `client.file(file_id).content()` function, it just returns a string, and if I use `client.file(file_id).get()` then it just gives me a `boxsdk.object.file.File`.
Does anybody know how to write either of these to an Excel file on the local machine? Or a better method of using Python to download an excel file from Box.
(I discovered that `boxsdk.object.file.File` has an option `download_to(writeable_stream` [here](http://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html) but I have no idea how to use that to create an Excel file and my searches haven't been helpful). | 2016/07/25 | [
"https://Stackoverflow.com/questions/38571667",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6635737/"
] | It is correct that the documentation and source for `download_to` can be found [here](http://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html?highlight=download_to#boxsdk.object.file.File.download_to) and [here](http://box-python-sdk.readthedocs.io/en/latest/_modules/boxsdk/object/file.html#File.download_to). I learned about it from [this answer](https://stackoverflow.com/a/49315500/778533) myself. You just need to do the following
```
path = 'anyFileName.xlsx'
with open(path, 'wb') as f:
client.file(file_id).download_to(f)
``` | You could use python [csv library](https://docs.python.org/2/library/csv.html), along with dialect='excel' flag. It works really nice for exporting data to Microsoft Excel.
The main idea is to use csv.writer inside a loop for writing each line. Try this and if you can't, post the code here. |
38,571,667 | I'm trying to use Python to download an Excel file to my local drive from Box.
Using the boxsdk I was able to authenticate via OAuth2 and successfully get the file id on Box.
However when I use the `client.file(file_id).content()` function, it just returns a string, and if I use `client.file(file_id).get()` then it just gives me a `boxsdk.object.file.File`.
Does anybody know how to write either of these to an Excel file on the local machine? Or a better method of using Python to download an excel file from Box.
(I discovered that `boxsdk.object.file.File` has an option `download_to(writeable_stream` [here](http://box-python-sdk.readthedocs.io/en/latest/boxsdk.object.html) but I have no idea how to use that to create an Excel file and my searches haven't been helpful). | 2016/07/25 | [
"https://Stackoverflow.com/questions/38571667",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6635737/"
] | This is what I use to read my excel files from box and you can check the content character type and use that when decoding.
```
from boxsdk import JWTAuth
from boxsdk import Client
import io
import pandas as pd
import chardet # for checking char type
# Configure JWT auth object
sdk = JWTAuth.from_settings_file('config/box_config.json')
# Get auth client
client = Client(sdk)
s = client.file(file.id).content()
print(chardet.detect(open(s, 'rb').read())['encoding']) # gives char type
outputDF = pd.read_excel(io.StringIO(s.decode('utf-8')))
``` | You could use python [csv library](https://docs.python.org/2/library/csv.html), along with dialect='excel' flag. It works really nice for exporting data to Microsoft Excel.
The main idea is to use csv.writer inside a loop for writing each line. Try this and if you can't, post the code here. |
53,077,341 | I am trying to find the proper python syntax to create a flag with a value of `yes` if `columnx` contains any of the following numbers: **`1, 2, 3, 4, 5`**.
```
def create_flag(df):
if df['columnx'] in (1,2,3,4,5):
return df['flag']=='yes'
```
I get the following error.
>
> TypeError: invalid type comparison
>
>
>
Is there an obvious mistake in my syntax? | 2018/10/31 | [
"https://Stackoverflow.com/questions/53077341",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6365890/"
] | Use `np.where` with pandas `isin` as:
```
df['flag'] = np.where(df['columnx'].isin([1,2,3,4,5]),'yes','no')
``` | You have lot of problems in your code! i assume you want to try something like this
```
def create_flag(df):
if df['columnx'] in [1,2,3,4,5]:
df['flag']='yes'
x = {"columnx":2,'flag':None}
create_flag(x)
print(x["flag"])
``` |
25,299,625 | I have implemented a REST Api (<http://www.django-rest-framework.org/>) as follows:
```
@csrf_exempt
@api_view(['PUT'])
def updateinfo(request, id, format=None):
try:
user = User.objects.get(id=id)
except User.DoesNotExist:
return HttpResponse(status=status.HTTP_404_NOT_FOUND)
if request.method == 'PUT':
serializer = UserSerializer(user, data=request.DATA)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
```
which works fine when I update user info through browser.
But I have difficulties calling this Api using Requests (<http://docs.python-requests.org/en/latest/>).
This is my code where I am calling the above api:
```
payload = {'id':id, ...}
resp = requests.put(updateuserinfo_url, data=payload)
```
and this is the response that I receive:
```
resp.text
{"id": ["This field is required."], ...}
```
I checked `request.DATA` and it seems that it is empty. I appreciate if someone could help with finding what is wrong with my code, or if I am missing some additional settings/arguments required to make this simple request. | 2014/08/14 | [
"https://Stackoverflow.com/questions/25299625",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3324751/"
] | You are missing the django-rest framework parser decorator, in your case, you need use `@parser_classes((FormParser,))` to populate request.DATA dict. [Read more here](http://www.django-rest-framework.org/api-guide/parsers)
try with that:
```
from rest_framework.parsers import FormParser
@parser_classes((FormParser,))
@csrf_exempt
@api_view(['PUT'])
def updateinfo(request, id, format=None):
try:
user = User.objects.get(id=id)
except User.DoesNotExist:
return HttpResponse(status=status.HTTP_404_NOT_FOUND)
if request.method == 'PUT':
serializer = UserSerializer(user, data=request.DATA)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
``` | Try doing everything using JSON.
1. Add JSONParser, like [levi](https://stackoverflow.com/users/1539655/levi) explained
2. Add custom headers to your request, like in [this example](http://docs.python-requests.org/en/latest/user/quickstart/#custom-headers)
So for you, maybe something like:
```
>>> payload = {'id':id, ...}
>>> headers = {'content-type': 'application/json'}
>>> r = requests.put(url, data=json.dumps(payload), headers=headers)
``` |
25,299,625 | I have implemented a REST Api (<http://www.django-rest-framework.org/>) as follows:
```
@csrf_exempt
@api_view(['PUT'])
def updateinfo(request, id, format=None):
try:
user = User.objects.get(id=id)
except User.DoesNotExist:
return HttpResponse(status=status.HTTP_404_NOT_FOUND)
if request.method == 'PUT':
serializer = UserSerializer(user, data=request.DATA)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
```
which works fine when I update user info through browser.
But I have difficulties calling this Api using Requests (<http://docs.python-requests.org/en/latest/>).
This is my code where I am calling the above api:
```
payload = {'id':id, ...}
resp = requests.put(updateuserinfo_url, data=payload)
```
and this is the response that I receive:
```
resp.text
{"id": ["This field is required."], ...}
```
I checked `request.DATA` and it seems that it is empty. I appreciate if someone could help with finding what is wrong with my code, or if I am missing some additional settings/arguments required to make this simple request. | 2014/08/14 | [
"https://Stackoverflow.com/questions/25299625",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3324751/"
] | You are missing the django-rest framework parser decorator, in your case, you need use `@parser_classes((FormParser,))` to populate request.DATA dict. [Read more here](http://www.django-rest-framework.org/api-guide/parsers)
try with that:
```
from rest_framework.parsers import FormParser
@parser_classes((FormParser,))
@csrf_exempt
@api_view(['PUT'])
def updateinfo(request, id, format=None):
try:
user = User.objects.get(id=id)
except User.DoesNotExist:
return HttpResponse(status=status.HTTP_404_NOT_FOUND)
if request.method == 'PUT':
serializer = UserSerializer(user, data=request.DATA)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
``` | There was a problem with Requests' package. I reinstalled the package and now it is working.
Thank you all. |
25,299,625 | I have implemented a REST Api (<http://www.django-rest-framework.org/>) as follows:
```
@csrf_exempt
@api_view(['PUT'])
def updateinfo(request, id, format=None):
try:
user = User.objects.get(id=id)
except User.DoesNotExist:
return HttpResponse(status=status.HTTP_404_NOT_FOUND)
if request.method == 'PUT':
serializer = UserSerializer(user, data=request.DATA)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
```
which works fine when I update user info through browser.
But I have difficulties calling this Api using Requests (<http://docs.python-requests.org/en/latest/>).
This is my code where I am calling the above api:
```
payload = {'id':id, ...}
resp = requests.put(updateuserinfo_url, data=payload)
```
and this is the response that I receive:
```
resp.text
{"id": ["This field is required."], ...}
```
I checked `request.DATA` and it seems that it is empty. I appreciate if someone could help with finding what is wrong with my code, or if I am missing some additional settings/arguments required to make this simple request. | 2014/08/14 | [
"https://Stackoverflow.com/questions/25299625",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3324751/"
] | Try doing everything using JSON.
1. Add JSONParser, like [levi](https://stackoverflow.com/users/1539655/levi) explained
2. Add custom headers to your request, like in [this example](http://docs.python-requests.org/en/latest/user/quickstart/#custom-headers)
So for you, maybe something like:
```
>>> payload = {'id':id, ...}
>>> headers = {'content-type': 'application/json'}
>>> r = requests.put(url, data=json.dumps(payload), headers=headers)
``` | There was a problem with Requests' package. I reinstalled the package and now it is working.
Thank you all. |
33,715,198 | I am new to python. I was trying to make a random # generator but nothing works except for the else statement. I cannot tell what the issue is. Please Help!
```
import random
randomNum = random.randint(1, 10)
answer = int(raw_input("Try to guess a random number between 1 and 10. "))
if (answer > randomNum) and (answer < randomNum):
if (answer == randomNum + 1):
print "Super Close"
print randomNum
elif (answer == randomNum + 2):
print "Pretty Close"
print randomNum
elif (answer == randomNum + 3):
print "Fairly Close"
print randomNum
elif (answer == randomNum + 4):
print "Not Really Close"
print randomNum
elif (answer == randomNum + 5):
print "Far"
print randomNum
elif (answer == randomNum - 5):
print "Far"
print randomNum
elif (answer == randomNum - 4):
print "Not Really Close"
print randomNum
elif (answer == randomNum - 3):
print "Fairly Close"
print randomNum
elif (answer == randomNum - 2):
print "Pretty Close"
print randomNum
elif (answer == randomNum - 1):
print "Super Close"
print randomNum
else:
print "Good Job!"
print randomNum
``` | 2015/11/15 | [
"https://Stackoverflow.com/questions/33715198",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5563197/"
] | Your first `if` statement logic is incorrect. `answer` cannot *at the same time* be both smaller and larger than `randomNum`, yet that is what your test asks for.
You want to use `or` instead of `and` there, if the `answer` value is larger *or* smaller than `randomNum`:
```
if (answer > randomNum) or (answer < randomNum):
```
or simply use `!=` to test for inequality:
```
if answer != randomNum:
``` | **I used this code for my random number generator and it works, I hope it helps**
You can change the highest and lowest random number you want to generate (0,20)
```
import random
maths_operator_list=['+','-','*']
maths_operator = random.choice(maths_operator_list)
number_one = random.randint(0,20)
number_two = random.randint(0,20)
correct_answer = 0
print(str(number_one), str(maths_operator), number_two)
if maths_operator == '+':
correct_answer = number_one + number_two
elif maths_operator == '-':
correct_answer = number_one - number_two
elif maths_operator == '*':
correct_answer = number_one * number_two
print(correct_answer)
``` |
68,737,471 | I have a dict with some value in it. Now at the time of fetching value I want to check if value is `None` replace it with `""`. Is there any single statement way for this.
```
a = {'x' : 1, 'y': None}
x = a.get('x', 3) # if x is not present init x with 3
z = a.get('z', 1) # Default value of z to 1
y = a.get('y', 1) # It will initialize y with None
# current solution I'm checking
if y is None:
y = ""
```
What I want is something single line (pythonic way). I can do this in below way
```
# This is one way I can write but
y = "" if a.get('y',"") is None else a.get('y', "")
```
But from what I know there must be some better way of doing this. Any help | 2021/08/11 | [
"https://Stackoverflow.com/questions/68737471",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8595891/"
] | If the only falsy values you care about are `None` and `''`, you could do:
```
y = a.get('y', 1) or ''
``` | ```
y = a.get('y',"") or ""
``` |
68,737,471 | I have a dict with some value in it. Now at the time of fetching value I want to check if value is `None` replace it with `""`. Is there any single statement way for this.
```
a = {'x' : 1, 'y': None}
x = a.get('x', 3) # if x is not present init x with 3
z = a.get('z', 1) # Default value of z to 1
y = a.get('y', 1) # It will initialize y with None
# current solution I'm checking
if y is None:
y = ""
```
What I want is something single line (pythonic way). I can do this in below way
```
# This is one way I can write but
y = "" if a.get('y',"") is None else a.get('y', "")
```
But from what I know there must be some better way of doing this. Any help | 2021/08/11 | [
"https://Stackoverflow.com/questions/68737471",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8595891/"
] | [Jasmijn's answer](https://stackoverflow.com/a/68737515/12975140) is very clean. If you need to accommodate other [falsy](https://stackoverflow.com/a/39983806/12975140) values *and* you insist on doing it in one line, you could use an [assignment expression](https://www.python.org/dev/peps/pep-0572/):
```
y = "" if (initial := a.get('y', "")) is None else initial
```
But personally I would prefer your separate `if` check for clarity over this. | ```
y = a.get('y',"") or ""
``` |
68,737,471 | I have a dict with some value in it. Now at the time of fetching value I want to check if value is `None` replace it with `""`. Is there any single statement way for this.
```
a = {'x' : 1, 'y': None}
x = a.get('x', 3) # if x is not present init x with 3
z = a.get('z', 1) # Default value of z to 1
y = a.get('y', 1) # It will initialize y with None
# current solution I'm checking
if y is None:
y = ""
```
What I want is something single line (pythonic way). I can do this in below way
```
# This is one way I can write but
y = "" if a.get('y',"") is None else a.get('y', "")
```
But from what I know there must be some better way of doing this. Any help | 2021/08/11 | [
"https://Stackoverflow.com/questions/68737471",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8595891/"
] | If the only falsy values you care about are `None` and `''`, you could do:
```
y = a.get('y', 1) or ''
``` | [Jasmijn's answer](https://stackoverflow.com/a/68737515/12975140) is very clean. If you need to accommodate other [falsy](https://stackoverflow.com/a/39983806/12975140) values *and* you insist on doing it in one line, you could use an [assignment expression](https://www.python.org/dev/peps/pep-0572/):
```
y = "" if (initial := a.get('y', "")) is None else initial
```
But personally I would prefer your separate `if` check for clarity over this. |
55,231,300 | I am using Django Rest Framework. I have an existing database (cannot make any changes to it). I have defined a serializer - ReceiptLog with no model, which should create entries in TestCaseCommandRun and TestCaseCommandRunResults when a post() request is made to ReceiptLog api endpoint. Receipt log doesn't exist in the database, I am using it just as an endpoint to accept a combined payload and create entries in underlying tables. Post() to TestCaseCommandRunResults and TestCaseCommandRun works independently, however, when I try to post through ReceiptLog it throws below error
Error Traceback:
```
File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/exception.py" in inner
35. response = get_response(request)
File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/base.py" in _get_response
128. response = self.process_exception_by_middleware(e, request)
File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/base.py" in _get_response
126. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/usr/lib/python3.6/contextlib.py" in inner
52. return func(*args, **kwds)
File "/usr/local/lib/python3.6/dist-packages/django/views/decorators/csrf.py" in wrapped_view
54. return view_func(*args, **kwargs)
File "/usr/local/lib/python3.6/dist-packages/django/views/generic/base.py" in view
69. return self.dispatch(request, *args, **kwargs)
File "/usr/local/lib/python3.6/dist-packages/rest_framework/views.py" in dispatch
495. response = self.handle_exception(exc)
File "/usr/local/lib/python3.6/dist-packages/rest_framework/views.py" in handle_exception
455. self.raise_uncaught_exception(exc)
File "/usr/local/lib/python3.6/dist-packages/rest_framework/views.py" in dispatch
492. response = handler(request, *args, **kwargs)
File "/usr/local/lib/python3.6/dist-packages/rest_framework/generics.py" in post
192. return self.create(request, *args, **kwargs)
File "/usr/local/lib/python3.6/dist-packages/rest_framework/mixins.py" in create
21. self.perform_create(serializer)
File "/usr/local/lib/python3.6/dist-packages/rest_framework/mixins.py" in perform_create
26. serializer.save()
File "/usr/local/lib/python3.6/dist-packages/rest_framework/serializers.py" in save
216. '`create()` did not return an object instance.'
Exception Type: AssertionError at /dqf_api/ReceiptLog/
Exception Value: `create()` did not return an object instance.
```
models.py
```
class TestCaseCommandRun(models.Model):
# fields ..Doesn't have id field as the database doesn't have it
class Meta:
managed = False
db_table = 'test_case_command_run'
unique_together = (('team_name', 'suite_name', 'suite_run_id', 'case_name', 'command_name'),)
class TestCaseCommandRunResults(models.Model):
# fields ..Doesn't have id field as the database doesn't have it
class Meta:
managed = False
db_table = 'test_case_command_run_results'
unique_together = (('suite_run_id', 'command_run_id', 'rule_name', 'result_id'),)
```
views.py
```
class TestCaseCommandRunViewSet(viewsets.ModelViewSet):
queryset = models.TestCaseCommandRunViewSet.objects.values('team_name','suite_name','suite_run_id', 'case_name','command_name','command_run_id','run_start','run_end','result','run_status')
serializer_class = serializers.TestCaseCommandRunViewSet
class TestCaseCommandRunResultsViewSet(viewsets.ModelViewSet):
queryset = models.TestCaseCommandRunResultsViewSet.objects.values('suite_run_id','command_run_id','rule_name', 'result_id',
'result','expected_values','actual_values','report_values','extended_values')
serializer_class = serializers.TestCaseCommandRunResultsViewSet
class ReceiptLogViewSet(CreateAPIView):
serializer_class = serializers.ReceiptLogSerializer.ReceiptLogSerializerClass
```
serializers.py
```
class TestCaseCommandRunResultsViewSet(serializers.ModelSerializer):
class Meta:
model = models.TestCaseCommandRunResultsViewSet
fields = ['suite_run_id','command_run_id','rule_name', 'result_id','result','expected_values','actual_values','report_values','extended_values']
class TestCaseCommandRunSerializer(serializers.ModelSerializer):
class Meta:
model = models.TestCaseCommandRunSerializer
fields = ['team_name','suite_name','suite_run_id', 'case_name','command_name','command_run_id','run_start','run_end','result','run_status']
class ReceiptLogSerializerClass(serializers.Serializer):
team_name = serializers.CharField(max_length=30)
suite_name = serializers.CharField(max_length=100)
suite_run_id = serializers.CharField(max_length=50,required=False, allow_blank=True, default=datetime.now().strftime('%Y%m%d%H%M%S'))
case_name = serializers.CharField(max_length=50)
command_name = serializers.CharField(max_length=50)
command_run_id = serializers.CharField(max_length=50,required=False, allow_blank=True, default='Not Applicable')
run_start = serializers.DateTimeField(default=datetime.now, required=False)
run_end = serializers.DateTimeField(default=datetime.now, required=False)
result = serializers.CharField(max_length=10, default='Not Applicable')
run_status = serializers.CharField(max_length=10)
rule_name = serializers.CharField( max_length=50, required=False, allow_blank=True, default='Not Applicable')
expected_values = serializers.CharField(max_length=200, allow_blank=True)
actual_values = serializers.CharField(max_length=200, allow_blank=True)
report_values = serializers.CharField(max_length=200, allow_blank=True)
extended_values = serializers.CharField(max_length=200, allow_blank=True)
def create(self, validated_data):
# command_run_data_list = []
command_run_results_data_list = []
raw_data_list = []
many = isinstance(validated_data, list)
if many:
raw_data_list = validated_data
else:
raw_data_list.append(validated_data)
result_id = 1
for data_row in raw_data_list:
new_command_run_entry = {
'team_name': data_row.get('team_name'),
'suite_name': data_row.get('suite_name'),
'suite_run_id': data_row.get('suite_run_id'),
'case_name': data_row.get('case_name'),
'command_name': data_row.get('command_name'),
'command_run_id': data_row.get('command_run_id'),
'run_start': data_row.get('run_start'),
'run_end': data_row.get('run_end'),
'result': data_row.get('result'),
'run_status': data_row.get('run_status')
}
command_run_data_list.append(new_command_run_entry)
new_command_run_result_entry = {
'suite_run_id': data_row.get('suite_run_id'),
'command_run_id': data_row.get('command_run_id'),
'rule_name': data_row.get('rule_name'),
'result_id': result_id,
'result': data_row.get('result'), # PASS or FAIL
'expected_values': data_row.get('expected_values'),
'actual_values': data_row.get('actual_values'),
'report_values': data_row.get('report_values'),
'extended_values': data_row.get('extended_values'),
}
command_run_results_data_list.append(new_command_run_result_entry)
result_id += 1
for item in command_run_results_data_list:
response_run_results = models.TestCaseCommandRunResults.objects.create(**item)
for item in command_run_data_list:
response_run = models.TestCaseCommandRun.objects.create(**item)
```
urls.py
```
router = routers.DefaultRouter()
router.register(r'test_case_command_runs', views.TestCaseCommandRunViewSet)
router.register(r'test_case_command_run_results', views.TestCaseCommandRunResultsViewSet)
urlpatterns = [
url(r'^buildInfo', views.build_info),
url(r'^isActive', views.is_active),
url(r'^dqf_api/', include(router.urls)),
url(r'^dqf_api/ReceiptLog/', views.ReceiptLogView.ReceiptLogViewSet.as_view(), name='ReceiptLog')]
```
Any help is really appreciated.I am new to Django and DRF | 2019/03/18 | [
"https://Stackoverflow.com/questions/55231300",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6885999/"
] | Your serializer's `create` method MUST return an instance of the object it represents. Also, you should not iterate inside the serializer to create instances, that should be done on the view: you iterate through the data, calling the serializer each iteration. | Updated the serializers.py file to include the below code
```
class ReceiptLogSerializerClass(serializers.Serializer):
#Fields
def create(self, validated_data):
raw_data_list = []
many = isinstance(validated_data, list)
if many:
raw_data_list = validated_data
else:
raw_data_list.append(validated_data)
result_id = 1
for data_row in raw_data_list:
new_command_run_entry = {
'team_name': data_row.get('team_name'),
'suite_name': data_row.get('suite_name'),
'suite_run_id': data_row.get('suite_run_id'),
'case_name': data_row.get('case_name'),
'command_name': data_row.get('command_name'),
'command_run_id': data_row.get('command_run_id'),
'run_start': data_row.get('run_start'),
'run_end': data_row.get('run_end'),
'result': data_row.get('result'),
'run_status': data_row.get('run_status')
}
response = TestCaseCommandRunSerializer.create(TestCaseCommandRunSerializer(),validated_data= new_command_run_entry)
new_command_run_result_entry = {
'suite_run_id': data_row.get('suite_run_id'),
'command_run_id': data_row.get('command_run_id'),
'rule_name': data_row.get('rule_name'),
'result_id': result_id,
'result': data_row.get('result'), # PASS or FAIL
'expected_values': data_row.get('expected_values'),
'actual_values': data_row.get('actual_values'),
'report_values': data_row.get('report_values'),
'extended_values': data_row.get('extended_values'),
}
response = TestCaseCommandRunResultsSerializer.create(TestCaseCommandRunResultsSerializer(),validated_data= new_command_run_result_entry)
logger.info(" new_command_run_result_entry response %s" % response)
result_id += 1
return validated_data
```
I was not de-serializing the data correctly and hence ran into multiple issues.
return validated\_data
rectified all the errors and now I am able to post() data to multiple models through single API.
For posting a multiple payloads in a single API Call added below lines in ReceiptLogViewSet
```
def get_serializer(self, *args, **kwargs):
if "data" in kwargs:
data = kwargs["data"]
if isinstance(data, list):
kwargs["many"] = True
return super(ReceiptLogViewSet, self).get_serializer(*args, **kwargs)
```
Ref: [Django rest framework cannot deal with multple objects in model viewset](https://stackoverflow.com/questions/43525860/django-rest-framework-cannot-deal-with-multple-objects-in-model-viewset) |
55,231,300 | I am using Django Rest Framework. I have an existing database (cannot make any changes to it). I have defined a serializer - ReceiptLog with no model, which should create entries in TestCaseCommandRun and TestCaseCommandRunResults when a post() request is made to ReceiptLog api endpoint. Receipt log doesn't exist in the database, I am using it just as an endpoint to accept a combined payload and create entries in underlying tables. Post() to TestCaseCommandRunResults and TestCaseCommandRun works independently, however, when I try to post through ReceiptLog it throws below error
Error Traceback:
```
File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/exception.py" in inner
35. response = get_response(request)
File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/base.py" in _get_response
128. response = self.process_exception_by_middleware(e, request)
File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/base.py" in _get_response
126. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/usr/lib/python3.6/contextlib.py" in inner
52. return func(*args, **kwds)
File "/usr/local/lib/python3.6/dist-packages/django/views/decorators/csrf.py" in wrapped_view
54. return view_func(*args, **kwargs)
File "/usr/local/lib/python3.6/dist-packages/django/views/generic/base.py" in view
69. return self.dispatch(request, *args, **kwargs)
File "/usr/local/lib/python3.6/dist-packages/rest_framework/views.py" in dispatch
495. response = self.handle_exception(exc)
File "/usr/local/lib/python3.6/dist-packages/rest_framework/views.py" in handle_exception
455. self.raise_uncaught_exception(exc)
File "/usr/local/lib/python3.6/dist-packages/rest_framework/views.py" in dispatch
492. response = handler(request, *args, **kwargs)
File "/usr/local/lib/python3.6/dist-packages/rest_framework/generics.py" in post
192. return self.create(request, *args, **kwargs)
File "/usr/local/lib/python3.6/dist-packages/rest_framework/mixins.py" in create
21. self.perform_create(serializer)
File "/usr/local/lib/python3.6/dist-packages/rest_framework/mixins.py" in perform_create
26. serializer.save()
File "/usr/local/lib/python3.6/dist-packages/rest_framework/serializers.py" in save
216. '`create()` did not return an object instance.'
Exception Type: AssertionError at /dqf_api/ReceiptLog/
Exception Value: `create()` did not return an object instance.
```
models.py
```
class TestCaseCommandRun(models.Model):
# fields ..Doesn't have id field as the database doesn't have it
class Meta:
managed = False
db_table = 'test_case_command_run'
unique_together = (('team_name', 'suite_name', 'suite_run_id', 'case_name', 'command_name'),)
class TestCaseCommandRunResults(models.Model):
# fields ..Doesn't have id field as the database doesn't have it
class Meta:
managed = False
db_table = 'test_case_command_run_results'
unique_together = (('suite_run_id', 'command_run_id', 'rule_name', 'result_id'),)
```
views.py
```
class TestCaseCommandRunViewSet(viewsets.ModelViewSet):
queryset = models.TestCaseCommandRunViewSet.objects.values('team_name','suite_name','suite_run_id', 'case_name','command_name','command_run_id','run_start','run_end','result','run_status')
serializer_class = serializers.TestCaseCommandRunViewSet
class TestCaseCommandRunResultsViewSet(viewsets.ModelViewSet):
queryset = models.TestCaseCommandRunResultsViewSet.objects.values('suite_run_id','command_run_id','rule_name', 'result_id',
'result','expected_values','actual_values','report_values','extended_values')
serializer_class = serializers.TestCaseCommandRunResultsViewSet
class ReceiptLogViewSet(CreateAPIView):
serializer_class = serializers.ReceiptLogSerializer.ReceiptLogSerializerClass
```
serializers.py
```
class TestCaseCommandRunResultsViewSet(serializers.ModelSerializer):
class Meta:
model = models.TestCaseCommandRunResultsViewSet
fields = ['suite_run_id','command_run_id','rule_name', 'result_id','result','expected_values','actual_values','report_values','extended_values']
class TestCaseCommandRunSerializer(serializers.ModelSerializer):
class Meta:
model = models.TestCaseCommandRunSerializer
fields = ['team_name','suite_name','suite_run_id', 'case_name','command_name','command_run_id','run_start','run_end','result','run_status']
class ReceiptLogSerializerClass(serializers.Serializer):
team_name = serializers.CharField(max_length=30)
suite_name = serializers.CharField(max_length=100)
suite_run_id = serializers.CharField(max_length=50,required=False, allow_blank=True, default=datetime.now().strftime('%Y%m%d%H%M%S'))
case_name = serializers.CharField(max_length=50)
command_name = serializers.CharField(max_length=50)
command_run_id = serializers.CharField(max_length=50,required=False, allow_blank=True, default='Not Applicable')
run_start = serializers.DateTimeField(default=datetime.now, required=False)
run_end = serializers.DateTimeField(default=datetime.now, required=False)
result = serializers.CharField(max_length=10, default='Not Applicable')
run_status = serializers.CharField(max_length=10)
rule_name = serializers.CharField( max_length=50, required=False, allow_blank=True, default='Not Applicable')
expected_values = serializers.CharField(max_length=200, allow_blank=True)
actual_values = serializers.CharField(max_length=200, allow_blank=True)
report_values = serializers.CharField(max_length=200, allow_blank=True)
extended_values = serializers.CharField(max_length=200, allow_blank=True)
def create(self, validated_data):
# command_run_data_list = []
command_run_results_data_list = []
raw_data_list = []
many = isinstance(validated_data, list)
if many:
raw_data_list = validated_data
else:
raw_data_list.append(validated_data)
result_id = 1
for data_row in raw_data_list:
new_command_run_entry = {
'team_name': data_row.get('team_name'),
'suite_name': data_row.get('suite_name'),
'suite_run_id': data_row.get('suite_run_id'),
'case_name': data_row.get('case_name'),
'command_name': data_row.get('command_name'),
'command_run_id': data_row.get('command_run_id'),
'run_start': data_row.get('run_start'),
'run_end': data_row.get('run_end'),
'result': data_row.get('result'),
'run_status': data_row.get('run_status')
}
command_run_data_list.append(new_command_run_entry)
new_command_run_result_entry = {
'suite_run_id': data_row.get('suite_run_id'),
'command_run_id': data_row.get('command_run_id'),
'rule_name': data_row.get('rule_name'),
'result_id': result_id,
'result': data_row.get('result'), # PASS or FAIL
'expected_values': data_row.get('expected_values'),
'actual_values': data_row.get('actual_values'),
'report_values': data_row.get('report_values'),
'extended_values': data_row.get('extended_values'),
}
command_run_results_data_list.append(new_command_run_result_entry)
result_id += 1
for item in command_run_results_data_list:
response_run_results = models.TestCaseCommandRunResults.objects.create(**item)
for item in command_run_data_list:
response_run = models.TestCaseCommandRun.objects.create(**item)
```
urls.py
```
router = routers.DefaultRouter()
router.register(r'test_case_command_runs', views.TestCaseCommandRunViewSet)
router.register(r'test_case_command_run_results', views.TestCaseCommandRunResultsViewSet)
urlpatterns = [
url(r'^buildInfo', views.build_info),
url(r'^isActive', views.is_active),
url(r'^dqf_api/', include(router.urls)),
url(r'^dqf_api/ReceiptLog/', views.ReceiptLogView.ReceiptLogViewSet.as_view(), name='ReceiptLog')]
```
Any help is really appreciated.I am new to Django and DRF | 2019/03/18 | [
"https://Stackoverflow.com/questions/55231300",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6885999/"
] | Your serializer's `create` method MUST return an instance of the object it represents. Also, you should not iterate inside the serializer to create instances, that should be done on the view: you iterate through the data, calling the serializer each iteration. | The serializer ReceiptLogSerializerClass MUST be a **ModelSerializer**, not a Serializer |
55,231,300 | I am using Django Rest Framework. I have an existing database (cannot make any changes to it). I have defined a serializer - ReceiptLog with no model, which should create entries in TestCaseCommandRun and TestCaseCommandRunResults when a post() request is made to ReceiptLog api endpoint. Receipt log doesn't exist in the database, I am using it just as an endpoint to accept a combined payload and create entries in underlying tables. Post() to TestCaseCommandRunResults and TestCaseCommandRun works independently, however, when I try to post through ReceiptLog it throws below error
Error Traceback:
```
File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/exception.py" in inner
35. response = get_response(request)
File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/base.py" in _get_response
128. response = self.process_exception_by_middleware(e, request)
File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/base.py" in _get_response
126. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/usr/lib/python3.6/contextlib.py" in inner
52. return func(*args, **kwds)
File "/usr/local/lib/python3.6/dist-packages/django/views/decorators/csrf.py" in wrapped_view
54. return view_func(*args, **kwargs)
File "/usr/local/lib/python3.6/dist-packages/django/views/generic/base.py" in view
69. return self.dispatch(request, *args, **kwargs)
File "/usr/local/lib/python3.6/dist-packages/rest_framework/views.py" in dispatch
495. response = self.handle_exception(exc)
File "/usr/local/lib/python3.6/dist-packages/rest_framework/views.py" in handle_exception
455. self.raise_uncaught_exception(exc)
File "/usr/local/lib/python3.6/dist-packages/rest_framework/views.py" in dispatch
492. response = handler(request, *args, **kwargs)
File "/usr/local/lib/python3.6/dist-packages/rest_framework/generics.py" in post
192. return self.create(request, *args, **kwargs)
File "/usr/local/lib/python3.6/dist-packages/rest_framework/mixins.py" in create
21. self.perform_create(serializer)
File "/usr/local/lib/python3.6/dist-packages/rest_framework/mixins.py" in perform_create
26. serializer.save()
File "/usr/local/lib/python3.6/dist-packages/rest_framework/serializers.py" in save
216. '`create()` did not return an object instance.'
Exception Type: AssertionError at /dqf_api/ReceiptLog/
Exception Value: `create()` did not return an object instance.
```
models.py
```
class TestCaseCommandRun(models.Model):
# fields ..Doesn't have id field as the database doesn't have it
class Meta:
managed = False
db_table = 'test_case_command_run'
unique_together = (('team_name', 'suite_name', 'suite_run_id', 'case_name', 'command_name'),)
class TestCaseCommandRunResults(models.Model):
# fields ..Doesn't have id field as the database doesn't have it
class Meta:
managed = False
db_table = 'test_case_command_run_results'
unique_together = (('suite_run_id', 'command_run_id', 'rule_name', 'result_id'),)
```
views.py
```
class TestCaseCommandRunViewSet(viewsets.ModelViewSet):
queryset = models.TestCaseCommandRunViewSet.objects.values('team_name','suite_name','suite_run_id', 'case_name','command_name','command_run_id','run_start','run_end','result','run_status')
serializer_class = serializers.TestCaseCommandRunViewSet
class TestCaseCommandRunResultsViewSet(viewsets.ModelViewSet):
queryset = models.TestCaseCommandRunResultsViewSet.objects.values('suite_run_id','command_run_id','rule_name', 'result_id',
'result','expected_values','actual_values','report_values','extended_values')
serializer_class = serializers.TestCaseCommandRunResultsViewSet
class ReceiptLogViewSet(CreateAPIView):
serializer_class = serializers.ReceiptLogSerializer.ReceiptLogSerializerClass
```
serializers.py
```
class TestCaseCommandRunResultsViewSet(serializers.ModelSerializer):
class Meta:
model = models.TestCaseCommandRunResultsViewSet
fields = ['suite_run_id','command_run_id','rule_name', 'result_id','result','expected_values','actual_values','report_values','extended_values']
class TestCaseCommandRunSerializer(serializers.ModelSerializer):
class Meta:
model = models.TestCaseCommandRunSerializer
fields = ['team_name','suite_name','suite_run_id', 'case_name','command_name','command_run_id','run_start','run_end','result','run_status']
class ReceiptLogSerializerClass(serializers.Serializer):
team_name = serializers.CharField(max_length=30)
suite_name = serializers.CharField(max_length=100)
suite_run_id = serializers.CharField(max_length=50,required=False, allow_blank=True, default=datetime.now().strftime('%Y%m%d%H%M%S'))
case_name = serializers.CharField(max_length=50)
command_name = serializers.CharField(max_length=50)
command_run_id = serializers.CharField(max_length=50,required=False, allow_blank=True, default='Not Applicable')
run_start = serializers.DateTimeField(default=datetime.now, required=False)
run_end = serializers.DateTimeField(default=datetime.now, required=False)
result = serializers.CharField(max_length=10, default='Not Applicable')
run_status = serializers.CharField(max_length=10)
rule_name = serializers.CharField( max_length=50, required=False, allow_blank=True, default='Not Applicable')
expected_values = serializers.CharField(max_length=200, allow_blank=True)
actual_values = serializers.CharField(max_length=200, allow_blank=True)
report_values = serializers.CharField(max_length=200, allow_blank=True)
extended_values = serializers.CharField(max_length=200, allow_blank=True)
def create(self, validated_data):
# command_run_data_list = []
command_run_results_data_list = []
raw_data_list = []
many = isinstance(validated_data, list)
if many:
raw_data_list = validated_data
else:
raw_data_list.append(validated_data)
result_id = 1
for data_row in raw_data_list:
new_command_run_entry = {
'team_name': data_row.get('team_name'),
'suite_name': data_row.get('suite_name'),
'suite_run_id': data_row.get('suite_run_id'),
'case_name': data_row.get('case_name'),
'command_name': data_row.get('command_name'),
'command_run_id': data_row.get('command_run_id'),
'run_start': data_row.get('run_start'),
'run_end': data_row.get('run_end'),
'result': data_row.get('result'),
'run_status': data_row.get('run_status')
}
command_run_data_list.append(new_command_run_entry)
new_command_run_result_entry = {
'suite_run_id': data_row.get('suite_run_id'),
'command_run_id': data_row.get('command_run_id'),
'rule_name': data_row.get('rule_name'),
'result_id': result_id,
'result': data_row.get('result'), # PASS or FAIL
'expected_values': data_row.get('expected_values'),
'actual_values': data_row.get('actual_values'),
'report_values': data_row.get('report_values'),
'extended_values': data_row.get('extended_values'),
}
command_run_results_data_list.append(new_command_run_result_entry)
result_id += 1
for item in command_run_results_data_list:
response_run_results = models.TestCaseCommandRunResults.objects.create(**item)
for item in command_run_data_list:
response_run = models.TestCaseCommandRun.objects.create(**item)
```
urls.py
```
router = routers.DefaultRouter()
router.register(r'test_case_command_runs', views.TestCaseCommandRunViewSet)
router.register(r'test_case_command_run_results', views.TestCaseCommandRunResultsViewSet)
urlpatterns = [
url(r'^buildInfo', views.build_info),
url(r'^isActive', views.is_active),
url(r'^dqf_api/', include(router.urls)),
url(r'^dqf_api/ReceiptLog/', views.ReceiptLogView.ReceiptLogViewSet.as_view(), name='ReceiptLog')]
```
Any help is really appreciated.I am new to Django and DRF | 2019/03/18 | [
"https://Stackoverflow.com/questions/55231300",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6885999/"
] | Your serializer's `create` method MUST return an instance of the object it represents. Also, you should not iterate inside the serializer to create instances, that should be done on the view: you iterate through the data, calling the serializer each iteration. | if you written your own model manager for default user model then there are chances of your method not returning the user instance which should be return.
for example:
```
class CustomUserManager(BaseUserManager):
def _create_user(self, email, password=None, **extra_kwargs):
if not email:
raise ValueError("email should be present")
user = self.model(email=email, **extra_kwargs)
user.set_password(password)
user.save(using=self._db)
return user
def create_user(self, email, password=None, **extra_kwargs):
extra_kwargs.setdefault('is_staff', False)
extra_kwargs.setdefault('is_superuser', False)
#self._create_user(email, password, **extra_kwargs) if this method not returning user instance upon creation this will cause problem `create()` did not return an object instance
return self._create_user(email, password, **extra_kwargs)
def create_superuser(self, email, password=None, **extra_kwargs):
extra_kwargs.setdefault('is_staff', True)
extra_kwargs.setdefault('is_superuser', True)
#self._create_user(email, password, **extra_kwargs) if this method not returning user instance upon creation this will cause problem `create()` did not return an object instance
return self._create_user(email, password, **extra_kwargs)
``` |
55,231,300 | I am using Django Rest Framework. I have an existing database (cannot make any changes to it). I have defined a serializer - ReceiptLog with no model, which should create entries in TestCaseCommandRun and TestCaseCommandRunResults when a post() request is made to ReceiptLog api endpoint. Receipt log doesn't exist in the database, I am using it just as an endpoint to accept a combined payload and create entries in underlying tables. Post() to TestCaseCommandRunResults and TestCaseCommandRun works independently, however, when I try to post through ReceiptLog it throws below error
Error Traceback:
```
File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/exception.py" in inner
35. response = get_response(request)
File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/base.py" in _get_response
128. response = self.process_exception_by_middleware(e, request)
File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/base.py" in _get_response
126. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/usr/lib/python3.6/contextlib.py" in inner
52. return func(*args, **kwds)
File "/usr/local/lib/python3.6/dist-packages/django/views/decorators/csrf.py" in wrapped_view
54. return view_func(*args, **kwargs)
File "/usr/local/lib/python3.6/dist-packages/django/views/generic/base.py" in view
69. return self.dispatch(request, *args, **kwargs)
File "/usr/local/lib/python3.6/dist-packages/rest_framework/views.py" in dispatch
495. response = self.handle_exception(exc)
File "/usr/local/lib/python3.6/dist-packages/rest_framework/views.py" in handle_exception
455. self.raise_uncaught_exception(exc)
File "/usr/local/lib/python3.6/dist-packages/rest_framework/views.py" in dispatch
492. response = handler(request, *args, **kwargs)
File "/usr/local/lib/python3.6/dist-packages/rest_framework/generics.py" in post
192. return self.create(request, *args, **kwargs)
File "/usr/local/lib/python3.6/dist-packages/rest_framework/mixins.py" in create
21. self.perform_create(serializer)
File "/usr/local/lib/python3.6/dist-packages/rest_framework/mixins.py" in perform_create
26. serializer.save()
File "/usr/local/lib/python3.6/dist-packages/rest_framework/serializers.py" in save
216. '`create()` did not return an object instance.'
Exception Type: AssertionError at /dqf_api/ReceiptLog/
Exception Value: `create()` did not return an object instance.
```
models.py
```
class TestCaseCommandRun(models.Model):
# fields ..Doesn't have id field as the database doesn't have it
class Meta:
managed = False
db_table = 'test_case_command_run'
unique_together = (('team_name', 'suite_name', 'suite_run_id', 'case_name', 'command_name'),)
class TestCaseCommandRunResults(models.Model):
# fields ..Doesn't have id field as the database doesn't have it
class Meta:
managed = False
db_table = 'test_case_command_run_results'
unique_together = (('suite_run_id', 'command_run_id', 'rule_name', 'result_id'),)
```
views.py
```
class TestCaseCommandRunViewSet(viewsets.ModelViewSet):
queryset = models.TestCaseCommandRunViewSet.objects.values('team_name','suite_name','suite_run_id', 'case_name','command_name','command_run_id','run_start','run_end','result','run_status')
serializer_class = serializers.TestCaseCommandRunViewSet
class TestCaseCommandRunResultsViewSet(viewsets.ModelViewSet):
queryset = models.TestCaseCommandRunResultsViewSet.objects.values('suite_run_id','command_run_id','rule_name', 'result_id',
'result','expected_values','actual_values','report_values','extended_values')
serializer_class = serializers.TestCaseCommandRunResultsViewSet
class ReceiptLogViewSet(CreateAPIView):
serializer_class = serializers.ReceiptLogSerializer.ReceiptLogSerializerClass
```
serializers.py
```
class TestCaseCommandRunResultsViewSet(serializers.ModelSerializer):
class Meta:
model = models.TestCaseCommandRunResultsViewSet
fields = ['suite_run_id','command_run_id','rule_name', 'result_id','result','expected_values','actual_values','report_values','extended_values']
class TestCaseCommandRunSerializer(serializers.ModelSerializer):
class Meta:
model = models.TestCaseCommandRunSerializer
fields = ['team_name','suite_name','suite_run_id', 'case_name','command_name','command_run_id','run_start','run_end','result','run_status']
class ReceiptLogSerializerClass(serializers.Serializer):
team_name = serializers.CharField(max_length=30)
suite_name = serializers.CharField(max_length=100)
suite_run_id = serializers.CharField(max_length=50,required=False, allow_blank=True, default=datetime.now().strftime('%Y%m%d%H%M%S'))
case_name = serializers.CharField(max_length=50)
command_name = serializers.CharField(max_length=50)
command_run_id = serializers.CharField(max_length=50,required=False, allow_blank=True, default='Not Applicable')
run_start = serializers.DateTimeField(default=datetime.now, required=False)
run_end = serializers.DateTimeField(default=datetime.now, required=False)
result = serializers.CharField(max_length=10, default='Not Applicable')
run_status = serializers.CharField(max_length=10)
rule_name = serializers.CharField( max_length=50, required=False, allow_blank=True, default='Not Applicable')
expected_values = serializers.CharField(max_length=200, allow_blank=True)
actual_values = serializers.CharField(max_length=200, allow_blank=True)
report_values = serializers.CharField(max_length=200, allow_blank=True)
extended_values = serializers.CharField(max_length=200, allow_blank=True)
def create(self, validated_data):
# command_run_data_list = []
command_run_results_data_list = []
raw_data_list = []
many = isinstance(validated_data, list)
if many:
raw_data_list = validated_data
else:
raw_data_list.append(validated_data)
result_id = 1
for data_row in raw_data_list:
new_command_run_entry = {
'team_name': data_row.get('team_name'),
'suite_name': data_row.get('suite_name'),
'suite_run_id': data_row.get('suite_run_id'),
'case_name': data_row.get('case_name'),
'command_name': data_row.get('command_name'),
'command_run_id': data_row.get('command_run_id'),
'run_start': data_row.get('run_start'),
'run_end': data_row.get('run_end'),
'result': data_row.get('result'),
'run_status': data_row.get('run_status')
}
command_run_data_list.append(new_command_run_entry)
new_command_run_result_entry = {
'suite_run_id': data_row.get('suite_run_id'),
'command_run_id': data_row.get('command_run_id'),
'rule_name': data_row.get('rule_name'),
'result_id': result_id,
'result': data_row.get('result'), # PASS or FAIL
'expected_values': data_row.get('expected_values'),
'actual_values': data_row.get('actual_values'),
'report_values': data_row.get('report_values'),
'extended_values': data_row.get('extended_values'),
}
command_run_results_data_list.append(new_command_run_result_entry)
result_id += 1
for item in command_run_results_data_list:
response_run_results = models.TestCaseCommandRunResults.objects.create(**item)
for item in command_run_data_list:
response_run = models.TestCaseCommandRun.objects.create(**item)
```
urls.py
```
router = routers.DefaultRouter()
router.register(r'test_case_command_runs', views.TestCaseCommandRunViewSet)
router.register(r'test_case_command_run_results', views.TestCaseCommandRunResultsViewSet)
urlpatterns = [
url(r'^buildInfo', views.build_info),
url(r'^isActive', views.is_active),
url(r'^dqf_api/', include(router.urls)),
url(r'^dqf_api/ReceiptLog/', views.ReceiptLogView.ReceiptLogViewSet.as_view(), name='ReceiptLog')]
```
Any help is really appreciated.I am new to Django and DRF | 2019/03/18 | [
"https://Stackoverflow.com/questions/55231300",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6885999/"
] | Updated the serializers.py file to include the below code
```
class ReceiptLogSerializerClass(serializers.Serializer):
#Fields
def create(self, validated_data):
raw_data_list = []
many = isinstance(validated_data, list)
if many:
raw_data_list = validated_data
else:
raw_data_list.append(validated_data)
result_id = 1
for data_row in raw_data_list:
new_command_run_entry = {
'team_name': data_row.get('team_name'),
'suite_name': data_row.get('suite_name'),
'suite_run_id': data_row.get('suite_run_id'),
'case_name': data_row.get('case_name'),
'command_name': data_row.get('command_name'),
'command_run_id': data_row.get('command_run_id'),
'run_start': data_row.get('run_start'),
'run_end': data_row.get('run_end'),
'result': data_row.get('result'),
'run_status': data_row.get('run_status')
}
response = TestCaseCommandRunSerializer.create(TestCaseCommandRunSerializer(),validated_data= new_command_run_entry)
new_command_run_result_entry = {
'suite_run_id': data_row.get('suite_run_id'),
'command_run_id': data_row.get('command_run_id'),
'rule_name': data_row.get('rule_name'),
'result_id': result_id,
'result': data_row.get('result'), # PASS or FAIL
'expected_values': data_row.get('expected_values'),
'actual_values': data_row.get('actual_values'),
'report_values': data_row.get('report_values'),
'extended_values': data_row.get('extended_values'),
}
response = TestCaseCommandRunResultsSerializer.create(TestCaseCommandRunResultsSerializer(),validated_data= new_command_run_result_entry)
logger.info(" new_command_run_result_entry response %s" % response)
result_id += 1
return validated_data
```
I was not de-serializing the data correctly and hence ran into multiple issues.
return validated\_data
rectified all the errors and now I am able to post() data to multiple models through single API.
For posting a multiple payloads in a single API Call added below lines in ReceiptLogViewSet
```
def get_serializer(self, *args, **kwargs):
if "data" in kwargs:
data = kwargs["data"]
if isinstance(data, list):
kwargs["many"] = True
return super(ReceiptLogViewSet, self).get_serializer(*args, **kwargs)
```
Ref: [Django rest framework cannot deal with multple objects in model viewset](https://stackoverflow.com/questions/43525860/django-rest-framework-cannot-deal-with-multple-objects-in-model-viewset) | The serializer ReceiptLogSerializerClass MUST be a **ModelSerializer**, not a Serializer |
55,231,300 | I am using Django Rest Framework. I have an existing database (cannot make any changes to it). I have defined a serializer - ReceiptLog with no model, which should create entries in TestCaseCommandRun and TestCaseCommandRunResults when a post() request is made to ReceiptLog api endpoint. Receipt log doesn't exist in the database, I am using it just as an endpoint to accept a combined payload and create entries in underlying tables. Post() to TestCaseCommandRunResults and TestCaseCommandRun works independently, however, when I try to post through ReceiptLog it throws below error
Error Traceback:
```
File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/exception.py" in inner
35. response = get_response(request)
File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/base.py" in _get_response
128. response = self.process_exception_by_middleware(e, request)
File "/usr/local/lib/python3.6/dist-packages/django/core/handlers/base.py" in _get_response
126. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/usr/lib/python3.6/contextlib.py" in inner
52. return func(*args, **kwds)
File "/usr/local/lib/python3.6/dist-packages/django/views/decorators/csrf.py" in wrapped_view
54. return view_func(*args, **kwargs)
File "/usr/local/lib/python3.6/dist-packages/django/views/generic/base.py" in view
69. return self.dispatch(request, *args, **kwargs)
File "/usr/local/lib/python3.6/dist-packages/rest_framework/views.py" in dispatch
495. response = self.handle_exception(exc)
File "/usr/local/lib/python3.6/dist-packages/rest_framework/views.py" in handle_exception
455. self.raise_uncaught_exception(exc)
File "/usr/local/lib/python3.6/dist-packages/rest_framework/views.py" in dispatch
492. response = handler(request, *args, **kwargs)
File "/usr/local/lib/python3.6/dist-packages/rest_framework/generics.py" in post
192. return self.create(request, *args, **kwargs)
File "/usr/local/lib/python3.6/dist-packages/rest_framework/mixins.py" in create
21. self.perform_create(serializer)
File "/usr/local/lib/python3.6/dist-packages/rest_framework/mixins.py" in perform_create
26. serializer.save()
File "/usr/local/lib/python3.6/dist-packages/rest_framework/serializers.py" in save
216. '`create()` did not return an object instance.'
Exception Type: AssertionError at /dqf_api/ReceiptLog/
Exception Value: `create()` did not return an object instance.
```
models.py
```
class TestCaseCommandRun(models.Model):
# fields ..Doesn't have id field as the database doesn't have it
class Meta:
managed = False
db_table = 'test_case_command_run'
unique_together = (('team_name', 'suite_name', 'suite_run_id', 'case_name', 'command_name'),)
class TestCaseCommandRunResults(models.Model):
# fields ..Doesn't have id field as the database doesn't have it
class Meta:
managed = False
db_table = 'test_case_command_run_results'
unique_together = (('suite_run_id', 'command_run_id', 'rule_name', 'result_id'),)
```
views.py
```
class TestCaseCommandRunViewSet(viewsets.ModelViewSet):
queryset = models.TestCaseCommandRunViewSet.objects.values('team_name','suite_name','suite_run_id', 'case_name','command_name','command_run_id','run_start','run_end','result','run_status')
serializer_class = serializers.TestCaseCommandRunViewSet
class TestCaseCommandRunResultsViewSet(viewsets.ModelViewSet):
queryset = models.TestCaseCommandRunResultsViewSet.objects.values('suite_run_id','command_run_id','rule_name', 'result_id',
'result','expected_values','actual_values','report_values','extended_values')
serializer_class = serializers.TestCaseCommandRunResultsViewSet
class ReceiptLogViewSet(CreateAPIView):
serializer_class = serializers.ReceiptLogSerializer.ReceiptLogSerializerClass
```
serializers.py
```
class TestCaseCommandRunResultsViewSet(serializers.ModelSerializer):
class Meta:
model = models.TestCaseCommandRunResultsViewSet
fields = ['suite_run_id','command_run_id','rule_name', 'result_id','result','expected_values','actual_values','report_values','extended_values']
class TestCaseCommandRunSerializer(serializers.ModelSerializer):
class Meta:
model = models.TestCaseCommandRunSerializer
fields = ['team_name','suite_name','suite_run_id', 'case_name','command_name','command_run_id','run_start','run_end','result','run_status']
class ReceiptLogSerializerClass(serializers.Serializer):
team_name = serializers.CharField(max_length=30)
suite_name = serializers.CharField(max_length=100)
suite_run_id = serializers.CharField(max_length=50,required=False, allow_blank=True, default=datetime.now().strftime('%Y%m%d%H%M%S'))
case_name = serializers.CharField(max_length=50)
command_name = serializers.CharField(max_length=50)
command_run_id = serializers.CharField(max_length=50,required=False, allow_blank=True, default='Not Applicable')
run_start = serializers.DateTimeField(default=datetime.now, required=False)
run_end = serializers.DateTimeField(default=datetime.now, required=False)
result = serializers.CharField(max_length=10, default='Not Applicable')
run_status = serializers.CharField(max_length=10)
rule_name = serializers.CharField( max_length=50, required=False, allow_blank=True, default='Not Applicable')
expected_values = serializers.CharField(max_length=200, allow_blank=True)
actual_values = serializers.CharField(max_length=200, allow_blank=True)
report_values = serializers.CharField(max_length=200, allow_blank=True)
extended_values = serializers.CharField(max_length=200, allow_blank=True)
def create(self, validated_data):
# command_run_data_list = []
command_run_results_data_list = []
raw_data_list = []
many = isinstance(validated_data, list)
if many:
raw_data_list = validated_data
else:
raw_data_list.append(validated_data)
result_id = 1
for data_row in raw_data_list:
new_command_run_entry = {
'team_name': data_row.get('team_name'),
'suite_name': data_row.get('suite_name'),
'suite_run_id': data_row.get('suite_run_id'),
'case_name': data_row.get('case_name'),
'command_name': data_row.get('command_name'),
'command_run_id': data_row.get('command_run_id'),
'run_start': data_row.get('run_start'),
'run_end': data_row.get('run_end'),
'result': data_row.get('result'),
'run_status': data_row.get('run_status')
}
command_run_data_list.append(new_command_run_entry)
new_command_run_result_entry = {
'suite_run_id': data_row.get('suite_run_id'),
'command_run_id': data_row.get('command_run_id'),
'rule_name': data_row.get('rule_name'),
'result_id': result_id,
'result': data_row.get('result'), # PASS or FAIL
'expected_values': data_row.get('expected_values'),
'actual_values': data_row.get('actual_values'),
'report_values': data_row.get('report_values'),
'extended_values': data_row.get('extended_values'),
}
command_run_results_data_list.append(new_command_run_result_entry)
result_id += 1
for item in command_run_results_data_list:
response_run_results = models.TestCaseCommandRunResults.objects.create(**item)
for item in command_run_data_list:
response_run = models.TestCaseCommandRun.objects.create(**item)
```
urls.py
```
router = routers.DefaultRouter()
router.register(r'test_case_command_runs', views.TestCaseCommandRunViewSet)
router.register(r'test_case_command_run_results', views.TestCaseCommandRunResultsViewSet)
urlpatterns = [
url(r'^buildInfo', views.build_info),
url(r'^isActive', views.is_active),
url(r'^dqf_api/', include(router.urls)),
url(r'^dqf_api/ReceiptLog/', views.ReceiptLogView.ReceiptLogViewSet.as_view(), name='ReceiptLog')]
```
Any help is really appreciated.I am new to Django and DRF | 2019/03/18 | [
"https://Stackoverflow.com/questions/55231300",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6885999/"
] | Updated the serializers.py file to include the below code
```
class ReceiptLogSerializerClass(serializers.Serializer):
#Fields
def create(self, validated_data):
raw_data_list = []
many = isinstance(validated_data, list)
if many:
raw_data_list = validated_data
else:
raw_data_list.append(validated_data)
result_id = 1
for data_row in raw_data_list:
new_command_run_entry = {
'team_name': data_row.get('team_name'),
'suite_name': data_row.get('suite_name'),
'suite_run_id': data_row.get('suite_run_id'),
'case_name': data_row.get('case_name'),
'command_name': data_row.get('command_name'),
'command_run_id': data_row.get('command_run_id'),
'run_start': data_row.get('run_start'),
'run_end': data_row.get('run_end'),
'result': data_row.get('result'),
'run_status': data_row.get('run_status')
}
response = TestCaseCommandRunSerializer.create(TestCaseCommandRunSerializer(),validated_data= new_command_run_entry)
new_command_run_result_entry = {
'suite_run_id': data_row.get('suite_run_id'),
'command_run_id': data_row.get('command_run_id'),
'rule_name': data_row.get('rule_name'),
'result_id': result_id,
'result': data_row.get('result'), # PASS or FAIL
'expected_values': data_row.get('expected_values'),
'actual_values': data_row.get('actual_values'),
'report_values': data_row.get('report_values'),
'extended_values': data_row.get('extended_values'),
}
response = TestCaseCommandRunResultsSerializer.create(TestCaseCommandRunResultsSerializer(),validated_data= new_command_run_result_entry)
logger.info(" new_command_run_result_entry response %s" % response)
result_id += 1
return validated_data
```
I was not de-serializing the data correctly and hence ran into multiple issues.
return validated\_data
rectified all the errors and now I am able to post() data to multiple models through single API.
For posting a multiple payloads in a single API Call added below lines in ReceiptLogViewSet
```
def get_serializer(self, *args, **kwargs):
if "data" in kwargs:
data = kwargs["data"]
if isinstance(data, list):
kwargs["many"] = True
return super(ReceiptLogViewSet, self).get_serializer(*args, **kwargs)
```
Ref: [Django rest framework cannot deal with multple objects in model viewset](https://stackoverflow.com/questions/43525860/django-rest-framework-cannot-deal-with-multple-objects-in-model-viewset) | if you written your own model manager for default user model then there are chances of your method not returning the user instance which should be return.
for example:
```
class CustomUserManager(BaseUserManager):
def _create_user(self, email, password=None, **extra_kwargs):
if not email:
raise ValueError("email should be present")
user = self.model(email=email, **extra_kwargs)
user.set_password(password)
user.save(using=self._db)
return user
def create_user(self, email, password=None, **extra_kwargs):
extra_kwargs.setdefault('is_staff', False)
extra_kwargs.setdefault('is_superuser', False)
#self._create_user(email, password, **extra_kwargs) if this method not returning user instance upon creation this will cause problem `create()` did not return an object instance
return self._create_user(email, password, **extra_kwargs)
def create_superuser(self, email, password=None, **extra_kwargs):
extra_kwargs.setdefault('is_staff', True)
extra_kwargs.setdefault('is_superuser', True)
#self._create_user(email, password, **extra_kwargs) if this method not returning user instance upon creation this will cause problem `create()` did not return an object instance
return self._create_user(email, password, **extra_kwargs)
``` |
55,052,811 | I've got this basic python3 server but can't figure out how to serve a directory.
```
class SimpleHTTPRequestHandler(BaseHTTPRequestHandler):
def do_GET(self):
print(self.path)
if self.path == '/up':
self.send_response(200)
self.end_headers()
self.wfile.write(b'Going Up')
if self.path == '/down':
self.send_response(200)
self.end_headers()
self.wfile.write(B'Going Down')
httpd = socketserver.TCPServer(("", PORT), SimpleHTTPRequestHandler)
print("Server started on ", PORT)
httpd.serve_forever()
```
If Instead of the custom class above, I simply pass `Handler = http.server.SimpleHTTPRequestHandler` into TCPServer():, the default functionality is to serve a directory, but I want to serve that directory and have functionality on my two GETs above.
As an example, if someone were to go to localhost:8080/index.html, I'd want that file to be served to them | 2019/03/07 | [
"https://Stackoverflow.com/questions/55052811",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1240649/"
] | if you are using 3.7, you can simply serve up a directory where your html files, eg. index.html is still
```
python -m http.server 8080 --bind 127.0.0.1 --directory /path/to/dir
```
for the [docs](https://docs.python.org/3/library/http.server.html) | The simple way
--------------
You want to *extend* the functionality of `SimpleHTTPRequestHandler`, so you **subclass** it! Check for your special condition(s), if none of them apply, call `super().do_GET()` and let it do the rest.
Example:
```
class MyHandler(http.server.SimpleHTTPRequestHandler):
def do_GET(self):
if self.path == '/up':
self.send_response(200)
self.end_headers()
self.wfile.write(b'up')
else:
super().do_GET()
```
The long way
------------
To serve files, you basically just have to open them, read the contents and send it.
To serve directories (indexes), use `os.listdir()`. (If you want, you can when receiving directories first check for an index.html and then, if that fails, serve an index listing).
Putting this into your code will give you:
```
class MyHandler(http.server.BaseHTTPRequestHandler):
def do_GET(self):
print(self.path)
if self.path == '/up':
self.send_response(200)
self.end_headers()
self.wfile.write(b'Going up')
elif os.path.isdir(self.path):
try:
self.send_response(200)
self.end_headers()
self.wfile.write(str(os.listdir(self.path)).encode())
except Exception:
self.send_response(500)
self.end_headers()
self.wfile.write(b'error')
else:
try:
with open(self.path, 'rb') as f:
data = f.read()
self.send_response(200)
self.end_headers()
self.wfile.write(data)
except FileNotFoundError:
self.send_response(404)
self.end_headers()
self.wfile.write(b'not found')
except PermissionError:
self.send_response(403)
self.end_headers()
self.wfile.write(b'no permission')
except Exception:
self.send_response(500)
self.end_headers()
self.wfile.write(b'error')
```
This example has a lot of error handling. You might want to move it somewhere else.
The problem is **this serves from *your root* directory**. To stop this, you'll have to (easy way) just add the serving directory to the beginning of `self.path`. Also check if `..` cause you to land higher than you want. A way to do this is `os.path.abspath(serve_from+self.path).startswith(serve_from)`
Putting this inside (after the check for /up):
```
class MyHandler(http.server.BaseHTTPRequestHandler):
def do_GET(self):
print(self.path)
path = serve_from + self.path
if self.path == '/up':
self.send_response(200)
self.end_headers()
self.wfile.write(b'Going up')
elif not os.path.abspath(path).startswith(serve_from):
self.send_response(403)
self.end_headers()
self.wfile.write(b'Private!')
elif os.path.isdir(path):
try:
self.send_response(200)
self.end_headers()
self.wfile.write(str(os.listdir(path)).encode())
except Exception:
self.send_response(500)
self.end_headers()
self.wfile.write(b'error')
else:
try:
with open(path, 'rb') as f:
data = f.read()
self.send_response(200)
self.end_headers()
self.wfile.write(data)
# error handling skipped
except Exception:
self.send_response(500)
self.end_headers()
self.wfile.write(b'error')
```
Note you define `path` and use it subsequently, otherwise you will still serve from / |
55,052,811 | I've got this basic python3 server but can't figure out how to serve a directory.
```
class SimpleHTTPRequestHandler(BaseHTTPRequestHandler):
def do_GET(self):
print(self.path)
if self.path == '/up':
self.send_response(200)
self.end_headers()
self.wfile.write(b'Going Up')
if self.path == '/down':
self.send_response(200)
self.end_headers()
self.wfile.write(B'Going Down')
httpd = socketserver.TCPServer(("", PORT), SimpleHTTPRequestHandler)
print("Server started on ", PORT)
httpd.serve_forever()
```
If Instead of the custom class above, I simply pass `Handler = http.server.SimpleHTTPRequestHandler` into TCPServer():, the default functionality is to serve a directory, but I want to serve that directory and have functionality on my two GETs above.
As an example, if someone were to go to localhost:8080/index.html, I'd want that file to be served to them | 2019/03/07 | [
"https://Stackoverflow.com/questions/55052811",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1240649/"
] | if you are using 3.7, you can simply serve up a directory where your html files, eg. index.html is still
```
python -m http.server 8080 --bind 127.0.0.1 --directory /path/to/dir
```
for the [docs](https://docs.python.org/3/library/http.server.html) | @user24343's [answer](https://stackoverflow.com/a/55053562/771768) to subclass `SimpleHTTPRequestHandler` is really helpful! One detail I couldn't figure out was how to customize the `directory=` constructor arg when I pass `MyHandler` into `HTTPServer`. Use any of [these answers](https://stackoverflow.com/a/71399394/771768), i.e.
```py
HTTPServer(('', 8001), lambda *_: MyHandler(*_, directory=sys.path[0]))
``` |
55,052,811 | I've got this basic python3 server but can't figure out how to serve a directory.
```
class SimpleHTTPRequestHandler(BaseHTTPRequestHandler):
def do_GET(self):
print(self.path)
if self.path == '/up':
self.send_response(200)
self.end_headers()
self.wfile.write(b'Going Up')
if self.path == '/down':
self.send_response(200)
self.end_headers()
self.wfile.write(B'Going Down')
httpd = socketserver.TCPServer(("", PORT), SimpleHTTPRequestHandler)
print("Server started on ", PORT)
httpd.serve_forever()
```
If Instead of the custom class above, I simply pass `Handler = http.server.SimpleHTTPRequestHandler` into TCPServer():, the default functionality is to serve a directory, but I want to serve that directory and have functionality on my two GETs above.
As an example, if someone were to go to localhost:8080/index.html, I'd want that file to be served to them | 2019/03/07 | [
"https://Stackoverflow.com/questions/55052811",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1240649/"
] | if you are using 3.7, you can simply serve up a directory where your html files, eg. index.html is still
```
python -m http.server 8080 --bind 127.0.0.1 --directory /path/to/dir
```
for the [docs](https://docs.python.org/3/library/http.server.html) | With python3, you can serve the current directory by simply running:
`python3 -m http.server 8080`
Of course you can configure many parameters as per the [documentation](https://docs.python.org/3/library/http.server.html). |
55,052,811 | I've got this basic python3 server but can't figure out how to serve a directory.
```
class SimpleHTTPRequestHandler(BaseHTTPRequestHandler):
def do_GET(self):
print(self.path)
if self.path == '/up':
self.send_response(200)
self.end_headers()
self.wfile.write(b'Going Up')
if self.path == '/down':
self.send_response(200)
self.end_headers()
self.wfile.write(B'Going Down')
httpd = socketserver.TCPServer(("", PORT), SimpleHTTPRequestHandler)
print("Server started on ", PORT)
httpd.serve_forever()
```
If Instead of the custom class above, I simply pass `Handler = http.server.SimpleHTTPRequestHandler` into TCPServer():, the default functionality is to serve a directory, but I want to serve that directory and have functionality on my two GETs above.
As an example, if someone were to go to localhost:8080/index.html, I'd want that file to be served to them | 2019/03/07 | [
"https://Stackoverflow.com/questions/55052811",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1240649/"
] | The simple way
--------------
You want to *extend* the functionality of `SimpleHTTPRequestHandler`, so you **subclass** it! Check for your special condition(s), if none of them apply, call `super().do_GET()` and let it do the rest.
Example:
```
class MyHandler(http.server.SimpleHTTPRequestHandler):
def do_GET(self):
if self.path == '/up':
self.send_response(200)
self.end_headers()
self.wfile.write(b'up')
else:
super().do_GET()
```
The long way
------------
To serve files, you basically just have to open them, read the contents and send it.
To serve directories (indexes), use `os.listdir()`. (If you want, you can when receiving directories first check for an index.html and then, if that fails, serve an index listing).
Putting this into your code will give you:
```
class MyHandler(http.server.BaseHTTPRequestHandler):
def do_GET(self):
print(self.path)
if self.path == '/up':
self.send_response(200)
self.end_headers()
self.wfile.write(b'Going up')
elif os.path.isdir(self.path):
try:
self.send_response(200)
self.end_headers()
self.wfile.write(str(os.listdir(self.path)).encode())
except Exception:
self.send_response(500)
self.end_headers()
self.wfile.write(b'error')
else:
try:
with open(self.path, 'rb') as f:
data = f.read()
self.send_response(200)
self.end_headers()
self.wfile.write(data)
except FileNotFoundError:
self.send_response(404)
self.end_headers()
self.wfile.write(b'not found')
except PermissionError:
self.send_response(403)
self.end_headers()
self.wfile.write(b'no permission')
except Exception:
self.send_response(500)
self.end_headers()
self.wfile.write(b'error')
```
This example has a lot of error handling. You might want to move it somewhere else.
The problem is **this serves from *your root* directory**. To stop this, you'll have to (easy way) just add the serving directory to the beginning of `self.path`. Also check if `..` cause you to land higher than you want. A way to do this is `os.path.abspath(serve_from+self.path).startswith(serve_from)`
Putting this inside (after the check for /up):
```
class MyHandler(http.server.BaseHTTPRequestHandler):
def do_GET(self):
print(self.path)
path = serve_from + self.path
if self.path == '/up':
self.send_response(200)
self.end_headers()
self.wfile.write(b'Going up')
elif not os.path.abspath(path).startswith(serve_from):
self.send_response(403)
self.end_headers()
self.wfile.write(b'Private!')
elif os.path.isdir(path):
try:
self.send_response(200)
self.end_headers()
self.wfile.write(str(os.listdir(path)).encode())
except Exception:
self.send_response(500)
self.end_headers()
self.wfile.write(b'error')
else:
try:
with open(path, 'rb') as f:
data = f.read()
self.send_response(200)
self.end_headers()
self.wfile.write(data)
# error handling skipped
except Exception:
self.send_response(500)
self.end_headers()
self.wfile.write(b'error')
```
Note you define `path` and use it subsequently, otherwise you will still serve from / | @user24343's [answer](https://stackoverflow.com/a/55053562/771768) to subclass `SimpleHTTPRequestHandler` is really helpful! One detail I couldn't figure out was how to customize the `directory=` constructor arg when I pass `MyHandler` into `HTTPServer`. Use any of [these answers](https://stackoverflow.com/a/71399394/771768), i.e.
```py
HTTPServer(('', 8001), lambda *_: MyHandler(*_, directory=sys.path[0]))
``` |
55,052,811 | I've got this basic python3 server but can't figure out how to serve a directory.
```
class SimpleHTTPRequestHandler(BaseHTTPRequestHandler):
def do_GET(self):
print(self.path)
if self.path == '/up':
self.send_response(200)
self.end_headers()
self.wfile.write(b'Going Up')
if self.path == '/down':
self.send_response(200)
self.end_headers()
self.wfile.write(B'Going Down')
httpd = socketserver.TCPServer(("", PORT), SimpleHTTPRequestHandler)
print("Server started on ", PORT)
httpd.serve_forever()
```
If Instead of the custom class above, I simply pass `Handler = http.server.SimpleHTTPRequestHandler` into TCPServer():, the default functionality is to serve a directory, but I want to serve that directory and have functionality on my two GETs above.
As an example, if someone were to go to localhost:8080/index.html, I'd want that file to be served to them | 2019/03/07 | [
"https://Stackoverflow.com/questions/55052811",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1240649/"
] | The simple way
--------------
You want to *extend* the functionality of `SimpleHTTPRequestHandler`, so you **subclass** it! Check for your special condition(s), if none of them apply, call `super().do_GET()` and let it do the rest.
Example:
```
class MyHandler(http.server.SimpleHTTPRequestHandler):
def do_GET(self):
if self.path == '/up':
self.send_response(200)
self.end_headers()
self.wfile.write(b'up')
else:
super().do_GET()
```
The long way
------------
To serve files, you basically just have to open them, read the contents and send it.
To serve directories (indexes), use `os.listdir()`. (If you want, you can when receiving directories first check for an index.html and then, if that fails, serve an index listing).
Putting this into your code will give you:
```
class MyHandler(http.server.BaseHTTPRequestHandler):
def do_GET(self):
print(self.path)
if self.path == '/up':
self.send_response(200)
self.end_headers()
self.wfile.write(b'Going up')
elif os.path.isdir(self.path):
try:
self.send_response(200)
self.end_headers()
self.wfile.write(str(os.listdir(self.path)).encode())
except Exception:
self.send_response(500)
self.end_headers()
self.wfile.write(b'error')
else:
try:
with open(self.path, 'rb') as f:
data = f.read()
self.send_response(200)
self.end_headers()
self.wfile.write(data)
except FileNotFoundError:
self.send_response(404)
self.end_headers()
self.wfile.write(b'not found')
except PermissionError:
self.send_response(403)
self.end_headers()
self.wfile.write(b'no permission')
except Exception:
self.send_response(500)
self.end_headers()
self.wfile.write(b'error')
```
This example has a lot of error handling. You might want to move it somewhere else.
The problem is **this serves from *your root* directory**. To stop this, you'll have to (easy way) just add the serving directory to the beginning of `self.path`. Also check if `..` cause you to land higher than you want. A way to do this is `os.path.abspath(serve_from+self.path).startswith(serve_from)`
Putting this inside (after the check for /up):
```
class MyHandler(http.server.BaseHTTPRequestHandler):
def do_GET(self):
print(self.path)
path = serve_from + self.path
if self.path == '/up':
self.send_response(200)
self.end_headers()
self.wfile.write(b'Going up')
elif not os.path.abspath(path).startswith(serve_from):
self.send_response(403)
self.end_headers()
self.wfile.write(b'Private!')
elif os.path.isdir(path):
try:
self.send_response(200)
self.end_headers()
self.wfile.write(str(os.listdir(path)).encode())
except Exception:
self.send_response(500)
self.end_headers()
self.wfile.write(b'error')
else:
try:
with open(path, 'rb') as f:
data = f.read()
self.send_response(200)
self.end_headers()
self.wfile.write(data)
# error handling skipped
except Exception:
self.send_response(500)
self.end_headers()
self.wfile.write(b'error')
```
Note you define `path` and use it subsequently, otherwise you will still serve from / | With python3, you can serve the current directory by simply running:
`python3 -m http.server 8080`
Of course you can configure many parameters as per the [documentation](https://docs.python.org/3/library/http.server.html). |
55,052,811 | I've got this basic python3 server but can't figure out how to serve a directory.
```
class SimpleHTTPRequestHandler(BaseHTTPRequestHandler):
def do_GET(self):
print(self.path)
if self.path == '/up':
self.send_response(200)
self.end_headers()
self.wfile.write(b'Going Up')
if self.path == '/down':
self.send_response(200)
self.end_headers()
self.wfile.write(B'Going Down')
httpd = socketserver.TCPServer(("", PORT), SimpleHTTPRequestHandler)
print("Server started on ", PORT)
httpd.serve_forever()
```
If Instead of the custom class above, I simply pass `Handler = http.server.SimpleHTTPRequestHandler` into TCPServer():, the default functionality is to serve a directory, but I want to serve that directory and have functionality on my two GETs above.
As an example, if someone were to go to localhost:8080/index.html, I'd want that file to be served to them | 2019/03/07 | [
"https://Stackoverflow.com/questions/55052811",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1240649/"
] | @user24343's [answer](https://stackoverflow.com/a/55053562/771768) to subclass `SimpleHTTPRequestHandler` is really helpful! One detail I couldn't figure out was how to customize the `directory=` constructor arg when I pass `MyHandler` into `HTTPServer`. Use any of [these answers](https://stackoverflow.com/a/71399394/771768), i.e.
```py
HTTPServer(('', 8001), lambda *_: MyHandler(*_, directory=sys.path[0]))
``` | With python3, you can serve the current directory by simply running:
`python3 -m http.server 8080`
Of course you can configure many parameters as per the [documentation](https://docs.python.org/3/library/http.server.html). |
40,749,737 | Currently I have an Arduino hooked up to a Raspberry Pi. The Arduino controls a water level detection circuit in service to an automatic pet water bowl. The program on the Arduino has several "serial.println()" statements to update the user on the status of the water bowl, filling or full. I have the Arduino connected to the Raspberry Pi via USB. The small python program on the Pi that captures the serial data from the Arduino is as follows:
```
import serial
ser = serial.Serial('/dev/ttyUSB0',9600)
file = open('index.html', 'a+')
message1 = """<html>
<head><meta http-equiv="refresh" content="1"/></head>
<body><p>"""
message2 = """</p></body>
</html>"""
while 1:
line=ser.readline()
messagefinal1 = message1 + line + message2
print(line)
file.write(messagefinal1)
file.close()
```
As you can see it captures the serial data coming over USB, creates and html page, and inserts the data into the page. I am using a service called "dataplicity" (<https://www.dataplicity.com>), more specifically their "Wormhole" tool (<https://docs.dataplicity.com/docs/host-a-website-from-your-pi>), to view that html file over the web at a link that the wormhole tool generates. The problem I am having is this:
```
Traceback (most recent call last):
File "commprog.py", line 15, in <module>
file.write(messagefinal1)
ValueError: I/O operation on closed file
```
I want to continuously update the html page with the status of the water bowl (it is constantly printing its status). However once I close the page using "file.close()" I can't access it again, presumably because the wormhole service is accessing it. If I don't include .close() I have to end the process manually using ctrl c. Is there a way I can continuously update the html file? | 2016/11/22 | [
"https://Stackoverflow.com/questions/40749737",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4086994/"
] | After the first iteration of your while loop, you close the file and never open it again for editing. When you try to append to a file that is closed, you get an error. You could instead move the open statement inside your loop like so:
```
while 1:
line=ser.readline()
messagefinal1 = message1 + line + message2
print(line)
file = open('index.html', 'a+')
file.write(messagefinal1)
file.close()
``` | If you want to continuously update your webpage you have couple of options. I don't know how you serve your page but you might want to look at using Flask web framework for python and think about using templating language such as jinja2. A templating language will let you create variables in your html files that can be updated straight from python script. This is useful if you want the user to see new data on your page each time after they refresh it or perform some operation on the page.
Alternatively you might want to think about using websockets similarly as in the example I made [here](https://www.hackster.io/dataplicity/control-raspberry-pi-gpios-with-websockets-af3d0c?ref=user&ref_id=95392&offset=2) . Websockets are useful if you want your user to see new updates on your page in real time.
I appreciate the fact that the above answer doesn't answer your question directly but what I'm offering here is a clean and easy to maintain solution once you set it up. |
62,002,462 | I'm trying to prune a pre-trained model: **MobileNetV2** and I got this error. Tried searching online and couldn't understand. I'm running on **Google Colab**.
**These are my imports.**
```
import tensorflow as tf
import tensorflow_model_optimization as tfmot
import tensorflow_datasets as tfds
from tensorflow import keras
import os
import numpy as np
import matplotlib.pyplot as plt
import tempfile
import zipfile
```
***This is my code.***
```
model_1 = keras.Sequential([
basemodel,
keras.layers.GlobalAveragePooling2D(),
keras.layers.Dense(1)
])
model_1.compile(optimizer='adam',
loss=keras.losses.BinaryCrossentropy(from_logits=True),
metrics=['accuracy'])
model_1.fit(train_batches,
epochs=5,
validation_data=valid_batches)
prune_low_magnitude = tfmot.sparsity.keras.prune_low_magnitude
pruning_params = {
'pruning_schedule': tfmot.sparsity.keras.PolynomialDecay(initial_sparsity=0.50,
final_sparsity=0.80,
begin_step=0,
end_step=end_step)
}
model_2 = prune_low_magnitude(model_1, **pruning_params)
model_2.compile(optmizer='adam',
loss=keres.losses.BinaryCrossentropy(from_logits=True),
metrics=['accuracy'])
```
***This is the error i get.***
```
---> 12 model_2 = prune_low_magnitude(model, **pruning_params)
ValueError: Please initialize `Prune` with a supported layer. Layers should either be a `PrunableLayer` instance, or should be supported by the PruneRegistry. You passed: <class 'tensorflow.python.keras.engine.training.Model'>
``` | 2020/05/25 | [
"https://Stackoverflow.com/questions/62002462",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12540447/"
] | I believe you are following `Pruning in Keras Example` and jumped into `Fine-tune pre-trained model with pruning` section without setting your prunable layers. You have to reinstantiate model and set layers you wish to set as `prunable`. Follow this guide for further information on how to set prunable layers.
<https://www.tensorflow.org/model_optimization/guide/pruning/comprehensive_guide.md> | I faced the same issue with:
* tensorflow version: `2.2.0`
Just updating the version of tensorflow to `2.3.0` solved the issue, I think Tensorflow added support to this feature in 2.3.0. |
62,002,462 | I'm trying to prune a pre-trained model: **MobileNetV2** and I got this error. Tried searching online and couldn't understand. I'm running on **Google Colab**.
**These are my imports.**
```
import tensorflow as tf
import tensorflow_model_optimization as tfmot
import tensorflow_datasets as tfds
from tensorflow import keras
import os
import numpy as np
import matplotlib.pyplot as plt
import tempfile
import zipfile
```
***This is my code.***
```
model_1 = keras.Sequential([
basemodel,
keras.layers.GlobalAveragePooling2D(),
keras.layers.Dense(1)
])
model_1.compile(optimizer='adam',
loss=keras.losses.BinaryCrossentropy(from_logits=True),
metrics=['accuracy'])
model_1.fit(train_batches,
epochs=5,
validation_data=valid_batches)
prune_low_magnitude = tfmot.sparsity.keras.prune_low_magnitude
pruning_params = {
'pruning_schedule': tfmot.sparsity.keras.PolynomialDecay(initial_sparsity=0.50,
final_sparsity=0.80,
begin_step=0,
end_step=end_step)
}
model_2 = prune_low_magnitude(model_1, **pruning_params)
model_2.compile(optmizer='adam',
loss=keres.losses.BinaryCrossentropy(from_logits=True),
metrics=['accuracy'])
```
***This is the error i get.***
```
---> 12 model_2 = prune_low_magnitude(model, **pruning_params)
ValueError: Please initialize `Prune` with a supported layer. Layers should either be a `PrunableLayer` instance, or should be supported by the PruneRegistry. You passed: <class 'tensorflow.python.keras.engine.training.Model'>
``` | 2020/05/25 | [
"https://Stackoverflow.com/questions/62002462",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12540447/"
] | I believe you are following `Pruning in Keras Example` and jumped into `Fine-tune pre-trained model with pruning` section without setting your prunable layers. You have to reinstantiate model and set layers you wish to set as `prunable`. Follow this guide for further information on how to set prunable layers.
<https://www.tensorflow.org/model_optimization/guide/pruning/comprehensive_guide.md> | One thing I found is that the experimental preprocessing I added to my model was throwing this error. I had this at the beginning of my model to help add some more training samples but the keras pruning code doesn't like subclassed models like this. Similarly, the code doesn't like the experimental preprocessing like I have with centering of the image. Removing the preprocessing from the model solved the issue for me.
```
def classificationModel(trainImgs, testImgs):
L2_lambda = 0.01
data_augmentation = tf.keras.Sequential(
[ layers.experimental.preprocessing.RandomFlip("horizontal", input_shape=IM_DIMS),
layers.experimental.preprocessing.RandomRotation(0.1),
layers.experimental.preprocessing.RandomZoom(0.1),])
model = tf.keras.Sequential()
model.add(data_augmentation)
model.add(layers.experimental.preprocessing.Rescaling(1./255, input_shape=IM_DIMS))
...
``` |
62,002,462 | I'm trying to prune a pre-trained model: **MobileNetV2** and I got this error. Tried searching online and couldn't understand. I'm running on **Google Colab**.
**These are my imports.**
```
import tensorflow as tf
import tensorflow_model_optimization as tfmot
import tensorflow_datasets as tfds
from tensorflow import keras
import os
import numpy as np
import matplotlib.pyplot as plt
import tempfile
import zipfile
```
***This is my code.***
```
model_1 = keras.Sequential([
basemodel,
keras.layers.GlobalAveragePooling2D(),
keras.layers.Dense(1)
])
model_1.compile(optimizer='adam',
loss=keras.losses.BinaryCrossentropy(from_logits=True),
metrics=['accuracy'])
model_1.fit(train_batches,
epochs=5,
validation_data=valid_batches)
prune_low_magnitude = tfmot.sparsity.keras.prune_low_magnitude
pruning_params = {
'pruning_schedule': tfmot.sparsity.keras.PolynomialDecay(initial_sparsity=0.50,
final_sparsity=0.80,
begin_step=0,
end_step=end_step)
}
model_2 = prune_low_magnitude(model_1, **pruning_params)
model_2.compile(optmizer='adam',
loss=keres.losses.BinaryCrossentropy(from_logits=True),
metrics=['accuracy'])
```
***This is the error i get.***
```
---> 12 model_2 = prune_low_magnitude(model, **pruning_params)
ValueError: Please initialize `Prune` with a supported layer. Layers should either be a `PrunableLayer` instance, or should be supported by the PruneRegistry. You passed: <class 'tensorflow.python.keras.engine.training.Model'>
``` | 2020/05/25 | [
"https://Stackoverflow.com/questions/62002462",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12540447/"
] | I believe you are following `Pruning in Keras Example` and jumped into `Fine-tune pre-trained model with pruning` section without setting your prunable layers. You have to reinstantiate model and set layers you wish to set as `prunable`. Follow this guide for further information on how to set prunable layers.
<https://www.tensorflow.org/model_optimization/guide/pruning/comprehensive_guide.md> | Saving the model as below and reloading worked for me.
```
_, keras_file = tempfile.mkstemp('.h5')
tf.keras.models.save_model(model, keras_file, include_optimizer=False)
print('Saved baseline model to:', keras_file)
``` |
62,002,462 | I'm trying to prune a pre-trained model: **MobileNetV2** and I got this error. Tried searching online and couldn't understand. I'm running on **Google Colab**.
**These are my imports.**
```
import tensorflow as tf
import tensorflow_model_optimization as tfmot
import tensorflow_datasets as tfds
from tensorflow import keras
import os
import numpy as np
import matplotlib.pyplot as plt
import tempfile
import zipfile
```
***This is my code.***
```
model_1 = keras.Sequential([
basemodel,
keras.layers.GlobalAveragePooling2D(),
keras.layers.Dense(1)
])
model_1.compile(optimizer='adam',
loss=keras.losses.BinaryCrossentropy(from_logits=True),
metrics=['accuracy'])
model_1.fit(train_batches,
epochs=5,
validation_data=valid_batches)
prune_low_magnitude = tfmot.sparsity.keras.prune_low_magnitude
pruning_params = {
'pruning_schedule': tfmot.sparsity.keras.PolynomialDecay(initial_sparsity=0.50,
final_sparsity=0.80,
begin_step=0,
end_step=end_step)
}
model_2 = prune_low_magnitude(model_1, **pruning_params)
model_2.compile(optmizer='adam',
loss=keres.losses.BinaryCrossentropy(from_logits=True),
metrics=['accuracy'])
```
***This is the error i get.***
```
---> 12 model_2 = prune_low_magnitude(model, **pruning_params)
ValueError: Please initialize `Prune` with a supported layer. Layers should either be a `PrunableLayer` instance, or should be supported by the PruneRegistry. You passed: <class 'tensorflow.python.keras.engine.training.Model'>
``` | 2020/05/25 | [
"https://Stackoverflow.com/questions/62002462",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12540447/"
] | I believe you are following `Pruning in Keras Example` and jumped into `Fine-tune pre-trained model with pruning` section without setting your prunable layers. You have to reinstantiate model and set layers you wish to set as `prunable`. Follow this guide for further information on how to set prunable layers.
<https://www.tensorflow.org/model_optimization/guide/pruning/comprehensive_guide.md> | Had the same problem today, its the following [error](https://github.com/tensorflow/model-optimization/blob/master/tensorflow_model_optimization/python/core/sparsity/keras/pruning_wrapper.py#L156-L162).
If you don't want the layer to be pruned or don't care for it, you can use this code to only prune the prunable layers in a model:
```
from tensorflow_model_optimization.python.core.sparsity.keras import prunable_layer
from tensorflow_model_optimization.python.core.sparsity.keras import prune_registry
def apply_pruning_to_prunable_layers(layer):
if isinstance(layer, prunable_layer.PrunableLayer) or hasattr(layer, 'get_prunable_weights') or prune_registry.PruneRegistry.supports(layer):
return tfmot.sparsity.keras.prune_low_magnitude(layer)
print("Not Prunable: ", layer)
return layer
model_for_pruning = tf.keras.models.clone_model(
base_model,
clone_function=apply_pruning_to_pruneable_layers
)
``` |
42,010,684 | I have a script written in python 2.7 that calls for a thread. But, whatever I do, the thread won't call the function.
The function it calls:
```
def siren_loop():
while running:
print 'dit is een print'
```
The way I tried to call it:
```
running = True
t = threading.Thread(target=siren_loop)
t.start()
```
or:
```
running = True
thread.start_new_thread( siren_loop, () )
```
I even tried to add arguments to siren\_loop to see if that would work, but no change. I just can't get it to print the lines in the siren\_loop function.
I also tried many other strange things, which obviously didn't work. What am I doing wrong?
edit: Since people said it worked, I tried to call the thread from another function. So it looked something like this:
```
def start_sirene():
running = True
t = threading.Thread(target=siren_loop)
t.start()
```
And then that part was called from:
```
if zwaailichtbool == False:
start_sirene()
print 'zwaailicht aan'
zwaailichtbool = True
sleep(0.5)
```
Maybe that could cause the problem?
The print statement in the last one works, and when I added a print before or after the thread statement it also worked. | 2017/02/02 | [
"https://Stackoverflow.com/questions/42010684",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5837270/"
] | So, after trying various things for hours i and hours, I found a solution but still don't understand the problem.
Apparently the program didnt like the many steps. I took one step away (the start siren method) but used the exact same code, and suddenly it worked. Stl no clue why that was the problem. If anybody knows, please enlighten me xD | `running` is a local variable in your code. Add `global running` to `start_sirene()` |
42,010,684 | I have a script written in python 2.7 that calls for a thread. But, whatever I do, the thread won't call the function.
The function it calls:
```
def siren_loop():
while running:
print 'dit is een print'
```
The way I tried to call it:
```
running = True
t = threading.Thread(target=siren_loop)
t.start()
```
or:
```
running = True
thread.start_new_thread( siren_loop, () )
```
I even tried to add arguments to siren\_loop to see if that would work, but no change. I just can't get it to print the lines in the siren\_loop function.
I also tried many other strange things, which obviously didn't work. What am I doing wrong?
edit: Since people said it worked, I tried to call the thread from another function. So it looked something like this:
```
def start_sirene():
running = True
t = threading.Thread(target=siren_loop)
t.start()
```
And then that part was called from:
```
if zwaailichtbool == False:
start_sirene()
print 'zwaailicht aan'
zwaailichtbool = True
sleep(0.5)
```
Maybe that could cause the problem?
The print statement in the last one works, and when I added a print before or after the thread statement it also worked. | 2017/02/02 | [
"https://Stackoverflow.com/questions/42010684",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5837270/"
] | So, after trying various things for hours i and hours, I found a solution but still don't understand the problem.
Apparently the program didnt like the many steps. I took one step away (the start siren method) but used the exact same code, and suddenly it worked. Stl no clue why that was the problem. If anybody knows, please enlighten me xD | It's working perfectly fine for me, you can also specify running as keyword arguments to the thread\_function.
```
import threading
def siren_loop(running):
while running:
print 'dit is een print'
t = threading.Thread(target=siren_loop, kwargs=dict(running=True))
t.start()
``` |
20,794,258 | I have an appengine app that I want to use as a front end to some existing web services. How can I consume those WS from my app?
I'm using python | 2013/12/27 | [
"https://Stackoverflow.com/questions/20794258",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/251154/"
] | You are calling `string.replace` without assigning the output anywhere. The function does not modify the original string - it creates a new one - but you are not storing the returned value.
Try this:
```
...
str = str.replace(/\r?\n|\r/g, " ");
...
```
---
However, if you actually want to remove *all* whitespace from around the input (not just newline characters at the end), you should use [`trim`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/Trim):
```
...
str = str.trim();
...
```
It will likely be more efficient since it is already implemented in the Node.js binary. | you need to convert the data into **JSON** format.
**JSON.parse(data)** you will remove all new line character and leave the data in **JSON** format. |
20,794,258 | I have an appengine app that I want to use as a front end to some existing web services. How can I consume those WS from my app?
I'm using python | 2013/12/27 | [
"https://Stackoverflow.com/questions/20794258",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/251154/"
] | You are calling `string.replace` without assigning the output anywhere. The function does not modify the original string - it creates a new one - but you are not storing the returned value.
Try this:
```
...
str = str.replace(/\r?\n|\r/g, " ");
...
```
---
However, if you actually want to remove *all* whitespace from around the input (not just newline characters at the end), you should use [`trim`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/Trim):
```
...
str = str.trim();
...
```
It will likely be more efficient since it is already implemented in the Node.js binary. | You were trying to console output the value of `str` without updating it.
You should have done this
```
str = str.replace(/\r?\n|\r/g, " ");
```
before console output. |
20,794,258 | I have an appengine app that I want to use as a front end to some existing web services. How can I consume those WS from my app?
I'm using python | 2013/12/27 | [
"https://Stackoverflow.com/questions/20794258",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/251154/"
] | You were trying to console output the value of `str` without updating it.
You should have done this
```
str = str.replace(/\r?\n|\r/g, " ");
```
before console output. | you need to convert the data into **JSON** format.
**JSON.parse(data)** you will remove all new line character and leave the data in **JSON** format. |
55,010,607 | I am new to machine learning and have spent some time learning python. I have started to learn TensorFlow and Keras for machine learning and I literally have no clue nor any understanding of the process to make the model. How do you know which models to use? which activation functions to use? The amount of layers and dimensions of the output space?
I've noticed most models were the Sequential type, and tend to have 3 layers, why is that? I couldn't find any resources that explain which to use, why we use them, and when. The best I could find was tensorflow's function details. Any elaboration or any resources to clarify would be greatly appreciated.
Thanks. | 2019/03/05 | [
"https://Stackoverflow.com/questions/55010607",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9919507/"
] | `*m` is the same as `m[0]`, i.e. the first element of the array pointed to by `m` which is the character `'s'`.
By using the `%d` format specifier, you're printing the given argument as an integer. The ASCII value of `'s'` is 115, which is why you get that value.
If you want to print the string, use the `%s` format specifier (which expects a `char *` argument) instead and pass the pointer `m`.
```
printf("%s\n", m);
``` | You have a few problems here,
the first one is that you're trying to add three bytes to a char, a char is one byte.
the second problem is that char \*m is a pointer to an address and is not a modifiable lvalue. The only time you should use pointers is when you are trying to point to data
example:
```
char byte = "A"; //WRONG
char byte = 0x61; //OK
char byte = 'A'; //OK
//notice that when setting char byte = "A" you will recieve an error,
//the double quotations is for character arrays where as single quotes,
// are used to identify a char
enter code here
char str[] = "ABCDEF";
char *m = str;
printf("%02x", *m); //you are pointing to str[0]
printf("%02x", *m[1]); //you are pointing to str[1]
printf("%02x", *m[1]); //you are pointing to str[1]
printf("%02x", *(m + 1)); //you are still pointing to str[1]
//m is a pointer to the address in memory calling it like
// *m[1] or *(m + 1) is saying address + one byte
//these examples are the same as calling (more or less)
printf("%02x", str[0]); or
printf("%02x", str[1]);
``` |
55,010,607 | I am new to machine learning and have spent some time learning python. I have started to learn TensorFlow and Keras for machine learning and I literally have no clue nor any understanding of the process to make the model. How do you know which models to use? which activation functions to use? The amount of layers and dimensions of the output space?
I've noticed most models were the Sequential type, and tend to have 3 layers, why is that? I couldn't find any resources that explain which to use, why we use them, and when. The best I could find was tensorflow's function details. Any elaboration or any resources to clarify would be greatly appreciated.
Thanks. | 2019/03/05 | [
"https://Stackoverflow.com/questions/55010607",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9919507/"
] | `*m` is the same as `m[0]`, i.e. the first element of the array pointed to by `m` which is the character `'s'`.
By using the `%d` format specifier, you're printing the given argument as an integer. The ASCII value of `'s'` is 115, which is why you get that value.
If you want to print the string, use the `%s` format specifier (which expects a `char *` argument) instead and pass the pointer `m`.
```
printf("%s\n", m);
``` | Pointers and arrays act similarly .Array names are also pointers pointing to the first element of the array.
You have stored "srm" as a character array with m pointing to the first element.
"%d" will give you the ASCII value of the item being pointed by the pointer.
ASCII value of "s" is 115.
if you increment your pointer (m++) then print it's ascii value , output will be ascii value of "r" - 114.
```
#include <stdio.h>
int main()
{
char *m ;
m="srm";
m++; //pointing to the 2nd element of the array
printf("%d",*m); //output = 114
return 0;
}
``` |
18,787,722 | Is there are a way to change the user directory according to the username, something like
```
os.chdir('/home/arn/cake/')
```
But imagine that I don't know what's the username on that system. How do I find out what's the username, I know that python doesn't have variables so it's hard for me to get the username without variable. | 2013/09/13 | [
"https://Stackoverflow.com/questions/18787722",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2641084/"
] | ```
pwd.getpwnam(username).pw_dir
```
is the home directory of `username`. The user executing the program has username `os.getlogin()`.
"I know that python doesn't have variables" -- that's nonsense. You obviously mean environment variables, which you can access using `os.getenv` or `os.environ`. | Maybe there is a better answer but you can always use command calls:
```
import commands
user_dir = commands.getoutput("cd; pwd")
``` |
32,702,954 | I am trying to rename multiple mp3 files I have in a folder. They start with something like "1 Hotel California - The Eagles" and so on. I would like it to be just "Hotel California - The Eagles".
Also, there could be a "05 Hotel California - The Eagles" as well, which means removing the number from a different files would create duplicates, which is the problem I am facing. I want it to replace existing files/overwrite/delete one of them or whatever a solution might be.
P.S, Adding "3" to the "1234567890 " would remove the "3" from the .mp3 extension
I am new to python, but here is the code I am using to implement this
```
import os
def renamefiles():
list = os.listdir(r"E:\NEW")
print(list)
path = os.getcwd()
print(path)
os.chdir(r"E:\NEW")
for name in list:
os.rename(name, name.translate(None, "124567890 "))
os.chdir(path)
renamefiles()
```
And here is the error I get
WindowsError: [Error 183] Cannot create a file when that file already exists
Any help on how I could rename the files correctly would be highly appreciated! | 2015/09/21 | [
"https://Stackoverflow.com/questions/32702954",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3803648/"
] | You need to verify that the names being changed actually changed. If the name doesn't have digits or spaces in it, the `translate` will return the same string, and you'll try to rename `name` to `name`, which Windows rejects. Try:
```
for name in list:
newname = name.translate(None, "124567890 ")
if name != newname:
os.rename(name, newname)
```
Note, this will still fail if the file target exists, which you'd probably want if you were accidentally collapsing two names into one. But if you want silent replace behavior, if you're on Python 3.3 or higher, you can change `os.rename` to `os.replace` to silently overwrite; on earlier Python, you can explicitly `os.remove` before calling `os.rename`. | You just need to change directory to where \*.mp3 files are located and execute 2 lines of below with python:
```
import os,re
for filename in os.listdir():
os.rename(filename, filname.strip(re.search("[0-9]{2}", filename).group(0)))
``` |
32,702,954 | I am trying to rename multiple mp3 files I have in a folder. They start with something like "1 Hotel California - The Eagles" and so on. I would like it to be just "Hotel California - The Eagles".
Also, there could be a "05 Hotel California - The Eagles" as well, which means removing the number from a different files would create duplicates, which is the problem I am facing. I want it to replace existing files/overwrite/delete one of them or whatever a solution might be.
P.S, Adding "3" to the "1234567890 " would remove the "3" from the .mp3 extension
I am new to python, but here is the code I am using to implement this
```
import os
def renamefiles():
list = os.listdir(r"E:\NEW")
print(list)
path = os.getcwd()
print(path)
os.chdir(r"E:\NEW")
for name in list:
os.rename(name, name.translate(None, "124567890 "))
os.chdir(path)
renamefiles()
```
And here is the error I get
WindowsError: [Error 183] Cannot create a file when that file already exists
Any help on how I could rename the files correctly would be highly appreciated! | 2015/09/21 | [
"https://Stackoverflow.com/questions/32702954",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3803648/"
] | You can catch an `OSError` and also use `glob` to find the .mp3 files:
```
import os
from glob import iglob
def renamefiles(pth):
os.chdir(pth)
for name in iglob("*.mp3"):
try:
os.rename(name, name.translate(None, "124567890").lstrip())
except OSError:
print("Caught error for {}".format(name))
# os.remove(name) ?
```
What you do when you catch the error is up to you, you could keep some record of names found and increment a count for each or leave as is.
If the numbers are always at the start you can also just lstrip then away so you can then use 3 safely:
```
os.rename(name, name.lstrip("0123456789 "))
```
using one of your example strings:
```
In [2]: "05 Hotel California - The Eagles.mp3".lstrip("01234567890 ")
Out[2]: 'Hotel California - The Eagles.mp3'
```
Using your original approach could never work as desired as you would remove all spaces:
```
In [3]: "05 Hotel California - The Eagles.mp3".translate(None,"0124567890 ")
Out[3]: 'HotelCalifornia-TheEagles.mp3'
```
If you don't care what file gets overwritten you can use `shutil.move`:
```
import os
from glob import iglob
from shutil import move
def renamefiles(pth):
os.chdir(pth)
for name in iglob("*.mp3"):
move(name, name.translate(None, "124567890").lstrip())
```
On another note, don't use `list` as a variable name. | You just need to change directory to where \*.mp3 files are located and execute 2 lines of below with python:
```
import os,re
for filename in os.listdir():
os.rename(filename, filname.strip(re.search("[0-9]{2}", filename).group(0)))
``` |
32,702,954 | I am trying to rename multiple mp3 files I have in a folder. They start with something like "1 Hotel California - The Eagles" and so on. I would like it to be just "Hotel California - The Eagles".
Also, there could be a "05 Hotel California - The Eagles" as well, which means removing the number from a different files would create duplicates, which is the problem I am facing. I want it to replace existing files/overwrite/delete one of them or whatever a solution might be.
P.S, Adding "3" to the "1234567890 " would remove the "3" from the .mp3 extension
I am new to python, but here is the code I am using to implement this
```
import os
def renamefiles():
list = os.listdir(r"E:\NEW")
print(list)
path = os.getcwd()
print(path)
os.chdir(r"E:\NEW")
for name in list:
os.rename(name, name.translate(None, "124567890 "))
os.chdir(path)
renamefiles()
```
And here is the error I get
WindowsError: [Error 183] Cannot create a file when that file already exists
Any help on how I could rename the files correctly would be highly appreciated! | 2015/09/21 | [
"https://Stackoverflow.com/questions/32702954",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3803648/"
] | You can catch an `OSError` and also use `glob` to find the .mp3 files:
```
import os
from glob import iglob
def renamefiles(pth):
os.chdir(pth)
for name in iglob("*.mp3"):
try:
os.rename(name, name.translate(None, "124567890").lstrip())
except OSError:
print("Caught error for {}".format(name))
# os.remove(name) ?
```
What you do when you catch the error is up to you, you could keep some record of names found and increment a count for each or leave as is.
If the numbers are always at the start you can also just lstrip then away so you can then use 3 safely:
```
os.rename(name, name.lstrip("0123456789 "))
```
using one of your example strings:
```
In [2]: "05 Hotel California - The Eagles.mp3".lstrip("01234567890 ")
Out[2]: 'Hotel California - The Eagles.mp3'
```
Using your original approach could never work as desired as you would remove all spaces:
```
In [3]: "05 Hotel California - The Eagles.mp3".translate(None,"0124567890 ")
Out[3]: 'HotelCalifornia-TheEagles.mp3'
```
If you don't care what file gets overwritten you can use `shutil.move`:
```
import os
from glob import iglob
from shutil import move
def renamefiles(pth):
os.chdir(pth)
for name in iglob("*.mp3"):
move(name, name.translate(None, "124567890").lstrip())
```
On another note, don't use `list` as a variable name. | I was unable to easily get any of the answers to work with Python 3.5, so here's one that works under that condition:
```
import os
import re
def rename_files():
path = os.getcwd()
file_names = os.listdir(path)
for name in file_names:
os.rename(name, re.sub("[0-9](?!\d*$)", "", name))
rename_files()
```
This should work for a list of files like "1 Hotel California - The Eagles.mp3", renaming them to "Hotel California - The Eagles.mp3" (so the extension is untouched). |
32,702,954 | I am trying to rename multiple mp3 files I have in a folder. They start with something like "1 Hotel California - The Eagles" and so on. I would like it to be just "Hotel California - The Eagles".
Also, there could be a "05 Hotel California - The Eagles" as well, which means removing the number from a different files would create duplicates, which is the problem I am facing. I want it to replace existing files/overwrite/delete one of them or whatever a solution might be.
P.S, Adding "3" to the "1234567890 " would remove the "3" from the .mp3 extension
I am new to python, but here is the code I am using to implement this
```
import os
def renamefiles():
list = os.listdir(r"E:\NEW")
print(list)
path = os.getcwd()
print(path)
os.chdir(r"E:\NEW")
for name in list:
os.rename(name, name.translate(None, "124567890 "))
os.chdir(path)
renamefiles()
```
And here is the error I get
WindowsError: [Error 183] Cannot create a file when that file already exists
Any help on how I could rename the files correctly would be highly appreciated! | 2015/09/21 | [
"https://Stackoverflow.com/questions/32702954",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3803648/"
] | I was unable to easily get any of the answers to work with Python 3.5, so here's one that works under that condition:
```
import os
import re
def rename_files():
path = os.getcwd()
file_names = os.listdir(path)
for name in file_names:
os.rename(name, re.sub("[0-9](?!\d*$)", "", name))
rename_files()
```
This should work for a list of files like "1 Hotel California - The Eagles.mp3", renaming them to "Hotel California - The Eagles.mp3" (so the extension is untouched). | Ok so what you want is:
* create a new filename removing *leading* numbers
* if that new filename exists, remove it
* rename the file to that new filename
The following code should work (not tested).
```
import os
import string
class FileExists(Exception):
pass
def rename_files(path, ext, remove_existing=True):
for fname in os.listdir(path):
# test if the file name ends with the expected
# extension else skip it
if not fname.endswith(ext):
continue
# chdir is not a good idea, better to work
# with absolute path whenever possible
oldpath = os.path.join(path, fname)
# remove _leading_ digits then remove all whitespaces
newname = fname.lstrip(string.digits).strip()
newpath = os.path.join(path, newname)
# check if the file already exists
if os.path.exists(newpath):
if remove_existing:
# it exists and we were told to
# remove existing file:
os.remove(newpath)
else:
# it exists and we were told to
# NOT remove existing file:
raise FileExists(newpath)
# ok now we should be safe
os.rename(oldpath, newpath)
# only execute the function if we are called directly
# we dont want to do anything if we are just imported
# from the Python shell or another script or module
if __name__ == "__main__":
# exercice left to the reader:
# add command line options / arguments handling
# to specify the path to browse, the target
# extension and whether to remove existing files
# or not
rename_files(r"E:\NEW", ".mp3", True)
``` |
32,702,954 | I am trying to rename multiple mp3 files I have in a folder. They start with something like "1 Hotel California - The Eagles" and so on. I would like it to be just "Hotel California - The Eagles".
Also, there could be a "05 Hotel California - The Eagles" as well, which means removing the number from a different files would create duplicates, which is the problem I am facing. I want it to replace existing files/overwrite/delete one of them or whatever a solution might be.
P.S, Adding "3" to the "1234567890 " would remove the "3" from the .mp3 extension
I am new to python, but here is the code I am using to implement this
```
import os
def renamefiles():
list = os.listdir(r"E:\NEW")
print(list)
path = os.getcwd()
print(path)
os.chdir(r"E:\NEW")
for name in list:
os.rename(name, name.translate(None, "124567890 "))
os.chdir(path)
renamefiles()
```
And here is the error I get
WindowsError: [Error 183] Cannot create a file when that file already exists
Any help on how I could rename the files correctly would be highly appreciated! | 2015/09/21 | [
"https://Stackoverflow.com/questions/32702954",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3803648/"
] | instead of using name.translate, import the re lib (regular expressions) and use something like
```
"(?:\d*)?\s*(.+?).mp3"
```
as your pattern. You can then use
```
Match.group(1)
```
as your rename.
For dealing with multiple files, add an if statement that checks if the file already exists in the library like this:
```
os.path.exists(dirpath)
```
where dirpath is the directory that you want to check in | You just need to change directory to where \*.mp3 files are located and execute 2 lines of below with python:
```
import os,re
for filename in os.listdir():
os.rename(filename, filname.strip(re.search("[0-9]{2}", filename).group(0)))
``` |
32,702,954 | I am trying to rename multiple mp3 files I have in a folder. They start with something like "1 Hotel California - The Eagles" and so on. I would like it to be just "Hotel California - The Eagles".
Also, there could be a "05 Hotel California - The Eagles" as well, which means removing the number from a different files would create duplicates, which is the problem I am facing. I want it to replace existing files/overwrite/delete one of them or whatever a solution might be.
P.S, Adding "3" to the "1234567890 " would remove the "3" from the .mp3 extension
I am new to python, but here is the code I am using to implement this
```
import os
def renamefiles():
list = os.listdir(r"E:\NEW")
print(list)
path = os.getcwd()
print(path)
os.chdir(r"E:\NEW")
for name in list:
os.rename(name, name.translate(None, "124567890 "))
os.chdir(path)
renamefiles()
```
And here is the error I get
WindowsError: [Error 183] Cannot create a file when that file already exists
Any help on how I could rename the files correctly would be highly appreciated! | 2015/09/21 | [
"https://Stackoverflow.com/questions/32702954",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3803648/"
] | instead of using name.translate, import the re lib (regular expressions) and use something like
```
"(?:\d*)?\s*(.+?).mp3"
```
as your pattern. You can then use
```
Match.group(1)
```
as your rename.
For dealing with multiple files, add an if statement that checks if the file already exists in the library like this:
```
os.path.exists(dirpath)
```
where dirpath is the directory that you want to check in | Ok so what you want is:
* create a new filename removing *leading* numbers
* if that new filename exists, remove it
* rename the file to that new filename
The following code should work (not tested).
```
import os
import string
class FileExists(Exception):
pass
def rename_files(path, ext, remove_existing=True):
for fname in os.listdir(path):
# test if the file name ends with the expected
# extension else skip it
if not fname.endswith(ext):
continue
# chdir is not a good idea, better to work
# with absolute path whenever possible
oldpath = os.path.join(path, fname)
# remove _leading_ digits then remove all whitespaces
newname = fname.lstrip(string.digits).strip()
newpath = os.path.join(path, newname)
# check if the file already exists
if os.path.exists(newpath):
if remove_existing:
# it exists and we were told to
# remove existing file:
os.remove(newpath)
else:
# it exists and we were told to
# NOT remove existing file:
raise FileExists(newpath)
# ok now we should be safe
os.rename(oldpath, newpath)
# only execute the function if we are called directly
# we dont want to do anything if we are just imported
# from the Python shell or another script or module
if __name__ == "__main__":
# exercice left to the reader:
# add command line options / arguments handling
# to specify the path to browse, the target
# extension and whether to remove existing files
# or not
rename_files(r"E:\NEW", ".mp3", True)
``` |
32,702,954 | I am trying to rename multiple mp3 files I have in a folder. They start with something like "1 Hotel California - The Eagles" and so on. I would like it to be just "Hotel California - The Eagles".
Also, there could be a "05 Hotel California - The Eagles" as well, which means removing the number from a different files would create duplicates, which is the problem I am facing. I want it to replace existing files/overwrite/delete one of them or whatever a solution might be.
P.S, Adding "3" to the "1234567890 " would remove the "3" from the .mp3 extension
I am new to python, but here is the code I am using to implement this
```
import os
def renamefiles():
list = os.listdir(r"E:\NEW")
print(list)
path = os.getcwd()
print(path)
os.chdir(r"E:\NEW")
for name in list:
os.rename(name, name.translate(None, "124567890 "))
os.chdir(path)
renamefiles()
```
And here is the error I get
WindowsError: [Error 183] Cannot create a file when that file already exists
Any help on how I could rename the files correctly would be highly appreciated! | 2015/09/21 | [
"https://Stackoverflow.com/questions/32702954",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3803648/"
] | I was unable to easily get any of the answers to work with Python 3.5, so here's one that works under that condition:
```
import os
import re
def rename_files():
path = os.getcwd()
file_names = os.listdir(path)
for name in file_names:
os.rename(name, re.sub("[0-9](?!\d*$)", "", name))
rename_files()
```
This should work for a list of files like "1 Hotel California - The Eagles.mp3", renaming them to "Hotel California - The Eagles.mp3" (so the extension is untouched). | You just need to change directory to where \*.mp3 files are located and execute 2 lines of below with python:
```
import os,re
for filename in os.listdir():
os.rename(filename, filname.strip(re.search("[0-9]{2}", filename).group(0)))
``` |
32,702,954 | I am trying to rename multiple mp3 files I have in a folder. They start with something like "1 Hotel California - The Eagles" and so on. I would like it to be just "Hotel California - The Eagles".
Also, there could be a "05 Hotel California - The Eagles" as well, which means removing the number from a different files would create duplicates, which is the problem I am facing. I want it to replace existing files/overwrite/delete one of them or whatever a solution might be.
P.S, Adding "3" to the "1234567890 " would remove the "3" from the .mp3 extension
I am new to python, but here is the code I am using to implement this
```
import os
def renamefiles():
list = os.listdir(r"E:\NEW")
print(list)
path = os.getcwd()
print(path)
os.chdir(r"E:\NEW")
for name in list:
os.rename(name, name.translate(None, "124567890 "))
os.chdir(path)
renamefiles()
```
And here is the error I get
WindowsError: [Error 183] Cannot create a file when that file already exists
Any help on how I could rename the files correctly would be highly appreciated! | 2015/09/21 | [
"https://Stackoverflow.com/questions/32702954",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3803648/"
] | You can catch an `OSError` and also use `glob` to find the .mp3 files:
```
import os
from glob import iglob
def renamefiles(pth):
os.chdir(pth)
for name in iglob("*.mp3"):
try:
os.rename(name, name.translate(None, "124567890").lstrip())
except OSError:
print("Caught error for {}".format(name))
# os.remove(name) ?
```
What you do when you catch the error is up to you, you could keep some record of names found and increment a count for each or leave as is.
If the numbers are always at the start you can also just lstrip then away so you can then use 3 safely:
```
os.rename(name, name.lstrip("0123456789 "))
```
using one of your example strings:
```
In [2]: "05 Hotel California - The Eagles.mp3".lstrip("01234567890 ")
Out[2]: 'Hotel California - The Eagles.mp3'
```
Using your original approach could never work as desired as you would remove all spaces:
```
In [3]: "05 Hotel California - The Eagles.mp3".translate(None,"0124567890 ")
Out[3]: 'HotelCalifornia-TheEagles.mp3'
```
If you don't care what file gets overwritten you can use `shutil.move`:
```
import os
from glob import iglob
from shutil import move
def renamefiles(pth):
os.chdir(pth)
for name in iglob("*.mp3"):
move(name, name.translate(None, "124567890").lstrip())
```
On another note, don't use `list` as a variable name. | Ok so what you want is:
* create a new filename removing *leading* numbers
* if that new filename exists, remove it
* rename the file to that new filename
The following code should work (not tested).
```
import os
import string
class FileExists(Exception):
pass
def rename_files(path, ext, remove_existing=True):
for fname in os.listdir(path):
# test if the file name ends with the expected
# extension else skip it
if not fname.endswith(ext):
continue
# chdir is not a good idea, better to work
# with absolute path whenever possible
oldpath = os.path.join(path, fname)
# remove _leading_ digits then remove all whitespaces
newname = fname.lstrip(string.digits).strip()
newpath = os.path.join(path, newname)
# check if the file already exists
if os.path.exists(newpath):
if remove_existing:
# it exists and we were told to
# remove existing file:
os.remove(newpath)
else:
# it exists and we were told to
# NOT remove existing file:
raise FileExists(newpath)
# ok now we should be safe
os.rename(oldpath, newpath)
# only execute the function if we are called directly
# we dont want to do anything if we are just imported
# from the Python shell or another script or module
if __name__ == "__main__":
# exercice left to the reader:
# add command line options / arguments handling
# to specify the path to browse, the target
# extension and whether to remove existing files
# or not
rename_files(r"E:\NEW", ".mp3", True)
``` |
32,702,954 | I am trying to rename multiple mp3 files I have in a folder. They start with something like "1 Hotel California - The Eagles" and so on. I would like it to be just "Hotel California - The Eagles".
Also, there could be a "05 Hotel California - The Eagles" as well, which means removing the number from a different files would create duplicates, which is the problem I am facing. I want it to replace existing files/overwrite/delete one of them or whatever a solution might be.
P.S, Adding "3" to the "1234567890 " would remove the "3" from the .mp3 extension
I am new to python, but here is the code I am using to implement this
```
import os
def renamefiles():
list = os.listdir(r"E:\NEW")
print(list)
path = os.getcwd()
print(path)
os.chdir(r"E:\NEW")
for name in list:
os.rename(name, name.translate(None, "124567890 "))
os.chdir(path)
renamefiles()
```
And here is the error I get
WindowsError: [Error 183] Cannot create a file when that file already exists
Any help on how I could rename the files correctly would be highly appreciated! | 2015/09/21 | [
"https://Stackoverflow.com/questions/32702954",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3803648/"
] | You need to verify that the names being changed actually changed. If the name doesn't have digits or spaces in it, the `translate` will return the same string, and you'll try to rename `name` to `name`, which Windows rejects. Try:
```
for name in list:
newname = name.translate(None, "124567890 ")
if name != newname:
os.rename(name, newname)
```
Note, this will still fail if the file target exists, which you'd probably want if you were accidentally collapsing two names into one. But if you want silent replace behavior, if you're on Python 3.3 or higher, you can change `os.rename` to `os.replace` to silently overwrite; on earlier Python, you can explicitly `os.remove` before calling `os.rename`. | Ok so what you want is:
* create a new filename removing *leading* numbers
* if that new filename exists, remove it
* rename the file to that new filename
The following code should work (not tested).
```
import os
import string
class FileExists(Exception):
pass
def rename_files(path, ext, remove_existing=True):
for fname in os.listdir(path):
# test if the file name ends with the expected
# extension else skip it
if not fname.endswith(ext):
continue
# chdir is not a good idea, better to work
# with absolute path whenever possible
oldpath = os.path.join(path, fname)
# remove _leading_ digits then remove all whitespaces
newname = fname.lstrip(string.digits).strip()
newpath = os.path.join(path, newname)
# check if the file already exists
if os.path.exists(newpath):
if remove_existing:
# it exists and we were told to
# remove existing file:
os.remove(newpath)
else:
# it exists and we were told to
# NOT remove existing file:
raise FileExists(newpath)
# ok now we should be safe
os.rename(oldpath, newpath)
# only execute the function if we are called directly
# we dont want to do anything if we are just imported
# from the Python shell or another script or module
if __name__ == "__main__":
# exercice left to the reader:
# add command line options / arguments handling
# to specify the path to browse, the target
# extension and whether to remove existing files
# or not
rename_files(r"E:\NEW", ".mp3", True)
``` |
32,702,954 | I am trying to rename multiple mp3 files I have in a folder. They start with something like "1 Hotel California - The Eagles" and so on. I would like it to be just "Hotel California - The Eagles".
Also, there could be a "05 Hotel California - The Eagles" as well, which means removing the number from a different files would create duplicates, which is the problem I am facing. I want it to replace existing files/overwrite/delete one of them or whatever a solution might be.
P.S, Adding "3" to the "1234567890 " would remove the "3" from the .mp3 extension
I am new to python, but here is the code I am using to implement this
```
import os
def renamefiles():
list = os.listdir(r"E:\NEW")
print(list)
path = os.getcwd()
print(path)
os.chdir(r"E:\NEW")
for name in list:
os.rename(name, name.translate(None, "124567890 "))
os.chdir(path)
renamefiles()
```
And here is the error I get
WindowsError: [Error 183] Cannot create a file when that file already exists
Any help on how I could rename the files correctly would be highly appreciated! | 2015/09/21 | [
"https://Stackoverflow.com/questions/32702954",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3803648/"
] | You can catch an `OSError` and also use `glob` to find the .mp3 files:
```
import os
from glob import iglob
def renamefiles(pth):
os.chdir(pth)
for name in iglob("*.mp3"):
try:
os.rename(name, name.translate(None, "124567890").lstrip())
except OSError:
print("Caught error for {}".format(name))
# os.remove(name) ?
```
What you do when you catch the error is up to you, you could keep some record of names found and increment a count for each or leave as is.
If the numbers are always at the start you can also just lstrip then away so you can then use 3 safely:
```
os.rename(name, name.lstrip("0123456789 "))
```
using one of your example strings:
```
In [2]: "05 Hotel California - The Eagles.mp3".lstrip("01234567890 ")
Out[2]: 'Hotel California - The Eagles.mp3'
```
Using your original approach could never work as desired as you would remove all spaces:
```
In [3]: "05 Hotel California - The Eagles.mp3".translate(None,"0124567890 ")
Out[3]: 'HotelCalifornia-TheEagles.mp3'
```
If you don't care what file gets overwritten you can use `shutil.move`:
```
import os
from glob import iglob
from shutil import move
def renamefiles(pth):
os.chdir(pth)
for name in iglob("*.mp3"):
move(name, name.translate(None, "124567890").lstrip())
```
On another note, don't use `list` as a variable name. | instead of using name.translate, import the re lib (regular expressions) and use something like
```
"(?:\d*)?\s*(.+?).mp3"
```
as your pattern. You can then use
```
Match.group(1)
```
as your rename.
For dealing with multiple files, add an if statement that checks if the file already exists in the library like this:
```
os.path.exists(dirpath)
```
where dirpath is the directory that you want to check in |
27,821,776 | I want to set a value in editbox of android app using appium. And I am using python script to automate it. But I am always getting some errors.
My python script is
```
import os
import unittest
import time
from appium import webdriver
from time import sleep
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
import uiautomator
import math
element = self.driver.find_element_by_class_name('android.widget.EditText')
element.set_value('qwerty')
element = self.driver.find_element_by_name("Let's get started!")
element.click()
time.sleep(5)
```
When ever I am running it, I am always getting an error:
```
AttributeError: 'WebElement' object has no attribute 'set_value'
``` | 2015/01/07 | [
"https://Stackoverflow.com/questions/27821776",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4429165/"
] | To type a value into a WebElement, use the Selenium WebDriver method `send_keys`:
```
element = self.driver.find_element_by_class_name('android.widget.EditText')
element.send_keys('qwerty')
```
See the [Selenium Python Bindings documentation](http://selenium-python.readthedocs.org/en/latest/api.html?highlight=send_keys#selenium.webdriver.remote.webelement.WebElement.send_keys) for more details. | It's as simple as the error:
The type element is, has no set\_value(str) or setValue(str) method.
Maybe you meant
```
.setText('qwerty')?
```
Because there is no setText method in a EditText widget:
<http://developer.android.com/reference/android/widget/EditText.html> |
44,307,988 | I'm really new to python and trying to build a Hangman Game for practice.
I'm using Python 3.6.1
The User can enter a letter and I want to tell him if there is any occurrence of that letter in the word and where it is.
I get the total number of occurrences by using `occurrences = currentWord.count(guess)`
I have `firstLetterIndex = (currentWord.find(guess))`, to get the index.
Now I have the index of the first Letter, but what if the word has this letter multiple times?
I tried `secondLetterIndex = (currentWord.find(guess[firstLetterIndex, currentWordlength]))`, but that doesn't work.
Is there a better way to do this? Maybe a build in function i can't find? | 2017/06/01 | [
"https://Stackoverflow.com/questions/44307988",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7952215/"
] | One way to do this is to find the indices using list comprehension:
```
currentWord = "hello"
guess = "l"
occurrences = currentWord.count(guess)
indices = [i for i, a in enumerate(currentWord) if a == guess]
print indices
```
output:
```
[2, 3]
``` | I would maintain a second list of Booleans indicating which letters have been correctly matched.
```
>>> word_to_guess = "thicket"
>>> matched = [False for c in word_to_guess]
>>> for guess in "te":
... matched = [m or (guess == c) for m, c in zip(matched, word_to_guess)]
... print(list(zip(matched, word_to_guess)))
...
[(True, 't'), (False, 'h'), (False, 'i'), (False, 'c'), (False, 'k'), (False, 'e'), (True, 't')]
[(True, 't'), (False, 'h'), (False, 'i'), (False, 'c'), (False, 'k'), (True, 'e'), (True, 't')]
``` |
44,307,988 | I'm really new to python and trying to build a Hangman Game for practice.
I'm using Python 3.6.1
The User can enter a letter and I want to tell him if there is any occurrence of that letter in the word and where it is.
I get the total number of occurrences by using `occurrences = currentWord.count(guess)`
I have `firstLetterIndex = (currentWord.find(guess))`, to get the index.
Now I have the index of the first Letter, but what if the word has this letter multiple times?
I tried `secondLetterIndex = (currentWord.find(guess[firstLetterIndex, currentWordlength]))`, but that doesn't work.
Is there a better way to do this? Maybe a build in function i can't find? | 2017/06/01 | [
"https://Stackoverflow.com/questions/44307988",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7952215/"
] | One way to do this is to find the indices using list comprehension:
```
currentWord = "hello"
guess = "l"
occurrences = currentWord.count(guess)
indices = [i for i, a in enumerate(currentWord) if a == guess]
print indices
```
output:
```
[2, 3]
``` | ```
def findall(sub, s) :
pos = -1
hits=[]
while (pos := s.find(sub,pos+1)) > -1 :
hits.append(pos)
return hits
``` |
51,411,244 | I have the following dictionary:
```
equipment_element = {'equipment_name', [0,0,0,0,0,0,0]}
```
I can't figure out what is wrong with this list?
I'm trying to work backwards from this post [Python: TypeError: unhashable type: 'list'](https://stackoverflow.com/questions/13675296/python-typeerror-unhashable-type-list)
but my key is not a list, my value is.
What am I doing wrong? | 2018/07/18 | [
"https://Stackoverflow.com/questions/51411244",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/84885/"
] | It's not a dictionary, it's a set. | maybe you were looking for this syntax
```
equipment_element = {'equipment_name': [0,0,0,0,0,0,0]}
```
or
```
equipment_element = dict('equipment_name' = [0,0,0,0,0,0,0])
```
or
```
equipment_element = dict([('equipment_name', [0,0,0,0,0,0,0])])
```
This syntax is for creating a set:
```
equipment_element = {'equipment_name', [0,0,0,0,0,0,0]}
``` |
51,411,244 | I have the following dictionary:
```
equipment_element = {'equipment_name', [0,0,0,0,0,0,0]}
```
I can't figure out what is wrong with this list?
I'm trying to work backwards from this post [Python: TypeError: unhashable type: 'list'](https://stackoverflow.com/questions/13675296/python-typeerror-unhashable-type-list)
but my key is not a list, my value is.
What am I doing wrong? | 2018/07/18 | [
"https://Stackoverflow.com/questions/51411244",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/84885/"
] | You are trying to create set, not a dictionary
Modify it as follows. Replace the `,` in between to `:`
```
equipment_element = {'equipment_name': [0,0,0,0,0,0,0]}
``` | maybe you were looking for this syntax
```
equipment_element = {'equipment_name': [0,0,0,0,0,0,0]}
```
or
```
equipment_element = dict('equipment_name' = [0,0,0,0,0,0,0])
```
or
```
equipment_element = dict([('equipment_name', [0,0,0,0,0,0,0])])
```
This syntax is for creating a set:
```
equipment_element = {'equipment_name', [0,0,0,0,0,0,0]}
``` |
69,782,728 | I am trying to read an image URL from the internet and be able to get the image onto my machine via python, I used example used in this blog post <https://www.geeksforgeeks.org/how-to-open-an-image-from-the-url-in-pil/> which was <https://media.geeksforgeeks.org/wp-content/uploads/20210318103632/gfg-300x300.png>, however, when I try my own example it just doesn't seem to work I've tried the HTTP version and it still gives me the 403 error. Does anyone know what the cause could be?
```
import urllib.request
urllib.request.urlretrieve(
"http://image.prntscr.com/image/ynfpUXgaRmGPwj5YdZJmaw.png",
"gfg.png")
```
Output:
urllib.error.HTTPError: HTTP Error 403: Forbidden | 2021/10/30 | [
"https://Stackoverflow.com/questions/69782728",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16956765/"
] | The server at `prntscr.com` is actively rejecting your request. There are many reasons why that could be. Some sites will check for the user agent of the caller to make see if that's the case. In my case, I used [httpie](https://httpie.io/docs) to test if it would allow me to download through a non-browser app. It worked. So then I simply reused made up a user header to see if it's just the lack of user-agent.
```
import urllib.request
opener = urllib.request.build_opener()
opener.addheaders = [('User-Agent', 'MyApp/1.0')]
urllib.request.install_opener(opener)
urllib.request.urlretrieve(
"http://image.prntscr.com/image/ynfpUXgaRmGPwj5YdZJmaw.png",
"gfg.png")
```
It worked! Now I don't know what logic the server uses. For instance, I tried a standard `Mozilla/5.0` and that did not work. You won't always encounter this issue (most sites are pretty lax in what they allow as long as you are reasonable), but when you do, try playing with the user-agent. If nothing works, try using the same user-agent as your browser for instance. | I had the same problem and it was due to an expired URL. I checked the response text and I was getting "URL signature expired" which is a message you wouldn't normally see unless you checked the response text.
This means some URLs just expire, usually for security purposes. Try to get the URL again and update the URL in your script. If there isn't a new URL for the content you're trying to scrape, then unfortunately you can't scrape for it. |
3,757,738 | Ok say I have a string in python:
```
str="martin added 1 new photo to the <a href=''>martins photos</a> album."
```
*the string contains a lot more css/html in real world use*
What is the fastest way to change the 1 (`'1 new photo'`) to say `'2 new photos'`. of course later the `'1'` may say `'12'`.
Note, I don't know what the number is, so doing a replace is not acceptable.
I also need to change `'photo'` to `'photos'` but I can just do `a .replace(...)`.
Unless there is a neater, easier solution to modify both? | 2010/09/21 | [
"https://Stackoverflow.com/questions/3757738",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/258236/"
] | It sounds like this is what you want (although *why* is another question :^)
```
import re
def add_photos(s,n):
def helper(m):
num = int(m.group(1)) + n
plural = '' if num == 1 else 's'
return 'added %d new photo%s' % (num,plural)
return re.sub(r'added (\d+) new photo(s?)',helper,s)
s = "martin added 0 new photos to the <a href=''>martins photos</a> album."
s = add_photos(s,1)
print s
s = add_photos(s,5)
print s
s = add_photos(s,7)
print s
```
### Output
```
martin added 1 new photo to the <a href=''>martins photos</a> album.
martin added 6 new photos to the <a href=''>martins photos</a> album.
martin added 13 new photos to the <a href=''>martins photos</a> album.
``` | since you're not parsing html, just use an regular expression
```
import re
exp = "{0} added ([0-9]*) new photo".format(name)
number = int(re.findall(exp, strng)[0])
```
This assumes that you will always pass it a string with the number in it. If not, you'll get an `IndexError`.
I would store the number and the format string though, in addition to the formatted string. when the number changes, remake the format string and replace your stored copy of it. This will be much mo'bettah' then trying to parse a string to get the count.
In response to your question about the html mattering, I don't think so. You are not trying to extract information that the html is encoding so you are not parsing html with regular expressions. This is just a string as far as that concern goes. |
3,757,738 | Ok say I have a string in python:
```
str="martin added 1 new photo to the <a href=''>martins photos</a> album."
```
*the string contains a lot more css/html in real world use*
What is the fastest way to change the 1 (`'1 new photo'`) to say `'2 new photos'`. of course later the `'1'` may say `'12'`.
Note, I don't know what the number is, so doing a replace is not acceptable.
I also need to change `'photo'` to `'photos'` but I can just do `a .replace(...)`.
Unless there is a neater, easier solution to modify both? | 2010/09/21 | [
"https://Stackoverflow.com/questions/3757738",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/258236/"
] | It sounds like this is what you want (although *why* is another question :^)
```
import re
def add_photos(s,n):
def helper(m):
num = int(m.group(1)) + n
plural = '' if num == 1 else 's'
return 'added %d new photo%s' % (num,plural)
return re.sub(r'added (\d+) new photo(s?)',helper,s)
s = "martin added 0 new photos to the <a href=''>martins photos</a> album."
s = add_photos(s,1)
print s
s = add_photos(s,5)
print s
s = add_photos(s,7)
print s
```
### Output
```
martin added 1 new photo to the <a href=''>martins photos</a> album.
martin added 6 new photos to the <a href=''>martins photos</a> album.
martin added 13 new photos to the <a href=''>martins photos</a> album.
``` | **Update**
Never mind. From the comments it is evident that the OP's requirement is more complicated than it appears in the question. I don't think it can be solved by my answer.
**Original Answer**
You can convert the string to a template and store it. Use placeholders for the variables.
```
template = """%(user)s added %(count)s new %(l_object)s to the
<a href='%(url)s'>%(text)s</a> album."""
options = dict(user = "Martin", count = 1, l_object = 'photo',
url = url, text = "Martin's album")
print template % options
```
This expects the object of the sentence to be pluralized externally. If you want this logic (or more complex conditions) in your template(s) you should look at a templating engine such as [Jinja](http://jinja.pocoo.org/) or [Cheetah](http://www.cheetahtemplate.org/). |
70,884,314 | I'm trying to match all of the items in one list (list1) with some items in another list (list2).
```
list1 = ['r','g','g',]
list2 = ['r','g','r','g','g']
```
For each successive object in list1, I want to find all indices where that pattern shows up in list2:
Essentially, I'd hope the result to be something along the lines of:
"r is at indices 0,2 in list2"
"r,g is at indices, 1,3 in list2" (I only want to find the last index in the pattern)
"r,g,g is at index 4 in list2"
As for things I've tried:
Well... a lot.
The one that has gotten closest is this:
`print([x for x in list1 if x not in set(list2)])`
This doesn't work fr me because it doesn't look for a **group of objects**, it only tests for **one object** in list1 being in list2.
I don't really need the answer to be pythonic or even that fast. As long as it works!
Any help is greatly appreciated!
Thanks! | 2022/01/27 | [
"https://Stackoverflow.com/questions/70884314",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18050991/"
] | Here's an attempt:
```py
list1 = ['r','g','g']
list2 = ['r','g','r','g','g']
def inits(lst):
for i in range(1, len(lst) + 1):
yield lst[:i]
def rolling_windows(lst, length):
for i in range(len(lst) - length + 1):
yield lst[i:i+length]
for sublen, sublst in enumerate(inits(list1), start=1):
inds = [ind for ind, roll
in enumerate(rolling_windows(list2, sublen), start=sublen)
if roll == sublst]
print(f"{sublst} is in list2 at indices: {inds}")
# ['r'] is in list2 at indices: [1, 3]
# ['r', 'g'] is in list2 at indices: [2, 4]
# ['r', 'g', 'g'] is in list2 at indices: [5]
```
Basically, it generates relevant sublists using two functions (`inits` and `rolling_windows`) and then compare them. | Pure python solution which is going to be pretty slow for big lists:
```
def ind_of_sub_list_in_list(sub: list, main: list) -> list[int]:
indices: list[int] = []
for index_main in range(len(main) - len(sub) + 1):
for index_sub in range(len(sub)):
if main[index_main + index_sub] != sub[index_sub]:
break
else: # `sub` fits completely in `main`
indices.append(index_main)
return indices
list1 = ["r", "g", "g"]
list2 = ["r", "g", "g", "r", "g", "g"]
print(ind_of_sub_list_in_list(sub=list1, main=list2)) # [0, 3]
```
Naive implementation with two for loops that check entry by entry the two lists. |
70,884,314 | I'm trying to match all of the items in one list (list1) with some items in another list (list2).
```
list1 = ['r','g','g',]
list2 = ['r','g','r','g','g']
```
For each successive object in list1, I want to find all indices where that pattern shows up in list2:
Essentially, I'd hope the result to be something along the lines of:
"r is at indices 0,2 in list2"
"r,g is at indices, 1,3 in list2" (I only want to find the last index in the pattern)
"r,g,g is at index 4 in list2"
As for things I've tried:
Well... a lot.
The one that has gotten closest is this:
`print([x for x in list1 if x not in set(list2)])`
This doesn't work fr me because it doesn't look for a **group of objects**, it only tests for **one object** in list1 being in list2.
I don't really need the answer to be pythonic or even that fast. As long as it works!
Any help is greatly appreciated!
Thanks! | 2022/01/27 | [
"https://Stackoverflow.com/questions/70884314",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18050991/"
] | Here's an attempt:
```py
list1 = ['r','g','g']
list2 = ['r','g','r','g','g']
def inits(lst):
for i in range(1, len(lst) + 1):
yield lst[:i]
def rolling_windows(lst, length):
for i in range(len(lst) - length + 1):
yield lst[i:i+length]
for sublen, sublst in enumerate(inits(list1), start=1):
inds = [ind for ind, roll
in enumerate(rolling_windows(list2, sublen), start=sublen)
if roll == sublst]
print(f"{sublst} is in list2 at indices: {inds}")
# ['r'] is in list2 at indices: [1, 3]
# ['r', 'g'] is in list2 at indices: [2, 4]
# ['r', 'g', 'g'] is in list2 at indices: [5]
```
Basically, it generates relevant sublists using two functions (`inits` and `rolling_windows`) and then compare them. | Convert your list from which you need to match to string and then use regex and find all substring
```
import re
S1 = "".join(list2) #it will convert your list2 to string
sub_str = ""
for letter in list1:
sub_str+=letter
r=re.finditer(sub_str, S1)
for i in r:
print(sub_str , " found at ", i.start() + 1)
```
This will gives you starting index of the matched item |
70,884,314 | I'm trying to match all of the items in one list (list1) with some items in another list (list2).
```
list1 = ['r','g','g',]
list2 = ['r','g','r','g','g']
```
For each successive object in list1, I want to find all indices where that pattern shows up in list2:
Essentially, I'd hope the result to be something along the lines of:
"r is at indices 0,2 in list2"
"r,g is at indices, 1,3 in list2" (I only want to find the last index in the pattern)
"r,g,g is at index 4 in list2"
As for things I've tried:
Well... a lot.
The one that has gotten closest is this:
`print([x for x in list1 if x not in set(list2)])`
This doesn't work fr me because it doesn't look for a **group of objects**, it only tests for **one object** in list1 being in list2.
I don't really need the answer to be pythonic or even that fast. As long as it works!
Any help is greatly appreciated!
Thanks! | 2022/01/27 | [
"https://Stackoverflow.com/questions/70884314",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18050991/"
] | Here's an attempt:
```py
list1 = ['r','g','g']
list2 = ['r','g','r','g','g']
def inits(lst):
for i in range(1, len(lst) + 1):
yield lst[:i]
def rolling_windows(lst, length):
for i in range(len(lst) - length + 1):
yield lst[i:i+length]
for sublen, sublst in enumerate(inits(list1), start=1):
inds = [ind for ind, roll
in enumerate(rolling_windows(list2, sublen), start=sublen)
if roll == sublst]
print(f"{sublst} is in list2 at indices: {inds}")
# ['r'] is in list2 at indices: [1, 3]
# ['r', 'g'] is in list2 at indices: [2, 4]
# ['r', 'g', 'g'] is in list2 at indices: [5]
```
Basically, it generates relevant sublists using two functions (`inits` and `rolling_windows`) and then compare them. | If all entries in both lists are actually strings the solution can be simplified to:
```
list1 = ["r", "g", "g"]
list2 = ["r", "g", "g", "r", "g", "g"]
main = "".join(list2)
sub = "".join(list1)
indices = [index for index in range(len(main)) if main.startswith(sub, index)]
print(indices) # [0, 3]
```
We `join` both lists to a string and then use the `startswith` method to determine all indices. |
70,884,314 | I'm trying to match all of the items in one list (list1) with some items in another list (list2).
```
list1 = ['r','g','g',]
list2 = ['r','g','r','g','g']
```
For each successive object in list1, I want to find all indices where that pattern shows up in list2:
Essentially, I'd hope the result to be something along the lines of:
"r is at indices 0,2 in list2"
"r,g is at indices, 1,3 in list2" (I only want to find the last index in the pattern)
"r,g,g is at index 4 in list2"
As for things I've tried:
Well... a lot.
The one that has gotten closest is this:
`print([x for x in list1 if x not in set(list2)])`
This doesn't work fr me because it doesn't look for a **group of objects**, it only tests for **one object** in list1 being in list2.
I don't really need the answer to be pythonic or even that fast. As long as it works!
Any help is greatly appreciated!
Thanks! | 2022/01/27 | [
"https://Stackoverflow.com/questions/70884314",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18050991/"
] | This is quite an interesting question. Python has powerful **list indexing** methods, that allow you to efficiently make these comparisons. From a programming/maths perspective, what you are trying to do is compare **sublists** of a longer list with a pattern of your chosing. That can be implemented with:
```
# sample lists
pattern = [1,2,3]
mylist = [1,2,3,4,1,2,3,4,1,2,6,7,1,2,3]
# we want to check all elements of mylist
# we can stop len(pattern) elements before the end
for i in range(len(mylist)-len(pattern)):
# we generate a sublist of mylist, and we compare with list pattern
if mylist[i:i+len(pattern)]==pattern:
# we print the matches
print(i)
```
This code will print 0 and 4, the indexes where we have the [1,2,3] in mylist. | Pure python solution which is going to be pretty slow for big lists:
```
def ind_of_sub_list_in_list(sub: list, main: list) -> list[int]:
indices: list[int] = []
for index_main in range(len(main) - len(sub) + 1):
for index_sub in range(len(sub)):
if main[index_main + index_sub] != sub[index_sub]:
break
else: # `sub` fits completely in `main`
indices.append(index_main)
return indices
list1 = ["r", "g", "g"]
list2 = ["r", "g", "g", "r", "g", "g"]
print(ind_of_sub_list_in_list(sub=list1, main=list2)) # [0, 3]
```
Naive implementation with two for loops that check entry by entry the two lists. |
70,884,314 | I'm trying to match all of the items in one list (list1) with some items in another list (list2).
```
list1 = ['r','g','g',]
list2 = ['r','g','r','g','g']
```
For each successive object in list1, I want to find all indices where that pattern shows up in list2:
Essentially, I'd hope the result to be something along the lines of:
"r is at indices 0,2 in list2"
"r,g is at indices, 1,3 in list2" (I only want to find the last index in the pattern)
"r,g,g is at index 4 in list2"
As for things I've tried:
Well... a lot.
The one that has gotten closest is this:
`print([x for x in list1 if x not in set(list2)])`
This doesn't work fr me because it doesn't look for a **group of objects**, it only tests for **one object** in list1 being in list2.
I don't really need the answer to be pythonic or even that fast. As long as it works!
Any help is greatly appreciated!
Thanks! | 2022/01/27 | [
"https://Stackoverflow.com/questions/70884314",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18050991/"
] | This is quite an interesting question. Python has powerful **list indexing** methods, that allow you to efficiently make these comparisons. From a programming/maths perspective, what you are trying to do is compare **sublists** of a longer list with a pattern of your chosing. That can be implemented with:
```
# sample lists
pattern = [1,2,3]
mylist = [1,2,3,4,1,2,3,4,1,2,6,7,1,2,3]
# we want to check all elements of mylist
# we can stop len(pattern) elements before the end
for i in range(len(mylist)-len(pattern)):
# we generate a sublist of mylist, and we compare with list pattern
if mylist[i:i+len(pattern)]==pattern:
# we print the matches
print(i)
```
This code will print 0 and 4, the indexes where we have the [1,2,3] in mylist. | Convert your list from which you need to match to string and then use regex and find all substring
```
import re
S1 = "".join(list2) #it will convert your list2 to string
sub_str = ""
for letter in list1:
sub_str+=letter
r=re.finditer(sub_str, S1)
for i in r:
print(sub_str , " found at ", i.start() + 1)
```
This will gives you starting index of the matched item |
70,884,314 | I'm trying to match all of the items in one list (list1) with some items in another list (list2).
```
list1 = ['r','g','g',]
list2 = ['r','g','r','g','g']
```
For each successive object in list1, I want to find all indices where that pattern shows up in list2:
Essentially, I'd hope the result to be something along the lines of:
"r is at indices 0,2 in list2"
"r,g is at indices, 1,3 in list2" (I only want to find the last index in the pattern)
"r,g,g is at index 4 in list2"
As for things I've tried:
Well... a lot.
The one that has gotten closest is this:
`print([x for x in list1 if x not in set(list2)])`
This doesn't work fr me because it doesn't look for a **group of objects**, it only tests for **one object** in list1 being in list2.
I don't really need the answer to be pythonic or even that fast. As long as it works!
Any help is greatly appreciated!
Thanks! | 2022/01/27 | [
"https://Stackoverflow.com/questions/70884314",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18050991/"
] | This is quite an interesting question. Python has powerful **list indexing** methods, that allow you to efficiently make these comparisons. From a programming/maths perspective, what you are trying to do is compare **sublists** of a longer list with a pattern of your chosing. That can be implemented with:
```
# sample lists
pattern = [1,2,3]
mylist = [1,2,3,4,1,2,3,4,1,2,6,7,1,2,3]
# we want to check all elements of mylist
# we can stop len(pattern) elements before the end
for i in range(len(mylist)-len(pattern)):
# we generate a sublist of mylist, and we compare with list pattern
if mylist[i:i+len(pattern)]==pattern:
# we print the matches
print(i)
```
This code will print 0 and 4, the indexes where we have the [1,2,3] in mylist. | If all entries in both lists are actually strings the solution can be simplified to:
```
list1 = ["r", "g", "g"]
list2 = ["r", "g", "g", "r", "g", "g"]
main = "".join(list2)
sub = "".join(list1)
indices = [index for index in range(len(main)) if main.startswith(sub, index)]
print(indices) # [0, 3]
```
We `join` both lists to a string and then use the `startswith` method to determine all indices. |
1,454,941 | I Have run into a few examples of managing threads with the threading module (using Python 2.6).
What I am trying to understand is how is this example calling the "run" method and where. I do not see it anywhere. The ThreadUrl class gets instantiated in the main() function as "t" and this is where I would normally expect the code to start the "run" method.
Maybe this is not the preferred way of working with threads? Please enlighten me:
```
#!/usr/bin/env python
import Queue
import time
import urllib2
import threading
import datetime
hosts = ["http://example.com/", "http://www.google.com"]
queue = Queue.Queue()
class ThreadUrl(threading.Thread):
"""Threaded Url Grab"""
def __init__(self, queue):
threading.Thread.__init__(self)
self.queue = queue
def run(self):
while True:
#grabs host from queue
host = self.queue.get()
#grabs urls of hosts and prints first 1024 bytes of page
url = urllib2.urlopen(host)
print url.read(10)
#signals to queue job is done
self.queue.task_done()
start = time.time()
def main():
#spawn a pool of threads, and pass them queue instance
for i in range(1):
t = ThreadUrl(queue)
t.setDaemon(True)
t.start()
for host in hosts:
queue.put(host)
queue.join()
main()
print "Elapsed time: %s" % (time.time() - start)
``` | 2009/09/21 | [
"https://Stackoverflow.com/questions/1454941",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/89528/"
] | The method run() is called behind the scene by "threading.Thread" (Google inheritance and polymorphism concepts of OOP). The invocation will be done just after t.start() has called.
If you have an access to threading.py (find it in python folder). You will see a class name Thread. In that class, there is a method called "start()". start() called '\_start\_new\_thread(self.\_\_bootstrap, ())' a low-level thread start-up which will run a wrapper method called '\_\_bootstrap()' by a new thread. '\_\_bootstrap()', then, called '\_\_bootstrap\_inner()' which do some more preparation before, finally, call 'run()'.
Read the source, you can learn a lot. :D | `t.start()` creates a new thread in the OS and when this thread begins it will call the thread's `run()` method (or a different function if you provide a `target` in the `Thread` constructor) |
1,454,941 | I Have run into a few examples of managing threads with the threading module (using Python 2.6).
What I am trying to understand is how is this example calling the "run" method and where. I do not see it anywhere. The ThreadUrl class gets instantiated in the main() function as "t" and this is where I would normally expect the code to start the "run" method.
Maybe this is not the preferred way of working with threads? Please enlighten me:
```
#!/usr/bin/env python
import Queue
import time
import urllib2
import threading
import datetime
hosts = ["http://example.com/", "http://www.google.com"]
queue = Queue.Queue()
class ThreadUrl(threading.Thread):
"""Threaded Url Grab"""
def __init__(self, queue):
threading.Thread.__init__(self)
self.queue = queue
def run(self):
while True:
#grabs host from queue
host = self.queue.get()
#grabs urls of hosts and prints first 1024 bytes of page
url = urllib2.urlopen(host)
print url.read(10)
#signals to queue job is done
self.queue.task_done()
start = time.time()
def main():
#spawn a pool of threads, and pass them queue instance
for i in range(1):
t = ThreadUrl(queue)
t.setDaemon(True)
t.start()
for host in hosts:
queue.put(host)
queue.join()
main()
print "Elapsed time: %s" % (time.time() - start)
``` | 2009/09/21 | [
"https://Stackoverflow.com/questions/1454941",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/89528/"
] | Per the [pydoc](http://docs.python.org/library/threading.html#threading.Thread.start):
>
> `Thread.start()`
>
>
> Start the thread’s activity.
>
>
> It must be called at most once per thread object. It arranges for the
> object’s run() method to be invoked in
> a separate thread of control.
>
>
> This method will raise a RuntimeException if called more than
> once on the same thread object.
>
>
>
The way to think of python `Thread` objects is that they take some chunk of python code that is written synchronously (either in the `run` method or via the `target` argument) and wrap it up in C code that knows how to make it run asynchronously. The beauty of this is that you get to treat `start` like an opaque method: you don't have any business overriding it unless you're rewriting the class in C, but you get to treat `run` very concretely. This can be useful if, for example, you want to test your thread's logic synchronously. All you need is to call `t.run()` and it will execute just as any other method would. | The method run() is called behind the scene by "threading.Thread" (Google inheritance and polymorphism concepts of OOP). The invocation will be done just after t.start() has called.
If you have an access to threading.py (find it in python folder). You will see a class name Thread. In that class, there is a method called "start()". start() called '\_start\_new\_thread(self.\_\_bootstrap, ())' a low-level thread start-up which will run a wrapper method called '\_\_bootstrap()' by a new thread. '\_\_bootstrap()', then, called '\_\_bootstrap\_inner()' which do some more preparation before, finally, call 'run()'.
Read the source, you can learn a lot. :D |
1,454,941 | I Have run into a few examples of managing threads with the threading module (using Python 2.6).
What I am trying to understand is how is this example calling the "run" method and where. I do not see it anywhere. The ThreadUrl class gets instantiated in the main() function as "t" and this is where I would normally expect the code to start the "run" method.
Maybe this is not the preferred way of working with threads? Please enlighten me:
```
#!/usr/bin/env python
import Queue
import time
import urllib2
import threading
import datetime
hosts = ["http://example.com/", "http://www.google.com"]
queue = Queue.Queue()
class ThreadUrl(threading.Thread):
"""Threaded Url Grab"""
def __init__(self, queue):
threading.Thread.__init__(self)
self.queue = queue
def run(self):
while True:
#grabs host from queue
host = self.queue.get()
#grabs urls of hosts and prints first 1024 bytes of page
url = urllib2.urlopen(host)
print url.read(10)
#signals to queue job is done
self.queue.task_done()
start = time.time()
def main():
#spawn a pool of threads, and pass them queue instance
for i in range(1):
t = ThreadUrl(queue)
t.setDaemon(True)
t.start()
for host in hosts:
queue.put(host)
queue.join()
main()
print "Elapsed time: %s" % (time.time() - start)
``` | 2009/09/21 | [
"https://Stackoverflow.com/questions/1454941",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/89528/"
] | Per the [pydoc](http://docs.python.org/library/threading.html#threading.Thread.start):
>
> `Thread.start()`
>
>
> Start the thread’s activity.
>
>
> It must be called at most once per thread object. It arranges for the
> object’s run() method to be invoked in
> a separate thread of control.
>
>
> This method will raise a RuntimeException if called more than
> once on the same thread object.
>
>
>
The way to think of python `Thread` objects is that they take some chunk of python code that is written synchronously (either in the `run` method or via the `target` argument) and wrap it up in C code that knows how to make it run asynchronously. The beauty of this is that you get to treat `start` like an opaque method: you don't have any business overriding it unless you're rewriting the class in C, but you get to treat `run` very concretely. This can be useful if, for example, you want to test your thread's logic synchronously. All you need is to call `t.run()` and it will execute just as any other method would. | `t.start()` creates a new thread in the OS and when this thread begins it will call the thread's `run()` method (or a different function if you provide a `target` in the `Thread` constructor) |
55,508,028 | I'm trying to use the ocr method from computer visio to extract all the text from a specific image. Nevertheless it doesn't return the info I know which is there, because when I analize the image directly in the available option in this page <https://azure.microsoft.com/es-es/services/cognitive-services/computer-vision/>, it does return the data.
This is the image im traying to get the data from
<https://bitbucket.org/miguel_acevedo_ve/python-stream/raw/086279ad6885a490e521785ba288914ed98cfd1d/test.jpg>
I have followed all the python tutorial available in the azure documentation site.
```
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle
from PIL import Image
from io import BytesIO
subscription_key = "<Subscription Key>"
assert subscription_key
vision_base_url = "https://westcentralus.api.cognitive.microsoft.com/vision/v2.0/"
ocr_url = vision_base_url + "ocr"
image_url = "https://bitbucket.org/miguel_acevedo_ve/python-stream/raw/086279ad6885a490e521785ba288914ed98cfd1d/test.jpg"
'''image_url = "https://upload.wikimedia.org/wikipedia/commons/thumb/a/af/" + \
"Atomist_quote_from_Democritus.png/338px-Atomist_quote_from_Democritus.png"
'''
headers = {'Ocp-Apim-Subscription-Key': subscription_key}
params = {'mode' : 'Printed'}
data = {'url': image_url}
response = requests.post(ocr_url, headers=headers, params=params, json=data)
response.raise_for_status()
analysis = response.json()
print(analysis)
```
and this is my current output:
```
{u'regions': [], u'textAngle': 0.0, u'orientation': u'NotDetected', u'language': u'unk'}
```
UPDATE: The solution is to use recognizeText not the ocr function from computer visio. | 2019/04/04 | [
"https://Stackoverflow.com/questions/55508028",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11309249/"
] | I'll try to describe my thought process so you can follow. This function fits the pattern of creating an output list (here a string) from an input seed (here a string) by repeated function application (here dropping some elements). Thus I choose an implementation with `Data.List.unfoldr`.
```
unfoldr :: (b -> Maybe (a, b)) -> b -> [a]
```
Okay so, I need to turn the seed `b` into (`Maybe`) an output `a` and the rest of the string. I'll call this subfunction `f` and pass it into `unfoldr`.
```
printing s n = unfoldr f s
where f b = case drop n b of
[] -> Nothing
(x:xs) -> Just (x,xs)
```
It turns out that attempting to take the head off the front of the list and returning a `Maybe` is also a common pattern. It's `Data.List.uncons`, so
```
printing s n = unfoldr (uncons . drop n) s
```
Very smooth! So I test it out, and the output is wrong! Your specified output actually eg. for `n=2` selects every 2nd character, ie. drops `(n-1)` characters.
```
printing s n = unfoldr (uncons . drop (n-1)) s
```
I test it again and it matches the desired output. Phew! | To demonstrate the Haskell language some alternative solutions to the accepted answer.
Using **list comprehension**:
```
printing :: Int -> String -> String
printing j ls = [s | (i, s) <- zip [1 .. ] ls, mod i j == 0]
```
Using **recursion**:
```
printing' :: Int -> String -> String
printing' n ls
| null ls' = []
| otherwise = x : printing' n xs
where
ls' = drop (n - 1) ls
(x : xs) = ls'
```
In both cases I flipped the arguments so it is easier to do partial application: `printing 5` for example is a new function and will give each 5th character when applied to a string.
Note with a minor modification they will work for any list
```
takeEvery :: Int -> [a] -> [a]
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.