content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def svn_repos_get_logs2(*args): """ svn_repos_get_logs2(svn_repos_t repos, apr_array_header_t paths, svn_revnum_t start, svn_revnum_t end, svn_boolean_t discover_changed_paths, svn_boolean_t strict_node_history, svn_repos_authz_func_t authz_read_func, svn_log_message_receiver_t...
8580b4df10d6a6ebecbea960e14cd2ca79720beb
3,659,544
def error_function(theta, X, y): """Error function J definition""" diff = np.dot(X, theta) - y return (1. / 2 * m) * np.dot(np.transpose(diff), diff)
0762651fe9f33107a4e198e70319f77a5ae50e0b
3,659,545
def register(operation_name): """ Registers the decorated class as an Operation with the supplied operation name :param operation_name: The identifying name for the Operation """ def wrapper(clazz): if operation_name not in OPERATIONS: OPERATIONS[operation_name] = clazz ...
036612a64d987ede2546bd5dbc9d848e6ed6c48b
3,659,546
def log2_grad(orig, grad): """Returns [grad * 1 / (log(2) * x)]""" x = orig.args[0] ones = ones_like(x) two = const(2.0, dtype=x.checked_type.dtype) return [grad * ones / (log(two) * x)]
c17d7eeee43e64e0eeb7feb86f357374cc2516e4
3,659,549
import posixpath import requests def _stream_annotation(file_name, pn_dir): """ Stream an entire remote annotation file from Physionet. Parameters ---------- file_name : str The name of the annotation file to be read. pn_dir : str The PhysioNet directory where the annotation f...
8a1168562b87f27cc035d21b7f91cb23a611d0b4
3,659,550
def get_scenarios(): """ Return a list scenarios and values for parameters in each of them :return: """ # Recover InteractiveSession isess = deserialize_isession_and_prepare_db_session() if isess and isinstance(isess, Response): return isess scenarios = get_scenarios_in_state(i...
2812cab14347f03e208d5c3b6399ffa954dfe843
3,659,551
def download() -> str: """ Returns a download of the active files. :return: the zip files needs to be downloaded. """ file_manager = utility.load_file_manager() response = make_response(file_manager.zip_active_files( "scrubbed_documents.zip")) # Disable download caching response.h...
a507c6fd2281226a0db4f4e9e84d2c4f0e6e9562
3,659,552
import pickle def load_from_pickle_file(filepath): """ Loads a pickle file into a python variable """ with open(filepath, "rb") as f: python_obj = pickle.load(f) return python_obj
8ad8b947e762590d1be8d6b3ca4b519293692f09
3,659,554
from aiida.orm import Dict from aiida_quantumespresso.utils.resources import get_default_options def generate_inputs_pw(fixture_code, generate_structure, generate_kpoints_mesh, generate_upf_data): """Generate default inputs for a `PwCalculation.""" def _generate_inputs_pw(): """Generate default input...
fbe0a332a011b1909380275b1f70444b2dfb5d17
3,659,555
def connected_components(edge_index, num_nodes=None): """Find the connected components of a given graph. Args: edge_index (LongTensor): Edge coordinate matrix. num_nodes (int, optional): Number of nodes. Defaults to None. Returns: LongTensor: Vector assigning each node to i...
cb0b620fbd5577375b2ac79d62194537e61a1204
3,659,556
import tqdm def assembly2graph(path=DATA_PATH): """Convert assemblies (assembly.json) to graph format""" """Return a list of NetworkX graphs""" graphs = [] input_files = get_input_files(path) for input_file in tqdm(input_files, desc="Generating Graphs"): ag = AssemblyGraph(input_file) ...
46f2ed913c5047d68ee523f1a23382c2036fc1d7
3,659,557
def _get_default_backing(backing): """ _get_default_backing(backing) Returns the prefered backing store - if user provides a valid Backing object, use it - if there is a default_backing object instantiated, use it - if the user provided a configuration dict, use it to create a new de...
60f878ee730bea33b93b88e88dfe29885f6fac85
3,659,558
def slice(request, response, start, end=None): """Send a byte range of the response body :param start: The starting offset. Follows python semantics including negative numbers. :param end: The ending offset, again with python semantics and None (spelled "null" in a query ...
450e43afb988736dee991bcf284d5b92e11aec74
3,659,559
import warnings def get_ps(sdfits, scan, ifnum=0, intnum=None, plnum=0, fdnum=0, method='vector', avgf_min=256): """ Parameters ---------- sdfits : scan : int Scan number. plnum : int Polarization number. method : {'vector', 'classic'}, optional Method...
8226f4e38ab7fce3c1c7f66c88b275e7c7798d86
3,659,560
import click def choiceprompt(variable: Variable) -> Binding: """Prompt to choose from several values for the given name.""" if not variable.choices: raise ValueError("variable with empty choices") choices = {str(number): value for number, value in enumerate(variable.choices, 1)} lines = [ ...
78700032f93abaca2227d653d5f199e6dbf3b4ba
3,659,561
import base64 import hashlib def rehash(file_path): """Return (hash, size) for a file with path file_path. The hash and size are used by pip to verify the integrity of the contents of a wheel.""" with open(file_path, 'rb') as file: contents = file.read() hash = base64.urlsafe_b64encode(has...
167449640e8cbf17d36e7221df3490a12381dd8e
3,659,563
import requests def _magpie_update_services_conflict(conflict_services, services_dict, request_cookies): # type: (List[Str], ServicesSettings, AnyCookiesType) -> Dict[Str, int] """ Resolve conflicting services by name during registration by updating them only if pointing to different URL. """ magp...
71f72680aebd1fd781c5cbd9e77eeba06a64062e
3,659,564
def rtc_runner(rtc): """Resolved tool contract runner.""" return run_main(polish_chunks_pickle_file=rtc.task.input_files[0], sentinel_file=rtc.task.input_files[1], subreads_file=rtc.task.input_files[2], output_json_file=rtc.task.output_files[0], ...
c9d5a1c23e5b88c6d7592dde473dc41123616a77
3,659,565
from typing import Any import json def dict_to_json_str(o: Any) -> str: """ Converts a python object into json. """ json_str = json.dumps(o, cls=EnhancedJSONEncoder, sort_keys=True) return json_str
8377cee2e25d5daeefd7a349ede02f7134e052b2
3,659,566
def paramid_to_paramname(paramid): """Turn a parameter id number into a parameter name""" try: return param_info[paramid]['n'] except KeyError: return "UNKNOWN_%s" % str(hex(paramid))
c5e47c6754448a20d79c33b6b501039b1463108e
3,659,567
def max_dist_comp(G, cc0, cc1): """ Maximum distance between components Parameters ---------- G : nx.graph Graph cc0 : list Component 0 cc1 : list Compoennt 1 Returns ------- threshold : float Maximum distance """ # Ass...
5df633ee746d537462b84674dc5adadd6f6f7e53
3,659,568
def convert_examples_to_features( examples, label_list, max_seq_length, tokenizer, cls_token_at_end=False, cls_token="[CLS]", cls_token_segment_id=1, sep_token="[SEP]", sep_token_extra=False, pad_on_left=False, pad_token=0, pad_token_segment_id=0, pad_token_label_id=-...
02e4a731c818e0833152aa8e44d6a49e523ef1fb
3,659,569
def exp(var): """ Returns variable representing exp applied to the input variable var """ result = Var(np.exp(var.val)) result.parents[var] = var.children[result] = np.exp(var.val) return result
d2811bbb240da33ce158a8bff5739ace2275da0e
3,659,570
from typing import List from typing import Any from typing import Callable def invalidate_cache( key: str = None, keys: List = [], obj: Any = None, obj_attr: str = None, namespace: str = None, ): """Invalidates a specific cache key""" if not namespace: namespace = HTTPCache.namespa...
1b200db81db9d1134bbbbb8a09d3b57f5c6623dc
3,659,571
def read_dataset(filename): """Reads in the TD events contained in the N-MNIST/N-CALTECH101 dataset file specified by 'filename'""" # NMIST: 34×34 pixels big f = open(filename, 'rb') raw_data = np.fromfile(f, dtype=np.uint8) f.close() raw_data = np.uint32(raw_data) all_y = raw_data[1::5] ...
74861968e36d3e357ce62f615456aa02eb3bd28b
3,659,572
def prge_annotation(): """Returns an annotation with protein/gene entities (PRGE) identified. """ annotation = {"ents": [{"text": "p53", "label": "PRGE", "start": 0, "end": 0}, {"text": "MK2", "label": "PRGE", "start": 0, "end": 0}], "text": "p53 and MK2", ...
dda417c1c1a1146482f4a3340741d938714dbf30
3,659,573
from scipy.spatial import Delaunay def inner_points_mask(points): """Mask array into `points` where ``points[msk]`` are all "inner" points, i.e. `points` with one level of edge points removed. For 1D, this is simply points[1:-1,:] (assuming ordered points). For ND, we calculate and remove the convex h...
d81788fdbe3f19f67719951b319bcdd5e01d4d60
3,659,574
from typing import Union import torch from typing import Tuple from typing import List def array2list(X_train: Union[np.ndarray, torch.Tensor], y_train: Union[np.ndarray, torch.Tensor], X_test: Union[np.ndarray, torch.Tensor], y_test: Union[np.ndarray, torch.Tensor], ...
8b4703b9296a786d24ae97edf142fc917d9a3b07
3,659,575
def livecoding_redirect_view(request): """ livecoding oath2 fetch access token after permission dialog """ code = request.GET.get('code') if code is None: return HttpResponse("code param is empty/not found") try: url = "https://www.livecoding.tv/o/token/" data = dict(cod...
acf06a996da8b70d982fa670080b48faeb452f60
3,659,576
from typing import OrderedDict def sort_dict(value): """Sort a dictionary.""" return OrderedDict((key, value[key]) for key in sorted(value))
93e03b64d44ab79e8841ba3ee7a3546c1e38d6e4
3,659,577
def hyb_stor_capacity_rule(mod, prj, prd): """ Power capacity of a hybrid project's storage component. """ return 0
86ed72e48738df66fca945ff8aaf976f0a7d14e0
3,659,578
def gilr_layer_cpu(X, hidden_size, nonlin=tf.nn.elu, name='gilr'): """ g_t = sigmoid(Ux_t + b) h_t = g_t h_{t-1} + (1-g_t) f(Vx_t + c) """ with vscope(name): n_dims = X.get_shape()[-1].value act = fc_layer(X, 2 * hidden_size, nonlin=tf.identity) gate, impulse =...
fce2d10be0b8ccb5923d1781795d08b562d602bf
3,659,579
import urllib import json def activation(formula=None, instrument=None, flux=None, cdratio=0, fastratio=0, mass=None, exposure=24, getdata=False): """Calculate sample activation using the FRM II activation web services. ``formula``: the chemical formula, see belo...
40588f5d5d76625b759f6642205b28aba8b9ceb8
3,659,582
def wrap_parfor_blocks(parfor, entry_label = None): """wrap parfor blocks for analysis/optimization like CFG""" blocks = parfor.loop_body.copy() # shallow copy is enough if entry_label == None: entry_label = min(blocks.keys()) assert entry_label > 0 # we are using 0 for init block here # ...
03528c18c9cd1f8d9671d12e0a4fa8668003305b
3,659,583
from typing import Counter def frequency_of_occurrence(words, specific_words=None): """ Returns a list of (instance, count) sorted in total order and then from most to least common Along with the count/frequency of each of those words as a tuple If specific_words list is present then SUM of frequencie...
a98670a89e843774bd1237c0d2e518d2cd8fb242
3,659,584
from typing import Union def cache_remove_all( connection: 'Connection', cache: Union[str, int], binary=False, query_id=None, ) -> 'APIResult': """ Removes all entries from cache, notifying listeners and cache writers. :param connection: connection to Ignite server, :param cache: name or ID o...
81e7cdbae9b3a04e205e15275dee2c45caa96d36
3,659,585
from typing import List def choices_function() -> List[str]: """Choices functions are useful when the choice list is dynamically generated (e.g. from data in a database)""" return ['a', 'dynamic', 'list', 'goes', 'here']
30b4b05435bacc0a42c91a3f0be09a90098a012f
3,659,587
def GetInfraPythonPath(hermetic=True, master_dir=None): """Returns (PythonPath): The full working Chrome Infra utility path. This path is consistent for master, slave, and tool usage. It includes (in this order): - Any environment PYTHONPATH overrides. - If 'master_dir' is supplied, the master's python p...
a43486c68559e42606a3a55444c998640529ef2b
3,659,588
import uuid def nodeid(): """nodeid() -> UUID Generate a new node id >>> nodeid() UUID('...') :returns: node id :rtype: :class:`uuid.UUID` """ return uuid.uuid4()
88a3ddc335ce2ca07bfc0e2caf8487dc2342e80f
3,659,589
def drop_redundant_cols(movies_df): """ Drop the following redundant columns: 1. `release_data_wiki` - after dropping the outlier 2. `revenue` - after using it to fill `box_office` missing values 3. `budget_kaggle` - after using it to fill `budget_wiki` missing values 4. `duration` - after usin...
f4fb2c98eafc4ec9074cbc659510af30c7155b9c
3,659,590
import pickle import gzip import collections import re import fnmatch def get_msids_for_add_msids(opt, logger): """ Parse MSIDs spec file (opt.add_msids) and return corresponding list of MSIDs. This implements support for a MSID spec file like:: # MSIDs that match the name or pattern are include...
b7f2a5b9f1452c8f43684223313716253e27848b
3,659,591
def gaussian_similarity(stimulus_representation, i, j, w, c, r): """ Function that calculates and returns the gaussian similarity of stimuli i and j (equation 4b in [Noso86]_) Parameters ---------- stimulus_representation : np.array The stimuli are given to this function in the form of a n ...
e1436a26d4f028f237e03d40590cb6b7405b3f16
3,659,592
def windShearVector(u, v, top, bottom, unit=None): """ calculate the u and v layer difference and return as vector """ udiff = layerDiff(u, top, bottom, unit) vdiff = layerDiff(v, top, bottom, unit) return makeVector(udiff, vdiff)
fa9fe1869621c04f00004a8a5c01e78d4faa3221
3,659,593
def withdraw_entry(contest): """Withdraws a submitted entry from the contest. After this step the submitted entry will be seen as a draft. """ return _update_sketch(contest, code=None, action="withdraw")
fdedfeb61e0fe3b47918b66ca1f9dfd56450e39c
3,659,594
def _conditional_field(if_, condition, colon, comment, eol, indent, body, dedent): """Formats an `if` construct.""" del indent, dedent # Unused # The body of an 'if' should be columnized with the surrounding blocks, so # much like an inline 'bits', its body is treated as an inline list o...
09c357659d5f78946d74cddc83f3e4c5c9cad0ed
3,659,595
def check_sum_cases(nation='England'): """check total data""" ck=LocalLatest() fail=False data=ck.data.get('data') latest={} data=clean_cases(data) #repair glitches #check latest data matches stored data for nation for i in data: _code=i['areaCode'] latest[_code...
5f30d4a856c21c1397e2f1cdd9a0ee03d026b5a2
3,659,596
def get_module_name() -> str: """Gets the name of the module that called a function Is meant to be used within a function. :returns: The name of the module that called your function """ return getmodulename(stack()[2][1])
12541aa8445ebd796657d76d3001523882202ea0
3,659,597
def elements_counter(arr, count=0): """递归计算列表包含的元素数 Arguments: arr {[list]} -- [列表] Keyword Arguments: count {int} -- [列表包含的元素数] (default: {0}) Returns: [int] -- [列表包含的元素数] """ if len(arr): arr.pop(0) count += 1 return elements_counter(arr, coun...
80809781fd2d6a7a2fa92a4b7d5713771a07f8eb
3,659,599
from typing import Dict def dataset_is_open_data(dataset: Dict) -> bool: """Check if dataset is tagged as open data.""" is_open_data = dataset.get("isOpenData") if is_open_data: return is_open_data["value"] == "true" return False
fc1591d4a045ba904658bb93577a364145492465
3,659,600
def _remove_suffix_apple(path): """ Strip off .so or .dylib. >>> _remove_suffix_apple("libpython.so") 'libpython' >>> _remove_suffix_apple("libpython.dylib") 'libpython' >>> _remove_suffix_apple("libpython3.7") 'libpython3.7' """ if path.endswith(".dylib"): return path[:...
c5526b0f3420625c2efeba225187f72c7a51fb4b
3,659,601
def sparsenet201(**kwargs): """ SparseNet-201 model from 'Sparsely Aggregated Convolutional Networks,' https://arxiv.org/abs/1801.05895. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/.torch/models' ...
83de415e043876ae90dd3f79c3ca26dd82d8c5df
3,659,602
def alt_text_to_curly_bracket(text): """ Converts the text that appears in the alt attribute of image tags from gatherer to a curly-bracket mana notation. ex: 'Green'->{G}, 'Blue or Red'->{U/R} 'Variable Colorless' -> {XC} 'Colorless' -> {C} 'N colorless' -> {N}, where N is some ...
c604b236a8d0baeff244e0e246176a406674c9e2
3,659,603
def massage_primary(repo_primary, src_cache, cdt): """ Massages the result of dictify() into a less cumbersome form. In particular: 1. There are many lists that can only be of length one that don't need to be lists at all. 2. The '_text' entries need to go away. 3. The real information st...
fd57ff925b46eb5adddee2c180fbc01b3c60ec7c
3,659,604
def ansi_color_name_to_escape_code(name, style="default", cmap=None): """Converts a color name to the inner part of an ANSI escape code""" cmap = _ensure_color_map(style=style, cmap=cmap) if name in cmap: return cmap[name] m = RE_XONSH_COLOR.match(name) if m is None: raise ValueError...
70b8fe19fc34d14c678c9e54890a4da7e0e37c24
3,659,605
import shlex import getopt from datetime import datetime def twitter(bot, message): """#twitter [-p 天数] -p : 几天以前 """ try: cmd, *args = shlex.split(message.text) except ValueError: return False if not cmd[0] in config['trigger']: return False if not cmd[1:] == 'tw...
ba02cebb5a680f26f2eb17c32b62ead9ac3995a3
3,659,606
import logging def get_zones(request): """Returns preprocessed thermal data for a given request or None.""" logging.info("received zone request:", request.building) zones, err = _get_zones(request.building) if err is not None: return None, err grpc_zones = [] for zones in zones: ...
b04dca4da5b68faea64744c9c7093a977eb120c1
3,659,608
def proper_classification(sp): """ Uses splat.classifyByStandard to classify spectra using spex standards """ #sp.slitpixelwidth=1 #sp.slitwidth=1 #sp.toInstrument('WFC3-G141') wsp= wisps.Spectrum(wave=sp.wave.value, flux=sp.flux.value, ...
31529d96fbc4fec69a5996fb33829be4caf51529
3,659,609
from typing import Tuple import torch def sum_last_4_layers(sequence_outputs: Tuple[torch.Tensor]) -> torch.Tensor: """Sums the last 4 hidden representations of a sequence output of BERT. Args: ----- sequence_output: Tuple of tensors of shape (batch, seq_length, hidden_size). For BERT base, th...
14bba441a116712d1431b1ee6dda33dc5ec4142c
3,659,610
def TotalCust(): """(read-only) Total Number of customers served from this line section.""" return lib.Lines_Get_TotalCust()
58984b853cdd9587c7db5ff6c30b7af20a64985a
3,659,611
import re def extra_normalize(text_orig: str): """ This function allows a simple normalization to the original text to make possible the aligning process. The replacement_patterns were obtained during experimentation with real text it is possible to add more or to get some errors without new rule...
d06ee939c8035cd7b83ed7f1577b383bfcaf203d
3,659,612
def list2str(lst: list) -> str: """ 将 list 内的元素转化为字符串,使得打印时能够按行输出并在前面加上序号(从1开始) e.g. In: lst = [a,b,c] str = list2str(lst) print(str) Out: 1. a 2. b 3. c """ i = 1 res_list = [] for x in lst: res_list.append(str(i)+'. '+str(x)) i += 1 res...
3da11748d650e234c082255b8d7dff5e56e65732
3,659,613
def _prompt_save(): # pragma: no cover """Show a prompt asking the user whether he wants to save or not. Output is 'save', 'cancel', or 'close' """ b = prompt( "Do you want to save your changes before quitting?", buttons=['save', 'cancel', 'close'], title='Save') return show_box(b...
859cbbe94ef35bf434b1c4f6cac9ec61a6311fb8
3,659,614
def plot_dataset_samples_1d( dataset, n_samples=10, title="Dataset", figsize=DFLT_FIGSIZE, ax=None, plot_config_kwargs={}, seed=123, ): """Plot `n_samples` samples of the a datset.""" np.random.seed(seed) with plot_config(plot_config_kwargs): if ax is None: f...
41b34e276a0236d46e13d7b0f24797e739384661
3,659,615
def list_versions(namespace, name, provider): """List version for mnodule. Args: namespace (str): namespace for the version name (str): Name of the module provider (str): Provider for the module Returns: response: JSON formatted respnse """ try: return make_...
dca0c24f391cce69a10fe7e61165647c9ce1cf66
3,659,616
import requests def script_cbor(self, script_hash: str, **kwargs): """ CBOR representation of a plutus script https://docs.blockfrost.io/#tag/Cardano-Scripts/paths/~1scripts~1{script_hash}~1cbor/get :param script_hash: Hash of the script. :type script_hash: str :param return_type: Optional. ...
fdb71d1e95d67da4a18552f4e42a28e27c7ab95a
3,659,617
def ithOfNPointsOnCircleY(i,n,r): """ return x coordinate of ith value of n points on circle of radius r points are numbered from 0 through n-1, spread counterclockwise around circle point 0 is at angle 0, as of on a unit circle, i.e. at point (0,r) """ # Hints: similar to ithOfNPointsOnCircle...
d4e697145423146b085f8423315c795745498afd
3,659,618
def get_tags(ec2id, ec2type, region): """ get tags return tags (json) """ mytags = [] ec2 = connect('ec2', region) if ec2type == 'volume': response = ec2.describe_volumes(VolumeIds=[ec2id]) if 'Tags' in response['Volumes'][0]: mytags = response['Volumes'][0]['Tags...
c150d83b6563f79140febb65a4ea7e50bc733286
3,659,619
def parse(data, raw=False, quiet=False): """ Main text parsing function Parameters: data: (string) text data to parse raw: (boolean) unprocessed output if True quiet: (boolean) suppress warning messages if True Returns: Dictionary. Raw or process...
dd7da8a23a0691dc2df75391c77fa1448362330a
3,659,620
def callNasaApi(date='empty'): """calls NASA APIS Args: date (str, optional): date for nasa APOD API. Defaults to 'empty'. Returns: Dict: custom API response """ print('calling nasa APOD API...') url = nasaInfo['nasa_apod_api_uri'] if date != 'empty': params = getA...
5eaa7fe9434c608df47828c8ce19d4e5e5cfe799
3,659,622
def train_reduced_model(x_values: np.ndarray, y_values: np.ndarray, n_components: int, seed: int, max_iter: int = 10000) -> sklearn.base.BaseEstimator: """ Train a reduced-quality model by putting a Gaussian random projection in front of the multinomial logistic regression stage of t...
ab2871875c751b5d7abb56991a55607e79c17e6e
3,659,623
def pv(array): """Return the PV value of the valid elements of an array. Parameters ---------- array : `numpy.ndarray` array of values Returns ------- `float` PV of the array """ non_nan = np.isfinite(array) return array[non_nan].max() - array[non_nan].min()
987ae80fa68cd1dee3e179975b283bb7f48dd2aa
3,659,624
def format_bad_frames(bad_frames): """Create an array of bad frame indices from string loaded from yml file.""" if bad_frames == "": bads = [] else: try: bads = [x.split("-") for x in bad_frames.split(",")] bads = [[int(x) for x in y] for y in bads] bads ...
433bcba8cc8bf7985a8103d595759d04099dce6a
3,659,625