content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def count_consonants(string): """ Function which returns the count of all consonants in the string \"string\" """ consonants = "bcdfghjklmnpqrstvwxz" counter = 0 if string: for ch in string.lower(): if ch in consonants: counter += 1 return counter
4a852b3ec9f8f660d71dde547cbffb0c25b1e209
54,257
import socket def in6_isaddrTeredo(x): """ Return True if provided address is a Teredo, meaning it is under the /32 conf.teredoPrefix prefix value (by default, 2001::). Otherwise, False is returned. Address must be passed in printable format. """ our = inet_pton(socket.AF_INET6, x)[0:4] ...
e7931d4250c119018d69fd4e257f5491fd3a46b8
54,258
def get_resized_raster_8chan_image(image_id, band_rgb_th, band_mul_th): """ RGB + multispectral (total: 8 channels) """ im = [] fn = train_image_id_to_path(image_id) with rasterio.open(fn, 'r') as f: values = f.read().astype(np.float32) for chan_i in range(3): min_va...
51c259c3628f1c356f9d4f515cb454f5c91a1504
54,259
def calculateDailyResult_init(): """主函数,供其他python程序进行模块化程序初始化调用""" reload(ADRB) # 创建回测引擎 engine = BacktestingEngine() # 设置引擎的回测模式为K线 engine.setBacktestingMode(engine.BAR_MODE) # 设置产品相关参数 engine.setSlippage(0) # 股指1跳 engine.setRate(0) # 万0.3 engine.setSize(...
392741b76c482bfa6794025dabf1e16e2ae68018
54,260
import itertools def bonds_getting_formed_or_broken(rsmi, psmi, n_atoms): """ Based on the reaction and product structure, the bonds that are fomed/broken are singled out for contraintment the difference in the afjacency matric tells whether bond has been formed (+1) or bond is broken (-1) """...
9bab5c5a155c0b926b42f840d9834a9c4e63f9f7
54,261
import tqdm from io import StringIO def write_msp(all_preds_in, peprec_in, output_filename='MS2PIP_Predictions', write_mode='wt+', unlog=True, return_stringbuffer=False): """ Write MS2PIP predictions to MSP spectral library file. """ def write(msp_output): if use_tqdm & len(spec_ids) > 100000: spec_ids...
14b722413135f07ba1bbbb75d2be09035b1036e4
54,262
from typing import Optional from typing import List from typing import Dict from typing import Any async def votes_by_comment( req: Request, res: Response, comment_ID: int, limit: Optional[int] = 20, offset: Optional[int] = 0, sort: Optional[str] = "id:asc", ) -> Optional[List[Dict[str, Any]]]...
db6560d99c1c656552b203f09e34ce8f38677062
54,263
def retrieve_context_path_routing_constraint_requested_capacity_bandwidth_profile_committed_burst_size_committed_burst_size(uuid): # noqa: E501 """Retrieve committed-burst-size Retrieve operation of resource: committed-burst-size # noqa: E501 :param uuid: ID of uuid :type uuid: str :rtype: Capac...
708519c1c6a7ace71c07b7371495aa0d1eca438f
54,264
def _create_file(my_data, sheet_name): """Create .xlsx file in memory.""" df = pd.DataFrame(my_data[1:], columns=my_data[0], index=None) file = BytesIO() with pd.ExcelWriter(file, date_format='YYYY-MM-DD', mode='w', engine='xlsxwriter') as writer: df.to_excel(writer, sheet_name=sheet_name, na_rep='', index=False)...
170b14c0fc1a9ea09517c85c1c455477af701873
54,265
def get_symbol(parent_node): """Fetches the node tag value for 'printSymbol'""" def traverse(node): while node != Node.TEXT_NODE: if len(node.childNodes) != 0: traverse(node.childNodes[0]) else: return get_name(parent_node) return node.data...
2fcce6214be1807117b76ee25410dce84f837b8f
54,266
def compute_point_area(surf, cell_area=None, area_as='one_third'): """Compute point area from its adjacent cells. Parameters ---------- surf : vtkPolyData or BSPolyData Input surface. cell_area : str, 1D ndarray or None, optional Array with cell areas. If str, it must be in the cell...
abbac6604754c9828daa89b7231cb88de8c695f7
54,267
from urllib import quote_plus def getLogoutlink(): """Return the HTML required to clear and expire the current OAuth2 token.""" u = '' host = request.headers['Host'] if session and 'u' in session: u = session['u'] elif request.args and 'u' in request.args: u = request.args.get('u') if u: u = q...
8ed62dbd877b021e71a8e2640c1f91f9af853443
54,268
def run_pyscf(molecule, run_scf=True, run_mp2=False, run_cisd=False, run_ccsd=False, run_fci=False, verbose=False): """ This function runs a pyscf calculation. Args: molecule: An instance of the MolecularData or Pys...
d45c366d8a5baa1e020dd6c87d54b927369993b9
54,269
def soft_contingency_table(resp1, resp2): """Compute the soft contingency table for two responsibility matrices Args: resp1 (numpy array): N x K_1 responsibility matrix - each row is a probability vector for one of the N items belonging to each of K_1 modes resp1 (numpy array): ...
50ee20e05755d320fe9f130a6ca57728d1e1b5ad
54,270
from typing import Optional def is_opt(typ) -> bool: """ Test if the type is `typing.Optional`. >>> is_opt(Optional[int]) True >>> is_opt(Optional) True >>> is_opt(None.__class__) False """ args = type_args(typ) if args: return typing_inspect.is_optional_type(typ) ...
a467d685596fe4ab1a0431b36d5a5e70f3901659
54,271
def on_blue(string, *funcs, **additional): """Text background color - blue. (see _combine()).""" return bg_blue(string, *funcs, **additional)
442ee4a9d175815fe09b2a76d8b828cedfa03790
54,273
def allowed_request_lot_filters(lot_filters): """Create a set of (name, value) pairs for all form filters.""" filters = set() def recursive_search(filters): more_filters = set() for f in filters: more_filters.add((f['name'], f['value'])) children = f.get('children')...
1b265e0233e08d0cab4248f28424b5b26ad28340
54,274
def render_error_response( description: str, status_code: int = status.HTTP_400_BAD_REQUEST, content_type: str = "application/json", ) -> Response: """ Renders an error response in Django. Currently supports HTML or JSON responses. """ resp_data = { "data": {"error": description...
a79f8f7b02c677caaf3ed2f55ca6336ef57923e1
54,275
def decode_token(token): """ Decode token but don;t check the signature :param token: :return decoded token: """ return jwt.decode(token, verify=False, algorithms=[__algorithm__])
9a1c4152d47976c26b94ecd859faa5ec2c8be7d0
54,276
import random import time import threading def test_ps_s3_notification_push_http_on_master(): """ test pushing http s3 notification on master """ if skip_push_tests: return SkipTest("PubSub push tests don't run in teuthology") hostname = get_ip() zones, _ = init_env(require_ps=False) real...
87c0862e795ac025075aaa448b75934e8cc1e608
54,277
def FindPosition(point, points): """Determines the position of point in the vector points""" if point < points[0]: return -1 for i in range(len(points) - 1): if point < points[i + 1]: return i return len(points)
11ccabcade65053ccfa6751813d90a0eeaccc339
54,278
def PARTE_ELSE(): """ PARTE_ELSE : else COMANDO | e """ global current_token, tabela, pilha_tipos if current_token['token'] == 'else': getSimbol() if not COMANDO(): return False else: return True # vazio return True
5e9722241fca29744222ed81b8bc8da1e741262a
54,279
def _check_if_StrNotBlank(string): """ check if a sting is blank/empty Parameters ---------- Returns ------- : boolean True if string is not blank/empty False if string is blank/empty """ return bool(string and string.str...
e5de1d902f8e3931d23e04c6ba825b17d90e8d1d
54,280
def createRectangle(image=None,topLeftPoint=None,bottomRightPoint=None,color=(255,255,255),lineThickness=3,fill=False,fillColor=None): """ Creates a rectangle on an image Arguments: image = 3D Numpy array; image on which the rectangle has to be created topLeftPoint = (x,y); top left point of...
632990a633365bb0debe786ae6a1a195ba90154f
54,281
def confirmedPattern(passW,pat): """ Checks if the password has the right pattern """ if(len(passW)<pat.min_length or len(passW)>pat.max_length): return False if(isStatusChecked(pat.numbers,hasNumber(passW))==False): return False if(isStatusChecked(pat.capital,hasCapitalLetters(p...
bcd1c6c2cf2f34cbed197dd3c25dfd1d6c4d5db9
54,282
from math import asin, atan2, sqrt, degrees def normal2SD(x,y,z): """Converts a normal vector to a plane (given as x,y,z) to a strike and dip of the plane using the Right-Hand-Rule. Input: x: The x-component of the normal vector y: The y-component of the normal vector z: The z-com...
6b8bcfb9444352f8722aa1742909544202fa32d9
54,283
import re def parse_date_string(s): """Attempt to parse the expression as a simple date string.""" # https://en.wikipedia.org/wiki/ISO_8601 y = r'(\d\d\d\d)' m = r'(\d\d)' d = m # wk = r'W' + d # wd = r'(\d)' # yd = r'(\d\d\d)' # def groups(*strings, sep='-'): # it = (f'({...
86f37b24f3df21863888924fdc0a6098dbc2f56c
54,284
def append_result(results, result_hash, item): """Append to results, creating an index if needed.""" if result_hash not in results: results[result_hash] = [item] else: results[result_hash].append(item) return results
1b2af69ad291f885a8f52ce95ba7e0d82792e835
54,287
def rotateToHome(x, y): """Rotate to the home coordinate frame. Home coordinate frame starts at (0,0) at the start of the runway and ends at (0, 2982 at the end of the runway). Thus, the x-value in the home coordinate frame corresponds to crosstrack error and the y-value corresponds...
4d4c5cd5a3e5186d81bff60266c99128ad8a9d51
54,288
def utc_time(ms): """return UTC format time""" return dt.datetime(1970, 1, 1) + dt.timedelta(milliseconds=ms*100)
5b7089098ec9b50d6c2f6275200af6f959708e30
54,289
from typing import Sequence from typing import Union from typing import Any from typing import Optional def cli_args(args: Sequence[str]) -> ToxIniFmtNamespace: """Load the tools options. :param args: CLI arguments :return: the parsed options """ parser = ArgumentParser() parser.add_argument(...
3d57de8f318b87593cea36118e78ad07751e335d
54,290
import ctypes def FindFirstVolumeMountPoint(volume_name): """Find the first volume mount point which the system recognises. If none is found, raise x_kernel32. Otherwise return the search handle and the volume mount point name. """ volume_mount_point_name = ctypes.create_unicode_buffer(" " * VOLUM...
0c8ed0f47c9a041ce871dd09980daaf21bcc5318
54,292
def uniq(seq): """ the 'set()' way ( use dict when there's no set ) """ return list(set(seq))
e8136a633fdf08d7c79e8d47b8c90dc2409e9d2f
54,293
def compute_angles(v1: ndarray, v2: ndarray, axis: int = -1) -> ndarray: """ Computes angle cosines between sets of vectors. Parameters ---------- v1 v2 Sets of vectors. axis Dimension to sum over. Returns ------- A numpy array with angle cosines. """ re...
e55928c10c47f098a0883ccf3d2c6577d1f0e3c7
54,294
def decorator(d): """Make function d a decorator: d wraps function fn.""" def _d(fn): return update_wrapper(d(fn), fn) update_wrapper(_d, d) return _d
4a2ae600ef6952b6829d275b415b3ef98514a37e
54,295
def plot_surface(trimesh): """ Plots a surface over a matplotlib Triangulation. Assumes that the height of the surface has been stored in an attribute 'z' on the trimesh object. """ fig,ax = plt.subplots() ax = fig.gca(projection='3d') polycollection = ax.plot_trisurf(trimesh, trimesh....
34c5f83674966eb13a94771215d3cb7f78565edf
54,296
import csv import random def get_prioritized_county_list(): """the scraper prioritizes its work such that counties with less recorded information are addressed before counties with more information. This is accomplished by dividing the counties into quartiles based on an estimate of the amount of info...
e9962949026c6b1b2a969dfb27a0fc62c5b66325
54,297
from typing import Tuple from typing import Union from typing import List from typing import Optional def gen_rand_ddf( batch_size: int, image_size: Tuple[int, ...], field_strength: Union[Tuple, List, int, float], low_res_size: Union[Tuple, List], seed: Optional[int] = None, ) -> tf.Tensor: ""...
17cc8e7af0777aa1a8ae6b8a6f4cd315e3f1d9f4
54,298
def sanitize_codes(codes): """ Sanitize codes by splitting and removing unnecessarsy characters Params: codes (list): target codes Returns: the sanitized codes """ codes = codes.split(';') codes = [sanitize_code(code) for code in codes] return codes
503b41ee015cc9c5c642e9151c1ce60ba84eb914
54,299
from typing import Any from typing import Dict def execute( schema: GraphQLSchema, document: DocumentNode, root_value: Any=None, context_value: Any=None, variable_values: Dict[str, Any]=None, operation_name: str=None, field_resolver: GraphQLFieldResolver=None ) -> MaybeAwaitabl...
5cc9d6f26001c312a43c7da410f5edf616185057
54,300
def _two_func_initializer(freqs, signal): """ This is a helper function for heuristic estimation of the initial parameters used in fitting dual peak functions _do_two_lorentzian_fit _do_two_gaussian_fit """ # Use the signal for a rough estimate of the parameters for initialization: r_signal = n...
023561a6a09c157cff284055cb6d5a24b6cc297c
54,301
def ReadContourStructures(DCM): """Reads a dicom (.dcm) file and returns a dictionary with contour information. The information including colour, name and contour data Contour data include all the (x,y,z) data points used to build the contour """ contours = [] ds = dicom.read_file(DCM) num...
423f57fb6ee41adfb04e551237b4d9f4bbef7574
54,303
def list_projects(request): """ Tags: projects --- Lists projects on cloud. Only supported for EquinixMetal. For other providers,returns an empty list READ permission required on cloud. --- cloud: in: path required: true type: string """ auth_context = auth_...
9834f3c6b50aa69b7e4722f00bc2556d02aa1179
54,304
def run_policy_loop(agent, env, max_num_episodes, fps): """Execute the policy and render onto the screen, using the standard agent interface.""" agent.initialize() episode_rewards = [] for _ in range(max_num_episodes): obs, done = env.reset(), False episode_reward = 0 while not...
a6dd2d0629cb2463ace7687163b0d0e0fcf36873
54,305
def calc_energy_forces_3D(pos, cell_dim, bond_indices, angle_indices, angle_bond_indices, param): """ calc_energy_forces(pos, cell_dim, bond_indices, angle_indices, angle_bond_indices, vdw_coeff, param) Return tot potential energy and forces on each bead in simulation Parameters ---------- dxy: array_like (fl...
1d312a318a3347fd3687e5d0abc1d1856011c8e3
54,306
def gen_range(start, end): """Return a list of the numbers between |start| and |end|. This filters out surrogate pairs. """ return [x for x in range(start, end) if x < 0xd800 or x >= 0xe000]
009b0af854b5ad6d8a06d01a24cf08b26a644dbc
54,307
def cmp_to_key(mycmp): """functools.cmp_to_key backport""" class KeyClass(object): """Key class""" def __init__(self, obj, *args): # pylint: disable=unused-argument self.obj = obj def __lt__(self, other): return mycmp(self.obj, other.obj) < 0 def __gt__(s...
685035bff0e2df45c5c5698787a012a38f623142
54,308
import socket def compress_ipv6(ipv6_addr): """ Compress ipv6 address, i.e: compress_ipv6(0001:0001:0000:0000:0000:1111:0000:0000') -> '1:1::1111:0:0' """ ipv6_addr = is_valid_ipv6_ret(ipv6_addr) return socket.inet_ntop(socket.AF_INET6, ipv6_addr)
258fd4911092d33b591f66dfa04ddda8ba5f5d9c
54,309
def _whois(COMMAND, nick, mask='', prefix='', msg=None): """Returns a WHOIS for nick.""" if conf.supybot.protocols.irc.strictRfc(): assert areNicks(nick), repr(nick) if msg and not prefix: prefix = msg.prefix args = (nick,) if mask: args = (nick, mask) return IrcMsg(prefi...
de1fb928dde32de79cf1d709e379001a2906b9f1
54,310
def fit_learning_curve(train_set_size, error_test, error_train=None, pinit=(1.0, -1.0), funcs=1): """ returns parameters to predict learning curve as a power function with the form y = a + b * x**alpha where x is the training set size, i.e., the independent variable You provi...
d4f3f609aee475d390f62262f16db7848b69e4c7
54,311
def textsize(txt, font=None): """ Calculates the bounding box of the text, as drawn in the specified font. This method is most useful for when the :py:class:`~luma.core.legacy.font.proportional` wrapper is used. :param txt: the text string to calculate the bounds for :type txt: str :param fo...
ef64f0712bc720984290e503cc7dc1c6d62b1ca2
54,313
def chirp_amp_phase(v,i, t, start=0.0, end=19.9, down_rate=20000.0, min_freq=0.2, max_freq=20.): """ Calculate amplitude and phase of chirp responses Parameters ---------- sweep_set: SweepSet Set of chirp sweeps start: float (optional, default 0.6) Start of chirp stimulus in...
cf395e390cf8b6f32e0458fea12a456b7ec2d820
54,314
def off_target_coverage(bam, bed, dir): """ Calculate (using mosdepth and the off_target_bed) the mean coverage in the off target regions, with coverage weighted by length of the intervals. Return as dictionary to be inserted in the coverage DataFrame """ df = mosdepth(bam, bed, dir, prefix="off...
eeef9d21a0366d725202b531584c10ac8e683bdc
54,316
import json def get_json_data(): """Fixture to return the json data as a Python variable.""" def _method(_file): """Fixture to return the json data as a Python variable, given a file location Args: _file (str): The location of the json file to input data from. Returns: ...
8544db10f0d4558c030ffb8a1455aed91b832ac3
54,317
def convert_model(saved_model_dir): """ Convert a SavedModel into Tensorflow Lite Format. `saved_model_dir`: the path to the SavedModel directory returns: the converted Tensorflow Lite model """ logger.info('Converting SavedModel from: {}'.format(saved_model_dir)) converter = tf.lite.TFLiteC...
2dd2436285acd0dc488d0023d091a75cf4ecad07
54,318
def connect(): """ Open a connection to the typesense server. """ with open('/etc/typesense/typesense-server.ini') as f: lines = f.readlines() api_key = [line[10:] for line in lines if line.startswith('api-key = ')][0].rstrip() return typesense.Client({ 'nodes': [{ 'host'...
dadc9ec6667aedc080aa4421020b0be7ec1c41a2
54,319
def _make_url(raw, sig, quick=True): """ Return usable url. Set quick=False to disable ratebypass override. """ if quick and "ratebypass=" not in raw: raw += "&ratebypass=yes" if "signature=" not in raw: if sig is None: raise IOError("Error retrieving url") raw += "&si...
b1c3c61ba60f21b436a70a9eff3d629600b76fc6
54,320
from typing import Optional from typing import Any def get_component_exceptions( cluster: str, environ: str, topology: str, component: str, role: Optional[str]=None, ) -> Any: """Get exceptions for 'component' for 'topology'.""" base_url = create_url(EXCEPTIONS_URL_FMT) params = { "clu...
cadabb7e306ca56fed1d8254ce5a6b6ec399b6e1
54,321
def UnpackHWIDDigest(base, header): """Unpacks HWID digest section.""" offset = base + GBB_HWID_DIGEST_OFFSET size = GBB_HWID_DIGEST_SIZE return GBBField(header.hwid_digest.hex(), offset, size)
6c6a37090e149f4dcc0a1c74bb1c0399bc204a97
54,322
import itertools def group_into_dict(items, key_fn): """ Groups items into a dictionary based on a key generated by a given function Examples: items = [ Car(make="Honda", model="Civic"), Car(make="Honda", model="Accord"), Car(make="Ford", model="F150"), ...
bdf4fbb4cd1df0b187e0aed2fc8916530711365d
54,323
def _get_table_meta(): """gets the meta data about fields from meta.agolitems """ mapping = {} with pyodbc.connect(config.get_source_connection()[6:]) as connection: cursor = connection.cursor() cursor.execute('SELECT [TABLENAME],[AGOL_PUBLISHED_NAME],[GEOMETRY_TYPE] FROM [SGID].[META]...
fbafb21ce24101b980702b374cc588522e5a5705
54,324
def _estimate_ratios_by_kmeans(obs, guess, **kmeans_kws): """ Adapted kmeans to use norm1 distances (identical to euclidean-norm2 for 1D) and using median() for each guess, to ignore outliers and identify "gear-lines". """ def _1d_kmeans(obs, guess, guess_func, thresh=1e-5): """ The "ra...
cc2b727e7fc9f64292438c2755fe31c6da77f3d2
54,325
from typing import Collection import logging def construct_grammar(grammar_config: GrammarConfig, vocab: Collection[str]) -> state_tree.NQCFG: """Builds the grammar according to `grammar_config`.""" productions = [] # Lexical rules. if grammar_config.grammar_type in ( GrammarType...
a16caaf212ae2d843f295d0c3f2ae29444e97547
54,326
import requests def get_channel_id(username, API_KEY): """ i might have been entering the wrong usernames or something but, this thing only works half of the time """ url = f"https://www.googleapis.com/youtube/v3/channels" payload = {"forUsername":username, "part":"id,snippet", "key":API_K...
da90cdec623d5c3e4ee210cc133ee9900db340f9
54,327
def pick_npoints_on_hemisphere(N = 2500): """Randomly pick N points on the upper part of a hemisphere. see http://mathworld.wolfram.com/SpherePointPicking.html """ xs, ys, zs = [], [], [] us, vs = np.random.rand(N) * 2 * np.pi, np.arccos(np.random.rand(N)) for i in range(N): x, y, z = u...
40e469bdb2eb4b35e8e6e7f22f961d4777082281
54,328
import scipy def plot_histogram( ax, x, maxima: bool = False, maxima_props: dict = None, annotate_props: dict = None, hist_props: dict = None, ax_props: dict = None, plot_props: dict = None, inter_props: dict = None): """Plot a histogram from...
237776e080ad9ded2950f13fe7d1fa06306f80ee
54,330
import json def print_columns(response, response_type): """prints a column style output for a list of networks currently only supports 'pureport accounts network list :param response: the response object :type response: array :returns a formatted output string :rtype: str """ colu...
328ec7f12856b69c8290d5bed3c2efc3cfe4ceb1
54,331
from datetime import datetime def get_geo(hdfname, monotonic_lons=True,root_name=None): """ given the name of any hdf file from the Cloudsat data archive return lat,lon,time_vals,prof_times,dem_elevation for the cloudsat orbital swath usage: lat,lon,date_times,prof_times,dem_elevation=get_ge...
3908d697bc92098ca6b9dc25de3bb03cd69f9b30
54,332
def get_metadata(tsuid): """ Get metadata from metadata api If `fid` is in the user provided pattern add that to metadata :param tsuid: TSUID to get metadata from IKATS :type tsuid: str :return: the metadata list for this timeseries :rtype dict """ metadata = IkatsApi.md.read(tsui...
c402fbe554e99089a2d4457489ff42c49e7cb58b
54,333
def get_author_list(): """ Get author list --- responses: 200: description: Returns author list schema: id: AuthorList properties: code: type: string message: ...
0a1d68466b8c84f0a01924bf53ce83ef78c8a29a
54,334
import re def parse_extra_metadata_to_selector(option: str, operation: str, value: str) -> str: """Method tries to convert the extra metadata received into selectors :param option: option (extra, python_version, sys_platform) :param operation: (>, >=, <, <=, ==, !=) :param value: value after the oper...
4be00559ada260d569a1efe7d027f843dbf3e8b1
54,335
def vgg11_quantized(num_classes=10, dataset='cifar10'): """VGG 11-layer model (configuration "A")""" return VGG(make_layers(cfg['A']), num_classes, dataset)
471bb48d930c790e633ffb04c13278d750b23e99
54,336
def get_paint_dc(win): """ A utility function for obtaining a BufferedPaintDC on Windows. """ if get_platform() == 'windows': dc = wx.BufferedPaintDC(win) dc.SetBrush(wx.Brush((win if win.UseBgCol() else win.GetParent()).GetBackgroundColour())) dc.SetPen(wx.TRANSPARENT_PEN) dc.Dr...
9e5f7b72ef835ce4957a46c4f65f85e605b552a9
54,337
def average_data(df): """ Average data over eval runs then scenario runs """ df = df.astype({"solved": int}) avg_eval_df = df.groupby(["scenario", "agent", "run"]).mean().reset_index() eval_err = df.groupby(["scenario", "agent", "run"]).sem().reset_index() # run_err = avg_eval_df.groupby(["scenario"...
e0f6bc8f8ee59b6b5855324baf6a2ecee4a25e2e
54,338
def get_value_names_from_timestamp(timestamp, file_id=None, mode='r'): """ Returns value_names from the HDF5 file specified by timestamp. :param timestamp: (str) measurement timestamp of form YYYYMMDD_hhmmsss :return: list of value_names """ folder = a_tools.get_folder(timestamp) h5filepath ...
dd5a4ff776715cb67e553d4a8284dfc415de73ff
54,339
def get_element(X, bb, shape): """ returns the bounding box area from the image X """ x,y,w,h = bb x,y,w,h = int(x),int(y),int(w),int(h) return resize(X[y:y+h,x:x+w], shape, mode='constant')
010cb2809efa919228229252418427ee8fb54b74
54,340
def non_psd_kernel(a, b): """An implementation of a non-psd kernel. Args: a: A vector b: A vector """ if(np.allclose(a,b,rtol=1e-5)): return -1 return 0
f52b891bab20d29b955f5df13dc8449af5ddfb38
54,342
def delta_func(beta): """ Compute delta_beta as per Heuristic 1. """ rep = ((pi * beta) ** (1 / beta)) * beta / (2 * pi * exp(1)) rep = rep ** (1 / (2 * (beta - 1))) return rep
2f8bf7bfbae8d8f5fcd4a6f7dff9b44648655eb1
54,343
def encode(plain_text, a_value, b_value): """ Encode text """ if gcd(a_value, 26) != 1: raise ValueError("a and m must be coprime.") plain_text = list(filter(lambda x: x.isalnum(), list(plain_text))) for index, char in enumerate(plain_text): if char.isalpha(): new...
cba8a4d84b4d2bdd06d1502047fc164bd42969e1
54,344
def pad_to_shape(d, dshape, mode = "constant"): """ pad array d to shape dshape """ if d.shape == dshape: return d diff = np.array(dshape)- np.array(d.shape) #first shrink slices = tuple(slice(-x//2,x//2) if x<0 else slice(None,None) for x in diff) res = d[slices] #then pad...
61786ff3ea975015cf56bc2716cedb3b359fb8b4
54,345
from datetime import datetime def addFooter(template, clientAddress=None): """Add a footer:: -- <3 BridgeDB ________________________________________________________________________ Public Keys: https://bridges.torproject.org/keys This email was generated with rainbows, unico...
e4e679e1d49e3368a77ec00702742864614c6958
54,347
def _trace_lines(frame, event, arg): """ Function used for tracing executed lines. Inserts into log: lineno : Tuple[line_str, locals] """ global logger co = frame.f_code parent = frame.f_back.f_code func_name = co.co_name if event == 'line': if func_name.split('::')[-1] ...
274890305c9b1b1399c63d65924f597e1bbdc683
54,348
def confirm_superuser_changes(request, user_id): """Renders the confirmation page to confirm the successful changes made to the selected user's account settings by the group superuser. Parameters: request - The request object sent with the call to the confirm page if the request...
3ded3fae6f8d9af55da076631c6e9addeb3be503
54,349
def grad_refactor_simple_2(x, y, z): """ add """ return x * y + z + x * y * z + x + x * y
38bc1120ec6804f364d8c98f91d6301ef609ecf4
54,350
def heading_section(title: str, to_list: bool = False): """Construct a section heading. """ linelist = [title, hr(len(title), '=')] return linelist if to_list else '\n'.join(linelist)
f5f6d7fa1e0b3a459df7a3f40247f7eec54123fc
54,351
def _GetStarredIssues(cnxn, logged_in_user_id, services): """Get the set of issues that the logged in user has starred.""" starred_iids = services.issue_star.LookupStarredItemIDs( cnxn, logged_in_user_id) return set(starred_iids)
6185371138da1e79673d7347770073a18f82b099
54,353
import pytz def AdaptReadableDatetime(date_obj): """Adapts a datetime.datetime object to its ISO-8601 date/time notation.""" try: date_obj = date_obj.astimezone(pytz.utc) except ValueError: pass # naive datetime object return date_obj.isoformat()
feceafb58995001acdeb2285fa5782bec7cc756d
54,354
def iou_loss(true, pred): """ Calcaulate the intersection over union metric """ intersection = true * pred notTrue = 1 - true union = true + (notTrue * pred) return tf.subtract(1.0, tf.reduce_sum(intersection)/tf.reduce_sum(union))
7d2dae13252d472749932363a37716bde8addfed
54,355
def get_gop_pos(frame_idx, representation): """given frame idx to find the group idx and the position inside a group""" gop_index = frame_idx // GOP_SIZE gop_pos = frame_idx % GOP_SIZE if representation in ['residual', 'mv', 'flow']: if gop_pos == 0: # use the previous frame's residual and MV...
6c284bc957c24b553b66bf4ddb23814ad7246f03
54,356
import asyncio async def _get_server_host_key(host, port=(), *, tunnel=(), family=(), flags=0, local_addr=None, client_version=(), kex_algs=(), server_host_key_algs=(), config=(), options=None): """Retrieve an SSH server's host key This is a coro...
ad7837090e8fc43ff68797c4b722c79fd4c88b20
54,357
def prompt_choice(length, select_action, per_page): """ Prompt the user for a choice of entry, to continue or to quit. An invalid choice will repeat the prompt. @param length: the largest choosable value @param select_action: description of what choosing an entry will result in. @param per_pag...
4b957479d96e5b8c642db4e888faf92c8c9cf945
54,358
from re import T def _e_step(psamples, W_list, b_list, n_steps=100, eps=1e-5): """ Performs 'n_steps' of mean-field inference (used to compute positive phase statistics) Parameters ---------- psamples : array-like object of theano shared variables State of each layer of the DBM (durin...
8bafc87c33367ed999d80de027201d7680db1d40
54,359
from typing import Tuple def get_stencils( stencil_sizes: Tuple[int, ...], offset: Tuple[float, ...], steps: Tuple[float, ...] ) -> Tuple[np.ndarray]: """Computes stencils locations. Generates stencils such that the target offset is placed at (0.,)*ndims. This is needed to obtain correct polynomial...
72ec1d453533dc6787825e03702b4c6226493e5e
54,360
import time def neo_start(self, container_name, project_name, port, pwd): """ 启动neo4j Args: pwd: port: project_name: self: container_name: Returns: """ # 在js取到 data['state'] != 'CREATE NEO4J SANDBOX' 后将配置展示(仅仅展示) self.update_state( state="S...
ab85d0f2d4de5279812bdc9f81a45bc51770c69b
54,361
def normalize(data, axis=None, index=None): """ Normalize data on the given axis data: a multi-dim array. axis: axis or axes which makes subarrays to be normalized together. E.g., axis=-1 means to normalize the innermost dimension. None (i.e., all axes) or int or tuple of int. index: in...
a901b794ff4e1f4dc5944494d9163a2cecabddb7
54,362
import collections def make_map(connections): """Return the map of caves based on connections.""" neighbors = collections.defaultdict(list) for start, end in connections: neighbors[start].append(end) neighbors[end].append(start) return neighbors
10f35208fa75b5ae4723d9d55e022a0fcc857e51
54,364
def des_key_64(K): """ Return an 64-bit des key by adding a zero to the least significant bit of each character. K should be a 7 char string """ in_key = K + "\0" out_key = [K[0]] for ix in xrange(1,len(in_key)): out_key.append(chr( ((ord(in_key[ix-1]) << (8-ix)) & 0xFF) | (ord(i...
bffbb3217d6818c6bfece656978af6ff413ecb41
54,365
def l2_norm(x): """ Returns ------- normalization of data in range(0,1) with method euclidean distance Parameters ---------- x: x is we data in shape Matrix note -------- most import numpy as np """ a = np.sqrt(np.square(x)) size_of_vector = np.sqrt(np.sum(a ** 2, a...
4a130f8abb4b1a9adb5dbeb932cd43ea0889c296
54,366
from typing import Tuple def info_to_table(rows: list) -> Tuple[list, list]: """ Formats raw row data into a table format that will be used with other render functions. This function is where column headers should be defined. Arguments: rows(list): Rows of data Return: ...
3f92acccb3d93aa539ef34f136c557ca3ecb324b
54,367
def calcExRIndex(inputRasterImage,mode): """ calcExRIndex. :param inputRasterImage: (Image) input raster image. :param mode: (String) mode RGB or GBR :returns outputRasterImage: (Image) output raster image. """ if mode=='RGB' : chRed,chGreen,chBlue = cv2.split(inputRasterImage) else: chGreen,chRed,chBlu...
8ee2ea0b767bae69a22b790229fa78645c29121e
54,368