content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
import random def get_random_number_with_zero(min_num: int, max_num: int) -> str: """ Get a random number in range min_num - max_num of len max_num (padded with 0). @param min_num: the lowest number of the range in which the number should be generated @param max_num: the highest number of the range i...
bdc9f192286262566d2b2a87e8124abdf745ecbd
703,439
def union(list1, list2): """Union of two lists, returns the elements that appear in one list OR the other. Args: list1 (list): A list of elements. list2 (list): A list of elements. Returns: result_list (list): A list with the union elements. Examples: >>> union([1,2,3...
983e96ceb4f4eeb2b4b2d96362a0977be0cb2222
703,445
import re def list_all_links_in_page(source: str): """Return all the urls in 'src' and 'href' tags in the source. Args: source: a strings containing the source code of a webpage. Returns: A list of all the 'src' and 'href' links in the source code of the webpage. """ retu...
f17f2ac2724fcfdd041e2ad001557a0565b51e00
703,446
def get_direction(source, destination): """Find the direction drone needs to move to get from src to dest.""" lat_diff = abs(source[0] - destination[0]) long_diff = abs(source[1] - destination[1]) if lat_diff > long_diff: if source[0] > destination[0]: return "S" else: ...
224a8df79cbafbcf1eed8df522ab7f58cc93598d
703,447
def identity(*args, **kwargs): """ An identity function used as a default task to test the timing of. """ return args, kwargs
472808f6b5260569538f26513f24ffcb1bd88c4d
703,450
def create_logdir(method, weight, label, rd): """ Directory to save training logs, weights, biases, etc.""" return "bigan/train_logs/mnist/{}/{}/{}/{}".format(weight, method, label, rd)
4b4edcc9c0c36720e76013a6fb0faf1b49472bc0
703,454
import re def camel_case_to_title_case(camel_case_string): """ Turn Camel Case string into Title Case string in which first characters of all the words are capitalized. :param camel_case_string: Camel Case string :return: Title Case string """ if not isinstance(camel_case_string, str): ...
bcc40753a8672355519741f5aec64c262431d582
703,456
def pmr_corr(vlos, r, d): """ Correction on radial proper motion due to apparent contraction/expansion of the cluster. Parameters ---------- vlos : float Line of sight velocity, in km/s. r : array_like, float Projected radius, in degrees. d : float Cluster distan...
c9136c5ae33e89d6f57b936b92c23001fd30ccfa
703,457
def get_min_corner(sparse_voxel): """ Voxel should either be a schematic, a list of ((x, y, z), (block_id, ?)) objects or a list of coordinates. Returns the minimum corner of the bounding box around the voxel. """ if len(sparse_voxel) == 0: return [0, 0, 0] # A schematic if len(...
371b25b795a1a2ffeb0fc3724f01f1a329f917ae
703,458
from typing import Any def validate_delta(delta: Any) -> float: """Make sure that delta is in a reasonable range Args: delta (Any): Delta hyperparameter Raises: ValueError: Delta must be in [0,1]. Returns: float: delta """ if (delta > 1) | (delta < 0): raise ...
1fd3084c047724a14df753e792b8500a103a34c0
703,461
def build_authenticate_header(realm=''): """Optional WWW-Authenticate header (401 error)""" return {'WWW-Authenticate': 'OAuth realm="%s"' % realm}
74c2e4e4188b608120f241aadb20d8480ac84008
703,464
import json import copy def get_args(request, required_args): """ Helper function to get arguments for an HTTP request Currently takes args from the top level keys of a json object or www-form-urlencoded for backwards compatability. Returns a tuple (error, args) where if error is non-null, the...
b44e058590945211ca410005a5be2405b4756ca4
703,466
def determine_header_length(trf_contents: bytes) -> int: """Returns the header length of a TRF file Determined through brute force reverse engineering only. Not based upon official documentation. Parameters ---------- trf_contents : bytes Returns ------- header_length : int ...
e8aa5110691e877c34f208af5bd508f0f5ec4760
703,469
import re def _join_lines(source): """Remove Fortran line continuations""" return re.sub(r'[\t ]*&[\t ]*[\r\n]+[\t ]*&[\t ]*', ' ', source)
9caa3b6f470a96a7b473f3cce12f57d3787e91dd
703,470
import requests def get_kalliope_bijlage(path, session): """ Perform the API-call to get a poststuk-uit bijlage. :param path: url of the api endpoint that we want to fetch :param session: a Kalliope session, as returned by open_kalliope_api_session() :returns: buffer with bijlage """ r = ...
b2a126b8e33bab50b1e2aa122645d7a45d6dfea9
703,472
def filter_by_book_style(bibtexs, book_style): """Returns bibtex objects of the selected book type. Args: bibtexs (list of core.models.Bibtex): queryset of Bibtex. book_style (str): book style key (e.g. JOUNRAL) Returns: list of Bibtex objectsxs """ return [bib for bib in ...
ca3b46772930a6f6e28b6fc0ee4d175ee8d69c3c
703,474
import random def random_val(index, tune_params): """return a random value for a parameter""" key = list(tune_params.keys())[index] return random.choice(tune_params[key])
1cf7ba9d1a3ff651f946a8013e338d62f4fec3ab
703,478
def coding_problem_19(house_costs): """ A builder is looking to build a row of N houses that can be of K different colors. He has a goal of minimizing cost while ensuring that no two neighboring houses are of the same color. Given an N by K matrix where the nth row and kth column represents the cost to ...
f9d8b33f449d7a2f87118be3e4d894988b781476
703,486
import requests def requests_get(url): """Make a get request using requests package. Args: url (str): url to do the request Raises: ConnectionError: If a RequestException occurred. Returns: response (str): the response from the get request """ try: r = reque...
a438d211e6b5bf78af56783b5d22c85961a2d563
703,487
def cases_vs_deaths(df): """Checks that death count is no more than case count.""" return (df['deaths'] <= df['cases']).all()
994ae93fb23090de50fc4069342487d0d8e621ed
703,489
import re def add_pronom_link_for_puids(text): """If text is a PUID, add a link to the PRONOM website""" PUID_REGEX = r"fmt\/[0-9]+|x\-fmt\/[0-9]+" # regex to match fmt/# or x-fmt/# if re.match(PUID_REGEX, text) is not None: return '<a href="https://nationalarchives.gov.uk/PRONOM/{}" target="_bla...
5fdc9c15895dfd75be54ad0258e66625462204a2
703,491
import random def shuffle_string(s): """ Shuffle a string. """ if s is None: return None else: return ''.join(random.sample(s, len(s)))
25d109f11737b60cecf391fd955f2df4366de7e6
703,494
def get_rule_full_description(tool_name, rule_id, test_name, issue_dict): """ Constructs a full description for the rule :param tool_name: :param rule_id: :param test_name: :param issue_dict: :return: """ issue_text = issue_dict.get("issue_text", "") # Extract just the first lin...
546dcb5ce2cbc22db652b3df2bf95f07118611cf
703,495
import itertools def check_length(seed, random, query_words, key_max): """ Google limits searches to 32 words, so we need to make sure we won't be generating anything longer Need to consider - number of words in seed - number of words in random phrase - number of words in the lists from the qu...
14871b468454f324223673a0c57941ea9e63341a
703,496
def is_string(val): """ Is the supplied value a string or unicode string? See: https://stackoverflow.com/a/33699705/324122 """ return isinstance(val, (str, u"".__class__))
99b082ec080f261a7485a4e8e608b7350997cf18
703,497
def context_get(stack, name): """ Find and return a name from a ContextStack instance. """ return stack.get(name)
a5a9a50c54e8f0f685e0cf21991e5c71aee0c3d6
703,501
def tree_names (tree): """Get the top-level names in a tree (including files and directories).""" return [x[0] for x in list(tree.keys()) + tree[None] if x is not None]
12a5522974671f3ab81f3a1ee8e8c4db77785bd3
703,504
def fixed_width_repr_of_int(value, width, pad_left=True): """ Format the given integer and ensure the result string is of the given width. The string will be padded space on the left if the number is small or replaced as a string of asterisks if the number is too big. :param int value: An inte...
adb212746dd081112ec1de2c4ea8745d2601c055
703,505
def ConvertListToCSVString(csv_list): """Helper to convert a list to a csv string.""" return ','.join(str(s) for s in csv_list)
547311ceac094211d47d0cc667d54b2a3e697f4e
703,508
def min_distance_bottom_up(word1: str, word2: str) -> int: """ >>> min_distance_bottom_up("intention", "execution") 5 >>> min_distance_bottom_up("intention", "") 9 >>> min_distance_bottom_up("", "") 0 """ m = len(word1) n = len(word2) dp = [[0 for _ in range(n + 1)] for _ in ...
8cd87ffe877aa24d5b1fa36ce1d3b96efb7b4e1e
703,510
def periodize_filter_fourier(h_f, nperiods=1, aggregation='sum'): """ Computes a periodization of a filter provided in the Fourier domain. Parameters ---------- h_f : array_like complex numpy array of shape (N*n_periods,) n_periods: int, optional Number of periods which should be...
f9a2845dcf40eedce9d46faba506f1c1358ce6a5
703,511
def slope_id(csv_name): """ Extract an integer slope parameter from the filename. :param csv_name: The name of a csv file of the form NWS-<SLP>-0.5.csv :return: int(<SLP>) """ return int(csv_name.split("-")[1])
1ae34f1e5cc91fdc3aaff9a78e1ba26962475625
703,513
def minbox(points): """Returns the minimal bounding box necessary to contain points Args: points (tuple, list, set): ((0,0), (40, 55), (66, 22)) Returns: dict: {ulx, uly, lrx, lry} Example: >>> minbox((0, 0), (40, 55), (66,22)) {'ulx': 0, 'uly': 55, 'lrx': 66, 'lry': 0...
d8b11d40b52886f290d28f3434b17d2b9641c4fb
703,514
def apply_regression(df, w): """ Apply regression for different classifiers. @param df pandas dataframe; @param w dict[classifier: list of weights]; @return df with appended result. """ # get input if 'state' in df.columns: x = df.drop('state', axis=1).to_numpy(dtype='float64') ...
1fb5fd9f4b297cd024e405dc5d9209213d28ff0d
703,516
def get_lambda_cloud_watch_func_name(stackname, asg_name, instanceId): """ Generate the name of the cloud watch metrics as a function of the ASG name and the instance id. :param stackname: :param asg_name: :param instanceId: :return: str """ name = asg_name + '-cwm-' + str(instan...
893abaf60684cbf9d72774d6f5bb2c4351744290
703,518
def secondary_training_status_changed(current_job_description, prev_job_description): """Returns true if training job's secondary status message has changed. Args: current_job_description: Current job description, returned from DescribeTrainingJob call. prev_job_description: Previous job descri...
b1d1a83cccb8cf84fa678345bcf7b3f6531aa2c5
703,519
def string_concat(str1, str2): """Concatenates two strings.""" return str1 + str2
5b6d842fca2d3623d33341d9bba4e4a76ec29e15
703,520
def remove_spaces(input_text, main_rnd_generator=None, settings=None): """Removes spaces. main_rnd_generator argument is listed only for compatibility purposes. >>> remove_spaces("I love carrots") 'Ilovecarrots' """ return input_text.replace(" ", "")
a9ba3bcca4a4ff1610d52271562e053f25815618
703,521
from typing import List from typing import Counter import heapq def top_k_frequent_pq(nums: List[int], k: int) -> List[int]: """Given a list of numbers, return the the top k most frequent numbers. Solved using priority queue approach. Example: nums: [1, 1, 1, 2, 2, 3], k=2 output: [1, 2]...
4d30bd7e11a087be1a23f9db5c8af7f78c083a5f
703,522
def monthFormat(month: int) -> str: """Formats a (zero-based) month number as a full month name, according to the current locale. For example: monthFormat(0) -> "January".""" months = [ "January", "February", "March", "April", "May", "June", "July", ...
cb675f547d9beec0751d8252e99b5c025b8fd291
703,524
def build_fnln_contact(individual_contact): """ Expected parameter format for individual_contact ('My Name', 'myname@gmail.com') Sample output: {'email': 'myname@gmail.com', 'name': 'My Name'} """ return { "email": individual_contact[-1], "name": individual_...
54080191320cfeb425de0f765f10e29726405d0d
703,525
import math def bearing(lat1: float, lon1: float, lat2: float, lon2: float) -> float: """Calculate bearing from lat1/lon2 to lat2/lon2 Arguments: lat1 {float} -- Start latitude lon1 {float} -- Start longitude lat2 {float} -- End latitude lon2 {float} -- End longitude Retu...
9148bc2726247cedf8a7de7279dac47316f2864f
703,536
def get_title(reg_doc): """ Extract the title of the regulation. """ parent = reg_doc.xpath('//PART/HD')[0] title = parent.text return title
744759addf0cea3ba6cc3dadad05d535b66b20d6
703,537
import random import requests def get_rising_submissions(subreddit): """Connects to the Reddit API and queries the top rising submission from the specified subreddit. Parameters ---------- subreddit : str The name of the subreddit without forward slashes. Returns ------- ...
115edc8986acdefbb232218d237bcba7320db9a0
703,538
def new_headers() -> list: """Return list of new headers with clean names.""" return [ "date", "Rohs FB1", "Rohs FB2", "Rohs gesamt", "TS Rohschlamm", "Rohs TS Fracht", "Rohs oTS Fracht", "Faulschlamm Menge FB1", "Faulschlamm Menge FB2", ...
c81c38e8521f159f0bbf29b3a32adeaa13d4c38f
703,541
import hashlib import io def calc_file_md5(filepath, chunk_size=None): """ Calculate a file's md5 checksum. Use the specified chunk_size for IO or the default 256KB :param filepath: :param chunk_size: :return: """ if chunk_size is None: chunk_size = 256 * 1024 md5sum = has...
8f391ade85a5b69ca63d8adb3eff6ff6af7a08e3
703,542
import struct def _read_int(f, b): """ Read an integer of a specified number of bytes from the filestream f """ if b == 1: return struct.unpack('<B', f.read(b))[0] elif b == 2: return struct.unpack('<H', f.read(b))[0] elif b == 4: return struct.unpack('<I', f.read(b))[0...
36bcc2ccd4edd61fd9c6a438c3a069e699b7b17a
703,544
def terminal_values(rets): """ Computes the terminal values from a set of returns supplied as a T x N DataFrame Return a Series of length N indexed by the columns of rets """ return (rets+1).prod()
bea1f2a668deac3e915f7531ab68aea207e57d91
703,551
def getColumnNames(hdu): """Get names of columns in HDU.""" return [d.name for d in hdu.get_coldefs()]
9ac8fefe6fcf0e7aed10699f19b849c14b022d47
703,553
def get_url(server_name, listen_port): """ Generating URL to get the information from namenode/namenode :param server_name: :param listen_port: :return: """ if listen_port < 0: print ("Invalid Port") exit() if not server_name: print("Pass valid Host...
097e347a75eb581ae97734552fa6f9e7d3b11ce6
703,555
def latex_code(size): """ Get LaTeX code for size """ return "\\" + size + " "
03478f8f62bb2b70ab5ca6ece66d4cdca3595dd6
703,557
def has_cycle_visit(visiting, parents, adjacency_list, s): """ Check if there is a cycle in a graph starting at the node s """ visiting[s] = True for u in adjacency_list[s]: if u in visiting: return True if u in parents: continue parents[u] = s if has_cycle_visit(visiting, paren...
5f87f6f39d88cbae93e7e461590002ca6a94aa20
703,558
def remove_trailing_whitespace(line): """Removes trailing whitespace, but preserves the newline if present. """ if line.endswith("\n"): return "{}\n".format(remove_trailing_whitespace(line[:-1])) return line.rstrip()
2c5f7b3a35152b89cda6645911569c9d2815f47e
703,559
import networkx def make_cross(length=20, width=2) -> networkx.Graph: """Builds graph which looks like a cross. Result graph has (2*length-width)*width vertices. For example, this is a cross of width 3: ... +++ +++ ...+++++++++++... ...+++++++++++... ...+++++...
f0be683fd8971ea8b3cc0b40977a939c117e9906
703,561
def must_be_known(in_limit, out_limit): """ Logical combinatino of limits enforcing a known state The logic determines that we know that the device is fully inserted or removed, alerting the MPS if the device is stuck in an unknown state or broken Parameters ---------- in_limit : ``boo...
241b66b359643d069aa4066965879bb6ac76f2ae
703,564
def scale(x): """Scales values to [-1, 1]. **Parameters** :x: array-like, shape = arbitrary; unscaled data **Returns** :x_scaled: array-like, shape = x.shape; scaled data """ minimum = x.min() return 2.0 * (x - minimum) / (x.max() - minimum) - 1.0
e5c40a4a840a1fa178a2902378a51bfefc83b368
703,565
def GetStaticPipelineOptions(options_list): """ Takes the dictionary loaded from the yaml configuration file and returns it in a form consistent with the others in GenerateAllPipelineOptions: a list of (pipeline_option_name, pipeline_option_value) tuples. The options in the options_list are a dict: Key i...
d49effbdeb687ec62a2e2296330f66521023944c
703,567
import json def read_json(json_file_path: str) -> dict: """Takes a JSON file and returns a dictionary""" with open(json_file_path, "r") as fp: data = json.load(fp) return data
07cb6c606de83b2b51ddcbf64f7eb45d6907f973
703,572
def enthalpy_Shomate(T, hCP): """ enthalpy_Shomate(T, hCP) NIST vapor, liquid, and solid phases heat capacity correlation H - H_ref (kJ/mol) = A*t + 1/2*B*t^2 + 1/3*C*t^3 + 1/4*D*t^4 - E*1/t + F - H t (K) = T/1000.0 H_ref is enthalpy in kJ/mol at 298.15 K...
05e3f3a35a87f767a44e2e1f4e35e768e12662f7
703,577
def get_acres(grid, coordinates): """Get acres from coordinates on grid.""" acres = [] for row, column in coordinates: if 0 <= row < len(grid) and 0 <= column < len(grid[0]): acres.append(grid[row][column]) return acres
e4ba6aabe07d8859481aefaba4d4559f1ec25e96
703,578
def highest_mag(slide): """Returns the highest magnification for the slide """ return int(slide.properties['aperio.AppMag'])
d42361c979a5addf0ebf4c7081a284c9bc0477ec
703,579
import re def enumerate_destination_file_name(destination_file_name): """ Append a * to the end of the provided destination file name. Only used when query output is too big and Google returns an error requesting multiple file names. """ if re.search(r'\.', destination_file_name): dest...
6b398597db26a175e305446ac39c363a5077ba96
703,581
def combine_envs(*envs): """Combine zero or more dictionaries containing environment variables. Environment variables later from dictionaries later in the list take priority over those earlier in the list. For variables ending with ``PATH``, we prepend (and add a colon) rather than overwriting. If...
feb6e00b9c0b1262220339feac6c5ac2ae6b6b17
703,585
def pattern_matching(pattern, genome): """Find all occurrences of a pattern in a string. Args: pattern (str): pattern string to search in the genome string. genome (str): search space for pattern. Returns: List, list of int, i.e. all starting positions in genome where pattern appea...
86ae704586fbac937e044f41a8831f2669c4e7dc
703,594
import glob def findLblWithoutImg(pathI, pathII): """ :param pathI: a glob path. example: "D:/大块煤数据/大块煤第三次标注数据/images/*.jpg" :param pathII: a glob path. example: "D:/大块煤数据/大块煤第三次标注数据/labels/*.txt" :return: num of image which not has label """ num = 0 pathI = glob.glob(pathI) pathII = g...
30edbff244acb0014b54cf3c85d86a47d779d226
703,595
import math def lcf_float(val1, val2, tolerance): """Finds lowest common floating point factor between two floating point numbers""" i = 1.0 while True: test = float(val1) / i check = float(val2) / test floor_check = math.floor(check) compare = floor_check * test if...
b4bef1a63984440f43a1b0aa9bf9805cb4bfd466
703,596
def _convert_text_to_logs_format(text: str) -> str: """Convert text into format that is suitable for logs. Arguments: text: text that should be formatted. Returns: Shape for logging in loguru. """ max_log_text_length = 50 start_text_index = 15 end_text_index = 5 return...
4f7ff95a5cd74bdccd41559f58292cc9b1003ba2
703,598
def digits_to_num(L, reverse=False): """Returns a number from a list of digits, given by the lowest power of 10 to the highest, or the other way around if `reverse` is True""" digits = reversed(L) if reverse else L n = 0 for i, d in enumerate(digits): n += d * (10 ** i) return n
1648073d46411fd430afea4f40f7fa9f4567793c
703,600
def parse_problems(lines): """ Given a list of lines, parses them and returns a list of problems. """ return [len(p) for p in lines]
83747e57bddf24484633e38ce27c51c7c8fce971
703,605
def create_class_hierarchy_dict(cls): """Returns the dictionary with all members of the class ``cls`` and its superclasses.""" dict_extension_order = cls.__mro__[-2::-1] # Reversed __mro__ without the 'object' class attrs_dict = {} for base_class in dict_extension_order: attrs_dict.update(vars(...
0378fb3243a48964fcec42fddb38c0664a338ee4
703,608
def encode(string): """Encode some critical characters to html entities.""" return string.replace('&', '&amp;') \ .replace('<', '&lt;') \ .replace('>', '&gt;') \ .replace(' ', '&nbsp;&nbsp;') \ .replace('\n', ...
faea4b2f2e032b5e05e2c99bc56a1cf35e60b85d
703,610
def rem(x, a): """ x: a non-negative integer argument a: a positive integer argument returns: integer, the remainder when x is divided by a. """ if x == a: return 0 elif x < a: return x else: return rem(x-a, a)
22b421c090970810f9aa4d55ff5a700e1301c0b8
703,611
def identity(value): """ Node returning the input value. """ return value
e1af1346b11bc36a4426ad3c557dc01045657de8
703,616
import re def parse_members_for_workspace(toml_path): """Parse members from Cargo.toml of the worksapce""" with open(toml_path, mode='rb') as f: data = f.read() manifest = data.decode('utf8') regex = re.compile(r"^members\s*=\s*\[(.*?)\]", re.S | re.M) members_block = regex.findall(manif...
63926ac1eaadc360e2407f2fff5f41b7667e52b4
703,618
def decodeXMLName(name): """ Decodes an XML (namespace, localname) pair from an ASCII string as encoded by encodeXMLName(). """ if name[0] is not "{": return (None, name.decode("utf-8")) index = name.find("}") if (index is -1 or not len(name) > index): raise ValueError("Invalid enc...
28a81aed2477b444ac061b21ca838912ee2bf24b
703,620
def plural(items_or_count, singular: str, count_format='', these: bool = False, number: bool = True, are: bool = False) -> str: """Returns the singular or plural form of a word based on a count.""" try: count = len(items_or_count) except TypeEr...
01f397579b60538f25710566507973bdc6422874
703,627
def role_object_factory(role_name='role.test_role'): """Cook up a fake role.""" role = { 'nameI18n': role_name[:32], 'active': 1 } return role
e79e7b22a83d9da721b074d32878eabeca4054cd
703,629
import itertools def create_possible_expected_messages(message_template, expected_types): """ Some error messages contain dictionaries with error types. Dictionaries in Python are unordered so it makes testing unpredictable. This function takes in a message template and a list of types and returns ...
674dec990e0786d3e313a9b8deec72e37588d8eb
703,630
from pathlib import Path def fp_search_rglob(spt_root="../", st_rglob='*.py', ls_srt_subfolders=None, verbose=False, ): """Searches for files with search string in a list of folders Parameters ---------- spt_root : string...
e8fe03f9549ae77147ec96263411db9273d2c4cb
703,636
def get_minimum(feature): """Get minimum of either a single Feature or Feature group.""" if hasattr(feature, "location"): return feature.location.min() return min(f.location.min() for f in feature)
aec98f5bc065c6a97d32bc9106d67579f76f7751
703,637
def get_player_actions(game, player): """ Returns player's actions for a game. :param game: game.models.Game :param player: string :rtype: set """ qs = game.action_set.filter(player=player) return set(list(qs.values_list('box', flat=True)))
9b961afbee7c3a0e8f44e78c269f37a9b6613488
703,643
def create_lkas_ui(packer, main_on, enabled, steer_alert): """Creates a CAN message for the Ford Steer Ui.""" if not main_on: lines = 0xf elif enabled: lines = 0x3 else: lines = 0x6 values = { "Set_Me_X80": 0x80, "Set_Me_X45": 0x45, "Set_Me_X30": 0x30, "Lines_Hud": lines, "Ha...
16c226698160b14194daf63baf61bb3952e1cd59
703,644
import torch def get_pytorch_device() -> torch.device: """Checks if a CUDA enabled GPU is available, and returns the approriate device, either CPU or GPU. Returns ------- device : torch.device """ device = torch.device("cpu") if torch.cuda.is_available(): device = torch.devic...
0109f3146c96bec08bbe6fa62e5a8bc5638e461c
703,645
import time import random def creat_order_num(user_id): """ 生成订单号 :param user_id: 用户id :return: 订单号 """ time_stamp = int(round(time.time() * 1000)) randomnum = '%04d' % random.randint(0, 100000) order_num = str(time_stamp) + str(randomnum) + str(user_id) return order_num
339764f7dc943c46d959a9bfdc6c48dc9ecd6bef
703,646
def get_rst_title_char(level): """Return character used for the given title level in rst files. :param level: Level of the title. :type: int :returns: Character used for the given title level in rst files. :rtype: str """ chars = (u'=', u'-', u'`', u"'", u'.', u'~', u'*', u'+', u'^') if...
b646b9e0010d87ece7f5c8c53c8abf89ca557a21
703,647
def format_sqlexec(result_rows, maxlen): """ Format rows of a SQL query as a discord message, adhering to a maximum length. If the message needs to be truncated, a (truncated) note will be added. """ codeblock = "\n".join(str(row) for row in result_rows) message = f"```\n{codeblock}```" ...
3b98590c72245241ba488e07fdfdd20acae441cf
703,652
import re def regex_sub_groups_global(pattern, repl, string): """ Globally replace all groups inside pattern with `repl`. If `pattern` doesn't have groups the whole match is replaced. """ for search in reversed(list(re.finditer(pattern, string))): for i in range(len(search.groups()), 0 if ...
67e909778d9565d498fc3e7b3c9522378e971846
703,653
def deregister_device(device): """ Task that deregisters a device. :param device: device to be deregistered. :return: response from SNS """ return device.deregister()
44bec0e3ac356f150a0c4a6a0632939a20caafb0
703,656
def sequential_colors(n): """ Between 3 and 9 sequential colors. .. seealso:: `<https://personal.sron.nl/~pault/#sec:sequential>`_ """ # https://personal.sron.nl/~pault/ # as implemented by drmccloy here https://github.com/drammock/colorblind assert 3 <= n <= 9 cols = ['#FFFFE5', '#FFFB...
d2ad5f8993f8c7dac99a577b6115a8452ad30024
703,657
def box2start_row_col(box_num): """ Converts the box number to the corresponding row and column number of the square in the upper left corner of the box :param box_num: Int :return: len(2) tuple [0] start_row_num: Int [1] start_col_num: Int """ start_row_num = 3 * (box_num // 3...
b11e7d4317e1dd32e896f1541b8a0cf05a342487
703,661
import re def hashtag(phrase, plain=False): """ Generate hashtags from phrases. Camelcase the resulting hashtag, strip punct. Allow suppression of style changes, e.g. for two-letter state codes. """ words = phrase.split(' ') if not plain: for i in range(len(words)): try: if not words[i]: del word...
b6e7ab647330a42cf9b7417469565ce5198edd4f
703,665
import re def is_ignored(filename, ignores): """ Checks if the filename matches any of the ignored keywords :param filename: The filename to check :type filename: `str` :param ignores: List of regex paths to ignore. Can be none :type ignores: `list` of `str` or...
3d5016d5ac86efdf9f67a251d5d544b06347a3bf
703,668
def flip_thetas(thetas, theta_pairs): """Flip thetas. Parameters ---------- thetas : numpy.ndarray Joints in shape (num_thetas, 3) theta_pairs : list List of theta pairs. Returns ------- numpy.ndarray Flipped thetas with shape (num_thetas, 3) """ thetas...
e19a274953a94c3fb4768bcd6ede2d7556020ab2
703,672
def from_time (year=None, month=None, day=None, hours=None, minutes=None, seconds=None, microseconds=None, timezone=None): """ Convenience wrapper to take a series of date/time elements and return a WMI time of the form yyyymmddHHMMSS.mmmmmm+UUU. All elements may be int, string or omitted altogether. If omitted...
61d2bf9fb36225990ac0ac9d575c3931ef66e9f6
703,674
def plural(num, one, many): """Convenience function for displaying a numeric value, where the attached noun may be both in singular and in plural form.""" return "%i %s" % (num, one if num == 1 else many)
f29753d25e77bcda2fb62440d8eb19d9bd332d1e
703,675
import math import time def test_query_retry_maxed_out( mini_sentry, relay_with_processing, outcomes_consumer, events_consumer ): """ Assert that a query is not retried an infinite amount of times. This is not specific to processing or store, but here we have the outcomes consumer which we can us...
9339078c432cd087dcdbf799cad8d881defb41c2
703,676
def _to_bytes(str_bytes): """Takes UTF-8 string or bytes and safely spits out bytes""" try: bytes = str_bytes.encode('utf8') except AttributeError: return str_bytes return bytes
fd16c24e80bdde7d575e430f146c628c0000bf9a
703,678
def determine_host(environ): """ Extract the current HTTP host from the environment. Return that plus the server_host from config. This is used to help calculate what space we are in when HTTP requests are made. """ server_host = environ['tiddlyweb.config']['server_host'] port = int(serv...
6e91f93d5854600fe4942f093de593e53aaf2aa0
703,680
def read_messages(message_file): """ (file open for reading) -> list of str Read and return the contents of the file as a list of messages, in the order in which they appear in the file. Strip the newline from each line. """ # Store the message_file into the lst as a list of messages...
0e4b1a6995a6dd25ab3783b53e730d0dd446747c
703,681
def cradmin_titletext_for_role(context, role): """ Template tag implementation of :meth:`django_cradmin.crinstance.BaseCrAdminInstance.get_titletext_for_role`. """ request = context['request'] cradmin_instance = request.cradmin_instance return cradmin_instance.get_titletext_for_role(role)
8e6a29c369c5ae407701c12dc541e82dda31f193
703,684