content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
from typing import Tuple from typing import List from typing import Type from typing import _Final def build_type(tp) -> Tuple[str, List[Type]]: """ Build typescript type from python type. """ tokens = tokenize_python_type(tp) dependencies = [ token for token in tokens if t...
475362488b7fe07db035ce70ddb3ac40580412dd
3,651,043
def laplacian_radial_kernel(distance, bandwidth=1.0): """Laplacian radial kernel. Parameters ---------- distance : array-like Array of non-negative real values. bandwidth : float, optional (default=1.0) Positive scale parameter of the kernel. Returns ------- weight : ar...
fd5f777b0d21e3a7673a6589a76dd50f48384029
3,651,044
def build_eslog_config_param( group_id, task_name, rt_id, tasks, topic, table_name, hosts, http_port, transport, es_cluster_name, es_version, enable_auth, user, password, ): """ es参数构建 :param group_id: 集群名 :param task_name: 任务名 :param rt_id: rt...
826b8d97ef14792845b4ced98ab5dcb3f36e57f3
3,651,045
def disclosure(input_df, cur_period): """ Reading in a csv, converting to a data frame and converting some cols to int. :param input_df: The csv file that is converted into a data frame. :param cur_period: The current period for the results process. :return: None. """ input_df = pd.read_csv...
65702fa309884206f284b35c48e2e8c8a34aef2b
3,651,046
def kitchen_sink(): """Combines all of the test data.""" return word_frequencies.load(_KITCHEN_SINK_DATA)
4e0b0d38465fb02cd4f8aeb5e54c2f6bcbdf2cda
3,651,048
import torch def sim_matrix(a, b, eps=1e-8): """ added eps for numerical stability """ a = normalize_embeddings(a, eps) b = normalize_embeddings(b, eps) sim_mt = torch.mm(a, b.transpose(0, 1)) return sim_mt
d0caa5ce6e9f86b861910221321b80752b4f24e4
3,651,049
def read_addon_xml(path): """Parse the addon.xml and return an info dictionary""" info = dict( path='./', # '/storage/.kodi/addons/plugin.video.vrt.nu', profile='special://userdata', # 'special://profile/addon_data/plugin.video.vrt.nu/', type='xbmc.python.pluginsource', ) tree...
6ead602b97c12bfd78ddc7194102a84793aa631b
3,651,050
import requests def get_submission_list(start_timestamp, end_timestamp, args=None): """ Scrapes a subreddit for submissions between to given dates. Due to limitations of the underlying service, it may not return all the possible submissions, so it will be necessary to call this method again. The metho...
7fa053c27787136420a9004721c1954318deeedb
3,651,051
def loadDataSet(): """ load data from data set Args: Returns: dataSet: train input of x labelSet: train input of y """ # initialize x-trainInput,y-trainInput dataSet = [] labelSet = [] # open file reader fr = open('testSet.txt') for line in fr.readlines(): # strip() -- get rid of the space on bot...
38f42a8a7c6b12e3d46d757d98565222e931149f
3,651,052
def xds_read_xparm_new_style(xparm_file): """Parse the XPARM file to a dictionary.""" data = map(float, " ".join(open(xparm_file, "r").readlines()[1:]).split()) starting_frame = int(data[0]) phi_start, phi_width = data[1:3] axis = data[3:6] wavelength = data[6] beam = data[7:10] spac...
ba5a851c68c54aa0c9f82df1dc2334f427c8cea8
3,651,053
def clear_bit(val, offs): """Clear bit at offset 'offs' in value.""" return val & ~(1 << offs)
e50e5f8ccc3fe08d9b19248e290c2117b78379ee
3,651,054
def get_org_details(orgs): """Get node and site details, store in Org object""" org_details = [] for org in orgs: org_id = org['id'] org_name = org['name'] org_longname = org['longname'] Org = namedtuple('Org', ['org_id', 'org_name', 'org_longname']) org_details.exten...
94bec33c2fbee35210ca61f6b8d3694d198c80ee
3,651,055
import logging def flush_after(handler, delay): """Add 'handler' to the queue so that it is flushed after 'delay' seconds by the flush thread. Return the scheduled event which may be used for later cancellation (see cancel()). """ if not isinstance(handler, logging.Handler): raise TypeError(...
a8cb8197643dbd092f709bed0726d076997e4715
3,651,056
def _ExtractCLPath(output_of_where): """Gets the path to cl.exe based on the output of calling the environment setup batch file, followed by the equivalent of `where`.""" # Take the first line, as that's the first found in the PATH. for line in output_of_where.strip().splitlines(): if line.startswith('LOC:'...
6a0c0d4aa74b4e84de69de023e2721edd95c36bd
3,651,057
import math def logGamma(x): """The natural logarithm of the gamma function. Based on public domain NETLIB (Fortran) code by W. J. Cody and L. Stoltz<BR> Applied Mathematics Division<BR> Argonne National Laboratory<BR> Argonne, IL 60439<BR> <P> References: <OL> <LI>W. J. Cody and K. E. Hillstrom, 'Chebyshev Appro...
36128e9a4b765dcc85ef42866fdbe7d16140ea1d
3,651,058
def regional_validity(query_point, regional_inclusion, regional_exclusions): """ regional_validity Returns whether a coordinate point is inside a polygon and outside of excluded regions. Input: A Point object, a Polygon Object of the inclusion region; a list of Polygon Objects of excluded regions. Output: True if t...
68e06b3d89e4783130f123d6c91dc5c43a9788ba
3,651,059
def get_word_vector_list(doc, w2v): """Get all the vectors for a text""" vectors = [] for word in doc: try: vectors.append(w2v.wv[word]) except KeyError: continue return vectors
f228c2100b6a622fdb677954257e2d1590dcc0ff
3,651,060
def solve(lines, n): """Apply the rules specified in the input lines to the starting pattern for n iterations. The number of lit pixels in the final pattern is returned. """ rules = load_rulebook(lines) pattern = START for _ in range(n): pattern = enhance(pattern, rules) return s...
781c349bfa186ac04daea60fe7e954431787ea15
3,651,061
def _to_plotly_color(scl, transparence=None): """ converts a rgb color in format (0-1,0-1,0-1) to a plotly color 'rgb(0-255,0-255,0-255)' """ plotly_col = [255 * _c for _c in mplc.to_rgba(scl)] if len(scl) == 3 else [255 * _c for _c in mplc.to_rgb(scl)] if transparence is not None: assert 0....
95b7686f913c69792e18f127176db68a3f72622f
3,651,062
def dense_attention_block(seqs_repr, is_training, num_layers, decay_variable, decay_constant, units, dropout, query_dropout, l2_scale, name=''): """ """ for i in range(num_layers): with tf.variable_scope('dense_attention{}'.format...
db50dd5e4d8d61622a9f989ec0ae9c02c5a4cfe1
3,651,063
def generate_schema_type(app_name: str, model: object) -> DjangoObjectType: """ Take a Django model and generate a Graphene Type class definition. Args: app_name (str): name of the application or plugin the Model is part of. model (object): Django Model Example: For a model wit...
b57cd78cce59dacf1fdb1d14c667405b6cfdcc90
3,651,064
def do_authorize(): """ Send a token request to the OP. """ oauth2.client_do_authorize() try: redirect = flask.session.pop("redirect") return flask.redirect(redirect) except KeyError: return flask.jsonify({"success": "connected with fence"})
1e19f501ac6da94058619e8dd5905d6cd2ab1a69
3,651,065
import re def get_windows(): """ Return all windows found by WM with CPU, fullscreen, process name, and class information. """ # Basic window information result = check_output('nice -n 19 wmctrl -l -p', shell=True) lines = [a for a in result.decode('utf8').split('\n') if a != ''] windows =...
dd0f6f702592cf7f2fdd8541959682890dcc271e
3,651,066
import google def get_google_open_id_connect_token(service_account_credentials): """Get an OpenID Connect token issued by Google for the service account. This function: 1. Generates a JWT signed with the service account's private key containing a special "target_audience" claim. 2. Sends it to t...
08e483865d26772112ffaf9837692f001598ced5
3,651,067
def term_to_atoms(terms): """Visitor to list atoms in term.""" if not isinstance(terms, list): terms = [terms] new_terms = [] for term in terms: if isinstance(term, And): new_terms += term_to_atoms(term.to_list()) elif isinstance(term, Or): new_terms += te...
6262ea7b1df124a4717d1452a23c33175b5da7a8
3,651,068
def expr_max(argv): """ Max aggregator function for :class:`Expression` objects Returns ------- exp : :class:`Expression` Max of given arguments Examples -------- >>> x = so.VariableGroup(10, name='x') >>> y = so.expr_max(2*x[i] for i in range(10)) """ return expr...
182157a627b12db6c41c79a99f135a7a493d4410
3,651,069
def handle_size(bytes_in=False, bytes_out=False): """ a function that converts bytes to human readable form. returns a string like: 42.31 TB. example: your_variable_name = make_readable(value_in_bytes) """ tib = 1024 ** 4 gib = 1024 ** 3 mib = 1024 ** 2 kib = 1024 if bytes_in: ...
6e2b3b758e1afc1cea43bbe7ac0c6179b1d32c5f
3,651,070
def return_elapsed(gs): """Returns a description of the elapsed time of recent operations. Args: gs: global state. Returns: A dictionary containing the count, minimum elapsed time, maximum elapsed time, average elapsed time, and list of elapsed time records. """ assert isinstance(gs, global_state....
af832a3bac239e24f610e39c5dee8fde6a1a25c8
3,651,071
def calculate_per_class_lwlrap(truth, scores): """Calculate label-weighted label-ranking average precision. Arguments: truth: np.array of (num_samples, num_classes) giving boolean ground-truth of presence of that class in that sample. scores: np.array of (num_samples, num_classes) giving the classi...
7cc9187f96d0899d0ce554164df553cc9b5f79a0
3,651,072
import hashlib import zipfile from datetime import datetime def generate_manifest(name, p, h=None): """ generate_manifest(name, p, h) -> mapping Generates a mapping used as the manifest file. :param name: a dotted package name, as in setup.py :param p: the zip file with package content....
13c10ae405dbc6fe5acf92180e7981d07fdb9c60
3,651,074
def benchrun(methods, model, case_args, filename, cpus=1,): """ Parameters ---------- methods : list of str Voter systems to be assessed by the election model. model : func Election model running function as ...
414c96deb9a8d2f64b6808323465f8647aa5e48a
3,651,075
def retry( exceptions,times=3,sleep_second=0): """ Retry Decorator Retries the wrapped function/method `times` times if the exceptions listed in ``exceptions`` are thrown :param times: The number of times to repeat the wrapped function/method :type times: Int :param Exceptions: Lists of exceptions that trigg...
de715a0f903386358265c3fe4a13f1d91bcb177e
3,651,076
def positiveId(obj): """Return id(obj) as a non-negative integer.""" result = id(obj) if result < 0: result += _address_mask assert result > 0 return result
5d3f987c621cf3d43ac31e9300a4d54ba208a7a0
3,651,077
def compute_annualized_total_return_over_months(df, column_price, months): """ Computed the annualized total return over the specified number of months. This is equivalent to Compound Annual Growth Rate (CAGR). Note: If the period is less than one year, it is best not to use annualized total return as...
a75886ae85ab5bb146d93bd159a0a2a32f950678
3,651,079
from functools import reduce def build_sparse_ts_from_distributions(start_date, end_date, seasonalities, time_interval, dist_dict, **kwargs): """constructs a time series with given distributions and seasonalities in a given frequency time_interval""" ts_list = [] for (name, dist), seasonality in zip(dist_...
81d2ebc32a2b62ed967377faf90b3b58e7c753ff
3,651,080
def preprocess_label(labels, scored_classes, equivalent_classes): """ convert string labels to binary labels """ y = np.zeros((len(scored_classes)), np.float32) for label in labels: if label in equivalent_classes: label = equivalent_classes[label] if label in scored_classes: ...
3e2465bb0db04afaaca0576f6c97847bd0fd2b2e
3,651,081
import math def vec_abs(field: SampledField): """ See `phi.math.vec_abs()` """ if isinstance(field, StaggeredGrid): field = field.at_centers() return field.with_values(math.vec_abs(field.values))
91395513b7e457bdfdded484db1069e8c3b95805
3,651,084
def spoofRequest(app): """ Make REQUEST variable to be available on the Zope application server. This allows acquisition to work properly """ _policy=PermissiveSecurityPolicy() _oldpolicy=setSecurityPolicy(_policy) newSecurityManager(None, OmnipotentUser().__of__(app.acl_users)) info = ...
d1b3bd1a37d69f6500d23e55b5318b6519ed04be
3,651,085
def data_to_percentage(data_list: pd.DataFrame) -> pd.DataFrame: """ Takes a dataframe with one or more columns filled with digits and returns a dataframe with the percentages corresponding to the number of times the numbers 1-9 appear in each column. Args: data_list: a dataframe of integer...
18316ddf999419290d572e77d2934241359e45a3
3,651,086
from .models.models import EncoderClassifier import torch def create_classifier_from_encoder(data:DataBunch, encoder_path:str=None, path=None, dropout1=0.5, device: torch.device = torch.device('cuda', 0), **kwargs): """Factory function to create classifier from encoder to allo...
736cfec768b6d659ab6fa1f087474a482409b66e
3,651,087
from typing import Hashable def filter_string( df: pd.DataFrame, column_name: Hashable, search_string: str, complement: bool = False, case: bool = True, flags: int = 0, na=None, regex: bool = True, ) -> pd.DataFrame: """Filter a string-based column according to whether it contains ...
9e5598a4afcff41ec5dc67c38b68efbacf3f09ec
3,651,088
from typing import List from typing import Dict from typing import Union import functools def on_demand_feature_view( features: List[Feature], inputs: Dict[str, Union[FeatureView, RequestDataSource]] ): """ Declare an on-demand feature view :param features: Output schema with feature names :param...
0ea45df22cb167ad2aa919a0be40f2a11574a69a
3,651,089
from typing import cast def get_error_string(ftdi): """ get_error_string(context ftdi) -> char * Get string representation for last error code Parameters: ----------- ftdi: pointer to ftdi_context Returns: -------- Pointer: to error string """ errstr = ftdi_get_er...
e0d3eaa19014fff9840e7a8e629651107ae25495
3,651,090
def DenseNet52k12(growth_rate = 12, reduction = 0.5): """ Parameters: ---------- Returns ------- """ return DenseNet(reduction = reduction, growth_rate = growth_rate, layers=52)
a295bcae685ae36bcbe356099d404403f7b8c0b6
3,651,091
def construct_fid_mask(catalog): """ Constructs the fidelity mask based off my results, not Robertos :param catalog: :return: """ line_widths = [i for i in range(3, 21, 2)] fid_catalog = load_table("fidelity_snr.out", start=0) fid_limit = 0.4 six_fids = [] for width in line_widt...
81f50ae4dd092482eb406bef331075245989d2f3
3,651,092
def _run_job(tgt, fun, arg, kwarg, tgt_type, timeout, retry): """ Helper function to send execution module command using ``client.run_job`` method and collect results using ``client.get_event_iter_returns``. Implements basic retry mechanism. If ``client.get_event_iter_returns`` return no results, `...
e23c189063e5d7df542d8e774acf655f4af61289
3,651,094
def _set_rank_colorbar(ax, img, norm): """ Set color bar for rankshow on the right of the ax """ divider = make_axes_locatable(ax) cax = divider.append_axes("right", size="5%", pad=0.05) plt.colorbar(img, cax=cax) y_tick_values = cax.get_yticks() boundary_means = [np.mean((y_tick_values[...
f21f59ac69c79cf9449d28710abdeeb730004077
3,651,095
from typing import Optional from pathlib import Path import importlib def destination(stub: str) -> Optional[Path]: """Determine stub path Only handle micropython stubs, ignoring any cPython stdlib equivalents. """ prefix, _, suffix = stub.partition(".") if importlib.util.find_spec(prefix): ...
8b2552513dbeaa9dc09cb85703b736e17c4788b5
3,651,096
def train_IPCA(X,n_dims,batch_size,model='ipca'): """ name: train_IPCA Linear dimensionality reduction using Singular Value Decomposition of centered data, keeping only the most significant singular vectors to project the data to a lower dimensional space. returns: the transformer model """...
282c885a562b5b3dbe356050ef5f270f49d7014d
3,651,098
def _str_cell(cell: Cell) -> str: """Строковое представление клетки. Данной строкой клетка будет выводится на экран. """ if cell.is_open: if cell.is_empty: return " " elif cell.value: return f" {cell.value} " elif cell.is_flagged: return "[F]" e...
2e4428196601a726b488e3ec4d966072033c5bfe
3,651,099
def mvw_ledoit_wolf(prices, weight_bounds=(0.,1.), rf = 0., options = None): """ Calculates the mean-variance weights given a DataFrame of returns. Wraps mean_var_weights with ledoit_wolf covariance calculation method Args: * prices (...
086f6430d189fd12509d56ce4a96a351a178979b
3,651,100
def _PadLabels3d(logits, labels): """Pads or slices 3-d labels to match logits. Covers the case of 2-d softmax output, when labels is [batch, height, width] and logits is [batch, height, width, onehot] Args: logits: 4-d Pre-softmax fully-connected output. labels: 3-d, but not necessarily matching in si...
223f7dfea9ebc970e62dbe71e2f27dfb5c9f161d
3,651,101
def intx(): """Returns the default int type, as a string. (e.g. 'int16', 'int32', 'int64'). # Returns String, the current default int type. """ return _INTX
57661ef00953e07228ff81abc93ec22c216797ff
3,651,102
import json def dev_end_hardware_script() -> Response: """Designate the end of a hardware script in flask log. Can be invoked by: curl http://localhost:4567/development/end_hardware_script """ return Response(json.dumps({}), mimetype="application/json")
714b448642180753e639992f2d101841074aeefd
3,651,103
def _init_train(opt): """Common initilization stuff for all training process.""" ArgumentParser.validate_prepare_opts(opt) if opt.train_from: # Load checkpoint if we resume from a previous training. checkpoint = load_checkpoint(ckpt_path=opt.train_from) fields = load_fields(opt.save...
bb2a043d1a59f996b303aabf9db724ced3505dbf
3,651,104
def compare(isamAppliance1, isamAppliance2): """ Compare Update Servers between two appliances """ ret_obj1 = get_all(isamAppliance1) ret_obj2 = get_all(isamAppliance2) for obj in ret_obj1['data']: del obj['uuid'] for obj in ret_obj2['data']: del obj['uuid'] return ibms...
e29025ca0af897f10b3b8498f8def86841b76c97
3,651,106
import random def get_random(): """ Retrieves the current issue of XKCD, chooses an issue 1 - current issue #, and returns a json object. Returns null if an requests error occurs. """ return get_issue(random.randint(1, int(get_current()["num"])))
10fbf75681901722510b0b9fbb2de298eb80b45e
3,651,108
def get_fasta_readlengths(fasta_file): """ Get a sorted list of contig lengths :return: (tuple) """ lens = [] with open_fasta_reader(fasta_file) as f: for record in f: lens.append(len(record.sequence)) lens.sort() return lens
769cf5af50ba684c107a1312d2aeaab2721a29c6
3,651,109
def postprocess(p, gt, width_and_height, p_binary, false_positives=False, false_negatives=False): """ This function does matching and then postprocessing of p's and gt's :param p: the objects given from rcnn :param gt: the objects we get from the ground truth :param width_and_height: the width and h...
dd83de4547f7c1461b64fcd2dfa4c3df54aefd10
3,651,110
from csb.bio.structure import TorsionAngles import numpy def deg(x): """ Convert an array of torsion angles in radians to torsion degrees ranging from -180 to 180. @param x: array of angles @type x: numpy array @rtype: numpy array """ func = numpy.vectorize(TorsionAngles.d...
95e37a0c644df1562e417c1ad61e4788bd46c279
3,651,111
import timeit def run_median_trial(): """Generate table for Median Trial.""" tbl = DataTable([10,15,15],['N', 'median_time', 'sort_median']) trials = [2**k+1 for k in range(8,20)] for n in trials: t_med = 1000*min(timeit.repeat(stmt='assert(linear_median(a) == {}//2)'.format(n), ...
ed4c5ebe8bd6259c4adc45c4b023cc5bb96a1055
3,651,112
def regroup(X, N): """ Regroups the rows and columns of X such that rows/cols that are N apart in X, are adjeacent in Y. If N is a 2 element vector, N[0] is used for rows and N[1] is used for columns. Parameters: X: m by n matrix to be regrouped. N: Integer or two element vector...
7ad92b878cb6a55820ef9ad92c68e934184d725d
3,651,113
def return_estimators(n_components): """Returns all of the estimators that can be used to generate models. A larger selection of possible estimators have been commented out, but could be uncommented.""" estimators = [ ('PCArandom', decomposition.PCA(n_components=n_components, svd_solve...
680aa1d50c4e2db0e4d3df9e60749350df437bb8
3,651,114
def _check_type_picks(picks): """helper to guarantee type integrity of picks""" err_msg = 'picks must be None, a list or an array of integers' if picks is None: pass elif isinstance(picks, list): if not all(isinstance(i, int) for i in picks): raise ValueError(err_msg) ...
79493f75db8e57f32a6369ad18900e0632d2bc18
3,651,115
def get_test_standard_scaler_str(): """ Get a pandas projection code str """ test_code = cleandoc(""" standard_scaler = StandardScaler() encoded_data = standard_scaler.fit_transform(df) """) return test_code
fd6e1daa7e0dddb603437e5b35c283a11e68ec00
3,651,116
from typing import List from typing import Tuple import re def add_command( command_list: List[Tuple[re.Pattern, callable]], func: callable, command_str: str ) -> List[Tuple[re.Pattern, callable]]: """Add a function and the command pattern to the command list. Args: func: Function it will be call...
f8076e4a6b37722591eae04a67feb1c25e606b84
3,651,117
def get_clusters_and_critical_nodes(G, k, rho_star, phi_in): """ The implementation of the main body of the partitioning Algorithm. The main while-loop of the algorithm is executed as long as a refinement is still possible. :param phi_in: An algorithm parameter used to lower bound the inner conductance...
e7374c9cad30a87477ee5b9ce4d0a0e9cb7de041
3,651,118
def get_edges_out_for_vertex(edges: list, vertex: int) -> list: """Get a sublist of edges that have the specified vertex as first element :param edges: edges of the graph :param vertex: vertex of which we want to find the corresponding edges :return: selected edges """ return [e for e in edge...
21485073df1c754e7c8e2b7dd9cafef284e601e7
3,651,119
def pellet_plot_multi_unaligned(FEDs, shade_dark, lights_on, lights_off,**kwargs): """ FED3 Viz: Plot cumulaive pellet retrieval for multiple FEDs, keeping the x-axis to show absolute time. Parameters ---------- FEDs : list of FED3_File objects FED3 files...
3601e8ecff20a3d7978f7261ebaa5236d662a25e
3,651,120
import time def sync_via_mrmsdtw(f_chroma1: np.ndarray, f_chroma2: np.ndarray, f_DLNCO1: np.ndarray = None, f_DLNCO2: np.ndarray = None, input_feature_rate: float = 50, step_sizes: np.ndarray = np.array([[1, 0], [...
00dac7bdde14597e0daece958e65761ec01d1494
3,651,121
def simulate_beta_binomial( K, D, sigma2, theta, mu=0, invlink=logistic, seed=None): """Simulates from binomial Gaussian process with Beta latent noise. Args: K: Cell-state kernel, for example as generated by create_linear_kernel or create_rbf_kernel. D: Array of total counts. ...
de4648af70a6b35c7b7f5edc2c151a98db6d7603
3,651,122
def convert_to_floats(tsi): """ A helper function that tax all of the fields of a TaxSaveInputs model and converts them to floats, or list of floats """ def numberfy_one(x): if isinstance(x, float): return x else: return float(x) def numberfy(x): ...
a6f93f402c547435fa9fe611481084215f52f13b
3,651,123
def properties_filter(mol): """ Calculates the properties that contain logP, MW, HBA, HBD, TPSA, NRB """ #frag = Chem.rdmolops.GetMolFrags(mol) # remove '.' #if len(frag) > 1: #return False MW_s = Descriptors.MolWt(mol) # MW if MW_s < 250 or MW_s > 750: return False A...
bc124620baddb828b4c5cb82e0b0374bdb51bad7
3,651,124
def _create_certificate_chain(): """ Construct and return a chain of certificates. 1. A new self-signed certificate authority certificate (cacert) 2. A new intermediate certificate signed by cacert (icert) 3. A new server certificate signed by icert (scert) """ caext = X509Exten...
156a61e8159b1826def8fa33d5c5965add2c7f2e
3,651,125
def build_job_spec_name(file_name, version="develop"): """ :param file_name: :param version: :return: str, ex. job-hello_world:develop """ name = file_name.split('.')[-1] job_name = 'job-%s:%s' % (name, version) return job_name
55a45052852e6b24cb4370f7efe5c213da83e423
3,651,126
import torch def draw_mask(im: torch.Tensor, mask: torch.Tensor, t=0.2, color=(255, 255, 255), visualize_instances=True): """ Visualize mask where mask = 0. Supports multiple instances. mask shape: [N, C, H, W], where C is different instances in same image. """ assert len(mask.shap...
45d12dbc695755f0231ca2a8d0f8d1cdf2f423ff
3,651,127
def view_about(): """ shows the about page :return: :rtype: """ return render_template('about.html', title="About Flask AWS Template")
a364842c165864aba34605f3ffdd8c1d412015e8
3,651,128
import numpy def viterbi(observed_values, transition_probabilities, emission_probabilities, initial_distribution, file_name, log=True): """Calculates the viterbi-path for a given hidden-markov-model, heavily inspired by Abhisek Janas Blogpost "Implem...
b063e5c5bbf566afb0f16175d9d229bef7a953f1
3,651,129
def extract_psf_fitting_names(psf): """ Determine the names of the x coordinate, y coordinate, and flux from a model. Returns (xname, yname, fluxname) """ if hasattr(psf, 'xname'): xname = psf.xname elif 'x_0' in psf.param_names: xname = 'x_0' else: raise ValueError...
cee108dd1f97e506b60ba621c7f08efa7b5c33d7
3,651,130
def config_check_conformance(cookie, dn): """ Auto-generated UCS XML API Method. """ method = ExternalMethod("ConfigCheckConformance") method.cookie = cookie method.dn = dn xml_request = method.to_xml(option=WriteXmlOption.DIRTY) return xml_request
598fbd665dcf18a35104400bf7debfc64347c3b5
3,651,132
def get_dist_to_port(geotiff): """ Extract "truth" dist_to_port from geotiff """ with Geotiff(geotiff) as tif: dist_to_port = tif.values return dist_to_port
1a77c2ac905eea2d1796529297168dac394b4bdb
3,651,133
import inspect def build_dataset_exporter( dataset_type, strip_none=True, warn_unused=True, **kwargs ): """Builds the :class:`DatasetExporter` instance for the given parameters. Args: dataset_type: the :class:`fiftyone.types.dataset_types.Dataset` type strip_none (True): whether to exclud...
6a21c90ee2a9c297ad86515f5078221459b1fb01
3,651,134
def conditions(x): """ This function will check whether the constraints that apply to our optimization are met or not. """ if ( (10/x[0]) > 66.0 ): return False elif ( (10/x[0] + 12/x[1]) > 88.0 ): return False elif ( (10/x[0] + 12/x[1] + 7/x[2]) > 107.0 ): return ...
263fdc3fd07aa656982401f71071fcd684b8625f
3,651,135
def get_commit_ancestors_graph(refenv, starting_commit): """returns a DAG of all commits starting at some hash pointing to the repo root. Parameters ---------- refenv : lmdb.Environment lmdb environment where the commit refs are stored starting_commit : string commit hash to start c...
078819cf0291a5e4e1e8ad4ea409f475c0df93fd
3,651,137
def is_verification_handshake(rjson): """ Determines if the request is the Slack application APIs verification handshake :rtype: bool """ # Check body contains the right keys for x in ['token', 'challenge', 'type']: if x not in rjson: return False # Check type is correct...
1ceccd9ca578bd09e9629cd59e565bc523502030
3,651,138
def template_node(scope_key): """ Create and return a new template node. Parameters ---------- scope_key : object The key for the local scope in the local storage maps. Returns ------- result : TemplateNode A new compiler template node. """ node = TemplateNode() ...
4cd9721dd9f9f91cb84326391630274b8f5764a7
3,651,139
def GetAutoResult(chroot_path, buildbucket_id): """Returns the conversion of the result of 'cros buildresult'.""" # Calls 'cros buildresult' to get the status of the tryjob. build_result = GetStatusFromCrosBuildResult(chroot_path, buildbucket_id) # The string returned by 'cros buildresult' might not be in the...
705fbc011c11fa67d0b61f130a3b6f024a6dcd44
3,651,140
def rft(x): """ Real Fourier Transform """ # XXX figure out what exactly this is doing... s = x.shape[-1] xp = np.zeros(x.shape,dtype="complex64") xp[...,1:s/2] = x[...,1:-1:2]+x[...,2::2]*1.j xp[...,0] = x[...,0]/2. xp[...,s/2] = x[...,-1]/2. return np.array(nmr_reorder(np.fft...
3a65f0a0059df4c74b223f3284e996b82d7ebf02
3,651,141
def yam_path(manifestsdir): """Bundletracker manifest.""" return join(manifestsdir, 'yam.json')
5d1b5162bd8285d8e33c822a3b5edcc996452719
3,651,142
def single_from(iterable): """Check that an iterable contains one unique value, and return it.""" unique_vals = set(iterable) if len(unique_vals) != 1: raise ValueError('multiple unique values found') return unique_vals.pop()
c8fb8864083195ad913ff1ddf0114b5a50068902
3,651,143
import requests def vthash(filehash: str): """Returns the analysis data class for a file in VirusTotal's database""" endpoint_path = f'/files/{filehash}' endpoint = f"{api_base_url}{endpoint_path}" r = requests.get(endpoint, headers=header) if r.status_code == 404 and r.json()['error']['code'] ...
bf4f334ad7a35e1141f9e00a44544fdd0709b411
3,651,144
def prod(x, axis=None, keepdims=False): """ product of all element in the array Parameters ---------- x : tensor_like input array axis : int, tuple of ints axis or axes along which a product is performed keepdims : bool keep dimensionality or not Returns ---...
8962e7b6abd16c9354f076c0c6d718b82fe44223
3,651,145
from typing import List import difflib def menu(queue: List[str] = None): """Fred Menu""" fred_controller = FredController(queue) an_input = "HELP_ME" while True: # There is a command in the queue if fred_controller.queue and len(fred_controller.queue) > 0: # If the comman...
b8133dd748f0a48099359b6503edee6c9f875fb6
3,651,146
def generic_repr(name, obj, deferred): """ Generic pretty printer for NDTable and NDArray. Output is of the form:: Array(3, int32) values := [Numpy(ptr=60597776, dtype=int64, shape=(3,))]; metadata := [contigious] layout := Identity; [1 2 3] """ ...
c9de29b792d943420b02455752f01a9c12fcf66c
3,651,147
def build_model(X, y, ann_hidden_dim, num_passes=20000): """ :param ann_hidden_dim: Number of nodes in the hidden layer :param num_passes: Number of passes through the training data for gradient descent :return: returns the parameters of artificial neural network for prediction using forward propagation...
bccdf828050af8a6ff5943eb84b574756f9f54ab
3,651,148
def g_square_dis(dm, x, y, s): """G square test for discrete data. Args: dm: the data matrix to be used (as a numpy.ndarray). x: the first node (as an integer). y: the second node (as an integer). s: the set of neibouring nodes of x and y (as a set()). levels: levels of ...
2f0f0b44a919177c0f5775a34e0493c62720a21d
3,651,149
def start(name): """ Start the specified service CLI Example: .. code-block:: bash salt '*' service.start <service name> """ cmd = "/usr/sbin/svcadm enable -s -t {0}".format(name) retcode = __salt__["cmd.retcode"](cmd, python_shell=False) if not retcode: return True ...
607b559281c6b13002d7237b8c4409533074d0bc
3,651,150
from typing import Dict def line_coloring(num_vertices) -> Dict: """ Creates an edge coloring of the line graph, corresponding to the optimal line swap strategy, given as a dictionary where the keys correspond to the different colors and the values are lists of edges (where edges are specified as ...
423e626ecbf4f48e0a192241375484a077fbe0b2
3,651,151
def flatten_outputs(predictions, number_of_classes): """Flatten the prediction batch except the prediction dimensions""" logits_permuted = predictions.permute(0, 2, 3, 1) logits_permuted_cont = logits_permuted.contiguous() outputs_flatten = logits_permuted_cont.view(-1, number_of_classes) return out...
c58fb965443a5402e9bec32afaebe9376c74653f
3,651,152
def get_r_vals(cell_obj): """Get radial distances for inner and outer membranes for the cell object""" r_i = cell_obj.coords.calc_rc(cell_obj.data.data_dict['storm_inner']['x'], cell_obj.data.data_dict['storm_inner']['y']) r_o = cell_obj.coords.calc_rc(cell_obj.data.data_di...
d51c926791845006dfe9a97cbd9c82c041ea701b
3,651,153