content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def export_ruptures_csv(ekey, dstore): """ :param ekey: export key, i.e. a pair (datastore key, fmt) :param dstore: datastore object """ oq = dstore['oqparam'] if 'scenario' in oq.calculation_mode: return [] dest = dstore.export_path('ruptures.csv') header = ('rupid multiplicity ...
b23f6b9fea092822d9700017bf92aab322577da6
3,634,800
import argparse def get_arguments(): """Parse all the arguments provided from the CLI. Returns: A list of parsed arguments. """ parser = argparse.ArgumentParser(description="DeepLabLFOV NetworkEv") parser.add_argument("--pred-path", type=str, default='', help="Path t...
12e8f214e5ef97e0a5a5e3aafaa8395a9e845601
3,634,801
def get_google_auth(state=None, token=None): """Helper function to create OAuth2Session object.""" if token: return requests_oauthlib.OAuth2Session(Auth.CLIENT_ID, token=token) if state: return requests_oauthlib.OAuth2Session(Auth.CLIENT_ID, state=state, ...
70f60828f6ad7c6a7658a217f98a22cfd07067ae
3,634,802
def _normalize_dataframe(dataframe, index): """Take a pandas DataFrame and count the element present in the given columns, return a hierarchical index on those columns """ #groupby the given keys, extract the same columns and count the element # then collapse them with a mean data = dataframe[in...
fdc49912f538694048560f1c1453714791a7c6e4
3,634,803
import json def load_network_from_checkpoint(checkpoint, model_json, input_shape=None): """Function to read the weights from checkpoint based on json description. Args: checkpoint: tensorflow checkpoint with trained model to verify model_json: path of json file with model description of ...
75c877c66c7397366c1f88aaa218487aa11c08d4
3,634,804
def get_indicator_plugin_manager(): """ Import all Hook classes that are in the plugins package and make this availables for be called from master sources """ pm = pluggy.PluginManager("indicator") pm.add_hookspecs(IndicatorSpec) for class_imported in indicatorPluginClasses: # noqa: F405 ...
610d21bab6f58a0b43539b5b382233b71937e764
3,634,805
def run(command, **kwargs): """Run and return the output of a command. Raise CalledProcessError on error. Pass in any kind of shell-executable line you like, with one or more commands, pipes, etc. Any kwargs will be shell-escaped and then subbed into the command using ``format()``:: >>> r...
5022e5cb1fe4863e1bd2293385eb8f13fe763e58
3,634,806
from datetime import datetime def to_date(string, format="%d/%m/%Y"): """Converts a string to datetime :param string: String containing the date. :type string: str :param format: The date format. Use %Y for year, %m for months and %d for daus, defaults to "%d/%m/%Y" :type format: str, optional ...
83fa8e8a0cdfae9546c7a83e55ddcf84ec667646
3,634,807
def invert_apply_grouping2(grouped_items, groupxs, dtype=None): """use only when ungrouping will be complete""" maxval = _max(list(map(_max, groupxs))) ungrouped_items = np.zeros((maxval + 1,), dtype=dtype) for itemgroup, ix_list in zip(grouped_items, groupxs): ungrouped_items[ix_list] = itemgro...
c1e7d46ddf57bc7bf1f7123fbd18061b63fb8a8d
3,634,808
def make_aware_assuming_local(dt): """ Just a wrapper for Django's method, which will takes a naive datetime, and makes it timezone aware, assuming the current timezone if none is passed (which it isn't from this wrapper function). It will also raise an exception if the passed datetime is already timezo...
3b9f142f11bc918a7faebcb0309f43dc6e9a5d2b
3,634,809
def pad_word_array(word_array, MAX_SEQUENCE_LENGTH, padding='pre', truncating='pre'): """Return a word array that is of a length MAX_SEQUENCE_LENGTH by truncating the original array or padding it Args: word_array: MAX_SEQUENCE_LENGTH: padding: truncating: Returns: """ ...
33d33284eb347f9f4b242932c42b7b8b68219135
3,634,810
def nbconvert(code): """Create Jupyter Notebook code Return dict in ipynb format Arguments: code -- code string separated by \\n """ cells = [] for cell in code.split("\n# <codecell>\n"): cells.append({ "cell_type": "code", "execution_count": None, ...
f7e895e107f07850652e762a4b382ec299e6d352
3,634,811
def add_box(width, height, depth): """ This function takes inputs and returns vertex and face arrays. no actual mesh data creation is done here. """ verts = [ (+1.0, +1.0, 0.0), (+1.0, -1.0, 0.0), (-1.0, -1.0, 0.0), (-1.0, +1.0, 0.0), (+1.0, +1.0, +2.0), ...
930dedbba8a1c11999d4ffdb98b0032bae743498
3,634,812
import time def pixmap(randoms, targets, rand_density, nside=256, gaialoc=None): """HEALPix map of useful quantities for a Legacy Surveys Data Release Parameters ---------- randoms : :class:`~numpy.ndarray` or `str` Catalog or file of randoms as made by :func:`select_randoms()` or :fu...
cda21bb679c84d1842ca1de675db0daf3ed79534
3,634,813
from typing import Union from typing import Callable from typing import Sequence from typing import Tuple def filter_keys(data: dict, keys: Union[Callable, Sequence], return_popped=False) -> Union[dict, Tuple[dict, dict]]: """ Filters keys from a given data dict Args: data: the di...
ecfd6985242d802401c25046745afade16ceec24
3,634,814
def beta_ion(T_rad, species): """Case-B photoionization coefficient. Parameters ---------- T_rad : float The radiation temperature. species : {'HI', 'HeI_21s', 'HeI_23s'} The relevant species. Returns ------- float Case-B photoionization coefficient in s\ :sup:`...
d82b37fcfd4852722260a7b4f6c92e58e8588b11
3,634,815
from pathlib import Path def load_template(template_path, template_name): """Loads a Jinja template from a given path and name Arguments: template_file {PathToDir: Path/String} template_name {Filename: String} Raises: IOError: This path does not exist """ if isinstance(te...
8e935d2f0ab41174237d4b7c803d5e16687d3bd0
3,634,816
def html(string): """Return inline html element.""" return RawInline('html', string)
980b409f769a38102398c81006dfd220b8865715
3,634,817
def mock_user_moira_lists(mocker): """Return a fake moira client""" mocked = mocker.patch("ui.utils.user_moira_lists") mocked.return_value = set() return mocked
8dedab7071deae4f1e5fa3ffc7b79149fc49e795
3,634,818
def translateAllIndex(text): """ This is the translator API Call this api passing a piece of text and get back the Swedish translation --- tags: - Translation API parameters: - name: text in: path type: string required: true description: The text r...
e7740738d112c64a6dfa30be7825e4db9b89f6f0
3,634,819
import os import logging def get_network_config(net_topology, ignore_env_vars=False, net_topology_file="network.yaml"): """Get network info from environment. Get network info from network.yaml, override the values if specific environment variables are set for the undercloud. T...
2fd063de58cabbfcd42be8efe30dd0a7fd4fd826
3,634,820
import imp import os def get_testbeds_dict(): """Return a dictionary containing mapping from dut hostname to testbed name.""" testbed = imp.load_source('testbed', os.path.join(SONIC_MGMT_DIR, 'tests/common/testbed.py')) testbeds_dict = testbed.TestbedInfo(TESTBED_FILE).testbed_topo return testbeds_dic...
f04902b0f599ed0c9acc6fec6da5883b3924652e
3,634,821
def AIHT(x, A, AT, m, M, thresh, proximalProjection=None): """ Accelerated Iterative Hard thresholding algorithm that keeps exactly M elements in each iteration. This algorithm includes an additional double overrelaxation step that significantly improves convergence speed without destroying any of the theoretical...
a4eed242acddf61059d3a77367a89d6966b16c63
3,634,822
def permutate(array: list, permutation: list): """ permutate a fixed array with a given permutation list Args: array: An array of random elements permutation: The permutation of the given array Returns: """ _swapped_array = [] _counter = 0 for i in permutation: ...
5b4f603c030276dcd78b6334ec00c901ca003c63
3,634,823
def has_collided_with_wall( width: int, height: int, segments: list[SnakeSegment] ) -> bool: """Return True if the snake has collided with a wall.""" head = segments[0] return ( head.x <= 1 or head.x > width - 3 or head.y < 1 or head.y >= height - 2 )
54f96b2a28f56e440f647316fe9e9e0dac356c34
3,634,824
def plot_heatmap_max_val(env, value): """ Generate heatmap showing maximum value at each state (not for n-armed bandit). """ if env.name == 'n_armed_bandit': print("Heatmap can only be generated for grid worlds.") return None if value.ndim == 1: value_max = np.reshape(v...
b39c43aa87bbae78b519e5f1042a63359a0c9f48
3,634,825
def separate_lines(lines,imshape): """ separate_lines(lines) Classifies left and right lines based on slope --------------------------------------------------------------------------- INPUT: lines: line points [[x1,y1,x2,y2]] OUTPUT: right{}: right line dictionary with the follo...
3d7ee319456202cc7478a97afc78922761a9e86e
3,634,826
def p_climo_one_season( seasonname, datafilenames, omit_files, varnames, fileout_template, time_units, calendar, dt, force_scalar_avg1, input_global_attributes, filerank={}, filetag={}, outseasons=None, queue1=None, lock1=None, comm1=None ): """cli...
dfd41e9cce28fbca51a4a838df831aa95c62b3af
3,634,827
def two_view_reconstruction_rotation_only(p1, p2, camera1, camera2, threshold): """Find rotation between two views from point correspondences. Args: p1, p2: lists points in the images camera1, camera2: Camera models threshold: reprojection error threshold Returns: rotation ...
25bc0038970eae23cf8443f4de1a7f89e5ff4f34
3,634,828
def state_lookup(): """Look up state from given zipcode. Once state is found, redirect to call_senators for forwarding. """ zip_digits = request.values.get('Digits', None) # NB: We don't do any error handling for a missing/erroneous zip code # in this sample application. You, gentle reader, sho...
13219025777e50422ab30902f0f3d35f7b73afed
3,634,829
def vmtkmeshtosurface(mesh, cleanoutput=1): """Convert a mesh to a surface by throwing out volume elements and (optionally) the relative points Args: mesh: Volumetric mesh. cleanoutput (bool): Remove unused points. Returns: vtkPolyData object. """ extractor = vmtkscripts.v...
78b311d8523b495b36be5f64767389bf3c71a13a
3,634,830
def time_delta_calc(contiguous_trajectory,order = 2): """Computes the time derivatives of a contiguous trajectory. INPUT contiguous_trajectory An array of space-time cordinates order The order up to which the time derivatives are calculated. If order=1, the velo...
17352f37f69e9947c0cea8e9fd7cf54ea3ff6e2e
3,634,831
def tasks_page(): """ Tasks and completions page """ return flask.render_template( 'tasks.html', config=g.project.config, project=g.project, version=label_studio.__version__, **find_editor_files() )
56656a8571e33fb40f3790a207faa2fccc7315a0
3,634,832
def outformathtml(pandasdf): """ change a few formating things to prettify and make it match """ pandas_table = pandasdf.to_html() pandas_table = pandas_table.replace(""" border="1" """, " ") pandas_table = pandas_table.replace("""<tr style="text-align: right;">\n <th></th>\n <th></th>...
5f8abf88a2aead4f095f52c1f49ab4ad609c04a5
3,634,833
def list_catalogs(**kwargs): """ Return the available Cone Search catalogs as a list of strings. These can be used for the ``catalog_db`` argument to :func:`conesearch`. Parameters ---------- cache : bool Use caching for VO Service database. Access to actual VO websites refe...
b539746edb4b6aa256bcbac3153b9a323bb41882
3,634,834
def rot_decode(data: str, n: int = 13) -> str: """Decode a ROT-encoded string that was shifted by `n` places.""" if not 1 <= n < 26: raise ValueError('n must be in range [1, 26)') return rot_encode(data, 26 - n)
f001f15684cc77e8ea52cf481626c6bdaf97c071
3,634,835
from datetime import datetime def searchlight(x, y, m=None, groups=None, cv=None, write=False, logger=None, permutations=0, random_state=42, **searchlight_args): """ Wrapper to launch searchlight :param x: Data :param y: labels :param m: mask :param groups: group labels :pa...
799f2496c0609050e6914576cfbdaba972320723
3,634,836
def codegen_reload_data(): """Parameters to codegen used to generate the fn_ioc_parser_v2 package""" reload_params = {"package": u"fn_ioc_parser_v2", "incident_fields": [], "action_fields": [], "function_params": [u"ioc_parser_v2_artifact_id", u"ioc_...
9c279e24b2e05adc5b1573393368216483307071
3,634,837
def Pattern2(s): """ Compute the correlator for this pattern: ↓ ↓ ↑ ↑ and symmetry-equivalent patterns """ res = 0.0 s = np.pad(s, ((0, 0), (2, 2), (2, 2))) L = s.shape[-1] for i in range(L-2): for j in range(L-2): res += s[1, i, j] * s[0, i+1,...
390cf6b8262f00d396235fb8ef5d4acc72d1df9e
3,634,838
import math def gauss(x, x0, sigma): """ This function returns a Gaussian distribution. """ return (1/(sigma*math.sqrt(2 * math.pi))) * np.exp(-(x - x0)**2 / (2 * sigma**2))
c4ebd141e68e59567b21355fb3b813c7f4ff914b
3,634,839
import math def distance(): """ Calculate the distance between two points. return: Distance. """ return lambda a, b: math.sqrt((a.x-b.x)*(a.x-b.x)+(a.y-b.y)*+(a.y-b.y)+(a.z-b.z)*(a.z-b.z))
ab3a14e7033afab66db7c283aefda745158bad65
3,634,840
import numpy def rational_sum(numerator, denominator, *argv): """Sum of rational numbers.""" if len(argv) < 2: gcd = numpy.gcd(numerator, denominator) num_out, den_out = numerator//gcd, denominator//gcd else: num_2 = argv[0] den_2 = argv[1] num_3 = numerator*den_2 +...
b34d01ea2bcfd072430501828401d5b492b2bae5
3,634,841
import time def nonce() -> str: """Return a nounce counter (monotonic clock). References: * https://support.kraken.com/hc/en-us/articles/360000906023-What-is-a-nonce- """ # pylint: disable=line-too-long return str(time.monotonic_ns())
fb6221fef4c2c8af66200c4c9da8f6253854b186
3,634,842
def fetch_single_equity(stock_code, start, end): """ 从本地数据库读取股票期间日线交易数据 注 -- 1. 除OHLCV外,还包括涨跌幅、成交额、换手率、流通市值、总市值、流通股本、总股本 2. 添加后复权价格,使用复权价在图中去除间隙断层 3. 使用bcolz格式写入时,由于涨跌幅存在负数,必须剔除该列 Parameters ---------- stock_code : str 要获取数据的股票代码 start_date : datetime-like 自...
04e63665fe9b05dfcca8387519d2a178d117acb5
3,634,843
import os import re def generate(): """Generates a dictionary of all the known CRC formats from: https://reveng.sourceforge.io/crc-catalogue/all.htm See pwnlib/data/crcsum.txt for more information. """ curdir, _ = os.path.split(__file__) path = os.path.join(curdir, '..', '..', 'data', 'crcsu...
bac4d66babe3e01c703fb6f10d78b85021c62f3b
3,634,844
import string def base62_encode(number): """Encode a number in base62 (all digits + a-z + A-Z).""" base62chars = string.digits + string.ascii_letters l = [] while number > 0: remainder = number % 62 number = number // 62 l.insert(0, base62chars[remainder]) return ''.join(l)...
b1f10fe69b6263d54f2e00a32b8260cbb3c42747
3,634,845
import json def handle_update(config_path): """ handle changes in globalConfig.json Args: config_path : path to globalConfig.json Returns: dictionary : schema_content (globalConfig.json) """ with open(config_path) as config_file: schema_content = json.load(config_file...
f51f52f9353339ba1cf080b10ad8f28691deefe9
3,634,846
from typing import Sequence from typing import Tuple import urllib def encode(s: Sequence[Tuple[str, str]], similar_to: str=None) -> str: """ Takes a list of (key, value) tuples and returns a urlencoded string. If similar_to is passed, the output is formatted similar to the provided urlencoded str...
c0153b77ec03708d54574062d15c7f81df59510b
3,634,847
def gis_ellipse_polygon(origin, a, b, orientation=0.0, complexity=128): """ Generate a polygon of an ellipse suitable for GIS applications. :param origin: the center of the ellipse (expected to be UTM, m) :param a: the a/semi-major axis length (expected to be UTM, m) :param b: the b/semi-minor axis...
48df0adbc7fd04508a6d3a8288c6b46fe9f9bdb0
3,634,848
def activate_lesson(): """ { "id": 51, "active": "A" } """ domain = request.get_json() return lesson_service.activate_lesson(domain)
a4e48ca2c8e65e9ff0e2fb95b61ef776573a9649
3,634,849
def split(labels, n_per_class=20, seed=0): """ Randomly split the training data. Parameters ---------- labels: array-like [n_nodes] The class labels n_per_class : int Number of samples per class seed: int Seed Returns ------- split_train: array-like [n_p...
69c7510f9be494afe7bb0c1492870c1d7c2d6694
3,634,850
from setfilter.setfilter import Setfilter def base(): """test Setfilter """ # build fixture # initialization center = np.array([0, 0, 0, 0.]) body = np.array([[1., 0., 0., 0.], [0., 1., 0., 0.], [0., 0., 1., 0.], [0., 0., 0., 1.]]) ...
b306d6425a6e1e329e0af006585c06be4585972e
3,634,851
def stack(*cons): """ Combine constraints into a large constaint by intersection. Parameters ---------- cons : [`selection.affine.constraints`_] A sequence of constraints. Returns ------- intersection : `selection.quasi_affine.constraints`_ Notes ----- Res...
8ddc52aa41c2ef4ec784067692efa1f3643a130c
3,634,852
def _create_poi_gdf( tags, polygon=None, north=None, south=None, east=None, west=None, timeout=180, memory=None, custom_settings=None, ): """ Create GeoDataFrame from POIs json returned by Overpass API. Parameters ---------- tags : dict Dict of tags used ...
4d88c0bb60ee836131bf5197c0caad17c0358f5b
3,634,853
def prepare_data(seqs, labels, maxlen=None, x_dim = 3, mapping=None, max_mapping=None): """Create the matrices from the datasets. This pad each sequence to the same length: the length of the longest sequence or maxlen. if maxlen is set, we will cut all sequence to this maximum length. This sw...
e2582ce07fa770b78bcd02dae26b345059c051c0
3,634,854
import types def _get_prediction_tensor( predictions_dict): """Returns prediction Tensor for a specific Estimators. Returns the prediction Tensor for some regression Estimators. Args: predictions_dict: Predictions dictionary. Returns: Predictions tensor, or None if none of the expected keys are...
0bd509d4021e0f0622b0cf685e5bf8682f47daa0
3,634,855
def gen_confirm_code(): """ Generate a new email confirmation code and return it """ return generate_uuid_readable(9)
992844a42886892cfa7eebc44e8efb61aa547725
3,634,856
from typing import List from typing import Dict from typing import cast import json from datetime import datetime def make_event_crawl_jobs(entries: List[BugoutSearchResult]) -> List[EventCrawlJob]: """ Create EventCrawlJob objects from bugout entries. """ crawl_job_by_hash: Dict[str, EventCrawlJob] ...
3aba2871df1cf35bb6337cbe8d8482437c3c91e0
3,634,857
def update_profile(): """ Update profile page """ form = UpdateProfileForm() # Update profile form if form.validate_on_submit(): # If form is submitted and validated if form.picture.data: # If picture is uploaded picture = save_picture(form.picture.data) # Save picture ...
ad2b427487cc63aa64068b86254c2d5b6b363c2c
3,634,858
def get_version_info(pe): """Return version information""" res = {} for fileinfo in pe.FileInfo: if fileinfo.Key == 'StringFileInfo': for st in fileinfo.StringTable: for entry in st.entries.items(): res[entry[0]] = entry[1] if fileinfo.Key == '...
8a01062de92cd4887f5cc7a292ffb644a701b43c
3,634,859
import torch def data_prepare(coord, feat, label, split='train', voxel_size=0.04, voxel_max=None, transform=None, shuffle_index=False, origin='min'): """ coord, feat, label - an entire cloud """ if transform: coord, feat, label = transform(coord, feat, label) if voxel_size: # voxelize ...
988a7068d0fc383f86c853b0593189633a87a53d
3,634,860
def add_wsl_blobs(blobs, im_scales, im_crops, roidb): """Add blobs needed for training Fast R-CNN style models.""" # Sample training RoIs from each image and append them to the blob lists for im_i, entry in enumerate(roidb): frcn_blobs = _sample_rois(entry, im_scales[im_i], im_crops[im_i], im_i) ...
296ae92af7656be15963508e1562afc5e62fb05b
3,634,861
def _right_branching(nodes): """ Parameters ---------- nodes: list[T], where T denotes NonTerminal or Terminal Returns ------- list[T], where T denotes NonTerminal or Terminal """ if len(nodes) == 2: return nodes lhs = nodes[0] # The left-most child node is head ind...
9bfa47daa95be30b7f9a9ada882e1fdceb1295e5
3,634,862
import random def random_swap(o_a, o_b): """ Randomly swap elements of two observation vectors and return new vectors. :param o_a: observation vector a :param o_b: observation vector b :return: shuffled vectors """ X, Y = [], [] tf = [True, False] for x, y in zip(o_a, o_b): ...
f243e91e5b281c682601fdb8df49bd7e6209274c
3,634,863
def parse_multiplicative(index): """Parse multiplicative expression.""" return parse_series( index, parse_unary, {token_kinds.star: expr_nodes.Mult, token_kinds.slash: expr_nodes.Div, token_kinds.mod: expr_nodes.Mod})
e314ca44735db31d00fe55268be8a7f69816db45
3,634,864
def return_factorized_dict(ls): """ ###### Factorize any list of values in a data frame using this neat function if your data has any NaN's it automatically marks it as -1 and returns that for NaN's Returns a dictionary mapping previous values with new values. """ factos = pd.unique(pd.factoriz...
7804f12f953eabcdc7bb398121500c2c8f2e278f
3,634,865
def _strip_asserts(source): """ Remove assert method calls from source code. Using RedBaron, replace some assert calls with print statements that print the actual value given in the asserts. Depending on the calls, the actual value can be the first or second argument. Parameters ----------...
4c484635328e9610bd07004cfba63acc4ae039d1
3,634,866
def _index_clusters(feat_mat, init_mat): """Creates a hierarchical binary tree till the top-level clusters supplied.""" cluster_feat = init_mat.T.dot(feat_mat) cluster_feat = cluster_feat.tocsr() cluster_feat = skprep.normalize(cluster_feat, "l2", axis=1) init_cluster = HierarchicalKMeans.gen( ...
f48e32507e298c4b089c9358c14727c4b8444ee5
3,634,867
from functools import reduce def gcd(numbers): """Return greatest common divisor of integer numbers. Using Euclid's algorithm. Examples -------- >>> gcd([4]) 4 >>> gcd([3, 6]) 3 >>> gcd([6, 7]) 1 """ def _gcd(a, b): """Return greatest common divisor of two i...
da7ae2a24649bc05e233533735baf850a37dcc5a
3,634,868
def normal_attention(tensor_base, tensor_to_attend, mask_for_tensor_base, mask_for_tensor_to_attend, similarity_method='inner', hn=100, use_pooling=False, pooling_method='max', reverse=False, scope=None): """ ...
93df4d084bb76cba4ab227928de6eb72e7f5af76
3,634,869
from bs4 import BeautifulSoup def getPageNum(html): """解析第一页网页,返回该用户的书评页数 """ soup=BeautifulSoup(html,'html.parser') paginator=soup.find('div','paginator') pas=paginator.findAll('a') num=int(pas[-2].text) return num
626a6f580e5634ba741d0794f6fc4c020aecabd0
3,634,870
async def get_user(api_management_name=None,resource_group_name=None,user_id=None,opts=None): """ Use this data source to access information about an existing API Management User. > This content is derived from https://github.com/terraform-providers/terraform-provider-azurerm/blob/master/website/docs/d/api...
c5bdf6aa7d0c69a59b9b8f6a93f63a9cba9a00cd
3,634,871
def makeCC_allpair(spikes, Begin, End, N_thred): """ 全てのCCをBegin~Endの間で計算する args: spikes: list型 Begin, End: int型 N_thred: 並列計算をするときに与えるスレッド数 return: X: ペアごとに計算したCC. X.shape = (ニューロンのペア数、CCの幅) index: ペアのニューロンの番号. index.shape = (ニューロンのペア数、2). index[i][0]は結合先ニューロン、in...
e9e5b9bd805251b4244ab89e6a1e11316617101d
3,634,872
def move_position(facility, cur_position, direction): """Move position from cur_position in the direction on facility.""" changes = DIRECTIONS[direction] doors = DIRECTION_TO_DOOR[direction] for cell in (doors, ROOM): next_position = [] for coordinate, change in zip(cur_position, changes...
64601f07378da56eaa03d896987491cd6f93182b
3,634,873
from typing import Callable import itertools from typing import OrderedDict import pprint def search_for_improvements( targets : [Exp], wf_solver : ModelCachingSolver, context : Context, examples : [{str:object}], cost_model : CostModel, stop_cal...
374a5a16f6ec4e69e983613aedbb298df1411cca
3,634,874
def down_sample(fft_vec, freq_ratio): """ Downsamples the provided data vector Parameters ---------- fft_vec : 1D complex numpy array Waveform that is already FFT shifted freq_ratio : float new sampling rate / old sampling rate (less than 1) Returns ------- ...
1ddfaa075c1d8bc68f9348d4f49807b61eceb60c
3,634,875
import os import json def main(args=None): """This is the Main Method. """ # loads setting file set parameters settings = os.path.join(get_package_share_directory('ros2_camera_publish'), "settings.json") with open(settings) as fp: content = json.l...
96e34fc4e4283fbe5f33050cf97969a6f1bba446
3,634,876
import torch def set_device(cuda: bool) -> int: """Set the device for computation. Args: cuda (bool): Determine whether to use GPU or not (if available). Returns: int: Index of a currently selected device, CPU or GPU. """ device = torch.device("cuda" if (torch.cuda.is_available() a...
f65fc5e38f14b8de78d14ac150ac14e5c8788e26
3,634,877
import torch def hsic_regular(x, y, sigma=None, use_cuda=True, to_numpy=False): """ """ Kxc = kernelmat(x, sigma) Kyc = kernelmat(y, sigma) KtK = torch.mul(Kxc, Kyc.t()) Pxy = torch.mean(KtK) return Pxy
551ed76c2f902b662ffe2c693da4474b6eb3958e
3,634,878
def random_correlation(size, n_factors, random_seed=None): """ Generates a random correlation matrix with 'size' lines and columns and 'n_factors' factors in the underlying structure of correlation. :param size: int. Size of the correlation matrix :param n_factors: int. number of factors in the corr...
92cd98bdf95e0ffef51c016c1c9ef05391c483dd
3,634,879
import urllib import requests def http_get_request(url, params, add_to_headers=None, _async=False): """ from 火币demo, get方法 :param url: :param params: :param add_to_headers: :return: """ headers = { 'Content-type': 'application/x-www-form-urlencoded', 'User-Agent...
b9274adeae67f9509fa5926d404866716b0d775e
3,634,880
def eigendecompose(S): """Eigendecompose the input matrix.""" eigvals, V = np.linalg.eig(S) return eigvals, V
0658d3b83d54a7435862b89d0a1fa3e82f4082fd
3,634,881
def _CreateSampleDirectoryCoverageData(builder='linux-code-coverage', modifier_id=0): """Returns a sample directory SummaryCoverageData for testing purpose. Note: only use this method if the exact values don't matter. """ return SummaryCoverageData.Create( server_ho...
3edebb67f0b4dafa837c14b99fd0b2b241da784d
3,634,882
def sched_time(update_time) -> int: """ Return interval between the current time and the update time in seconds """ current_time_ss = hhmm_to_seconds(current_time_hhmm()) update = hhmm_to_seconds(update_time) interval = update-current_time_ss return interval
5a57f591550a9f72dc7e9aa87a75c7aacf624cbe
3,634,883
def http_jsonrpc_post(hostname, port, uri, method, params): """Perform a plain HTTP JSON RPC post (for task farming)""" url = "http://%s:%s%s" % (hostname, port, uri) data = simplejson.dumps({ 'method': method, 'params': params, 'jsonrpc': '2.0', 'id': 1 }) req = urllib2.Request(url, data, {'...
8ac5e836564c4ddc2a277c4aea8bf0ff6b8836c2
3,634,884
def get_user_event(current_user, event_id): """ Query the user to find and return the event specified by the event Id :param event_id: Event Id :param current_user: User :return: """ user_event = User.get_by_id(current_user.id).events.filter_by(event_id=event_id).first() return user_even...
d65e3a65cb4400a9b4173b8ea4d45f6f94e0993c
3,634,885
def get_distances(scr_data_dict, distance_keys, data_centroid=None): """ @param scr_data_dict: @param distance_keys: @param data_centroid: Do not provide if calculating distances for establishing s thresholding @return: """ dataset_keys = scr_data_dict.keys() # Extracting dataset point o...
c0aec2de89bd7c7150d3f5fcbc3161f9f2d441c0
3,634,886
def compare_numeric_abundances(values_in_taxa_list_1, values_in_taxa_list_2): """Retun a Pandas Series with [abundance-in, abundance-out, p-value].""" mean1 = mean_ignore_nans(values_in_taxa_list_1) mean2 = mean_ignore_nans(values_in_taxa_list_2) keyslist1 = list(values_in_taxa_list_1.keys()) keysli...
f2e6e4326b12242a8493b82e37190a47d60b44e6
3,634,887
def parse_folder(folder, start_time=None, grepcmd=None, tmp_folder=None, force_grep=False): """ Args: grepcmd, tmp_folder, force_grep's default value should be the same with parse_single_log_with_pregrep Yields: [[yield], []]: nested yields """ def get_first_last_line(filepath): ...
b8d233ba8ad579d38e3353b841ea03d52bb83962
3,634,888
def search(request): """ search function which reads get data from a requests and uses it to find stuff in elasticsearch """ context = {"table": []} if "subject" in request.GET or "predicate" in request.GET or "object" in request.GET: es = elasticsearch.Elasticsearch(settings.ELASTICSEARCH) ...
85b1daba7d6a815f3e465b23ef369d439834de9c
3,634,889
import os def Write_data(data_name,parameters,metrics_name_list,length_input,metrics_mean_list,metrics_std_dev_list): """Writes the metrics of a given simulation in a datasheet in .txt format. Parameters ---------- data_name: string Desired name of data_sheet archive. metrics...
83478d88f45203b22373dfb42ae0e4a1338b2355
3,634,890
from typing import Dict def parse_measurement_lines(xml_root: Element) -> Dict[int, LineString]: """Parses the measurement line from the given xml root Args: xml_root (ET.ElementTree): root of the xml file Returns: measurement lines to use in the analysis (id, line) """ measureme...
8e7ff2a75189e8f6c1960f6849c1b63bc1ff4821
3,634,891
from typing import Any from typing import Optional def compute_and_apply_approximate_vocabulary( x: common_types.ConsistentTensorType, default_value: Any = -1, top_k: Optional[int] = None, num_oov_buckets: int = 0, vocab_filename: Optional[str] = None, weights: Optional[tf.Tensor] = None, ...
9662796984852ff255ca923e1048121427debfe6
3,634,892
import io def album_cover(): """Get the current song's album cover.""" cover = app.config["player"].album_cover() image = io.BytesIO(cover) if cover else "static/no_cover.jpg" return send_file(image, mimetype="image/jpeg")
3c2c7b9513bd36e49f27d4b58ca1408932402d72
3,634,893
def verify_bgp_community( tgen, addr_type, router, network, input_dict=None, vrf=None, bestpath=False, expected=True, ): """ API to veiryf BGP large community is attached in route for any given DUT by running "show bgp ipv4/6 {route address} json" command. Parameters ...
12190c76f9d2bae40c8c2859de9813d3c8af38a4
3,634,894
def create_new_filename(original_filename: str, user_response: str): """ Creates new file name depending on the users response :param original_filename: str :param user_response: str :return: str | new filename """ if user_response == "1": time = str(today.time())[:8].repla...
789bf9f73b4647c534859a2ae97b9ec806b02d1c
3,634,895
from typing import Optional import os from pathlib import Path import shutil def get_maestral_command_path() -> str: """ Returns the path to the maestral executable. May be an empty string if the executable cannot be found. """ try: dist_files = files("maestral") except PackageNotFoun...
6291cc4da5771d60d3fdfbe3abceb4c76733fef6
3,634,896
from typing import OrderedDict def genertate_info_tree(traces, trace_events, level="module"): """ """ assert level in ["module", "operator", "mixed"] tree = OrderedDict() for trace in traces: path, module = trace # unwrap all of the events, in case model is called multiple times ...
cc885b41df2d2ecf0484c55a07f9b8ef381263d8
3,634,897
def interpolate(x, ratio): """Interpolate data in time domain. This is used to compensate the resolution reduction in downsampling of a CNN. Args: x: (batch_size, time_steps, classes_num) ratio: int, ratio to interpolate Returns: upsampled: (batch_size, time_steps * ratio, classes_num...
54ceb6aee15de3c775d3be93bbc48422dc542641
3,634,898
from astroquery.mast import MastClass def _resolve_object(target): """Ask MAST to resolve an object string to a set of coordinates.""" # Note: `_resolve_object` was renamed `resolve_object` in astroquery 0.3.10 (2019) return MastClass().resolve_object(target)
bf9c0bb3a09fac1622cc107cf3f9532888b3a4f9
3,634,899