content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def ESS(works_prev, works_incremental): """ compute the effective sample size (ESS) as given in Eq 3.15 in https://arxiv.org/abs/1303.3123. Parameters ---------- works_prev: np.array np.array of floats representing the accumulated works at t-1 (unnormalized) works_incremental: np.array ...
514ca2462708a4c163f45e92854159d50eb5f3a8
16,162
def new_line_over(): """Creates a new line over the cursor. The cursor is also moved to the beginning of the new line. It is not possible to create more than one new line over the cursor at a time for now. Usage: `In a config file:` .. code-block:: yaml - new_line_over: `Usi...
41da4d301240a8ea3d9108dd1d957a30cff1097b
16,163
import json def lambda_handler(event, context): """Calls custom job waiter developed by user Arguments: event {dict} -- Dictionary with details on previous processing step context {dict} -- Dictionary with details on Lambda context Returns: {dict} -- Dictionary with Processed Buc...
e5a4055a39d0df1fabd3ad5f70a2859524378f44
16,164
def put_path(components, value): """Recursive function to put value in component""" if len(components) > 1: new = components.pop(0) value = put_path(components, value) else: new = components[0] return {new: value}
77db4064a77cf1cdcde1d74d901410525722b66e
16,165
def con_orthogonal_checkboard(X,c_v1,c_v2,c_v3,c_v4,num,N): """for principal / isothermic / developable mesh / aux_diamond / aux_cmc (v1-v3)*(v2-v4)=0 """ col = np.r_[c_v1,c_v2,c_v3,c_v4] row = np.tile(np.arange(num),12) d1 = X[c_v2]-X[c_v4] d2 = X[c_v1]-X[c_v3] d3 = X[c_v4]-X[c_v2] ...
f05228d6caa49f60a2a9f515ce5590e6f13127e0
16,166
def _PropertyGridInterface_GetPropertyValues(self, dict_=None, as_strings=False, inc_attributes=False): """ Returns all property values in the grid. :param `dict_`: A to fill with the property values. If not given, then a new one is created. The dict_ can be an object as well, in which ...
06974bec88351d5e8743b43e7c0495bb40545ef0
16,167
def get_pipelines(exp_type, cal_ver=None, context=None): """Given `exp_type` and `cal_ver` and `context`, locate the appropriate SYSTEM CRDSCFG reference file and determine the sequence of pipeline .cfgs required to process that exp_type. """ context = _get_missing_context(context) cal_ver = _g...
7fb4a02ffe7598df4621b2fd4a6863094616fd41
16,168
def distance_to_line(p,a,b): """ Computes the perpendicular distance from a point to an infinite line. Parameters ---------- p : (x,y) Coordinates of a point. a : (x,y) Coordinates of a point on a line. b : (x,y) Coordinates of another point on a line. Return...
1b1d0ef37587cd8cb0f5730ac78c39ec8b42faec
16,169
def pearsonr(A, B): """ A broadcasting method to compute pearson r and p ----------------------------------------------- Parameters: A: matrix A, (i*k) B: matrix B, (j*k) Return: rcorr: matrix correlation, (i*j) pcorr: matrix correlation p, (i*j) Example: ...
f66ca9eb6c6367580043ab9d512400c826d30d39
16,170
def inst_bench(dt, gt, bOpts, tp=None, fp=None, score=None, numInst=None): """ ap, rec, prec, npos, details = inst_bench(dt, gt, bOpts, tp = None, fp = None, sc = None, numInst = None) dt - a list with a dict for each image and with following fields .boxInfo - info that will be used to cpmpute the ...
9f8e12863205c24247003a4c95cf52f99086a6a6
16,171
def normalized_str(token): """ Return as-is text for tokens that are proper nouns or acronyms, lemmatized text for everything else. Args: token (``spacy.Token`` or ``spacy.Span``) Returns: str """ if isinstance(token, SpacyToken): return token.text if preserve_case(...
c5e30b48716fa99bfbcf8252b3ecd018cc921cbe
16,173
def scatter_nd(*args, **kwargs): """ See https://www.tensorflow.org/api_docs/python/tf/scatter_nd . """ return tensorflow.scatter_nd(*args, **kwargs)
5b5d457c91df73314de6d81c105132d6b69eb1aa
16,174
from typing import Union from typing import Tuple def concatenate_sequences(X: Union[list, np.ndarray], y: Union[list, np.ndarray], sequence_to_value: bool = False) \ -> Tuple[np.ndarray, np.ndarray, np.ndarray]: """ Concatenate multiple sequences to scikit-learn compatible n...
b4b2489eeb601ce5378f6cf7b2cce7daf68bdf1d
16,175
def run_command_with_code(cmd, redirect_output=True, check_exit_code=True): """Runs a command in an out-of-process shell. Returns the output of that command. Working directory is self.root. """ if redirect_output: stdout = sp.PIPE else: stdout = None p...
45e8592def8290f45458a183bed410072cc15000
16,177
from typing import Union import ast def _create_element_invocation(span_: span.Span, callee: Union[ast.NameRef, ast.ModRef], arg_array: ast.Expr) -> ast.Invocation: """Creates a function invocation on the first element of ...
0449c27fc6e7f16054bddfd99bd9e64109b9ee0e
16,179
import time def train_deeper_better(train_data, train_labels, test_data, test_labels, params): """Same as 'train_deeper', but now with tf.contrib.data.Dataset input pipeline.""" default_params = { 'regularization_coeff': 0.00001, 'keep_prob': 0.5, 'batch_size': 128, 'fc1_size':...
c2d2c56ac7dbb52d072f2397540d4d793ac0d0c4
16,181
def redirect_return(): """Redirects back from page with url generated by url_return.""" return redirect(str(Url.get_return()))
f1ce09afef02651e0331a930e53211f9eb4f2a54
16,182
def setup(coresys: CoreSys) -> EvaluateBase: """Initialize evaluation-setup function.""" return EvaluateOperatingSystem(coresys)
daf3bd3ddca0085d6305535b27c28d70ac240dac
16,183
def _weight_initializers(seed=42): """Function returns initilializers to be used in the model.""" kernel_initializer = tf.keras.initializers.TruncatedNormal( mean=0.0, stddev=0.02, seed=seed ) bias_initializer = tf.keras.initializers.Zeros() return kernel_initializer, bias_initializer
1c7652b787d4a69d3a43983c2c291c09337d06d0
16,184
def get_non_ready_rs_pod_names(namespace): """ get names of rs pods that are not ready """ pod_names = [] rs_pods = get_pods(namespace, selector='redis.io/role=node') if not rs_pods: logger.info("Namespace '%s': cannot find redis enterprise pods", namespace) return [] fo...
167922c4fa03127a3371f2c5b7516bb6462c6253
16,186
def lookup_material_probase(information_extractor, query, num): """Lookup material in Probase""" material_params = { 'instance': query, 'topK': num } result = information_extractor.lookup_probase(material_params) rank = information_extractor.rank_probase_result_material(result) r...
9cecf99e3a9689f85788df21ef01d4e86c9a392d
16,187
def get_unexpected_exit_events(op): """Return all unexpected exit status events.""" events = get_events(op) if not events: return None return [e for e in events if is_unexpected_exit_status_event(e)]
171158d16c34e2764bc8c91f4888863c162043c4
16,188
async def delete_user(username: str) -> GenericResponse: """Delete concrete user by username""" try: await MongoDbWrapper().remove_user(username) except Exception as exception_message: raise DatabaseException(error=exception_message) return GenericResponse(detail="Deleted user")
8b2756922ab79d058097105fa8cd000396350a3b
16,189
def get_changelog(): """download ChangeLog.txt from github, extract latest version number, return a tuple of (latest_version, contents) """ # url will be chosen depend on frozen state of the application source_code_url = 'https://github.com/pyIDM/pyIDM/raw/master/ChangeLog.txt' new_release_url = 'h...
7c8df0cbc5fa85642e4e23106006445f59539a1f
16,190
def get_train_tags(force=False): """ Download (if needed) and read the training tags. Keyword Arguments ----------------- force : bool If true, overwrite existing data if it already exists. """ download_train_tags(force=force) return read_tags(train_tags_file_path)
5d67422a275011a719c0121206397fb99e6e4f70
16,191
def select_own(ligands, decoys, scores): """Select ligand ids and decoy ids from full ranked ids.""" #scores format is full OUTDOCK line selected = set(ligands) selected.update(decoys) results = [] for scoreline in scores: #id = scoreline[extract_all.zincCol] #refer to correct column alw...
444555a30571e61fad7eac36389e2dd638313744
16,192
def cmp_text_file(text, file): """returns True when text and file content are identical """ fh = open(file) ftext = fh.read() fh.close() return cmp(ftext, text)
ecf10004cd3fa230d0e794c4c89e45ca91e7e40e
16,194
def get_alignment_summary(seq_info): """ Determine the consensus sequence of an alignment, and create position matrix Definition of consensus: most common base represented at that position. """ consensus_sequence = [] position_matrix = [] for position in seq_info: #Ignore any ambi...
f91e4dcea2f4570a194524970fdbc95eacc455b2
16,195
def _get_variables(exp:Experiment, config: dict) -> dict: """Process the configuration's variables before rendering it""" return {key: value.format(exp=exp) for key, value in config.get("variables", {}).items()}
1b819c93ef079557908c216dc5c9fa75d55fe0f3
16,197
def func_calc_M(S): """ Use molecules structure/symbol to calculate molecular weight Parameter: S : structrue in a format: (atomType number) separated by '-' or blank space number of '-' and spaces does not matter precendent: '-' > blank space Examp...
ed8e3d5ccd5305caccfac64cb0ecb200fde650eb
16,198
def find_NN(ngbrof, ngbrin, distance_ULIM=NP.inf, flatten=False, parallel=False, nproc=None): """ ----------------------------------------------------------------------------- Find all nearest neighbours of one set of locations in another set of locations within a specified distance. ...
131d136ad92900f3ee624982f70234070d0d76a6
16,199
from datetime import datetime def index(request): """Magicaltastic front page. Plugins can register a hook called 'frontpage_updates_<type>' to add updates to the front page. `<type>` is an arbitrary string indicating the sort of update the plugin knows how to handle; for example, spline-forum h...
14e4200c2277e48792fd4d02f0126293a82a9ba8
16,200
def fd_d1_o4_smoothend(var,grid,mat=False): """Centered finite difference, first derivative, 4th order using extrapolation to get boundary points var: quantity to be differentiated. grid: grid for var mat: matrix for the finite-differencing operator. if mat=False then it is created""" dx = grid[1]...
e1b57204e6fd9fe2839e4fb2e7230dd0f8854841
16,201
def find_node_pair_solutions(node_pairs, graph): """ Return path and cost for all node pairs in the path sets. """ node_pair_solutions = {} counter = 0 for node_pair in node_pairs: if node_pair not in node_pair_solutions: cost, path = dijkstra.find_cost(node_pair, graph) ...
f2f742cc1e969b4b60394148508cbb9cacaa3cfc
16,202
import math def get_step(a, b, marks=1): """Return a coordinate set between ``a`` and ``b``. This function returns a coordinate point between the two provided coordinates. It does this by determining the angle of the path between the two points and getting the sine and cosine from that angle. The...
e242823df263f1cee28409ef3f984f9b3066dad5
16,203
import torch def get_model_mask_neurons(model, layers): """ Defines a dictionary of type {layer: tensor} containing for each layer of a model, the binary mask representing which neurons have a value of zero (all of its parameters are zero). :param model: PyTorch model. :param layers: Tuple of laye...
2e24af14d05802bac69b65a225ce284b5a7785e7
16,204
def connection(): """Open a new connection or return the cached existing one""" try: existing_connection = GLOBAL_CACHE[CACHE_KEY_CONNECTION] except KeyError: new_connection = win32com.client.Dispatch(ADO_CONNECTION) new_connection.Provider = CONNECTION_PROVIDER new_connectio...
f2c09fac89e0b0c9f9894869bb559ce61bca942a
16,205
def precision(theta,X,Y): """ accuracy function computes the accuracy of the logistic model theta on X with true target variable Y """ m = np.shape(X)[0] H = sigmoid(np.dot(X,theta)) H[H >= 0.5] = 1 H[H < 0.5] = 0 return np.sum(H == Y)/m
e3b2c1c613f5ae2f20b2b9a8e6e343348be845df
16,207
def get_converter(obj, coords=None, dims=None, chains=None): """Get the converter to transform a supported object to an xarray dataset. This function sends `obj` to the right conversion function. It is idempotent, in that it will return xarray.Datasets unchanged. Parameters ---------- obj : A ...
ee293672d74de5f0e1de0ff25c806fa10327c71c
16,208
import pytz def timezone_by_tzvar(tzvar): """Convert a WWTS tzvar to a tzdata timezone""" return pytz.timezone(city_by_tzvar(tzvar))
0bc4d634ca5fcc55ceed062ae06fbe2eefb6c11a
16,209
def easy_map(parser, token): """ The syntax: {% easy_map <address> [<width> <height>] [<zoom>] [using <template_name>] %} The "address" parameter can be an Address instance or a string describing it. If an address is not found a new entry is created in the database. """ width, height, z...
b2968f6ff3cde324711f84a5b449fbab92cc22fa
16,211
import six def pack_feed_dict(name_prefixs, origin_datas, paddings, input_fields): """ Args: name_prefixs: A prefix string of a list of strings. origin_datas: Data list or a list of data lists. paddings: A padding id or a list of padding ids. input_fields: A list of input fiel...
2946a8869cac26737f6c5b6234ce0320cfdf5bcf
16,212
def get_session_maker(): """ Return an sqlalchemy sessionmaker object using an engine from get_engine(). """ return sessionmaker(bind=get_engine())
2f1a500cf799910f98e7821582cb78d063eeb273
16,213
def rescale_intensity(arr, in_range, out_range): """ Return arr after stretching or shrinking its intensity levels. Parameters ---------- arr: array input array. in_range, out_range: 2-tuple min and max intensity values of input and output arr. Returns ------- out: arra...
580c789a6eb2ad03bcbdefd8e5f27b0c6a239f32
16,214
import requests def call_oai_api(resumption_token): """ Request page of data from the Argitrop OAI API Parameters ---------- resumption_token : object (first page) or string or xml.etree.ElementTree.Element token returned by previous request. Returns ------- response_xml : st...
e69ec11f75676a94134f4541b421391367ab1e3c
16,216
import yaml def save_pano_config(p): """ saves a panorama config file to the local disk from the session vars. :return: """ filename = get_filename(p) with open(filename, 'w') as yml_fh: yml_fh.write(yaml.dump(session[p + '_config'], default_flow_style=False)) return redirect("/...
6a2575af4fe54caed7ce812d3fc2a876424912f7
16,217
def is_transport(name): """Test if all parts of a name are transport coefficients For example, efe_GB, chie_GB_div_efi_GB are all composed of transport coefficients, but gam_GB and chiee_GB_plus_gam_GB are not. """ transport = True try: for part_name in extract_part_names(split_parts(na...
1aea3915680b3c74422cbd7648fd920719dd3cc8
16,219
def detect_moved_files(file_manifest, diff): """ Detect files that have been moved """ previous_hashes = defaultdict(set) for item in file_manifest['files']: previous_hashes[item['hash']].add(item['path']) diff_dict = make_dict(diff) # files with duplicate hashes are assumed to have the same conten...
db97dfb88d4fa253351e149dacf68a9fa3043072
16,220
def decodecaps(blob): """decode a bundle2 caps bytes blob into a dictionary The blob is a list of capabilities (one per line) Capabilities may have values using a line of the form:: capability=value1,value2,value3 The values are always a list.""" caps = {} for line in blob.splitlines(...
3c18bbe6b4b6a0562719d4992d6937d60f6bc114
16,221
def an(pos=5): """ Alineamiento del texto. @pos: 1: Abajo izquierda 2: Abajo centro 3: Abajo derecha 4: Mitad derecha 5: Mitad centro 6: Mitad derecha 7: Arriba izquierda 8: Arriba centro 9: Arriba derecha """ apos = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] if pos not...
fbe1e89282ebdf7b4977bee295e2cac7735bd652
16,223
def main(iterator): """ Given a line iterator of the bash file, returns a dictionary of keys to values """ values = {} for line in iterator: if not line.startswith('#') and len(line.strip()) > 0: match_obj = line_regex.search(line) if match_obj is not None: key, value = match_obj.gr...
16cc188b367200c317119348d9440d57faa322a9
16,225
def is_any(typeref: irast.TypeRef) -> bool: """Return True if *typeref* describes the ``anytype`` generic type.""" return isinstance(typeref, irast.AnyTypeRef)
75ca055529fea35dfeb2519c3de61bf3739ce1f7
16,226
from typing import Union def repeat_1d(inputs: tf.Tensor, count: Union[tf.Tensor, int], name="repeat_1d"): """Repeats each element of `inputs` `count` times in a row. '''python repeat_1d(tf.range(4), 2) -> 0, 0, 1, 1, 2, 2, 3, 3 ''' Parameters: inputs: A 1D tensor wit...
44a8bb29dcd2ba0e2e5970aff1eab94b85a34c13
16,227
import logging def create_logger(logfile=r"/tmp/tomoproc.log"): """Default logger for exception tracking""" logger = logging.getLogger("tomoproc_logger") logger.setLevel(logging.INFO) # create the logging file handler fh = logging.FileHandler(logfile) fh.setFormatter( logging.Formatt...
a0c005c39af9d24d7198790cf0cfe31a1b6395a0
16,228
async def async_setup(opp: OpenPeerPower, config: ConfigType) -> bool: """Set up the Twente Milieu components.""" async def update(call) -> None: """Service call to manually update the data.""" unique_id = call.data.get(CONF_ID) await _update_twentemilieu(opp, unique_id) opp.servic...
f2c0dd14e9193b9fa3ae3ea87689e90d9eb2c1bc
16,229
import re def parsePDCfile(fpath='data/CPTAC2_Breast_Prospective_Collection_BI_Proteome.tmt10.tsv'): """ Takes a PDC file ending in .tmt10.tsv or .itraq.tsv and creates tidied data frame with Gene, Patient, logratio and diffFromMean values Parameters ---------- fpath : chr, optional ...
48b421d965e9b7f337a1f58c3665643eba514a7c
16,230
def ave(x): """ Returns the average value of a list. :param x: a given list :return: the average of param x """ return np.mean(x)
ad7737321d9f0fc8461129b0153f40da2d75dc70
16,231
def information_gain(f1, f2): """ This function calculates the information gain, where ig(f1,f2) = H(f1) - H(f1|f2) Input ----- f1: {numpy array}, shape (n_samples,) f2: {numpy array}, shape (n_samples,) Output ------ ig: {float} """ ig = entropyd(f1) - conditional_entropy...
39c60bf6a9fbf18f4d5ba3af609fed53771bd817
16,232
def subsequent_chunk_mask( size: int, chunk_size: int, num_left_chunks: int=-1, ) -> paddle.Tensor: """Create mask for subsequent steps (size, size) with chunk size, this is for streaming encoder Args: size (int): size of mask chunk_size (int): size of chunk ...
512def08ef2fe35cdd80ba7eb92f30b73aef1782
16,234
def top_tags(request): """ Shows a list of the most-used Tags. Context:: object_list The list of Tags Template:: cab/top_tags.html """ return render_to_response('cab/top_tags.html', { 'object_list': Snippet.objects.top_item...
07cf792fb3bd0ed5a1185986fb3154cb645b2a75
16,235
def check_integer_sign(value): """ :param value: :return: """ return value >= 0
0ab012b62bf7b12ecabea8d1a4538bb30e197e07
16,236
import torch def masks_empty(sample, mask_names): """ Tests whether a sample has any non-masked values """ return any(not torch.any(sample[name] != 0) for name in mask_names)
4c13b123fe6f5a17c3cd2ee673c54de331af7b23
16,237
def quantize_factor(factor_data, quantiles=5, bins=None, by_group=False): """ Computes period wise factor quantiles. Parameters ---------- factor_data : pd.DataFrame - MultiIndex A MultiIndex DataFrame indexed by date (level 0) and asset (level 1), containing the values for a single...
1b51b84e9f22a1b0e0c2bb578a2011c1b8f725e2
16,238
def listSplit(aList, n): """将一个列表以n个元素为一个单元进行均分,返回嵌套列表""" return [aList[i:i+n] for i in range(0,len(aList),n)]
936d4ff5b3bbbc39c57c01dc6a12e42b7dc6e0de
16,240
import json def refs(request): """ Настройка назначения анализов вместе """ if request.method == "GET": rows = [] fraction = directory.Fractions.objects.get(pk=int(request.GET["pk"])) for r in directory.References.objects.filter(fraction=fraction).order_by("pk"): rows.appen...
7635525efbdab8e22c21019f8de9cc74a83c9c2a
16,241
def transform(data): """replace the data value in the sheet if it is zero :param data: data set :return: data set without zero """ data_transformed = data.applymap(zero2minimum) return data_transformed
b717c6f42c8f0ae0c68c97647a33e77aec2f1508
16,242
def findChildren(node, name): """Returns all the children of input node, with a matching name. Arguments: node (dagNode): The input node to search name (str): The name to search Returns: dagNode list: The children dagNodes """ return __findChildren(node, name, False)
9258dac1261e24d3cc5e58030147ce693fbd0356
16,243
def get_process_rss(force_update=False, pid=None): """ <Purpose> Returns the Resident Set Size of a process. By default, this will return the information cached by the last call to _get_proc_info_by_pid. This call is used in get_process_cpu_time. <Arguments> force_update: Allows the caller ...
99c1c3fd35db4bb22c2c37aba48ddb7049ec26fa
16,244
from typing import Dict def doc_to_dict(doc) -> Dict: """Takes whatever the mongo doc is and turns into json serializable dict""" ret = {k: stringify_mongovalues(v) for k, v in doc.items() if k != "_id"} ret["_id"] = str(doc["_id"]) return ret
9e3f72568cf25ac864c1add2989c8e1cb064661d
16,245
def add_srv_2cluster(cluster_name, srvjson): """ 添加服务到数据库 :param cluster_name: :param srvjson: :return: """ status = '' message = '' resp = {"status": status, "message": message} host_name = srvjson.get('host_name') service_name = srvjson.get('service_name') sfo_clu_node ...
2e3c6ec6a312016785affbc71c5c2f178a0ecd84
16,246
def _add_left_zeros(number, iteration_digits): """Add zeros to the left side of the experiment run number. Zeros will be added according to missing spaces until iterations_digits are reached. """ number = str(number) return f'{"0" * (iteration_digits - len(number))}{number}'
e3f86a7e7f276ceff4eb662a3f5bc364b4d10ea3
16,247
def sharpdiff(y_true, y_pred): """ @param y_true: tensor of shape (batch_size, height, width, channels) @param y_pred: tensor of shape (batch_size, height, width, channels) @return: the sharpness difference as a scalar """ def log10(tensor): numerator = tf.math.log(tensor); ...
0c08541fd5c551c5a2ca1afb598adfc627c06286
16,248
import logging def admin_setfriend(): """ Set the friend state of a user """ uid = request.args.get("uid", "") state = request.args.get("state", "1") # Default: set as friend try: state = bool(int(state)) except Exception: return ( "<html><body><p>Invalid state string:...
f4b3a04b18735320968513666ad5901a68e5a492
16,249
def LF_CG_BICLUSTER_BINDS(c): """ This label function uses the bicluster data located in the A global network of biomedical relationships """ sen_pos = c.get_parent().position pubmed_id = c.get_parent().document.name query = bicluster_dep_df.query("pubmed_id==@pubmed_id&sentence_num==@sen_p...
29aeb5af69257a9c762bccc45c09e68d0799174c
16,250
from typing import List import random def single_point_crossover(parents: List[Chromosome], probability: float = 0.7) -> List[Chromosome]: """ Make the crossover of two parents to generate two child. The crossover has a probability to be made. The crossover point is random. :param parents: selected p...
4e8dd96fc42a8a1a1feb7c1c3dad42892e060425
16,252
def get_node_count(network=None, base_url=DEFAULT_BASE_URL): """Reports the number of nodes in the network. Args: network (SUID or str or None): Name or SUID of a network or view. Default is the "current" network active in Cytoscape. base_url (str): Ignore unless you need to specify...
c80e34443c4e39a96496eca5867333800b0208c5
16,253
from typing import Dict from typing import Any from typing import Tuple from typing import Optional import re def process_sample( sample: Dict[str, Any], relation_vocab: Dict[str, int], spacy_model: Any, tokenizer: Any, ) -> Tuple[Optional[Dict[str, Any]], Dict[str, int]]: """Processes WebRED sample...
74a80fb69fdebb35c86830f54344fc770ad91cd4
16,254
import tempfile def transform_s3(key, bucket="songsbuckettest"): """ REMEBER TO DO DEFENSIVE PROGRAMMING, WRAP IN TRY/CATCH """ s3 = boto3.client('s3') # print("connection to s3 -- Test") with tempfile.NamedTemporaryFile(mode='wb') as tmp: s3.download_fileobj(bucket, key, tmp) ...
3e7419185ab3c3581ea24227c204fd207b113b1e
16,255
def get_active_users(URM, popular_threshold=100): """ Get the users with activity above a certain threshold :param URM: URM on which users will be extracted :param popular_threshold: popularty threshold :return: """ return _get_popular(URM, popular_threshold, axis=1)
6b05e1a4288e00903ce9b396407c4e3547402710
16,256
def default_data_to_device( input, target=None, device: str = "cuda", non_blocking: bool = True ): """Sends data output from a PyTorch Dataloader to the device.""" input = input.to(device=device, non_blocking=non_blocking) if target is not None: target = target.to(device=device, non_blocking=n...
8dafddbd52b54a576ddc67d7d79af4372fbd57dc
16,257
def _get_diff2_data(request, ps_left_id, ps_right_id, patch_id, context, column_width, tab_spaces, patch_filename=None): """Helper function that returns objects for diff2 views""" ps_left = models.PatchSet.get_by_id(int(ps_left_id), parent=request.issue.key) if ps_left is None: return Http...
47aef66544acec7d57125f3c7c0f8edb385ba150
16,258
def vec_add(iter_a, iter_b): """element wise addition""" if len(iter_a) != len(iter_b): raise ValueError return (a + b for a, b in zip(iter_a, iter_b))
f3e5bf50d61cfe518ee8b0eb838503a7f054baa8
16,259
def run(): """ Read inputs into a dictionary for recursive searching """ for line in inputs: # Strip the trailing "." and split container, rest = line[:-1].split(" contain ") # Strip the trailing " bags" container = container[:-5] contained = [] for bag in rest.sp...
c3b565efbb923562c13955d808cf6ac2f09b616b
16,260
def _get_prolongation_coordinates(grid, d1, d2): """Calculate required coordinates of finer grid for prolongation.""" D2, D1 = np.broadcast_arrays( getattr(grid, 'vectorN'+d2), getattr(grid, 'vectorN'+d1)[:, None]) return np.r_[D1.ravel('F'), D2.ravel('F')].reshape(-1, 2, order='F')
6534c456413cd062f9c35c14f5d9b57b1aba6c12
16,261
def get_info(obj): """ get info from account obj :type obj: account object :param obj: the object of account :return: dict of account info """ if obj: return dict(db_instance_id=obj.dbinstance_id, account_name=obj.account_name, account_status=o...
c654ab1bdb4b4bf20223172dae450e1e7e6a52b9
16,263
def vlookup(x0, vals, ind, approx=True): """ Equivalent to the spreadsheet VLOOKUP function :param vals: array_like 2d array of values - first column is searched for index :param x0: :param ind: :param approx: :return: """ if isinstance(vals[0][0], str): x0 = str(x0)...
59ee6ecd7c001bf6cf3f03ad678d93eda33f5e21
16,264
def matmul(a00, a10, a01, a11, b00, b10, b01, b11): """ Compute 2x2 matrix mutiplication in vector way C = A*B C = [a00 a01] * [b00 b01] = [c00 c01] [a10 a11] [b10 b11] [c10 c11] """ c00 = a00*b00 + a01*b10 c10 = a10*b00 + a11*b10 c01 = a00*b01 + a01*...
d34506cc8099cbbf8b7a9e1eb9d4d068d768ebac
16,265
import collections import random def random_sample_with_weight_and_cost(population, weights, costs, cost_limit): """ Like random_sample_with_weight but with the addition of a cost and limit. While performing random samples (with priority for higher weight) we'll keep track of cost If cost exceeds the ...
637afd1c0e83bbda879f41bd15feb0f65b238fb3
16,266
def hardnet68ds(pretrained=False, **kwargs): """ # This docstring shows up in hub.help() Harmonic DenseNet 68ds (Depthwise Separable) model pretrained (bool): kwargs, load pretrained weights into the model """ # Call the model, load pretrained weights model = hardnet.HarDNet(depth_wise=True, arc...
5167b79f8effdb9a4b94e9d0a7902f35468a1d8b
16,267
def get_config(): """Base config for training models.""" config = ml_collections.ConfigDict() # How often to save the model checkpoint. config.save_checkpoints_steps: int = 1000 # Frequency fo eval during training, e.g. every 1000 steps. config.eval_frequency: int = 1000 # Total batch size for training....
67dfe8aff3f1a3e660d9debccc181690ea561ae2
16,268
def slave_addresses(dns): """List of slave IP addresses @returns: str Comma delimited list of slave IP addresses """ return ', '.join(['{}:53'.format(s['address']) for s in dns.pool_config])
e293442272496f02a58055dd778ecfe875124ccd
16,269
def processAndLabelStates(role, states, reason, positiveStates=None, negativeStates=None, positiveStateLabelDict={}, negativeStateLabelDict={}): """Processes the states for an object and returns the appropriate state labels for both positive and negative states. @param role: The role of the object to process states f...
23be0c7d943961f756a02abea98c51500f92b00f
16,270
def shape_for_stateful_rnn(data, batch_size, seq_length, seq_step): """ Reformat our data vector into input and target sequences to feed into our RNN. Tricky with stateful RNNs. """ # Our target sequences are simply one timestep ahead of our input sequences. # e.g. with an input vector "wherefor...
431eb54acc9bfe2281a3a863335eb135f050f47e
16,271
import time import tqdm def setup_features(dataRaw, label='flux', notFeatures=[], pipeline=None, verbose=False, resample=False, returnAll=None): """Example function with types documented in the docstring. For production level usage: All scaling and transformations must be done with resp...
7c1fb86dc66d97610bd1d22ef65ccb88e105dd92
16,272
from typing import List from typing import Any def plot_marginal_effects(model: ModelBridge, metric: str) -> AxPlotConfig: """ Calculates and plots the marginal effects -- the effect of changing one factor away from the randomized distribution of the experiment and fixing it at a particular level. ...
f68c72d54e4e8ff1011ae6daec8a00ab30069d78
16,273
def _client_row_class(client: dict) -> str: """ Set the row class depending on what's in the client record. """ required_cols = ['trust_balance', 'refresh_trigger'] for col in required_cols: if col not in client: return 'dark' try: if client['trust_balance'] > clien...
cd5ebd8fd64c7d994d6803df473cd317af65e9ac
16,274
def num2ord(place): """Return ordinal for the given place.""" omap = { u'1' : u'st', u'2' : u'nd', u'3' : u'rd', u'11' : u'th', u'12' : u'th', u'13' : u'th' } if place in omap: return place + omap[place] elif place.isdigit(): ...
3552257bba134ac00ed8c68d72bf5c947424b2e7
16,275
from typing import Type def _get_dist_class( policy: Policy, config: AlgorithmConfigDict, action_space: gym.spaces.Space ) -> Type[TFActionDistribution]: """Helper function to return a dist class based on config and action space. Args: policy: The policy for which to return the action ...
08c09b876d5c2797d517a87957049c34939aee3a
16,276
def expectation_values(times, states, operator): """expectation values of operator at times wrt states""" def exp_value(state, operator, time): if len(state.shape) == 2: #DensityMatrix return np.trace(np.dot(state, operator(time))) else: #Stat...
4c18fa3b2ad7bec01f8f833ade59fe90315724ec
16,277
import http def bookmark(request): """ Add or remove a bookmark based on POST data. """ if request.method == 'POST': # getting handler model_name = request.POST.get('model', u'') model = django_apps.get_model(*model_name.split('.')) if model is None: # inva...
32743894345e170d6d0efc427f3be0fb8d24b044
16,279