content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def compose_class(class_names): """Create a composite class from a list of class names.""" classes = [] classes.append(Basic) # Class is the root of inheritance for class_name in class_names: if class_name != "basic": # Normally this is not explicitly specified, so is implicit, but even it i...
a3884b8a5bc5f836b12757a288605f49a57b6e9f
3,611,027
def create_cancel_jobs_messages(job_ids, when): """Creates messages to cancel the given jobs :param job_ids: The job IDs to cancel :type job_ids: list :param when: The cancel time :type when: :class:`datetime.datetime` :return: The list of messages :rtype: list """ messages = [] ...
876e255f221b79da3aac10757ff3af9ada50974e
3,611,029
import functools def postprocess(output, length_1, length_2): """Post process the output of the inferred alignment.""" score, paths, sw_params = tf.nest.map_structure( functools.partial(tf.squeeze, axis=0), output) # Stacks SW params, flipping sign of gap penalties for convenience. substitution_scores, ...
e7027fa4d7e8408b491e7fd9febad99e5ac20e98
3,611,030
def select_random_word() -> str: """Selects a random word from the lexicon.""" next_word = lexicon.sample(RandomWordSelectStrategy()) print(f"Chose: {next_word}!") return next_word
412a62c58ea6978e2ca40e5ca614c06589f5ba64
3,611,031
import regex def split_at_pattern(text, pattern): """ Split a string where a pattern begins """ obj = regex.search(pattern, text) if obj: start = obj.start() return text[0:start], text[start:] else: return text, ""
a33bc599eb2575fc0ec0e09571095b49fa3ac74b
3,611,033
def focal_lossIII(prediction_tensor, target_tensor, weights, gamma=2., epsilon=0.00001, ): """Compute loss function. This function was adapted from the Tensorflow issues section on GitHub. Args: prediction_tens...
4f9b332165ce2565344de4d62dd7e73e2dee35af
3,611,035
def draw_vertical_bar(info:pd.Series)->plt.Figure: """Dibuja un vertical bar chart basado en un analisis previamente hecho Args: info (pd.Series): Los datos a graficar Returns: [plt.Figure]: La figura armada """ plt.bar(info.index, height=info) return plt.gcf()
93b46e3dd5f15d8c8d619db79145b10fd50eb391
3,611,036
import collections def set_seed_iftrue(condition, seed=10): """ Fix the seed for random test. Parameters ---------- seed : int Random seed passed to np.random.seed Returns ------- decorator : function Decorator which, when applied to a function, sets the random ...
d791bb843594ea64f795b517334da6364a9d3e95
3,611,037
from datetime import datetime def get_current_utc_time(): """Return string representation of current time in UTC.""" utcnow = datetime.datetime.utcnow() return str(utcnow.timestamp())
0f5be8928a6706e9fe8db497d314502db35b6317
3,611,038
import unittest def _split_extension_test(ctx): """Unit tests for paths.split_extension.""" env = unittest.begin(ctx) # Try some degenerate cases. asserts.equals(env, ("", ""), paths.split_extension("")) asserts.equals(env, ("/", ""), paths.split_extension("/")) asserts.equals(env, ("foo", ""...
c60a5ce93cc746a7e0c1d140931298c9e54712a0
3,611,039
import configparser def get_cluster_details(): """ Gets the credentials from the config file """ config = configparser.ConfigParser() config.read_file(open('dwh.cfg')) KEY = config.get('AWS','KEY') SECRET = config.get('AWS','SECRET') DWH_CLUSTER...
a7d19c76e134b74d18a37289c16221064664c036
3,611,040
import select def get_publication_comments(project, publication_id): """ List all comments for the given publication """ connection = db_engine.connect() publications = get_table("publication") publication_comments = get_table("publication_comment") statement = select([publications.c.publi...
286c6ab192fdd5d235bf52ae4191ef37a1b99ab5
3,611,041
from typing import Dict from typing import Optional def parse_genapp_customer(genapp_record: Dict) -> Optional[X12Demographics]: """ Parses a GenApp Customer from a JSON response to a X12Demographics model :param genapp_record: The GenApp Customer record :return: The X12Demographics model for the cust...
4fae35ea6f8fc57639f0eb7672eae7d359b0c1f4
3,611,042
def get_best_shift(img): """ DESCRIPTION: Calculate the center of mass of the input image and return the best shift amount to center an image on the character. INPUT: Image OUTPUT: Calculated shift amount for x and y directions """ # Calculate the center of mass through scipy center_y, c...
328a48d0a2c041c55260f591ce50ef93f3265b63
3,611,044
def main(): """ The main function to execute upon call. Returns ------- int returns integer 0 for safe executions. """ print("Program to check positive, negative, or zero input.") temp = check_number_sign() return 0
cd551c867c50b258bfd109b1c6ad326a6d039b19
3,611,045
import torch def class_to_val(raw_scores): """ Finds the highest softmax for each class :param raw_scores: tensor (batch, verts, classes) :return: highest class (batch, verts) """ cls = torch.argmax(raw_scores, dim=2) val = (cls + 0.5) / DEEPCONTACT_NUM_BINS return val
9d42a6d3457fd98b2174dc7bf7ffbf444aef5b38
3,611,047
import functools import inspect import six def map_arg(**maps): """ Apply a mapping on certains argument before calling the original function. Args: maps (dict): {key: map_func} """ def deco(func): @functools.wraps(func) def wrapper(*args, **kwargs): argmap = i...
4b327d3167a6c9bd4da84671a661767db04bcb6b
3,611,048
def create_spark_session(): """Create an apache spark session on AWS""" spark = SparkSession \ .builder \ .config("spark.jars.packages", "org.apache.hadoop:hadoop-aws:2.7.0") \ .getOrCreate() return spark
3077bb7bb67c404131b04119e8791e64758c6362
3,611,049
def clean_catalog(ukidss_catalog, clean_band='K_1', badclass=-9999, maxerrbits=41, minerrbits=0, maxpperrbits=60): """ Attempt to remove 'bad' entries in a catalog. Parameters ---------- ukidss_catalog : `~astropy.io.fits.BinTableHDU` A FITS binary table instance from the ...
4fa593f758a645bf49fe7479a0876e6a1fc6068b
3,611,050
def setmask(arr, x1=None, x2=None): """setmask(arr, x1, x2) arr = 1D arr x1 = lower value x2 = upper value by default it returns a mask that is the full range of arr returns ======= mask, x1, x2 if input x1 and x2 are out of bounds then it sets x1 and x2 to the boundry of arr...
a2e97675045dfb67ba23838493ce19020453c4f9
3,611,051
def get_tree(splits): """Convert a dict keyed by splits into the equivalent tree. The dict values should be dicts appropriate for the params input to TreeBuilder.create_edge. """ Edge = TreeBuilder().create_edge # Create a star from the tips tips = [] the_rest = [] for split, params...
29fbdb3682713cdf18174981bfc8d71f2d188a2f
3,611,052
import hashlib def create_hash(secret: str, url: str) -> str: """Create a hash of the secret and url.""" s = f'{secret}{url}' return str(hashlib.md5(s.encode()).hexdigest()[0:8])
891fcc45fe7706a984fb9282ab17887710e6da0a
3,611,053
def get_model_name(model): """Obtains the model name for a Scikit-Learn, ML Studio estimator Obtains the model name for Scikit-Learn estimators, ML Studio estimators, and GridSearchCV and RandomSearchCV objects Parameters ---------- model : BaseEstimator, GridSearchCV, RandomSearchCV ...
a6385bf7795a0966bfb0a61c9a74f1e1ca969802
3,611,054
import collections def create_script_to_chars(): """Returns a mapping from script to defined characters, based on script and extensions, for all scripts.""" load_data() result = collections.defaultdict(set) for cp in _defined_characters: if cp in _script_data: result[_script_da...
e837b1993e17971a97cc48c35bf0b1db01e6d59c
3,611,055
import math def get_filter(): """ Вывод товаров на странице каталогов :return: context """ price = dict() seller = Seller.objects.values('title', 'title_en').all() price['max'] = math.ceil(seller.aggregate(max=Max('catalog__price')).get('max')) price['min'] = math.floor(seller.aggrega...
8089414ee80db8e5f45f8b41647a0a31f7234138
3,611,056
from datetime import datetime def email_weekly_orders_csv(current_menu_meal_totals): """ Emails all the current admins an email containing every users current order. Email contains a csv file as well. Returns total emails sent and the email for every admin. """ all_orders = get_all_users_order...
2bcb92ae291ab0e031e0c920e43ccad2d05969c7
3,611,057
from typing import Sequence from typing import Optional from typing import Tuple def ConvTranspose(out_chan: int, filter_shape: Sequence[int], strides: Optional[Sequence[int]] = None, padding: str = Padding.VALID.name, W_std: float = 1.0, ...
0e3fdc2fc414e2198b2b4696923047fd1c3da958
3,611,058
import time def wait_for_result_is_none(method, timeout, wait_msg=None): """Calls the method until the return value is None.""" count = 0 end_time = time.time() + timeout while True: try: result = method() if result is None: return True except: ...
e90d40b319762da41f315820c00e6d8b04cb5565
3,611,059
def connect(db_uri): """Connect to a database to record deployments. :param db_uri: Database URI to connect to :return: SQLAlchemy session for interacting with this database """ engine = create_engine(db_uri, convert_unicode=True) session = scoped_session(sessionmaker(autocommit=False, autoflus...
4063331d42c29e0c012e513a978c8bad1ffc935b
3,611,060
def final_run_could_be_extended(values, end_idx): """Heuristically see if the value run at end_idx could be extended Returns true if there is a run at end_idx, if end_idx is not the last value, and if the value after end_idx could be part of a run. To keep this constant-time, we aren't checking if the...
99244baa3379f261d9cc2e5475b33c824dff6781
3,611,061
from typing import Optional import http async def fetch_geoloc_web(ip: IPAddress) -> Optional[Geolocation]: """Fetch geolocation data based on ip (using ip-api).""" url = f"http://ip-api.com/line/{ip}" async with http.get(url) as resp: if not resp or resp.status != 200: log("Failed to...
478e66fe31d16f28a90ad640bbae40dab4b63f6a
3,611,063
def task_query(job_key=None, hosts=None, job_keys=None): """Creates TaskQuery optionally scoped by a job(s) or hosts. Arguments: job_key -- AuroraJobKey to scope the query by. hosts -- list of hostnames to scope the query by. job_keys -- list of AuroraJobKeys to scope the query by. """ return TaskQuery( ...
2728aedfc31d1f6299e457292cd23fddd5b62ea2
3,611,064
def previous_scheduled_day(date, first_trading_day, is_scheduled_day_hook): """ Returns the previous session date in the calendar before the provided date. Parameters ---------- date : Timestamp The date whose previous date is needed. Returns ------- Timestamp The previ...
aafe234037da69ffc07474e48106ff29c22c46d9
3,611,065
def measure_distance_euclidean(point1, point2): """Return euclidean distance between two shapely Points as float.""" if (type(point1) != Point) or (type(point2) != Point): raise TypeError("Only Points are supported as arguments, got {} and {}".format(point1, point2)) return point1.distance(point2)
42c26523df3568029ba705e420abee91b850bef0
3,611,066
import struct def _unpack_asf_image(data): """Unpack image data from a WM/Picture tag. Return a tuple containing the MIME type, the raw image data, a type indicator, and the image's description. This function is treated as "untrusted" and could throw all manner of exceptions (out-of-bounds, etc.)...
cd6b4646cb8b4c10043935761cd2d6929f27fa68
3,611,067
def dicenet_w3d2(**kwargs): """ DiCENet x1.5 model from 'DiCENet: Dimension-wise Convolutions for Efficient Networks,' https://arxiv.org/abs/1906.03516. Parameters: ---------- pretrained : bool, default False Whether to load the pretrained weights for model. root : str, default '~/....
11a460ad45dc97be6ce9125c2a7b4c2c7fea33a2
3,611,068
def patch_vertices(vertices,pole, width): """ find 'vertices' within the cone of 'width' degrees around 'pole' """ return [i for i,v in enumerate(vertices) if np.abs(np.dot(v,pole)) > np.abs(np.cos(np.pi*width/180))]
ccefb15414bfa3fc6c24eb82687fb5f6d84197d8
3,611,069
def plot_gcam_reclassified(gcam_df, landclass, start_yr=2015, through_yr=2100, interval=5): """Plot GCAM landclass allocation over a time period reclassified to Demeter land cover types.""" yrs = [str(i) for i in range(start_yr, through_yr + interval, interval)] lc_mapping = gcam_to_demeter_lc_map() ...
03892897c1e18a0f3e7320783b9b7471de4ec68d
3,611,070
def get_sigmas_index(indices): """Takes a tuple and gives back a length-16 array with a single 1. Parameters ---------- indices: a tuple of two integers, each one between 0 and 3. Examples -------- >>> get_sigmas_index((1, 0)) array([ 0., 0., 0., 0., 1., 0., 0., 0., 0., 0., 0...
a7120ca1633d3ce2fca9466b36ed6fdce0bfd18e
3,611,071
def authenticated(): """Utility function checking if the current user is logged in or not.""" fas_user = None try: fas_user = flask.g.fas_user except (RuntimeError, AttributeError): pass return fas_user is not None
0a8c1071897d2914bb00a21b7bd2660d37c1cb32
3,611,072
from azureml._base_sdk_common.workspace.models import Workspace def _get_or_create_workspace(auth, subscription_id, resource_group_name, workspace_name, location): """ Gets or creates a workspace. :param auth: :type auth: azureml.core.authentication.AbstractAuthentication :param subscription_id: ...
c7440195d85d680acb8fa8b3be48c7fbcdc87435
3,611,073
def check_if_all_passed(statuses): # type: (Dict[str, str]) -> bool """ Check if all items in supplied `statuses` dict passed parsing and conversion. :param statuses: dictionary init info statuses (files/nodes to their status) :type statuses: dict :return: boolean indicating if all files and no...
e44b363684fd072bdd4a1859a0943dd829e78645
3,611,075
def _get_config(**kwargs): """ Return configuration """ config = { "filter_id_regex": [".*!doc_skip"], "filter_function_regex": [], "replace_text_regex": {}, "proccesser": "highstate_doc.proccesser_markdown", "max_render_file_size": 10000, "note": None, ...
437dfc35b5f24b8322df9ef7415577e9437187e8
3,611,077
from typing import Union import torch from typing import List def signal_framing( signal: Union[torch.Tensor, ComplexTensor], frame_length: int, frame_step: int, bdelay: int, do_padding: bool = False, pad_value: int = 0, indices: List = None, ) -> Union[torch.Tensor, ComplexTensor]: ""...
dbbc1cd37deb2fb4a08eea3b7f026a691b0801f6
3,611,079
def test_abstract_classes(): """很多时候我们会觉得mongoengine.Document提供的方法不够多, 我们会想要自定义 一些方法。为了减少冗余代码, 我们想要将通用的方法以继承的方式实现。这时, 我们 需要建立一个新的Document的基类, 然后用户的类都从这个基类继承而来。 具体做法如下: Ref: http://docs.mongoengine.org/guide/defining-documents.html?#abstract-classes """ class ExtendedDocument(Document): ...
3e480cb95ffe98ba483b4f3249c69e833f56917d
3,611,080
from typing import Dict def evaluate_conditional(string: str, fields: Dict[str, str]) -> bool: """ Evaluates a conditional from $string on a Anki card template using the field values $fields. """ field_name = get_field_name(string) if field_name not in fields: logger.warning("Field '{}' from c...
39a96ff101eee733ea7fe3cb976abb5ab55f0b25
3,611,081
def has_all_channels(stream, channels, starttime, endtime): """Check whether all channels have any data within time range. Parameters ---------- stream: obspy.core.Stream The input stream we want to make certain has data channels: array_like The list of channels that we want to have...
c6e658e6f0fc4816b9a2faeb4d129c951bb5749f
3,611,082
def world_xyzn_im_to_pts(world_xyz, world_n): """Makes a 10K long XYZN pointcloud from an XYZ image and a normal image.""" # world im + world normals -> world points+normals is_valid = np.logical_not(np.all(world_xyz == 0.0, axis=-1)) world_xyzn = np.concatenate([world_xyz, world_n], axis=-1) world_xyzn = wo...
307df640c9cbcc4d09241b0f2a34c4c9f2e99b1e
3,611,083
def clean_email_default(email, allowed_domains): """ Clean email address and check if it has allowed domain :param email: emailadress in string :param allowed_domains: FQDN of allowed domain of mail :return: cleaned lowercase email addresss string or ValidationError """ email = email.strip(...
46e2e38729b7d2e90659995066f886f599e8d952
3,611,084
def add_binary_prefix(value: float) -> str: """ Function that converts a number to his version with Binary prefix @input value (an integer) @example: >>> add_binary_prefix(65536) '64.0 kilo' """ for prefix in BinaryUnit: numerical_part = value / (2**prefix.value) if numer...
ac938217c26be7032dd87fc060593b1155179157
3,611,086
def exhibit_type(elem): """Returns the exhibit type of the file.""" val = attr_val(elem, 'exhibitType') if val is None: return 'EX-101' return val
63078fa4fb75a757b00c9f32d68bd00caf9b432d
3,611,087
def get_mailboxes_v2(): """ Get all mailboxes - including unverified mailboxes Output: - mailboxes: list of mailbox dict """ user = g.user mailboxes = [] for mailbox in Mailbox.query.filter_by(user_id=user.id): mailboxes.append(mailbox) return ( jsonify(mailboxe...
d7a74e0a983ab8aa890e684c3e8e7d45e54096a8
3,611,088
def angle_to_direction(input_angle, full=False, level=3): """Convert the meteorological angle to directional text. Works for angles greater than or equal to 360 (360 -> N | 405 -> NE) and rounds to the nearest angle (355 -> N | 404 -> NNE) Parameters ---------- input_angle : numeric or array-l...
77e3ac983357741073b48dba958066e080ec4498
3,611,089
def asset(ses, ticker_sym): """ function that returns a single asset object given for a given ticker """ return _assets_response_handle(_get_assets_json( ses, ticker=ticker_sym), ticker=ticker_sym)
2a09e22995c50b1083f172d2003ac311a685c7a1
3,611,090
import time def multi_check_output(cmd_lst, stderr=None, env=None, num_retry=NUM_RETRY): """ This routine should always return a (unicode) string. NOTE: Under python3, sp.check_output returns bytes by default, so we set universal_newlines=True to guarantee strings. """ itry, cmd_retry = 1, True ...
2b137081dd75bda1f0b2623016257259819b2ebc
3,611,091
async def github_get_pr_reviews(client_session, owner, repo, pr_number): """ Get the reviews of a given pull-request. Args: client_session: aiohttp ClientSession. owner: owner of the repository at github. repo: repository name at github (without owner part). pr_number (int):...
b934628696534f6a33a5cee081b181b0700916d0
3,611,092
def read_array_objects(container, size, items, dkey, akey, obj): """Read data from the container. Args: container (DaosContainer): the container from which to read objects size (int): number of arrays to read items (int): number of items in each array to read dkey (str): dkey us...
acfc0ebf60008ee2f27108e4cb120e44938afb05
3,611,093
def get_nth_digit(N, n): """ return the nth digit from an N digit number >>> get_nth_digit(12345, 3) 4 >>> get_nth_digit(12345, 7) Traceback (most recent call last): ... IndexError: string index out of range """ return int(str(N)[n])
25c01c14589fb091154e8509a84f98811946938f
3,611,094
def check_device() -> str: """Check if there is an available remote :return: The name of the device """ cmd = adb_command_handler('devices').strip().split('\n') devices = [] device = '' del cmd[0] for line in cmd: if 'device' not in line: continue device = li...
2f86e6dbff6a5a07bb07789383ff6aaa2f65f8d8
3,611,095
def prints_ofp(msg): """ Args: msg: OpenFlow 1.3 message unpacked by python-openflow Returns: """ try: msg_types = {0: print_ofpt_hello, # ok 1: print_ofpt_error, # ok 2: print_ofpt_echo_request, # ok 3: print_ofpt_ec...
034bc765b2580eac2afd045aaab730e5470fe54d
3,611,096
def unitTest(): """A simple unit test for the am_ribbon command""" curve = cmds.curve(d=3, p=[[-3,0,-5], [-2.75,0,-3.916667], [-2.25,0,-1.75], [0,0,0], [2.25,0,1.75], [2.75,0,3.916667], [3,0,5]], k=[0,0,0,1,2,3,4,4,4]) # test create mode print '---TESTING CREATE---' ribbon = cmds.am_ribbo...
601d24668442c529c8d7cad0d4d17dbc6697f781
3,611,099
def mul_param(arr_t, param_dtype): """ Returns a scaling transformation with a dynamic parameter (1 output, 1 input, 1 scalar): ``output = input * param``. """ return Transformation( [Parameter('output', Annotation(arr_t, 'o')), Parameter('input', Annotation(arr_t, 'i')), Par...
59a2959f514d1facf934d295b371a49cf99a9b7c
3,611,100
def plotApprox3D(kernel, parameter, lD, uD, name=None): """Draws a 2-dimensional kernel summation function of the form in between the squared domain from lD to uD Parameters ---------- kernel : IKernelBase object that implements the IKernelBase interface parameter : numpy array ...
0cd9c625cb454f2cd8cad72513cc31efec4c5981
3,611,101
from datetime import datetime def GetDateAndTime(): """Obtain date and time.""" return datetime.datetime.utcnow().isoformat() + "Z"
4261f2b20d38b483d9fa528bfd7d59bb01cc7e86
3,611,102
from sklearn.feature_selection import VarianceThreshold def get_columns_by_variance(X, y, threshold=0.0): """ Method to fetch columns based on threshold variance """ selector = VarianceThreshold(threshold).fit(X, y) return X.columns[selector.get_support()]
3b82a549b328d0a7b043b7fa982c9a7887f08519
3,611,103
from typing import Tuple from typing import List def split_outputs_per_head(outputs: Tuple[NDArray], heads: list) -> List[List[NDArray]]: """ Split outputs into outputs per head :param outputs: list of all outputs :param heads: list of all heads :return: list of outputs for each head """ h...
446a507a82602b932c257c05aff4128dc0158075
3,611,104
def get_neighbors(glycan, glycans, libr = None, graphs = None): """find (observed) biosynthetic precursors of a glycan\n | Arguments: | :- | glycan (string): glycan in IUPAC-condensed format | glycans (list): list of glycans in IUPAC-condensed format | libr (list): library of monosaccharides; if you have on...
c0e1e767a519c3a4959a986d787ee438d051cec9
3,611,105
from statistics import mean import torch def get_saliency_from_feat_list(feat_list, model, device, got_tensors=True, sal_type=1): """ Given a features list from one instance, get saliencies of this instance. Return list of saliencies. n_class...
8e27e2c349f563d89c1b67a3e804797395fc4c08
3,611,106
def vjp_maker_solve_Hz_source(Hz, info_dict, eps_vec, source, iterative=False, method=DEFAULT_SOLVER): """ Gives vjp for solve_Hz with respect to source """ A = make_A_Hz(info_dict, eps_vec) def vjp(v): return 1j * info_dict['omega'] * sparse_solve(A.T, v, iterative=iterative, method=method) ...
3d4971c70898c42670e7bc607d1f69d5cf77c83d
3,611,107
def _update_state_dict_according_to_operation(state_dict, operation, qubit_indexes, merge_strings=None): """ Updates the keys of the state_dict according to the operation being applied to the circuit Args: state_dict: A dictionary wi...
a85c74c70d205ef64e5b53fffeff596f4540fc26
3,611,108
def run_cmd(command, verbose=True, shell='/bin/bash'): """internal helper function to run shell commands and get output""" process = Popen(command, shell=True, stdout=PIPE, stderr=STDOUT, executable=shell) output = process.stdout.read().decode().strip().split('\n') if verbose: # return full outp...
a8eb07d1ac96037d06926e2ad5290b3c1847cafe
3,611,109
def _strip_version(version): """Strip trailing characters that aren't digits or '.' from version names. Some OS versions look like "9.0gm", which is not useful for select() statements. Thus, we strip the trailing "gm" part. Args: version: the version string Returns: The version with trailing letter...
483851b67347c2e23d1c625fc7bb925664f8e1e1
3,611,110
def calculate_head_direction_from_leds(positions, return_as_deg=False): """ Calculates head direction based on X and Y coordinates with two LEDs. Parameters ---------- positions : (N, 2) array_like N samples of observations, containing X and Y coordinates return_as_deg : bool R...
82b5e6e6b531b8c60af3f4f0f28edf6c918a56a3
3,611,112
import itertools def GridGraph(dim_list): """ Returns an n-dimensional grid graph. INPUT: - ``dim_list`` - a list of integers representing the number of nodes to extend in each dimension. PLOTTING: When plotting, this graph will use the default spring-layout algorithm, unless a po...
5f389833c006162ba7e9d5f2fa03b60e87045d69
3,611,113
def calculate_turn(state: str): """ Calculates which player's turn it is given board state. """ num_black = 0 num_white = 0 for cell in state: if cell in cellState.black_pieces: num_black += 1 elif cell in cellState.white_pieces: num_white += 1 return ...
00767d45ffdcd44de87f900f583e13e33df84080
3,611,114
from datetime import datetime def set_token_in_cookie(res): """Cookieへのトークンの保存 一度送られてOKだったトークン情報はCookieに入れてブラウザからのアクセスに対応する。 """ if request.endpoint == 'login': return res token = read_token() if token: max_age = 60 * 60 * 24 * 1 expires = int(datetime.now().timestamp(...
3b3d64a3119468f17b9b4864242b90a0f5217392
3,611,115
def PrayerTimes(method=CalculationMethod.MWL, asr=AsrMethod.STANDARD) -> GeneralMethod: """Generates an object that can be used to generate prayer times. Args: method (CalculationMethod): Method to use for general calculations. Defaults to CalculationMethod.MWL. asr (AsrMethod): Met...
e88e57a5dd1eba8d52318bd6c19a4caff373093a
3,611,116
def change_vpsa_cache(session, vpsa_id, quantity, return_type=None, **kwargs): """ Sets the quantity of additional cache groups for a VPSA. The quantity of cache groups that comes with the base engine is not included in this calculation. For example, if the engine comes with 2 cache groups, passin...
ec5dcf6ac108853c5f62b55cdaba5a9c2cc7dfc8
3,611,118
def parse_radius(radius): """ Method for parsing min/max radius argument :param radius: point radius :type: str, numeric, or None :returns: min or max radius :type: float or None """ err_msg = "Invalid radius: (%s) must be a positive float." % (radius) radius = str_to_float(radius, e...
fff4cd876a49b6120384fd4176d49b84f765d2ea
3,611,119
import json import base64 def export_package(): """Export package as JSON.""" package_doc = frappe.get_single("Package Publish Tool") package = [] for doctype in package_doc.package_details: filters = [] if doctype.get("filters_json"): filters = json.loads(doctype.get("filters_json")) docs = frappe.ge...
0d3445ee5aacbcc62058b5c9795c7c1633fd41d8
3,611,120
from typing import List def station_reindex(stations: List[dict]) -> List[dict]: """ reindexes the opnnem formatted facilities from a list to a dict keyed by duid """ stations_return = {} for station_code, station in stations.items(): facs = [] if "facilities" in sta...
d0c8fad568120b8b111a2153241a75bfff6675a5
3,611,121
def load_jcmod(eid, params): """ Basically trying to dynamically load the correct job controller (perform a 'from typejobcontroller import TypeJobController') """ # build with a known naming convention module_name = params['run']['scheduler'] + "jobcontroller" class_name_cc = param...
ff7cc4f1e3ad04704e4edec4ef6aaaab8acfca09
3,611,122
def config_entry_fixture(hass, config): """Define a config entry fixture.""" entry = MockConfigEntry(domain=DOMAIN, data=config) entry.add_to_hass(hass) return entry
d7174ca251821e4b281db23540d28ce0bb228b09
3,611,123
from DBReleaseHandler import DBReleaseHandler def processDBRelease(inputFiles, inFilesGuids, realDatasetsIn, dispatchDblock, dispatchDBlockToken, prodDBlockToken, workdir, jobPars): """ remove any DBRelease files from the input file list and send back instruction to move the created DBRelease file to job dir """ ...
838fb977b2380463002f59e725d00fcbd8ec2af4
3,611,124
from typing import Dict from typing import Any def radar_analysis_status_command(client: PolarisClient, args: Dict[str, Any]): """ Check the Radar Event for updates. :type client: ``PolarisClient`` :param client: Rubrik Polaris client to use :type args: ``dict`` :param args: arguments obtain...
7eca1158e59c37d995b54b901a1c8391df7e31b1
3,611,125
import json def create_vote(user_id: str) -> FlexSendMessage: """投票創建確認 Args: user_id (str): 使用者 ID Returns: FlexSendMessage: 投票創建確認 """ with open("line/model/create_vote.json") as json_file: contents = json.load(json_file) contents["footer"]["contents"][0]["action"][...
1691cbcf6720bd725c787b306911bd0015530f15
3,611,126
def followRedirects(categories): """If a category is a redirect, replace the category with the target.""" result = [] for cat in categories: categoryPage = pywikibot.Page(pywikibot.Site(u'commons', u'commons'), cat, ns=14) if categoryPage.isCategoryRedir...
ea78ab12b5ab7322f3f04444c1e2f551e8cd1746
3,611,127
def ncdf(x): """Cumulative normal dist'n.""" global rt2 return 1.0 - 0.5*erfcc(x/rt2)
a411624d85db6edcf507c41a5bc769f03240bba1
3,611,128
from unittest.mock import patch import builtins def patch_input(**kwargs): """A helper to provide mocked cm patching input function which was renamed in PY3""" return patch.object(builtins, 'input', **kwargs)
1f70b4b3507f914c5546fa823d6de084b3be8870
3,611,129
def hash_1(): """ Test hash 1""" return "73bef2ac39be261ae9a06076302c1d0af982e0560e88ac168980fab6ea5dd9c4"
e6aef2a19657e727778ac117ec75d75cf5c4944a
3,611,130
def is_sequence(obj) -> bool: """ Return True if obj is a generic sequence type, like a list or tuple. """ return isinstance(obj, (list, tuple, set, DictKeySet, DictValueSet))
7a65363e2c6933ccd88005a291fc75d4f2947021
3,611,131
def adjust_learning_rate(optimizer, epoch, lr, epochs_for_decay): """Sets the learning rate to the initial LR decayed by 10 every 30 epochs""" new_lr = lr * (0.1 ** (epoch // epochs_for_decay)) print('Changing learning rate in ', new_lr) for param_group in optimizer.param_groups: param_group['lr...
b19195f2cdf1fc30d63442770aeb0a9dc867b99e
3,611,132
def _RGB2sRGB(RGB): """ Convert the 24-bits Adobe RGB color to the standard RGB color defined in Web Content Accessibility Guidelines (WCAG) 2.0 see https://www.w3.org/TR/2008/REC-WCAG20-20081211/#relativeluminancedef for more references :param RGB: The input RGB color or colors shape== ... x 3 (R,...
c2c5c25d64cc7b0cb9b004846b72aecada7c5d85
3,611,133
def find_meeting_point(river_1, river_2): """ Find the first meeting point of two rivers """ meeting_points = [] while not meeting_points: points_1 = [] points_2 = [] for _ in range(10000): points_1.append(next(river_1)) points_2.append(next(river_2)) ...
22763dc4d88e7261eb3f67f910379a0791bf9fc4
3,611,134
def _is_physical_entity(pe): """Return True if the element is a physical entity""" val = isinstance(pe, _bp('PhysicalEntity')) or \ isinstance(pe, _bpimpl('PhysicalEntity')) return val
e156efb1336d3ec31290a66e49da8f542b3a5c46
3,611,135
from typing import Callable def time_function(func: Callable) -> Callable: """ Decorator/wrapper function. Make a function print how long it took to call whenever it is called. Parameter: function func: any arbitrary function Returns: function timed_func: same function, but now ...
a34f2ef91530b4f9c6811cda8b456baa887177cd
3,611,136
def paragraphs(text): """ Add line breaks to text to implement line breaks """ if isinstance(text, SafeData): return text text = escape(text) return mark_safe('<p class="no-margin">{}</p>'.format(text.replace('\n', '</p>\n<p class="no-margin">')))
66311b52330fd0bbbaedcb004be5dc6fc22eec92
3,611,137
def countChrom(ls_chrom): """ Counts how often the different chromosomes are present in the list and returns this as a list. """ count = [] for i in LS_CHECK: count.append(ls_chrom.count(i)) return count
85b3562ee42aaabab8361dad2899e49db709d6be
3,611,138
from datetime import datetime def tacacs_auth_lockout(username: str, report_failure: bool = False) -> bool: """ Upon a TACACS authentication failure, as seen by Netmiko, update a dict in Redis that holds failures for this user. And if we've exceeded 10 failures in 10 minutes, lock this user out of the API...
258e9d97dba76953dfbe104618083f9614c3b059
3,611,139
from typing import Optional from typing import Dict from typing import Union from typing import List from typing import Tuple from typing import Sequence def fold(x: VariableLike, dim: str, sizes: Optional[Dict[str, int]] = None, dims: Optional[Union[List[str], Tuple[str, ...]]] = None, ...
6002cc2104dd74287062fa4a18e3ee60eb1a5061
3,611,140