question_id
int64
59.5M
79.4M
creation_date
stringlengths
8
10
link
stringlengths
60
163
question
stringlengths
53
28.9k
accepted_answer
stringlengths
26
29.3k
question_vote
int64
1
410
answer_vote
int64
-9
482
64,799,422
2020-11-12
https://stackoverflow.com/questions/64799422/python-with-sparql-client-importerror-cannot-import-name-encodestring-from
I am Python newbie. Trying to use this module https://pypi.org/project/sparql-client/ module.py from sparql import Service class MyModule: def my_method(self): s = Service('https://my-endpoint:8182/sparql', "utf-8", "GET") statement = """ MOVE uri:temp_graph TO uri:user_graph ADD uri:temp_graph TO uri:user_graph """.format(user_graph="http://aws.amazon.com/account-uid", temp_graph="http://aws.amazon.com/account-uid-temp") s.query(statement) I am trying to test it test_module.py import unittest from unittest.mock import patch, Mock class TestModule(unittest.TestCase): @patch('sparql.Service', autospec=True) def test_mymethod(self, sparql_mock): sparql_instance = sparql_mock.return_value sparql_instance.query = Mock() While running I get File "/usr/local/Cellar/[email protected]/3.9.0_1/Frameworks/Python.framework/Versions/3.9/lib/python3.9/unittest/mock.py", line 1564, in <lambda> getter = lambda: _importer(target) File "/usr/local/Cellar/[email protected]/3.9.0_1/Frameworks/Python.framework/Versions/3.9/lib/python3.9/unittest/mock.py", line 1236, in _importer thing = __import__(import_path) File "/usr/local/lib/python3.9/site-packages/sparql.py", line 50, in <module> from base64 import encodestring ImportError: cannot import name 'encodestring' from 'base64' (/usr/local/Cellar/[email protected]/3.9.0_1/Frameworks/Python.framework/Versions/3.9/lib/python3.9/base64.py) So it can not import this line https://github.com/eea/sparql-client/blob/master/sparql.py#L50 Any idea how to fix this?
The problem is caused by the version of base64 module you are running while the version of sparql you have installed is dependent on a lower version of the base64 module. The sparql is dependent on base64 version built for python3.1. encodestring() and decodestring() have since been deprecated. Option 1 - Your best bet (if you must continue using this version of sparql) is to downgrade your version of python to 3.1 from 3.9 which is your current version. Option 2 - will be to adopt the new specifications for the current version of base64 you have installed. this will mean updating sparql and anywhere you are calling deprecated methods of base64. If you choose to go with option 2, then open the sparql module and edit the import statement. Change from base64 import encodestring to from base64 import encodebytes and replace any occurrences of encodestring with encodebytes in your code and any module you have dependent on base64. That should solve your problem.
7
13
64,846,222
2020-11-15
https://stackoverflow.com/questions/64846222/store-networkx-graph-object
I have a huge graph with about 5000 nodes that I made it with networkX. It takes about 30 seconds to create this graph each time I execute my script. After this relatively long time I can run my analysis like shortest_path and so on. My question is, is there any way to store the object of this graph in file or something like this and each time I run my script, networkX read that file and load all of my graph?
As of version 2.6, methods write_gpickle and read_gpickle are deprecated. Try this instead: import pickle # save graph object to file pickle.dump(G, open('filename.pickle', 'wb')) # load graph object from file G = pickle.load(open('filename.pickle', 'rb')) Note the options 'wb' to dump and 'rb' to load in open().
13
18
64,780,251
2020-11-11
https://stackoverflow.com/questions/64780251/how-to-annotate-a-seaborn-barplot-with-the-aggregated-value
How can the following code be modified to show the mean as well as the different error bars on each bar of the bar plot? import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns sns.set_style("white") a,b,c,d = [],[],[],[] for i in range(1,5): np.random.seed(i) a.append(np.random.uniform(35,55)) b.append(np.random.uniform(40,70)) c.append(np.random.uniform(63,85)) d.append(np.random.uniform(59,80)) data_df =pd.DataFrame({'stages':[1,2,3,4],'S1':a,'S2':b,'S3':c,'S4':d}) print("Delay:") display(data_df) S1 S2 S3 S4 0 43.340440 61.609735 63.002516 65.348984 1 43.719898 40.777787 75.092575 68.141770 2 46.015958 61.244435 69.399904 69.727380 3 54.340597 56.416967 84.399056 74.011136 meansd_df=data_df.describe().loc[['mean', 'std'],:].drop('stages', axis = 1) display(meansd_df) sns.set() sns.set_style('darkgrid',{"axes.facecolor": ".92"}) # (1) sns.set_context('notebook') fig, ax = plt.subplots(figsize = (8,6)) x = meansd_df.columns y = meansd_df.loc['mean',:] yerr = meansd_df.loc['std',:] plt.xlabel("Time", size=14) plt.ylim(-0.3, 100) width = 0.45 for i, j,k in zip(x,y,yerr): # (2) ax.bar(i,j, width, yerr = k, edgecolor = "black", error_kw=dict(lw=1, capsize=8, capthick=1)) # (3) ax.set(ylabel = 'Delay') from matplotlib import ticker ax.yaxis.set_major_locator(ticker.MultipleLocator(10)) plt.savefig("Over.png", dpi=300, bbox_inches='tight')
Given the example data, for a seaborn.barplot with capped error bars, data_df must be converted from a wide format, to a tidy (long) format, which can be accomplished with pandas.DataFrame.stack or pandas.DataFrame.melt It is also important to keep in mind that a bar plot shows only the mean (or other estimator) value Sample Data and DataFrame .iloc[:, 1:] is used to skip the 'stages' column at column index 0. import pandas as pd import numpy as np import seaborn as sns import matplotlib.pyplot as plt # given data_df from the OP, select the columns except stage and reshape to long format df = data_df.iloc[:, 1:].melt(var_name='set', value_name='val') # display(df.head()) set val 0 S1 43.340440 1 S1 43.719898 2 S1 46.015958 3 S1 54.340597 4 S2 61.609735 Updated as of matplotlib v3.4.2 Use matplotlib.pyplot.bar_label See How to add value labels on a bar chart for additional details and examples with .bar_label. Some formatting can be done with the fmt parameter, but more sophisticated formatting should be done with the labels parameter, as show in How to add multiple annotations to a barplot. Tested with seaborn v0.11.1, which is using matplotlib as the plot engine. fig, ax = plt.subplots(figsize=(8, 6)) # add the plot sns.barplot(x='set', y='val', data=df, capsize=0.2, ax=ax) # add the annotation ax.bar_label(ax.containers[-1], fmt='Mean:\n%.2f', label_type='center') ax.set(ylabel='Mean Time') plt.show() plot with seaborn.barplot Using matplotlib before version 3.4.2 The default for the estimator parameter is mean, so the height of the bar is the mean of the group. The bar height is extracted from p with .get_height, which can be used to annotate the bar. fig, ax = plt.subplots(figsize=(8, 6)) sns.barplot(x='set', y='val', data=df, capsize=0.2, ax=ax) # show the mean for p in ax.patches: h, w, x = p.get_height(), p.get_width(), p.get_x() xy = (x + w / 2., h / 2) text = f'Mean:\n{h:0.2f}' ax.annotate(text=text, xy=xy, ha='center', va='center') ax.set(xlabel='Delay', ylabel='Time') plt.show()
7
16
64,837,376
2020-11-14
https://stackoverflow.com/questions/64837376/how-to-efficiently-run-multiple-pytorch-processes-models-at-once-traceback
Background I have a very small network which I want to test with different random seeds. The network barely uses 1% of my GPUs compute power so i could in theory run 50 processes at once to try many different seeds at once. Problem Unfortunately i can't even import pytorch in multiple processes. When the nr of processes exceeds 4 I get a Traceback regarding a too small paging file. Minimal reproducable codeΒ§ - dispatcher.py from subprocess import Popen import sys procs = [] for seed in range(50): procs.append(Popen([sys.executable, "ml_model.py", str(seed)])) for proc in procs: proc.wait() Β§I increased the number of seeds so people with better machines can also reproduce this. Minimal reproducable code - ml_model.py import torch import time time.sleep(10) Traceback (most recent call last): File "ml_model.py", line 1, in <module> import torch File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\site-packages\torch\__init__.py", line 117, in <module> import torch File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\site-packages\torch\__init__.py", line 117, in <module> raise err OSError: [WinError 1455] The paging file is too small for this operation to complete. Error loading "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\site-packages\torch\lib\cudnn_cnn_infer64_8.dll" or one of its dependencies. raise err Further Investigation I noticed that each process loads a lot of dll's into RAM. And when i close all other programs which use a lot of RAM i can get up to 10 procesess instead of 4. So it seems like a resource constraint. Questions Is there a workaround ? What's the recommended way to train many small networks with pytorch on a single gpu ? Should i write my own CUDA Kernel instead, or use a different framework to achieve this ? My goal would be to run around 50 processes at once (on a 16GB RAM Machine, 8GB GPU RAM)
I've looked a bit into this tonight. I don't have a solution (edit: I have a mitigation, see the edit at end), but I have a bit more information. It seems the issue is caused by NVidia fatbins (.nv_fatb) being loaded into memory. Several DLLs, such as cusolver64_xx.dll, torcha_cuda_cu.dll, and a few others, have .nv_fatb sections in them. These contain tons of different variations of CUDA code for different GPUs, so it ends up being several hundred megabytes to a couple gigabytes. When Python imports 'torch' it loads these DLLs, and maps the .nv_fatb section into memory. For some reason, instead of just being a memory mapped file, it is actually taking up memory. The section is set as 'copy on write', so it's possible something writes into it? I don't know. But anyway, if you look at Python using VMMap ( https://learn.microsoft.com/en-us/sysinternals/downloads/vmmap ) you can see that these DLLs are committing huge amounts of committed memory for this .nv_fatb section. The frustrating part is it doesn't seem to be using the memory. For example, right now my Python.exe has 2.7GB committed, but the working set is only 148MB. Every Python process that loads these DLLs will commit several GB of memory loading these DLLs. So if 1 Python process is wasting 2GB of memory, and you try running 8 workers, you need 16GB of memory to spare just to load the DLLs. It really doesn't seem like this memory is used, just committed. I don't know enough about these fatbinaries to try to fix it, but from looking at this for the past 2 hours it really seems like they are the issue. Perhaps its an NVidia problem that these are committing memory? edit: I made this python script: https://gist.github.com/cobryan05/7d1fe28dd370e110a372c4d268dcb2e5 Get it and install its pefile dependency ( python -m pip install pefile ). Run it on your torch and cuda DLLs. In OPs case, command line might look like: python fixNvPe.py --input=C:\Users\user\AppData\Local\Programs\Python\Python38\lib\site-packages\torch\lib\*.dll (You also want to run this wherever your cusolver64_*.dll and friends are. This may be in your torch\lib folder, or it may be, eg, C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\vXX.X\bin . If it is under Program Files, you will need to run the script with administrative privileges) What this script is going to do is scan through all DLLs specified by the input glob, and if it finds an .nv_fatb section it will back up the DLL, disable ASLR, and mark the .nv_fatb section read-only. ASLR is 'address space layout randomization.' It is a security feature that randomizes where a DLL is loaded in memory. We disable it for this DLL so that all Python processes will load the DLL into the same base virtual address. If all Python processes using the DLL load it at the same base address, they can all share the DLL. Otherwise each process needs its own copy. Marking the section 'read-only' lets Windows know that the contents will not change in memory. If you map a file into memory read/write, Windows has to commit enough memory, backed by the pagefile, just in case you make a modification to it. If the section is read-only, there is no need to back it in the pagefile. We know there are no modifications to it, so it can always be found in the DLL. The theory behind the script is that by changing these 2 flags that less memory will be committed for the .nv_fatb, and more memory will be shared between the Python processes. In practice, it works. Not quite as well as I'd hope (it still commits a lot more than it uses), so my understanding may be flawed, but it significantly decreases memory commit. In my limited testing I haven't ran into any issues, but I can't guarantee there are no code paths that attempts to write to that section we marked 'read only.' If you start running into issues, though, you can just restore the backups. edit 2022-01-20: Per NVIDIA: "We have gone ahead and marked the nv_fatb section as read-only, this change will be targeting next major CUDA release 11.7 . We are not changing the ASLR, as that is considered a safety feature ." This should certainly help. If it's not enough without ASLR as well then the script should still work
26
30
64,781,191
2020-11-11
https://stackoverflow.com/questions/64781191/asyncio-gather-on-list-of-dict-which-has-a-field-of-coroutine
I have the following two async function from tornado.httpclient import AsyncHTTPClient async def get_categories(): # return a list of str # .... http = AsyncHTTPClient() resp = await http.fetch(....) return [....] async def get_details(category): # return a list of dict # .... http = AsyncHTTPClient() resp = await http.fetch(....) return [....] Now I need to create a function to get the details (run http fetch concurrently) for all the categories and combine them together. async def get_all_details(): categories = await get_categories() tasks = list(map(lambda x: {'category': x, 'task':get_details(x)}, categories)) r = await asyncio.gather(*tasks) # error # need to return [ # {'category':'aaa', 'detail':'aaa detail 1'}, # {'category':'aaa', 'detail':'aaa detail 2'}, # {'category':'bbb', 'detail':'bbb detail 1'}, # {'category':'bbb', 'detail':'bbb detail 2'}, # {'category':'bbb', 'detail':'bbb detail 3'}, # {'category':'ccc', 'detail':'ccc detail 1'}, # {'category':'ccc', 'detail':'aaa detail 2'}, # ] However, the list line return the error: TypeError: unhashable type: 'dict' The tasks has the following values: [{'category': 'aaa', 'task': <coroutine object get_docker_list at 0x000001B12B8560C0>}, {'category': 'bbb', 'task': <coroutine object get_docker_list at 0x000001B12B856F40>}, {'category': 'ccc', 'task': <coroutine object get_docker_list at 0x000001B12B856740>}] BTW, is it a way to throttle the http fetch calls? For example, at most four fetches running at the same time.
gather accepts coroutine (or other awaitable) arguments and returns a tuple of their results in the same order. You are passing it a sequence of dicts some of whose values are coroutines. gather doesn't know what to do with that and attempts to treat the dicts as awaitable objects, which fails soon enough. The correct way to generate the list of dicts would be to pass just the coroutines to gather, await the results, and process them into a new dict: async def get_all_details(): category_list = await get_categories() details_list = await asyncio.gather( *[get_details(category) for category in category_list] ) return [ {'category': category, 'details': details} for (category, details) in zip(category_list, details_list) ] BTW, is it a way to throttle the http fetch calls? For example, at most four fetches running at the same time. The convenient and idiomatic way to limit parallel calls is by using a semaphore: async def get_details(category, limit): # acquiring the semaphore passed as `limit` will allow at most a # fixed number of coroutines to proceed concurrently async with limit: ... the rest of the code ... async def get_all_details(): limit = asyncio.Semaphore(4) category_list = await get_categories() details_list = await asyncio.gather( *[get_details(category, limit) for category in category_list] ) ... the rest of the code ...
6
11
64,792,295
2020-11-11
https://stackoverflow.com/questions/64792295/how-to-get-self-instance-in-mock-mock-call-args
I observe an inconsistent behavior when patching a dummy class: class A: def f(self, *args, **kwargs): pass If I patch manually the function: call_args_list = [] def mock_fn(*args, **kwargs): call_args_list.append(mock.call(*args, **kwargs)) with mock.patch.object(A, 'f', mock_fn): A().f(1, 2) print(call_args_list) # [call(<__main__.A object at 0x7f0da0c08b50>, 1, 2)] As expected mock_fn is called with the self argument (mock_fn(self, 1, 2)). However, if I'm using a mock.Mock object, somehow the self argument is removed from the call: mock_obj = mock.Mock() with mock.patch.object(A, 'f', mock_obj): A().f(1, 2) print(mock_obj.call_args_list) # [call(1, 2)] This feel inconsistent. mock_obj is called as mock_obj(self, 1, 2), yet mock_obj.call_args == call(1, 2). It removes the self argument from call_args. How can I access the bounded-method instance ?
with mock.patch.object(A, 'f', autospec=True) as mock_obj: A().f(1, 2) print(mock_obj.call_args_list) # [call(<__main__.A object at 0x7fb2908fc880>, 1, 2)] From the documentation: If you pass autospec=True [...] the mocked function will be turned into a bound method if it is fetched from an instance. It will have self passed in as the first argument [...]
10
15
64,797,838
2020-11-12
https://stackoverflow.com/questions/64797838/libgcc-s-so-1-must-be-installed-for-pthread-cancel-to-work
I'm on python; I am trying to shut down a function running through a ThreadPoolExecutor, but the shutdown is crashing with the error: libgcc_s.so.1 must be installed for pthread_cancel to work The function is submitted with: record_future = self.executor.submit(next,primitive) primitive is an iterator that usually returns a value but in some cases, it needs to wait a while before returning a value (because of long calculations, etc). In these cases, when I need to shut down the running thread, I cannot wait for the iterator to finish returning, and need to shut it down immediately. I did it with: executor.shutdown(wait=False) However, when execution reaches this point, I get the libgcc error. I tried 'solving' it by manually installing with: apt-get install libgcc1:amd64 but no dice. I am not sure where exactly python is looking for this library, otherwise I would try creating a symbolic link, because the library is already installed at: $ /sbin/ldconfig -p | grep libgcc libgcc_s.so.1 (libc6,x32) => /usr/libx32/libgcc_s.so.1 libgcc_s.so.1 (libc6,x86-64) => /lib/x86_64-linux-gnu/libgcc_s.so.1 libgcc_s.so.1 (libc6) => /usr/lib32/libgcc_s.so.1
I found a potential workaround in the Python mailing list to explicitly load libgcc_.so.1 via ctypes as follows: import ctypes libgcc_s = ctypes.CDLL('libgcc_s.so.1') One has to make sure that this is loaded before any threads are created and that the variable libgcc_s lasts until all of the threads are closed (i.e. put this at the beginning of your file).
7
15
64,792,041
2020-11-11
https://stackoverflow.com/questions/64792041/white-gap-between-python-folium-map-and-jupyter-notebook-cell
How can I remove the undesired gap between the Python folium map and the next cell inside my jupyter notebook. Here the naive code to reproduce my problem : import folium m = folium.Map(width=600, height=400, location=[12, 12], zoom_start=2) m
Here the solution need to use Figure : from branca.element import Figure fig = Figure(width=600, height=400) m = folium.Map(location=[12, 12], zoom_start=2) fig.add_child(m)
12
16
64,795,881
2020-11-11
https://stackoverflow.com/questions/64795881/collapse-output-in-vs-code-jupyter-notebook-into-scrollable-window
Is there a way to show the output such as a very long data-frame in a scrollable window in VS Code Jupyter Notebook? I am aware that pressing letter "o" allows you to collapse all output. But having the scrollable window is still preferable as it allows you to check the output while referring to other windows. I also checked this link but couldn't get it work.
Per the comments, a workaround to trigger the scrollable window is to add a print statement to the cell output. For example print("foo") at the beginning or end of a cell.
13
7
64,856,195
2020-11-16
https://stackoverflow.com/questions/64856195/what-is-tape-based-autograd-in-pytorch
I understand autograd is used to imply automatic differentiation. But what exactly is tape-based autograd in Pytorch and why there are so many discussions that affirm or deny it. For example: this In pytorch, there is no traditional sense of tape and this We don’t really build gradient tapes per se. But graphs. but not this Autograd is now a core torch package for automatic differentiation. It uses a tape based system for automatic differentiation. And for further reference, please compare it with GradientTape in Tensorflow.
There are different types of automatic differentiation e.g. forward-mode, reverse-mode, hybrids; (more explanation). The tape-based autograd in Pytorch simply refers to the uses of reverse-mode automatic differentiation, source. The reverse-mode auto diff is simply a technique used to compute gradients efficiently and it happens to be used by backpropagation, source. Now, in PyTorch, Autograd is the core torch package for automatic differentiation. It uses a tape-based system for automatic differentiation. In the forward phase, the autograd tape will remember all the operations it executed, and in the backward phase, it will replay the operations. Same in TensorFlow, to differentiate automatically, It also needs to remember what operations happen in what order during the forward pass. Then, during the backward pass, TensorFlow traverses this list of operations in reverse order to compute gradients. Now, TensorFlow provides the tf.GradientTape API for automatic differentiation; that is, computing the gradient of computation with respect to some inputs, usually tf.Variables. TensorFlow records relevant operations executed inside the context of a tf.GradientTape onto a tape. TensorFlow then uses that tape to compute the gradients of a recorded computation using reverse mode differentiation. So, as we can see from the high-level viewpoint, both are doing the same operation. However, during the custom training loop, the forward pass and calculation of the loss are more explicit in TensorFlow as it uses tf.GradientTape API scope whereas in PyTorch it's implicit for these operations but it requires to set required_grad flags to False temporarily while updating the training parameters (weights and biases). For that, it uses torch.no_grad API explicitly. In other words, TensorFlow's tf.GradientTape() is similar to PyTorch's loss.backward(). Below is the simplistic form in the code of the above statements. # TensorFlow [w, b] = tf_model.trainable_variables for epoch in range(epochs): with tf.GradientTape() as tape: # forward passing and loss calculations # within explicit tape scope predictions = tf_model(x) loss = squared_error(predictions, y) # compute gradients (grad) w_grad, b_grad = tape.gradient(loss, tf_model.trainable_variables) # update training variables w.assign(w - w_grad * learning_rate) b.assign(b - b_grad * learning_rate) # PyTorch [w, b] = torch_model.parameters() for epoch in range(epochs): # forward pass and loss calculation # implicit tape-based AD y_pred = torch_model(inputs) loss = squared_error(y_pred, labels) # compute gradients (grad) loss.backward() # update training variables / parameters with torch.no_grad(): w -= w.grad * learning_rate b -= b.grad * learning_rate w.grad.zero_() b.grad.zero_() FYI, in the above, the trainable variables (w, b) are manually updated in both frameworks but we generally use an optimizer (e.g. adam) to do the job. # TensorFlow # .... # update training variables optimizer.apply_gradients(zip([w_grad, b_grad], model.trainable_weights)) # PyTorch # .... # update training variables / parameters optimizer.step() optimizer.zero_grad()
21
25
64,789,217
2020-11-11
https://stackoverflow.com/questions/64789217/how-can-i-do-a-seq2seq-task-with-pytorch-transformers-if-i-am-not-trying-to-be-a
I may be mistaken, but it seems that PyTorch Transformers are autoregressive, which is what masking is for. However, I've seen some implementations where people use just the Encoder and output that directly to a Linear layer. In my case, I'm trying to convert a spectrogram (rows are frequencies and columns are timesteps) to another spectrogram of the same dimensions. I'm having an impossible time trying to figure out how to do this. For my model, I have: class TransformerReconstruct(nn.Module): def __init__(self, feature_size=250, num_layers=1, dropout=0.1, nhead=10, output_dim=1): super(TransformerReconstruct, self).__init__() self.model_type = 'Transformer' self.src_mask = None self.pos_encoder = PositionalEncoding(feature_size) self.encoder_layer = nn.TransformerEncoderLayer(d_model=feature_size, nhead=nhead, dropout=dropout) self.transformer_encoder = nn.TransformerEncoder(self.encoder_layer, num_layers=num_layers) self.decoder = nn.Linear(feature_size, output_dim) self.init_weights() def init_weights(self): initrange = 0.1 self.decoder.bias.data.zero_() self.decoder.weight.data.uniform_(-initrange, initrange) def forward(self, src): if self.src_mask is None or self.src_mask.size(0) != len(src): device = src.device mask = self._generate_square_subsequent_mask(len(src)).to(device) self.src_mask = mask src = self.pos_encoder(src) output = self.transformer_encoder(src, self.src_mask) output = self.decoder(output) return output def _generate_square_subsequent_mask(self, sz): mask = (torch.triu(torch.ones(sz, sz)) == 1).transpose(0, 1) mask = mask.float().masked_fill(mask == 0, float('-inf')).masked_fill(mask == 1, float(0.0)) return mask And when training, I have: model = TransformerReconstruct(feature_size=128, nhead=8, output_dim=128, num_layers=6).to(device) This returns the right shape, but doesn't seem to learn. My basic training loop looks like: for i in range(0, len(data_source) - 1, input_window): data, target = get_batch(data_source, i, 1) output = recreate_model(data) and I'm using an MSELoss and I'm trying to learn a very simple identity. Where the input and output are the same, however this is not learning. What could I be doing wrong? Thanks in advance.
Most of the models in Huggingface Transformers are some version of BERT and thus not autoregressive, the only exceptions are decoder-only models (GPT and similar) and sequence-to-sequence model. There are two conceptually different types of masks: one is the input mask that is specific to the input batch and the purpose is allowing using sequences of different lengths in a single batch. When the sequences get padded to the same length, the self-attention should attend to the padding positions. This is what you are supposed to use when you call self.transformer_encoder in the forward method. In addition, the autoregressive Transformer decoder uses another type of mask. It is the triangular mask that prevents the self-attention to attend to tokens that are right of the current position (at inference time, words right of the current position are unknown before they are actually generated). This is what you have in the _generate_square_subsequent_mask method and this is what makes the model autoregressive. It is constant and does not depend on the input batch. To summarize: to have a bidirectional Transformer, just get rid of the triangular mask. If your input sequences are of different lengths, you should use batch-specific masking, if not, just pass a matrix with ones.
10
2
64,876,788
2020-11-17
https://stackoverflow.com/questions/64876788/how-to-use-the-pytorch-transformer-with-multi-dimensional-sequence-to-seqence
I'm trying to go seq2seq with a Transformer model. My input and output are the same shape (torch.Size([499, 128]) where 499 is the sequence length and 128 is the number of features. My input looks like: My output looks like: My training loop is: for batch in tqdm(dataset): optimizer.zero_grad() x, y = batch x = x.to(DEVICE) y = y.to(DEVICE) pred = model(x, torch.zeros(x.size()).to(DEVICE)) loss = loss_fn(pred, y) loss.backward() optimizer.step() My model is: import math from typing import final import torch import torch.nn as nn class Reconstructor(nn.Module): def __init__(self, input_dim, output_dim, dim_embedding, num_layers=4, nhead=8, dim_feedforward=2048, dropout=0.5): super(Reconstructor, self).__init__() self.model_type = 'Transformer' self.src_mask = None self.pos_encoder = PositionalEncoding(d_model=dim_embedding, dropout=dropout) self.transformer = nn.Transformer(d_model=dim_embedding, nhead=nhead, dim_feedforward=dim_feedforward, num_encoder_layers=num_layers, num_decoder_layers=num_layers) self.decoder = nn.Linear(dim_embedding, output_dim) self.decoder_act_fn = nn.PReLU() self.init_weights() def init_weights(self): initrange = 0.1 nn.init.zeros_(self.decoder.weight) nn.init.uniform_(self.decoder.weight, -initrange, initrange) def forward(self, src, tgt): pe_src = self.pos_encoder(src.permute(1, 0, 2)) # (seq, batch, features) transformer_output = self.transformer_encoder(pe_src) decoder_output = self.decoder(transformer_output.permute(1, 0, 2)).squeeze(2) decoder_output = self.decoder_act_fn(decoder_output) return decoder_output My output has a shape of torch.Size([32, 499, 128]) where 32 is batch, 499 is my sequence length and 128 is the number of features. But the output has the same values: tensor([[[0.0014, 0.0016, 0.0017, ..., 0.0018, 0.0021, 0.0017], [0.0014, 0.0016, 0.0017, ..., 0.0018, 0.0021, 0.0017], [0.0014, 0.0016, 0.0017, ..., 0.0018, 0.0021, 0.0017], ..., [0.0014, 0.0016, 0.0017, ..., 0.0018, 0.0021, 0.0017], [0.0014, 0.0016, 0.0017, ..., 0.0018, 0.0021, 0.0017], [0.0014, 0.0016, 0.0017, ..., 0.0018, 0.0021, 0.0017]]], grad_fn=<PreluBackward>) What am I doing wrong? Thank you so much for any help.
There are several points to be checked. As you have same output to the different inputs, I suspect that some layer zeros out all it's inputs. So check the outputs of the PositionalEncoding and also Encoder block of the Transformer, to make sure they are not constant. But before that, make sure your inputs differ (try to inject noise, for example). Additionally, from what I see in the pictures, your input and output are speech signals and was sampled at 22.05kHz (I guess), so it should have ~10k features, but you claim that you have only 128. This is another place to check. Now, the number 499 represent some time slice. Make sure your slices are in reasonable range (20-50 msec, usually 30). If it is the case, then 30ms by 500 is 15 seconds, which is much more you have in your example. And finally you are masking off a third of a second of speech in your input, which is too much I believe. I think it would be useful to examine Wav2vec and Wav2vec 2.0 papers, which tackle the problem of self supervised training in speech recognition domain using Transformer Encoder with great success.
9
4
64,791,380
2020-11-11
https://stackoverflow.com/questions/64791380/can-homebrew-run-on-apple-arm-processors
I ordered a MacBook Pro equipped with an M1 ARM processor. Will I be able to run Homebrew and install dev tools like Python, Node etc..?
Yes. Now Homebrew fully supports Apple Silicon https://brew.sh/2021/02/05/homebrew-3.0.0/
6
3
64,788,656
2020-11-11
https://stackoverflow.com/questions/64788656/exe-file-made-with-pyinstaller-being-reported-as-a-virus-threat-by-windows-defen
I'm trying to create an exe using pyinstaller for a school project but, windows defender seems to report a virus threat and blocks the file. I want to send this exe to some other people but i wouldn't be able to do that unless I fix this. So these are my queries- Why does the exe file get reported as a virus? A quick scan on virus total says that 16 engines detect this file as a Trojan. Also, is there any way to prevent windows defender or any other antivirus from alerting users of a virus threat , I mean, is there any way to make my file look safe to antiviruses in case it was just a false threat? And in case that is not possible, what are the other safe alternatives to pyinstaller? I'm just a beginner so any tips would be really appreciated. Thanks. EDIT: as requested by @Pro Chess, ive included my script. import socket import threading import pickle class Server : def __init__(self) : self.HEADER = 64 self.PORT = 5050 self.SERVER = socket.gethostbyname(socket.gethostname()) self.ADDR = (self.SERVER, self.PORT) self.FORMAT = 'utf-8' self.DISCONNECT_MESSAGE = "!DISCONNECT" self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.server.bind(self.ADDR) self.save_dict = {} def file_access(self) : with open("project_data\\savedata.dat","rb") as save_file : save_dict = pickle.load(save_file) return save_dict def file_dump(self) : with open("project_data\\savedata.dat","wb") as save_file : pickle.dump(self.save_dict,save_file) def recieve(self,conn) : msg_length = conn.recv(self.HEADER).decode(self.FORMAT) if msg_length: msg_length = int(msg_length) msg = conn.recv(msg_length).decode(self.FORMAT) return msg def handle_client(self,conn, addr): print(f"[NEW CONNECTION] {addr} connected.") connected = True while connected: try : self.save_dict = self.file_access() msg = self.recieve(conn) if msg == self.DISCONNECT_MESSAGE: connected = False elif msg == "Save Data" : player_id = conn.recv(5000) try : name,code = pickle.loads(player_id) except EOFError : pass if (name,code) not in self.save_dict : conn.send("Available".encode(self.FORMAT)) msg1 = self.recieve(conn) if msg1 == "Game Data" : game_data = conn.recv(5000) #msg = pickle.loads(msg_data) self.save_dict[(name,code)] = game_data print(self.save_dict) conn.send("Success".encode(self.FORMAT)) else : conn.send("Exists".encode(self.FORMAT)) msg1 = self.recieve(conn) if msg1 == "Game Data" : game_data = conn.recv(5000) self.save_dict[(name,code)] = game_data conn.send("Success".encode(self.FORMAT)) elif msg == "Wipe" : self.save_dict.pop((name,code)) print(f"new dict is ",self.save_dict) elif msg == "Load" : player_id = conn.recv(5000) try : name,code = pickle.loads(player_id) except EOFError : pass if (name,code) in self.save_dict : conn.send("Present".encode(self.FORMAT)) conn.send(self.save_dict[(name,code)]) else : conn.send("Absent".encode(self.FORMAT)) elif msg == "Check Data" : player_id = conn.recv(5000) try : name,code = pickle.loads(player_id) except EOFError : pass if (name,code) in self.save_dict : conn.send("Exists".encode(self.FORMAT)) else : conn.send("New".encode(self.FORMAT)) self.file_dump() except ConnectionResetError : connected = False conn.close() print(f"[Terminated] connection terminated for {addr}") def start(self): self.server.listen() print(f"[LISTENING] Server is listening on {self.SERVER}") while True: conn, addr = self.server.accept() thread = threading.Thread(target=self.handle_client, args=(conn, addr)) thread.start() print(f"[ACTIVE CONNECTIONS] {threading.activeCount() - 1}") print("[STARTING] server is starting...") server = Server() server.start() Ive used the socket package to run a server on my local network.
METHOD 1 A possible solution for this would be to encrypt your code. There are several ways of encrypting your code. But the easiest one is to use base64 or basically converting text-to-binary encoding. and you need to make sure that there is no special character because base64 only have this charachter set. You can check here the base64 table https://en.wikipedia.org/wiki/Base64 import base64 your_code = base64.b64encode(b""" # All your code goes in here. import socket import threading import pickle class Server : def __init__(self) : self.HEADER = 64 self.PORT = 5050 self.SERVER = socket.gethostbyname(socket.gethostname()) self.ADDR = (self.SERVER, self.PORT) self.FORMAT = 'utf-8' self.DISCONNECT_MESSAGE = "!DISCONNECT" # Continue your code... """) exec(base64.b64decode(your_code)) This technique is used for hacking and other malicious purposes to avoid anti-virus software detecting it as a malware. This might work for you. Try recompiling it. Let us know if it works. METHOD 2 If the above method doesn't work, try out this method. This method uses fernet cryptography. This means that the code is more tightly encrypted makes it even difficult for the anti-virus software to recognize this as a malware than the first method. For this, you need a python module called cryptography https://pypi.org/project/cryptography/ from cryptography.fernet import Fernet import base64 code = b""" import socket import threading import pickle class Server : def __init__(self) : self.HEADER = 64 self.PORT = 5050 self.SERVER = socket.gethostbyname(socket.gethostname()) self.ADDR = (self.SERVER, self.PORT) self.FORMAT = 'utf-8' self.DISCONNECT_MESSAGE = "!DISCONNECT" self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.server.bind(self.ADDR) self.save_dict = {} def file_access(self) : with open("project_data\\savedata.dat","rb") as save_file : save_dict = pickle.load(save_file) return save_dict def file_dump(self) : with open("project_data\\savedata.dat","wb") as save_file : pickle.dump(self.save_dict,save_file) def recieve(self,conn) : msg_length = conn.recv(self.HEADER).decode(self.FORMAT) if msg_length: msg_length = int(msg_length) msg = conn.recv(msg_length).decode(self.FORMAT) return msg def handle_client(self,conn, addr): print(f"[NEW CONNECTION] {addr} connected.") connected = True while connected: try : self.save_dict = self.file_access() msg = self.recieve(conn) if msg == self.DISCONNECT_MESSAGE: connected = False elif msg == "Save Data" : player_id = conn.recv(5000) try : name,code = pickle.loads(player_id) except EOFError : pass if (name,code) not in self.save_dict : conn.send("Available".encode(self.FORMAT)) msg1 = self.recieve(conn) if msg1 == "Game Data" : game_data = conn.recv(5000) #msg = pickle.loads(msg_data) self.save_dict[(name,code)] = game_data print(self.save_dict) conn.send("Success".encode(self.FORMAT)) else : conn.send("Exists".encode(self.FORMAT)) msg1 = self.recieve(conn) if msg1 == "Game Data" : game_data = conn.recv(5000) self.save_dict[(name,code)] = game_data conn.send("Success".encode(self.FORMAT)) elif msg == "Wipe" : self.save_dict.pop((name,code)) print(f"new dict is ",self.save_dict) elif msg == "Load" : player_id = conn.recv(5000) try : name,code = pickle.loads(player_id) except EOFError : pass if (name,code) in self.save_dict : conn.send("Present".encode(self.FORMAT)) conn.send(self.save_dict[(name,code)]) else : conn.send("Absent".encode(self.FORMAT)) elif msg == "Check Data" : player_id = conn.recv(5000) try : name,code = pickle.loads(player_id) except EOFError : pass if (name,code) in self.save_dict : conn.send("Exists".encode(self.FORMAT)) else : conn.send("New".encode(self.FORMAT)) self.file_dump() except ConnectionResetError : connected = False conn.close() print(f"[Terminated] connection terminated for {addr}") def start(self): self.server.listen() print(f"[LISTENING] Server is listening on {self.SERVER}") while True: conn, addr = self.server.accept() thread = threading.Thread(target=self.handle_client, args=(conn, addr)) thread.start() print(f"[ACTIVE CONNECTIONS] {threading.activeCount() - 1}") print("[STARTING] server is starting...") server = Server() server.start() """ key = Fernet.generate_key() encryption_type = Fernet(key) encrypted_message = encryption_type.encrypt(code) decrypted_message = encryption_type.decrypt(encrypted_message) exec(decrypted_message) This time the compiled exe was uploaded to https://www.virustotal.com/gui/ and the results were better METHOD 3 - Use another method to freeze your code There are many methods to convert your code to an exe. Another most popular way to freeze your code is to use py2exe. Install the module from the pypi website. Create a new python file called setup.py in the same directory as your main code file. Then paste following in your setup.py file. from distutils.core import setup import py2exe setup(console=['main.py']) Open cmd and type python setup.py py2exe After a while, a folder named dist will be created. It will contain all dependencies for your exe. Now you can compress this file by zipping it and send it to another person. Another possible solution is to use a compiler like InnoSetup to compile all your exe and the dependencies into a single msi file.
19
19
64,833,782
2020-11-14
https://stackoverflow.com/questions/64833782/aws-lambda-keeps-returning-hello-from-lambda
I'm having some issues with AWS Lambda for Python 3.8. No matter what code I try running, AWS Lambda keeps returning the same response. I am trying to retrieve a information from a DynamoDB instance with the code below: import json import boto3 dynamodb = boto3.resource('dynamodb') table = dynamodb.Table('planets') def lambda_handler(event, context): response = table.get_item( Key = { 'id':'mercury' } ) print(response) # TODO implement return { 'statusCode': 200, 'body': response) } I am expecting an output like 'body':{'Item': {'id':'mercury', 'temp':'sizzling hot'}}, or an error even, but I keep getting the response below: Response: { "statusCode": 200, "body": "\"Hello from Lambda!\"" } I even change up the code, expecting an error, but I still get the same output.
Usually this is due to one of the following reasons: You are not deploying your code changes. In the new UI, you have to explicitly Deploy your function using Orange button. You are invoking old lambda version, rather then your latest version, if you are versioning your functions. You must explicitly choose the correct version to invoke.
16
36
64,878,908
2020-11-17
https://stackoverflow.com/questions/64878908/low-parallelism-when-running-apache-beam-wordcount-pipeline-on-spark-with-python
I am quite experienced with Spark cluster configuration and running Pyspark pipelines, but I'm just starting with Beam. So, I am trying to do an apple-to-apple comparison between Pyspark and the Beam python SDK on a Spark PortableRunner (running on top of the same small Spark cluster, 4 workers each with 4 cores and 8GB RAM), and I've settled on a wordcount job for a reasonably large dataset, storing the results in a Parquet table. I have thus downloaded 50GB of Wikipedia text files, splitted across about 100 uncompressed files, and stored them in the directory /mnt/nfs_drive/wiki_files/ (/mnt/nfs_drive is a NFS drive mounted on all workers). First, I am running the following Pyspark wordcount script: from pyspark.sql import SparkSession, Row from operator import add wiki_files = '/mnt/nfs_drive/wiki_files/*' spark = SparkSession.builder.appName("WordCountSpark").getOrCreate() spark_counts = spark.read.text(wiki_files).rdd.map(lambda r: r['value']) \ .flatMap(lambda x: x.split(' ')) \ .map(lambda x: (x, 1)) \ .reduceByKey(add) \ .map(lambda x: Row(word=x[0], count=x[1])) spark.createDataFrame(spark_counts).write.parquet(path='/mnt/nfs_drive/spark_output', mode='overwrite') The script runs perfectly well and outputs the parquet files at the desired location in about 8 minutes. The main stage (reading and splitting tokens) is divided in a reasonable number of tasks, so that the cluster is used efficiently: I am now trying to achieve the same with Beam and the portable runner. First, I have started the Spark job server (on the Spark master node) with the following command: docker run --rm --net=host -e SPARK_EXECUTOR_MEMORY=8g apache/beam_spark_job_server:2.25.0 --spark-master-url=spark://localhost:7077 Then, on the master and worker nodes, I am running the SDK Harness as follows: docker run --net=host -d --rm -v /mnt/nfs_drive:/mnt/nfs_drive apache/beam_python3.6_sdk:2.25.0 --worker_pool Now that the Spark cluster is set up to run Beam pipelines, I can submit the following script: import apache_beam as beam import pyarrow from apache_beam.options.pipeline_options import PipelineOptions from apache_beam.io import fileio options = PipelineOptions([ "--runner=PortableRunner", "--job_endpoint=localhost:8099", "--environment_type=EXTERNAL", "--environment_config=localhost:50000", "--job_name=WordCountBeam" ]) wiki_files = '/mnt/nfs_drive/wiki_files/*' p = beam.Pipeline(options=options) beam_counts = ( p | fileio.MatchFiles(wiki_files) | beam.Map(lambda x: x.path) | beam.io.ReadAllFromText() | 'ExtractWords' >> beam.FlatMap(lambda x: x.split(' ')) | beam.combiners.Count.PerElement() | beam.Map(lambda x: {'word': x[0], 'count': x[1]}) ) _ = beam_counts | 'Write' >> beam.io.WriteToParquet('/mnt/nfs_drive/beam_output', pyarrow.schema( [('word', pyarrow.binary()), ('count', pyarrow.int64())] ) ) result = p.run().wait_until_finish() The code is submitted successfully, I can see the job on the Spark UI and the workers are executing it. However, even if left running for more than 1 hour, it does not produce any output! I thus wanted to make sure that there is not a problem with my setup, so I've run the exact same script on a smaller dataset (just 1 Wiki file). This completes successfully in about 3.5 minutes (Spark wordcount on the same dataset takes 16s!). I wondered how could Beam be that slower, so I started looking at the DAG submitted to Spark by the Beam pipeline via the job server. I noticed that the Spark job spends most of the time in the following stage: This is just splitted in 2 tasks, as shown here: Printing debugging lines show that this task is where the "heavy-lifting" (i.e. reading lines from the wiki files and splitting tokens) is performed - however, since this happens in 2 tasks only, the work will be distributed on 2 workers at most. What's also interesting is that running on the large 50GB dataset results on exactly the same DAG with exactly the same number of tasks. I am quite unsure how to proceed further. It seems like the Beam pipeline has reduced parallelism, but I'm not sure if this is due to sub-optimal translation of the pipeline by the job server, or whether I should specify my PTransforms in some other way to increase the parallelism on Spark. Any suggestion appreciated!
It took a while, but I figured out what's the issue and a workaround. The underlying problem is in Beam's portable runner, specifically where the Beam job is translated into a Spark job. The translation code (executed by the job server) splits stages into tasks based on calls to sparkContext().defaultParallelism(). The job server does not configure default parallelism explicitly (and does not allow the user to set that through pipeline options), hence it falls back, in theory, to configure the parallelism based on the numbers of executors (see the explanation here https://spark.apache.org/docs/latest/configuration.html#execution-behavior). This seems to be the goal of the translation code when calling defaultParallelism(). Now, in practice, it is well known that, when relying on the fallback mechanism, calling sparkContext().defaultParallelism() too soon can result in lower numbers than expected since executors might not have registered with the context yet. In particular, calling defaultParallelism() too soon will give 2 as result, and stages will be split into 2 tasks only. My "dirty hack" workaround thus consists in modifying the source code of the job server by simply adding a delay of 3 seconds after instantiating SparkContext and before doing anything else: $ git diff v2.25.0 diff --git a/runners/spark/src/main/java/org/apache/beam/runners/spark/translation/SparkContextFactory.java b/runners/spark/src/main/java/org/apache/beam/runners/spark/translation/SparkContextFactory.java index aa12192..faaa4d3 100644 --- a/runners/spark/src/main/java/org/apache/beam/runners/spark/translation/SparkContextFactory.java +++ b/runners/spark/src/main/java/org/apache/beam/runners/spark/translation/SparkContextFactory.java @@ -95,7 +95,13 @@ public final class SparkContextFactory { conf.setAppName(contextOptions.getAppName()); // register immutable collections serializers because the SDK uses them. conf.set("spark.kryo.registrator", SparkRunnerKryoRegistrator.class.getName()); - return new JavaSparkContext(conf); + JavaSparkContext jsc = new JavaSparkContext(conf); + try { + Thread.sleep(3000); + } catch (InterruptedException e) { + } + return jsc; } } } After recompiling the job server and launching it with this change, all the calls to defaultParallelism() are done after the executors are registered, and the stages are nicely split in 16 tasks (same as numbers of executors). As expected, the job now completes much faster since there are many more workers doing the work (it is however still 3 times slower than the pure Spark wordcount). While this works, it is of course not a great solution. A much better solution would be one of the following: change the translation engine so that it can deduce the number of tasks based on the number of available executors in a more robust way; allow the user to configure, via pipeline options, the default parallelism to be used by the job server for translating jobs (this is what's done by the Flink portable runner). Until a better solution is in place, it clearly prevents any use of Beam Spark job server in a production cluster. I will post the issue to Beam's ticket queue so that a better solution can be implemented (hopefully soon).
6
1
64,807,850
2020-11-12
https://stackoverflow.com/questions/64807850/sqlalchemy-multiple-one-to-one-and-one-to-many-relationships
I've got two models: Game and Player. I want to have a list of all players in the Game Model, as well as one of these players in a different field. It's a flask server and a sqlite database. Here is my Player Model: class Player(db.Model): id = db.Column(db.Integer, primary_key=True) # other fields... game_id = db.Column(db.Integer, db.ForeignKey('game.id')) game = db.relationship('Game', back_populates='players', foreign_keys=game_id) Here is my Game Model: class Game(db.Model): id = db.Column(db.Integer, primary_key=True) # other fields... current_president_id = db.Column(db.Integer, db.ForeignKey('player.id')) current_president = db.relationship("Player", foreign_keys=current_president_id) # other one-to-one relationships to the Player Model, exactly like the first one... players = db.relationship('Player', back_populates='game', foreign_keys=Player.game_id) I made the two models based on this Response. But I still get the same Warning: SAWarning: Cannot correctly sort tables; there are unresolvable cycles between tables "game, player", which is usually caused by mutually dependent foreign key constraints. Foreign key constraints involving these tables will not be considered; this warning may raise an error in a future release. Like the Warning says, when using this configuration I then get at some point: sqlalchemy.exc.CircularDependencyError: Circular dependency detected. (SaveUpdateState(<Game at 0x23009e00160>), SaveUpdateState(<Player at 0x23009e141c0>), ProcessState(ManyToOneDP(Game.current_president), <Game at 0x23009e00160>, delete=False), ProcessState(OneToManyDP(Game.players), <Game at 0x23009e00160>, delete=False)) I have no idea what to do, I tried to read through the documentation and tested many other configurations, but nothing works. All help greatly appreciated. Thanks!
So I tried to learn SQLAlchemy a bit deeper, and found a solution. First you set the use_alter Flag to True in the one-to-one relationship: current_president_id = db.Column(db.Integer, db.ForeignKey('player.id', use_alter=True)) This makes the Warning go away. But you still need to be careful now. Because the Player model has a Column referencing the Game.id and the Game model has a Column referencing the Player.id you cannot declare the relationships in one commit: g, p1, p2 = Game(), Player(), Player() db.session.add_all([g, p1, p2]) db.session.commit() g.players = [p1, p2] g.current_president = p3 db.session.commit() This will raise the CircularDependencyError. But this will not: g, p1, p2 = Game(), Player(), Player() db.session.add_all([g, p1, p2]) db.session.commit() g.players = [p1, p2] db.session.commit() g.current_president = p3 db.session.commit() EDIT: Use use_alter=True in the relationship to prevent any CircularDependencyErrors. This way, when you add a Game with Players and the relationship in one commit, the relationship will be set in a second 'ALTER' statement to prevent the circular dependency.
11
10
64,856,328
2020-11-16
https://stackoverflow.com/questions/64856328/selenium-works-on-aws-ec2-but-not-on-aws-lambda
I've looked at and tried nearly every other post on this topic with no luck. EC2 I'm using python 3.6 so I'm using the following AMI amzn-ami-hvm-2018.03.0.20181129-x86_64-gp2 (see here). Once I SSH into my EC2, I download Chrome with: sudo curl https://intoli.com/install-google-chrome.sh | bash cp -r /opt/google/chrome/ /home/ec2-user/ google-chrome-stable --version # Google Chrome 86.0.4240.198 And download and unzip the matching Chromedriver: sudo wget https://chromedriver.storage.googleapis.com/86.0.4240.22/chromedriver_linux64.zip sudo unzip chromedriver_linux64.zip I install python36 and selenium with: sudo yum install python36 -y sudo /usr/bin/pip-3.6 install selenium Then run the script: import os import selenium from selenium import webdriver CURR_PATH = os.getcwd() chrome_options = webdriver.ChromeOptions() chrome_options.add_argument('--no-sandbox') chrome_options.add_argument('--headless') chrome_options.add_argument('--window-size=1280x1696') chrome_options.add_argument('--disable-gpu') chrome_options.add_argument('--disable-dev-shm-usage') chrome_options.add_argument('--hide-scrollbars') chrome_options.add_argument('--enable-logging') chrome_options.add_argument('--log-level=0') chrome_options.add_argument('--v=99') chrome_options.add_argument('--single-process') chrome_options.add_argument('--ignore-certificate-errors') chrome_options.add_argument('--remote-debugging-port=9222') chrome_options.binary_location = f"{CURR_PATH}/chrome/google-chrome" driver = webdriver.Chrome( executable_path = f"{CURR_PATH}/chromedriver", chrome_options=chrome_options ) driver.get("https://www.google.com/") html = driver.page_source print(html) This works Lambda I then zip my chromedriver and Chrome files: mkdir tmp mv chromedriver tmp mv chrome tmp cd tmp zip -r9 ../chrome.zip chromedriver chrome And copy the zipped file to an S3 bucket This is my lambda function: import os import boto3 from botocore.exceptions import ClientError import zipfile import selenium from selenium import webdriver s3 = boto3.resource('s3') def handler(event, context): chrome_bucket = os.environ.get('CHROME_S3_BUCKET') chrome_key = os.environ.get('CHROME_S3_KEY') # DOWNLOAD HEADLESS CHROME FROM S3 try: # with open('/tmp/headless_chrome.zip', 'wb') as data: s3.meta.client.download_file(chrome_bucket, chrome_key, '/tmp/chrome.zip') print(os.listdir('/tmp')) except ClientError as e: raise e # UNZIP HEADLESS CHROME try: with zipfile.ZipFile('/tmp/chrome.zip', 'r') as zip_ref: zip_ref.extractall('/tmp') # FREE UP SPACE os.remove('/tmp/chrome.zip') print(os.listdir('/tmp')) except: raise ValueError('Problem with unzipping Chrome executable') # CHANGE PERMISSION OF CHROME try: os.chmod('/tmp/chromedriver', 0o775) os.chmod('/tmp/chrome/chrome', 0o775) os.chmod('/tmp/chrome/google-chrome', 0o775) except: raise ValueError('Problem with changing permissions to Chrome executable') # GET LINKS chrome_options = webdriver.ChromeOptions() chrome_options.add_argument('--no-sandbox') chrome_options.add_argument('--headless') chrome_options.add_argument('--window-size=1280x1696') chrome_options.add_argument('--disable-gpu') chrome_options.add_argument('--disable-dev-shm-usage') chrome_options.add_argument('--hide-scrollbars') chrome_options.add_argument('--enable-logging') chrome_options.add_argument('--log-level=0') chrome_options.add_argument('--v=99') chrome_options.add_argument('--single-process') chrome_options.add_argument('--ignore-certificate-errors') chrome_options.add_argument('--remote-debugging-port=9222') chrome_options.binary_location = "/tmp/chrome/google-chrome" driver = webdriver.Chrome( executable_path = "/tmp/chromedriver", chrome_options=chrome_options ) driver.get("https://www.google.com/") html = driver.page_source print(html) I'm able to see my unzipped files in the /tmp path. And my error: { "errorMessage": "Message: unknown error: unable to discover open pages\n", "errorType": "WebDriverException", "stackTrace": [ [ "/var/task/lib/observer.py", 69, "handler", "chrome_options=chrome_options" ], [ "/var/task/selenium/webdriver/chrome/webdriver.py", 81, "__init__", "desired_capabilities=desired_capabilities)" ], [ "/var/task/selenium/webdriver/remote/webdriver.py", 157, "__init__", "self.start_session(capabilities, browser_profile)" ], [ "/var/task/selenium/webdriver/remote/webdriver.py", 252, "start_session", "response = self.execute(Command.NEW_SESSION, parameters)" ], [ "/var/task/selenium/webdriver/remote/webdriver.py", 321, "execute", "self.error_handler.check_response(response)" ], [ "/var/task/selenium/webdriver/remote/errorhandler.py", 242, "check_response", "raise exception_class(message, screen, stacktrace)" ] ] } EDIT: I am willing to try out anything at this point. Different versions of Chrome or Chromium, Chromedriver, Python or Selenium. EDIT2: The answer below did not solve the problem.
I was finally able to get it to work Python 3.7 selenium==3.14.0 headless-chromium v1.0.0-55 chromedriver 2.43 Headless-Chromium https://github.com/adieuadieu/serverless-chrome/releases/download/v1.0.0-55/stable-headless-chromium-amazonlinux-2017-03.zip Chromedriver https://chromedriver.storage.googleapis.com/2.43/chromedriver_linux64.zip I added headless-chromium and chromedriver to a Lambda Layer Permissions 755 for both works Lambda The Lambda function looks like this import os import selenium from selenium import webdriver def handler(event, context): print(os.listdir('/opt')) # chrome_options = webdriver.ChromeOptions() chrome_options.add_argument('--no-sandbox') chrome_options.add_argument('--headless') chrome_options.add_argument('--single-process') chrome_options.add_argument('--disable-dev-shm-usage') chrome_options.binary_location = f"/opt/headless-chromium" driver = webdriver.Chrome( executable_path = f"/opt/chromedriver", chrome_options=chrome_options ) driver.get("https://www.google.com/") html = driver.page_source driver.close() driver.quit() print(html) Hope this helps someone in Q4 2020 and after.
8
2
64,838,803
2020-11-14
https://stackoverflow.com/questions/64838803/is-there-any-way-to-use-sagemath-on-macos-big-sur
I downloaded SageMath-9.2 on my mac, but every time I try to use the notebook by running "sage -n jupyter" on my terminal I get the following massage: Please wait while the Sage Jupyter Notebook server starts... Traceback (most recent call last): File "/Applications/SageMath-9.2.app/Contents/Resources/sage/local/lib/python3.8/site-packages/sage/repl/ipython_kernel/install.py", line 307, in have_prerequisites from notebook.notebookapp import NotebookApp File "/Applications/SageMath-9.2.app/Contents/Resources/sage/local/lib/python3.8/site-packages/notebook/notebookapp.py", line 66, in from tornado import httpserver File "/Applications/SageMath-9.2.app/Contents/Resources/sage/local/lib/python3.8/site-packages/tornado/httpserver.py", line 29, in import ssl File "/Applications/SageMath-9.2.app/Contents/Resources/sage/local/lib/python3.8/ssl.py", line 98, in import _ssl # if we can't import it, let the error propagate ModuleNotFoundError: No module named '_ssl' The Jupyter notebook requires ssl, even if you do not use https. Install the openssl development packages in your system and then rebuild Python (sage -f python3). And also I can't open the app either for some reason ..... every time I click on the app I get a small window saying : Jupyter Server failed to start For some reason the Jupyter server failed to start. Please check the log for clues, and have that information handy when asking for help. I hope for some help, its very important for me because I must use SageMath for my college project.. thanks in advance
On macOS Big Sur, there are several ways to install SageMath using Conda: https://doc.sagemath.org/html/en/installation/conda.html building from source, using as many Homebrew packages as you can: https://doc.sagemath.org/html/en/installation/source.html using CoCalc-Docker: https://github.com/sagemathinc/cocalc-docker Sage can also be used online using Binder https://sage-package.readthedocs.io/en/latest/sage_package/thebe.html https://opendreamkit.org/2018/07/23/live-online-slides-with-sagemath-jupyter-rise-binder/ https://github.com/sagemath/sage-binder-env CoCalc: https://cocalc.com SageCell: https://sagecell.sagemath.org The installation you currently have was downloaded as a macOS app, which ships its own Python which lacks the SSL module (for licence reasons). To repair it: change to the Sage directory optionally get the latest development version set number of jobs to run in parallel get rid of that Sage's Python configure optionally follow the brew install recommendations at the end of configure make $ DIR=/Applications/SageMath-9.2.app/Contents/Resources/sage $ cd $DIR $ git checkout develop $ git pull origin develop --tags $ MAKE='make -j8' $ V=0 $ source .homebrew-build-env $ make -s V=0 python3-clean $ make -s V=0 configure $ ./configure $ make -s V=0 The other way to solve your problem is to use the SageMath Jupyter kernel provided by Sage with your system-wide Jupyter (eg as installed via Homebrew). This should achieve that goal: $ SAGE_LOCAL=`sage -c 'print(SAGE_LOCAL)'` $ SAGE_KERNEL=$SAGE_LOCAL/share/jupyter/kernels/sagemath $ KERNELS=$HOME/Library/Jupyter/kernels $ ln -s $SAGE_KERNEL $KERNELS
6
5
64,821,850
2020-11-13
https://stackoverflow.com/questions/64821850/error-when-importing-geopandas-oserror-could-not-find-lib-c-or-load-any-of-its
I'm using Spyder with Anaconda and since MacOS last update (Big Sur 11.0.1), when doing import geopandas, I get the following error: OSError: Could not find lib c or load any of its variants []. There are several subjects on the matter (particularly this one and this one), that mainly recommends to reset the environment variable DYLD_FALLBACK_LIBRARY_PATH by putting in the Terminal: export DYLD_FALLBACK_LIBRARY_PATH=$(HOME)/lib:/usr/local/lib:/lib:/usr/lib However, here is what I get: -bash: HOME: command not found A brew or pip install didn't fix the problem either. Does anyone have an idea on how I can fix this? Am I suppose to replace $(HOME) by something? Many thanks!
For references: I ended up reinstalling a new environment on Anaconda an it works but I wasn't able to fix the original problem.
7
0
64,871,329
2020-11-17
https://stackoverflow.com/questions/64871329/does-string-slicing-perform-copy-in-memory
I'm wondering if : a = "abcdef" b = "def" if a[3:] == b: print("something") does actually perform a copy of the "def" part of a somewhere in memory, or if the letters checking is done in-place ? Note : I'm speaking about a string, not a list (for which I know the answer)
String slicing makes a copy in CPython. Looking in the source, this operation is handled in unicodeobject.c:unicode_subscript. There is evidently a special-case to re-use memory when the step is 1, start is 0, and the entire content of the string is sliced - this goes into unicode_result_unchanged and there will not be a copy. However, the general case calls PyUnicode_Substring where all roads lead to a memcpy. To empirically verify these claims, you can use a stdlib memory profiling tool tracemalloc: # s.py import tracemalloc tracemalloc.start() before = tracemalloc.take_snapshot() a = "." * 7 * 1024**2 # 7 MB of ..... # line 6, first alloc b = a[1:] # line 7, second alloc after = tracemalloc.take_snapshot() for stat in after.compare_to(before, 'lineno')[:2]: print(stat) You should see the top two statistics output like this: /tmp/s.py:6: size=7168 KiB (+7168 KiB), count=1 (+1), average=7168 KiB /tmp/s.py:7: size=7168 KiB (+7168 KiB), count=1 (+1), average=7168 KiB This result shows two allocations of 7 meg, strong evidence of the memory copying, and the exact line numbers of those allocations will be indicated. Try changing the slice from b = a[1:] into b = a[0:] to see that entire-string-special-case in effect: there should be only one large allocation now, and sys.getrefcount(a) will increase by one. In theory, since strings are immutable, an implementation could re-use memory for substring slices. This would likely complicate any reference-counting based garbage collection process, so it may not be a useful idea in practice. Consider the case where a small slice from a much larger string was taken - unless you implemented some kind of sub-reference counting on the slice, the memory from the much larger string could not be freed until the end of the substring's lifetime. For users that specifically need a standard type which can be sliced without copying the underlying data, there is memoryview. See What exactly is the point of memoryview in Python for more information about that.
44
41
64,871,133
2020-11-17
https://stackoverflow.com/questions/64871133/reportlab-installation-failed-after-upgrading-to-macos-big-sur
I'm trying to reinstall my virtual env after upgrade to MacOS Big Sur. But error appears: 4 warnings generated. clang -Wno-unused-result -Wsign-compare -Wunreachable-code -fno-common -dynamic -DNDEBUG -g -fwrapv -O3 -Wall -isysroot /Library/Developer/CommandLineTools/SDKs/MacOSX11.0.sdk -I/Library/Developer/CommandLineTools/SDKs/MacOSX11.0.sdk/usr/include -I/Library/Developer/CommandLineTools/SDKs/MacOSX11.0.sdk/System/Library/Frameworks/Tk.framework/Versions/8.5/Headers -Qunused-arguments -Qunused-arguments -DRENDERPM_FT -DLIBART_COMPILATION -DLIBART_VERSION=2.3.21 -Isrc/rl_addons/renderPM -Isrc/rl_addons/renderPM/libart_lgpl -Isrc/rl_addons/renderPM/gt1 -I/usr/local/include/freetype2 -I/usr/local/include -I/usr/local/opt/[email protected]/include -I/usr/local/opt/sqlite/include -I/Users/zulfugar/PycharmProjects/AppForm/.venv/include -I/usr/local/Cellar/[email protected]/3.8.6_1/Frameworks/Python.framework/Versions/3.8/include/python3.8 -c src/rl_addons/renderPM/gt1/gt1-parset1.c -o build/temp.macosx-11.0-x86_64-3.8/src/rl_addons/renderPM/gt1/gt1-parset1.o src/rl_addons/renderPM/gt1/gt1-parset1.c:604:28: warning: for loop has empty body [-Wempty-body] for (i = 0; i < size; i++); ^ src/rl_addons/renderPM/gt1/gt1-parset1.c:604:28: note: put the semicolon on a separate line to silence this warning src/rl_addons/renderPM/gt1/gt1-parset1.c:1907:16: warning: comparison of integers of different signs: 'int' and 'unsigned long' [-Wsign-compare] for (i = 0; i < sizeof(internal_procs) / sizeof(InternalGt1ProcListing); i++) ~ ^ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ src/rl_addons/renderPM/gt1/gt1-parset1.c:710:1: warning: function 'print_value_deep' is not needed and will not be emitted [-Wunneeded-internal-declaration] print_value_deep (Gt1PSContext *psc, Gt1Value *val, int nest) ^ 3 warnings generated. clang -Wno-unused-result -Wsign-compare -Wunreachable-code -fno-common -dynamic -DNDEBUG -g -fwrapv -O3 -Wall -isysroot /Library/Developer/CommandLineTools/SDKs/MacOSX11.0.sdk -I/Library/Developer/CommandLineTools/SDKs/MacOSX11.0.sdk/usr/include -I/Library/Developer/CommandLineTools/SDKs/MacOSX11.0.sdk/System/Library/Frameworks/Tk.framework/Versions/8.5/Headers -Qunused-arguments -Qunused-arguments -DRENDERPM_FT -DLIBART_COMPILATION -DLIBART_VERSION=2.3.21 -Isrc/rl_addons/renderPM -Isrc/rl_addons/renderPM/libart_lgpl -Isrc/rl_addons/renderPM/gt1 -I/usr/local/include/freetype2 -I/usr/local/include -I/usr/local/opt/[email protected]/include -I/usr/local/opt/sqlite/include -I/Users/zulfugar/PycharmProjects/AppForm/.venv/include -I/usr/local/Cellar/[email protected]/3.8.6_1/Frameworks/Python.framework/Versions/3.8/include/python3.8 -c src/rl_addons/renderPM/gt1/gt1-dict.c -o build/temp.macosx-11.0-x86_64-3.8/src/rl_addons/renderPM/gt1/gt1-dict.o clang -Wno-unused-result -Wsign-compare -Wunreachable-code -fno-common -dynamic -DNDEBUG -g -fwrapv -O3 -Wall -isysroot /Library/Developer/CommandLineTools/SDKs/MacOSX11.0.sdk -I/Library/Developer/CommandLineTools/SDKs/MacOSX11.0.sdk/usr/include -I/Library/Developer/CommandLineTools/SDKs/MacOSX11.0.sdk/System/Library/Frameworks/Tk.framework/Versions/8.5/Headers -Qunused-arguments -Qunused-arguments -DRENDERPM_FT -DLIBART_COMPILATION -DLIBART_VERSION=2.3.21 -Isrc/rl_addons/renderPM -Isrc/rl_addons/renderPM/libart_lgpl -Isrc/rl_addons/renderPM/gt1 -I/usr/local/include/freetype2 -I/usr/local/include -I/usr/local/opt/[email protected]/include -I/usr/local/opt/sqlite/include -I/Users/zulfugar/PycharmProjects/AppForm/.venv/include -I/usr/local/Cellar/[email protected]/3.8.6_1/Frameworks/Python.framework/Versions/3.8/include/python3.8 -c src/rl_addons/renderPM/gt1/gt1-namecontext.c -o build/temp.macosx-11.0-x86_64-3.8/src/rl_addons/renderPM/gt1/gt1-namecontext.o src/rl_addons/renderPM/gt1/gt1-namecontext.c:100:9: error: implicitly declaring library function 'strlen' with type 'unsigned long (const char *)' [-Werror,-Wimplicit-function-declaration] len = strlen (s); ^ src/rl_addons/renderPM/gt1/gt1-namecontext.c:100:9: note: include the header <string.h> or explicitly provide a declaration for 'strlen' src/rl_addons/renderPM/gt1/gt1-namecontext.c:102:3: error: implicitly declaring library function 'memcpy' with type 'void *(void *, const void *, unsigned long)' [-Werror,-Wimplicit-function-declaration] memcpy (new, s, len); ^ src/rl_addons/renderPM/gt1/gt1-namecontext.c:102:3: note: include the header <string.h> or explicitly provide a declaration for 'memcpy' src/rl_addons/renderPM/gt1/gt1-namecontext.c:172:10: error: implicitly declaring library function 'strcmp' with type 'int (const char *, const char *)' [-Werror,-Wimplicit-function-declaration] if (!strcmp (nc->table[i & mask].name, name)) ^ src/rl_addons/renderPM/gt1/gt1-namecontext.c:172:10: note: include the header <string.h> or explicitly provide a declaration for 'strcmp' 3 errors generated. error: command 'clang' failed with exit status 1 ---------------------------------------- ERROR: Command errored out with exit status 1: /Users/zulfugar/PycharmProjects/AppForm/.venv/bin/python3 -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/_w/8xmqn_ys20n91w63y9lcl6nr0000gn/T/pip-install-_q2xgbny/reportlab/setup.py'"'"'; __file__='"'"'/private/var/folders/_w/8xmqn_ys20n91w63y9lcl6nr0000gn/T/pip-install-_q2xgbny/reportlab/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record /private/var/folders/_w/8xmqn_ys20n91w63y9lcl6nr0000gn/T/pip-record-08bq_70o/install-record.txt --single-version-externally-managed --compile --install-headers /Users/zulfugar/PycharmProjects/AppForm/.venv/include/site/python3.8/reportlab Check the logs for full command output. I tried: Reinstall xcode-select --install; Reinstalled Python brew install [email protected]; Installed Xcode itself; None of above helped. What can be the issue?
this worked for me CFLAGS="-Wno-error=implicit-function-declaration" pip install reportlab
14
41
64,794,378
2020-11-11
https://stackoverflow.com/questions/64794378/correct-pb-file-to-move-tensorflow-model-into-ml-net
I have a TensorFlow model that I built (a 1D CNN) that I would now like to implement into .NET. In order to do so I need to know the Input and Output nodes. When I uploaded the model on Netron I get a different graph depending on my save method and the only one that looks correct comes from an h5 upload. Here is the model.summary(): If I save the model as an h5 model.save("Mn_pb_model.h5") and load that into the Netron to graph it, everything looks correct: However, ML.NET will not accept h5 format so it needs to be saved as a pb. In looking through samples of adopting TensorFlow in ML.NET, this sample shows a TensorFlow model that is saved in a similar format to the SavedModel format - recommended by TensorFlow (and also recommended by ML.NET here "Download an unfrozen [SavedModel format] ..."). However when saving and loading the pb file into Netron I get this: And zoomed in a little further (on the far right side), As you can see, it looks nothing like it should. Additionally the input nodes and output nodes are not correct so it will not work for ML.NET (and I think something is wrong). I am using the recommended way from TensorFlow to determine the Input / Output nodes: When I try to obtain a frozen graph and load it into Netron, at first it looks correct, but I don't think that it is: There are four reasons I do not think this is correct. it is very different from the graph when it was uploaded as an h5 (which looks correct to me). as you can see from earlier, I am using 1D convolutions throughout and this is showing that it goes to 2D (and remains that way). this file size is 128MB whereas the one in the TensorFlow to ML.NET example is only 252KB. Even the Inception model is only 56MB. if I load the Inception model in TensorFlow and save it as an h5, it looks the same as from the ML.NET resource, yet when I save it as a frozen graph it looks different. If I take the same model and save it in the recommended SavedModel format, it shows up all messed up in Netron. Take any model you want and save it in the recommended SavedModel format and you will see for yourself (I've tried it on a lot of different models). Additionally in looking at the model.summary() of Inception with it's graph, it is similar to its graph in the same way my model.summary() is to the h5 graph. It seems like there should be an easier way (and a correct way) to save a TensorFlow model so it can be used in ML.NET. Please show that your suggested solution works: In the answer that you provide, please check that it works (load the pb model [this should also have a Variables folder in order to work for ML.NET] into Netron and show that it is the same as the h5 model, e.g., screenshot it). So that we are all trying the same thing, here is a link to a MNIST ML crash course example. It takes less than 30s to run the program and produces a model called my_model. From here you can save it according to your method and upload it to see the graph on Netron. Here is the h5 model upload:
This answer is made of 3 parts: going through other programs NOT going through other programs Difference between op-level graph and conceptual graph (and why Netron show you different graphs) 1. Going through other programs: ML.net needs an ONNX model, not a pb file. There is several ways to convert your model from TensorFlow to an ONNX model you could load in ML.net : With WinMLTools tools: https://learn.microsoft.com/en-us/windows/ai/windows-ml/convert-model-winmltools With MMdnn: https://github.com/microsoft/MMdnn With tf2onnx: https://github.com/onnx/tensorflow-onnx If trained with Keras, with keras2onnx: https://github.com/onnx/keras-onnx This SO post could help you too: Load model with ML.NET saved with keras And here you will find more informations on the h5 and pb files formats, what they contain, etc.: https://www.tensorflow.org/guide/keras/save_and_serialize#weights_only_saving_in_savedmodel_format 2. But you are asking "TensorFlow -> ML.NET without going through other programs": 2.A An overview of the problem: First, the pl file format you made using the code you provided from seems, from what you say, to not be the same as the one used in the example you mentionned in comment (https://learn.microsoft.com/en-us/dotnet/machine-learning/tutorials/text-classification-tf) Could to try to use the pb file that will be generated via tf.saved_model.save ? Is it working ? A thought about this microsoft blog post: From this page we can read: In ML.NET you can load a frozen TensorFlow model .pb file (also called β€œfrozen graph def” which is essentially a serialized graph_def protocol buffer written to disk) and: That TensorFlow .pb model file that you see in the diagram (and the labels.txt codes/Ids) is what you create/train in Azure Cognitive Services Custom Vision then exporte as a frozen TensorFlow model file to be used by ML.NET C# code. So, this pb file is a type of file generated from Azure Cognitive Services Custom Vision. Perharps you could try this way too ? 2.B Now, we'll try to provide the solution: In fact, in TensorFlow 1.x you could save a frozen graph easily, using freeze_graph. But TensorFlow 2.x does not support freeze_graph and converter_variables_to_constants. You could read some usefull informations here too: Tensorflow 2.0 : frozen graph support Some users are wondering how to do in TF 2.x: how to freeze graph in tensorflow 2.0 (https://github.com/tensorflow/tensorflow/issues/27614) There are some solutions however to create the pb file you could load in ML.net as you want: https://leimao.github.io/blog/Save-Load-Inference-From-TF2-Frozen-Graph/ How to save Keras model as frozen graph? (already linked in your question though) Difference between op-level graph and conceptual graph (and why Netron show you different graphs): As @mlneural03 said in a comment to you question, Netron shows a different graph depending on what file format you give: If you load a h5 file, Netron wil display the conceptual graph If you load a pb file, Netron wil display the op-level graph What is the difference between a op-level graph and a conceptual graph ? In TensorFlow, the nodes of the op-level graph represent the operations ("ops"), like tf.add , tf.matmul , tf.linalg.inv, etc. The conceptual graph will show you your your model's structure. That's completely different things. "ops" is an abbreviation for "operations". Operations are nodes that perform the computations. So, that's why you get a very large graph with a lot of nodes when you load the pb fil in Netron: you see all the computation nodes of the graph. but when you load the h5 file in Netron, you "just" see your model's tructure, the design of your model. In TensorFlow, you can view your graph with TensorBoard: By default, TensorBoard displays the op-level graph. To view the coneptual graph, in TensorBoard, select the "keras" tag. There is a Jupyter Notebook that explains very clearly the difference between the op-level graph and the coneptual graph here: https://colab.research.google.com/github/tensorflow/tensorboard/blob/master/docs/graphs.ipynb You can also read this "issue" on the TensorFlow Github too, related to your question: https://github.com/tensorflow/tensorflow/issues/39699 In a nutshell: In fact there is no problem, just a little misunderstanding (and that's OK, we can't know everything). You would like to see the same graphs when loading the h5 file and the pb file in Netron, but it has to be unsuccessful, because the files does not contains the same graphs. These graphs are two ways of displaying the same model. The pb file created with the method we described will be the correct pb file to load whith ML.NET, as described in the Microsoft's tutorial we talked about. SO, if you load you correct pb file as described in these tutorials, you wil load your real/true model.
8
4
64,811,022
2020-11-12
https://stackoverflow.com/questions/64811022/how-to-import-a-python-py-file-in-jupyter-notebook
I have a Jupyter Notebook and I would like to use some credentials I have put into a config.py file. This file is in the same folder as the Jupyter Notebook. I use the line import config The problem is Jupyter replies with this message: ModuleNotFoundError: No module named 'config.py'; 'config' is not a package Thank you for your help
After some research, I have found a way to solve my need using Dotenv Python Package: pypi.org/project/python-dotenv What needs to be done? Insert the following lines: !pip install python-dotenv # Credentials file %load_ext dotenv %dotenv import os Then place a hidden file named .env where the credentials are places. In my case it looks like this: CLIENT_ID = "XXXX" CLIENT_SECRET = "YYYY" Then, in your notebook file, whenever you need to load the credentials use: CLIENT_ID = os.getenv("CLIENT_ID") CLIENT_SECRET = os.getenv("CLIENT_SECRET") And you are good to go! Credit to http://veekaybee.github.io/2020/02/25/secrets/ for the solution
8
1
64,872,560
2020-11-17
https://stackoverflow.com/questions/64872560/elementwise-maximum-of-sparse-scipy-matrix-vector-with-broadcasting
I need a fast element-wise maximum that compares each row of an n-by-m scipy sparse matrix element-wise to a sparse 1-by-m matrix. This works perfectly in Numpy using np.maximum(mat, vec) via Numpy's broadcasting. However, Scipy's .maximum() does not have broadcasting. My matrix is large, so I cannot cast it to a numpy array. My current workaround is to loop over the many rows of mat with mat[row,:].maximum(vec). This big loop is ruining my code efficiency (it has to be done many times). My slow solution is in the second code snippet below -- Is there a better solution? # Example import numpy as np from scipy import sparse mat = sparse.csc_matrix(np.arange(12).reshape((4,3))) vec = sparse.csc_matrix([-1, 5, 100]) # Numpy's np.maximum() gives the **desired result** using broadcasting (but it can't handle sparse matrices): numpy_result = np.maximum( mat.toarray(), vec.toarray() ) print( numpy_result ) # [[ 0 5 100] # [ 3 5 100] # [ 6 7 100] # [ 9 10 100]] # Scipy only compares the top row of mat to vec (no broadcasting!): scipy_result = mat.maximum(vec) print( scipy_result.toarray() ) # [[ 0 5 100] # [ 3 4 5] # [ 6 7 8] # [ 9 10 11]] #Reversing the order of mat and vec in the call to vec.maximum(mat) results in a single row output, and also frequently seg faults (!): Larger example & current solution for speed testing import numpy as np from scipy import sparse import timeit mat = sparse.csc_matrix( sparse.random(20000, 4000, density=.01, data_rvs=lambda s: np.random.randint(0, 5000, size=s)) ) vec = sparse.csc_matrix( sparse.random(1, 4000, density=.01, data_rvs=lambda s: np.random.randint(0, 5000, size=s)) ) def sparse_elementwise_maximum(mat, vec): output = sparse.lil_matrix(mat.shape) for row_idx in range( mat.shape[0] ): output[row_idx] = mat[row_idx,:].maximum(vec) return output # Time it num_timing_loops = 3.0 starttime = timeit.default_timer() for _ in range(int(num_timing_loops)): sparse_elementwise_maximum(mat, vec) print('time per call is:', (timeit.default_timer() - starttime)/num_timing_loops, 'seconds') # 15 seconds per call (way too slow!) EDIT I'm accepting Max's answer, as the question was specifically about a high performance solution, and Max's solution offers huge 1000x-2500x speedups on various inputs I tried at the expense of more lines of code and Numba compiling. However, for general use, Daniel F's one-liner is a great solution offers 10x-50x speedups on examples I tried--I will probably use for many other things.
A low level approach As always you can think on how a proper sparse matrix format for this operation is built up, for csr-matrices the main components are shape, data_arr,indices and ind_ptr. With these parts of the scipy.sparse.csr object it is quite straight forward but maybe a bit time consuming to implement an efficient algorithm in a compiled language (C,C++,Cython, Python-Numba). Int his implemenation I used Numba, but porting it to C++ should be easily possible (syntax changes) and maybe avoiding the slicing. Implementation (first try) import numpy as np import numba as nb # get all needed components of the csr object and create a resulting csr object at the end def sparse_elementwise_maximum_wrap(mat,vec): mat_csr=mat.tocsr() vec_csr=vec.tocsr() shape_mat=mat_csr.shape indices_mat=mat_csr.indices indptr_mat=mat_csr.indptr data_mat=mat_csr.data indices_vec=vec_csr.indices data_vec=vec_csr.data res=sparse_elementwise_maximum_nb(indices_mat,indptr_mat,data_mat,shape_mat,indices_vec,data_vec) res=sparse.csr_matrix(res, shape=shape_mat) return res @nb.njit(cache=True) def sparse_elementwise_maximum_nb(indices_mat,indptr_mat,data_mat,shape_mat,vec_row_ind,vec_row_data): data_res=[] indices_res=[] indptr_mat_res=[] indptr_mat_=0 indptr_mat_res.append(indptr_mat_) for row_idx in range(shape_mat[0]): mat_row_ind=indices_mat[indptr_mat[row_idx]:indptr_mat[row_idx+1]] mat_row_data=data_mat[indptr_mat[row_idx]:indptr_mat[row_idx+1]] mat_ptr=0 vec_ptr=0 while mat_ptr<mat_row_ind.shape[0] and vec_ptr<vec_row_ind.shape[0]: ind_mat=mat_row_ind[mat_ptr] ind_vec=vec_row_ind[vec_ptr] #value for both matrix and vector is present if ind_mat==ind_vec: data_res.append(max(mat_row_data[mat_ptr],vec_row_data[vec_ptr])) indices_res.append(ind_mat) mat_ptr+=1 vec_ptr+=1 indptr_mat_+=1 #only value for the matrix is present vector is assumed 0 elif ind_mat<ind_vec: if mat_row_data[mat_ptr] >0: data_res.append(mat_row_data[mat_ptr]) indices_res.append(ind_mat) indptr_mat_+=1 mat_ptr+=1 #only value for the vector is present matrix is assumed 0 else: if vec_row_data[vec_ptr] >0: data_res.append(vec_row_data[vec_ptr]) indices_res.append(ind_vec) indptr_mat_+=1 vec_ptr+=1 for i in range(mat_ptr,mat_row_ind.shape[0]): if mat_row_data[i] >0: data_res.append(mat_row_data[i]) indices_res.append(mat_row_ind[i]) indptr_mat_+=1 for i in range(vec_ptr,vec_row_ind.shape[0]): if vec_row_data[i] >0: data_res.append(vec_row_data[i]) indices_res.append(vec_row_ind[i]) indptr_mat_+=1 indptr_mat_res.append(indptr_mat_) return np.array(data_res),np.array(indices_res),np.array(indptr_mat_res) Implementation (optimized) In this approach the lists are replaced by a dynamically resized array. I increased the size of the output in 60 MB steps. On creation of the csr-object, there is also no copy of the data made, just references. If you want avoid a memory overhead you have to copy the arrays in the end. @nb.njit(cache=True) def sparse_elementwise_maximum_nb(indices_mat,indptr_mat,data_mat,shape_mat,vec_row_ind,vec_row_data): mem_step=5_000_000 #preallocate memory for 5M non-zero elements (60 MB in this example) data_res=np.empty(mem_step,dtype=data_mat.dtype) indices_res=np.empty(mem_step,dtype=np.int32) data_res_p=0 indptr_mat_res=np.empty((shape_mat[0]+1),dtype=np.int32) indptr_mat_res[0]=0 indptr_mat_res_p=1 indptr_mat_=0 for row_idx in range(shape_mat[0]): mat_row_ind=indices_mat[indptr_mat[row_idx]:indptr_mat[row_idx+1]] mat_row_data=data_mat[indptr_mat[row_idx]:indptr_mat[row_idx+1]] #check if resizing is necessary if data_res.shape[0]<data_res_p+shape_mat[1]: #add at least memory for another mem_step elements size_to_add=mem_step if shape_mat[1] >size_to_add: size_to_add=shape_mat[1] data_res_2 =np.empty(data_res.shape[0] +size_to_add,data_res.dtype) indices_res_2=np.empty(indices_res.shape[0]+size_to_add,indices_res.dtype) for i in range(data_res_p): data_res_2[i]=data_res[i] indices_res_2[i]=indices_res[i] data_res=data_res_2 indices_res=indices_res_2 mat_ptr=0 vec_ptr=0 while mat_ptr<mat_row_ind.shape[0] and vec_ptr<vec_row_ind.shape[0]: ind_mat=mat_row_ind[mat_ptr] ind_vec=vec_row_ind[vec_ptr] #value for both matrix and vector is present if ind_mat==ind_vec: data_res[data_res_p]=max(mat_row_data[mat_ptr],vec_row_data[vec_ptr]) indices_res[data_res_p]=ind_mat data_res_p+=1 mat_ptr+=1 vec_ptr+=1 indptr_mat_+=1 #only value for the matrix is present vector is assumed 0 elif ind_mat<ind_vec: if mat_row_data[mat_ptr] >0: data_res[data_res_p]=mat_row_data[mat_ptr] indices_res[data_res_p]=ind_mat data_res_p+=1 indptr_mat_+=1 mat_ptr+=1 #only value for the vector is present matrix is assumed 0 else: if vec_row_data[vec_ptr] >0: data_res[data_res_p]=vec_row_data[vec_ptr] indices_res[data_res_p]=ind_vec data_res_p+=1 indptr_mat_+=1 vec_ptr+=1 for i in range(mat_ptr,mat_row_ind.shape[0]): if mat_row_data[i] >0: data_res[data_res_p]=mat_row_data[i] indices_res[data_res_p]=mat_row_ind[i] data_res_p+=1 indptr_mat_+=1 for i in range(vec_ptr,vec_row_ind.shape[0]): if vec_row_data[i] >0: data_res[data_res_p]=vec_row_data[i] indices_res[data_res_p]=vec_row_ind[i] data_res_p+=1 indptr_mat_+=1 indptr_mat_res[indptr_mat_res_p]=indptr_mat_ indptr_mat_res_p+=1 return data_res[:data_res_p],indices_res[:data_res_p],indptr_mat_res Maximum memory allocated in the beginning The performance and usability of this approach heavily depends on the inputs. In this approach the maximal memory is allocated (this could easily cause out of memory errors). @nb.njit(cache=True) def sparse_elementwise_maximum_nb(indices_mat,indptr_mat,data_mat,shape_mat,vec_row_ind,vec_row_data,shrink_to_fit): max_non_zero=shape_mat[0]*vec_row_data.shape[0]+data_mat.shape[0] data_res=np.empty(max_non_zero,dtype=data_mat.dtype) indices_res=np.empty(max_non_zero,dtype=np.int32) data_res_p=0 indptr_mat_res=np.empty((shape_mat[0]+1),dtype=np.int32) indptr_mat_res[0]=0 indptr_mat_res_p=1 indptr_mat_=0 for row_idx in range(shape_mat[0]): mat_row_ind=indices_mat[indptr_mat[row_idx]:indptr_mat[row_idx+1]] mat_row_data=data_mat[indptr_mat[row_idx]:indptr_mat[row_idx+1]] mat_ptr=0 vec_ptr=0 while mat_ptr<mat_row_ind.shape[0] and vec_ptr<vec_row_ind.shape[0]: ind_mat=mat_row_ind[mat_ptr] ind_vec=vec_row_ind[vec_ptr] #value for both matrix and vector is present if ind_mat==ind_vec: data_res[data_res_p]=max(mat_row_data[mat_ptr],vec_row_data[vec_ptr]) indices_res[data_res_p]=ind_mat data_res_p+=1 mat_ptr+=1 vec_ptr+=1 indptr_mat_+=1 #only value for the matrix is present vector is assumed 0 elif ind_mat<ind_vec: if mat_row_data[mat_ptr] >0: data_res[data_res_p]=mat_row_data[mat_ptr] indices_res[data_res_p]=ind_mat data_res_p+=1 indptr_mat_+=1 mat_ptr+=1 #only value for the vector is present matrix is assumed 0 else: if vec_row_data[vec_ptr] >0: data_res[data_res_p]=vec_row_data[vec_ptr] indices_res[data_res_p]=ind_vec data_res_p+=1 indptr_mat_+=1 vec_ptr+=1 for i in range(mat_ptr,mat_row_ind.shape[0]): if mat_row_data[i] >0: data_res[data_res_p]=mat_row_data[i] indices_res[data_res_p]=mat_row_ind[i] data_res_p+=1 indptr_mat_+=1 for i in range(vec_ptr,vec_row_ind.shape[0]): if vec_row_data[i] >0: data_res[data_res_p]=vec_row_data[i] indices_res[data_res_p]=vec_row_ind[i] data_res_p+=1 indptr_mat_+=1 indptr_mat_res[indptr_mat_res_p]=indptr_mat_ indptr_mat_res_p+=1 if shrink_to_fit==True: data_res=np.copy(data_res[:data_res_p]) indices_res=np.copy(indices_res[:data_res_p]) else: data_res=data_res[:data_res_p] indices_res=indices_res[:data_res_p] return data_res,indices_res,indptr_mat_res # get all needed components of the csr object and create a resulting csr object at the end def sparse_elementwise_maximum_wrap(mat,vec,shrink_to_fit=True): mat_csr=mat.tocsr() vec_csr=vec.tocsr() shape_mat=mat_csr.shape indices_mat=mat_csr.indices indptr_mat=mat_csr.indptr data_mat=mat_csr.data indices_vec=vec_csr.indices data_vec=vec_csr.data res=sparse_elementwise_maximum_nb(indices_mat,indptr_mat,data_mat,shape_mat,indices_vec,data_vec,shrink_to_fit) res=sparse.csr_matrix(res, shape=shape_mat) return res Timings Numba has a compilation overhead or some overhead to load the function from cache. Don't consider the first call if you want to get the runtime and not compilation+runtime. import numpy as np from scipy import sparse mat = sparse.csr_matrix( sparse.random(20000, 4000, density=.01, data_rvs=lambda s: np.random.randint(0, 5000, size=s)) ) vec = sparse.csr_matrix( sparse.random(1, 4000, density=.01, data_rvs=lambda s: np.random.randint(0, 5000, size=s)) ) %timeit output=sparse_elementwise_maximum(mat, vec) #for csc input 37.9 s Β± 224 ms per loop (mean Β± std. dev. of 7 runs, 1 loop each) #for csr input 10.7 s Β± 90.8 ms per loop (mean Β± std. dev. of 7 runs, 1 loop each) #Daniel F %timeit sparse_maximum(mat, vec) 164 ms Β± 1.74 ms per loop (mean Β± std. dev. of 7 runs, 10 loops each) #low level implementation (first try) %timeit res=sparse_elementwise_maximum_wrap(mat,vec) 89.7 ms Β± 2.51 ms per loop (mean Β± std. dev. of 7 runs, 1 loop each) #low level implementation (optimized, csr) %timeit res=sparse_elementwise_maximum_wrap(mat,vec) 16.5 ms Β± 122 Β΅s per loop (mean Β± std. dev. of 7 runs, 100 loops each) #low level implementation (preallocation, without copying at the end) %timeit res=sparse_elementwise_maximum_wrap(mat,vec) 16.5 ms Β± 122 Β΅s per loop (mean Β± std. dev. of 7 runs, 100 loops each) #low level implementation (preallocation, with copying at the end) %timeit res=sparse_elementwise_maximum_wrap(mat,vec) 16.5 ms Β± 122 Β΅s per loop (mean Β± std. dev. of 7 runs, 100 loops each) %timeit res=sparse_elementwise_maximum_wrap(mat,vec,shrink_to_fit=False) 14.9 ms Β± 110 Β΅s per loop (mean Β± std. dev. of 7 runs, 100 loops each) %timeit res=sparse_elementwise_maximum_wrap(mat,vec,shrink_to_fit=True) 21.7 ms Β± 399 Β΅s per loop (mean Β± std. dev. of 7 runs, 10 loops each) #For comparison, copying the result takes %%timeit np.copy(res.data) np.copy(res.indices) np.copy(res.indptr) 7.8 ms Β± 47.8 Β΅s per loop (mean Β± std. dev. of 7 runs, 100 loops each)
7
6
64,792,460
2020-11-11
https://stackoverflow.com/questions/64792460/how-to-code-a-residual-block-using-two-layers-of-a-basic-cnn-algorithm-built-wit
I have a basic CNN model's code built with tensorflow.keras library: model = Sequential() # First Layer model.add(Conv2D(64, (3,3), input_shape = (IMG_SIZE,IMG_SIZE,1))) model.add(Activation("relu")) model.add(MaxPooling2D(pool_size = (3,3))) # Second Layer model.add(Conv2D(64, (3,3))) model.add(Activation("relu")) model.add(MaxPooling2D(pool_size = (3,3))) # Third Layer model.add(Conv2D(64, (3,3))) model.add(Activation("relu")) model.add(MaxPooling2D(pool_size = (3,3))) # Fourth Layer model.add(Conv2D(64, (3,3))) model.add(Activation("relu")) model.add(MaxPooling2D(pool_size = (3,3))) # Fifth Layer model.add(Conv2D(64, (3,3))) model.add(Activation("relu")) model.add(MaxPooling2D(pool_size = (3,3))) model.add(Flatten()) # Sixth Layer model.add(Dense(64)) model.add(Activation("relu")) # Seventh Layer model.add(Dense(1)) model.add(Activation('sigmoid')) Now, I want to make a connection between the second and the fourth layer to achieve a residual block using tensorflow.keras library. So, How should I modify the code to achieve such a residual block?
Residual Block from ResNet Architecture is the following : You need to use the Keras functionnal API because Sequential models are too limited. Its implementation in Keras is : from tensorflow.keras import layers def resblock(x, kernelsize, filters): fx = layers.Conv2D(filters, kernelsize, activation='relu', padding='same')(x) fx = layers.BatchNormalization()(fx) fx = layers.Conv2D(filters, kernelsize, padding='same')(fx) out = layers.Add()([x,fx]) out = layers.ReLU()(out) out = layers.BatchNormalization()(out) return out BatchNormalisation()layer is not essential but may be a solid option to increase its accuracy. x needs also to have the same number of filters than the filters parameter.
6
16
64,863,147
2020-11-16
https://stackoverflow.com/questions/64863147/python3-reload-project-that-use-python-c-api
I have a project that I built for it a Class in C (python c-api) which I extended more in the python project. The project's purpose is to provide a test framework for a C library. The test is mainly executed for each pull request of the C library. The project needs to download form a Nexus server the relevant build of the C library, Compile the python class that is dependent on the C library, then to perform the tests. The Problem: import / reload the project modules after the compilation of C code. The Question: In my opinion, it's not that elegant to do import in each function that depends on the C library, So I tried to invoke reload, but it seems that it doesn't work, or at least not as I expecting. Code The code is super-simplified to illustrate the issue, you can check this thread history to see the previous code. main.py from utils.my_custom_py import MyCustomExtended from importlib.util import find_spec from importlib import reload from os import system, stat import weakref import sys def setup(): if system('./setup.py clean build install') > 0: raise SystemError("Failed to setup python c-api extention class") def main(): if find_spec('custom2') is None: setup() for module_name in list(sys.modules.keys()): m = sys.modules.get(module_name) if not hasattr(m, '__file__'): continue if getattr(m, '__name__', None) in [None, '__mp_main__', '__main__']: continue try: # superreload(m) # from ==> IPython.extensions # sys.modules[module_name] = reload(m) reload(m) except Exception as e: ... MyCustomExtended(1, 2, 3) print("COOL") if __name__ == "__main__": main() utils.my_custom_py.py from importlib.util import find_spec if find_spec('custom2'): import custom2 else: class custom2: class Custom: ... class MyCustomExtended(custom2.Custom): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) setup.py from distutils.core import Extension, setup custom_ext = Extension("custom2", ["src/custom.c"]) setup(name="custom2", version="1.0", ext_modules=[custom_ext]) src.custom.c is taken from: docs.python.org The error output: running clean running build running build_ext building 'custom2' extension creating build creating build/temp.linux-x86_64-3.6 creating build/temp.linux-x86_64-3.6/src x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -g -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -fPIC -I/tmp/PlayAround/.venv/include -I/usr/include/python3.6m -c src/custom.c -o build/temp.linux-x86_64-3.6/src/custom.o creating build/lib.linux-x86_64-3.6 x86_64-linux-gnu-gcc -pthread -shared -Wl,-O1 -Wl,-Bsymbolic-functions -Wl,-Bsymbolic-functions -Wl,-z,relro -Wl,-Bsymbolic-functions -Wl,-z,relro -g -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 build/temp.linux-x86_64-3.6/src/custom.o -o build/lib.linux-x86_64-3.6/custom2.cpython-36m-x86_64-linux-gnu.so running install running install_lib copying build/lib.linux-x86_64-3.6/custom2.cpython-36m-x86_64-linux-gnu.so -> /tmp/PlayAround/.venv/lib/python3.6/site-packages running install_egg_info Removing /tmp/PlayAround/.venv/lib/python3.6/site-packages/custom2-1.0.egg-info Writing /tmp/PlayAround/.venv/lib/python3.6/site-packages/custom2-1.0.egg-info Traceback (most recent call last): File "./main.py", line 38, in <module> main() File "./main.py", line 33, in main MyCustomExtended(1, 2, 3) File "/tmp/PlayAround/utils/my_custom_py.py", line 12, in __init__ super().__init__(*args, **kwargs) TypeError: object.__init__() takes no parameters main that work: from importlib.util import find_spec from importlib import reload from os import system, stat import weakref import sys def setup(): if system('./setup.py clean build install') > 0: raise SystemError("Failed to setup python c-api extention class") def main(): if find_spec('custom2') is None: setup() from utils.my_custom_py import MyCustomExtended MyCustomExtended(1, 2, 3) print("COOL") if __name__ == "__main__": main()
Finally, I found the solution by trial and error. for this example code id did the following: from utils.my_custom_py import MyCustomExtended from importlib.util import find_spec from importlib import reload from sys import modules from os import system def setup(): if system('./setup.py clean build install') > 0: raise SystemError("Failed to setup python c-api extention class") def reload_my_libs(): global MyCustomExtended reload(modules['utils']) reload(modules['utils.my_custom_py']) from utils.my_custom_py import MyCustomExtended def main(): if find_spec('custom2') is None: setup() reload_my_libs() MyCustomExtended(1, 2, 3) print("COOL") if __name__ == "__main__": main() as a result, I got: running clean running build running build_ext building 'custom2' extension creating build creating build/temp.linux-x86_64-3.6 creating build/temp.linux-x86_64-3.6/src x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -g -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -fPIC -I/tmp/PlayAround/.venv/include -I/usr/include/python3.6m -c src/custom.c -o build/temp.linux-x86_64-3.6/src/custom.o creating build/lib.linux-x86_64-3.6 x86_64-linux-gnu-gcc -pthread -shared -Wl,-O1 -Wl,-Bsymbolic-functions -Wl,-Bsymbolic-functions -Wl,-z,relro -Wl,-Bsymbolic-functions -Wl,-z,relro -g -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 build/temp.linux-x86_64-3.6/src/custom.o -o build/lib.linux-x86_64-3.6/custom2.cpython-36m-x86_64-linux-gnu.so running install running install_lib copying build/lib.linux-x86_64-3.6/custom2.cpython-36m-x86_64-linux-gnu.so -> /tmp/PlayAround/.venv/lib/python3.6/site-packages running install_egg_info Removing /tmp/PlayAround/.venv/lib/python3.6/site-packages/custom2-1.0.egg-info Writing /tmp/PlayAround/.venv/lib/python3.6/site-packages/custom2-1.0.egg-info COOL It also worked for my previous question version, which was way more complicated. regardless, thanks for the effort to help :)
6
3
64,825,967
2020-11-13
https://stackoverflow.com/questions/64825967/pygame-tic-tak-toe-logic-how-would-i-do-it
I am trying to make a tic tak toe game with pygame and I was wondering how would I do the logic here is what I have so far. VIDEO < I only have it when I click on the middle button it will display the player 2 x on the screen and then the image that is hovering over my mouse will turn into O for player 1 turn to go BUT my question is how would I do the logic like if player 1 gets 3 in a row or player 2 gets 3 across in a row I am really confused on this and I need someone to walk me throw it my tic tak toe game right now CODE import pygame,random pygame.init() # draw our window window = pygame.display.set_mode((500,540),pygame.NOFRAME) pygame.display.set_caption("Tic Tac TOE") MANUAL_CURSOR = pygame.image.load('nw.png').convert_alpha() MANUAL_CURSOR2 = pygame.image.load('nOW.png').convert_alpha() bg = pygame.image.load("ticO.png") fps = 40 clock = pygame.time.Clock() class button(): def __init__(self, color, x,y,width,height, text=''): self.color = color self.x = x self.y = y self.width = width self.height = height self.text = text self.over = False def draw(self,window,outline=None): #Call this method to draw the button on the screen if outline: pygame.draw.rect(window, outline, (self.x-2,self.y-2,self.width+4,self.height+4),0) pygame.draw.rect(window, self.color, (self.x,self.y,self.width,self.height),0) if self.text != '': font = pygame.font.SysFont('comicsans', 60) text = font.render(self.text, 1, (0,0,0)) window.blit(text, (self.x + (self.width/2 - text.get_width()/2), self.y + (self.height/2 - text.get_height()/2))) def isOver(self, pos): #Pos is the mouse position or a tuple of (x,y) coordinates if pos[0] > self.x and pos[0] < self.x + self.width: if pos[1] > self.y and pos[1] < self.y + self.height: return True return False def playSoundIfMouseIsOver(self, pos, sound): if self.isOver(pos): if not self.over: beepsound.play() self.over = True else: self.over = False class particle: def __init__(self,x): self.x = x self.partilight = pygame.image.load("noW.png") def draw(self,window): window.blit(self.partilight,(self.x)) white = (250,250,250) greenbutton2 = button((0,255,0),190,215,100,100, '') greenbutton3 = button((0,255,0),335,215,100,100, '') greenbutton4 = button((0,255,0),70,215,100,100, '') greenbutton5 = button((0,255,0),70,350,100,100, '') greenbutton6 = button((0,255,0),190,350,100,100, '') greenbutton7 = button((0,255,0),335,350,100,100, '') greenbutton8 = button((0,255,0),70,90,100,100, '') greenbutton9 = button((0,255,0),190,90,100,100, '') greenbutton10 = button((0,255,0),335,90,100,100, '') font = pygame.font.Font("fos.ttf", 60) score = 1 cointext = font.render("" + str(score), True, (255,255,255)) coinrect = cointext.get_rect() coinrect.center = ((100,50)) particles = [] pos = pygame.mouse.get_pos() def redraw(): window.fill((174, 214, 241)) window.blit(bg,(0,0)) greenbutton2.draw(window) greenbutton3.draw(window) greenbutton4.draw(window) greenbutton5.draw(window) greenbutton6.draw(window) greenbutton7.draw(window) greenbutton8.draw(window) greenbutton9.draw(window) greenbutton10.draw(window) for particle in particles: particle.draw(window) pos = pygame.mouse.get_pos() if score >= 0: window.blit(MANUAL_CURSOR, MANUAL_CURSOR.get_rect(center = pygame.mouse.get_pos())) pygame.mouse.set_visible(False) if score >= 1: window.blit(MANUAL_CURSOR2, MANUAL_CURSOR2.get_rect(center = pygame.mouse.get_pos())) if score >= 2: window.blit(MANUAL_CURSOR, MANUAL_CURSOR.get_rect(center = pygame.mouse.get_pos())) if score >= 3: window.blit(MANUAL_CURSOR2, MANUAL_CURSOR2.get_rect(center = pygame.mouse.get_pos())) if score >= 4: window.blit(MANUAL_CURSOR, MANUAL_CURSOR.get_rect(center = pygame.mouse.get_pos())) if score >= 5: window.blit(MANUAL_CURSOR2, MANUAL_CURSOR2.get_rect(center = pygame.mouse.get_pos())) if score >= 6: window.blit(MANUAL_CURSOR, MANUAL_CURSOR.get_rect(center = pygame.mouse.get_pos())) if score >= 7: window.blit(MANUAL_CURSOR2, MANUAL_CURSOR2.get_rect(center = pygame.mouse.get_pos())) if score >= 8: window.blit(MANUAL_CURSOR, MANUAL_CURSOR.get_rect(center = pygame.mouse.get_pos())) # our main loop runninggame = True while runninggame: clock.tick(fps) for event in pygame.event.get(): if event.type == pygame.QUIT: runninggame = False if event.type == pygame.MOUSEBUTTONDOWN: pos = pygame.mouse.get_pos() if greenbutton2.isOver(pos): score += 1 cointext = font.render("" + str(score), True, (255,255,255)) coinrect.center = ((100,50)) for x in range(4): particles.append(particle(MANUAL_CURSOR.get_rect(center = pygame.mouse.get_pos()))) redraw() pygame.display.update() pygame.quit() the assets I am using Please! use so when your testing out the code
Class names should normally use the CapWords convention. The name of the class should be Button rather than button. Instance Variables should be lowercase. Hence the name of an object of the typ Button should be button. Furthermore use a pygame.Rect object and collidepoint. See How do I detect if the mouse is hovering over a button? PyGame button class is not displaying the text or changing colour on hover. For Instance: class Button(): def __init__(self, color, x, y, width, height, text=''): self.color = color self.rect = pygame.Rect(x, y, width, height) self.text = text self.over = False def draw(self, window, outline=None): pygame.draw.rect(window, self.color, self.rect) if outline: pygame.draw.rect(window, outline, self.rect.inflate(-4, -4), 3) def isOver(self, pos): return self.rect.collidepoint(pos) Create a 3x3 grid of Buttons and an 3x3 grid for the Particle objects. The initial value of the particle grid is None: button_grid = [[Button((0, 128, 0), 70+i*120, 90+j*120, 100, 100, '') for i in range(3)] for j in range(3)] particle_grid = [[None for i in range(3)] for j in range(3)] Draw the grids in redraw def redraw(): window.fill((32, 32, 32)) for i in range(len(button_grid)): for j in range(len(button_grid[0])): b = button_grid[i][j] p = particle_grid[i][j] is_over = p == None and b.isOver(pygame.mouse.get_pos()) b.draw(window, (255, 255, 255) if is_over else None) if p: p.draw(window) The particle image ahs to be an argument of the constructor of the class Particle. Add a method to the class to set the position: class Particle: def __init__(self, image): self.pos = (0, 0) self.image = image def set_pos(self, pos): self.pos = pos def draw(self, window): window.blit(self.image, self.image.get_rect(center = self.pos)) Create a method that creates a new particle dependent on the current turn: def new_particle(turn): image = MANUAL_CURSOR if turn % 2 == 0 else MANUAL_CURSOR2 return Particle(image) Add a variable for the current turn and create an initial Particle object: turn = 0 particle = new_particle(turn) Set the position of the Particle object using the current mouse position and draw the object in the application loop: runninggame = True while runninggame: # [...] particle.set_pos(pygame.mouse.get_pos()) redraw() particle.draw(window) pygame.display.update() When you click a field, check that the corresponding field in the particle grid is empty. Copy the center of the field to the position of the particle. Assign the particle to the grid. Increment the turn and create a new particle: while runninggame: clock.tick(fps) for event in pygame.event.get(): if event.type == pygame.QUIT: runninggame = False if event.type == pygame.MOUSEBUTTONDOWN: for i in range(len(button_grid)): for j in range(len(button_grid[0])): b = button_grid[i][j] if b.isOver(event.pos) and particle_grid[i][j] == None: particle.set_pos(b.rect.center) particle_grid[i][j] = particle turn += 1 particle = new_particle(turn) Add a score for both players: score1 = 0 score2 = 0 Add a function that evaluates whether there are 3 identical images in a row: def has_won(pg): pg = particle_grid for i in range(3): if pg[i][0] and pg[i][1] and pg[i][2]: if pg[i][0].image == pg[i][1].image == pg[i][2].image: return pg[i][0].image for j in range(3): if pg[0][j] and pg[1][j] and pg[2][j]: if pg[0][j].image == pg[1][j].image == pg[2][j].image: return pg[0][j].image if pg[0][0] and pg[1][1] and pg[2][2]: if pg[0][0].image == pg[1][1].image == pg[2][2].image: return pg[0][0].image if pg[0][2] and pg[1][1] and pg[2][0]: if pg[0][2].image == pg[1][1].image == pg[2][0].image: return pg[0][2].image return None Test to see if a player has won after clicking a button. When a player wins, increase the appropriate score and reset the particle grid: while runninggame: clock.tick(fps) for event in pygame.event.get(): # [...] if event.type == pygame.MOUSEBUTTONDOWN: [...] won = has_won(particle_grid) if won: if won == MANUAL_CURSOR: score1 += 1 else: score2 += 1 print(score1, score2) particle_grid = [[None for i in range(3)] for j in range(3)] Add a function that evaluates whether the grid is full: def grid_is_full(pg): return all(cell for row in pg for cell in row) Clear the grid when it's full: while runninggame: clock.tick(fps) for event in pygame.event.get(): # [...] if event.type == pygame.MOUSEBUTTONDOWN: [...] if grid_is_full(particle_grid): particle_grid = [[None for i in range(3)] for j in range(3)] Minimal example: import pygame,random pygame.init() class Button(): def __init__(self, color, x, y, width, height, text=''): self.color = color self.rect = pygame.Rect(x, y, width, height) self.text = text self.over = False def draw(self, window, outline=None): pygame.draw.rect(window, self.color, self.rect) if outline: pygame.draw.rect(window, outline, self.rect.inflate(-4, -4), 3) def isOver(self, pos): return self.rect.collidepoint(pos) class Particle: def __init__(self, image): self.pos = (0, 0) self.image = image def set_pos(self, pos): self.pos = pos def draw(self, window): window.blit(self.image, self.image.get_rect(center = self.pos)) def new_particle(turn): image = MANUAL_CURSOR if turn % 2 == 0 else MANUAL_CURSOR2 return Particle(image) def has_won(pg): pg = particle_grid for i in range(3): if pg[i][0] and pg[i][1] and pg[i][2]: if pg[i][0].image == pg[i][1].image == pg[i][2].image: return pg[i][0].image for j in range(3): if pg[0][j] and pg[1][j] and pg[2][j]: if pg[0][j].image == pg[1][j].image == pg[2][j].image: return pg[0][j].image if pg[0][0] and pg[1][1] and pg[2][2]: if pg[0][0].image == pg[1][1].image == pg[2][2].image: return pg[0][0].image if pg[0][2] and pg[1][1] and pg[2][0]: if pg[0][2].image == pg[1][1].image == pg[2][0].image: return pg[0][2].image return None def grid_is_full(pg): return all(cell for row in pg for cell in row) def redraw(): window.fill((32, 32, 32)) for i in range(len(button_grid)): for j in range(len(button_grid[0])): b = button_grid[i][j] p = particle_grid[i][j] is_over = p == None and b.isOver(pygame.mouse.get_pos()) b.draw(window, (255, 255, 255) if is_over else None) if p: p.draw(window) window = pygame.display.set_mode((500,540)) pygame.display.set_caption("Tic Tac TOE") fps = 40 clock = pygame.time.Clock() font = pygame.font.SysFont(None, 50) #MANUAL_CURSOR = pygame.image.load('nw.png').convert_alpha() #MANUAL_CURSOR2 = pygame.image.load('nOW.png').convert_alpha() size = (60, 60) MANUAL_CURSOR = pygame.Surface(size) MANUAL_CURSOR.fill((127, 127, 127)) pygame.draw.line(MANUAL_CURSOR, (0, 127, 255), (5, 5), (size[0]-5, size[1]-5), 3) pygame.draw.line(MANUAL_CURSOR, (0, 127, 255), (size[0]-5, 5), (5, size[1]-5), 3) MANUAL_CURSOR2 = pygame.Surface(size) MANUAL_CURSOR2.fill((127, 127, 127)) pygame.draw.circle(MANUAL_CURSOR2, (127, 0, 255), (size[0]//2, size[1]//2), size[0]//2-5, 3) score1 = 0 score2 = 0 button_grid = [[Button((0, 128, 0), 70+i*120, 90+j*120, 100, 100, '') for i in range(3)] for j in range(3)] particle_grid = [[None for i in range(3)] for j in range(3)] turn = 0 particle = new_particle(turn) runninggame = True while runninggame: clock.tick(fps) for event in pygame.event.get(): if event.type == pygame.QUIT: runninggame = False if event.type == pygame.MOUSEBUTTONDOWN: for i in range(len(button_grid)): for j in range(len(button_grid[0])): b = button_grid[i][j] if b.isOver(event.pos) and particle_grid[i][j] == None: particle.set_pos(b.rect.center) particle_grid[i][j] = particle turn += 1 particle = new_particle(turn) won = has_won(particle_grid) if won: if won == MANUAL_CURSOR: score1 += 1 else: score2 += 1 print(score1, score2) particle_grid = [[None for i in range(3)] for j in range(3)] if grid_is_full(particle_grid): particle_grid = [[None for i in range(3)] for j in range(3)] particle.set_pos(pygame.mouse.get_pos()) scoreText1 = font.render("Player 1 Score: " + str(score1), True, (128, 0, 0)) scoreText2 = font.render("Player 2 Score: " + str(score2), True, (128, 0, 0)) redraw() window.blit(scoreText1, (70, 30)) window.blit(scoreText2, (70, 460)) particle.draw(window) pygame.display.update() pygame.quit() exit()
8
10
64,874,129
2020-11-17
https://stackoverflow.com/questions/64874129/alpha-blending-two-images-with-opencv-and-or-numpy
I would like to add a semi-transparent rectangle filled with a solid colour to an already loaded semi-transparent PNG. Here's an example input image I am using: That image is loaded with a standard cv2.IMREAD_UNCHANGED flag so that alpha channel is perfectly preserved. That input image is stored in the image variable. Here's my code that I have so far: # get image dimensions imgHeight, imgWidth = image.shape[:2] # create empty overlay layer with 4 channels overlay = np.zeros((imgHeight, imgWidth, 4), dtype = "uint8") # draw semi-transparent red rectangle overlay[200:300, 0:imgWidth] = (0, 0, 255, 200) # extract alpha channel from overlay alpha = cv2.split(overlay)[3] # compute mask mask = (np.multiply(alpha, 1.0 / 255))[:, :, np.newaxis] # blend input image and overlay output = cv2.convertScaleAbs(overlay * mask + image * (1 - mask)) And here's the result that I am getting: At first glance it looks acceptable. We have our input image with a semi-transparent rectangle in the middle. However, upon closer inspection, we can observe strange behaviour when mixing alpha channels (marked with arrows): It seems that alpha is not blended at all which results in original image pixels being only fully opaque or fully transparent. Perhaps my method of blending transparent PNG with semi-transparent shapes is far from ideal. As a side note, I did try the cv2.addWeighted method but that yielded even worse results. I would like the solution to be limited to OpenCV and/or Numpy. Any help would be greatly appreciated.
As unlut pointed out this is indeed a duplicate. Just in case someone stumbles on it, Mark Setchell's answer works pretty well: # get image dimensions imgHeight, imgWidth = image.shape[:2] # create empty overlay layer with 4 channels overlay = np.zeros((imgHeight, imgWidth, 4), dtype = "uint8") # draw semi-transparent red rectangle overlay[200:300, 0:imgWidth] = (0, 0, 255, 200) # Extract the RGB channels srcRGB = image[...,:3] dstRGB = overlay[...,:3] # Extract the alpha channels and normalise to range 0..1 srcA = image[...,3]/255.0 dstA = overlay[...,3]/255.0 # Work out resultant alpha channel outA = srcA + dstA*(1-srcA) # Work out resultant RGB outRGB = (srcRGB*srcA[...,np.newaxis] + dstRGB*dstA[...,np.newaxis]*(1-srcA[...,np.newaxis])) / outA[...,np.newaxis] # Merge RGB and alpha (scaled back up to 0..255) back into single image outRGBA = np.dstack((outRGB,outA*255)).astype(np.uint8) plt.imshow(outRGBA)
12
10
64,837,917
2020-11-14
https://stackoverflow.com/questions/64837917/build-a-basic-cube-with-numpy
I was wondering if numpy could be used to build the most basic cube model where all cross-combinations and their computed value are stored. Let's take the following example of data: AUTHOR BOOK YEAR SALES Shakespeare Hamlet 2000 104.2 Shakespeare Hamlet 2001 99.0 Shakespeare Romeo 2000 27.0 Shakespeare Romeo 2001 19.0 Dante Inferno 2000 11.6 Dante Inferno 2001 12.6 And to be able to build something like: YEAR TOTAL AUTHOR BOOK 2000 2001 (ALL) (ALL) 142.8 130.6 273.4 Shakespeare (ALL) 131.2 118.0 249.2 Dante (ALL) 11.6 12.6 24.2 Shakespeare Hamlet 104.2 99.0 203.2 Shakespeare Romeo 27.0 19.0 46.0 Dante Inferno 11.6 12.6 24.2 I'm hoping that the usage of using something like meshgrid might get me 75% there. Basically, I'd like to see if it's possible to build a structure of all pre-computed values with numpy (not pandas) to build a structure so that I could retrieve the above result of all possible combination. For the sake of simplicity, let's only consider the SUM as the only possible calculation. Perhaps this is a roundable way of asking, but could numpy be the backbone of doing this, or do I need to use something else? And finally, if not possible in numpy how might this be stored in a MDA?
I think numpy record arrays can be used for this task, below is my solution based on record arrays. class rec_array(): def __init__(self,author=None,book=None,year=None,sales=None): self.dtype = [('author','<U20'), ('book','<U20'),('year','<U20'),('sales',float)] self.rec_array = np.rec.fromarrays((author,book,year,sales),dtype=self.dtype) def add_record(self,author,book,year,sales): new_rec = np.rec.fromarrays((author,book,year,sales),dtype=self.dtype) if not self.rec_array.shape == (): self.rec_array = np.hstack((self.rec_array,new_rec)) else: self.rec_array = new_rec def get_view(self,conditions): """ conditions: A list of conditions, for example [["author",<,"Shakespeare"],["year","<=","2000"]] """ mask = np.ones(self.rec_array.shape[0]).astype(bool) for item in conditions: field,op,target = item field_op = "self.rec_array['%s'] %s '%s'" % (field,op,target) mask &= eval(field_op) selected_sales = self.rec_array['sales'][mask] return np.sum(selected_sales) Based on this rec_array, given the data author = 4*["Shakespeare"]+ 2*["Dante"] book = 2*["Hamlet"] + 2*["Romeo"] + 2*["Inferno"] year = 3*["2000", "2001"] sales = [104.2, 99.0, 27.0, 19.0, 11.6, 12.6] we create an instance test = rec_array() test.add_record(author,book,year,sales) If, for example, you want the sales of Shakespeare's Romeo, you can simply do this test.get_view([["author","==","Shakespeare"],["book","==","Romeo"]]) the output is 46.0 or, you can also do test.get_view([["author","==","Shakespeare"],["year","<=","2000"]]) the output is 131.2
18
9
64,834,321
2020-11-14
https://stackoverflow.com/questions/64834321/how-can-i-arbitarily-rotate-rearrange-etc-pdf-pages-in-python
I have an input.pdf which is "normal" (a number of pages all the same orientation and direction) and I want to create a new pdf which can arbitrarily rearrange the input pages For example: I only need rotation and scaling. Each input page will be present in its entirety as some component of the output. I don't need to fiddle with text, colours, cropping, etc. In pseudocode these are all the features I need: in = open_pdf("input.pdf") out = new_pdf () p = createpage (size) p.add (in.get_page(123), origin=(0,100), scale=(0.5,0.5), angle=degrees(270)) p.add (...) out.add(p) out.save("output.pdf") Can I do this in Python? If not Python, some other linux-friendly scripting language?
With PyPDF2, you can write a script to accomplish this task that looks very similar to your pseudocode. Here’s some sample code, using a nightly build of the Homotopy Type Theory textbook as input: #!/usr/bin/env python3 from PyPDF2 import PdfFileReader, PdfFileWriter # matrix helper class class AfMatrix: """ A matrix of a 2D affine transform. """ __slots__ = ('__a', '__b', '__c', '__d', '__e', '__f') def __init__(self, a, b, c, d, e, f): self.__a = float(a) self.__b = float(b) self.__c = float(c) self.__d = float(d) self.__e = float(e) self.__f = float(f) def __iter__(self): yield self.__a yield self.__b yield self.__c yield self.__d yield self.__e yield self.__f def __hash__(self): return hash(tuple(self)) def __eq__(self, other): return tuple(self) == tuple(other) @classmethod def compose(cls, *what): a, b, c, d, e, f = ( 1, 0, 0, 1, 0, 0, ) for rhs in what: A, B, C, D, E, F = rhs a, b, c, d, e, f = ( a * A + b * C, a * B + b * D, c * A + d * C, c * B + d * D, e * A + f * C + E, e * B + f * D + F, ) return cls( a, b, c, d, e, f ) @classmethod def translate(cls, x=0, y=0): return cls( 1, 0, 0, 1, x, y ) def __takes_origin(func): def translated_func(cls, *args, origin=(0, 0), **kwargs): if origin == (0, 0): return func(cls, *args, **kwargs) return cls.compose( cls.translate(-origin[0], -origin[1]), func(cls, *args, **kwargs), cls.translate(origin[0], origin[1]) ) return translated_func @classmethod @__takes_origin def shear(cls, x=1, y=1): return cls( x, 0, 0, y, 0, 0 ) @classmethod @__takes_origin def rotate(cls, angle): from math import cos, sin, radians angle = radians(angle) C = cos(angle) S = sin(angle) return cls( C, S, -S, C, 0, 0 ) # reader = PdfFileReader('hott-online-1272-ga50f9bd.pdf') writer = PdfFileWriter() ipgs = [reader.getPage(i) for i in range(8)] # page 1 writer.addPage(ipgs[0]) # page 2 opg1src = ipgs[2:5] opg1 = writer.addBlankPage(0, 0) yaccum = 0 for ipg in opg1src: opg1.mergeTransformedPage(ipg, AfMatrix.compose( AfMatrix.rotate(90), AfMatrix.translate(x=ipg.mediaBox.getHeight(), y=yaccum) ), expand=True) yaccum += ipg.mediaBox.getWidth() # page 3 opg2 = writer.addBlankPage( ipgs[6].mediaBox.getWidth(), ipgs[6].mediaBox.getHeight() ) opg2.mergeTransformedPage(ipgs[6], ( AfMatrix.shear(x=1/3) ), expand=True) opg2.mergeTransformedPage(ipgs[7], AfMatrix.compose( AfMatrix.translate( x=-opg2.mediaBox.getWidth() / 8, y=-opg2.mediaBox.getHeight() / 8 ), AfMatrix.rotate(-15, origin=(opg2.mediaBox.getWidth(), 0)), AfMatrix.shear(x=0.75, y=0.75, origin=(opg2.mediaBox.getWidth(), 0)) ), expand=False) # output with open('sample.pdf', 'wb') as ostream: writer.write(ostream) And here’s the output: Note on transformation matrices: in PDF and PostScript, the X coordinate grows rightwards and the Y coordinate grows upwards, like in mathematical custom (and unlike the custom in computer graphics, where Y grows downwards). Unlike mathematical custom, points are treated as row-vectors instead of column-vectors, and therefore appear on the left-hand side of matrix multiplication. This means matrix transformations compose left-to-right instead of right-to-left: the leftmost operation is applied first. Also, to make rotations by positive angles come out as counterclockwise (again like mathematical custom), the rotation matrix above appears transposed to its usual form. When transforming pages, beware of content that falls off the page boundary on the original page; on the new page, it might actually render. (I have not found a solution to this yet.)
11
8
64,867,031
2020-11-16
https://stackoverflow.com/questions/64867031/tensorflow-error-tensorflow-core-framework-op-kernel-cc1767-op-requires-faile
I am trying to train an object detection algorithm with samples that I have labeled using Label-img. My images have dimensions of 1100 x 1100 pixels. The algorithm I am using is the Faster R-CNN Inception ResNet V2 1024x1024, found on the TensorFlow 2 Detection Model Zoo. The specs of my operation are as follows: TensorFlow 2.3.1 Python 3.8.6 GPU: NVIDIA GEFORCE RTX 2060 (laptop has 16 GB RAM and 6 processing cores) CUDA: 10.1 cuDNN: 7.6 Anaconda 3 command prompt The .config file is as follows: # Faster R-CNN with Inception Resnet v2 (no atrous) # Sync-trained on COCO (with 8 GPUs) with batch size 16 (800x1333 resolution) # Initialized from Imagenet classification checkpoint # TF2-Compatible, *Not* TPU-Compatible # # Achieves 39.6 mAP on COCO model { faster_rcnn { num_classes: 1 image_resizer { keep_aspect_ratio_resizer { min_dimension: 800 max_dimension: 1333 pad_to_max_dimension: true } } feature_extractor { type: 'faster_rcnn_inception_resnet_v2_keras' } first_stage_anchor_generator { grid_anchor_generator { scales: [0.25, 0.5, 1.0, 2.0] aspect_ratios: [0.5, 1.0, 2.0] height_stride: 16 width_stride: 16 } } first_stage_box_predictor_conv_hyperparams { op: CONV regularizer { l2_regularizer { weight: 0.0 } } initializer { truncated_normal_initializer { stddev: 0.01 } } } first_stage_nms_score_threshold: 0.0 first_stage_nms_iou_threshold: 0.7 first_stage_max_proposals: 300 first_stage_localization_loss_weight: 2.0 first_stage_objectness_loss_weight: 1.0 initial_crop_size: 17 maxpool_kernel_size: 1 maxpool_stride: 1 second_stage_box_predictor { mask_rcnn_box_predictor { use_dropout: false dropout_keep_probability: 1.0 fc_hyperparams { op: FC regularizer { l2_regularizer { weight: 0.0 } } initializer { variance_scaling_initializer { factor: 1.0 uniform: true mode: FAN_AVG } } } } } second_stage_post_processing { batch_non_max_suppression { score_threshold: 0.0 iou_threshold: 0.6 max_detections_per_class: 100 max_total_detections: 100 } score_converter: SOFTMAX } second_stage_localization_loss_weight: 2.0 second_stage_classification_loss_weight: 1.0 } } train_config: { batch_size: 1 num_steps: 200000 optimizer { momentum_optimizer: { learning_rate: { cosine_decay_learning_rate { learning_rate_base: 0.008 total_steps: 200000 warmup_learning_rate: 0.0 warmup_steps: 5000 } } momentum_optimizer_value: 0.9 } use_moving_average: false } gradient_clipping_by_norm: 10.0 fine_tune_checkpoint_version: V2 fine_tune_checkpoint: "pre-trained-models/faster_rcnn_inception_resnet_v2_1024x1024_coco17_tpu-8/checkpoint/ckpt-0" fine_tune_checkpoint_type: "detection" data_augmentation_options { random_horizontal_flip { } } data_augmentation_options { random_adjust_hue { } } data_augmentation_options { random_adjust_contrast { } } data_augmentation_options { random_adjust_saturation { } } data_augmentation_options { random_square_crop_by_scale { scale_min: 0.6 scale_max: 1.3 } } } train_input_reader: { label_map_path: "annotations/label_map.pbtxt" tf_record_input_reader { input_path: "annotations/train.record" } } eval_config: { metrics_set: "coco_detection_metrics" use_moving_averages: false batch_size: 1; } eval_input_reader: { label_map_path: "annotations/label_map.pbtxt" shuffle: false num_epochs: 1 tf_record_input_reader { input_path: "annotations/test.record" } } The following error is thrown after about 5 minutes of running: 2020-11-16 16:52:14.415133: W tensorflow/core/framework/op_kernel.cc:1767] OP_REQUIRES failed at conv_ops.cc:539 : Resource exhausted: OOM when allocating tensor with shape[64,288,9,9] and type float on /job:localhost/replica:0/task:0/device:GPU:0 by allocator GPU_0_bfc Traceback (most recent call last): File "model_main_tf2.py", line 113, in <module> tf.compat.v1.app.run() File "C:\Users\user\anaconda3\envs\object_detection_api\lib\site-packages\tensorflow\python\platform\app.py", line 40, in run _run(main=main, argv=argv, flags_parser=_parse_flags_tolerate_undef) File "C:\Users\user\anaconda3\envs\object_detection_api\lib\site-packages\absl\app.py", line 303, in run _run_main(main, args) File "C:\Users\user\anaconda3\envs\object_detection_api\lib\site-packages\absl\app.py", line 251, in _run_main sys.exit(main(argv)) File "model_main_tf2.py", line 104, in main model_lib_v2.train_loop( File "C:\Users\user\anaconda3\envs\object_detection_api\lib\site-packages\object_detection\model_lib_v2.py", line 639, in train_loop loss = _dist_train_step(train_input_iter) File "C:\Users\user\anaconda3\envs\object_detection_api\lib\site-packages\tensorflow\python\eager\def_function.py", line 780, in __call__ result = self._call(*args, **kwds) File "C:\Users\user\anaconda3\envs\object_detection_api\lib\site-packages\tensorflow\python\eager\def_function.py", line 840, in _call return self._stateless_fn(*args, **kwds) File "C:\Users\user\anaconda3\envs\object_detection_api\lib\site-packages\tensorflow\python\eager\function.py", line 2829, in __call__ return graph_function._filtered_call(args, kwargs) # pylint: disable=protected-access File "C:\Users\user\anaconda3\envs\object_detection_api\lib\site-packages\tensorflow\python\eager\function.py", line 1843, in _filtered_call return self._call_flat( File "C:\Users\user\anaconda3\envs\object_detection_api\lib\site-packages\tensorflow\python\eager\function.py", line 1923, in _call_flat return self._build_call_outputs(self._inference_function.call( File "C:\Users\user\anaconda3\envs\object_detection_api\lib\site-packages\tensorflow\python\eager\function.py", line 545, in call outputs = execute.execute( File "C:\Users\user\anaconda3\envs\object_detection_api\lib\site-packages\tensorflow\python\eager\execute.py", line 59, in quick_execute tensors = pywrap_tfe.TFE_Py_Execute(ctx._handle, device_name, op_name, tensorflow.python.framework.errors_impl.ResourceExhaustedError: 2 root error(s) found. (0) Resource exhausted: OOM when allocating tensor with shape[64,256,17,17] and type float on /job:localhost/replica:0/task:0/device:GPU:0 by allocator GPU_0_bfc [[node functional_3/conv2d_160/Conv2D (defined at \site-packages\object_detection\meta_architectures\faster_rcnn_meta_arch.py:1149) ]] Hint: If you want to see a list of allocated tensors when OOM happens, add report_tensor_allocations_upon_oom to RunOptions for current allocation info. [[Identity_1/_432]] Hint: If you want to see a list of allocated tensors when OOM happens, add report_tensor_allocations_upon_oom to RunOptions for current allocation info. (1) Resource exhausted: OOM when allocating tensor with shape[64,256,17,17] and type float on /job:localhost/replica:0/task:0/device:GPU:0 by allocator GPU_0_bfc [[node functional_3/conv2d_160/Conv2D (defined at \site-packages\object_detection\meta_architectures\faster_rcnn_meta_arch.py:1149) ]] Hint: If you want to see a list of allocated tensors when OOM happens, add report_tensor_allocations_upon_oom to RunOptions for current allocation info. 0 successful operations. 0 derived errors ignored. [Op:__inference__dist_train_step_79248] Errors may have originated from an input operation. Input Source operations connected to node functional_3/conv2d_160/Conv2D: MaxPool2D/MaxPool (defined at \site-packages\object_detection\meta_architectures\faster_rcnn_meta_arch.py:1973) Input Source operations connected to node functional_3/conv2d_160/Conv2D: MaxPool2D/MaxPool (defined at \site-packages\object_detection\meta_architectures\faster_rcnn_meta_arch.py:1973) Function call stack: _dist_train_step -> _dist_train_step A common solution to this problem is to reduce your batch size, but I have already reduced it to 1. Is the issue that I am out of memory for processing, or is there something else that could be done to fix this problem? Note: Here is an output that was given right before the exception was thrown: 2020-11-16 16:52:14.409101: I tensorflow/core/common_runtime/bfc_allocator.cc:1046] Stats: Limit: 4817616896 InUse: 4809875456 MaxInUse: 4817131776 NumAllocs: 11104 MaxAllocSize: 4129325056 Reserved: 0 PeakReserved: 0 LargestFreeBlock: 0 2020-11-16 16:52:14.413310: W tensorflow/core/common_runtime/bfc_allocator.cc:439] ****************************************************************************************************
Take a look on this thread ( By your post I think you are read it): Resource exhausted: OOM when allocating tensor only on gpu The two possible solutions are to change config.gpu_options.per_process_gpu_memory_fraction to a greater number. The other solutions were to reinstall cuda. You can use nvidia docker. Then you can switch between versions quickly. https://github.com/NVIDIA/nvidia-docker You can change cuda versions and see if the error persists.
6
2
64,881,855
2020-11-17
https://stackoverflow.com/questions/64881855/kernel-and-recurrent-kernel-in-keras-lstms
I'm trying to draw in my mind the structure of the LSTMs and I don't understand what are the Kernel and Recurrent Kernel. According to this post in LSTMs section, the Kernel it's the four matrices that are multiplied by the inputs and Recurrent Kernel it's the four matrices that are multiplied by the hidden state, but, what are those 4 matrices in this diagram? Are the gates? I was testing with this app how the unit variable of the code below affect the kernel, recurrent kernel and bias: model = Sequential() model.add(LSTM(unit = 1, input_shape=(1, look_back))) with look_back = 1 it returns me that: with unit = 2 it returns me this With unit = 3 this Testing with this values I could deducted this expressions but I don't know how this works by inside. What does mean <1x(4u)> or <ux(4u)>? u = units
The kernels are basically the weights handled by the LSTM cell units = neurons, like the classic multilayer perceptron It is not shown in your diagram, but the input is a vector X with 1 or more values, and each value is sent in a neuron with its own weight w (the which we are going to learn with backpropagation) The four matrices are these (expressed as Wf, Wi, Wc, Wo): When you add a neuron, you are adding other 4 weights\kernel So for your input vector X you have four matrix. And therefore 1 * 4 * units = kernel Regarding the recurrent_kernel here you can find the answer. Basically in keras input and hidden state are not concatenated like in the example diagrams (W[ht-1, t]) but they are split and handled with other four matrices called U: Because you have a hidden state x neuron, the weights U (all four U) are: units * (4 * units) = recurrent kernel ht-1 comes in a recurrent way from all your neurons. Like in a multilayer perceptron, each output of a neuron goes in all the next recurrent layer neurons source: http://colah.github.io/posts/2015-08-Understanding-LSTMs/
6
3
64,883,998
2020-11-17
https://stackoverflow.com/questions/64883998/pytorch-dataloader-shows-odd-behavior-with-string-dataset
I'm working on an NLP problem and am using PyTorch. For some reason, my dataloader is returning malformed batches. I have input data that comprises sentences and integer labels. The sentences can either a list of sentences or a list of list of tokens. I will later convert the tokens to integers in a downstream component. list_labels = [ 0, 1, 0] # List of sentences. list_sentences = [ 'the movie is terrible', 'The Film was great.', 'It was just awful.'] # Or list of list of tokens. list_sentences = [['the', 'movie', 'is', 'terrible'], ['The', 'Film', 'was', 'great.'], ['It', 'was', 'just', 'awful.']] I created the following custom dataset: import torch from torch.utils.data import DataLoader, Dataset class MyDataset(torch.utils.data.Dataset): def __init__(self, sentences, labels): self.sentences = sentences self.labels = labels def __getitem__(self, i): result = {} result['sentences'] = self.sentences[i] result['label'] = self.labels[i] return result def __len__(self): return len(self.labels) When I provide input in the form of a list of sentences, the dataloader correctly returns batches of complete sentences. Note that batch_size=2: list_sentences = [ 'the movie is terrible', 'The Film was great.', 'It was just awful.'] list_labels = [ 0, 1, 0] dataset = MyDataset(list_sentences, list_labels) dataloader = DataLoader(dataset, batch_size=2) batch = next(iter(dataloader)) print(batch) # {'sentences': ['the movie is terrible', 'The Film was great.'], <-- Great! 2 sentences in batch! # 'label': tensor([0, 1])} The batch correctly contains two sentences and two labels because batch_size=2. However, when I instead enter the sentences as pre-tokenized list of list of token, I get weird results: list_sentences = [['the', 'movie', 'is', 'terrible'], ['The', 'Film', 'was', 'great.'], ['It', 'was', 'just', 'awful.']] list_labels = [ 0, 1, 0] dataset = MyDataset(list_sentences, list_labels) dataloader = DataLoader(dataset, batch_size=2) batch = next(iter(dataloader)) print(batch) # {'sentences': [('the', 'The'), ('movie', 'Film'), ('is', 'was'), ('terrible', 'great.')], <-- WHAT? # 'label': tensor([0, 1])} Note that this batch's sentences is one single list with tuples of word pairs. I was expecting sentences to be a list of two lists, like this: {'sentences': [['the', 'movie', 'is', 'terrible'], ['The', 'Film', 'was', 'great.'] What is going on?
This behavior is because the default collate_fn does the following when it has to collate lists (which is the case for ['sentences']): # [...] elif isinstance(elem, container_abcs.Sequence): # check to make sure that the elements in batch have consistent size it = iter(batch) elem_size = len(next(it)) if not all(len(elem) == elem_size for elem in it): raise RuntimeError('each element in list of batch should be of equal size') transposed = zip(*batch) return [default_collate(samples) for samples in transposed] The "problem" happens because, in the last two lines, it'll recursively call zip(*batch) while the batch is a container_abcs.Sequence (and list is), and zip behaves like this. As you can see: batch = [['the', 'movie', 'is', 'terrible'], ['The', 'Film', 'was', 'great.']] list(zip(*batch)) # [('the', 'The'), ('movie', 'Film'), ('is', 'was'), ('terrible', 'great.')] I don't see a workaround in your case, except implementing a new collator and passing it to the DataLoader(..., collate_fn=mycollator). For instance, a simple ugly one could be: def mycollator(batch): assert all('sentences' in x for x in batch) assert all('label' in x for x in batch) return { 'sentences': [x['sentences'] for x in batch], 'label': torch.tensor([x['label'] for x in batch]) }
7
5
64,882,432
2020-11-17
https://stackoverflow.com/questions/64882432/sklearn-preprocessing-standardscaler-valueerror-expected-2d-array-got-1d-array
I'm trying to work through a tutorial at http://www.semspirit.com/artificial-intelligence/machine-learning/regression/support-vector-regression/support-vector-regression-in-python/ but there's no csv file included, so I'm using my own data. Here's the code so far: import numpy as np import pandas as pd from matplotlib import cm from matplotlib import pyplot as plt from mpl_toolkits.mplot3d import Axes3D from scipy import stats # Here's where I import my data; there's no csv file included in the tutorial import quasar_functions as qf dataset, datasetname, mags = qf.loaddata('sdss12') S = np.asarray(dataset[mags]) t = np.asarray(dataset['z']) t.reshape(-1,1) # Feature scaling from sklearn.preprocessing import StandardScaler as scale sc_S = scale() sc_t = scale() S2 = sc_S.fit_transform(S) t2 = sc_t.fit_transform(t) The last line throws an error: ValueError: Expected 2D array, got 1D array instead: array=[4.17974 2.06468 5.46959 ... 0.41398 0.3672 1.9235 ]. Reshape your data either using array.reshape(-1, 1) if your data has a single feature or array.reshape(1, -1) if it contains a single sample. and yes, I've reshaped my target array t with t.reshape(-1,1) as shown here, here, here and here, but to no avail. Am I reshaping correctly? Here's all my variables:
I am guessing you have a dataframe, so you need to reassign the variable t = t.reshape(-1,1): import pandas as pd dataset = pd.DataFrame(np.random.normal(2,1,(100,4)),columns=['z','x1','x2','x3']) mags = ['x1','x2','x3'] S = np.asarray(dataset[mags]) t = np.asarray(dataset['z']) t = t.reshape(-1,1) from sklearn.preprocessing import StandardScaler as scale sc_S = scale() sc_t = scale() S2 = sc_S.fit_transform(S) t2 = sc_t.fit_transform(t) To check it works: np.mean(t2) 2.4646951146678477e-16
6
5
64,861,610
2020-11-16
https://stackoverflow.com/questions/64861610/easily-check-if-table-exists-with-python-sqlalchemy-on-an-sql-database
Hello I am using sqlalchemy and pandas to process some data and then save everything to a table in an sql database. I am trying to find a quick easy and standardized way to check if a table exists in a database based on a table name. I have found the has_table() function but no working examples. Does anyone has something like give "engine connection" & "table name"-> return true or false if table exists
With SQLAlchemy 1.4+ you can call has_table by using an inspect object, like so: import sqlalchemy as sa # … engine = sa.create_engine(connection_uri) insp = sa.inspect(engine) print(insp.has_table("team", schema="dbo")) # True (or False, as the case may be) For earlier versions of SQLAlchemy, see the other answer here.
12
26
64,866,338
2020-11-16
https://stackoverflow.com/questions/64866338/is-it-right-that-i-need-to-deploy-my-lambda-in-order-to-test-it
I'm writing some Python code on AWS Lambda. I haven't used AWS for a few months and I noticed that when I hit the TEST button the test no longer runs on the latest code that I've entered into the Lambda editor, even when I save the code. After some playing around I've found I need to press the DEPLOY button first, then my test runs fine. Is this right? Surely I should be able to test my code before deploying it. The official AWS documentation doesn't specify that deploying is necessry to run a test.
Yes, The Deploy button is updating the code, The Test button just Invoke your lambda with a test Event (That can be configured)
13
11
64,873,588
2020-11-17
https://stackoverflow.com/questions/64873588/typevar-in-class-init-type-hinting
I am trying to use a TypeVar to indicate an init parameter as a certain type. But I am doing it wrong, or it might not even be possible. from typing import TypeVar T=TypeVar("T") class TestClass: def __init__(self,value:T): self._value=value a = TestClass(value=10) b = TestClass(value="abc") reveal_type(a._value) reveal_type(b._value) I was hoping the reveal type of a._value would have been int and b._value to have been string. But they are both revealed as 'T`-1' Any help or insight appreciated! [EDIT] A little more expanded example. The BaseClass will be overridden and the actual type hint is provided by the overriding class. from typing import TypeVar T=TypeVar("T") class BaseClass: def __init__(self,value): self._value = value class Class1(BaseClass): def __init__(self,value:str): super().__init__(value) class Class2(BaseClass): def __init__(self,value:int): super().__init__(value) a = Class1("A value") b = Class2(10) reveal_type(a._value) reveal_type(b._value)
By default, using a TypeVar restricts its scope only to the method/function in which it is used as an annotation. In order to scope a TypeVar to the instance and all methods/attributes, declare the class as Generic. from typing import TypeVar, Generic T=TypeVar("T") class BaseClass(Generic[T]): # Scope of `T` is the class: def __init__(self, value: T): # Providing some `T` on `__init__` self._value = value # defines the class' `T` This allows declaring subclasses either as generic or as concrete. class Class1(BaseClass[str]): # "is a" BaseClass where `T = str` pass # No need to repeat ``__init__`` class ClassT(BaseClass[T]): # "is a" BaseClass where `T = T'` @property def value(self) -> T: return self._value reveal_type(Class1("Hello World")._value) # Revealed type is 'builtins.str*' reveal_type(Class1(b"Uh Oh!")._value) # error: Argument 1 to "Class1" has incompatible type "bytes"; expected "str" reveal_type(ClassT(42).value) # Revealed type is 'builtins.int*'
6
9
64,823,332
2020-11-13
https://stackoverflow.com/questions/64823332/gradients-returning-none-in-huggingface-module
I want to get the gradient of an embedding layer from a pytorch/huggingface model. Here's a minimal working example: from transformers import pipeline nlp = pipeline("zero-shot-classification", model="facebook/bart-large-mnli") responses = ["I'm having a great day!!"] hypothesis_template = 'This person feels {}' candidate_labels = ['happy', 'sad'] nlp(responses, candidate_labels, hypothesis_template=hypothesis_template) I can extract the logits just fine, inputs = nlp._parse_and_tokenize(responses, candidate_labels, hypothesis_template) predictions = nlp.model(**inputs, return_dict=True, output_hidden_states=True) predictions['logits'] and the model returns a layer I'm interested in. I tried to retain the gradient and backprop with respect to a single logit I'm interested in: layer = predictions['encoder_hidden_states'][0] layer.retain_grad() predictions['logits'][0][2].backward(retain_graph=True) However, layer.grad == None no matter what I try. The other named parameters of the model have their gradients computed, so I'm not sure what I'm doing wrong. How do I get the grad of the encoder_hidden_states?
I was also very surprised of this issue. Although I have never used the library I went down and did some debugging and found out that the issue is coming from the library transformers. The problem is comming from from this line : encoder_states = tuple(hidden_state.transpose(0, 1) for hidden_state in encoder_states) If you comment it out, you will get the gradient just with some dimensions transposed. This issue is related to the fact that Pytorch Autograd does not do very well on inplace operations as mentioned here. So to recap the solution is to comment line 382 in modeling_bart.py. You will get the gradient with this shape T x B x C instead of B x T x C, but you can reshape it as you want later.
6
6
64,863,439
2020-11-16
https://stackoverflow.com/questions/64863439/tensorflow-with-gpu-how-to-see-tensorflow-is-using-the-gpu
Trying to install tensorflow to work with the GPU. Some documentation I see says tensorflow comes out of box with gpu support when detected. If so, what command can I use to see tensorflow is using my GPU? I have seen other documentation saying you need tensorflow-gpu installed. I have tried both but do not see how my GPU is being used?
Go to command line and run Python The following example lists the number of visible GPUs on the host. Docs import tensorflow as tf devices = tf.config.list_physical_devices('GPU') print(len(devices)) For CUDA Docs import tensorflow as tf tf.test.is_built_with_cuda() Returns whether TensorFlow was built with CUDA (GPU) support. Docs You can check with following function too but it's deprecated** import tensorflow as tf tf.test.is_gpu_available() Both returns True if your GPU is available
6
8
64,838,511
2020-11-14
https://stackoverflow.com/questions/64838511/opencv-imshow-crashes-python-launcher-on-macos-11-0-1-big-sur
I'm trying to run some old code from gaussian filter when I find out that python launcher gets stuck trying to do the imshow function. I tried: Used Matplotlib to display a graph to see if the python launcher was the problem but no, graph showed up fine. Remove process in between just to have the image read and display in fear that something in my code was breaking the launcher but no success. Reinstalled opencv-python but no success. Also saw one question like this in the google search but OP deleted it. Has anyone encounter this issue or has any fix for this? Example code: import cv2 as cv filename = 'chessboard.png' img = cv.imread(filename) cv.imshow('dst',img) cv.waitKey(0) OS: MacOS Big Sur (11.0.1)
I resolved the issue with below steps: Install the anaconda. Install the libraries needed. Run the script, there is an error appeared as below: You might be loading two sets of Qt binaries into the same process. Check that all plugins are compiled against the right Qt binaries. Export DYLD_PRINT_LIBRARIES=1 and check that only one set of binaries are being loaded. then I installed two libraies: pip install opencv-python opencv-python-headless Retry run the script, the image can be shown on the left top of the monitor.
10
10
64,853,113
2020-11-16
https://stackoverflow.com/questions/64853113/how-to-integrate-flutter-app-with-python-code
I want to make a Flutter app that uses a Python module. What are the options to integrate Python code, how can I marshal data between the 2 runtimes, can I make a standalone app that includes Python module that doesn't depend on local Python installation? My context: I have written Python code that can mark attendance using face recognition. It basically writes the (Name, Registration no. and entry time) to a .csv file of those whose faces match with the data(images of my friends and mine) that I've provided. I would like to create a desktop and/or mobile app that utilises that existing code.
I suggest you to use or convert your Python code as a Back-end code and Flutter code as Front End code. After that, your Flutter application can call the API via HTTP Requests and get data that it wants. Further reading about my suggestion: Build a REST API with Python HTTP Requests Front-End Back-End : Introduction
10
14
64,851,261
2020-11-16
https://stackoverflow.com/questions/64851261/why-is-this-memoized-euler14-implementation-so-much-slower-in-raku-than-python
I was recently playing with problem 14 of the Euler project: which number in the range 1..1_000_000 produces the longest Collatz sequence? I'm aware of the issue of having to memoize to get reasonable times, and the following piece of Python code returns an answer relatively quickly using that technique (memoize to a dict): #!/usr/bin/env python L = 1_000_000 cllens={1:1} cltz = lambda n: 3*n + 1 if n%2 else n//2 def cllen(n): if n not in cllens: cllens[n] = cllen(cltz(n)) + 1 return cllens[n] maxn=1 for i in range(1,L+1): ln=cllen(i) if (ln > cllens[maxn]): maxn=i print(maxn) (adapted from here; I prefer this version that doesn't use max, because I might want to fiddle with it to return the longest 10 sequences, etc.). I have tried to translate it to Raku staying as semantically close as I could: #!/usr/bin/env perl6 use v6; my $L=1_000_000; my %cllens = (1 => 1); sub cltz($n) { ($n %% 2) ?? ($n div 2) !! (3*$n+1) } sub cllen($n) { (! %cllens{$n}) && (%cllens{$n} = 1+cllen($n.&cltz)); %cllens{$n}; } my $maxn=1; for (1..$L) { my $ln = cllen($_); ($ln > %cllens{$maxn}) && ($maxn = $_) } say $maxn Here are the sorts of times I am consistently getting running these: $ time <python script> 837799 real 0m1.244s user 0m1.179s sys 0m0.064s On the other hand, in Raku: $ time <raku script> 837799 real 0m21.828s user 0m21.677s sys 0m0.228s Question(s) Am I mistranslating between the two, or is the difference an irreconcilable matter of starting up a VM, etc.? Are there clever tweaks / idioms I can apply to the Raku code to speed it up considerably past this? Aside Naturally, it's not so much about this specific Euler project problem; I'm more broadly interested in whether there are any magical speedup arcana appropriate to Raku I am not aware of.
I think the majority of the extra time is because Raku has type checks, and they aren't getting removed by the runtime type specializer. Or if they are getting removed it is after a significant amount of time. Generally the way to optimize Raku code is first to run it with the profiler: $ raku --profile test.raku Of course that fails with a Segfault with this code, so we can't use it. My guess would be that much of the time is related to using the Hash. If it was implemented, using native ints for the key and value might have helped: my int %cllens{int} = (1 => 1); Then declaring the functions as using native-sized ints could be a bigger win. (Currently this is a minor improvement at best.) sub cltz ( int $n --> int ) {…} sub cllen( int $n --> int ) {…} for (1..$L) -> int $_ {…} Of course like I said native hashes aren't implemented, so that is pure speculation. You could try to use the multi-process abilities of Raku, but there may be issues with the shared %cllens variable. The problem could also be because of recursion. (Combined with the aforementioned type checks.) If you rewrote cllen so that it used a loop instead of recursion that might help. Note: The closest to n not in cllens is probably %cllens{$n}:!exists. Though that might be slower than just checking that the value is not zero. Also cellen is kinda terrible. I would have written it more like this: sub cllen($n) { %cllens{$n} //= cllen(cltz($n)) + 1 }
10
7
64,850,321
2020-11-15
https://stackoverflow.com/questions/64850321/windows-keeps-crashing-when-trying-to-install-pytorch-via-pip
I am currently trying to install PyTorch (using the installation commands posted on PyTorch.org for pip) and when I run the command, my computer completely freezes. I tried this multiple times with the same result. I had to restart the computer a few times as well. On my current try, I put "-v" when trying to install and the pip seems to be stuck on "Looking up in the cache". I do not know how to proceed. As I mentioned, I've already tried this method multiple times. It worked the first time but did not install PyTorch as it gave me an error for not using "--user". Are there any solutions to this? EDIT: I did want to add that I have Python 3.8.6 (64bit)
After troubling shooting and a lot of restart, it seems like the issue came from when pip was trying to load a pre-downloaded file. Essentially, the first time I ran the installation command, pip downloaded files for pytorch but did not install pytorch due to some user privilege issue. The fix is to add --no-cache-dir in the pip install command. This will override the cache (pre-downloaded files) and download the files all over again. For me specifically, I also needed to add --user. In other words, the command went from pip install torch===1.7.0+cu110 torchvision===0.8.1+cu110 torchaudio===0.7.0 -f https://download.pytorch.org/whl/torch_stable.html to pip --no-cache-dir install torch===1.7.0+cu110 torchvision===0.8.1+cu110 torchaudio===0.7.0 -f https://download.pytorch.org/whl/torch_stable.html --user
13
25
64,841,082
2020-11-15
https://stackoverflow.com/questions/64841082/segmentation-fault-11-python-after-upgrading-to-os-big-sur
Yesterday, my program was working perfectly fine. However, today it stopped working. I think that it may have something to do with the latest Mac OS update, as I had just installed it today. My testing code is shown below import matplotlib.pyplot as plt import numpy as np print("ehllow") zeroes = np.zeros((10,10)) plt.imshow(zeroes) plt.show() Everything is going fine until I get to plt.show(). I had tried removing it, and the program ran smoothly, but once I added it back in I got the error Segmentation fault: 11 and then it shows a python crash screen I have python version 3.7.6 64 bit for Mac.
Ok. Just for anyone wondering Just uninstalling and reinstalling the packages that were giving the error worked for me pip uninstall matplotlib pip install matplotlib
15
35
64,837,148
2020-11-14
https://stackoverflow.com/questions/64837148/how-to-create-a-co-occurence-matrix-of-product-orders-in-python
Let's assume we have the following dataframe that includes customer orders (order_id) and the products that the individual order contained (product_id): import pandas as pd df = pd.DataFrame({'order_id' : [1, 1, 1, 1, 2, 2, 2, 3, 3, 3, 3], 'product_id' : [365, 48750, 3333, 9877, 48750, 32001, 3333, 3333, 365, 11202, 365]}) print(df) order_id product_id 0 1 365 1 1 48750 2 1 3333 3 1 9877 4 2 48750 5 2 32001 6 2 3333 7 3 3333 8 3 365 9 3 11202 10 3 365 It would be interesting to know how often product pairs appeared together in the same basket. How does one create a co-occurence matrix in python that looks like this: 365 48750 3333 9877 32001 11202 365 1 1 2 1 0 1 48750 1 0 2 1 1 0 3333 2 2 0 1 1 1 9877 1 1 1 0 0 0 32001 0 1 1 0 0 0 11202 1 0 1 0 0 0 I would be very thankful for your help!
We start by grouping the df by order_id, and within each group calculate all possible pairs. Note we sort first by product_id so the same pairs in different groups are always in the same order import itertools all_pairs = [] for _, group in df.sort_values('product_id').groupby('order_id'): all_pairs += list(itertools.combinations(group['product_id'],2)) all_pairs we get a list of all pairs from all orders [('3333', '365'), ('3333', '48750'), ('3333', '9877'), ('365', '48750'), ('365', '9877'), ('48750', '9877'), ('32001', '3333'), ('32001', '48750'), ('3333', '48750'), ('11202', '3333'), ('11202', '365'), ('11202', '365'), ('3333', '365'), ('3333', '365'), ('365', '365')] Now we count duplicates from collections import Counter count_dict = dict(Counter(all_pairs)) count_dict so we get the count of each pair, basically what you are after {('3333', '365'): 3, ('3333', '48750'): 2, ('3333', '9877'): 1, ('365', '48750'): 1, ('365', '9877'): 1, ('48750', '9877'): 1, ('32001', '3333'): 1, ('32001', '48750'): 1, ('11202', '3333'): 1, ('11202', '365'): 2, ('365', '365'): 1} Putting this back into a cross-product table is a bit of work, the key bit is spliitng the tuples into columns by calling .apply(pd.Series) and eventually moving one of the columns to the column names via unstack: (pd.DataFrame.from_dict(count_dict, orient='index') .reset_index(0) .set_index(0)['index'] .apply(pd.Series) .rename(columns = {0:'pid1',1:'pid2'}) .reset_index() .rename(columns = {0:'count'}) .set_index(['pid1', 'pid2'] ) .unstack() .fillna(0)) this produces a 'compact' form of the table you are after that only includes products that appeared in at least one pair count pid2 3333 365 48750 9877 pid1 11202 1.0 2.0 0.0 0.0 32001 1.0 0.0 1.0 0.0 3333 0.0 3.0 2.0 1.0 365 0.0 1.0 1.0 1.0 48750 0.0 0.0 0.0 1.0 UPDATE Here is a rather simplified version of the above, following various discussions in the comments import numpy as np import pandas as pd from collections import Counter # we start as in the original solution but use permutations not combinations all_pairs = [] for _, group in df.sort_values('product_id').groupby('order_id'): all_pairs += list(itertools.permutations(group['product_id'],2)) count_dict = dict(Counter(all_pairs)) # We create permutations for _all_ product_ids ... note we use unique() but also product(..) to allow for (365,265) combinations total_pairs = list(itertools.product(df['product_id'].unique(),repeat = 2)) # pull out first and second elements separately pid1 = [p[0] for p in total_pairs] pid2 = [p[1] for p in total_pairs] # and get the count for those permutations that exist from count_dict. Use 0 # for those that do not count = [count_dict.get(p,0) for p in total_pairs] # Now a bit of dataFrame magic df_cross = pd.DataFrame({'pid1':pid1, 'pid2':pid2, 'count':count}) df_cross.set_index(['pid1','pid2']).unstack() and we are done. df_cross below count pid2 11202 32001 3333 365 48750 9877 pid1 11202 0 0 1 2 0 0 32001 0 0 1 0 1 0 3333 1 1 0 3 2 1 365 2 0 3 2 1 1 48750 0 1 2 1 0 1 9877 0 0 1 1 1 0
9
5
64,833,580
2020-11-14
https://stackoverflow.com/questions/64833580/django-annotate-whether-field-is-null
I want to annotate a datetime field to know whether it is null. Something like: Table.objects.all().annotate(date_is_null=XXX(YYY)).values(date_is_null, .....) What do I need to replace XXX(YYY) to check if the field is null? (I'm using .values().annotate() later for a Group By, so it must be in annotate first)
You can use an ExpressionWrapper to convert a Q object to an annotated BooleanField: from django.db.models import BooleanField, ExpressionWrapper, Q Table.objects.annotate( date_is_null=ExpressionWrapper( Q(date=None), output_field=BooleanField() ) ) Here Q(date=None) is thus the condition. If the DateTimeField has a different name, you should alter the condition accordingly. You can make the condition more verbose with: from django.db.models import BooleanField, ExpressionWrapper, Q Table.objects.annotate( date_is_null=ExpressionWrapper( Q(date__isnull=True), output_field=BooleanField() ) )
12
25
64,831,017
2020-11-14
https://stackoverflow.com/questions/64831017/how-do-i-get-the-discord-py-intents-to-work
I am trying to make a bot that welcomes people to the server that it's in and all of the code works except for the on_member_join event because it utilizes the new intents. I googled on how to work with the intents and tried everything but it still isn't working. intents = discord.Intents.default() intents.members = True client = commands.Bot(command_prefix=',', intents = intents) How do I fix this?
intents = discord.Intents.default() intents.members = True client = commands.Bot(command_prefix=',', intents=intents) You also have to enable privileged intents in the developer portal A Primer Gateway to Intents
14
19
64,826,735
2020-11-13
https://stackoverflow.com/questions/64826735/pandas-write-dataframe-in-fixed-width-formatted-lines-to-a-file
Have a huge pandas dataframe (df) like this: id date a b c 0 0023 201110132120 -30 -45 7 1 0023 201110132130 -30 11 9111 2 0023 201110132140 -24 44 345 3 0023 201110132150 -19 223 11 4 0023 201110132200 -23 -3456 -1250 I need to write this dataframe to a file with special fixed-width for each field. For this i used numpy, f.e.: np.savetxt('out.txt', df.values, fmt='%+4s %+12s %+5s %+5s %+6s') That work's fine. Only lost header in this case. Is there a workaround? I tested it also with pandas to_string function: df.to_string() But it is so slow. Why? Are there other options?
One option is to abuse header option in savetxt: formats = '%+4s %+12s %+5s %+5s %+6s' headers = [format(str(x),y.replace('%+','>')) for x, y in zip(df.columns,formats.split())] np.savetxt('out.txt', df.values, fmt=formats, header=' '.join(headers), comments='')
6
2
64,821,441
2020-11-13
https://stackoverflow.com/questions/64821441/collecting-package-metadata-repodata-json-killed
I have a fresh EC2 Ubuntu 18.04 I have installed anaconda as it it in the official guide https://docs.anaconda.com/anaconda/install/linux/ apt-get install libgl1-mesa-glx libegl1-mesa libxrandr2 libxrandr2 libxss1 libxcursor1 libxcomposite1 libasound2 libxi6 libxtst6 64 bit installation But then I have YML files that I have used to create conda environments before on other EC2s and when I ma tiring to setup a new environment with it ubuntu@ip........:~$ conda env create --name my_env_name --file=my_env_file.yml it it gives me the following error Collecting package metadata (repodata.json): / Killed Now I am trying with the following guide
Adding more RAM helps I switched from 0.5 GB to 8GB RAM than the problem disappears
10
13
64,784,834
2020-11-11
https://stackoverflow.com/questions/64784834/draw-grid-line-on-secondaryaxis-matplotlib
The question I am trying to draw grid lines from the ticks of my SecondaryAxis with ax2.grid(color=color,linestyle='--') nothing shows up on the figure, I believe I am in the same situation as for Format SecondaryAxis ticklabels Matplotlib, aren't I ? However, does anybody have a workaround for the issue without reversing the scales ? I mean by reversing the scale is to have the percentages scale on the main axis and the normal scale on the secondary axis. The full code import matplotlib.pyplot as plt import numpy as np #generate dummy load duration curve dur=2500 load = np.random.normal(60,30,dur+1) load[::-1].sort() x=range(0,dur+1) perticks = np.linspace(0,1,11) xticks = perticks*dur # get yticks from xticks yticks = np.interp(xticks, range(0,dur+1), load) print(yticks) # create figure object with axe object fig, ax1 = plt.subplots(figsize=(16, 8)) ax1.plot(x, load) #create second axis ax2 = ax1.secondary_yaxis('right') # label and color of the secondaryaxis perlabels = ['0%', '10%', '20%', '30%', '40%', '50%', '60%', '70%', '80%', '90%', '100%'] color ='tab:blue' ax2.set_yticks(yticks) ax2.set_yticklabels(labels=perlabels) ax2.tick_params(axis='y', color=color, labelcolor=color) # draw grid lines on the secondaryaxis ax2.grid(color=color,linestyle='--') # do the same for x axis ax3 = ax1.secondary_xaxis('top') ax3.set_xticks(xticks) ax3.set_xticklabels(labels=perlabels) ax3.tick_params(axis='x', color=color, labelcolor=color) ax3.grid(color=color,linestyle='--') The output
I did some digging on this topic, and opened an issue on GitHub. Here's what I found out: The SecondaryAxis is "quite new thing", added in matplotlib 3.1.0. (May 2019). Even the v.3.3.3 docs say that the secondary_xaxis() method is experimental. The SecondaryAxis inherits from _AxesBase, which is an "implementation detail". It is not supposed (as of v.3.3.3) to work as Axes object, and the SecondaryAxis.grid() is not supposed to draw anything (like _AxesBase.grid() does). Although, I agree it is misleading that there is a non-working method. Therefore, at the time of writing, .grid() is only assumed to work on primaxy axes. Making the blue axis primary Since .grid() only works on non-secondary axis, you make the primary axis blue, and move it to top & right. Code # Take the x and y-ticks for transfering them to secondary axis xticks_orig = ax1.get_xticks() yticks_orig = ax1.get_yticks() # Make the primary axis blue since we want to draw grid on it ax1.xaxis.tick_top() ax1.yaxis.tick_right() ax1.set_xticks(xticks) ax1.set_yticks(yticks) ax1.set_yticklabels(labels=perlabels) ax1.set_xticklabels(labels=perlabels) ax1.tick_params(axis="both", color=color, labelcolor=color) ax1.grid(color=color, linestyle="--") # Draw the black secondary axis ax2 = ax1.secondary_yaxis("left") ax3 = ax1.secondary_xaxis("bottom") ax2.set_yticks(yticks_orig) ax3.set_xticks(xticks_orig) Adding grid lines manually You could add the grid lines also manually, like this xlim = ax1.get_xlim() for y in ax2.get_yticks(): ax1.plot(xlim, (y, y), ls="--", color=color, lw=0.5) ax1.set_xlim(xlim) ylim = ax1.get_ylim() for x in ax3.get_xticks(): ax1.plot((x, x), ylim, ls="--", color=color, lw=0.5) ax1.set_ylim(ylim) The output would look like this: The difference here is now we draw lines on the figure which look like the grid lines.
6
6
64,811,350
2020-11-12
https://stackoverflow.com/questions/64811350/is-setuptools-always-installed-in-python-by-default
Is setuptools always installed with Python? I would like to invoke setuptools at runtime outside of a setup.py script. In other words, should I include setuptools inside my package's requirements.txt and setup.py's install_requires list? Background I have noticed when creating a new virtual environment (with Python 3.7.9) that both pip and setuptools are installed by default: python -m venv venv source ./venv/bin/activate pip list Package Version ---------- ------- pip 20.1.1 setuptools 47.1.0 This is documented here: Creating Virtual Environments: venv is available by default in Python 3.3 and later, and installs pip and setuptools into created virtual environments in Python 3.4 and later. Even in a vanilla version of Python 3.7.6 (installed via pyenv), the packages installed by default are both pip and setuptools. Research Should setuptools be included in setup_requires in Python? Informs that setuptools should not be included in setup_requires, but does not talk about it being included in package requirements for runtime use.
TL;DR Formally, No. Usually, Yes. the setuptools is not part of the python vanilla codebase, hence not a vanilla modules. python.org installers or mac homebrew will install it for you, but if someone compile the python by himself or install it on some linux distribution he may not get it and will need to install it by himself.
8
6
64,803,895
2020-11-12
https://stackoverflow.com/questions/64803895/how-can-i-count-the-number-of-cases-in-recursive-functions
def calcPath(trace_map, x, y): n = len(trace_map) count = 0 if x > n - 1 or y > n - 1: pass elif x < n and y < n: if x + trace_map[x][y] == (n - 1) and y == (n - 1): count += 1 elif x == (n - 1) and y + trace_map[x][y] == (n - 1): count += 1 else: calcPath(trace_map, x + trace_map[x][y], y) calcPath(trace_map, x, y + trace_map[x][y]) return count if __name__ == "__main__": trace_map = [ [1, 2, 9, 4, 9], [9, 9, 9, 9, 9], [9, 3, 9, 9, 2], [9, 9, 9, 9, 9], [9, 9, 9, 1, 0], ] print(calcPath(trace_map, 0, 0)) trace_map = [[1, 1, 1], [1, 1, 2], [1, 2, 0]] print(calcPath(trace_map, 0, 0)) I want to count the existing routes of the given maze. (anyway, the problem itself is not that important) Problem is, I tried to count the number of cases that fit the conditions within the recursive functions. These are two conditions that have to be counted. if x + trace_map[x][y] == (n - 1) and y == (n - 1): if x == (n - 1) and y + trace_map[x][y] == (n - 1): I tried counting the conditions like this count = 0 if condition = True: count +=1 But since I'm using recursive functions, if I declare count = 0 in the function, the count value stays 0. Shortly, I just want to keep the counter unaffected by the recursive function.
One of the ways to solve this is by adding the count you get from each recursive function's return. When you call the recursive function, take the count that is returned and add it to the count variable in the current scope. For example: def calcPath(trace_map, x, y): n = len(trace_map) count = 0 if x > n - 1 or y > n - 1: pass elif x < n and y < n: if x + trace_map[x][y] == (n - 1) and y == (n - 1): count += 1 elif x == (n - 1) and y + trace_map[x][y] == (n - 1): count += 1 else: count += calcPath(trace_map, x + trace_map[x][y], y) count += calcPath(trace_map, x, y + trace_map[x][y]) return count An alternative solution would be to create a global variable and reset it to 0 every time the function is called (although I don't recommend this since it requires ceremony everytime the function is called). That might look something like this: count = 0 # Global variable def calcPath(trace_map, x, y): global count n = len(trace_map) if x > n - 1 or y > n - 1: pass elif x < n and y < n: if x + trace_map[x][y] == (n - 1) and y == (n - 1): count += 1 elif x == (n - 1) and y + trace_map[x][y] == (n - 1): count += 1 else: calcPath(trace_map, x + trace_map[x][y], y) calcPath(trace_map, x, y + trace_map[x][y]) if __name__ == "__main__": trace_map = [ [1, 2, 9, 4, 9], [9, 9, 9, 9, 9], [9, 3, 9, 9, 2], [9, 9, 9, 9, 9], [9, 9, 9, 1, 0], ] print(calcPath(trace_map, 0, 0)) # Use count in some way count = 0 # Reset the count trace_map = [[1, 1, 1], [1, 1, 2], [1, 2, 0]] print(calcPath(trace_map, 0, 0))
7
6
64,800,003
2020-11-12
https://stackoverflow.com/questions/64800003/seaborn-confusion-matrix-heatmap-2-color-schemes-correct-diagonal-vs-wrong-re
Background In a confusion matrix, the diagonal represents the cases that the predicted label matches the correct label. So the diagonal is good, while all other cells are bad. To clarify what is good and what is bad in a CM for non-experts, I want to give the diagonal a different color than the rest. I want to achieve this with Python & Seaborn. Basically I'm trying to achieve what this question does in R (ggplot2 Heatmap 2 Different Color Schemes - Confusion Matrix: Matches in Different Color Scheme than Missclassifications) Normal Seaborn Confusion Matrix with heatmap import numpy as np import seaborn as sns cf_matrix = np.array([[50, 2, 38], [7, 43, 32], [9, 4, 76]]) sns.heatmap(cf_matrix, annot=True, cmap='Blues') # cmap='OrRd' Which results in this image: Goal I would like to color the non-diagonal cells with e.g. cmap='OrRd'. So I imagine there would be 2 colorbars, 1 blue for the diagonal and 1 for the other cells. Preferably the values of both colorbars match (so both e.g. 0-70 and not 0-70 and 0-40). How would I approach this? The following is not made with code, but with photo editing software:
You can use mask= in the call to heatmap() to choose which cells to show. Using two different masks for the diagonal and the off_diagonal cells, you can get the desired output: import numpy as np import seaborn as sns cf_matrix = np.array([[50, 2, 38], [7, 43, 32], [9, 4, 76]]) vmin = np.min(cf_matrix) vmax = np.max(cf_matrix) off_diag_mask = np.eye(*cf_matrix.shape, dtype=bool) fig = plt.figure() sns.heatmap(cf_matrix, annot=True, mask=~off_diag_mask, cmap='Blues', vmin=vmin, vmax=vmax) sns.heatmap(cf_matrix, annot=True, mask=off_diag_mask, cmap='OrRd', vmin=vmin, vmax=vmax, cbar_kws=dict(ticks=[])) If you want to get fancy, you can create the axes using GridSpec to have a better layout: import numpy as np import seaborn as sns fig = plt.figure() gs0 = matplotlib.gridspec.GridSpec(1,2, width_ratios=[20,2], hspace=0.05) gs00 = matplotlib.gridspec.GridSpecFromSubplotSpec(1,2, subplot_spec=gs0[1], hspace=0) ax = fig.add_subplot(gs0[0]) cax1 = fig.add_subplot(gs00[0]) cax2 = fig.add_subplot(gs00[1]) sns.heatmap(cf_matrix, annot=True, mask=~off_diag_mask, cmap='Blues', vmin=vmin, vmax=vmax, ax=ax, cbar_ax=cax2) sns.heatmap(cf_matrix, annot=True, mask=off_diag_mask, cmap='OrRd', vmin=vmin, vmax=vmax, ax=ax, cbar_ax=cax1, cbar_kws=dict(ticks=[]))
10
16
64,797,192
2020-11-12
https://stackoverflow.com/questions/64797192/how-to-do-multiple-queries
I want to do a multiple queries. Here is my data frame: data = {'Name':['Penny','Ben','Benny','Mark','Ben1','Ben2','Ben3'], 'Eng':[5,1,4,3,1,2,3], 'Math':[1,5,3,2,2,2,3], 'Physics':[2,5,3,1,1,2,3], 'Sports':[4,5,2,3,1,2,3], 'Total':[12,16,12,9,5,8,12], 'Group':['A','A','A','A','A','B','B']} df1=pd.DataFrame(data, columns=['Name','Eng','Math','Physics','Sports','Total','Group']) df1 I have 3 queries: Group A or B Math > Eng Name starts with 'B' I tried to do it one by one df1[df1.Name.str.startswith('B')] df1.query('Math > Eng') df1[df1.Group == 'A'] #I cannot run the code with df1[df1.Group == 'A' or 'B'] Then, I tried to merge those queries df1.query("'Math > Eng' & 'df1[df1.Name.str.startswith('B')]' & 'df1[df1.Group == 'A']") TokenError: ('EOF in multi-line statement', (2, 0)) I also tried to pass str.startswith() into df.query() df1.query("df1.Name.str.startswith('B')") UndefinedVariableError: name 'df1' is not defined I have tried lots of ways but no one works. How can I put those queries together?
The long way to solve this – and the one with the most transparency, so best for beginners – is to create a boolean column for each filter. Then sum those columns as one final filter: df1['filter_1'] = df1['Group'].isin(['A','B']) df1['filter_2'] = df1['Math'] > df1['Eng'] df1['filter_3'] = df1['Name'].str.startswith('B') # If all are true df1['filter_final'] = df1[['filter_1', 'filter_2', 'filter_3']].all(axis=1) You can certainly combine these steps into one: mask = ((df1['Group'].isin(['A','B'])) & (df1['Math'] > df1['Eng']) & (df1['Name'].str.startswith('B')) ) df['filter_final'] = mask Lastly, selecting rows which satisfy your filter is done as follows: df_filtered = df1[df1['filter_final']] This selects rows from df1 where final_filter == True
8
8
64,793,581
2020-11-11
https://stackoverflow.com/questions/64793581/python-selenium-get-page-title
from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.firefox.options import Options options = Options() options.headless = True driver = webdriver.Firefox(options=options) driver.get("https://hapondo.qa/rent/doha/apartments/studio") element = WebDriverWait(driver, 10).until( EC.presence_of_element_located((By.XPATH, "/html/head/title")) ) print(element.text) Unable to get page title under headless option? Tried to wait and even tried driver.title
You need to take care of a couple of things as follows: To retrieve the Page Title instead of using a xpath you need to use driver.title The hapondo website contains JavaScript enabled elements. Solution To extract the Page Title you need to induce WebDriverWait for the title_contains() and you can use either of the following Locator Strategy: Code Block: from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC options = webdriver.ChromeOptions() options.add_argument('--headless') options.add_argument('--window-size=1920,1080') driver = webdriver.Chrome(options=options, executable_path=r'C:\WebDrivers\chromedriver.exe') driver.get('https://hapondo.qa/rent/doha/apartments/studio') WebDriverWait(driver, 10).until(EC.title_contains("hapondo")) print(driver.title) Console Output: Studio Apartments for rent in Doha | hapondo References You can find a couple of relevant detailed discussions in: How to make selenium wait before getting contents from the actual website which loads after the landing page through IEDriverServer and IE
10
8
64,782,008
2020-11-11
https://stackoverflow.com/questions/64782008/how-to-use-fastapi-depends-for-endpoint-route-in-separate-file
I have an Websocket endpoint defined in separate file, like: from starlette.endpoints import WebSocketEndpoint from connection_service import ConnectionService class WSEndpoint(WebSocketEndpoint): """Handles Websocket connections""" async def on_connect(self, websocket: WebSocket, connectionService: ConnectionService = Depends(ConnectionService)): """Handles new connection""" self.connectionService = connectionService ... and in the main.py I register endpoint as: from fastapi import FastAPI from starlette.routing import WebSocketRoute from ws_endpoint import WSEndpoint app = FastAPI(routes=[ WebSocketRoute("/ws", WSEndpoint) ]) But Depends for my endpoint is never resolved. Is there a way to make it work? Plus, what is even the purpose of this mechanism in FastAPI? Cannot we just use local/global variables?
TL;DR The documents seem to hint that you can only use Depends for request functions. Explanation I found a related issue #2057 in the FastAPI repo and it seems the Depends(...) only works with the requests and not anything else. I confirmed this by, from fastapi import Depends, FastAPI app = FastAPI() async def foo_func(): return "This is from foo" async def test_depends(foo: str = Depends(foo_func)): return foo @app.get("/") async def read_items(): depends_result = await test_depends() return depends_result In this case, the dependency didn't get resolved. Coming to your case, you can resolve the dependency something like this, from starlette.endpoints import WebSocketEndpoint from connection_service import ConnectionService class WSEndpoint(WebSocketEndpoint): async def on_connect( self, websocket: WebSocket, connectionService=None ): if connectionService is None: connectionService = ConnectionService() # calling the depend function self.connectionService = connectionService
6
5
64,780,009
2020-11-11
https://stackoverflow.com/questions/64780009/typeerror-cannot-index-by-location-index-with-a-non-integer-key
I am trying to re-write this code, which was written a while ago. It has multiple chuncks, hence, I separated it into smaller pieces and re-write step by step. For instance, converting .ix to iloc, etc. This chunk gives me an error: #Loop through all rows, skip the user column, and fill with similarity scores for i in range(0,len(data_sims.index)): for j in range(1,len(data_sims.columns)): user = data_sims.index[i] product = data_sims.columns[j] if data.iloc[i][j] == 1: data_sims.iloc[i][j] = 0 else: product_top_names = data_neighbours.iloc[product][1:10] product_top_sims = data_ibs.iloc[product].order(ascending=False)[1:10] user_purchases = data_germany.iloc[user,product_top_names] data_sims.iloc[i][j] = getScore(user_purchases,product_top_sims) Get an error TypeError: Cannot index by location index with a non-integer key I guess there is something here, which requires updating, but cannot find what exactly. I do not think it is about data. It is just about updating the code. Appreciate any tips!
I'm not exactly sure what that piece of code is supposed to do (though it seems like there may be a more efficient way of doing it). Also, it looks like you are referencing j outside the j loop. However, the specific error you're getting is mostly likely related to: product_top_names = data_neighbours.iloc[product][1:10] iloc only works with integers, and I guess product is a string. If that's the case, something like product_top_names = data_neighbours[product].iloc[1:10] should get rid of the error (assuming product is the name of a column).
8
4
64,685,527
2020-11-4
https://stackoverflow.com/questions/64685527/pip-install-with-all-extras
How does one pip install with all extras? I'm aware that doing something like: pip install -e .[docs,tests,others] is an option. But, is it possible to do something like: pip install -e .[all] This question is similar to setup.py/setup.cfg install all extras. However, the answer there requires that the setup.cfg file be edited. Is it possible to do it without modifying setup.py or setup.cfg?
pip has a --report= option which we can use: --report <file> Generate a JSON file describing what pip did to install the provided requirements. Can be used in combination with --dry-run and --ignore-installed to 'resolve' the requirements. When - is used as file name it writes to stdout. When writing to stdout, please combine with the --quiet option to avoid mixing pip logging output with JSON output. So let's install the package once without extras and with the --report=- option to get JSON on standard output. Pipe the JSON to jq, digging out the extras defined for the package. Then install the package again with all extras if any exist. (You could also --dry-run the first step to postpone actual installation until the last step). EXTRAS=$(\ pip install --quiet --report=- --editable="." \ | jq --raw-output '.install[0].metadata.provides_extra|join(",")' 2> /dev/null \ ) [ -n "${EXTRAS}" ] && pip install --editable=".[${EXTRAS}]"
15
3
64,734,118
2020-11-8
https://stackoverflow.com/questions/64734118/environment-variable-not-loading-with-load-dotenv-in-linux
I'm trying to make a discord bot, and when I try to load a .env with load_dotenv() it doesn't work because it says Traceback (most recent call last): File "/home/fanjin/Documents/Python Projects/Discord Bot/bot.py", line 15, in <module> client.run(TOKEN) File "/home/fanjin/.local/lib/python3.8/site-packages/discord/client.py", line 708, in run return future.result() File "/home/fanjin/.local/lib/python3.8/site-packages/discord/client.py", line 687, in runner await self.start(*args, **kwargs) File "/home/fanjin/.local/lib/python3.8/site-packages/discord/client.py", line 650, in start await self.login(*args, bot=bot) File "/home/fanjin/.local/lib/python3.8/site-packages/discord/client.py", line 499, in login await self.http.static_login(token.strip(), bot=bot) AttributeError: 'NoneType' object has no attribute 'strip Here's my code for the bot: import os import discord from dotenv import load_dotenv load_dotenv() TOKEN = os.getenv('DISCORD_TOKEN') client = discord.Client() @client.event async def on_ready(): print(f'{client.user} has connected to Discord!') client.run(TOKEN) And the save.env file: (It's a fake token) # .env DISCORD_TOKEN={XXXXXXXX} Both files are in the same directory, and I even tried to explicitly specify the .env's path with env_path = Path('path/to/file') / '.env' load_dotenv(dotenv_path=env_path) but that also didn't work
TL:DR You need to put the full path. Use either os.path.expanduser('~/Documents/MY_PROJECT/.env') or: load_dotenv('/home/MY_USER/Documents/MY_PROJECT/.env') and it will work. Or you change your current working directory in your code editor to where the ".env" file is (which should be the project folder). Or you open the project folder in the menu of your code editor, this should make the project folder the current working directory. On Linux, you can also go to the project folder in the terminal and start the code editor from there, type for example codium or whatever you use in the command prompt. Background Quote from the other answer Since, I moved my .env file's inside another subfolder config, then I had to provide the full path to load_dotenv() to make it work. This gave me the idea of checking the working directory. Current working directory os.getcwd() gave me a folder further up the tree. And then I copied the ".env" file into that working directory and it worked. Changing the working directory depends on your code editor. I use codium, which is the open source version of vscode, then you may follow for example Python in VSCode: Set working directory to python file's path everytime Full path You can also put the full path. Funny enough, I had checked that before coming here, but I copied the path that you get from the terminal, starting with '~/Documents/MY_PROJECT, which does not find the file but does not alert either, any tried environment variables were just empty - just because the ".env" file itself was never read.
14
12
64,761,870
2020-11-10
https://stackoverflow.com/questions/64761870/python-subprocess-doesnt-inherit-virtual-environment
When operating with a venv on Windoes 10 if I invoke a subprocess from a file in the directory, the subprocess does not seem to have access to the venv. Is there a way to make it work? Ideally I would like the approach to be portable to Linux but I'll take whatever gets the project running. Here is my test: main.py uses Popen to invoke sub_proc.py. sub_proc.py imports uuid_shortener, which has been installed in the virtual environment. If I run sub_proc.py directly it runs without an error. However, if I run main.py I see an error on the import statement for uuid_shortener. main.py import subprocess import time print(subprocess.Popen(['python', 'sub_proc.py'])) time.sleep(1) sub_proc.py import uuid_shortener Here is the output from running the code. (venv) PS C:\Users\...\popenvenv> python .\sub_proc.py (no error above) (venv) PS C:\Users\...\popenvenv> python .\main.py <Popen: returncode: None args: ['python', 'sub_proc.py']> Traceback (most recent call last): File "C:\Users\...\popenvenv\sub_proc.py", line 1, in <module> import uuid_shortener ModuleNotFoundError: No module named 'uuid_shortener' (venv) PS C:\Users\...\popenvenv>
Use sys.executable in place of 'python'. sys.executable refers to the executable you're running with. This will preserve access to the virtualenv in subprocesses.
14
19
64,710,616
2020-11-6
https://stackoverflow.com/questions/64710616/whats-the-difference-between-the-write-and-typewrite-functions-in-pyautogui
I've seen the use of pyautogui.typewrite() but I can't find the documentation for it in the pyautogui docs. I did find the pyautogui.write() function in the docs and I wanted to know if they are the same thing, because from what I can see, they seem very similar.
As of version 1.0 there is no difference between write and typewrite. The write function has been chosen as the preferred invocation but currently write is just an alias for typewrite: write = typewrite # In PyAutoGUI 1.0, write() replaces typewrite().
6
10
64,766,354
2020-11-10
https://stackoverflow.com/questions/64766354/unittest-and-mocks-how-to-reset-them
I am testing a class that needs a mock in the constructor, so I usually do this: class TestActionManager(unittest.TestCase): @patch('actionlib.SimpleActionClient', return_value=create_autospec(actionlib.SimpleActionClient)) def setUp(self, mock1): self.action_manager = ActionManager() Then in this class I add all the tests. So the first one is working fine def test_1(self): self.action_manager.f() self.action_manager.f.assert_called_once() But if I add another test and run both def test_2(self): self.action_manager.f() self.action_manager.f.assert_called_once() It says f has been called twice. I was expecting setUp to create a new ActionManager (and hence create a new mock) before starting every test, but it is clearly not happening, since the mock is somehow shared. Also I tried to do def tearDown(self): del self.action_manager But it does not fix the problem. I have read something related in Python Testing - Reset all mocks? where the solution is to use a different library (something that I would like to avoid) and in Any way to reset a mocked method to its original state? - Python Mock - mock 1.0b1 where it is using different classes to do it. Is there any possibility to reset the mock in the same class before or after every test?
I believe what you're looking for is reset_mock Here's, in general, how it works: def test_1(self): f = MagicMock() # or whatever you're mocking f() f.assert_called_once() f.reset_mock() f() f.assert_called_once() The result will be PASSED If you want to automate, then you store the mocked thing inside setUp, and in tearDown you call the mocked thing's .reset_mock() method. def setUp(self, mock1): self.mock1 = mock1 # ... do other things ... def tearDown(self): self.mock1.reset_mock()
16
29
64,690,820
2020-11-5
https://stackoverflow.com/questions/64690820/does-pytest-cache-fixture-data-when-called-by-multiple-test-functions
I have unit tests that require test data. This test data is downloaded and has decently large filesize. @pytest.fixture def large_data_file(): large_data = download_some_data('some_token') return large_data # Perform tests with input data def test_foo(large_data_file): pass def test_bar(large_data_file): pass def test_baz(large_data_file): pass # ... and so on I do not want to download this data more than once. It should only be downloaded once, and passed to all the tests that require it. Does pytest call on large_data_file once and use it for every unit test that uses that fixture, or does it call the large_data_file each time? In unittest, you would simply download the data for all the tests once in the setUpClass method. I would rather not just have a global large_data_file = download_some_data('some_token') in this py script. I would like to know how to handle this use-case with Pytest.
Does pytest call on large_data_file once and use it for every unit test that uses that fixture, or does it call the large_data_file each time? It depends on the fixture scope. The default scope is function, so in your example large_data_file will be evaluated three times. If you broaden the scope, e.g. @pytest.fixture(scope="session") def large_data_file(): ... the fixture will be evaluated once per test session and the result will be cached and reused in all dependent tests. Check out the section Scope: sharing fixtures across classes, modules, packages or session in pytest docs for more details.
29
31
64,729,944
2020-11-7
https://stackoverflow.com/questions/64729944/runtimeerror-the-current-numpy-installation-fails-to-pass-a-sanity-check-due-to
I am using Python 3.9 on Windows 10 version 2004 x64. PowerShell as Administrator. Python version: Python 3.9.0 (tags/v3.9.0:9cf6752, Oct 5 2020, 15:34:40) [MSC v.1927 64 bit (AMD64)] on win32 Install matplotlib error. pip install virtualenv virtualenv foo cd .\foo .\Scripts\active pip install numpy pip install matplotlib Error Windows PowerShell Copyright (C) Microsoft Corporation. All rights reserved. Try the new cross-platform PowerShell https://aka.ms/pscore6 PS C:\WINDOWS\system32> Set-ExecutionPolicy Unrestricted -Force PS C:\WINDOWS\system32> cd /d C:\Windows\System32\cmd.exe Set-Location : A positional parameter cannot be found that accepts argument 'C:\Windows\System32\cmd.exe'. At line:1 char:1 + cd /d C:\Windows\System32\cmd.exe + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidArgument: (:) [Set-Location], ParameterBindingException + FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell.Commands.SetLocationCommand PS C:\WINDOWS\system32> cd C:\Windows\System32\cmd.exe cd : Cannot find path 'C:\Windows\System32\cmd.exe' because it does not exist. At line:1 char:1 + cd C:\Windows\System32\cmd.exe + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : ObjectNotFound: (C:\Windows\System32\cmd.exe:String) [Set-Location], ItemNotFoundExcepti on + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.SetLocationCommand PS C:\WINDOWS\system32> cd D:\ PS D:\> cd .\Users\donhuvy\ PS D:\Users\donhuvy> ls Directory: D:\Users\donhuvy Mode LastWriteTime Length Name ---- ------------- ------ ---- d----- 10/26/2020 3:35 PM AppData d----- 11/7/2020 9:33 AM PycharmProjects PS D:\Users\donhuvy> cd .\PycharmProjects\pythonProject\ PS D:\Users\donhuvy\PycharmProjects\pythonProject> virtualenv foo virtualenv : The term 'virtualenv' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:1 + virtualenv foo + ~~~~~~~~~~ + CategoryInfo : ObjectNotFound: (virtualenv:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException PS D:\Users\donhuvy\PycharmProjects\pythonProject> pip install virtualenv Collecting virtualenv Downloading virtualenv-20.1.0-py2.py3-none-any.whl (4.9 MB) |β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 4.9 MB 1.1 MB/s Collecting distlib<1,>=0.3.1 Downloading distlib-0.3.1-py2.py3-none-any.whl (335 kB) |β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 335 kB 6.4 MB/s Requirement already satisfied: six<2,>=1.9.0 in c:\users\donhuvy\appdata\roaming\python\python39\site-packages (from virtualenv) (1.15.0) Collecting filelock<4,>=3.0.0 Downloading filelock-3.0.12-py3-none-any.whl (7.6 kB) Collecting appdirs<2,>=1.4.3 Downloading appdirs-1.4.4-py2.py3-none-any.whl (9.6 kB) Installing collected packages: distlib, filelock, appdirs, virtualenv Successfully installed appdirs-1.4.4 distlib-0.3.1 filelock-3.0.12 virtualenv-20.1.0 PS D:\Users\donhuvy\PycharmProjects\pythonProject> virtualenv foo created virtual environment CPython3.9.0.final.0-64 in 1312ms creator CPython3Windows(dest=D:\Users\donhuvy\PycharmProjects\pythonProject\foo, clear=False, global=False) seeder FromAppData(download=False, pip=bundle, setuptools=bundle, wheel=bundle, via=copy, app_data_dir=C:\Users\donhuvy\AppData\Local\pypa\virtualenv) added seed packages: pip==20.2.4, setuptools==50.3.2, wheel==0.35.1 activators BashActivator,BatchActivator,FishActivator,PowerShellActivator,PythonActivator,XonshActivator PS D:\Users\donhuvy\PycharmProjects\pythonProject> cd .\foo PS D:\Users\donhuvy\PycharmProjects\pythonProject\foo> .\Scripts\activate (foo) PS D:\Users\donhuvy\PycharmProjects\pythonProject\foo> pip install numpy Collecting numpy Using cached numpy-1.19.4-cp39-cp39-win_amd64.whl (13.0 MB) Installing collected packages: numpy Successfully installed numpy-1.19.4 (foo) PS D:\Users\donhuvy\PycharmProjects\pythonProject\foo> pip install matplotlib Collecting matplotlib Using cached matplotlib-3.3.2.tar.gz (37.9 MB) ** On entry to DGEBAL parameter number 3 had an illegal value ** On entry to DGEHRD parameter number 2 had an illegal value ** On entry to DORGHR DORGQR parameter number 2 had an illegal value ** On entry to DHSEQR parameter number 4 had an illegal value ERROR: Command errored out with exit status 1: command: 'D:\Users\donhuvy\PycharmProjects\pythonProject\foo\Scripts\python.exe' -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\donhuvy\\AppData\\Local\\Temp\\pip-install-8bn40qg7\\matplotlib\\setup.py'"'"'; __file__='"'"'C:\\Users\\donhuvy\\AppData\\Local\\Temp\\pip-install-8bn40qg7\\matplotlib\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base 'C:\Users\donhuvy\AppData\Local\Temp\pip-pip-egg-info-39nmc0pe' cwd: C:\Users\donhuvy\AppData\Local\Temp\pip-install-8bn40qg7\matplotlib\ Complete output (61 lines): Edit setup.cfg to change the build options; suppress output with --quiet. BUILDING MATPLOTLIB matplotlib: yes [3.3.2] python: yes [3.9.0 (tags/v3.9.0:9cf6752, Oct 5 2020, 15:34:40) [MSC v.1927 64 bit (AMD64)]] platform: yes [win32] sample_data: yes [installing] tests: no [skipping due to configuration] macosx: no [Mac OS-X only] running egg_info creating C:\Users\donhuvy\AppData\Local\Temp\pip-pip-egg-info-39nmc0pe\matplotlib.egg-info writing C:\Users\donhuvy\AppData\Local\Temp\pip-pip-egg-info-39nmc0pe\matplotlib.egg-info\PKG-INFO writing dependency_links to C:\Users\donhuvy\AppData\Local\Temp\pip-pip-egg-info-39nmc0pe\matplotlib.egg-info\dependency_links.txt writing namespace_packages to C:\Users\donhuvy\AppData\Local\Temp\pip-pip-egg-info-39nmc0pe\matplotlib.egg-info\namespace_packages.txt writing requirements to C:\Users\donhuvy\AppData\Local\Temp\pip-pip-egg-info-39nmc0pe\matplotlib.egg-info\requires.txt writing top-level names to C:\Users\donhuvy\AppData\Local\Temp\pip-pip-egg-info-39nmc0pe\matplotlib.egg-info\top_level.txt writing manifest file 'C:\Users\donhuvy\AppData\Local\Temp\pip-pip-egg-info-39nmc0pe\matplotlib.egg-info\SOURCES.txt' Traceback (most recent call last): File "<string>", line 1, in <module> File "C:\Users\donhuvy\AppData\Local\Temp\pip-install-8bn40qg7\matplotlib\setup.py", line 242, in <module> setup( # Finally, pass this all along to distutils to do the heavy lifting. File "D:\Users\donhuvy\PycharmProjects\pythonProject\foo\lib\site-packages\setuptools\__init__.py", line 153, in setup return distutils.core.setup(**attrs) File "d:\users\donhuvy\appdata\local\programs\python\python39\lib\distutils\core.py", line 148, in setup dist.run_commands() File "d:\users\donhuvy\appdata\local\programs\python\python39\lib\distutils\dist.py", line 966, in run_commands self.run_command(cmd) File "d:\users\donhuvy\appdata\local\programs\python\python39\lib\distutils\dist.py", line 985, in run_command cmd_obj.run() File "D:\Users\donhuvy\PycharmProjects\pythonProject\foo\lib\site-packages\setuptools\command\egg_info.py", line 298, in run self.find_sources() File "D:\Users\donhuvy\PycharmProjects\pythonProject\foo\lib\site-packages\setuptools\command\egg_info.py", line 305, in find_sources mm.run() File "D:\Users\donhuvy\PycharmProjects\pythonProject\foo\lib\site-packages\setuptools\command\egg_info.py", line 536, in run self.add_defaults() File "D:\Users\donhuvy\PycharmProjects\pythonProject\foo\lib\site-packages\setuptools\command\egg_info.py", line 572, in add_defaults sdist.add_defaults(self) File "d:\users\donhuvy\appdata\local\programs\python\python39\lib\distutils\command\sdist.py", line 228, in add_defaults self._add_defaults_ext() File "d:\users\donhuvy\appdata\local\programs\python\python39\lib\distutils\command\sdist.py", line 311, in _add_defaults_ext build_ext = self.get_finalized_command('build_ext') File "d:\users\donhuvy\appdata\local\programs\python\python39\lib\distutils\cmd.py", line 299, in get_finalized_command cmd_obj.ensure_finalized() File "d:\users\donhuvy\appdata\local\programs\python\python39\lib\distutils\cmd.py", line 107, in ensure_finalized self.finalize_options() File "C:\Users\donhuvy\AppData\Local\Temp\pip-install-8bn40qg7\matplotlib\setup.py", line 88, in finalize_options self.distribution.ext_modules[:] = [ File "C:\Users\donhuvy\AppData\Local\Temp\pip-install-8bn40qg7\matplotlib\setup.py", line 91, in <listcomp> for ext in package.get_extensions() File "C:\Users\donhuvy\AppData\Local\Temp\pip-install-8bn40qg7\matplotlib\setupext.py", line 345, in get_extensions add_numpy_flags(ext) File "C:\Users\donhuvy\AppData\Local\Temp\pip-install-8bn40qg7\matplotlib\setupext.py", line 469, in add_numpy_flags import numpy as np File "D:\Users\donhuvy\PycharmProjects\pythonProject\foo\lib\site-packages\numpy\__init__.py", line 305, in <module> _win_os_check() File "D:\Users\donhuvy\PycharmProjects\pythonProject\foo\lib\site-packages\numpy\__init__.py", line 302, in _win_os_check raise RuntimeError(msg.format(__file__)) from None RuntimeError: The current Numpy installation ('D:\\Users\\donhuvy\\PycharmProjects\\pythonProject\\foo\\lib\\site-packages\\numpy\\__init__.py') fails to pass a sanity check due to a bug in the windows runtime. See this issue for more information: https://tinyurl.com/ y3dm3h86 ---------------------------------------- ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output. (foo) PS D:\Users\donhuvy\PycharmProjects\pythonProject\foo> A screenshot of some of the above text Error information link to fmod(), after an update to windows 2004, is causing a strange interaction with other code I use PyCharm 2020.2 Ultimate, and it also catches the error. How can I fix it?
The temporary solution is to use NumPy 1.19.3. pip install numpy==1.19.3 From a Microsoft thread, a fix was promised to be available around January 2021. It was fixed in the KB4598291 update.
85
242
64,741,015
2020-11-8
https://stackoverflow.com/questions/64741015/plotly-how-to-color-the-fill-between-two-lines-based-on-a-condition
I want to add a fill colour between the black and blue line on my Plotly chart. I am aware this can be accomplished already with Plotly but I am not sure how to fill the chart with two colours based on conditions. The chart with the blue background is my Plotly chart. I want to make it look like the chart with the white background. (Ignore the red and green bars on the white chart) The conditions I want it to pass is: Fill the area between the two lines GREEN, if the black line is above the blue line. Fill the area between the two lines RED, if the black line is below the blue line. How can this be done with Plotly? If this is not possible with Plotly can it be accomplished with other graphing tools that work with Python.
For a number of reasons (that I'm willing to explain further if you're interested) the best approach seems to be to add two traces to a go.Figure() object for each time your averages cross eachother, and then define the fill using fill='tonexty' for the second trace using: for df in dfs: fig.add_traces(go.Scatter(x=df.index, y = df.ma1, line = dict(color='rgba(0,0,0,0)'))) fig.add_traces(go.Scatter(x=df.index, y = df.ma2, line = dict(color='rgba(0,0,0,0)'), fill='tonexty', fillcolor = fillcol(df['label'].iloc[0]))) fillcol is a simple custom function described in the full snippet below. And I've used the approach described in How to split a dataframe each time a string value changes in a column? to produce the necessary splits in the dataframe each time your averages cross eachother. Plot Complete code: import plotly.graph_objects as go import numpy as np import pandas as pd from datetime import datetime pd.options.plotting.backend = "plotly" # sample data df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/finance-charts-apple.csv') df.index = df.Date df = df[['AAPL.Close', 'mavg']] df['mavg2'] = df['AAPL.Close'].rolling(window=50).mean() df.columns = ['y', 'ma1', 'ma2'] df=df.tail(250).dropna() df1 = df.copy() # split data into chunks where averages cross each other df['label'] = np.where(df['ma1']>df['ma2'], 1, 0) df['group'] = df['label'].ne(df['label'].shift()).cumsum() df = df.groupby('group') dfs = [] for name, data in df: dfs.append(data) # custom function to set fill color def fillcol(label): if label >= 1: return 'rgba(0,250,0,0.4)' else: return 'rgba(250,0,0,0.4)' fig = go.Figure() for df in dfs: fig.add_traces(go.Scatter(x=df.index, y = df.ma1, line = dict(color='rgba(0,0,0,0)'))) fig.add_traces(go.Scatter(x=df.index, y = df.ma2, line = dict(color='rgba(0,0,0,0)'), fill='tonexty', fillcolor = fillcol(df['label'].iloc[0]))) # include averages fig.add_traces(go.Scatter(x=df1.index, y = df1.ma1, line = dict(color = 'blue', width=1))) fig.add_traces(go.Scatter(x=df1.index, y = df1.ma2, line = dict(color = 'red', width=1))) # include main time-series fig.add_traces(go.Scatter(x=df1.index, y = df1.y, line = dict(color = 'black', width=2))) fig.update_layout(showlegend=False) fig.show()
16
22
64,717,302
2020-11-6
https://stackoverflow.com/questions/64717302/deprecationwarning-executable-path-has-been-deprecated-selenium-python
I am using sublime to code python scripts. The following code is for selenium in python to install the driver automatically by using the webdriver_manager package # pip install webdriver-manager from selenium import webdriver from selenium.webdriver.chrome.service import Service from webdriver_manager.chrome import ChromeDriverManager from selenium.webdriver.common.by import By driver = webdriver.Chrome(ChromeDriverManager().install()) driver.maximize_window() #s=Service(path) #driver=webdriver.Chrome(service=s) driver.get('https://www.google.com') driver.find_element(By.NAME, 'q').send_keys('Yasser Khalil') The code works fine but I got a warning like that Demo.py:7: DeprecationWarning: executable_path has been deprecated, please pass in a Service object driver = webdriver.Chrome(ChromeDriverManager().install()) How to fix such a bug?
This error message... DeprecationWarning: executable_path has been deprecated, please pass in a Service object ...implies that the key executable_path will be deprecated in the upcoming releases. This change is inline with the Selenium 4.0 Beta 1 changelog which mentions: Deprecate all but Options and Service arguments in driver instantiation. (#9125,#9128) Solution With selenium4 as the key executable_path is deprecated you have to use an instance of the Service() class along with ChromeDriverManager().install() command as discussed below. Pre-requisites Ensure that: Selenium is upgraded to v4.0.0 pip3 install -U selenium Webdriver Manager for Python is installed pip3 install webdriver-manager You can find a detailed discussion on installing Webdriver Manager for Python in ModuleNotFoundError: No module named 'webdriver_manager' error even after installing webdrivermanager Selenium v4 compatible Code Block from selenium import webdriver from selenium.webdriver.chrome.service import Service from webdriver_manager.chrome import ChromeDriverManager driver = webdriver.Chrome(service=Service(ChromeDriverManager().install())) driver.get("https://www.google.com") Console Output: [WDM] - ====== WebDriver manager ====== [WDM] - Current google-chrome version is 96.0.4664 [WDM] - Get LATEST driver version for 96.0.4664 [WDM] - Driver [C:\Users\Admin\.wdm\drivers\chromedriver\win32\96.0.4664.45\chromedriver.exe] found in cache You can find a detailed discussion on installing Webdriver Manager for Python in Selenium ChromeDriver issue using Webdriver Manager for Python Incase you want to pass the Options() object you can use: from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.chrome.service import Service from webdriver_manager.chrome import ChromeDriverManager options = Options() options.add_argument("start-maximized") driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()), options=options) driver.get("https://www.google.com") TL; DR You can find the relevant Bug Report/Pull Request in: Bug Report: deprecate all but Options and Service arguments in driver instantiation Pull Request: deprecate all but Options and Service arguments in driver instantiation
203
269
64,712,375
2020-11-6
https://stackoverflow.com/questions/64712375/fine-tune-bert-for-specific-domain-unsupervised
I want to fine-tune BERT on texts that are related to a specific domain (in my case related to engineering). The training should be unsupervised since I don't have any labels or anything. Is this possible?
What you in fact want to is continue pre-training BERT on text from your specific domain. What you do in this case is to continue training the model as masked language model, but on your domain-specific data. You can use the run_mlm.py script from the Huggingface's Transformers.
7
9
64,711,663
2020-11-6
https://stackoverflow.com/questions/64711663/setting-up-hydrogen-and-atom-with-anaconda-on-windows
I would like to run python interactively in ATOM using the Hydrogen package. I am on Windows 10. I would like to be able to initiate an ATOM session by double-clicking the ATOM icon in my toolbar or double-clicking a .py file and not have to resort to initiating ATOM via the command line. I have installed Python 3.8 via the Anaconda distribution. I have used pip install to install the ipykernel. I get a series of Traceback errors which seems to be common; Traceback (most recent call last): File "C:\Users\BRB\anaconda3\lib\runpy.py", line 194, in _run_module_as_main return _run_code(code, main_globals, None, File "C:\Users\BRB\anaconda3\lib\runpy.py", line 87, in _run_code exec(code, run_globals) File "C:\Users\BRB\anaconda3\lib\site-packages\ipykernel_launcher.py", line 15, in from ipykernel import kernelapp as app File "C:\Users\BRB\anaconda3\lib\site-packages\ipykernel__init__.py", line 2, in from .connect import File "C:\Users\BRB\anaconda3\lib\site-packages\ipykernel\connect.py", line 18, in import jupyter_client File "C:\Users\BRB\anaconda3\lib\site-packages\jupyter_client__init__.py", line 4, in from .connect import File "C:\Users\BRB\anaconda3\lib\site-packages\jupyter_client\connect.py", line 21, in import zmq File "C:\Users\BRB\anaconda3\lib\site-packages\zmq__init__.py", line 47, in from zmq import backend File "C:\Users\BRB\anaconda3\lib\site-packages\zmq\backend__init__.py", line 40, in reraise(*exc_info) File "C:\Users\BRB\anaconda3\lib\site-packages\zmq\utils\sixcerpt.py", line 34, in reraise raise value File "C:\Users\BRB\anaconda3\lib\site-packages\zmq\backend__init__.py", line 27, in _ns = select_backend(first) File "C:\Users\BRB\anaconda3\lib\site-packages\zmq\backend\select.py", line 28, in select_backend mod = import(name, fromlist=public_api) File "C:\Users\BRB\anaconda3\lib\site-packages\zmq\backend\cython__init__.py", line 6, in from . import (constants, error, message, context, ImportError: DLL load failed while importing error: The specified module could not be found. Things I have tried: I first added the Python3 executable to the system PATH (against the advice of Anaconda). This does work if I initiate ATOM via the command line, but if I double-click the ATOM icon or .py file, I get the usual traceback errors. This answer https://discuss.atom.io/t/solved-how-to-use-the-hydrogen-package/30190 says it was a problem with Atom on macOS machines on older versions of Atom but has since been corrected for macOS. The answer was 4 years ago, so I assume it has been corrected for Windows, but I cannot find a soltion. This answer Setting up Hydrogen and Atom with Anaconda managing python installation says to (A) run: conda activate myenv python -m ipykernel install --user and (B) clean up the PATH. I did do both of these things. Removing the Python3 executable from PATH was a step backwards. Now it doesn't work even from the command line. I also don't understand why this is even bad in the first place... This guy Atom: Setting up Hydrogen Launcher for use with Python 3.7 has the same problems. But no solution. Can someone point me in the right direction? I am relatively new so would prefer not to complicate things by setting up multiple virtual environments etc at this stage (I don't yet have a need and I want simple).
I use Atom + Hydrogen extensively. And it is works which whatever python version and if it uses Anaconda, Miniconda, or simply python. Please do not mess with the system environment PATH. Maybe you are confused about which python executable is which. Or, is Atom.exe and Hydrogen using the same version, same path, of python executable? Atom thingy I am sure that Atom.exe uses the default python version that exists system-wide or a virtual environment. If you run Atom.exe without a virtual environment from the terminal, or simply double click the icon from the desktop, Atom.exe will use python available in the system. But if you run Atom.exe from a virtual environment-activated terminal/cmd, then Atom.exe will use python that is available in the virtual environment. Why does it matters? If you use an Atom.exe package, for example, python-import-magic, Atom.exe will ask you for a python package named isort. If you installed isort in a virtual environment named work, Atom.exe will always tell you that isort is not available, unless you start Atom.exe from the work virtual environment. Then, should I start Atom.exe from a virtual environment-activated terminal? I think that is not a good idea. Hydrogen thingy It doesn't matter how many pythons are installed or virtual environments are created, Hydrogen will use installed/registered kernels of python executables. For example, I installed several python versions (Yup, sorry I don't use pipenv) that located in: python37 in D:\python\python37\python.exe python38 in D:\python\python38\python.exe And then I want to use Hydrogen with a kernel that uses python37, I should install the kernel once with: D:\python\python37\python.exe -m ipykernel install --name "python37_something" or if I need python38 D:\python\python38\python.exe -m ipykernel install --name "python38_something" or I just want to install a kernel with whatever python is available system-wide: python.exe -m ipykernel install --name "python_for_the_win" After that, the installed kernel will appear in the Hydrogen (or even Jupyter Notebook/Lab) kernel selection. Screenshot below. But how if I use a virtual environment? Just switch to the virtual environment and install the kernel. For example, if I want to use a virtual environment named work with Hydrogen, I should activate the virtual environment and install the kernel once for the first time: workon work python -m ipykernel install --name "work_venv" or if you are using conda: conda activate work python -m ipykernel install --name "work_env" The work virtual environment will appear in Hydrogen kernel selection. Here is my installed kernels as an example: The important thing is, you should name the installed ipykernel with a --name argument and then choose a more meaningful name, such as work, flask development or anything you like, but not python or python3. The --user argument depends on your needs. Why can't I use 'python' or 'python3' as a kernel name? If you insist to run: python -m ipykernel install --name "python" or python -m ipykernel install --name "python3" or even the instruction from official nteract page: python -m ipykernel install from the virtual environment or not, the kernel will be installed, but the location of the kernel will be different depending on the virtual environment or system python path. Please take a look at my screenshots. The terminal in the back is without activating a virtual environment and the terminal in the front is using a virtual environment named work. When I run jupyter kernelspec list from both terminals, all the installed kernels are listed, and the file paths to them are the same on both terminals. Except for the python3, I do not know why, but it seems that python or python3 is a default name for ipykernels kernel and also when installing a kernel without a name. And you cannot choose which python3 to run from Atom+Hydrogen without, MAYBE, running atom.exe from virtual environment activated terminal. Bonus You may notice that in my last screenshot above, 'domainopsy' and 'javascript' are installed in C:\Users\faruq directory, it seems because I passed --user when I installed the kernel, while 'gym' and 'work' are not. I think, 'domainopsy' and 'javascript' are not accessible if I log in with another username. Please pardon my English, and this writing is based on my experience, so please correct me if I am wrong.
9
1
64,687,757
2020-11-4
https://stackoverflow.com/questions/64687757/authorization-architecture-in-microservice-cluster
I have a project with microservice architecture (on Docker and Kubernetes), and 2 main apps are written in Python using AIOHTTP and Django (also there are and Ingress proxy, static files server, a couple more made with NginX). I'd like to split these Python apps into separate smaller microservices, but to accomplish this probably I also should move authentication in a separate app. But how can I do this? Probably I should also add that I'm asking not about specific authentication methods like OAuth, JWT, etc, but about dependencies and responsibilities splitting inside cluster architecture. To my mind, a nice solution would be some plugin to Ingress NginX proxy server, or a microservice before it, so that my Python authenticating proxy won't care about methods destination, like some middleware, just read headers/cookies, check access token or sessionId, then set userId if the access is valid, and pass the request further. A brief and simplified architecture is presented below: And here is what I imagine, mention fewer complicated connections: But I'm not sure if this is reasonable. In addition, such approach would reduce advantages of K8s Ingress, which provides amazing interface for updating path table from the bash, but, as far as I know, doesn't allow to run any request handler before it, so I'll have to run custom NginX proxy without nice K8s integration. Thus, what are other possible architectural solutions? I could only imagine creation of a single request handler, that performs all the authorisation and passes requests to other microservices (or by RPC), which don't care about authentication, but I don't think this is a generally perfect solution.
Theory Well, I found a lot of info after digging on the Internet and one and a half of consultations. There is an architectural pattern named API Gateway, which describes an entry point in a cluster, and this is just what Kubernetes Ingress does, and what I imagined in my question. In a general case, it is proxy server, which is the only entry point to the cluster microservices, and it may perform caching, DDoS protection, it may support different API protocols, manipulate URIs, manage API throttling, monetisation, and perform the authentication I need. Therefore, there is no authentication during microservices communication inside the cluster, because all the required arguments, identifiers will be presented in the requests. Implementation In Kubernetes, NginX Ingress is quite popular, it also supports Basic Auth and OAuth2, which is not a perfect solution, but at least something. There are alternative Ingress solutions for Kubernetes: Kong, Ambassador, Traefik, which provide much more features (though Kong is based on NginX too). In the world of Java and Spring the Spring Cloud Gateway exists to solve such problems, which, just like K8s Ingress, allows to describe path tables with YAML, yet it is extendable, allows to easily embed your custom code for any authentication method. Besides, most of cloud platforms provide their own API gateway services with more or less features, including Google Cloud, Red Hat, AWS, Yandex Cloud. However, it seems they lack authentication methods just like opportunity to be extended, though they aren't much relevant in this question. To read You can find more about API Gateway pattern and it's implementations here: microservices.io: API Gateway pattern RedHat: What does an API gateway do? kubernetes.github.io: NginX Ingress External OAUTH Authentication learnK8S.io: Kubernetes API Gateway cloud.spring.io: Spring Cloud Gateway
6
6
64,763,770
2020-11-10
https://stackoverflow.com/questions/64763770/why-we-use-yield-to-get-sessionlocal-in-fastapi-with-sqlalchemy
def get_db(): db = SessionLocal() try: return db finally: db.close() I got this code snipped to get Sessionlocal in fastapi with Sqlalchemy. Well, when I used return instead of Yield. My code still works. Then, I do not understand the reason of using Yield. Can someone help me?
Well, when I used return instead of Yield. My code still works. Then, I do not understand the reason of using Yield. It's a great question, the answer is, yes there's a reason to use yield instead of return. SQLAlchemy has a Connection Pooling mechanism by default. That means with yield you are creating a single session for each request. When you use return you are using a single database connection for all your app. Isn't it clear? Let's visualize it to make things more interesting. So what do we have in this example? A connection pool that holds 5 different connections. 2 endpoint 3 incoming requests. When you use yield it would look something like this underneath because it goes to an endpoint, asks something to the database and yield creates a new Session object every time. It provides a transactional scope around a series of operations, but using return there instead of yield will just return that session object.
23
24
64,769,205
2020-11-10
https://stackoverflow.com/questions/64769205/seaborn-lineplot-logarithmic-scale
I'm having a problem with adding a logarithmic X-axis to my plot. I want to show results based on the sample size with methods A, B and C. My dataframe result: A B C 15 0.733333 0.613333 0.733333 30 0.716667 0.693333 0.766667 59 0.733684 0.678485 0.745763 118 0.796667 0.726087 0.779661 236 0.817862 0.788333 0.838983 470 0.832125 0.814468 0.836170 What I'm trying to make work: sample_count = np.around(np.logspace(math.log10(15),math.log10(470),6)) sample_count = sample_count.astype(int) sns.set_style('whitegrid') g_results=sns.lineplot(data=results,dashes=0,markers=['o','o','o']) g_results.set(xticks=sample_count) g_results.set(xscale='log') However the result is not what I exactly want, as the ticks are completely gone: Without the last xscale line it looks like this, which is the linear scale of course, but this time with the correct ticks: What I want to achieve is something like this: How do I get my desired output?
First set the scale for the x-axis to logarithmic and then set xticks and labels as you want. sns.set_style('whitegrid') g_results=sns.lineplot(data=results,dashes=0,markers=['o','o','o']) g_results.set(xscale='log') g_results.set(xticks=sample_count) g_results.set(xticklabels=sample_count) This gives you this result: Note that I'm using sample_count as defined with the logarithmic scale: sample_count = np.around(np.logspace(math.log10(15),math.log10(470),6))
17
19
64,763,274
2020-11-10
https://stackoverflow.com/questions/64763274/module-cv2-cv2-has-no-attribute-dnn-superres
I am trying to upscale image (performing super resolution) using OpenCV, but I am getting this error that module 'cv2.cv2' has no attribute 'dnn_superres'. Any help would be greatly appreciated. I am using 4.4.0.44 OpenCV version. Here is the code section. import cv2 sr = cv2.dnn_superres.DnnSuperResImpl_create() sr.readModel(args["model"]) sr.setModel(modelName, modelScale)
In case you are using python3, you need to download opencv with pip3 First uninstall opencv: pip uninstall opencv-python pip uninstall opencv-contrib-python Then install latest version of opencv with pip3: pip3 install opencv-contrib-python
12
15
64,718,655
2020-11-6
https://stackoverflow.com/questions/64718655/plotly-fails-to-show-text-in-latex-labels-in-python
I am using plotly to do some plots. I need to use math symbols in the labels of the axes. Plotly shows the latex parts but not the text parts: import plotly.graph_objects as go import numpy as np x = np.array([1,2,3,4,5,6,7,8,9]) fig = go.Figure() fig.add_trace( go.Scatter( x = x, y = x**2, ) ) fig.update_layout( title = 'My figure', xaxis_title = r'$\Delta t$ (s)', yaxis_title = r'This text is not displayed/$\sqrt{2}$ (ps)', ) fig.show() produces Note that the text parts in the labels are not being displayed. I am using Python 3.8.5 with Plotly 4.9.0 and viewing the plots with Firefox 81.0.2 in Ubuntu 20.04.
I came across to the same problem too. The temporary solution is to quote the text in \textrm. i.e. fig.update_layout( title = 'My figure', xaxis_title = r'$\Delta t\textrm{(s)}$', yaxis_title = r'This text is not displayed/$\sqrt{2}\textrm{(ps)}$', ) The result looks like this below. <html> <head><meta charset="utf-8" /></head> <body> <div> <script src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/MathJax.js?config=TeX-AMS-MML_SVG"></script><script type="text/javascript">if (window.MathJax) {MathJax.Hub.Config({SVG: {font: "STIX-Web"}});}</script> <script type="text/javascript">window.PlotlyConfig = {MathJaxConfig: 'local'};</script> <script src="https://cdn.plot.ly/plotly-latest.min.js"></script> <div id="7b53913b-db4a-4833-8079-266d3d528b3d" class="plotly-graph-div" style="height:100%; width:100%;"></div> <script type="text/javascript"> window.PLOTLYENV=window.PLOTLYENV || {}; if (document.getElementById("7b53913b-db4a-4833-8079-266d3d528b3d")) { Plotly.newPlot( "7b53913b-db4a-4833-8079-266d3d528b3d", [{"type": "scatter", "x": [1, 2, 3, 4, 5, 6, 7, 8, 9], "y": [1, 4, 9, 16, 25, 36, 49, 64, 81]}], {"template": {"data": {"bar": [{"error_x": {"color": "#2a3f5f"}, "error_y": {"color": "#2a3f5f"}, "marker": {"line": {"color": "#E5ECF6", "width": 0.5}}, "type": "bar"}], "barpolar": [{"marker": {"line": {"color": "#E5ECF6", "width": 0.5}}, "type": "barpolar"}], "carpet": [{"aaxis": {"endlinecolor": "#2a3f5f", "gridcolor": "white", "linecolor": "white", "minorgridcolor": "white", "startlinecolor": "#2a3f5f"}, "baxis": {"endlinecolor": "#2a3f5f", "gridcolor": "white", "linecolor": "white", "minorgridcolor": "white", "startlinecolor": "#2a3f5f"}, "type": "carpet"}], "choropleth": [{"colorbar": {"outlinewidth": 0, "ticks": ""}, "type": "choropleth"}], "contour": [{"colorbar": {"outlinewidth": 0, "ticks": ""}, "colorscale": [[0.0, "#0d0887"], [0.1111111111111111, "#46039f"], [0.2222222222222222, "#7201a8"], [0.3333333333333333, "#9c179e"], [0.4444444444444444, "#bd3786"], [0.5555555555555556, "#d8576b"], [0.6666666666666666, "#ed7953"], [0.7777777777777778, "#fb9f3a"], [0.8888888888888888, "#fdca26"], [1.0, "#f0f921"]], "type": "contour"}], "contourcarpet": [{"colorbar": {"outlinewidth": 0, "ticks": ""}, "type": "contourcarpet"}], "heatmap": [{"colorbar": {"outlinewidth": 0, "ticks": ""}, "colorscale": [[0.0, "#0d0887"], [0.1111111111111111, "#46039f"], [0.2222222222222222, "#7201a8"], [0.3333333333333333, "#9c179e"], [0.4444444444444444, "#bd3786"], [0.5555555555555556, "#d8576b"], [0.6666666666666666, "#ed7953"], [0.7777777777777778, "#fb9f3a"], [0.8888888888888888, "#fdca26"], [1.0, "#f0f921"]], "type": "heatmap"}], "heatmapgl": [{"colorbar": {"outlinewidth": 0, "ticks": ""}, "colorscale": [[0.0, "#0d0887"], [0.1111111111111111, "#46039f"], [0.2222222222222222, "#7201a8"], [0.3333333333333333, "#9c179e"], [0.4444444444444444, "#bd3786"], [0.5555555555555556, "#d8576b"], [0.6666666666666666, "#ed7953"], [0.7777777777777778, "#fb9f3a"], [0.8888888888888888, "#fdca26"], [1.0, "#f0f921"]], "type": "heatmapgl"}], "histogram": [{"marker": {"colorbar": {"outlinewidth": 0, "ticks": ""}}, "type": "histogram"}], "histogram2d": [{"colorbar": {"outlinewidth": 0, "ticks": ""}, "colorscale": [[0.0, "#0d0887"], [0.1111111111111111, "#46039f"], [0.2222222222222222, "#7201a8"], [0.3333333333333333, "#9c179e"], [0.4444444444444444, "#bd3786"], [0.5555555555555556, "#d8576b"], [0.6666666666666666, "#ed7953"], [0.7777777777777778, "#fb9f3a"], [0.8888888888888888, "#fdca26"], [1.0, "#f0f921"]], "type": "histogram2d"}], "histogram2dcontour": [{"colorbar": {"outlinewidth": 0, "ticks": ""}, "colorscale": [[0.0, "#0d0887"], [0.1111111111111111, "#46039f"], [0.2222222222222222, "#7201a8"], [0.3333333333333333, "#9c179e"], [0.4444444444444444, "#bd3786"], [0.5555555555555556, "#d8576b"], [0.6666666666666666, "#ed7953"], [0.7777777777777778, "#fb9f3a"], [0.8888888888888888, "#fdca26"], [1.0, "#f0f921"]], "type": "histogram2dcontour"}], "mesh3d": [{"colorbar": {"outlinewidth": 0, "ticks": ""}, "type": "mesh3d"}], "parcoords": [{"line": {"colorbar": {"outlinewidth": 0, "ticks": ""}}, "type": "parcoords"}], "pie": [{"automargin": true, "type": "pie"}], "scatter": [{"marker": {"colorbar": {"outlinewidth": 0, "ticks": ""}}, "type": "scatter"}], "scatter3d": [{"line": {"colorbar": {"outlinewidth": 0, "ticks": ""}}, "marker": {"colorbar": {"outlinewidth": 0, "ticks": ""}}, "type": "scatter3d"}], "scattercarpet": [{"marker": {"colorbar": {"outlinewidth": 0, "ticks": ""}}, "type": "scattercarpet"}], "scattergeo": [{"marker": {"colorbar": {"outlinewidth": 0, "ticks": ""}}, "type": "scattergeo"}], "scattergl": [{"marker": {"colorbar": {"outlinewidth": 0, "ticks": ""}}, "type": "scattergl"}], "scattermapbox": [{"marker": {"colorbar": {"outlinewidth": 0, "ticks": ""}}, "type": "scattermapbox"}], "scatterpolar": [{"marker": {"colorbar": {"outlinewidth": 0, "ticks": ""}}, "type": "scatterpolar"}], "scatterpolargl": [{"marker": {"colorbar": {"outlinewidth": 0, "ticks": ""}}, "type": "scatterpolargl"}], "scatterternary": [{"marker": {"colorbar": {"outlinewidth": 0, "ticks": ""}}, "type": "scatterternary"}], "surface": [{"colorbar": {"outlinewidth": 0, "ticks": ""}, "colorscale": [[0.0, "#0d0887"], [0.1111111111111111, "#46039f"], [0.2222222222222222, "#7201a8"], [0.3333333333333333, "#9c179e"], [0.4444444444444444, "#bd3786"], [0.5555555555555556, "#d8576b"], [0.6666666666666666, "#ed7953"], [0.7777777777777778, "#fb9f3a"], [0.8888888888888888, "#fdca26"], [1.0, "#f0f921"]], "type": "surface"}], "table": [{"cells": {"fill": {"color": "#EBF0F8"}, "line": {"color": "white"}}, "header": {"fill": {"color": "#C8D4E3"}, "line": {"color": "white"}}, "type": "table"}]}, "layout": {"annotationdefaults": {"arrowcolor": "#2a3f5f", "arrowhead": 0, "arrowwidth": 1}, "autotypenumbers": "strict", "coloraxis": {"colorbar": {"outlinewidth": 0, "ticks": ""}}, "colorscale": {"diverging": [[0, "#8e0152"], [0.1, "#c51b7d"], [0.2, "#de77ae"], [0.3, "#f1b6da"], [0.4, "#fde0ef"], [0.5, "#f7f7f7"], [0.6, "#e6f5d0"], [0.7, "#b8e186"], [0.8, "#7fbc41"], [0.9, "#4d9221"], [1, "#276419"]], "sequential": [[0.0, "#0d0887"], [0.1111111111111111, "#46039f"], [0.2222222222222222, "#7201a8"], [0.3333333333333333, "#9c179e"], [0.4444444444444444, "#bd3786"], [0.5555555555555556, "#d8576b"], [0.6666666666666666, "#ed7953"], [0.7777777777777778, "#fb9f3a"], [0.8888888888888888, "#fdca26"], [1.0, "#f0f921"]], "sequentialminus": [[0.0, "#0d0887"], [0.1111111111111111, "#46039f"], [0.2222222222222222, "#7201a8"], [0.3333333333333333, "#9c179e"], [0.4444444444444444, "#bd3786"], [0.5555555555555556, "#d8576b"], [0.6666666666666666, "#ed7953"], [0.7777777777777778, "#fb9f3a"], [0.8888888888888888, "#fdca26"], [1.0, "#f0f921"]]}, "colorway": ["#636efa", "#EF553B", "#00cc96", "#ab63fa", "#FFA15A", "#19d3f3", "#FF6692", "#B6E880", "#FF97FF", "#FECB52"], "font": {"color": "#2a3f5f"}, "geo": {"bgcolor": "white", "lakecolor": "white", "landcolor": "#E5ECF6", "showlakes": true, "showland": true, "subunitcolor": "white"}, "hoverlabel": {"align": "left"}, "hovermode": "closest", "mapbox": {"style": "light"}, "paper_bgcolor": "white", "plot_bgcolor": "#E5ECF6", "polar": {"angularaxis": {"gridcolor": "white", "linecolor": "white", "ticks": ""}, "bgcolor": "#E5ECF6", "radialaxis": {"gridcolor": "white", "linecolor": "white", "ticks": ""}}, "scene": {"xaxis": {"backgroundcolor": "#E5ECF6", "gridcolor": "white", "gridwidth": 2, "linecolor": "white", "showbackground": true, "ticks": "", "zerolinecolor": "white"}, "yaxis": {"backgroundcolor": "#E5ECF6", "gridcolor": "white", "gridwidth": 2, "linecolor": "white", "showbackground": true, "ticks": "", "zerolinecolor": "white"}, "zaxis": {"backgroundcolor": "#E5ECF6", "gridcolor": "white", "gridwidth": 2, "linecolor": "white", "showbackground": true, "ticks": "", "zerolinecolor": "white"}}, "shapedefaults": {"line": {"color": "#2a3f5f"}}, "ternary": {"aaxis": {"gridcolor": "white", "linecolor": "white", "ticks": ""}, "baxis": {"gridcolor": "white", "linecolor": "white", "ticks": ""}, "bgcolor": "#E5ECF6", "caxis": {"gridcolor": "white", "linecolor": "white", "ticks": ""}}, "title": {"x": 0.05}, "xaxis": {"automargin": true, "gridcolor": "white", "linecolor": "white", "ticks": "", "title": {"standoff": 15}, "zerolinecolor": "white", "zerolinewidth": 2}, "yaxis": {"automargin": true, "gridcolor": "white", "linecolor": "white", "ticks": "", "title": {"standoff": 15}, "zerolinecolor": "white", "zerolinewidth": 2}}}, "title": {"text": "My figure"}, "xaxis": {"title": {"text": "$\\Delta t\\textrm{(s)}$"}}, "yaxis": {"title": {"text": "This text is not displayed/$\\sqrt{2}\\textrm{(ps)}$"}}}, {"responsive": true} ) }; </script> </div> </body> </html>
6
3
64,718,274
2020-11-6
https://stackoverflow.com/questions/64718274/how-to-update-python-in-raspberry-pi
I need python newest version in raspberry pi. I tried apt install python3 3.8 apt install python3 but this didnot work. And I also needed to update my raspberry pi python IDLE
First update the Raspbian. sudo apt-get update Then install the prerequisites that will make any further installation of Python and/or packages much smoother. sudo apt-get install -y build-essential tk-dev libncurses5-dev libncursesw5-dev libreadline6-dev libdb5.3-dev libgdbm-dev libsqlite3-dev libssl-dev libbz2-dev libexpat1-dev liblzma-dev zlib1g-dev libffi-dev And then install Python, maybe by downloading a compressed file? example 1 : wget https://www.python.org/ftp/python/3.8.0/Python-3.8.0.tgz Extract the folder : sudo tar zxf Python-3.8.0.tgz Move into the folder : cd Python-3.8.0 Initial configuration : sudo ./configure --enable-optimizations Run the makefile inside the folder with the mentioned parameters : sudo make -j 4 Run again the makefile this time installing directly the package : sudo make altinstall Maybe You already did it but You don't know how to setup the new version as a default version of the system? Check first that it has been installed : python3.8 -V Send a strong command to .bashrc telling him who (which version) is in charge of Python echo "alias python=/usr/local/bin/python3.8" >> ~/.bashrc Again! Tell him because .bashrc has to understand! I am joking - You have to source the file so the changes can be applied immediately : source ~/.bashrc And then check that Your system changed the default version of Python to Python 3.8 python -V The failure depends on many factors : what dependencies are installed, what are the packages added to the source_list.d, some inconvenient coming up during the installation. All may give you more information than you think, just read carefully. Hope it helped.
22
60
64,680,361
2020-11-4
https://stackoverflow.com/questions/64680361/vscode-autocompletion-doesnt-work-for-jupyter-notebook
I recently started using Jupyter Notebooks on vscode but i've notices that code autocompletion doesn't work properly. If i create a regular .py file everything works correctly as you can see. It shows function signature and docstring. In both core python language and extern modules. But if i try the same in a .ipynb file it completely ignores autocompletion for print() And what confuses me too if that for example it shows me np.sum() docstring but it doesn't show me any np.concatenate() information gamong any other np.functions or other modules [ Just in case im using Vscode and an conda enviroment as my python interpreter. Here is my settings.json file: { "python.dataScience.jupyterServerURI": "local", "python.pythonPath": "C:\\Users\\myUser\\anaconda3\\envs\\myEnv\\python.exe" }
According to your description, the reason for this situation is that different language services provide different functions such as automatic completion and prompts. For the "print()" and "np.concatenate()" you mentioned, it is recommended that you use the "Pylance" extension, which provides excellent language services and auto-complete functions. Please add the following settings in settings.json: "python.languageServer": "Pylance", Update: Starting from November 2020, the function of Jupyter notebook in VSCode is provided by the extension "Jupyter", which uses the "IntelliSense" provided by the extension "Jupyter". And in "VSCode-insider" Jupyter notebook has better "IntelliSense": Github link: Hover Documentation Pop up does not work after VSCode 1.52 update.
30
33
64,760,817
2020-11-9
https://stackoverflow.com/questions/64760817/after-upgrade-raw-sql-queries-return-json-fields-as-strings-on-postgres
I am upgrading a Django app from 2.2.7 to 3.1.3. The app uses Postgres 12 & psycopg2 2.8.6. I followed the instructions and changed all my django.contrib.postgres.fields.JSONField references to django.db.models.JSONField, and made and ran the migrations. This produced no changes to my schema (which is good.) However, when I execute a raw query the data for those jsonb columns is returned as text, or converted to text, at some point. I don't see this issue when querying the models directly using Model.objects.get(...). import os, django os.environ.setdefault("DJANGO_SETTINGS_MODULE", "big_old_project.settings") django.setup() with connection.cursor() as c: c.execute("select name, data from tbl where name=%s", ("rex",)) print(c.description) for row in c.fetchall(): for col in row: print(f"{type(col)} => {col!r}") (Column(name='name', type_code=1043), Column(name='data', type_code=3802)) <class 'str'> => 'rex' <class 'str'> => '{"toy": "bone"}' [edit] Using a raw connection gives the expected results: conn = psycopg2.connect("dbname=db user=x password=z") with conn.cursor() as c: ... <class 'str'> => 'rex' <class 'dict'> => {'toy': 'bone'} Trying the old trick of "registering" the adapter doesn't work, and shouldn't be needed anyway. import psycopg2.extras psycopg2.extras.register_json(oid=3802, array_oid=3807, globally=True) This app has a lot of history, so maybe something is stepping on psycopg2's toes? I can't find anything so far, and have commented out everything that seems tangentially related. Going through the release notes didn't help. I do use other postgres fields so I can't delete all references to contrib.postgres.fields from my models. Any ideas as to why this is happening would be greatly appreciated.
To add to @Andrew Backer's helpful answer, this is apparently intentional. From the 3.1.1 release notes: Fixed a QuerySet.order_by() crash on PostgreSQL when ordering and grouping by JSONField with a custom decoder (#31956). As a consequence, fetching a JSONField with raw SQL now returns a string instead of pre-loaded data. You will need to explicitly call json.loads() in such cases. It's surprising to find an API-incompatible change as an aside in a bugfix release. For now I'll be adding json.loads() calls since, as already mentioned, there's no guarantee the ::json workaround doesn't break as well!
8
5
64,680,438
2020-11-4
https://stackoverflow.com/questions/64680438/how-does-joblib-parallel-deal-with-global-variables
My code looks something like this: from joblib import Parallel, delayed # prediction model - 10s of megabytes on disk LARGE_MODEL = load_model('path/to/model') file_paths = glob('path/to/files/*') def do_thing(file_path): pred = LARGE_MODEL.predict(load_image(file_path)) return pred Parallel(n_jobs=2)(delayed(do_thing)(fp) for fp in file_paths) My question is whether LARGE_MODEL will be pickled/unpickled with each iteration of the loop. And if so, how can I make sure each worker caches it instead (if that's possible)?
TLDR The parent process pickles large model once. That can be made more performant by ensuring large model is a numpy array backed to a memfile. Workers can load_temporary_memmap much faster than from disk. Your job is parallelized and likely to be using joblibs._parallel_backends.LokyBackend. In joblib.parallel.Parallel.__call__, joblib tries to initialize the backend to use LokyBackend when n_jobs is set to a count greater than 1. LokyBackend uses a shared temporary folder for the same Parallel object. This is relevant for reducers that modify the default pickling behavior. Now, LokyBackend configures a MemmappingExecutor that shares this folder to the reducers. If you have numpy installed and your model is a clean numpy array, you are guaranteed to have it pickled once as a memmapped file using the ArrayMemmapForwardReducer and passed from parent to child processes. Otherwise it is pickled using the default pickling as a bytes object. You can know how your model is pickled in the parent process reading the debug logs from joblib. Each worker 'unpickles' large model so there is really no point in caching the large model there. You can only improve the source from where the pickled large model is loaded from in the workers by backing your models as a memory mapped file.
6
5
64,761,911
2020-11-10
https://stackoverflow.com/questions/64761911/sqlalchemy-accessing-column-types-from-query-results
I am connecting to a SQL Server database using SQLAlchemy (with the pymssql driver). import sqlalchemy conn_string = f'mssql+pymssql://{uid}:{pwd}@{instance}/?database={db};charset=utf8' sql = 'SELECT * FROM FAKETABLE;' engine = sqlalchemy.create_engine(conn_string) connection = engine.connect() result = connection.execute(sql) result.cursor.description which results in: (('col_1', 1, None, None, None, None, None), ('col_2', 1, None, None, None, None, None), ('col_3', 4, None, None, None, None, None), ('col_4', 3, None, None, None, None, None), ('col_5', 3, None, None, None, None, None)) As per PEP 249 (cursor's .description attribute): The first two items (name and type_code) are mandatory, the other five are optional and are set to None if no meaningful values can be provided. I am assuming the integers (1, 1, 4, 3, 3) are column types. My two questions: How to map these integers to data types (like char, integer, etc.)? Are these SQL data types? If no, is it possible to get the SQL data types? FWIW, I get the same result when using raw_connection() instead of connect(). Came across three questions along similar lines (which do not answer this specific question). I need to use the connect() + execute() approach. SQLAlchemy getting column data types of query results How to get columns' sql type queried by sqlalchemy Easy convert betwen SQLAlchemy column types and python data types?
If no, is it possible to get the SQL data types? SQL Server function sys.dm_exec_describe_first_result_set could be used to get SQL column's data type directly for provided query: SELECT column_ordinal, name, system_type_name, * FROM sys.dm_exec_describe_first_result_set('here goes query', NULL, 0) ; In your example: sql = """SELECT column_ordinal, name, system_type_name FROM sys.dm_exec_describe_first_result_set('SELECT * FROM FAKETABLE', NULL, 0) ;""" For: CREATE TABLE FAKETABLE(id INT, d DATE, country NVARCHAR(10)); SELECT column_ordinal, name, system_type_name FROM sys.dm_exec_describe_first_result_set('SELECT * FROM FAKETABLE', NULL, 0) ; +-----------------+----------+------------------+ | column_ordinal | name | system_type_name | +-----------------+----------+------------------+ | 1 | id | int | | 2 | d | date | | 3 | country | nvarchar(10) | +-----------------+----------+------------------+ db<>fiddle demo
10
3
64,760,423
2020-11-9
https://stackoverflow.com/questions/64760423/pipfile-hash-creation
I am having issues with Pipenv. I run pipenv install --dev in order to install some dependencies from a Pipfile within my project. Upon running this command, Pipenv generates an MD5 hash for a certain dependency. The error is saying that MD5 is not supported yet still generates it. I have not set any configurations on my local machine or in any configuration file. I cannot seem to pinpoint this issue. Any help is greatly appreciated. [pipenv.exceptions.InstallError]: pip: error: Allowed hash algorithms for --hash are sha256, sha384, sha512. Pipfile.lock { "_meta": { "hash": { "sha256": "7e0f1d75f7df19f9500f55bd2f1da163cb4a8c7f485aab61c521d70e3865a507" }, "pipfile-spec": 6, "requires": { "python_version": "3.6" }, "sources": [ { "name": "pypi", "url": "https://pypi.org/simple", "verify_ssl": true } ] }, "default": { "certain-dependency": { "hashes": [ "md5:8faf2e4ff85c34b5d0c000c017f81f52", "md5:1508a7f05b17d292f7890b8c58a451cf", ], "version": "==11.10.20" } } }
Try clearing your pipenv cache: Make sure your dependencies actually do resolve. If you’re confident they are, you may need to clear your resolver cache. Run the following command: pipenv lock --clear and try again. If this does not work, try manually deleting the whole cache directory. It is usually one of the following locations: ~/Library/Caches/pipenv (macOS) %LOCALAPPDATA%\pipenv\pipenv\Cache (Windows) ~/.cache/pipenv (other operating systems) While the current release of pipenv only accepts sha256 hashes, it loads package URLs from a cache and writes those cached URLs' hashes to Pipfile.lock. If those cached hashes are md5 hashes from previously-installed packages, pipenv uses those values as-is without verifying that they are sha256/FAVORITE_HASH. Clearing the cache and re-locking will cause pipenv to cache miss and re-fetch package URLs which end in sha256 hashes, and write them to Pipfile.lock as you'd hope, and prevent you from running into the issue again.
10
4
64,777,931
2020-11-10
https://stackoverflow.com/questions/64777931/what-is-the-recommended-way-to-include-properties-in-dataclasses-in-asdict-or-se
Note this is similar to How to get @property methods in asdict?. I have a (frozen) nested data structure like the following. A few properties that are (purely) dependent on the fields are defined. import copy import dataclasses import json from dataclasses import dataclass @dataclass(frozen=True) class Bar: x: int y: int @property def z(self): return self.x + self.y @dataclass(frozen=True) class Foo: a: int b: Bar @property def c(self): return self.a + self.b.x - self.b.y I can serialize the data structure as follows: class CustomEncoder(json.JSONEncoder): def default(self, o): if dataclasses and dataclasses.is_dataclass(o): return dataclasses.asdict(o) return json.JSONEncoder.default(self, o) foo = Foo(1, Bar(2,3)) print(json.dumps(foo, cls=CustomEncoder)) # Outputs {"a": 1, "b": {"x": 2, "y": 3}} However, I would like to also serialize the properties (@property). Note I do not want to turn the properties into fields using __post_init__ as I would like to keep the dataclass' frozen. I do not want to use obj.__setattr__ to work around the frozen fields. I also do not want to pre-compute the values of the properties outside the class and pass them in as fields. The current solution I am using is to explicitly write out how each object is serialized as follows: class CustomEncoder2(json.JSONEncoder): def default(self, o): if isinstance(o, Foo): return { "a": o.a, "b": o.b, "c": o.c } elif isinstance(o, Bar): return { "x": o.x, "y": o.y, "z": o.z } return json.JSONEncoder.default(self, o) foo = Foo(1, Bar(2,3)) print(json.dumps(foo, cls=CustomEncoder2)) # Outputs {"a": 1, "b": {"x": 2, "y": 3, "z": 5}, "c": 0} as desired For a few levels of nesting, this is manageable but I am hoping for a more general solution. For example, here is a (hacky) solution that monkey-patches the _asdict_inner implementation from the dataclasses library. def custom_asdict_inner(obj, dict_factory): if dataclasses._is_dataclass_instance(obj): result = [] for f in dataclasses.fields(obj): value = custom_asdict_inner(getattr(obj, f.name), dict_factory) result.append((f.name, value)) # Inject this one-line change result += [(prop, custom_asdict_inner(getattr(obj, prop), dict_factory)) for prop in dir(obj) if not prop.startswith('__')] return dict_factory(result) elif isinstance(obj, tuple) and hasattr(obj, '_fields'): return type(obj)(*[custom_asdict_inner(v, dict_factory) for v in obj]) elif isinstance(obj, (list, tuple)): return type(obj)(custom_asdict_inner(v, dict_factory) for v in obj) elif isinstance(obj, dict): return type(obj)((custom_asdict_inner(k, dict_factory), custom_asdict_inner(v, dict_factory)) for k, v in obj.items()) else: return copy.deepcopy(obj) dataclasses._asdict_inner = custom_asdict_inner class CustomEncoder3(json.JSONEncoder): def default(self, o): if dataclasses and dataclasses.is_dataclass(o): return dataclasses.asdict(o) return json.JSONEncoder.default(self, o) foo = Foo(1, Bar(2,3)) print(json.dumps(foo, cls=CustomEncoder3)) # Outputs {"a": 1, "b": {"x": 2, "y": 3, "z": 5}, "c": 0} as desired Is there a recommended way to achieve what I am trying to do?
There's no "recommended" way to include them that I know of. Here's something that seems to work and I think meets your numerous requirements. It defines a custom encoder that calls its own _asdict() method when the object is a dataclass instead of monkey-patching the (private) dataclasses._asdict_inner() function and encapsulates (bundles) the code within the customer encoder that makes use of it. Like you, I used the current implementation of dataclasses.asdict() as a guide/template since what you're asking for is basically just a customized version of that. The current value of each field that's a property is obtained by calling its __get__ method. import copy import dataclasses from dataclasses import dataclass, field import json import re from typing import List class MyCustomEncoder(json.JSONEncoder): is_special = re.compile(r'^__[^\d\W]\w*__\Z', re.UNICODE) # Dunder name. def default(self, obj): return self._asdict(obj) def _asdict(self, obj, *, dict_factory=dict): if not dataclasses.is_dataclass(obj): raise TypeError("_asdict() should only be called on dataclass instances") return self._asdict_inner(obj, dict_factory) def _asdict_inner(self, obj, dict_factory): if dataclasses.is_dataclass(obj): result = [] # Get values of its fields (recursively). for f in dataclasses.fields(obj): value = self._asdict_inner(getattr(obj, f.name), dict_factory) result.append((f.name, value)) # Add values of non-special attributes which are properties. is_special = self.is_special.match # Local var to speed access. for name, attr in vars(type(obj)).items(): if not is_special(name) and isinstance(attr, property): result.append((name, attr.__get__(obj))) # Get property's value. return dict_factory(result) elif isinstance(obj, tuple) and hasattr(obj, '_fields'): return type(obj)(*[self._asdict_inner(v, dict_factory) for v in obj]) elif isinstance(obj, (list, tuple)): return type(obj)(self._asdict_inner(v, dict_factory) for v in obj) elif isinstance(obj, dict): return type(obj)((self._asdict_inner(k, dict_factory), self._asdict_inner(v, dict_factory)) for k, v in obj.items()) else: return copy.deepcopy(obj) if __name__ == '__main__': @dataclass(frozen=True) class Bar(): x: int y: int @property def z(self): return self.x + self.y @dataclass(frozen=True) class Foo(): a: int b: Bar @property def c(self): return self.a + self.b.x - self.b.y # Added for testing. d: List = field(default_factory=lambda: [42]) # Field with default value. foo = Foo(1, Bar(2,3)) print(json.dumps(foo, cls=MyCustomEncoder)) Output: {"a": 1, "b": {"x": 2, "y": 3, "z": 5}, "d": [42], "c": 0}
21
3
64,681,232
2020-11-4
https://stackoverflow.com/questions/64681232/why-is-it-that-input-shape-does-not-include-the-batch-dimension-when-passed-as
In Keras, why is it that input_shape does not include the batch dimension when passed as an argument to layers like Dense but DOES include the batch dimension when input_shape is passed to the build method of a model? import tensorflow as tf from tensorflow.keras.layers import Dense if __name__ == "__main__": model1 = tf.keras.Sequential([Dense(1, input_shape=[10])]) model1.summary() model2 = tf.keras.Sequential([Dense(1)]) model2.build(input_shape=[None, 10]) # why [None, 10] and not [10]? model2.summary() Is this a conscious choice of API design? If it is, why?
You can specify the input shape of your model in several different ways. For example by providing one of the following arguments to the first layer of your model: batch_input_shape: A tuple where the first dimension is the batch size. input_shape: A tuple that does not include the batch size, e.g., the batch size is assumed to be None or batch_size, if specified. input_dim: A scalar indicating the dimension of the input. In all these cases, Keras is internally storing an attribute _batch_input_size to build the model. Regarding the build method, my guess is that this is indeed a conscious choice - information about the batch size might be useful to build the model in some (perhaps unthought-of) situations. Therefore, a framework that includes the batch dimension as input to build is more generic and complete than a framework that doesn't. Nonetheless, I agree with you that naming the argument batch_input_shape instead of input_shape would make everything more consistent. It is also worth mentioning that users rarely need to call the build method by themselves. This happens internally when it is needed. Nowadays, it is even possible to ignore the input_shape argument when creating the model (although methods like summary will then not work until the model is built). In this case, Keras is able to infer the input shape from the argument x of fit.
13
7
64,731,890
2020-11-7
https://stackoverflow.com/questions/64731890/fastapi-supporting-multiple-authentication-dependencies
Problem I currently have JWT dependency named jwt which makes sure it passes JWT authentication stage before hitting the endpoint like this: sample_endpoint.py: from fastapi import APIRouter, Depends, Request from JWTBearer import JWTBearer from jwt import jwks router = APIRouter() jwt = JWTBearer(jwks) @router.get("/test_jwt", dependencies=[Depends(jwt)]) async def test_endpoint(request: Request): return True Below is the JWT dependency which authenticate users using JWT (source: https://medium.com/datadriveninvestor/jwt-authentication-with-fastapi-and-aws-cognito-1333f7f2729e): JWTBearer.py from typing import Dict, Optional, List from fastapi import HTTPException from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials from jose import jwt, jwk, JWTError from jose.utils import base64url_decode from pydantic import BaseModel from starlette.requests import Request from starlette.status import HTTP_403_FORBIDDEN JWK = Dict[str, str] class JWKS(BaseModel): keys: List[JWK] class JWTAuthorizationCredentials(BaseModel): jwt_token: str header: Dict[str, str] claims: Dict[str, str] signature: str message: str class JWTBearer(HTTPBearer): def __init__(self, jwks: JWKS, auto_error: bool = True): super().__init__(auto_error=auto_error) self.kid_to_jwk = {jwk["kid"]: jwk for jwk in jwks.keys} def verify_jwk_token(self, jwt_credentials: JWTAuthorizationCredentials) -> bool: try: public_key = self.kid_to_jwk[jwt_credentials.header["kid"]] except KeyError: raise HTTPException( status_code=HTTP_403_FORBIDDEN, detail="JWK public key not found" ) key = jwk.construct(public_key) decoded_signature = base64url_decode(jwt_credentials.signature.encode()) return key.verify(jwt_credentials.message.encode(), decoded_signature) async def __call__(self, request: Request) -> Optional[JWTAuthorizationCredentials]: credentials: HTTPAuthorizationCredentials = await super().__call__(request) if credentials: if not credentials.scheme == "Bearer": raise HTTPException( status_code=HTTP_403_FORBIDDEN, detail="Wrong authentication method" ) jwt_token = credentials.credentials message, signature = jwt_token.rsplit(".", 1) try: jwt_credentials = JWTAuthorizationCredentials( jwt_token=jwt_token, header=jwt.get_unverified_header(jwt_token), claims=jwt.get_unverified_claims(jwt_token), signature=signature, message=message, ) except JWTError: raise HTTPException(status_code=HTTP_403_FORBIDDEN, detail="JWK invalid") if not self.verify_jwk_token(jwt_credentials): raise HTTPException(status_code=HTTP_403_FORBIDDEN, detail="JWK invalid") return jwt_credentials jwt.py: import os import requests from dotenv import load_dotenv from fastapi import Depends, HTTPException from starlette.status import HTTP_403_FORBIDDEN from app.JWTBearer import JWKS, JWTBearer, JWTAuthorizationCredentials load_dotenv() # Automatically load environment variables from a '.env' file. jwks = JWKS.parse_obj( requests.get( f"https://cognito-idp.{os.environ.get('COGNITO_REGION')}.amazonaws.com/" f"{os.environ.get('COGNITO_POOL_ID')}/.well-known/jwks.json" ).json() ) jwt = JWTBearer(jwks) async def get_current_user( credentials: JWTAuthorizationCredentials = Depends(auth) ) -> str: try: return credentials.claims["username"] except KeyError: HTTPException(status_code=HTTP_403_FORBIDDEN, detail="Username missing") api_key_dependency.py (very simplified right now, it will be changed): from fastapi import Security, FastAPI, HTTPException from fastapi.security.api_key import APIKeyHeader from starlette.status import HTTP_403_FORBIDDEN async def get_api_key( api_key_header: str = Security(api_key_header) ): API_KEY = ... getting API KEY logic ... if api_key_header == API_KEY: return True else: raise HTTPException( status_code=HTTP_403_FORBIDDEN, detail="Could not validate credentials" ) Question Depending on the situation, I would like to first check if it has API Key in the header, and if its present, use that to authenticate. Otherwise, I would like to use jwt dependency for authentication. I want to make sure that if either api-key authentication or jwt authentication passes, the user is authenticated. Would this be possible in FastAPI (i.e. having multiple dependencies and if one of them passes, authentication passed). Thank you!
Sorry, got lost with things to do The endpoint has a unique dependency, call it check from the file check_auth ENDPOINT from fastapi import APIRouter, Depends, Request from check_auth import check from JWTBearer import JWTBearer from jwt import jwks router = APIRouter() jwt = JWTBearer(jwks) @router.get("/test_jwt", dependencies=[Depends(check)]) async def test_endpoint(request: Request): return True The function check will depend on two separate dependencies, one for api-key and one for JWT. If both or one of these passes, the authentication passes. Otherwise, we raise exception as shown below. DEPENDENCY def key_auth(api_key=Header(None)): if not api_key: return None ... verification logic goes here ... def jwt(authorization=Header(None)): if not authorization: return None ... verification logic goes here ... async def check(key_result=Depends(jwt_auth), jwt_result=Depends(key_auth)): if not (key_result or jwt_result): raise Exception
15
12
64,777,820
2020-11-10
https://stackoverflow.com/questions/64777820/do-i-need-to-keep-track-of-the-asyncio-event-loop-or-can-i-just-call-asyncio-ge
I am writing a REST API using aiohttp. Some of the coroutines need to call the database using the aiomysql library. The documentation for aiomysql has the following example: import asyncio import aiomysql loop = asyncio.get_event_loop() async def test_example(): conn = await aiomysql.connect(host='127.0.0.1', port=3306, user='root', password='', db='mysql', loop=loop) cur = await conn.cursor() await cur.execute("SELECT Host,User FROM user") print(cur.description) r = await cur.fetchall() print(r) await cur.close() conn.close() loop.run_until_complete(test_example()) My question is concerning the definition of the global variable loop: loop = asyncio.get_event_loop() Do I really need to keep loop as a global variable somewhere, or can I just call asyncio.get_event_loop() when I need it? For example, it the code example above, I could get the event loop when I am connecting to the database: conn = await aiomysql.connect(host='127.0.0.1', port=3306, user='root', password='', db='mysql', loop=asyncio.get_event_loop()) Is there a non-trivial runtime cost to calling asyncio.get_event_loop() or something else that I am missing?
loop argument should go. aiomysql should be updated to don't accept the loop. You can just skip loop=... in your code right now because aiomysql.connect() has the default loop=None value for the argument. In general, asyncio.get_event_loop() will be deprecated; asyncio.get_running_loop() is recommended for the usage from an async code when needed. Passing an explicit loop to asyncio API is deprecated starting from Python 3.8.
6
2
64,775,717
2020-11-10
https://stackoverflow.com/questions/64775717/calling-generated-init-in-custom-init-override-on-dataclass
Currently I have something like this: @dataclass(frozen=True) class MyClass: a: str b: str c: str d: Dict[str, str] ...which is all well and good except dicts are mutable, so I can't use my class to key another dictionary. Instead, I'd like field d to be something like a FrozenSet[Tuple[str, str]], but I'd still like someone constructing an instance of my class to be able to pass a dictionary on the constructor as this is much more intuitive. So I'd like to do something like @dataclass(frozen=True) class MyClass: a: str b: str c: str d: FrozenSet[Tuple[str, str]] = field(init=False) def __init__(self, a, b, c, d: Dict[str, str]): self.original_generated_init(a, b, c) # ??? object.setattr(self, 'd', frozenset(d.items())) # required because my dataclass is frozen How do I achieve this? Alternatively is there a more elegant way to achieve the same thing?
You can use an InitVar and assign to d in __post_init__: @dataclass(frozen=True) class MyClass: a: str b: str c: str d: FrozenSet[Tuple[str, str]] = field(init=False) d_init: InitVar[Dict[str, str]] def __post_init__(self, d_init): object.__setattr__(self, 'd', frozenset(d_init.items()))
7
9
64,771,988
2020-11-10
https://stackoverflow.com/questions/64771988/python-selenium-click-on-button-based-on-text-inside-span-tag
I want to click on this button when <Span text is "OK": <button type="button" class="ant-btn ant-btn-primary" style="float: right;"><span>OK</span></button> The soluton would be something like that (this code donΒ΄t work because itΒ΄s not clickable): driver.find_element_by_xpath('//span[text()="OK"]').click() I found a way that works, but I canΒ΄t garantee the text inside Span is "OK": button = driver.find_element_by_css_selector('#root > section > section > div.ant-row > div:nth-child(2) > div.ant-spin-nested-loading > div > div > div > div > div.ant-collapse-content.ant-collapse-content-active > div > div > div > div:nth-child(17) > button.ant-btn.ant-btn-primary') button.click() How can I click on buttons based on Span tag? Edit: Button code line
So, based on your button HTML <button type="button" class="ant-btn ant-btn-primary" style="float: right;"><span>OK</span></button> I think that the following xapth would help you. //button[contains(@class, 'ant-btn-primary')]//*[contains(., 'OK')]/.. The /.. helps you traverse back 1 level; sending you to the main button. In order to search for the "OK" text in a span, you need to use the node / period search. Which is why I did //*[contains(., 'OK')]. To find this button and then click on it, you would do the following driver.find_element(By.XPATH, "//button[contains(@class, 'ant-btn-primary')]//*[contains(., 'OK')]/..").click() ALTERNATE XPATH //button[contains(@class, 'ant-btn-primary') and contains(., 'OK')] And you would click on the button as such driver.find_element(By.XPATH, "//button[contains(@class, 'ant-btn-primary') and contains(., 'OK')]").click()
7
11
64,770,298
2020-11-10
https://stackoverflow.com/questions/64770298/how-to-repeat-the-body-of-a-with-statement-in-python
I want to implement a way to repeat a section of code as many times as it's needed using a context manager only, because of its pretty syntax. Like this: with try_until_success(attempts=10): command1() command2() command3() The commands must be executed once if no errors happen. And they should be executed again if an error occurred, until 10 attempts has passed, if so the error must be raised. For example, it can be useful to reconnect to a data base. The syntax I represented is literal, I do not want to modify it (so do not suggest me to replace it with a kind of for of while statements). Is there a way to implement try_until_success in Python to do what I want? What I tried is: from contextlib import contextmanager @contextmanager def try_until_success(attempts=None): counter = 0 while True: try: yield except Exception as exc: pass else: break counter += 1 if attempts is not None and counter >= attempts: raise exc And this gives me the error: RuntimeError: generator didn't stop after throw() I know, there are many ways to reach what I need using a loop instead of with-statement or with the help of a decorator. But both have syntax disadvantages. For example, in case of a loop I have to insert try-except block, and in case of a decorator I have to define a new function. I have already looked at the questions: How do I make a contextmanager with a loop inside? Conditionally skipping the body of Python With statement They did not help in my question.
The problem is that the body of the with statement does not run within the call to try_until_success. That function returns an object with a __enter__ method; that __enter__ method calls and returns, then the body of the with statement is executed. There is no provision for wrapping the body in any kind of loop that would allow it to be repeated once the end of the with statement is reached.
7
2
64,753,347
2020-11-9
https://stackoverflow.com/questions/64753347/should-domain-model-classes-always-depend-on-primitives
Halfway through Architecture Patterns with Python, I have two questions about how should the Domain Model Classes be structured and instantiated. Assume on my Domain Model I have the class DepthMap: class DepthMap: def __init__(self, map: np.ndarray): self.map = map According to what I understood from the book, this class is not correct since it depends on Numpy, and it should depend only on Python primitives, hence the question: Should Domain Model classes rely only on Python primitives, or is there an exception? Assuming the answer to the previous question is that classes should solely depend on primitives, what would the correct way create a DepthMap from a Numpy array be? Assume now I have more formats from where I can make a DepthMap object. class DepthMap: def __init__(self, map: List): self.map = map @classmethod def from_numpy(cls, map: np.ndarray): return cls(map.tolist()) @classmethod def from_str(cls, map: str): return cls([float(i) for i in s.split(',')]) or a factory: class DepthMapFactory: @staticmethod def from_numpy(map: np.ndarray): return DepthMap(map.tolist()) @staticmethod def from_str(map: str): return DepthMap([float(i) for i in s.split(',')]) I think even the Repository Pattern, which they go through in the book, could fit in here: class StrRepository: def get(map: str): return DepthMap([float(i) for i in s.split(',')]) class NumpyRepository: def get(map: np.ndarray): return DepthMap(map.tolist()) The second question: When creating a Domain Model Object from different sources, what is the correct approach? Note: My background is not software; hence some OOP concepts may be incorrect. Instead of downvoting, please comment and let me know how to improve the question.
I wrote the book, so I can at least have a go at answering your question. You can use things other than primitives (str, int, boolean etc) in your domain model. Generally, although we couldn't show it in the book, your model classes will contain whole hierarchies of objects. What you want to avoid is your technical implementation leaking into your code in a way that makes it hard to express your intent. It would probably be inappropriate to pass instances of Numpy arrays around your codebase, unless your domain is Numpy. We're trying to make code easier to read and test by separating the interesting stuff from the glue. To that end, it's fine for you to have a DepthMap class that exposes some behaviour, and happens to have a Numpy array as its internal storage. That's not any different to you using any other data structure from a library. If you've got data as a flat file or something, and there is complex logic involved in creating the Numpy array, then I think a Factory is appropriate. That way you can keep the boring, ugly code for producing a DepthMap at the edge of your system, and out of your model. If creating a DepthMap from a string is really a one-liner, then a classmethod is probably better because it's easier to find and understand.
19
16
64,760,484
2020-11-9
https://stackoverflow.com/questions/64760484/plotly-how-to-display-different-color-segments-on-a-line-chart-for-specified-th
I have a multi-line graph that displays percent increase over time. I'd like to set a threshold in my code to have an upper and lower bound. If the line falls outside these bounds, I'd like that specific part of the line graph to be a different color than its parent. This is what I am doing: import plotly.express as px import plotly.graph_objects as go fig = px.line(df14, x = "Date", y = "Percent", color = "id", title = "id Growth in Percentage (US)", labels = {"Percent": "Percent Growth"}) fig.update_layout( font_family="Arial", font_color="black", title_font_family="Arial", title_font_color="black", legend_title_font_color="black" #style the text (legend, title etc) ) fig.update_xaxes(title_font_family="Arial") #style ance center title fig.update_layout( title={ 'text': "id Growth Percentage in US (Line Graph)", 'y':0.9, 'x':0.5, 'xanchor': 'center', 'yanchor': 'top'}) fig.update_traces(mode='markers+lines') #add dots to line fig.show() This is the visual result: Let me zoom in on one line to better explain: I would like a threshold set for each id, and if the line goes above or below this threshold, the color will be different for that part of the line graph. For instance: The upper bound for id IAA may be 5 and the lower bound for IAA may be 0. Any value that is over 5 , or below 0, show be highlighted a specific color. The upper bound for id SSS may be 10 and the lower bound for SSS may be 3 Any value that is over 10, or below 3, should be highlighted a specific color. I am wanting the thresholds to be for each id Please see below: The highlighted yellow parts of the line reflect where the line graph has exceeded or decreased a set threshold. Is this possible to do this using Plotly? Here is the raw data example: Updated: id Start End Diff Percent Date IAA 4/1/2019 5/1/2019 160.4279 11.10809 04-01-2019 to 05-01-2019 IAA 5/1/2019 6/1/2019 136.0248 8.476798 05-01-2019 to 06-01-2019 IAA 6/1/2019 7/1/2019 174.0513 9.998946 06-01-2019 to 07-01-2019 IAA 7/1/2019 8/1/2019 112.0424 5.851551 07-01-2019 to 08-01-2019 IAA 8/1/2019 9/1/2019 141.8488 6.998691 08-01-2019 to 09-01-2019 IAA 9/1/2019 10/1/2019 103.5522 4.774984 09-01-2019 to 10-01-2019 IAA 10/1/2019 11/1/2019 125.6087 5.528085 10-01-2019 to 11-01-2019 IAA 11/1/2019 12/1/2019 145.2591 6.058016 11-01-2019 to 12-01-2019 IAA 12/1/2019 1/1/2020 115.5121 4.542251 12-01-2019 to 01-01-2020 IAA 1/1/2020 2/1/2020 185.7191 6.985673 01-01-2020 to 02-01-2020 IAA 2/1/2020 3/1/2020 126.7386 4.455896 02-01-2020 to 03-01-2020 IAA 3/1/2020 4/1/2020 231.3461 7.786734 03-01-2020 to 04-01-2020 IAA 4/1/2020 5/1/2020 97.02587 3.02981 04-01-2020 to 05-01-2020 IAA 5/1/2020 6/1/2020 42.85235 1.298792 05-01-2020 to 06-01-2020 IAA 6/1/2020 7/1/2020 124.666 3.729997 06-01-2020 to 07-01-2020 IAA 7/1/2020 8/1/2020 357.9974 10.32609 07-01-2020 to 08-01-2020 IAA 8/1/2020 9/1/2020 490.9587 12.8358 08-01-2020 to 09-01-2020 IAA 9/1/2020 10/1/2020 204.5478 4.739428 09-01-2020 to 10-01-2020 IAA 10/1/2020 11/1/2020 287.6025 6.362292 10-01-2020 to 11-01-2020 SSStest 4/1/2019 5/1/2019 12.38486 5.780551 04-01-2019 to 05-01-2019 SSStest 5/1/2019 6/1/2019 -2.61735 -1.15487 05-01-2019 to 06-01-2019 SSStest 6/1/2019 7/1/2019 -5.6187 -2.50814 06-01-2019 to 07-01-2019 SSStest 7/1/2019 8/1/2019 3.204252 1.467153 07-01-2019 to 08-01-2019 SSStest 8/1/2019 9/1/2019 -25.3782 -11.4521 08-01-2019 to 09-01-2019 SSStest 9/1/2019 10/1/2019 -10.9717 -5.59137 09-01-2019 to 10-01-2019 Any suggestions is appreciated Update Is there a way to make the full line display the marker dots on them? I have tried this: mode = 'markers+lines' but did not get the desired result: **Update, I have figured this out:** fig.update_traces(mode='markers+lines') Updated Question: Also,is there a way to add the Date and Percent titles on the hover annotation here?. I am researching the Plotly docs. [![enter image description here][4]][4]
I've put together a suggestion that should do exactly what you're asking for. The following figure is produced by the code sample below. The code uses a dictionary that contains the different upper and lower limits for your different PODs along with a possibility to set different colors for different pods: lim = {'IAD': {'lower': 90,'upper': 350, 'color':'yellow'}, 'SJCtest': {'lower': 10,'upper': 12, 'color':'green'}} Plot I was tempted to filter your dataframe first, and then add new traces to the figure based on that. But my solution actually goes through each datapoint for each trace, and colors the points based on the dictionary above. So no need for any datamunging. Take a look, run a few tests, and let me know how it works out for you. Complete code import pandas as pd import plotly.express as px import plotly.graph_objects as go df = pd.DataFrame({'POD': {0: 'IAD', 1: 'IAD', 2: 'IAD', 3: 'IAD', 4: 'IAD', 5: 'IAD', 6: 'IAD', 7: 'IAD', 8: 'IAD', 9: 'IAD', 10: 'IAD', 11: 'IAD', 12: 'IAD', 13: 'IAD', 14: 'IAD', 15: 'IAD', 16: 'IAD', 17: 'IAD', 18: 'IAD', 19: 'SJCtest', 20: 'SJCtest', 21: 'SJCtest', 22: 'SJCtest', 23: 'SJCtest', 24: 'SJCtest'}, 'Start': {0: '4/1/2019', 1: '5/1/2019', 2: '6/1/2019', 3: '7/1/2019', 4: '8/1/2019', 5: '9/1/2019', 6: '10/1/2019', 7: '11/1/2019', 8: '12/1/2019', 9: '1/1/2020', 10: '2/1/2020', 11: '3/1/2020', 12: '4/1/2020', 13: '5/1/2020', 14: '6/1/2020', 15: '7/1/2020', 16: '8/1/2020', 17: '9/1/2020', 18: '10/1/2020', 19: '4/1/2019', 20: '5/1/2019', 21: '6/1/2019', 22: '7/1/2019', 23: '8/1/2019', 24: '9/1/2019'}, 'End': {0: '5/1/2019', 1: '6/1/2019', 2: '7/1/2019', 3: '8/1/2019', 4: '9/1/2019', 5: '10/1/2019', 6: '11/1/2019', 7: '12/1/2019', 8: '1/1/2020', 9: '2/1/2020', 10: '3/1/2020', 11: '4/1/2020', 12: '5/1/2020', 13: '6/1/2020', 14: '7/1/2020', 15: '8/1/2020', 16: '9/1/2020', 17: '10/1/2020', 18: '11/1/2020', 19: '5/1/2019', 20: '6/1/2019', 21: '7/1/2019', 22: '8/1/2019', 23: '9/1/2019', 24: '10/1/2019'}, 'Diff': {0: 160.4279, 1: 136.0248, 2: 174.0513, 3: 112.0424, 4: 141.8488, 5: 103.5522, 6: 125.6087, 7: 145.2591, 8: 115.5121, 9: 185.7191, 10: 126.7386, 11: 231.3461, 12: 97.02587, 13: 42.85235, 14: 124.666, 15: 357.9974, 16: 490.9587, 17: 204.5478, 18: 287.6025, 19: 12.38486, 20: -2.61735, 21: -5.6187, 22: 3.204252, 23: -25.3782, 24: -10.9717}, 'Percent': {0: 11.108089999999999, 1: 8.476797999999999, 2: 9.998946, 3: 5.851551000000001, 4: 6.998691, 5: 4.774984, 6: 5.528085, 7: 6.058016, 8: 4.542251, 9: 6.985672999999999, 10: 4.455896, 11: 7.786734, 12: 3.02981, 13: 1.298792, 14: 3.729997, 15: 10.326089999999999, 16: 12.8358, 17: 4.739428, 18: 6.362292, 19: 5.780551, 20: -1.15487, 21: -2.50814, 22: 1.4671530000000002, 23: -11.4521, 24: -5.5913699999999995}, 'Date': {0: '04-01-2019 to 05-01-2019', 1: '05-01-2019 to 06-01-2019', 2: '06-01-2019 to 07-01-2019', 3: '07-01-2019 to 08-01-2019', 4: '08-01-2019 to 09-01-2019', 5: '09-01-2019 to 10-01-2019', 6: '10-01-2019 to 11-01-2019', 7: '11-01-2019 to 12-01-2019', 8: '12-01-2019 to 01-01-2020', 9: '01-01-2020 to 02-01-2020', 10: '02-01-2020 to 03-01-2020', 11: '03-01-2020 to 04-01-2020', 12: '04-01-2020 to 05-01-2020', 13: '05-01-2020 to 06-01-2020', 14: '06-01-2020 to 07-01-2020', 15: '07-01-2020 to 08-01-2020', 16: '08-01-2020 to 09-01-2020', 17: '09-01-2020 to 10-01-2020', 18: '10-01-2020 to 11-01-2020', 19: '04-01-2019 to 05-01-2019', 20: '05-01-2019 to 06-01-2019', 21: '06-01-2019 to 07-01-2019', 22: '07-01-2019 to 08-01-2019', 23: '08-01-2019 to 09-01-2019', 24: '09-01-2019 to 10-01-2019'}}) fig = px.line(df, x="Date", y="Diff", color = 'POD') import plotly.graph_objects as go included = 0 lim = {'IAD': {'lower': 90,'upper': 350, 'color':'yellow'}, 'SJCtest': {'lower': 10,'upper': 12, 'color':'green'}} for i, d in enumerate(fig.data): for j, y in enumerate(d.y): if y < lim[d.name]['lower'] or y > lim[d.name]['upper']: if j == 0: fig.add_traces(go.Scatter(x=[fig.data[i]['x'][j]], y=[fig.data[i]['y'][j]], mode = 'markers', marker = dict(color=lim[d.name]['color']), name = d.name + ' threshold', legendgroup = d.name + ' threshold')) included = included + 1 else: fig.add_traces(go.Scatter(x=[fig.data[i]['x'][j-1], fig.data[i]['x'][j]], y=[fig.data[i]['y'][j-1], fig.data[i]['y'][j]], mode = 'lines', # marker = dict(color='yellow'), line = dict(width = 6, color = lim[d.name]['color']), name = d.name + ' threshold', legendgroup = d.name + ' threshold', showlegend = False if included > 0 else True, )) included = included + 1 fig.show()
10
3
64,712,172
2020-11-6
https://stackoverflow.com/questions/64712172/deprecationwarning-please-use-dns-resolver-resolver-resolve
When using dns.resolver.Resolver() it returns a warning that I should use dns.resolver.Resolver.resolve () When I changed it, it further gives error: TypeError: resolve() missing 2 required positional arguments: 'self' and 'qname' This is the code: # my_resolver = dns.resolver.Resolver() my_resolver = dns.resolver.Resolver.resolve() answers = my_resolver.query(host, "A") answer_txt = my_resolver.query(host, "TXT") Any suggestions to fix this?
faced the same problem You should remove .resolve from my_resolver = dns.resolver.Resolver.resolve() and replace my_resolver.query() with my_resolver.resolve() Example: my_resolver = dns.resolver.Resolver() answers = my_resolver.resolve(host, "A") answer_txt = my_resolver.resolve(host, "TXT")
6
6
64,761,547
2020-11-10
https://stackoverflow.com/questions/64761547/using-python-f-string-in-a-json-list-of-data
I need to push data to a website through their API and I'm trying to find a way to use F-string to pass the variable in the data list but couldn't find a way. Here's what I've tried so far: today = datetime.date.today() tomorrow = today + datetime.timedelta(days = 1) #trying to pass *tomorrow* value with f-string below data = f'[{"date": "{tomorrow}", "price": {"amount": 15100}}]' response = requests.put('https://api.platform.io/calendar/28528204', headers=headers, data=data) How can I achieve this?
I would personally do something like this: import json import datetime today = datetime.date.today() tomorrow = today + datetime.timedelta(days = 1) data = [{ "date": str(tomorrow), "price": { "amount": 15100 } }] print(json.dumps(data)) Of course, after this, you can do anything you want with json.dumps(data): in your case, send it in a request.
7
12
64,754,025
2020-11-9
https://stackoverflow.com/questions/64754025/calculate-all-distances-between-two-geodataframe-of-points-in-geopandas
This is quite simple case, but I did not find any easy way to do it so far. The idea is to get a set of distances between all the points defined in a GeoDataFrame and the ones defined in another GeoDataFrame. import geopandas as gpd import pandas as pd # random coordinates gdf_1 = gpd.GeoDataFrame(geometry=gpd.points_from_xy([0, 0, 0], [0, 90, 120])) gdf_2 = gpd.GeoDataFrame(geometry=gpd.points_from_xy([0, 0], [0, -90])) print(gdf_1) print(gdf_2) # distances are calculated elementwise print(gdf_1.distance(gdf_2)) This produces the element-wise distance between points in gdf_1 and gdf_2 that share the same index (with also a warning because the two GeoSeries do not have the same index, which will be my case). geometry 0 POINT (0.000 0.000) 1 POINT (0.000 90.000) 2 POINT (0.000 120.000) geometry 0 POINT (0.00000 0.00000) 1 POINT (0.00000 -90.00000) /home/seydoux/anaconda3/envs/chelyabinsk/lib/python3.8/site-packages/geopandas/base.py:39: UserWarning: The indices of the two GeoSeries are different. warn("The indices of the two GeoSeries are different.") 0 0.0 1 180.0 2 NaN The question is; how is it possible to get a series of all points to points distances (or at least, the unique combinations of the index of gdf_1 and gdf_2 since it is symmetric). EDIT In this post, the solution is given for a couple of points; but I cannot find a straightforward way to combine all points in two datasets. In this post only element-wise operations are proposed. An analogous question was also raised on the GitHub repo of geopandas. One of the proposed solution is to use the apply method, without any detailed answer.
You have to apply over each geometry in first gdf to get distance to all geometric in second gdf. import geopandas as gpd import pandas as pd # random coordinates gdf_1 = gpd.GeoDataFrame(geometry=gpd.points_from_xy([0, 0, 0], [0, 90, 120])) gdf_2 = gpd.GeoDataFrame(geometry=gpd.points_from_xy([0, 0], [0, -90])) gdf_1.geometry.apply(lambda g: gdf_2.distance(g)) 0 1 0 0.0 90.0 1 90.0 180.0 2 120.0 210.0
9
14
64,744,849
2020-11-9
https://stackoverflow.com/questions/64744849/how-do-i-use-scale-color-manual-in-python
I've been using ggplot for a long time now and am very comfortable using it in R. I am working in Python right now for school and I am having the toughest time understanding this error. When I try to use scale_color_manual to manually assign colors to my variable called "CellTypeOther" which has unique values 0/1, I keep getting the following error: NameError: name 'c' is not defined Here is my code to create the ggplot: from plotnine import * plot = ( ggplot(Y_tsne,aes(x = 'X',y = 'Y')) + geom_point(aes(color = 'CellTypeOther'),alpha = 0.4,size = 2) + scale_color_manual(c("blue","red")) ) The plot renders fine without the last line. Does anyone have any clue as to what might be going on? I can't share my data because it is sensitive. Important note: I am using the plotnine Python module to utilize ggplot2.
You should use [] rather than c() in python:
6
8
64,716,495
2020-11-6
https://stackoverflow.com/questions/64716495/how-to-delete-the-file-after-a-return-fileresponsefile-path
I'm using FastAPI to receive an image, process it and then return the image as a FileResponse. But the returned file is a temporary one that need to be deleted after the endpoint return it. @app.post("/send") async def send(imagem_base64: str = Form(...)): # Convert to a Pillow image image = base64_to_image(imagem_base64) temp_file = tempfile.mkstemp(suffix = '.jpeg') image.save(temp_file, dpi=(600, 600), format='JPEG', subsampling=0, quality=85) return FileResponse(temp_file) # I need to remove my file after return it os.remove(temp_file) How can I delete the file after return it ?
You can delete a file in a background task, as it will run after the response is sent. import os import tempfile from fastapi import FastAPI from fastapi.responses import FileResponse from starlette.background import BackgroundTasks app = FastAPI() def remove_file(path: str) -> None: os.unlink(path) @app.post("/send") async def send(background_tasks: BackgroundTasks): fd, path = tempfile.mkstemp(suffix='.txt') with os.fdopen(fd, 'w') as f: f.write('TEST\n') background_tasks.add_task(remove_file, path) return FileResponse(path) Another approach is to use dependency with yield. The finally block code will be executed after the response is sent and even after all background tasks have been completed. import os import tempfile from fastapi import FastAPI, Depends from fastapi.responses import FileResponse app = FastAPI() def create_temp_file(): fd, path = tempfile.mkstemp(suffix='.txt') with os.fdopen(fd, 'w') as f: f.write('TEST\n') try: yield path finally: os.unlink(path) @app.post("/send") async def send(file_path=Depends(create_temp_file)): return FileResponse(file_path) Note: mkstemp() returns a tuple with a file descriptor and a path.
31
33
64,737,143
2020-11-8
https://stackoverflow.com/questions/64737143/is-there-a-networkx-algorithm-to-find-the-longest-path-from-a-source-to-a-target
I need to find a longest path in an unweighted graph from s to t. I am using NetworkX, which has an algorithm for finding a longest path in a directed, acyclic graph, but I am not able to specify the source and the target nodes. I have not been able to find any info online, but it seems like such an obvious algorithm to have laying around. Is there any way I can do this?
"[T]he longest path problem is the problem of finding a simple path of maximum length in a given graph."[1] NetworkX has a simple_paths module, that contains the function all_simple_paths. Below is one solution for finding the longest simple paths between two nodes. from typing import List import networkx as nx def longest_simple_paths(graph, source, target) -> List[List]: longest_paths = [] longest_path_length = 0 for path in nx.all_simple_paths(G, source=source, target=target): if len(path) > longest_path_length: longest_path_length = len(path) longest_paths.clear() longest_paths.append(path) elif len(path) == longest_path_length: longest_paths.append(path) return longest_paths G = nx.complete_graph(4) longest_paths = longest_simple_paths(G, source=0, target=3) if longest_paths: print(f"Longest simple path contains {len(longest_paths[0])} nodes") print(longest_paths) Output Longest simple path contains 4 nodes [[0, 1, 2, 3], [0, 2, 1, 3]] [1] Wikipedia contributors. "Longest path problem." Wikipedia, The Free Encyclopedia. Available from: https://en.wikipedia.org/wiki/Longest_path_problem. Accessed 8 November 2020.
6
4
64,733,556
2020-11-7
https://stackoverflow.com/questions/64733556/error-command-errored-out-with-exit-status-1-python-setup-py-egg-info-check-th
I'm trying to install dotenv for my discord bot with pip3 install dotenv but it keeps giving me this error: ERROR: Command errored out with exit status 1: command: /usr/bin/python3 -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-xmobtpdk/dotenv/setup.py'"'"'; __file__='"'"'/tmp/pip-install-xmobtpdk/dotenv/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base /tmp/pip-install-xmobtpdk/dotenv/pip-egg-info cwd: /tmp/pip-install-xmobtpdk/dotenv/ Complete output (51 lines): ERROR: Command errored out with exit status 1: command: /usr/bin/python3 -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-wheel-ts7a2idz/distribute/setup.py'"'"'; __file__='"'"'/tmp/pip-wheel-ts7a2idz/distribute/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base /tmp/pip-pip-egg-info-vsx7w_h3 cwd: /tmp/pip-wheel-ts7a2idz/distribute/ Complete output (15 lines): Traceback (most recent call last): File "<string>", line 1, in <module> File "/tmp/pip-wheel-ts7a2idz/distribute/setuptools/__init__.py", line 2, in <module> from setuptools.extension import Extension, Library File "/tmp/pip-wheel-ts7a2idz/distribute/setuptools/extension.py", line 5, in <module> from setuptools.dist import _get_unpatched File "/tmp/pip-wheel-ts7a2idz/distribute/setuptools/dist.py", line 7, in <module> from setuptools.command.install import install File "/tmp/pip-wheel-ts7a2idz/distribute/setuptools/command/__init__.py", line 8, in <module> from setuptools.command import install_scripts File "/tmp/pip-wheel-ts7a2idz/distribute/setuptools/command/install_scripts.py", line 3, in <module> from pkg_resources import Distribution, PathMetadata, ensure_directory File "/tmp/pip-wheel-ts7a2idz/distribute/pkg_resources.py", line 1518, in <module> register_loader_type(importlib_bootstrap.SourceFileLoader, DefaultProvider) AttributeError: module 'importlib._bootstrap' has no attribute 'SourceFileLoader' ---------------------------------------- ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output. Traceback (most recent call last): File "/home/fanjin/.local/lib/python3.8/site-packages/setuptools/installer.py", line 126, in fetch_build_egg subprocess.check_call(cmd) File "/usr/lib/python3.8/subprocess.py", line 364, in check_call raise CalledProcessError(retcode, cmd) subprocess.CalledProcessError: Command '['/usr/bin/python3', '-m', 'pip', '--disable-pip-version-check', 'wheel', '--no-deps', '-w', '/tmp/tmpa_3vnder', '--quiet', 'distribute']' returned non-zero exit status 1. The above exception was the direct cause of the following exception: Traceback (most recent call last): File "<string>", line 1, in <module> File "/tmp/pip-install-xmobtpdk/dotenv/setup.py", line 13, in <module> setup(name='dotenv', File "/home/fanjin/.local/lib/python3.8/site-packages/setuptools/__init__.py", line 152, in setup _install_setup_requires(attrs) File "/home/fanjin/.local/lib/python3.8/site-packages/setuptools/__init__.py", line 147, in _install_setup_requires dist.fetch_build_eggs(dist.setup_requires) File "/home/fanjin/.local/lib/python3.8/site-packages/setuptools/dist.py", line 673, in fetch_build_eggs resolved_dists = pkg_resources.working_set.resolve( File "/home/fanjin/.local/lib/python3.8/site-packages/pkg_resources/__init__.py", line 764, in resolve dist = best[req.key] = env.best_match( File "/home/fanjin/.local/lib/python3.8/site-packages/pkg_resources/__init__.py", line 1049, in best_match return self.obtain(req, installer) File "/home/fanjin/.local/lib/python3.8/site-packages/pkg_resources/__init__.py", line 1061, in obtain return installer(requirement) File "/home/fanjin/.local/lib/python3.8/site-packages/setuptools/dist.py", line 732, in fetch_build_egg return fetch_build_egg(self, req) File "/home/fanjin/.local/lib/python3.8/site-packages/setuptools/installer.py", line 128, in fetch_build_egg raise DistutilsError(str(e)) from e distutils.errors.DistutilsError: Command '['/usr/bin/python3', '-m', 'pip', '--disable-pip-version-check', 'wheel', '--no-deps', '-w', '/tmp/tmpa_3vnder', '--quiet', 'distribute']' returned non-zero exit status 1. ---------------------------------------- ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output. I'm using Linux and I already tried sudo pip3 install --upgrade pip setuptools wheel and tried install dotenv again but that didn't work. I also tried sudo easy_install -U setuptools but that didn't work either. I also tried installing another module and it worked, but not for dotenv.
Oh it's because the package is called python-dotenv not dotenv.
26
92
64,727,187
2020-11-7
https://stackoverflow.com/questions/64727187/tqdm-multiple-progress-bars-with-nested-for-loops-in-pycharm
The below question is for people who use PyCharm. There are nested for loops and tqdm is used for progress bars corresponding to each for loop. The code is shown below. from tqdm import tqdm import time for i in tqdm(range(5), desc="i", colour='green'): for j in tqdm(range(10), desc="j", colour='red'): time.sleep(0.5) But the problem is, the progress bars for the inner loop appear in newline everytime there is an update in the bar as shown below. i: 0%| | 0/5 [00:00<?, ?it/s] j: 0%| | 0/10 [00:00<?, ?it/s] j: 10%|β–ˆ | 1/10 [00:00<00:04, 1.94it/s] j: 20%|β–ˆβ–ˆ | 2/10 [00:01<00:04, 1.94it/s] j: 30%|β–ˆβ–ˆβ–ˆ | 3/10 [00:01<00:03, 1.96it/s] j: 40%|β–ˆβ–ˆβ–ˆβ–ˆ | 4/10 [00:02<00:03, 1.96it/s] j: 50%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ | 5/10 [00:02<00:02, 1.97it/s] j: 60%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ | 6/10 [00:03<00:02, 1.97it/s] j: 70%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ | 7/10 [00:03<00:01, 1.97it/s] j: 80%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ | 8/10 [00:04<00:01, 1.98it/s] j: 90%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ | 9/10 [00:04<00:00, 1.98it/s] j: 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 10/10 [00:05<00:00, 1.98it/s] i: 20%|β–ˆβ–ˆ | 1/5 [00:05<00:20, 5.06s/it] j: 0%| | 0/10 [00:00<?, ?it/s] j: 10%|β–ˆ | 1/10 [00:00<00:04, 2.00it/s] j: 20%|β–ˆβ–ˆ | 2/10 [00:01<00:04, 1.99it/s] j: 30%|β–ˆβ–ˆβ–ˆ | 3/10 [00:01<00:03, 1.99it/s] j: 40%|β–ˆβ–ˆβ–ˆβ–ˆ | 4/10 [00:02<00:03, 1.99it/s] j: 50%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆ | 5/10 [00:02<00:02, 1.99it/s] j: 60%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ | 6/10 [00:03<00:02, 1.99it/s] j: 70%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ | 7/10 [00:03<00:01, 1.99it/s] j: 80%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ | 8/10 [00:04<00:01, 1.99it/s] j: 90%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ | 9/10 [00:04<00:00, 1.99it/s] j: 100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 10/10 [00:05<00:00, 1.99it/s] i: 40%|β–ˆβ–ˆβ–ˆβ–ˆ | 2/5 [00:10<00:15, 5.05s/it] Setting the parameter 'position` for each loop also doesn't fix the issue. from tqdm import tqdm import time for i in tqdm(range(5), desc="i", colour='green', position=0): for j in tqdm(range(10), desc="j", colour='red', position=1): time.sleep(0.5) How does one get the progress bar to update in the same line?
The solution is two fold. Go to "Edit configurations". Click on the run/debug configuration that is being used. There should be an option "Emulate terminal in output console". Check that. Image added for reference. Along with the position argument also set the leave argument. The code should look like this. I have added ncols so that the progress bar doesn't take up whole of the console. from tqdm import tqdm import time for i in tqdm(range(5), position=0, desc="i", leave=False, colour='green', ncols=80): for j in tqdm(range(10), position=1, desc="j", leave=False, colour='red', ncols=80): time.sleep(0.5) When the code is now run, the output of the console is as shown below. i: 20%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ– | 1/5 [00:05<00:20, 5.10s/it] j: 60%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–Œ | 6/10 [00:03<00:02, 1.95it/s] The updates happen on the same line.
25
37
64,723,478
2020-11-7
https://stackoverflow.com/questions/64723478/do-full-outer-join-with-pandas-merge-asof
Hi I need to align some time series data with nearest timestamps, so I think pandas.merge_asof could be a good candidate. However, it does not have an option to set how='outer' like in the standard merge method. An example can be: df1: Value1 Time 2020-07-17 14:25:03.535906075 108 2020-07-17 14:25:05.457247019 110 2020-07-17 14:25:07.467777014 126 df2: Value2 Time 2020-07-17 14:25:03.535018921 222 2020-07-17 14:25:04.545104980 150 2020-07-17 14:25:07.476825953 60 Then for example, do this merge_asof: pd.merge_asof(df1, df2, left_index=True, right_index=True, direction='nearest', tolerance=pd.Timedelta('0.3s')) The results will be: Value1 Value2 Time 2020-07-17 14:25:03.535906075 108 222.0 2020-07-17 14:25:05.457247019 110 NaN 2020-07-17 14:25:07.467777014 126 60.0 But what I want is: Value1 Value2 Time 2020-07-17 14:25:03.535906075 108 222.0 2020-07-17 14:25:04.545104980 NaN 150.0 <---- this is the difference 2020-07-17 14:25:05.457247019 110 NaN 2020-07-17 14:25:07.467777014 126 60.0 basically like a full outer join. Any suggestion? Thanks in advance. EDIT: So this is the case with 2 dataframes. What if, say for example, there are 10 dataframes (i.e. df1, df2, ..., df10) need to do this "nearest" merging, what will be a good way to do?
This seems simple enough yet no direct solution. There's an option to merge again to bring in the missing rows: # enumerate the rows of `df2` to later identify which are missing df2 = df2.reset_index().assign(idx=np.arange(df2.shape[0])) (pd.merge_asof(df1.reset_index(), df2[['Time','idx']], on='Time', direction='nearest', tolerance=pd.Timedelta('0.3s')) .merge(df2, on='idx', how='outer') # merge back on row number .assign(Time=lambda x: x['Time_x'].fillna(x['Time_y'])) # fill the time .set_index(['Time']) # set index back .drop(['Time_x','Time_y','idx'], axis=1) .sort_index() ) Value1 Value2 Time 2020-07-17 14:25:03.535906075 108.0 222.0 2020-07-17 14:25:04.545104980 NaN 150.0 2020-07-17 14:25:05.457247019 110.0 NaN 2020-07-17 14:25:07.467777014 126.0 60.0
7
2
64,697,755
2020-11-5
https://stackoverflow.com/questions/64697755/exporting-forecast-data-from-darts
I am trying to export the forecasts I made with Pytorch models in darts library to some exchangeable format like XLS or CSV. Is it somehow possible to export the predictions from the Timeseries class? How can I specify output format?
Forecasts in Darts are nothing but regular TimeSeries objects and a TimeSeries is internally represented as a pandas.DataFrame. You can access this DataFrame using series.pd_dataframe() (to get a copy of the DataFrame) or series._df directly if you want to avoid copying the DataFrame to save it. Be careful in the latter case however, as modifying the DataFrame in place will break the TimeSeries immutability. You can then use any method you'd like to save pandas dataframes, e.g. pandas.DataFrame.to_csv() or pandas.DataFrame.to_pickle(). You can have a look at this article on Medium to see a comparison of a couple different formats' performances for saving and loading dataframes.
6
11
64,716,790
2020-11-6
https://stackoverflow.com/questions/64716790/save-pytorch-4d-tensor-as-image
I have a 4-d Pytorch tensor that I would like to save to disk as a .jpg My tensor is the following size: print(image_tensor.size()) >>>torch.Size([1, 3, 400, 711]) I can view the entire tensor as one image within my IDE: ax1.imshow(im_convert(image_tensor)) Since I am able to view the entire tensor as one image, I am assuming there is a way to also save it as such. However, when I try to save the image, it looks like it only saves the blue color channel. I would like to save the entire tensor as a single image. img1 = image_tensor[0] save_image(img1, 'img1.jpg')
In PyTorch this snippet is working and saving the image: from torchvision.utils import save_image import torch import torchvision tensor= torch.rand(2, 3, 400, 711) img1 = tensor[0] save_image(img1, 'img1.png') Before saving the image can you check the shape of the img1 in any case something happened.
6
15