qid
int64
46k
74.7M
question
stringlengths
54
37.8k
date
stringlengths
10
10
metadata
listlengths
3
3
response_j
stringlengths
17
26k
response_k
stringlengths
26
26k
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 ev...
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...
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 ev...
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...
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 `d...
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 fro...
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 ...
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 ...
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 ...
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; ```...
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...
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; ```...
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...
``` 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; ```...
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...
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, ...
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 ...
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 cxFr...
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() ...
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]...
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 th...
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() ...
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 re...
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 th...
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 coun...
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,...
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 coun...
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,...
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)`...
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 coun...
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,...
**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...
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 coun...
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)`...
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 coun...
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...
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 wh...
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 garble...
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(), B...
52,753,613
I have a dataframe say `df`. `df` has a column `'Ages'` `>>> df['Age']` [![Age Data](https://i.stack.imgur.com/pcs2l.png)](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 =...
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['AgeG...
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],"</t...
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...
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...
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],"</t...
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...
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...
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],"</t...
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...
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...
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],"</t...
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...
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 l...
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],"</t...
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 l...
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...
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(): ...
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: [![enter image description here](https://i.stack.imgur.com/O2INd.p...
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...
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 ...
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...
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 ...
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("defau...
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 ...
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...
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 ...
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("defau...
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...
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 ...
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("defau...
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 `...
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: ``` ...
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. Subtrac...
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 dic...
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 under...
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 qu...
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 dic...
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 under...
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 dic...
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 under...
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 m...
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 m...
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 m...
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=...
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"); documen...
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 j...
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)....
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 j...
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('confi...
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 com...
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.m...
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,...
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...
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.m...
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,...
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.m...
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...
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 (answe...
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 < rando...
**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 = rando...
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) # ...
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) # ...
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 (i...
``` 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) # ...
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 (i...
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 th...
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: ...
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 th...
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 th...
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: rais...
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 th...
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: ...
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 th...
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: ...
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: rais...
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() ...
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(se...
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() ...
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/7...
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() ...
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() ...
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(se...
@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/7...
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() ...
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(se...
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() ...
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/7...
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 ...
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 + message...
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...
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...
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:/...
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...
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:/...
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...
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...
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:/...
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...
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:/...
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 laye...
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...
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,...
`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...
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,...
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 f...
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 f...
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 d...
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 ...
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"...
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 d...
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 ...
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 poin...
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 with...
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 w...
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 != ne...
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 w...
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 err...
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 w...
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 err...
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_file...
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 w...
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_file...
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...
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 w...
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 t...
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 w...
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 t...
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...
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 w...
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_file...
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 w...
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 err...
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...
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 w...
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 != ne...
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...
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 w...
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 err...
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 t...
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.co...
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_k...
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 hav...
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)...
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 hav...
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-lis...
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 = {...
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-lis...
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 = {...
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>, howev...
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 work...
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 ...
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 ...
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...
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 fo...
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 ...
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...
**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...
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 ...
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): ...
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...
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 ...
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): ...
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()...
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 ...
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): ...
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...
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 ...
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...
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...
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 ...
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...
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()...
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 ...
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...
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...
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 exp...
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 call...
`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 exp...
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 ...
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 call...
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 exp...
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 ...
`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...
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...
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'...