content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
import json import subprocess def get_simulator_list(): """Gets list of available simulator as a dictionary.""" return json.loads(subprocess.check_output(['xcrun', 'simctl', 'list', '-j']))
a4bbeef8ec098f6a2b753a97539e4e6183c7ab81
630,459
def readSif(fn): """reads in the sif file fn and ouptputs a dictionary and a list: interDict : has "interaction" as key and [(node1,node2), (node3,node4)] as values nodes list : is the list of unique node names (both on the right or left hand of an interaction) """ interDict = {} ...
6f8070e95de228291480120bbf86fe628e857dfa
630,460
def extend_model_with_DB_plainText(model, reactionsDB): """ Extends the given model with the reactions in reactionsDB. This is done by loading the model in plain text format reactionsDB and adding only the reactions that are not part of "model" to it. Arguments: model : ...
0eb1b74a40b172645bcc95da3bf7a2d8696df947
630,461
import random def remove_missing(dataframe): """Create initial dataset without NaN for testing of functions by filling with random values from the column. """ dataframe = dataframe.apply(lambda x: x.fillna(random.choice(x.dropna())), axis=1) return dataframe
d52ff03d12c7427bdf7314a135b9560775f0156b
630,463
import math def airmass(Z, units='degrees'): """Calculate the airmass for a source according to Airmass=sec(Z) where Z is the zenith distnce Z--zenith distance units--units of Z """ if units=='degrees': Z=math.radians(Z) return 1.0/math.cos(Z)
4ba98faff36c5615b978f1b58ed6c7e679b2aa80
630,464
import os import configparser def load_configs(config_file, config_section, config_keys): """Loads configurations from config file based on given config section and values Arguments: config_file {string} -- configuration section to read config_keys {string[]} -- list of keys to read from ...
ab02d482650c890aa5be60f1cd4f2bc256d162cb
630,465
def enum_words(words_iterable): """Return string: () -> '' ('a') -> 'a' ('a', 'b') -> 'a and b' ('a', 'b', 'c') -> 'a, b and c' """ ws = words_iterable if not ws: return '' elif len(ws) == 1: return ws[0] elif len(ws) == 2: return f'{ws[0]} and {ws[1]}' ...
52897d2dc61337acc840adf134317f7cae391b5f
630,466
def shift(txt, indent = ' ', prepend = ''): """Return a list corresponding to the lines of text in the `txt` list indented by `indent`. Prepend instead the string given in `prepend` to the beginning of the first line. Note that if len(prepend) > len(indent), then `prepend` will be truncated (doing be...
a8c75a35bcffb07c2a619d1a208a12fb1ba8c0f8
630,468
import argparse def load_arguments(): """ Get arguments from command line. """ # cur_path = os.path.dirname(os.path.realpath(__file__)) p = argparse.ArgumentParser() p.add_argument("repo_url", help="Url of a git repository to clone") p.add_argument("--conda_env", "-n", default=None, ...
e467d8e7528ad015fe003bff5ce6f719f0acea37
630,469
def redact_after_symbol(text:str, symbol:str) ->str: """Replaces all characters after a certain symbol appears with XXXXX""" r_start = text.find(symbol) r_len = len(text) - r_start to_redact = text[r_start:] return text.replace(to_redact, "X"*r_len)
a9a46f4222aff97c5aec2a2d843b4e7bffab031b
630,470
import argparse def parse_args(): """ parses the arguments :return: argparse object containing all provided arguments """ print("parsing args...") parser = argparse.ArgumentParser(description="Generates a IGV genome JSON") parser.add_argument("template_file", help="Templa...
eaf5e2ee96081a1b93cd3a99b6e24af4931cc766
630,471
from typing import List from typing import Dict from typing import Any import csv def get_data( input_file: str, save_directory: str, critical_bands: List[int], unity_db_level: int) -> List[Dict[str, Any]]: """Returns data.""" with open(input_file, "r") as infile: csvreader = csv.reader(infile, delimi...
b2fc7a4ed953e54312d6b05fd7fbdd09730aec06
630,472
import argparse def str2bool(v): """This is taken from: https://stackoverflow.com/questions/15008758/parsing-boolean-values-with-argparse Because type=bool is not interpreted as a bool and action='store_true' cannot be undone. Parameters ---------- v : string ...
64d0c7dc1622077bab0038067156c7e3cfc59b6f
630,473
import re def _find_pred_in_init(pred_name, param, sig_pos, init): """ This method is used to check whether an instantiation of the predicate denoted by pred_name with the parameter param at position sig_pos is present in the initial condition. Useful to evaluate static preconditions efficiently....
85042182bb1478d767a4b5b9879574615f7781a8
630,474
def is_aware(dt): """Return whether the datetime is aware. See https://docs.python.org/3/library/datetime.html#determining-if-an-object-is-aware-or-naive :param dt: The datetime object to check. :returns: True if ``datetime`` is aware, False otherwise. """ return dt.tzinfo is not None and dt.t...
d3c2f44727f5eb1be5011c2eeb07aaa1fe55ab33
630,475
from pathlib import Path def load_txt_to_string(file_path): """ Loads a txt file and returns a str representation of it. :param file_path: str or Path object :return: The file's text as a string >>> from pathlib import Path >>> from gender_analysis.testing.common import TEST_DATA_DIR >>>...
c38518d98fc05cb1bab0cc07888ae94ad937c534
630,476
def pull_context_windows(notes, i, col): """ notes: dataframe i: int that represents index in notes col: name of column that has merged context windows """ # string that holds text for pulled context windows sequence = "" for j in range(len(notes[col][i])): # if multiple c...
f9478cefcaa11891b5fc7b51cf987c36ab1d232c
630,477
def promote_maximally(x): """Return copy of x with high precision dtype. Converts input of 'f2', 'f4', or 'f8' to 'f8'. Please don't pass f16. f16 is misleading and naughty. Converts input of 'u1', 'u2', 'u4', 'u8' to 'u8'. Converts input of 'i1', 'i2', 'i4', 'i8' to 'i8'. Naturally, this c...
4c1c7a29b65720a8845dd085b8ae2281cb401223
630,478
def _to_extended_delta_code(seconds): """Return the deltaCode encoding for the ExtendedZoneProcessor which is roughtly: deltaCode = (deltaSeconds + 1h) / 15m. With 4-bits, this will handle deltaOffsets from -1:00 to +2:45. """ return f"({seconds // 900} + 4)"
e24189c73900cceaa125f6f471633362ec82e27c
630,479
from typing import Callable from typing import Dict def _get_globalns_as_get_type_hints(func: Callable) -> Dict: """ Global namespace resolution extracted from ``get_type_hints`` method. Python 3.7 (https://github.com/python/cpython/blob/3.7/Lib/typing.py#L981-L988) Note that this is only supporting funct...
eabfc83422067508ca0b8bdc4e2c2146f0e4c0c7
630,482
def build_response_block(name: str, vote, removalreasons: list) -> dict: """Build blocks for moderator responses in archive message""" textstring = f"{name}: {vote}" if removalreasons: textstring += "\n\t" for reason in removalreasons: textstring += f" {reason}," textstri...
321011bd4c8f3b356f6fbdac48e321abc33285d6
630,483
def fmtticks(fmt, fmt0, ticks, tickscle, tickscle0): """Formats x and y axis tick labels for a seaborn plot Parameters ---------- fmt : str The formatting string to use for all tick labels fmt0 : str The formatting string to use for only the first tick label ticks : numpy.ndarra...
1b5df83ddf94aec1ea7fea4b696250047126ad46
630,484
from typing import List def right_cones(array: List[int]) -> List[int]: """ We have an array, say 3 4 9 6 1. We want to return a new array where 3 is replaced by the number of number of smaller elements of 3 (1). We want to return a new array where 4 is replaced by the number of number of smaller elem...
d031ee5e238bd10c17fa859a93cf89b47dfcc972
630,485
def classifier_outperformance(a_metric_samples, b_metric_samples, margin=0.): """calculate the chance that a outperforms b by a given margin. Input: samples from the metrics for classifiers a and b""" greater = (a_metric_samples - margin) > b_metric_samples return greater.sum() / float(len(greater))
85f1ba60968a8e60a9b2b3d4852e98beadbef655
630,486
def func_build_hsc_sdss(obj, overwrite=False, **kwargs): """ Params ------ obj overwrite=False **kwargs: environment='iaa' Return ------ status """ # setting environment = kwargs.pop('environment', 'iaa') humvi_bands = 'riz' # running statuss = [obj.add_hsc(), obj.add_sdss() ] return all...
01715bed253b37651f483551ee7a073371b9bf6d
630,487
def CheckTerminateHypothesis(config_number): """ Shows hypothesis which are proposed ('hypotheses_type2.txt') only for tracks chosen to be terminated ('optimized_type2.txt'). """ file_hyp = "/Volumes/lowegrp/Data/Kristina/MDCK_90WT_10Sc_NoComp/17_07_24/pos13/tracker_performance_evaluation/" \ ...
4160e89ef8a9103724adc36ca12fba05f2c1f9a2
630,488
import unicodedata def remove_diacritics(input_str): """ Removes diacritics. @param input_str string to clean @return cleaned string Example:: enguérand --> enguerand """ nkfd_form = unicodedata.normalize('NFKD', input_str) only_ascii = nkfd_fo...
fdff6e0691f70a298980074fca1369e8d4b985f2
630,490
import torch def _laplacian(G, D): """ Creates the laplacian matrix, starting from the gradient and the divergence operators Parameters ---------- G : list the gradient operator D : list the divergence operator Returns ------- Tensor the laplacian matrix ...
73f3fbb326920cc41f13774541f1289f0eb57453
630,491
def has_repeat_digits(grid: list[list[str]]) -> bool: """Returns if given 2d grid has repeating digit strings""" digit_strings = {str(i) for i in range(1, 10)} for row in grid: for digit in row: if digit == '.': continue if digit not in digit_strings: ...
c137ae9011a68d0110e53198a0643775b458dacd
630,492
import re def regex_validator(regex): """ Creates a callable which will validate text input against the provided regex string. Parameters ---------- regex : unicode A regular expression string to use for matching. Returns ------- results : callable A callable which ta...
656749fea031a4ad67848180b10e1e25408de174
630,493
def linear_reduction(L): """ Input: L is a list of elements [m, Fi, Li], where mi is accumulated multiplicity Fi is a poly in three variables Li is a linear form in two variables Return: Linear reduction of each Fi*Li. """ cycles = [] x0,x1,x2 = L[0][1].parent().g...
0134372e7d114f432d8180cbc07cfd9a711f4e16
630,494
def unpack_uncertainty_parameter(u): """Unpack uncertainty parameter (integer or single character). See: https://www.minorplanetcenter.net/iau/info/MPOrbitFormat.html Args: u (str): Packed uncertainty parameter. Returns: int: Uncertainty parameter, or -1 if invalid. s...
17260dc1ee0b1bddde52431d61cf4b8ea8197816
630,495
def prefs_line_to_string(line): """ Converts a prefs line to a string. Prefs line is in the format tb(..);tc(..);..;..;. tb(x, y) are "no preference" intervals (i.e., white) that last for y 15-minute intervals (x has no meaning): e.g., tb(0, 4) is an hour of white; tb(2, 8) is two hours. ...
3497018ebf6306fdd23c8a12b9ad67a09811200c
630,496
def match_file(matcher, analyzer, ht, filename, hashList): """ Read in an audio file, calculate its landmarks, query against hash table. Return top N matches as (id, filterdmatchcount, timeoffs, rawmatchcount), also length of input file in sec, and count of raw query hashes extracted ""...
c8995fac958f029587072553970d19ce0b5df552
630,497
def splitBase(idx): """ Return a named used when a big case is split into several pieces """ name = '' if len(idx) == 0: return 'base' for ii, n in enumerate(idx): name += 'sp%d-split-%d-' % (ii, n) name = name[0:-1] return name
c2deee08225ec6a4973443108a0ae5fca32c0fe5
630,498
def average(numlist): """ Find average of a list of numbers. Uses for loop to iterate through parameter NUMLIST and adds the sum of each element until the end of the list. AVERAGE then returns the sum divided by the length of NUMLIST. """ numlist_sum = 0 # initialize sum to zero # ...
e4191ca069df41e773052a2e39bb5eb0d47d7b1f
630,499
def normalize(knot_vector, decimals=18): """ Normalizes the input knot vector to [0, 1] domain. :param knot_vector: knot vector to be normalized :type knot_vector: list, tuple :param decimals: rounding number :type decimals: int :return: normalized knot vector :rtype: list """ try: ...
93b300c9dcb6c84a87a6a2dab0b7675101e1991e
630,501
def card_check(numbers_called, list_of_cards): """ADD DOCSTRING""" for k in range(len(numbers_called)): for i in range(len(list_of_cards[0])): for j in range(5): # compare each row and column from each card to the numbers called row_to_check = list_of_cards[0...
b2677eb87c76538b01a6cfc12ea020562e7ee0cd
630,502
def FixControlQ(): """Allow ctrl-q to be passed to the application on unix systems. Control+Q is usually used to unpause the terminal after Control+S pauses it on unix systems. To prevent this, we need to disable the termios.IXON flag. termios is not available on all platforms. Returns: A callable to re...
358a8f985bee231c5a14c6d88b7e016e6623640e
630,503
def segment_labels_to_floats(segments): """Converts the string labels to floats. Parameters ---------- segments: list List of mir_eval.segment.tree.Segment """ labels = [] for segment in segments: labels.append(segment.label) unique_labels = set(labels) unique_labels = list(unique_labels) return [uniqu...
994be86ea5e19252e0de29a83ec80db6454f044b
630,504
def orig_atom(atom,big_table): """ Returns the 0-indexed position of atom from the full list of atoms in the supercell mapped back into the original unit cell """ n = 0 bonds_per_pair = len(big_table[0])/len(big_table) while atom > bonds_per_pair: atom -= bonds_per_pair n += ...
d8aafec556a49a3c61d67079a81b63ce86acb8c7
630,505
def get_indices(l): """ Description ... Args: l: ... Returns: meta ... For example: ... """ meta = dict({}) for i, k in enumerate(l): if k == 0: continue k_str = str(k) if k_str not in meta.keys(): meta.update({ ...
402784302eef31a6620c955961430c429a983020
630,506
def bottom_remineralization(vs, source, sink, scale): """Exported material falling through the ocean floor is converted to nutrients Note ---- There can be no source, because that is handled by the sinking code Parameters ---------- scale Factor to convert remineralized material to...
d30c9f9ee29532fb8452e1c4130a43dc9f57024a
630,507
def extract_commit_msgs(output, is_git=True): """ Returns a list of commit msgs from the given output. """ msgs = [] if output: msg = [] for line in output.split('\n'): if not line: continue is_commit_msg = line.startswith(' ') or not line ...
b51f3d3edec8940e0e5fc5e34f3d746dccf7fcf8
630,508
def even_and_odd(n: int) -> tuple: """ This function return two numbers NE and NO such as NE is formed by even digits of N and NO is formed by odd digits of N """ NE = ''.join(i for i in str(n) if not int(i) % 2) NO = ''.join(i for i in str(n) if int(i) % 2) if not NE: return (0, int(NO)) ...
36761881200d39f3544d38fd7b05e41e00bf9404
630,510
def create_lookup(results): """Create a lookup table by key name.""" return {key["key_name"]["web"]: key for key in results}
809c247b85a9b807c47848490572316f29e70107
630,511
def solve(N, M, items): """ Greedy version """ res = 0 shoots = [0] * (N + M) for n, m in items: shoots[n] += 1 shoots[N + m] += 1 while any(s != None for s in shoots): av = min([(n, s) for n, s in enumerate(shoots) if s != None], key=lambda x: x[1])[0] res += 1 shoots[av] = None if av < N: # is a row...
6224b8896ad98c7f583ec9aa04f8fe267f6a3c33
630,512
import numpy def get_pY(pY_true, y_fake): """ Recieves a vector with the probability to be true (pY_true) returns a matrix with the probability to be in each class we put pY_true as the probability of the true class and (1-pY_true)/(nof_lables-1) for all other classes """ nof_objects = le...
0ed0665c3509629925698fb60c3e5398795bcf04
630,513
def add_axes(fig, axwin=(0.05, 0.03, 0.87, 0.93), **kwa): """Add axes to figure from input list of windows. """ return fig.add_axes(axwin, **kwa)
c0e600eaa9e9ebb93b0d7cffad0dc282c40201d2
630,514
def min_value2(digits): """Apply 10 to the powers approach.""" sorted_digits_ls = sorted(set(digits)) value = 0 for p, d in enumerate(reversed(sorted_digits_ls)): # Why reverse? [1, 4, 8] => [8, 4, 1] w/ power 0, 1, 2. value += d * (10 ** p) return value
fbd1c89851a51a2f04cd089b0e237c28f975a478
630,515
def get_client_from_scope(scope): """HACK: extract client IP from uvicorn scope dict""" client = scope.get("client") if not client: return "" return client[0]
a61612e0fdce7c3e0349f07badca43eaa2a46d12
630,516
def parse_line(line): """ Parse a queue trace line into a dict """ result = {} line = line.split() if len(line) < 5 or line[0][0] == "#": return result result["time"] = float(line[0]) result["from"] = int(line[1]) result["to"] = int(line[2]) result["len_bytes"] = float(line[3...
b1c4b5ed022b54c30072caf92d5257d401e106d8
630,517
def evaluate_accuracy_ch3(data_iter, net): """evaluate_accuracy""" acc_sum, n = 0.0, 0 for X, y in data_iter: # 如果ctx代表GPU即相应的显存,将数据复制到显存上。(新增) y = y.astype('float32') acc_sum += (net(X).argmax(axis=1) == y).sum().asscalar() n += y.size return acc_sum / n
f1e48668252f7f50be3b10a40b33bef3cd212a5c
630,518
from typing import Optional from typing import Tuple from pathlib import Path def dataset_adress( adress_archive_root: Optional[str], corpus_name: str, dataset_type: str, preprocess_args: str, ) -> Tuple[str, Path]: """Path of dataset archive file and contents directory. Args: adr...
77f87d18b5532b8381adc218a8c3a21fe30caf3c
630,519
def distribute(items, n): """ Distributes items into n (almost) equally large batches. Example: items = [1,2,3,4,5,6,7,8,9], n = 4 gives batches = [[1,5,9], [2,6], [3,7], [4,8]] Args: data ([any]): List of items of any type n (int): Number of max items of a batch ...
817b29aa20f7cdfbbdd7199d93676d46007967ca
630,520
def salt_factories_config(salt_factories_config, host_docker_network_ip_address): """ Return a dictionary with the keyworkd arguments for FactoriesManager """ config = salt_factories_config.copy() config["log_server_host"] = host_docker_network_ip_address return config
172fd1bba169bd72f86804fc89834b36f4b90cb2
630,521
def react_polymer(polymer): """React polymer removing all units paired with opposite polarity.""" next_polymer = [] for cur_unit in polymer: prev_unit = next_polymer[-1] if next_polymer else '' if (prev_unit and cur_unit.lower() == prev_unit.lower() and cur_un...
0c5af4e7f8316794c2586435e2042b0c2fa79a11
630,523
async def ping(): """Inspects if the API instance is running.""" return {"ping": "pong"}
fb2cb7128a66bda332e0a0e65314bfd5e9fee305
630,524
def clean_primary_types(val): """UDF function to fix duplicate primary types""" if val in ("NON - CRIMINAL", "NON-CRIMINAL", "NON-CRIMINAL (SUBJECT SPECIFIED)"): return "NON-CRIMINAL" if "NARCOTIC" in val: return "NARCOTICS" return val
584a491cc8400e19a14c76fb264e8718990453e3
630,525
from datetime import datetime def _parse_trackinfo(track): """Parses the track info into something more comprehensible""" now_playing = False if "@attr" in track and "nowplaying" in track["@attr"]: now_playing = bool(track["@attr"]["nowplaying"]) playtime = datetime.utcnow() else: ...
cf4f2d57a90040a819efec474e5289655c2f8364
630,526
import os def get_file_size(fp): """ Get the file size for a file-like object :param fp: file-like object :return: """ original_file_position = fp.tell() fp.seek(0, os.SEEK_END) file_len = fp.tell() fp.seek(original_file_position, os.SEEK_SET) return file_len
334d79b4abe92149bf941a68b83f23576c83b1c0
630,528
def get_origin_scale(h2tkt): """get origin and scale from a Shadow.Beam.histo2() instance ####################################### .. warning:: TEMPORARY, WILL BE REMOVED ####################################### :param h2tkt: Shadow.Beam.histo2() :returns: origin, scale :rtype: tuples of flo...
9e60d0b3cb1ea36b8d1ac61bb55e5c38ac6ed4c6
630,529
import torch def _parabolic_trend_crosscov(S1, L1, S2, L2, gamma0, sigma0s, betas, s0): """ Same as above, but for non-stationary variance models. The model is the following: \sigma_i(s) = \sigma0_i + \beta_i * (s - s0)**2 The genial simplicity of the implementation is this: instead of having an...
a44e20aefa094189858f0f99b068070bba8ca60a
630,530
def is_left_bracket(token): """ returns true if token is left bracket """ return token == "("
d799afbdfd880edf127d43dfae1363783c5fe401
630,531
import torch def load_latest_model(model, name="model.pt"): """ Helper function for Load model :param model: current model :param name: model name :return: loaded model default model.pt """ model.load_state_dict(torch.load(name)) return model
38f10a1c5235d0736321f7c739cb9e0f6b4488e6
630,532
def get_g_score(node, pq): """Check if the combination of upper tokens and lower tokens can be found in the priority queue; if yes, return the g-score of the similar node found in the priority queue. Return - 1 if it is not present. Priority queue has format[[f-score, node], ...]. """ nodes = ...
d37654da2264ced3bd2de88a33f24bc49a06fce4
630,533
def dummy_tx_hist_file_content() -> dict: """ Return initial tx file content. """ content = { 'txid_stake_previous': '', 'txcount_previous': '0' } return content
9b06c8f70edefa39a851237730289199fc519a0e
630,534
def point_to_line(tower): """ Returns if you can place tower based on distance from. path :param tower: Tower class object :return: Bool """ return True, tower
20ddfa3bbb53d57e2f3d14fdf237dc6a5402d2e8
630,535
def get_same_caps(pattern, word): """ Соответствие прописных и строчных букв (возвращает слово такого же типа, что и заданное) """ if pattern.istitle(): items = [part.lower() for part in word.strip().split()] if len(items) == 1: return word.title() items[0] = items[0]...
d3cf926f7b847a86c8048fbb1090042ef2789625
630,536
import random def shuffle_image_label_0(images, labels): """ Randomly disrupt two list with the same shuffle """ randnum = random.randint(0, len(images)) random.seed(randnum) random.shuffle(images) random.seed(randnum) random.shuffle(labels) return images, labels
edebd972796af4a211c5e93fd8be43cee89a6e0f
630,537
from typing import Any def is_ref(entry: Any) -> bool: """ Checks if entry is a reference """ return isinstance(entry, dict) \ and '$ref' in entry
30381c5f7af9d53d33eb6e2a33fab412c6217909
630,538
def underscore_to_camelcase(keyword): """Change underscore '_' to CamelCase string in string param keyword: string which has to be modified as above return: string. Example one_two changes to OneTwo """ parts = keyword.split('_') keyword = '' for part in parts: if part ...
d971306e305236d67bce4cf085ccf0b59d7e42a5
630,539
def derive_unique_id(row, is_fabs): """ Derives the unique ID of a row and puts it in the proper format for the error/warning report. Args: row: the dataframe row to derive the unique ID for is_fabs: a boolean indicating if the submission is a FABS submission or not Returns...
78d455473baeda04f4cbf34197b740be46c25b94
630,540
def get_raw_text(tag): """ :type tag: Tag :rtype: NoneType or str """ if hasattr(tag, 'text'): text = tag.text if text is None: return None else: text = str(tag) return text
d73b5d4d4000405b17c37f859aa3a38bb5f1d653
630,541
def rearrange(widgets: list): """ Sort widget boxes according to priority. """ mapping = { 'small': 1, 'big': 2, 'full': 3, } def sort_key(element): return ( element.get('priority', 1), mapping.get(element.get('display_size', 'small'), 1),...
2b470394b25d331dfcdf6bb15553c8cd02b7600e
630,542
def trim_attribs(elem_attribs, attrib_type="question"): """deletes non-useful data from attribs dict for questions / answers, returns remaining""" if attrib_type == "question": to_keep = ['Id', 'Body', 'Title', 'Tags', 'AnswerCount', 'AcceptedAnswerId', 'PostTypeId', 'Score', 'BodyParsed', 'TitlePArsed'...
32eead0b92fff2a49088465cb13c0d438f461a7b
630,543
def convert(lines): """Convert compiled .ui file from PySide2 to Qt.py Arguments: lines (list): Each line of of .ui file Usage: >> with open("myui.py") as f: .. lines = convert(f.readlines()) """ def parse(line): line = line.replace("from PySide2 import", "from ...
70324df5dfec895d6bbd5100d7634cbb8b6a358a
630,544
def _get_next_chunk(stream, chunk_size): """Get a chunk from an I/O stream. The ``stream`` may have fewer bytes remaining than ``chunk_size`` so it may not always be the case that ``end_byte == start_byte + chunk_size - 1``. Args: stream (IO[bytes]): The stream (i.e. file-like object). ...
fe9771cd98cc629f806bede0314cdfea629c65e7
630,546
import os def _find_gdal_path(): """find the gdal installed path from the system enviroment variables.""" evn_name = 'GDAL_DATA' # print os.environ[gdal_env_var_name] return os.environ[evn_name].replace('\\gdal-data', '') if evn_name in os.environ else None
84e86fa2d4319a7fbcacf40455462414553c6047
630,547
from typing import Dict def enabled(gParameters: Dict, key): """Is this parameter set to True?""" return key in gParameters and gParameters[key]
924f55f9346da741dacd3992b7d8e836c83835dc
630,548
def find_old_mp3(dir_for_search): """ Функция возвращает полный путь к исходному mp3 файлу, на основании записи в исходном конфиг файле osu :param dir_for_search: пака в которой лежит конфигуратор :return: Полный путь к исходному файлу mp3 """ res = [] for i in dir_for_search: file =...
5fa4c29767ab1cb3b5394fbc7ea073516cfbbe8c
630,549
def test_for_blank_lines_separating_reference_lines(ref_sect): """Test to see if reference lines are separated by blank lines so that these can be used to rebuild reference lines. @param ref_sect: (list) of strings - the reference section. @return: (int) 0 if blank lines do not separate referen...
3a07fa4c4373e56ca873dd39b431639850687148
630,550
def get_non_null_product_fields(): """"Returns non-null fields for Product model""" return ['name', 'price', 'status', 'inventory_product_id', 'wishlist_id']
9cef4a076bfd300efae0826df2dfa73fbc1c7bb4
630,551
import typing def noop(data: typing.Any) -> typing.Any: """Return the input value Arguments: data {typing.Any} -- any value Returns: typing.Any -- input value """ return data
20b71c569c727e6dc66442f9fd7271bfdbe6f93d
630,552
import time def decorator_time(func): """This function adds time value of execution of original sort func and return sort list and time in sec""" def wrapper(*args, **kwargs): start = time.time() lst = func(*args, **kwargs) stop = time.time() - start return lst, ...
707683efa1385215d4eb041de1dcafe1598044ac
630,553
def contains_digit(input_string): """ check if string contains digit >>> contains_digit("5") True >>> contains_digit("5a") True >>> contains_digit("cat") False """ return any(_.isdigit() for _ in input_string)
45afeb35d7bd29808d5dbeb3eba6715ae1a15916
630,554
import os def hashes_dirpath(): """returns the dirpath where the plan hashes will be found""" return os.environ['CORRIGIBLE_HASHES'] if 'CORRIGIBLE_HASHES' in os.environ else "/corrigible/hashes"
f11574847a330d0794369c7b05d6f924ed547d6f
630,555
def get_unique_parents(entity_list): """Translate a list of entities to a list of their (unique) parents.""" unique_parents = set(entity.parent for entity in entity_list) return list(unique_parents)
cf855369a632ca71a99b833a4f1373325c142e7d
630,557
from PIL import Image, ImageChops def apply_mask(layer, image, bbox=None): """ Apply raster mask to the image. This might change the size and offset of the image. Resulting offset wrt the psd viewport is kept in `image.info['offset']` field. :param layer: `~psd_tools.api.layers.Layer` :param...
40c9a809573b947e4ba103eab0adb922ee831880
630,558
def find_prime(a): """Find prime numbers.""" res = [] for num in range(2, a): prime = True for i in range(2, num): if num % i == 0: prime = False if prime: res.append(num) return set(res)
d15d01497f275d0dad92d11122d85b3ba4c72335
630,560
import os import json def math_data(): """import data from json file created by mathematica script and import as 'ground truth' """ math_json_filename = os.path.basename(__file__).split(".")[0] + ".json" with open( os.path.dirname(os.path.realpath(__file__)) + "/" + math_json_filename ...
8a98da362ec62717283c2ab41099936cbda509c9
630,561
def tc_idle(): """Total time town center spent idle in Dark Age.""" query = """ select match_id, player_number as number, (extract(\'epoch\' from started)::int % 25) * interval '1 sec' as value from research where research.technology_id=101 """ return query, dict()
159a8f36bd7545ac910b83c217513342b70d1c43
630,562
from typing import Iterable def parse(data: str) -> Iterable[int]: """Returns a list of digits form string `data`""" # List instead of generator since we wil slice it later return [int(x) for x in data]
8d81910d43a0e5a5a832902c1ab6b8ed85f9bfff
630,563
import subprocess import os def run_application(): """Start running the compatibility checker server.""" cmd = 'python badge_server/badge_server.py ' \ '--host=\'0.0.0.0\' --port=8080' process = subprocess.Popen( cmd, stdout=subprocess.PIPE, shell=True, preexec_fn...
b66afb7bdb19d6169866f47649999f9cad8c5dfe
630,566
import re def parse_dockerimage_string(instr): """ Parses a string you'd give 'docker pull' into its consitutent parts: registry, repository, tag and/or digest. Returns a dict with keys: host - hostname for registry port - port for registry repo - repository name and user/namespace if present...
da9aa8a32ce9bd194a10d57f746701e1d71bc37f
630,567
import os import argparse def parse_arguments(): """Parses command-line options.""" def check_file_path(path): if os.path.isfile(path): return path else: raise ValueError(path) parser = argparse.ArgumentParser() parser.add_argument("benchmark_files", metavar="<bench...
07547293b8624d658bb95511c018212662d8d016
630,568
def LocateSpecialWord(senti_dict, not_dict, degree_dict, sent): """Find the location of Sentiment words, Not words, and Degree words The idea is pretty much naive, iterate every word to find the location of Sentiment words, Not words, and Degree words, additionally, storing the index into corresponding arr...
1cfed9765c4f6ab5f970d0ad0a4f663f19ed58a6
630,569
import copy def bubble_sort(l): """Sort list from smallest to largest using bubble sort algorithm. Args: l (list): unsorted list. Return: list: Sorted list. """ target = copy.copy(l) begin, end = 0, len(target) - 1 while end != 0: for i in range(end): ...
0d82a919228e25a1f53d59507a533f84e0f26134
630,570
def check_duplicated_number(main_list: list): """This function will check the first element duplicated in the list of list""" checked_numbers = set() first_duplicated_number = -1 for number in main_list: if number in checked_numbers: first_duplicated_number = number brea...
9157af114ad614af82beb7864d626828a12b27d8
630,571
import os def test_data_dir(test_data_dir): """The path to the directory that contains the fixture data""" return os.path.join(test_data_dir, "demo")
fbe36292decdf60088005e753bf35a091c382ed8
630,572