content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import os import zipfile import tarfile def extract_archive(fname, targetdir=None, verbose=False): """Extract .zip, .exe (considered to be a zip archive) or .tar.gz archive to a temporary directory (if targetdir is None). Return the temporary directory path""" if targetdir is None: targetdir =...
92b9b2ff54b08d5938dbb898d6962e364bf45315
43,200
def calculaterND(_ranking_k,_pro_k,items_n,proItems_n): """ Calculate the normalized difference of input ranking :param _ranking_k: A permutation of k numbers that represents a ranking of k individuals, e.g., [0, 3, 5, 2, 1, 4]. Each number is an identifier ...
f794c48943d7d01fa2a42b96443a1df5f42c2896
43,201
def point_to_rhino_point(pt): # type: (compas.geometry.Point) -> rg.Point3d """Convert :class:`compas.geometry.Point` to :class:`Rhino.Geometry.Point3d`.""" return rg.Point3d(*pt.data)
e5d03a61898b86e3aaa772bb6edcce880751b468
43,202
def get_default_gateway(): """ Returns the default gateway """ octet_list = [] gw_from_route = None f = open ('/proc/net/route', 'r') for line in f: words = line.split() dest = words[1] try: if (int (dest) == 0): gw_from_route = words[2] ...
8dc810468eece5cb35381b449fe69c7904c82cce
43,203
def parse_dict_items(s, label_col, val_col): """ Parse the dictionary embedded in a text columns. The resulting data frame will tuples. This assumes the values in the dict are integers. TODO: improve this. Use this when the # of dictionary items differs. """ s_split = s_split ...
d6a4eb12691227703c3a886bad749edc1bf9dad4
43,204
def nrmse(image, reference_image): """ Compute the normalized root mean square error between image and reference_image. Args: image: Calculated image reference_image: Ground truth image Returns: Root mean square of (image - reference_image) divided by RMS of reference_image "...
c6c23a972d4e2dd0101f2047372555ffaa6f217b
43,205
import pkg_resources def get_known_transports(): """Return a dictionary of all known transport mechanisms.""" if not hasattr(get_known_transports, "cache"): setattr( get_known_transports, "cache", { e.name: e.load() for e in pkg_resou...
a6176e79cb23c3bc29ce5f66bbb0ccb266ff93a6
43,206
def make_gif(): """ 制作一张GIF图片 """ def make_number_img(t): size = (80, 60) img = Image.new('RGB', size, (255, 255, 255)) # 创建Font对象: # font = ImageFont.truetype('Arial.ttf', 36) # 创建Draw对象: draw = ImageDraw.Draw(img) draw.text((35, 25), t, fill='red') ...
356ff349f4b6401890559086b4d6a56c9d201ba7
43,207
def get_full_name(qt_ptr): """ Get full name of qt widget from pointer Args: qt_ptr (ptr): Pointer to QWidget Returns: (unicode): full name of qt widget """ return omUI.MQtUtil.fullName(long(qt_ptr))
6858fd813458469bac65f625f2b95bfd4dd94afb
43,208
def class_combinations(c, n, m=np.inf): """ Generates an array of n-element combinations where each element is one of the c classes (an integer). If m is provided and m < n^c, then instead of all n^c combinations, m combinations are randomly sampled. Arguments: c {int} -- the number of classes ...
83a9e8d3ec2c3156b3cc6eed508ebc53ebc601d0
43,209
def dropout(X, rate, test_mode=False): """ Applies dropout to input matrix X using the given dropout rate [0,1). If test_mode is false, returns pair (Z, M) where Z = M * X and M is a matrix of bernoulli trials (M.dtype is bool). If test_mode is True, returns pair (Z, None) where Z = (1-rate)*...
d0da3b5ba4fd502123f15048316742894d90c4a4
43,210
def read_config(config_file): """Reads a config XML file to find extra projects to add or remove. Args: config_file: The filename of the config XML. Returns: A tuple of (set of remove_projects, set of add_projects) from the config. """ root = ET.parse(config_file).getroot() remove_projects = set( ...
c7430b42cdad9a17aff07579f838763171410472
43,211
def get_side_effect_targets_fishers(drug_to_geneids, drug_to_side_effects, cutoff=0.2, correct_pvalues=True): # min_n_drug=5, """ cutoff: p-value or fdr cutoff (0.2) correct_pvalues: apply multiple hypothesis testing (True) (obselete) min_n_drug: Consider only side effects that are associated with at l...
8ef290a0f035ed6b3290c38f05003fe97c4624e0
43,212
def set_active_design(oProject, designname): """ Set the active design. Parameters ---------- oProject : pywin32 COMObject The HFSS design upon which to operate. designname : str Name of the design to set as active. Returns ------- oDesign : pywin32 COMObjec...
825108bbfe21baa73e256d527fb982919a6b08ea
43,213
import sys def to_fs_encoding(value): """ Convert an unicode value to a str in the filesystem encoding. """ if not isinstance(value, unicode): raise TypeError("expected a unicode value") return value.encode(sys.getfilesystemencoding())
920d9cac856f32b76501e5a62492a4cec2a5f336
43,214
def init_encoders(): """ Initializes label and one hot encoders from sklearn. This is needed to avoid creating 2 encoder objects for each encoded sequence. :return: a tuple representing label_enoder, ohe_encoder """ integer_encoder = LabelEncoder() one_hot_encoder = OneHotEncoder(sparse=Fals...
09a920d33b05f7fc595ab7a2d8dffa89838e740d
43,215
def upload_bytes(interface: str, scale="bytes", precision=2): """Returns total bytes uploaded in the given interface :Params: :interface (str): Interface name :scale (str): Chosen scale (bytes, KiB, MiB, GiB, TiB, kB, MB, GB, TB or auto) :precision (int): Number of r...
becb8a6ff6739f58c974b61a89c531715281e231
43,216
import scipy def fidelity(state1: np.ndarray, state2: np.ndarray) -> float: """Fidelity of two quantum states. The fidelity of two density matrices ρ and σ is defined as trace(sqrt(sqrt(ρ) σ sqrt(ρ)))^2. The given states can be state vectors or density matrices. Args: state1: The f...
40297bab71790907c41d8478084cbe5a09d25f4d
43,217
import time def preprocess_img(img_path, height, width, channel): """ pre-process images located in img_path parameter by resizing them to desired shape then horizontally flip them to double the data size :param list of str img_path: locations of all images in the list :param int height: desired ...
ceafcf5ba93e8d431f2f31cb2b49657fca8fc072
43,218
def _iter_extension_names_and_paths(name): """ Fetches the names This function is a generator. Parameters ---------- name : `str` or `iterable` of `str` The name to fetch to single strings. Yields ------ name : `str` Extension names. path : `str` ...
017b1391a566d73d350dc9c677d442b17622edbe
43,219
def compute_headings(traces): """ Given a list of traces, compute the heading of each point and append. """ headings = [] for trace in traces: trace_headings = [] dir_vector = direction(trace[0], trace[1]) angle = atan2(dir_vector[1], dir_vector[0]) if angle < 0: angle += 2*pi tr...
eadcbddb355ec11a93ca6cf20c9b274aa899660d
43,220
def createobslogfits(headerDict): """Create the fits table for the observation log""" # define generic columns of output table col=[] for k, f in zip(headerList, formatList): print k,f, headerDict[k] col.append(fits.Column(name=k, format=f, array=headerDict[k])) for k, f in zip(scamheaderLi...
7b750c0e439dc2600fee6d67287b80b144835b33
43,221
def write_tags(tag, content='', attrs=None, cls_attr=None, uid=None, new_lines=False, indent=0, **kwargs): """ Write an HTML element enclosed in tags. Parameters ---------- tag : str Name of the tag. content : str or list(str) This goes into the body of the elemen...
ed0ade998b0232b8bca5cbb6083f8b60481b3ad9
43,222
def ExecuteBlueprint(): """ Execute a blueprint on the ZeroRobot It is handler for POST /blueprints """ return handlers.ExecuteBlueprintHandler()
cba8a6c736dbc2dbd8cc9377410216f1957cca11
43,223
def vgg8(**kwargs): """VGG 8-layer model (configuration "S") """ model = VGG(config['S'], **kwargs) return model
9628b5efa4fd56a39317af34adaf954d91b348ca
43,224
def pn_cli(module): """ This method is to generate the cli portion to launch the Netvisor cli. It parses the username, password, switch parameters from module. :param module: The Ansible module to fetch username, password and switch. :return: The cli string for further processing. """ userna...
da1affb920aac4128be57c35718ba43ed6c9917d
43,225
import Core.Statistics import Lib.PcapFile as PcapFile def get_botnet_pcap_db(): """ Reads a botnet resource pcap, calculates statistics for it and returns the DB path. :return: the database path for the botnet resource pcap statistics DB """ bot_pcap = PcapFile.PcapFile(BOTNET_PCAP) bot_sta...
50cafdea22a424ae4654da70bc04bd4b068798f9
43,226
def colorize(msg, color): """Given a string add necessary codes to format the string.""" if DONT_COLORIZE: return msg else: return '{0}{1}{2}'.format(COLORS[color], msg, COLORS['endc'])
528635adfb8db89f8ec365b447c3cce0acbc15a1
43,227
def setplot(plotdata): #-------------------------- """ Specify what is to be plotted at each frame. Input: plotdata, an instance of clawpack.visclaw.data.ClawPlotData. Output: a modified version of plotdata. """ from clawpack.visclaw import colormaps plotdata.clearfigures() # clear an...
9469f471e38d2005056e5f23208a4acb0fd16d09
43,228
def generateCircles(n): """ 生成圆圈数据 """ data, _ = make_circles(n_samples=n, factor=0.5, noise=0.06) return data
404f37af6765572ebdace9f7f90f3607f8574724
43,229
def calc_BMI(w,h): """calculates the BMI Arguments: w {[float]} -- [weight] h {[float]} -- [height] Returns: [float] -- [calculated BMI = w / (h*h)] """ return (w / (h*h))
ee4d7b99a0bb1129d316c7031a65c465092358a3
43,230
from typing import Union from typing import Coroutine from typing import Any import inspect async def wait_for(fut: Union[Future, Task, Coroutine], timeout: Union[int, float], loop: base_loop.BaseLoop=None) -> Coroutine[Any, None, None]: """ wait for a Future to be completed in `timeout` seconds if the Futur...
a714ce914b638adae3f2b7a91293fd1e4fb280c2
43,231
def get_message_box_text(): """Generates text for message boxes in HTML.""" html_begin = '<span style="font-size: 15px">' html_end = '</span>' shortcuts_table = "<table>" \ "<tr>" \ "<th>Shortcuts&nbsp;&nbsp;</th>" \ ...
29eb35e2b968fa125b77fde08669b75b5372de71
43,232
import os import pickle def load(filename: str) -> object: """ Load from pickle file :param filename: :return: """ if not os.path.exists(filename): raise Exception(f"Unable to fine file {filename}") with open(filename, 'rb') as fin: obj = pickle.load(fin) return obj
3cda74b48c4e7d70d9b6462284e0bcafb8469f8e
43,233
import os def find_serial_port(ports_list=None): """ Return the port path once the device is identified, otherwise raise an exception. """ device_info_request = bytearray([0x01, 0x2b, 0x0e, 0x01, 0x00, 0x70, 0x77]) # Raw device information request if not ports_list: # This pythonic line of code...
508e076d54ff1893df9379e4cb616b334ca876cb
43,234
import requests def _formal_post_request(hub, endpoint, **data): """ Required Parameters: hub.callback Subscribers Endpoint hub.mode subscribe / unsubscribe hub.topic Content of Subcription Optional Parameters: hub.lease_seconds Duration of th...
9630e277073786a439b9041631c8bda010c924ec
43,235
import numpy def CalculateBurdenVDW(mol): """ ################################################################# Calculate Burden descriptors based on atomic vloumes res-->dict type with 16 descriptors ################################################################# """ temp = _GetBurdenM...
0111bf2d5b6373738ffef3cb9ec6978169e535f0
43,236
import json import traceback def getUploadedMd5(req, courseId, assignmentId): """ Returns the md5 file for the current user""" websutil.sanityCheckAssignmentId(assignmentId) websutil.sanityCheckCourseId(courseId) # Check permission req.content_type = 'text/html' s = Session.Session(req) ...
993e1657d2a0e93ac0eee5911cc268af8dd2223f
43,237
import random def PolicyIteration(gamma=0.95, th=0.01): """ policy iterationで状態の価値評価する. ->return:状態価値テーブルV """ actions = list(range(4)) states = all_solvable_boards() policy = {} for state in states: policy[tuple(state)] = [random() for _ in actions] def estimate_by_policy...
2bd40c770a486f03c3b96efd5cd3deb1119fe46d
43,238
def scale_destructive(im, fac): """Degrades image by reducing scale then rescaling to original size """ amt = np.interp(fac, [0.0, 1.0], (1.0, 0.25)) w,h = im.shape[:2][::-1] nw,nh = (int(amt * w), int(amt * h)) im_dst = resize(im, width=nw, height=nh, interp=cv.INTER_CUBIC) im_dst = resize(im_dst, width=...
c2494882318de6db0247d536143734fe0a31dad3
43,239
def get_file_content(filename): """ Function reads the given file @parameters filename: Path to the file @return This function returns content of the file inputed""" with open(filename, encoding='utf-8', errors='ignore') as file_data: # pragma: no mutate return file_data...
1396b6eae7addd329466e1e3ad597cf965360b60
43,240
import functools import json def _files(*p_args, **p_kwargs): """ :param p_args: :param p_kwargs: :return: """ def paramed_decorator(func): @functools.wraps(func) def decorated(*args, **kwargs): request = args[0] for file_name in p_args: ...
f9349d7076a2cfb12210f68a727dfc1c71f14acf
43,241
from functools import reduce def _process_parallel(tasks, data, reduce_method=combine_result_with_and): """Process a list of tasks in parallel This method processes a list of tasks and then combines the results using the reduce_method Args: tasks (list): List of bound tasks data (Res...
90007930c4705722e5b8d8fd52dbd0b1ad2a9c89
43,242
import os def read_corpus(corpus_dir): """ Read de corpus html files from the received directory. :param corpus_dir: corpus directory :return: {doc_name:[doc_terms]} """ LOGGER.info('Reading corpus') corpus = {} for _, _, files in os.walk(corpus_dir): for file in files: ...
595a4b3587311dc3ea364ad82351b2c8a748f716
43,243
import math def math_sinh(x): """Implement the SQLite3 math built-in 'sinh' via Python. """ try: return math.sinh(x) except: pass
636933e1c12ce15960354bd7c14a4b9d2cf44a6a
43,244
import random import string def rand_string(n): """ Return a random string. """ return ''.join( random.SystemRandom().choice( string.ascii_lowercase + string.digits) for _ in range(n))
38fb6ecf42f7407db85856be67a21f792e5455ab
43,245
def authenticate(email: str, pw: str) -> Return: """Checks the user's email and password to authenticate them. Args: email: The user's email address. pw: The user's password Returns: An object describing the status of the user's attempt. """ user = db.session.query(User).fi...
7811f2e1a7b721a490970ddcf4be4389fd4bfe80
43,246
def is_thursday(date_str): """ >>> is_thursday('2019-07-03') False >>> is_thursday('2019-07-04') True >>> is_thursday('1999-11-04') True """ d = date.fromisoformat(date_str) return d.weekday() == 3
783bce7059ecdc95bb9c6f1a9ad3e2140d7a3867
43,247
def mb_to_human(num): """Translates float number of bytes into human readable strings.""" suffixes = ['M', 'G', 'T', 'P'] if num == 0: return '0 B' i = 0 while num >= 1024 and i < len(suffixes) - 1: num /= 1024 i += 1 return "{:.2f} {}".format(num, suffixes[i])
95f6ae29c8031347e32f51f349afc986abe31473
43,248
def inrad(v1, v2, r): """Are two points winthin r?""" if (abs(v1[0]-v2[0])) > r: return False elif (abs(v1[1]-v2[1])) > r: return False elif (abs(v1[2]-v2[2])) > r: return False elif dvv(v1,v2) > r: return False else: return True
90e2f4d1efbce27064e1d9b74a3e1a32da7d8efa
43,249
def check_n_cycles(n_cycles, len_cycles=None): """Check an input as a number of cycles definition, and make it iterable. Parameters ---------- n_cycles : float or list Definition of number of cycles. If a single value, the same number of cycles is used for each frequency value. ...
05fdd8895eabf665ddf7fd69dc2d6011e720d193
43,250
from datetime import datetime def get_test_triplegs_with_modes(): """get modal split for randomly generated data""" n = 200 day_1_h1 = pd.Timestamp('1970-01-01 00:00:00', tz='utc') one_day = datetime.timedelta(days=1) mode_list = ['car', 'walk', 'train', 'bus', 'bike', 'walk', 'bike'] df = pd....
763b1267e9a0d2cb410c8c0893ecf9bbc92a62ea
43,251
import random import torch def sample_batch(scramble_buffer, net, device, batch_size, value_targets): """ Sample batch of given size from scramble buffer produced by make_scramble_buffer :param scramble_buffer: scramble buffer :param net: network to use to calculate targets :param device: device t...
807d774787814ea555a1d7475a878fce131f80e2
43,252
def solve_nonlinear(info_dict, eps_fn, b, iterative=False, method=DEFAULT_SOLVER, verbose=False, atol=1e-10, max_iters=10): """ Solve Ax=b for x where A is a function of x using direct substitution """ def relative_residual(eps, x, b): """ computes relative residual: ||Ax - b|| / ||b|| """ A = ...
79587d444c2a7d7df925201a9139ac0b0685339e
43,253
def success(message, data=None, code=200): """Return custom success message Args: message(string): message to return to the user data(dict): response data code(number): status code of the response Returns: tuple: custom success REST response """ response = {'status':...
721542f71ad3a641efbe0a0d62723a2df23960a5
43,254
import math import array def confidenceInterval(x, p): """ returns the smallest interval (start, end) and its size that covers at least a fraction of 'p' of the data-points given by x. """ x = sort(array(x)) ## set n to the next integer that is greater or equal ## to #data-points * ...
bc38dc0ab372a27dbe8df4be0bed006eae1c900c
43,255
def tokenize(s): """ Ковертирует строку в питон список токенов """ return s.replace('(', ' ( ').replace(')', ' ) ').replace('>', ' > ').replace('-', ' - ').split()
66ac357b371750354f6e6ca6b35122fd81549ae6
43,256
from clawpack import petclaw as pyclaw from clawpack import pyclaw from clawpack.riemann import rp2_acoustics def acoustics2D(iplot=False,kernel_language='Fortran',htmlplot=False,use_petsc=False,outdir='./_output',solver_type='classic'): """ Example python script for solving the 2d acoustics equations. ""...
ca4b4e364bff09bc8bf3e89f6ba703abb9f523dd
43,257
def run_tests_with_coverage(test_labels, verbosity=1, interactive=True, extra_tests=[], xml_out=False): """ Run the unit tests for all the test labels in the provided list. Labels must be of the form: - app.TestClass.test_method Run a single specific test method - app.TestClass Run...
67b5bba7e4ca0c2903ebe9b1a2d575bb651465a1
43,258
from imcsdk.mometa.comm.CommSnmp import CommSnmpConsts def snmp_enable(handle, community=None, privilege="disabled", trap_community=None, sys_contact=None, sys_location=None, port="161", **kwargs): """ Enables SNMP. Args: handle (ImcHandle) community (strin...
881f35a90149bb36e370a0ad6c2049430d79c02e
43,259
import torch def reset_model(n_clicks): """ Creates the model at loading, then upon click, resets the model, and probably solve all human problems inputs: reset_model n_clicks (int): clicks on the button outputs: reset_model_status children (string): the status update """ glob...
52110a595f37b9ed267f6ecd6415ca7baac83748
43,260
import urllib def GetKey(): """Fetches rcpkey from metadata of the instance. Returns: RPC key in string. """ try: response = urllib.urlopen( 'http://metadata/computeMetadata/v1beta1/instance/attributes/rpckey') return response.read() except IOError: return ''
9d35537b193332d775784c52c2c1bfb9960409c5
43,261
def past_days(next_day_to_be_planned): """ Return the past day indices. """ return range(1, next_day_to_be_planned)
d4b0e7387303f48bc3668f5d71b374dace6e7f44
43,262
import time import logging def get_client(): """Return instance of _Mongo with set up connection. If connection exists and is new, reuse it. If it is old, check if it is working and reuse it, or create new one. """ global _GLOBAL_MONGO_CHECKUP global _GLOBAL_MONGO last_success = _GLOBAL_M...
a4989261f0ed8d8065d28e42e75f18f9fbea2d77
43,263
def range_window(preceding=None, following=None, group_by=None, order_by=None): """Create a range-based window clause for use with window functions. This RANGE window clause aggregates rows based upon differences in the value of the order-by expression. All window frames / ranges are inclusive. P...
f7894c8ad32b98d70cc4c88c014fc171ff5fd7bb
43,264
def wrapto360(angle): """ Wrap a value on -180, 180 to 360. :param degrees: float :return: float """ if angle >= 0: return angle else: return 360 + angle
b5e6ad718bd2ac142d563da6e97021c6b5990bf4
43,265
import argparse def parse_args(args): """Parse command line arguments.""" parser = argparse.ArgumentParser(description='Run opsdroid.') parser.add_argument('--gen-config', action="store_true", help='prints out an example configuration file') return parser.parse_args(args)
e4bf8f3117c5064f6dc76f257eb63233e69da3cb
43,266
from typing import Dict def get_collection_member( query_info: Dict[str, str], session: scoped_session ) -> Dict[str, str]: """ Get member from a collection :param query_info: Dict containing the ids and @type of object that has to retrieved :param session: sqlalchemy session :return: dict of ...
bd6fcecac10131f7c9ee245a0b11b3f36325b578
43,267
def deci2sexa(deci, pre=3, trunc=False, lower=None, upper=None, b=False, upper_trim=False): """Returns the sexagesimal representation of a decimal number. Parameters ---------- deci : float Decimal number to be converted into sexagesimal. If `lower` and `upper` are given t...
38a802485985c0e86f9c541bc422a637b88e5fc9
43,268
def get_bprop_get_tensor_slice_operator(self): """Backpropagator for _GetTensorSlice""" def bprop(x, dev_mat, tensor_map, out, dout): return (zeros_like(x),) return bprop
5170d7b32344d12036a4d969503b2b664c87c967
43,269
def compute_o_value_legacy(owner_pwd, user_pwd, rev, keylen): """ Implementation of algorithm 3.3 of the PDF standard security handler, section 3.5.2 of the PDF 1.6 reference. """ # steps 1 - 4 key = compute_o_value_legacy_prep(owner_pwd, rev, keylen) # 5. Pad or truncate the user password ...
d60fce42c86b569eb9599f488522fd5ac5386206
43,270
def webex_buffer_input_cb(data, buffer, input_data): """ Callback called for input data on a buffer. """ chat = get_chat_from_buffer(buffer) if chat: chat.send_message(input_data) return weechat.WEECHAT_RC_OK
1cc1d037d8f8400bee985b77adecb5bc7556dc84
43,271
def base_corner(baseparams, base, newbase, tri, sobol=1.0, outbasename=""): """ Plots the new vs. old base of across interpolation, as long as dim(base) > 1, and produces a corner plot for dim(base) > 2. Parameters ---------- baseparams : dict Parameters forming the base of the grid, an...
a1c51dda4fe84864fd30dcc3b6e16835aad8bb7d
43,272
def import_obj(obj_path, hard=False): """ import_obj imports an object by uri, example:: >>> import_obj("module:main") <function main at x> :param obj_path: a string represents the object uri. ;param hard: a boolean value indicates whether to raise an exception on impor...
cceed0d6162d4ab281472c1f2c9bb58a0b9195d1
43,273
import inspect def refine_field(field_class,values,*,name=None): """Factory function that returns a field sub-class with restricted values. A helper factory function to define a sub-class of a BaseField (or sub-class) that restricts the allowable values. For example, if you have a constant in a predi...
e9bbc8c7aabb2c9e7266909345262f06d5d82c10
43,274
import warnings def mlregress(x, y, intercept=True): """ Parameters ---------- x y intercept Returns ------- """ """Return the coefficients from a multiple linear regression, along with R, the coefficient of determination. x: The independent variables (pxn or nxp). ...
164b4d76a70234ebe6fce76f9b0c4a3bda698aae
43,275
import sys def get_dropq_compute_from_module(module_import_path, attr='dropq_compute', MockComputeObj=MockCompute, **mc_args): """ mocks dropq compute object from specified module returns: mocked dropq compute object """ module_views = sys.modules[module_import_p...
99b5713dd5fd9126027f1b2b1b8842612789d64f
43,276
def format_numbers( data, headers, column_types=(), integer_format=None, float_format=None, **_ ): """Format numbers according to a format specification. This uses Python's format specification to format numbers of the following types: :class:`int`, :class:`py2:long` (Python 2), :class:`float`, and ...
4572e1c633dbc86644b3447a6153957094ec6620
43,277
def quoted_native_concat(nodes): """This is almost native_concat from the NativeTemplate, except in the special case of a single argument that is a quoted string and returns a string, the quotes are re-inserted. """ head = list(islice(nodes, 2)) if not head: return '' if len(head) ...
2a122f2c9b4857e9bded4958cd4914e6c436e776
43,278
def load(tree_file: t.IO[str]) -> Program: """Load the input data, parse it and construct the tree.""" lines = tree_file.readlines() programs_by_name: t.Dict[str: Program] = {} # Start by just finding out whom everyone is programs = {p.name: p for p in map(Program.from_line, lines)} def is_ho...
016f689e46567cd90a8f69934f8787326eb0ec23
43,279
import logging import os def trace( record, sl, kwargs_data={}, fit_modekwargs_legend={}, kwargs_subplots={}, title=None, kwargs_plot={}, errorbar_kwargs=None, xlim=None, ylim=None, xlabel='Time in fs', ylabel='Relative Bl...
fb77381c43de3e0442f4ab56271d786c7b16e240
43,280
from datetime import datetime def generate_date_now(): """Get current timestamp date.""" return "{0}".format(datetime.utcnow().strftime('%s'))
84489bee5b01537c273c4dc64e96586434c405e4
43,281
import signal def calculate_dvdt(v, t, filter=None): """Low-pass filters (if requested) and differentiates voltage by time. Parameters ---------- v : numpy array of voltage time series in mV t : numpy array of times in seconds filter : cutoff frequency for 4-pole low-pass Bessel filter in kHz...
74f2810f4baaf670a1c6c3afb760e3a0dbef2cd7
43,282
def f_to_ppm(f, larmor): """ Converts frequency (Hz) to ppm Parameters: f (float): frequency or array in Hz larmor (float): Larmor frequency (in Hz) Returns: ppm (float) """ ppm = f/larmor*1.0e6 + PPM_OFFSET return(ppm)
764db8ea7296d23b7271fed230bf66fbd8781509
43,283
import torch def allreduce_hook( process_group: dist.ProcessGroup, bucket: dist.GradBucket ) -> torch.futures.Future: """ This DDP communication hook just calls ``allreduce`` using ``GradBucket`` tensors. Once gradient tensors are aggregated across all workers, its ``then`` callback takes the mean...
b3f58e30cd38f2f0bd36b2029a64b68007de5c01
43,284
def submit_apbs_json(): """ Handles APBS job submissions. Runs the APBS main function originally from 'apbs_cgi.py'. """ json_response = None http_status_response = None if request.method == 'POST': form = loads(request.data)['form'] for key in form.keys(): if k...
39f8c2fbc235d0893bfb3e87b4d1e9231be273ec
43,285
import tqdm import operator import gc def check_coverage(vocab, embeddings_index): """ :param vocab: the output Counter from the count method :param embeddings_index: embedding loaded from files :return: those words:their count that not find in word-embedding """ a = [] oov = {} find_...
17267c6aac33a863eff84100a08716aa1ba6837e
43,286
def my_rbf(x, y=None, gamma=1.0/(2.1)**2, withnorm=False): """ """ if y is None: y = x if withnorm: xn = x/np.linalg.norm(x) yn = y/np.linalg.norm(y) else: xn = x yn = y dist = np.linalg.norm(xn - yn) return np.exp(-gamma*(dist**2))
a346e8a71cc4efef1c70245b32e5d096ff9af84a
43,287
def pareto_dominates(u, v, tolerance=None): """ Returns true if u >= v elementwise, and at least one of the elements is not an equality. """ u = np.asarray(u, dtype=np.float32) v = np.asarray(v, dtype=np.float32) if tolerance is None: return np.all(u >= v) and not np.all(u == v) else: return n...
9ccdd8f82ef99193f789a030151d85c1cd6f7c50
43,288
def hashing(file,pp): """ Map an input file and a postprocessing config to an unique hash. The hash is used to store the item in the database. It needs to be persistent across different python implementations and platforms, so we implement the hashing manually. """ def myhash(instring): ...
d27bdadf4f5bced1e9f207767deaae769c194f64
43,289
def from_arrow_to_python_class(type: pa.DataType) -> DTypeLike: """Convert an Arrow type to an (almost) equivalent Python class. For now, Arrowbic is using Numpy dtype for timestamp and duration conversion, to keep the proper time unit information. """ return _base_from_arrow_to_python_mapping[type...
16f83cdab3c9048c0312d30b97c000c6c70d54e0
43,290
from typing import Sequence def convert_sequence_to_actions(sequence: Sequence, agent_start_dir: Direction) -> Sequence: """ Converts a sequence containing East, West, North, South to a sequence of actions from an agents perspective :param sequence: a sequence of steps ...
d32b0b896d4013cd28a2791191095ef303bfee88
43,291
import random def create_contig_and_fragments(contig, overlap_size, fragment_size): """ Creates a contig and overlapping fragments :param str contig: original sequence to create test data from :param int overlap_size: number of bases fragments should overlap :param int fragment_size: length of ba...
cb6394004f1500aefb55354cadd9788ab29749f7
43,292
def get_all_accounts(): """ Get all member accounts of the organization. """ accounts=[] token_tracker = {} while True: members = session.client('organizations').list_accounts( **token_tracker ) accounts.extend(members['Accounts']) if 'NextTo...
a7bdfe0a4991f9663060bf23a9f9b5ef0b74f196
43,293
def resolve_ctx(cli, prog_name, args): """ Parse into a hierarchy of contexts. Contexts are connected through the parent variable. :param cli: command definition :param prog_name: the program that is running :param args: full list of args :return: the final context/command parsed """ ctx...
fa1501d2baab9abf4ca4e8f62d9d10eee3b3fa49
43,294
def main(): """Simple Login App""" menu = ["Home","Login","SignUp"] choice = st.sidebar.selectbox("Menu",menu) if choice == "Home": Jobs = pd.read_csv('Resume_data_fordebug.csv') #jds = pd.read_csv('jobdesc.csv') st.markdown("<h1 style='text-align:center;'>Welcome to ScreenRes</h1>", unsafe_allow_html...
bf69b2723684865688a544872da41d328b6b1372
43,295
from typing import List from pathlib import Path def _apache_ssl_context( *, apache_cacerts_list: List[Path], scale_factor: int ) -> List[SSLContext]: """ Provides an SSLContext referencing the temporary CA certificate trust store that contains the certificate of the secure apache service. """ ...
e3852e64f2b75e402a5a08214829e3c6622821a7
43,296
def display_map(energy_type, year, scope): """ Docs """ # scope = "Africa" df = df_notna.query("Year==@year & energy_type==@energy_type") fig = px.choropleth( df, locations="Code", color="percentage", hover_name="Entity", hover_data={ "Year": ...
0aaa7bf715d9b9bbd510c7448941a6f36ad55478
43,297
from typing import Mapping from typing import Callable from pathlib import Path def build_indicator_module_from_yaml( filename: PathLike, name: str | None = None, indices: Mapping[str, Callable] | ModuleType | PathLike | None = None, translations: dict[str, dict | PathLike] | None = None, mode: st...
f40f57965c41a1c208da8d262fad4f9221d834b9
43,298
def getnameinfo(sockaddr, flags): """ getnameinfo(sockaddr, flags) -> (host, port) Get host and port for a sockaddr. .. seealso:: :doc:`/dns` """ return get_hub().resolver.getnameinfo(sockaddr, flags)
2d9d7fb72244b9188b895d8430b6075f1d5d6630
43,299