content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def circle_location_Pass(circle_, image_, margin=0.15): """ Function for check if the circle_ is overlapping with the margin of the image_. """ cy, cx, rad, accum = circle_ image_sizeY_, image_sizeX_ = image_.shape[0], image_.shape[1] margin_min_x = int(image_sizeX_ * margin) margin_max_...
4ad94552bc1bf06282a691edede89a65f8b9c328
3,657,000
import ftplib def session_factory( base_class=ftplib.FTP, port=21, use_passive_mode=None, *, encrypt_data_channel=True, debug_level=None, ): """ Create and return a session factory according to the keyword arguments. base_class: Base class to use for the session class (e. g. ...
9fa29732dc14705317e4bbb3752330de5f0282c6
3,657,001
def calculate_molecular_mass(symbols): """ Calculate the mass of a molecule. Parameters ---------- symbols : list A list of elements. Returns ------- mass : float The mass of the molecule """ mass = 0 for i in range(len(symbols)): mass =...
7ac18cffc02652428b51009d2bf304301def96dd
3,657,002
def _color_str(string, color): """Simple color formatter for logging formatter""" # For bold add 1; after "[" start_seq = '\033[{:d}m'.format(COLOR_DICT[color]) return start_seq + string + '\033[0m'
715b0b597885f1cffa352cc01bdb743c3ed23dd4
3,657,003
def parser_tool_main(args): """Main function for the **parser** tool. This method will parse a JSON formatted Facebook conversation, reports informations and retrieve data from it, depending on the arguments passed. Parameters ---------- args : Namespace (dict-like) Arguments passe...
1e07a60e78b042c6c229410e5d1aaf306e692f61
3,657,004
from functools import reduce def merge(from_args): """Merge a sequence of operations into a cross-product tree. from_args: A dictionary mapping a unique string id to a raco.algebra.Operation instance. Returns: a single raco.algebra.Operation instance and an opaque data structure suitable for pas...
e3690a26fc9e3e604984aab827617ffc535f63d3
3,657,005
import subprocess import mimetypes def get_content_type(file_resource): """Gets a file's MIME type. Favors returning the result of `file -b --mime ...` if the command is available and users have enabled it. Otherwise, it returns a type based on the file's extension. Args: file_resource (resource_refer...
d58e60262cd762ae412580effc022f643132cb69
3,657,006
def graph(task_id): """Return the graph.json results""" return get_file(task_id, "graph.json")
4d8728d3b61cf62057525054d8eafa127b1c48ff
3,657,007
def parse_components_from_aminochange(aminochange): """ Returns a dictionary containing (if possible) 'ref', 'pos', and 'alt' characteristics of the supplied aminochange string. If aminochange does not parse, returns None. :param aminochange: (str) describing amino acid change :return: dict or Non...
69877d635b58bdc3a8a7f64c3c3d86f59a7c7548
3,657,008
import random import string import csv def get_logs_csv(): """ get target's logs through the API in JSON type Returns: an array with JSON events """ api_key_is_valid(app, flask_request) target = get_value(flask_request, "target") data = logs_to_report_json(target) keys = data[...
f9296cfc7c6559ebccbfa29268e3b22875fb9fed
3,657,009
def _cache_key_format(lang_code, request_path, qs_hash=None): """ função que retorna o string que será a chave no cache. formata o string usando os parâmetros da função: - lang_code: código do idioma: [pt_BR|es|en] - request_path: o path do request - qs_hash: o hash gerado a partir dos parametro...
365b1ff144f802e024da5d6d5b25b015463da8b3
3,657,010
from typing import Iterable from pathlib import Path from typing import Callable from typing import Any from typing import List def select_from(paths: Iterable[Path], filter_func: Callable[[Any], bool] = default_filter, transform: Callable[[Path], Any] = None, order_fun...
d952d7d81932c5f6d206c39a5ac12aae1e940431
3,657,011
import torch from typing import Counter def dbscan(data:torch.Tensor, epsilon:float, **kwargs) -> torch.Tensor: """ Generate mask using DBSCAN. Note, data in the largest cluster have True values. Parameters ---------- data: torch.Tensor input data with shape (n_samples, n_features) ...
0121b8b9dceaf9fc8399ffd75667afa6d34f66e1
3,657,012
import copy def simulate_multivariate_ts(mu, alpha, beta, num_of_nodes=-1,\ Thorizon = 60, seed=None, output_rejected_data=False): """ Inputs: mu: baseline intesnities M X 1 array alpha: excitiation rates of multivariate kernel pf HP M X M array beta: decay rates of kernel of multivariate HP ...
85ab71fa3f2b16cbe296d21d6bc43c15c94aa40a
3,657,013
import base64 def token_urlsafe(nbytes): """Return a random URL-safe text string, in Base64 encoding. The string has *nbytes* random bytes. If *nbytes* is ``None`` or not supplied, a reasonable default is used. >>> token_urlsafe(16) #doctest:+SKIP 'Drmhze6EPcv0fN_81Bj-nA' """ tok = to...
1855dc44cec1ddd0c6c83d0f765c15fd98d1ec98
3,657,014
def sha206a_get_pk_useflag_count(pk_avail_count): """ calculates available Parent Key use counts Args: pk_avail_count counts available bit's as 1 (int) Returns: Status Code """ if not isinstance(pk_avail_count, AtcaReference): status = Status.ATCA_BAD_PARAM e...
389174a21efe1ca78037b479895035b4bdd66b87
3,657,015
from typing import Tuple def rotate_points_around_origin( x: tf.Tensor, y: tf.Tensor, angle: tf.Tensor, ) -> Tuple[tf.Tensor, tf.Tensor]: """Rotates points around the origin. Args: x: Tensor of shape [batch_size, ...]. y: Tensor of shape [batch_size, ...]. angle: Tensor of shape [batch_si...
8d4bf5f94964271f640def7d7e2b4242fbfe8e7b
3,657,016
import inspect def form_of(state): """Return the form of the given state.""" if hasattr(state, "__form__"): if callable(state.__form__) and not inspect.isclass(state.__form__): return state.__form__() else: return state.__form__ else: raise ValueError(f"{st...
e39aa7db7b324ab38b65232b34b987b862812c54
3,657,017
def poly_to_geopandas(polys, columns): """ Converts a GeoViews Paths or Polygons type to a geopandas dataframe. Parameters ---------- polys : gv.Path or gv.Polygons GeoViews element columns: list(str) List of columns Returns ------- gdf : Geopandas dataframe ""...
889fc5b1bf5bf15cd9612c40e7bf14b1c05043f6
3,657,018
def get_sequences(query_file=None, query_ids=None): """Convenience function to get dictionary of query sequences from file or IDs. Parameters: query_file (str): Path to FASTA file containing query protein sequences. query_ids (list): NCBI sequence accessions. Raises: ValueError: Did...
8056ce1c98b7a4faa4bb5a02505d527df31c7c8b
3,657,019
import os def _get_tickets(manifest, container_dir): """Get tickets.""" principals = set(manifest.get('tickets', [])) if not principals: return False tkts_spool_dir = os.path.join( container_dir, 'root', 'var', 'spool', 'tickets') try: tickets.request_tickets( ...
39d73322620ea9a6f1da4bfb693336dfc68748bb
3,657,020
def random_show_date(database_connection: mysql.connector.connect) -> str: """Return a random show date from the ww_shows table""" database_connection.reconnect() cursor = database_connection.cursor(dictionary=True) query = ("SELECT s.showdate FROM ww_shows s " "WHERE s.showdate <= NOW() "...
e3afdf9aa1fe9a02adab72c424caa80d60280699
3,657,021
def get_output_tensor(interpreter, index): """Returns the output tensor at the given index.""" output_details = interpreter.get_output_details()[index] tensor = np.squeeze(interpreter.get_tensor(output_details["index"])) return tensor
158db3fc7ba13ee44d422248a9b96b7738a486e3
3,657,022
def make_d_mappings(n_dir, chain_opts): """Generate direction to solution interval mapping.""" # Get direction dependence for all terms. dd_terms = [dd for _, dd in yield_from(chain_opts, "direction_dependent")] # Generate a mapping between model directions gain directions. d_map_arr = (np.arange(...
fd9eddf81b4388e3fa40c9b65a591af9aabf9014
3,657,023
from typing import cast from typing import Dict import os import cmd import traceback import pprint def main(): """Loop to test the postgres generation with REPL""" envs = cast(Dict[str, str], os.environ) if "HAYSTACK_DB" not in envs: envs["HAYSTACK_DB"] = "sqlite3:///:memory:" provider = get_...
caaaaafd9407417e4be334963c72a2b5d0c970fb
3,657,024
def _calculateVolumeByBoolean(vtkDataSet1,vtkDataSet2,iV): """ Function to calculate the volumes of a cell intersecting a mesh. Uses a boolean polydata filter to calculate the intersection, a general implementation but slow. """ # Triangulate polygon and calc normals baseC = vtkTools.datas...
a2c30133973527fb339c9d1e33cc2a937b35d958
3,657,025
def WebChecks(input_api, output_api): """Run checks on the web/ directory.""" if input_api.is_committing: error_type = output_api.PresubmitError else: error_type = output_api.PresubmitPromptWarning output = [] output += input_api.RunTests([input_api.Command( name='web presubmit', cmd=[ ...
5fb828cc98da71bd231423223336ec81e02505ff
3,657,026
from HUGS.Util import load_hugs_json def synonyms(species: str) -> str: """ Check to see if there are other names that we should be using for a particular input. E.g. If CFC-11 or CFC11 was input, go on to use cfc-11, as this is used in species_info.json Args: species (str): Input string ...
31013464ce728cc3ed93b1a9318af3dbcf3f65ec
3,657,027
def _blkid_output(out): """ Parse blkid output. """ flt = lambda data: [el for el in data if el.strip()] data = {} for dev_meta in flt(out.split("\n\n")): dev = {} for items in flt(dev_meta.strip().split("\n")): key, val = items.split("=", 1) dev[key.lower...
2cbcbb3ec9b732c3c02183f43ca5a5d5e876af71
3,657,028
def as_iso_datetime(qdatetime): """ Convert a QDateTime object into an iso datetime string. """ return qdatetime.toString(Qt.ISODate)
8dba5d1d6efc0dc17adc26a5687923e067ca3c29
3,657,029
def spec_means_and_magnitudes(action_spec): """Get the center and magnitude of the ranges in action spec.""" action_means = tf.nest.map_structure( lambda spec: (spec.maximum + spec.minimum) / 2.0, action_spec) action_magnitudes = tf.nest.map_structure( lambda spec: (spec.maximum - spec.minimum) / 2.0,...
119054966a483bb60e80941a6bf9dc5a4a0778f6
3,657,030
def clean_data(df): """ Clean Data : 1. Clean and Transform Category Columns from categories csv 2.Drop Duplicates 3.Remove any missing values Args: INPUT - df - merged Dataframe from load_data function OUTPUT - Returns df - cleaned Dataframe """ # Split categories into...
752d675d8ac5e27c61c9b8c90acee4cdab8c08fc
3,657,031
def commitFile(file: str = None, message: str = None, debug: bool = False) -> bool: """Commit a file when it is changed. :param file: The name of the file we want to commit. :type file: str :param message: The commit message we want to use. :type message: str :param debug: If we want debug logg...
2821da94cf727ee4d5098ccacc78c8368e7899aa
3,657,032
def all_pairs_shortest_path_length(G,cutoff=None): """ Compute the shortest path lengths between all nodes in G. Parameters ---------- G : NetworkX graph cutoff : integer, optional depth to stop the search. Only paths of length <= cutoff are returned. Returns ------- lengths :...
1d312a71bd97d4f1a51a8b1e24331d54055bc156
3,657,033
def get_cols_to_keep(gctoo, cid=None, col_bool=None, cidx=None, exclude_cid=None): """ Figure out based on the possible columns inputs which columns to keep. Args: gctoo (GCToo object): cid (list of strings): col_bool (boolean array): cidx (list of integers): exclude_cid...
1215a392ecb068e2d004c64cf56f2483c722f3f6
3,657,034
import shutil def check_zenity(): """ Check if zenity is installed """ warning = '''zenity was not found in your $PATH Installation is recommended because zenity is used to indicate that protonfixes is doing work while waiting for a game to launch. To install zenity use your system's package ...
decea9be11e0eb1d866ed295cb33a06aa663a432
3,657,035
def get_auth_token(): """ Return the zerotier auth token for accessing its API. """ with open("/var/snap/zerotier-one/common/authtoken.secret", "r") as source: return source.read().strip()
bd74fde05fbb375f8899d4e5d552ad84bcd80573
3,657,036
def sph_harm_transform(f, mode='DH', harmonics=None): """ Project spherical function into the spherical harmonics basis. """ assert f.shape[0] == f.shape[1] if isinstance(f, tf.Tensor): sumfun = tf.reduce_sum def conjfun(x): return tf.conj(x) n = f.shape[0].value else: s...
a88f9a71fa19a57441fdfe88e8b0632cc08fb413
3,657,037
def create_model(experiment_settings:ExperimentSettings) -> OuterModel: """ function creates an OuterModel with provided settings. Args: inner_settings: an instannce of InnerModelSettings outer_settings: an instannce of OuterModelSettings """ model = OuterModel(experiment_settings.ou...
e6af03c5afd53a39e6929dba71990f91ff8ffbb3
3,657,038
import pickle def LoadTrainingTime(stateNum): """ Load the number of seconds spent training """ filename = 'time_' + str(stateNum) + '.pth' try: timeVals = pickle.load( open(GetModelPath() + filename, "rb")) return timeVals["trainingTime"] except: print("ERROR: Faile...
1db59103bf3e31360237951241b90b3a85dae2bc
3,657,039
def adjust_learning_rate(optimizer, epoch): """Sets the learning rate to the initial LR decayed by 10 every 15 epochs""" lr = args.lr * (0.1 ** (epoch // args.lr_epochs)) print('Learning rate:', lr) for param_group in optimizer.param_groups: if args.retrain and ('mask' in param_group['key']): # ...
dc08034b0176ac0062d6fc7640a115f916a663a8
3,657,040
def disk_status(hardware, disk, dgtype): """ Status disk """ value = int(float(disk['used']) / float(disk['total']) * 100.0) if value >= 90: level = DiagnosticStatus.ERROR elif value >= 70: level = DiagnosticStatus.WARN else: level = DiagnosticStatus.OK # Make boa...
f248ccb0ba07106c3ed923f9ac7bc2e85d9b5e63
3,657,041
def hr_admin(request): """ Views for HR2 Admin page """ user = request.user # extra_info = ExtraInfo.objects.select_related().get(user=user) designat = HoldsDesignation.objects.select_related().get(user=user) if designat.designation.name =='hradmin': template = 'hr2Module/hradmin.h...
1b2c1027f8f4caf716019d9e5500223f76119a0b
3,657,042
import six def test_extra(): """Returns dict of extrapolation testing modules.""" return {name: module.test_extra() for name, module in six.iteritems(all_)}
5538f81891c0388ae0f5e312cb6c521ee19d18a5
3,657,043
import torch def _switch_component( x: torch.Tensor, ones: torch.Tensor, zeros: torch.Tensor ) -> torch.Tensor: """ Basic component of switching functions. Args: x (torch.Tensor): Switch functions. ones (torch.Tensor): Tensor with ones. zeros (torch.Tensor): Zero tensor R...
8d60c09428440be704e8ced9b8ac19219a0d0b04
3,657,044
def get_vector(x_array, y_array, pair): """This function is for calculating a vector of a bone from the openpose skelleton""" x = x_array[:,pair[0]]-x_array[:,pair[1]] y = y_array[:,pair[0]]-y_array[:,pair[1]] return [x, y]
e2bfcce3952c6b0a2c8cd9c67c4cd7b52547694d
3,657,045
def update_bar(tweets_json, handle): """ Pull data from signal and updates aggregate bar graph This is using thresholds that combine toxicity and severe toxicity models suggested by Lucas. """ if not tweets_json: raise PreventUpdate('no data yet!') tweets_df = pd.read_json(tweets_j...
1c523a455393ce211b8ef6483ee25b981e028bd0
3,657,046
import argparse def defineConsole(): """ defines the program console line commands """ parser = argparse.ArgumentParser(description="SBML to BNGL translator") parser.add_argument( "-f1", "--file1", type=str, help="reference file", required=True ) parser.add_argument( "-f2",...
77f403040cf250810c5b4098c6b9818e5f17117e
3,657,047
from typing import List from typing import Dict def render_foreign_derivation(tpl: str, parts: List[str], data: Dict[str, str]) -> str: """ >>> render_foreign_derivation("bor", ["en", "ar", "الْعِرَاق", "", "Iraq"], defaultdict(str)) 'Arabic <i>الْعِرَاق</i> (<i>ālʿrāq</i>, “Iraq”)' >>> render_foreign...
af3c37664e683d9bff610ad1fa53a167f5390988
3,657,048
def create_from_ray(ray): """Converts a ray to a line. The line will extend from 'ray origin -> ray origin + ray direction'. :param numpy.array ray: The ray to convert. :rtype: numpy.array :return: A line beginning at the ray start and extending for 1 unit in the direction of the ray. ...
6d0429abbacd235f95636369985bea8a17117409
3,657,049
from typing import List def cluster_sampling(sents: List[Sentence], tag_type: str, **kwargs) -> List[int]: """Cluster sampling. We create cluster sampling as a kind of diversity sampling method. Different with most of sampling methods that are based on sentence level, Cluster sampling method is imple...
a953ec5eced13e626a3b00769a7e5d505fcb1692
3,657,050
import os def paths_to_dirs(paths): # type: (t.List[str]) -> t.List[str] """Returns a list of directories extracted from the given list of paths.""" dir_names = set() for path in paths: while True: path = os.path.dirname(path) if not path or path == os.path.sep: ...
3472093ffb4870082e7d198410118169683ed786
3,657,051
def opts2dict(opts): """Converts options returned from an OptionParser into a dict""" ret = {} for k in dir(opts): if callable(getattr(opts, k)): continue if k.startswith('_'): continue ret[k] = getattr(opts, k) return ret
cfa828f0248ff7565aabbb5c37a7bc6fa38c6450
3,657,052
def combined_directions(a_list, b_list): """ Takes two NoteList objects. Returns a list of (3)tuples each of the form: ( int: a dir, int: b dir, (int: bar #, float: beat #) ) """ onsets = note_onsets(a_list, b_list) a_dirs = directions(a_list) b_dirs = directi...
8b66d4de725c51b1abdedb8a8e4c48e78f4ca953
3,657,053
def _naive_csh_seismology(l, m, theta, phi): """ Compute the spherical harmonics according to the seismology convention, in a naive way. This appears to be equal to the sph_harm function in scipy.special. """ return (lpmv(m, l, np.cos(theta)) * np.exp(1j * m * phi) * np.sqrt(((2 * l + 1)...
ba2a17f0dfa6035a05d16c8af79310657fe6ecd7
3,657,054
def is_room_valid(room): """Check if room is valid.""" _, names, checksum = room letters = defaultdict(int) complete_name = ''.join(names) for letter in complete_name: letters[letter] += 1 sorted_alphabetic = sorted(letters) sorted_by_occurrences = sorted( sorted_alphabetic, ...
b893cf97ee28b033741e4b2797b2a4aef485324f
3,657,055
from typing import Dict def _get_attributes_entropy(dataset: FingerprintDataset, attributes: AttributeSet ) -> Dict[Attribute, float]: """Give a dictionary with the entropy of each attribute. Args: dataset: The fingerprint dataset used to comput...
616abbd292f10d0a01d7d56ab5636ac5883fa230
3,657,056
def _mag_shrink_hard(x, r, t): """ x is the input, r is the magnitude and t is the threshold """ gain = (r >= t).float() return x * gain
da795bcfc2a6e4bfa3e54d1334c9d8865141a4f1
3,657,057
from sys import base_prefix def is_macports_env(): """ Check if Python interpreter was installed via Macports command 'port'. :return: True if Macports else otherwise. """ # Python path prefix should start with Macports prefix. env_prefix = get_macports_prefix() if env_prefix and base_pre...
b90c43f7ef267ab237e8f6c205eb2a62969b5539
3,657,058
def wiki_data(request, pro_id): """ 文章标题展示 """ data = models.Wiki.objects.filter(project_id=pro_id).values('id', 'title', 'parent_id').order_by('deepth') return JsonResponse({'status': True, 'data': list(data)})
6dfbb79b78133935356bd87cc24a294ed0001b73
3,657,059
import os import json def create_task_spec_def(): """Returns the a :class:`TaskSpecDef` based on the environment variables for distributed training. References ---------- - `ML-engine trainer considerations <https://cloud.google.com/ml-engine/docs/trainer-considerations#use_tf_config>`__ - `Tenso...
fdf1680e41f072ebf0c9b2b228095fba91d5af09
3,657,060
def many_capitalized_words(s): """Returns a function to check percentage of capitalized words. The function returns 1 if percentage greater then 65% and 0 otherwise. """ return 1 if capitalized_words_percent(s) > 66 else 0
cc82a2708defd545a1170bfeabb5848e3092fc39
3,657,061
def cmd_te_solution_build(abs_filename,wait=False,print_output=False,clear_output=False): """ソリューションをビルドする(テキストエディタ向け) ファイルが含まれるVisual Studioを探し出してソリューションをビルドする。 VisualStudioの「メニュー -> ビルド -> ソリューションのビルド」と同じ動作。 abs_filename- ファイル名の絶対パス (Ex.) c:/project/my_app/src/main.cpp ...
db48988d483da6ae9a012460e0d5fdd326d5ae40
3,657,062
def log_ratio_measure( segmented_topics, accumulator, normalize=False, with_std=False, with_support=False): """ If normalize=False: Popularly known as PMI. This function calculates the log-ratio-measure which is used by coherence measures such as c_v. This is defined as: ...
73fec59f84402066ccbbcd25d30cc69698f6b721
3,657,063
def _calculate_monthly_anomaly(data, apply_filter=False, base_period=None, lat_name=None, lon_name=None, time_name=None): """Calculate monthly anomalies at each grid point.""" # Ensure that the data provided is a data array data = rdu.ensure_data_array(data) # Get coordi...
397bffb8f22ae26cf2c41cd8c056951ef55d692d
3,657,064
def process_song(song_id): """ 歌曲id、歌曲名、歌手id、所属专辑id、歌词、评论数 process song information :param song_id: 歌曲id :return: 处理状态(True or False) """ log("正在处理歌曲:{}".format(song_id)) if db.hexists("song:" + song_id, "id"): log("有缓存(已做过处理),歌曲id:{}".format(song_id)) return True els...
148953bd42ce8aba3bf6b90aed7a5276dd0794c3
3,657,065
import os def expand_path(path): """ Convert a path to an absolute path. This does home directory expansion, meaning a leading ~ or ~user is translated to the current or given user's home directory. Relative paths are relative to the current working directory. :param path: Relative or absolut...
dc73eb377fd5b16091596f4345ee024c3d42e5bc
3,657,066
import pprint def oxe_system_alaw_to_mulaw(host, token, mode): """Summary Args: host (TYPE): Description token (TYPE): Description mode (TYPE): Description Returns: TYPE: Description """ payload = { 'T0_Mu_Law': mode } packages.urllib3.disa...
19bb98f8326e84cde83691028a2fc2585a7abe6e
3,657,067
def update_weights(comment_weights, comment_usage): """Updates the weights used to upvote comments so that the actual voting power usage is equal to the estimated usage. """ desired_usage = 1.0 - VP_COMMENTS / 100.0 actual_usage = 1.0 - comment_usage / 100.0 scaler = np.log(desired_usage) / np.l...
19d2f0a9ec790c26000946c0b91ef3bc00f36905
3,657,068
import math def smaller2k(n): """ Returns power of 2 which is smaller than n. Handles negative numbers. """ if n == 0: return 0 if n < 0: return -2**math.ceil(math.log2(-n)) else: return 2**math.floor(math.log2(n))
0d0bbbf95cb22bf1b9ffb29012075534bcc9646d
3,657,069
from PIL import Image from lxml import etree import sys import os.path import pickle import time import urllib.request import io import requests import tensorflow as tf from mynet import CaffeNet def create_anime_image_data(anime): """Create (or load) a dict for each anime that has a high level CNN representation...
fbe6fc4bbfd3623c40bf78c8c33bc960bea307d2
3,657,070
def deferred_bots_for_alias(alias): """Returns a dict where the keys are bot names whose commands have an alias that conflicts with the provided alias, and the values are a list of prefixes that would cause that conflict.""" return { # TODO Support more prefixes than one config['name']: ...
338776546622ed0bb6290b2d93ddb3129e764d02
3,657,071
import opcode def modeify(intcode, i): """Apply a mode to a parameter""" j = i + 1 _opcode = opcode(intcode[i]) params = intcode[j: j + _opcode['param_count']] modes = _opcode['modes'] mode_covert = { 0: lambda x: intcode[x], # position mode 1: lambda x: x ...
230fb2e43c33558d94a7d60c6dd16978098421aa
3,657,072
def unwind(g, num): """Return <num> first elements from iterator <g> as array.""" return [next(g) for _ in range(num)]
59b724ca27729b4fc20d19a40f95d590025307c4
3,657,073
def find_best_control(db, input_features, max_distance=200.0, debug=False, control_cache=None): """ Search all controls with AST vector magnitudes within max_distance and find the best hit (lowest product of AST*call distance) against suitable controls. Does not currently use literal distance for the calculati...
21589a3070f59f556a7cc540b5d69839fbb95327
3,657,074
import re def CPPComments(text): """Remove all C-comments and replace with C++ comments.""" # Keep the copyright header style. line_list = text.splitlines(True) copyright_list = line_list[0:10] code_list = line_list[10:] copy_text = ''.join(copyright_list) code_text = ''.join(code_list) # Remove */ ...
0dd490f5497c073534abc30944bd49d0a3cf7e3e
3,657,075
def get_bulk_statement( stmt_type, table_name, column_names, dicts=True, value_string="%s", odku=False ): """Get a SQL statement suitable for use with bulk execute functions Parameters ---------- stmt_type : str One of REPLACE, INSERT, or INSERT IGNORE. **Note:** Backend support for ...
ba2277fc6f84d79a97d70cf98d2e26f308b8fa82
3,657,076
def map_remove_by_value_range(bin_name, value_start, value_end, return_type, inverted=False): """Creates a map_remove_by_value_range operation to be used with operate or operate_ordered The operation removes items, with values between value_start(inclusive) and value_end(exclusive) from the map Args: ...
42a49aefb92f61a3064e532390bdcf26b6266f40
3,657,077
def rationalApproximation(points, N, tol=1e-3, lowest_order_only=True): """ Return rational approximations for a set of 2D points. For a set of points :math:`(x,y)` where :math:`0 < x,y \\leq1`, return all possible rational approximations :math:`(a,b,c) \\; a,b,c \\in \\mathbb{Z}` such that :math:`...
614c230ad7fd68cb60d0203cba2bd15e30f3f36a
3,657,078
import subprocess def get_notebook_server_instance(try_use_existing=False): """Create a notebook server instance to use. Optionally attempting to re-use existing instances. """ pid = get_cache_pid() servers = list_running_servers() # If we already have a server, use that for server in s...
b11932b2be3319be388913427ef7623690fa11f1
3,657,079
def to_dict(doc, fields): """Warning: Using this convenience fn is probably not as efficient as the plain old manually building up a dict. """ def map_field(prop): val = getattr(doc, prop) if isinstance(val, list): return [(e.to_dict() if hasattr(e, 'to_dict') else e) for e i...
cb51e3dfdf8c313f218e38d8693af9e7c6bf5045
3,657,080
import time def _auto_wrap_external(real_env_creator): """Wrap an environment in the ExternalEnv interface if needed. Args: real_env_creator (fn): Create an env given the env_config. """ def wrapped_creator(env_config): real_env = real_env_creator(env_config) if not isinstanc...
ef7f0c7ecdf3eea61a4e9dc0ad709e80d8a09e08
3,657,081
def _get_binary_link_deps( base_path, name, linker_flags = (), allocator = "malloc", default_deps = True): """ Return a list of dependencies that should apply to *all* binary rules that link C/C++ code. This also creates a sanitizer configuration rule if necessary, s...
06a52934a0c121b606c79a6f5ae58863645bba34
3,657,082
def create_dummy_ligand(ligand, cut_idx=None): """ Takes mol object and splits it based on a primary amine such that the frags can connect to the tertiary amine on the Mo core. Args: cut_idx tuple(int): ligand (mol): Returns: ligands List(mol) : """ # TODO AllChem.Rep...
b74bc21003c33234d310121331ab61887536709e
3,657,083
def double2pointerToArray(ptr, n, m_sizes): """ Converts ctypes 2D array into a 2D numpy array. Arguments: ptr: [ctypes double pointer] n: [int] number of cameras m_sizes: [list] number of measurements for each camera Return: arr_list: [list of ndarrays] list of numpy ...
f556c5a36f645c6047c3b487b7cd865edc3b76db
3,657,084
def read_varint(stream: bytes): """ 读取 varint。 Args: stream (bytes): 字节流。 Returns: tuple[int, int],真实值和占用长度。 """ value = 0 position = 0 shift = 0 while True: if position >= len(stream): break byte = stream[position] value += (byte...
58c8187501dc08b37f777256474f95412649bf04
3,657,085
import argparse def get_arguments(): """ get commandline arguments """ # Parse command line arguments parser = argparse.ArgumentParser(description="P1 reader interface") parser.add_argument("--config-file", default=__file__.replace('.py', '.yml').replace('/bin/', '/etc...
f35a364c96705c764064c536519dc9d3730d9310
3,657,086
def any(array, mapFunc): """ Checks if any of the elements of array returns true, when applied on a function that returns a boolean. :param array: The array that will be checked, for if any of the elements returns true, when applied on the function. \t :type array: [mixed] \n :param mapFunc: The fun...
1e635da691fd1c2fc9d99e15fd7fa0461a7bdf0e
3,657,087
def qt_point_to_point(qt_point, unit=None): """Create a Point from a QPoint or QPointF Args: qt_point (QPoint or QPointF): The source point unit (Unit): An optional unit to convert values to in the output `Point`. If omitted, values in the output `Point` will be plain `i...
595dacc2d39d126822bf680e1ed1784c05deb6d7
3,657,088
import requests import json def apiRequest(method, payload=None): """ Get request from vk server :param get: method for vkApi :param payload: parameters for vkApi :return: answer from vkApi """ if payload is None: payload = {} if not ('access_token' in payload): pay...
b60c77aec5ae500b9d5e9901216c7ff7c93676ad
3,657,089
def page_required_no_auth(f): """Full page, requires user to be logged out to access, otherwise redirects to main page.""" @wraps(f) def wrapper(*args, **kwargs): if "username" in session: return redirect("/") else: return f(*args, **kwargs) return wrapper
7d7d314e10dcaf1d81ca5c713afd3da6a021247d
3,657,090
import argparse import re def parse_arguments(args): """ Parse all given arguments. :param args: list :return: argparse.Namespace """ parser = argparse.ArgumentParser( description=__description__, epilog="Example-usage in apache-config:\n" 'CustomLog "| /path/to/anonip...
7d24618fc40835488a7d05a748f462826311a30a
3,657,091
import sympy def generate_forward(): """ Generate dataset with forward method It tries to integrate random function. The integral may not be symbolically possible, or may contains invalid operators. In those cases, it returns None. """ formula = symbolic.fixed_init(15) integrated = sympy.integrate(fo...
91a91e5b23f3f59b49d8f7102585ff7fbfbbf6c4
3,657,092
import pickle def load_agent(agent_args, domain_settings, experiment_settings): """ This function loads the agent from the results directory results/env_name/method_name/filename Args: experiment_settings Return: sarsa_lambda agent """ with open('results...
a5769c952d9fcc583b8fb909e6e772c83b7126ca
3,657,093
def unpickle_robust(bytestr): """ robust unpickle of one byte string """ fin = BytesIO(bytestr) unpickler = robust_unpickler(fin) return unpickler.load()
42fee03886b36aef5ab517e0abcb2cc2ecfd6a8b
3,657,094
def build_ins_embed_branch(cfg, input_shape): """ Build a instance embedding branch from `cfg.MODEL.INS_EMBED_HEAD.NAME`. """ name = cfg.MODEL.INS_EMBED_HEAD.NAME return INS_EMBED_BRANCHES_REGISTRY.get(name)(cfg, input_shape)
4d8242614426a13f9e93a241184bd3d8f57ef648
3,657,095
def atl03sp(ipx_region, parm, asset=icesat2.DEFAULT_ASSET): """ Performs ATL03 subsetting in parallel on ATL03 data and returns photon segment data. See the `atl03sp <../api_reference/icesat2.html#atl03sp>`_ function for more details. Parameters ---------- ipx_region: Query ...
8c822af0d2f9b6e42bd6a1efeb29249a04079e66
3,657,096
def get_sample_activity_from_batch(activity_batch, idx=0): """Return layer activity for sample ``idx`` of an ``activity_batch``. """ return [(layer_act[0][idx], layer_act[1]) for layer_act in activity_batch]
0302fdf215e63d6cbcd5dafc1bd36ae3d27712f2
3,657,097
def _reorder_for_qbb_experiment(df: pd.DataFrame) -> pd.DataFrame: """By default the entries are ordered alphabetically. We want SPOTA, EPOpt, PPO""" print("Changed the order") return df.iloc[[2, 0, 1]]
beccd22a765eb526ed855fd34dde4a05e2b394f2
3,657,098
def get_field(self, *args, is_squeeze=False, node=None, is_rthetaz=False): """Get the value of variables stored in Solution. Parameters ---------- self : SolutionData an SolutionData object *args: list of strings List of axes requested by the user, their units and values (optional) ...
e93455cbc4b306762336fd13603342e9d92badd1
3,657,099