content
stringlengths
22
815k
id
int64
0
4.91M
def token_bytes(nbytes): """Return a random byte string containing *nbytes* bytes. If *nbytes* is ``None`` or not supplied, a reasonable default is used. >>> token_bytes(16) #doctest:+SKIP b'\\xebr\\x17D*t\\xae\\xd4\\xe3S\\xb6\\xe2\\xebP1\\x8b' """ return os.urandom(nbytes)
16,500
def test_three_related_branch_w_ac(clean_db, three_family_branch_with_trials, capsys): """Test three related experiments in a branch with --collapse and --all.""" orion.core.cli.main(["status", "--collapse", "--all"]) captured = capsys.readouterr().out expected = """\ test_double_exp-v1 ==============...
16,501
def quat2expmap(q): """ Converts a quaternion to an exponential map Matlab port to python for evaluation purposes https://github.com/asheshjain399/RNNexp/blob/srnn/structural_rnn/CRFProblems/H3.6m/mhmublv/Motion/quat2expmap.m#L1 Args q: 1x4 quaternion, w, x, y, z Returns ...
16,502
def test_is_swagger_documentation_route_without_route_is_safe(): """ Not sure if `None` is an option for the `route_info` dict, but make sure nothing crashes in that possible scenario. """ from pyramid_swagger.tween import is_swagger_documentation_route assert is_swagger_documentation_route(None...
16,503
def log_to_file(filename, level=None, formatter=None): """ Output logs to a file Causes logs to be additionally directed to a file, if you call this twice you will get duplicated logging. This does not disable or invalidate other logging options , it adds to them. Supported Logging levels are CRIT...
16,504
def create_referral(sender, **kwargs): """ This function is more of a middleman, it signals the referral to validate and create referral """ create_flat_referral.send(sender=get_user_model(), request=kwargs['request'], user=kwargs['user'])
16,505
def candidate_results_for_race_type(result_form, race_type, num_results=None): """Return the candidates and results for a result form and race type. :param result_form: The result form to return data for. :param race_type: The race type to get results for, get component results if this is None. ...
16,506
def sort_2metals(metals): """ Handles iterable or string of 2 metals and returns them in alphabetical order Args: metals (str || iterable): two metal element names Returns: (tuple): element names in alphabetical order """ # return None's if metals is None if metals is None:...
16,507
def parse_join(tables, operation, left, right): """ Parses a join from the where clause """ # Verify Left table_name = left['column']['table'] column_name = left['column']['name'] # If table and column, check that table for presense if table_name is not None and not tables[table_name].h...
16,508
def address_id_handler(id): """ GET - called as /addresses/25 PUT - called to update as /addresses/25?address='abc'&lat=25&lon=89 DELETE - called as /addresses/25 :param id: :return: """ if request.method == 'GET': return jsonify(read_address(session, address_id=id)) elif re...
16,509
def get_change_token_status(ChangeToken=None): """ Returns the status of a ChangeToken that you got by calling GetChangeToken . ChangeTokenStatus is one of the following values: See also: AWS API Documentation Exceptions Examples The following example returns the status of a change token w...
16,510
def init( cur ): """Create a temporaty table for generating scinet. """ global gb_ cur.execute( 'DROP TABLE IF EXISTS scinet' ) cur.execute( """ CREATE TABLE IF NOT EXISTS scinet ( speaker_a VARCHAR(100) NOT NULL , speaker_b VARCHAR(100) NOT NU...
16,511
def sync(path, project): """Upload mlflow runs data to Neptune. PATH is a directory where Neptune will look for `mlruns` directory with mlflow data. Examples: neptune mlflow . neptune mlflow /path neptune mlflow /path --project username/sandbox """ # We do not want to i...
16,512
def prefix_search_heuristic_split(mat: np.ndarray, chars: str) -> str: """Prefix search decoding with heuristic to speed up the algorithm. Speed up prefix computation by splitting sequence into subsequences as described by Graves (p66). Args: mat: Output of neural network of shape TxC. cha...
16,513
def _parse_proc_mounts() -> typing.Iterator[MountTpl]: """ :return: A list of mapping objects each gives mount info """ for line in pathlib.Path("/proc/mounts").read_text().splitlines(): match = _PROC_MNT_LINE_RE.match(line) if match is None: continue # Although it should no...
16,514
def _make_set_permissions_url(calendar_id, userid, level): """ :return: the URL string for GET request call to Trumba SetPermissions method """ return "{0}?CalendarID={1}&Email={2}@uw.edu&Level={3}".format( set_permission_url_prefix, calendar_id, userid, level)
16,515
def pack_inputs(inputs): """Pack a list of `inputs` tensors to a tuple. Args: inputs: a list of tensors. Returns: a tuple of tensors. if any input is None, replace it with a special constant tensor. """ inputs = tf.nest.flatten(inputs) outputs = [] for x in inputs: if x is No...
16,516
def upload_blob(bucket_name, data, destination_blob_name): """Uploads a file to the bucket.""" # bucket_name = "your-bucket-name" # data = "local/path/to/file" # destination_blob_name = "storage-object-name" storage_client = storage.Client() bucket = storage_client.bucket(bucket_name) blob ...
16,517
def datetime_without_seconds(date: datetime) -> datetime: """ Returns given datetime with seconds and microseconds set to 0 """ return date.replace(second=0, microsecond=0)
16,518
def update_br(request): """ 更新会议室 :param request: :return: """ if request.method == 'POST': dbs = request.dbsession app_path = request.registry.settings['app_path'] br = dbs.query(HasBoardroom).filter(HasBoardroom.id == request.POST.get('br_id', 0)).first() old_b...
16,519
def find_north_pole(valid_rooms): """ Decode the room names and find the north pole. Args: valid_rooms (list): A list of valid rooms to decode/search. Returns: tuple """ global NORTH_POLE_NAME for room in valid_rooms: room_name, sector_id, checksum = room ...
16,520
def cli(gene1, gene2, gene3, frameness, keep_exon, fusion_fraction, add_insertion, total_coverage, output, common_filename): """[Simulator] Fusion generator.""" normal_coverage = total_coverage * (1. - fusion_fraction) fusion_coverage = total_coverage * fusion_fraction normal_ref = generate_norm...
16,521
def build_upsample_layer(cfg, *args, **kwargs): """Build upsample layer. Args: cfg (dict): The upsample layer config, which should contain: - type (str): Layer type. - scale_factor (int): Upsample ratio, which is not applicable to deconv. - layer args...
16,522
def ctime_ticks(t): """This is for backwards compatibility and should not be used.""" return tsc_time.TSC_from_ticks(t).ctime()
16,523
def _dynamo_set_last_processed_jenkins_run_id(dynamo_db, jenkins_run): """ Mark the passed Jenkins run as processed in the database. This allows to avoid duplicate processing in future. It's important that runs are processed from oldest to latest (and not in parallel) since we expect to only increase th...
16,524
def vitruvian_loss(input, mask, dataset): """Vitruvian loss implementation""" if dataset == "itop": # 1 - 2 e 1 - 3 -> collo spalle # 2 - 4 e 3 - 5 -> spalle gomito # 4 - 6 e 5 - 7 -> gomito mano # 9 - 11 e 10 - 12 -> anca ginocchio # 11 - 13 e 12 - 14 -> ginocchio piede ...
16,525
def LoadElement(href, only_etag=False): """ Return an instance of a element as a ElementCache dict used as a cache. :rtype ElementCache """ request = SMCRequest(href=href) request.exception = FetchElementFailed result = request.read() if only_etag: return result.etag ...
16,526
def load_config(config_file: str) -> EnvironmentAwareConfigParser: """Load the main configuration and return a config object.""" config = EnvironmentAwareConfigParser() if not os.path.exists(config_file): main_logger.critical('Configuration file "%s" does not exist!', config_file) sys.exit(1...
16,527
def xreplace_indices(exprs, mapper, candidates=None, only_rhs=False): """ Create new expressions from ``exprs``, by replacing all index variables specified in mapper appearing as a tensor index. Only tensors whose symbolic name appears in ``candidates`` are considered if ``candidates`` is not None. ...
16,528
def format_ratio(in_str, separator='/'): """ Convert a string representing a rational value to a decimal value. Args: in_str (str): Input string. separator (str): Separator character used to extract numerator and denominator, if not found in ``in_str`` whitespace is ...
16,529
def fill_tidal_data(da,fill_time=True): """ Extract tidal harmonics from an incomplete xarray DataArray, use those to fill in the gaps and return a complete DataArray. Uses all 37 of the standard NOAA harmonics, may not be stable with short time series. A 5-day lowpass is removed from the ...
16,530
def wrapper_unit_scaling(x, T, s_ref, n_gt, *args, **kwargs): """Normalize segments to unit-length and use center-duration format """ xc = segment_format(x, 'b2c') init_ref = np.repeat(s_ref[:, 0], n_gt) return segment_unit_scaling(xc, T, init_ref)
16,531
def fairseq_generate(data_lines, args, models, task, batch_size, beam_size, device): """beam search | greedy decoding implemented by fairseq""" src_dict = task.source_dictionary tgt_dict = task.target_dictionary gen_args = copy.copy(args) with open_dict(gen_args): gen_args.beam = bea...
16,532
def retrieve_features(dataframe): """ Retrieves features (X) from dataframe :param dataframe: :return: """ return list(dataframe["tweet"])
16,533
def atarzia_short_MD_settings(): """My default settings for short, crude cage optimizations in stk. Modified on 26/04/19. """ Settings = { 'output_dir': None, 'timeout': None, 'force_field': 16, 'temperature': 700, # K 'conformers': 50, 'time_step': 1, ...
16,534
def result_by_score_from_csv(f, score, ascending=True): """Return result with the best defined score""" df = pd.read_csv(f) df.sort_values(score, ascending=ascending, inplace=True) return df.loc[0, ["pdb_code", score]].tolist()
16,535
def similarity_metric_simple_test(cur_samples, next_samples, bins, min_r, max_r): """ Test the output of the 6 similarity metrics for a single set of current and next samples :param cur_samples: samples of the current distribution :param next_samples: samples of the target distribution :param bins: ...
16,536
def create_column_dnn( predict_feature='close', ticker='', debug=False, use_epochs=10, use_batch_size=10, use_test_size=0.1, use_random_state=1, use_seed=7, use_shuffle=False, model_verbose=True, fit_verbose=True, use_scalers=True, df=[], dnn_config={}, compil...
16,537
def _release_lock(key): """Release the lock by deleting the key from the cache.""" django_cache.delete(key)
16,538
def main(): """ Generate CoreML model for benchmark by using non-trained model. It's useful if you just want to measure the inference speed of your model """ hack_coremltools() sizes = [224, 192, 160, 128] alphas = [1., .75, .50, .25] name_fmt = 'mobile_unet_{0:}_{1:03.0f}_{2:03.0f}...
16,539
def get_default_hand_connection_style( ) -> Mapping[Tuple[int, int], DrawingSpec]: """Returns the default hand connection drawing style. Returns: A mapping from each hand connection to the default drawing spec. """ hand_connection_style = {} for k, v in _HAND_CONNECTION_STYLE.items(): for connectio...
16,540
def lists_to_html_table(a_list): """ Converts a list of lists to a HTML table. First list becomes the header of the table. Useful while sending email from the code :param list(list) a_list: values in the form of list of lists :return: HTML table representation corresponding to the values in the li...
16,541
def from_matrix_vector(matrix, vector): """Combine a matrix and vector into a homogeneous transform. Combine a rotation matrix and translation vector into a transform in homogeneous coordinates. Parameters ---------- matrix : ndarray An NxM array representing the the linear part of...
16,542
def test_escaped_brackets(capsys): """Don't warn if it seems fine.""" # escaped cases command_fix('one two three \(\) four five six') out, _err = capsys.readouterr() assert "unescaped brackets" not in out command_fix('one two three \'()\' four five six') out, _err = capsys.readouterr() ...
16,543
async def _time_sync_task(time_between_syncs_s=300): """ task for synchronising time """ while True: try: server_time = await _time_from_server() _set_system_time(server_time) except Exception as e: grown_log.error("time_control: %s" % str(e)) ...
16,544
def take_closest(myList, myNumber): """ Assumes myList is sorted. Returns closest value to myNumber. If two numbers are equally close, return the smallest number. """ pos = bisect_left(myList, myNumber) if pos == 0: return myList[0] if pos == len(myList): return myList[-1] ...
16,545
def check_host(host): """ Helper function to get the hostname in desired format """ if not ('http' in host and '//' in host) and host[len(host) - 1] == '/': return ''.join(['http://', host[:len(host) - 1]]) elif not ('http' in host and '//' in host): return ''.join(['http://', host]) elif host[len(host) - 1] ==...
16,546
def job_wrapper_output_files(params, user_defined_work_func, register_cleanup, touch_files_only): """ job wrapper for all that only deals with output files. run func on any output file if not up to date """ job_wrapper_io_files(params, user_defined_work_func, register_cleanup, touch_files_only, ...
16,547
def do_bay_show(cs, args): """Show details about the given bay. (Deprecated in favor of cluster-show.) """ bay = cs.bays.get(args.bay) if args.long: baymodel = cs.baymodels.get(bay.baymodel_id) del baymodel._info['links'], baymodel._info['uuid'] for key in baymodel._info: ...
16,548
def task_time_slot_add(request, task_id, response_format='html'): """Time slot add to preselected task""" task = get_object_or_404(Task, pk=task_id) if not request.user.profile.has_permission(task, mode='x'): return user_denied(request, message="You don't have access to this Task") if request....
16,549
def get_artist_names(res: dict[str, Any]) -> str: """ Retrieves all artist names for a given input to the "album" key of a response. """ artists = [] for artist in res["artists"]: artists.append(artist["name"]) artists_str = ", ".join(artists) return artists_str
16,550
def json_response(func): """ View decorator function that converts the dictionary response returned by a view function to django JsonResponse. """ @wraps(func) def func_wrapper(request, *args, **kwargs): func_response = func(request, *args, **kwargs) status_code = func_response.g...
16,551
def clean_df(df): """return : pandas.core.frame.DataFrame""" df.index = pd.DatetimeIndex(df.comm_time) df = df.sort_index() df = df[~(np.abs(df.com_per-df.com_per.mean())>(3*df.com_per.std()))]#清洗出三个标准差之外的数据,人均有关的计算用df2 df = df.drop('_id',1) df = df.drop_duplicates() return df
16,552
def _nonnull_powerset(iterable) -> Iterator[Tuple[Any]]: """Returns powerset of iterable, minus the empty set.""" s = list(iterable) return itertools.chain.from_iterable( itertools.combinations(s, r) for r in range(1, len(s) + 1))
16,553
def _parse_obs_status_file(filename): """ Parse a yaml file and return a dictionary. The dictionary will be of the form: {'obs': [], 'bad': [], 'mags: []} :param filename: :return: """ with open(filename) as fh: status = yaml.load(fh, Loader=yaml.SafeLoader) if 'obs' not in sta...
16,554
def extract_optional_suffix(r): """ a | a b -> a b? """ modified = False def match_replace_fn(o): if isinstance(o, Antlr4Selection): potential_prefix = None potential_prefix_i = None to_remove = [] for i, c in enumerate(o): if...
16,555
def _heading_index(config, info, token, stack, level, blockquote_depth): """Get the next heading level, adjusting `stack` as a side effect.""" # Treat chapter titles specially. if level == 1: return tuple(str(i) for i in stack) # Moving up if level > len(stack): if (level > len(stac...
16,556
def sin_salida_naive(vuelos: Data) -> List[str]: """Retorna una lista de aeropuertos a los cuales hayan llegado vuelos pero no hayan salido vuelos de este. :param vuelos: Información de los vuelos. :vuelos type: Dict[str, Dict[str, Union[str, float]]] :return: Lista de aeropuertos :rtype: List[...
16,557
def test_persistent_group_missed_inv_resp(dev): """P2P persistent group re-invocation with invitation response getting lost""" form(dev[0], dev[1]) addr = dev[1].p2p_dev_addr() dev[1].global_request("SET persistent_reconnect 1") dev[1].p2p_listen() if not dev[0].discover_peer(addr, social=True):...
16,558
def converter(doc): """ This is a function for converting various kinds of objects we see inside a graffle document. """ if doc.nodeName == "#text": return str(doc.data) elif doc.nodeName == "string": return str(doc.firstChild.data) elif doc.nodeName == 'integer': return int(doc.firstChi...
16,559
def printable_cmd(c): """Converts a `list` of `str`s representing a shell command to a printable `str`.""" return " ".join(map(lambda e: '"' + str(e) + '"', c))
16,560
def details_from_params( params: QueryParams, items_per_page: int, items_per_page_async: int = -1, ) -> common.Details: """Create details from request params.""" try: page = int(params.get('page', 1)) except (ValueError, TypeError): page = 1 try: anchor =...
16,561
def write_gif_with_tempfiles(clip, filename, fps=None, program= 'ImageMagick', opt="OptimizeTransparency", fuzz=1, verbose=True, loop=0, dispose=True, colors=None, tempfiles=False): """ Write the VideoClip to a GIF file. Converts a VideoClip into an animated GIF using ImageMagick or ffmpeg. ...
16,562
def error(msg): """Exit with error 'msg' """ sys.exit("ERROR: " + msg)
16,563
def run_nuclei_type_stat( pred_dir, true_dir, nuclei_type_dict, type_uid_list=None, exhaustive=True, rad=12, verbose=False ): """ rad = 12 if x40 rad = 6 if x20 """ def _get_type_name(uid, ntd=nuclei_type_dict): for name,v in ntd.items(): if v == uid: return n...
16,564
def redirect(): """ Redirects standard input into standard output """ for line in sys.stdin: print(line, file=sys.stdout, end="")
16,565
def _signature_pre_process_predict( signature: _SignatureDef) -> Tuple[Text, Mapping[Text, Text]]: """Returns input tensor name and output alias tensor names from signature. Args: signature: SignatureDef Returns: A tuple of input tensor name and output alias tensor names. """ input_tensor_names ...
16,566
def _generate_features(reader, paths, same_size=False): """Load and stack features in a memory efficient way. This function is meant to be used inside :py:func:`vstack_features`. Parameters ---------- reader : ``collections.Callable`` See the documentation of :py:func:`vstack_features`. paths : ``colle...
16,567
def draw_polygon_outline(point_list: PointList, color: Color, line_width: float=1): """ Draw a polygon outline. Also known as a "line loop." Args: :point_list: List of points making up the lines. Each point is in a list. So it is a list of lists. :color: co...
16,568
def edit_photo_caption(token: str, photo: Path): """Run a bot that tests sendPhoto and editMessageCaption""" trio.run(run_bot, token, lambda b, u: edit_photo_caption_handler(b, u, photo))
16,569
def test_key_raises(): """Constructing Site with an invalid key should raise an exception.""" with pytest.raises(ValueError): Site("invalid_key")
16,570
def virtualenv(ctx: DoctorContext): """Check that we're in the correct virtualenv.""" try: venv_path = pathlib.Path(os.environ['VIRTUAL_ENV']).resolve() except KeyError: ctx.error('VIRTUAL_ENV not set') return # When running in LUCI we might not have gone through the normal envi...
16,571
def style_95_read_mode(line, patterns): """Style the EAC 95 read mode line.""" # Burst mode doesn't have multiple settings in one line if ',' not in line: return style_setting(line, 'bad') split_line = line.split(':', 1) read_mode = split_line[0].rstrip() line = line.replace(read_mode,...
16,572
def test_get_organizations(gc): """Check that get_organizations is able to retrieve a list of organization""" responses.add( responses.GET, 'https://api.github.com/user/orgs', json=[{'login': 'power_rangers'}, {'login': 'teletubbies'}], status=200, ) res = gc.get_organiza...
16,573
def trange( client, symbol, timeframe="6m", highcol="high", lowcol="low", closecol="close" ): """This will return a dataframe of true range for the given symbol across the given timeframe Args: client (pyEX.Client): Client symbol (string): Ticker timeframe (string): timeframe to...
16,574
def ConvolveUsingAlm(map_in, psf_alm): """Convolve a map using a set of pre-computed ALM Parameters ---------- map_in : array_like HEALPix map to be convolved psf_alm : array_like The ALM represenation of the PSF Returns ------- map_out : array_like The smeared ...
16,575
def load_summary_data(): """ Function to load data param DATA_URL: data_url return: pandas dataframe """ DATA_URL = 'data/summary_df.csv' data = pd.read_csv(DATA_URL) return data
16,576
def _enumerate_trees_w_leaves(n_leaves): """Construct all rooted trees with n leaves.""" def enumtree(*args): n_args = len(args) # trivial cases: if n_args == 0: return [] if n_args == 1: return args # general case of 2 or more args: # build index array idxs = range(0, n_args...
16,577
def list_collections(NextToken=None, MaxResults=None): """ Returns list of collection IDs in your account. If the result is truncated, the response also provides a NextToken that you can use in the subsequent request to fetch the next set of collection IDs. For an example, see Listing Collections in the Ama...
16,578
def lint(shout, requirements): """Check for unused dependencies.""" unused = list(_unused()) if shout: if unused: print("Unused deps:") for d in unused: print(f" - {d}") if unused: exit(1) reqs = _load(requirements) if reqs != sorted(reqs, key=s...
16,579
def main(): """Make a jazz noise here""" args = get_args() sub = args.substring word = args.word # Sanity check if sub not in word: sys.exit(f'Substring "{sub}" does not appear in word "{word}"') # Create a pattern that replaces the length of the sub with any letters pattern =...
16,580
def gen_tfidf(tokens, idf_dict): """ Given a segmented string and idf dict, return a dict of tfidf. """ # tokens = text.split() total = len(tokens) tfidf_dict = {} for w in tokens: tfidf_dict[w] = tfidf_dict.get(w, 0.0) + 1.0 for k in tfidf_dict: tfidf_dict[k] *...
16,581
def timestamp_to_seconds(timestamp): """Convert timestamp to python (POSIX) time in seconds. :param timestamp: The timestamp. :return: The python time in float seconds. """ return (timestamp / 2**30) + EPOCH
16,582
def launch_dpf(ansys_path, ip=LOCALHOST, port=DPF_DEFAULT_PORT, timeout=10, docker_name=None): """Launch Ansys DPF. Parameters ---------- ansys_path : str, optional Root path for the Ansys installation directory. For example, ``"/ansys_inc/v212/"``. The default is the latest Ansys insta...
16,583
def fit_lowmass_mstar_mpeak_relation(mpeak_orig, mstar_orig, mpeak_mstar_fit_low_mpeak=default_mpeak_mstar_fit_low_mpeak, mpeak_mstar_fit_high_mpeak=default_mpeak_mstar_fit_high_mpeak): """ """ mid = 0.5*(mpeak_mstar_fit_low_mpeak + mpeak_mstar_fit_high_mpeak) mask = (mpeak_orig ...
16,584
def load_ref_system(): """ Returns benzaldehyde as found in the IQMol fragment library. All credit to https://github.com/nutjunkie/IQmol """ return psr.make_system(""" C 0.3179 1.0449 -0.0067 C 1.6965 0.8596 -0.0102 C 2.2283 -0.4253 -0...
16,585
def get_department_level_grade_data_completed(request_ctx, account_id, **request_kwargs): """ Returns the distribution of grades for students in courses in the department. Each data point is one student's current grade in one course; if a student is in multiple courses, he contributes one value per cou...
16,586
def allocate_samples_to_bins(n_samples, ideal_bin_count=100): """goal is as best as possible pick a number of bins and per bin samples to a achieve a given number of samples. Parameters ---------- Returns ---------- number of bins, list of samples per bin """ if n_samples <= i...
16,587
def create_algo(name: str, discrete: bool, **params: Any) -> AlgoBase: """Returns algorithm object from its name. Args: name (str): algorithm name in snake_case. discrete (bool): flag to use discrete action-space algorithm. params (any): arguments for algorithm. Returns: d3...
16,588
def tf_inv(T): """ Invert 4x4 homogeneous transform """ assert T.shape == (4, 4) return np.linalg.inv(T)
16,589
def send_reset_password_email(token, to, username): """ send email to user for reset password :param token: token :param to: email address :param username: user.username :return: """ url_to = current_app.config["WEB_BASE_URL"] + "/auth/reset-password?token=" + token response = _send...
16,590
def cleanup_test_resources(instance=None, vm_firewall=None, key_pair=None, network=None): """Clean up any combination of supplied resources.""" with cb_helpers.cleanup_action( lambda: cleanup_network(network) if network else None): with cb_helpers.cleanup_action( ...
16,591
def part1(data): """Solve part 1""" countIncreased = 0 prevItem = None for row in data: if prevItem == None: prevItem = row continue if prevItem < row: countIncreased += 1; prevItem = row return countIncreased
16,592
def yzrotation(theta = np.pi*3/20.0): """ Returns a simple planar rotation matrix that rotates vectors around the x-axis. args: theta: The angle by which we will perform the rotation. """ r = np.eye(3) r[1,1] = np.cos(theta) r[1,2] = -np.sin(theta) r[2,1] = np.sin(theta) ...
16,593
def is_compiled_release(data): """ Returns whether the data is a compiled release (embedded or linked). """ return 'tag' in data and isinstance(data['tag'], list) and 'compiled' in data['tag']
16,594
def resize_frame( frame: numpy.ndarray, width: int, height: int, mode: str = "RGB" ) -> numpy.ndarray: """ Use PIL to resize an RGB frame to an specified height and width. Args: frame: Target numpy array representing the image that will be resized. width: Width of the resized image. ...
16,595
def get_proxies(host, user, password, database, port=3306, unix_socket=None): """"Connect to a mysql database using pymysql and retrieve proxies for the scraping job. Args: host: The mysql database host user: The mysql user password: The database password port: The mysql port, b...
16,596
def main(): """Process files according to the command line arguments.""" parser = ArgParser() handler = Handler(parser.args) print(handler.message) handler.log.logger.info(handler.message) handler.process() handler.log.logger.info(f"Process finished\n") handler.log.close()
16,597
def APIRevision(): """Gets the current API revision to use. Returns: str, The revision to use. """ return 'v1beta3'
16,598
def pretty_string_value_error(value, error, error_digits=2, use_unicode=True): """ Returns a value/error combination of numbers in a scientifically 'pretty' format. Scientific quantities often come as a *value* (the actual quantity) and the *error* (the uncertainty in the value). ...
16,599