content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
import glob import os def _build_files(workspace_dir): """Return all BUILD files under the workspace dir. This excludes symbolic links. """ build_files = [] for file in glob.glob(workspace_dir + "/**/BUILD", recursive=True): # Glob will follow symbolic links, which creates a lot of troubl...
b534b38868361e59af98fe4aeaa42cf4e5ba914e
687,318
def check_plugin_enabled(ext): """Used for EnabledExtensionManager.""" return ext.obj.enabled
5395c39a029c339e17daca61d7ecca55d8e986fe
687,319
import itertools def to_combinations(list_of_objs: list): """ Create array of all combinations of a list of length n of the shape (1, 2, ..., n) :param list_of_objs: :return: Combinations """ combinations = [] for i in range(2, len(list_of_objs)): combinations.extend(itertools.com...
066369efbe6543da4f553ff937d4451a5480a8ee
687,321
def generate_consortium_members(authors): """ Generate the list of consortium members from the authors """ # Consortium members are all authors who are not consortia # Sort members by the last token of their name consortium_members = [author["name"] for author in authors if "consortium" not in a...
06f8c99d8c47c3fda2299662740b88a0287d9d6c
687,322
def fmt(x, pos): """ A utility function to improve the formatting of plot labels """ a, b = '{:.2e}'.format(x).split('e') b = int(b) return r'${} \times 10^{{{}}}$'.format(a, b)
3fbcc50194f2ac5f71ca11fb52ec4a1283c571ca
687,323
def is_binary(plist_path): """Checks if a plist is a binary or not.""" result = False with open(plist_path, 'rb') as _f: for _block in _f: if b'\0' in _block: result = True break return result
d14de5e8d85235f9013ac75141c36883e67b42d7
687,324
import torch def merge_input_and_domain(input_, domains): """Prepare inputs for multi-modal nets""" domains = domains.view(domains.size(0), domains.size(1), 1, 1) domains = domains.repeat(1, 1, input_.size(2), input_.size(3)) return torch.cat([input_, domains], dim=1)
c7a9ce70b7014558965a6272d10e0362029488eb
687,326
def validate_ppoi_tuple(value): """ Validates that a tuple (`value`)... ...has a len of exactly 2 ...both values are floats/ints that are greater-than-or-equal-to 0 AND less-than-or-equal-to 1 """ valid = True while valid is True: if len(value) == 2 and isinstance(value, tuple...
4f5dae26d24a31c9a9384e804cab983c1444d238
687,327
import argparse def get_args(): """get args""" parser = argparse.ArgumentParser( description='get canonical features from prodigal output', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('-i', '--imp', help='imput file', metavar='imp', t...
e2a36c2905d6720f15466ae6a7fc587426fb89ea
687,330
def dec2dec(dec): """ Convert sexegessimal RA string into a float in degrees. Parameters ---------- dec : str A string separated representing the Dec. Expected format is `[+- ]hh:mm[:ss.s]` Colons can be replaced with any whit space character. Returns ------- de...
f791d24a1ba6831b793e217c2f72dba67b31bd25
687,331
import random import numpy def floating(start, end, steps=0.5, max_decimals=2): """ Function floating Return a random float Inputs: - start: minimum allowed value - end: maximum allowed value (inclusive) - steps: the interval from which to select the random floats ...
a6c3d931c3a807a45693f2ea1911f652e1b02a79
687,332
import torch def cosine_similarity(x1, x2): """Calculates cosine similarity of two tensor.""" dist = torch.sum(torch.multiply(x1, x2), dim=-1) dist = dist / (torch.linalg.norm(x1, dim=-1) * torch.linalg.norm(x2, dim=-1)) return dist
7506fd6379a7ba604852f4bd9f969c9dfb82f09a
687,333
def get_content(obj): """ Works arround (sometimes) non predictible results of pythonzimbra Sometime, the content of an XML tag is wrapped in {'_content': foo}, sometime it is accessible directly. """ if isinstance(obj, dict): return obj['_content'] else: return obj
1d44ba1ba2e85668da722143dd7d82276abbd99b
687,334
import math def simulate_saving(career_length, annual_donation, growth_rate, inflation, donations_per_year): """ calculate the amount of money you would have saved up if you set a certain FRACTION OF YOUR INCOME aside a certain NUMBER OF TIMES A YEAR for a certain NUMBER OF YEARS given an INFLATION RA...
6b89c550b1568e38d1bb1eeaa4ccfe1275b35b26
687,335
from typing import List def generate_board( row: int, column: int, ) -> List[List[str]]: """ Generate a new board in a row * column manner. Parameters ---------- row: int A number that indicate how many row should be generated. column: int ...
86610239ec107eb5261f10a0425773310b3fb343
687,336
import os def getUserEditor(): """Return a string containing user's favourite editor.""" # Try finding editor through environment variable lookup editorName = os.environ.get("EDITOR") if editorName: return editorName # Leave it to the user return "editor_name_here"
4148c39b2a55f43111e0abbe52d253648e60be9e
687,337
def xy2irishgrid(x, y): """ Convert x and y coordinate integers into irish grid reference string """ x = str(x) y = str(y) grid = [("V", "W", "X", "Y", "Z"), ("Q", "R", "S", "T", "U"), ("L", "M", "N", "O", "P"), ("F", "G", "H", "J", "K"), ("A", "B...
7a5731b87db4f35220cba2231599f268b989743b
687,338
import re def get_col_name(*list_pck_cleansing: list, direction: str): """sample: <outputColumn refId="Package\DTF Carga Tabela SCCD10_MAXIMO_TICKET\ADO_SRC - SCCD10_MAXIMO_TICKET.Outputs[Saída de Erro de Origem do ADO NET].Columns[dtcarga]" dataType="dbTimeStamp" lineageI...
af2f72c331a1c621ed5885a85d2764549ae3bd7f
687,339
def find_by_key(data: dict, target): """Find a key value in a nested dict""" for k, v in data.items(): if k == target: return v elif isinstance(v, dict): return find_by_key(v, target) elif isinstance(v, list): for i in v: if isinstance(...
415defb0dcf3d40ee45523fe2af40953192e7e63
687,340
def cpd_int(p, r, t, n=12): """ Calculate compound interest :param p: (float) - principal :param r: (float) - annual interest rate :param t: (int) - time(years) :param n: (int) - number of times interest is compounded each year :return a: (float) - compound interest """ a = p * (1 + ...
56493d9c3e77f23f0a56bb262ecee6ab2b98ba83
687,341
import re def clean_newline(line): """Cleans string so formatting does not cross lines when joined with \\n. Just looks for unpaired '`' characters, other formatting characters do not seem to be joined across newlines. For reference, discord uses: https://github.com/Khan/simple-markdown/blob/mas...
0b8c294e9dfd806bcafeefd682af785f02a1fe7e
687,342
def basic_crux_csv(basic_crux_df, tmp_path): """A simple crux-like csv file""" out_file = tmp_path / "crux.csv" basic_crux_df.to_csv(out_file, sep=",", index=False) return out_file
d6e3c2dc9d5ec9080a2db08821c271411a45e20d
687,343
import os import sys def get_resource_dir(): """Finds _resources/ directory or terminates this script.""" for res in ['_resources/', '../_resources']: if os.path.isdir(res): return res sys.exit("Can't find _resources/ directory.") return None
60f16dd193b94d29b5ac05662930c681e66aac10
687,344
def get_action(head, M, N): """Given the location of the head of the snake, returns an action for that location. Args: head (tuple): a tuple of length 2 representing the location of the head of the snake on a 2D grid. Returns: int: an action """ # top left corner goes down. if head == (0, 0)...
60874eedf3e61417c2dea8596945b4e06ed73ab5
687,345
def get_arguments_without_key(value): """ :param value: функция :return: Функция возвращает аргументы, если в переданном значении нет ключевых слов """ value = value.rstrip(' ').lstrip(' ')[1:-1] return value.split(",")
a49d3e6eff033eca9e7e724926fff880e6d508f3
687,346
def value(event): """ Return the value of an event that was constructed by `sequence`. """ return event.value[0]
b7f21788762096fd46a49b914013f63eb078d4e0
687,347
import random def salt(): """Returns a string of 2 randome letters""" letters = 'abcdefghijklmnopqrstuvwxyz' \ 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' \ '0123456789/.' return random.choice(letters) + random.choice(letters)
b95b73e0038c9af7abdcc7be69123e57fc093d0a
687,348
def delete_redon_nominal_group(nominal_group_list): """ delete the redundancy in the list of nominal groups Input=nominal group list Output=nominal group list """ #init i = 0 j = 0 #We have to loop the list twice whi...
a6a039a856e6c1eadc82ec0f3ec5f8ad965a9641
687,350
def _None(value): """ None """ return value == None or value == "None"
969ba246e5c22ad9ab2f65db919bba92e46e80f0
687,351
def lu_decomposition(matrix_in, q=0): """ LU-Factorization method using Doolittle's Method for solution of linear systems. Decomposes the matrix :math:`A` such that :math:`A = LU`. The input matrix is represented by a list or a tuple. If the input matrix is 1-dimensional, i.e. a list or tuple of integ...
452668c88cc39bed3c804bdcdec6650412d5355f
687,352
def count_user_type(data_list): """ Conta os tipos de usuário nos registros de uma lista. Argumentos: data_list: Lista de registros contendo o tipo do usuário em uma das colunas. Retorna: Número de usuários 'Subscriber' e 'Customer', nesta ordem. """ subscriber = 0 customer ...
cf464f8f276e337a0254988a58b7caa9b70083cb
687,353
def index_api_data(parsed_json, id_field): """Transform a list of dicts into a dict indexed by one of their fields. >>> index_api_data([{'id': 'eggs', 'val1': 42, 'foo': True}, ... {'id': 'spam', 'val1': 1, 'foo': True}], 'id') {'eggs': {'val1': 42, 'foo': True}, 'spam': {'val1': 1,...
fbee9dbfdf3f75c2a1a0f2e2b8b71be0bb5569fa
687,354
def binary_image_to_gray(image): """ Used to convert a binarized image to gray scale """ return image * 255
3d9ddf1b83c6c85b30b5fcb26371b8c8c9def0c9
687,355
def client_factory(client_cls, dispatcher, settings): """Shared logic to instantiate a configured torque client utility.""" torque_url = settings.get('torque.url') torque_api_key = settings.get('torque.api_key') return client_cls(dispatcher, torque_url, torque_api_key)
c174a2a65bd8146c0f52db07b43d4a80eb37e04e
687,356
from typing import Tuple import torch from typing import List def encode_supervisions( supervisions: dict, subsampling_factor: int ) -> Tuple[torch.Tensor, List[str]]: """ Encodes Lhotse's ``batch["supervisions"]`` dict into a pair of torch Tensor, and a list of transcription strings. The supervi...
8cd6a0ef6fa5027af454e804b82dacfe6f44be12
687,357
from bs4 import BeautifulSoup def fetch_links_from_html(html_doc): """ Given a blob of HTML, this function returns a list of PDF links """ soup = BeautifulSoup(html_doc) pdf_attachments = [] for link in soup.findAll('a'): value = link.get('href') if "http" in value: ...
b2b8c2b4102637a5b011988d6d63f8f74ba3eca0
687,358
def create_nodes(pages, init_id=0): """ args: [[url, html_text]] init_id: start id number of relatives """ nodes = [] count_id = init_id for page in pages: node = {} node["r_id"] = count_id node["r_url"] = page[0] node["r_html"] = page[1] #...
190dea86a0b7fcb5bcc8d1f7bcd5031d71b98b83
687,359
def _get_class_name(table_name): """ Get the class name for a given Xylinq table name. @param IN table_name Xylinq table name @return Class name """ # Just make sure the first letter is upper case cls_name = "%s%s" % (table_name[0].upper(), table_name[1:]) return cls_name
a447771f1183eddfd6530be2eb1970d015f67313
687,360
def func_3(): """ Функция без параметров и возвращает значение :return: возвращает строку 'test' """ return 'test'
d2aa5d2c90eab3dcacfd1596f7086e39b1918dc7
687,361
import importlib def get_controller(version): """ Get real controller class by game version. """ try: module = importlib.import_module('.versions.%s' % version, package=__package__) except ModuleNotFoundError: raise RuntimeError("version %s is not supported currently" % version) ...
5d19f0fb886d3e62f8772ed538ae62548a284590
687,362
def solved_steps(scenario): """A list of all the outline steps for a scenario.""" return tuple(step for _, steps in scenario.evaluated for step in steps)
c59af89d5a45fa897dd1108a1866d0e1f1b93819
687,363
def quicksort(items): """O(n * log n).""" if len(items) < 2: return items else: pivot_index = len(items) // 2 pivot = items[pivot_index] left = [num for i, num in enumerate(items) if num <= pivot and i != pivot_index] right = [num for i, num in enumerate(items) if num...
f440c16986dea1980550b21af1e3bc1deeda5463
687,364
import math def aggregatestddevfeat(part_features, accumulator_features, totalfeat, sdfeat, meanfeat, meanscene): """a helper method that calculates the aggregated standard deviation of a target feature over a list of Segments Returns: the weighted average of the ratefeat over the Segments """ ...
8a3875b3e18cbd3814e156f266aef919bbfb33e4
687,365
def label_gesture(df, label_id, cat, label, start_time, session): """ Add labels to single ``gesture'' sequence """ idx = df[df["start_time"] == start_time].index if len(idx) != 1: print("Error: too many idx.", idx) idx = idx[0] df.loc[idx:(idx+64*2-1), "label"] = label df.loc[idx:(i...
70fe423f03a9208a3139a932fd9d344bdefa5e26
687,366
import torch def depth_map_to_3d_torch(depth, cam_K, cam_W): """Derive 3D locations of each pixel of a depth map. Args: depth (torch.FloatTensor): tensor of size B x 1 x N x M with depth at every pixel cam_K (torch.FloatTensor): tensor of size B x 3 x 4 representing ca...
adfa95abb2cf5be5ccf499f8231743a1416c9c50
687,367
import argparse def parse_args(args): """define arguments""" parser = argparse.ArgumentParser(description="Fasta2Bed") parser.add_argument( "promoter_fasta", type=str, help="Input location of promoter.fasta file", ) parser.add_argument( "promoter_bed", type=str, hel...
548c8d0cbe86940afe59bc3e5bcac493b2f7460d
687,368
import torch def create_sentence_dummy_activations( sentence_len: int, activations_dim: int, identifier_value_start: int = 0 ) -> torch.Tensor: """ Create dummy activations for a single sentence. """ activations = torch.ones(sentence_len, activations_dim) # First activation is a vector of one...
f2951ca13b402b2e672918482336fa8787abf43d
687,369
def _run(module, logger, chore, completed_chores, from_command_line=False, args=None, kwargs=None): """ @type module: module @type logger: Logger @type chore: Chore @type completed_chores: set Chore @rtype: set Chore @return: Updated set of completed tasks after satisfying all dependencies. ...
f3f4ba3822252401a97f1781032672905dc90bb1
687,370
from typing import Iterable def flatten_iterable(its: Iterable, deep: bool = False) -> list: """ flatten instance of Iterable to list Notes: 1. except of str, won't flatten 'abc' to 'a', 'b', 'c' demo: [[[1], [2], [3]], 4] if deep is True: flatten to [1, 2, 3, 4] if deep is Fal...
4c17d75a7dde4d0b9002dedea2938deacfef813f
687,371
def extended_gcd(int_a, int_b): """Find the gcd as a linear combination of 2 numbers""" if int_a == 0: return (int_b, 0, 1) int_g, int_y, int_x = extended_gcd(int_b % int_a, int_a) return (int_g, int_x - (int_b // int_a) * int_y, int_y)
8aae8b7411211c5772e621b4fce2a640ffec1177
687,372
def find_frequency_bandwidth(frequency, simulation_parameters): """ Finds the correct bandwidth for a specific frequency from the simulation parameters. """ simulation_parameter = 'channel_bandwidth_{}'.format(frequency) if simulation_parameter not in simulation_parameters.keys(): KeyEr...
f511ca981cba86a4ca3b741fc492bf6b36ef26b5
687,374
def merge_conclusion_elements(elements): """ Merge similar conclusion elements in a single one, more descriptive :param elements: conclusion elements :type elements: [dict] :return: conclusion elements :rtype: [dict] """ final_elements = {} for e in elements: ...
00f99505425fc616871fdb657978189bd9ab007f
687,375
import re def process_names_for_suggestion(*args): """Process names (remove non alpha chars, lowercase, trim) Break each name word and re-insert them in to the array along with the original name (ex 'John Smith 123' -> ['John Smith', 'John', 'Smith'] ) Returns: [List[str]] -- a list of w...
6dc6c0ac44a5f8a89ca6f6eef9838aac995fa4c2
687,376
def constraint_function(x, probs=[], interval_count=0, word_indices=[]): """ Enforces correct word order """ return x[1:]-x[:-1]
cf3c9e9a556952ea075fa0e628fffa397a906b03
687,377
import os from pathlib import Path def find_so_project_directory(): """ Determines the directory for the current snakeobjects project. Several approaches are attempted and the first suitable directory found is returned. If everything fails, the current working directory is returned. 1....
aa6acfc3433e064921fdd39a84b864f5e388c689
687,378
def isLoopClockwise(loop): """Gets if a loop of line segments is clockwise Parameters ---------- loop : List or np array of shape (-1, 2, 2) -1 number of line segments, [startPoint, endPoint], [x,y] Returns ------- bool Note ------- https://stackoverflow.com/questions/...
1db58340ac6a8d0e958344148290d6762f876947
687,380
def prepare_header_name(name): """ 由于django将request里的header值做了转化,所以要有一个格式标准 >> prepare_header_name("Accept-Language") http_accept_language """ return "http_{0}".format(name.strip().replace("-", "_")).upper()
40172e3012a1e511f260537951d1d10868d619dc
687,381
def mean_irrad(arr): """Calc the annual irradiance at a site given an irradiance timeseries. Parameters ---------- arr : np.ndarray | pd.Series Annual irradiance array in W/m2. Row dimension is time. Returns ------- mean : float | np.ndarray Mean irradiance values in kWh/m2...
d48203fed3db34175f3050d4f6d5d3364afe2bd2
687,382
def returnStateMentIfMessageIsEmpty(msg, statement): """ """ if msg is None: return statement + ":" else: return msg + ":\n| >> " + statement
4fa60510d3839b44a98102a85c28b4a4406ebb56
687,383
def getEnglishText(prop): """Gets the English text for the given property and returns a string. Must be parent node that contains "gco:CharacterString" as a direct child. Args: prop: Nodelist object to retrieve text from. Returns: String of English text (or empty if none exists). ...
7545f78633e8d1b68c26f25e30253023d897a3d1
687,384
import time def id_card2(): """ 身份证号,限定其年份、月份、日,其他数据随即 """ return f"{4108121993}{time.strftime('%m%d%M%S')}"
559a5cf8dfc5e5bf59aa9a7a0f542f43141b6b1b
687,385
def is_smile_inside_face(smile_coords, face_coords): """Function to check if the smile detected is inside a face or not Args: smile_coords (list): list of smaile coordinates of form [x, y, (x+w), (y+h)] face_coords (list): list of face coordinates of form [x, y, (x+w), (y+h)] Returns: ...
7a8d1a03ec3eed2743b6c70ed6df6a871a8b1276
687,386
def get_max_drawdown_from_series(r): """Risk Analysis from asset value cumprod way Parameters ---------- r : pandas.Series daily return series """ # mdd = ((r.cumsum() - r.cumsum().cummax()) / (1 + r.cumsum().cummax())).min() mdd = (((1 + r).cumprod() - (1 + r).cumprod().cumma...
afb637f4d79c3a10738be6723c7078003b2eae61
687,387
def _quant_zoom(z): """Return the zoom level as a positive or negative integer.""" if z == 0: return 0 # pragma: no cover return int(z) if z >= 1 else -int(1. / z)
94cf4f58caee5cffa68be51c9eed2b781e6a3db7
687,388
def kesirKarsilastirma(kesir1, kesir2): """ kesir1 ve kesir2, [pay, payda] seklinde tutulan iki elemanli listelerdir. Buyukten kucuge, ya da kucukten buyuge siralama yaparken iki kesrin karsilastirilmasini bu fonksiyon blogunda tanimlayiniz: Kodunuzu bu satirdan itibaren yaziniz, verilen satirlari...
616b648ca7d11ab0c4b48b98729459ff446454b1
687,389
import math def dist_to_line(line, point): """ Finds a point's distance from a line of infinite length. To find a point's distance from a line segment, use dist_to_line_seg instead. line: ((lx0,ly0), (lx1,ly1)) Two points on the line point: (px, py) The point to find the distance from returns: the distance...
f5bb6468666a64790a21b027392c4b4acf530048
687,390
def fibonacci(n): """ Deliberately inefficient recursive implementation of the Fibonacci series. Parameters ---------- n : int Nonnegative integer - the index into the Fibonacci series. Returns ------- fib : int The value of the Fibonacci series at n. """ return...
7122d86483f4d012008fdf84e3e3c5da30ca2eb0
687,391
def is_overlap(a, b): """ 判断2区间是否重叠 参数 :param a 数字数组,比如[1, 1.8] :param b 数字数组,比如[0.5, 1.8] 返回 True 重叠 False 不重叠 """ return max(a[0], b[0]) <= min(a[1], b[1])
574ec058b21ba9ca5be30d7525af24ae02205e20
687,392
def personal_best(scores): """ Return the highest score in scores. param: list of scores return: highest score in scores """ return max(scores)
e2fe2bcb01923e1f55cc2883d3dbb3e9b2712437
687,393
def validate_validator_type(validator_type): """ Property: Validators.Type """ VALID_VALIDATOR_TYPE = ("JSON_SCHEMA", "LAMBDA") if validator_type not in VALID_VALIDATOR_TYPE: raise ValueError( "ConfigurationProfile Validator Type must be one of: %s" % ", ".join(VALI...
6bc66877ed972a9484325889ecdb7d965d4879eb
687,395
def trans(string): """ Given: A DNA string t having length at most 1000 nt. Return: The transcribed RNA string of t.""" return string.replace('T', 'U')
25fa1062db8f123dc03d12bf7e543f07c37cfa15
687,396
def identify_value_block(block: dict) -> str: """Given a key block, find the ID of the corresponding value block.""" return [x for x in block["Relationships"] if x["Type"] == "VALUE"][0]["Ids"][0]
e2ce357bbd675a35e58671acd6dbaf01acfefae5
687,397
def choose_hospital_msg(inner_hospital_infos): """ 选择社区医院 :param inner_hospital_infos: 医院完整信息 :return: """ for j, info in enumerate(inner_hospital_infos["aaData"], start=1): print("%d.\t疫苗余量:%d\t医院名称:【%s(%s)】\t疫苗厂家:%s - %s" % ( j, info["SeqNo"], info["InstitutionName"], info[...
115bcbf80da3be51769f4373be15acc15fbdf403
687,398
import logging def mergeDoc(existing_doc, new_doc): """ existing_doc is merged with new_doc. Returns true/false if existing_doc is modified. """ records = existing_doc.setdefault("records", []) if 'records' not in new_doc: return False isModified = False for new_record in ...
e59317ae2bc20de1f71f901b2258b2926a7cbc0a
687,399
def build_iterator(obj_x, obj_y): """Build a cross-tabulated iterator""" l = [] for x in obj_x: for y in obj_y: l.append((x, y)) return l
437baa471089e57c68b9b05b2aa0783979f416cc
687,400
def eqn17_rule(model,g,g1,d,t,tm,s): """ Computes total flow rate across all distribution modes.""" return model.total_flow_rate[g,g1,d,t,tm,s] == \ sum(model.flow_rate[g,g1,d,dist_mode,t,tm,s] for dist_mode in model.DIST_MODE)
ed1af3f7c2f848a4e612ffc7ea482d37d3e75105
687,401
import json def parse_codacy_conf(filename, toolname="cfn-lint"): """Try to load codacy.json file If the file is missing return two empty lists, otherwise, if the file exist and has files and/or patterns return those. :param filename: name of the file to parse (typically /.codacyrc) :param tooln...
aedf32d51dd56b2e939a733121ef72eb9211ed54
687,402
def convert_mip_type_to_python_type(mip_type: str): """ Converts MIP's types to the relative python class. The "MIP" type that this method is expecting is related to the "sql_type" enumerations contained in the CDEsMetadata. """ type_mapping = { "int": int, "real": float, ...
4d00909eb5dee1212ef6e45a5a7cf3a5341b36aa
687,403
from typing import Sequence from typing import Tuple import math def quaternion_to_euler(quat: Sequence[float]) -> Tuple[float,float,float]: """ Convert WXYZ quaternion to XYZ euler angles, using the same method as MikuMikuDance. Massive thanks and credit to "Isometric" for helping me discover the transformation m...
6bbce0b502f42e63b181ea65b6fff66d7294210b
687,404
def slot_is_full(effect): """ Slot is full. Capacity is filled by participants. """ participant_count = effect.instance.slot_participants.filter(participant__status='accepted').count() if effect.instance.capacity \ and participant_count >= effect.instance.capacity: return True ...
26d0a29d703a1af21a4458c4669253635ae94dbe
687,405
import jinja2 def load_jinja( path, file, vrf_name, bandwidth, packet_size, ref_packet_size, time_interval, ipp4_bps, ipp2_bw_percent, ipp0_bw_percent, interface, ): """Use Jinja templates to build the device configuration Args: device (`obj`): Devi...
db4087efdfe1e6982ce8ce670542c41a3b4fa100
687,406
from typing import Any import sys def export(target: Any) -> Any: """ Mark a module-level object as exported. Simplifies tracking of objects available via wildcard imports. """ mod = sys.modules[target.__module__] __all__ = getattr(mod, '__all__', None) if __all__ is None: __all__ = [] setat...
66c3e438853ad2fa8bfb0fe21ab1e5270f1949f0
687,407
def menu_fechamento(request): """ Funcão que contém as configurações do menu de fechamento de onts do Cont2. Retorna um dicionário com as configurações """ menu_buttons = [ {'link': '/almoxarifado/cont/fechamento/entrada/defeito', 'text': 'Entrada de ONT\'s com defeito'}, {'link': '...
dca3d72131481b94a9f5e95097245d8cda86bc1b
687,408
async def ladders(database, platform_id): """Get ladders for a platform.""" query = "select id as value, name as label from ladders where platform_id=:platform_id" return list(map(dict, await database.fetch_all(query, values={'platform_id': platform_id})))
56beb60e2fc1df38a222aac4e661ac27b8b52f7a
687,409
import hashlib def get_unique_str(seed: str) -> str: """Generate md5 unique sting hash given init_string.""" return hashlib.md5(seed.encode("utf-8")).hexdigest()
be42bddd7f952017f3f88cbc5ccaa916a5e47872
687,410
import hashlib def _get_hash(x): """Generate a hash from a string, or dictionary. """ if isinstance(x, dict): x = tuple(sorted(pair for pair in x.items())) return hashlib.md5(bytes(repr(x), 'utf-8')).hexdigest()
75feed91d7b693095af3793711744260a2dd799c
687,411
def get_data(df, year): """ Takes in df and filters depending on timeframe (start and end years). Returns subset of data for training in timeframe. """ # want to include where there is NOT a break year (those will be our non-broken positive examples --> 'DATE' == 0) - DATE col # want to include...
ababd08709690e153aa38f5546c588f3e88acb5a
687,412
from typing import List def get_characters_from_file(file_path: str) -> List[str]: """ Opens the specified file and retrieves a list of characters. Assuming each character is in one line. Characters can have special characters including a space character. Args: file_path (str): path to th...
50fda9d3e4b2e1dd5724174549967165879dcc14
687,413
def get_documents_async(future_session, connection, search_term, certified_status, search_pattern='EXACTLY', offset=0, limit=-1, fields=None, error_msg=None): """Get the list of available documents asynchronously. Args: connection: MicroStrategy REST API connection object error_msg (string, opt...
00c5f08ef13daed34ffacfdbba4d8376b4f6b6bd
687,414
def find_parenthesis_pairs(s, one, two): """ :param s: The string to look for pairs in. :param one: The first of a pair. :param two: The second of a pair. :return: returns a list of pairs. """ counter = 0 pairs = [] for i in range(0, len(s)): if s[i] == one: # STA...
2bc9aa2c4835f8fc60a923fefa1cde9fd37b0411
687,415
def _get_edge(layer_idx_start, layer_idx_end): """ Returns a tuple which is an edge. """ return (str(layer_idx_start), str(layer_idx_end))
3dff85ce5c328451dafbb9704d08db2a9cea0019
687,416
def _fasta_slice(fasta, seqid, start, stop, strand): """ Return slice of fasta, given (seqid, start, stop, strand) """ _strand = 1 if strand == '+' else -1 return fasta.sequence({'chr': seqid, 'start': start, 'stop': stop, \ 'strand': _strand})
49ab8d1ec4de8ee0f027c06dbcdaf4eb5c270c67
687,417
import re def url_format(url): """Returns a fully qualified url sorta""" if not re.match(R"(?:http|https)://", str(url)): return 'http://{}'.format(url) return url
ed0f656bcbd912a5a422e2bfbbdfbace59c5af21
687,418
def create_EQbasedcurve( oEditor, xt, yt, zt, tstart, tend, numpoints, Version=1, Name='EQcurve1', ...
a143c38ecc8c60b74075de79f9595df9c87f6888
687,419
def set_coordinates(atoms, V, title="", decimals=8): """ Print coordinates V with corresponding atoms to stdout in XYZ format. Parameters ---------- atoms : list List of atomic types V : array (N,3) matrix of atomic coordinates title : string (optional) Title of molec...
c818824ed98711de6fbbd9499999692debbb5307
687,421
from typing import Dict from typing import Set def __find_max_complete_subgraph_recursive( directed_graph: Dict[int, Set[int]], relevant_nodes: Set[int], subgraph: Set[int] ) -> Set[int]: """Find the maximum complete subgraph.""" max_complete_subgraph = subgraph for current_node in relevant_nodes ...
8671d66d9a0d73e4aedd2e9c964134a64405df02
687,422
import os def pathsplit(path): """ Split a path into a list of directories making up the path. eg. '/usr/share/src' -> ['usr', 'share', 'src'] :param path: a file path :return: a list of path components """ ret = [] head, tail = os.path.split(path) if not tail: head, tail = os...
593a577b66cfbe328724a69e095fc3d425661973
687,423
from typing import Dict def strip_leading_underscores_from_keys(d: Dict) -> Dict: """ Clones a dictionary, removing leading underscores from key names. Raises ``ValueError`` if this causes an attribute conflict. """ newdict = {} for k, v in d.items(): if k.startswith('_'): ...
a31e5bfe9b55c61364f166b33e4a575171feb0bf
687,425
import re import os def FindModules(path): """ Build a dict that maps paths to modules. """ pathToModule = dict() fileProg = re.compile(r'vtk\.module$') for root, dirs, files in os.walk(path): for f in files: if fileProg.match(f): with open(os.path.join(root...
cf57dd120f6a2f5d2f6e8c5a6356c20317d765ee
687,426
def dummy_filelist(tmp_path): """Creates a dummy file tree""" root_file = tmp_path / "root_file.txt" root_file.touch() first_dir = tmp_path / "first" first_dir.mkdir() second_dir = first_dir / "second" second_dir.mkdir() third_dir = second_dir / "third" third_dir.mkdir() for ...
acc9b1459a4b5e459142a3f0393fcb12ab886809
687,427