content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
from typing import Dict from pathlib import Path import yaml def get_categories_and_file_names() -> Dict: """Returns a dictionary of categories and files Returns ------- Dict Key is the name of the category, value is a dictionary with information on files in that \ category """ ...
4e7d0295e6e40e5c443f5d91c18d83d138b092f4
3,631,273
from typing import Dict from typing import Set def process_class_items(game_class: GameClass, categories: Dict[str, Dict[str, int]], items_def: Dict, removals: Set[str], locked: Set[str]) -> ClassUnlockables: """ Process a hierarchical definition of a class's items into a ClassUnlockab...
64290748b72dac3590e6677dcd65af62677cee79
3,631,274
def MakeByte(ea): """ Convert the current item to a byte @param ea: linear address @return: 1-ok, 0-failure """ return idaapi.doByte(ea, 1)
ce8925c66d3e4a6c811f2a244f56b4317c66a877
3,631,276
def upload_persons(request): """ Options for upload form to define person and person roles :param request: :return: """ print('persons upload request: ', request.GET) selection = NmPersonsEntries.objects.all().distinct('entry_id') myFilter = PersonsFilter(request.GET, queryset=selection...
2caf9a8c10c12aaa9b46bd83666c39dac4dd6492
3,631,278
from neon.backends.nervanacpu import NervanaCPU from neon.backends.util import check_gpu from neon.backends.nervanagpu import NervanaGPU from mgpu.nervanamgpu import NervanaMGPU from argon.neon_backend.ar_backend import ArBackend import logging import atexit def gen_backend(backend='cpu', rng_seed=None, datatype=np.f...
8e6127d70a1fa4bee0d1e3a5c6855338f1254218
3,631,279
from redis import exceptions import socket def get_redis_error_classes(): """Return tuple of redis error classes.""" # This exception suddenly changed name between redis-py versions if hasattr(exceptions, 'InvalidData'): DataError = exceptions.InvalidData else: DataError = exceptions....
7d2331de649430a857c1575ccc590c642ff36e4a
3,631,280
from typing import Dict from typing import Any def create_property(supported_prop: Dict[str, Any]) -> HydraClassProp: """Create a HydraClassProp object from the supportedProperty.""" # Syntax checks doc_keys = { "property" : False, "title": False, "readonly": True, "writeo...
7f0aa8252f995d0ae7a9fad5f5690a034d159458
3,631,281
import scipy.weave.md5_load as md5 def expr_to_filename(expr): """ Convert an arbitrary expr string to a valid file name. The name is based on the md5 check sum for the string and Something that was a little more human readable would be nice, but the computer doesn't seem to care. """...
0fde1beda5e073890258f3fba5a8b5f38b1129fb
3,631,282
def getIDList(): """getIDList() -> list(string) Returns a list of all lanes in the network. """ return _getUniversal(tc.ID_LIST, "")
e7c3f0134f8a91778cc8caf252eaf0f11cdb8e46
3,631,283
def cmor(B, C): """ Returns the n-point continuous Morlet wavelet Args: B the bandwidth parameter C the central frequency """ def time(t, s=1.): s = jnp.atleast_2d(jnp.asarray(s)).T t = t / s # the sinusoid output = jnp.exp(1j * 2 * jnp.pi * C * t) ...
dc7e521113837423e37c20d2f31ad7222dd37fd6
3,631,284
def calculateMid(paddle): """Calculates midpoint for each paddle, much easier to move the paddle this way""" midpoint = int(paddle[0][1] + paddle[1][1]) / 2 return midpoint
83fbba67945d158807bd9c3aebcab63342ce7599
3,631,285
def autotune(i): """ Input: { See 'crowdsource program.optimization' (iterations) - change iterations Force: local = yes only_one_run = yes keep_tmp = yes skip_exchange...
22e29831cfaa040ff0425a87f482be857a12004f
3,631,286
import io def generate_from_file(abouts, is_about_input, license_dict, scancode, min_license_score, template_loc=None, vartext=None): """ Generate an attribution text from an `abouts` list of About objects, a `template_loc` template file location and a `vartext` optional dict of extra variables. ...
099152905ded65278d1b382956f35b110692b8f2
3,631,287
from typing import Match from datetime import datetime def user_past_parties(): """List parties the logged in user has been in. Params: page (int): Optional. Page number to return. """ received = request.get_json() page = received.get('page', 1) # User record user = util.user_fro...
6a6cd86abe39e962a2b09a7204ad62f5be894df4
3,631,288
def bits_list(number): """return list of bits in number Keyword arguments: number -- an integer >= 0 """ # https://wiki.python.org/moin/BitManipulation if number == 0: return [0] else: # binary_literal string e.g. '0b101' binary_literal = bin(number) bit...
6f27715dbccefe56d77c800a44c4fa5e82d35b50
3,631,289
def show_funcs(): """ List of of algos presently available """ return(sorted(func_registry.keys()))
e685c92ee8cbc8a7d5d1c7323976eaccd10fa4fa
3,631,290
def _FakeQuantWithMinMaxVars(inputs, min_var, max_var, per_channel, num_bits, narrow_range): """Adds a fake quantization operation. Depending on value of per_channel, this operation may do global quantization or per channel quantization. min_var and max_var should have corresponding...
1457d7f7661ed336421f715f4841c6e7a1518537
3,631,291
def join_and_keep_order(left, right, remove_duplicates, keep='first', **kwargs): """ :type left: DataFrame :type right: DataFrame :rtype: DataFrame """ left = left.copy() right = right.copy() left['_left_id'] = range(left.shape[0]) right['_right_id'] = range(right.shape[0]) result = left.merge(right=right, **...
a3044f7de9c1f8ffb50cf1e57997307ee0e3d840
3,631,292
import typing from typing import Counter def count_variants(graph) -> typing.Counter[str]: """Count how many of each type of variant a graph has. :param pybel.BELGraph graph: A BEL graph """ return Counter( variant_data[KIND] for data in graph if has_variant(graph, data) ...
194a3881e0cb4b73520293ec587cae96de932958
3,631,293
def collate(expression, collation): """Return the clause ``expression COLLATE collation``. e.g.:: collate(mycolumn, 'utf8_bin') produces:: mycolumn COLLATE utf8_bin """ expr = _literal_as_binds(expression) return _BinaryExpression( expr, _literal_as_text(col...
37896bfce0f7c02c4021af75105a878831de4838
3,631,294
def crop_images(x, y, w, h, *args): """ Crops all the images passed as parameter using the box coordinates passed """ assert len(args) > 0, "At least 1 image needed." cropped = [] for img in args: cropped.append(img[x : x + h, y : y + w]) return cropped
e8f78246c0bfeb3d370b8fe01e264b2f7e0e1c49
3,631,295
import time import json def WriteResultToJSONFile(test_suites, results, json_path): """Aggregate a list of unittest result object and write to a file as a JSON. This takes a list of result object from one or more runs (for retry purpose) of Python unittest tests; aggregates the list by appending each test resu...
cb53b65bf5c8ceb1d0695e38c4ebeedd4916fe14
3,631,296
def svn_prop_has_svn_prop(*args): """svn_prop_has_svn_prop(apr_hash_t props, apr_pool_t pool) -> svn_boolean_t""" return _core.svn_prop_has_svn_prop(*args)
5ca451ecd2d945ace6f690ada61abc6de1bef445
3,631,297
def test_analysis_dual_grad(n, lbda): """ Test the gradient of dual analysis. """ rng = check_random_state(None) x, _, _, _, D, A = synthetic_1d_dataset(n=n, s=0.5, snr=0.0, seed=rng) eps = 1e-3 v_dim = D.shape[1] v = np.clip(rng.randn(n, v_dim), -(lbda - eps), (lbda - eps)) Psi_A = np.linal...
5ba56bc1621f7e159c4cb5c5e2309272690b787f
3,631,298
def dojo_gbrv_results(pseudo, struct_type, num_sites, volumes, etotals): """ This function computes the GBRV results and returns the dictionary to be inserted in the dojoreport file. Args: pseudo: Pseudopotential object. struct_type: "fcc" or "bcc" num_sites: Number of sites in ...
f20eac647f4bc83235ea71187dcd493392028472
3,631,299
def split_person_name(name): """ A helper function. Split a person name into a first name and a last name. Example. >>> split_person_name("Filip Oliver Klimoszek") ("Filip Oliver", "Klimoszek") >>> split_person_name("Klimoszek") ("", "Klimoszek") """ parts = name.split(" ") return " ".join(parts[:-1...
86b7c7cec1e7772437f41f11437834cfa34051c7
3,631,300
def readFile(file): """Reads file and returns lines from file. Args: string: file name Returns: list: lines from file """ fin = open(file) lines = fin.readlines() fin.close() return lines
52c62e6c97caad053cd6619935d8d3674cc3b8cb
3,631,301
def vec_rotate_left(x): """Circular left shift the contents of the vector Args: x (jax.numpy.ndarray): A line vector. Returns: jax.numpy.ndarray: Left rotated x. """ return jnp.roll(x, -1)
58bc95e73ba45829c588c07682f1b04f9f2b6f30
3,631,302
def play_game(my_play='PUT',game_id='PUT'): """Submit a play to a game. Return results of the game.""" # If no my_play then something is wrong # If no game_id and no match_id then create a new game and play it # If game_id then play that game # If match_id and no game_id then .. idk .. tea? # Pu...
50bd11a8f89f68ca981eecc96c6c225cd84fd1c7
3,631,303
def get_inputs(seq_len): """Get input layers. See: https://arxiv.org/pdf/1810.04805.pdf :param seq_len: Length of the sequence or None. """ names = ['Token', 'Segment', 'Masked'] return [keras.layers.Input( batch_shape=(1, seq_len,), name='Input-%s' % name, ) for name in name...
585d6bae73b7b9f4fc6e9dcafd85ee0e4be88b44
3,631,304
import base64 def get_credentials(args): """Read credentials from args""" # cmdline credentials override those stored in config file if args.api_key or args.api_secret: if not args.api_key or not args.api_secret: raise AuthError( ( "Both --key and --...
f4f69b20e5ea2fe58a8ee22920c7faeea8738aae
3,631,305
import logging def GetRange(spreadsheet_id, sheet_name, range_in_sheet): """Gets the given range in the given spreadsheet. Args: spreadsheet_id: The id from Google Sheets, like https://docs.google.com/spreadsheets/d/<THIS PART>/ sheet_name: The name of the sheet to get, from the bottom tab. ran...
08eaa5f761679622b6561c7ed56d41ef725c940e
3,631,306
def format_price(raw_price): """Formats the price to account for bestbuy's raw price format Args: raw_price(string): Bestbuy's price format (ex: $5999 is $59.99) Returns: string: The formatted price """ formatted_price = raw_price[:len(raw_price) - 2] + "." + raw_price[len(raw_pric...
a3b0adc94421334c3f1c4fe947329d329e68990e
3,631,307
def access_app(app_label, *permissions): """ Returns a scope that represents access for the given permissions to the given app. """ return _make_grant( ( app_label, ), permissions, )
ef9ad2827cd38d70760618c7f3af8ab645a3b22f
3,631,309
def mock_device_with_capabilities(monkeypatch): """A function to create a mock device with non-empty observables""" with monkeypatch.context() as m: m.setattr(Device, '__abstractmethods__', frozenset()) m.setattr(Device, '_capabilities', mock_device_capabilities) def get_device(wires=1)...
d21e319645ce4ae59db1cea9c38c1e5bc8bf967f
3,631,310
def replicated_data(index): """Whether data[index] is a replicated data item""" return index % 2 == 0
26223e305d94be6e092980c0eb578e138cfa2840
3,631,311
def create_source_list(uris_list): """ Create a source_list object Adds list of uris to soure_list object. @arg uris_list List of list of GCS uris @returns A source_list object @example uris_list = [["gs://my-bucket/my-image-1.tif"], ["gs://my-bucket/my-image-2.tif"]] print(create_s...
cd5ca853d1c388d5be0c5591a64eff4120af5b3e
3,631,312
def sigmoid_rampup(current, rampup_length): """ Exponential rampup from https://arxiv.org/abs/1610.02242 . """ if rampup_length == 0: return 1.0 else: current = np.clip(current, 0.0, rampup_length) phase = 1.0 - current / rampup_length return float(np.exp(-5.0 * phase * ...
a003cb14073b14789e221197d42f818ee29b863b
3,631,313
def photos_restaurants(): """returns photos""" return render_template('photos.html')
f0404e9cd0cd97018f64f415612180828afaef1d
3,631,314
def encode(obj, outtype='json', raise_error=False): """ encode objects, via encoder plugins, to new types Parameters ---------- outtype: str use encoder method to_<outtype> to encode raise_error : bool if True, raise ValueError if no suitable plugin found Examples -------- ...
7408fc616c7b1c99a47a33b55bf9c0cabcd1cf70
3,631,315
def minorify_scale(scale): """Turns a major scale into a minor scale""" return rotate(scale, 5)
a0f2e5d7307095eb6c6b426a32c7958082d1eff9
3,631,316
def _get_dtype_maps(): """ Get dictionaries to map numpy data types to ITK types and the other way around. """ # Define pairs tmp = [ (np.float32, 'MET_FLOAT'), (np.float64, 'MET_DOUBLE'), (np.uint8, 'MET_UCHAR'), (np.int8, 'MET_CHAR'), (np.uint16, 'MET_USHORT'), (...
a5816325737a97054764b0b266353053cf83b025
3,631,317
def get_user_roles_common(user): """Return the users role as saved in the db.""" return user.role
cf25f029325e545f5d7685e6ac19e0e09105d65a
3,631,318
def getlist(self, option: str, fallback: list=None, *, raw: bool=False, vars: dict=None) -> list: """ Converts a SectionProxy cvs option to a list :param option: the option to get :param fallback: default value, if option does not exist :param raw: True to disable interpolation :param vars: addi...
b451c48bfaa0dc1cf51f6ffd52866a9d5c1ad761
3,631,319
def _schedule_spatial_pack(cfg, s, output, conv, data_vec, kernel_vec): """schedule the spatial packing for conv2d""" data = s[data_vec].op.input_tensors[0] max_unroll = 16 vec_size = [1, 2, 4, 8, 16] # get tunable parameters (they are defined in compute) BC, TC, VC = cfg["tile_co"].size BH...
91f3cb0b442b1b35fbdcb532b0d229b05a56b09f
3,631,320
from .spectral import TemplateSpectralModel from .spatial import ConstantSpatialModel def create_fermi_isotropic_diffuse_model(filename, **kwargs): """Read Fermi isotropic diffuse model. See `LAT Background models <https://fermi.gsfc.nasa.gov/ssc/data/access/lat/BackgroundModels.html>`_ Parameters -...
6233fa84e2234722587c17289522e61e8fcc453b
3,631,321
def get_auto_sync(admin_id): """Method to return status of the auto synchronization statement. Args: admin_id (str): Root privileges flag. """ return r_synchronizer.is_sync_auto()
897a30c35eb115e359dae844a81155bfa3b93b12
3,631,322
def create_inchi_groups(ctfile): """Organize `InChI` into groups based on their identical `InChI` string and similar coupling type. :param ctfile: `SDfile` instance. :type ctfile: :class:`~ctfile.ctfile.SDfile` :return: Dictionary of related `InChI` groups. :rtype: :rtype: :py:class:`dict` """ ...
819239eac4298be1de63510faf67e282ee20bb91
3,631,323
def loocvRF(data, idcolumn, outcomevar, dropcols=[], numestimators=1000, fs=0.02): """ Main loocv RF function that calls other functions to do RF feature selection, training, and testing. Args: data (pandas DataFrame): This is a dataframe containing each participant's features and outcome...
3681923d34334e16490586e143cb29dd9b426461
3,631,325
from typing import Union def sqla_session(x: Union['db_url', 'engine']): """ Do a pile of sane defaults to get a sqla session. Example usage: db = sqla_session(...) df = pd.read_sql(sql=..., con=db.bind) """ # Resolve args if isinstance(x, str): db_url = x if '/' ...
4a7b6fa07d360a884d60982083a4a70a7699dd1c
3,631,326
def box_iou(box1, box2, order='xyxy'): """Compute the intersection over union of two set of boxes. The default box order is (xmin, ymin, xmax, ymax). Args: box1: (tf.tensor) bounding boxes, sized [A, 4]. box2: (tf.tensor) bounding boxes, sized [B, 4]. order: (str) box order, either 'xyxy'...
03b40728a52cc4b825e2e9473ce5ada6dfa07d2e
3,631,327
def get_bmi_category(df): """ This function adds the BMI category and Health risk based on the BMI value :param df: input dataframe with BMI values :return: Dataframe with BMI category and Health risk derived from their respective BMI values """ return df.withColumn('BMI Category', F.when(df.BM...
85574ae7e1b9887b86aa06881e6950d30e2e2aea
3,631,328
def create_mm_sim(molecule): """Create vacuum simulation system""" platform = Platform.getPlatformByName('CPU') properties={} properties["Threads"]="2" integrator = LangevinIntegrator(temperature, collision_rate, stepsize) topology = molecule.to_topology() system = forcefield.create_openmm...
7023320e9344bf9601844917692f36650ee57376
3,631,330
def team_event_awards(team_key: TeamKey, event_key: EventKey) -> Response: """ Returns a list of awards for a team at an event. """ track_call_after_response("team/event/awards", f"{team_key}/{event_key}") awards = TeamEventAwardsQuery(team_key=team_key, event_key=event_key).fetch_dict( Api...
942f6576bec422a84d9d1ad220b38a050ff4b466
3,631,331
def partial_es(Y_idx, X_idx, pred, data_in, epsilon=0.0001): """ The analysis on the single-variable dependency in the neural network. The exact partial-related calculation may be highly time consuming, and so the estimated calculation can be used in the bad case. Args: Y_idx: index of Y to acce...
12186469b27bebea4735372e2b45f463bbfbaff1
3,631,334
def process_source_text( source_text: str, endpoint_config: submanager.models.config.FullEndpointConfig, ) -> str: """Perform text processing operations on the source text.""" source_text = submanager.sync.utils.replace_patterns( source_text, endpoint_config.replace_patterns, ) s...
318a66717008a57c0a975359092a925d55dfe44a
3,631,335
def angle(v1, v2, deg=False): """ Angle between two N dimmensional vectors. :param v1: vector 1. :param v2: vector 2. :param deg: if True angle is in Degrees, else radians. :return: angle in radians. Example:: >>> angle_between((1, 0, 0), (0, 1, 0)) 1.5707963267948966 ...
0d85cc76085468401fcb805d0df5a83862791d49
3,631,336
def random_pure_actions(nums_actions, random_state=None): """ Return a tuple of random pure actions (integers). Parameters ---------- nums_actions : tuple(int) Tuple of the numbers of actions, one for each player. random_state : int or np.random.RandomState, optional Random see...
300c77583d60e0fa5d5be240ae1beb8c4555db22
3,631,337
import pandas import numpy def prepare_and_store_dataframe(test_df: pandas.DataFrame, current_datetime: str, prediction: numpy.ndarray, eval_identity: str, df_output_dir: str): """Prepares a dataframe that includes the testing data (timestamp, value), the detected anomalies and the...
a2aa5d9ffb9ec495abb96ddebc820dd351392b1a
3,631,339
def read_terrace_centrelines(DataDirectory, shapefile_name): """ This function reads in a shapefile of terrace centrelines using shapely and fiona Args: DataDirectory (str): the data directory shapefile_name (str): the name of the shapefile Returns: shapely polygons with terraces ...
bd527dc9c890f3e0efd7076803ce1288f2643062
3,631,340
def isfloat(s): """ Checks whether the string ``s`` represents a float. :param s: the candidate string to test :type s: ``str`` :return: True if s is the string representation of a number :rtype: ``bool`` """ try: x = float(s) return True except: r...
2233d0a06b9ff0be74f76ef2fce31c816f68584c
3,631,341
import aiohttp async def _fetch_team_info(team_id=None): """Get general team information""" url = f"{BASE_URL}teams/{team_id}" async with aiohttp.ClientSession() as session: data = await _fetch_data(session, url) team_info = data['teams'][0] return team_info
b846b71cf65d2179c59f108c3c0e27ff4eb25149
3,631,342
def numeric(typ): """Check whether `typ` is a numeric type""" return typ.tcon in (Bool, Int, Float, Complex)
b03a2042072a084e8482e5782ffc074512bf52e2
3,631,343
def quadtree_point_in_polygon( poly_quad_pairs, quadtree, point_indices, points_x, points_y, poly_offsets, ring_offsets, poly_points_x, poly_points_y, ): """ Test whether the specified points are inside any of the specified polygons. Uses the table of (polygon, quadrant)...
898e8d4da600da559605146a451093c0452ce6cc
3,631,344
from typing import Dict def obtain_treasury_maturities(treasuries: Dict) -> pd.DataFrame: """Obtain treasury maturity options [Source: EconDB] Parameters ---------- treasuries: dict A dictionary containing the options structured {instrument : {maturities: {abbreviation : name}}} Returns ...
02dfc478be14cf63938b43420c61b359baf06ab3
3,631,345
def graph(gra): """ write a molecular graph to a string """ gra_str = automol.graph.string(gra) return gra_str
635ee0fcad2aa1b5d2542c9d89a492692efbcf0a
3,631,346
def diag(v, k=0): """ Extract a diagonal or construct a diagonal array. See syntax here: https://numpy.org/doc/stable/reference/generated/numpy.diag.html """ if not is_casadi_type(v): return _onp.diag(v, k=k) else: if k != 0: raise NotImplementedError( ...
983ff1bd5c753d40b44f8fe38dadab9febfccffa
3,631,347
def which_set(connections_list_of_dics): """ """ set_of_derivations=get_set_of_derivations(connections_list_of_dics) list_of_derivations=[] list_of_derivations.append("all") list_of_derivations.append("each") for this_deriv in list(set_of_derivations): list_of_derivations.append(this_deriv) list_of_...
d4b93396a9966d532c4a46acb88467d8cbe00914
3,631,348
def ensure_derived_space(func): """ Decorator for Surface functions that require ImageSpace arguments. Internally, Surface objecs store information indexed to a minimal enclosing voxel grid (referred to as the self.index_grid) based on some arbitrary ImageSpace. When interacting with other ImageS...
3f293d0833fd7079a49eaf5ce2de53c76d238da8
3,631,349
def available_datasets(): """ Returns the list of available datasets. """ return sorted(_datasets.keys())
77b1d451f89f76486d36a03008634fc1b5728150
3,631,350
def readable_date(input_date): """helper method to make a date object more readable :param input_date: a date object :return: more readable string representation of a date """ return "{} {}, {}".format(month_name[input_date.month], str(input_date.day), str(input_date.year))
a22649298ef2fd488257091bfdf82a11f8de1846
3,631,351
def get_unicode_from_response(response): """Return the requested content back in unicode. This will first attempt to retrieve the encoding from the response headers. If that fails, it will use :func:`requests_toolbelt.utils.deprecated.get_encodings_from_content` to determine encodings from HTML ele...
3b7b9ced468e3a26cd7c322b6c0a6c0552215e7b
3,631,352
def stack_layers(inputs, net_layers, kernel_initializer='glorot_uniform'): """Builds the architecture of the network by applying each layer specified in net_layers to inputs. Args: inputs: a dict containing input_types and input_placeholders for each key and value pair, respecively. net_layers: a li...
a010ec3e1c02978c28c2df2f947f1360ccb35deb
3,631,353
def instance_gpu() -> str: """ Returns the GPU for the Colab instance. :return: The GPU model """ devices = device_lib.list_local_devices() gpu = [x.physical_device_desc for x in devices if x.device_type == "GPU"][0] return gpu.split(",")[1].split(":")[1].strip()
37af910eb3bac5b089f28ee73fb9040b686b516e
3,631,354
def _get_expected_samples(A_s, b_s, mu_0, sample_shape) -> np.ndarray: """ Given an initial `mu_0`, calculate the expected samples from an almost-deterministic `StateSpaceModel`. """ *batch_shape, transitions, state_dim = b_s.shape means_list = [mu_0] for i in range(transitions): mea...
46a88611ae0a04851474fbbe5605a523e3e42a6a
3,631,355
import ast def local_vars(fn: ast.AST): """Returns a set of all function local variables.""" return set(_locals_impl(fn))
c51290884099957063be9bc0814dca13ceb7566e
3,631,356
def swap(size: int, target0: int, target1: int) -> Matrix: """ Construct swap gate which swaps two states :param int size: total number of qubits in circuit :param int target0: The first target bit to swap :param int target1: The second target bit to swap returns: Matrix: Matrix repres...
a34d15c5b74ad49b01b6dfe894f640982c88d4fe
3,631,357
def get_ELS_file_name(dt, remove_extension=False): """ >>> get_ELS_file_name('28-06-2004/22:00') 'ELS_200418018_V01.DAT' >>> get_ELS_file_name('28-06-2004/09:00') 'ELS_200418006_V01.DAT' >>> get_ELS_file_name('29-06-2004/09:00') 'ELS_200418106_V01.DAT' >>> get_ELS_file_name('29-06-2005/0...
f6a9f0dfff3501379f94e55e3fecdf2033400db2
3,631,358
def percentage_to_float(x): """Convert a string representation of a percentage to float. >>> percentage_to_float('55%') 0.55 Args: x: String representation of a percentage Returns: float: Percentage in decimal form """ return float(x.strip('%')) / 100
6c1aeac99278963d3dd207d515e72b6e1e79f09f
3,631,359
def _naics_code_to_name(naics_val: str) -> str: """Converts NAICS codes to their industry using the _NAICS_MAP. Args: naics_val: A NAICS string literal to process. Expected syntax of naics_val - NAICS/{codes} '-' can be used to denote range of codes that may or may not belong ...
96e5f7d951c81337ee3d431f765a98c6d12f737f
3,631,360
from typing import Optional import re def get_pragma_spec(source: str) -> Optional[NpmSpec]: """ Extracts pragma information from Solidity source code. Args: source: Solidity source code Returns: NpmSpec object or None, if no valid pragma is found """ pragma_match = next(re.finditer(r"...
8a5af024c1105a52140b2bfefb583b67568964d5
3,631,362
def delete_form(context, *args, **kwargs): """Тег формы удаления объекта. """ action = (args[0] if len(args) > 0 else kwargs.get('action')) if action is None: raise TemplateSyntaxError( "delete_form template tag " "requires at least one argument: " ...
c99736384eb149869bc4110e90427fe21beaecc7
3,631,363
def _ligandscout_xml_tree(pharmacophore): """ Get an xml element tree necesary to create a ligandscout pharmacophore. Parameters ---------- pharmacophore : openpharmacophore.Pharmacophore Pharmacophore object that will be saved to a file. Returns ------- ...
c9e8b09a103917ceb6242dd74de4c93198cf841d
3,631,364
import time import requests def request_get_content(url: str, n_retry: int = 3) -> bytes: """Retrieve the binary content at url. Retry on connection errors. """ t0 = time.time() for i in range(1, n_retry + 1): try: r = _session().get(url) r.raise_for_status() ...
6fc3882243b4d23f7311ab9d7b5a1bf946a801d7
3,631,366
def _escape_special_chars(content): """No longer used.""" content = content.replace("\N{RIGHT-TO-LEFT OVERRIDE}", "") if len(content) > 300: # https://github.com/discordapp/discord-api-docs/issues/1241 content = content[:300] + content[300:].replace('@', '@ ') return content
816fc3ba15150c3e254a17d1a021d1ddee11e49f
3,631,367
def gather(results_dir): """Move all of the files and directories from the present working directory into results_dir. If results_dir doesn't exist, create it. Delete any symbolic links so that the present working directory is empty. :param results_dir: Path of the directory into which to store t...
375154347ea57147d236c4fbf1da01791e654684
3,631,368
def system_dynamics(t, x, params,): """ Parameters ---------- x0 : State vector t : Current time step params : Simulation parameters Returns ------- dx : State vector dynamics for time step integration """ # Extract state variables and parameters # Python star...
1d9ef4f2ff304f14f961620af3ec646a3a6ad1b3
3,631,369
def key(): """Connection key""" return ConnectionKey('localhost', 80, False, None, None, None, None)
4af1cc0619db168f9e9110095accab1836031bd4
3,631,370
import ipdb def _check_deviation(indexesv, xdatav, ydatav, yarray_, ii, start_, end_, mbf, dev_thresh, no_data, ...
541acff0c88b3912e185989348d4c81fa4275507
3,631,371
def crop_boxes_inv(cropped_boxes, crop_shape): """ Inverse operation of crop_boxes """ crop_x1 = crop_shape[0] crop_y1 = crop_shape[1] raw_boxes = np.zeros_like(cropped_boxes) raw_boxes[:, 0::4] = cropped_boxes[:, 0::4] + crop_x1 raw_boxes[:, 1::4] = cropped_boxes[:, 1::4] + crop_y1 ...
309eba1ddde6a9474bab132b5f2deaae75b772e4
3,631,372
from typing import OrderedDict import inspect def build_paramDict(cur_func): """ This function iterates through all inputs of a function, and saves the default argument names and values into a dictionary. If any of the default arguments are functions themselves, then recursively (depth-first) ad...
b62daf5ffe7b9211d898d26dc754875459dbe1ba
3,631,373
def auto_gen_message(open, fill, close): """ Produces the auto-generated warning header with language-spcific syntax open - str - The language-specific opening of the comment fill - str - The values to fill the background with close - str - The language-specific closing of the commen...
e72ff3760ea78efb969f5c457caca726e070a387
3,631,374
def neighbor(matrix, taxa=None, distances=True): """ Function clusters data according to the Neighbor-Joining algorithm \ (:evobib:`Saitou1987`). """ clusters = dict([(i, [i]) for i in range(len(taxa))]) formatter = "({0}:{2:.4f},{1}:{3:.4f})" if distances else "({0},{1})" taxa = check_langu...
8bd655082cb6c5e1b9ba7efdda5241ea0943782c
3,631,375
def mixed_type_frame(): """ Fixture for DataFrame of float/int/string columns with RangeIndex Columns are ['a', 'b', 'c', 'float32', 'int32']. """ return DataFrame({'a': 1., 'b': 2, 'c': 'foo', 'float32': np.array([1.] * 10, dtype='float32'), 'int32': np....
7a07b77413839104b687e095b8805a205f3b14fc
3,631,376
def dar_state(): """Get DAR state """ return jsonify(state=dar.state)
df188f3f9c37e011f820453740f9758adf2dabb9
3,631,377
def has_prefix(sub_s): """ :param sub_s: the list which includes the permutations of string's alphabet :return: if the permutations of string's alphabet not exists in dictionary """ global d for word in d: if d[word].startswith(sub_s): return True return False
07c4636e1e85029c8cc5e5d8450ceae1a6511846
3,631,378
def MaskStringWithIPs(string): """Mask all private IP addresses listed in a string.""" ips = ExtractIPsFromString(string) for ip in ips: use_bits = IsPrivateIP(ip) if use_bits: masked_ip = MaskIPBits(ip, use_bits) string = string.replace(ip, masked_ip) return string
b90f194cd038c1979b38ac57c8e30326a19ca4b8
3,631,379
def DiagGaussian_UnifBins(mean, stdd, bin_min, bin_max, coding_prec, n_bins, rebalanced=True): """ Codec for data from a diagonal Gaussian with uniform bins. rebalanced=True will ensure no zero frequencies, but is slower. """ if rebalanced: bins = np.linspace(bin_min, bin_max, n_bins) ...
d54464e8a4bf2e5f93ee228b19b9de92e00dfafd
3,631,380
def GetUserFansCount(user_url: str) -> int: """获取用户粉丝数 Args: user_url (str): 用户个人主页 Url Returns: int: 用户粉丝数 """ AssertUserUrl(user_url) AssertUserStatusNormal(user_url) json_obj = GetUserJsonDataApi(user_url) result = json_obj["followers_count"] return result
057a732bff7ae74896b598022d57754e034a02af
3,631,381
from typing import Counter def majority_vote(labels): """assumes labels sorted by distance ASC""" vote_counts = Counter(labels) winner, winner_count = vote_counts.most_common(1)[0] num_winners = len([count for count in vote_counts.values() if count...
f56aede57a08ee4d9190e3b69daa48a7946fcb99
3,631,382