content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def guess_tile_size(image): """Try to pick an appropriate tile size based on the image's size.""" # Formula: 5% of the largest dimension of the image return int(max(image.size) * 0.05)
75b530397f6a5079e6d45c98cdece4d612f7f7af
69,857
import unittest def config_is_available(config_section, config_names, config_read, set_wps_host=False): """Check if a config section & parameters are available for tests. Parameters ---------- config_section : string section of a cfg file. config_names : list of st...
edb8da52125f153d8c82cc2f9a38691960ff80d1
69,859
def _tf_combo_string(row): """ Creates a formatted string for the histogram legends. Helper function for imdb_gene_hist_df. Parameters ---------- row : ~pandas.Series Boolean series indexed by TFs for a given gene Returns ------- str A string formatted for display (...
ca2acbe479dac814f5aca3f5c5c6db6ae76ece9e
69,863
def is_valid_data(object): """ Checks if the data object has the following attributes/methods: * nevents * weights * set_weights * space """ is_sampled_data = hasattr(object, "resample") try: has_nevents = hasattr(object, "nevents") except RuntimeError: ...
8b1450e3ac254b5ad1fcf4abfecdab0e1c94e263
69,864
def clamp(val, valmin, valmax): """Simple clamping function, limits to [min, max]""" if val < valmin: return valmin if val > valmax: return valmax return val
56ed278a3ba66d355cccbf3c7726c219e53cdefa
69,868
def do_any_are_in(candidates, bucket): """ :param candidates: [] of * List of objects :param bucket: [] of * List of objects :return: bool True iff any object of the first list is in bucket """ for candidate in candidates: if candidate in bucket: retu...
2ed6a21f6773225c059edf69c4e2d2635cadd988
69,870
import json def attachment_dialog(payload): """ Create a dialog json to get more required data from user. https://api.slack.com/dialogs Args: payload(dict): Slack action payload Returns: (dict): A json object to Slack for opening the dialog. """ description = payload["messa...
6d690f797c5e333bdb5eafe457be81716667d8bb
69,875
from bs4 import BeautifulSoup def extract_soup(html): """Extract the soup object from the passed HTML.""" soup = BeautifulSoup(html.text, "html.parser") return soup
5f9a8a9feb92313123b2b1f2fdfe21aa3556caf5
69,876
import click def usage_flag(help_message, long="--usage", name="usage", show_default=True): """ Usage flag standard definition. Use as decorator for commands where displaying the usage may be desired. """ return click.option( long, name, is_flag=True, default=False, show_default=show_defa...
c2bca50601d7b5f6aa545d33c3a2e913d7eaa767
69,877
def _get_ending(lookup_url: str, api_base: str): """ Returns the short url ending from a short url or an short url ending. """ if lookup_url.startswith(api_base): return lookup_url[len(api_base) + 1:] return lookup_url
82fa472debc09da5fb0c73871e4ef4674e45846e
69,878
import re def extract_command_from_litani_command(command): """Extract the shell command from a litani command.""" command = command.strip() match1 = re.search(' --command +"([^"]*)"', command) match2 = re.search(" --command +'([^']*)'", command) match3 = re.search(' --command +([^ ]*)', command)...
c65bbd9096d5b394965e38b691bf5eb6c8eb8dd7
69,884
def lt(y): """lt(y)(x) = x < y >>> list(filter(lt(3), [1,2,3,4,5])) [1, 2] """ return lambda x : x < y
a98e87097e0518b30c456d380509551f7516f1d6
69,892
def _fmt_cmds(cmds): """ Formats the supported commands nicely. """ keys = sorted(cmds.keys()) fk = "\n" for k in keys: fk += "`" + k + "`, " return fk
f745ce4798265e7c2c48490608ac1f65642f5358
69,897
def unknown_els(dim): """ The elements of the "unknown" basis. Just returns an empty list. Parameters ---------- dim : int The dimension of the basis (doesn't really matter). Returns ------- list """ assert(dim == 0), "Unknown basis must have dimension 0!" return [...
1dc0872419c7c4c7ce9ba6624802cb75c11fa76e
69,899
import math def get_digit_zero_based(index: int) -> int: """ Finds digit that is placed on 0-based index in string of numbers from zero to infinity. :param int index: index :return: digit on index in string from zero to infinity :rtype: int """ digits_amount = 1 bound = 9 number =...
0228501b0ca6747b7a9ba557e98dd1785cafe9d5
69,900
def unnp(dicary): """Return `dicary` with any ndarray values replaced by lists.""" ndicary = {} for k, v in dicary.items(): try: v.shape except AttributeError: ndicary[k] = v else: ndicary[k] = v.tolist() return ndicary
88d43d36de93883d9332d78c02880eeb344d6c70
69,902
import pathlib def prefix_path(jp_root_dir, tmp_path): """If a given path is prefixed with the literal strings `/jp_root_dir` or `/tmp_path`, replace those strings with these fixtures. Returns a pathlib Path object. """ def _inner(rawpath): path = pathlib.PurePosixPath(rawpath) ...
6b6edd11eadb5c9043e33bc4d723bfb43313afb7
69,903
from typing import Iterable import torch def flatten(*args): """ Flattens an array comprised of an arbitrary number of lists. Solution found at: https://stackoverflow.com/questions/2158395/flatten-an-irregular-list-of-lists :param iterable: The iterable you wish to flatten. :type iterable: col...
179491bc124c1a4b800a65692aef7a35b16e48db
69,907
def make_granular_marking(marking_defs, selectors): """ Makes a granular marking reference from STIX. This goes in the granular_markings list of an object example result: "granular_markings": [ { "marking_ref": "SOME UUID THAT IS VALID BUT NOT REALLY", "...
aca1e45ab17c3af6a5b8fb0093cba98693b6a535
69,913
def get_best_k(trials, k=1, status_whitelist=None, optimization_goal='minimize'): """Returns the top k trials sorted by objective_value. Args: trials: The trials (Trail objects) to sort and return the top_k of. k: The top k trials to return. If k=1 we don't retu...
626c9664f013ed37c435a466603372d6f615d4c8
69,921
def calculate_junction_temperature( temperature_case: float, power_operating: float, theta_jc: float, ) -> float: """Calculate the junction temperature (Tj). :param temperature_case: the temperature of the IC case in C. :param power_operating: the operating power if the IC in W. :param thet...
449bf584755f18cefd2a45e7df19c5f71e7162e3
69,925
import glob def getFilesInDir(dirPath,fileExt): """ List all the files with desired extension in a specific directory """ if not dirPath.is_dir(): return {'ErrorCode':'404','ErrorMsg':'Directory {0} Not Found.'.format(dirPath)} filePattern = "{0}/{1}".format(str(dirPath),fileExt) fil...
7f43f6e70bdda6eae214b676424e56258b924a7c
69,927
def assign(target, *sources): """ Description ---------- Assign all values from the sources into the target dictioanary.\n Mutates target dictionary. Parameters ---------- target : dict - target dictionary to assign values to\n *sources : dict - dictionaries to pull keys and vlaues ...
a375e694ee6edf9cd83304695e5014280ef6fa54
69,930
def make_posix_path(windows_path): """Convert a Windows path to a posix path""" return windows_path.replace('\\', '/').replace('C:', '/c')
6cb985e2d387c5e6bb7de9fcd60240f0f9c468d6
69,938
def nonZeroIndex(arr): """ :param arr: a numpy 1-D array. Returns the list of indices of nonzero elements in ``arr``. \n Example: [0,0,0,1] => [4] """ return arr.nonzero()[0]
c99191c63552b4399050e20f5676409f2d23f3ed
69,947
def skiptest(reason): """ Decorate a test that should be skipped with a reason. NOTE: Don't import this as `skip`, because that will cause trial to skip the entire module that imports it. """ def skipdeco(func): func.skip = reason return func return skipdeco
2204e5d61cae7aebeacc440b5d501bb35e378010
69,949
import random def make_data(n,prob): """make_data: prepare data for a random graph Parameters: - n: number of vertices - prob: probability of existence of an edge, for each pair of vertices Returns a tuple with a list of vertices and a list edges. """ V = range(1,n+1) E = [(...
6495d6bb9475421b528a35c4f6cb016dc15ac66e
69,953
def snake2camel(s: str): """Converts a string in snake_case into CamelCase. For example: JULICH_BRAIN -> JulichBrain""" return "".join([w[0].upper() + w[1:].lower() for w in s.split("_")])
200503f60a55e69d15874084b8d25948fcb37794
69,956
def parse_number(x): """Parse a number from a string.""" return round(float(x), 6)
5e24a16aabf58082ff2636d3b3b8b8fa48a3df0b
69,960
def merge_codegen_params(reload_list, arg_list): """Merge the codegen reload params list additional arguments list with no duplicates""" if reload_list: new_reload_list = reload_list else: new_reload_list = [] if arg_list: new_arg_list = arg_list else: new_arg_list ...
3fdb11bbded7f2300a159cc2510e4ee13c02fe1b
69,961
from typing import Iterable from typing import Any from typing import List def parse_keywords(columns: Iterable[Any], candidates: List[str]): """ Matches values in `columns` that are present in `candidates` Parameters ---------- columns: Iterable[str] A list of the columns in the table. candidates: Lis...
6e2c712ee940bd4354d4815bc586d746c0486e3b
69,963
def use_12_hour_heartbeat(connection, server_proposal): """ Configures a Rabbit connection to use a 12-hour heartbeat interval. If a task takes longer than the heartbeat interval, then the rabbit server will kill the connection, since the worker doesn't use a background thread to acknowledge heartb...
dae57568b6677d3116b2d8cd35652af017847d53
69,964
def count_unique(conn, table_name, *columns): """Count each unique combination of column values. For example, for columns = ["a", "b"] and data a b c d ---------- 1 1 1 0 1 1 2 0 1 1 3 0 1 2 4 0 1 2 5 0 2 2 6 0 result = [ # a, b, count [1...
bcb44a474459c9c7e63dd1787260c3a92ca64b19
69,965
def nce_correct_prob(y_pred, y_noise): """ p(correct| x, y) used in NCE. :param y_pred: Model distribution (p_m(y|x; \theta)) :param y_noise: Noisy distribution (p_n(y|x)) :return: Probability that a given example is predicted to be a correct training (p(correct|x, y)) """ return y_pred / (y...
4eebc1d17c8c2cb06b8e70844ff9468eb35f89b6
69,966
def bind_hass(func): """Decorate function to indicate that first argument is hass.""" # pylint: disable=protected-access func.__bind_hass = True return func
4d81507a5774e662b3ade4f3a92e720780ef54e0
69,969
def bash_quote(s): """ POSIX-compatible argument escape function designed for bash. Use this to quote variable arguments that you send to `container.bash("...")`. Note that pipes.quote and subprocess.list2cmdline both produce the INCORRECT value to use in this scenario. Do not use those. Use this. ...
aaaf646fb07aa785f71a334f5eb971ec876447ff
69,973
def get_network_security_ratio(network_json): """ Returns network security as a ratio number """ total_active_bond = int(network_json['bondMetrics']['totalActiveBond']) total_staked = int(network_json['totalPooledRune']) return total_active_bond / (total_active_bond + total_staked)
34c5df6eeacaea32cc11def5ab66bac654c5ba47
69,974
def change_spaces(string): """Returns a string with all spaces in 'string' have been replaced with '_' :param string: String to have spaces replaced :type: str :return: Supplied 'string' with spaces replaced with '_' :rtype: str """ return string.replace(" ", "_")
dbb773fd97c423dc501992bf581bc1a03552df01
69,975
import re def verify_duration(time_str): """ This is to verify the duration which is the journey length between two stations. It is in the format of 'Hour:Minute'. * Hour can be any number of digits and the value must be greater or equal than 0; * Minute can have one or two digits and the value mu...
91d3c9f0b5c239ac09318c91b4332d7709cf3388
69,979
def unquote_path_component(text): """ Removes quotes around a quoted path component, and unescapes any special characters. """ if text[0] != "'" or text[-1] != "'": raise ValueError("value must be a quoted string") return text[1:-1].replace("\\'", "'").replace("\\\\", "\\")
428c0aa4cbcb635c8d05a11f2320fbd90b6193da
69,980
import requests def http_req(host, get, port): """Get JSON using `requests` Parameters ---------- host : str host name (IP address) get : str the resource name port : int port number Returns ------- r : requests.models.Response a Response object ...
dfc80d0bccb3a0a8ef1c654481908d2542dbdb30
69,983
def reverse_words(string: str) -> str: """Sort words in reverse order. Examples: >>> assert reverse_words('hello world!') == 'world! hello' """ return ' '.join(string.split()[::-1])
ec5ad7fa50c70543693d69856db7fe21fa85d632
69,984
import re def parse_for_encoding(value): """ Helper function called by Message's __init__ Try to get an encoding in headers. If it's not found, set encoding to UTF-8 and hope for the best. """ mo = re.search('charset="(.*?)"', value) if mo is None: emailEncoding = "UTF-8" e...
e3c29b26ca09be8120c843779ef576aacf2de306
69,985
def removes_indexes(lst, indexes): """ Remove all indexes from a list. :param lst: The list to remove the indexes from. :param indexes: The indexes to remove from the list. :return: A copy of the list with all items removed at specific indexes. Examples: >>> removes_indexes([4, 8, 15, 16, 23, 4...
d0c79ecf868abf26f131177ac5c69369b7d9af5d
69,987
import collections def section_item(title, url, not_numbered="true"): """Create an ordered dict to add an item to the toc.yml""" _contents = collections.OrderedDict() _contents["title"] = title _contents["url"] = url _contents["not_numbered"] = not_numbered return _contents
54647cb8726126e5bc7f8132d6cafb67dc0b72ff
69,988
import math def h(state): """ Admissible heuristic for single-player Chexers: In the best case, a piece can get to the edge of the board in exit_dist // 2 jump actions (plus 1 move action when the distance is odd), and then can exit with 1 action. Since all pieces must exit, we sum these bes...
03d79fb23f71e331c852c4e753ee830cb92378be
69,989
def average_predictions(predictions): """ Returns the average of all predictions. Parameters ---------- predictions : list Predictions (i.e. NN activation functions). Returns ------- numpy array Averaged prediction. """ # average predictions if needed if le...
79ab3b46e625fad13d4e06d991f18daa8b9ddcb2
69,993
import re def _increase_heading_level(s, increase=0): """ increase heading level by `increase` steps """ if increase <= 0: return s repl = "#"*(increase+1) return re.subn("^#", repl, s, flags=re.MULTILINE)[0]
60cf5ad18b08d9f00bc1df6c4286c81a067de43d
69,997
def get_shells(data): """ :param data: an iterable :return: a list holding tuples. Each tuple holds the shells in outer-to-inner order. If the data holds an odd number of elements, the central element is returned as a singleton. :rtype: list >>> l = [1, 2, 3, 4] >>> get_shells(l) [(1, 4), (2, 3)] >>> l...
012e3d6dfb7ea434200a217cf6fb672e69a0a1a9
69,998
from typing import List def digitalize(number: int) -> List[int]: """Convert number to reversed array of digits. Examples: >>> assert digitalize(4567) == [7, 6, 5, 4] >>> >>> assert digitalize(4321) == [1, 2, 3, 4] """ return list(map(int, str(number)))[::-1]
931b54dfb3ea743ef6d9519ef5768c03f1d0a849
70,000
def get_local(positions, sequence, i): """ Get a local slice of positions and sequence around i :param positions: The positions along the superhelical in floating index "units" :param sequence: The sequence of the superhelical DNA :param i: The position at which to slice :return: A slice of 2 or...
e09c1703accc5ef24a347fd0bd1cbc5dc897d1f3
70,001
import pathlib def resolve_output_path(file_path): """Resolves and creates the output path for a given examples artifacts Args: file_path (str): file path string Returns: [str]: path to the examples output """ output_path = f"{file_path}/output" pathlib.Path(output_path).mk...
9960ef91d2e83a8884be470ddf0d70b22279cc69
70,005
def _check_size(video_results, size): """Check if the video sizes and size attributes match the given size.""" for h in video_results['height']: if h != size[0]: return False for w in video_results['width']: if w != size[1]: return False for video in video_results...
3f2e8c79931e3bec50c27d4e04aee6d40a1fbef5
70,006
def get_column(data, header): #new """ Features: Get the data under a specific header from the dataset. Parameters: data: List. The whole dataset. header: String. The header of the data that want to get. Returns: List of string. The data want...
d8cdf33cb6c15fbcc846da0ba5f72048aa3d7416
70,007
import math def slice_int(x, k, d): """ Slices an integer in the domain [0,2**d] to k-bit parts, and returns the respective parts (in range 0-2**k - 1), MSB to LSB. :param x: A positive integer :param k: An integer representing the size of the slices, in bits :param d: The range of x. If x < 2...
14ca3f70fdd9fbd4c3441402692b8dd6df1e5a11
70,014
def url_avatar(hashed, quality='full'): """Provides the full URL for a steam avatar. Parameters ---------- hashed : str The avatar hash. quality : str, optional The quality to use; may be any of: - icon - medium - full Returns ------- ...
a1f7b68bc92eb7f19d83d24f82aa8231cd318263
70,019
def _pce_ce(pce): """ Generate text for course enrollment, including ID and is_active value. """ enrollment = pce.course_enrollment if not enrollment: return None active_string = "Active" if enrollment.is_active else "Inactive" return "id={enrollment.id:09} ({active_string})".format(...
a4085578adf17565fe758c03b5f41d481b26a7b1
70,021
def transcripts_in_window(df, window, feature='transcript'): """ Return the transcript names for which either the end or the begin of an exon is within the window """ return df.loc[df['begin'].between(window.begin, window.end) | df['end'].between(window.begin, window.end), feature]...
cc552e3645fe48ca9bb2c413a283d7cc2d6f4011
70,022
import random def amount_generator(min=200, max=999999): """ Used to generate a random amount in cents """ return str(random.randrange(min, max))
c9d00781c3d92d3d62a68d4e30fbb7e660122be9
70,023
def mvTBUsage(err=''): """ Prints the Usage() statement for this method """ m = '%s\n' %err m += ' This script will merge a number of Task Branches (TBs) on SalesForce.\n' m += ' Use one of the forms below to meet your needs.\n' m += ' \n' m += ' mvBR -s 4.1 -b <branch_Name> <branch t...
f61346d7def9b78bc9c76d75403323bdd03de925
70,024
import itertools import re def make_command_table(entry_points): """ Return a nicely formatted table of all the PIP commands installed on this system to incorporate into the help text. The table will have two columns. The first will list the commands that comprise the main pipeline and the se...
dae6c2cba1011148e6944bd9a7cff718b1015e36
70,027
def trange(df, high, low, close, tr): """ Welles Wilder described these calculations to determine the trading range for a stock or commodity. True Range is defined as the largest of the following: - The distance from today's high to today's low. - The distance from yesterday's close to today's ...
2023e927f837f563a86fa8897e25aec05671cc4e
70,029
def echo(*_): """Return all parameters unchanged""" return _
b5b8670ce744dac665201d457efb2b1ac956a65c
70,030
def removeDuplicates(duplist): """ 双指针法去除有序列表中的重复项 Parameters ---------- duplist : list 待去重的有序列表 Returns ------- list [description] """ n = len(duplist) if n <= 1: return duplist fast = slow = 1 while fast < n: if duplist[fast] != dup...
f7d9c996108d3330d8ebd3ea88bb52e9b38ad1f4
70,031
import hashlib def make_part_address(namespace_prefix, part_id): """ Creates a part address which will be used to recover the associated UUID if the part already exists in the state storage; or, used as a key to store the new data into the state storage. Args: namespace_prefix (str): ...
871f208de9292b898853e4b3a172065bcc8c6330
70,032
import aiohttp async def request( bot, method, url, session_kwargs={}, method_kwargs={}, response_method='text', response_method_kwargs={}): """Wraps aiohttp methods for making a request.""" async with aiohttp.ClientSession(**session_kwargs) as session: async with getattr(session, meth...
5dc11701f39ef19e370ce543215b440972ad1f09
70,036
def first_inside_quotes(s): """ Returns the first substring of s between two (double) quotes A quote character is one that is inside a string, not one that delimits it. We typically use single quotes (') to delimit a string if want to use a double quote character (") inside...
f7ed6c79ee1d6415a06e96ac63298c5b419eac3f
70,037
import getpass def user_input( field, default='', choices=None, password=False, empty_ok=False, accept=False): """Prompt user for input until a value is retrieved or default is accepted. Return the input. Arguments: *field* - Description of the input being prompted for. *default...
af4b0a9e2892e7585cde460ea50de517b473bd98
70,039
def get_coordinate_tuple(position, lat_first=False): """ Returns the longitude and latitude of this position as a tuple. If lat_first is True, the order will be reversed. """ if lat_first: return (position.latitude, position.longitude) else: return (position.longitude, position.l...
1d45dba0ce4fffe145c9c1c4c743da76a9248ba5
70,042
def compute_gaussian_similarity(distance, variance=1): """Compute Gaussian similarity Args: distance (numpy.ndarray(numpy.float)): Distance of shape [n_samples, ] between two points. Can be also used for whole numpy arrays for vectorization. variance (float): Variance of Gaussian Di...
e8a9adfd1fff583f2aeb6fa828dc6d67a56f7e26
70,043
def std_level_prompt(doc): """ Returns the name from the std level names table corresponding to the object's intended_std_level (with the word RFC appended in some cases), or a prompt requesting that the intended_std_level be set.""" prompt = "*** YOU MUST SELECT AN INTENDED STATUS FOR THIS DRA...
cba0aa6ae96567d9e23fec4a110a934698a5080e
70,049
def build_test_args(parser): """Build test arguments.""" parser.add_argument("--model_file", type=str, required=True) parser.add_argument("--test_file", type=str, required=True) parser.add_argument("--batch_size", type=int, default=32) parser.add_argument("--sent_length_trunc", type=int, default=0) ...
0598686930afe99c8649490371a294d0075ecaf2
70,052
def genericGetContent(path): """ Retrieve the data from a given file path. """ # We are not currently willing to use a with-statement here, for backwards # compatibility. fp = path.open() try: return fp.read() finally: fp.close()
d2404ef7eff427fa22e4ff9e6970bd684d9f4983
70,053
def _requires_copy(experiment_data) -> bool: """Return True if a copy of the experiment data should be made.""" # If data is from DB or contains analysis results it should be copied if ( experiment_data._created_in_db or experiment_data._analysis_results or experiment_data._figures ...
566a98bf4bf7ed76ec49dbf0103d82fd372c5784
70,056
def is_supported_num_dtype(data): """Return True if data type is a numerical type supported by CodraFT""" return data.dtype.name.startswith(("int", "uint", "float", "complex"))
6caf6743432aad9124af418dcf2c58297b5a41d0
70,059
import re def clean_str(text): """clean the string from unusable characters, numbers, etc. Parameters ---------- text : str the input string/text Returns ------- str the cleaned string/text """ text = str(text) # replace word binding # replace Umlaute ...
6137e3b2bd9c86120b139b392c0cb97a6aa9c9a1
70,065
def format_help(help): """ Reformat the given help text ready to be placed in an embed. Replace single newlines with spaces, and replace double newlines with a single newline. This has the effect of removing line wrapping and only having a line break between paragraphs instead of leaving a blank li...
ffec7f0ba34d3fcfb8cd92cee134240bfb3c6ba6
70,069
def cast_to_int(value: str) -> int: """ Casts to int. Casts the empty string to 0. """ if value == '': return 0 return int(value)
3b6381278815fbef35c577d4ab7368dcd95644e2
70,071
def getmaxv(n): """ Returns the maximum value of an unsigned n-bit integer. """ return 2**n - 1
5e00c359114094bf92815096fe237825d76b4e3d
70,076
def gauss_sum(number): """ Computes the gaussian sum for an input number. """ return (number * (number + 1)) / 2
53cb6e7695c266a1f00f8a780d8b320340feb370
70,077
def cost_based_on_consistency(arc, label="+"): """ Assign cost to arcs based on consistency of decision and anaphoricity. An anaphor-antecedent decision is consistent if either (a) the mentions are coreferent, or (b) the antecedent is the dummy mention, and the anaphor does not have ...
d9ecbb62161441e8c0547155d4766df1cc153eee
70,080
import re def _build_ioreg_device_name(device_name: str, location_id: str) -> str: """Converts extracted `_name` and `location_id` attributes from `system_profiler` to a valid ioreg device name. `system_profiler` utility returns location ids in the form of `0xNNNNNNN`, with an optional suffix of ` / N`. ...
e5739d04fa4523114cad57d5274f938a8d6bcecc
70,082
def file_path_from_request(request_obj): """Extract the file path from the incoming request object.""" if request_obj: # return request_obj["file_path"].replace("%20", " ") return request_obj["file_path"].replace("%20", " ").rstrip("/") return None
9718ae2edf0ec43ce69c81b6db39dd005febb63d
70,084
import re def make_choices_tuple(type_class): """Creates a tuple of tuples object used as the choices attribute for a CharField that we want to limit choices. Args: type_class: A class with the attributes defining the types. """ return tuple([ (type_name, type_name) for type_n...
169a7714124be033a2bb188d8a1eac86087e9637
70,089
import locale def get_playlist(youtube, title): """Return users's playlist ID by title (None if not found)""" playlists = youtube.playlists() request = playlists.list(mine=True, part="id,snippet") current_encoding = locale.getpreferredencoding() while request: results = request.execut...
44d53e58b2c10049fcc6f979dd2d6b26c60d458d
70,092
def compute_min_max(bitmap, width, height): """Minimum and maximum pixel value computation.""" # pro prepocet intenzit pixelu min = float("inf") max = float("-inf") # ziskani statistiky o obrazku - minimalni a maximalni hodnoty for j in range(height): for i in range(width): ...
7f2a99c9efa772d4d0d5df0cad8d72609f61ff36
70,093
def _bytes_hex(inp): """Returns the hexadecimal string that encodes the input bytes""" return ''.join('{:02x}'.format(ord(char)) for char in inp)
a0ae3a1d78112dcba39d037409bacd001223724c
70,095
def computeExtendedDependencies(dependencies): """ Computes the extended dependencies for the given dependencies. The extended dependencies are defined as follows: In the following let E denote the set of existential variables (i.e. the keys of <dependencies>) ext_dep(e):=dep(e) union {v in E | dep(v) < de...
47d0e7603c6bf1cc843b0f420287495ddedcfbb9
70,097
def diff_sec(time1, time2): """Calculate the difference between two times in seconds.""" # return (as_utc(time1) - as_utc(time2)).total_seconds() return (time1 - time2).total_seconds()
f964eb8a6cbdccca32668ccc67b8d4d42471dc41
70,098
import hashlib def md5(userString): """ Returns MD5 hashed string """ m = hashlib.md5() m.update(userString) return m.hexdigest()
5c7dffe76b52da09fab84d3856bff8996d70a4af
70,099
def uniquify_sequence(sequence): """Uniqify sequence. Makes sure items in the given sequence are unique, having the original order preserved. :param iterable sequence: :return list: """ seen = set() seen_add = seen.add return [x for x in sequence if x not in seen and not seen_add(x...
240b48b5f155701b38cf3dac4ccfaaa24bb3196c
70,107
def intersect(key_a, mask_a, key_b, mask_b): """Return if key-mask pairs intersect (i.e., would both match some of the same keys). For example, the key-mask pairs ``00XX`` and ``001X`` both match the keys ``0010`` and ``0011`` (i.e., they do intersect):: >>> intersect(0b0000, 0b1100, 0b0010, 0...
693a80420539d12491f41b902fd05d871c22339e
70,108
def make_summary(serialized_data): """ Take in a full serialized object, and return dict containing just the id and the name Parameter: serialized_data, dict, or list of dicts Returns: dict, or list of dicts, containing just "name" and "id" key/values. """ def summarize_one(data): ...
659c977178ac7006cc3d021e90fc128675167e0a
70,110
def find_in_map(map_name, key, value): """The intrinsic function Fn::FindInMap returns the value of a key from a \ mapping declared in the Mappings section. Args: map_name: The logical name of the mapping declared in the Mappings section that contains the key-value pair. key: Th...
491168fb619334f8dac8857b96481d90d9f8675f
70,113
from typing import Optional def asset_name( asset: str, subset: str, namespace: Optional[str] = None ) -> str: """Return a consistent name for an asset.""" name = f"{asset}" if namespace: name = f"{name}_{namespace}" name = f"{name}_{subset}" return name
19a25e62685ba362fc5561082e34b2139cee669a
70,115
import io import zipfile def create_zip(files): """ Write all given files in a dict to a ZIP file and return it as raw data """ byte_file = io.BytesIO() zip_file = zipfile.ZipFile(byte_file, 'w', zipfile.ZIP_DEFLATED) for file_name, file_data in files.iteritems(): zip_file.writestr(fi...
0f097d3200ae20401276027af63a3b80c2ce44d4
70,119
from operator import and_ def get_component_review_by_repository_review_id_component_id( trans, repository_review_id, component_id ): """Get a component_review from the database via repository_review_id and component_id.""" return trans.sa_session.query( trans.model.ComponentReview ) \ ...
0e6ae38aa461fd3f9ddf42e4c7cfd2fcc25c6aa7
70,121
from pathlib import Path def populated_tmp_dir(tmpdir): """Create files to test `ls` function""" tmpdir = Path(tmpdir) for dir_ in ["dir1/subdir1", "dir1/subdir2", "dir2"]: (tmpdir / dir_).mkdir(parents=True) for file in ["at_root.txt", "dir1/subdir1/at_subdir.txt", "dir2/at_dir.txt"]: ...
a387fb165f08438698086b19026e7b96c1f8fdbb
70,122
def subtype(type_, supertype): """Check if type_ is a subtype of supertype.""" return type_.startswith(supertype)
ef39532a334c7bc8ebc1d90066df22ba544f2a18
70,124
def contained_items_once(str, start, end): """ Given a string that represents items as asterisks (*) and compartment walls as pipes (|), a start index, and an end index, return the number of items in a closed compartment. >>> str = '|**|*|*' >>> contained_items_once(str, 0, 5) 2 >>> contai...
8c56a58fd487db747e4e4b8a46081265d1a1486e
70,125