content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def get_property(name,*args): """Convenience function to quickly retrieve any stellar property/properties for a given KepID/KOI numbers Parameters ---------- name : int, float or str, or array_like KOI or KIC name (or array of names) *args : string, properties to return (must...
599ea8a604b6c42320dc6212766993585d4b89a9
3,617,400
def property_immutable_cache(f): """ This cache should only be used on properties that return an immutable object """ @wraps(f) def inner(self): if f.__name__ not in self.cache: self.cache[f.__name__] = f(self) return self.cache[f.__name__] return property(inner)
89938fe0599dc19d7d93cee0d524d52fe6a7dd24
3,617,401
def normalize(vec): """normalizes an Nd list of vectors or a single vector to unit length. The vector is **not** changed in place. For zero-length vectors, the result will be np.nan. :param numpy.array vec: an Nd array with the final dimension being vectors :: numpy.array...
93503a9314b1e2982f7afb75009a2d8736fdc621
3,617,402
def lam(m, f, w): """Compute lambda""" s = 0 for i in range(len(f)): s += f[i] * w[i] return float(m)/float(s)
6a71eb0020a5c2d86d88504f9867150c0fa7e248
3,617,403
import os from datetime import datetime def is_old_file(filename, max_days=0, max_seconds=3600, verbose=True): """Returns true if the file modification date > max_days / max_seconds ago or if the file does not exist""" if os.path.isfile(filename) is not True: return True st = os.stat(filename)...
73fe2a1894ad42cb681baa0e9cebb789bd3a0d0b
3,617,404
def _get_binary_xentropy(target_values, forecast_probabilities): """Computes binary cross-entropy. This function satisfies the requirements for `cost_function` in the input to `run_permutation_test`. E = number of examples :param: target_values: length-E numpy array of target values (integer clas...
fc40aeeb0151f66f596ddf2c042a254cde1f8522
3,617,405
def _check_for_collision(sprite1: Sprite, sprite2: Sprite) -> bool: """ Check for collision between two sprites. :param Sprite sprite1: Sprite 1 :param Sprite sprite2: Sprite 2 :returns: Boolean """ collision_radius_sum = sprite1.collision_radius + sprite2.collision_radius diff_x = sp...
53fd13d622a2b37040c334430c88b7263e9c4bed
3,617,406
def get_value(lst, row_name, idx): """ :param lst: data list, each entry is another list with whitespace separated data :param row_name: name of the row to find data :param idx: numeric index of desired value :return: value """ val = None for l in lst: if not l: conti...
aa5ba25c4a431fe470921d344887fb02fee68712
3,617,407
import numpy def in_domain(X, a_array, c_array): """ Check is a given point is inside or outside the design domain """ flag = 1 for n in range(numpy.shape(a_array)[0]): a = a_array[n] c = c_array[n] dist = numpy.dot(X-c,a) if(dist > 0.7): flag = 0 if(abs(dist)<0.7): flag = 2 return flag
e39e779b456ea8df4f217d1c2ed5eaddf498881a
3,617,408
def generate_script(job): """ Generates a script from a job. """ work_dir = job.path json_data = hjson.loads(job.json_text) # The base url to the site. url_base = f'{settings.PROTOCOL}://{settings.SITE_DOMAIN}{settings.HTTP_PORT}' # Extra context added to the script. runtime = dict...
5fb8074df30f7b394d649f7b7c7bcceff360a64e
3,617,409
from datetime import datetime def metadata(ts, capture_block_id, report_path, run, st=None): """Create a dictionary with required metadata. Parameters ---------- ts : : class:`katsdptelstate.TelescopeState` telescope state capture_block_id : int capture_block_id report_path : ...
35460bab4f945f6ad53dfb59160653a8b35608df
3,617,410
def raw_compare_ge(stage: ImportStage, left: ir.Value, right: ir.Value) -> ir.Value: """Emits an ApplyCompareOp for 'ge'.""" return d.ApplyCompareOp(d.BoolType.get(), ir.StringAttr.get("ge"), left, right).result
8eded11bff34003a6df0d482b3478c26e6b3fc00
3,617,411
def SearchLunarApsis(startTime): """Finds the time of the first lunar apogee or perigee after the given time. Given a date and time to start the search in `startTime`, this function finds the next date and time that the center of the Moon reaches the closest or farthest point in its orbit with respect ...
2f62c2b15c4ed808aaef14f8fbe7ad4359d63c31
3,617,412
def _get_dataset_from_filename( instruction: _Instruction, do_skip: bool, do_take: bool, file_format: file_adapters.FileFormat, add_tfds_id: bool, ) -> tf.data.Dataset: """Returns a tf.data.Dataset instance from given instructions.""" ds = file_adapters.ADAPTER_FOR_FORMAT[file_format].make_tf_da...
0a7a10156cb69583043fb6cb1db8ed472960ecdd
3,617,413
def clamp(x, inf=0, sup=1): """Clamps x in the range [inf, sup].""" return inf if x < inf else sup if x > sup else x
42c178afc0bdfc02fd31fe3f211f23cc04b40d2e
3,617,414
def open_current_file(): """ Opens the current maya scene file. :return: <bool> True for success. """ cmds.file(cmds.file(q=1, loc=1), o=1, f=1) return True
57e777c9a11b959b19fd25195bfe8ff1c511cf22
3,617,415
def flatten(x, name=None, reuse=None): """Flatten Tensor to 2-dimensions. Parameters ---------- x : tf.Tensor Input tensor to flatten. name : None, optional Variable scope for flatten operations Returns ------- flattened : tf.Tensor Flattened tensor. """ ...
f279f78891ab4741ee2b305529f14c7bcfbf61a7
3,617,416
def attribute_startswith(search_string, limit=20): """Query attributes starting search_string :param search_string: e.g. al to match allow_from, allow_to etc. :param limit: limit result to n results :return: """ query = Attribute.objects.filter( attribute_id__startswith=search_string)...
4fadd9c02f8596324735e342cc3efea20acc9c2c
3,617,417
def jaccard_stability(explainer, x, neighborhood, k=1): """Jaccard adaptation Stability function. Takes as argument an explanation method, a single observation x of shape (n_features, ), the neighborhood as a matrix of shape (n_neighbors, n_features), and the size of the subset being considered k ...
b9db7a391ce7163aee3c4f568adb8db3c30c12b5
3,617,418
def _get_item_kind(item): """Return (kind, isunittest) for the given item.""" try: itemtype = item.kind except AttributeError: itemtype = item.__class__.__name__ if itemtype == 'DoctestItem': return 'doctest', False elif itemtype == 'Function': return 'function', Fal...
c597db3de4447c68f3d8187e2f988e6c81e19d00
3,617,419
def search_by_classifier(): """Use PyPI XML-RPC API to get all Lektor-tagged distributions. https://warehouse.pypa.io/api-reference/xml-rpc.html """ client = ServerProxy("https://pypi.org/pypi") return set(name for name, version in client.browse(["Framework :: Lektor"]))
9e74644b0edb52f1cd2b423349866a2f4a614001
3,617,420
from bs4 import BeautifulSoup import requests import re def _get_page(url: str, headers: dict = {}, cookies: dict = {}) -> BeautifulSoup: """ Return page as BeautifulSoup object Parameters ---------- url : str a useable url headers : dict, optional headers, by default {} c...
fea97883c5aa19af6a3f037f32a73269d6e8cb66
3,617,421
def champ_win_rate(matches_df, champ, lane='all'): """Calculate the win rate of a single champion. By default, looks in every lane. Lane can also be specified (eg. TOP_SOLO) """ teams_lanes_roles = dc.get_teams_lanes_roles() if lane != 'all': teams_lanes_roles = ['100_' + lane, '200...
64be101dd939df5b25ef5523651b41b121c7045e
3,617,422
from datetime import datetime def convert_to_datetime(line): """TODO 1: Extract timestamp from logline and convert it to a datetime object. For example calling the function with: INFO 2014-07-03T23:27:51 supybot Shutdown complete. returns: datetime(2014, 7, 3, 23, 27, 51) ""...
262d78afe0464935e872853a3b6ebb6a8b6f726b
3,617,423
def computeDiffSig (train_X, train_Y, mu, classLabel): """ Computes the means of the GDA """ m = train_Y.shape[0] classIndicator = np.array(train_Y == classLabel).flatten() classCount = np.sum(classIndicator == True) Sigma = np.matrix([[0, 0], [0, 0]]) for (indicator, x) in zip(classInd...
a8d133f848804f705c9791f51e95e0e9a2a06662
3,617,424
def _inc_path(path): """:returns: The path of the next sibling of a given node path.""" newpos = MP_Node._str2int(path[-MP_Node.steplen :]) + 1 key = MP_Node._int2str(newpos) if len(key) > MP_Node.steplen: raise Exception("Path Overflow from") return "{0}{1}{2}".format( path[: -MP_No...
80f77ba2499bed3b82705fae96ac88a6bb4f1664
3,617,425
def delete(): """ delete() : Delete a document from Firestore collection """ try: # Check for ID in URL query doc_id = request.args.get('id') db_ref.document(doc_id).delete() return jsonify({"success": True}), 200 except Exception as e: return f"An Error O...
092464c5dd46fb2225bdf94f0d53dafd06dcb98a
3,617,426
from typing import Optional def mongo_event(event: str, resource: str, func: Optional[EventFuncType]=None ) -> Event: """A function to return an :class:`Event` with aliases set-up for mongo events. The following aliases can be used for mongo events:: +----------+--------------+ ...
0d0b89ec0611f4b8ccc4eaac692552352c93fab1
3,617,427
import json def xml_to_json(survey: database.Survey): """Convert survey from Ankieter xml format to json format :param survey: The Survey that is edited or created :type survey: Survey :return: The survey in json format :rtype: Dict """ def write_element(question, res): res[...
4a7c7ee03d47b435f04e6fa0c54153ae37b76868
3,617,428
from typing import Optional from typing import Union from typing import Tuple def payoff_table_method( problem: MOProblem, initial_guess: Optional[np.ndarray] = None, solver_method: Optional[Union[ScalarMethod, str]] = "scipy_de", ) -> Tuple[np.ndarray, np.ndarray]: """Uses the payoff table method to ...
c3917b52e04bf631d9033ac2a99ec2a3e89a262d
3,617,429
def absmag(mag, z, band1='megacam_r', band2='megacam_r', model='cb07_burst_0.1_z_0.02_salp.model', zf=5): """ Takes a set of magnitudes all at the same redshift z and returns the aboslute magnitudes. This does not need to be done for each object since the conversion from apparent to absol...
7cd52aed7d65fc69721ec0b281554c6d639656f7
3,617,430
def load_yields(location): """Loads up the county corn yields""" pgconn = get_dbconn('coop') df = read_sql(""" select year, num_value as yield from nass_quickstats where county_ansi = %s and state_alpha = 'IA' and year >= 1980 and commodity_desc = 'CORN' and statisticcat_desc...
f1ae5a06216916fa7358821ebc192ff2ea158359
3,617,431
def mapattr(value, arg): """ Maps an attribute from a list into a new list. e.g. value = [{'a': 1}, {'a': 2}, {'a': 3}] arg = 'a' result = [1, 2, 3] """ if len(value) > 0: res = [getattr(o, arg) for o in value] return res else: return []
34e45bcf804d37feb5995b88534cca78679d8cfb
3,617,432
def _rxcheck(model_type, interval, iss_id, number_of_wind_samples): """Gives an estimate of the fraction of packets received. Ref: Vantage Serial Protocol doc, V2.1.0, released 25-Jan-05; p42""" # The formula for the expected # of packets varies with model number. if model_type == 1: _expec...
610fa2c2aa83e6d0c9cf9c93961ba8aa6b496188
3,617,433
def hashable_tensor_or_op(tensor_or_op): """Returns a hashable reference to a Tensor if given a Tensor/CompositeTensor. Use deref_tensor_or_op on the result to get the Tensor (or SparseTensor). Args: tensor_or_op: A `tf.Tensor`, `tf.CompositeTensor`, or other type. Returns: A hashable representation ...
140a5f2cfc933fa3a83daa3753cbedebb23de356
3,617,434
import lxml.etree as ET def header_to_xml(header): """ Converts image header metadata into an XML Tree that can be inserted into a JP2 file header. Parameters ---------- header : `MetaDict` A header dictionary to convert to xml. Returns ---------- `lxml.etree._Element` ...
2a9e3391076db3253c99127f7258bec01c01ebeb
3,617,435
def string_in_list(str, substr_list): """Returns True if the string appears in the list.""" return any([str.find(x) >= 0 for x in substr_list])
b6e8ce2f918fec0b9a671f1c557f6f1d005c734e
3,617,436
import asyncio from datetime import datetime async def _async_watch(job_id, directory, python_datetime=None, first_time=True, **kwargs): """Wait until a list of jobs finishes and get updates.""" watch_one = qwatch.Qwatch(jobs=[job_id], directory=directory, watch=True, users=None, **kwargs) job_dict = wa...
12f436301fe5f237e8ff21c70cf2a79bb408456e
3,617,437
def vals_missing_plot_list_cmap(binned_array, listed_cmap): """Returns a normalized imshow plot using a 3 value array w vals 2,3,4.""" cmap, norm = listed_cmap bins, arr = binned_array arr[arr == 1] = 2 arr[arr == 5] = 4 f, ax = plt.subplots(figsize=(5, 5)) return ax.imshow(arr, cmap=cmap...
ef56fb6e657325645103310bab9f64424acbbdde
3,617,438
def click_by_js(element): """Clicks on element by triggering .click() using JavaScript Arguments: element -- the Selenium WebDriver Element to click Returns: True or False """ if verbose: print 'Clicking on element by js...' try: Browser.execute_script('arguments[0].click();', element) ...
bfab7d634029dd96ff8b8103145438e96e12dd4e
3,617,439
import pickle def get_disk_rse_ids(): """Get rse:rse_id map from pickle file TODO: Get rse:rse_id map via Rucio python library. I could not run Rucio python library unfortunately. Used code in LxPlus (author: David Lange): ```py #!/usr/bin/env python from subprocess import Popen,PIPE import os,sys,...
6c5889f965c666e0b07807f97687cf9c252cfb75
3,617,440
def process(tweet, preserve_case=True, preserve_stopwords=False): """ Perform tweet preprocessing :param tweet: :param preserve_case: :param preserve_stopwords: :return: """ tweet = basicProcess(tweet) # perform basic preprocessing if preserve_stopwords is False: # in case we want ...
7f2e321ef8a4663b983f6425630e25acf18837b4
3,617,441
def loadRaster(source): """ Load a raster dataset from a path to a file on disc Parameters: ----------- source : str or gdal.Dataset * If a string is given, it is assumed as a path to a raster file on disc * If a gdal.Dataset is given, it is assumed to already be an open raster ...
4b89d5f4e890f850f18d69cb745023ffa25b23b3
3,617,442
import os import json def save_json(info, folder, audio_name): """ TODO DOCUMENTATION :param info: :param folder: :param audio_name: :return: """ check_folder(os.path.join(folder, audio_name), True) out_file = os.path.join(folder, audio_name, 'info.json') with open(out_file, 'w...
3cd87be05370c5dc890732ab78a011842fab25d1
3,617,443
def process(fname): """Process verif output file. fname: name of file return: tuple of (exp_name, solver, dx, dt, dome_e, max_e, min_e, mean_e, sd_e)""" # extract errors ncf = Scientific.IO.NetCDF.NetCDFFile(fname) diff = ncf.variables['thke'][-1,:,:] - ncf.variables['thk'][-1,:,:] centre...
07cbe5e776c55c92a792b8f3502d59015b15daea
3,617,444
import copy def build_kfold_config(params_dict, train_path, dev_path): """按k-fold拆分好的数据,构造新的json配置,用来启动训练任务 :param params_dict: 原始json配置构造出来的param_dict :param train_path: k-fold拆分之后的训练集路径,list类型 :param dev_path: k-fold拆分之后的评估集路径,list类型 :return: task_param_list: 生成新的json配置,用来启动run_with_json """...
e13a7468a2fa3fd33219abfdf3347579a82de518
3,617,445
def bft_events_graph(start): """Builds graph of events traversing events in breadth-first order This graph doesnt necessary reflect deployment order, it is used to show dependencies between resources """ dg = nx.DiGraph() stack = [start] visited = set() while stack: item = stac...
f14af4f6c0e8ac13e2d7d048d05dbddd170d4fc0
3,617,446
import bisect def _get_past_names(cur: cx_Oracle.Cursor) -> dict[str, list[str]]: """Returns all the names that each InterPro entry ever had. Names are sorted chronologically. :param cur: Oracle connection cursor. :return: A dictionary (key: entry accession, value: list of names) """ versions...
d4096eeae756793dbfdfe0f22ac8e61208332402
3,617,447
def serve_subtitles(request, great_media_id, language): """Subtitles are stored along with the core.models.GreatMedia instance but they need to be served via their own dedicated URL. """ video = get_object_or_404(GreatMedia, id=great_media_id) # See if there's a subtitle field for the appropriate ...
b89907bf722ddb49fde24e48794ce4152ba887de
3,617,448
import numpy def makeMostCommonPatternHeuristic(weights): """Return a function that chooses the most common (currently most-used) pattern.""" def weightedPatternHeuristic(wave, total_wave): print(total_wave.shape) # [print(e) for e in wave] wave_sums = numpy.sum(total_wave, (1, 2)) ...
514bd14e6f04896165d2068a3ddaa77e778e19c5
3,617,449
def ServicesDecorator(func): """ Make sure cfn-hup is running """ def wrapper(*args, **kwargs): kwargs['services'] = { 'sysvinit': InitServices( { 'cfn-hup': InitService( ensureRunning='true', enabled='true',...
2951b4f87d63ecea3de6728024a4175abedb0566
3,617,450
import uuid async def _fetch( flow_id: uuid.UUID, yaml_only: bool = False ): """ Get Flow information using `flow_id`. Following details are sent: - Flow YAML - Gateway host - Gateway port """ try: with flow_store._session(): host, port_expose, yaml_spec = ...
d6698d17fe47810fd8944a68c726e56b6b5b21ca
3,617,451
from typing import Optional def get_sample_graph(model_name: Optional[str] = None) -> tf.Graph: """Return a sample model as tf.Graph""" graph_def = get_sample_graph_def(model_name, fmt='proto') graph = tf.Graph() with tf.compat.v1.Session(graph=graph): tf.graph_util.import_graph_def(graph_def,...
7e00b28a41f83e40cf2da5aa75ab4ce0bae6f0c7
3,617,452
def selectMetric(name: str): """Return the metric defined by name. Args: name (str): a string referenced in DeepHyper, one referenced in keras or an attribute name to import. Returns: str or callable: a string suppossing it is referenced in the keras framework or a callable taking (y_true,...
356f35faa40c1f70f0d2f65cb74ac216d029dd9c
3,617,453
def getTagNames(domain): """ Returns a list of tag names used by the domain. :param domain: a domain object :type domain: `escript.Domain` :return: a list of tag names used by the domain :rtype: ``list`` of ``str`` """ return [n.strip() for n in domain.showTagNames().split(",") ]
f24ccdec61eca07cef283ed4e9d981236b530c62
3,617,454
def matching(fingerAi, finger_i): """ Matching entre dos huellas """ it = 0 ta = 0 tb = 0 for i in range(len(fingerAi)): if fingerAi["f0"].iloc[i]==finger_i["f0"] and \ fingerAi["f1"].iloc[i]==finger_i["f1"] and \ fingerAi["utime"].iloc[i]==finger_i["...
2ca3c16c5a9ac126314a39598719c8f7f64fa97a
3,617,455
def glob_texture_files(texture_file_pattern): """Collect / glob specified image file path. :arg texture_file_pattern: Image file path need to glob, file name must have glob pattern '*' (asterix). :type texture_file_pattern: str or path.Path :rtype: list of path.Path """ texture_file_glob =...
1a9287331d5ad2007a63eb3ead1a6d697244aec8
3,617,456
def make_rotation(theta): """ makes a rotation matrix Note: HWP is a mirror matrix, not a rotation! :param theta: :return: """ a = cos(theta) b = -sin(theta) c = sin(theta) d = cos(theta) retMat = np.array([[a,b], [c, d]]) # need to remove issues from machine precision ...
e57a90f8c4363fcfa22f9d881bad52191849d8cd
3,617,457
def verify_routing_route_ip_on_interface(device, interface_dict): """ Verify routes match the configured IP address in running config Args: device (`obj`): Device object interface_dict (`dict`): Interface dict contain ip route info. Get from libs/routing/verify.py::verify_routing_lo...
30572c447ac0a30dea1cd21d60f00194f1a67bba
3,617,458
def calculate_denominator(unvisited_nodes, pheromone_matrix, distance_matrix, current_node, node, load, max_load, demand, alpha, beta, gamma, lam): """ Calculate denominator to compute the probability of a route """ sum = 0.0 for node in unvisited_nodes: tau = calculate_tau(pheromone_matrix...
65447eec8383cf43d26c9ee7f483f090a0cd2d89
3,617,459
import ipdb def get_right_stem_aligned_indices( string, inner_potential_indices, outer_potential_indices ): """Return the indices of the aligned strings :param str string: the original string :param tuple inner_potential_indices: [start, end) of inner part :param tuple outer_potential_indices: [s...
cddf26b5200f05a8aaece22ebe4b659208c63b04
3,617,460
def stack_tensor_dict_list(tensor_dict_list): """ Stack a list of dictionaries of {tensors or dictionary of tensors}. :param tensor_dict_list: a list of dictionaries of {tensors or dictionary of tensors}. :return: a dictionary of {stacked tensors or dictionary of stacked tensors} """ keys = list...
21dbd264571f76c743aecfa7a7d3cd1cd5c65ee5
3,617,461
def db_insert(conn, query): """ Execute the insert the query on the db and return the insert id @param conn: Connection @param query: Query string to be executed """ logger = bp_logger('dbutils') try : conn.query(query) except _mysql_exceptions.ProgrammingError as (errno, strerr...
bf6d20dfdc4550b6948103dba2ae97d8bf7fa8fc
3,617,462
import socket def is_gce_instance(): """Check if it's GCE instance via DNS lookup to metadata server""" try: socket.getaddrinfo('metadata.google.internal', 80) except socket.gaierror: return False return True
74605bca73a9a46b629212c87f154aa9a4920a1d
3,617,463
def get_count_value(context, fieldname): """ {% get_count_value fieldname %} """ return {"value":fieldname}
9356b602b2685341f402193c830842e656acc6cb
3,617,464
import os import gzip def download_feature(feature_name, cache=False, **kwargs): """download a single feature Args: feature_name: (str) name of feature cache: (bool) set to True if you plan on using the instance for more than one job kwargs: Returns: pd.DataFrame """ ...
9ec8d637e1711359f872d1cb20c1fb57242299b2
3,617,465
from parrot_api.core.requests import get_request_access_token def post_json_example(body: dict) -> dict: """Sample API handler that accepts a json body :param body: the json body variable :return: dictionary containing a single "value" parameter """ return dict(value=True, token=get_request_acces...
3b0a5708042022ea271eb245ff5223b51fdde825
3,617,466
def registerShortcut(categories, keyseq, context=Qt.WidgetShortcut, actionName=None): """Decorate a function to be called when a keyboard shortcut is typed When the keyboard shortcut `keyseq` is pressed in any widget matching `categories`, the decorated function will be called, with the widget passed as first param...
427a8d4e19ff04c999ca4b4d95ad9795ebb3dbae
3,617,467
def fit_normal(x, y): """ Fit Gaussian """ if sum(y) == 0: _logger.debug("Problem with fit: all data points have zero value. Return zeros instead fit parameters!") return [0, 0, 0], None mean = sum(x * y) / sum(y) sigma = np.sqrt(sum(y * (x - mean) ** 2) / sum(y)) area = sum(y[:-...
aada730d25b504106d1a57ce94d0e23ff6b85e9a
3,617,468
def as_strided(x, shape, strides, storage_offset=None): """Create a new view of array with the given shape, strides, and offset. Args: x (tuple of :class:`~chainer.Variable` or :class:`numpy.ndarray` or \ :class:`cupy.ndarray`): The array pointing a memory buffer. Its view is totall...
613f71045f77aa71fe0dbc096c87aff2b04f6b07
3,617,469
def GranularFormLayout(request): """ A simple demonstration of partial rendering of parts of forms. """ schema = schemaish.Structure() schema.add( 'firstName', schemaish.String(title='First Name', \ description='The name before your last one', \ validator=v...
c69725b91e44c0259ce8fd318fb0dca97bf3646a
3,617,470
import functools def _find_metadata(func): """ Support `xarray.DataArray` for find function. """ @functools.wraps(func) def wrapper(*args, **kwargs): x, y = args x_in, y_in, kwargs = _dataarray_strip(x, y, suffix=('', '_track'), **kwargs) x_out, y_out = func(x_in, y_in, **k...
c0803fc3d443aa807c692bacbf21240c4730aad1
3,617,471
from typing import Dict from typing import Union import os def create_key_pair(dump: bool = True) -> Dict[str, Union[str, bytes]]: """create key pair :param dump: bool, True: return `bytes.hex`, False: return bytes :return: dict, { 'privateKey': private_key, 'publicKey': public_key, ...
c1e019bb688a085f3ffee50fba44f493d32b4ff8
3,617,472
def _forgy_center_initializer( X: np.ndarray, n_clusters: int, random_state: np.random.RandomState ) -> np.ndarray: """Compute the initial centers using forgy method. Parameters ---------- X : np.ndarray (3d array of shape (n_instances,n_dimensions,series_length)) Time series instances to c...
bba4bd967297501f73d0e641df421baeb9bf18c8
3,617,473
import os import io import subprocess import time def run_migration(migration_id: str, config: dict, app_logger: logger.Logger) -> bool: """ Run migration :param migration_id:. :param migration_id: id of migration to run :param config: pymigrate configuration :param app_logger: instance of config...
1d353aa4f3fedf716fd6ae582ddcdd5096773529
3,617,474
from typing import Optional def generate_richcompare_wrapper(cl: ClassIR, emitter: Emitter) -> Optional[str]: """Generates a wrapper for richcompare dunder methods.""" # Sort for determinism on Python 3.5 matches = sorted([name for name in RICHCOMPARE_OPS if cl.has_method(name)]) if not matches: ...
cbbc66a22ee61ed869331fbecd59eb615588fd48
3,617,475
import imageio import numpy as np def assign_embedding_colors(points, texPath, flipTexUD=False, flipTexLR=False, rot90=0): """ :param points: :param texPath: :return: """ # read texture tex = np.array(imageio.imread(texPath)) if flipTexUD: tex = np.flipud(tex) if flipTex...
9fec12cdf8c6a6429a2d250a0c28b885a4833ca0
3,617,476
def parse_table_html(s, first_row_th=True, first_col_th=False, cls=None): """ parser for csv table, creates html :s: the input string to parse, which should be of the format v11, v12, v13, v14 v21, v22, v23, v24 v31, v32, v...
86b375b2e0785512325ad6e44f48f4a4e6d9d71a
3,617,477
import decimal def get_savings_rate(exp_records: list, inc_records: list) -> decimal.Decimal: """ :param List[far_core.db.ExpenseRecord] exp_records: window of expenses :param List[far_core.db.IncomeRecord] inc_records: window of incomes :return: the savings rate over the window, which is defined as: ...
905000fa95fecdace5a01e84fbb98e412d07b605
3,617,478
def random_row(gdf,x,y): """ sampling the GNSS data randomly by entering the specific number of samples Parameters ---------- gdf: geodataframe geodataframe of all gnss data(population) x : int x is the number of samples y: int y is the random seed, different ran...
eb8c5ab2c577045cf21b9292f1c92cfb5dea5ab5
3,617,479
import pathlib import typing def _get_data_for_write( path: pathlib.Path, file_format: str, prefix_keys: typing.Iterable[str], ) -> typing.Tuple[typing.Dict[str, typing.Any], typing.Dict[str, typing.Any]]: """ Retrieve the data from the file if it exists or create a new data object if not. :p...
22ecaaad57f025431db484e1d07db63e95832a70
3,617,480
import ctypes import sys def _fix(): """ Apply some fixes and patches. """ NS = globals() # Fix glGetActiveAttrib, since if its just the ctypes function if ('glGetActiveAttrib' in NS and hasattr(NS['glGetActiveAttrib'], 'restype')): def new_glGetActiveAttrib(program, index): ...
1c92230bbadcd06be82b524c68dbcf072e52ae3a
3,617,481
import functools import scipy def scipy_powell( criterion_and_derivative, x, lower_bounds, upper_bounds, *, convergence_relative_params_tolerance=CONVERGENCE_RELATIVE_PARAMS_TOLERANCE, convergence_relative_criterion_tolerance=CONVERGENCE_RELATIVE_CRITERION_TOLERANCE, stopping_max_crite...
e3a535669eb9ceed6398d2e9795934be5b1a4f84
3,617,482
def prettyPrintDataFrame(df: pd.DataFrame, url_columns=["url"], max_column=50): """Prints pandas dataframes with custom max-width for column and potentially transforms URL into clickable content by using to_html(escape=False) method. WARNING!: Can potentially execute external code if not properly used. ...
534a90aae1497945ea5c73895629aa7818490812
3,617,483
import unittest def require_retrieval(test_case): """ Decorator marking a test that requires a set of dependencies necessary for pefrorm retrieval with [`RagRetriever`]. These tests are skipped when respective libraries are not installed. """ if not (is_tf_available() and is_datasets_availab...
a1c3c81cccbcedf7f82519eecf05789433a238c4
3,617,484
def edge_validator_debug(input: 'Socket', output: 'Socket') -> bool: """This will consider edge always valid, however writes bunch of debug stuff into console""" print("VALIDATING:") print(input, "input" if input.is_input else "output", "of node", input.node) for s in input.node.inputs+input.node.outpu...
9482288e7152fe17d87951ab895545182f399638
3,617,485
from typing import List def missing_impact_1v1( # pylint: disable=too-many-locals df: dd.DataFrame, x: str, y: str, bins: int, ndist_sample: int ) -> Intermediate: """ Calculate the distribution change on another column y when the missing values in x is dropped. """ df0 = df[[x, y]] df1 ...
e74cc7ceed3017422566b95660306ad34c4eaf53
3,617,486
import os def db_connection(f): """ Supply the decorated function with a database connection. Commit/rollback and close the connection after the function call. """ def with_connection_(*args, **kwargs): con = pymysql.connect( host="localhost", user=os.environ["DB_...
e5af11db5a4ab7ad2095b7eedb6b3ab48d152667
3,617,487
def rle_kyc(seq: str) -> str: """ Run-length encoding """ counts = [] count = 0 prev = '' for char in seq: # We are at the start if prev == '': prev = char count = 1 # This letter is the same as before elif char == prev: count += 1...
c617ca2bfe62baed5e141c65ec923297f27ac488
3,617,488
def is_legal_parameter(name): """ Function that returns true if the given name can be used as a parameter in the c programming language. """ if name == "": return False if " " in name: return False if "." in name: return False if not name[0].isalpha(): ...
de4426f5fc14740439c8f278d19e8ec9944e1a2f
3,617,489
import requests def getDefaultGateway(host, args, session): """ Called by the network function. Prints out the DefaultGateway. @param host: string, the hostname or IP address of the bmc @param args: contains additional arguments used by the ldap subcommand args.json: bool...
eaae94a1b9c92d359fcd6ba786e05c6738023be9
3,617,490
def unity(): """Return a unity function""" return lambda x:x
5e7aa6bfe20f0534244ed0932b3bf87bf7505230
3,617,491
from typing import List from typing import Tuple def tf_idf(search_keys:str, data:List) -> Tuple: """calculate the tf-idf matrices for the vocabulary and keyword matrix""" tfidf_vectorizer = TfidfVectorizer() tfidf_weights_matrix = tfidf_vectorizer.fit_transform(data) search_query_weights = tfidf_...
dd63e2496a05936670e52bce6aa02ec03cc99213
3,617,492
def scale(prob): """Scales a problem to lie in :math:`[-1, +1]^D`. :param prob: a :ref:`problem <problem>`. :return: a scaled :ref:`problem <problem>` with the ``limits`` and ``scale`` as additional keys. """ lims = limits(prob) mid = (lims[0] + lims[1])/2 scale = (lims[1] - lims[0])/2 ...
5e6cd771a9603dbdb50aecf9b5af9390cd6d1c98
3,617,493
import io def run_opt(mol, prog, meth, bas, mol_is_smiles=True): """ Runs a g09 or molpro job for INPUT: stoich - stoichiometry of molecule theory - theory energy should be listed or computed with basisset - basis set energy should be listed or computed with prog - program an energ...
613ec51ec002388a7fbb33c9d40810e5a63f686f
3,617,494
from sys import path def locate_package_directory(): """Identify directory of the package and its associated files.""" try: return path.abspath(path.dirname(__file__)) except Exception: message = ('The directory in which the package and its ' 'associated files are stored...
5fb54b1cc93e65b9d10397833d01c04ae7ff71c1
3,617,495
from typing import Union def rf_make_zeros_tile(num_cols: int, num_rows: int, cell_type: Union[str, CellType] = CellType.float64()) -> Column: """Create column of constant tiles of zero""" jfcn = RFContext.active().lookup('rf_make_zeros_tile') return Column(jfcn(num_cols, num_rows, _parse_cell_type(cell_t...
a0c6ca9ddaa78c4618115277f6193f851f94f753
3,617,496
def generateAndTrain(generationParameters, trainingParameters, resultsDir): """ Creates a random tree, creates its tuples and trains a tree from these tuples Return generatedTree, trainedTree, purity """ generatedObjectTree = simpleRandomBifurcatio...
2b3e292b84a096016fb5fe92d4505d0b49e19136
3,617,497
import requests def amac_person_bond_org_list() -> pd.DataFrame: """ 中国证券投资基金业协会-信息公示-从业人员信息-债券投资交易相关人员公示 https://human.amac.org.cn/web/org/personPublicity.html :return: 债券投资交易相关人员公示 :rtype: pandas.DataFrame """ url = "https://human.amac.org.cn/web/api/publicityAddress" params = {"rand...
6e1630e66cb640f853e6ed828301f081ed529a00
3,617,498
def check_line_comp_options(lam_gal,line_list,comp_options,edge_pad=10,verbose=True): """ Checks each entry in the complete (narrow, broad, outflow, absorption, and user) line list and ensures all necessary keywords are input. It also checks every line entry against the front-end component options (co...
eb7a1f003b119846e7aac8801cf745e9f7e01071
3,617,499