content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def str2bytes(s): """ Returns byte string representation of product state. Parameters ---------- s : str Representation of a product state, in terms of a string. """ return bitarray2bytes(str2bitarray(s))
defb9f471ba6108a0d667b6f4e9522c8b6f38649
3,654,100
import re def find_links(text, image_only=False): """ Find Markdown links in text and return a match object. Markdown links are expected to have the form [some txt](A-url.ext) or ![Alt text](cool-image.png). Parameters ---------- text : str Text in which to search for links. ...
5f96672b48d3d911faf2e398c86f622676263d73
3,654,101
def least_one_row(data_frame): """ checking at least one row in dataframe Input: pandas dataframe Output: True or False """ if data_frame: return True return False
a72cbd3d504140547233481ec8340a8510e35f52
3,654,102
import inspect from textwrap import dedent def get_reference_docs(): """Create reference documentation from the source code. A bit like Sphinx autodoc, but using Markdown, and more basic. Returns a str in Markdown format. Note that this function is used to build the Dash Slicer chapter in the Das...
e7727704026d6b0013f15e1be966ee92dbc19ef5
3,654,103
import math def generate_label_colors(labels: list, colors: list, palette='Set2'): """Matches labels with colors If there are more labels than colors, repeat and cycle through colors """ label_colors = defaultdict(dict) num_repeats = math.ceil(len(labels) / len(colors)) for label in enumerate(...
8b4b35498d4478604e81987b127ab099ebb0e70b
3,654,104
import os def get_xml_file_path_from_image_name(image_name, xml_dir_or_txt): """Retrieve xml filepath from xml dir Args: image_name: xml_dir_or_txt: Returns: xml_path: """ if os.path.isfile(xml_dir_or_txt): filepaths = fileio.read_list_from_txt(xml_dir_or_txt, fiel...
1b9e62bf77e1055a230ea47ea628677bfb8cde86
3,654,105
def index(): """ View root page function that returns the index page and its data """ # getting top headlines in sources topheadlines_sources = get_sources('top-headlines') business_sources = get_sources('business') entertainment_sources = get_sources('entertainment') title = 'Home - We...
df3c5d0471cde998f6ea5a0de2b41ab16ef775c6
3,654,106
def start_ltm(tup, taus, w=0.1, add_coh=False, use_cv=False, add_const=False, verbose=False, **kwargs): """Calculate the lifetime density map for given data. Parameters ---------- tup : datatuple t...
d24d2fdc9740a12766b5424a20c98f4ab14222eb
3,654,107
def manhattan_distance(origin, destination): """Return the Manhattan distance between the origin and the destination. @type origin: Location @type destination: Location @rtype: int >>> pt1 = Location(1,2) >>> pt2 = Location(3,4) >>> print(manhattan_distance(pt1, pt2)) 4 """ ret...
0bcfd7767e44b0dcc47890dc4bcb2c054abb4bde
3,654,108
import os import json def get_release(): """Get the current release of the application. By release, we mean the release from the version.json file à la Mozilla [1] (if any). If this file has not been found, it defaults to "NA". [1] https://github.com/mozilla-services/Dockerflow/blob/master/docs/...
5aece4ae245637243543e3bd5d81b4dabf0e968e
3,654,109
from typing import Dict from typing import List import logging def find_best_resampler( features_train: pd.DataFrame, labels_train: pd.DataFrame, parameters: Dict ) -> List: """Compare several resamplers and find the best one to handle imbalanced labels. Args: features_train: Training data of ind...
29c14261e0c5131c8fad653bb286d03c73b8ddd7
3,654,110
def grid(dim, num): """Build a one-dim grid of num points""" if dim.type == "categorical": return categorical_grid(dim, num) elif dim.type == "integer": return discrete_grid(dim, num) elif dim.type == "real": return real_grid(dim, num) elif dim.type == "fidelity": re...
1d59936882cd15372e0c13c02d80cbe739650134
3,654,111
def path(graph, source, target, excluded_edges=None, ooc_types=ooc_types): """ Path of functions between two types """ if not isinstance(source, type): source = type(source) if not isinstance(target, type): target = type(target) for cls in concatv(source.mro(), _virtual_superclasses): ...
6bdf2adbfc754dc5350406570bc865ac17c088ce
3,654,112
def is_resource_sufficient(order_ingredients): """Return true or false""" for item in order_ingredients: if order_ingredients[item]>=resources[item]: print(f"Sorry not Enough {item} to Make Coffee.") return False return True
758ab17760aac8f32b4d5fb93e42e01bc780507b
3,654,113
import requests def get_gh_releases_api(project, version=None): """ """ # https://developer.github.com/v3/auth/ # self.headers = {'Authorization': 'token %s' % self.api_token} # https://api.github.com/repos/pygame/stuntcat/releases/latest repo = get_repo_from_url(project.github_repo) if no...
348857ab557277f7b26cb93866284ac899746524
3,654,114
import random import logging def weak_move(board): """Weak AI - makes a random valid move. Args: board: (Board) The game board. Returns: Array: Our chosen move. """ valid_moves = _get_moves(board, Square.black) # Return a random valid move our_move = valid_moves[random.randrange(0, len(valid_m...
6c978b58cca58baadaab5417b27adbf4444d59ff
3,654,115
def flow_to_image(flow): """ Input: flow: Output: Img array: Description: Transfer flow map to image. Part of code forked from flownet. """ out = [] maxu = -999. maxv = -999. minu = 999. minv = 999. maxrad = -1 for i in range(flow.shape[0])...
b7ed9cf684b4b818397f0329f3c7de1dbfa2ecd8
3,654,116
def parse_model_value(value, context): """ do interpolation first from context, "x is {size}" with size = 5 will be interpolated to "x is 5" then return interpolated string :param value: :param context: :return: """ return value.format(**context)
58cee6092bc03debe636ae8fa47878727457d334
3,654,117
def apply_tropomi_operator( filename, n_elements, gc_startdate, gc_enddate, xlim, ylim, gc_cache, build_jacobian, sensi_cache, ): """ Apply the tropomi operator to map GEOS-Chem methane data to TROPOMI observation space. Arguments filename [str] : TR...
c449ddaf8113a3adfcd0e501cacc245bcf0af495
3,654,118
import yaml from typing import cast def load_configuration(yaml: yaml.ruamel.yaml.YAML, filename: str) -> DictLike: """Load an analysis configuration from a file. Args: yaml: YAML object to use in loading the configuration. filename: Filename of the YAML configuration file. Returns: ...
6c3b9b54b6e22b40c61c901b2bcb3b6af4847214
3,654,119
def device_list(request): """ :param request: :return: """ device_list = True list = Device.objects.all() return render(request, "back/device_list.html", locals())
f4892f40831d25182b55414a666fbd62d6d978ef
3,654,120
def L008_eval(segment, raw_stack, **kwargs): """ This is a slightly odd one, because we'll almost always evaluate from a point a few places after the problem site """ # We need at least two segments behind us for this to work if len(raw_stack) < 2: return True else: cm1 = raw_stack[-...
71c42999ffc76bd28a61b640cf85086b0b9e8d69
3,654,121
def overwrite_ruffus_args(args, config): """ :param args: :param config: :return: """ if config.has_section('Ruffus'): cmdargs = dict() cmdargs['draw_horizontally'] = bool cmdargs['flowchart'] = str cmdargs['flowchart_format'] = str cmdargs['forced_tasks']...
6f947c362a37bfdc6df53c861783604999621a88
3,654,122
def read_sfr_df(): """Reads and prepares the sfr_df Parameters: Returns: sfr_df(pd.DataFrame): dataframe of the fits file mosdef_sfrs_latest.fits """ sfr_df = read_file(imd.loc_sfrs_latest) sfr_df['FIELD_STR'] = [sfr_df.iloc[i]['FIELD'].decode( "utf-8").rstrip() for i in range(le...
9d0d16929ffd5043853096c01cafa00747104b9f
3,654,123
def redshift(x, vo=0., ve=0.,def_wlog=False): """ x: The measured wavelength. v: Speed of the observer [km/s]. ve: Speed of the emitter [km/s]. Returns: The emitted wavelength l'. Notes: f_m = f_e (Wright & Eastman 2014) """ if np.isnan(vo): vo = 0 # propagate ...
0dee71d862d2dc4252033964a9adcb4428c5dfa9
3,654,124
import mmap def overlay_spectra_plot(array, nrow=5,ncol=5,**kwargs): """ Overlay spectra on a collapsed cube. Parameters ---------- array : 3D numpy array nrow : int Number of rows in the figure. ncol : int Number of columns in the figure. ...
8abbbbe7667c57bea50575a58bf11c3b080c8608
3,654,125
def digest_from_rsa_scheme(scheme, hash_library=DEFAULT_HASH_LIBRARY): """ <Purpose> Get digest object from RSA scheme. <Arguments> scheme: A string that indicates the signature scheme used to generate 'signature'. Currently supported RSA schemes are defined in `securesystemslib.keys.RS...
6eaf10657a0e80f2ddfa5eacbcc1bac72437ca51
3,654,126
import os def getconfig(filename): """ 1. Checks if the config file exists. 2. If not, creates it with the content in default_config. 3. Reads the config file and returns it. Returns False in case of errors. """ global default_config if os.path.exists(filename): conf...
8c9cf7110a7279638e2051454a1e26ca25f69e6b
3,654,127
def table(content, accesskey:str ="", class_: str ="", contenteditable: str ="", data_key: str="", data_value: str="", dir_: str="", draggable: str="", hidden: str="", id_: str="", lang: str="", spellcheck: str="", style: str="", tabindex: str="", title: str="", transl...
b27cf1b1897bdbc764fff76edc2e53fa0aca7861
3,654,128
def _ev_match( output_dir, last_acceptable_entry_index, certificate, entry_type, extra_data, certificate_index): """Matcher function for the scanner. Returns the certificate's hash if it is a valid, non-expired, EV certificate, None otherwise.""" # Only generate whitelist for non-precertific...
acd8416546d5f687fd1bfc1f0edfc099cde4408d
3,654,129
def axis_ratio_disklike(scale=0.3, truncate=0.2): """Sample (one minus) the axis ratio of a disk-like galaxy from the Rayleigh distribution Parameters ---------- scale : float scale of the Rayleigh distribution; the bigger, the smaller the axis ratio truncate : float the minimum val...
d001ef0b2f5896f4e7f04f314cd4e71ffd97a277
3,654,130
import numpy def rk4(y0, t0, te, N, deriv, filename=None): """ General RK4 driver for N coupled differential eq's, fixed stepsize Input: - y0: Vector containing initial values for y - t0: Initial time - te: Ending time - N: Number of steps - deriv...
93b7255fc95f06f765df12930efcf89338970ee6
3,654,131
from typing import Dict from typing import Tuple def create_txt_substitute_record_rule_command(client: Client, args: Dict) -> Tuple[str, Dict, Dict]: """ Args: client: Client object args: Usually demisto.args() Returns: Outputs """ name = args.get('name') rp_zone = arg...
ada3c412ec166eedd04edb2219396da6aef967ea
3,654,132
def pot_rho_linear(SP, t, rho0=1025, a=2e-4, b=7e-4, SP0=35, t0=15): """ Potential density calculated using a linear equation of state: Parameters ---------- SP : array-like Salinity [g/kg] t : array-like Temperature [°C] rho0 : float, optional Constant ...
47dd8248239d2147ff50d1b179d3fc4392c173cb
3,654,133
def oembed(url, params=""): """ Render an OEmbed-compatible link as an embedded item. :param url: A URL of an OEmbed provider. :return: The OEMbed ``<embed>`` code. """ # Note: this method isn't currently very efficient - the data isn't # cached or stored. kwargs = dict(urlparse.parse_...
eece184ee8a17613607f190b2de002fb6026340c
3,654,134
async def create_assc(conn : asyncpg.Connection, name : str, type : str, base : str, leader : int) -> Association: """Create an association with the fields given. type must be 'Brotherhood','College', or 'Guild'. """ psql = """ SELECT assc_id FROM associations ...
3089b6033e31325d7b3942d9d887b89cec21ca1c
3,654,135
def filter_tof_to_csr( tof_slices: np.ndarray, push_indices: np.ndarray, tof_indices: np.ndarray, push_indptr: np.ndarray, ) -> tuple: """Get a CSR-matrix with raw indices satisfying push indices and tof slices. Parameters ---------- tof_slices : np.int64[:, 3] Each row of the a...
925fc93c6e275ead7d472469764fbbb1093aa6bd
3,654,136
def get_path_from_query_string(req): """Gets path from query string Args: req (flask.request): Request object from Flask Returns: path (str): Value of "path" parameter from query string Raises: exceptions.UserError: If "path" is not found in query string """ if req.arg...
7e279e8e33dbbaa6ceb18d4b9a61723826522ec3
3,654,137
import scipy def entropy_grassberger(n, base=None): """" Estimate the entropy of a discrete distribution from counts per category n: array of counts base: base in which to measure the entropy (default: nats) """ N = np.sum(n) entropy = np.log(N) - np.sum(n*scipy.special.digamma(n+1e-20))...
1dc5ced1f5bb43bce30fa9501632825648b19cb8
3,654,138
def get_param_layout(): """Get layout for causality finding parameters definition window Parameters ---------- Returns ------- `List[List[Element]]` Layout for causality finding parameters window """ box = [ [ sg.Text('Parameters') ],...
e09db05b848e71449d7d17004793e8ce167dca1a
3,654,139
def senti_histplot(senti_df): """histogram plot for sentiment""" senti_hist = ( alt.Chart(senti_df) .mark_bar() .encode(alt.Y(cts.SENTI, bin=True), x="count()", color=cts.SENTI,) .properties(height=300, width=100) ).interactive() return senti_hist
731fda9cf5af49fdbec7d1a16edbf65148e67d5a
3,654,140
def pd_df_sampling(df, coltarget="y", n1max=10000, n2max=-1, isconcat=1): """ DownSampler :param df: :param coltarget: binary class :param n1max: :param n2max: :param isconcat: :return: """ df1 = df[df[coltarget] == 0].sample(n=n1max) n2max = len(df[df[coltarget] == 1]) ...
2cec90c189d00a8cd3ec19224fa7a2685c135bf2
3,654,141
from functools import partial from pathlib import Path from argparse import ( ArgumentParser, ArgumentDefaultsHelpFormatter, ) from packaging.version import Version from .version import check_latest, is_flagged from niworkflows.utils.spaces import Reference, OutputReferencesAction from json import l...
ac2a2b8b3f6cab89f0720cb666ae3c7b9d69d730
3,654,142
def get_deliverer(batch_size, max_staleness, session): """ Helper function to returns the correct deliverer class for the batch_size and max_stalennes parameters """ if batch_size < 1: return SimpleDeliverer(session) else: return BatchDeliverer(session, batch_size, max_staleness)
544740a5f38befc4d8123e7835ba758feac2d35b
3,654,143
import copy def trace_fweight_deprecated(fimage, xinit, ltrace=None, rtraceinvvar=None, radius=3.): """ Python port of trace_fweight.pro from IDLUTILS Parameters: ----------- fimage: 2D ndarray Image for tracing xinit: ndarray Initial guesses for x-trace invvar: ndarray, optional ...
e927113477a277ceb9acc8ce6af8bd1689c2913c
3,654,144
from datetime import datetime def home(): """Renders the card page.""" cardStack = model.CardStack() return render_template( 'cards.html', title ='POSTIN - Swipe', cardSet = cardStack.cardList, year=datetime.now().year, )
203021b1da4833418aafd3e3e20964e3b765a816
3,654,145
import os import io import sys import tarfile def uncompress(filename: str, path: str = os.getcwd()) -> None: """Uncompress a tar file Args: filename: a tar file (tar, tgz, ...) path: where the filename will be uncompressed Example: >>> import robotathome as rh >...
797c8a0073fdc73d9a42f5089bc38ff51d71ceb7
3,654,146
def index(request): """ User profile page. """ user = request.user profile = user.userprofile context = collect_view_data(request, 'profile') context['user'] = user context['profile'] = profile context['uform'] = UserForm(request, request.user, init=True) context['upform'] = User...
1a8cc98ba476e21986f79ec8e662bb222df79fae
3,654,147
def user_confirm_email(token): """Confirm a user account using his email address and a token to approve. Parameters ---------- token : str The token associated with an email address. """ try: email = ts.loads(token, max_age=86400) except Exception as e: logger.error(...
3f26a4872af9759165d0592ac8d966f2e27a9bf6
3,654,148
def num_zeros_end(num): """ Counts the number of zeros at the end of the number 'num'. """ iszero = True num_zeros = 0 i = len(num)-1 while (iszero == True) and (i != 0): if num[i] == "0": num_zeros += 1 elif num[i] != "0": ...
f227cce65e26a0684a10755031a4aeff2156015a
3,654,149
from typing import List def batch_summarize(texts: List[str]) -> List[str]: """Summarizes the texts (local mode). :param texts: The texts to summarize. :type texts: List[str] :return: The summarized texts. :rtype: List[str] """ if _summarizer is None: load_summarizer() asse...
7c05b8f612faab808fbeb1ef7c21f8b3b2487be5
3,654,150
def Vp_estimation(z, T, x, g=param.g): """ Estimation of the Vp profile from the results of solving the system. """ DT = T - T[-1] # temperature variation in the layer compared to T[ICB] drhoP = -param.rhoH**2. * g * z / Seismic_observations.calcK(z) drhoT = -param.rhoH * param.alpha * DT # *(Mp*...
4f1e1936cc98cfd84d87a651c8deac5bb7aa39e0
3,654,151
def pp_date(dt): """ Human-readable (i.e. pretty-print) dates, e.g. for spreadsheets: See http://docs.python.org/tutorial/stdlib.html e.g. 31-Oct-2011 """ d = date_to_datetime(dt) return d.strftime('%d-%b-%Y')
a6c8cd97785212afebb2b8948117815f5553dc24
3,654,152
import copy import math def optimizer_p(cd, path, i, obs, path_penalty): """Optimizer of the current path. Reduce the piece-wise path length in the free space of the environment.""" p_tmp = copy.deepcopy(path) p_tmp[i].x = p_tmp[i].x + cd[0] p_tmp[i].y = p_tmp[i].y + cd[1] r1 = math.sqrt((p_tmp[i-...
da126e3e7c0013748b1bc5b39c1b51aa2bf0d68b
3,654,153
import base64 def create_message(sender_address, receiver_address , subject, email_content): """Create a message for an email. Args: sender: Email address of the sender. to: Email address of the receiver. subject: The subject of the email message. message_text: The text of the email message. R...
3970272fda9650b5b59de9a57b2579374088b5c4
3,654,154
import functools def handle_view_errors(func): """ view error handler wrapper # TODO - raise user related errors here """ @functools.wraps(func) def wrapper(*args, **kwargs): debug: bool = current_app.config.get('DEBUG') try: return func(*args, **kwargs) ...
8687214b9ad659a19699c3563a9a5890358e4c71
3,654,155
def get_latest_revision_number(request, package_id): """ returns the latest revision number for given package """ package = get_object_or_404(Package, id_number=package_id) return HttpResponse(simplejson.dumps({ 'revision_number': package.latest.revision_number}))
3f8053656cbd7e08336a4632f1deaf43e58bc3eb
3,654,156
from typing import Mapping def _make_mesh_tensors(inputs: Mapping[K, np.ndarray]) -> Mapping[K, tf.Tensor]: """ Computes tensors that are the Cartesian product of the inputs. This is around 20x faster than constructing this in Python. Args: inputs: A mapping from keys to NumPy arrays. R...
65a97e7f7d85668acd2af50ba9ed745190181018
3,654,157
def make_counters(): """Creates all of the VariantCounters we want to track.""" def _gt_selector(*gt_types): return lambda v: variantutils.genotype_type(v) in gt_types return VariantCounters([ ('All', lambda v: True), ('SNPs', variantutils.is_snp), ('Indels', variantutils.is_indel), ...
b7a943f045018556a2a5d0dbf5e093906d10242a
3,654,158
def connect_registry_client(): """ connect the module client for the Registry implementation we're using return the client object """ client = adapters.RegistryClient() client.connect(environment.service_connection_string) return client
f2e2bccb4cfacd86af36e3924463541d9e3dcdcd
3,654,159
def get_group_average_score(gid=None, name=None): """ Get the average score of teams in a group. Args: gid: The group id name: The group name Returns: The total score of the group """ group_scores = get_group_scores(gid=gid, name=name) total_score = sum([entry['scor...
cdea61e388b47f399fbc8e228e313d6199164b2f
3,654,160
def solve_with_cdd_for_II(A, verbose=False): """This method finds II's minmax strategy for zero-sum game A""" m = A.shape[0] # number of rows n = A.shape[1] # number of columns A = np.column_stack([[0]*m,-A,[1]*m]) I = np.eye(n) nn = np.column_stack([[0]*n,I,[0]*n]) # non-negativity cons...
87ac90691fcbbe2f89bf9090c31f86c165c007ed
3,654,161
def build_none() -> KeySetNone: """Returns NONE.""" return KeySetNone()
8ba38204cd763597c66d51466f5d2ffa5c9a19bf
3,654,162
import csv import numpy def load_csv(file, shape=None, normalize=False): """ Load CSV file. :param file: CSV file. :type file: file like object :param shape : data array is reshape to this shape. :type shape: tuple of int :return: numpy array """ value_list = [] for row in cs...
07f3b61bbdb6c9937f3cc4b0ae98fdfb7d8de48a
3,654,163
from typing import Tuple def flip_around_axis( coords: np.ndarray, axis: Tuple[float, float, float] = (0.2, 0.2, 0.2) ) -> np.ndarray: """Flips coordinates randomly w.r.t. each axis with its associated probability.""" for col in range(3): if np.random.binomial(1, axis[col]): ...
914834a8492998b4e1e0b93e5e9677ec9af2d736
3,654,164
import math def get_tc(name): """Determine the amount of tile columns to use.""" args = ["ffprobe", "-hide_banner", "-select_streams", "v", "-show_streams", name] proc = sp.run(args, text=True, stdout=sp.PIPE, stderr=sp.DEVNULL) lines = proc.stdout.splitlines() d = {} for ln in lines[1:-1]: ...
ee917cd8cebfe7dc4ae718d883c657cf23bff1cf
3,654,165
import os import socket def get_my_nodes(): """Get nodes assigned to this host for computation """ if not os.path.exists("/etc/cluster-hosts"): raise Exception("No cluster hosts specified") #grab list of hosts in cluster, in order hosts = [] with open("/etc/cluster-hosts", "r") as fp: for line in fp: ho...
3f3f57a3239d71850f1ee72ab108255d5f152830
3,654,166
def cmap_hex_color(cmap, i): """ Convert a Colormap to hex color. Parameters ---------- cmap : matplotlib.colors.ListedColormap Represents the Colormap. i : int List color index. Returns ------- String Represents corresponding hex string. """ return ...
9ac7753cde9470e3dd9fbd4a66373b25126635ca
3,654,167
def train_folds(X, y, fold_count, batch_size, get_model_func): """ K-Fold Cross-Validation for Keras Models Inspired by PavelOstyakov https://github.com/PavelOstyakov/toxic/blob/master/toxic/train_utils.py """ fold_size = len(X[0]) // fold_count models = [] for fold_id in range(0, fold_co...
51a38243925c76ac6179a90be46be31fcb685054
3,654,168
import socket import os, random, string import json def reset_password(request): """ View to handle password reset """ helper.log_entrace(logger,request) postEmail = request.POST.get('email', '') try: user = User.objects.get(email = postEmail) chars = string.ascii_letters + ...
50c8b1d058a168176b528bb9168d4e0e179a08c5
3,654,169
async def cancel(command: HALCommandType, script: str): """Cancels the execution of a script.""" try: await command.actor.helpers.scripts.cancel(script) except Exception as err: command.warning(text=f"Error found while trying to cancel {script}.") return command.fail(error=err) ...
438297845f5ba4ffc49b95a798adf61294371694
3,654,170
def get_nodes_by_betweenness_centrality(query_id, node_number): """Get a list of nodes with the top betweenness-centrality. --- tags: - query parameters: - name: query_id in: path description: The database query identifier required: true type: integer ...
44d97e443c6bef4d7048496674a2382a6c4f2ade
3,654,171
import sympy def preprocess(function): """ Converts a given function from type str to a Sympy object. Keyword arguments: function -- a string type representation of the user's math function """ expr = function while True: if '^' in expr: expr = expr[:expr.index('...
001bd04d27db2afa4debbe776e5fe3cf1af1476d
3,654,172
import re def tot_changes(changes: str) -> int: """Add deletions and insertions.""" insertions_pat = re.compile(r"(\d+) insertion") deletions_pat = re.compile(r"(\d+) deletion") insertions = insertions_pat.search(changes) insertions = int(insertions.group(1)) if insertions else 0 deletions =...
74742baf63db51b5c59b332f0104008500f330b9
3,654,173
def update_from_mcd(full_table, update_table): # type: (pd.DataFrame, pd.DataFrame) -> pd.DataFrame """ Update the full table (aka the PDG extended-style table) with the up-to-date information from the PDG .mcd file. Example ------- >>> new_table = update_from_mcd('mass_width_2008.fwf', 'ma...
c60daea5719445fb696ef21bbc0f233fea4e48cd
3,654,174
import socket def resolve_hostname(host): """Get IP address of hostname or URL.""" try: parsed = urlparse.urlparse(host) except AttributeError as err: error = "Hostname `%s`is unparseable. Error: %s" % (host, err) LOG.exception(error) raise errors.SatoriInvalidNetloc(error)...
1792d943e490661b4dd42608f2b025096810688f
3,654,175
import pandas as pd import numpy as np from .data_utils import keep_common_genes from .data_utils import df_normalization def DeconRNASeq_main(rna_df, sig_df, patient_IDs='ALL', args={}): """ This function does the following: - parses the dictionary 'args' for the arguments to pass on to the DeconRNAS...
44bf01b0d53110610d3219e3002cca0ab35720b5
3,654,176
import re from typing import OrderedDict def parse_c_interface(c_interface_file): """ @brief Parses a c-interface file and generates a dictionary of function names to parameter lists. Exported functions are expected to be preceded by 'DLL_EXPORT'. Python keywords should not be used as variable names f...
06a4edb40e12343cda688da82c9042d1342e6429
3,654,177
def con_minimize(fun, bounds, constr=(), x0=None, args=(), callback=None, options={}, workers=None): """Constrained minimization of `fun` using Genetic Algorithm. This function is a wrapper over modetga.minimize(). The constraints are defined as a tuple of functions (`fcon1(x, *args)`, `...
46a7400953e54dfb9b2364832e6029a508acc9de
3,654,178
def unique_v2(lst): """ Returns a list of all unique elements in the input list "lst." This algorithm runs in o(n), as it only passes through the list "lst" twice """ dd = defaultdict(int) # avoids blank dictionary problem (KeyError when accessing nonexistent entries) unique_list = [] for va...
d7c5706908d569b3ee93ba1bebbd09bc6f335ad2
3,654,179
import ipaddress def is_ip_network(network, strict=False): """Returns True/False if a string is a valid network.""" network = str(network) try: ipaddress.ip_network(network, strict) return True except ValueError: return False
84206586412b76816fa845a75fc6c121bfdf0989
3,654,180
def assign_point_of_contact(point_of_contact): """ Assign a user to be the point of contact in emails/letters :param point_of_contact: A string containing the user_guid if point of contact has been set for a request :return: A User object to be designated as the point of contact for a request """ ...
99f2e7d036c4f7cf71be2bd6b82a313f26b3af41
3,654,181
def response_with_pagination(guests, previous, nex, count): """ Make a http response for GuestList get requests. :param count: Pagination Total :param nex: Next page Url if it exists :param previous: Previous page Url if it exists :param guests: Guest :return: Http Json response """ ...
00373c866b6cc8384a88e62b63fcaa5950ccc1c1
3,654,182
def put_object(request, old_pid): """MNStorage.update(session, pid, object, newPid, sysmeta) → Identifier.""" if django.conf.settings.REQUIRE_WHITELIST_FOR_UPDATE: d1_gmn.app.auth.assert_create_update_delete_permission(request) d1_gmn.app.util.coerce_put_post(request) d1_gmn.app.views.assert_db....
192ed2a7efc35baf28605de9db594319370f294d
3,654,183
def _match_gelu_pattern(gf, entry_node): """ Return the nodes that form the subgraph of a GELU layer """ try: if not len(entry_node.outputs) == 3: return None pow_1, add_2, mul_3 = [gf[x] for x in entry_node.outputs] if not (pow_1.op == 'Pow' and add_2.op == 'Add' and mul...
6e08578a9cb9bea96c939a4fbee31003d6c575d4
3,654,184
def assign_obs_error(param, truth_mag, band, run): """ Assign errors to Object catalog quantities Returns ------- obs_err : float or np.array The error values in units defined in get_astrometric_error(), get_photometric_error err_type : str Type of observational error ...
9a90b80755941ac19cbf023f7ee63f4650518242
3,654,185
from typing import List from typing import Tuple import tokenize def dir_frequency(dirname: str, amount=50) -> List[Tuple[str, int]]: """Pipeline of word_frequency from a directory of raw input file.""" md_list = md.collect_md_text(dirname) return compute_frequency(tokenize(normalize(" ".join(md_list))), ...
3daddb1930e80235887b51ed5918e9d7cb1fff71
3,654,186
def test_solver1(N, version='scalar'): """ Very simple test case. Store the solution at every N time level. """ def I(x): return sin(2*x*pi/L) def f(x,t): return 0 solutions = [] # Need time_level_counter as global variable since # it is assigned in the action function (that makes ...
7c74b3f731c0aa613c7a9f8da82533c1239a574f
3,654,187
import requests def get_auth_data(): """ Create auth data. Returns: return: access token and token expiring time. """ payload = { 'client_id': CLIENT_ID, 'client_secret': CLIENT_SECRET, 'grant_type': 'client_credentials', } api_url = '{0}/oauth/access_toke...
ecd921c1ef3639c388111ec5952c887867076d99
3,654,188
def datatable(module, tag): """Mapping for DataTable.""" if tag == "DataTable": return module, tag
1eaa06771ecdd99dfa102ec249b23db3999b6fd7
3,654,189
def remove_prepending(seq): """ Method to remove prepending ASs from AS path. """ last_add = None new_seq = [] for x in seq: if last_add != x: last_add = x new_seq.append(x) is_loopy = False if len(set(seq)) != len(new_seq): is_loopy = True ...
78bb1554678af0998e15ecf9ed8f4e379ac2e2ad
3,654,190
def github_handle_error(e): """ Handles an error from the Github API an error example: Error in API call [401] - Unauthorized {"message": "Bad credentials", "documentation_url": "https://docs.github.com/rest"} The error might contain error_code, error_reason and error_message The error_reason an...
1b3d7ef6756c02d7bf1b8db506dbf926dd3e6abd
3,654,191
def netmask_to_bits(net_mask): """ Convert netmask to bits Args: net_mask ('str'): Net mask IP address ex.) net_mask = '255.255.255.255' Raise: None Returns: Net mask bits """ return IPAddress(net_mask).netmask_bits()
7ecc069e14242ebffd840b989331a431f6c2ecbc
3,654,192
def register_corrector(cls=None, *, name=None): """A decorator for registering corrector classes.""" def _register(cls): if name is None: local_name = cls.__name__ else: local_name = name if local_name in _CORRECTORS: raise ValueError(f'Already registered model with name: {local_name}...
90795496caff7958af52bbe1518582a2a2ceea73
3,654,193
import numpy def _sample_perc_from_list(lst, perc=100, algorithm="cum_rand", random_state=None): """ Sample randomly a certain percentage of items from the given list. The original order of the items is kept. :param lst: list, shape = (n,), input items :param perc: scalar, percentage to sample ...
4ec000e9bd8f5e10550040e49018e2a045659397
3,654,194
def irods_setacls(path, acl_list, verbose=False): """ This function will add the ACLs listed in 'acl_list' to the collection or data object at 'path'. 'acl_list' is a list where each element itself is a list consisting of the username in name#zone format, and the access level ('read', 'write', ...
5727d6ff96e2d693323d5d88ed81eafbd4de0435
3,654,195
from datetime import datetime def add_years(date_to_change, years): """ Return a date that's `years` years after the date (or datetime) object `date_to_change`. Return the same calendar date (month and day) in the destination year, if it exists, otherwise use the following day (thus changing Febru...
e9b71d190f7629a3edc0902d0582005a26a33956
3,654,196
def concurrency_update_done(client, function_name, qualifier): """wait fn for ProvisionedConcurrencyConfig 'Status'""" def _concurrency_update_done(): status = client.get_provisioned_concurrency_config( FunctionName=function_name, Qualifier=qualifier )["Status"] if status ==...
4d168e4e9648c3a3d8cb149aad1e835362bd271a
3,654,197
def googleapis_email(url, params): """Loads user data from googleapis service, only email so far as it's described in http://sites.google.com/site/oauthgoog/Home/emaildisplayscope Parameters must be passed in queryset and Authorization header as described on Google OAuth documentation at: http://gr...
c6123e367f093a512ac17797da487e733503dc11
3,654,198
def _compose_query_string(ctx, query_string, **args): """ Return the SQL for an ad-hoc named query on the given context. NOTE: This is a debug ONLY method, do NOT use this in production code. """ query = _construct_adhoc_query(ctx, query_string, **args) wrapped_ctx = _CtxWrapper.wrap(ctx) as...
b64d17d11b8b9947eac9c59510254d33018d519b
3,654,199