Unnamed: 0
int64 0
1.91M
| id
int64 337
73.8M
| title
stringlengths 10
150
| question
stringlengths 21
64.2k
| answer
stringlengths 19
59.4k
| tags
stringlengths 5
112
| score
int64 -10
17.3k
|
---|---|---|---|---|---|---|
1,908,600 | 63,350,626 |
Is there a reason why I'm getting a BadRequestKeyError when retrieving POST data from a form?
|
<p>Hello this is a flask app and I'm unable to insert into the database using this code and template.</p>
<p>The error I am receiving is</p>
<pre><code>2020-08-11 02:15:17,851: werkzeug.exceptions.BadRequestKeyError: 400 Bad Request: The browser (or proxy) sent a request that this server could not understand.
</code></pre>
<p>flask_app.py:</p>
<pre><code>@app.route('/submission', methods=['GET', 'POST'])
def do_submission() -> 'html':
@copy_current_request_context
def log_request(req: 'flask_request', res: str) -> None:
sleep(1)
with UseDatabase(app.config['dbconfig']) as cursor:
_SQL = """insert into client
(email, phonenumber)
values
(%s, %s)"""
cursor.execute(_SQL, (req.form['useremail'],
req.form['phone'],))
results = ""
try:
t = Thread(target=log_request, args=(request, results))
t.start()
except Exception as err:
print('***** Logging failed with this error:', str(err))
return render_template('index.html',)
</code></pre>
<p>index.html:</p>
<pre><code> <form method='POST' action='/submission'>
<table>
<p>Use this form to submit a search request:</p>
<tr><td>Email:</td><td><input name='useremail' type='EMAIL' width='60'></td></tr>
<tr><td>Phone number:</td><td><input name='phone' type='TEXT' value='12505555555'></td></tr>
</table>
<p>When you're ready, click this button:</p>
<p><input value='Do it!' type='SUBMIT'></p>
</form>
</code></pre>
<p>DBcm.py</p>
<p>I suppose I should have added this code too. Here is the missing code below: I really can't figure out why this isn't working. It seems like it is totally ok.</p>
<pre><code># Context manager for connecting/disconnecting to a database.
import mysql.connector
class SQLError(Exception):
"""Raised if the query caused problems."""
pass
class UseDatabase:
def __init__(self, config: dict):
self.configuration = config
def __enter__(self) -> 'cursor':
try:
self.conn = mysql.connector.connect(**self.configuration)
self.cursor = self.conn.cursor()
return self.cursor
except mysql.connector.errors.InterfaceError as err:
raise ConnectionError(err) from err
except mysql.connector.errors.ProgrammingError as err:
raise CredentialsError(err) from err
def __exit__(self, exc_type, exc_value, exc_traceback):
self.conn.commit()
self.cursor.close()
self.conn.close()
if exc_type is mysql.connector.errors.ProgrammingError:
raise SQLError(exc_value)
elif exc_type:
raise exc_type(exc_value)
</code></pre>
|
<p><strong>What does the error mean?</strong></p>
<p>See, there is the word <code>BadRequestKeyError</code> which means that you are trying to access data using a key that <strong>doesn't exist</strong>.</p>
<p><strong>Why this error?</strong></p>
<p>This error happens generally when there is a mismatch between the names you have provided in the input fields and the names using which you are trying to get the values from the request object. In your case, when you are starting the server and when the <code>log_request</code> method is called, you are trying to access <code>useremail</code> and <code>phone</code> from an empty request object as no <code>POST</code> request happened yet. As the request object is empty, so these keys <strong>don't exist</strong>.</p>
<p><strong>How to solve this error?</strong></p>
<p>So, we need to check if the request object is empty or not. Now, the request object might be empty, but make sure that the <code>log_request</code> method gets called only when there is <code>POST</code> request. There are different edge cases which you need to handle but I am assuming that the request object will not be empty if it is coming as <code>POST</code> request.</p>
<pre class="lang-py prettyprint-override"><code>@app.route('/submission', methods=['GET', 'POST'])
def do_submission() -> 'html':
if request.method == 'POST':
@copy_current_request_context
def log_request(req: 'flask_request', res: str) -> None:
sleep(1)
with UseDatabase(app.config['dbconfig']) as cursor:
_SQL = """insert into client
(email, phonenumber)
values
(%s, %s)"""
cursor.execute(_SQL, (req.form['useremail'],
req.form['phone']))
# rest of the logic
results = ""
try:
t = Thread(target=log_request, args=(request, results))
t.start()
except Exception as err:
print('***** Logging failed with this error:', str(err))
else:
return render_template('index.html')
</code></pre>
<p><strong>Recommendation</strong></p>
<p>However, I will highly recommend you not to use <code>Thread</code> for such a simple application. It is too much overkill for a simple task.</p>
|
python|html|flask
| 1 |
1,908,601 | 56,632,419 |
How to deserialize/serialize byte array to structure in python?
|
<p>I have this code in C#:</p>
<p>Structure:</p>
<pre><code>[StructLayout(LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Ansi, Size = 116)]
public struct pLogin
{
public pHeader _header;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 12)]
public string senha;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 12)]
public string login;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)]
public byte[] unk1;
public int algo1;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 42)]
public byte[] unk2;
public short algo2;
//versao do cliente
public ushort cliver;
public ushort unk3;
public int umBool;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)]
public byte[] mac;
}
[StructLayout(LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Ansi, Size = 12)]
public struct pHeader
{
public ushort size;
public byte key;
public byte checksum;
public ushort packetId;
public ushort clientId;
public uint timestamp;
}
</code></pre>
<p>Login Func:</p>
<pre><code>pLogin pLogin;
public void iniciarLogin(string login, string senha, int cliver, string p_mac = "")
{
pLogin = new pLogin();
pLogin._header = buildHeader(0x20D, 116);
pLogin.senha = senha;
pLogin.login = login;
pLogin.cliver = (ushort)cliver;
pLogin.umBool = 1;
pLogin.algo1 = 132;
pLogin.algo2 = 152;
if (p_mac.Length == 0)
{
pLogin.mac = Encoding.ASCII.GetBytes(Functions.RandomString(16));
}
else
{
pLogin.mac = Functions.StringToByteArray(p_mac);
}
byte[] buffer = BufferConverter.StructureToBuffer<pLogin>(pLogin);
EncDec.Encrypt(ref buffer);
socket.Send(BufferConverter.StringToByteArray("11F3111F"));
socket.Send(buffer);
logger.Text += "[Cliente] Solicitando login...\n";
}
pHeader packetHeader;
private pHeader buildHeader(int _packetID, int size)
{
packetHeader = new pHeader();
packetHeader.size = (ushort)size;
packetHeader.key = EncDec.GetHashByte();
packetHeader.checksum = 0;
packetHeader.packetId = (ushort)_packetID;
packetHeader.clientId = (ushort)serverData.playerMob.Mob.ClientId;
packetHeader.timestamp = getCurrentTime();
return packetHeader;
}
</code></pre>
<p>Now the buffer converter class:</p>
<pre><code>public static Byte[] StructureToBuffer<T>(T structure)
{
Byte[] buffer = new Byte[Marshal.SizeOf(typeof(T))];
unsafe
{
fixed (byte* pBuffer = buffer)
{
Marshal.StructureToPtr(structure, new IntPtr((void*)pBuffer), true);
}
}
return buffer;
}
public static T BufferToStructure<T>(Byte[] buffer, Int32 offset)
{
unsafe
{
fixed (Byte* pBuffer = buffer)
{
return (T)Marshal.PtrToStructure(new IntPtr((void*)&pBuffer[offset]), typeof(T));
}
}
}
</code></pre>
<p>The code abocve create a byte array with a login data, from a structure.
Is there a way to do serialize/deserialize a buffer array in python? <code>-</code>
I have no idea how to do it in python, since I don't see a lot of articles dealing with byte array stuff.</p>
|
<p>There's a couple ways, sure.</p>
<p>There's the <a href="https://docs.python.org/3/library/struct.html" rel="nofollow noreferrer">built-in <code>struct</code> module</a>, which requires a little bit of manual work to figure out the format string for your structures.</p>
<p>You can also use a higher-level 3rd party library such as <a href="https://construct.readthedocs.io/en/latest/" rel="nofollow noreferrer"><code>construct</code></a> (which I can recommend).</p>
<p>With Construct, your structures might look something like</p>
<pre><code>Header = Struct(
'size' / Int16ub,
'key' / Int8ub,
'checksum' / Int8ub,
'packetId' / Int16ub,
'clientId' / Int16ub,
'timestamp' / Int32ub,
)
Login = Struct(
"header" / Header,
# ...
)
</code></pre>
<p>– a fairly straightforward translation of the C# originals, and given a buffer of data, you can then just do something like </p>
<pre class="lang-py prettyprint-override"><code>login_data = Login.parse(buffer)
</code></pre>
|
c#|python|python-3.x
| 1 |
1,908,602 | 66,084,843 |
How to signify that the bot is offline by using the discord bot
|
<p>I am building a discord bot thats written in Python, and I just need to know how to let the server know the bot is offline by using the bot. Kinda like this: the bot sends a message to the general channel saying the bot is offline, then it shuts off. This is what I have for code:</p>
<pre><code>@client.event
async def on_disconnect():
general_channel = client.get_channel(general_channel_id)
await general_channel.send('Discord protection bot is offline...')
</code></pre>
<p>I have tried looking up how to do this, but I can't find anything. Please help me.</p>
|
<p>It's really not possible, logically if you think about it, the code does not know its going to be shut down and would not be able to call a function prior to a shutdown.</p>
<p>Unless you shutdown your bot within the code itself, but operations you want to complete must be handled before the bot logs out/shutdown.</p>
<pre><code>@client.command()
async def shutdown(ctx):
await ctx.send("Discord protection bot is offline...")
await client.logout()
</code></pre>
<p>From that the bot also cannot start up itself even after a set amount of time, unless you re-run the terminal</p>
|
python|discord|bots|discord.py
| 1 |
1,908,603 | 68,111,985 |
Can pip install first search wheel in a specified local dir and then the pypi?
|
<p>Can pip install first search wheel in a specified local dir and then the pypi?</p>
<p>If the specified local dir doesn't contain the want wheel, it will search the pypi.</p>
<p>Especially when use <code>pip install -r requirements.txt</code> command.</p>
|
<p>Sure is. Add</p>
<pre><code>--find-links some/local/directory/with/wheels
</code></pre>
<p>to the command line.</p>
<p>If you also add <code>--no-index</code>, it won't consult the online index.</p>
<p>If that doesn't work for you, try</p>
<pre><code>--index-url=/some/local/directory --extra-index-url=https://pypi.org/simple
</code></pre>
<p>instead.</p>
|
python|pip
| 3 |
1,908,604 | 59,318,935 |
How does gensim.models.FatText.wv.wmdistance calculate between two documents?
|
<p>I already have a training model for fastText with gensim, and<br>
I can get the distance between two sentence as described below, </p>
<pre><code>sentence_1 = "Today is very cold."
sentence_2 = "I'd like something to drink."
print(model.wv.wmdistance(sentence_1.split(" "), sentence_2.split(" ")))
# 0.8446287678977793 # for example
</code></pre>
<p>but how does <code>vmdistance</code> calculate this value?<br>
I'd like to know the formula. </p>
<p>API documents: <a href="https://radimrehurek.com/gensim/models/keyedvectors.html#gensim.models.keyedvectors.Doc2VecKeyedVectors.distance" rel="nofollow noreferrer">https://radimrehurek.com/gensim/models/keyedvectors.html#gensim.models.keyedvectors.Doc2VecKeyedVectors.distance</a></p>
|
<p>The <code>wmdistance()</code> function calculates the "Word Mover's Distance" between two sets-of-words. </p>
<p>You can view the academic paper which coined the "Word Mover's Distance" (WMD) measure, via the application of an older idea from operations research called "Earth Mover's Distance" to text, at:</p>
<p><a href="http://proceedings.mlr.press/v37/kusnerb15.pdf" rel="nofollow noreferrer">From Word Embeddings To Document Distances</a>, by Matt Kusner et al</p>
<p>You can view the exact code used by gensim's <code>wmdistance()</code> function at:</p>
<p><a href="https://github.com/RaRe-Technologies/gensim/blob/de0dcc39fee0ae4eaf45d79bd5418d32780f9aa5/gensim/models/keyedvectors.py#L677" rel="nofollow noreferrer">https://github.com/RaRe-Technologies/gensim/blob/de0dcc39fee0ae4eaf45d79bd5418d32780f9aa5/gensim/models/keyedvectors.py#L677</a></p>
<p>WMD is fairly time-consuming to calculate, as it involves a search through many possible "shifts" of the "piles of meaning" for a minimal-expenditure approach. It becomes especially time-consuming as the texts become longer. (It's more practical for short sentences than full paragraphs or documents.)</p>
<p>Often texts are instead summarized into a single vectors – via either an averaging of their word-vectors, or a shallow text-to-vector algorithm like <code>Doc2Vec</code>, or a deep-learning model (BERT, ELMo, etc). Then those single vectors can be far more quickly compared via simple cosine-similarity. (That's what the plain <code>similarity()</code> or <code>distance()</code> methods of gensim's vector models do.)</p>
|
python-3.x|gensim|fasttext
| 2 |
1,908,605 | 59,048,042 |
TypeError: unsupported operand type(s) for -: 'generator' and 'NoneType'
|
<p>When trying to do a simple substraction Python gives me a typererror : TypeError: unsupported operand type(s) for -: 'generator' and 'NoneType'. In my idea the 2 sides are just numbers, so I do not understand the problem really. This is my code</p>
<pre><code>m.addConstr(sum(x[i,j,t] for i in sub_nodes[z] for j in sub_nodes[z] if j>i) <=
sum(y[i,t] for i in sub_nodes[z]) - max([y[k,t] for k in sub_nodes[z]])
for z in range(len(sub_nodes))
for t in periods)
</code></pre>
<p>It is about the minus in the second line. I am using the Gurobi solver. Has anyone an idea on how to make this code work?</p>
|
<p>I believe your code should be <code>m.addConstrs</code> instead of <code>m.addConstr</code> (notice the <strong>s</strong> in "addConstr<strong>s</strong>").</p>
<p>This is because you're attempting to use a summation.</p>
|
python|gurobi
| 2 |
1,908,606 | 72,992,099 |
Calculate Subway time
|
<p>There is a question I'm trying to answer and I have a problem with final outputs.</p>
<p>question:</p>
<p>The names of all stations in this file are in 7 lines. in line, the names of the line stations Metro has come in order and with space. (Note that the name of a station does not contain a space character .)</p>
<p>The train travel time between two stations is 2 minutes
The time required to enter the station where we intend to board the train, 17 minutes
It takes 12 minutes to get out of the station where we are going to walk.
The time we need to change the line is also 10 minutes.
Note that at stations where two lines cross, you can board through both lines and you don't need to wait to change lines.</p>
<p>Mohsen wants not to make his own purchases from Digikala and go shopping by metro. After routing, he understood that he should go from the stations set on the subway and get to the station getting off.</p>
<p>We want you to write a program that calculates the minimum time it takes for Mohsen to reach the shopping place.</p>
<p>file:</p>
<pre><code>Tajrish Gheytariyeh Shahid_Sadr Gholhak Doctor_Shari'ati Mirdamad Shahid_Haghani Shahid_Hemmat Mosalla-ye_Emam_Khomeini Shahid_Beheshti Shahid_Mofatteh Shohada-ye_Haftom-e_Tir Taleghani Darvazeh_Dowlat Sa'di Emam_Khomeini Panzdah-e_Khordad Khayyam Meydan-e_Mohammadiyeh Shoush Payaneh_Jonoub Shahid_Bokharaei Ali_Abad Javanmard-e_Ghassab Shahr-e_Rey Palayeshgah Shahed-Bagher_Shahr Haram-e_Motahhar-e_Emam_Khomeini Kahrizak
Farhangsara Tehranpars Shahid_Bagheri Daneshgah-e_Elm-o_San'at Sarsabz Janbazan Fadak Sabalan Shahid_Madani Emam_Hossein Darvazeh_Shemiran Baharestan Mellat Emam_Khomeini Hasan_Abad Daneshgah-e_Emam_Ali Meydan-e_Hor Shahid_Navab-e_Safavi Shademan Daneshgah-e_Sharif Tarasht Tehran_Sadeghiyeh
Gha'em Shahid_Mahallati Aghdasiyeh Nobonyad Hossein_Abad Meydan-e_Heravi Shahid_Zeynoddin Khajeh_Abdollah-e_Ansari Shahid_sayyad-e_Shirazi Shahid_Ghodousi Sohrevardi Shahid_Beheshti Mirza-ye_Shirazi Meydan-e_Jahad Meydan-e_Hazrat-e_Vali_Asr Teatr-e_Shahr Moniriyeh Mahdiyeh Rahahan Javadiyeh Zamzam Shahrak-e_Shari'ati Abdol_Abad Ne'mat_Abad Azadegan
Shahid_Kolahdouz Nirou_Havaei Nabard Pirouzi Ebn-e_Sina Meydan-e_Shohada Darvazeh_Shemiran Darvazeh_Dowlat Ferdowsi Teatr-e_Shahr Meydan-e_Enghelab-e_Eslami Towhid Shademan Doctor_Habibollah Ostad_Mo'in Meydan-e_Azadi Bimeh Shahrk-e_Ekbatan Eram-e_Sabz
Shahid_Sepahbod_Qasem_Soleimani Golshahr Mohammad_Shahr Karaj Atmosfer Garmdarreh Vardavard Iran_Khodro Chitgar Varzeshgah-e_Azadi Eram-e_Sabz Tehran_Sadeghiyeh
Shahid_Sattari Shahid_Ashrafi_Esfahani Yadegar-e_Emam Marzdaran Shahrak-e_Azmayesh Daneshgah-e_Tarbiat_Modarres Meydan-e_Hazrat-e_Vali_Asr Shohada-ye_Haftom-e_Tir Emam_Hossein Meydan-e_Shohada Amir_Kabir Shahid_Rezaei Be'sat Kiyan_Shahr Dowlat_Abad
Meydan-e_San'at Borj-e_Milad-e_Tehran Boostan-e_Goftegou Daneshgah-e_Tarbiat_Modarres Modafean-e_Salamat Towhid Shahid_Navab-e_Safavi Roudaki Komeyl Beryanak Helal_Ahmar Mahdiyeh Meydan-e_Mohammadiyeh Mowlavi Meydan-e_Ghiyam Chehel_Tan-e_Doulab Ahang Basij
</code></pre>
<p>here is what I've done so far:</p>
<pre><code># tmp = []
results = []
def find_in_list_of_list(mylist, char):
for sub_list in mylist:
if char in sub_list:
return [mylist.index(sub_list), sub_list.index(char)]
raise ValueError("'{char}' is not in list".format(char=char))
with open("metro.txt", "r") as file:
lines = [line.split(" ") for line in file.read().split("\n")]
for i in range(int(input())):
destination = input().split(" ")
for line in lines:
if destination[0] in line and destination[1] in line:
start = line.index(destination[0])
stop = line.index(destination[1])
time = (stop - start) * 2
results.append(17 + 12 + time)
elif destination[0] in line and destination[1] not in line:
start = line.index(destination[0])
stop = len(line)
line1 = lines.index(line)
line2 = find_in_list_of_list(lines, destination[1])
# tmp.append(line2[1])
# tmp.append(stop)
# tmp.append(start)
time = (stop - line2[1])
results.append(17 + 12 + time + 10)
else:
continue
# print(tmp)
for item in results:
print(item)
</code></pre>
<p>my output which is wrong:</p>
<pre><code>31
35
43
45
47
46
</code></pre>
<p>sample input:</p>
<pre><code>5
Tajrish Gheytariyeh
Tajrish Gholhak
Tarasht Eram-e_Sabz
Aghdasiyeh Sohrevardi
Towhid Baharestan
</code></pre>
<p>sample output:</p>
<pre><code>31
35
43
45
51
</code></pre>
<p>description:</p>
<p>The first trip from "Tajrish" to "Qaytaria":</p>
<p>It takes 17 minutes to enter and board the train at Tajrish station.
It takes 2 minutes to reach Qaitariya from "Tajrish" station on line 1.
It takes 12 minutes to get out of "Qaytarieh" station.
Therefore, the total time of this trip is equal to:
17 + 2 + 12 = 31</p>
<p>The second trip from "Tajrish" to "Gholhak":</p>
<p>It takes 17 minutes to enter and board the train at Tajrish station.
It takes 6 minutes to reach "Ghalhak" from "Tajrish" station on line 1.
It takes 12 minutes to leave the "Ghalhak" station.
Therefore, the total time of this trip is equal to:
17 + 6 + 12 = 35</p>
<p>The third journey from "Tarsh" to "Eram Sabz":</p>
<p>It takes 17 minutes to enter and board the train at "Tarsh" station.
It takes 2 minutes to reach "Tehran (Sadeghie)" from "Taresh" station on line 2.
It takes 10 minutes to change direction from line 2 to 5 at "Tehran (Sadegh)" station.
It takes 2 minutes to reach "Eram Sabz" from "Tehran (Sadeghie)" station on line 5.
It takes 12 minutes to leave "Eram Sabz" station.
Therefore, the total time of this trip is equal to:
17 + 2 + 10 + 2 + 12 = 43</p>
<p>The fourth journey from "Aghdiseh" to "Sohrvardi":</p>
<p>It takes 17 minutes to enter and board the train at "Aqdasiyeh" station.
It takes 16 minutes to reach "Sohrvardi" from "Aqdasiyeh" station on line 3.
It takes 12 minutes to get out of "Sohrvardi" station.
Therefore, the total time of this trip is equal to:
17 + 16 + 12 = 45</p>
<p>The fifth journey from "Tawheed" to "Baharistan":</p>
<p>It takes 17 minutes to enter and board the train at "Tawheed" station.
It takes 10 minutes to reach "Darvaze Shemiran" from "Tawheed" station on line 4.
It takes 10 minutes to change direction from line 4 to line 2 at "Darvaze Shemiran" station.
It takes 2 minutes to reach "Baharistan" from "Darvaze Shemiran" station on line 5.
It takes 12 minutes to leave "Baharistan" station.
Therefore, the total time of this trip is equal to:
17 + 10 + 10 + 2 + 12 = 51</p>
|
<p>I couldn't find where error exactly is in your code, however I figured rewriting your code could help.</p>
<pre class="lang-py prettyprint-override"><code>results = []
with open("metro.txt", "r") as file:
lines = [line.split(" ") for line in file.read().split("\n")]
for i in range(int(input())):
destination = input().split(" ")
for index, line in enumerate(lines):
if destination[0] in line:
# start is a tuple - (index of line in lines, index of station in line)
start = (index, line.index(destination[0]))
if destination[1] in line:
stop = (index, line.index(destination[0]))
# This else is useless, when we are at the end of a for block,
# we are automatically calling continue
# else:
# continue
# Calculate travel time and append it to results here, right after the for loop
for item in results:
print(item)
</code></pre>
<p>We now know where are the stations exactly in <strong>lines</strong> (you can acess stations like this: <code>lines[start[0]][start[1]]</code>). In my opinion now it will be easier to calculate the distances and you don't need <code>find_in_list_of_list(mylist, char)</code>.</p>
<p>If you want I can provide you will fully working example, but I think that you want to do it alone.</p>
|
python
| 1 |
1,908,607 | 63,055,732 |
How do I cache files within a function app?
|
<p>I am trying to temporarily store files within a function app. The function is triggered by an http request which contains a file name. I first check if the file is within the function app storage and if not, I write it into the storage.</p>
<p><strong>Like this:</strong></p>
<pre><code> if local_path.exists():
file = json.loads(local_path.read_text('utf-8'))
else:
s = AzureStorageBlob(account_name=account_name, container=container,
file_path=file_path, blob_contents_only=True,
mi_client_id=mi_client_id, account_key=account_key)
local_path.write_bytes(s.read_azure_blob())
file = json.loads((s.read_azure_blob()).decode('utf-8'))
</code></pre>
<p><strong>This is how I get the local path</strong></p>
<pre><code> root = pathlib.Path(__file__).parent.absolute()
file_name = pathlib.Path(file_path).name
local_path = root.joinpath('file_directory').joinpath(file_name)
</code></pre>
<p>If I upload the files when deploying the function app everything works as expected and I read the files from the function app storage. But if I try to save or cache a file, it breaks and gives me this error <code>Error: [Errno 30] Read-only file system:</code></p>
<p>Any help is greatly appreciated</p>
|
<p>So after a year I discovered that Azure function apps can utilize the python os module to save files which will persist throughout calls to the function app. No need to implement any sort of caching logic. Simply use os.write() and it will work just fine.</p>
<p>I did have to implement a function to clear the cache after a certain period of time but that was a much better alternative to the verbose code I had previously.</p>
|
python|azure|caching|azure-function-app
| 0 |
1,908,608 | 62,234,787 |
Requests (Caused by SSLError("Can't connect to HTTPS URL because the SSL module is not available.") On Linux
|
<p>This question has been answered <a href="https://stackoverflow.com/questions/54135206/requests-caused-by-sslerrorcant-connect-to-https-url-because-the-ssl-module">here</a> but for Windows users. I am getting this error on a Linux machine on a 3rd party application under a Anaconda environment. I added the following paths to my <code>PATH</code> env:</p>
<pre><code><path>/anaconda2/lib
<path>/anaconda2/bin
</code></pre>
<p>But when I run:</p>
<pre><code>import requests
requests.get("https://api.ipify.org")
</code></pre>
<p>I get the error:</p>
<pre><code>requests.exceptions.SSLError: HTTPSConnectionPool(host='api.ipify.org',
port=443): Max retries exceeded with url: / (Caused by SSLError("Can't
connect to HTTPS URL because the SSL module is not available."))
</code></pre>
<p>The 3rd party application and a conda shell both include those paths in the <code>PATH</code> env but it only works on the shell.</p>
|
<p>The error message says "SSL module is not available". Requests uses <code>openssl</code> for its "SSL module" so make sure <code>openssl</code> is installed and working correctly.</p>
<p>First run:</p>
<pre><code>~$ conda list
</code></pre>
<p>You should see <code>openssl</code> and <code>pyopenssl</code> in the output</p>
<p>if you don't install <code>openssl</code> and <code>pyopenssl</code></p>
<p>If openssl is installed run:</p>
<pre><code>~$ openssl
</code></pre>
<p>If you get:</p>
<pre><code>openssl: error while loading shared libraries: libcrypto.so.1.0.0: cannot enable executable stack as shared object requires: Invalid argument
</code></pre>
<p>Run using the version number from above</p>
<pre><code>~$ sudo find / -name libcrypto.so.[your version]
</code></pre>
<p>Then using the path to libcrypto.so.[your version] from the output of the above:</p>
<pre><code>~$ sudo execstack -c [path to]/libcrypto.so.[your version]
</code></pre>
<p>Then run to test:</p>
<pre><code>~$ openssl
OpenSSL>
</code></pre>
<p>You will need to do this for all environments</p>
|
python|linux|ssl|python-requests|anaconda
| 0 |
1,908,609 | 35,561,635 |
Packaging a python application ( with enthought, matplotlib, wxpython) into executable
|
<p>My Python 2.7 application uses matplotlib, enthought (mayavi, traits), wxpython libraries. I need to package it into an executable on Windows, which, after some research and experimenting seems like a not straightforward task. </p>
<p>I have so far experimented with PyInstaller and bbfreeze. In both of them I specify hidden imports/includes (which I could gather fromrandom information on the web) to import the Enthought packeges. Both manage to create an executable (for bbfreeze I excluded the matplotlib part of my application so far), but when I run it, both return the same error: </p>
<pre><code>Traceback (most recent call last):
File "<string>", line 6, in <module>
File "__main__.py", line 128, in <module>
File "__main__test__.py", line 23, in <module>
File "traitsui/api.py", line 36, in <module>
File "traitsui/editors/__init__.py", line 23, in <module>
File "traitsui/editors/api.py", line 49, in <module>
File "traitsui/editors/table_editor.py", line 37, in <module>
File "traitsui/table_filter.py", line 35, in <module>
File "traitsui/menu.py", line 128, in <module>
File "pyface/toolkit.py", line 98, in __init__
NotImplementedError: the wx pyface backend doesn't implement MenuManager
</code></pre>
<p>Any ideas what should I do? Alternatively has anyone had experience with creating such an executable and can recommend a tool or method ? So far I have seen only <a href="http://www.geophysique.be/2011/08/01/pack-an-enthought-traits-app-inside-a-exe-using-py2exe-ets-4-0-edit/" rel="nofollow">this tutorial</a> but it uses py2exe and apparently requires downloading the whole ETS - if nothing else gonna give it a try...</p>
|
<p>Here is the solution which worked for me.</p>
<p>I have tried to use bbfreeze, PyInstaller , py2exe and cx_Freeze. In the end I decided to go with cx_Freeze as it is apparently popular with people who are packaging the applications with enthought classes.</p>
<p>With cx_Freeze I got the similar error message as above. The problem is that it saves the necessary modules in "library.zip" file, which is something that enthought classes including mayavi have problem with. Fortunately cx_Freeze allows specifying <code>"create_shared_zip": False</code> option, which then makes it so that source files are directly copied into the build directory as they are, instead of in a zip file.</p>
<p>Additionally, I have found that some Enthought files and folders have to be manually included in <code>include_files</code> (same goes for scipy, source: <a href="https://stackoverflow.com/questions/32694052/scipy-and-cx-freeze-error-importing-scipy-you-cannot-import-scipy-while-being">here</a>). After this it worked. I add my setup file code below, hope it helps. </p>
<pre><code>import sys
import os
from cx_Freeze import setup, Executable
import scipy
scipy_path = os.path.dirname(scipy.__file__) #use this if you are also using scipy in your application
build_exe_options = {"packages": ["pyface.ui.wx", "tvtk.vtk_module", "tvtk.pyface.ui.wx", "matplotlib.backends.backend_tkagg"],
"excludes": ['numarray', 'IPython'],
"include_files": [("C:\\Python27\\Lib\\site-packages\\tvtk\\pyface\\images\\", "tvtk\\pyface\\images"),
("C:\\Python27\\Lib\\site-packages\\pyface\\images\\", "pyface\\images"),
("C:\\Python27\\Lib\\site-packages\\tvtk\\plugins\\scene\\preferences.ini", "tvtk\\plugins\\scene\\preferences.ini"),
("C:\\Python27\\Lib\\site-packages\\tvtk\\tvtk_classes.zip", "tvtk\\tvtk_classes.zip"),
("C:\\Python27\\Lib\\site-packages\\mayavi\\core\\lut\\pylab_luts.pkl","mayavi\\core\\lut\\pylab_luts.pkl"),
("C:\\Python27\\Lib\\site-packages\\mayavi\\preferences\\preferences.ini","mayavi\\preferences\\preferences.ini"),
("C:\\Python27\\Lib\\site-packages\\numpy\\core\\libifcoremd.dll","numpy\\core\\libifcoremd.dll"),
("C:\\Python27\\Lib\\site-packages\\numpy\\core\\libmmd.dll","numpy\\core\\libmmd.dll"),
(str(scipy_path), "scipy") #for scipy
]
,"create_shared_zip": False #to avoid creating library.zip
}
executables = [
Executable('myfile.py', targetName="myfile.exe", base=None)
]
setup(name='myfile',
version='1.0',
description='myfile',
options = {"build_exe": build_exe_options},
executables=executables
)
</code></pre>
<p>Configuration:</p>
<pre><code>python 2.7
altgraph==0.9
apptools==4.3.0
bbfreeze==1.1.3
bbfreeze-loader==1.1.0
configobj==5.0.6
cx-Freeze==4.3.3
Cython==0.23.4
matplotlib==1.4.3
mayavi==4.4.3
MySQL-python==1.2.5
natgrid==0.2.1
numpy==1.10.0b1
opencv-python==2.4.12
pandas==0.16.2
pefile==1.2.10.post114
Pillow==3.1.1
plyfile==0.4
psutil==4.1.0
pyface==5.0.0
Pygments==2.0.2
pygobject==2.28.6
pygtk==2.22.0
PyInstaller==3.1
pyparsing==2.0.3
pypiwin32==219
PySide==1.2.2
python-dateutil==2.4.2
pytz==2015.4
scipy==0.16.0
six==1.9.0
subprocess32==3.2.7
traits==4.5.0
traitsui==5.0.0
transforms3d==0.2.1
VTK==6.2.0
</code></pre>
|
python|matplotlib|wxpython|cx-freeze|enthought
| 0 |
1,908,610 | 73,506,025 |
Can't get a steam user's inventory through the API
|
<p>I'm trying to get info about a Steam user's inventory but it seems that I'm doing something wrong. After running script below (ofc first I replace PROFILEID with my Steam User ID) all I get is {'success': False}. Can anyone tell me how to fix this? I set my inventory as visible for everyone.</p>
<pre><code>import requests
inventory = requests.get("http://steamcommunity.com/profiles/PROFILEID/inventory/json/730/1").json()
print(inventory)
</code></pre>
<p>After deleting ".json()" it prints <Response [200]></p>
|
<p>Changing the <code>1</code> at the end of the URL to a <code>2</code> worked for me.</p>
<p><a href="https://steamcommunity.com/profiles/76561198048165534/inventory/json/730/1" rel="nofollow noreferrer">https://steamcommunity.com/profiles/76561198048165534/inventory/json/730/1</a> → <code>{"success":false}</code></p>
<p><a href="https://steamcommunity.com/profiles/76561198048165534/inventory/json/730/2" rel="nofollow noreferrer">https://steamcommunity.com/profiles/76561198048165534/inventory/json/730/2</a> → <code>{"success":true,"rgInventory":{"23071433672":{"id":"23071433672","classid":"1989287349","instanceid":"302028390",</code> ...</p>
|
python|api|steam|steam-web-api
| 1 |
1,908,611 | 73,328,131 |
Why is Python not updating my pyqt5 button text
|
<p>I'm having a strange issue that I can't figure out.</p>
<p>When I click a button, I want it to update it's own text, but in some cases it's as if it's being blocked!
Excuse my rubbish coding - my first time trying to make a GUI for something. Anyways, this is my buttons function</p>
<pre><code>def ConvertToSTL(self):
if DEBUG:
print("You Clicked on ConvertToSTL")
self.btnConvertToSTL.setText("Processing...")
self.btnConvertToSTL.setEnabled(False)
if not (FILE_OUTLINE and FILE_OTHER):
print("You MUST select BOTH files!")
self.btnConvertToSTL.setText(CONVERT_BTN_TEXT)
self.btnConvertToSTL.setEnabled(True)
else:
if DEBUG:
print("Outline: " + FILE_OUTLINE)
if self.inputPCB.isChecked():
print("Mask Top: " + FILE_OTHER)
elif self.inputSolderStencil.isChecked():
print("Paste Mask Top: " + FILE_OTHER)
# Processing Files!
outline_file = open(FILE_OUTLINE, "r")
other_file = open(FILE_OTHER, "r")
outline = gerber.loads(outline_file.read())
other = gerber.loads(other_file.read())
# outline=None
if outline and other:
output = process_gerber(
outline,
other,
self.inputThickness.value(),
self.inputIncludeLedge.isChecked,
self.inputHeight.value(),
self.inputGap.value(),
self.inputIncreaseHoleSize.value(),
self.inputReplaceRegions.isChecked(),
self.inputFlip.isChecked(),
)
file_id = randint(1000000000, 9999999999)
scad_filename = "./gerbertostl-{}.scad".format(file_id)
stl_filename = "./gerbertostl-{}.stl".format(file_id)
with open(scad_filename, "w") as scad_file:
scad_file.write(output)
p = subprocess.Popen(
[
SCAD_BINARY,
"-o",
stl_filename,
scad_filename,
]
)
p.wait()
if p.returncode:
print("Failed to create an STL file from inputs")
else:
with open(stl_filename, "r") as stl_file:
stl_data = stl_file.read()
os.remove(stl_filename)
# Clean up temporary files
os.remove(scad_filename)
self.btnConvertToSTL.setText("Saving file...")
saveFilename = QFileDialog.getSaveFileName(None, "Save STL", stl_filename, "STL File (*.stl)")[0]
if DEBUG:
print("File saved to: " + saveFilename)
# needs a handler if user clicks cancel!
saveFile = open(saveFilename,'w')
saveFile.write(stl_data)
saveFile.close()
self.btnConvertToSTL.setEnabled(True)
self.btnConvertToSTL.setText(CONVERT_BTN_TEXT)
</code></pre>
<p>Now, if <code>outline</code> or <code>other</code> is FALSE for any reason - to test I manually added set <code>outline=None</code> then my Button DOES correctly set it's text to read "Processing...". The problem however is that if <code>outline</code> and <code>other</code> are both TRUE so the functions progresses, the button text does NOT get set to "Processing".</p>
<p>Instead, the button text is not changed until it reaches <code>self.btnConvertToSTL.setText("Saving file...")</code> which as expected sets the text correctly. Then, once the file is saved, the button again correctly updates again to the variable <code>CONVERT_BTN_TEXT</code></p>
<p>So my question is, why on earth does the initial "Processing..." text NOT get set correctly? I don't understand</p>
<p>Edit: minimal reproducible example. In this case, the button text never changes to "Processing..." for me. Obviously, Requires PYQT5</p>
<pre><code># -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'tmp.ui'
#
# Created by: PyQt5 UI code generator 5.15.7
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know what you are doing.
from PyQt5 import QtCore, QtGui, QtWidgets
import time
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(800, 600)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.pushButton = QtWidgets.QPushButton(self.centralwidget)
self.pushButton.setGeometry(QtCore.QRect(160, 160, 421, 191))
self.pushButton.setObjectName("pushButton")
self.pushButton.clicked.connect(self.PushButtonClicked)
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 24))
self.menubar.setObjectName("menubar")
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.pushButton.setText(_translate("MainWindow", "PushButton"))
def PushButtonClicked(self):
print("Button Clicked")
self.pushButton.setText("Processing")
self.pushButton.setEnabled(False)
if True and True:
print("Sleep")
time.sleep(5)
print("Continue")
self.pushButton.setText("DONE")
self.pushButton.setEnabled(True)
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
</code></pre>
<p>The button will correctly say "DONE" after 5 seconds, but it never changes to "Processing"</p>
|
<p>The issue is because the code you are invoking once the button is pressed is locking the GUI, so when it is finally released back to the main event loop it processes all of the changes at once which is why you only see the final message displayed in the button description. That is also why you can't move around the window or interact with it in any other way while the method is processing.</p>
<p>The solution to this is to simply not write code that freezes the GUI. This means either breaking up the process or running it in a separate thread, and using Qt's signals and slots API.</p>
<p>For example:</p>
<pre><code>from PyQt5 import QtCore, QtWidgets
import time
class MainWindow(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super().__init__(parent)
self.setObjectName("MainWindow")
self.resize(800, 600)
self.centralwidget = QtWidgets.QWidget(self)
self.centralwidget.setObjectName("centralwidget")
self.pushButton = QtWidgets.QPushButton("Button", self.centralwidget)
self.pushButton.setGeometry(QtCore.QRect(160, 160, 421, 191))
self.pushButton.setObjectName("pushButton")
self.pushButton.clicked.connect(self.PushButtonClicked)
self.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(self)
self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 24))
self.menubar.setObjectName("menubar")
self.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(self)
self.statusbar.setObjectName("statusbar")
self.setStatusBar(self.statusbar)
def PushButtonClicked(self):
self.thread = Thread(self)
self.thread.started.connect(self.show_processing)
self.thread.finished.connect(self.show_done)
self.thread.start()
def show_done(self):
self.pushButton.setText("DONE")
self.pushButton.setEnabled(True)
def show_processing(self):
self.pushButton.setText("Processing")
self.pushButton.setEnabled(False)
class Thread(QtCore.QThread):
def run(self):
print("Button Clicked")
if True and True:
print("Sleep")
time.sleep(5)
print("Continue")
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
</code></pre>
<p>So for your specific use case, it might look something like this:</p>
<pre><code>...
...
...
...
...
def convert_to_STL(self):
if DEBUG:
print("You Clicked on ConvertToSTL")
self.btnConvertToSTL.setText("Processing...")
self.btnConvertToSTL.setEnabled(False)
if not (FILE_OUTLINE and FILE_OTHER):
print("You MUST select BOTH files!")
self.btnConvertToSTL.setText(CONVERT_BTN_TEXT)
self.btnConvertToSTL.setEnabled(True)
else:
self.thread = Thread(self)
self.thread.finished.connect(self.show_done)
self.thread.start()
def show_done(self):
self.btnConvertToSTL.setEnabled(True)
self.btnConvertToSTL.setText(CONVERT_BTN_TEXT)
class Thread(QtCore.QThread):
def __init__(self, parent):
self.window = parent
def run(self):
if DEBUG:
print("Outline: " + FILE_OUTLINE)
if self.window.inputPCB.isChecked():
print("Mask Top: " + FILE_OTHER)
elif self.window.inputSolderStencil.isChecked():
print("Paste Mask Top: " + FILE_OTHER)
# Processing Files!
outline_file = open(FILE_OUTLINE, "r")
other_file = open(FILE_OTHER, "r")
outline = gerber.loads(outline_file.read())
other = gerber.loads(other_file.read())
# outline=None
if outline and other:
output = process_gerber(
outline,
other,
self.window.inputThickness.value(),
self.window.inputIncludeLedge.isChecked,
self.window.inputHeight.value(),
self.window.inputGap.value(),
self.window.inputIncreaseHoleSize.value(),
self.window.inputReplaceRegions.isChecked(),
self.window.inputFlip.isChecked(),
)
file_id = randint(1000000000, 9999999999)
scad_filename = "./gerbertostl-{}.scad".format(file_id)
stl_filename = "./gerbertostl-{}.stl".format(file_id)
with open(scad_filename, "w") as scad_file:
scad_file.write(output)
p = subprocess.Popen(
[
SCAD_BINARY,
"-o",
stl_filename,
scad_filename,
]
)
p.wait()
if p.returncode:
print("Failed to create an STL file from inputs")
else:
with open(stl_filename, "r") as stl_file:
stl_data = stl_file.read()
os.remove(stl_filename)
# Clean up temporary files
os.remove(scad_filename)
saveFilename = QFileDialog.getSaveFileName(None, "Save STL", stl_filename, "STL File (*.stl)")[0]
if DEBUG:
print("File saved to: " + saveFilename)
# needs a handler if user clicks cancel!
saveFile = open(saveFilename,'w')
saveFile.write(stl_data)
saveFile.close()
</code></pre>
<p>P.S. You shouldn't edit UIC files.</p>
|
python|python-3.x|pyqt5
| 1 |
1,908,612 | 59,740,108 |
Why iterating over ndb Datastore query consumes too much memory?
|
<p>I have a query like:</p>
<pre><code>query = HistoryLogs.query()
query = query.filter(HistoryLogs.exec_id == exec_id)
iter = query.iter()
for ent in iter:
# write log to file, nothing memory intensive
</code></pre>
<p>I added logs in the for loop and reading 10K rows increases memory usage by 200MB, then reading the next 10K rows adds extra 200MB and so on. Reading 100K requires 2GB, which exceeds the highmem memory limit.</p>
<p>I tried clearing the memcache in the for loop, after reading 10K rows, by adding:</p>
<pre><code> # clear ndb cache in order to reduce memory footprint
context = ndb.get_context()
context.clear_cache()
</code></pre>
<p>in the for loop, on each 10K-th iteration, but it resulted in the query being timed out, error <code>BadRequestError: The requested query has expired. Please restart it with the last cursor to read more results. ndb</code> was raised.</p>
<p>My initial expectation was that by using <code>query.iter()</code> instead of <code>query.fetch()</code> I wouldn't face any memory issue and the memory would be pretty much constant, but that isn't the case. Is there a way to read the data with iterator, without exceeding time nor memory limits? By clearing the context cache I see the memory consumption is pretty much constant, but I ran into troubles with the time it takes to retrieve all rows.</p>
<p>BTW, there are a lot of rows to be retrieved, up to 150K. Is it possible to get this done with some simple tweaks or I need a more complex solution, e.g. one which would use some parallelization? </p>
|
<p>Are you running this in the remote-api-shell? Otherwise I'd imagine app engine's max request timeout would start to be a problem.</p>
<p>You should definitely run this in google dataflow instead. It will parallelize it for you / run faster.</p>
<p><a href="https://beam.apache.org/documentation/programming-guide/" rel="nofollow noreferrer">https://beam.apache.org/documentation/programming-guide/</a>
<a href="https://beam.apache.org/releases/pydoc/2.17.0/index.html" rel="nofollow noreferrer">https://beam.apache.org/releases/pydoc/2.17.0/index.html</a>
<a href="https://github.com/apache/beam/blob/master/sdks/python/apache_beam/examples/cookbook/datastore_wordcount.py" rel="nofollow noreferrer">https://github.com/apache/beam/blob/master/sdks/python/apache_beam/examples/cookbook/datastore_wordcount.py</a></p>
<p>I imagine your pipline code would look something like this:</p>
<pre><code>def run(project, gcs_output_prefix, exec_id):
def format_result(element):
csv_cells = [
datastore_helper.get_value(element.properties['exec_id']),
# extract other properties here!!!!!
]
return ','.join([str(cell) for cell in csv_cells])
pipeline_options = PipelineOptions([])
pipeline_options.view_as(SetupOptions).save_main_session = True
p = beam.Pipeline(options=pipeline_options)
query = query_pb2.Query()
query.kind.add().name = 'HistoryLogs'
datastore_helper.set_property_filter(query.filter, 'exec_id', PropertyFilter.EQUAL, exec_id)
_ = (p
| 'read' >> ReadFromDatastore(project, query, None)
| 'format' >> beam.Map(format_result)
| 'write' >> beam.io.WriteToText(file_path_prefix=gcs_output_prefix,
file_name_suffix='.csv',
num_shards=1) # limits output to a single file
result = p.run()
result.wait_until_finish()
if __name__ == '__main__':
logging.getLogger().setLevel(logging.INFO)
run(project='YOUR-PROJECT-ID',
gcs_output_prefix='gs://YOUR-PROJECT-ID.appspot.com/history-logs-export/some-time-based-prefix/',
exec_id='1234567890')
</code></pre>
<p>This code reads from Google Datastore and exports to Google Cloud Storage as csv. </p>
|
python|python-2.7|performance|google-cloud-datastore|app-engine-ndb
| 2 |
1,908,613 | 59,792,842 |
Django is giving me an "invalid date format" error when running tests despite specifying date format in settings
|
<p>My settings file has these settings:</p>
<pre><code># settings.py
USE_L10N = False
DATE_INPUT_FORMATS = ['%m/%d/%Y']
</code></pre>
<p>In my test file, I'm creating an object requires a date and looks like this:</p>
<pre><code># tests.py
my_model = Thing(a_date='11/22/2019').save()
</code></pre>
<p>When I run the test, however, the test gets stuck when it goes to create the object and throws the error:</p>
<blockquote>
<p>django.core.exceptions.ValidationError: ["'11/22/2019' value has an invalid date format. It must be in YYYY-MM-DD format."]</p>
</blockquote>
<p>Is there something I'm missing? Why would it be throwing this error?</p>
|
<p>You need to set <code>DATE_INPUT_FORMATS</code>, as <code>DATE_FORMAT</code> sets how Django displays the date.</p>
<p>Change your code with:</p>
<p><code>DATE_INPUT_FORMATS = ['%m/%d/%Y']</code></p>
|
python|django|django-models|datefield|django-validation
| 1 |
1,908,614 | 59,739,399 |
Implement a Deck of cards in python. Problem when trying to print all cards while calling list.pop()
|
<pre><code>class Card:
def __init__(self, suit, value):
self.suit = suit
self.value = value
def show(self):
# print(f"{self.value} of {self.suit}")
return (self.suit, self.value)
class Deck(Card):
"""
Deck is collection of 52 cards.
"""
colour = ('Hearts', 'Diamonds', 'Spades', 'Clubs')
rank = ('Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Jack', 'Queen', 'King', 'Ace')
def __init__(self):
d = []
for s in Deck.colour:
for r in Deck.rank:
c = Card(s,r)
d.append(c)
self.pack = d
def draw(self):
return self.pack.pop()
mydeck = Deck()
j =1
for i in mydeck.pack:
print(j, "\t", mydeck.draw().show(), " count remaining ", len(mydeck.pack))
j +=1
</code></pre>
<p>while trying to print the contents of <code>mydeck.deck</code>, which is a list, it only prints half of total values. If run again it prints next half of values.</p>
<p>Please help me to figure out why all content is not printed?</p>
<p>I am a beginner and any feedback is very much appreciated.
Thanks in advance.</p>
|
<p>I fixed this way :</p>
<pre class="lang-py prettyprint-override"><code>class Card:
def __init__(self, suit, value):
self.suit = suit
self.value = value
def show(self):
# print(f"{self.value} of {self.suit}")
return (self.suit, self.value)
class Deck():
"""
Deck is collection of 52 cards.
"""
colour = ('Hearts', 'Diamonds', 'Spades', 'Clubs')
rank = ('Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Jack', 'Queen', 'King', 'Ace')
def __init__(self):
d = []
for s in Deck.colour:
for r in Deck.rank:
c = Card(s,r)
d.append(c)
self.pack = d
def draw(self):
return self.pack.pop()
mydeck = Deck()
j =1
breakpoint()
for i in mydeck.pack:
print(j, "\t", i.show(), " count remaining ", len(mydeck.pack)-j)
j +=1
</code></pre>
<p>OUTPUT </p>
<pre class="lang-sh prettyprint-override"><code>1 ('Hearts', 'Two') count remaining 51
2 ('Hearts', 'Three') count remaining 50
3 ('Hearts', 'Four') count remaining 49
4 ('Hearts', 'Five') count remaining 48
5 ('Hearts', 'Six') count remaining 47
6 ('Hearts', 'Seven') count remaining 46
7 ('Hearts', 'Eight') count remaining 45
8 ('Hearts', 'Nine') count remaining 44
9 ('Hearts', 'Ten') count remaining 43
10 ('Hearts', 'Jack') count remaining 42
......................
</code></pre>
|
python|list|blackjack|playing-cards
| 0 |
1,908,615 | 59,477,947 |
Update multiple labels in bokeh
|
<p>I'm trying to create a bokeh plot where, with a slider, it updates multiple labels.
The code I have below is a combination from two questions posed on stackoverflow <a href="https://stackoverflow.com/questions/56518254/trigger-display-of-the-hovertool-tooltips-via-customjs-in-bokeh">here</a> and <a href="https://stackoverflow.com/questions/34680708/load-graph-data-from-files-on-button-click-with-bokeh">here</a>.</p>
<p>In the code i have static x and y coordinates, its just the text labels that i want to manipulate with the slider. With code below it doesnt seem to show or even update. Why is it not showing and/or updating?</p>
<pre><code>from bokeh.plotting import figure, show, output_file
from bokeh.models import ColumnDataSource, Range1d, LabelSet, Label, Slider, TextInput, CustomJS
from bokeh.layouts import column, row
output_file("image.html")
plot = figure(x_range=(0, 100), y_range=(0, 100))
source = ColumnDataSource(
data=dict(
x=[55, 28, 18, 74, 76, 28, 32, 18, 60, 84, 44, 56, 56, 76],
y=[8, 8, 33, 14, 72, 64, 46, 20, 52, 56, 84, 22, 36, 32],
v1=prices_final["1"].values,
v2=prices_final["2"].values,
v3=prices_final["3"].values,
v4=prices_final["4"].values,
)
)
labels = ColumnDataSource(data=dict(x=[], y=[], t=[], ind=[]))
plot.add_layout(
LabelSet(
x="x",
y="y",
text="t",
source=labels,
level="overlay",
x_offset=0,
y_offset=0,
render_mode="canvas",
text_font_size="10pt",
text_color="black",
background_fill_color="white",
border_line_color="black",
)
)
# Set up widgets
slider = Slider(title="Hour of day", value=1.0, start=1.0, step=1.0, end=24.0)
code = """
labels.data = {'x':[],'y':[],'t':[]}
source.selected.indices = [slider.value]
labels.data = {'ind':[slider.value],
'x':[source.data.x],
'y':[source.data.y],
't':[source.data.v[slider.value]]}
labels.change.emit()
source.change.emit()
"""
callback = CustomJS(args=dict(source=source, slider=slider, labels=labels), code=code)
slider.js_on_change("value", callback)
layout = column(slider, plot)
show(layout)
</code></pre>
<p>prices final looks like:</p>
<pre><code>prices_final['1'].values = array([ -5.25, 2.67, 10.67, -0.95, -9.54,
-4.22, -5.2 , -5.53, -9.33, -3.49, -0.47, -8.96, -17.88, -5.49])
</code></pre>
<p>all other prices_final have similar data structure.</p>
|
<p>Edited:
This code shows a graph with sliders and v1, v2, .. values as labels. You'll need to change v1, ... v4 part. I couldn't write short with many v, so it might be very long with 24.</p>
<pre><code>from bokeh.layouts import row, column
from bokeh.models import CustomJS, Slider, LabelSet
from bokeh.plotting import figure, output_file, show, ColumnDataSource
x = [55, 28, 18, 74, 76, 28, 32, 18, 60, 84, 44, 56, 56, 76]
y = [8, 8, 33, 14, 72, 64, 46, 20, 52, 56, 84, 22, 36, 32]
label_selected = [''] * 14
# To simplify, make v1 to v4 with same num
v1 = [1] * 14
v2 = [2] * 14
v3 = [3] * 14
v4 = [4] * 14
# list of all v1,v2...
v = [v1, v2, v3, v4]
source = ColumnDataSource(
data=dict(x=x, y=y, v=v, label_selected=label_selected)
)
plot = figure(x_range=(0, 100), y_range=(0, 100), plot_width=400, plot_height=400)
plot.circle(x, y, radius=5, fill_color="red", fill_alpha=0.6, line_color=None)
slider = Slider(title="Hour of day", value=1.0, start=1.0, step=1.0, end=24.0)
code = """
const data = source.data;
const A = hour.value; /* hour starts from 1*/
const x = data['x'];
const y = data['y'];
let label_selected = data['label_selected'];
const v1 = data['v'][0];
const v2 = data['v'][1];
const v3 = data['v'][2];
const v4 = data['v'][3];
if (A == 1){
label_list = v1
} else if (A == 2) {
label_list = v2
} else if (A == 3) {
label_list = v3
} else if (A == 4) {
label_list = v4
}
for (var i = 0; i < label_selected.length; i++){
label_selected[i] = label_list[i]
}
source.change.emit();
"""
callback = CustomJS(
args=dict(source=source, hour=slider),
code=code
)
slider.js_on_change("value", callback)
labels = LabelSet(
x="x",
y="y",
text="label_selected",
level="glyph",
x_offset=5,
y_offset=5,
source=source,
render_mode="canvas",
)
plot.add_layout(labels)
layout = row(plot, column(slider))
output_file("slider.html", title="slider.py example")
show(layout)
</code></pre>
<p>Showing snapshot with slider 3... <a href="https://i.stack.imgur.com/GY0Mm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/GY0Mm.png" alt="enter image description here"></a></p>
|
python|bokeh
| 1 |
1,908,616 | 49,222,155 |
Python socket : Error receive data
|
<p>I write a network application. The server has ability to find client base on given subnet. If the client receive authentication message from server, it will respond to server. Everything working good but server, it can't receiver from client.</p>
<p>Client :</p>
<pre><code>def ListenServer():
# Listen init signal from Server to send data
HOST = '' # Symbolic name meaning all available interfaces
PORT = 50007 # Arbitrary non-privileged port
# UDP Socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind((HOST, PORT))
data, addr = s.recvfrom(1024)
if data == 'Authen':
SocketConnect(addr[0])
def SocketConnect(HOST):
# Connect to Server to send data
print HOST
PORT = 50008 # The same port as used by the server
# Create Socket
print "Create Socket"
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error, e:
print "Error creating socket: %s" %e
sys.exit(1)
# Connect
print "Connect"
try:
s.connect((HOST, PORT))
except socket.error, e:
print "Connection error: %s" %e
sys.exit(1)
# Send Data
print "Send Data"
try:
s.sendall('Hello, world')
except socket.error, e:
print "Error sending data: %s" % e
sys.exit(1)
# Close Socket
s.close()
print "Close Socket"
ListenServer()
</code></pre>
<p>Server :</p>
<pre><code>from netaddr import IPAddress
import socket
import sys
import ipaddress
import time
def FindAgent():
PORT = 50007 # Port use to find Agent
#Find broadcast address
"""IPAddress("255.255.255.0").netmask_bits() #Convert Subnet Mask to Prefix Length, Result is 24"""
try :
HOST = str(ipaddress.ip_network(u'192.168.10.0/24')[-1])
except ValueError as e :
"""e = sys.exc_info()[0] # Find Exception you need"""
print e
# UDP client
MESSAGE = "Authen"
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
for x in range(0,2):
sock.sendto(MESSAGE, (HOST, PORT))
def ListenClient():
# Listen Client sent data
HOST = socket.gethostbyname(socket.gethostname())
PORT = 50008
# TCP socket
# Create Socket
print "Create Socket"
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error, e:
print "Error creating socket: %s" %e
sys.exit(1)
# Bind
print "Bind"
try:
s.bind((HOST, PORT))
except socket.error, e:
print "Error bind: %s" %e
sys.exit(1)
# Listen
print "Listen"
try:
s.listen(10)
except socket.error, e:
print "Error listen: %s" %e
sys.exit(1)
# Accept data from client
print "Accept data from client"
try:
conn, addr = s.accept()
data = s.recv(1024)
except socket.error, e:
print "Error listen: %s" %e
sys.exit(1)
print data
s.close()
FindAgent()
ListenClient()
</code></pre>
<p>Error on Server :</p>
<pre><code>Create Socket
Bind
Listen
Accept data from client
Error listen: [Errno 10057] A request to send or receive data was disallowed because the socket is not connected and (when sending on a datagram socket using a sendto call) no address was supplied
[Finished in 0.8s with exit code 1]
[shell_cmd: python -u "C:\Users\Win7_Lab\Desktop\Server.py"]
[dir: C:\Users\Win7_Lab\Desktop]
[path: C:\Python27\;C:\Python27\Scripts;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\]
</code></pre>
<p>Without the line <strong>data = s.recv(1024)</strong> on Server, it working fine. But with it, the error show up. Can anybody please tell me why it happen ?</p>
|
<p>The crash come from <code>s.recv(1024)</code> as you said it's because the recieve (<code>.recv()</code>) methode on your server need to be called on the client connection. </p>
<p>Follow this example : <a href="https://docs.python.org/2/library/socket.html#example" rel="nofollow noreferrer">here</a></p>
<p>Server file : </p>
<pre><code>conn, addr = s.accept()
data = conn.recv(1024)
</code></pre>
<p>Client file : </p>
<pre><code>s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.connect((HOST, PORT))
data = s.recv(1024)
</code></pre>
<p>As you see the client recieve data from socket (server).
And server recieve data from client connection.</p>
<p>Hope that was usefull.</p>
<blockquote>
<p>Edit add some examples links.</p>
</blockquote>
<p>You can find what you want in these tutorial:</p>
<ul>
<li><a href="https://docs.python.org/2/howto/sockets.html" rel="nofollow noreferrer">How to use socket</a></li>
<li><a href="https://pymotw.com/2/socket/tcp.html" rel="nofollow noreferrer">How to create server with socket and select</a></li>
<li><a href="https://github.com/antoineFrau/td-reseau" rel="nofollow noreferrer">Example client server giving time</a></li>
<li><a href="https://github.com/antoineFrau/python-chat" rel="nofollow noreferrer">Example chat client server</a></li>
</ul>
|
python|python-2.7|sockets
| 0 |
1,908,617 | 49,075,560 |
Recursive function that remembers its path in global list python
|
<p>I have problem with function:</p>
<pre><code>tested_zeros = [(-1, -1)]
def reveal_zeros(x, y):
board_visible[y*row+x] = board[y*row+x]
for p in range(x - 1, x + 2):
for o in range(y - 1, y + 2):
if o >= 0 and p >= 0 and o <= row and p <= col:
for zero in tested_zeros:
if zero != (p, o):
tested_zeros.append((p, o)) <--broke part in my 'super' idea xD
if board[o*row+p] == " ":
return reveal_zeros(p, o)
</code></pre>
<p>so what is doing is checking if in array 'board[(x, y)]' is zero and its neighbors, when it is, its copying it to 'board_visible', the problem is that it bugs in (0, 0),[and calling it endlessly] so my idea was adding list tested_zeros so he remembers which points it tested but recursive function does not works that way :), and i know i can check last by(x, y) but it will loop somewhere else.
My question is how to handle this?</p>
<p>Here is my whole code:</p>
<pre><code>import random
import numpy as np
row = 10
col = row
mine_list = list()
board = list()
board_visible = list()
num = 0
is_over = False
def get_num_of_mines():
global num
while True:
print("Podaj liczbe min: \n(z zakresu od 1 do ", (row * col) - 1, ")")
num = int(input())
if 1 <= num <= (row * col) - 1:
return num
else:
print("Błędna liczba. Podaj poprawną z zakresu")
def deploy_mines():
global mine_list
mine_x = random.randint(0, row - 1)
mine_y = random.randint(0, col - 1)
par = mine_x, mine_y
for l in mine_list:
if par == l:
return deploy_mines()
return mine_x, mine_y
def number_of_neighboring_mines(x, y):
global mine_list
num_of_neighbors = 0
for p in range(x - 1, x + 2):
for o in range(y - 1, y + 2):
if o >= 0 and p >= 0 and o <= row and p <= col:
par = p, o
for l in mine_list:
if par == l:
num_of_neighbors += 1
if num_of_neighbors == 0:
return " "
else:
return num_of_neighbors
def add_bomb(x, y):
for l in mine_list:
if (x, y) == l:
board.append("*")
return False
return True
def create_board():
global mine_list, num, board_visible
for k in range(0, num):
mine_list.append(deploy_mines())
for i in range(0, col):
for j in range(0, row):
if add_bomb(i, j):
board.append(number_of_neighboring_mines(i, j))
for i in range(0, col):
for j in range(0, row):
board_visible.append(chr(9552))
def show_board():
for l in range(0, col+1):
print('{0:2d}'.format(l), end="\t")
print()
for l in range(0, col):
print('{0:2d}'.format(l+1), end=" ")
print(np.split(np.asarray(board), row)[l])
def print_board():
for l in range(0, col+1):
print('{0:2d}'.format(l), end="\t")
print()
for l in range(0, col):
print('{0:2d}'.format(l+1), end=" ")
print(np.split(np.asarray(board_visible), row)[l])
tested_zeros = [(-1, -1)]
def reveal_zeros(x, y):
board_visible[y*row+x] = board[y*row+x]
for p in range(x - 1, x + 2):
for o in range(y - 1, y + 2):
if o >= 0 and p >= 0 and o <= row and p <= col:
for zero in tested_zeros:
if zero != (p, o) or zero is None:
print(p, o)
tested_zeros.append((p, o))
if board[o*row+p] == " ":
return reveal_zeros(p, o)
def reveal_squares(x, y):
global is_over
if board[y*row+x] == "*":
show_board()
print("Koniec gry!")
is_over = True
elif board[y*row+x] == " ":
reveal_zeros(x, y)
else:
board_visible[y*row+x] = board[y*row+x]
def sapper():
get_num_of_mines()
create_board()
while not is_over:
print_board()
reveal_squares(int(input("Podaj współrzędną x: "))-1, int(input("Podaj
współrzędną y: "))-1)
sapper()
</code></pre>
|
<p>I came up with a working function:</p>
<pre><code>def reveal_zeros(x, y, steps):
board_visible[y*row+x] = board[y*row+x]
can_return = True
for p in range(x - 1, x + 2):
for o in range(y - 1, y + 2):
if o >= 0 and p >= 0 and o < row and p < col:
for i in steps:
if (p, o) == i:
can_return = False
if board[o*row+p] == " " and can_return:
return reveal_zeros(p, o, steps + [(p, o)])
if p == x or o == y or o < 0 or p < 0 or not can_return:
can_return = True
continue
return
</code></pre>
<p>Here is a sapper simulation with no winning.</p>
|
python|arrays|function|recursion
| 0 |
1,908,618 | 49,090,796 |
How to change a live object's isinstance() behavior?
|
<p>I want to change the behavior of <code>isinstance</code> for a live python object.</p>
<p>One solution is to create a simple wrapper like the following, but I do not like it:</p>
<pre><code>class Widget:
def __init__(self, obj):
self.inner_self = obj
lizard = ['head', 'nose', 'tail']
wlizard = Widget(lizard)
assert(isinstance(wlizard, Widget)) # no assertion error thrown
</code></pre>
<p>What I don't like about this particular wrapper, is that we must extract the <code>lizard</code> from <code>wlizard</code> before we can use the <code>lizard</code> again</p>
<pre><code>try:
wlizard[0]
except:
print('sorry, wlizard doesn\'t behave like a lizard')
lizard = wlizard.inner_self
print(lizard[0]) # works fine
</code></pre>
<p>What I really want is for <code>wlizard</code> to behave exactly like lizard except that <code>isinstance</code> returns <code>True</code> for <code>wlizard</code> and it returns false for <code>lizard</code>.</p>
<p>The following sort-of works, but has some drawbacks:</p>
<pre><code>class Widget:
pass
def MakeAWidget(obj):
class Blah(type(obj), Widget):
pass
# inherits type(obj)'s __init__ method
wobj = Blah(obj) # calls type(obj)'s copy constructor
return wobj
</code></pre>
<p>One problem is that this only works if <code>type(obj)</code>'s <code>__init__()</code> method takes in more than just <code>self</code>; in particular, that <code>__init__</code> can take in an instance of <code>type(obj)</code>, and when it does, it copies the attributes of <code>obj</code> into <code>self</code>. I would like something that works even if <code>obj</code> does not have a copy constructor. Something like the following might be possible to force the existence of a copy-constructor:</p>
<pre><code>import copy
class Blah(type(obj), Widget):
def __init__(*args, **kwargs):
if isinstance(args[0], type(obj)):
self = copy.deepcopy(args[0])
return self
return super(type(self), self).__init__(*args, **kwargs)
</code></pre>
<p>However, I would rather not copy the object, only modify it in-place.
Something like the following might be possible, but I am not sure what <code>__BLAH__</code> would be:</p>
<pre><code>obj = ['apple', 'pear', 'banana']
assert(not isinstance(obj, Widget)) # no error thrown
obj.__BLAH__.append('Widget')
assert(isinstance(obj, Widget)) # no error thrown
</code></pre>
|
<p>Here's something I think does what you want. The <code>wrap()</code> function dynamically creates a class which is derived from the class of the <code>obj</code> argument passed to it, and then returns an instance of that class created from it. This assumes the class of <code>obj</code> supports copy construction (initialization from an instance of the same — or derived — class).</p>
<pre><code>def wrap(obj):
class MetaClass(type):
def __new__(mcls, classname, bases, classdict):
wrapped_classname = '_%s_%s' % ('Wrapped', type(obj).__name__)
return type.__new__(mcls, wrapped_classname, (type(obj),)+bases, classdict)
class Wrapped(metaclass=MetaClass):
pass
return Wrapped(obj)
lizard = ['head', 'nose', 'tail']
wlizard = wrap(lizard)
print(type(wlizard).__name__) # -> _Wrapped_list
print(isinstance(wlizard, list)) # -> True
try:
wlizard[0]
except Exception as exc:
print(exc)
print("sorry, wlizard doesn't behave like lizard")
else:
print('wlizard[0] worked')
</code></pre>
|
python|python-3.x|class|inheritance|metaclass
| 1 |
1,908,619 | 24,962,800 |
python script from youtube video doesn't work
|
<p>I am trying to learn python from this youtube video: <a href="https://www.youtube.com/watch?v=RrPZza_vZ3w" rel="nofollow">https://www.youtube.com/watch?v=RrPZza_vZ3w</a></p>
<p>In the video they have given the viewers a script to run:</p>
<pre><code>">>> import urllib"
">>> u = urllib.urlopen('http://ctabustracker.com/bustime/map/getBusesForRoute.jsp?route=22')"
">>> data = u.read()"
">>> f = open('rt22.xml','wb')"
">>> f.write(data)"
">>> f.close()"
</code></pre>
<p>which pulls up data from a website and saves it in an xml file. But when I check the xml file I only get this: XML Parsing Error: no element found </p>
|
<p>I am pretty sure this is all the code needed for the video, It might help as a reference. </p>
<pre><code>import urllib
import webbrowser
import time
from xml.etree.ElementTree import parse
u = urllib.urlopen("http://ctabustracker.com/bustime/map/getBusesForRoute.jsp?route=22")
data = u.read()
with open("rt22.xml", "wb") as f:
f.write(data)
f.close()
office_lat = 41.980262
doc = parse("rt22.xml")
def distance(lat1, lat2):
'Return approx miles between lat1 and lat2'
return 69 * abs(lat1 - lat2)
def check_bus_location():
for bus in doc.findall("bus"):
if bus.findtext("lat") >= office_lat:
latitude = float(bus.findtext("lat"))
longitude = float(bus.findtext("lon"))
bus_id = (bus.findtext("id"))
direction = bus.findtext("d")
north_buses = [[bus_id, latitude, longitude]]
if direction.startswith("North"):
print('%s %s %0.2f miles' % (bus_id, direction, distance(latitude, office_lat)))
for bus in north_buses:
if distance(float(latitude), office_lat) < 0.5:
print(webbrowser.open(
'http://maps.googleapis.com/maps/api/staticmap?size=500x500&sensor=false&markers=|%f,%f' % (
latitude, longitude)))
while True:
check_bus_location()
time.sleep(10)
</code></pre>
|
python
| 0 |
1,908,620 | 70,917,258 |
Every time I try to launch my app to heroku it crashes (Python) and I don't know why
|
<p>So I created an app with FastAPI and I did everything accordingly. I implemented my config vars in the Heroku dashboard and I added the postgresql addons. However, despite all this, I still receive pydantic errors when I log. Here is the sample code:</p>
<pre><code>(venv) C:\Users\HP\OneDrive\Рабочий стол\PythonBootcamp\Python\fast_api-social-media>heroku logs -t
2022-01-30T17:36:20.843976+00:00 app[web.1]: File "/app/./app/config.py", line 20, in <module>
2022-01-30T17:36:20.843977+00:00 app[web.1]: settings = Settings()
2022-01-30T17:36:20.843990+00:00 app[web.1]: File "pydantic/env_settings.py", line 38, in pydantic.env_settings.BaseSettings.__init__
2022-01-30T17:36:20.844004+00:00 app[web.1]: File "pydantic/main.py", line 331, in pydantic.main.BaseModel.__init__
2022-01-30T17:36:20.844050+00:00 app[web.1]: pydantic.error_wrappers.ValidationError: 2 validation errors
for Settings
2022-01-30T17:36:20.844050+00:00 app[web.1]: database_hostname
2022-01-30T17:36:20.844050+00:00 app[web.1]: field required (type=value_error.missing)
2022-01-30T17:36:20.844051+00:00 app[web.1]: access_token_expire_minutes
2022-01-30T17:36:20.844051+00:00 app[web.1]: field required (type=value_error.missing)
2022-01-30T17:36:24.575359+00:00 app[api]: Release v42 created by user carlstraumann@gmail.com
2022-01-30T17:36:24.575359+00:00 app[api]: Set ACCESS_TOKEN_EXPIRE_MINUTES config vars by user carlstraumann@gmail.com
2022-01-30T17:36:25.970437+00:00 heroku[web.1]: Restarting
2022-01-30T17:36:30.427409+00:00 heroku[web.1]: Starting process with command `uvicorn app.main:app --host=0.0.0.0 --port=${PORT:-5000}`
2022-01-30T17:36:31.971812+00:00 app[web.1]: INFO: Uvicorn running on http://0.0.0.0:5337 (Press CTRL+C to quit)
2022-01-30T17:36:31.971890+00:00 app[web.1]: INFO: Started parent process [4]
2022-01-30T17:36:34.033473+00:00 app[web.1]: Process SpawnProcess-1:
2022-01-30T17:36:34.034793+00:00 app[web.1]: Process SpawnProcess-2:
2022-01-30T17:36:34.035643+00:00 app[web.1]: Traceback (most recent call last):
2022-01-30T17:36:34.035742+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/multiprocessing/process.py", line 315, in _bootstrap
2022-01-30T17:36:34.035742+00:00 app[web.1]: self.run()
2022-01-30T17:36:34.035745+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/multiprocessing/process.py", line 108, in run
2022-01-30T17:36:34.035745+00:00 app[web.1]: self._target(*self._args, **self._kwargs)
2022-01-30T17:36:34.035747+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/uvicorn/subprocess.py", line 76, in subprocess_started
2022-01-30T17:36:34.035748+00:00 app[web.1]: target(sockets=sockets)
2022-01-30T17:36:34.035759+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/uvicorn/server.py", line 68, in run
2022-01-30T17:36:34.035760+00:00 app[web.1]: return asyncio.run(self.serve(sockets=sockets))
2022-01-30T17:36:34.035762+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/asyncio/runners.py",
line 44, in run
2022-01-30T17:36:34.035763+00:00 app[web.1]: return loop.run_until_complete(main)
2022-01-30T17:36:34.035773+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/asyncio/base_events.py", line 642, in run_until_complete
2022-01-30T17:36:34.035774+00:00 app[web.1]: return future.result()
2022-01-30T17:36:34.035776+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/uvicorn/server.py", line 76, in serve
2022-01-30T17:36:34.035776+00:00 app[web.1]: config.load()
2022-01-30T17:36:34.035791+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/uvicorn/config.py", line 448, in load
2022-01-30T17:36:34.035791+00:00 app[web.1]: self.loaded_app = import_from_string(self.app)
2022-01-30T17:36:34.035813+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/uvicorn/importer.py", line 21, in import_from_string
2022-01-30T17:36:34.035814+00:00 app[web.1]: module = importlib.import_module(module_str)
2022-01-30T17:36:34.035816+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/importlib/__init__.py", line 127, in import_module
2022-01-30T17:36:34.035816+00:00 app[web.1]: return _bootstrap._gcd_import(name[level:], package, level)
2022-01-30T17:36:34.035827+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1030, in _gcd_import
2022-01-30T17:36:34.035830+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1007, in _find_and_load
2022-01-30T17:36:34.035842+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked
2022-01-30T17:36:34.035844+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 680, in _load_unlocked
2022-01-30T17:36:34.035856+00:00 app[web.1]: File "<frozen importlib._bootstrap_external>", line 850, in exec_module
2022-01-30T17:36:34.035858+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed
2022-01-30T17:36:34.035884+00:00 app[web.1]: File "/app/./app/main.py", line 3, in <module>
2022-01-30T17:36:34.035885+00:00 app[web.1]: from . import models
2022-01-30T17:36:34.035896+00:00 app[web.1]: File "/app/./app/models.py", line 3, in <module>
2022-01-30T17:36:34.035896+00:00 app[web.1]: from .database import Base
2022-01-30T17:36:34.035898+00:00 app[web.1]: File "/app/./app/database.py", line 7, in <module>
2022-01-30T17:36:34.035899+00:00 app[web.1]: from .config import settings
2022-01-30T17:36:34.035910+00:00 app[web.1]: File "/app/./app/config.py", line 20, in <module>
2022-01-30T17:36:34.035910+00:00 app[web.1]: settings = Settings()
2022-01-30T17:36:34.035913+00:00 app[web.1]: File "pydantic/env_settings.py", line 38, in pydantic.env_settings.BaseSettings.__init__
2022-01-30T17:36:34.035924+00:00 app[web.1]: File "pydantic/main.py", line 331, in pydantic.main.BaseModel.__init__
2022-01-30T17:36:34.035946+00:00 app[web.1]: pydantic.error_wrappers.ValidationError: 1 validation error for Settings
2022-01-30T17:36:34.035947+00:00 app[web.1]: database_hostname
2022-01-30T17:36:34.035947+00:00 app[web.1]: field required (type=value_error.missing)
2022-01-30T17:36:34.036613+00:00 app[web.1]: Traceback (most recent call last):
2022-01-30T17:36:34.036697+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/multiprocessing/process.py", line 315, in _bootstrap
2022-01-30T17:36:34.036698+00:00 app[web.1]: self.run()
2022-01-30T17:36:34.036714+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/multiprocessing/process.py", line 108, in run
2022-01-30T17:36:34.036714+00:00 app[web.1]: self._target(*self._args, **self._kwargs)
2022-01-30T17:36:34.036733+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/uvicorn/subprocess.py", line 76, in subprocess_started
2022-01-30T17:36:34.036734+00:00 app[web.1]: target(sockets=sockets)
2022-01-30T17:36:34.036749+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/uvicorn/server.py", line 68, in run
2022-01-30T17:36:34.036749+00:00 app[web.1]: return asyncio.run(self.serve(sockets=sockets))
2022-01-30T17:36:34.036764+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/asyncio/runners.py",
line 44, in run
2022-01-30T17:36:34.036764+00:00 app[web.1]: return loop.run_until_complete(main)
2022-01-30T17:36:34.036779+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/asyncio/base_events.py", line 642, in run_until_complete
2022-01-30T17:36:34.036779+00:00 app[web.1]: return future.result()
2022-01-30T17:36:34.036794+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/uvicorn/server.py", line 76, in serve
2022-01-30T17:36:34.036794+00:00 app[web.1]: config.load()
2022-01-30T17:36:34.036809+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/uvicorn/config.py", line 448, in load
2022-01-30T17:36:34.036810+00:00 app[web.1]: self.loaded_app = import_from_string(self.app)
2022-01-30T17:36:34.036825+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/uvicorn/importer.py", line 21, in import_from_string
2022-01-30T17:36:34.036825+00:00 app[web.1]: module = importlib.import_module(module_str)
2022-01-30T17:36:34.036840+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/importlib/__init__.py", line 127, in import_module
2022-01-30T17:36:34.036840+00:00 app[web.1]: return _bootstrap._gcd_import(name[level:], package, level)
2022-01-30T17:36:34.036855+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1030, in _gcd_import
2022-01-30T17:36:34.036869+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1007, in _find_and_load
2022-01-30T17:36:34.036884+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked
2022-01-30T17:36:34.036898+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 680, in _load_unlo
(venv) C:\Users\HP\OneDrive\Рабочий стол\PythonBootcamp\Python\fast_api-social-media>heroku ps:restart
Restarting dynos on ⬢ fastapi-sam... done
(venv) C:\Users\HP\OneDrive\Рабочий стол\PythonBootcamp\Python\fast_api-social-media>heroku logs -t
2022-01-30T17:36:24.575359+00:00 app[api]: Set ACCESS_TOKEN_EXPIRE_MINUTES config vars by user carlstraumann@gmail.com
2022-01-30T17:36:25.970437+00:00 heroku[web.1]: Restarting
2022-01-30T17:36:30.427409+00:00 heroku[web.1]: Starting process with command `uvicorn app.main:app --host=0.0.0.0 --port=${PORT:-5000}`
2022-01-30T17:36:31.971812+00:00 app[web.1]: INFO: Uvicorn running on http://0.0.0.0:5337 (Press CTRL+C to quit)
2022-01-30T17:36:31.971890+00:00 app[web.1]: INFO: Started parent process [4]
2022-01-30T17:36:34.033473+00:00 app[web.1]: Process SpawnProcess-1:
2022-01-30T17:36:34.034793+00:00 app[web.1]: Process SpawnProcess-2:
2022-01-30T17:36:34.035643+00:00 app[web.1]: Traceback (most recent call last):
2022-01-30T17:36:34.035742+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/multiprocessing/process.py", line 315, in _bootstrap
2022-01-30T17:36:34.035742+00:00 app[web.1]: self.run()
2022-01-30T17:36:34.035745+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/multiprocessing/process.py", line 108, in run
2022-01-30T17:36:34.035745+00:00 app[web.1]: self._target(*self._args, **self._kwargs)
2022-01-30T17:36:34.035747+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/uvicorn/subprocess.py", line 76, in subprocess_started
2022-01-30T17:36:34.035748+00:00 app[web.1]: target(sockets=sockets)
2022-01-30T17:36:34.035759+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/uvicorn/server.py", line 68, in run
2022-01-30T17:36:34.035760+00:00 app[web.1]: return asyncio.run(self.serve(sockets=sockets))
2022-01-30T17:36:34.035762+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/asyncio/runners.py", line 44, in run
2022-01-30T17:36:34.035763+00:00 app[web.1]: return loop.run_until_complete(main)
2022-01-30T17:36:34.035773+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/asyncio/base_events.py", line 642, in run_until_complete
2022-01-30T17:36:34.035774+00:00 app[web.1]: return future.result()
2022-01-30T17:36:34.035776+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/uvicorn/server.py", line 76, in serve
2022-01-30T17:36:34.035776+00:00 app[web.1]: config.load()
2022-01-30T17:36:34.035791+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/uvicorn/config.py", line 448, in load
2022-01-30T17:36:34.035791+00:00 app[web.1]: self.loaded_app = import_from_string(self.app)
2022-01-30T17:36:34.035813+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/uvicorn/importer.py", line 21, in import_from_string
2022-01-30T17:36:34.035814+00:00 app[web.1]: module = importlib.import_module(module_str)
2022-01-30T17:36:34.035816+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/importlib/__init__.py", line 127, in import_module
2022-01-30T17:36:34.035816+00:00 app[web.1]: return _bootstrap._gcd_import(name[level:], package, level)
2022-01-30T17:36:34.035827+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1030, in _gcd_import
2022-01-30T17:36:34.035830+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1007, in _find_and_load
2022-01-30T17:36:34.035842+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked
2022-01-30T17:36:34.035844+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 680, in _load_unlocked
2022-01-30T17:36:34.035856+00:00 app[web.1]: File "<frozen importlib._bootstrap_external>", line 850, in exec_module
2022-01-30T17:36:34.035858+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed
2022-01-30T17:36:34.035884+00:00 app[web.1]: File "/app/./app/main.py", line 3, in <module>
2022-01-30T17:36:34.035885+00:00 app[web.1]: from . import models
2022-01-30T17:36:34.035896+00:00 app[web.1]: File "/app/./app/models.py", line 3, in <module>
2022-01-30T17:36:34.035896+00:00 app[web.1]: from .database import Base
2022-01-30T17:36:34.035898+00:00 app[web.1]: File "/app/./app/database.py", line 7, in <module>
2022-01-30T17:36:34.035899+00:00 app[web.1]: from .config import settings
2022-01-30T17:36:34.035910+00:00 app[web.1]: File "/app/./app/config.py", line 20, in <module>
2022-01-30T17:36:34.035910+00:00 app[web.1]: settings = Settings()
2022-01-30T17:36:34.035913+00:00 app[web.1]: File "pydantic/env_settings.py", line 38, in pydantic.env_settings.BaseSettings.__init__
2022-01-30T17:36:34.035924+00:00 app[web.1]: File "pydantic/main.py", line 331, in pydantic.main.BaseModel.__init__
2022-01-30T17:36:34.035946+00:00 app[web.1]: pydantic.error_wrappers.ValidationError: 1 validation error for Settings
2022-01-30T17:36:34.035947+00:00 app[web.1]: database_hostname
2022-01-30T17:36:34.035947+00:00 app[web.1]: field required (type=value_error.missing)
2022-01-30T17:36:34.036613+00:00 app[web.1]: Traceback (most recent call last):
2022-01-30T17:36:34.036697+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/multiprocessing/process.py", line 315, in _bootstrap
2022-01-30T17:36:34.036698+00:00 app[web.1]: self.run()
2022-01-30T17:36:34.036714+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/multiprocessing/process.py", line 108, in run
2022-01-30T17:36:34.036714+00:00 app[web.1]: self._target(*self._args, **self._kwargs)
2022-01-30T17:36:34.036733+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/uvicorn/subprocess.py", line 76, in subprocess_started
2022-01-30T17:36:34.036734+00:00 app[web.1]: target(sockets=sockets)
2022-01-30T17:36:34.036749+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/uvicorn/server.py", line 68, in run
2022-01-30T17:36:34.036749+00:00 app[web.1]: return asyncio.run(self.serve(sockets=sockets))
2022-01-30T17:36:34.036764+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/asyncio/runners.py", line 44, in run
2022-01-30T17:36:34.036764+00:00 app[web.1]: return loop.run_until_complete(main)
2022-01-30T17:36:34.036779+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/asyncio/base_events.py", line 642, in run_until_complete
2022-01-30T17:36:34.036779+00:00 app[web.1]: return future.result()
2022-01-30T17:36:34.036794+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/uvicorn/server.py", line 76, in serve
2022-01-30T17:36:34.036794+00:00 app[web.1]: config.load()
2022-01-30T17:36:34.036809+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/uvicorn/config.py", line 448, in load
2022-01-30T17:36:34.036810+00:00 app[web.1]: self.loaded_app = import_from_string(self.app)
2022-01-30T17:36:34.036825+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/uvicorn/importer.py", line 21, in import_from_string
2022-01-30T17:36:34.036825+00:00 app[web.1]: module = importlib.import_module(module_str)
2022-01-30T17:36:34.036840+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/importlib/__init__.py", line 127, in import_module
2022-01-30T17:36:34.036840+00:00 app[web.1]: return _bootstrap._gcd_import(name[level:], package, level)
2022-01-30T17:36:34.036855+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1030, in _gcd_import
2022-01-30T17:36:34.036869+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1007, in _find_and_load
2022-01-30T17:36:34.036884+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked
2022-01-30T17:36:34.036898+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 680, in _load_unlocked
2022-01-30T17:36:34.036913+00:00 app[web.1]: File "<frozen importlib._bootstrap_external>", line 850, in exec_module
2022-01-30T17:36:34.036927+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed
2022-01-30T17:36:34.036942+00:00 app[web.1]: File "/app/./app/main.py", line 3, in <module>
2022-01-30T17:36:34.036942+00:00 app[web.1]: from . import models
2022-01-30T17:36:34.036957+00:00 app[web.1]: File "/app/./app/models.py", line 3, in <module>
2022-01-30T17:36:34.036957+00:00 app[web.1]: from .database import Base
2022-01-30T17:36:34.036972+00:00 app[web.1]: File "/app/./app/database.py", line 7, in <module>
2022-01-30T17:36:34.036973+00:00 app[web.1]: from .config import settings
2022-01-30T17:36:34.036988+00:00 app[web.1]: File "/app/./app/config.py", line 20, in <module>
2022-01-30T17:36:34.036988+00:00 app[web.1]: settings = Settings()
2022-01-30T17:36:34.037002+00:00 app[web.1]: File "pydantic/env_settings.py", line 38, in pydantic.env_settings.BaseSettings.__init__
2022-01-30T17:36:34.037017+00:00 app[web.1]: File "pydantic/main.py", line 331, in pydantic.main.BaseModel.__init__
2022-01-30T17:36:34.037044+00:00 app[web.1]: pydantic.error_wrappers.ValidationError: 1 validation error for Settings
2022-01-30T17:36:34.037045+00:00 app[web.1]: database_hostname
2022-01-30T17:36:34.037045+00:00 app[web.1]: field required (type=value_error.missing)
2022-01-30T17:36:37.912121+00:00 heroku[web.1]: Error R10 (Boot timeout) -> Web process failed to bind to $PORT within 60 seconds of launch
2022-01-30T17:36:37.945001+00:00 heroku[web.1]: Stopping process with SIGKILL
2022-01-30T17:36:38.178707+00:00 heroku[web.1]: Process exited with status 137
2022-01-30T17:36:49.093141+00:00 heroku[web.1]: Stopping all processes with SIGTERM
2022-01-30T17:36:49.178611+00:00 app[web.1]: INFO: Stopping parent process [4]
2022-01-30T17:36:49.396356+00:00 heroku[web.1]: Process exited with status 0
2022-01-30T17:36:59.178430+00:00 heroku[web.1]: Error R10 (Boot timeout) -> Web process failed to bind to $PORT within 60 seconds of launch
2022-01-30T17:36:59.235776+00:00 heroku[web.1]: Stopping process with SIGKILL
2022-01-30T17:36:59.405074+00:00 heroku[web.1]: Process exited with status 137
2022-01-30T17:37:05.783578+00:00 heroku[web.1]: Restarting
2022-01-30T17:37:10.878424+00:00 heroku[web.1]: Starting process with command `uvicorn app.main:app --host=0.0.0.0 --port=${PORT:-5000}`
2022-01-30T17:37:12.206224+00:00 app[web.1]: INFO: Uvicorn running on http://0.0.0.0:33262 (Press CTRL+C to quit)
2022-01-30T17:37:12.206331+00:00 app[web.1]: INFO: Started parent process [4]
2022-01-30T17:37:16.049293+00:00 app[web.1]: Process SpawnProcess-1:
2022-01-30T17:37:16.051032+00:00 app[web.1]: Traceback (most recent call last):
2022-01-30T17:37:16.055811+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/multiprocessing/process.py", line 315, in _bootstrap
2022-01-30T17:37:16.055813+00:00 app[web.1]: self.run()
2022-01-30T17:37:16.055835+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/multiprocessing/process.py", line 108, in run
2022-01-30T17:37:16.055836+00:00 app[web.1]: self._target(*self._args, **self._kwargs)
2022-01-30T17:37:16.055853+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/uvicorn/subprocess.py", line 76, in subprocess_started
2022-01-30T17:37:16.055854+00:00 app[web.1]: target(sockets=sockets)
2022-01-30T17:37:16.055870+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/uvicorn/server.py", line 68, in run
2022-01-30T17:37:16.055872+00:00 app[web.1]: return asyncio.run(self.serve(sockets=sockets))
2022-01-30T17:37:16.055889+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/asyncio/runners.py", line 44, in run
2022-01-30T17:37:16.055889+00:00 app[web.1]: return loop.run_until_complete(main)
2022-01-30T17:37:16.055906+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/asyncio/base_events.py", line 642, in run_until_complete
2022-01-30T17:37:16.055906+00:00 app[web.1]: return future.result()
2022-01-30T17:37:16.055923+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/uvicorn/server.py", line 76, in serve
2022-01-30T17:37:16.055923+00:00 app[web.1]: config.load()
2022-01-30T17:37:16.055940+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/uvicorn/config.py", line 448, in load
2022-01-30T17:37:16.055940+00:00 app[web.1]: self.loaded_app = import_from_string(self.app)
2022-01-30T17:37:16.055956+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/uvicorn/importer.py", line 21, in import_from_string
2022-01-30T17:37:16.055957+00:00 app[web.1]: module = importlib.import_module(module_str)
2022-01-30T17:37:16.055973+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/importlib/__init__.py", line 127, in import_module
2022-01-30T17:37:16.055973+00:00 app[web.1]: return _bootstrap._gcd_import(name[level:], package, level)
2022-01-30T17:37:16.055990+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1030, in _gcd_import
2022-01-30T17:37:16.056006+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1007, in _find_and_load
2022-01-30T17:37:16.056022+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked
2022-01-30T17:37:16.056039+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 680, in _load_unlocked
2022-01-30T17:37:16.056055+00:00 app[web.1]: File "<frozen importlib._bootstrap_external>", line 850, in exec_module
2022-01-30T17:37:16.056072+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed
2022-01-30T17:37:16.056088+00:00 app[web.1]: File "/app/./app/main.py", line 3, in <module>
2022-01-30T17:37:16.056089+00:00 app[web.1]: from . import models
2022-01-30T17:37:16.056105+00:00 app[web.1]: File "/app/./app/models.py", line 3, in <module>
2022-01-30T17:37:16.056106+00:00 app[web.1]: from .database import Base
2022-01-30T17:37:16.056122+00:00 app[web.1]: File "/app/./app/database.py", line 7, in <module>
2022-01-30T17:37:16.056122+00:00 app[web.1]: from .config import settings
2022-01-30T17:37:16.056138+00:00 app[web.1]: File "/app/./app/config.py", line 20, in <module>
2022-01-30T17:37:16.056139+00:00 app[web.1]: settings = Settings()
2022-01-30T17:37:16.056155+00:00 app[web.1]: File "pydantic/env_settings.py", line 38, in pydantic.env_settings.BaseSettings.__init__
2022-01-30T17:37:16.056172+00:00 app[web.1]: File "pydantic/main.py", line 331, in pydantic.main.BaseModel.__init__
2022-01-30T17:37:16.056206+00:00 app[web.1]: pydantic.error_wrappers.ValidationError: 1 validation error for Settings
2022-01-30T17:37:16.056207+00:00 app[web.1]: database_hostname
2022-01-30T17:37:16.056207+00:00 app[web.1]: field required (type=value_error.missing)
2022-01-30T17:37:16.083410+00:00 app[web.1]: Process SpawnProcess-2:
2022-01-30T17:37:16.084901+00:00 app[web.1]: Traceback (most recent call last):
2022-01-30T17:37:16.090024+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/multiprocessing/process.py", line 315, in _bootstrap
2022-01-30T17:37:16.090025+00:00 app[web.1]: self.run()
2022-01-30T17:37:16.090697+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/multiprocessing/process.py", line 108, in run
2022-01-30T17:37:16.090699+00:00 app[web.1]: self._target(*self._args, **self._kwargs)
2022-01-30T17:37:16.090717+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/uvicorn/subprocess.py", line 76, in subprocess_started
2022-01-30T17:37:16.090718+00:00 app[web.1]: target(sockets=sockets)
2022-01-30T17:37:16.090734+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/uvicorn/server.py", line 68, in run
2022-01-30T17:37:16.090735+00:00 app[web.1]: return asyncio.run(self.serve(sockets=sockets))
2022-01-30T17:37:16.090752+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/asyncio/runners.py", line 44, in run
2022-01-30T17:37:16.090752+00:00 app[web.1]: return loop.run_until_complete(main)
2022-01-30T17:37:16.090768+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/asyncio/base_events.py", line 642, in run_until_complete
2022-01-30T17:37:16.090769+00:00 app[web.1]: return future.result()
2022-01-30T17:37:16.090785+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/uvicorn/server.py", line 76, in serve
2022-01-30T17:37:16.090785+00:00 app[web.1]: config.load()
2022-01-30T17:37:16.090801+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/uvicorn/config.py", line 448, in load
2022-01-30T17:37:16.090802+00:00 app[web.1]: self.loaded_app = import_from_string(self.app)
2022-01-30T17:37:16.090817+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/site-packages/uvicorn/importer.py", line 21, in import_from_string
2022-01-30T17:37:16.090818+00:00 app[web.1]: module = importlib.import_module(module_str)
2022-01-30T17:37:16.090834+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/importlib/__init__.py", line 127, in import_module
2022-01-30T17:37:16.090835+00:00 app[web.1]: return _bootstrap._gcd_import(name[level:], package, level)
2022-01-30T17:37:16.090850+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1030, in _gcd_import
2022-01-30T17:37:16.090867+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1007, in _find_and_load
2022-01-30T17:37:16.090884+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked
2022-01-30T17:37:16.090900+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 680, in _load_unlocked
2022-01-30T17:37:16.090916+00:00 app[web.1]: File "<frozen importlib._bootstrap_external>", line 850, in exec_module
2022-01-30T17:37:16.090932+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed
2022-01-30T17:37:16.090948+00:00 app[web.1]: File "/app/./app/main.py", line 3, in <module>
2022-01-30T17:37:16.090948+00:00 app[web.1]: from . import models
2022-01-30T17:37:16.090964+00:00 app[web.1]: File "/app/./app/models.py", line 3, in <module>
2022-01-30T17:37:16.090965+00:00 app[web.1]: from .database import Base
2022-01-30T17:37:16.090981+00:00 app[web.1]: File "/app/./app/database.py", line 7, in <module>
2022-01-30T17:37:16.090982+00:00 app[web.1]: from .config import settings
2022-01-30T17:37:16.090998+00:00 app[web.1]: File "/app/./app/config.py", line 20, in <module>
2022-01-30T17:37:16.090998+00:00 app[web.1]: settings = Settings()
2022-01-30T17:37:16.091014+00:00 app[web.1]: File "pydantic/env_settings.py", line 38, in pydantic.env_settings.BaseSettings.__init__
2022-01-30T17:37:16.091030+00:00 app[web.1]: File "pydantic/main.py", line 331, in pydantic.main.BaseModel.__init__
2022-01-30T17:37:16.091066+00:00 app[web.1]: pydantic.error_wrappers.ValidationError: 1 validation error for Settings
2022-01-30T17:37:16.091066+00:00 app[web.1]: database_hostname
2022-01-30T17:37:16.091067+00:00 app[web.1]: field required (type=value_error.missing)
2022-01-30T17:37:27.864676+00:00 heroku[web.1]: Stopping all processes with SIGTERM
2022-01-30T17:37:27.907957+00:00 app[web.1]: INFO: Stopping parent process [4]
2022-01-30T17:37:28.081625+00:00 heroku[web.1]: Process exited with status 0
2022-01-30T17:38:11.062535+00:00 heroku[web.1]: Error R10 (Boot timeout) -> Web process failed to bind to $PORT within 60 seconds of launch
2022-01-30T17:38:11.137884+00:00 heroku[web.1]: Stopping process with SIGKILL
2022-01-30T17:38:11.438440+00:00 heroku[web.1]: Process exited with status 137
2022-01-30T17:38:11.491140+00:00 heroku[web.1]: State changed from starting to crashed
</code></pre>
<p>As you can see it is giving out pydanctic errors. I did restart via heroku ps:restart, too.</p>
<p>This is my config.py file</p>
<pre><code>from pydantic import BaseSettings
from app import database
class Settings(BaseSettings):
database_hostname: str
database_port: str
database_password: str
database_name: str
database_username: str
secret_key: str
algorithm: str
access_token_expire_minutes: int
class Config:
env_file = ".env"
settings = Settings()
</code></pre>
|
<p>You are using individual settings for your database hostname, port, user, password, and database name. But Heroku provides database credentials as a single value, via the <code>DATABASE_URL</code> environment variable.</p>
<p>Database URLs are quite common, and there's a good chance you can just pass one into whatever you're using to create your database connection.</p>
<p>I suggest you modify your settings class to do the same:</p>
<pre class="lang-py prettyprint-override"><code>class Settings(BaseSettings):
database_url: str
# ...other, non-database stuff
</code></pre>
<p>Then you can update your <code>.env</code> file to contain a database URL instead of individual values, e.g. something like</p>
<pre class="lang-sh prettyprint-override"><code># Replace
#
# DATABASE_HOSTNAME=database-host.tld
# DATABASE_PORT=5432
# DATABASE_PASSWORD=password
# DATABASE_NAME=project-database
# DATABASE_USERNAME=user
#
# with
#
DATABASE_URL=postgres://user:password@database-host.tld:5432/project-database
</code></pre>
<p>If you <em>really</em> want to keep using individual values you'll have to parse the <code>DATABASE_URL</code>, e.g. using <a href="https://docs.python.org/library/urllib.parse.html#urllib.parse.urlparse" rel="nofollow noreferrer"><code>urllib.parse.urlparse</code></a>.</p>
<p>Note that your <code>.env</code> file should be ignored. It should never make its way to Heroku.</p>
|
python|heroku|fastapi
| 0 |
1,908,621 | 70,738,417 |
GitLab CI/CD pytests
|
<p>I'm trying to understand one particular job in CI/CD pipeline, which has the following logic:</p>
<pre><code> test:
stage: test
image: python:3.8
rules:
- if: $CI_COMMIT_TAG
when: never
- when: always
before_script:
- mkdir -p ~/.ssh && chmod 700 ~/.ssh
- ssh-keyscan -H gitlab.com >> ~/.ssh/known_hosts
- eval $(ssh-agent -s)
- echo "$DEPLOY_KEY" | ssh-add -
- pip3 install poetry==$POETRY_VERSION
- poetry install
- source $(poetry env info --path)/bin/activate
script:
- pytest tests
</code></pre>
<p>For now it seems like we're going to run multiple unit tests under the tests folder in the root of our GitLab project using the python image to actually run the python code, which is more or less obvious why. To actually run the tests we would need some dependencies that are listed in the poetry.lock file, so we install poetry package manager and all the needed libraries. My understanding ends here. I'm particularly interested in the first 4 commands and the last one (activate something like a virtual env?) under the before_script tag. Why do we need them and what do they do? The same goes for the rules tag. Why do we check for this $CI_COMMIT_TAG variable? Any help would be appreciated, thanks!</p>
|
<p>CI_COMMIT_TAG is one of <a href="https://docs.gitlab.com/ee/ci/variables/" rel="nofollow noreferrer">GitLab CI/CD variables</a>, populated by gitlab itself on every CI/CD job</p>
<pre><code> rules:
- if: $CI_COMMIT_TAG
when: never
- when: always
</code></pre>
<p>Basically says 'skip this job if commit has an attached tag, run otherwise'. So your tests should run on any untagged commits.</p>
<p>The first 4 commands are needed to configure SSH agent in a container, let's break in down:</p>
<pre><code>mkdir -p ~/.ssh && chmod 700 ~/.ssh
</code></pre>
<p>create .ssh directory and restrict access to it. This is necessary, because by default, there is no .ssh folder, and ~/.ssh/known_hosts is file used by ssh to validate remote server keys</p>
<pre><code>ssh-keyscan -H gitlab.com >> ~/.ssh/known_hosts
</code></pre>
<p>this command gets fingerprint of gitlab.com public key and puts it into ~/.ssh/known_hosts. Without filling known hosts, any ssh command, aimed towards gitlab.com would ask you to confirm if you trust this server or not. This exact command kinda pointless from security perspective, because it just blindly trusts whatever server host key is present, and doesn't protect from MitM attacks. The proper way of doing it should be manually adding this key to your pipelines, i.e. by storing it inside some variable and echoing into ~/.ssh/known_hosts . See <a href="https://docs.gitlab.com/ee/user/gitlab_com/#ssh-host-keys-fingerprints" rel="nofollow noreferrer">https://docs.gitlab.com/ee/user/gitlab_com/#ssh-host-keys-fingerprints</a> to get correct known_hosts entries</p>
<pre><code>eval $(ssh-agent -s)
</code></pre>
<p>this command launches ssh-agent - so every subsequent SSH command won't prompt you for password.</p>
<pre><code>echo "$DEPLOY_KEY" | ssh-add -
</code></pre>
<p>adds a deploy key to ssh-agent, so any subsequent SSH commands would automatically use it.</p>
<p>Personally, depending on your risk model, I'd skip all "ssh-agent" stuff and just echo your deploy into ~/.ssh/id_rsa. There reason why agent is used might be to not ever store your deploy key on any filesystem, since variables are stored in memory, and ssh-agents also work from memory.</p>
<p>Finally, <code>source $(poetry env info --path)/bin/activate</code> just enters a virtualenv of this project. Poetry is a neat packaging and dependency management tool,when you ran a <code>poetry install</code> command, it automatically generated a venv for you. <code>poetry env info --path</code> prints path to venv root directory, and <code>source</code> command executes instructions in <code>bin/activate</code> inside venv.</p>
<p>This is also seems unnecessary, because you can just run</p>
<pre><code>poetry run pytest tests
</code></pre>
<p>inside <code>script:</code> section, and it will execute pytest inside poetry env.</p>
|
gitlab|pytest|gitlab-ci|python-poetry
| 0 |
1,908,622 | 2,540,043 |
Return current 11-digit timestamp in Python
|
<p>How can I return the current time of the local machine?</p>
|
<p>Do you mean this: <a href="http://docs.python.org/library/time.html#time.time" rel="noreferrer">time.time()</a>?</p>
<p>From the docs:</p>
<p><em>Return the time as a floating point number expressed in seconds since the epoch, in UTC</em></p>
<pre><code>>>> import time
>>> time.time()
1269884900.480978
>>>
</code></pre>
|
python|timestamp
| 40 |
1,908,623 | 5,649,385 |
Many to One relationship with SQLAlchemy in the same table
|
<p>I have a table of 'Clients' where a client can be a child of another client.</p>
<p>Here's the table definition.</p>
<pre><code>[ClientID] [int] IDENTITY(1,1) NOT NULL,
[name] [varchar](50) NOT NULL,
[VPFSID] [varchar](50) NOT NULL,
[Type] [varchar](25) NULL,
[ROHostID] [varchar](60) NOT NULL,
[RWHostID] [varchar](60) NOT NULL,
[ParentClientID] [int] NULL
</code></pre>
<p>In SQLAlchemy, how do I create the relationship between the ParentClientID and ClientID. I put together this class using declarative but I'm not sure if it's valid or not. A Client can have many children, but can only have a single parent, so it's a Many-to-1 relationship</p>
<pre><code>class Client(Base):
""" Client Filesystems """
__tablename__ = 'Client'
client_id = Column('ClientID', int, primary_key=True, nullable=Flase)
name = Column('name', String(50), nullable=False)
vpfs_id = Column('VPFSID', String(50), nullable=False)
type = Column('Type',String(25))
ro_host_id = Column('ROHostID', String(60), ForeignKey('DataMover.HostID'), nullable=False)
rw_host_id = Column('RWHostID', String(60), ForeignKey('DataMover.HostID'), nullable=False)
rw_host = relation('Datamover',backref="rw_clients")
ro_host = relation('Datamover',backref="ro_clients")
parent_client_id = Column('ParentClientID',int,ForeignKey('Client.ClientID'))
parent = relation('Client',ForeignKey('Client.ClientID'))
</code></pre>
<p>Any suggestions on accomplishing this?</p>
|
<pre><code>class Client(Base):
...<snip>...
parent = relation('Client', remote_side=[client_id])
</code></pre>
<p>Docs here: <a href="http://docs.sqlalchemy.org/en/rel_1_0/orm/self_referential.html" rel="noreferrer">orm/self_referential.html</a></p>
|
python|sql|sqlalchemy
| 18 |
1,908,624 | 5,728,279 |
Handling application/json data with bottle
|
<p>I'm trying to write a simple server frontend to a python3 application, using a restful JSON-based protocol. So far, <a href="http://bottlepy.org" rel="nofollow">bottle</a> seems the best suited framework for the task (it supports python3, handles method dispatching in a nice way, and easily returns JSON.) The problem is parsing the JSON in the input request.</p>
<p>The documentation only mention <code>request.fields</code> and <code>request.files</code>, both I assume refer to multipart/form-data data. No mention of accessing the request data directly.</p>
<p>Peeking at the source code, I can see a <code>request.body</code> object of type BytesIO. <code>json.load</code> refuses to act on it directly, dying in the json lib with <code>can't use a string pattern on a bytes-like object</code>. The proper way to do it may be to first decode the bytes to unicode characters, according to whichever charset was specified in the <code>Content-Type</code> HTTP header. I don't know how to do that; I can see a StringIO class and assume it may hold a buffer of characters instead of bytes, but see no way of decoding a BytesIO to a StringIO, if this is even possible at all.</p>
<p>Of course, it may also be possible to read the BytesIO object into a bytestring, then decode it into a string before passing it to the JSON decoder, but if I understand correctly, that breaks the nice buffering behavior of the whole thing.</p>
<p>Or is there any better way to do it ?</p>
|
<p>It seems that <a href="http://docs.python.org/py3k/library/io.html?highlight=textiowrapper#io.TextIOWrapper" rel="nofollow">io.TextIOWrapper</a> from the standard library does the trick !</p>
<pre><code>def parse(request):
encoding = ... #get encoding from headers
return json.load(TextIOWrapper(request.body, encoding=encoding))
</code></pre>
|
json|python-3.x|bottle
| 2 |
1,908,625 | 30,466,039 |
I just want direct children of an XML element, not all descendents
|
<p>I have an XML document that represents a directed graph. It contains a large number of direct children, all with ids, and a large number of nested children, all with the same tag names but no ids, just references. </p>
<p>I would like to iterate over all of the direct children of the root node, but exclude the nested children. The files look something like this, but with hundreds of nodes and dozens of different tags:</p>
<pre><code><graph>
<foo id="f1"><bar ref="b1" /><baz ref="z1" />...</foo>
<bar id="b1"><foo ref="f1" /></bar>
<baz id="z1"></baz>
...
</graph>
</code></pre>
<p>I don't want to use <code>getElementsByTagName</code> because it returns all descendents. I suspect I will need to use <code>.childnodes</code> and filter the results, but I want to make sure there isn't something I'm missing.</p>
<p>Also, I don't have control of the input, it's from an outside source, and I'm using Python's xml.dom.minidom module, but I expect that to be an implementation detail.</p>
|
<p>Not really sure what you wanted to get out of the directed children, so gave you a few different examples. </p>
<pre><code>from lxml import etree
root = etree.fromstring(xml)
for node in root.iter("graph"):
#To get the namespaces of the direct children
namespaces = [child.namespace for child in node]
#To get the tags of the direct children
tags = [child.tag for child in node]
#To get the text of the direct children
texts = [child.text for child in node]
</code></pre>
|
python|xml|dom|xml-parsing
| 1 |
1,908,626 | 30,577,483 |
sorting csv python 2.7
|
<p>I am trying to sort a csv file on column 3. python sorts the csv but for two rows. Really confused</p>
<p>here is the code i am using.</p>
<pre><code>import csv
import operator
import numpy
sample = open('data.csv','rU')
csv1 = csv.reader(sample,delimiter=',')
sort=sorted(csv1,key=lambda x:x[3])
for eachline in sort:
print eachline
</code></pre>
<p>and here is the o/p From the third row the O/P looks good. Any ideas ?</p>
<pre><code>['6/23/02', 'Julian Jaynes', '618057072', '12.5']
['7/15/98', 'Timothy "The Parser" Campbell', '968411304', '18.99']
['10/4/04', 'Randel Helms', '879755725', '4.5']
['9/30/03', 'Scott Adams', '740721909', '4.95']
['10/4/04', 'Benjamin Radcliff', '804818088', '4.95']
['1/21/85', 'Douglas Adams', '345391802', '5.95']
['12/3/99', 'Richard Friedman', '60630353', '5.95']
['1/12/90', 'Douglas Hofstadter', '465026567', '9.95']
['9/19/01', 'Karen Armstrong', '345384563', '9.95']
['6/23/02', 'David Jones', '198504691', '9.95']
['REVIEW_DATE', 'AUTHOR', 'ISBN', 'DISCOUNTED_PRICE']
</code></pre>
|
<p>You are sorting strings, you need to use <code>float(x[3])</code></p>
<pre><code>sort=sorted(csv1,key=lambda x:float(x[3]))
</code></pre>
<p>If you want to sort by the third column it is x[2], casting to <code>int</code>:</p>
<pre><code>sort=sorted(csv1,key=lambda x:int(x[2]))
</code></pre>
<p>You will also need to skip the header to avoid a ValueError:</p>
<pre><code>csv1 = csv.reader(sample,delimiter=',')
header = next(csv1)
sort=sorted(csv1,key=lambda x:int(x[2]))
</code></pre>
<p>Python will compare the strings character by character putting <code>"2"</code> after <code>"12"</code> unless you cast to int:</p>
<pre><code>In [82]: "2" < "12"
Out[82]: False
In [83]: int("2") < int("12")
Out[83]: True
</code></pre>
|
python|sorting|csv
| 1 |
1,908,627 | 67,026,086 |
How to compare two timezone strings?
|
<p>Is there some library or built-in to compare two timezones? What I want is the offset of hours between two timezones</p>
<p>For example:</p>
<pre><code>hours = diff_timezones("America/Los_Angeles", "America/Sao_Paulo")
print(hours) # -> 3
</code></pre>
|
<p>FYI: Python 3.9+ ships with <a href="https://docs.python.org/3/library/zoneinfo.html" rel="nofollow noreferrer">zoneinfo</a> in its standard library, while dateutil (below) is a third-party package available on PyPI as <code>python-dateutil</code>.</p>
<hr />
<p>Using <a href="https://dateutil.readthedocs.io/en/stable/tz.html" rel="nofollow noreferrer"><code>dateutil.tz.gettz</code></a>:</p>
<pre class="lang-py prettyprint-override"><code>from datetime import datetime, timedelta
from dateutil.tz import gettz
def diff_timezones(tz1: str, tz2: str) -> timedelta:
zero = datetime.utcfromtimestamp(0)
diff = zero.replace(tzinfo=gettz(tz1)) - zero.replace(tzinfo=gettz(tz2))
return diff
</code></pre>
<p>Sample usage:</p>
<pre><code>>>> diff_timezones('America/Los_Angeles', 'America/Sao_Paulo')
datetime.timedelta(seconds=18000)
</code></pre>
<p>The result here is a <code>datetime.timedelta</code> instance. To get a float of hours:</p>
<pre><code>>>> td.total_seconds() / (60 * 60)
5.0
</code></pre>
<p><strong>CAUTION</strong>: I don't believe this would take into account DST since it uses a fixed datetime of the Unix epoch (1970-01-01), so it might be off in cases where one area obeys DST and another does not. To account for that you might be able to use the current timestamp as a reference date instead.</p>
|
python|timezone|timezone-offset
| 2 |
1,908,628 | 42,681,220 |
plots don't work in matplotlib
|
<p>I am unable to display images in iPython from matplotlib, an image appears for a split of a second in a pop up window instead of inline and then closes immediately. nothing appears in the iPython console which is inside Spyder.</p>
<pre><code>from statistics import mean
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.pyplot import style
style.use('fivethirtyeight')
xs = np.array([1,2,3,4,5,6], dtype=np.float64)
ys = np.array([5,4,6,5,6,7], dtype=np.float64)
def best_fit_slop_and_intercept (xs,ys):
m = ( ((mean(xs)*mean(ys))-mean(xs*ys)) /
((mean(xs)**2)-mean(xs**2)) )
b = mean(ys)-m*mean(xs)
return m,b
m,b = best_fit_slop_and_intercept(xs,ys)
print (m,b)
regression_line = [m*x + b for x in xs ]
print (regression_line)
predict_x = 9
predict_y = predict_x*m + b
plt.scatter(predict_x,predict_y, color = 'g')
plt.scatter(xs,ys)
plt.plot(xs, regression_line)
plt.show()
</code></pre>
|
<p>You can type <code>%matplotlib inline</code> inside the iPython console to generate your plots within the console inside spyder. You can also type <code>%matplotlib qt</code>to get an interactive window.</p>
<p>Your code snippet works for me with both settings. Failing that you can go to [preferences>iPython console>Graphics>Graphics backend] to adjust the graphics defaults and settings to see if that fixes the problem.</p>
|
python|matplotlib|ipython
| 0 |
1,908,629 | 42,697,350 |
How to remove columns from a pre-selected dataframe which contain only NaN's
|
<p>I want to remove all columns which contain only NaN's. This is my example code:</p>
<pre><code>rutte2[[u'50PLUS', u'AOV', u'Bontes', u'Bontes/Van Klaveren',
u'Brinkman', u'CD', u'CDA', u'ChristenUnie', u'D66', u'De Jong',
u'Eerdmans/Van Schijndel', u'GPV', u'GroenLinks', u'Hendriks',
u'Houwers', u'Klein', u'Kortenoeven/Hernandez', u'Kuzu/Öztürk',
u'Lazrak', u'LN', u'LPF', u'Nawijn', u'Nijpels', u'PvdA', u'PvdD',
u'PVV', u'RPF', u'SGP', u'SP', u'Unie 55+', u'Van Klaveren',
u'Van Oudenallen', u'Van Vliet', u'Verdonk', u'Verkerk', u'VVD',
u'Wijnschenk', u'Wilders']].dropna(axis=1, how='all')
</code></pre>
<p>When I do </p>
<pre><code>type(rutte2[[u'50PLUS', u'AOV', u'Bontes', u'Bontes/Van Klaveren',
u'Brinkman', u'CD', u'CDA', u'ChristenUnie', u'D66', u'De Jong',
u'Eerdmans/Van Schijndel', u'GPV', u'GroenLinks', u'Hendriks',
u'Houwers', u'Klein', u'Kortenoeven/Hernandez', u'Kuzu/Öztürk',
u'Lazrak', u'LN', u'LPF', u'Nawijn', u'Nijpels', u'PvdA', u'PvdD',
u'PVV', u'RPF', u'SGP', u'SP', u'Unie 55+', u'Van Klaveren',
u'Van Oudenallen', u'Van Vliet', u'Verdonk', u'Verkerk', u'VVD',
u'Wijnschenk', u'Wilders']])
</code></pre>
<p>it returns this:</p>
<pre><code>pandas.core.frame.DataFrame
</code></pre>
<p>Here's an image for further explanation:</p>
<p><a href="https://i.stack.imgur.com/l9soy.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/l9soy.png" alt="pandas screenshot"></a></p>
<p>Why is this not working?</p>
|
<p>So "type" returns the type of the Python object which apparently in your case is a pandas Dataframe. If you want to print the dataframe use </p>
<pre><code>print rutte2
</code></pre>
<p>or in Python 3.x.</p>
<pre><code>print(rutte2)
</code></pre>
<p>dropna returns a new dataframe with NaN's removed. If you want to remove the NaN's from rutte2 use: </p>
<p>(edit: use subset to do inplace removal on selected columns)</p>
<pre><code>rutte2.dropna(subset=[u'50PLUS', u'AOV', u'Bontes', u'Bontes/Van Klaveren',
u'Brinkman', u'CD', u'CDA', u'ChristenUnie', u'D66', u'De Jong',
u'Eerdmans/Van Schijndel', u'GPV', u'GroenLinks', u'Hendriks',
u'Houwers', u'Klein', u'Kortenoeven/Hernandez', u'Kuzu/Öztürk',
u'Lazrak', u'LN', u'LPF', u'Nawijn', u'Nijpels', u'PvdA', u'PvdD',
u'PVV', u'RPF', u'SGP', u'SP', u'Unie 55+', u'Van Klaveren',
u'Van Oudenallen', u'Van Vliet', u'Verdonk', u'Verkerk', u'VVD',
u'Wijnschenk', u'Wilders'], axis=1, how='all', inplace=True)
</code></pre>
<p>Are you sure rutte2 is not an empty dataframe :-) ?</p>
|
python|pandas
| 0 |
1,908,630 | 72,253,624 |
Ursina.build can't find modules?
|
<p>I was reading <a href="https://stackoverflow.com/questions/71184949/i-have-problem-with-ursina-when-it-get-compiled-to-exe">This</a>, when it said I was supposed to use the command <code>python -m ursina.build</code> to compile my project. When I launched the .bat file I got this error</p>
<pre><code>package_folder: C:\Users\sbahr\OneDrive\Documents\programming\Python\MeshGame\build\python\lib\site-packages\ursina
asset_folder: src
screen resolution: (1920, 1080)
Traceback (most recent call last):
File "C:\Users\sbahr\OneDrive\Documents\programming\Python\MeshGame\main.py", line 3, in <module>
from mesh import ChunkManager
File "C:\Users\sbahr\OneDrive\Documents\programming\Python\MeshGame\mesh.py", line 19, in <module>
from noise import generateSaveNoise
File "C:\Users\sbahr\OneDrive\Documents\programming\Python\MeshGame\noise.py", line 3, in <module>
import numpy as np
ModuleNotFoundError: No module named 'numpy'
</code></pre>
<p>I ran <code>pip install numpy</code> and it said numpy was already installed.</p>
|
<p>This used to be automatic, but broke in a newer version of Python. Therefore you'll have to provide a list of extra modules to copy, if you're using any.
From ursina's documentation (<a href="https://www.ursinaengine.org/building.html" rel="nofollow noreferrer">https://www.ursinaengine.org/building.html</a>):</p>
<blockquote>
<p>Make sure to include any extra modules with <code>--include_modules PIL,numpy</code> for example.</p>
</blockquote>
|
python|numpy|panda3d|ursina
| 1 |
1,908,631 | 65,638,820 |
replace special characters using unicode
|
<p>how can i replace the double quotation marks with the stylistically correct quotation marks („ U+201e or “ U+201c ) according to German spelling.</p>
<p>example:</p>
<p>zitat = 'Laut Durkheim ist ein "soziologischer Tatbestand jede mehr oder weniger [...] unabhängiges Eigenleben besitzt"'</p>
<p>I've tried the code</p>
<pre><code>import re
zitatnew = re.sub(r'"', r'[u+201e]', zitat)
print(zitatnew)
Laut Durkheim ist ein [u+201e]soziologischer Tatbestand jede mehr oder weniger [...] unabhängiges Eigenleben besitzt[u+201e]
</code></pre>
<p>How can i replace the double quotations marks with the correct one using unicode?</p>
<p>Maybe one of you can help me.
P.S. I'm sorry for my bad english!</p>
|
<p>You can iterate while there are <code>"</code> in the string and in every iteration replace one pair of quotes:</p>
<pre class="lang-python prettyprint-override"><code>zitat = 'Laut Durkheim ist ein "soziologischer Tatbestand jede mehr oder weniger [...] unabhängiges Eigenleben besitzt"'
print(f"Before replace: {zitat}")
while "\"" in zitat:
zitat = zitat.replace("\"", "\u201e", 1)
zitat = zitat.replace("\"", "\u201c", 1)
print(f"After replace: {zitat}")
</code></pre>
<p>The <code>1</code> as third argument in <code>replace()</code> is important to replace only the first ocurrence of the <code>"</code>. This should give a correct output for any string with an even number of <code>"</code>.</p>
<p>Output:</p>
<pre class="lang-none prettyprint-override"><code>Before replace: Laut Durkheim ist ein "soziologischer Tatbestand jede mehr oder weniger [...] unabhängiges Eigenleben besitzt"
After replace: Laut Durkheim ist ein „soziologischer Tatbestand jede mehr oder weniger [...] unabhängiges Eigenleben besitzt“
</code></pre>
|
python|regex|unicode
| 1 |
1,908,632 | 50,340,734 |
tensorflow polynomial regression cannot train
|
<p>I'm trying to do polynomal regression using tensorflow.
The fake data using in this code and real data that will applied to this model follow Bivariate Distribution so I want to find the sigma1, sigma2, mux, muy of Bivariate Distribution.</p>
<p>Here is link which describe Bivariate Distribution
<a href="http://mathworld.wolfram.com/BivariateNormalDistribution.html" rel="nofollow noreferrer">http://mathworld.wolfram.com/BivariateNormalDistribution.html</a></p>
<pre><code>import math as m
import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
from mpl_toolkits.mplot3d import Axes3D
num_points = 40
vectors_set = []
sigma_x1 = 0.01
sigma_y1 = 0.02
mu_x1 = 30
mu_y1 = 120
weight1 = 0.01
# create fake data
def normalf(x, y):
return weight1 / (2 * m.pi * sigma_x1 * sigma_y1) * m.exp(
-(x - mu_x1) * (x - mu_x1) / (2 * sigma_x1) - (y - mu_y1) * (y - mu_y1) / (2 * sigma_y1))
for i in range(num_points):
x1 = np.random.normal(30, 0.1)
y1 = np.random.normal(120, 0.1)
z1 = normalf(x1, y1)
vectors_set.append([x1, y1, z1])
x_data = [v[0] for v in vectors_set]
y_data = [v[1] for v in vectors_set]
z_data = [v[2] for v in vectors_set]
print('x_data :', x_data)
print('y_data :', y_data)
print('z_data :', z_data)
fig = plt.figure()
ax = Axes3D(fig)
for i in range(40):
xs = x_data[i]
ys = y_data[i]
zs = z_data[i]
ax.scatter(xs, ys, zs, color='blue')
ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
plt.show()
# train
sigma_x = tf.Variable(tf.random_uniform([1],0,1), trainable=True)
sigma_y = tf.Variable(tf.random_uniform([1],0,1), trainable=True)
mu_x = tf.Variable(tf.random_uniform([1], 129, 131), trainable=True)
mu_y = tf.Variable(tf.random_uniform([1], 29, 31), trainable=True)
weight = tf.Variable(tf.random_uniform([1],0,1), trainable=True)
var_x_data = tf.Variable(x_data)
var_y_data = tf.Variable(y_data)
z = weight/(2 * m.pi * sigma_x * sigma_y)*tf.exp(-(x_data - mu_x)*(x_data - mu_x)/(2 * sigma_x)-(y_data - mu_y)*(y_data - mu_y)/(2 * sigma_y))
loss = tf.reduce_mean(tf.square(z - z_data))
optimizer = tf.train.GradientDescentOptimizer(0.5)
train = optimizer.minimize(loss)
init = tf.global_variables_initializer()
sess = tf.Session()
sess.run(init)
for step in range(10):
sess.run(train)
print('step :', step, '-', sess.run(sigma_x), sess.run(sigma_y), sess.run(mu_x), sess.run(mu_y), sess.run(weight))
</code></pre>
<p>result</p>
<pre><code>x_data : [30.019169654005868, 30.04151686293841, 30.003138702178568, 29.948259618114108, 29.973804961551597, 30.106418046307358, 30.02377731407854, 29.995462731965706, 30.060531767570676, 30.016641427558056, 29.79484435714953, 30.002353505751056, 29.93743604963893, 30.088668570426364, 29.789298610893283, 30.003070898711083, 30.07451548627123, 29.828669735419904, 29.928255899050924, 30.175214235408138, 29.930167990278186, 29.90277620297527, 29.91114439856375, 30.050973680551458, 29.881981688838813, 29.886764810970924, 30.12852171960371, 29.976742858188068, 30.102555513370692, 30.08058843864956, 30.01423060105985, 30.1417785666331, 29.94505775236722, 30.036190477298756, 29.999186746912457, 29.801194309808547, 29.86687585345513, 30.17350921771019, 29.84327182238387, 29.978272129448513]
y_data : [120.04311664719668, 120.04728396026447, 120.01752613183059, 119.96947626260086, 120.0074708368806, 119.85338543010528, 119.96354679730872, 120.0944221002095, 120.03622348805933, 119.91071772762156, 120.05201177439841, 119.88085394982495, 120.05182262414606, 119.96638039334746, 119.73626135724012, 120.0385386987263, 120.04360494847882, 119.78820975685764, 119.84457167286291, 119.94155466510361, 119.92755300397495, 120.24845049779589, 119.91834572339475, 120.04973567488224, 120.07455650203526, 120.18076686378147, 120.05745691621354, 120.00766570986937, 119.95423853371014, 120.01967657984122, 120.11763488442516, 120.0020441058596, 120.03321571537539, 120.03342406652649, 119.89723002259565, 119.89898775137291, 120.02497021225373, 120.0325009361513, 119.95872465372054, 120.04806845389801]
z_data : [7.458065212215647, 6.903780231006986, 7.892983766488841, 6.800527070280217, 7.6786335024572026, 2.639290437583994, 7.483173794841493, 6.3612714682233475, 6.41178477092057, 6.4302664723366, 0.9067154836465008, 5.578804230084947, 6.118359074221694, 5.221492189799962, 0.15189593638054374, 7.664073535801603, 5.74875474926795, 0.5975396029452897, 3.3630086876332186, 1.5742013987259473, 5.4690573960257325, 1.0600661981383745, 4.538944615534413, 6.5691812133605465, 3.451341688493068, 1.8517276371989146, 3.208238036016542, 7.734045908198488, 4.463402992774631, 5.695873253187933, 5.5737678967269515, 2.9124171786511046, 6.656749594702553, 7.24802632727239, 6.110882289123907, 0.854596336208196, 3.229916326704241, 1.7202433033042304, 2.233050305489856, 7.335873672423284]
/.local/lib/python3.5/site-packages/matplotlib/figure.py:1999: UserWarning: This figure includes Axes that are not compatible with tight_layout, so results might be incorrect.
warnings.warn("This figure includes Axes that are not compatible "
2018-05-15 09:10:05.847451: W tensorflow/core/platform/cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE4.1 instructions, but these are available on your machine and could speed up CPU computations.
2018-05-15 09:10:05.847481: W tensorflow/core/platform/cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use SSE4.2 instructions, but these are available on your machine and could speed up CPU computations.
2018-05-15 09:10:05.847489: W tensorflow/core/platform/cpu_feature_guard.cc:45] The TensorFlow library wasn't compiled to use AVX instructions, but these are available on your machine and could speed up CPU computations.
step : 0 - [ nan] [ nan] [ nan] [ nan] [ nan]
step : 1 - [ nan] [ nan] [ nan] [ nan] [ nan]
step : 2 - [ nan] [ nan] [ nan] [ nan] [ nan]
step : 3 - [ nan] [ nan] [ nan] [ nan] [ nan]
step : 4 - [ nan] [ nan] [ nan] [ nan] [ nan]
step : 5 - [ nan] [ nan] [ nan] [ nan] [ nan]
step : 6 - [ nan] [ nan] [ nan] [ nan] [ nan]
step : 7 - [ nan] [ nan] [ nan] [ nan] [ nan]
step : 8 - [ nan] [ nan] [ nan] [ nan] [ nan]
step : 9 - [ nan] [ nan] [ nan] [ nan] [ nan]
</code></pre>
|
<p>Looks like you are initializing your sigma_x and sigma_y to zero. This will cause a division by zero on the very first weight update and everything will be set to nan. The best bet is to initialize with high variance and then let it fit from there.</p>
|
python|tensorflow
| 0 |
1,908,633 | 50,574,293 |
flask.cli.NoAppException: Could not import "flaskr.flaskr"
|
<p>I'm working through: <a href="http://flask.pocoo.org/docs/1.0/tutorial/" rel="noreferrer">http://flask.pocoo.org/docs/1.0/tutorial/</a></p>
<p>I've written <code>__init__.py</code> (code here: <a href="http://codepad.org/4FGIE901" rel="noreferrer">http://codepad.org/4FGIE901</a>) in a /flaskr/ directory, set up a virtual environment called 'venv' and installed Flask.</p>
<p>I then ran these commands — on the command line, in the flaskr directory – as 'Run the application' advises: (<code>export FLASK_APP=flaskr</code>, <code>export FLASK_ENV=development</code>, <code>flask run</code>)</p>
<p>What I should see is <code>Hello, World!</code></p>
<p>Instead, I'm presented with the following errors:</p>
<pre><code>Traceback (most recent call last):
File "/Users/David/Desktop/flaskr/venv/lib/python3.6/site-packages/flask/cli.py", line 330, in __call__
rv = self._load_unlocked()
File "/Users/David/Desktop/flaskr/venv/lib/python3.6/site-packages/flask/cli.py", line 317, in _load_unlocked
self._app = rv = self.loader()
File "/Users/David/Desktop/flaskr/venv/lib/python3.6/site-packages/flask/cli.py", line 372, in load_app
app = locate_app(self, import_name, name)
File "/Users/David/Desktop/flaskr/venv/lib/python3.6/site-packages/flask/cli.py", line 246, in locate_app
'Could not import "{name}".'.format(name=module_name)
flask.cli.NoAppException: Could not import "flaskr.flaskr".
</code></pre>
<p>Simply, I'm not sure how I should respond to or work upon fixing an error like this. Perhaps I have a mismatch in what I have installed in the venv and what this particular project requires? </p>
<p>Like this person: <a href="https://stackoverflow.com/questions/26481285/could-not-import-pandas-typeerror">Could not Import Pandas: TypeError</a> </p>
<p>Flask: </p>
<ul>
<li><code>/Users/David/Desktop/flaskr/venv/bin/Flask</code></li>
<li>Version: 1.0.2</li>
</ul>
<p>Pip:</p>
<ul>
<li><code>from /Users/David/Desktop/flaskr/venv/lib/python3.6/site-packages (python 3.6)</code></li>
<li>Version: 9.0.1</li>
</ul>
<p>Python: </p>
<ul>
<li><code>/Users/David/Desktop/flaskr/venv/bin/python</code></li>
<li>Version: 3.6.0</li>
</ul>
|
<p>I think you are in the wrong folder. You probably did:</p>
<pre><code>cd flask_tutorial/flaskr
</code></pre>
<p>You need to go up to the tutorial folder:</p>
<pre><code>cd ..
</code></pre>
<p>You should <code>flask run</code> in the <code>flask_tutorial</code> folder rather than <code>flask_tutorial/flaskr</code> because you want to import <code>flaskr</code> from that folder, not <code>flaskr/flaskr</code> (which doesn't exist).</p>
|
python|flask
| 94 |
1,908,634 | 26,442,543 |
Which operations can be done in parallel without grabbing the GIL?
|
<p>I'm looking at embedding Python in a multi-threaded C++ program and doing simple computations using numpy in parallel.</p>
<p>On other words, I'm using <code>PyRun_SimpleString</code> to call numpy functions. Is grabbing GIL required if I only write to existing numpy arrays, and take care not to modify the same array from different threads?</p>
<p><strong>Edit</strong>, as mentioned in comments, this was addressed here: <a href="https://stackoverflow.com/questions/8824739/global-interpreter-lock-and-access-to-data-eg-for-numpy-arrays">Global Interpreter Lock and access to data (eg. for NumPy arrays)</a> </p>
<p>and a possible solution is to use numpy c interface directly using ctypes which takes care of releasing GIL: <a href="https://stackoverflow.com/a/5868051/419116">https://stackoverflow.com/a/5868051/419116</a></p>
<p>For posterity, here's what actually happens when you try to do "a*=2" without grabbing GIL:</p>
<pre><code>Program received signal SIGSEGV, Segmentation fault.
0x0000000000acc242 in PyImport_GetModuleDict ()
at python_runtime/v2_7/Python/import.c:433
433 PyInterpreterState *interp = PyThreadState_GET()->interp;
#0 0x0000000000acc242 in PyImport_GetModuleDict ()
at python_runtime/v2_7/Python/import.c:433
#1 0x0000000000accca1 in PyImport_AddModule (
name=0x13e9255 <.L.str53> "__main__")
at python_runtime/v2_7/Python/import.c:672
#2 0x0000000000aab29f in PyRun_SimpleStringFlags (
command=0x13e8831 <.L.str10> "a*=2", flags=0x0)
at python_runtime/v2_7/Python/pythonrun.c:976
#3 0x00000000008e3300 in main (argc=1, argv=0x7fffd2226ec0)
at python_embed/interactive_nogil.cc:56
</code></pre>
<p>Here <code>PyThreadState_GET</code> is macro for <code>_PyThreadState_Current</code> which is a null-pointer. So apparently grabbing the GIL also involves setting up some Thread variables which are needed for any Python operation</p>
|
<p>The GIL is required for <code>PyRun_SimpleString</code> because it invokes the Python interpreter. If you use <code>PyRun_SimpleString</code> without owning the GIL the process will segfault.</p>
<p>There are parts of the NumPy C API that do not require the GIL, but only the parts that do not touch Python objects or the interpreter. One example is the <code>PyArray_DATA</code> macro. </p>
|
python|numpy|python-internals
| 0 |
1,908,635 | 26,895,317 |
Can't import matplotlib.pyplot, IOError related to a font
|
<p>I recently installed the Anaconda distribution of Python. When I try to import matplotlib.pyplot, I receive a "Permission denied" error as the font manager tries to access one of the fonts on my computer. </p>
<pre><code>Python 2.7.8 |Anaconda 2.1.0 (x86_64)| (default, Aug 21 2014, 15:21:46)
[GCC 4.2.1 (Apple Inc. build 5577)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
Anaconda is brought to you by Continuum Analytics.
Please check out: http://continuum.io/thanks and https://binstar.org
>>> import matplotlib.pyplot as plt
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/lck/anaconda/lib/python2.7/site-packages/matplotlib/pyplot.py", line 27, in <module>
import matplotlib.colorbar
File "/Users/lck/anaconda/lib/python2.7/site-packages/matplotlib/colorbar.py", line 34, in <module>
import matplotlib.collections as collections
File "/Users/lck/anaconda/lib/python2.7/site-packages/matplotlib/collections.py", line 27, in <module>
import matplotlib.backend_bases as backend_bases
File "/Users/lck/anaconda/lib/python2.7/site-packages/matplotlib/backend_bases.py", line 56, in <module>
import matplotlib.textpath as textpath
File "/Users/lck/anaconda/lib/python2.7/site-packages/matplotlib/textpath.py", line 19, in <module>
import matplotlib.font_manager as font_manager
File "/Users/lck/anaconda/lib/python2.7/site-packages/matplotlib/font_manager.py", line 1412, in <module>
_rebuild()
File "/Users/lck/anaconda/lib/python2.7/site-packages/matplotlib/font_manager.py", line 1397, in _rebuild
fontManager = FontManager()
File "/Users/lck/anaconda/lib/python2.7/site-packages/matplotlib/font_manager.py", line 1052, in __init__
self.ttflist = createFontList(self.ttffiles)
File "/Users/lck/anaconda/lib/python2.7/site-packages/matplotlib/font_manager.py", line 579, in createFontList
font = ft2font.FT2Font(fpath)
IOError: [Errno 13] Permission denied: u'/Library/Fonts/Finale Lyrics Italic.ttf'
</code></pre>
<p>How can I get matplotlib.pyplot to load and not stop at this "Permission denied" font error? I don't need any particular font (eg, I don't need to use "Finale Lyrics Italics" - any font is fine). Any thoughts would be much appreciated!</p>
|
<p>I have the same problem in Linux Mint 17.2. I do this in my terminal :
sudo chmod 644 /my-fonts-path/*</p>
<p>For you, try :
sudo chmod 644 /Library/Fonts/Finale/*</p>
<p>More information can be found here <a href="http://ubuntuforums.org/showthread.php?t=1976037" rel="nofollow">http://ubuntuforums.org/showthread.php?t=1976037</a></p>
|
python|matplotlib|fonts|anaconda
| 4 |
1,908,636 | 26,440,570 |
How to efficiently generate all unique words with a number of (possibly repeated) letters
|
<p>I have a number of letters say three a's and two b's and I want to find all possible words with them. I have tried <code>itertools.permutations</code> and <code>itertools.product</code> but they didn't help because:</p>
<p>1) The results <code>permutations</code> contains repetitions (i.e. the same word appears multiple times). For example:</p>
<pre><code>> print [''.join(i) for i in itertools.permutations('aab', 3)]
['aab', 'aba', 'aab', 'aba', 'baa', 'baa']
</code></pre>
<p>2) The results of <code>product</code> can contain words with only one of the letters:</p>
<pre><code>> print [''.join(i) for i in itertools.product('ab', repeat=3)]
['aaa', 'aab', 'aba', 'abb', 'baa', 'bab', 'bba', 'bbb']
</code></pre>
<p>With two a's and one b I want to get `['aab', 'aba', 'baa']. Also I need the approach to use iterators and not lists (or any other way the stores everything in memory) because the results can be very large.</p>
|
<pre><code>def _permute(xs):
if not xs:
yield ()
for x in xs:
xs[x] -= 1
if not xs[x]:
xs.pop(x)
for ys in _permute(xs):
yield (x,) + ys
xs[x] += 1
from collections import Counter
def permute(xs):
return _permute(Counter(xs))
</code></pre>
<p>Usage:</p>
<pre><code>>>> list(permute('aab'))
[('a', 'a', 'b'), ('a', 'b', 'a'), ('b', 'a', 'a')]
>>> [''.join(xs) for xs in permute('aab')]
['aab', 'aba', 'baa']
>>> map(''.join, permute('aab')) # list(map(...)) in Python 3.x
['aab', 'aba', 'baa']
</code></pre>
|
python|permutation|itertools
| 2 |
1,908,637 | 45,188,206 |
Image link download works on Python 3, but not on Python 2.7
|
<p>I have the following image link:
'<a href="http://vignette2.wikia.nocookie.net/matrix/images/d/df/Thematrixincode99.jpg/revision/latest?cb=20140425045724" rel="nofollow noreferrer">http://vignette2.wikia.nocookie.net/matrix/images/d/df/Thematrixincode99.jpg/revision/latest?cb=20140425045724</a>'</p>
<p>M unable to download it using any of the following methods on Python 2.7.13: </p>
<pre><code># METHOD 1
url = 'http://vignette2.wikia.nocookie.net/matrix/images/d/df/Thematrixincode99.jpg/revision/latest?cb=20140425045724'
urllib.urlretrieve(url, "local-filename.jpg")
</code></pre>
<p>and</p>
<pre><code># METHOD 2
resp = urllib.urlopen(url)
image_data = resp.read()
f = open('/tmp/abc.jpg', 'wb')
f.write(image_data);
f.close();
</code></pre>
<p>and</p>
<pre><code>req = urllib2.Request(img_url, headers={"User-Agent": "Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.27 Safari/537.17"})
response = urllib2.urlopen(req, None,15)
obj_file = open(output_file,'wb')
data = response.read()
obj_file.write(data)
response.close();
</code></pre>
<p>The output file size in each of the cases is 3KB.<br>
How do I figure out the reason for failure of downloading the image? And is there any resolution?</p>
<p>UPDATE: Got an update that it works on Python 3. Need a working solution on Python 2.7</p>
|
<p>Try one more:</p>
<pre><code>import requests
r = requests.get("http://vignette2.wikia.nocookie.net/matrix/images/d/df/Thematrixincode99.jpg/revision/latest?cb=20140425045724")
with open("local-filename.jpg", 'wb') as f:
f.write(r.content)
</code></pre>
|
python|python-2.7|urllib2|urllib
| 1 |
1,908,638 | 65,037,867 |
How to print a specific row from a list in python
|
<p>I have a list called 'DistInt' that contains values of Intensity with corresponding Distances for an earthquake event. Is there a way I can just print a specific row within list?</p>
<pre><code>import math
import json
# Open JSON file
f = open("Path_to.geojson")
# Returns JSON object as a dictionary
data = json.load(f)
for feature in data['features']:
ml = float(feature['properties']['magnitude'])
h = float(feature['properties']['depth'])
i = 0
# Formula for working out Distances for MMI
Io = 1.5 * (ml - 1.7 * 0.4343 * math.log(h) + 1.4)
for i in range(1, 13, 1):
Iso = float(i)
a = (Io - Iso) / (1.8 * 0.4343)
d = math.exp(a)
d = d - 1
if d <= 0:
d = 0
else:
d = math.sqrt(h * h * d)
DistInt = [Iso, d]
print(DistInt)
</code></pre>
<p>Would print the DistInt list:</p>
<pre><code>[1.0, 609.1896122140013]
[2.0, 321.0121765154287]
[3.0, 168.69332169329735]
[4.0, 87.7587868508665]
[5.0, 43.88709626561051]
[6.0, 17.859906969392682]
</code></pre>
<p>I would like to just print, for example, the row - [2.0, 321.0121765154287]</p>
|
<p>I guess what you want to do is something like this:</p>
<pre><code>DistIntArray = []
for i in range(1, 13, 1):
Iso = float(i)
a = (Io - Iso) / (1.8 * 0.4343)
d = math.exp(a)
d = d - 1
if d <= 0:
d = 0
else:
d = math.sqrt(h * h * d)
DistInt = [Iso, d]
print(DistInt)
DistIntArray.append(DistInt)
print("the first element of array: ", DistIntArray[0])
print("the second element of array: ", DistIntArray[1])
for i in range(0,len(DistIntArray)):
print("An element of DistIntArray",DistIntArray[i])
for aDistInt in DistIntArray:
print("Getting an element of DistIntArray",aDistInt)
</code></pre>
<p>I just created an array and added the calculated DistInt tuple in each iteration of the first for loop. This way I can get any element of the calculated DistInt variables.</p>
<p>Here, DistIntArray is an array of array because the variable DistInt is a tuple which is an array.
The for loops are just different ways of iterating over arrays.</p>
<p>Besides this, I think your code seems to be buggy since the
DistInt = [Iso, d]
is indented with the else block. It means it will do the assignment only in the else block. I guess this line and the print line should be written like this:</p>
<pre><code>if d <= 0:
d = 0
else:
d = math.sqrt(h * h * d)
DistInt = [Iso, d]
print(DistInt)
DistIntArray.append(DistInt)
</code></pre>
|
python|json|list|pyqgis
| 1 |
1,908,639 | 61,583,393 |
How does one plot the ratio of of a categorical column in a long form data set?
|
<p>I have a long form data set with a column <code>type</code> and <code>date</code>. <code>type</code> has two categories <code>gold</code> and<code>silver</code>. I'd like to plot the ratio of the two by date. To do that a series of transformations have to happen. They look like this in <code>pandas</code></p>
<pre><code>mock_df = df.groupby(["date"])["type"].value_counts().unstack()
mock_df["gs_ratio"] = mock_df["gold"]/mock_df["silver"]
mock_df
</code></pre>
<p><a href="https://i.stack.imgur.com/HmsAs.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/HmsAs.png" alt="enter image description here"></a></p>
<p>Data</p>
<pre><code>import pandas
df = pd.DataFrame.from_records([
{"date": "2020-04-20", "type": "gold"},
{"date": "2020-04-20", "type": "silver"},
{"date": "2020-04-20", "type": "silver"},
{"date": "2020-04-21", "type": "gold"},
{"date": "2020-04-21", "type": "gold"},
{"date": "2020-04-21", "type": "silver"},
{"date": "2020-04-22", "type": "gold"},
{"date": "2020-04-22", "type": "silver"},
{"date": "2020-04-22", "type": "silver"},
{"date": "2020-04-22", "type": "silver"}
])
df
</code></pre>
<p><a href="https://i.stack.imgur.com/XYfej.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/XYfej.png" alt="enter image description here"></a></p>
<p>Code tried: </p>
<pre><code>alt.Chart(df).transform_joinaggregate(
gs_count='count(type)',
groupby=["date:T"]
).transform_pivot(
'type',
groupby=['date:T'],
value='gs_count'
).transform_calculate(
gs_ratio="datum.gold/datum.silver"
).mark_line().encode(
x='date:T',
y="gs_ratio:Q"
)
</code></pre>
<p><a href="https://i.stack.imgur.com/9SNZ0.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9SNZ0.png" alt="enter image description here"></a></p>
|
<p>There were a few issues in your approach:</p>
<ul>
<li>you can't use type shorthands in transforms. So you should be using the actual name of the column,<code>"date"</code> rather than <code>"date:T"</code></li>
<li><code>count(type)</code> is not equivalent to <code>df.type.value_counts()</code>. What you should do is use <code>count()</code> grouped by <code>type</code>.</li>
<li>use <code>transform_aggregate</code> rather than <code>transform_joinaggregate</code></li>
</ul>
<p>Putting this together:</p>
<pre><code>alt.Chart(df).transform_aggregate(
gs_count='count()',
groupby=["date", "type"]
).transform_pivot(
'type',
groupby=['date'],
value='gs_count'
).transform_calculate(
gs_ratio="datum.gold/datum.silver"
).mark_line().encode(
x='date:T',
y="gs_ratio:Q"
)
</code></pre>
<p><a href="https://i.stack.imgur.com/oOiM4.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/oOiM4.png" alt="enter image description here"></a></p>
|
python-3.x|altair
| 1 |
1,908,640 | 57,965,493 |
How to convert NumPy arrays obtained from cv2.findContours to Shapely polygons?
|
<p>I am using CV2 to find contours from an image and then converting them into polygons using Shapely. I am currently stuck because when I try putting one of the contour arrays into <code>Polygon()</code> from Shapely it throws an unspecified error. </p>
<p>I have double-checked that I imported everything I needed, and that creating a Shapely polygon works when I manually enter the array coordinate points. </p>
<p>Here is the problematic section of the code:</p>
<pre><code>contours, hierarchy = cv2.findContours(thresh, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE)
testcontour = contours[1]
ply = Polygon(testcontour)
</code></pre>
<p>Where the list of contours looks like this:</p>
<pre><code>contours = [np.array([[[700, 700]],
[[700, 899]],
[[899, 899]],
[[899, 700]]]),
np.array([[[774, 775]],
[[775, 774]],
[[824, 774]],
[[825, 775]],
[[825, 824]],
[[824, 825]],
[[775, 825]],
[[774, 824]]]),
np.array([[[200, 200]],
[[200, 399]],
[[399, 399]],
[[399, 200]]]),
np.array([[[274, 275]],
[[275, 274]],
[[324, 274]],
[[325, 275]],
[[325, 324]],
[[324, 325]],
[[275, 325]],
[[274, 324]]])]
</code></pre>
<p>The error I get is:</p>
<pre><code>---------------------------------------------------------------------------
AssertionError Traceback (most recent call last)
<ipython-input-65-4124f49b42e1> in <module>
----> 1 ply = Polygon(testcontour)
~\AppData\Local\Continuum\anaconda3\envs\geocomp\lib\site-packages\shapely\geometry\polygon.py in __init__(self, shell, holes)
238
239 if shell is not None:
--> 240 ret = geos_polygon_from_py(shell, holes)
241 if ret is not None:
242 self._geom, self._ndim = ret
~\AppData\Local\Continuum\anaconda3\envs\geocomp\lib\site-packages\shapely\geometry\polygon.py in geos_polygon_from_py(shell, holes)
492
493 if shell is not None:
--> 494 ret = geos_linearring_from_py(shell)
495 if ret is None:
496 return None
~\AppData\Local\Continuum\anaconda3\envs\geocomp\lib\site-packages\shapely\speedups\_speedups.pyx in shapely.speedups._speedups.geos_linearring_from_py()
AssertionError:
</code></pre>
|
<p>The problem is that for some reason <code>cv2.findContours</code> returns each contour as a 3D NumPy array with one redundant dimension:</p>
<pre><code>>>> contours[1]
array([[[774, 775]],
[[775, 774]],
[[824, 774]],
[[825, 775]],
[[825, 824]],
[[824, 825]],
[[775, 825]],
[[774, 824]]])
</code></pre>
<p>but Shapely expects a 2D array in this form (<a href="https://shapely.readthedocs.io/en/latest/manual.html#numpy-and-python-arrays" rel="noreferrer">see the docs</a>):</p>
<pre><code>array([[774, 775],
[775, 774],
[824, 774],
[825, 775],
[825, 824],
[824, 825],
[775, 825],
[774, 824]])
</code></pre>
<p>So, what we can do is to use <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.squeeze.html" rel="noreferrer"><code>np.squeeze</code></a> to remove that redundant dimension, and use the result to obtain our polygon:</p>
<pre><code>import numpy as np
from shapely.geometry import Polygon
contour = np.squeeze(contours[1])
polygon = Polygon(contour)
print(polygon.wkt)
# POLYGON ((774 775, 775 774, 824 774, 825 775, 825 824, 824 825, 775 825, 774 824, 774 775))
</code></pre>
<hr>
<p>In case if you want to convert all of the contours at once, I would do it like this:</p>
<pre><code>contours = map(np.squeeze, contours) # removing redundant dimensions
polygons = map(Polygon, contours) # converting to Polygons
multipolygon = MultiPolygon(polygons) # putting it all together in a MultiPolygon
</code></pre>
<p>The resulting <code>multipolygon</code> will look like this: </p>
<p><a href="https://i.stack.imgur.com/2cu74t.png" rel="noreferrer"><img src="https://i.stack.imgur.com/2cu74t.png" alt="enter image description here"></a></p>
<p>And to get the second polygon from here you would just write: </p>
<pre><code>my_polygon = multipolygon[1]
print(my_polygon.wkt)
# POLYGON ((774 775, 775 774, 824 774, 825 775, 825 824, 824 825, 775 825, 774 824, 774 775))
</code></pre>
|
python|numpy|opencv|shapely
| 17 |
1,908,641 | 58,005,608 |
Convert csv to list of dictionaries of array
|
<p>I have a <code>csv</code> file which is in the format</p>
<pre><code>id1, atr1, atr2.... atrn
id2, atr2_1,atr2_2....atr2_n
.
.
idn, atrn_1,atrn_2....atrn_n
</code></pre>
<p>I need to convert it to <code>list(dict(array))</code>, for example </p>
<pre><code>'id1': array([atr1, atr2.... atrn]),'id2': array([atr2_1,atr2_2....atr2_n])}]
</code></pre>
<p>Please help.</p>
|
<p>You can read the csv file in python using the csv module . It will read each line as a list so u will be able to attain your need . </p>
<pre><code>import csv
res_dict = {}
with open(<file name>) as csv_file:
csv_reader = csv.reader(csv_file, delimiter=',')
for row in csv_reader:
key_ = row[0]
values_ = row[1:]
res_dict[key] = value
print(res_dict)
</code></pre>
|
python|csv|dictionary
| 2 |
1,908,642 | 58,032,830 |
Python can't find where my txt file is, how can i link it or where do i need to put the file?
|
<p>Python can't find where my .txt file is, how can I find the correct path to it or where do I need to put the file?</p>
<p>I tried the following but got an error:</p>
<pre><code>with open("C:\Users\raynaud\Downloads\notlar.txt","r",encoding="utf-8") as file:
with open("dosya.txt","r",encoding= "utf-8") as file:
</code></pre>
<blockquote>
<p><code>FileNotFoundError: [Errno 2] No such file or directory: 'dosya.txt'</code></p>
</blockquote>
|
<p>If you are not using absolute path, you must place the file in the same directory as the script is. On absolute paths you should not use \ like <code>"C:\Users\UserName\"</code>, because \ is the escape character in Python (and many more languages). You must use it like this: <code>"C:\\Users\\UserName\\"</code></p>
|
python
| 1 |
1,908,643 | 56,110,364 |
Sequentialmodels without `input_shape` passed to the 1st layer cannot reload optimizer state
|
<p>WARNING:tensorflow:Sequential models without an <code>input_shape</code> passed to the first layer cannot reload their optimizer state. As a result, your model is starting with a freshly initialized optimizer.</p>
<p>while trying to load a saved model i encountered this warning from tensorflow</p>
<pre><code>import tensorflow.keras as keras
import tensorflow as tf
mnist = tf.keras.datasets.mnist
(x_train, y_train),(x_test, y_test) = mnist.load_data()
x_train = tf.keras.utils.normalize(x_train, axis=1)
x_test = tf.keras.utils.normalize(x_test, axis=1)
model = tf.keras.models.Sequential()
model.add(tf.keras.layers.Flatten())
model.add(tf.keras.layers.Dense(128, activation=tf.nn.relu))
model.add(tf.keras.layers.Dense(128, activation=tf.nn.relu))
model.add(tf.keras.layers.Dense(10, activation=tf.nn.softmax))
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
model.fit(x_train, y_train, epochs=3)
model.save('epic_num_reader.model')
new_model = tf.keras.models.load_model('epic_num_reader.model')
predictions = new_model.predict(x_test)
</code></pre>
|
<p>Had the same problem after upgrading to TF 1.14, I fixed it changing the definition of the first layer from this:</p>
<pre><code>model.add(tf.keras.layers.Flatten())
</code></pre>
<p>to this</p>
<pre><code>model.add(tf.keras.layers.Flatten(input_shape=(28, 28)))
</code></pre>
<p>where 28 is the size of the input map to be flattened (mnist pixels in our case)</p>
|
tensorflow|keras|tf.keras
| 2 |
1,908,644 | 56,208,731 |
Windows 10 RTX 2070 using keras gpu with anaconda optimize?
|
<p>I got a new pc recently with a windows 10 and an RTX 2070. I installed anaconda in order to use python and the deep learning frameworks available as keras. I install with anaconda navigator the keras-gpu package. It seems that installing this package will install a "cuda-toolkit 10" and "cudnn" package on anaconda. </p>
<p>I was wondering if my gpu will be used in a optimize way during the training on keras. In fact, in the past, when I installed keras gpu , I had to install microsoft community 2015 and cuda toolkit 9.0/Cudnn on my own in order to make keras gpu working. So, it seems a bit weird that I had no error.</p>
<p>Thank for the help !</p>
|
<p>It depends on what backends your keras is using.
e.g. If you are using tensorflow, the following statement will give you the answer.</p>
<pre><code>print(tf.test.is_gpu_available())
</code></pre>
|
python|keras|windows-10|anaconda|gpu
| 1 |
1,908,645 | 18,321,274 |
Pygame/Python. Left seems to move faster than right. Why?
|
<p>I've coded a bit c++ and java during the past few years and now i've started with python. The goal is to make a game. I've noticed, however, that at the basic animation part of a player moving left and right, my left "speed" is faster than the right "speed". Although my "speed" values are exactly the same.</p>
<p>The update function:</p>
<pre><code>def update(self,dt,game):
last=self.rect.copy()
self.time+=dt
if self.left:
self.rect.x-=300*dt
if self.right:
self.rect.x+=300*dt
</code></pre>
<p>I've noticed that if i change the left speed to 250, instead of 300, it will run the same. For example if i press both left and right keys the player will stay on the exact same spot. However if i have the left and right speed both at 300. The player will move slowly to the left.</p>
<p>My game loop:</p>
<pre><code>while 1:
dt=clock.tick(60)
if dt>1000/60.0:
dt=1000/60.0
for event in pygame.event.get():
if event.type==pygame.QUIT:
return
if event.type==pygame.KEYDOWN and event.key==pygame.K_ESCAPE:
return
if event.type==pygame.KEYDOWN and event.key==pygame.K_LEFT:
self.player.left=True
self.player.image=self.player.leftimages[1]
if event.type==pygame.KEYDOWN and event.key==pygame.K_RIGHT:
self.player.right=True
self.player.image=self.player.rightimages[1]
if event.type==pygame.KEYUP and event.key==pygame.K_LEFT:
self.player.left=False
self.player.image=self.player.leftimages[0]
if event.type==pygame.KEYUP and event.key==pygame.K_RIGHT:
self.player.right=False
self.player.image=self.player.rightimages[0]
self.tilemap.update(dt/1000.0,self)
screen.fill((0,0,0))
self.tilemap.draw(screen)
pygame.display.update()
</code></pre>
<p>I'm using a tmx library from Richard Jones to be able to import my map made in tiled map editor. I hope this is sufficient information to answer my weird question. I've asked my other programming friend and he finds it weird.</p>
<p>Some code might be off, beacause i've just copy pasted from my original code that has some more stuff into it. But i've extracted the most basic parts that control the movement.</p>
<p>Thank you for your time!</p>
|
<p>Have you tried printing the value of <code>dt</code> from your <code>update</code> function? If the speed is different when you move left from when you move right, then that is what must be changing (backed up by you saying that holding left and right at the same time results in no movement).</p>
<p>Based on my own testing, it looks like <code>pygame.time.Clock.tick()</code> returns an integer value representing the number of milliseconds that have passed since the last call. Where you attempt to correct this value (<code>dt=1000/60.0</code>), you will be getting a floating point value. I suspect that for some reason, the timer is off when either pressing left or right, and your attempts to correct it manually are causing a different <code>dt</code> value to be passed in to the <code>update</code> function during these situations. </p>
<p>The pygame documentation suggests <code>pygame.time.Clock.tick_busy_loop()</code> if you need a more accurate (but CPU intensive) timer.</p>
<p><a href="http://www.pygame.org/docs/ref/time.html#pygame.time.Clock.tick_busy_loop" rel="nofollow">http://www.pygame.org/docs/ref/time.html#pygame.time.Clock.tick_busy_loop</a></p>
|
python|animation|pygame
| 1 |
1,908,646 | 55,309,046 |
Python efficient way of writing switch case with comparison
|
<p>I normally implement switch/case for equal comparison using a dictionary.</p>
<pre><code>dict = {0:'zero', 1:'one', 2:'two'};
a=1; res = dict[a]
</code></pre>
<p>instead of</p>
<pre><code>if a == 0:
res = 'zero'
elif a == 1:
res = 'one'
elif a == 2:
res = 'two'
</code></pre>
<p>Is there a strategy to implement similar approach for non-equal comparison?</p>
<pre><code>if score <= 10:
cat = 'A'
elif score > 10 and score <= 30:
cat = 'B'
elif score > 30 and score <= 50:
cat = 'C'
elif score > 50 and score <= 90:
cat = 'D'
else:
cat = 'E'
</code></pre>
<p>I know that may be tricky with the <, <=, >, >=, but is there any strategy to generalize that or generate automatic statements from let's say a list</p>
<pre><code>{[10]:'A', [10,30]:'B', [30,50]:'C',[50,90]:'D',[90]:'E'}
</code></pre>
<p>and some flag to say if it's <code><</code> or <code><=</code>.</p>
|
<p>A dictionary can hold a lot of values. If your ranges aren't too broad, you could make a dictionary that is similar to the one you had for the equality conditions by expanding each range programmatically:</p>
<pre><code>from collections import defaultdict
ranges = {(0,10):'A', (10,30):'B', (30,50):'C',(50,90):'D'}
valueMap = defaultdict(lambda:'E')
for r,letter in ranges.items():
valueMap.update({ v:letter for v in range(*r) })
valueMap[701] # 'E'
valueMap[7] # 'A'
</code></pre>
<p>You could also just remove the redundant conditions from your <em>if</em>/<em>elif</em> statement and format it a little differently. That would almost look like a case statement:</p>
<pre><code>if score < 10 : cat = 'A'
elif score < 30 : cat = 'B'
elif score < 50 : cat = 'C'
elif score < 90 : cat = 'D'
else : cat = 'E'
</code></pre>
<p>To avoid repeating <code>score <</code>, you could define a case function and use it with the value:</p>
<pre><code>score = 43
case = lambda x: score < x
if case(10): cat = "A"
elif case(30): cat = "B"
elif case(50): cat = "C"
elif case(90): cat = "D"
else : cat = "E"
print (cat) # 'C'
</code></pre>
<p>You could generalize this by creating a switch function that returns a "case" function that applies to the test value with a generic comparison pattern:</p>
<pre><code>def switch(value):
def case(check,lessThan=None):
if lessThan is not None:
return (check is None or check <= value) and value < lessThan
if type(value) == type(check): return value == check
if isinstance(value,type(case)): return check(value)
return value in check
return case
</code></pre>
<p>This generic version allows all sorts of combinations:</p>
<pre><code>score = 35
case = switch(score)
if case(0,10) : cat = "A"
elif case([10,11,12,13,14,15,16,17,18,19]):
cat = "B"
elif score < 30 : cat = "B"
elif case(30) \
or case(range(31,50)) : cat = 'C'
elif case(50,90) : cat = 'D'
else : cat = "E"
print(cat) # 'C'
</code></pre>
<p>And there is yet another way using a lambda function when all you need to do is return a value:</p>
<pre><code>score = 41
case = lambda x,v: v if score<x else None
cat = case(10,'A') or case(20,'B') or case(30,'C') or case(50,'D') or 'E'
print(cat) # "D"
</code></pre>
<p>This last one can also be expressed using a list comprehension and a mapping table:</p>
<pre><code>mapping = [(10,'A'),(30,'B'),(50,'C'),(90,'D')]
scoreCat = lambda s: next( (L for x,L in mapping if s<x),"E" )
score = 37
cat = scoreCat(score)
print(cat) #"D"
</code></pre>
<p>More specifically to the question, a generalized solution can be created using a setup function that returns a mapping function in accordance with your parameters:</p>
<pre><code>def rangeMap(*breaks,inclusive=False):
default = breaks[-1] if len(breaks)&1 else None
breaks = list(zip(breaks[::2],breaks[1::2]))
def mapValueLT(value):
return next( (tag for tag,bound in breaks if value<bound), default)
def mapValueLE(value):
return next( (tag for tag,bound in breaks if value<=bound), default)
return mapValueLE if inclusive else mapValueLT
scoreToCategory = rangeMap('A',10,'B',30,'C',50,'D',90,'E')
print(scoreToCategory(53)) # D
print(scoreToCategory(30)) # C
scoreToCategoryLE = rangeMap('A',10,'B',30,'C',50,'D',90,'E',inclusive=True)
print(scoreToCategoryLE(30)) # B
</code></pre>
<p><em>Note that with a little more work you can improve the performance of the returned function using the <em><a href="https://docs.python.org/3.8/library/bisect.html" rel="nofollow noreferrer">bisect</a></em> module.</em></p>
|
python|switch-statement
| 5 |
1,908,647 | 57,445,744 |
Heap argument must be a list in python 3
|
<p>I was trying to implement a data structure to returns a value such that set (key, value, timestamp_prev) was called previously, with timestamp_prev <= timestamp.
I tried to use a min heap in python. there was a fault flagged I don't quite understand.</p>
<pre><code>class TimeMap:
def __init__(self):
"""
Initialize your data structure here.
"""
self.mapping = collections.defaultdict(list)
def set(self, key: str, value: str, timestamp: int) -> None:
self.mapping[key].append([-timestamp, value])
def get(self, key: str, timestamp: int) -> str :
if not self.mapping[key]:
return ''
heap = heapq.heapify(self.mapping[key])
for pre_stamp, val in heapq.heappop(heap):
if -pre_stamp <= timestamp:
return val
return ''
</code></pre>
<p>A fault came out with: heap argument must be a list.</p>
<p>But it looks the mapping[key] returned value is a list.</p>
<p>Please advise. Thanks!</p>
|
<p>The fact that <code>self.mapping</code> is defined as <code>collections.defaultdict(list)</code> does not mean that <code>self.mapping[key]</code> will return a list for every arbitrary <code>key</code>. It just means that <code>self.mapping[key]</code> will return a list for every <code>key</code> that does <strong>not</strong> exist will return an empty list.</p>
<pre><code>import collections
d = collections.defaultdict(list)
d['a'] = 'not a list'
print(type(d['a']), d['a'])
</code></pre>
<p>outputs</p>
<pre><code><class 'str'> not a list
</code></pre>
|
python-3.x|heap
| 1 |
1,908,648 | 57,377,490 |
How to use timeout to stop blocking function subscribe.simple
|
<p>I want to use timeout to stop the blocking function of mqtt, I use a the timeout_decorator module, it can stop command function but cannot stop blocking function, <code>subscribe.simple</code>.</p>
<p>The following code runs successfully</p>
<pre><code>import time
import timeout_decorator
@timeout_decorator.timeout(5, timeout_exception=StopIteration)
def mytest():
print("Start")
for i in range(1,10):
time.sleep(1)
print("{} seconds have passed".format(i))
if __name__ == '__main__':
mytest()
</code></pre>
<p>the result as follow:</p>
<pre><code>Start
1 seconds have passed
2 seconds have passed
3 seconds have passed
4 seconds have passed
Traceback (most recent call last):
File "timeutTest.py", line 12, in <module>
mytest()
File "/home/gyf/.local/lib/python3.5/site-packages/timeout_decorator/timeout_decorator.py", line 81, in new_function
return function(*args, **kwargs)
File "timeutTest.py", line 8, in mytest
time.sleep(1)
File "/home/gyf/.local/lib/python3.5/site-packages/timeout_decorator/timeout_decorator.py", line 72, in handler
_raise_exception(timeout_exception, exception_message)
File "/home/gyf/.local/lib/python3.5/site-packages/timeout_decorator/timeout_decorator.py", line 45, in _raise_exception
raise exception()
timeout_decorator.timeout_decorator.TimeoutError: 'Timed Out'
</code></pre>
<p>but I failed with the subscribe.simple API</p>
<pre><code>import timeout_decorator
@timeout_decorator.timeout(5)
def sub():
# print(type(msg))
print("----before simple")
# threading.Timer(5,operateFail,args=)
msg = subscribe.simple("paho/test/simple", hostname=MQTT_IP,port=MQTT_PORT,)
print("----after simple")
return msg
publish.single("paho/test/single", "cloud to device", qos=2, hostname=MQTT_IP,port=MQTT_PORT)
try:
print("pub")
msg = sub()
print(msg)
except StopIteration as identifier:
print("error")
</code></pre>
<p>The result infinitely wait</p>
<pre><code>pub
----before simple
</code></pre>
<p>I want the function which include subscribe.simple API can stop after 5 seconds.</p>
|
<p>Asyncio won't be able to handle blocking function in the same thread. therefore using <code>asyncio.wait_for</code> failed. However, inspired by <a href="https://carlosmaniero.github.io/asyncio-handle-blocking-functions.html" rel="nofollow noreferrer">this blog post</a> I used <code>loop.run_in_executor</code> to keep control on the blocking thread.</p>
<pre><code>from paho.mqtt import subscribe
import asyncio
MQTT_IP = "localhost"
MQTT_PORT = 1883
msg = None
def possibly_blocking_function():
global msg
print("listenning for message")
msg = subscribe.simple(
"paho/test/simple",
hostname=MQTT_IP,
port=MQTT_PORT,
)
print("message received!")
async def main():
print("----before simple")
try:
await asyncio.wait_for(
loop.run_in_executor(None, possibly_blocking_function), timeout=5
)
except asyncio.TimeoutError:
pass
print("----after simple")
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
</code></pre>
<p>Output :</p>
<pre><code>----before simple
listenning for message
----after simple
</code></pre>
<p>Please note this is not perfect, the program won't end since there are running tasks. You can exit it using various solution but this is out of scope since I am still looking for a clean way to close that stuck thread.</p>
|
python-3.x|synchronization|mqtt|paho
| 0 |
1,908,649 | 42,270,732 |
how can I create this kind of filter box for a certain field in admin pages? django
|
<p>let's say I have an employee model with the field username which can be selected. Usually in admin > employee page, we will see a dropdown of a list of employee username but instead of doing that, is it possible to have like a select list and on top of that there's a filter so it'll be easier to find what is needed instead of scrolling through the whole dropdown if there are like hundreds....</p>
<p>an example of what I want is like this....
<a href="https://i.stack.imgur.com/8BDjX.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8BDjX.png" alt="enter image description here"></a>
so in the box it'll be like list of the employee's name so I can click and choose whichever needed and also use filter to find the username.</p>
<p>this image is actually cropped from admin > users</p>
<p>Thanks in advance for any suggestions.</p>
|
<p>This is auto generate form input when there is manytoMany relation in your model.</p>
<p>Fox ex, something like this. </p>
<pre><code>class Team(models.Model):
members= models.ManyToManyField(Employee)
</code></pre>
<p>In you admin.py you have to register your model to show in admin pages. </p>
<pre><code>class TeamAdmin(admin.ModelAdmin):
filter_horizontal = ('employees',)
admin.site.register(Team, TeamAdmin)
</code></pre>
<p>There is more evolved selection also possibly with some customisation. </p>
|
python|django|filter|model|customization
| 1 |
1,908,650 | 42,524,867 |
How do I add a new column to a Spark DataFrame from function value (using PySpark)
|
<p>I have a dataframe from sql:</p>
<pre><code>log = hc.sql("""select
, ip
, url
, ymd
from log """)
</code></pre>
<p>and function which apply "ip" value from dataframe and return three value:</p>
<pre><code>def get_loc(ip):
geodata = GeoLocator('SxGeoCity.dat', MODE_BATCH | MODE_MEMORY)
result = []
location = geodata.get_location(ip, detailed=True)
city_name_en = str(processValue(location['info']['city']['name_en']))
region_name_en = str(processValue(location['info']['region']['name_en']))
country_name_en = str(processValue(location['info']['country']['name_en']))
result = [city_name_en, region_name_en, country_name_en]
return result
</code></pre>
<p>I don't know how to pass value to function get_loc() and add returned value as a map column "property" to existing dataframe. Use python 2.7 and PySpark. </p>
|
<p>I do not know what does get_loc do.</p>
<p>But you can use UDF as below:</p>
<pre><code>from pyspark.sql import functions as f
def get_loc(ip):
return str(ip).split('.')
rdd = spark.sparkContext.parallelize([(1, '192.168.0.1'), (2, '192.168.0.1')])
df = spark.createDataFrame(rdd, schema=['idx', 'ip'])
My_UDF = f.UserDefinedFunction(get_loc, returnType=ArrayType(StringType()))
df = df.withColumn('loc', My_UDF(df['ip']))
df.show()
# output:
+---+-----------+----------------+
|idx| ip| loc|
+---+-----------+----------------+
| 1|192.168.0.1|[192, 168, 0, 1]|
| 2|192.168.0.1|[192, 168, 0, 1]|
+---+-----------+----------------+
</code></pre>
|
python-2.7|apache-spark|spark-dataframe
| 0 |
1,908,651 | 42,537,943 |
Scipy sparse matrix multiplication
|
<p>I have this example of matrix by matrix multiplication using numpy arrays:</p>
<pre><code>import numpy as np
m = np.array([[1,2,3],[4,5,6],[7,8,9]])
c = np.array([0,1,2])
m * c
array([[ 0, 2, 6],
[ 0, 5, 12],
[ 0, 8, 18]])
</code></pre>
<p>How can i do the same thing if m is scipy sparse CSR matrix? This gives dimension mismatch:</p>
<pre><code>sp.sparse.csr_matrix(m)*sp.sparse.csr_matrix(c)
</code></pre>
|
<p>You can call the <code>multiply</code> method of <code>csr_matrix</code> to do pointwise multiplication. </p>
<pre><code>sparse.csr_matrix(m).multiply(sparse.csr_matrix(c)).todense()
# matrix([[ 0, 2, 6],
# [ 0, 5, 12],
# [ 0, 8, 18]], dtype=int64)
</code></pre>
|
python|numpy|matrix|scipy|sparse-matrix
| 20 |
1,908,652 | 42,509,554 |
Writing files using django forms and multiprocessing
|
<p>I am uploading a large number of files to server side using python multiprocessing technique and django forms.Here is the code </p>
<pre><code>def pooltest(request):
file_list=request.FILES.getlist('docfile')
print 'cpu_count() = %d\n' % cpu_count()
total_no_files = len(request.FILES.getlist('docfile'))
chunk_size = total_no_files//cpu_count()
print chunk_size
t1 = time.time()
p = Pool()
p.map(upload_function, file_list,chunksize=chunk_size)
p.close()
p.join()
</code></pre>
<p>But when i trying to upload large number of files following error occuring</p>
<pre><code>expected string or Unicode object, NoneType found
</code></pre>
<p>Please help to fix this?Is this pool configurations are correct?How do i change this so that i can upload large number of files with minimum time.</p>
<p>Here is the traceback</p>
<pre><code> expected string or Unicode object, NoneType found
Internal Server Error: /pooltest/
Traceback (most recent call last):
File "/home/akhil/.virtualenvs/resumematch/local/lib/python2.7/site-packages/django/core/handlers/exception.py", line 39, in inner
response = get_response(request)
File "/home/akhil/.virtualenvs/resumematch/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 249, in _legacy_get_response
response = self._get_response(request)
File "/home/akhil/.virtualenvs/resumematch/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 198, in _get_response
"returned None instead." % (callback.__module__, view_name)
ValueError: The view matchingapp.views.pooltest didn't return an HttpResponse object. It returned None instead.
2017-02-28 12:52:17,218 [Thread-90 ] [ERROR] Internal Server Error: /pooltest/
Traceback (most recent call last):
File "/home/akhil/.virtualenvs/resumematch/local/lib/python2.7/site-packages/django/core/handlers/exception.py", line 39, in inner
response = get_response(request)
File "/home/akhil/.virtualenvs/resumematch/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 249, in _legacy_get_response
response = self._get_response(request)
File "/home/akhil/.virtualenvs/resumematch/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 198, in _get_response
"returned None instead." % (callback.__module__, view_name)
ValueError: The view matchingapp.views.pooltest didn't return an HttpResponse object. It returned None instead.
</code></pre>
|
<p>Two things:</p>
<ol>
<li>You should really use <code>celery</code> or <code><queue of your choice></code> instead of jumping into multiprocessing.</li>
<li>You should take into account that even with multiprocessing it could take a while for all the files to upload and the client will be waiting for some response from your view. I sense some timeouts in the Force.</li>
</ol>
<p>And, as @themanatuf2 said, your view function should return a value, either a template or just <code>HttpResponse(status=200)</code></p>
|
python|django|python-multiprocessing
| 0 |
1,908,653 | 59,043,352 |
Filling blank indices of multi-dimensional list then checking if full
|
<p>I have one existing multi-dimensional list with predetermined (final) values <code>self.origBoard</code> and another multi-dimensional list of the same size, <code>self.board</code> that allows the user to fill in values. <code>self.origBoard</code> starts with a few blanks (whitespace) and other integer values, while <code>self.board</code> starts completely blank (empty). </p>
<p>The user is shown the combination of <code>self.origBoard</code> and <code>self.board</code> with the goal to have the user provide an integer value for all the indices from <code>self.origBoard</code> that started blank. I have some separate code to run upon the user filling in all the blanks, but I am having trouble determining in the code when this full-event occurs. </p>
<p>As an example, <code>self.origBoard</code> is is defined by:</p>
<pre><code>self.origBoard[0]=' 19374652'
self.origBoard[1]='576182943'
self.origBoard[2]='342596718'
self.origBoard[3]='921753864'
self.origBoard[4]='638419527'
self.origBoard[5]='457628139'
self.origBoard[6]='185237496'
self.origBoard[7]='763941285'
self.origBoard[8]='29486537 '
</code></pre>
<p>This <code>self.origBoard</code> generates as expected, but I am having trouble dealing with the generation and full-checking of <code>self.board</code>. Here is my code for initializing <code>self.board</code></p>
<pre><code>self.board = [None] * 9 # Used to mark user-entered numbers
for i in range(9):
self.board[i] = [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ' ]
</code></pre>
<p>I currently check whether it is full using this internal method:</p>
<pre><code>def fullBoard(self):
for i in range(0,9):
for k in range(0,9):
if self.board[i][k] == ' ':
return False
return True
</code></pre>
<p>I fill in these blanks (' ') using this method which asks for user input. </p>
<pre><code>def nextMove(self):
row = int(input('Enter Row:'))
col = int(input("Enter Column:"))
num = input("Enter Number:")
self.board[row][col] = num
</code></pre>
<p>Since the user will only be prompted to fill in the blanks from <code>self.origBoard</code>, (i.e. two indices in this example), I'm not sure how to check if the whole combined board is full.</p>
<p>Now I know why <code>fullBoard()</code> won't ever return true and that is because the remaining indices in <code>self.board</code> will remain <code>' '</code>. How can I check whether the combined values of <code>self.board</code> and <code>self.origBoard</code> represent a full board? </p>
<p>Minimal working code example below:</p>
<pre><code>class Sudoku():
def __init__(self):
self.board = [None] * 9 # Used to mark user-entered numbers
for i in range(9):
self.board[i] = [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ' ]
self.origBoard[0]=' 19374652'
self.origBoard[1]='576182943'
self.origBoard[2]='342596718'
self.origBoard[3]='921753864'
self.origBoard[4]='638419527'
self.origBoard[5]='457628139'
self.origBoard[6]='185237496'
self.origBoard[7]='763941285'
self.origBoard[8]='29486537 '
self.board = self.origBoard
def display(self):
# display stuff
pass
def nextMove(self):
row = int(input('Enter Row:'))
col = int(input("Enter Column:"))
num = input("Enter Number:")
self.board[row][col] = num
def fullBoard(self):
for i in range(0,9):
for k in range(0,9):
if self.board[i][k] == ' ':
return False
return True
def winCheck(self):
# Do some checks
print("Testing ftw!")
if __name__ == '__main__':
game = Sudoku()
game.display()
while(True):
game.nextMove()
if game.fullBoard() == True:
break
if game.winCheck() == True:
game.display()
print("You win!")
break
elif game.winCheck() == False:
game.display()
print("One or more of your numbers are overlapping!")
continue
else:
game.display()
</code></pre>
|
<p>Based on the discussion in the comments, it seems the problem lies within the generation and assignment of values to <code>self.board</code> and the way the lists were setup (using strings as rows rather than another list). I'm guessing the user was confused by the fact that they could iterate through a string similar to how you can iterate through an array or list, but could not assign a value to a particular character, i.e. their previous <code>self.board[row][col] = num</code> was throwing an error of:</p>
<blockquote>
<p>TypeError: 'str' object does not support item assignment</p>
</blockquote>
<p>Even though <code>self.board[row][col]</code> will happily return a single character from the string. </p>
<p>From the code given, it seems the user needed to make a copy of <code>self.origBoard</code> prior to assigning new values to <code>self.board</code>. Without such a step, the <code>self.board</code> was never being populated with values other than the initial values of ' ', and those values assigned using the <code>nextMove()</code> method. Thus it makes sense that <code>fullBoard()</code> always returns False since the ' ' values would always remain in <code>self.board</code>. Example working code as follows:</p>
<pre><code>class Sudoku():
def __init__(self):
# Note the one liner to replace your initializer for this
self.origBoard = [[' '] * 9] * 9
# Note the change from single strings to a list of integers
self.origBoard[0]=[' ',1,9,3,7,4,6,5,2]
self.origBoard[1]=[5,7,6,1,8,2,9,4,3]
self.origBoard[2]=[3,4,2,5,9,6,7,1,8]
self.origBoard[3]=[9,2,1,7,5,3,8,6,4]
self.origBoard[4]=[6,3,8,4,1,9,5,2,7]
self.origBoard[5]=[4,5,7,6,2,8,1,3,9]
self.origBoard[6]=[1,8,5,2,3,7,4,9,6]
self.origBoard[7]=[7,6,3,9,4,1,2,8,5]
self.origBoard[8]=[2,9,4,8,6,5,3,7,' ']
self.board = self.origBoard
def display(self):
# display stuff
pass
def nextMove(self):
row = int(input('Enter Row:'))
col = int(input("Enter Column:"))
num = input("Enter Number:")
self.board[row][col] = num
def fullBoard(self):
for i in range(0,9):
for k in range(0,9):
if self.board[i][k] == ' ':
return False
return True
def winCheck(self):
# Do some checks
print("testing ftw!")
if __name__ == '__main__':
game = Sudoku()
game.display()
while(True):
game.nextMove()
if game.fullBoard() == True:
# a break statement here would mean the following if statements are never reached
if game.winCheck() == True:
game.display()
print("You win!")
break
elif game.winCheck() == False:
game.display()
print("One or more of your numbers are overlapping!")
continue
else:
game.display()
</code></pre>
<p>Here I define "working" as I enter num values for index 0,0 and 8,8 which results in the call of <code>game.winCheck()</code>. </p>
<p>As a side note, I tried to use as much of the existing code as possible as this seems like some assignment to learn how lists and python work in general rather than something that needs to be optimized, but I've chosen to initialize each board a lot easier and avoid the unnecessary loop with:</p>
<pre><code>self.board = [[' '] * 9] * 9
</code></pre>
<p>Or even better, you could use a Numpy array, and use the <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.all.html" rel="nofollow noreferrer">all</a> method to check if full rather than writing your own method to do so. i.e. </p>
<pre><code>import numpy as np
self.board = np.zeros([9,9])
def fullBoard(self):
np.all(self.board)
</code></pre>
|
python|list|multidimensional-array
| 1 |
1,908,654 | 54,126,238 |
How to execute codes while Tkinter mainloop for Debugging purposes
|
<p>Let's say I have this simple tkinter code:</p>
<pre><code>import tkinter as tk
root = tk.Tk()
root.geometry('200x50')
label = tk.Label(root, text='Dummy text')
label.pack()
root.mainloop()
</code></pre>
<p>After running it, I want to manually change the label by <strong>executing</strong> (<code>exec</code>/<code>eval</code>) this line: <code>label.configure(text='Manually changed the text!')</code> (or some other command) for debugging purposes.</p>
<p>However, during <code>mainloop()</code> I cannot execute any code in the Python Shell. How can I be able to execute the code without interrupting the <code>mainloop()</code> <strong>and</strong> have the effect of the code immediately be present on the Tkinter window?</p>
|
<p>What acw1668 suggested in code:</p>
<pre><code>import tkinter as tk
root = tk.Tk()
root.geometry('200x50')
entry = tk.Entry(root)
entry.pack()
button = tk.Button(root, command=lambda:exec(entry.get()),text='exec entry')
button.pack()
label = tk.Label(root, text='Dummy text')
label.pack()
root.mainloop()
</code></pre>
|
python-3.x|loops|debugging|tkinter|eval
| 0 |
1,908,655 | 58,526,990 |
How to convert negative datetime.timedelta to positive datetime.timedelta value
|
<p>so I have multiple time value which I wanna subtract with each other but some of the cases I receive negative timedelta how do I convert it into positive without change the actual value</p>
<p>I tried to use <strong>abs()</strong> but it change the actual value </p>
<pre><code>
#for example:
time1=timedelta(hours=23,minutes=25,seconds=00)
time2=timedelta(hours=6,minutes=13,seconds=00)
delta_time_value = time2 -time1
print(delta_time_value) #-1 day, 13:01:00 (ANSWER)
</code></pre>
<p>The result which I was getting is <strong>-1 day, 13:01:00</strong>
but I want the result like this <strong>1 day, 13:01:00</strong>
<strong>without -ve sign</strong></p>
|
<p>If you just want the positive value, you can use "abs()" but you need to change the value in a float first:</p>
<pre><code>time1=timedelta(hours=23,minutes=25,seconds=00)
time2=timedelta(hours=6,minutes=13,seconds=00)
delta_time_value = time2 -time1
print(delta_time_value) # OUTPUT -1 day, 13:01:00
print(delta_time_value.total_seconds()) # OUTPUT -61920.0
print(abs(delta_time_value.total_seconds())) # OUTPUT 61920.0
</code></pre>
<p>And if you want a string at the end, you just need to do a simple f-string with the value (in 'int' this time):</p>
<pre><code>a = int(abs(delta_time_value.total_seconds()))
format = f'{a // 3600}:{(a % 3600) // 60}:{a % 60}0'
print(format) # OUTPUT 17:12:00
</code></pre>
|
python|date|time|timedelta
| 0 |
1,908,656 | 58,600,149 |
Lambda expression in Python
|
<p>Does someone know the difference between these two and why?
lambda doesn't not allow to reverse a single string?</p>
<h1>Works fine with this</h1>
<pre><code>s = ['justdoit','asdf']
list(map(lambda s: s[::-1], s))
</code></pre>
<h1>Doesn't apply the slicer. But why?</h1>
<pre><code>s = 'justdoit'
list(map(lambda s: s[::-1], s))
</code></pre>
|
<p>It is applying the slicer, but because a string is iterable, it's being applied to each single letter of <code>s</code>, and the reversal of a single-letter string is just the single letter.</p>
<p>For example:</p>
<pre><code>>>> map(lambda x: print(x), 'justdoit')
>>> list(map(lambda x: print(x), 'justdoit'))
j
u
s
t
d
o
i
t
[None, None, None, None, None, None, None, None]
</code></pre>
<p>and so</p>
<pre><code>>>> s = 'justdoit'
>>> list(map(lambda s: s[::-1], s))
['j', 'u', 's', 't', 'd', 'o', 'i', 't'] # 'j' reversed, 'u' reversed, etc
</code></pre>
|
python|lambda
| 3 |
1,908,657 | 65,190,722 |
Bonus marks award according to class and Int
|
<p>I want to find a bonus mark for students who fail. If the student from room 1 fail less than 5 subjects he get 5 marks, if the student rom room 2 fail less than 4 subjects he gets 4 marks for each subject and if a student from class 3 fail less than 3 subjects, he gets 3 marks for each subject. If the students fails more, then they wont get any bonus marks. I expected the output to be 1. Bonus that the students get (if they dont get any bonus then it should display no bonus mark awarded) 2. The total number of bonus mark obtained.</p>
<p>When I did no bonus mark awarded, it gave me no output.</p>
<pre><code>def main():
room = int(input('Class: '))
failed = int(input('Subjects failed: '))
bonus = 0.0
if (room == 1 and failed <= 5):
bonus = (5 * failed)
perbonus = 5
elif (room == 2 and failed <= 4):
bonus = (failed * 4)
perbonus = 4
elif (room == 3 and failed <= 3):
bonus = (failed * 3)
perbonus = 3
else:
print("Your bonus: ",perbonus)
print("Total bonus",bonus)
main()
</code></pre>
<pre class="lang-none prettyprint-override"><code>Class: 2
Subjects failed: 2
Process finished with exit code 0
</code></pre>
|
<p>You have your output in the scope of an 'else' clause.</p>
<p>Try removing the else and outdent the print lines to remove them from the scope of the last 'elif' clause.</p>
|
python
| 0 |
1,908,658 | 22,934,996 |
pandas pytables append: performance and increase in file size
|
<p>I have more than 500 <code>PyTables</code> stores that contain about 300Mb of data each. I would like to merge these files into a big store, using pandas <code>append</code> as in the code below.</p>
<pre><code>def merge_hdfs(file_list, merged_store):
for file in file_list:
store = HDFStore(file, mode='r')
merged_store.append('data', store.data)
store.close()
</code></pre>
<p>The append operation is very slow (it is taking up to 10 minutes to append a single store to <code>merged_store</code>), and strangely the file size of <code>merged_store</code> seems to be increasing by 1Gb for each appended store.</p>
<p>I have indicated the total number of expected rows which according to the documentation should improve performance, and having read <a href="https://stackoverflow.com/questions/20083098/improve-pandas-pytables-hdf5-table-write-performance">Improve pandas (PyTables?) HDF5 table write performance</a> I was expecting large write times, but almost 10 minutes for every 300Mb seems to be too slow, and I cannot understand why the increase in size.</p>
<p>I wonder if I am missing something?</p>
<p>For additional information, here is a description of one of the 500 PyTables.</p>
<pre><code>/data/table (Table(272734,)) ''
description := {
"index": Int64Col(shape=(), dflt=0, pos=0),
"values_block_0": Float64Col(shape=(6,), dflt=0.0, pos=1),
"id": StringCol(itemsize=11, shape=(), dflt='', pos=2),
"datetaken": Int64Col(shape=(), dflt=0, pos=3),
"owner": StringCol(itemsize=15, shape=(), dflt='', pos=4),
"machine_tags": StringCol(itemsize=100, shape=(), dflt='', pos=5),
"title": StringCol(itemsize=200, shape=(), dflt='', pos=6),
"country": StringCol(itemsize=3, shape=(), dflt='', pos=7),
"place_id": StringCol(itemsize=18, shape=(), dflt='', pos=8),
"url_s": StringCol(itemsize=80, shape=(), dflt='', pos=9),
"url_o": StringCol(itemsize=80, shape=(), dflt='', pos=10),
"ownername": StringCol(itemsize=50, shape=(), dflt='', pos=11),
"tags": StringCol(itemsize=505, shape=(), dflt='', pos=12)}
byteorder := 'little'
chunkshape := (232,)
</code></pre>
|
<p>This is basically the answer <a href="https://stackoverflow.com/questions/22777284/improve-query-performance-from-a-large-hdfstore-table-with-pandas/22820780#22820780">here</a>, which I recently answered.</p>
<p>Bottom line is this, you need to turn off indexing <code>store.append('df',df,index=False)</code>. When creating the store, then index it at the end.</p>
<p>Furthermore turn off compression when merging the tables as well.</p>
<p>Indexing is a fairly expensive operation and if I recall correctly, only uses a single processor.</p>
<p>Finally, make sure that you create the merged with with <code>mode='w'</code> as all of the subsequent operations are appends and you want to start with a clean new file.</p>
<p>I also would NOT specify the <code>chunksize</code> upfront. Rather, after you have created the final index, perform the compression using <code>ptrepack</code> and specify <code>chunksize=auto</code> which will compute it for you. I don't think this will affect write performance but will optimize query performance.</p>
<p>You might try tweaking the <code>chunksize</code> parameter to <code>append</code> (this is the writing chunksize) to a larger number as well.</p>
<p>Obviously make sure that each of the appending tables has exactly the same structure (will raise if this is not the case).</p>
<p>I created this issue for an enhancement to do this 'internally': <a href="https://github.com/pydata/pandas/issues/6837" rel="nofollow noreferrer">https://github.com/pydata/pandas/issues/6837</a></p>
|
python|performance|pandas|hdfs|pytables
| 3 |
1,908,659 | 45,709,985 |
'int' object is not iterable no matter what I do
|
<p>So I'm trying to code for a function that determines what day of the week you were born on. One of the functions I'm trying to create looks like this:</p>
<pre><code>def days_in_year(x):
y = 0
n = x-1
for years in n:
if years % 4 == 0:
y = y + 3
elif y % 4 != 0:
y = y + 1
return y
</code></pre>
<p>This returns 'TypeError: 'int' object is not iterable' no matter what I do. Any help would be appreciated.</p>
|
<p>You have to change the for loop to</p>
<pre><code>for years in range(n):
</code></pre>
<p>range() generates a list of numbers, which is generally used to iterate over with for loops.</p>
|
python|python-3.x|iterable
| 0 |
1,908,660 | 28,760,356 |
AttributeError while using Django Rest Framework with serializers
|
<p>I am following a tutorial located <a href="https://godjango.com/41-start-your-api-django-rest-framework-part-1/">here</a> that uses <a href="http://www.django-rest-framework.org/">Django Rest Framework</a>, and I keep getting a weird error about a field.</p>
<p>I have the following model in my <code>models.py</code></p>
<pre><code>from django.db import models
class Task(models.Model):
completed = models.BooleanField(default=False)
title = models.CharField(max_length=100)
description = models.TextField()
</code></pre>
<p>Then my serializer in <code>serializers.py</code></p>
<pre><code>from rest_framework import serializers
from task.models import Task
class TaskSerializer(serializers.ModelSerializer):
class Meta:
model = Task
fields = ('title', 'description', 'completed')
</code></pre>
<p>and my <code>views.py</code> as follows:</p>
<pre><code>from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response
from task.models import Task
from api.serializers import TaskSerializer
@api_view(['GET', 'POST'])
def task_list(request):
"""
List all tasks, or create a new task
"""
if request.method == 'GET':
tasks = Task.objects.all()
serializer = TaskSerializer(tasks)
return Response(serializer.data)
elif request.method == 'POST':
serializer = TaskSerializer(data=request.DATA)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
else:
return Response(
serializer.errors, status=status.HTTP_400_BAD_REQUEST
)
</code></pre>
<p>and my urls.py has this line:</p>
<pre><code>url(r'^tasks/$', 'task_list', name='task_list'),
</code></pre>
<p>When I try accessing <code>curl http://localhost:9000/api/tasks/</code>, I keep getting the following error and I'm not sure what to make of it:</p>
<pre><code>AttributeError at /api/tasks/
Got AttributeError when attempting to get a value for field `title` on serializer `TaskSerializer`.
The serializer field might be named incorrectly and not match any attribute or key on the `QuerySet` instance.
Original exception text was: 'QuerySet' object has no attribute 'title'.
</code></pre>
<p>What I'm I missing?</p>
|
<p>Simple specify <code>many=True</code> when creating a serializer from queryset, <code>TaskSerializer(tasks)</code> will work only with one instance of <code>Task</code>:</p>
<pre><code>tasks = Task.objects.all()
serializer = TaskSerializer(tasks, many=True)
</code></pre>
|
python|django|serialization|django-rest-framework|django-1.7
| 91 |
1,908,661 | 28,749,046 |
Web2py - what are the official list of arguments for sessions2trash.py?
|
<p>sessions2trash.py source has the following:</p>
<pre><code>Typical usage:
# Delete expired sessions every 5 minutes
nohup python web2py.py -S app -M -R scripts/sessions2trash.py &
# Delete sessions older than 60 minutes regardless of expiration,
# with verbose output, then exit.
python web2py.py -S app -M -R scripts/sessions2trash.py -A -o -x 3600 -f -v
# Delete all sessions regardless of expiry and exit.
python web2py.py -S app -M -R scripts/sessions2trash.py -A -o -x 0
</code></pre>
<p>Is there a canonical list of arguments somewhere? Thanks!</p>
<p><strong>Update:</strong> found it by browsing the source. Is there a standard way to show the help text? <code>python web2py.py -S app -M -R scripts/sessions2trash.py</code> doesn't show any help.</p>
|
<p>Found it in a section of the source:</p>
<pre><code>parser.add_option('-f', '--force',
action='store_true', dest='force', default=False,
help=('Ignore session expiration. '
'Force expiry based on -x option or auth.settings.expiration.')
)
parser.add_option('-o', '--once',
action='store_true', dest='once', default=False,
help='Delete sessions, then exit.',
)
parser.add_option('-s', '--sleep',
dest='sleep', default=SLEEP_MINUTES * 60, type="int",
help='Number of seconds to sleep between executions. Default 300.',
)
parser.add_option('-v', '--verbose',
default=0, action='count',
help="print verbose output, a second -v increases verbosity")
parser.add_option('-x', '--expiration',
dest='expiration', default=None, type="int",
help='Expiration value for sessions without expiration (in seconds)',
)
</code></pre>
<p>Note that since we're calling sessions2trash from web2py, we have to precede these arguments with -A, so web2py knows they're for the child script and not web2py.py itself.</p>
|
python|web2py
| 1 |
1,908,662 | 14,613,099 |
How do you sort the output of a python command?
|
<p>Python beginner here. Let's say that I have something at the end of my script that queries info from a system and dumps it into this format:</p>
<pre><code>print my_list_of_food(blah)
</code></pre>
<p>and it outputs a list like:</p>
<pre><code>('Apples', 4, 4792320)
('Oranges', 2, 2777088)
('Pickles', 3, 4485120)
('Pumpkins', 1, 5074944)
('more stuff', 4545, 345345)
</code></pre>
<p>How do I then sort that output based on the 2nd field so that it would look like this:</p>
<pre><code>('Pumpkins', 1, 5074944)
('Oranges', 2, 2777088)
('Pickles', 3, 4485120)
('Apples', 4, 4792320)
</code></pre>
<p>Other than importing a bash command to <code>cut -d "," -f 2 | head 4</code> I'd rather use python. I know I can use sorted or sort to sort an existing tuple or dictionary but I'm not sure of how to sort the output of a print. I've done some research and everything points to implementing sort into my script instead of sorting a print output but who knows, maybe someone has a solution. Thanks.</p>
<p>UPDATE:</p>
<p>Thanks everyone. I've tried to make all of the solutions work but I keep getting this error: </p>
<pre><code>File "test.py", line 18, in <lambda>
print sorted(my_list_of_food(blah), key=lambda x: x[1])
TypeError: 'int' object is unsubscriptable
File "test.py", line 18, in <lambda>
print(sorted(my_list_of_food(blah), key=lambda k: k[1]))
TypeError: 'int' object is unsubscriptable
</code></pre>
<p>I tried to include this at the beginning of the script:</p>
<pre><code>from __future__ import print_function
</code></pre>
<p>but no luck. </p>
|
<p>You can use the key argument to the sort. In your case,</p>
<pre><code>print(sorted(list_of_food, key=lambda k:k[1]))
</code></pre>
<p>will do the trick. The key function should return an integer, usually.</p>
|
python|sorting
| 7 |
1,908,663 | 57,173,573 |
How to best(most efficiently) read the first sheet in Excel file into Pandas Dataframe?
|
<p>Loading the excel file using read_excel takes quite long. Each Excel file has several sheets. The first sheet is pretty small and is the sheet I'm interested in but the other sheets are quite large and have graphs in them. Generally this wouldn't be a problem if it was one file, but I need to do this for potentially thousands of files and pick and combine the necessary data together to analyze. If somebody knows a way to efficiently load in the file directly or somehow quickly make a copy of the Excel data as text that would be helpful!</p>
|
<p>See the documentation for <a href="https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_excel.html" rel="nofollow noreferrer">pandas.read_excel()</a>. You can use <code>sheet_name=0</code> to read in only the first sheet.</p>
|
python|pandas|python-2.7
| 1 |
1,908,664 | 57,204,382 |
Inputs inside multiple forms with no submit button need to be displayed
|
<p>I'm new here and I'm not at a high programming level...<br>
I have a problem with the developing of a web application using flask and html. In the same html page I have some input boxes (that will be compiled by a user) and their content would be inserted inside a select that initially is empty. In addition I have no submit button and I could not insert it in my app because of the will of my boss. Is there a way to do this?<br></p>
<p>I've tried searching through the web for hours, but still nothing... Is there someone that could help me?</p>
|
<p></p>
<p>Add onblur function to input box and write function to insert their content. You can use onfocusout function also.</p>
|
python|html|http|flask|web-applications
| 0 |
1,908,665 | 25,488,139 |
Interfacing to an ipy exe using a socket
|
<p>Recently, I've been tasked with creating automation for a .NET software (Audio Precision APx500). My company's automation is based around Python and Robot Framework. Since Python has no inherent .NET support, my primary option is as follows: create a script using IronPython that interfaces with the APx500 API, compile this to an exe, and talk to that exe over a socket.</p>
<p>The client would be the python lib that I would import in RF. Methods in this lib would send a message over the socket to the server (the ipy exe), which would interpret the message and run a particular function of the APx500 API.</p>
<p>The problem lies in my lack of understanding of how to configure the socket server-side. I don't know how to properly receive and interpret messages sent from the client.</p>
<p>Say I do something like:</p>
<pre><code>def startAP(self):
self.sock.send("open APx500")
</code></pre>
<p>How would the server interpret this to execute the correct task? </p>
<p>If there are better ways to do what I'm attempting, please, let me know.</p>
|
<p>If you use the robot framework <a href="http://robotframework.org/robotframework/latest/RobotFrameworkUserGuide.html#remote-library-interface" rel="nofollow">remote library API</a> you don't have to worry about the lower level implementation. In your test you call a keyword, and the remote API will send the request to the server which will execute a function and return the result. </p>
<p>You can build your server from scratch using iron python if you want, though it might be easier for you to use <a href="https://code.google.com/p/nrobotremote/" rel="nofollow">nrobotremote</a>. The wiki for that project has a page titled <a href="https://code.google.com/p/nrobotremote/wiki/HowToWriteKeywordLibrary" rel="nofollow">How to write a keyword library</a> which shows how to use the library. </p>
|
.net|sockets|ironpython|robotframework
| 1 |
1,908,666 | 44,611,987 |
input is getting overwritten python
|
<pre><code>T = int(input())
while T > 0:
rangeofnum = input().split(" ")
starting = int(rangeofnum[0])
ending = int(rangeofnum[1])
print(starting)
print(ending)
</code></pre>
<p>description: when input is given like:</p>
<pre><code>input: 2
1 10
output:1
10
input: 3 5
output:3
5
</code></pre>
<p>but when I give input as follows:</p>
<pre><code>input:2
1 10
3 5
output:1
10
</code></pre>
<p>Why ? and how to correct this?</p>
<p>I am a begginer to python?</p>
|
<p>As per the code you have given there should be two errors you should face:</p>
<p>(1) Indentation error: You have given indent at the start of while statement unnecessarily.</p>
<p>(2) Infinite loop: Your while loop never ends as the value of 'T' is always greater than '0' as you have decremented it.</p>
<p>As per your usage using a <strong>for</strong> loop with <strong>range(0,T)</strong> would be better. Below is the corrected code with while loop</p>
<pre><code>T = int(input())
while T > 0:
rangeofnum = input().split(" ")
starting = int(rangeofnum[0])
ending = int(rangeofnum[1])
print(starting)
print(ending)
T -= 1
</code></pre>
|
python|input|overriding
| 1 |
1,908,667 | 61,712,407 |
CORS error in firebase python cloud function
|
<p>My firebase python HTTP cloud function keeps throwing the CORS error:</p>
<pre><code>Access to fetch at 'https://<project>.cloudfunctions.net/<fn_name>' from origin 'http://localhost:3000' has been blocked by CORS policy:
Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
</code></pre>
<p>even though I'm handling the preflight requests: </p>
<pre class="lang-py prettyprint-override"><code>def get_user_db_exist(request):
"""Responds to any HTTP request.
Args:
request (flask.Request): HTTP request object.
Returns:
The response text or any set of values that can be turned into a
Response object using
`make_response <http://flask.pocoo.org/docs/1.0/api/#flask.Flask.make_response>`.
"""
if request.method == 'OPTIONS':
# Allows GET requests from any origin with the Content-Type
# header and caches preflight response for an 3600s
headers = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET',
'Access-Control-Allow-Headers': 'Content-Type',
'Access-Control-Max-Age': '3600'
}
return ('', 204, headers)
headers = {
'Access-Control-Allow-Origin': '*'
}
print(request)
return (json.dumps({ 'status': 'sucess' }), 200, headers)
</code></pre>
<p>I tried setting <code>Access-Control-Allow-Methods</code> to <code>'GET'</code>, <code>'POST'</code>, <code>'GET, POST'</code> to no avail (The request from frontend is a POST Request). </p>
<p>I also tried creating a copy of an existing function that worked. While the existing function worked, the newly created duplicate threw the CORS error. </p>
<p><a href="https://stackoverflow.com/questions/53035357/google-cloud-function-python-cors-error-no-access-control-allow-origin-header/55371251">google cloud function python CORS error No 'Access-Control-Allow-Origin' header is present on the requested resource.</a> and instructions at <a href="https://cloud.google.com/functions/docs/writing/http#functions_http_cors-python" rel="nofollow noreferrer">https://cloud.google.com/functions/docs/writing/http#functions_http_cors-python</a> didn't work. </p>
<p>The frontend is a React app which uses firebase sdk version <code>7.14.3</code>. (It didn't work with <code>v7.14.2</code> either). </p>
|
<p>You didn't set response headers correctly. Change </p>
<pre class="lang-py prettyprint-override"><code>return json.dumps({ 'status': 'sucess' }, 200, headers)
</code></pre>
<p>To:</p>
<pre class="lang-py prettyprint-override"><code>return (json.dumps({'status': 'sucess'}), 200, headers)
</code></pre>
<p>The complete code:</p>
<pre class="lang-py prettyprint-override"><code>from flask import json
def cors_enabled_function(request):
# Set CORS headers for preflight requests
if request.method == 'OPTIONS':
headers = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET',
'Access-Control-Allow-Headers': 'Content-Type',
'Access-Control-Max-Age': '3600',
}
return ('', 204, headers)
# Set CORS headers for main requests
headers = {
'Access-Control-Allow-Origin': '*',
}
return (json.dumps({'status': 'sucess'}), 200, headers)
</code></pre>
<p>And this is the frontend app running on <code>http://localhost:5000</code>:</p>
<pre class="lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Your front end app</title>
</head>
<body>
<script>
window.onload = async function () {
const endpoint = 'https://us-central1-xxxxx-218808.cloudfunctions.net/cors_enabled_function';
const res = await fetch(endpoint, { method: 'POST' }).then((res) => res.json());
console.log('res:', res);
};
</script>
</body>
</html>
</code></pre>
<p>The output of the <code>console.log</code>: <code>res: {status: "sucess"}</code></p>
<p>Check the response header from browser:</p>
<pre><code>access-control-allow-origin: *
alt-svc: h3-27=":443"; ma=2592000,h3-25=":443"; ma=2592000,h3-T050=":443"; ma=2592000,h3-Q050=":443"; ma=2592000,h3-Q049=":443"; ma=2592000,h3-Q048=":443"; ma=2592000,h3-Q046=":443"; ma=2592000,h3-Q043=":443"; ma=2592000,quic=":443"; ma=2592000; v="46,43"
cache-control: private
content-encoding: gzip
content-length: 40
content-type: text/html; charset=utf-8
date: Wed, 13 May 2020 09:05:21 GMT
function-execution-id: maluigz9ytxx
server: Google Frontend
status: 200
x-cloud-trace-context: 853d11ceef85ec4a231d45dd59f7377e;o=1
</code></pre>
<p><code>access-control-allow-origin: *</code> header set up successfully.</p>
|
python|firebase|cors|google-cloud-functions
| 1 |
1,908,668 | 23,642,158 |
search a element of a list in a string
|
<p>Can I do this:</p>
<pre><code>s="j g a c"
for a in ("a","b","c"):
if a in s:
print("asd")
break
</code></pre>
<p>Like this:</p>
<pre><code>if s in a:
print("asd")
</code></pre>
<p>or any other way to write less?</p>
|
<p>No, of course you can't do that; is <code>"j g a c" in ("a","b","c")</code>?</p>
<p>You could, however, use <a href="https://docs.python.org/2/library/functions.html#any" rel="nofollow"><code>any</code></a> to shorten your code:</p>
<pre><code>s = "j g a c"
if any(a in s for a in "abc"):
print("asd")
</code></pre>
|
python|if-statement|for-loop
| 2 |
1,908,669 | 20,411,647 |
wxPython: CustomTreeCtrl disable checking for event EVT_KEY_DOWN
|
<p>I am currently using CustomTreeCtrl instead of the regular TreeCtrl because it allows me to have checkbox / radio button with the tree nodes.</p>
<p>However, I realize the control itself catches event EVT_KEY_DOWN (whenever any key is pressed) to look for any matching tree nodes. I need the event EVT_KEY_DOWN for other purposes, so is there a way to disable the tree control from recognizing EVT_KEY_DOWN?</p>
<p>Or would it work if I create my own CustomTreeCtrl that does not have self.Bind(wx.EVT_KEY_DOWN, self.onKeyDown) inside? How would I locate that Python file then (wx.lib.agw.customtreectrl) on Linux?</p>
|
<p><code>treeCtrl.Unbind(wx.EVT_KEY_DOWN)</code></p>
<p>I think would work :P</p>
|
python|file|module|tree|wxpython
| 0 |
1,908,670 | 20,447,538 |
How do I prepopulate a text field with suggested text in Tkinter?
|
<p>I'm trying to prepopulate a text field based on the most recent entry. As this is not a Listbox, I don't see how to do it, and I'm not seeing any examples on the web. Thanks. </p>
<p>Update. I've managed to find a partial way of doing this. Still wondering, is it possible to supply suggested text in Tkinter which fades when the text box is clicked? </p>
<pre><code>from Tkinter import *
app = Tk()
app.title("GUI Example")
app.geometry('560x460+200+200')
x = Text(app)
x.insert(END, "Before")
x.pack()
def replace():
x.delete(1.0, END)
x.insert(END, "After")
abutton = Button(app, text="Click me", command=replace)
abutton.pack()
app.mainloop()
</code></pre>
|
<p>Well, I personally don't know of any options to do this (any answers giving one will easily trump this one). </p>
<p>However, you can closely <em>mimic</em> this behavior with a little coding. Namely, you can <a href="http://effbot.org/tkinterbook/tkinter-events-and-bindings.htm" rel="nofollow">bind</a> the textbox to a function that will insert/remove the default text for you.</p>
<p>Below is a simple script to demonstrate:</p>
<pre><code>import Tkinter as tk
tk.Tk()
textbox = tk.Text(height=10, width=10)
textbox.insert(tk.END, "Default")
textbox.pack()
# This is for demonstration purposes
tk.Text(height=10, width=10).pack()
def default(event):
current = textbox.get("1.0", tk.END)
if current == "Default\n":
textbox.delete("1.0", tk.END)
elif current == "\n":
textbox.insert("1.0", "Default")
textbox.bind("<FocusIn>", default)
textbox.bind("<FocusOut>", default)
tk.mainloop()
</code></pre>
<p>Notice how:</p>
<ol>
<li><p>When you click in the top textbox, the default text disappears.</p></li>
<li><p>When you click in the bottom textbox, the top one loses focus and the default text reappears.</p></li>
<li><p>This behavior will only occur if there is nothing in the top textbox.</p></li>
</ol>
|
python|tkinter
| 2 |
1,908,671 | 72,114,000 |
Hide div element using python in Flask
|
<p>I have a div element on ticket.html as
<code><div class="rgrp" style="visibility:hidden">....<\div></code></p>
<p>So on page /ticket is the form which on submitted redirect to same page as /ticket#</p>
<pre><code>@app.route('/ticket', methods=[POST]
def ticket_display() :
#now here I want to set visibility visible of that div class```
</code></pre>
|
<p>In your template for ticket.html you could put something like this:</p>
<pre><code><div class="rgrp" style="visibility:{{ visibility }}">....<\div>
</code></pre>
<p>Then when you're calling your render template, you can do something like this:</p>
<pre><code>return render_template('ticket.html', visibility="hidden" )
</code></pre>
<p>If you need to make it visible later, just change the value of the visibility variable you're passing into the render_template function.</p>
|
python|html|flask
| 1 |
1,908,672 | 71,865,359 |
Python Beginner: While Loop so long as item is in list
|
<p>I am trying to make a Hangman game and implement a while loop with the condition below. When I run it through Thonny the while loop comes back as false even though the variable display has that character in the list.</p>
<pre><code>display = []
for _ in range(word_length):
display += "_"
while "_" in display == True:
guess = input("Guess a letter: ").lower()
for position in range(word_length):
letter = chosen_word[position]
if letter == guess:
display[position] = letter
print(display)
</code></pre>
<p>What am I doing wrong?</p>
<p>Edit: Took out debugging code that wasn't relevant to question.</p>
|
<p><code>in</code> and <code>==</code> are both comparison operators, subject to comparison chaining. As a result, your unnecessary comparison to <code>True</code> makes this equivalent to</p>
<pre><code>"_" in display and display == True
</code></pre>
<p>You could parenthesize it explicitly to disable chaining</p>
<pre><code>("_" in display) == True
</code></pre>
<p>but you should just drop the <code>== True</code> altogether:</p>
<pre><code>while "_" in display:
...
</code></pre>
|
python
| 0 |
1,908,673 | 64,327,654 |
How do I normalize a 2d list? (python)
|
<p>I have a 2d list that looks something like this: [[5, 4, -1], [3, -7, 8], [2, -9, 4]]
How would I go about normalizing all the numbers in the list to be decimals between -1 and 1</p>
<p>anything helps, thanks</p>
|
<p>I am not too certain how you want to normalize your numbers, so I am just going to assume that you want to add all the numbers in the list, and then divide each element by that sum.</p>
<p>Assume that</p>
<pre><code>A = [[5, 4, -1], [3, -7, 8], [2, -9, 4]]
</code></pre>
<p>Running the below</p>
<pre><code>[list(map(lambda x: round(x / sum(sublist), 1), sublist)) for sublist in A]
</code></pre>
<p>You will get</p>
<pre><code>[[0.6, 0.5, -0.1], [0.8, -1.8, 2.0], [-0.7, 3.0, -1.3]]
</code></pre>
|
python|list
| 1 |
1,908,674 | 70,725,203 |
Formatting a Numpy array with even and odd numbers
|
<p>I am trying to write a code that replaces the even numbers with positive <code>init_val</code> value within the <code>sequence_numbers</code> and every odd and 0 valued variable into negative <code>init_val</code> values. How would I be able to code such a thing?</p>
<p>Code:</p>
<pre><code>import numpy as np
import pandas as pd
sequence_numbers= np.array([1,0,4,7,9,12,15,16,22,2,4,8,11,13,11,21,23,3])
#The choice could be 'even', 'odd' or '0'
choice = 'even'
init_val = 100
</code></pre>
<p>Expected output:</p>
<pre><code>[-100, -100, 100, -100, -100, 100, -100,100, 100,
100, 100, 100, -100, -100, -100, -100, -100, -100 ]
</code></pre>
|
<p>Use <code>numpy.where</code> and the modulo operator to determine the odd/even status.</p>
<p>Example for 'even':</p>
<pre><code>out = np.where(sequence_numbers%2, -init_val, init_val)
</code></pre>
<p>output:</p>
<pre><code>array([-100, 100, 100, -100, -100, 100, -100, 100, 100, 100, 100,
100, -100, -100, -100, -100, -100, -100])
</code></pre>
<p>For 'odd', just reverse the True/False values:</p>
<pre><code>out = np.where(sequence_numbers%2, init_val, -init_val)
</code></pre>
<p>or inverse the <code>init_val</code>:</p>
<pre><code>if choice == 'odd':
init_val *= -1
out = np.where(sequence_numbers%2, -init_val, init_val)
</code></pre>
|
python|arrays|numpy|iterator|format
| 2 |
1,908,675 | 69,855,166 |
I am trying to run a program which I have cloned from GitHub and followed every step that they told but I am having this problem running it in CMD
|
<pre class="lang-none prettyprint-override"><code>F:\Hacking\GitHub\sherlock>python3 -m pip install -r requirements.txt
Python was not found; run without arguments to install from the Microsoft Store, or disable this shortcut from Settings > Manage App Execution Aliases.
</code></pre>
|
<p>You provided limited information</p>
<ol>
<li><p>First off check if you have installed python: I suggest using Anaconda. It's quite straightforward.</p>
</li>
<li><p>After that create a conda (Anaconda) environment (imagine it as a space that you can have different versions of packages- Python packages tend to be very dependent on the version of related packages, conda usually check the compatibility of them when you are installing them)</p>
</li>
<li><p>Using pip and conda together can be tricky. I suggest first install the main packages then go for more specialized one, maybe using pip</p>
</li>
<li><p>Try to have an issue on the github page of the project. If the package is popular or fresh, they usually respond fast.</p>
</li>
</ol>
|
python|github|cmd
| 0 |
1,908,676 | 72,940,524 |
3D UNet activation function and number classes
|
<p>I am a beginner in deep learning and trying to develop a U-Net model for vessel segmentation (vessel (white pixels), background (black pixels)) on nifti images. I am confused on the defining the number of classes and sigmoid/softmax activation function. Should I set the number of n_classes = 2 and softmax activation function for this or n_classes = 1 and sigmoid activation function? below are the codes for the DataGenerator and UNet model.</p>
<pre><code>n_classes = 2
class DataGenerator(tf.keras.utils.Sequence):
def __init__(self, img_paths, mask_paths, batch_size, n_classes):
self.x, self.y = img_paths, mask_paths
self.batch_size = batch_size
self.n_classes = n_classes
def __len__(self):
return math.ceil(len(self.x) / self.batch_size)
def read_nifti(self, filepath):
volume = nib.load(filepath).get_fdata()
volume = np.array(volume)
return volume
def __getitem__(self, idx):
batch_x = self.x[idx * self.batch_size:(idx + 1) * self.batch_size]
batch_y = self.y[idx * self.batch_size:(idx + 1) * self.batch_size]
image = [self.read_nifti(image_file) for image_file in batch_x]
image = np.array(image, dtype=np.float32)
image = tf.expand_dims(image, axis=-1)
label = [self.read_nifti(mask_file) for mask_file in batch_y]
label = np.array(label, dtype=np.float32)
label = tf.keras.utils.to_categorical(label, num_classes=self.n_classes)
return image, label
'''---------------------build CNN model -------------------'''
def unet3d_model1(nx= 224, ny=224, nz=64):
inputs = Input((nx, ny, nz, 1))
conv1 = Conv3D(32, (3, 3, 3), activation='relu', padding='same')(inputs)
conv1 = Conv3D(32, (3, 3, 3), activation='relu', padding='same')(conv1)
pool1 = MaxPool3D(pool_size=(2, 2, 2))(conv1)
conv2 = Conv3D(64, (3, 3, 3), activation='relu', padding='same')(pool1)
conv2 = Conv3D(64, (3, 3, 3), activation='relu', padding='same')(conv2)
pool2 = MaxPool3D(pool_size=(2, 2, 2))(conv2)
conv3 = Conv3D(128, (3, 3, 3), activation='relu', padding='same')(pool2)
conv3 = Conv3D(128, (3, 3, 3), activation='relu', padding='same')(conv3)
pool3 = MaxPool3D(pool_size=(2, 2, 2))(conv3)
conv4 = Conv3D(256, (3, 3, 3), activation='relu', padding='same')(pool3)
conv4 = Conv3D(256, (3, 3, 3), activation='relu', padding='same')(conv4)
up5 = UpSampling3D(size=(2, 2, 2))(conv4)
merge5 = concatenate([up5, conv3])
conv5 = Conv3D(128, (3, 3, 3), activation='relu', padding='same')(merge5)
conv5 = Conv3D(128, (3, 3, 3), activation='relu', padding='same')(conv5)
up6 = UpSampling3D(size=(2, 2, 2))(conv5)
merge6 = concatenate([up6, conv2])
conv6 = Conv3D(64, (3, 3, 3), activation='relu', padding='same')(merge6)
conv6 = Conv3D(64, (3, 3, 3), activation='relu', padding='same')(conv6)
up7 = UpSampling3D(size=(2, 2, 2))(conv6)
merge7 = concatenate([up7, conv1])
conv7 = Conv3D(32, (3, 3, 3), activation='relu', padding='same')(merge7)
conv7 = Conv3D(32, (3, 3, 3), activation='relu', padding='same')(conv7)
conv8 = Conv3D(n_classes, (1, 1, 1), activation='softmax')(conv7)
model = Model(inputs=inputs, outputs=conv8)
return model
</code></pre>
|
<p>As you said, a pixel can belong to a vessel pixel or background pixel. So, what makes sense to use a single node with sigmoid activated output layer. With that, you will have a probability of the regarding pixel's "vessel-ness". Then obviously, you need to apply a threshold to extract the vessel image.</p>
<p>Hope that helps.</p>
|
python|keras|deep-learning|image-segmentation|unet-neural-network
| 1 |
1,908,677 | 55,632,867 |
How can I unroll and re_roll the matrix in numpy about specific axis?
|
<p>(Related to a project related to neural networks)I have 500 images in the form of numpy array of shape <code>(500, 200, 200, 1)</code> that is, 500 gray scale images of dimensions (200,200). I want to unroll this into shape=<code>(400, 500)</code> where each column comes from each of the images. </p>
<p>Currently I am doing it as :</p>
<pre><code> images.shape # (500,200,200,1)
images = images.transpose(1,2,3,0)
images = images.reshape(200*200*1, 500)
images.shape # (400, 500) -- each column is an un-rolled image
</code></pre>
<p>Then in back propagation, I wan to revert back to original shape which I am doing as:</p>
<pre><code> D_images.shape # prints (400, 500)
D_images = D_images.reshape(500, 200, 200, 1)
</code></pre>
<p>I suspect the reversion to original shape is not correct (I want the gradient of each example image to flow into respective example). Is there any fancier way to roll and unroll making sure examples are not mixing?</p>
|
<p>You will have to undo both actions bottom to top with their respective complementary operations:</p>
<pre><code>D_images = D_images.reshape(200, 200, 1, 500)
D_images = D_images.transpose(3, 0, 1, 2)
</code></pre>
|
python|numpy
| 0 |
1,908,678 | 55,681,186 |
How to make user input in Python 3
|
<p>I want to create a program that will say correct or incorrect when a user types down a answer.</p>
<p>I tried using Python storing variables to solve the problem but to no avail</p>
<p>The code is a bit like this</p>
<pre><code> question1 = input ("Type down a password!")
if input = "bannanas"
print('Sucess!')
else print("ohhhhh")
</code></pre>
<p>But the terminal says </p>
<pre><code>File "main.py", line 2
if input = "bannanas"
^
SyntaxError: invalid syntax`enter code here`
</code></pre>
|
<p>Your code must be like below:</p>
<pre><code>question1 = input("Type down a password!")
if question1 == 'bannanas':
print('Sucess!')
else:
print('ohhhhh')
</code></pre>
|
python|user-input
| 0 |
1,908,679 | 55,989,221 |
Error when selecting the number of features to be used to SVC classifier
|
<p>I am working on this project in this site </p>
<p><a href="https://scikit-learn.org/stable/auto_examples/svm/plot_iris.html" rel="nofollow noreferrer">https://scikit-learn.org/stable/auto_examples/svm/plot_iris.html</a> with the Iris dataset</p>
<p>However when I try to implement</p>
<pre><code>X = iris.data[:, :2]
</code></pre>
<p>an error comes saying </p>
<pre><code>File "`<pyshell#16>"`, line 1, in <module>
X = iris.data[:, :2]
NotImplementedError: multi-dimensional slicing is not implemented
</code></pre>
<p>Can someone tell me why this is and what can I do to avoid this please</p>
|
<p>It looks like the format of the data might have changed. </p>
<p><code>load_iris</code> seems to load the data as a dictionary.</p>
<p>This should work:</p>
<pre><code>iris = load_iris()
X = iris['data'][:, :2]
y = iris['target']
</code></pre>
|
python|scikit-learn
| 0 |
1,908,680 | 50,034,015 |
How to iterate through a list containing Twitter Stream data?
|
<p>I was streaming Data from twitter using tweepy Streaming api , </p>
<pre><code>class MyStreamListener(tweepy.StreamListener):
def __init__(self):
super().__init__()
self.counter = 0
self.limit = 8
self.q=list()
def on_status(self, status):
self.counter += 1
if self.counter < self.limit:
self.q.append(status.user.name)
self.q.append(status.user.statuses_count)
#print(status.text)
else:
myStream.disconnect()
print(self.q)
</code></pre>
<p>In <code>on_status</code> method I had stored all the data and <code>status_count</code> in the list, but when I tried to iterate the data I wasn't able to do so </p>
<pre><code>enter code here
tweet_list=list()
tweet_list.append(myStream.filter(track=[p]))
#tweet_list=myStream.filter(track=[p])
print(len(myStream.filter(track=[p])))
</code></pre>
<p>I get this result:</p>
<pre><code>['Chanchinthar', 1063, 'Sourabh', 4424]
Traceback (most recent call last):
File "C:/Users/TharunReddy/Desktop/pothi/twitter.py", line 51, in <module>
print(len(myStream.filter(track=[p])))
TypeError: object of type 'NoneType' has no len()
</code></pre>
<p>How can store the tweets in the list and be able to iterate over it?
someone please help!</p>
|
<p>Your <code>myStream</code> object is not a list but a generator (which is in turn a type of iterator). Iterators are basically iterables (like lists) whose elements are computed (lazily) one at a time: only once they are needed. This is a much more memory-efficient structure, but the length cannot be computed. (Also, you will also be able to iterate through them once).</p>
<p><strong>TLDR</strong>: convert your <code>myStream</code> into a list: <code>list(myStream)</code> and everything will be fine.</p>
<p>For more info on generators/iterators see <a href="http://nvie.com/posts/iterators-vs-generators/" rel="nofollow noreferrer">here</a></p>
|
python|twitter|tweepy|twitter-streaming-api
| 0 |
1,908,681 | 50,009,046 |
Return custom payload from default response
|
<p>In Django 2.0 I am using the rest_auth and currently it returns a response like </p>
<pre><code>{
"token": "foo_token",
"user":{
"pk": 1,
"username": "admin",
"email": "test@test.com",
"first_name": "John",
"last_name": "Doe"
}
}
</code></pre>
<p>I would like to change this to return something besides the default response django provides. Something like...</p>
<pre><code>{
"token": "foo_token",
"pk":1,
"username": "admin",
"somefield": "Foo Funk"
}
</code></pre>
<p>My urls.py look like this currently</p>
<pre><code>url(r'^rest-auth/registration/', include('rest_auth.registration.urls')),
url(r'^refresh-token/', refresh_jwt_token),
url(r'^api/userlist', users.user_list),
</code></pre>
<p>The only place I can find to possibly change the response is in library files which I am sure is not wise to change. Any help would be great. </p>
|
<p><code>rest_auth</code> allows you to change the responses by specifying your own serializer implementation in your <code>settings.py</code>.</p>
<p>For example if you wanted to customize the response for JWT authentication, then you might create:</p>
<pre><code># myapp/serializers.py
class MyCustomJWTSerializer(serializers.Serializer):
token = serializers.CharField()
pk = serializers.IntegerField()
username = serializers.CharField()
...
</code></pre>
<p>which you can then configure in your <code>settings.py</code> as:</p>
<pre><code>REST_AUTH_SERIALIZERS = {
'JWT_SERIALIZER': 'myapp.serializers.MyCustomJWTSerializer'
}
</code></pre>
<p>More info here: <a href="https://django-rest-auth.readthedocs.io/en/latest/configuration.html" rel="nofollow noreferrer">https://django-rest-auth.readthedocs.io/en/latest/configuration.html</a></p>
|
django|python-3.x|django-models|django-rest-framework|django-views
| 1 |
1,908,682 | 49,847,181 |
export .csv file in flask using ajax
|
<p>I am trying to upload a csv file from the page and send it to the backend made of python and flask, all the gets working fine, knowing that because backend returns: </p>
<blockquote>
<p>127.0.0.1 - - [15/Apr/2018 15:37:07] "GET /medal HTTP/1.1" 200</p>
</blockquote>
<p>but nothing on the POST. Tried almost everything but no connections or messages.</p>
<p><strong>BACKEND POST:</strong></p>
<pre><code>import pandas
from calest import calest_app, client
from flask import request, jsonify
from..models.Medals import Medal
db = client.estadisticas
collection = db.medallas
@calest_app.route('/result', methods = ["POST"])
def post_discipline():
csv_received = request.files['file']
csv_file = pandas.read_csv(csv_received)
discipline_result = Medal(csv_file).get_medals_discipline()
gender_result = Medal(csv_file).get_medals_gender()
city_result = Medal(csv_file).get_medals_city()
country_result = Medal(csv_file).get_medals_country()
medals_result = Medal(csv_file).get_medals_by_medals()
sport_result = Medal(csv_file).get_medals_by_sport()
cursor = collection.insert({
"discipline": discipline_result,
"gender": gender_result,
"city": city_result,
"country": country_result,
"medal": medals_result,
"sport": sport_result
})
return jsonify("Added"), 201
</code></pre>
<p><strong>FRONTEND AJAX:</strong></p>
<pre><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js" > </script>
< script >
$("#form").on("submit", function (e) {
var fileSelect = $("#csvFile");
var files = fileSelect[0].files;
// Create a new FormData object.
var formData = new FormData();
debugger;
formData.append("#csvFile", files[0].name, files[0], files[0].name);
<!--csv_received = request.-- >
$.ajax({
url: "http://localhost:5000/result",
method: "POST",
data: formData,
contentType: false, // The content type used when sending data to the server.
cache: false, // To unable request pages to be cached
processData: false, // To send DOMDocument or non processed data file it is set to false
success: function (data) {
debugger;
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
debugger;
}
})
});
</script>
</code></pre>
|
<p><code>formData.append</code> takes at most 3 parameters, you're passing 4.<br>
The first parameter is the field name(not the id selector as you have it).<br>
Second is the File/Blob/string data(where you put the file name).
Third field is the file name, which is really only necessary when you pass a Blob.<br>
Since you use <code>file</code> as the field name in your server code use that as the first parameter</p>
<pre><code>formData.append("file", files[0]);
</code></pre>
|
python|ajax|flask
| 0 |
1,908,683 | 64,032,731 |
TKINTER: I can't copy a string output
|
<p>I created a simple GUI application that returns a string after taking a user input. I want to be able to copy the string once it's printed on the GUI but I can't, I think it's because initally I used Label:</p>
<pre><code>d = 'some string that I want to copy'
data = Label(main, text=d)
data.pack()
</code></pre>
<p>I tried doing Text instead so that I can copy the output from a text box but I keep getting this error message:</p>
<p><strong>bad wrap "some string that I want to copy" must be char, none, or word.</strong></p>
<p>code:</p>
<pre><code>data = Text(main, wrap=d)
data.pack()
</code></pre>
|
<p>This works?</p>
<pre><code>from tkinter import *
main = Tk()
d='This is the input'
data = Label(main, text=d)
data.pack()
main.mainloop()
</code></pre>
<p>All though it would help if you posted your full code</p>
|
python|tkinter
| 0 |
1,908,684 | 52,925,979 |
Issue for Python RAWPY package installation on Windows
|
<p>I want to read RAW files on Python, and it seems that the Rawpy package is well suited for this. However when trying to install it using the Windows CMD</p>
<pre><code>C:\Users\myself>py -m pip install rawpy
</code></pre>
<p>Or directly using Spyder command line with</p>
<pre><code>!pip install rawpy
</code></pre>
<p>I get the following error</p>
<pre><code>Using cached https://files.pythonhosted.org/packages/67/05/866890cb4d0d76f12bf83cc55a935694c9febb4728cca861d3f7711f46f4/rawpy-0.12.0.tar.gz
Requirement already satisfied: numpy in c:\users\myself\appdata\local\continuum\anaconda3\lib\site-packages (from rawpy) (1.15.1)
Building wheels for collected packages: rawpy
Running setup.py bdist_wheel for rawpy ... error
Complete output from command C:\Users\myself\AppData\Local\Continuum\anaconda3\python.exe -u -c "import setuptools, tokenize;__file__='C:\\Users\\myself\\AppData\\Local\\Temp\\pip-install-40sfkvpi\\rawpy\\setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" bdist_wheel -d C:\Users\myself\AppData\Local\Temp\pip-wheel-3bs1uw1y --python-tag cp37:
LibRaw git submodule is not cloned yet, will invoke "git submodule update --init" now
copying CMake scripts from LibRaw-cmake repository
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "C:\Users\myself\AppData\Local\Temp\pip-install-40sfkvpi\rawpy\setup.py", line 298, in <module>
windows_libraw_compile()
File "C:\Users\myself\AppData\Local\Temp\pip-install-40sfkvpi\rawpy\setup.py", line 151, in windows_libraw_compile
clone_submodules()
File "C:\Users\myself\AppData\Local\Temp\pip-install-40sfkvpi\rawpy\setup.py", line 132, in clone_submodules
shutil.copy('external/LibRaw-cmake/CMakeLists.txt', 'external/LibRaw/CMakeLists.txt')
File "C:\Users\myself\AppData\Local\Continuum\anaconda3\lib\shutil.py", line 241, in copy
copyfile(src, dst, follow_symlinks=follow_symlinks)
File "C:\Users\myself\AppData\Local\Continuum\anaconda3\lib\shutil.py", line 120, in copyfile
with open(src, 'rb') as fsrc:
FileNotFoundError: [Errno 2] No such file or directory: 'external/LibRaw-cmake/CMakeLists.txt'
</code></pre>
<p>The last error line explicitly says that the file <em>external/LibRaw-cmake/CMakeLists.txt</em> cannot be found. Do you have any idea how to solve the issue?</p>
<p>For information, other packages don't show errors when running these CMD command lines. The error is really <em>rawpy</em> package dependent.</p>
|
<p>The version available at the time of the post (0.12.0) didn't offer Python 3.7 wheels, therefore pip downloaded the source distribution and tried to compile the package manually. This failed since it requires a more involved development setup.</p>
<p>A new rawpy version 0.13.0 is released now and offers wheels for Python 3.7 as well. A simple <code>pip install rawpy</code> should then work and download the wheel instead of the source distribution.</p>
|
python|package
| 1 |
1,908,685 | 65,090,371 |
How to replace a column in a excel workbook with a dataframe in python
|
<p>I've scraped data from internet and after some operation I've obtained a dataframe like this;</p>
<pre><code> 0 1 2 3
3 BAFRA 0 10000 0.114705
4 BAFRA 100001 300000 0.114705
1 BAFRA 300001 1000000 0.114705
0 BAFRA 1000001 10000000 0.114705
2 BAFRA 10000001 100000000 0.114705
5 BAFRA 100000000 100000001 0.114705
</code></pre>
<p>What I want is take the third column and replace it in exist excel file in a specific sheet and to a specific column and row.
I am using this code;</p>
<pre><code>with pd.ExcelWriter(...\Gas Settlement Aug20.xlsx",engine="openpyxl") as writer:
df[3].to_excel(writer, sheet_name='Unit Prices',header= False, index = False, startcol=12,startrow=24)
import openpyxl
wb = openpyxl.load_workbook(...\Gas Settlement Aug20.xlsx")
ws = wb['Unit Prices']
wb.save(...\Gas Settlement Aug20.xlsx")
</code></pre>
<p>But it delete all the information, I tried the mode 'a' but this time it creates a new sheet.
Is there any way to replace my old data with the new ones...</p>
|
<p>It seems you are using two different approaches at once: pd.ExcelWriter and openpyxl.
Just following the sample you provided you can use openpyxl like this to update your file:</p>
<pre><code>import openpyxl
wb = openpyxl.load_workbook("...\Gas Settlement Aug20.xlsx")
ws = wb['Unit Prices']
startcol = 12
startrow = 24
for item in df[3]:
ws.cell(startrow, startcol).value = item
startrow +=1
wb.save(...\Gas Settlement Aug20.xlsx")
</code></pre>
<p>But I suggest that you don't use this form of indexing with numbers, because it is easy to create errors, and very hard to find those errors. Depending on the size, even reading the whole file, updating and saving again would be much safer and easier to track.</p>
|
python|excel|pandas|openpyxl
| 0 |
1,908,686 | 68,490,564 |
urllib.error.HTTPError: HTTP Error 404: Not Found using pandas even though the url exists
|
<p>I was trying to run this code:</p>
<pre class="lang-py prettyprint-override"><code>import pandas as pd
df = pd.read_csv(r"C:\Users\Chaitanya\Desktop\Finsearch\AAPL.csv")
df = df.sort_values(by="Date")
df = df.dropna()
# calculate returns
df = df.assign(close_day_before=df.Close.shift(1))
df['returns'] = ((df.Close - df.close_day_before)/df.close_day_before)
# get options data from yahoo finance // in this case, exercise data is july 24th
r = pd.read_html('http://finance.yahoo.com/quote/AAPL/options?date=1655424000&p=AAPL')[0]
</code></pre>
<p>It shows error:</p>
<pre><code>Traceback (most recent call last):
File "c:\Users\Chaitanya\Desktop\Finsearch\finserach.py", line 10, in <module>
r = pd.read_html('http://finance.yahoo.com/quote/AAPL/options?date=1655424000&p=AAPL')[0]
File "C:\Users\Chaitanya\AppData\Local\Programs\Python\Python39\lib\site-packages\pandas\util\_decorators.py", line 311, in wrapper
return func(*args, **kwargs)
File "C:\Users\Chaitanya\AppData\Local\Programs\Python\Python39\lib\site-packages\pandas\io\html.py", line 1098, in read_html
return _parse(
File "C:\Users\Chaitanya\AppData\Local\Programs\Python\Python39\lib\site-packages\pandas\io\html.py", line 906, in _parse
tables = p.parse_tables()
File "C:\Users\Chaitanya\AppData\Local\Programs\Python\Python39\lib\site-packages\pandas\io\html.py", line 222, in parse_tables
tables = self._parse_tables(self._build_doc(), self.match, self.attrs)
File "C:\Users\Chaitanya\AppData\Local\Programs\Python\Python39\lib\site-packages\pandas\io\html.py", line 745, in _build_doc
raise e
File "C:\Users\Chaitanya\AppData\Local\Programs\Python\Python39\lib\site-packages\pandas\io\html.py", line 726, in _build_doc
with urlopen(self.io) as f:
File "C:\Users\Chaitanya\AppData\Local\Programs\Python\Python39\lib\site-packages\pandas\io\common.py", line 211, in urlopen
return urllib.request.urlopen(*args, **kwargs)
File "C:\Users\Chaitanya\AppData\Local\Programs\Python\Python39\lib\urllib\request.py", line 214, in urlopen
return opener.open(url, data, timeout)
File "C:\Users\Chaitanya\AppData\Local\Programs\Python\Python39\lib\urllib\request.py", line 523, in open
response = meth(req, response)
File "C:\Users\Chaitanya\AppData\Local\Programs\Python\Python39\lib\urllib\request.py", line 632, in http_response
response = self.parent.error(
File "C:\Users\Chaitanya\AppData\Local\Programs\Python\Python39\lib\urllib\request.py", line 555, in error
result = self._call_chain(*args)
File "C:\Users\Chaitanya\AppData\Local\Programs\Python\Python39\lib\urllib\request.py", line 494, in _call_chain
result = func(*args)
File "C:\Users\Chaitanya\AppData\Local\Programs\Python\Python39\lib\urllib\request.py", line 747, in http_error_302
return self.parent.open(new, timeout=req.timeout)
File "C:\Users\Chaitanya\AppData\Local\Programs\Python\Python39\lib\urllib\request.py", line 523, in open
response = meth(req, response)
File "C:\Users\Chaitanya\AppData\Local\Programs\Python\Python39\lib\urllib\request.py", line 632, in http_response
response = self.parent.error(
File "C:\Users\Chaitanya\AppData\Local\Programs\Python\Python39\lib\urllib\request.py", line 561, in error
return self._call_chain(*args)
File "C:\Users\Chaitanya\AppData\Local\Programs\Python\Python39\lib\urllib\request.py", line 494, in _call_chain
result = func(*args)
File "C:\Users\Chaitanya\AppData\Local\Programs\Python\Python39\lib\urllib\request.py", line 641, in http_error_default
raise HTTPError(req.full_url, code, msg, hdrs, fp)
urllib.error.HTTPError: HTTP Error 404: Not Found``
</code></pre>
|
<p>The stack trace you posted seems to indicate that the error is coming from code that you have not posted in your question:</p>
<pre><code>Traceback (most recent call last):
File "c:\Users\Chaitanya\Desktop\Finsearch\finserach.py",
line 10, in **r = pd.read_html('http://finance.yahoo.com/quote/AAPL/options?date=1655424000&p=AAPL')**[0] File
</code></pre>
<p>Specifically, the <strong>r = pd_read_html('...)</strong> portion.</p>
|
python|pandas|csv|url|https
| 0 |
1,908,687 | 68,805,028 |
How to silence specific words in an audio file using python?
|
<p>I want to mute specific words in audio files. I have a list of words that should be muted. I have tried converting the audio file to text using this code but how can I get the time frame of each word so I can mute them?</p>
<pre><code>import speech_recognition as sr
import moviepy.editor as mp
r = sr.Recognizer()
audio = sr.AudioFile("Welcome.wav")
print(audio)
with audio as source:
audio_file = r.record(source)
print(audio_file)
try:
# using google speech recognition
text = r.recognize_google(audio_file)
print('Converting audio transcripts into text ...')
print(text)
except:
print('Sorry.. run again...')
# exporting the result
with open('recognized.txt',mode ='w') as file:
file.write("Recognized Speech:")
file.write("\n")
file.write(text)
print("ready!")
</code></pre>
|
<p>This answer shows <a href="https://stackoverflow.com/a/65370463/1967571">how to get the timestamps of words</a>. The timestamps can then be used to silence sections containing the words to be muted.</p>
|
python|audio|speech-recognition|audio-processing|audio-analysis
| 1 |
1,908,688 | 5,226,893 |
Understanding A Chain of Imports in Python
|
<p>I know there are several similar questions, but I'm struggling to understand the error I'm getting and browsing the docs and similar questions hasn't helped yet. If anything, the similar questions make me feel like what I'm doing is right.</p>
<p>I have the following files:</p>
<p><em><strong>src/main.py</em></strong></p>
<pre><code>from pack import pack
if __name__ == '__main__':
pack.exec("Hello Universe!")
</code></pre>
<p><em><strong>src/pack/pack.py</em></strong></p>
<pre><code>import util
def exec(text):
util.write(text)
if __name__ == '__main__':
exec("Hello World!")
</code></pre>
<p><em><strong>src/pack/util.py</em></strong></p>
<pre><code>def write(text):
print(text)
</code></pre>
<p>*<strong>src/pack/_<em>init</em>_.py*</strong></p>
<pre><code>EMPTY FILE
</code></pre>
<hr>
<p>When I run <code>python pack.py</code> from the <code>src/pack</code> directory, it works (prints "Hello World!"). However when I run <code>python main.py</code> from the <code>src</code> directory I get the following exception:</p>
<pre><code>Traceback (most recent call last):
File ".../src/main.py", line 1, in <module>
from pack import pack
File ".../src/pack/pack.py", line 1, in <module>
import util
ImportError: No module named util
</code></pre>
<hr>
<p>If I change the import line in <code>pack.py</code> to <code>from . import util</code> as suggested, effectively the opposite occours. <code>main.py</code> runs successfully, however now <code>pack.py</code> fails, raising:</p>
<pre><code>Traceback (most recent call last):
File ".../src/pack/pack.py", line 1, in <module>
from . import util
ValueError: Attempted relative import in non-package
</code></pre>
<hr>
<p>I would have thought that imports are relative to the current location, and as such you ought to be able to construct a chain of imports like this. It seems very odd to me that module is supposed to import a sibling file differently depending on where the program starts.</p>
<p>Can someone explain why this error occurs in one way but not the other, and if there is some way to allow this file structure to run whether I want to run from <code>main.py</code> or <code>pack.py</code>?</p>
|
<p>You will have trouble making the import work in both cases. This is because in one case you are running pack.py as the main file and in another you run it as part of a package.</p>
<p>When you run it as a standalone script <code>python pack.py</code>, the "pack" directory gets added to the PYTHONPATH, meaning that you can import any module in it. Hence, <code>import util</code> will work.</p>
<p>When you run <code>python main.py</code> you add the src directory to your PYTHONPATH. This means that any module or package in <code>src</code>, for example the <code>pack</code> directory, now becomes importable. Hence <code>from pack import pack</code>. However, to access <code>util.py</code> you now need to do <code>from pack import util</code>. You can also do <code>from . import util</code> from within <code>pack.py</code>, as you noticed.</p>
<p>But you can't really do both at the same time. Either <code>src/</code> is the main directory or <code>src/pack</code> is.</p>
<p>The obvious, but wrong solution, is to let the main.py add the <code>src/pack</code> directory to the PYTHONPATH. That will work, but it's not a good idea. The correct way to do this is to make up your mind. Is <code>src/pack</code> a module that should be imported via <code>import pack</code> or is it just a folder with a bunch of Python scripts? Decide! :-)</p>
<p>I think in this case its' obvious that <code>src/pack</code> should be a module. So then treat it like a module, and make sure it's available like a module. Then you can <code>from pack import util</code> even when running <code>pack.py</code> as a main script.</p>
<p>How do you do that? Well, basically you either install the pack module in your site-packages, or you add the <code>src</code> directory to the PYTHONPATH. That last one is what you want during development. You can either do it manually with <code>export PYTHONPATH=<path></code> or you can let your testrunners do it for you. You don't have a testrunner? Well you should, but that's another question. :)</p>
<p>For installing it permanently once you don't do development anymore, take a look at <a href="http://packages.python.org/distribute/" rel="noreferrer">Distribute</a>. It includes a testrunner. ;)</p>
|
python|import|python-3.x
| 6 |
1,908,689 | 67,443,303 |
python3 bot.py django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet
|
<p>I have a telegram bot witch depends on a Django app, I'm trying to deploy it on Heroku but I get this error</p>
<blockquote>
<p>django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.</p>
</blockquote>
<p>when it runs python3 main/bot.py in Heroku</p>
<p>here is my Procfile:</p>
<pre><code>web: gunicorn telega.wsgi
worker: python main/bot.py
</code></pre>
<p>main/bot.py:</p>
<pre><code>import telebot
import traceback
from decimal import Decimal, ROUND_FLOOR
import requests
import json
from django.conf import settings
from preferences import preferences
from main.markups import *
from main.tools import *
config = preferences.Config
TOKEN = config.bot_token
from main.models import *
from telebot.types import LabeledPrice
# # #
if settings.DEBUG:
TOKEN = 'mybottoken'
# # #
bot = telebot.TeleBot(TOKEN)
admins = config.admin_list.split('\n')
admin_list = list(map(int, admins))
@bot.message_handler(commands=['start'])
def start(message):
user = get_user(message)
lang = preferences.Language
clear_user(user)
if user.user_id in admin_list:
bot.send_message(user.user_id,
text=clear_text(lang.start_greetings_message),
reply_markup=main_admin_markup(),
parse_mode='html')
else:
bot.send_message(user.user_id,
text=clear_text(lang.start_greetings_message),
reply_markup=main_menu_markup(),
parse_mode='html')
@bot.message_handler(func=lambda message: message.text == preferences.Language.porfolio_button)
def porfolio_button(message):
....
...
</code></pre>
<p>and my settings.py:</p>
<pre><code>"""
Django settings for telega project.
Generated by 'django-admin startproject' using Django 2.2.7.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.2/ref/settings/
"""
import django_heroku
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'sw)pfb7&!l98xdoxn9(hy4eacwm33tj1vknyhz#tmv3mr-@ueo'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ['localhost',
"https://olk-telegram-bot.herokuapp.com"
"olk-telegram-bot.herokuapp.com",
"www.olk-telegram-bot.herokuapp.com",
"olk-telegram-bot"
".herokuapp.com",
]
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.sites',
'preferences',
'main',
'ckeditor',
'dbbackup', # django-dbbackup
]
DBBACKUP_STORAGE = 'django.core.files.storage.FileSystemStorage'
DBBACKUP_STORAGE_OPTIONS = {'location': os.path.join(BASE_DIR, "backup")}
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'telega.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'telega.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'CONN_MAX_AGE': 3600,
'NAME': 'portfolio',
'USER': 'mysql',
'HOST': 'localhost',
'PORT': '3306',
'PASSWORD': 'mysql',
'OPTIONS': {
'charset': 'utf8mb4',
},
}
}
# Password validation
# https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/2.2/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.2/howto/static-files/
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
# STATICFILES_DIRS = [
# os.path.join(BASE_DIR, "static"),
# ]
CKEDITOR_CONFIGS = {
'default': {
'enterMode': 2,
'linkShowAdvancedTab': False,
'linkShowTargetTab': False,
'toolbar': 'Custom',
'toolbar_Custom': [
['Bold', 'Italic', 'Underline'],
['Link', 'Unlink'],
['RemoveFormat', 'Source']
],
}
}
# Activate Django-Heroku.
django_heroku.settings(locals())
del DATABASES['default']['OPTIONS']['sslmode']
SITE_ID = 2
</code></pre>
<p>I don't know if I'm doing right or no, it'll be appreciated if you guide me through :)</p>
|
<p>Turns out I should run <code>polling.py</code> not <code>main/bot.py</code> -__-</p>
|
python|django|heroku|telegram-bot
| 0 |
1,908,690 | 67,339,445 |
error "no_text" at Slack API chat.postMessage even though text attribute is there
|
<p>I tried out Slack's Bolt framework for Python. I was experimenting with the Calls API and wanted to post the call to the channel, along with some text. So I used chat.postMessage. However, I get an error ("no_text").</p>
<p>Below is my code (token starred out for security):</p>
<pre><code>client.chat_postMessage(
token="**************",
channel="general",
blocks=[
{
"type": "call",
"call_id": slackCallId,
}
],
text="Test of Calls Api"
)
</code></pre>
<p>However, in the Slack channel I see this and then call:</p>
<p><a href="https://i.stack.imgur.com/cUSTz.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/cUSTz.png" alt="enter image description here" /></a></p>
<p><a href="https://i.stack.imgur.com/Autaf.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Autaf.png" alt="enter image description here" /></a></p>
<p>I'm not sure why this is happening.</p>
|
<p>How about this?</p>
<pre><code> [
{
"type": "slackCallId",
"call_id": "test"
},
{
"type": "section",
"text": {
"type": "plain_text",
"text": "Test of Calls Api"
}
}
]
</code></pre>
|
python|python-3.x|slack|slack-api
| 0 |
1,908,691 | 60,374,967 |
Tensorflow serving custom gpu op cannot find dependency when compiling
|
<p>I fallowed the guides on making custom gpu op for tensorflow and could make shared lib. For tensorflow-serving I adapted required paths but I get error when building:</p>
<pre><code> ERROR: /home/g360/Documents/eduardss/serving/tensorflow_serving/custom_ops/CUSTOM_OP/BUILD:32:1: undeclared inclusion(s) in rule '//tensorflow_serving/custom_ops/CUSTOM_OP:CUSTOM_OP_ops_gpu':
this rule is missing dependency declarations for the following files included by 'tensorflow_serving/custom_ops/CUSTOM_OP/cc/magic_op.cu.cc':
'external/org_tensorflow/tensorflow/core/platform/stream_executor.h'
'external/org_tensorflow/tensorflow/stream_executor/cuda/cuda_platform_id.h'
'external/org_tensorflow/tensorflow/stream_executor/platform.h'
'external/org_tensorflow/tensorflow/stream_executor/device_description.h'
'external/org_tensorflow/tensorflow/stream_executor/launch_dim.h'
'external/org_tensorflow/tensorflow/stream_executor/platform/port.h'
'external/org_tensorflow/tensorflow/stream_executor/device_options.h'
'external/org_tensorflow/tensorflow/stream_executor/platform/logging.h'
'external/org_tensorflow/tensorflow/stream_executor/lib/status.h'
'external/org_tensorflow/tensorflow/stream_executor/lib/error.h'
'external/org_tensorflow/tensorflow/stream_executor/lib/status_macros.h'
'external/org_tensorflow/tensorflow/stream_executor/lib/statusor.h'
'external/org_tensorflow/tensorflow/stream_executor/lib/statusor_internals.h'
'external/org_tensorflow/tensorflow/stream_executor/plugin.h'
'external/org_tensorflow/tensorflow/stream_executor/trace_listener.h'
'external/org_tensorflow/tensorflow/stream_executor/device_memory.h'
'external/org_tensorflow/tensorflow/stream_executor/kernel.h'
'external/org_tensorflow/tensorflow/stream_executor/kernel_cache_config.h'
'external/org_tensorflow/tensorflow/stream_executor/lib/array_slice.h'
'external/org_tensorflow/tensorflow/stream_executor/dnn.h'
'external/org_tensorflow/tensorflow/stream_executor/event.h'
'external/org_tensorflow/tensorflow/stream_executor/host/host_platform_id.h'
'external/org_tensorflow/tensorflow/stream_executor/multi_platform_manager.h'
'external/org_tensorflow/tensorflow/stream_executor/lib/initialize.h'
'external/org_tensorflow/tensorflow/stream_executor/platform/initialize.h'
'external/org_tensorflow/tensorflow/stream_executor/platform/platform.h'
'external/org_tensorflow/tensorflow/stream_executor/platform/default/initialize.h'
'external/org_tensorflow/tensorflow/stream_executor/platform/dso_loader.h'
'external/org_tensorflow/tensorflow/stream_executor/platform/default/dso_loader.h'
'external/org_tensorflow/tensorflow/stream_executor/rocm/rocm_platform_id.h'
'external/org_tensorflow/tensorflow/stream_executor/scratch_allocator.h'
'external/org_tensorflow/tensorflow/stream_executor/temporary_device_memory.h'
'external/org_tensorflow/tensorflow/stream_executor/stream.h'
'external/org_tensorflow/tensorflow/stream_executor/blas.h'
'external/org_tensorflow/tensorflow/stream_executor/host_or_device_scalar.h'
'external/org_tensorflow/tensorflow/stream_executor/fft.h'
'external/org_tensorflow/tensorflow/stream_executor/platform/thread_annotations.h'
'external/org_tensorflow/tensorflow/stream_executor/temporary_memory_manager.h'
'external/org_tensorflow/tensorflow/stream_executor/stream_executor.h'
'external/org_tensorflow/tensorflow/stream_executor/kernel_spec.h'
'external/org_tensorflow/tensorflow/stream_executor/stream_executor_pimpl.h'
'external/org_tensorflow/tensorflow/stream_executor/device_memory_allocator.h'
'external/org_tensorflow/tensorflow/stream_executor/lib/threadpool.h'
'external/org_tensorflow/tensorflow/stream_executor/lib/env.h'
'external/org_tensorflow/tensorflow/stream_executor/lib/thread_options.h'
'external/org_tensorflow/tensorflow/stream_executor/rng.h'
'external/org_tensorflow/tensorflow/stream_executor/shared_memory_config.h'
'external/org_tensorflow/tensorflow/stream_executor/stream_executor_internal.h'
'external/org_tensorflow/tensorflow/stream_executor/allocator_stats.h'
'external/org_tensorflow/tensorflow/stream_executor/module_spec.h'
'external/org_tensorflow/tensorflow/stream_executor/plugin_registry.h'
'external/org_tensorflow/tensorflow/stream_executor/timer.h'
</code></pre>
<p>The function in question imports:</p>
<pre><code>#if GOOGLE_CUDA
#define EIGEN_USE_GPU
#include "third_party/eigen3/unsupported/Eigen/CXX11/Tensor"
#include "tensorflow/core/util/gpu_kernel_helper.h"
#include "math.h"
#include <iostream>
</code></pre>
<p>Of these dependencies I think <code>gpu_kernel_helper.h</code> is the one causing error as my <code>BUILD</code> file dependencies are:</p>
<pre><code> deps = [
"@org_tensorflow//tensorflow/core:framework",
"@org_tensorflow//tensorflow/core:lib",
"@org_tensorflow//third_party/eigen3",
] + if_cuda_is_configured([":cuda", "@local_config_cuda//cuda:cuda_headers"]),
</code></pre>
<p>If I try to import them directly it bazels complains that there is no <code>BUILD</code> file on path. I'm not really familiar with bazel build process so don't understand exactly how it needs to link imports.</p>
<p><strong>EDIT 1</strong>
I used tensorflow-serving 2.1.0 and tensorflow/serving:2.1.0-devel-gpu docker image.
Looking in @org_tensorflow/tensorflow/core/BUILD there is actually some reference to 'gpu_kernel_helper.h':</p>
<pre><code>tf_cuda_library(
name = "framework",
hdrs = [
...
"util/gpu_kernel_helper.h",
]
</code></pre>
<p>But apparently some futher downstream links are missing?</p>
|
<p><strong>Solution:</strong> The missing dependency can be linked in with:</p>
<pre><code>"@org_tensorflow//tensorflow/core:stream_executor_headers_lib"
</code></pre>
|
tensorflow|bazel|tensorflow-serving
| 0 |
1,908,692 | 71,146,568 |
get the average of some ranges of dates in pandas
|
<p>I need to group the data by customer_id and get the average of purchase dates intervals. My data looks like this:</p>
<pre><code>date customer_id
1/1/2020 1
1/2/2020 2
1/3/2020 3
1/4/2020 1
1/5/2020 2
1/1/2021 1
1/2/2021 2
1/3/2021 3
</code></pre>
<p>So I need to see what is the average date ranges for each customer. The desired output is:</p>
<pre><code>customer_id Average_date_ranges(in months)
1 7
2 5
3 12
</code></pre>
|
<p>I think you can simply use transforming the <em>date</em> column type into a <code>datetime</code> object then call <code>groupby</code> to get the average date. You can use code below:</p>
<pre class="lang-py prettyprint-override"><code>df["date"] = pd.to_datetime(df["date"])
df.groupby("customer_id").mean()
</code></pre>
|
python|average|date-range|pandas
| 0 |
1,908,693 | 70,297,426 |
Iterate over columns and rows in a pandas dataframe and convert string to float
|
<p>I have the following dataframe:</p>
<pre><code>col1 col2 col3
25,4 34,2 33,2
33,25 30.2 10,2
.................
</code></pre>
<p>and I want to iterate all over the columns and rows from this dataset.</p>
<pre><code>df_range = len(df)
for column in df:
for i in range(df_range):
str.replace(',', '.').astype(float)
print(df)
</code></pre>
<p>and I get the following error:</p>
<pre><code>TypeError Traceback (most recent call last)
<ipython-input-38-47f6c96d2e67> in <module>()
3 for column in df2:
4 for i in range(df_range):
----> 5 str.replace(',', '.').astype(float)
6
7 print(df)
TypeError: replace() takes at least 2 arguments (1 given)
</code></pre>
|
<p>Why would <code>str.replace(',', '.').astype(float)</code> give you anything useful? There's nothing in that expression that involves the thing you're iterating over. Even if it were to evaluate to something without an error, it would evaluate to the same thing in each iteration of the loop.</p>
<p>If you do <code>df.loc[i,column].replace(',','.')</code>, then <code>replace</code> is a method from the string object <code>df.loc[i,column]</code>, and takes two arguments <code>old</code> and <code>new</code>. However, when you do <code>str.replace(',','.')</code>, <code>replace</code> is a method from the <code>str</code> <em>type</em>, not from a string <em>instance</em>, and so requires the arguments <code>self</code> <code>old</code> and <code>new</code>. The first argument <code>','</code> gets interpreted as <code>self</code>, and that leaves <code>'.'</code> as <code>old</code> and nothing for <code>new</code>. When you use <code>replace</code>, you have to either give it the original string as an argument, or take the <code>replace</code> method from the original string.</p>
<p>Also, you shouldn't be iterating through <code>df</code> with indices. Us <code>applymap</code> instead.</p>
|
python|pandas|iteration|rows
| 0 |
1,908,694 | 70,104,059 |
Making a simple menu within a loop to call upon functions, stuck on why it won't work
|
<p>For a school project me and my group partner made a code, I tested each function in a separate test file to see if they worked and it all looks good, but the menu just isn't working as intended. My brain can't seem to figure out where I went wrong, I would love a second opinion on this.. thank you so much <3 Here is my code!</p>
<pre><code>def mainmenu():
print("Hello! Welcome to The Sprint Project Company! Please choose from 1-5: ")
print("1. Simple IPO Program")
print("2. IFs and Loop sample")
print("3. Strings and dates")
print("4. Data files and Default Values")
print("5. Quit")
while True:
choice = input("Enter choice (1-5): ")
if choice == 1:
ipo()
elif choice == 2:
ifloop()
elif choice == 3:
stringsdates()
elif choice == 4:
datafiles()
else:
break
mainmenu()
</code></pre>
<p>Whenever I run this it just automatically ends. I even tested by putting a print section under the else but it just skips straight to ending the code. Thank you so much for looking at my question <3</p>
|
<p>There are two points on your code.
First, the function "input()" returns a string, hence you are comparing a STRING with an INTEGER, then it evalueates to False.
It is like you are comparing 1 with '1', and they are not the same.</p>
<p>Second, your function mainmenu() must be put inside the loop.
Make this two changes and it will work.</p>
<pre><code>while True:
mainmenu() # Add the function here.
choice = int(input("Enter choice (1-5): ")) # Change here
if choice == 1:
</code></pre>
|
python|if-statement|while-loop|menu|user-defined-functions
| 1 |
1,908,695 | 11,282,134 |
Access form's instance in django
|
<p>I have a form which has is an instance of some model X.Now how can I access the form's instance in a view provided that I'm handling form submission(POST) in another view.One view is used to create the form and other view is used to process the form.</p>
|
<p>From the <a href="https://docs.djangoproject.com/en/dev/topics/forms/modelforms/#overriding-the-clean-method" rel="nofollow">documentation</a></p>
<blockquote>
<p>Also, a model form instance bound to a model object will contain a
self.instance attribute that gives model form methods access to that
specific model instance.</p>
</blockquote>
<pre><code>def myview(request):
if request.method == "POST":
form = MyModelForm(request.POST,request.FILES)
# form.instance -- this is the model
</code></pre>
|
python|django
| 1 |
1,908,696 | 11,214,620 |
Do I need to install Homebrew if I am planning to install Virtualenv?
|
<p>Being fairly new to programming, I am having trouble understanding exactly what Homebrew does... or rather - why it is needed. I know it contains pip for package management, but so does Virtualenv and I'm planning on installing this in due course. </p>
<p>Does Homebrew install another version of python that is not the system version, upon which you would install Virtualenv and manage the different development environments from there?</p>
<p>I have a clean install of OSX Lion and I want to keep my projects separated, but am unsure why I need Homebrew.</p>
<p>I realise this is basic stuff, but if someone could explain it, I would be grateful.</p>
|
<p>Homebrew is just a package manager for Mac, like <em>pip</em> for Python. Of course you never <em>need</em> a package manager, you can just get all the programs, or libraries in case of pip and Pypi yourself. The point of package managers however is to ease this process and give you a simple interface to install the software, and also to <em>remove</em> it as that is usually not so simply when compiling things yourself etc.</p>
<p>That being said, Homebrew will only install things you tell it to install, so by just having Homebrew you don’t randomly get new versions of something. Homebrew is just a nice way to install general OSX stuff you need/want in general.</p>
|
python|macos|osx-lion|virtualenv|homebrew
| 2 |
1,908,697 | 70,653,674 |
How to do multiple inheritance from different classes in python using super()?
|
<p>Lets say we have different kind of people, pianist,programmer and multitalented person.
so, How do i inherit like this? currently this code gives error Multitalented has no attribute canplaypiano.</p>
<pre><code>class Pianist:
def __init__(self):
self.canplaypiano=True
class Programer:
def __init__(self):
self.canprogram=True
class Multitalented(Pianist,Programer):
def __init__(self):
self.canswim=True
super(Pianist,self).__init__()
super(Programer,self).__init__()
Raju=Multitalented()
print(Raju.canswim)
print(Raju.canprogram)
print(Raju.canplaypiano)
</code></pre>
<p>Also Please mention some well written article about python inheritance/super() i couldnt find a perfect article with clear explaination. thankyou.</p>
|
<p><em>All</em> classes involved in cooperative multiple inheritance need to use <code>super</code>, even if the <em>static</em> base class is just <code>object</code>.</p>
<pre><code>class Pianist:
def __init__(self):
super().__init__()
self.canplaypiano=True
class Programer:
def __init__(self):
super().__init__()
self.canprogram=True
class Multitalented(Pianist,Programer):
def __init__(self):
super().__init__()
self.canswim=True
Raju=Multitalented()
print(Raju.canswim)
print(Raju.canprogram)
print(Raju.canplaypiano)
</code></pre>
<p>The order in which the initializers run is determined by the method resolution order for <code>Multitalented</code>, which you can affect by changing the order in which <code>Multitalented</code> lists its base classes.</p>
<p>The first, if not best, article to read is Raymond Hettinger's <a href="https://rhettinger.wordpress.com/2011/05/26/super-considered-super/" rel="nofollow noreferrer">Python's <code>super()</code> Considered Super!</a>, which also includes advice on how to adapt classes the <em>don't</em> themselves use <code>super</code> for use in a cooperative multiple-inheritance hierarchy, as well as advice on how to override a function that uses <code>super</code> (in short, you can't change the signature).</p>
|
python|inheritance|multiple-inheritance
| 2 |
1,908,698 | 70,438,811 |
Reading frames from two video sources is not in sync | OpenCV
|
<p>I am working on a python OpenCV script that will read from two video streams and put one onto the other one (Picture-In-Picture) and both are supposed to be in sync on the final video. My goal is to put one video on the bottom-left corner of the other one. It's somewhat working but the problem is that, even though I initialized both video sources and read frames from them at the same time, the videos are not in sync when I show the processed frames. I created a dedicated thread that reads frames from both videos at the same time and appends both (as a tuple) to a list of frame pairs (buffer). Then the main thread gets the frame pair from the buffer, processes the final frame, and shows it using <code>imshow</code>. But one video is several seconds ahead of the other one. I tried reading frames in the main thread but the same problem.
The program also reads some information from subtitle file and adds text to the final frame. But that is working fine. So just ignore the <code>getTelemetry()</code> function.
I would really appreciate some help. Thanks</p>
<pre><code>import cv2
import time
import _thread
telemetry = []
tel = []
def getTelemetry():
global telemetry, tel
file = open("subs.srt", "r")
lines = file.readlines()
chars = '-.0123456789'
distance, altitude, horizontal_speed, vertical_speed = None, None, None, None
for line in lines:
if line.startswith("F"):
# print(line.strip('\n'))
distance = line[line.index('D ')+2:line.index(', H') - 1]
altitude = line[line.index('H ')+2:line.index(', H.S') - 1]
horizontal_speed = line[line.index(
'H.S ')+4:line.index(', V.S') - 3]
vertical_speed = line[line.index('V.S ')+4:-5]
for char in distance:
if char not in chars:
distance = '0'
for char in altitude:
if char not in chars:
altitude = '0'
for char in horizontal_speed:
if char not in chars:
horizontal_speed = '0'
for char in vertical_speed:
if char not in chars:
vertical_speed = '0'
distance_float = float(distance)
altitude_float = float(altitude)
horizontal_speed_float = float(horizontal_speed)
vertical_speed_float = float(vertical_speed)
telemetry.append([distance_float, altitude_float,
horizontal_speed_float, vertical_speed_float])
# print(distance_float, altitude_float, horizontal_speed_float,
# vertical_speed_float)
# Put each element of telemetry 60 times in tel
for i in range(0, len(telemetry)):
for j in range(0, 60):
tel.append(telemetry[i])
# print(len(tel))
frame_buffer = []
def fil_buffer():
global frame_buffer
video = cv2.VideoCapture("Input_File.avi")
video2 = cv2.VideoCapture("Screenrecorder-2021-12-07-16-15-26-217.mp4")
# For each frame in the video
while(video.isOpened() and video2.isOpened()):
ret, frame = video.read()
ret2, frame2 = video2.read()
if ret == True and ret2 == True:
frame_buffer.append((frame, frame2))
video.release()
video2.release()
if __name__ == '__main__':
getTelemetry()
_thread.start_new_thread(fil_buffer, ())
time.sleep(5)
print(len(frame_buffer))
j = 0
while len(frame_buffer) != 0:
x = frame_buffer.pop(0)
frame1 = x[0]
frame2 = x[1]
# print(tel[j][0])
cv2.putText(frame1, "Distance: " + str(tel[j][0]), (10, 30),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 2)
cv2.putText(frame1, "Altitude: " + str(tel[j][1]), (10, 60),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 2)
cv2.putText(frame1, "Horizontal Speed: " + str(tel[j][2]), (10, 90),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 2)
cv2.putText(frame1, "Vertical Speed: " + str(tel[j][3]), (10, 120),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 2)
# Resize frame2 to 25%
frame2 = cv2.resize(frame2, (0, 0), fx=0.25, fy=0.25)
# Put frame2 over frame1
frame1[500:frame2.shape[0]+500, 0:frame2.shape[1]] = frame2
cv2.imshow('frame', frame1)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
</code></pre>
|
<p>As mentioned in the comments by Mark, the cameras need not be in be sync, to begin with. They can have different FPS even after having identical hardware. Also, in your fil_buffer() function, the reading of frames from both cameras is sequential, i.e. you read camera A first and then camera B. This will definitely increase some level of lag for camera A. I would like to approach the problem this way.</p>
<ol>
<li>Run the frame reading task for each camera in a separate thread of their own.</li>
<li>In the same thread, you can push the read camera frame in their own STACK(not queue/list).</li>
<li>In your main function, you should read that stack, and clear it instantly. This makes sure you are always reading the latest available frame in the stack.</li>
</ol>
<p>I am assuming that the processing time in your main function will be greater than the time taken to read the frame. This should hold true for your application.</p>
<p>(A few months back, I wrote <a href="https://marsar24.medium.com/handling-cameras-for-computer-vision-applications-330fe55b584f" rel="nofollow noreferrer">this article</a> about getting a higher FPS with cameras. Its implementation is in C++ but it has a structure to run multiple cameras in separate threads of their own. I have been using the same structure to read multiple FLIR cameras to read them at FPS of 50-55 and in sync with each other.)</p>
|
python|opencv|video-processing
| 2 |
1,908,699 | 69,786,048 |
How to use class attributes in method decorators in Python?
|
<p>I have a decorator responsible for logging. E.g. something like this:</p>
<pre><code>import logging
import functools
from typing import Callable
def log_container(func: Callable, logger=None):
if logger is None:
logger = logging.getLogger("default")
@functools.wraps(func)
def wrapper(*args, **kwargs):
logger.info(f"{func.__qualname__} started.")
result = func(*args, **kwargs)
logger.info(f"{func.__qualname__} ended.")
return result
return wrapper
</code></pre>
<p>I have a class that has a distinct logger as an attribute, and I want to give that logger as a decorator argument. Is this possible? and if so, how?</p>
<pre><code>class Dummy:
logger = logging.getLogger("Dummy")
@log_container(logger=Dummy.logger)
def do_something(self):
pass
</code></pre>
|
<p>Your decorator, as its currently defined, wouldn't work. You can't pass in the decorated function together with an argument since the decorator itself only accepts one argument: the <code>func</code> itself. If you want your decorator to accept an argument, you'll need to nest the decorator one level deeper. Which now becomes a function that returns a decorator:</p>
<pre><code>def log_container(logger=None):
if logger is None:
logger = logging.getLogger("default")
def inner(func: Callable):
@functools.wraps(func)
def wrapper(*args, **kwargs):
logger.info(f"{func.__qualname__} started.")
result = func(*args, **kwargs)
logger.info(f"{func.__qualname__} ended.")
return result
return wrapper
return inner
</code></pre>
<p>Then when decorating the method for the <code>Dummy</code> class, don't use <code>Dummy.logger</code> since <code>Dummy</code> won't be defined until the end of the class definition, instead, you can access the class attribute <code>logger</code> directly.</p>
<pre><code>class Dummy:
logger = logging.getLogger("Dummy")
@log_container(logger=logger)
def do_something(self):
pass
# Use default logger
@log_container()
def do_something_else(self):
pass
</code></pre>
|
python|logging|python-decorators|python-class
| 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.