content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def match_barcode_rule(trello_db, barcode): """Finds a barcode rule matching the given barcode. Returns the rule if it exists, otherwise returns None.""" for rule in trello_db.get_all('barcode_rules'): if rule['barcode'] == barcode: return rule return None
e6a240c265b61025f77175b7d4be4f7e868263b7
664,784
import os def countfiles(src_path = '.'): """Count the number of files in a path branch recursively.""" cnt = 0 for root, dirnames, filenames in os.walk(src_path): cnt += len(filenames) print('File count = %s in %s.' % (cnt, src_path)) return cnt
5944dfb09514737d2149de61ca1642862fb80392
664,785
from typing import TextIO from typing import List def parse_floats(io: TextIO) -> List[float]: """Parse first line of io to list of floats. Parameters ---------- io :: TextIO Object supporting `readline()` Returns ------- floats :: List[float] A list of floats Exampl...
58c6cc69e28f06c5d831b7bdab47793619110b12
664,786
import os import glob import re def get_files(f, args): """ given a folder will return all the files that are not txt, or contain NCOP or NCED. Will also change dir to folder. inpt: f - string of folder name args - argparse object oupt: list of strings """ os.chdir...
4c255eba8c8fb04e1f66e5a2ea706c07e61e7b04
664,787
def hex2int(hex_str): """ Convert hex characters (e.g. "23" or "011a") to int (35 or 282) :param hex_str: hex character string :return: int integer """ return int(hex_str, 16)
b6ba55909550a9e4714f6209b08bda633a2c9a4b
664,788
import re def cut_ansi_string_into_parts(string_with_ansi_codes): """ Converts a string with ambedded ANSI Color Codes and parses it to create a list of tuples describing pieces of the input string. :param string_with_ansi_codes: :return: [(sty, str, str, str), ...] A list of tuples. Each tuple ha...
fff04f1b06a59f385e2a4da500cd70da0a3bcef8
664,790
import os import sys def get_toolchain_path_or_die(ndk, host_tag): """Return the toolchain path or die.""" toolchain_path = os.path.join(ndk, 'toolchains/llvm/prebuilt', host_tag) if not os.path.exists(toolchain_path): sys.exit('Could not find toolchain: {}'.forma...
7f54305705304236f9fa7f4dd29c33eb835ce4f0
664,791
def determine_ambiguous_references(columns: set, definitions: set) -> set: """ Return the set of reference names that exist as both a column and a definition. """ # get the diffs between the two sets unambiguous_columns = columns - definitions unambiguous_definitions = definitions - columns # then...
2adbd2133d73f1c7fed6cae9ab2bd4099dde5b17
664,792
def find_toc_page_count(doc): """ TOC uses Roman numerals instead of Arabic. The last character on each page is the page number, Counts the number of pages from the start of the document until page 1 is found. """ for i in range(doc.pageCount): # page numbering starts from 1 after toc se...
1f4b0ab7ee64279ff50a28d54146dcf6a56cf5af
664,793
import os def get_long_description(): """ Retrieve the long description from the README. :return: The long description :rtype: str """ base = os.path.abspath(os.path.dirname(__file__)) file = open(os.path.join(base, "README.md")) data = file.read() file.close() return data
c2eddb92abc34ae3bbf918dc980bcff7b75bd302
664,794
def ansirgb(red: int, green: int, blue: int) -> str: """ This function converts RGB values to ANSI color codes. @param red: Red value of RGB 0-255. @type red: int. @param green: Green value of RGB 0-255. @type green: int. @param blue: Blue value of RGB 0-255. @type blue: int. @...
e5f6cfea68ac0ab86cfa6324201bd1c3117f4598
664,795
def make_tweet(text, time, lat, lon, sentiment): """Return a tweet, represented as a python dictionary. text -- A string; the text of the tweet, all in lowercase time -- A datetime object; the time that the tweet was posted lat -- A number; the latitude of the tweet's location lon -- A number; the ...
39b4a2340d82350259cecbb419c194fc1d849870
664,796
def row_major(l: list) -> tuple[list, int]: """ converts a 2d list to a 1d list using row major algorithm and returns a 1d list and row count """ out = [] i = 0 while i < len(l): ii = 0 a = l[i] while ii < len(a): out.append(a[ii]) ii += 1 i += 1 ...
dfe4adfaded6a43ebf5354669bc62a42fd9b003e
664,797
def get_repo_name(pull_request, key): """ Extract repo name from a pull request dict. """ return pull_request[key]["repo"]["name"]
34d002d70d92005bb512c7ce624a2244cfad5519
664,798
from typing import Any def convert_to_str(data: Any): """attempt to convert complex data to a string""" if data is not None: if isinstance(data, (str, int, float, bool)): return data if isinstance(data, list): return [convert_to_str(d) for d in data] if not isin...
80a4992a6d6c16444cebe0ef4208a2d5eb4f678c
664,799
import inspect def define_nameless_parameter(): """ Create Nameless Parameters A nameless parameter has a reduced string representation. This is done by cloning the parameter type and overwriting its __str__ method. The inner structure is still a valid parameter. """ def __str__(self): ...
3cef9779bbe9d8d4e7df7952bbc282ecbb7b9e71
664,800
def on_toolforge() -> bool: """Detect if this is a Wikimedia Cloud Services environment. While this function is ``on_toolforge``, it will also detect Cloud VPS. """ try: f = open("/etc/wmcs-project") except FileNotFoundError: wmcs = False else: wmcs = True f.clos...
2946545f1367b48d4cc6b8f464fdc0e4c7680c10
664,801
import math def gon_to_rad(angle: float) -> float: """Converts from gon (grad) to radiant. Args: angle: Angle in gon. Returns: Converted angle in rad. """ return angle * math.pi / 200
e87714d6162ea8457118dfd4cbdfc67a7a21069d
664,802
def prob_class_1_arrival(state, lambda_1, mu, num_of_servers): """Gets the probability of a class 1 arrival to occur""" return lambda_1 / (lambda_1 + (mu * min(state[1], num_of_servers)))
d3c20313ba1b7fac54fab8698589413bfb84941b
664,803
def decode_int(v): """Decodes integer value from hex string. Helper function useful when decoding data from contracts. :param str v: Hexadecimal string :return: Decoded number :rtype: num """ if v[0:2] == '0x': return int(v.replace('0x', ''), 16) else: return int(v)
3bf1ae523a4d1597a019d9ec7d83d2667f89aba9
664,804
def closed_neighborhood(graph, v): """The closed neighborhood of a vertex in a graph Args: graph (networkx.classes.graph.Graph): graph v: vertex in a graph Returns: The neighbors of v in graph, as a set. Example: >>> import networkx as nx >>> from pycliques.dominated imp...
451b7c57d339bb9826bb417ee064dc3fb62c0df3
664,805
def NP(record): """ "No Process": the linked record is not processed. This is the default behavior of EPICS links. Example (Python source) ----------------------- `my_record.INP = NP(other_record)` Example (Generated DB) ---------------------- `field(INP, "other NPP")` """ retu...
68041ce93ffa3df2d12b989a1105f194b341126a
664,806
def pretty_output(counter): """make Couter output more readable """ output = '' for item in counter: output += "{}[{}] ".format(item[0], item[1]) return output
b0e2f7a2b8ca1223311fc120fd06feed1050bb65
664,807
def rate_new_leaves_tabular( leaf, observation, model, discount, state_values ): """Rates new leaves based on hardcoded values.""" del leaf del observation del discount init_state = model.clone_state() def rating(action): (observation, reward, _, _) = model.step(action) mode...
6de23de5a3805b65b41997e71ca5d8df3a6d7a5e
664,808
def binarize(binarizer, labels): """ Returns: It can be feeded to the below placeholder. input_y = tf.placeholder( tf.float32, [None, num_classes], name="input_y") """ return binarizer.transform(labels)
38773490975d731583aeaa8ccf68442ce80be331
664,809
def find_stab(state, stab_xs, stab_zs): """ Find the sign of the logical operator. Args: state: stab_xs: stab_zs: Returns: """ # print(stab_xs, stab_zs) if len(stab_xs) == 0 and len(stab_zs) == 0: return True stab_xs = set(stab_xs) stab_zs = set(s...
3cc02c209622d6b83ce5c4a2b84dec0817eecc41
664,810
def pisum_c(N: int) -> float: """ Machin formula for Pi http://mathworld.wolfram.com/PiFormulas.html """ s = 0.0 for k in range(1, N + 1): s += (-1) ** (k + 1) / (2 * k - 1) return 4.0 * s
0992e3dcc1615bf7995b19f07749107db2323daa
664,811
def camels_in_dest(camel_dict, destination): """Find the camels in the destination square Parameters ---------- camel_dict : nested dict Dictionary with current camel positions destination : int Square where camels are moving Returns ------- max_height_dest : int ...
1a619f06ba4d606357d7229f6a5a0d2e8d717476
664,813
def _capability(interface, version=3, supports_deactivation=None, cap_type='AlexaInterface'): """Return a Smart Home API capability object. https://developer.amazon.com/docs/device-apis/alexa-discovery.html#capability-object There are some additional fields ...
b12abc29c9fa1dd5bb7e8795be6dd6de8c865f40
664,814
import re def list_urls_from_string(text): """ From: https://stackoverflow.com/a/48769624/2907906 Modified to require the protocol (http:// or https://) to be present It'll return a list of urls present in the string """ return re.findall("(?:(?:https?):\/\/)[\w/\-?=%.]+\.[\w/\-?=%.]+", text)
88338c3c4e1eb75f5ee0819ab0f4cc15405cdb06
664,815
def coords_zero(coords): """ Return the origin for the coords """ return (0,) * len(coords)
345240a2b060ce5f7a295967de4bf432c436efc4
664,816
import json def loads(kv_data): """ Decoding Key Value Json String :param kv_data: [String] JSON String representing the Key Value information :return: [Dictionary] Returns the JSON in dictionary form """ dict_kv = {} if isinstance(kv_data, str): kvs = json.loads(kv_data) ...
8713262b8cac0cdbe0f3fd7cdfb1e9771a0727ca
664,817
import argparse import logging import os import sys def load_context(): """Load and parse command line arguments and create runtime context. Parse command line arguments and create runtime context. Also set any logging parameters passed in (just to file for the moment). Returns: cont...
655322179aea21a4c58ed2c5c387f5106dd51710
664,818
import torch def get_flow_gradients(flow, device=None): """torch in, torch out""" flow = flow[:, None] sobel = [[1, 2, 1], [0, 0, 0], [-1, -2, -1]] sobel_kernel_y = torch.tensor(sobel, dtype=torch.float32).unsqueeze(0) sobel_kernel_x = torch.transpose(sobel_kernel_y, 1, 2) sobel_kernel_x, sobe...
b20117f7addc102f64c7da59fe046ea98bf6248e
664,819
import re def filter_lines(text: str, regex: str, flags=re.MULTILINE) -> str: """ Removes lines matching a certain regular expression from a text. :param flags: Indicate the flags to use with the regex. :param text: A string containing the text. :param regex: The regular expression of the lines to...
590a0cf4bd69ef373a583ced2f8da9cf03e3691e
664,820
import base64 def decode(encoded_message): """ Decodes the message in base64 Args: encoded_message (str): encoded message Returns: str: decoded message """ encoded_message_bytes = encoded_message.encode("ascii") decoded_base64_bytes = base64.b64decode(encoded_message_byt...
2d7a23bc4e0d36b4f72ae5b17d24f9957e187615
664,821
def is_unlimited(rate_limit): """ Check whether a rate limit is None or unlimited (indicated by '-1'). :param rate_limit: the rate limit to check :return: bool """ return rate_limit is None or rate_limit == -1
8e19a8aff46713c6e1886b40bf005217166eda01
664,822
def detailed_score(slides, photos): """Compute the detailedscore. Parameters ----------- slides : list of tuples Each item of the list is the tuple of photos ids photos : dict Dict of photos : {"id": {"orientation": "V/H", "tags": ["tag1", "tag2"]}} ...
beba0f4a96bfe270c1db84e6c0c5a61e67721ba7
664,823
def remove_arc(net, arc): """ Removes an arc from a Petri net Parameters --------------- net Petri net arc Arc of the Petri net Returns ------------- net Petri net """ net.arcs.remove(arc) arc.source.out_arcs.remove(arc) arc.target.in_arcs.re...
d8451203ab774ce936823a22022b0fdd2160162d
664,826
def get_overlap_between_intervals(a, b): """ Finds the overlap between two intervals end points inclusive. #Makes sure not to report overlap beyond either interval length. # a=[10,20]; b=[10,20] --> f(a,b)=10 !(not 11) # a=[10,20]; b=[20,30] --> f(a,b)=1 a=[10,20]; b=[15,30] --> f(a,b)=6 """ #lena=abs(float(a...
aac42510aa368cd793cc93cd3e9f840df9580005
664,827
def _async_get_hass_provider(hass): """Get the Home Assistant auth provider.""" for prv in hass.auth.auth_providers: if prv.type == 'homeassistant': return prv raise RuntimeError('No Home Assistant provider found')
2de333978a219f8a0aa2bc0942896477b8cbba9e
664,828
def split_train_test(X_all, y_all, frac_train): """ The first X% of X_all, y_all become the training set, the rest (1-X)% become the test set. Note that this assumes that the samples are already shuffled or if not (e.g. if we were to split MNIST) that this behavior is intended. """ num_total = X...
5939261def8afba47a2d0e88e23561f5d7e9acd3
664,829
def min_max_temp(cities_data): """Returns a list whose first and second elements are the min and the max temperatures of all the cities in cities_data. """ temps = [] for r in cities_data: temps.append(float(r['temperature'])) return [min(temps), max(temps)]
3b99aa8a1fd0c9d8539a3d7a7fe95bd80df47ab8
664,830
def apply_format(X, y, locs, regs, format_info): """Application of format of data.""" _, format_obj, format_pars, format_f = format_info X_nf, y_nf, locs_nf, regs_nf = [], [], [], [] for i in range(len(X)): X_new, y_new, locs_new, regs_new = format_f(X, y, locs, regs, ...
62ef81b7464271b941b7b88336a3e51a6e9a53ca
664,831
def trim(msa, threshold=0.0): """Trim a MSA to its first and last non-gap containing columns.""" def gap_pct(msa, index): return msa.column(index).count("-") / msa.count() length = len(msa) start, end = 0, length - 1 start_found, end_found = False, False for i in range(length): ...
c15a4e02af679ead90b90ef35d1d1d251971af84
664,832
def stray(arr): """ You are given an odd-length array of integers, in which all of them are the same, except for one single number. :param arr: an array of integers. :return: the single different number in the array. """ a, b = set(arr) return a if arr.count(a) == 1 else b
17e99c2d22baceb89c16c01a138896918ab3a9e6
664,833
def block_to_dict(block): """ Serialize a block as a dict. """ return { "type": block.type, "value": block.value }
c53b1d12eb1fd347b46afc2adb275cf41294b79e
664,834
def get_inside_outside_brackets(data, start_char, end_char, nested=True): """Split string into portions inside and outside delimiters Args: data: str The string to parse start_char: str Character indicating the beginning of a delimited string end_char: str ...
535c4d57ca8bfd7b9347e6251ecc95ffacdadf15
664,835
import hashlib def hash_string(string): """ return the md5 hash of a string""" return hashlib.md5(string).hexdigest()
356dd3c74b080fa8b305513c18ea5624f6e1435a
664,836
def read_senticap_anps(senticap_anp_file): """ :param senticap_anp_file: :return: twp lists, first has positive ANPs [beautiful dog, nice person] the second negative. """ positive_anps = [] negative_anps = [] current_sentiment = 'positive' # the file lists first the postives, then all the ne...
f51589fb7de55e9bbae14514f26ad6e8185916d2
664,837
import torch def sample_from_latent_distribution(z_mean, z_logvar): """Samples from the Gaussian distribution defined by z_mean and z_logvar.""" e = torch.randn_like(z_mean) return torch.add( z_mean, torch.exp(z_logvar / 2) * e, )
d085282de657a7bb540aad1520ca984ac158aeb5
664,839
def valid_type(str_of_type): """Function for returning a pandas type given a string value representing that type Args: str_of_type (str): a python type in string form Outputs: the Pandas term for that type """ if str_of_type in ['int','integer']: return('Int6...
1e75e2a752f7ce44b6e6839ce570c2872d950c95
664,840
def languages(): """A dictionary of languages per file extension.""" return {"c": "c", "i": "c", "bc": "llvm", "ll": "llvm", "bpl": "boogie"}
9096a12b433403e4cc6b25cbf40d6f10062b02a4
664,841
import filecmp def compare_exact(objfilea, objfileb): """Byte for byte comparison between object files. Returns True if equal, False otherwise. """ return filecmp.cmp(objfilea, objfileb)
1954b99f8d4f7ba8e32ac0e6954a9745bd12298c
664,842
def file_id(file_query): """Returns an ID of the form `_file_$ID` to represent a [snoop.data.models.File][]. This ID is used to cross-link objects in the API. """ return f'_file_{file_query.pk}'
372c2290c372130f6e5ce9c5001952595aea81e9
664,843
def multiline_top(): """This function returns 1. Multiline Top. Deprecation Note is inserted above this line. This is done via setting ``deprecation.message_location`` to 'top'. This is also here to show that multiline docstrings work """ return 1
57bb4e3a09ceaedc4947a1a87df7daac54488fe0
664,844
def composeVideoMaskName(maskprefix, starttime, suffix): """ :param maskprefix: :param starttime: :param suffix: :return: A mask file name using the provided components """ if maskprefix.endswith('_mask_' + str(starttime)): return maskprefix + '.' + suffix return maskprefix + '_m...
0fe45da135f79086fa52ca2fdca55a6cc51b9a3d
664,845
def lower (s): """ None-tolerant lower case """ if s is not None: s = s.strip().lower() return s
fd3d120f0f1466ee2388b336df915b8474a97f47
664,846
def handler(context, inputs): """Set a name for a machine :param inputs :param inputs.resourceNames: Contains the original name of the machine. It is supplied from the event data during actual provisioning or from user input for testing purposes. :param inputs.newName: The new mac...
87251564bf262d3ef114d171767ce0afb8d03c77
664,847
def make_dict(tokens): """Converts a parsed list of tokens to a dictionary.""" tokdict={} for t in tokens: tokdict[t[0]]=t[1:] return tokdict
5048267d24d211aef26a72e74a4aa96792713304
664,848
def erase(client, file_=None, erase_children=None): """Erase one or more models from memory. Args: client (obj): creopyson Client. `file_` (str|list:str, optional): File name or List of file names; (Wildcards allowed: True). if empty all models in...
6f60055a317bc258d379af4b9075f755752e9540
664,849
def reward2avg(rewards, lengths): """ for episodic environment, change overall rewards to the average reward for each episode :param rewards: the vector of rewards :param length: the vector of lengths for each episode :return: the average undiscounted return """ #rewards = np.array(rewards) ...
2e8c9d9b826b035070712431efff7469325c90a0
664,850
def tileKey(dataset_name, resolution, x, y, z, time=None): """Make a 64 bit key from a tile""" # Adding time to res. this seems like a stop-gap measure to accomodate time resolution = resolution + int(time or 0) # 8 bits for r and 8 bits for project id highkey = (resolution & 0XFFFF) + (dataset_name << 16) ...
8e6d061c404db1a243fa83c426960fd2de576c31
664,853
def _check_frequency(frequency): """Check given frequency is valid.""" if frequency is None: frequency = 'monthly' if frequency not in ('daily', 'monthly'): raise ValueError("Unsupported frequency '%r'" % frequency) return frequency
5195641096d468ec62522757b3172d25024f2543
664,855
def get_variable_shape(x): """Returns the shape of a variable. # Arguments x: A variable. # Returns A tuple of integers. """ return x.get_value(borrow=True, return_internal_type=True).shape
b6131c690035cca7f9d84c693a809fb202b99e9f
664,856
import os def load_root_path(): """Load the package's json configuration file.""" FILE_DIR = os.path.dirname(os.path.abspath(__file__)) ROOT_DIR = os.path.dirname(FILE_DIR) return ROOT_DIR
5891c4a6ace9dd7c4649c5b476e7c9e86c40f7bc
664,857
import random def soonest_op_dict(d1, d2) -> dict: """ 接受两个字典作为参数,每个字典有如下字段: op: 一个操作 weight: 权重,int,可选 :return 能更早产生op的那个dict 规则:1. 不为 None 的更快 2. op字段值不为 pending 的更快 3. op["time"]更小的更快 4. op["time"]相同时,根据weight字段进行一次带权随机 """ if d1 is None: ...
24579f578f8cd3f6d8742b42a8878d3a5ed148bd
664,858
def format_score(logpath, log, markup): """Turn a log file JSON into a pretty string.""" output = [] output.append('\nLog: ' + logpath) if log['unrecognized']: output.append('\nLog is unrecognized: {}'.format(log['unrecognized'])) else: if log['flagged']: output.append('\...
c3ac492375b72d05481a3a2dc2986149f79b405e
664,860
def calculate_change(total: float) -> float: """Determine how much change is needed.""" return round(1 - (total - int(total)), 2)
1a0ee4d07ff0b7eb096c506e681afeabed774e9c
664,861
def _is_python_synth_repo(gh, repo): """Finds Python repositories with synth files in the top-level directory.""" # Only python repos. if repo["language"] != "python": return False # No private repos. if "private" in repo["repo"]: return False # Only repos with a synth.py in the ...
cb7f06438bfac2807c9369d41377eb35e3f1f33c
664,862
def reply(f): """ Mark f as a handler for mention notifications. """ f.reply = True return f
7da700ed2ab1b4b6e82b7c6d7bc6bab4e4c228a8
664,863
def load_vocab(vocab_file): """Loads a vocabulary file into a dictionary.""" vocab = {} index = 0 with open(vocab_file, "r", encoding="utf-8") as reader: while True: token = reader.readline() if not token: break token = token.strip() ...
2b5dd2acf12f6917154734beb7ab209270bef5f7
664,864
import math def is_cross(x1, y1, x2, y2, r1, r2): """ Input: x1,y1: coordinates of center of first circle x2,y2: coordinates of center of second circle r1,r2: radius of first and second circle respectively Output: True if two circles cross, False if not. """ cat_a...
5a1c2aab0b78eb3116434d51bc14f918ba4d395b
664,865
def win_check(board, mark): """ function that takes in a board and checks to see if someone has won. :param board: the board to check :param mark: the last mark in placed in the board :return: True if game is win or False otherwise """ return ((board[7] == mark and board[8] == mark and board...
38cad514d38aa42fdb88ebe4cb174f2999a9ae9b
664,866
import argparse from typing import Optional from typing import MutableMapping from typing import Any import torch def get_adv_training_params( args: argparse.Namespace, res: Optional[dict] = None ) -> MutableMapping[str, Any]: """Setup Fast AdvProp training data config.""" res = res or {} if args.mult...
c5270173ac6fb62bcf5c752065732705d197e11a
664,867
import random def get_random_coordinate(image): """ Example: coordinates= get_random_coordinates() # gives random x-y coordinates inside image Output: return tupe (x,y). """ x,y,z=image.shape return (random.randint(0,y),random.randint(0,x))
54cbed37aba48363875602b60e2efa6c43dcff99
664,868
def contains(self, key): """ return True if key is in self, False otherwise """ try: # pylint: disable=pointless-statement self[key] return True except KeyError: return False
b8a0f34a5cfce124a474b881cfbdd822802e45c6
664,869
def dfdz_ReLU(z): """Derivative of the rectified linear unit function... Args: z (np.array) Returns: df(z)/dz = 1 if x > 0 else 0 (np.array) """ return (z > 0)
e980413031249fd84a50de21cc23d1a40ba2eeb2
664,870
def convert_seconds(seconds): """Converts the provided seconds value into days, hours, minutes, seconds and returns a tuple containing each of these values""" # Converting seconds to a standard python float type to resolve the "negative 0 when using numpy.float64 type" issue . seconds = float(seconds) ...
664aead3b845243921fe259d7b858fe91f488a37
664,871
def _hashable(x): """ Ensure that an point is hashable by a python dict. """ return tuple(map(float, x))
a76a98475400df98978f5e4f12c5fcd842b56b29
664,873
def make_sepset_node_name(node_a_name, node_b_name): """ Make a standard sepset node name using the two neighboring nodes. :param str node_a_name: The one node's name. :param str node_b_name: The other node's name. :return: The sepset's name :rtype: str """ return "sepset__" + "__".join...
ef8f645dd514b792d278386edac250c02e0a22a6
664,874
import os def default_warehouse(): """ Returns WAREHOUSE if env is set """ return os.environ.get('WAREHOUSE', '')
77fa4459f378e860f34fec50f328a10109f71ea7
664,875
def readHysteresisDelayfromGUI(delay, timeZero): """ Read and create Hysteresis Delays from GUI. The values are given relative to the timezero (so -20 means 20ps before the set t0). The returned value is the absolute ps Delay for the setting of the stage. :param delay, timeZero: :return: delayV...
f51e4a6348a63d6017a722457e661b6044a89317
664,876
import requests import os def get_jwt(): """Fetch an access token from the Auth0 API""" r = requests.post( "https://{}/oauth/token".format(os.getenv("AUTH0_DOMAIN")), data={ "grant_type": "refresh_token", "client_id": os.getenv("AUTH0_CLIENT_ID"), "refresh_t...
32cee9ec0f8a4d31a9f4bf98c2c3ee3485fbef6a
664,877
def sfc_sw_cld(swup_sfc, swup_sfc_clr, swdn_sfc, swdn_sfc_clr): """Cloudy-sky surface upward shortwave radiative flux.""" return swup_sfc - swup_sfc_clr - swdn_sfc + swdn_sfc_clr
6e6a653a89ee15345a9d2a883938b3013cba8125
664,878
def build_walls(tree_links, num_rows, num_columns, x0, y0, dx, dy): """ Build segments representing the maze's walls.""" # Make arrays to indicates whether a node's # left or top wall is broken by the tree. left_side_broken = [[False for c in range(num_columns + 1)] for r in range(num_rows)] top_sid...
6867ffd91d40ea56c5d40745a1c9b88a8973aaa6
664,879
def get_shortest_unique_filename(filename, filenames): """Get a representation of filename in a way that makes it look unique compared to the other given filenames. The most unique part of the path is used, and every directory in between that part and the actual filename is represented with a slash. ...
2ea4b747442021c26b9419c129f543da06af8bad
664,880
def to_ascii(text): """Convert text to ascii.""" asciiText = ''.join([ch if ord(ch) < 128 else ' ' for ch in text]) return asciiText
e66f47599cf3ace70636f2ccec540c7d753301a8
664,881
def rotate_string(string, offset): """ Rotate string in place :param string: given array of characters :type string: list[str] :param offset: offset for rotation :type offset: int :return: list[str] :rtype: rotated string """ if len(string) == 0 or offset == 0: return st...
97246bb38147f04dfdfeeff9d3a204ba1798e32f
664,882
import os def is_work_tree(path): """Check if 'path' is a valid git working tree. A working tree contains a ".git" directory. Arguments: path (string): The path to check. Returns: bool: True if path contains a ".git" """ return path and ".git" in os.listdir(path)
e5e7a942a3f29c72f9f7c576e409e24865d397c6
664,884
import torch def collate_fn(data, args, pad_idx=0): """Padding""" texts, labels = zip(*data) texts = [s + [pad_idx] * (args.max_len - len(s)) if len(s) < args.max_len else s[:args.max_len] for s in texts] return torch.LongTensor(texts), torch.LongTensor(labels)
fb942e5736879ff4b5d220ce93046039fab1be16
664,885
def SpanValue(span, arena): """Given an line_span and a arena of lines, return the string value. """ line = arena.GetLine(span.line_id) c = span.col return line[c : c + span.length]
2511452c2ba055f267d405b2e959e898ccb66ca0
664,886
def _charlie2_trials(): """Details of the trials from charlie v2 trail-making test (shorter). """ blocks = ([0] * 5) + ([1] * 20) + ([2] * 5) + ([3] * 20) + ([4] * 5) + ([5] * 20) block_types = ( (["practice"] * 5) + (["test"] * 20) + (["practice"] * 5) + (["test"] * 20)...
5b1570b6e3dd6f5a645a281799ff69f5a75b53f0
664,887
import re def format_string(s): """ Catch-all for formatting strings """ formatted = "_".join(re.split(r'[^_A-Za-z0-9\d]', s)) if re.match(r'\b[0-9]\b', formatted): formatted = f'_{formatted}' if 'lambda' in formatted: # edge case because Python reserves the token `lambda` for...
db64b2ffd44de45cf1e37fd0ca255d9b8dcd7c5c
664,888
import re def parse_direct_mention(message_text): """ Finds a direct mention (a mention that is at the beginning) in message text and returns the user ID which was mentioned. If there is no direct mention, returns None """ matches = re.search("^<@(|[WU].+?)>(.*)", message_text) # the f...
f72b248f8e31d0bbfb620fb37f382ca4f7c66d28
664,889
def fpd_locations(ctx): """ :param ctx :return: A list of all locations Platform: ASR9000 RP/0/RSP0/CPU0:cxr1#admin show hw-module fpd location all ===================================== ========================================== Existing Field Programm...
c3b3b252a8f4e789133fcaf01269395f11cdec86
664,890
def rpc_get_methods(client, current=None, include_aliases=None): """Get list of supported RPC methods. Args: current: Get list of RPC methods only callable in the current state. include_aliases: Include aliases in the list with RPC methods. """ params = {} if current: params...
7473720d7bfe354300176a107660ad4bdd4d4a88
664,891
import os import types def make_test_image_filenames(name, test_file): """ Create filenames for testing Parameters ---------- name : str An identifier for the specific test. This will make-up part of the filenames. test_file : str Full path of the test file. This will ...
a69d5cd0c6ba58c2c59b09c354c6c414c6117a3a
664,892
import time def rt_format_comment_time(t): """ Given a time struct representing the RT ticket's comment timestamp, this returns a formatted, printable version of this timestamp. :param t: the time struct of the RT ticket's comment timestamp """ return time.strftime("%a %b %d %H:%M:%S %Y UTC"...
83e230471d2d0dbffed2e4bfac668c93a2f6dd92
664,893
from typing import Tuple def extended_euclidean(num_a: int, num_b: int) -> Tuple[int, int, int]: """ Perform the extended euclidean algorithm on the input numbers. The method returns gcd, x, y, such that a*x + b*y = gcd. :param num_a: First number a. :param num_b: Second number b. :return: Tu...
0ea9ef0c45ec70cf0c6642ad74ab312fc30fb8bc
664,895