content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import os def RunTransformix(command): """Run the transfomix transformation. You must be able to call transformix from your command shell to use this. You must also have your transformation parameter files set before running (see transformix parameter files). Parameters ---------- command: string Sent to the...
01012ed8ff7d8fe807fc6dd6aa78e613868093ac
3,613,000
import time def timer(fcn): """Returns the runtime in ms of the function fcn""" def wrapper(*args, **kwargs): t0 = time.time_ns() res = fcn(*args, **kwargs) t = time.time_ns() - t0 print(f"{fcn.__name__}: {round(t * 10**-6, 1)} 'ms'") return res return wrapper
9a76c7222f9f427abdde9194535acdf9880a2807
3,613,001
def read_landmarks(f_landmarks): """ Reads file containing landmarks for image list. Specifically, <image name> x1 y1 ... xK yK is expected format. :param f_landmarks: text file with image list and corresponding landmarks :return: landmarks as type dictionary. """ landmarks_lut = {} ...
9c4bf6b405f4fb49ace8badb4b3151cc457bbf84
3,613,002
def parse_char(ch): """ 'A' or '\x41' or '0x41' or '41' '\x00' or '0x00' or '00' """ if ch is None: return None if len(ch) == 1: return ord(ch) if ch[0:2] in ("0x", "\\x"): ch = ch[2:] if not ch: raise ValueError("Empty char") if len(ch) > 2: r...
b3726d00839caf92b64d976ed447f8c1824efb9f
3,613,003
def validate_parameters(self, parameters, task_id=None): """Validate parameters generated by the parameter parsing task All validation should be done here - are there data restrictions? Combinations that aren't allowed? etc. Returns: parameter dict with all keyword args required to load data. ...
98e8e67d192dcc791c6585f76410bc516d88c4ae
3,613,004
def Get_Entry(): """ get the entry number of customers at every minute """ df['timestamp'] = df.index.time time_spent = df.groupby(['weekday','customer_no'], as_index=False).agg({'timestamp':'min'}) time_spent.head() entry = time_spent.groupby('timestamp').count() //5 entry['timestamp'] ...
e1760346b8b1852cfa0cb1a312d028d0a991b013
3,613,005
import copy def load_detections_into_dataset( dataset_name, dataset_dicts, det_file, top_k_per_obj=1, score_thr=0.0, train_objs=None, top_k_per_im=None, ): """Load test detections into the dataset. Args: dataset_name (str): dataset_dicts (list[dict]): annotations i...
baae94a1a5c36f916a7319dcb1c9342cbca03cd9
3,613,006
def revert_version(request, revision_id): """Roll back the object saved in a Version to the previous Version""" referer = request.META.get("HTTP_REFERER", "/") revision_obj = Revision.objects.get(pk=revision_id) revision_obj.revert() # revert all associated objects too msg = "Rolled back revision %...
70e7d541b2c700a88f0b718999acd4ca847b53a8
3,613,007
from typing import Optional from typing import Tuple def get_or_create_permission( session: Session, name: str, description: Optional[str] = None ) -> Tuple[Optional[Permission], bool]: """Get a permission or create it if it doesn't already exist. Returns: (permission, is_new) tuple """ p...
4a837f3ca9f5942368d75572b83de4f05e6d2c70
3,613,008
from typing import Any def get_user_me( db: Session = Depends(deps.get_db), current_user: models.User = Depends( deps.get_current_active_user ), ) -> Any: """ Get current user. """ if current_user is None: raise exceptions.get_user_exception() role = ( None ...
af61dc80820aaf2ce46b636b537413680976a6b0
3,613,009
import os import time def get_temp_dir(request): """ Action: If temporary directory does not exist, it is created. Then the temporary directory is returned Returns: Temporary Directory """ if request.session.get('tmp_dir', None) is None: tmp = os.path.join(gettempdir(), '{}'.format(hash(...
b4429066b9ffcdd60ed7b2a8398de086a16d18b8
3,613,010
import json def trigger_oauth_expires_test(limit): """ Test data for IFTTT trigger bunq_oauth_expires """ result = [{ "created_at": "2018-01-05T11:25:15+00:00", "expires_at": "2018-01-05T11:25:15+00:00", "meta": { "id": "1", "timestamp": "1515151515" } ...
6f0bf5ed1f2749bf67d9068ac9eb85cc6fd86e17
3,613,011
def translate_subset_type(subset_type): """Maps subset shortcut to full name. Args: subset_type (str): Subset shortcut. Returns: str: Subset full name. """ if subset_type == 'max': model = 'best' elif subset_type == 'random': model = 'random' elif subset_typ...
ff40e230c403818b55897ff96bee131d0c687096
3,613,012
def mid2aud(n_mid): """Return an audio segment from a mid file and build a wav meanwhile""" m2a.FluidSynth().midi_to_audio(mid_dir + n_mid + '.mid', wav_dir + n_mid + '.wav') seg = AudioSegment.from_file(wav_dir + n_mid + '.wav') return seg
f3573736541125dbb75439c038371e796a05ea02
3,613,013
import json def lambda_handler(event, context): """ expected event: { "body-json" : {}, "params" : { "path" : {}, "querystring" : { "game" : "string" }, "header" : {} }, "stage-variables" : { } """ if type(event) is not dict: ...
2e20e4bd02bba3de2b3dc416bad58243357120a4
3,613,014
def open_file_on_worker(view): """Open the file on the worker process""" service = cli.get_service() if not service: return None service.open_on_worker(view.file_name(), view.substr(sublime.Region(0, view.size())))
4260a77791932ed95b1851411c06b06ccc7ccccf
3,613,015
def solar_offset(geom: Geometry, precision: str = "h") -> timedelta: """ Given a geometry compute offset to add to UTC timestamp to get solar day right. This only work when geometry is "local enough". :param precision: one of ``'h'`` or ``'s'``, defaults to hour precision """ lon = mid_longitud...
afab5f060516584866a9c0d1c954ecadf4aa850b
3,613,016
def bgr_to_y(image): """Convert a bgr image to grayscale. :param image: an image denoted by a numpy array, which is HWC, and channels are in gbr :type image: np.array :return: the grayscale image :rtype: np.array (with dtype np.float32), in range 0~255 """ image = image.astype(np.float32) /...
d556f3e02a434be9283615e9ac833e9368d65df5
3,613,017
import email def _create_email( to_field="to_user@test1.com", from_field="from_user@test2.com", subject="This is a test email", body="Almost empty text message", attachment=None, maintype=None, subtype=None, ): """ Builds and returns an ``email.message.EmailMessage`` instance w...
7a918c4b49b7f68707e88a329bdde52eced01b46
3,613,018
def by_user_recipe_id(user_id, recipe_id): """ Get Recipe owned by a user """ session = query_session.get_session() return session.query(Recipe).filter(Recipe.id == recipe_id) \ .filter(Recipe.user_id == user_id) \ .first()
26c6425982d62cd92f50a43f8690e81aef40b324
3,613,019
def Z_score(data): """ Z_score标准化 :param data: :return: """ x, y, z = data.shape def z_score(data): return (data - np.mean(data)) / np.maximum(np.std(data), 1 / 256) for i in range(z): data[:, :, i] = z_score(data[:, :, i]) return data
97c16a46209cee792e6fbfa6688b70d6b06e495f
3,613,020
def torch_vad(sig, winLen=400, winSht=160, ener_thres=5.7, mean_scale=0.5, prop_thres=0.12, frm_context=2, twice_log_max_signed_int16=20.794354380710768, eps=1.19209e-07): """ Equivalent to KALDI's energy-based VAD implementation (https://github.com/kaldi-asr/kaldi/...
85b935c6842f82f411c7d1a0c967d8753cb38b29
3,613,021
async def create_sync_payload(dc, key): """Converts dictionary to JSON, encrypts it with provided public key (PEM) and returns it as a Base64-encoded string. """ return await _run_async(_create_sync_payload, dc, key)
dec64b2a8f2bb81a6cc82a4c419adbf0f21bca3e
3,613,022
import argparse def arg_setup(): """Sets up an argument parser and returns the arguments.""" parser = argparse.ArgumentParser( description="run simulations of agents with wishful thinking") parser.add_argument('scenario', help="""the scenario to use (currently: sequenc...
4a28bb0fa8925350d928b610b9b6bb62798aaf74
3,613,023
def graph_to_xarray(graph): """ Convert a hetnetpy.hetnet.Graph to an xarray.Dataset """ data_vars = dict() for metaedge in graph.metagraph.get_edges(exclude_inverts=True): data_array = metaedge_to_data_array(graph, metaedge) name = metaedge.get_abbrev() data_vars[name] = dat...
3540f30651bb5b98dc18eb793574c7c5259d603c
3,613,024
def get_shared_segments(poly1, poly2, bool_ret=False): """Returns the line segments in common to both polygons. Parameters ---------- poly1 : libpysal.cg.Polygon A Polygon. poly2 : libpysal.cg.Polygon A Polygon. bool_ret : bool Return only a ``bool``. Default is ``False`...
7e3305b7d5c9bbade0a86d32c060c2f54bd05992
3,613,025
def get_latest_resources_asset(name): """ Searches through hazm's releases and find latest release that contains resources. Parameters ---------- name: str The resource name Returns ------- asset: GitReleaseAsset The resources asset """ g = Github() repo...
ef9b3f450441cf2b6527b9ad6241cae59d3e472b
3,613,026
def conv1x1_1bit(in_channels, out_channels, stride=1, groups=1, bias=False, binarized=False): """ Convolution 1x1 layer with binarization. Parameters: ---------- in_channels : int Number of input channels. ...
a949c3b86f1331492e183528628a6ed2e13ff189
3,613,027
def get_vec_by_query(text): """提取文本向量 """ token_ids, segment_ids = tokenizer.encode(text, max_length=maxlen) # print("token_ids={},segment_ids={}".format(token_ids, segment_ids)) vec = encoder.predict([[token_ids], [segment_ids]])[0] # print('vec size={}, element={}'.format(len(vec), vec[-1])) ...
0f6f531344a79e169482975ebf35ac43304bcfad
3,613,028
def serving_input_receiver_fn(): """An input function for TensorFlow Serving.""" def _preprocess_image(image_bytes): """Preprocess a single raw image.""" image = tf.image.decode_jpeg(image_bytes, channels=IMG_CHANNEL) image.set_shape((None, None, IMG_CHANNEL)) image = tf.image.r...
47c6cc3056455a68be484fac114889943d04debe
3,613,029
def _process_optimization_results(results, results_arguments): """Expand the solutions back to the original problems. Args: results (list): list of dictionaries with the harmonized results objects. results_arguments (list): each element is a dictionary supplying the star...
64a74f22d5391c88fb0fdccc3c7d610c4e67f928
3,613,030
def is_valid_continuous_partition_object(partition_object): """Tests whether a given object is a valid continuous partition object. :param partition_object: The partition_object to evaluate :return: Boolean """ if (partition_object is None) or ("weights" not in partition_object) or ("bins" not in pa...
b1576c909a9e09db35362aff1e00ef69cf33be02
3,613,031
def get( hostname, refresh_key, authorization_host, org_id, sddc_id, tier1, nat, verify_ssl=True, cert=None, cursor=None, page_size=None, sort_by=None, sort_ascending=None, ): """ Retrieves nat rules for Given SDDC CLI Example: .. code-block:: bash ...
2fac63ca341a3f6589444daeddad79ba99c832aa
3,613,032
from typing import Optional from typing import Callable def add_fiber_array( component: Component, grating_coupler: Component = grating_coupler_te, gc_port_name: str = "W0", component_name: Optional[str] = None, taper_factory: Callable = taper, taper_length: float = 10.0, get_route_factory...
de2a99ca12f28debc321a855b8adb894ba457672
3,613,033
def run(prefix, items, timestamp, delta, output_path=None, creation_dir=None, parent_dir_name="logs", silent=False, interactive=False): """ collects log items and creates an archive with all collected items. items is a list of instances of 'Item' subclasses (see the collectables submodule). timestamp and de...
01368171994e097d7034bc9b31bd0c433d46d5e8
3,613,034
def get_instruments(instruments, level): """Returns a list of themis instruments for L2 data""" if level == 'l1': instr_list = ['bau', 'eff', 'efp', 'efw', 'esa', 'fbk', 'fff_16', 'fff_32', 'fff_64', 'ffp_16', 'ffp_32', 'ffp_64', 'ffw_16', 'ffw_32', 'ffw_64', ...
b797856b35f72eb34fa2d23a2e8d5ff7ade77516
3,613,035
def add_release( target_name, target_resource_group, remote_url=None, remote_branch=None, remote_access_token=None, vsts_account_name=None, vsts_project_name=None, registry_resource_id=None, registry_name=None): """ Creates a build definiti...
9365757705cd2244b754d9a3d31e71652e3e0d07
3,613,036
def connect(): """initialize a connection to a mysql db on a local host server """ try: return mysql.connect( host="127.0.0.1", port="3306", user="root", password=ROOT_PASSWORD , auth_plugin='mysql_native_password', database="sales"...
e44a386670720922488a6ee2556ac13966e90d82
3,613,037
def scatter(x, y, z, color=default_color, size=default_size, size_selected=default_size_selected, color_selected=default_color_selected, marker="diamond", selection=None, grow_limits=True, **kwargs): """Plots many markers/symbols in 3d :param x: {x} :param y: {y} :pa...
872d90ff1dfffbe80db8eb53af1469f96297675f
3,613,038
def create_openapi_spec(app: falcon.API) -> APISpec: """Creates an OpenAPI Spec for the Sustainerds API""" spec = APISpec( title="Sustainerds API", version="1.0.0", openapi_version="3.0.0", plugins=[MarshmallowPlugin()], ) return spec
1b5db71cc6266fd108a5138df559802ccae92dda
3,613,039
def trigger_oauth_expires_delete(identity): """ Delete a specific trigger identity for trigger bunq_oauth_expires """ # We don't store trigger identities, so this call can be ignored return ""
355084d71efc7789335b7f0ca15e90165a2b5e26
3,613,040
def bibTex_abs_format_export_post(): """ :return: """ results, status = export_post(request, 'BibTex Abs') if status == 200: maxauthor, keyformat, authorcutoff, journalformat = export_post_extras(request, 'BibTex Abs') return return_bibTex_format_export(solr_data=results, include_ab...
8d6a37504c8c5a51af2db18ce210e15f1d245b83
3,613,041
def ligands_rmsd_calculator(pdb_target, pdb_reference, resname="GRW"): """ :param pdb_target: problem pdb file :param pdb_reference: reference pdb file :param write2report: if True export results in a file :param write2pdb: pdb file with the result of the superposition between "pdb_target" and "pdb...
9cd18c0d6413fc18a6d558cdea4f98af3259acdf
3,613,042
def knn_points_idx(p1, p2, K, sorted=False, version=-1): """ K-Nearest neighbors on point clouds. Args: p1: Tensor of shape (N, P1, D) giving a batch of point clouds, each containing P1 points of dimension D. p2: Tensor of shape (N, P2, D) giving a batch of point clouds, each ...
8243f48bbe2c8c0c54f88d9fe04e6d541584e7be
3,613,043
def modularity_individual(individual, graph: igraph.Graph): """ Decode an individual into a community membership vector and calculates the modularity of the individual community set. """ members = decode(individual) try: return graph.modularity(members) except igraph.InternalError as...
9f9b8a341ad7012ac77d89316d01d74f8fa2f75a
3,613,044
def api_get_challenge_detail(challengeID: int): """ 查询挑战详情 { "name":"名称", "id":ID, "description":描述, "level":等级, "hasFinished":是否完成 "problemsetList":[ { "name":"名称", "hasFinished":"是否完成", "id":"ID" ...
149c746dfcb1b593cea078dfa594557b54e6633a
3,613,045
def superop2chi(superop: np.ndarray) -> np.ndarray: """ Converts a superoperator into a list of Kraus operators. Operators with small norm may be excluded. :param superop: a dim**2 by dim**2 superoperator :return: a dim**2 by dim**2 process matrix """ return kraus2chi(superop2kraus(superop...
ab7c60b927225ba002011d8b6f02d5d82208c7cb
3,613,046
def is_instation(stmt): """Check whether the statement is an 'instance' or 'instance-list' definition """ return is_instance(stmt) or is_instance_list(stmt)
172d592c7bf2beca1a46cfa4b86206a1824032e3
3,613,047
def check_multigene(overlaps, min_overlap_bp=0, min_query_overlap=0, min_gene_overlap=.5): """ overlaps is a list of: (gene, overlap_bp, overlap_gene_ratio, overlap_query_ratio) """ if all(x[1]>=min_overlap_bp and x[2]>=min_gene_overlap and x[3]>=min_query_overlap for x in overlaps): new_name = ...
5f7c3ba7231939e2e54ce236a79025952d5e9a84
3,613,048
def unpickle(): """Unpickle the bot token""" with open('token.pickle', 'rb') as file: token = pik(file) return token
3246a7da2d7257fa35cc6de78deabc726a1155e8
3,613,049
def calcInertiaTensor(coords): """"Calculate inertia tensor from coords""" coords = getCoords(coords) center = calcCenter(coords) coords = coords - center return dot(coords.transpose(), coords)
a16376078bb85c8e18f455df08d741b07171e287
3,613,050
from typing import Optional from typing import Set from typing import Callable def auto_eq(only: Optional[Set[str]] = None, exclude: Optional[Callable[[str], bool]] = None): """ Decorator. Auto-adds a __hash__ function by hashing its attributes. :param only: Only include these attributes :param exclude: Exclude ...
0278531c2b572754581310629f4c805e06cd8ee2
3,613,051
import tempfile def AddLoggingParent(android_manifest, logging_parent_value): """Add logging parent as an additional <meta-data> tag. Args: android_manifest: A string representing AndroidManifest.xml logging_parent_value: A string representing the logging parent value. Raises: RuntimeError: I...
6cd03b7dae970ea58a8493f3047ec77748724776
3,613,052
def replace_nans_binmean(d, by, aggreagation="mean"): """"Replace each NaN value in `d` by the mean in each bin when grouping by `by`.""" return d.where(~np.isnan(d), mean_per_bin(d, by, aggreagation=aggreagation))
4d24e58c04ee44d90a5e9820fa942cf244c28059
3,613,053
from typing import Sequence def repeatAndVarySequence(seq, poss, channels, names, args, iters): """ Repeat a sequence and vary part(s) of it. Returns a new sequence. Given N specifications of M steps, N parameters are varied in M steps. Args: seq (Sequence): The sequence to be repeated. ...
481f8f2765398362757f88fa10a42dd81066e252
3,613,054
def conv_bn(inp, oup, stride): """ :param inp: :param oup: :param stride: :return: """ return nn.Sequential( nn.Conv2d(inp, oup, 3, stride, 1, bias=False), nn.BatchNorm2d(oup), #nn.ReLU6(inplace=True), nn.ReLU(inplace=True) )
cbe7326aba5d2d7508deebfcd531a5c2d593ce3e
3,613,055
from re import T def normalize(x, axis=-1, mean=None, variance=None, epsilon=1e-5): """Normalizes an array by subtracting mean and dividing by sqrt(var).""" if mean is None: mean = T.mean(x, axis, keepdims=True) if variance is None: # this definition is traditionally seen as less accurate ...
2804df3370d92d32c13a87aaf647cd2a951f9087
3,613,056
def _get_restart_standard_names(restart_properties: RestartProperties = None): """Return a list of variable names needed for a smooth restart. By default uses restart_properties from RESTART_PROPERTIES.""" if restart_properties is None: restart_properties = RESTART_PROPERTIES return_dict = {} ...
8e45f22c7305160e29799a9480a9a35a9da81c82
3,613,057
import json async def portfolio_style_report(folio_id, request, *,factor_code=""): """ :param folio_id: :param request: :return: { 'T': 290, 'rolling_reg': [[{ 'month': 7, 'day': 25, 'year': 2017 }, { 'crisk': [0.2244239767675...
658ef0dd99fcdf4cad6652d3404bf43dae86df41
3,613,058
def flatten(l, types=(list, )): """ Given a list/tuple that potentially contains nested lists/tuples of arbitrary nesting, flatten into a single dimension. In other words, turn [(5, 6, [8, 3]), 2, [2, 1, (3, 4)]] into [5, 6, 8, 3, 2, 2, 1, 3, 4] This is safe to call on something not a list/tuple -...
5bdffb984fcd2614e4e71f19353b3d277dea368e
3,613,059
def bitwise_or(rasters, extent_type="FirstOf", cellsize_type="FirstOf", astype=None): """ The BitwiseOr operation The arguments for this function are as follows: :param rasters: array of rasters. If a scalar is needed for the operation, the scalar can be a double or string :param extent_type: one ...
ecaf7522c8943259d9b4d43b446cf77762c8de83
3,613,060
import scipy import math def Theory_Algebraic(N,Kappa,d) : """ Theoretical approximation for the algebraic connectivity of periodic RGGs Parameters ----------- N : int Network size Kappa : float Expected mean degree of the ensemble d: int Dimension of the embedding space Returns --------- Mu...
3229d3bc0990207d70464ef33cf37f51debcfd00
3,613,061
def define_passes(ext_val): """ Overwrite function based depending on enum flag. :param ext_val: :return: """ if ext_val in [EXTENSIONS.CGINC, EXTENSIONS.GLSLINC, EXTENSIONS.SHADER]: return format_write_cginc_first elif ext_val in [EXTENSIONS.CS]: return format_write_cs_first...
3a1eba7e9983e60fcce74e243ce20e58dcea4e8b
3,613,062
def get_path_prefix(path): """ gets path_prefixe given path """ temp_path=list(filter(None, path.split("/"))) j=0 path_prefix=[] for node in temp_path: path_prefix.append([node]) return path_prefix
728c019d842c3b5bf7c6f6b8cebf13a1ad90bd41
3,613,063
from typing import Any def test_pull_request_exists(monkeypatch: MonkeyPatch, branch: str) -> None: """It matches the branch in the process output.""" def stub(*args: Any, **kwargs: Any) -> Any: return pretend.stub(stdout="topic") with monkeypatch.context() as m: m.setattr("subprocess.ru...
2dc808e1127a7ec2fe4ca7506528e5a4819ae06a
3,613,064
def classify_image(interpreter, image, top_k=1): """ return a sorted array of classification results """ set_input_tensor(interpreter, image) interpreter.invoke() output_details = interpreter.get_output_details()[0] output = np.squeeze(interpreter.get_tensor(output_details['index'])) # if model...
212968b55e48517fec376b247cd09439545e0e14
3,613,065
import math def occupancy_to_color(occupancy): """ Return corresponding color from blue to red spectrum """ # color = [255*(1-isoval), 255*(1-isoval), 255] # white to blue # color = [255*isoval, 0, 255*(1-isoval)] # blue to red color = "gray" + str(int(math.floor((1-occupancy)*100))).zfill(2) if(color == "g...
838a6025c473b51dab6c38c28f70ba7bafed3071
3,613,066
from typing import List from typing import Tuple from typing import Dict def _simplify_cnots_triplets( cnots: List[Tuple[int, int]], flip_control_and_target: bool ) -> Tuple[bool, List[Tuple[int, int]]]: """Simplifies CNOT pairs according to equation 11 of [4]. CNOT(i, j) @ CNOT(j, k) == CNOT(j, k) @ CNO...
bd624a19336b636adcbc852cd912de6dd0290167
3,613,067
def reshape(a): """Combine the last two dimensions of a numpy array""" all_head_size = a.shape[-2] * a.shape[-1] new_shape = a.shape[:-2] + (all_head_size,) return a.reshape(new_shape)
7381657c14b8b9245af2d85c1d1b7a0f5d40fff8
3,613,068
from typing import OrderedDict import os import json def load_in_autotrack(trackDirPath, SCALE_FACTOR=1.0, TRACK_FILE_EXT="json"): """Load an predicted track""" trackDict = OrderedDict() frameDict = OrderedDict() #count = 0 for x in os.listdir(trackDirPath): path = os.path.join(trackDir...
95b37a105c7862fb24f76e5aba3a2fb5d36a9bd6
3,613,069
import torch def encode_selection(selection: SelectionNode, db: Database) -> EncodedSelection: """ Encoding is a vector of: ------------------------------------------------------------------------------- | *col | *rel | *hist | *freq | onehot dtype | op one hot | operand encoding | ...
831aecc8737a304f5f3375c39ca3c1834cc90559
3,613,070
def dict_keys(this): """ Return PyIterable for Dict keys. """ return mkiterable(this.getvalue().keys())
1e4575f109019e5314d53075987fcd1cf85c426d
3,613,071
def EMA2(df, n): """ 线性加权移动平均 WMA Args: df (pandas.DataFrame): Dataframe格式的K线序列 n (int): 线性加权移动平均的周期 Returns: pandas.DataFrame: 返回的DataFrame包含1列, 是"ema2", 代表计算出来的线性加权移动平均线 Example:: # 获取 CFFEX.IF1903 合约的线性加权移动平均线 from tqsdk import TqApi, TqSim fro...
d658d9813a55e26f22fb1dcb0490c94edee1b7d4
3,613,072
import random def pusher(obj_scale=None, obj_mass=None, obj_damping=None, object_pos=(0.45, -0.05, -0.275), distr_scale=None, axisangle=(0, 0, 1, 1.5), distr_mass=None, distr_damping=None, goal_pos=(0.45, -0.05, -0.3230), ...
10db02142bfdbf95a9c548e6e98bb1ece0f393ca
3,613,073
def create_from_pairs(pairs): """ Build graph from `pairs` of words. Accumulate weight for the edges that appear multiple time """ DG = nx.DiGraph() for (n1, n2, w) in pairs: if DG.has_edge(n1, n2): DG.edge[n1][n2]['weight'] = w else: DG.add_edge(n1, n2, {...
8cd39dcbfabbddfc737e533afa3ec72c2d64095f
3,613,074
import tqdm def loop(env, mind, interpreter=None, n_episodes=1, max_steps=-1, policy='deterministic', name="", debug_mode=False, render_mode=False, train_mode=True, verbose=2, callbacks=None, **kwargs): """Conduct series of plies. Args: env (Environment): Environment to take actions in. ...
78e07066e58ab3c60cbb94af23a9f2a4a6692891
3,613,075
def get_panelist_by_id(panelist_id: int): """Retrieve a panelist based on their ID""" return panelists.get_panelist_by_id(panelist_id, database_connection)
88ea2e420390fdf4972c1a8010905d8a7f33ff50
3,613,076
from apps.jsonapp import JSONApp def main_json(config, in_metadata, out_metadata): """ Alternative main function ------------- This function launches the app using configuration written in two json files: config.json and input_metadata.json. """ # 1. Instantiate and launch the App pri...
9306c9877f0558f04b31693c0f1bd63422716b93
3,613,077
def new_figure_manager(*args, **kwargs): """Create a new figure manager instance.""" _warn_if_gui_out_of_main_thread() return _backend_mod.new_figure_manager(*args, **kwargs)
bbef99f717cf2cb18622279c4b968d098505e75d
3,613,078
def given(distribution: Series, **givens) -> Series: """ Condition the distribution on given and/or not-given values of the variables. :param distribution: The probability distribution to condition e.g. P(A,B,C,D). :param givens: Names and values of variables to condition o...
2925671206004d4a3fc3fd4a4b782ff894a71cff
3,613,079
def cosine_similiarity(vec_left, vec_right): """ 余弦相似度 :param vec_left: :param vec_right: :return: """ num = np.dot(vec_left, vec_right) denom = np.linalg.norm(vec_left) * np.linalg.norm(vec_right) cos = -1 if denom == 0 else num / denom return cos
a3eb01f3739f1faf4d1dd84c4260a755224e19a9
3,613,080
def albedo_diffuse_bubbly_ice(wavelengths, a, f, ni="p2016"): """compute diffuse albedo of pure ice without taking into account for the surface reflectance and using the assymptotic radiative transfer theory :param a: bubble radius (m) :param f: is bubble fractional volume w/r to total volume (m3/m3)....
91bf8a741c8c731fdc9113baa0372bac59f2d28a
3,613,081
import argparse def parse_arguments(): """ Parse file arguments """ parser = argparse.ArgumentParser(description="Predict class for a given input image") parser.add_argument('image_url', help="url for a test image") return parser.parse_args()
d3f970c14474daa659c78542e709feb0f1e64794
3,613,082
def reflectance(*reference): """Reference to a factbase resource describing reflectance. Parameters ---------- *reference : :obj:`str` Keys pointing to the metadata object describing the resource within the reflectance category in the layout file of a factbase. Returns ------- :obj:`Cube...
782e169afa080cbccaf83863869cda84a9fa27d6
3,613,083
import six def get_validator_or_converter(name): """ Get a validator or converter by name """ if name == 'unicode': return six.text_type try: v = get_validator(name) return v except UnknownValidator: pass raise SchemingException('validator/converter not foun...
1635469ff793f98f01665af53c246c9b0af63801
3,613,084
def _d_sellmeier(b, c, lambda0): """ Calculate the first derivative (wrt wavelength) of the Sellmeier equation. This is a private method. Args: b : array of three Sellmeier Coefficients [--] c : array of three Sellmeier Coefficients [microns**2] lambda0 : wavelength in vacuum...
1c3431f8c6b5ae7cd95e5f7ca74ff09004f5a6d6
3,613,085
def is_running(): """ Check JDB process state """ return jdb_process is not None and jdb_process.poll() is None
aeafa3ca9f925e91eedb9e327f3389134b5ac974
3,613,086
def get_non_us_city(location: str) -> str: """ Deals with two types of non-US locations: "New Delhi (India)" and "Perth, Western Australia (Australia)" :param location: geo location of the person :return city :raises LocatorException: could not infer the city name """ sep_idx = location....
a7b69a8937141f7bff288d19bb92e41beb3a98c5
3,613,087
def row_to_top(df, index): """Bring row to top Parameters ---------- df: pandas.dataframe Dataframe to copy index: int Index of row to bring to top Returns ------- df_cp: pandas.dataframe Copy of dataframe with specified row at top """ df_cp = pd.concat...
519af78bb1a77debf69f23d4b6b6218d3c6087bb
3,613,088
def init_cache(cname): """ Wipes and initializes a cache dir for container name `cname`. """ cache = abspath('.tmptest/test-kraken-integration/{cname}/cache'.format(cname=cname)) if os.path.exists(cache): subprocess.check_call(['rm', '-rf', cache]) os.makedirs(cache) os.chmod(cache, ...
0f1b4a035b0a44e065a60ba9cce4699113f0dd9e
3,613,089
def encodeMask(M): """ Encode binary mask M using run-length encoding. :param M (bool 2D array) : binary mask to encode :return: R (object RLE) : run-length encoding of binary mask """ [h, w] = M.shape M = M.flatten(order='F') N = len(M) counts_list = [] pos = 0 # counts counts_list.append(1) diffs ...
bafe9ba42701d85fa3a572e86d0846a15fda067f
3,613,090
def flatten_model_graph(ir_model: Model): """ Flatten the subgraph into root graph. """ def _flatten(graph: Graph): """ flatten this graph """ model = graph.model node_to_remove = [] for node in graph.hidden_nodes: node_graph = model.graphs.ge...
ebe7a0c1519914de3088b65481f3368457dbbe1b
3,613,091
def get_cache(): """returns the cache""" return _cache
bb73c2f143bc2595085e63c028330b254f495464
3,613,092
def parse_message(message, nodata=False): """Parse df message from bytearray. @message - message data @nodata - do not load data @return - [binary header, metadata, binary data] """ header = read_machine_header(message) h_len = __get_machine_header_length(header) meta_raw = message[h_l...
9fbd2744e3c91e6db6ede20fd5bb50c84dbdc2e5
3,613,093
def reblock_array(df, nblocks, weights=None): """ Reblock df into nblocks new blocks :param df: data to reblock :type df: numpy array-like :param nblocks: number of resulting blocks :type nblocks: int :param weights: weights used to average data :type weights: array :return: reblock...
24adfe10ba1fbef5b7efb3d006a8e81be89d3f7a
3,613,094
def B_measure(D, Cm, verbose=False): """ Computes the B measure for each network edge with infinite distance, thus not existing in the original Distance graph. The formal definition is as follow: .. math:: b_{ij} = <d_{ik}> / d_{ij}^m b_{ji} = <d_{jk}> / d_{ij}^m which is the average distance of all edges t...
075ec0e4a3c50bd48cd8684317f63915c5eacc63
3,613,095
from typing import List def get_medias() -> List[Media]: """ Retrieve the list of medias to be processed into folders :return: the list of medias to process """ files = [] for folder in config['input']['folders']: files += scan_folder(folder) files.sort() medias = [] for ...
c6a42cacc2c517e410a51ddccc99217beac70377
3,613,096
def count_paths_recursive(graph, node_val, target): """A more conventional recursive function (not a recursive generator)""" if node_val >= target: return 1 total = 0 for next_node in graph[node_val]: total += count_paths_recursive(graph, next_node, target) return total
be2aba80ed7dc734fb30f3b8b1a675d97e73c860
3,613,097
import re def check_valency(mol): """ Checks that no atoms in the mol have exceeded their possible valency :return: True if no valency issues, False otherwise """ try: Chem.SanitizeMol(mol, sanitizeOps=Chem.SanitizeFlags.SANITIZE_PROPERTIES) return True, None except ValueEr...
ebcbcb31b89aae27066f841495d2aa4930a74e04
3,613,098
import time import yaml def ensure_pod(ctx): """创建configmap""" name = "kubectld-%s-u%s" % (ctx["source_cluster_id"], ctx["username_slug"]) name = name.lower() k8s_client = K8SClient(ctx) try: pod = k8s_client.v1.read_namespaced_pod(name, namespace=constants.NAMESPACE) if pod.stat...
a14dd0896e661d00ca088cdbf5a45e16ef47bd78
3,613,099