content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import time import hmac import hashlib import requests import json def bittrex_get_balance(api_key, api_secret): """Get your total balances for your bittrex account args: required: api_key (str) api_secret (str) return: results (DataFrame) of balance informatio...
a90979a495fe9410d76996006063ca01fdcfe04c
22,700
def check_vm_snapshot_sanity(vm_id): """ Checks if the snapshot information of VM is in sync with actual snapshots of the VM. """ vm_data = db.vm_data[vm_id] snapshot_check = [] try: conn = libvirt.openReadOnly('qemu+ssh://root@'+vm_data.host_id.host_ip.private_ip+'/system') doma...
c73985741c154178151aa6e2b2e3a9a64b0eee12
22,701
def evaluate_functions(payload, context, get_node_instances_method, get_node_instance_method, get_node_method): """ Evaluate functions in payload. :param payload: The payload to evaluate. :param context: Context used during evaluation. :param get_node_instances_method: A method for getting node ins...
2cac04f35ac6032ec0d06ff5c25da9b64c700f7c
22,702
import torch def rollout(render=False): """ Execute a rollout and returns minus cumulative reward. Load :params: into the controller and execute a single rollout. This is the main API of this class. :args params: parameters as a single 1D np array :returns: minus cumulative reward # Why is ...
9165642f37ef1ea6882c6be0a6fe493d2aff342c
22,703
import requests import json def get_request(url, access_token, origin_address: str = None): """ Create a HTTP get request. """ api_headers = { 'Authorization': 'Bearer {0}'.format(access_token), 'X-Forwarded-For': origin_address } response = requests.get( url, ...
0c7f577132b1fb92a8ea9073cb68e9b7bf3cd2a5
22,704
def join_metadata(df: pd.DataFrame) -> pd.DataFrame: """Joins data including 'agent_id' to work out agent settings.""" assert 'agent_id' in df.columns sweep = make_agent_sweep() data = [] for agent_id, agent_ctor_config in enumerate(sweep): agent_params = {'agent_id': agent_id} agent_params.update(ag...
c09a524484424fb0fdf329fd73e3ea489b8ae523
22,705
def mocked_get_release_by_id(id_, includes=[], release_status=[], release_type=[]): """Mimic musicbrainzngs.get_release_by_id, accepting only a restricted list of MB ids (ID_RELEASE_0, ID_RELEASE_1). The returned dict differs only in the release title and artist name, so that ID...
647b9bf54f27353834a30ec907ecc5114a782b93
22,706
import os import warnings import pickle def mp_rf_optimizer_func(fn_tuple): """Executes in parallel creation of random forrest creation.""" fn, flags, file_suffix = fn_tuple n_trees = flags["n_trees"] is_regressor = flags["is_regressor"] sample_size = flags["sample_size"] n_features = flags["n_features"...
b046a3dc6d49f4f39ee72893ae5fe751fff3f437
22,707
import os def GetTracePaths(bucket): """Returns a list of trace files in a bucket. Finds and loads the trace databases, and returns their content as a list of paths. This function assumes a specific structure for the files in the bucket. These assumptions must match the behavior of the backend: - The tr...
a067b21d570de398034ad74bbc04f5aca028ac88
22,708
import typing import pathlib import os def FindRunfilesDirectory() -> typing.Optional[pathlib.Path]: """Find the '.runfiles' directory, if there is one. Returns: The absolute path of the runfiles directory, else None if not found. """ # Follow symlinks, looking for my module space stub_filename = os.pa...
44390f1a4e973e8b5ee8fa1060706447ae07263f
22,709
def get_name_with_template_specialization(node): """ node is a class returns the name, possibly added with the <..> of the specialisation """ if not node.kind in ( CursorKind.CLASS_DECL, CursorKind.STRUCT_DECL, CursorKind.CLASS_TEMPLATE_PARTIAL_SPECIALIZATION): return None tokens = get_token...
4cf19f9f383174789c7ff3003bc1144167d3e84d
22,710
from typing import Optional from typing import Union def linear_timeseries( start_value: float = 0, end_value: float = 1, start: Optional[Union[pd.Timestamp, int]] = pd.Timestamp("2000-01-01"), end: Optional[Union[pd.Timestamp, int]] = None, length: Optional[int] = None, freq: str = "D", c...
ae8ef8252beee1e799182d0aaa499167c1abb78d
22,711
from typing import Dict def outlierBySd(X: Matrix, max_iterations: int, **kwargs: Dict[str, VALID_INPUT_TYPES]): """ Builtin function for detecting and repairing outliers using standard deviation :param X: Matrix X :param k: threshold values 1, 2, 3 for ...
eda872a6dd6f8de22620ecf599381d186641a772
22,712
from typing import Dict def encode_address(address: Dict) -> bytes: """ Creates bytes representation of address data. args: address: Dictionary containing the address data. returns: Bytes to be saved as address value in DB. """ address_str = '' address_str += address['bal...
fcf05da104551561e44b7ab9c2bf54a9bfcf801e
22,713
def analyze_image(image_url, tag_limit=10): """ Given an image_url and a tag_limit, make requests to both the Clarifai API and the Microsoft Congnitive Services API to return two things: (1) A list of tags, limited by tag_limit, (2) A description of the image """ clarifai_tags = clarifai_analysis(im...
8d3337c34369d69c9ae48f43100ecb2b930f8a15
22,714
def _decision_function(scope, operator, container, model, proto_type): """Predict for linear model. score = X * coefficient + intercept """ coef_name = scope.get_unique_variable_name('coef') intercept_name = scope.get_unique_variable_name('intercept') matmul_result_name = scope.get_unique_variab...
e5f105bfb09ac0b5aba0c7adcfd6cb6538911040
22,715
def create_mapping(dico): """ Create a mapping (item to ID / ID to item) from a dictionary. Items are ordered by decreasing frequency. """ sorted_items = sorted(list(dico.items()), key=lambda x: (-x[1], x[0])) id_to_item = {i: v[0] for i, v in enumerate(sorted_items)} item_to_id = {v: k for ...
cdfb0bd9ffa047e0214486a1b2e63b45e437cf22
22,716
import os def _splitall(path): """ This function splits a path /a/b/c into a list [/,a,b,c] """ allparts = [] while True: parts = os.path.split(path) if parts[0] == path: allparts.insert(0, parts[0]) break if parts[1] == path: allparts...
fe9d2124dad684b9a2e7a3366b80784c0779c105
22,717
def read_library(args): """Read in a haplotype library. Returns a HaplotypeLibrary() and allele coding array""" assert args.library or args.libphase filename = args.library if args.library else args.libphase print(f'Reading haplotype library from: {filename}') library = Pedigree.Pedigree() if ar...
e96b156db9cdcf0b70dfcdb2ba155f26a59f8d44
22,718
from typing import Callable def to_async(func: Callable, scheduler=None) -> Callable: """Converts the function into an asynchronous function. Each invocation of the resulting asynchronous function causes an invocation of the original synchronous function on the specified scheduler. Example: r...
aa66337b7463d97c47e8c42ea044157cb5bf616c
22,719
import sympy def get_symbolic_quaternion_from_axis_angle(axis, angle, convention='xyzw'): """Get the symbolic quaternion associated from the axis/angle representation. Args: axis (np.array[float[3]], np.array[sympy.Symbol[3]]): 3d axis vector. angle (float, sympy.Symbol): angle. conve...
8d753c72fc775de38b349e2bf77e3a61a84b07e9
22,720
def get_session(role_arn, session_name, duration_seconds=900): """ Returns a boto3 session for the specified role. """ response = sts_client.assume_role( RoleArn=role_arn, RoleSessionName=session_name, DurationSeconds=duration_seconds, ) creds = response["Credentials"] ...
d60b0b1c6288a8a594e0a1fe4175c69da80ffe29
22,721
import traceback def base_kinesis_role(construct, resource_name: str, principal_resource: str, **kwargs): """ Function that generates an IAM Role with a Policy for SQS Send Message. :param construct: Custom construct that will use this function. From the external construct is usually 'self'. :param re...
82c2d7b7b32857baa619ed7891956930e206bf78
22,722
def set_age_distribution_default(dic, value=None, drop=False): """ Set the ages_distribution key of dictionary to the given value or to the World's age distribution. """ ages = dic.pop("age_distribution", None) if ages is None: ages = world_age_distribution() if value is None else valu...
98ca6e784b240ee76ddb4a9d77b691ef08fa7057
22,723
def home(): """Home page""" return render_template('home.html')
dc63ced89e5176de1f77ea995678c2f5c37c2593
22,724
import copy def csv2dict(file_csv, delimiter=','): """ This function is used to load the csv file and return a dict which contains the information of the csv file. The first row of the csv file contains the column names. Parameters ---------- file_csv : str The input filename incl...
d971941b7c5f0bbf021c64cf7c30d1dcee710b9d
22,725
def make_bb_coord_l(contour_l, img, IMG_HEIGHT): """ Take in a list of contour arrays and return a list of four coordinates of a bounding box for each contour array. """ assert isinstance(contour_l, list) coord_l = [] for i in range(len(contour_l)): c = contour_l[i] ...
4f30c95db8a7d2ef81376aa0fa77d7cedc0a913c
22,726
def calc_pair_scale(seqs, obs1, obs2, weights1, weights2): """Return entropies and weights for comparable alignment. A comparable alignment is one in which, for each paired state ij, all alternate observable paired symbols are created. For instance, let the symbols {A,C} be observed at position i and {A...
6781b86719d669970d67753eabc91c60bc258dcc
22,727
def distance_to_line(pt, line_pt_pair): """ Returns perpendicular distance of point 'pt' to a line given by the pair of points in second argument """ x = pt[0] y = pt[1] p, q = line_pt_pair q0_m_p0 = q[0]-p[0] q1_m_p1 = q[1]-p[1] denom = sqrt(q0_m_p0*q0_m_p0 + q1_m_p1*q1_m_p1) ...
93500c0f8a4d8d11435647e1868fb929128d1273
22,728
def define_wfr(ekev): """ defines the wavefront in the plane prior to the mirror ie., after d1 :param ekev: energy of the source """ spb = Instrument() spb.build_elements(focus = 'nano') spb.build_beamline(focus = 'nano') spb.crop_beamline(element1 = "d1") bl = spb.get_beamline(...
8ccf7880ff22dc13f979b45c288a58bbb4e3c5c9
22,729
def ratlab(top="K+", bottom="H+", molality=False): """ Python wrapper for the ratlab() function in CHNOSZ. Produces a expression for the activity ratio between the ions in the top and bottom arguments. The default is a ratio with H+, i.e. (activity of the ion) / [(activity of H+) ^ (charge of t...
69c6a5fbbb344e5b0e063ea438994c3ce7e6cafb
22,730
def demean_dataframe_two_cat(df_copy, consist_var, category_col, is_unbalance): """ reference: Baltagi http://library.wbi.ac.id/repository/27.pdf page 176, equation (9.30) :param df_copy: Dataframe :param consist_var: List of columns need centering on fixed effects :param category_col: List of fixed...
a6a3f0bd56be214660eca857f0fb8630879bb2a8
22,731
from datetime import datetime import time def get_time_string(time_obj=None): """The canonical time string format (in UTC). :param time_obj: an optional datetime.datetime or timestruct (defaults to gm_time) Note: Changing this function will change all times that this project uses ...
73a623474e70850dc4194e2657b7e15aaa53996f
22,732
def apply_activation_checkpointing_wrapper( model, checkpoint_wrapper_fn=checkpoint_wrapper, check_fn=lambda _: True ): """ Applies :func:`checkpoint_wrapper` to modules within `model` based on a user-defined configuration. For each module within `model`, the `check_fn` is used to decide whether `mo...
ea4f7efef1f1c1c49a7cd078cae95be754f68c93
22,733
def train_validation_split(x, y): """ Prepare validation data with proper size Args: x: (pandas.DataFrame) Feature set / Affecting features y: (pandas.Dataframe) Target set / dependent feature Returns: x_train: (pandas.DataFrame) Feature set / Affecting features for training ...
eac70c13b2ebd592681dfdc5cc181b558a93b233
22,734
from typing import Union from typing import Tuple from typing import List def topk_accuracy( rankings: np.ndarray, labels: np.ndarray, ks: Union[Tuple[int, ...], int] = (1, 5) ) -> List[float]: """Computes Top-K accuracies for different values of k Args: rankings: 2D rankings array: shape = (inst...
36d3ac84b69b7d0f8764ad1213f56f82da717482
22,735
def has_substr(line, chars): """ checks to see if the line has one of the substrings given """ for char in chars: if char in line: return True return False
cf438600894ca43c177af1661a95447daa8b6b0d
22,736
def multifiltertestmethod(testmethod, strfilters): """returns a version of the testmethod that operates on filtered strings using strfilter""" def filteredmethod(str1, str2): return testmethod(multifilter(str1, strfilters), multifilter(str2, strfilters)) filteredmethod.__doc__ = testmethod.__doc__ ...
eec5e580bcc2987f8abfc23dd118897ed5d2b4c4
22,737
def getbasins(basin,Nx,Ny,Nz,S1,S2,S3): """ Args: basin (numpy array): including the Returns: N/A Only Extend CHGCAR while mode is 'all' """ temp = np.zeros(Nx*Ny*Nz*S1*S2*S3) basins = np.resize(temp,(Nz*S3,Ny*S2,Nx*S1)) block = np.resize(temp,(Nz*S3,Ny*S2,Nx*S1)) flag = 0 b = 1 teemp = [] for kss in...
97c489a7453aced3624f6898896924647f387d55
22,738
def makeframefromhumanstring(s): """Create a frame from a human readable string Strings have the form: <request-id> <stream-id> <stream-flags> <type> <flags> <payload> This can be used by user-facing applications and tests for creating frames easily without having to type out a bunch of const...
b588e61fb8b67b4160ac673eb3e70f373c7027b4
22,739
def display_full_name_with_correct_capitalization(full_name): """ See documentation here: https://github.com/derek73/python-nameparser :param full_name: :return: """ full_name.strip() full_name_parsed = HumanName(full_name) full_name_parsed.capitalize() full_name_capitalized = str(fu...
05133fc04631a39a19f2e27355456418ab7c78a7
22,740
from typing import Optional from typing import Iterable from typing import Dict from typing import Any import collections def load_experiment_artifacts( src_dir: str, file_name: str, selected_idxs: Optional[Iterable[int]] = None ) -> Dict[int, Any]: """ Load all the files in dirs under `src_dir` that matc...
67d8b9aba64f79b0361e7ed175ae597b22367f8a
22,741
from datetime import datetime from typing import Tuple def get_market_metrics(market_portfolio: pd.DataFrame, t_costs: float, index_id: str, index_name: str, test_data_start_date: datetime.date, test_data_end_date: datetime.date, market_logs=False) -> \ Tuple[pd.Series, pd.Series, pd.Se...
f5c77114c79ef901683ffdd4495a8a1022e42dc9
22,742
def get_puf_columns(seed=True, categorical=True, calculated=True): """Get a list of columns. Args: seed: Whether to include standard seed columns: ['MARS', 'XTOT', 'S006'] categorical: Whether to include categorical columns: ['F6251', 'MIDR', 'FDED', 'DSI'] calculated: Whether to includ...
af7d6799b7f17b2b05b62a7ed88d0695784cde59
22,743
def list_all_vms(osvars): """Returns a listing of all VM objects as reported by Nova""" novac = novaclient.Client('2', osvars['OS_USERNAME'], osvars['OS_PASSWORD'], osvars['OS_TENANT_NAME'], ...
b03bc9c5e458d62403b86346bdb4f9a2c3081909
22,744
def exec_cmd(cmd, path): """ Execute the specified command and return the result. """ out = '' err = '' sys.stdout.write("-------- Running \"%s\" in \"%s\"...\n" % (cmd, path)) parts = cmd.split() try: process = subprocess.Popen(parts, cwd=path, stdout=subprocess.PIPE, ...
ea75de47eebe526188533539a4d33e07d5a5bed3
22,745
def contains_numbers(iterable): """ Check if first iterable item is a number. """ return isinstance(iterable[0], Number)
0c6dc3031087e14ea50cb7d228da50b19a55a013
22,746
import tempfile from pathlib import Path import requests def get_image(img: PathStr) -> PILImage: """Get picture from either a path or URL""" if str(img).startswith("http"): with tempfile.TemporaryDirectory() as tmpdirname: dest = Path(tmpdirname) / str(img).split("?")[0].rpartition("/")[-...
374e2ff8f97c4d63ceb3d621ced25451d10b6793
22,747
def FAIMSNETNN_model(train_df, train_y, val_df, val_y, model_args, cv=3): """FIT neuralnetwork model.""" input_dim = train_df.shape[1] if model_args["grid"] == "tiny": param_grid = {"n1": [100], "d1": [0.3, 0.1], "lr": [0.001, 0.01], "epochs": [50], "batch_size": [32, 128], "in...
6f6520a3f9a746e6e1241f638358f00ce4f20ede
22,748
def assign_exam_blocks(data, departments, splitted_departments, number_exam_days): """ Assign departments to exam blocks and optimize this schedule to reduce conflicts. data (pandas.DataFrame): Course enrollments data departments (dict): Departments (str key) and courses in departments (list value) ...
ae272ea00a277960497d96b2593371bc35a9c3cb
22,749
import os def download_table_dbf(file_name, cache=True): """ Realiza o download de um arquivo auxiliar de dados do SINAN em formato "dbf" ou de uma pasta "zip" que o contém (se a pasta "zip" já não foi baixada), em seguida o lê como um objeto pandas DataFrame e por fim o elimina Parâmetros --...
90992f009a5a9d6f27c60b2dd68a83ec68f8540a
22,750
def aq_name(path_to_shp_file): """ Computes the name of a given aquifer given it's shape file :param path_to_shp_file: path to the .shp file for the given aquifer :return: a string (name of the aquifer) """ str_ags = path_to_shp_file.split('/') str_aq = "" if len(str_ags) >= 2: ...
1cb6f9881383b4627ea4f78bf2f6fd9cdf97dbc4
22,751
def gini(arr, mode='all'): """Calculate the Gini coefficient(s) of a matrix or vector. Parameters ---------- arr : array-like Array or matrix on which to compute the Gini coefficient(s). mode : string, optional One of ['row-wise', 'col-wise', 'all']. Default is 'all'. Returns ...
9fb3116506db949d273000510724bcce0ed165e2
22,752
import requests def getIndex(): """ Retrieves index value. """ headers = { 'accept': 'application/json', } indexData = requests.get( APIUrls.lnapi+APIUrls.indexUrl, headers=headers, ) if indexData.status_code == 200: return indexData.json() else: ...
ba35e1573a62e76d1f413036761b8a9054a3a878
22,753
import os def getDataFile(fname): """Return complete path to datafile fname. Data files are in the directory skeleton/skeleton/data """ return os.path.join(getDataPath(),fname)
8b359910ceac5216e5a968e7a07da47d558a20c1
22,754
def input_as_string(filename:str) -> str: """returns the content of the input file as a string""" with open(filename, encoding="utf-8") as file: return file.read().rstrip("\n")
0343de48580a71a62895aa093af1213c3f0c0b84
22,755
def channame_to_python_format_string(node, succgen=None): """See channame_str_to_python_format_string @succgen is optional, if given will check that identifiers can be found. """ if not node: #empty AST return (True, "") if node.type == 'Identifier': # and len(node.children) >= 1: ...
f7e71bd49624657e98e6f2c172e6f02d8bfc7307
22,756
import numpy import pandas def is_bad(x): """ for numeric vector x, return logical vector of positions that are null, NaN, infinite""" if can_convert_v_to_numeric(x): x = safe_to_numeric_array(x) return numpy.logical_or( pandas.isnull(x), numpy.logical_or(numpy.isnan(x), numpy.isin...
b4cf9de18cd8e52ff90a801f1eccf6a4ee2500db
22,757
import matplotlib.pyplot as plt import cv2 from tifffile import imsave from tifffile import imsave def psf_generator(cmap='hot', savebin=False, savetif=False, savevol=False, plot=False, display=False, psfvol=False, psftype=0, expsf=False, empsf=False, realshape=(0,0), **kwargs): """Calculate and save point spread fu...
3921a39839ece8be2aa762f27371707ff2c79914
22,758
def correct_format(): """ This method will be called by iolite when the user selects a file to import. Typically, it uses the provided name (stored in plugin.fileName) and parses as much of it as necessary to determine if this importer is appropriate to import the data. For example, although X S...
043238e6e26fb2844266b0b7462fe17c1b310d35
22,759
def T0_T0star(M, gamma): """Total temperature ratio for flow with heat addition (eq. 3.89) :param <float> M: Initial Mach # :param <float> gamma: Specific heat ratio :return <float> Total temperature ratio T0/T0star """ t1 = (gamma + 1) * M ** 2 t2 = (1.0 + gamma * M ** 2) ** 2 t3 = 2...
2e5c8ec2ab24dd0d4dfa2feddd0053f277665b33
22,760
from typing import Optional def remount_as( ip: Optional[str] = None, writeable: bool = False, folder: str = "/system" ) -> bool: """ Mount/Remount file-system. Requires root :param folder: folder to mount :param writeable: mount as writeable or readable-only :param ip: ...
8f343f96d066543359bdfcea3c42f41f40dcaf4d
22,761
def flip_channels(img): """Flips the order of channels in an image; eg, BGR <-> RGB. This function assumes the image is a numpy.array (what's returned by cv2 function calls) and uses the numpy re-ordering methods. The number of channels does not matter. If the image array is strictly 2D, no re-orde...
7aab0222f6fd66c06f8464cd042f30c6eac01c72
22,762
import os def autodiscover_datafiles(varmap): """Return list of (dist directory, data file list) 2-tuples. The ``data_dirs`` setup var is used to give a list of subdirectories in your source distro that contain data files. It is assumed that all such files will go in the ``share`` subdirector...
412e8beda31e19a4003b499e2e3596eb8e600424
22,763
def parse_main(index): """Parse a main function containing block items. Ex: int main() { return 4; } """ err = "expected main function starting" index = match_token(index, token_kinds.int_kw, ParserError.AT, err) index = match_token(index, token_kinds.main, ParserError.AT, err) index = mat...
ab932cf3d99340b97ec7d32fa668c4e00e16a3d1
22,764
def elist2tensor(elist, idtype): """Function to convert an edge list to edge tensors. Parameters ---------- elist : iterable of int pairs List of (src, dst) node ID pairs. idtype : int32, int64, optional Integer ID type. Must be int32 or int64. Returns ------- (Tensor, ...
a38c26a13b2fc7f111e3ec2c036e592b5b4c3c70
22,765
from datetime import datetime def _term_to_xapian_value(term, field_type): """ Converts a term to a serialized Xapian value based on the field_type. """ assert field_type in FIELD_TYPES def strf(dt): """ Equivalent to datetime.datetime.strptime(dt, DATETIME_FORMAT) but...
8fe2926a7093ff9a7b22cc222c4a3c5c8f6bc155
22,766
def pop_stl1(osurls, radiourls, splitos): """ Replace STL100-1 links in 10.3.3+. :param osurls: List of OS platforms. :type osurls: list(str) :param radiourls: List of radio platforms. :type radiourls: list(str) :param splitos: OS version, split and cast to int: [10, 3, 3, 2205] :type...
d88576028bbfbf61ab6fec517e7a66d731b4ebf3
22,767
def empty_search(): """ :return: json response of empty list, meaning empty search result """ return jsonify(results=[])
59ac0a6d3b9a3d17f7a80e633ea4bb5b2d07ca33
22,768
def clip_raster_mean(raster_path, feature, var_nam): """ Opens a raster file from raster_path and applies a mask based on a polygon (feature). It then extracts the percentage of every class with respects to the total number of pixels contained in the mask. :param raster_path: raster path (ras...
82244272c2da713f679d0f56f5736810fcf8649c
22,769
import json def load_data(in_file): """load json file from seqcluster cluster""" with open(in_file) as in_handle: return json.load(in_handle)
93c1766cb1e36410a8c67e2291b93aa7280abd63
22,770
import os def applyPatch(sourceDir, f, patchLevel='0'): """apply single patch""" if os.path.isdir(f): # apply a whole dir of patches out = True with os.scandir(f) as scan: for patch in scan: if patch.is_file() and not patch.name.startswith("."): ...
031ed88aa8407debacbf4c76f343ed8cd5646d2a
22,771
import re def expand_at_linestart(P, tablen): """只扩展行开头的制表符号""" def exp(m): return m.group().expandtabs(tablen) return ''.join([ re.sub(r'^\s+', exp, s) for s in P.splitlines(True) ])
2b8310e89efdba54b121667e11454281e2c214e3
22,772
def configs(): """Create a mock Configuration object with sentinel values Eg. Configuration( base_jar=sentinel.base_jar, config_file=sentinel.config_file, ... ) """ return Configuration(**dict( (k, getattr(sentinel, k)) for k in DEFAU...
c8aa44e1c9695a8fe0188d739c87be07ab06bdb0
22,773
def svn_fs_revision_root_revision(root): """svn_fs_revision_root_revision(svn_fs_root_t * root) -> svn_revnum_t""" return _fs.svn_fs_revision_root_revision(root)
ce153da9527fb8b1235f5591dbd68e2f1c1ecab2
22,774
def config_ospf_interface( tgen, topo=None, input_dict=None, build=False, load_config=True ): """ API to configure ospf on router. Parameters ---------- * `tgen` : Topogen object * `topo` : json file data * `input_dict` : Input dict data, required when configuring from testcase * `b...
9d5f91bd9d3e2ede8e83a538cc7c1e36a8cf9596
22,775
from typing import Any def is_floatscalar(x: Any) -> bool: """Check whether `x` is a float scalar. Parameters: ---------- x: A python object to check. Returns: ---------- `True` iff `x` is a float scalar (built-in or Numpy float). """ return isinstance(x, ( float, n...
2a93524290eaa4b4e1f0b0cc7a8a0dcb2a46f9d3
22,776
def http_header_control_cache(request): """ Tipo de control de cache url: direccion de la pagina web""" print "--------------- Obteniendo cache control -------------------" try: cabecera = request.headers cache_control = cabecera.get("cache-control") except Exception: cache_c...
976adffa3c3601c6f0fd49617e15e25aa9cb2c9b
22,777
def summation(limit): """ Returns the summation of all natural numbers from 0 to limit Uses short form summation formula natural summation :param limit: {int} :return: {int} """ return (limit * (limit + 1)) // 2 if limit >= 0 else 0
1ff16c7c4131458e50c9c9bd5c0f20895d8ab121
22,778
def load_and_initialize_hub_module(module_path, signature='default'): """Loads graph of a TF-Hub module and initializes it into a session. Args: module_path: string Path to TF-Hub module. signature: string Signature to use when creating the apply graph. Return: graph: tf.Graph Graph of the module. ...
b04b5f77c7e0207d314ebb5910ec1c5e61f4755c
22,779
def j_index(true_labels, predicts): """ j_index Computes the Jaccard Index of the given set, which is also called the 'intersection over union' in multi-label settings. It's defined as the intersection between the true label's set and the prediction's set, divided by the sum, or union, of th...
33bef64196acf441c299a4a90da64b2bb866e364
22,780
import torch def odefun(x, t, net, alph=[1.0,1.0,1.0]): """ neural ODE combining the characteristics and log-determinant (see Eq. (2)), the transport costs (see Eq. (5)), and the HJB regularizer (see Eq. (7)). d_t [x ; l ; v ; r] = odefun( [x ; l ; v ; r] , t ) x - particle position l - log...
1523b28f1568bcd668a3f8cc8ce39dfb7d8096fe
22,781
def create_transform(num_flow_steps, param_dim, context_dim, base_transform_kwargs): """Build a sequence of NSF transforms, which maps parameters x into the base distribution u (noise). Transforms are conditioned on strain data y. Note that the...
d4d556163af777f50aed2f4d86b1ae9c1de81047
22,782
import tarfile import sys def filterUniques(tar, to_filter, score, ns): """ Filters unique psms/peptides/proteins from (multiple) Percolator output XML files. Takes a tarred set of XML files, a filtering query (e.g. psms), a score to filter on and a namespace. Outputs an ElementTree. "...
0fdfb1084d803afab2b13241f5c0b75726fd10e0
22,783
def for_in_pyiter(it): """ >>> for_in_pyiter(Iterable(5)) [0, 1, 2, 3, 4] """ l = [] for item in it: l.append(item) return l
7d5c44ce771ea9847d57749235a31f200a01b67f
22,784
def train_test_split_with_none(X, y=None, sample_weight=None, random_state=0): """ Splits into train and test data even if they are None. @param X X @param y y @param sample_weight sample weight @param random_state random state @return ...
8a789d6001a56096eba556301e130c57edd8cf87
22,785
def measure_time(func, repeat=1000): """ Repeatedly executes a function and records lowest time. """ def wrapper(*args, **kwargs): min_time = 1000 for _ in range(repeat): start = timer() result = func(*args, **kwargs) curr_time = timer() - start ...
0515eca9cfa96a7395b3461bd3302a9780d05366
22,786
def initialise_players(frame_data, params): """ initialise_players(team,teamname,params) create a list of player objects that holds their positions and velocities from the tracking data dataframe Parameters ----------- team: row (i.e. instant) of either the home or away team tracking Datafram...
4126ba5cf1cdcd61017692260026dbdd03523874
22,787
import gc def read_edgelist(f, directed=True, sep=r"\s+", header=None, keep_default_na=False, **readcsvkwargs): """ Creates a csrgraph from an edgelist. The edgelist should be in the form [source destination] or [source destination edge_weight] The first column needs to be...
dd4110700857c3deb86c53a176ab93b0366cd900
22,788
def is_comment(txt_row): """ Tries to determine if the current line of text is a comment line. Args: txt_row (string): text line to check. Returns: True when the text line is considered a comment line, False if not. """ if (len(txt_row) < 1): return True if ((txt_row...
db54b90053244b17ec209ed1edb1905b62151165
22,789
import json def updateBillingPlanPaymentDefinition(pk, paypal_payment_definition): """Update an existing payment definition of a billing plan :param pk: the primary key of the payment definition (associated with a billing plan) :type pk: integer :param paypal_payment_definition: Paypal billing plan ...
b4bf58088c8e501ccf380dda98587467a8683ff9
22,790
from typing import List def format_float_list(array: List[float], precision: int = 4) -> List[str]: """ Formats a list of float values to a specific precision. :param array: A list of float values to format. :param precision: The number of decimal places to use. :return: A list of strings contain...
b790379327acc5ebdf54f99621a06edd6228941d
22,791
import html def counts_card() -> html.Div: """Return the div that contains the overall count of patients/studies/images.""" return html.Div( className="row", children=[ html.Div( className="four columns", children=[ html.Div( ...
f80ba28b7ef1b2407d6a8b3e8eaccf26c734566a
22,792
import logging def validate_est(est: EstData, include_elster_responses: bool = False): """ Data for a Est is validated using ERiC. If the validation is successful then this should return a 200 HTTP response with {'success': bool, 'est': est}. Otherwise this should return a 400 response if the validati...
2565572efd9b1ee52fabb98473b7934e13b691ca
22,793
from typing import Callable from typing import List async def list_solver_releases( solver_key: SolverKeyId, user_id: int = Depends(get_current_user_id), catalog_client: CatalogApi = Depends(get_api_client(CatalogApi)), url_for: Callable = Depends(get_reverse_url_mapper), ): """ Lists all releases...
0461e6ba72c01e789af8571d75b7da21d2f17801
22,794
def read_silicon_data(tool, target: Target): """ Reads silicon data from device :param tool: Programming/debugging tool used for communication :param target: The target object. :return: Device response """ logger.debug('Read silicon data') tool.reset(ResetType.HW) passed, response = ...
3b94234218f0a5573438851ec97d49856356fc7b
22,795
import copy def offset_perimeter(geometry, offset, side='left', plot_offset=False): """Offsets the perimeter of a geometry of a :class:`~sectionproperties.pre.sections.Geometry` object by a certain distance. Note that the perimeter facet list must be entered in a consecutive order. :param geometry: C...
e8b2851ea5ffd17faeb62bd3ca094e4cb6dd162a
22,796
def WalterComposition(F,P): """ Calculates the melt composition generated as a function of F and P, using the parameterisation of Duncan et al. (2017). Parameters ----- F: float Melt fraction P: float Pressure in GPa Returns ----- MeltComposition: series ...
54b2b5d6e6f4500da1c17e54bcb9b8804a65e9b0
22,797
from pathlib import Path def fetch_study_metadata( data_dir: Path, version: int = 7, verbose: int = 1 ) -> pd.DataFrame: """ Download if needed the `metadata.tsv.gz` file from Neurosynth and load it into a pandas DataFrame. The metadata table contains the metadata for each study. Each study (ID) ...
e04a0dd631f8b8a53708118134b8d5039e83bcdf
22,798
from typing import Union def proveFormula(formula: str) -> Union[int, str]: """ Implements proveFormula according to grader.py >>> proveFormula('p') 1 >>> proveFormula('(NOT (NOT (NOT (NOT not)) )\t)') 1 >>> proveFormula('(NOT (NOT (NOT (NOT not)) )') 'E' >>> proveFormula('(IF p ...
4c078bdfa586b9807b6265db43ee7187e6aef349
22,799