content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import time def seconds_benchmark(function_wrapper): """ outer wrapper function to perform inner wrap for seconds benchmark. :param function_wrapper: The entire function object. :return: """ @wraps(function_wrapper) def wrap(*args, **kwargs): """ :param args: positional a...
f392e26989c459d625f222740e133f2838c4f1a8
39,100
def lineage(taxonomy, data): """ Get a standardized lineage for the given taxon id. """ if data["ncbi_tax_id"] in taxonomy: return taxonomy["ncbi_tax_id"].lineage return phy.lineage(data["ncbi_tax_id"])
dcc3d583bcce2dcfc498e0cd8311a69a72a1a950
39,101
def label_accuracy_score(label_trues, label_preds, n_class): """Returns accuracy score evaluation result. - overall accuracy - mean accuracy - mean I0U - fwavacc """ hist = np.zeros((n_class, n_class)) for lt, lp in zip(label_trues, label_preds): hist += _fast_his...
3039e958862889f6efa9f1df156e76f8c4fd591d
39,102
def candidates(address, text, confidence=0.0, support=0, spotter='Default', disambiguator='Default', filters=None, headers=None): """ Get the candidate entities from a text. Uses the same arguments as :meth:`annotate`. :rtype: list of surface forms """ payload = {...
e03810151b54cc5e9dd65c846b3df77774a41a27
39,103
def service_account_permissions(session, service_account): # type: (Session, ServiceAccount) -> List[ServiceAccountPermission] """Return the permissions of a service account.""" permissions = session.query(Permission, ServiceAccountPermissionMap).filter( Permission.id == ServiceAccountPermissionMap....
a4fe5535a6c1b5fc788666ac50c3c79c5fd27d56
39,104
def compete_metabolite(model, metabolite, reference_dist, fraction=0.5, allow_accumulation=True, constant=1e4): """ Increases the usage of a metabolite based on a reference flux distributions. Parameters ---------- model : Model A constraint-based model. metabolite : cobra.Metabolite ...
f127454e6319754e5bd27ea32648cc35f0b9e887
39,105
import warnings def check_angle_sampling(nvecs, angles): """ Returns a list of the index of elements of n which do not have adequate toy angle coverage. The criterion is that we must have at least one sample in each Nyquist box when we project the toy angles along the vector n. Parameters ---...
60701c11d94624f9560379ef6f48bd7f3aa334b2
39,106
def corrfrac(filelist): """Invokes validate() on the given list of file names. Returns the fraction of correct predictions. """ return float(len(validate(filelist))) / len(filelist)
307c6e52f53162e1b24ec115f314930f3b7ed38b
39,107
import requests def create_graph(workspace: str, graph_name: str, edge_table: str) -> bool: """Create a graph.""" resp = requests.post( f"{root_api_endpoint()}/workspaces/{workspace}/graphs/{graph_name}", params={"edge_table": edge_table}, ) if resp.ok: return True return...
f6ab58b4d76909950e06e441874877009dfc732e
39,108
def main(): """Main method of this script.""" # Use the directory that contains recordings on Dreamboxes as default. default_directory = '/media/hdd/movie' # Per default we want to have 50GB of free space. min_avail_space = 50*1024 # Override defaults with values given on the command line. ...
8f89b2054c480974b70e487053582ed14ce006e0
39,109
from typing import Optional import re def extraer_numero_iniciativa(numero_evento: str) -> Optional[int]: """Algunos numeros de evento traen la iniciativa a la que pertenecen, esta función intenta extraer el ID Returns ------- int or None ID de iniciative o None si no existe un numero con...
3c1abffca75a66bfad5c9556a194b904b39422c0
39,110
def next_key(tuple_of_tuples, key): """Processes a tuple of 2-element tuples and returns the key which comes after the given key. """ for i, t in enumerate(tuple_of_tuples): if t[0] == key: try: return tuple_of_tuples[i + 1][0] except IndexError: ...
cb4cdad805049cf57db21180c390bccfb8483f45
39,111
def sort_crt(crt): """Sort df by CRT""" return (crt[1],) + get_name_sortkey(crt[0])
804d951aacd67184a6558a83812488051f4661bf
39,112
import argparse def parse_args(): """ Parses passed in CLI arguments. Output: tuple: YouTube playlist URL string, VLC Install Directory """ parser = argparse.ArgumentParser(description="Streams YouTube Playlist in VLC") parser.add_argument( "youtube_playlist_URL", metavar="YouT...
cb67db44f0009abec75b06bdf6b55a8b92980bf8
39,113
def zd_to_airmass(zd): """ conversion of zenith airmass into airmass assuming Pickering (2002). """ alt = 90. - zd # Altitude in degrees return 1. / np.sin((alt + 244. / (165. + 47. * alt**1.1)) / RAD2DEG)
634b94685c5575530585407241d4da26944f5ff7
39,114
def create_final_generator_network( Z, projection_layer, to_rgb_conv_layers, blocks, original_image_size, params): """Creates base generator network. Args: Z: tensor, latent vectors of shape [cur_batch_size, latent_size]. projection_layer: `Dense` layer for projection of noise into imag...
8f5a83a018f9d35817de92f156457b26716a4f64
39,115
def rss(app, request): """Dump the last N days' updates as an RSS feed. """ releases = app.db.packaging.get_recently_updated(num=40) for release in releases: values = dict(project_name=release['name'], version=release['version']) url = app.urls.build('warehouse.packaging.views.project_de...
bfd430cd4a74aa89d3e04099734af592eb7df71a
39,116
def delete_redshift_cluster(config, redshift): """ Deletes the Redshift cluster specified in config Args: config: a ConfigParser object redshift: a boto3 client object for the AWS Redshift service """ try: print("Deleting Redshift Cluster: ", config['CLUSTER']['IDENTIFIER']) ...
2267eb4f017354563c9a7cf047a3a84983cd0044
39,117
def NaturalColor(C, gamma=0.8, pseudoGreen=True, night_IR=False, **kwargs): """ Natural Color RGB based on CIMSS method. Thanks Rick Kohrs! (See `Quick Guide <http://cimss.ssec.wisc.edu/goes/OCLOFactSheetPDFs/ABIQuickGuide_CIMSSRGB_v2.pdf>`__ for reference) Check out Rick Kohrs `merged GOES images <htt...
86acae6d74057771578f25a9f9aac9369a570624
39,118
def _get_adjacency_list(graph): """Convert a list of edges into an adjacency list.""" adj = {} for i, j in graph: if i in adj: ni = adj[i] else: ni = adj[i] = set() if j in adj: nj = adj[j] else: nj = adj[j] = set() ni.a...
933ba9aa28a13e145be175120520253ef53c2a88
39,119
def behavior_of(classname): """ Finds and loads the behavior class for C++ (decoded) classname or returns None if there isn't one. Behaviors do not have a required base class, and they may be used with Awkward Array's ``ak.behavior``. The search strategy for finding behavior classes is: 1...
cd0a104620cb98edacad8d822d3d64a030b0ae99
39,120
def pareto_rank(df: pd.DataFrame, objectives: list, max_rank: int = 10) -> pd.DataFrame: """ Rank solutions based on pareto dominance :param df: :param objectives: :return: DataFrame with additional column 'pareto_rank' """ df['pareto_rank'] = np.nan rank = 0 evaluating = df[objecti...
60aeaa7c52adbcfb79a71ba754c2ae8fe13a35a1
39,121
def get_domain_notes(domain): """ Combine all domain notes if there are any. """ all_notes = domain.http.notes + domain.httpwww.notes + domain.https.notes + domain.httpswww.notes all_notes = all_notes.replace(',', ';') return all_notes
f199e909184475f6c84a290ef7ac5ad9ff160a54
39,122
def add_trailing_load(axle_spacing, axle_wt, space_to_trailing_load, distributed_load, span1_begin, span2_end, pt_load_spacing=0.5): """Approximates the distributed trailing load as closely spaced point loads. The distributed trailing load is approximated as discretly spaced point loads. The point ...
3eac900cff7d5e66c399e7f846d66aeff3e7389c
39,123
def str_append(string, add): """Append add in end string. Example: str_append('hou', 'se'); Return='house'""" return string + str(add) + "\n"
efbc9a085d1e63f290af3e6c447cde13bce5f5d0
39,124
def parse_trigger_plugin(trigger_path, plugin_config, parse_only=False): """Parse plugin file and return the trigger config.""" # Open and exec plugin definitions with open(trigger_path, 'r') as f: trigger_code = f.read() trigger_vars = {} exec(trigger_code, trigger_vars) # Get trigger...
69feab8e6d109f9f5a641c3fb738710e97707e19
39,125
import json def signout(): """Signout. 退出。 """ session.pop('kb', None) session.pop('islogin', None) database.skb = '' state = { 'success' : 1, 'message' : "退出成功" } return json.dumps(state)
dfb38a2aad6f4deaf0e971c3e604ab005759a353
39,126
import os import subprocess import io import shutil import asyncio async def make_spray(message): """ Creates a Source engine spray from an image. Example:: /drawtext Hello there! | make spray You can also upload an image as an attachment and then use this command. """ if not os.pa...
1c23d5b50ea7e5c6bc52bc6a96cb3a1c328b1ec0
39,127
from .plot_utils import make_3d_axis, Arrow3D def plot_axis_angle(ax=None, a=a_id, p=p0, s=1.0, ax_s=1, **kwargs): """Plot rotation axis and angle. Parameters ---------- ax : Matplotlib 3d axis, optional (default: None) If the axis is None, a new 3d axis will be created a : array-like, s...
5a239a26eb070c0f7a4126b22ceff5f40098b0fb
39,128
from typing import Tuple from typing import List import numpy def generate_hash_rates(hash_rate_parameter: int, number_of_honest_miners: int, malicious_hash_ratio: float) -> \ Tuple[List[float], List[float]]: """ :param number_of_honest_miners: :param malicious_hash_ratio: :return: """ ...
5c02a78015c8f0d16922a37e5de163ca287932ba
39,129
def create_function(treatment_system, parameter, values): """ Creates a function based on user input """ func = str(treatment_system.loc[0, parameter]) func = func.replace(' ', '') for key, value in values.items(): func = func.replace(key, str(value)) return func
d0afaf42e50aef943b7551c60f19d180bbbeba0b
39,130
def _ResourceGraphvizNode(resource, request, resource_to_index): """Returns the node description for a given resource. Args: resource: Resource. request: RequestData associated with the resource. resource_to_index: {Resource: int}. Returns: A string describing the resource in graphviz format. ...
e3a1ba2bbe73992444cd001f44f2ac9546f256af
39,131
def unformat(combination: str) -> str: """Unformats a formatted string to it's original state""" return str(combination).replace("<", "").replace(">", "")
d017903ddaac78adf5085198d25eb508b62a78b4
39,132
def common_base(cls: type, *clss: type) -> type: """ Overview: Get common base class of the given classes. Only ``__base__`` is considered. Arguments: - cls (:obj:`type`): First class. - clss (:obj:`type`): Other classes. Returns: - base (:obj:`type`): Common ba...
40d43f9aa71537604d2a48ea7705985653f4ed8b
39,133
def get_all_configs() -> Response: """Get and return all configs by name""" return flask.jsonify(config.get_config_names())
dda1c4991129e8c5072ab06c60777d8eeece3ffb
39,134
def dewpoint(temperature, humidity, *, model='hardy', isdew=True): """Calculate the dew point. Parameters ---------- temperature : :class:`float` The temperature [degree C]. humidity : :class:`float` The humidity [%RH]. model : :class:`str` The dew point model, valid mod...
f2e2b7512a3f7a4ce5ded2fd9f7e51cb9f743408
39,135
import re def parse_list_marker(line, offset): """ Parse a list marker and return data on the marker (type, start, delimiter, bullet character, padding) or null. """ rest = line[offset:] spaces_after_marker = None data = ListData() if reHrule.search(rest): return None ...
b295d46c5c4e3ad4b6ac845f883b949c3e18b75b
39,136
def resize(img, height=800, allways=False): """Resize image to given height.""" if (img.shape[0] > height or allways): rat = height / img.shape[0] return cv.resize(img, (int(rat * img.shape[1]), height)) return img
011e42c0ef4fbc1c7e77914673a1d3d61771ff92
39,137
import re def _size_to_bytes(size): """ Parse a string with a size into a number of bytes. I.e. parses "10m", "10MB", "10 M" and other variations into the number of bytes in ten megabytes. Floating-point numbers are rounded to the nearest byte. :type size: ``str`` :param size: The size to parse, given as a stri...
833657e51bb2c54b0e86684759e263d2f8b03ffe
39,138
import os def writetofile(filename, string_to_write): """Takes a string and writes to a filename TODO: Figure out why os.path.exists is not WORKING Example: writetofile("myfile.html", htmlbuffer) """ if os.path.exists(filename): return f"Error: {filename} exists already" else: ...
f77024b62c38691d55b4adbcb22d93abb9727115
39,139
import torch def transform_to_tensor_per_dataset(feature, label, drug,device, basal_expression_file): """ :param feature: features like pertid, dosage, cell id, etc. will be used to transfer to tensor over here :param label: :param drug: ??? a drug dictionary mapping drug name into smile strings ...
f238ffa2a042942d5df2cf858435a5b1e5080872
39,140
def isbn_gendigit (numStr): """ (string)-->(string + 1-digit) Generates the 10th digit in a given 9-digit isbn string. Multiplies the values of individual digits within the given 9-digit string to determine the 10th digit. Prints the original string with its additional 10th digit. ('123456788')-->12...
2ceb5cb4f2f8efc2ee9625138666f7cca2c4aefb
39,141
def count_unique_sequences_per_otu(otu_ids, otu_map_file, input_seqs_file): """Counts unique sequences per-OTU for a given set of OTUs otu_ids: a set of OTU IDs otu_map_file: file-like object in the format of an OTU map input_seqs_file: FASTA containing sequences that were used to generate ...
8a50160ac14a6a6960c63a68f8b23e5fe3df043a
39,142
from typing import Tuple def fetch_add_portmapping_services() -> Tuple[UPnPServiceNames, ...]: """ :return: returns the available devices and services for which the action 'AddPortMapping' exists """ devices = upnpclient.discover() if not devices: raise NoPortMapServiceFound("No UPnP devic...
006fc914558be3afa9f8c05451c8816d6e7c0cb4
39,143
def is_valid_group(group_name, nova_creds): """ Checks to see if the configuration file contains a SUPERNOVA_GROUP configuration option. """ valid_groups = [value['SUPERNOVA_GROUP'] for key, value in nova_creds.items() if 'SUPERNOVA_GROUP' in nova_creds[key].k...
6f94e88cfcea8775bab3c05a0720ba7df11f68cc
39,144
import os import json import glob def read_config(env): """ Read the build configuration file and creates a dictionary to be used throughout the project Args: env: Environmental variable where the config file is Return: Dictionary of the configuration Raises: Configu...
09d72b6aad290a553abbea751774a77a1600ab8a
39,145
import math def Make_scroll_bar(self, scroll_bar): """ Make a scroll_bar for a Text object. For internal use only. This function is therefore also not imported by __init__.py """ if isinstance(scroll_bar, Slider): scroll_bar.right = self.width - self.text_offset[0] scroll_bar.cente...
1cf7e94dfddb32a9ac55e72a58b41b6642a96411
39,146
def value_iteration(env, rewards): """ Computes a policy using value iteration given a list of rewards (one reward per state) """ n_states = env.observation_space.n n_actions = env.action_space.n V_states = np.zeros(n_states) theta = 1e-8 gamma = .9 maxiter = 1000 policy = np.zeros(n_sta...
29dcd90de0881986f2b08621dd0fac32c5eee305
39,147
def mktime(t): """mktime(tuple) -> floating point number Convert a time tuple in local time to seconds since the Epoch.""" tm_year = t[0] tm_mon = t[1] - 1 tm_mday = t[2] tm_hour = t[3] tm_min = t[4] tm_sec = t[5] date = JS("new Date(@{{tm_year}}, @{{tm_mon}}, @{{tm_mday}}, @{{tm_hou...
e35b7a4f1367f9951201540c17aa4032113e5113
39,148
import pandas def package_matrix(request, pkg=None, arch=None): """ Generate a build matrix for one or more specs. """ # Unique package names and os options packages = ( Spec.objects.exclude(build=None).values_list("name", flat=True).distinct() ) failed_packages = ( Spec.ob...
2bcfb437062b92bc4c02140b07a9cdf5803f0995
39,149
import argparse import textwrap def parse_args(argv): """ Parse list of strings into argparse.Namespace() Arguments: argv a list of strings, typically contents of sys.argv WARNING: if argv is malformed, the process will exit. Avoid using this function in tests. """ description =...
aae086b9d61c9e5928849691d5c7ded656c18074
39,150
def _PlcReady(timeout=1): """Returns True if PLC AIO node reports actuator state is 'ready'.""" t_start = time.time() while time.time() - t_start < timeout: ready = (listener.status_msg and (listener.status_msg.detwist_state == actuator_types.kActuatorStateReady)) if...
1da6241efdfe8b1bcae5e8894f35a6708a11f963
39,151
from typing import List def convert_dataframe(metrics: List[Metric]) -> pd.DataFrame: """ convert_dataframe converts list of metric to pandas DataFrame """ fields = ['date', 'point'] columns = {'date': 'ds', 'point': 'y'} return pd.DataFrame([{f: getattr(m, f) for f in fields} for m in metrics...
2bf41a0089928c6f1842dd56ff86e6ca47a7e079
39,152
def linear_shap_corr(model, data): """ Linear SHAP (corr 1000) """ return LinearExplainer(model, data, nsamples=1000).shap_values
9239b8a1083195321a766cd9894db307276ab33d
39,153
import torch def ind2sub(ind, shape, out=None): """Convert linear indices into sub indices (i, j, k). The rightmost dimension is the most rapidly changing one -> if shape == [D, H, W], the strides are therefore [H*W, W, 1] Parameters ---------- ind : tensor_like Linear indices sh...
001a88850721f8946c48a395454e6818e78a7887
39,154
import requests def get_repo_prs(r, state, base, session): """ Get all pull requests of a given repository :param r: repository name 'author/repo-name' :param state: state of the PR :param base: base branch :param session: open and authenticated session :type r: string ...
898f1937978114df673e0291a2a18f7e5f3f2d12
39,155
def register(): """Register user""" # Forget any user_id session.clear() # User reached route via POST (as by submitting a form via POST) if request.method == "POST": # Ensure username was submitted if not request.form.get("firstname"): return apology("must provide FIR...
7799a1a7284fb311bd58fbb1f6882bf84d49b2e7
39,156
def format_sse(data: str, event=None) -> str: """Formats a string and an event name in order to follow the event stream convention. >>> format_sse(data=json.dumps({'abc': 123}), event='Jackson 5') 'event: Jackson 5\\ndata: {"abc": 123}\\n\\n' """ msg = f'data: {data}\n\n' if event is not None:...
a97cbd392b3ed087c5663fc1e874c30c20d61039
39,157
from typing import Tuple async def _unpack_message(session: Session, enc_message: bytes) -> Tuple[str, str, str]: """Decode a message using the DIDComm v1 'unpack' algorithm.""" try: wrapper = JweEnvelope.from_json(enc_message) except ValidationError: raise WalletError("Invalid packed mess...
84c96ac11a19f59a2e205c3f3a6ec8597c22e519
39,158
def minweight_match_realmxeigs(a, b, metricfn=None, pass_indices_to_metricfn=False, eps=1e-9): """ Matches the elements of `a` and `b`, whose elements are assumed to either real or one-half of a conjugate pair. Matching is performed by minimizing the weight between elements, ...
e98d7f4f5f41e9672a2863fc5d7bc2c2c8bf0c10
39,159
def _invert_aliases(): """Reverse the alias dictionary to be a lookup from command to aliases.""" out = _defaultdict(list) for alias, name in ALIASES.items(): out[name].append(alias) return out
d4b88ee5434fe989cd71ae730573cd4b6bab1562
39,160
import math def get_positive_expectation(p_samples, average=True): """Computes the positive part of a JS Divergence. Args: p_samples: Positive samples. average: Average the result over samples. Returns: th.Tensor """ log_2 = math.log(2.) Ep = log_2 - tlx.softplus(- p_sa...
db8d991ebe2bf46c58d150cb7d0fdd5122e0ccaa
39,161
def setbit(byte, offset, value): """ Set a bit in a byte to 1 if value is truthy, 0 if not. """ if value: return byte | (1 << offset) else: return byte & ~(1 << offset)
037fa6e6a14c502554a3e5ee94e2f9ed63e2f717
39,162
def insertDoubleQuote(string, index): """ Insert a double quote in the specified string at the specified index and return the string.""" return string[:index] + '\"' + string[index:]
00d16f3bc619765895408f9fcdd3a7a6e428b153
39,163
import io import base64 def title_cloud(cat, rate, year): """ Makes a word cloud of movie and TV show titles. Parameters ---------- cat: list List of genres we want to filter out from the dataframe. rate: list List of ratings we want to filter out from the dataframe. y...
af42db09486a60fab6e7da5df0dc53b5f24deefc
39,164
import torch def run_one_epoch_aae(model, x, y, num_critic=1, clip_value=0.01, train=True, optimizer=None, batch_size=None, return_loss=True, loss_weight=[1., 1., 1.], loss_fn_cls=nn.CrossEntropyLoss(), loss_fn_reg=nn.MSELoss(), loss_fn_critic=nn.L1Lo...
125d6d34eb50b5f20b6d726a90cc85040f9c571c
39,165
def And(*seq): """ Return boolean expression ``x1 and x2 and ...``. """ c = Logic.convert return Logic.And(*map(c, seq))
f6229ca92a52263d26476741c2f3ce9e495678c1
39,166
def powerlaw(x, a, b, c): """Powerlaw function used by fitting software to characterise uncertainty.""" return a * x**b + c
e67a0be2f5faaff7867b713b43caec48910bad87
39,167
def quatFromXYZW(xyzw, seq): """Convert quaternion from XYZW (pybullet convention) to arbitrary sequence.""" assert ( len(seq) == 4 and "x" in seq and "y" in seq and "z" in seq and "w" in seq ), "Quaternion sequence {} is not valid, please double check.".format(seq) inds = ["xyzw".index(axis) fo...
87d8a907fd5fc95c320df03feeffe8c185ad78e9
39,168
def readPeakList(peak_file): """ Read in list of peaks to delete from peaks_file. Comment lines (#) and blank lines are ignored. """ f = open(peak_file,'r') peak_list = f.readlines() f.close() peak_list = [l for l in peak_list if l[0] != "#" and l.strip() != ""] peak_list = [...
7c99f9fb18b36b658fe142a43adf18db7c42c7bd
39,169
import ast def parse_coordinates(raw_coordinates): """Parses cell coordinates from text.""" return {ast.literal_eval(x) for x in ast.literal_eval(raw_coordinates)}
b550709c29ba56b1dec73a94bdccda1af743c2c9
39,170
import itk def array_view_from_vector_container( container: "itkt.VectorContainer", ttype=None ) -> np.ndarray: """Get an Array view with the content of the vector container""" container_template = itk.template(container) IndexType = container_template[1][0] # Find container type if ttype is...
0f2824993eb3f5504d6985e593a4b05ee49e9271
39,171
def convert_linear_problem_to_dual(model, sloppy=False, infinity=None, maintain_standard_form=True, prefix="dual_", dual_model=None): # NOQA """ A mathematical optimization problem can be viewed as a primal and a dual problem. If the primal problem is a minimization problem the dual is a maximization probl...
196ff6f48cdadce1f248586485adc772f889d0a7
39,172
def snake_case(text): """Converts `text` to snake case. Args: text (str): String to convert. Returns: str: String converted to snake case. Example: >>> snake_case('This is Snake Case!') 'this_is_snake_case' .. versionadded:: 1.1.0 .. versionchanged:: 4.0.0 ...
0836bc291e01daa74287af7e3e2e52b80628344a
39,173
def chunkify(tsd, seq_len): """ Splits a TimeSeriesDataset into chunks of length seq_len Args: tsd: TimeSeriesDataset object seq_len: length of the subsequences to return Returns: numpy arrays with chunks of size seq_len """ x, y = [], [] for s in tsd: for i in ra...
a3ad94bed06cfaad05663d4898fdeb9e3e6200e3
39,174
from typing import Dict import secrets def create_survey( title: str, hide_votes: bool, is_anonymous: bool, description: str, question_author_name_field_visible: bool, limit_question_characters_enabled: bool, limit_question_characters: int, author: User)...
9ae8271c4b2f228264555bc2daa887222b270a47
39,175
def remove_batch_dimension(shape: tuple) -> tuple: """Set the batch dimension to None as it does not matter for the Network interface.""" shape = list(shape) shape[0] = None shape = tuple(shape) return shape
92b7cd7a7165338cc397e530b0b81513910b46b0
39,176
import string def load(path): """Load an image from given path. Automatically de-compresses.""" file, reason = filesystem.open(path, 'rb') if file: ## print(f'Length: {file.proxy.size(path)[0]}') readSignature = string.char(file.readString(len(OCIFSignature))) if readSignature == OC...
32843e05059a468df8c6e5e2ef282e159da6caeb
39,177
def compute_windows(numpy_image, patch_size, patch_overlap): """Create a sliding window object from a raster tile. Args: numpy_image (array): Raster object as numpy array to cut into crops Returns: windows (list): a sliding windows object """ if patch_overlap > 1: raise Valu...
d85c91ad7684c03eea25763b9fbbcf87ddf78df4
39,178
from datetime import datetime def date_to_format(value, target_format): """Convert date to specified format""" if target_format == str: if isinstance(value, datetime.date): ret = value.strftime("%d/%m/%y") elif isinstance(value, datetime.datetime): ret = value.strftime(...
dba55f49ea4c2c016803d80b6c80809629062df5
39,179
import os def _extend_header(outfile, basepath, headvars): """ Rewrites the header with the information from the new tracks. Parameters ---------- outfile : hdf5 file New grid file to write to. basepath : str, optional Path in the grid where the tracks are stored. The default...
2a7e55b5f58bbac758dfb9bba0e1df1e55ea207f
39,180
def fetch_file(file_id: str, chunk: int = None, verify: bool = False) -> FileStatus: """Fetches file information Args: file_id: The id of the file to fetch chunk: (Optional) If included, fetches a single chunk instead of the entire file. verify: (Optional) If included, fetches file vali...
67a4a67cd70c97c0f50fd13924e293650b4a198a
39,181
import string def __get_settings(file_name): """ Opens the settings file associated to a csv file and returns it. :param file_name: The path to settings file. :type file_name: str :return: The settings. :rtype: dict[str, str] """ settings = {} if not file_name.endswith('.setting')...
4da37f3f2581196446515e06a3d4a6b93d0e15f2
39,182
import torch def set_device(args, distributed=False, rank=0): """ set parameter to gpu or cpu """ if torch.cuda.is_available(): if isinstance(args, list): return (set_gpu(item, distributed, rank) for item in args) elif isinstance(args, dict): return {key:set_gpu(args[ke...
99f5c1a1214d5c52003aa87dcb44845e2452594d
39,183
def oned_const_vel_bump(g=3.5,total=10000): """ make figure for traveling bump """ dat = oned_simple.SimDat(g=g,q=0,zshift=.1,T=total) # get four bumps at four equal time intervals. use second half of sim, # use velocity to determine time intervals # Peaks of phase plot over time are at ...
880eab55b73b71874da52d453c991150c3959d81
39,184
import os def load_pendigits(random_state=None, return_X_y=False, subset='kriegel11'): """Load and return the pendigits dataset. Kriegel's structure (subset='kriegel11') : =============== ======= anomalous class class 4 n_samples 9868 n_outliers 20 n_features 16 conta...
4c7d8667a4bbcd5474c63ba3d6ba5cdb83e8ea9c
39,185
def article_published_today(link): """ Compares the date the article was written with today's date.""" soup = lvm.soup_session(link) todays_date = (date.today() - timedelta(0)).strftime("%B %#d, %Y") # The # is platform specific date_to_check = soup.find('time', attrs={'class': 'date'}) return date_to_check ==...
bbc9b235e5cbe156e83dc103eafb1052ce99ccbb
39,186
import argparse def get_parser(): """ Returns the parser for the command line tool. :return: parser :rtype: argparse.ArgumentParser """ parser = argparse.ArgumentParser(description = 'MNIST initialization and normalization benchmark.') parser.add_argument('-epochs', dest = 'epochs', type...
7bc5e91ec2d25658846ac70bcacf13baea82317b
39,187
def nearest_neighbor(left_gdf, right_gdf, k_neighbors=1, return_left_columns=True, return_right_columns=True): """ For each point in left_gdf, find closest point in right GeoDataFrame and return them. Adapted from https://stackoverflow.com/questions/62198199/k-nearest-points-from-two-dataframes-with-geopand...
52f50bf54c9b12ef1ab11eaf3c83325b27f585a8
39,188
import string import json import torch def load_sequences_from_file(path, voc_path): """ Used for reading sentences or sequences of slots. Splits input lines into lists of words and performs word to id transformation. :param path: path to txt file with data :param voc_path: path to json file with ...
f23a55f550b5ae9cd852ee1e16532c0595f21380
39,189
def lambda_handler(event, context): """ main function """ try: for region in get_regions(): stop_instances(get_untagged_instances(region), region) return { "statusCode": 200, "body": "successfully shutted down all untagged instances", } except: ...
db7e683f6e98d546b3c77749e59b1baff52e4142
39,190
from sphinx.util.inventory import InventoryFile as IFile def sphinx_load_test(): """Return function to perform 'live' Sphinx inventory load test.""" def func(path): """Perform the 'live' inventory load test.""" with path.open("rb") as f: try: IFile.load(f, "", osp....
6ab148dd821119cf8d299cc6bbecfe82a6c2966f
39,191
from operator import pos def position() -> s.SearchStrategy[pos.Position]: """Generates a random Position. Returns: A new search strategy. """ return s.builds(pos.Position)
bd85a07677a5fa34842561549a318a4a138f742f
39,192
import base64 def get_gpg_keys(conn, dns): """ Grab pgpKeyInfo records (base64 encoded gpg keys) for the key attribute entries in LDAP, returning a dict {key_attr: pgpKeyInfo} """ r = {} for dn in dns: data = get_dn_attribute(conn, dn, '(objectClass=pgpKeyInfo)', 'pgpKey') ...
5fbc0dc8e7e7c45d500f5834ca6f1431532271ff
39,193
import numpy def get_pandas_field_metadata(pandas_col_metadata, field_name): """ Fetch information for a given column. The column statistics returned will be a bit different depending on if the types in the column are a number or a string. 'NAN' values are stripped from statistics and don't even s...
cbf1a740a202c36fa7b008451d44582e195d71f8
39,194
def predict_single_image(model, image): """ Predict the bounding box quads for a single image :param model: :param image: :return: """ im_resized, (ratio_h, ratio_w) = east_utils.resize_image(image) im_resized = cv2.cvtColor( im_resized, cv2.COLOR_BGR2RGB) image_batch = np.expand_di...
f22e7788d4be372b710ac5ead9188e5bb22b97d0
39,195
def get_reduced_string( text: list[int], suffix_arr: list[int], lms_suffixes: list[int] ) -> tuple[list[int], bool]: """ >>> suffix_arr = [10, 0, 1, 2, 3, 4, 6, 8, 5, 7, 9] >>> lms_suffixes = [6, 8, 10] >>> get_reduced_string("AAAAACACAG", suffix_arr, lms_suffixes) ([1, 2, 0], False) """ ...
b6b5078ec160799912eb99a02009d65751a1347f
39,196
from typing import Optional def add_cez_to_map( folium_map: folium.Map, exclusion_json_path: Optional[str] = None, add_layer_control: bool = False, ) -> folium.Map: """Add polygons of the Chernobyl Exclusion Zone (CEZ) to a folium map. Args: folium_map (folium.Map): [description] ...
611a2b68740262fe582e6d75bbb7e9161ca6036c
39,197
def gridappsdvolttron(config_path, **kwargs): """Parses the Agent configuration and returns an instance of the agent created using that configuration. :param config_path: Path to a configuration file. :type config_path: str :returns: Gridappsdvolttron :rtype: GridAPPSDVolttron """ try:...
1656b8d877a64a8ec746196fca162165a5fb67a0
39,198
def is_valid_if_yes_definition(definition): """ Returns true if the if_yes definition is valid. str -> bool """ if definition.count(constants.QUESTION_DENOTE) < 2 or definition[0] != constants.QUESTION_DENOTE: return False # First char is white space so it needs to be removed. if_tr...
a68e8e4bce14802cf8693bd2803669743298be4f
39,199