content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
import random def describe_current_subtask(subtask, prefix=True): """ Make a 'natural' language description of subtask name """ to_verb = {"AnswerQuestion": "answering a question", "ArmGoal": "moving my arm", "DemoPresentation": "giving a demo", "Find": "fi...
628c699201c26242bd72c6066cba07cce54b14ca
6,165
def addprint(x: int, y: int): """Print and "added" representation of `x` and `y`.""" expr = x + y return "base addprint(x=%r, y=%r): %r" % (x, y, expr)
e3f735afc1d4826a1af7210c3cec88c8b8c87dfe
6,166
import re def parse_date(deadline_date): """ Given a date in the form MM/DD/YY or MM/DD/YYYY, returns the integers MM, DD, and YYYY (or YY) in this order. """ deadline_split = re.split('\\/|\\-', deadline_date) return int(deadline_split[0]), int(deadline_split[1]), int(deadline_split[2])
0ded6bccce8437aad61cfa5ff121c5ed0595849b
6,167
import requests def jyfm_tools_position_fund_direction( trade_date="2020-02-24", indicator="期货品种资金流向排名", headers="" ): """ 交易法门-工具-资金分析-资金流向 https://www.jiaoyifamen.com/tools/position/fund/?day=2020-01-08 :param trade_date: 指定交易日 :type trade_date: str :param indicator: "期货品种资金流向排名" or "期货主...
10cfb29f1705460916fa93542ba72a22b3cdbf70
6,168
def generate_points_in_areas(gdf, values, points_per_unit=1, seed=None): """ Create a GeoSeries of random points in polygons. Parameters ---------- gdf : GeoDataFrame The areas in which to create points values : str or Series The [possibly scaled] number of points to create in each area points_per_unit : nu...
14232540c4bee8c9863b2af4f3f2f200bb261098
6,169
def template_dict(input_dict_arg, params_dict_arg): """function to enable templating a dictionary""" output_dict = input_dict_arg for key, value in output_dict.items(): if isinstance(value, str): output_dict[key] = params_re_str(value, params_dict_arg) elif isinstance(value, dict...
3a9e2df200f52f9ec320ab3900653851dfb77fcc
6,171
def _traverse_dictionaries(instance, parent="spin_systems"): """Parses through the instance object contained within the parent object and return a list of attributes that are populated. Args: instance: An instance object from the parent object. parent: a string object used to create the add...
9ecf8050e7c4d9c4f8e84f04303f0be186f594d5
6,172
def getSingleChildTextByName(rootNode, name): """Returns the text of a child node found by name. Only one such named child is expected. """ try: nodeList = [e.firstChild.data for e in rootNode.childNodes if e.localName == name] if len(nodeList) > 0: return nodeList[0] ...
48a8a4b2c3c95cac944bcb96e33e602d62499f19
6,173
def _get_energy_ratio_single_wd_bin_bootstrapping( df_binned, df_freq, N=1, percentiles=[5.0, 95.0], return_detailed_output=False, ): """Get the energy ratio for one particular wind direction bin and an array of wind speed bins. This function also includes bootstrapping functionality by ...
a29e1ebaa9994148e473d61d7881737b62a9082e
6,175
import re def get_file_name(part): """get file name using regex from fragment ID""" return re.findall(r"='(.*\-[a-z]+).*", part)[0]
30c8867d8e14b04c593359f1c16d9bf324711ba0
6,177
def get_helping_materials(project_id, limit=100, offset=0, last_id=None): """Return a list of helping materials for a given project ID. :param project_id: PYBOSSA Project ID :type project_id: integer :param limit: Number of returned items, default 100 :type limit: integer :param offset: Offset ...
163436a9a09816bc18b31c9911b87db74b8aefbd
6,178
import math def generate_sphere_points(n): """ Returns list of 3d coordinates of points on a sphere using the Golden Section Spiral algorithm. """ points = [] inc = math.pi * (3 - math.sqrt(5)) offset = 2 / float(n) for k in range(int(n)): y = k * offset - 1 + (offset / 2) ...
bd6c7624220f7928a44f6dcb24b7112e8d803eb4
6,179
def svn_repos_dir_delta2(*args): """ svn_repos_dir_delta2(svn_fs_root_t src_root, char src_parent_dir, char src_entry, svn_fs_root_t tgt_root, char tgt_path, svn_delta_editor_t editor, void edit_baton, svn_repos_authz_func_t authz_read_func, svn_boolean_t text_deltas, svn_depth...
c972237fee8c76a24fb9443a9607931566b642ff
6,180
def linear_r2_points(points: np.ndarray, coef: tuple, r2: R2 = R2.classic) -> float: """Computes the coefficient of determination (R2). Args: points (np.ndarray): numpy array with the points (x, y) coef (tuple): the coefficients from the linear fit r2 (R2): select the type of coefficien...
98c33ba3354ed22ddf3ab718f2f41967c2555f18
6,181
from typing import List from datetime import datetime def _show_tournament_list() -> List: """ Функция возвращает список предстоящих турниров """ tournaments = [] for tournament in loop.run_until_complete(get_request('https://codeforces.com/api/contest.list?gym=false')): if tournament['phase'] != 'BEFORE': ...
0815ae126671a8c85bb3311e900db48ce87fa1f0
6,182
def less_goals_scored(): """ returns the lowest number of goals scored during one week """ return goals_scored('min')
fda281196148370d4639aef9dabc6ad1cb4fd339
6,183
from typing import Sequence from typing import Union from typing import Tuple def compute_avgpool_output_shape(input_shape:Sequence[Union[int, None]], kernel_size:Union[Sequence[int], int]=1, stride:Union[Sequence[int], int]=1, ...
5116f6fdb95c1cf07d34c2193e6e08eee47a06da
6,184
def _obs_intersect(((x0, y0), (x1, y1)), ((x2, y2), (x3, y3))): """Check if two lines intersect. The boundaries don't count as intersection.""" base1 = (x0, y0) base2 = (x2, y2) dir1 = (x1-x0, y1-y0) dir2 = (x3-x2, y3-y2) t1, t2 = _intersect(base1, dir1, base2, dir2) eps = 0.00001 ...
ea2b268adac5fc1156b566ea0c6cabdd2f4fe94e
6,185
import json import re def project_configure(request, project_name): """ get configuration :param request: request object :param project_name: project name :return: json """ # get configuration if request.method == 'GET': project = Project.objects.get(name=project_name) ...
a033d7d1810cee5e5370d8d9f6562f23e3e7e64a
6,186
import time def run_epoch(session, model, eval_op=None, verbose=False): """Runs the model on the given data.""" start_time = time.time() costs = 0.0 iters = 0 state = session.run(model.initial_state) fetches = { "cost": model.cost, "final_state": model.final_state, } if eval_op is not None: fetches["...
641100d0789c3841a4b3cb67e42963387d0f888d
6,187
def unemployment( token="", version="stable", filter="", format="json", **timeseries_kwargs ): """Economic data https://iexcloud.io/docs/api/#economic-data Args: token (str): Access token version (str): API version filter (str): filters: https://iexcloud.io/docs/api/#filter-res...
a5412d78673f639e0d10a95bb91138da1b432221
6,188
import warnings def splitunc(p): """Deprecated since Python 3.1. Please use splitdrive() instead; it now handles UNC paths. Split a pathname into UNC mount point and relative path specifiers. Return a 2-tuple (unc, rest); either part may be empty. If unc is not empty, it has the form '//host/mo...
d9748b551e6a9ba101b3817ab22c74dd30cf89d1
6,189
def expand_locations(ctx, input, targets = []): """Expand location templates. Expands all `$(execpath ...)`, `$(rootpath ...)` and deprecated `$(location ...)` templates in the given string by replacing with the expanded path. Expansion only works for labels that point to direct dependencies of this ru...
efa482d928484b7d6f9c8acbf81e0a3d5b4cd50f
6,190
import requests import json def scrape_db(test=False, write_file=True): """ Function to scrape bodybuild.com recipe database and save results as json. Parameters: ----------- """ # Hacky way to get all recipes - you have to request the number. Luckily, # this is listed at the beginning ...
d9883058ac434fca861168625493467bfbcafaed
6,191
import functools def require(required): """ Decorator for checking the required values in state. It checks the required attributes in the passed state and stop when any of those is missing. """ def decorator(function): @functools.wraps(function) def wrapper(*args, **kwargs): ...
9bf04a95d39b89fd10c9872dd7fe29c5c10f06a1
6,192
import re def simplify_unicode(sentence): """ Most accented Latin characters are pronounced just the same as the base character. Shrink as many extended Unicode repertoire into the Estonian alphabet as possible. It is GOOD for machine learning to have smaller ortographic repertoire. It is a BAD id...
291a1e002d4d428697d7b892291ad314f0000a2a
6,193
import pickle def read_file(pickle_file_name): """Reads composite or non-composite novelty results from Pickle file. :param pickle_file_name: Path to input file (created by `write_standard_file` or `write_pmm_file`). :return: novelty_dict: Has the following keys if not a composite... novelty_...
fcc4976648bafc7e845a22552965e1f65e3ddc85
6,194
import re def AutoscalersForMigs(migs, autoscalers, project): """Finds Autoscalers with target amongst given IGMs. Args: migs: List of triples (IGM name, scope type, scope name). autoscalers: A list of Autoscalers to search among. project: Project owning resources. Returns: A list of all Autosc...
12b6e10c16c7ea5324f5090cdc3027a38e1247c1
6,195
def log_loss( predictions: ArrayLike, targets: ArrayLike, ) -> ArrayLike: """Calculates the log loss of predictions wrt targets. Args: predictions: a vector of probabilities of arbitrary shape. targets: a vector of probabilities of shape compatible with predictions. Returns: a vector of same...
a3d27b0229b287e32701fa80822ad1025e875a62
6,196
import json def GetAccessTokenOrDie(options): """Generates a fresh access token using credentials passed into the script. Args: options: Flag values passed into the script. Returns: A fresh access token. Raises: ValueError: response JSON could not be parsed, or has no access_token...
6ecbd6875931c6ef139da52578050380da4e62bd
6,197
def remove_whitespace(tokens): """Remove any top-level whitespace and comments in a token list.""" return tuple( token for token in tokens if token.type not in ('whitespace', 'comment'))
5ed78f38277487d2e05e20e10e25413b05cab8e5
6,198
def update(args): """ For LdaCgsMulti """ (docs, doc_indices, mtrand_state, dtype) = args start, stop = docs[0][0], docs[-1][1] global Ktype if _K.value < 2 ** 8: Ktype = np.uint8 elif _K.value < 2 ** 16: Ktype = np.uint16 else: raise NotImplementedError("Inv...
2dd014472c77e363fafab1f9dc22ce0267d3e3df
6,199
def warn(string: str) -> str: """Add warn colour codes to string Args: string (str): Input string Returns: str: Warn string """ return "\033[93m" + string + "\033[0m"
0bdbe5e7052e1994d978e45273baef75a1b72d89
6,200
def normalized_mean_square_error(logits, labels, axis = [0,1,2,3]): """ logits : [batch_size, w, h, num_classes] labels : [batch_size, w, h, 1] """ with tf.name_scope("normalized_mean_square_error"): nmse_a = tf.sqrt(tf.reduce_sum(tf.squared_difference(logits, labels), axis=[1,2,3])) ...
0aee175ed0be3132d02018961265461e4880221b
6,201
def get_partition_to_num_rows( namespace, tablename, partition_column, partition_column_values ): """ Helper function to get total num_rows in hive for given partition_column_values. """ partitions = { "{0}={1}".format(partition_column, partition_column_value) for partition_colum...
305d40fd326bc45e906925b94077182584ffe3be
6,203
def get_welcome_response(): """ If we wanted to initialize the session to have some attributes we could add those here """ session_attributes = initialize_game() card_title = "Welcome" speech_output = "Hello! I am Cookoo. Let's play a game. " \ "Are you ready to play?" ...
9c28194575013e98d1d6130a956714f65ebe3764
6,204
def kl_divergence_with_logits(logits_a, logits_b): """ Compute the per-element KL-divergence of a batch. Args: logits_a: tensor, model outputs of input a logits_b: tensor, model outputs of input b Returns: Tensor of per-element KL-divergence of model outputs a and b """...
7df5976287edf5de37291db653a4334ed046a2f3
6,205
import csv def load_labels(abs_path): """ loads relative path file as dictionary Args: abs_path: absolute path Returns dictionary of mappings """ label_tsv = open(abs_path, encoding="utf-8") labels = list(csv.reader(label_tsv, delimiter="\t")) return labels
8ded58965dcc98b7a0aaa6614cbe4b66722dc76b
6,206
def cut_tree_balanced(linkage_matrix_Z, max_cluster_size, verbose=False): """This function performs a balanced cut tree of a SciPy linkage matrix built using any linkage method (e.g. 'ward'). It builds upon the SciPy and Numpy libraries. The function looks recursively along the hierarchical ...
53290f432b9ad7404760e124ffe6d03e95e5d529
6,207
from typing import Callable def len_smaller(length: int) -> Callable: """Measures if the length of a sequence is smaller than a given length. >>> len_smaller(2)([0, 1, 2]) False """ def len_smaller(seq): return count(seq) < length return len_smaller
a43f1344a46a57d443d267de99ba7db08b9bf911
6,208
def e_2e_fun(theta, e_init=e_1f): """ Electron energy after Compton scattering, (using energy e_1f) :param theta: angle for scattered photon :param e_init: initial photon energy :return: """ return e_init / (((m_e * c ** 2) / e_init) * (1 / (1 - np.cos(theta))) + 1)
8785f6dfbb4226df88e6ab2b883a989ff799d240
6,209
from typing import List def interval_list_intersection(A: List[List], B: List[List], visualization: bool = True) -> List[List]: """ LeteCode 986: Interval List Intersections Given two lists of closed intervals, each list of intervals is pairwise disjoint and in sorted order. Return the intersectio...
722902e4c4c076a1dc25d07cc3253b2ec9f3d110
6,212
def tokenize_query(query): """ Tokenize a query """ tokenized_query = tokenizer.tokenize(query) stop_words = set(nltk.corpus.stopwords.words("english")) tokenized_query = [ word for word in tokenized_query if word not in stop_words] tokenized_query = [stemmer.stem(word) for word in tokenized...
422d59dc95661496dcfac83f142190a94127ae68
6,214
def rewrite_return(func): """Rewrite ret ops to assign to a variable instead, which is returned""" ret_normalization.run(func) [ret] = findallops(func, 'ret') [value] = ret.args ret.delete() return value
d141ae9d2f36f4f3e41da626ed43a3902e43c267
6,215
def get_loss_fn(loss_factor=1.0): """Gets a loss function for squad task.""" def _loss_fn(labels, model_outputs): start_positions = labels['start_positions'] end_positions = labels['end_positions'] start_logits, end_logits = model_outputs return squad_loss_fn( start_positions, end_p...
ad07afbd39aa1338a0aeb3c1398aefacebceffa3
6,216
import asyncio async def run_command(*args): """ https://asyncio.readthedocs.io/en/latest/subprocess.html """ # Create subprocess process = await asyncio.create_subprocess_exec( *args, # stdout must a pipe to be accessible as process.stdout stdout=asyncio.subprocess.PIPE) ...
a0071a1bb8ba169179c67d22f5c8caca717697b3
6,217
def get_variants_in_region(db, chrom, start, stop): """ Variants that overlap a region Unclear if this will include CNVs """ xstart = get_xpos(chrom, start) xstop = get_xpos(chrom, stop) variants = list(db.variants.find({ 'xpos': {'$lte': xstop, '$gte': xstart} }, projection={'_id': Fals...
5665f4ff65832449c2dd7edb182fc3bd0707d189
6,218
def get_business(bearer_token, business_id): """Query the Business API by a business ID. Args: business_id (str): The ID of the business to query. Returns: dict: The JSON response from the request. """ business_path = BUSINESS_PATH + business_id #4 return request(API_HOST, b...
982eb518b7d9f94b7208fb68ddbc9f6607d9be9a
6,219
from keras.layers import Conv2D, Input, MaxPooling2D, ZeroPadding2D from keras.layers.normalization import BatchNormalization from keras.layers.merge import concatenate from keras.models import Model from keras.regularizers import l2 def AlexNet_modified(input_shape=None, regularize_weight=0.0001): """ Alexn...
b4bf37200a2bf429fe09eb9893b673e381ce0b36
6,220
import re def readblock(fileObj): """ parse the block of data like below ORDINATE ERROR ABSCISSA 2.930E-06 1.8D-07 5.00E+02 X. 8.066E-06 4.8D-07 6.80E+02 .X. 1.468E-05 8.3D-07 9.24E+02 ..X. 2.204E-05 1.2D-06 1.26E+03 ...
838adc5e4efc4f97c255917e8d51b5da398718bd
6,221
def as_scalar(scalar): """Check and return the input if it is a scalar. If it is not scalar, raise a ValueError. Parameters ---------- scalar : Any the object to check Returns ------- float the scalar if x is a scalar """ if isinstance(scalar, np.ndarray): ...
ca5dd15eb2672ec61785dd2a36495d61ad4a3f9f
6,222
import itertools def evaluate_dnf( # pylint: disable=too-many-arguments,too-many-locals num_objects: int, num_vars: int, nullary: np.ndarray, unary: np.ndarray, binary: np.ndarray, and_kernel: np.ndarray, or_kernel: np.ndarray, target_arity: int, ) -> np.ndarray: """Evaluate given...
2a73f917594361ba4837e7e1d5f45398b3b0eb8d
6,223
def black_color_func(word, font_size, position, orientation, random_state=None, **kwargs): """Make word cloud black and white.""" return("hsl(0,100%, 1%)")
d5e874a4f62d30abcba29476d0ba7fc3a31b0ca6
6,224
import re def setup(hass, config): """ Setup history hooks. """ hass.http.register_path( 'GET', re.compile( r'/api/history/entity/(?P<entity_id>[a-zA-Z\._0-9]+)/' r'recent_states'), _api_last_5_states) hass.http.register_path('GET', URL_HISTORY_PERIOD, _api...
c87ddf7d7473d49b142a866043c0adee216aed39
6,225
import itertools def fitallseq(digitslist, list): """if there is repeating digits, itertools.permutations() is still usable if fail, still print some print, if i >= threshold, served as start point for new searching """ for p in itertools.permutations(digitslist): #print "".join(pw) i=0 ...
069c9a2038593e7146558a53ac86c8fe877b44d3
6,227
def adduser(args): """Add or update a user to the database: <username> <password> [[role] [role] ...]""" try: username, password = args[0:2] except (IndexError, ValueError), exc: print >> sys.stderr, "you must include at least a username and password: %s" % exc usage() try: ...
7522753dff0647ac0764078902bf87c888f5a817
6,228
def check_linear_dependence(matrix: np.ndarray) -> bool: """ Functions checks by Cauchy-Schwartz inqeuality whether two matrices are linear dependent or not. :param matrix: 2x2 matrix to be processed. :return: Boolean. """ for i in range(matrix.shape[0]): for j in range(matrix.shape[0]):...
1b962afc16c135c49409a1cfb1f4c2b6a5695c75
6,229
import json def cors_400(details: str = None) -> cors_response: """ Return 400 - Bad Request """ errors = Model400BadRequestErrors() errors.details = details error_object = Model400BadRequest([errors]) return cors_response( req=request, status_code=400, body=json.du...
1f775db943ed0989da49d1b7a6952d7614ace982
6,230
def detect_label_column(column_names): """ Detect the label column - which we display as the label for a joined column. If a table has two columns, one of which is ID, then label_column is the other one. """ if (column_names and len(column_names) == 2 and "id" in column_names): return [c fo...
40524e7ed0878316564ad8fd66a2c09fc892e979
6,231
import glob def sorted_files(pattern): """Return files matching glob pattern, *effectively* sorted by date """ return sort_files(glob.glob(pattern))
4fb2ad9f6396cb844320e4e3aeb2941567d8af4a
6,233
import torch def random_float_tensor(seed, size, a=22695477, c=1, m=2 ** 32, requires_grad=False): """ Generates random tensors given a seed and size https://en.wikipedia.org/wiki/Linear_congruential_generator X_{n + 1} = (a * X_n + c) % m Using Borland C/C++ values The tensor will have values be...
c6c8ce42b2774204c3156bdd7b545b08315d1606
6,234
def derivable_rng(spec, *, legacy=False): """ Get a derivable RNG, for use cases where the code needs to be able to reproducibly derive sub-RNGs for different keys, such as user IDs. Args: spec: Any value supported by the `seed` parameter of :func:`seedbank.numpy_rng`, in addition ...
0772c9d27ba166f0981b3eb1da359a3ebb973322
6,235
def table(custom_headings, col_headings_formatted, rows, spec): """ Create a LaTeX table Parameters ---------- custom_headings : None, dict optional dictionary of custom table headings col_headings_formatted : list formatted column headings rows : list of lists of cell-str...
0ca28fce26fc7476aa5b88a621c5476ae8d381ce
6,236
def skipIfNoDB(test): """Decorate a test to skip if DB ``session`` is ``None``.""" @wraps(test) def wrapper(self, db, *args, **kwargs): if db.session is None: pytest.skip('Skip because no DB.') else: return test(self, db, *args, **kwargs) return wrapper
a75cc067679aaab3fec78c2310cbc2e34a19cee7
6,238
def rboxes2quads_numpy(rboxes): """ :param rboxes: ndarray, shape = (*, h, w, 5=(4=(t,r,b,l) + 1=angle)) Note that angle is between [-pi/4, pi/4) :return: quads: ndarray, shape = (*, h, w, 8=(x1, y1,... clockwise order from top-left)) """ # dists, shape = (*, h, w, 4=(t,r,b,l)) # angles,...
a5c48d48444f3c063fe912e2c6e76de373f7a1fc
6,239
from typing import Callable from typing import Optional from typing import Mapping from typing import Any import reprlib from typing import List import inspect from typing import cast from typing import MutableMapping def repr_values(condition: Callable[..., bool], lambda_inspection: Optional[ConditionLambdaInspectio...
d7218029fd387bae108eedf49c9eef14d98e3c70
6,240
def human_permissions(permissions, short=False): """Get permissions in readable form. """ try: permissions = int(permissions) except ValueError: return None if permissions > sum(PERMISSIONS.values()) or permissions < min( PERMISSIONS.values() ): return "" ...
0d9c15659c93833042f44a0a96746e2f1dd9d307
6,241
def predict(): """ Prediction end point Post a JSON holding the features and expect a prediction Returns ------- JSON The field `predictions` will hold a list of 0 and 1's corresponding to the predictions. """ logger.info('Starting prediction') json_ = request.get_j...
6899725edff8d2536c4a97018a5c6c7a4e0d416e
6,242
from unittest.mock import call def run_program(program, cmdargs, stdin_f, stdout_f, stderr_f, run=True, cmd_prepend="", run_from_cmd=True, **kwargs): """Runs `program` with `cmdargs` using `subprocess.call`. :param str stdin_f: File from which to take standard input :param ...
aea74ec8ac296567b16e6f76eed1360e8bc76f69
6,243
def second_step_red(x: np.array, y: np.array, z: np.array, px: np.array, py: np.array, pz: np.array, Fx: np.array, Fy: np.array, Fz: np.array, z_start: float, z_stop: float) -> (np.array, np.array, np.array, ...
909f16a51074ca0c52641d3539509e513ca4ac80
6,244
def drop_tabu_points(xf, tabulist, tabulistsize, tabustrategy): """Drop a point from the tabu search list.""" if len(tabulist) < tabulistsize: return tabulist if tabustrategy == 'oldest': tabulist.pop(0) else: distance = np.sqrt(np.sum((tabulist - xf)**2, axis=1)) index ...
4cd8887bdd77bb001635f0fba57f5908f3451642
6,245
def get_atom_feature_dims(list_acquired_feature_names): """ tbd """ return list(map(len, [CompoundKit.atom_vocab_dict[name] for name in list_acquired_feature_names]))
575de38dc0fdd198f6a6eb5cbb972063260bc4d4
6,246
def parse_selector(selector): """Parses a block of selectors like div .name #tag to class=.name, selector=div and id=#tag. Returns (selector, id, class[]) """ m_class, m_id, m_selector, m_attr = [], None, None, {} if selector is not None and type(selector) == str: selector_labels = selector.spli...
eadaa4cd79ed933325b0058e752a7187d5a09085
6,247
def is_batch_enabled(release_id): """ Check whether batching is enabled for a release. """ details = get_release_details_by_id(release_id) return details['data']['attributes']['enable_batching']
e22965166b35584e172e775b16a9d84affe5868f
6,248
import contextlib def create(tiles): """Handler.""" with futures.ThreadPoolExecutor(max_workers=8) as executor: responses = executor.map(worker, tiles) with contextlib.ExitStack() as stack: sources = [ stack.enter_context(rasterio.open(tile)) for tile in responses if tile ...
cd080b0df34b12f8045420ac076f8e9ee6bc7c15
6,249
def _rfftn_empty_aligned(shape, axes, dtype, order='C', n=None): """Patched version of :func:`sporco.fft.rfftn_empty_aligned`. """ ashp = list(shape) raxis = axes[-1] ashp[raxis] = ashp[raxis] // 2 + 1 cdtype = _complex_dtype(dtype) return cp.empty(ashp, cdtype, order)
a85ab3a938694a82d186b968a2d7d4c710f1ecde
6,251
def get_test_config(): """ Returns a basic FedexConfig to test with. """ # Test server (Enter your credentials here) return FedexConfig(key='xxxxxxxxxxxxxxxxx', password='xxxxxxxxxxxxxxxxxxxxxxxxx', account_number='xxxxxxxxx', mete...
81b29fbb135b30f24aa1fe7cb32844970617f0ee
6,252
from datetime import datetime import itertools import json import logging import csv def write_data(movies, user, data_format='json'): """ """ assert movies, 'no data to write' date = datetime.now().strftime('%Y%m%d') movies_clean = itertools.chain.from_iterable((json.loads(el) for el in movies)) ...
704ebf1aa1b45855b8fade61cdf6a9bb12e44c83
6,253
import json import tempfile def get_genotypes( single_end: list, paired_end: list, metadata: str, bam_dir: str, intermediate_dir: str, reference_genome_path: str, mapping_quality: int, blacklist_path: str, snps_path: str, processes: int, memory: int, skip_preprocessing:...
7ee61a9b8dfbbedf7d595034a40ae9084e1fa69f
6,254
def async_handle_google_actions(hass, cloud, payload): """Handle an incoming IoT message for Google Actions.""" result = yield from ga.async_handle_message( hass, cloud.gactions_config, payload) return result
1c9ec2e37a1c752abb59301f546db4e14fdf57d8
6,255
def get_picture_landmarks(filepath, predictor, logs=True): """ Do the doc! """ if logs: print("Processing file: {}".format(filepath)) frame = cv2.imread(filepath) lm = FLandmarks() lm.extract_points(frame, predictor) return lm if logs: print('\n')
02b92c663c9efe3fad18b35b3808e0b004b1a8c0
6,256
def conflict(next_x: int, s: tuple) -> bool: """Return a boolean that defines the conflict condition of the next queen's position""" next_i = len(s) for i in range(next_i): if abs(s[i] - next_x) in (0, next_i - i): return True else: return False
cc29b142e1cc799c0a305523b713c5085af25fd0
6,257
async def main_page(): """Main page. Just for example.""" return APIResponse(message="ok")
f1a2022df08725388c02dabe77bc4ee29eb5f968
6,258
from typing import List def split_to_sublists(initial_list:list, n:int, strict:bool=True) -> List[list]: """Takes a list and splits it into sublists of size n Parameters ---------- initial_list : list The initial list to split into sublists n : int The size of each sublist s...
fcca74f9814020c99aaf8b31f092ca3ca9533216
6,259
from pathlib import Path def get_sha1(req_path: Path) -> str: """ For larger files sha1 algorithm is significantly faster than sha256 """ return get_hash(req_path, sha1)
768f101fe4ad57eaea9ccd68d247e6a85b1cebaa
6,261
def _make_note(nl_transcript: str, tl_audio_file: str) -> Note: """ Creates an Anki note from a native langauge transcript and a target language audio file. """ return Note(model=_MODEL, fields=[f"[sound:{tl_audio_file}]", nl_transcript])
4765e39b2c3a7794fb973de2b9424bad361cbe4c
6,263
from datetime import datetime def bed2beddb_status(connection, **kwargs): """Searches for small bed files uploaded by user in certain types Keyword arguments: lab_title -- limit search with a lab i.e. Bing+Ren, UCSD start_date -- limit search to files generated since a date formatted YYYY-MM-DD ru...
2fb1f67cc256bc1ff04c4a5e8c1fa61f43f69d30
6,264
def parse_urdf_file(package_name, work_name): """ Convert urdf file (xml) to python dict. Using the urdfpy package for now. Using the xml package from the standard library could be easier to understand. We can change this in the future if it becomes a mess. """ rospack = rospkg.RosPack() ...
7b209216d9f65303441e5e9f761119bfa9fc5810
6,265
def _get_mgmtif_mo_dn(handle): """ Internal method to get the mgmt_if dn based on the type of platform """ if handle.platform == IMC_PLATFORM.TYPE_CLASSIC: return("sys/rack-unit-1/mgmt/if-1") elif handle.platform == IMC_PLATFORM.TYPE_MODULAR: return("sys/chassis-1/if-1") else: ...
455c5baf0f659b98c78bfcc386bd03e0850df267
6,266
def sectionize(parts, first_is_heading=False): """Join parts of the text after splitting into sections with headings. This function assumes that a text was splitted at section headings, so every two list elements after the first one is a heading-section pair. This assumption is used to join sections wi...
402832d55268dc808888f94b95e3a1c991394041
6,268
def byte_compare(stream_a, stream_b): """Byte compare two files (early out on first difference). Returns: (bool, int): offset of first mismatch or 0 if equal """ bufsize = 16 * 1024 equal = True ofs = 0 while True: b1 = stream_a.read(bufsize) b2 = stream_b.read(bufsi...
59adfe50fefdb79edd082a35437018d4b954ec75
6,269
from re import A def get_resize_augmentation(image_size, keep_ratio=False, box_transforms=False): """ Resize an image, support multi-scaling :param image_size: shape of image to resize :param keep_ratio: whether to keep image ratio :param box_transforms: whether to augment boxes :return: album...
62affae338e16cb0e7fc609d0ee995c728d6ec47
6,270
def extract_question(metric): """Extracts the name and question from the given metric""" with open(metric) as f: data = f.readlines() data = [x.strip() for x in data] # filter out empty strings data = list(filter(None, data)) # data[0] = '# Technical Fork' metric_name = data[0].sp...
27ddc25c489d19e1ca17ae80774e20c14208b653
6,271
def get_side(node, vowels, matcher, r): """Get side to which char should be added. r means round (or repeat). Return 0 or plus int to add char to right, minus int to left, None if char node should be avoided. """ # check if node has both char neighbours if node.next is None: if node...
b7a34982bed475cacef08faf8f4d6155fc4147fb
6,272
def gap_perform_pruning(model_path, pruned_save_path=None, mode='gap', slim_ratio=0.5, mask_len=False, full_save=False, full_save_path=None, var_scope='', ver=1): """ Interface for GAP pruning step (step2). Args: model_path: path to the saved checkpoint, ...
b49b7f5d61113990746ef37d03267805424f10be
6,273
def html_wrap(ptext, owrapper, attribute=''): """ Wrap text with html tags. Input: ptext -- text to be wrapped owrapper -- tag to wrap ptext with attribute -- if set, attribute to add to ptext If owrapper ends with a newline, then the newline will appear after the bracket c...
3a9d6fcf165ce6ad46ecc2ab7437b794d03449d9
6,274
def names(namespace): """Return extension names without loading the extensions.""" if _PLUGINS: return _PLUGINS[namespace].keys() else: return _pkg_resources_names(namespace)
de772f9c671b92f9707e333006354d89ba166ae2
6,276
def cfq_lstm_attention_multi(): """LSTM+attention hyperparameters tuned for CFQ.""" hparams = common_hparams.basic_params1() hparams.daisy_chain_variables = False hparams.batch_size = 1024 hparams.hidden_size = 128 hparams.num_hidden_layers = 2 hparams.initializer = 'uniform_unit_scaling' hparams.initia...
7f982aff67a58200c7a297a5cfbfee6cc3c33173
6,277
def create_modeling_tables(spi_historical, spi_fixtures, fd_historical, fd_fixtures, names_mapping): """Create tables for machine learning modeling.""" # Rename teams for col in ['team1', 'team2']: spi_historical = pd.merge(spi_historical, names_mapping, left_on=col, right_on='left_team', how='left...
bfaab71b64979859b7ec474dbf1805e117d9730d
6,278
import math import random def daily_selection(): """ Select a random piece of material from what is available. A piece is defined by a newline; every line is a new piece of content. """ logger.log("Selecting today's material") with open(settings.CONTENT, "r") as file: content = file.re...
2b16be5e02273e539e7f0417ef72d28de91624cb
6,279