content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def snakecase_to_kebab_case(key: str) -> str: """Convert snake_case to kebab-case.""" return f'--{key.lower().replace("_", "-")}'
5a6f32ac7457b7d88bb717fbc1539ddca82177ce
37,390
def formatCoreTime(core_time_ms): """ Format core time in millis to core hours. """ return "%0.2f" % (core_time_ms / 1000 / 3600.0)
948245393134e1b9069ed6caab67fb5b028c2212
37,391
def getEnergy(tl, t, tr, l, r, dl, d, dr): """helper for getEnergyMap that returns the energy of a single pixel given its neighbors""" vertEnergy = tl + 2 * t + tr - dl - 2 * d - dr horizEnergy = tl + 2 * l + dl - tr - 2 * r - dr return (vertEnergy ** 2 + horizEnergy ** 2) ** 0.5
7f9fc3edb7c8987a2a7fac7a4145e0054fb6b8ee
37,399
def calc_line_x(y, slope, intercept): """Calculate x value given y, slope, intercept""" return int((y - intercept)/slope)
6597394f49ca74f70ca110cd83b258751ba3262d
37,405
def read_bands(bands): """ Read energy bands list, each band per line. """ bands = map(str.split, open(bands).readlines()) bands = ["-".join(b) for b in bands] return bands
b116e218df30c804142f6db74f9f886e424bef54
37,407
import logging def get_logger(name: str) -> logging.Logger: """ Gets the appropriate logger for this backend name. """ return logging.getLogger('proxytest.' + name)
d0e0f9de13d9b603326b70a6acdbff7f3288b421
37,409
def parse_str(s): """ parser for (stripped) string :s: the input string to parse :returns: the string, stripped of leading and trailing whitespace """ return s.strip()
f8f44a30384f634f6f07acd3de19bcb6c42541b6
37,411
def get_dict_fields(dict_obj): """Returns a list of fields in a `dict` object.""" return dict_obj.keys()
b4c8165ca8b883c6503c64d62e31ab99c932884b
37,418
def is_holidays(holidays_dt, day_dt): """ :param holidays_dt: List of holidays with format datetime :param day_dt: Day with format datetime to analyze :return: True if day is a holiday, False if not """ holidays_dt = [i.date() for i in holidays_dt] return day_dt.date() in holiday...
5a8db2929fdde4402bef87f355eb991cd2825e17
37,423
import re def clause_count(doc, infinitive_map): """Return clause count (heuristic). This function is decorated by the :func:`TRUNAJOD:surface_proxies.fix_parse_tree` function, in order to heuristically count clauses. :param doc: Text to be processed. :type doc: Spacy Doc :param infinitv...
98edc098f625cc8f8efb8f892df14f14c03c32a2
37,433
def humanize_key(key): """Returns a human-readable key as a series of hex characters.""" return ':'.join(["%02x" % ord(c) for c in key.get_fingerprint()])
caa98d4fe392627cc153dcc0dd9f29ca42548efe
37,434
def koma_sepp(n): """ Take input integer n and return comma-separated string, separating 1000s. >>> koma_sepp(131032047) '131,032,047' >>> koma_sepp(18781) '18,781' >>> koma_sepp(666) '666' """ return '{:,}'.format(n)
e72ebc81bf116720f17a005af7bff2b40569a822
37,440
def soundspeed(temperature=27, salinity=35, depth=10): """Get the speed of sound in water. Uses Mackenzie (1981) to compute sound speed in water. :param temperature: temperature in deg C :param salinity: salinity in ppt :param depth: depth in m :returns: sound speed in m/s >>> import arlp...
782bb031d879d8f7ffb9e412de716e78710abe4f
37,441
import requests def read_data(url_page, parser): """ Call requests.get for a url and return the extracted data. Parameters: url_page -- url of the Billboard data parser -- Instantiated parser (either ParseWeek() or ParseYear(). """ req = requests.get(url_page) parser.feed(req....
d9d8bedc0a18b64a197e007cf0fdc63d5a1e63cb
37,448
from typing import Tuple import re def parse_source_type_name(field_type_name: str) -> Tuple[str, str]: """ Split full source type name into package and type name. E.g. 'root.package.Message' -> ('root.package', 'Message') 'root.Message.SomeEnum' -> ('root', 'Message.SomeEnum') """ packag...
45a48a2ad53b3b98618d8a82a3bf2cb75cdab250
37,452
def solution(exponent: int = 30) -> int: """ For any given exponent x >= 0, 1 <= n <= 2^x. This function returns how many Nim games are lost given that each Nim game has three heaps of the form (n, 2*n, 3*n). >>> solution(0) 1 >>> solution(2) 3 >>> solution(10) 144 """ # ...
e61be3f0ed92954c6b7a0d25baffa9d6d40107a1
37,453
def split_curves(curves, param): """Split curves into lists sorted by the given parameter Parameters ---------- curves : array_like of Curve all curves param : str key of parameter to sort after Returns ------- split_curves : list of list of Curve """ out = {} ...
3b5e3f4fca8720ef5c50a24732d39f5f41dc4690
37,456
from typing import Tuple import math def get_roll_and_shift( input_offset: Tuple[float, ...], target_offset: Tuple[float, ...] ) -> Tuple[Tuple[int, ...], Tuple[float, ...]]: """Decomposes delta as integer `roll` and positive fractional `shift`.""" delta = [t - i for t, i in zip(target_offset, input_offse...
b2233aa0f8f22072239b46bc8eb0ef730ff53334
37,463
def normalise_toolshed_url(tool_shed): """ Return complete URL for a tool shed Arguments: tool_shed (str): partial or full URL for a toolshed server Returns: str: full URL for toolshed, including leading protocol. """ if tool_shed.startswith('http://') or \ ...
4837f69122dc841549a4fc1923300be4eb04057c
37,464
from typing import OrderedDict def parse_MTL(filename): """ Return an ordered dict from a Landsat "MTL" metadata file Args: filename (str): MTL filename Returns: OrderedDict: dict of MTL file """ data = OrderedDict() with open(filename, 'rt') as fid: for line in fid: ...
b06aa302475a0a4a5ee756db2d7f7aa02a44efd6
37,468
def _tensor_name(tensor): """Get a name of a tensor without trailing ":0" when relevant.""" # tensor.name is unicode in Python 3 and bytes in Python 2 so convert to # bytes here. name = str(tensor.name) return name[:-2] if name.endswith(':0') else name
57b05fd2aaa7f65e49f9eb27538e9d1dfbe1d5c0
37,475
def listdict_to_listlist_and_matrix(sparse): """Transforms the adjacency list representation of a graph of type listdict into the listlist + weight matrix representation :param sparse: graph in listdict representation :returns: couple with listlist representation, and weight matrix :complexity: lin...
fb4b113317f78320add25940adc2d2f04797e118
37,477
def filter_tags(tags, prefixes=None): """Filter list of relation tags matching specified prefixes.""" if prefixes is not None: # filter by specified relation tag prefixes tags = tuple( t for t in tags if any(( t.startswith(p) for p in prefixes )) ) return tags
4378831c0f6ebf290c9a6d0e33e7be1f57acb26d
37,479
def get_dict_value_insensitive(d: dict, k: str): """ Returns a value matching to a case insensitive key of a dict Args: d (dict): The dict k (str): The key Returns: val: The matching value """ return {key.lower(): val for key, val in d.items()}.get(k.lower(), None)
3c730c58fad48faa1bc6421f110b2174ba7d088c
37,480
def is_cwl_record(d): """Check if an input is a CWL record, from any level of nesting. """ if isinstance(d, dict): if d.get("type") == "record": return d else: recs = list(filter(lambda x: x is not None, [is_cwl_record(v) for v in d.values()])) return recs...
dbfa01c8d24d78e6da4fac0a4f912e3b11c56023
37,483
def unit_interval(x, xmin, xmax, scale_factor=1.): """ Rescale tensor values to lie on the unit interval. If values go beyond the stated xmin/xmax, they are rescaled in the same way, but will be outside the unit interval. Parameters ---------- x : Tensor Input tensor, of a...
4083e1904eefeec606e8a22e53485f7007257e71
37,489
def decoder_inputs_and_outputs(target_words, base_vocab): """Convert a sequence of tokens into a decoder input seq and output seq. Args: target_words (list[unicode]) base_vocab (Vocab) Returns: input_words (list[unicode]) output_words (list[unicode]) """ # prepe...
ec66ec0fa7161d65ce6dea6688aa32e44f1b6377
37,492
def join_paths(*args) -> str: """Collect given paths and return summary joined absolute path. Also calculate logic for `./` starting path, consider it as "from me" relative point. """ summary_path = "" for path in args: # Check if path starts from slash, to remove it to avoid errors...
12f79f94954202c643f6fb14ae58eb855d5e96c7
37,500
def group_by(df, group_by_col, value_col): """take a dataframe and group it by a single column and return the sum of another""" return df.groupby([group_by_col])[value_col].sum()
e82943568b8d107c0045af45a4923a442bf07486
37,505
import re def clearColors(message): """ Clears ANSI color codes >>> clearColors("\x1b[38;5;82mHello \x1b[38;5;198mWorld") 'Hello World' """ retVal = message if isinstance(message, str): retVal = re.sub(r"\x1b\[[\d;]+m", "", message) return retVal
4d5edbe7a2899803f14a2d1cdd043d65d3a25718
37,515
def rename_tree(tree, names=None): """Rename the leaves of a tree from ints to names""" # rename leaves to integers for node in list(tree): if node.is_leaf(): tree.rename(node.name, int(node.name)) if names: # rename leaves according to given names for i, name in en...
9ce485c73a2f71653e1bec4e78a44aaff7e9a654
37,520
def logout(identity): """Logout the user. :returns: a dict with the operation result """ if not identity: return {'no-data': ''} return {'success': 'Successfully logged out.'}
31bdee658dde3b636f2840c2c8a1b428c5049623
37,528
def add_desi_proc_joint_fit_terms(parser): """ Add parameters to the argument parser that are only used by desi_proc_joint_fit """ #parser.add_argument("-n", "--nights", type=str, help="YEARMMDD nights") parser.add_argument("-e", "--expids", type=str, help="Exposure IDs") parser.add_argument("-i...
80c23dcfe1e91df2b4d42ca066a697715b10d39d
37,531
def get_shape(card): """Returns the card's shape Args: card (webelement): a visible card Returns: str: card's shape """ return card.find_element_by_xpath(".//div/*[name()='svg']/*[name()='use'][1]").get_attribute("href")[1:]
fc7fc60766625a22ac9bf9942ccd5bf32d80d959
37,534
def get_iterable(input_var): """ Returns an iterable, in case input_var is None it just returns an empty tuple :param input_var: can be a list, tuple or None :return: input_var or () if it is None """ if input_var is None: return () return input_var
ad98d537e711a4357c1527df86b00d977d017a30
37,536
def check_category(driver, domain): """Check domain category on Fortiguard.""" print("Checking Fortiguard proxy") driver.get(f"https://www.fortiguard.com/webfilter?q={domain}&version=8") category = driver.find_element_by_xpath("//h4[@class='info_title']") return category.text.replace("Category: ", "...
4bd2f32b4df01971ba985daeb0134229e896f92a
37,537
import ast def to_dict(value): """ Create a dictionary from any kind of incoming object """ if value is None: return {} if isinstance(value, dict): myreturn = value else: myreturn = ast.literal_eval(value) return myreturn
a215554ca0bb86775b5cf97c793e163c78123fac
37,538
def get_path(path, npa): """ creates path string from list """ return ''.join(path[:npa+1])
46e0c1351facde66ab8de23628c7196544921fb9
37,539
import pytz from datetime import datetime def eventIsNow(event): """Checks if an event object is happening right now. Args: event: Object with 'start' and 'end' datetimes or dates. Returns: Whether the event is now. """ if 'start' not in event or 'end' not in event: return False # Since Goo...
f07735d3254e66c618776391914209cca902e532
37,541
from typing import List from typing import Tuple def bounded_rectangle( rect: List[Tuple[float, float]], bounds: List[Tuple[float, float]] ) -> List[Tuple[float, float]]: """ Resize rectangle given by points into a rectangle that fits within bounds, preserving the aspect ratio :param rect: Input recta...
30da7769b7ea6d8cf69d1c791614d7db1999d335
37,545
import time def getTimeStr(seconds): """Get HH:MM:SS time string for seconds. """ if seconds < 86400: return time.strftime('%H:%M:%S', time.gmtime(seconds)) else: return time.strftime('{}d%H:%M:%S'.format(int(seconds) // 86400), time.gmtime(int(seconds)))
174fab592b2edeae81a8bdd6688810eee8c5a53b
37,548
def celsius_to_fahrenheit(temp): """Simple temperature conversion Cº to Fº""" return temp * 1.8 + 32
d5574ffc5bb4e10e7e51af836c6a60dee76f488f
37,552
def json_to_uri(credentials_json): """ Convert JSON object containing database credentials into a string formatted for SQLAlchemy's create_engine, e.g.: drivername://user:password@host:port/dbname It is assumed that the json has already been validated against json_ops.CREDENTIALS_SCHEMA :pa...
821994b3d4d7bc8cda4bfb4324a4c23023586c70
37,553
def percentage(x, y): """ Convert x/y into a percentage. Useful for calculating success rate Args: x (int) y (int) Returns: str: percentage formatted into a string """ return '%.2f%%' % (100 * x / y)
361b427b413ef989dc2aec8d804a30641d0c49e8
37,555
def global_accuracy(task_accuracies, test_samples_per_task): """ Calculate global accuracy of the model based on accuracies from single tasks accounting number of test samples per task. :param task_accuracies: list of accuracies for each task :param test_samples_per_task: list of test samples for each ...
eab9c9000d16504ace30dc276faa1d24eeb427aa
37,556
def speed2dt(speed): """Calculate the time between consecutive fall steps using the *speed* parameter; *speed* should be an int between 1 and 9 (inclusively). Returns time between consecutive fall steps in msec.""" return (10-speed)*400
676fd396ca83cedc1a6e15addc06abdfd98bced9
37,564
def _flip_top_bottom_boundingbox(img, boxes): """Flip top bottom only bounding box. Args: img: np array image. boxes(np.ndarray): bounding boxes. shape is [num_boxes, 5(x, y, w, h, class_id)] """ height = img.shape[0] if len(boxes) > 0: boxes[:, 1] = height - boxes[:, 1] - b...
ad196f59f85d5a6027e0a17ce6d543303c102357
37,565
def get_subclasses(c): """ Get all subclasses of a given class """ return c.__subclasses__() + sum(map(get_subclasses, c.__subclasses__()), [])
c38c6d9df23039c816d508663c5f40a84b9de299
37,566
def get_wind_power(agent): """ Check if the wind generator is active. If it is, get the power out of it, otherwise return 0""" wind_power = 0 if agent.wind_generator.is_active(): wind_power = agent.wind_generator.erogate() return wind_power
971e70694b53fc7d2189a2eaf102f84ddf04e769
37,569
import mpmath def cdf(x): """ Cumulative distribution function (CDF) of the raised cosine distribution. The CDF of the raised cosine distribution is F(x) = (pi + x + sin(x))/(2*pi) """ with mpmath.extradps(5): x = mpmath.mpf(x) if x <= -mpmath.pi: return mpmat...
a1554e207af751fb3fcf85db80ec2c3c760dd551
37,572
def total_penup_travel(gs): """ Compute total distance traveled in a given ordering """ def distance_between_each_pair(gs): gs = iter(gs) prev = next(gs) for g in gs: yield prev.distance_to(g) prev = g return sum(distance_between_each_pair(gs))
af7d20a5954dc31e873d9a4148c37d31dc69ed61
37,583
import re def getProteinSequences(path_to_data: str) -> dict: """ Read protein sequence data file and extract protein sequences """ with open(path_to_data) as file: data = file.read() # Isolate protein sequences (using key: CRC64 with 12 empty spaces before start) pstart = [m.start() ...
3b9ebe071b16aa3af8cb85560fe71b68c609072a
37,585
def apply_function_on_array(f, input_data): """Apply a function on input data. This method will apply a function on the input data. If the input data is 1-d, it will expand the data to 2-d before feeding into the function, and then squeeze the output data back to 1-d if possible. Parameters -...
b22f955fdd80692719e9ae7422f73a6d09668a38
37,587
def next_biggest(target, in_list): """ Returns the next highest number in the in_list. If target is greater the the last number in in_list, will return the last item in the list. """ next_highest = None for item in in_list: if item > target: next_highest = item ...
4e5b8602e10fc8e9373c23a931e20bf454b6e21f
37,598
def order_by_dependence(parameters): """ Takes a list of parameters from a dynamoDB table and organize them by dependence. The output is a list of lists; for each sub-list there is a root parameter (that do not depend on anything) and the parameters that do depend """ # Selects all table items...
2e3f888e80c354bb414955c133da12eb23ed13b0
37,600
def log_request_entries(log_file='fastemplate.log'): """ Retrieves the amount of log entries. :param str log_file: name of the log file :return: int """ lines = open(file=log_file, mode='r').readlines() return len(lines)
b5f0710b9f4f6314c3e7cd1a73d5734c2b763193
37,606
def find_operation(api, key_op): """ Find an operation in api that matches key_op. This method first attempts to find a match by using the operation name (nickname). Failing that, it attempts to match up HTTP methods. Args: api - A Swagger API description (dictionary) key_op - A Swagger operation descr...
8d565f97acff1023a7ea68dbcec4335754864d2f
37,608
import math def volumen_cilindro(radio: float, altura: float) -> float: """ Volumen de un cilindro Parámetros: radio (float): Radio de la base del cilindro altura (float): Altura del cilindro Retorno: float: El volumen del cilindro readondeado a un decimal """ area_base = math.pi...
f97c187c65ce0e8ac6e3b74d8afa6657bc79bd93
37,610
def signed_number(number, precision=2): """ Return the given number as a string with a sign in front of it, ie. `+` if the number is positive, `-` otherwise. """ prefix = '' if number <= 0 else '+' number_str = '{}{:.{precision}f}'.format(prefix, number, precision=precision) return number_str
26406b5aab7537a37aa073d21d552f04eb3950e9
37,614
def _filter_vocab(vocab, min_fs): """Filter down the vocab based on rules in the vectorizers. :param vocab: `dict[Counter]`: A dict of vocabs. :param min_fs: `dict[int]: A dict of cutoffs. Note: Any key in the min_fs dict should appear in the vocab dict. :returns: `dict[dict]`: A dict of ...
0854c8a6bbf0c9c3805cc4b733589d36209bff58
37,615
def prompt(choices, label='choice'): """ Prompt the user to choose an item from the list. Options should be a list of 2-tuples, where the first item is the value to be returned when the option is selected, and the second is the label that will be displayed to the user. """ if len(choices) ==...
9c9c000f03c4e9752780787bd14aac53609f83c7
37,618
def attack(decrypt_oracle, iv, c, t): """ Uses a chosen-ciphertext attack to decrypt the ciphertext. :param decrypt_oracle: the decryption oracle :param iv: the initialization vector :param c: the ciphertext :param t: the tag corresponding to the ciphertext :return: the plaintext """ ...
80106b2376a8fa2d30afe96e5a763d6153ed3936
37,624
import threading def start_timer(timeout, callback): """Start a timer using the threading library (in seconds).""" tmr = threading.Timer(timeout, callback) tmr.start() return tmr
eef2c4ddf512e6111c18fcdbfa65de31c75b4a20
37,625
def _file_col(col): """ Converts a given column in a maze to the corresponding actual line number in the maze. Args: col (int): The column of the block the maze object. Returns: int: The column number in the file corresponding to the given column in the maze. """ ...
85c3ab8c9f2a0608cae61af22b162ddba3d03b5a
37,632
from typing import List def render_include_source_code( col_offset: int, include_path: str, include_code: str ) -> List[str]: """Annotate included source code with additional information about the source path of the included source. Args: col_offset: a col offset of the whole source code whic...
ae578e8369b68ae26008ca4185640c98dceb2b08
37,638
def _extend_pads(pads, rank): """Extends a padding list to match the necessary rank. Args: pads ([int] or None): The explicitly-provided padding list. rank (int): The rank of the operation. Returns: None: If pads is None [int]: The extended padding list. """ if ...
ce1342f3973b852259ea97d710c733ba2d90cace
37,639
def get_row_index(preDict, usrDict): """ Get the row positions for all words in user dictionary from pre-trained dictionary. return: a list of row positions Example: preDict='a\nb\nc\n', usrDict='a\nc\n', then return [0,2] """ pos = [] index = dict() with open(preDict, "r") as f: ...
1058f5fcad5ab88066312dabf931e1ac5519b193
37,640
import re def strip_namespace(path): """Removes namespace prefixes from elements of the supplied path. Args: path: A YANG path string Returns: A YANG path string with the namespaces removed. """ re_ns = re.compile(r"^.+:") path_components = [re_ns.sub("", comp) for comp in path.split("/")] pat...
5613411de8d796d3b671bbb94f055168eba2f5c7
37,642
def like_prefix(value, start='%'): """ gets a copy of string with `%` or couple of `_` values attached to beginning. it is to be used in like operator. :param str value: value to be processed. :param str start: start place holder to be prefixed. it could be `%` or couple of ...
8ef7e3fa2fc50723f483cc443e4bcbc098c16d32
37,643
def safe_unichr(intval): """Create a unicode character from its integer value. In case `unichr` fails, render the character as an escaped `\\U<8-byte hex value of intval>` string. Parameters ---------- intval : int Integer code of character Returns ------- string Unicod...
15c42a3ca0c528a1b27a6e1cb87bd2d788fafabf
37,652
def create_variant_to_alt_read_names_dict(isovar_results): """ Create dictionary from variant to names of alt reads supporting that variant in an IsovarResult. Parameters ---------- isovar_results : list of IsovarResult Returns ------- Dictionary from varcode.Variant to set(str) of...
aeff30e04dd479e020c1fdcea867f0f6c0a17d97
37,659
def _get_is_negative(offset_string: str) -> bool: """Check if a string has a negative sign.""" is_negative = False if offset_string.count('-') > 0 or offset_string.count('–'): if offset_string.count('-') == 1 or offset_string.count('–') == 1: is_negative = True if offset_string.coun...
589ae036a290f97450a8f32f3ad72acfd8ee267d
37,661
from datetime import datetime def generate_birthdays(birthdays: list, year_to_generate: int): """ generate birthdays from lists :param birthdays: :param year_to_generate: how many year from this year to add to the event :return: """ this_year = datetime.now().year event_list = [] f...
158c68da9f171904f76d2104dd6a6035a6bf7d39
37,669
def popup_element(value, title=None, format=None): """Helper function for quickly adding a popup element to a layer. Args: value (str): Column name to display the value for each feature. title (str, optional): Title for the given value. By default, it's the name of the value. format (st...
a30c88cd4dec6470643548807cfde9e608a6e8dd
37,672
import requests def get_object( token: str, url: str = "https://dev-api.aioneers.tech/v1/", object: str = "dotTypes", ) -> list: """Get JSON object. Parameters ---------- token : str Token which was returned from the user login. url : str = "https://dev-api.aioneers.tech/v1/" ...
c0ad1ba7caf13aafde888fdaad8a1670f6964c78
37,677
def get_endpoint(svc): """ Given a service object, return a formatted URL of the service. """ return f"{svc.get('protocol')}://{svc.get('host')}:{svc.get('port','80')}{svc.get('path','/')}"
ade630e7dd4446c89382022f06998a5d8918f699
37,680
import torch def create_length_mask(data, lengths): """ Create lengths mask for data along one dimension. """ n_sequences, max_length, _ = data.shape lengths_mask = torch.zeros(n_sequences, max_length) for i, length in enumerate(lengths): lengths_mask[i, :length + 1] = 1 return len...
2d0c4e8730f2ddf070fc94f024526fd6a01cda44
37,685
def get_size(img): """Return the size of the image in pixels.""" ih, iw = img.shape[:2] return iw * ih
392cb997016982d9e9bfaae9b7d202e01e66e8b0
37,689
def total_accessibility(in_rsa, path=True): """Parses rsa file for the total surface accessibility data. Parameters ---------- in_rsa : str Path to naccess rsa file. path : bool Indicates if in_rsa is a path or a string. Returns ------- dssp_residues : 5-tuple(float) ...
34c4cba6b8ac5092a1cf5194a6f7d7a3e037477e
37,698
def get_sleepiest_guard(sleep_record): """Finds guard in sleep_record who spent the most total minutes asleep. returns: ('guard', total_minutes_slept) """ sleepiest = '', 0 for guard in sleep_record: sleep_mins = 0 for minute in sleep_record[guard]: sleep_mins += sleep_r...
060f2d73471e4328100bca1759cf0e4dd6446dd1
37,700
def int_to_binary(d, length=8): """ Binarize an integer d to a list of 0 and 1. Length of list is fixed by `length` """ d_bin = '{0:b}'.format(d) d_bin = (length - len(d_bin)) * '0' + d_bin # Fill in with 0 return [int(i) for i in d_bin]
297c6633e984143af564d885c523c6f8d719a4e2
37,701
import jinja2 def render(data, template): """render jija2 template Args: data(obj): dict with data to pass to jinja2 template template(str): jinja2 template to use Returns: string, rendered all, or pukes with error :) """ with open(template, 'r'): templateLoader = jinja2.Fil...
caf24bccd0351f72f5750bcb7c43e676994fecea
37,702
def get_options_from_json(conf_json, ack, csr, acmd, crtf, chnf, ca): """Parse key-value options from config json and return the values sequentially. It takes prioritised values as params. Among these values, non-None values are preserved and their values in config json are ignored.""" opt = {'AccountKe...
1833e230750050b13f36156e83c3bf8a973cff62
37,705
def current_url_name(context): """ Returns the name of the current URL, namespaced, or False. Example usage: {% current_url_name as url_name %} <a href="#"{% if url_name == 'myapp:home' %} class="active"{% endif %}">Home</a> """ url_name = False if context.request.resolver_ma...
1ea2b6ef60a532131dc1c519fc3c5208b29c468b
37,707
import hashlib def HashFile(filename): """Returns SHA-256 hash of a given file.""" if isinstance(filename, list): filename = filename[0] try: return hashlib.sha256( open(filename, "rb").read()).hexdigest() except IOError: return "UNKNOWN FILE HASH"
6529334d79246ad113bed7bfcb3b84cc59679f90
37,708
def identity(test_item): """Identity decorator """ return test_item
799d2325e04066c0dfa405d24d5718b67eb64a00
37,709
def _tensor_max(*args): """Elementwise maximum of a sequence of tensors""" maximum, *rest = args for arg in rest: maximum = maximum.max(arg) return maximum
3046b6ae14368a7275f74ade42a1b179ae38b95e
37,710
def doing_pcomp(row_trigger_value: str) -> bool: """Indicate whether the row_trigger is for position compare.""" return row_trigger_value == "Position Compare"
b6433fc126bb56eefc4c9c73f21e4fb1a82f65d0
37,711
def gen_bwt_array(s: str, suf_tab: list[int]) -> list[str]: """ computes bwt array using suf_tab :param s: text for which bwt array is being computed :param suf_tab: suffix array for the input text :return: a bwt array for text """ s += '$' bwt_array: list[str] = [] for suf in suf_t...
a946519f8068e4aba04177afb2db032efc45e82e
37,712
def gwei_to_ether(wei): """Convert gwei to ether """ return 1.0 * wei / 10**9
95567f47f6e12d4aa3bbfdf7b0d6f1feaa96a9bd
37,717
def postprocess(simdata): """ Make an arbitrary edit to the simulation data, so we can check the postprocessing call works. """ mycol = simdata.cols['B'] simdata.data[4,mycol] = 123456. return simdata
0f3c8303d90b4f52a1d504bc4ba267a6854021e4
37,722
import yaml def load_yaml_file(file_path): """ Loads a yaml file and returns a dictionary with the contents. Args: file_path (str): Path to the yaml file Returns: yaml_dict: Dictionary with the contents of the yaml file """ with open(file_path, "r") as...
c0e2067d248dff3695380aa92c97ab621fae0d96
37,724
import logging def get_handler_filename(logger): """Gets logger filename Parameters: * logger (object): log file object Returns: * str: Log file name if any, None if not """ for handler in logger.handlers: if isinstance( handler, logging.FileHandler ): return handler.baseFilename re...
bdaa47977c14601aa2217fc8a3c734e97b9a0295
37,729
def ros_subscribe_cmd(topic, _id=None, _type=None): """ create a rosbridge subscribe command object messages on subscribed topics will be sent like this: outgoing_msg = {"op": "publish", "topic": topic, "msg": message} see rosbridge_library capabilities/subscribe.py :param topic: the string na...
b001bf487894a1fa238997b21d7264eb802312ed
37,732
def set_mode(mode_input): """ Setter of mode of mapping based on mode input Parameters: (bool) mode_input: The mode input Returns: (bool) mode: The result mode """ mode = None if mode_input is not None and isinstance(mode_input, bool) and mode_input == True: mode ...
79752605ce416c34a4a0efd6a5abde7e97096e8d
37,734
def selected(data, select): """ Takes data and removes any values/columns not in SELECT parameter :param data: List of data entries to be SELECT'ed. ex: [ { 'stb': 'stb1', 'title': 'the matrix', 'rev': '6.00', ...
da7dec6686ee57ec5e89f78e552eb5476f27c66c
37,743
def _masked_array_repr(values, mask): """Returns a string representation for a masked numpy array.""" assert len(values) == len(mask) if len(values.shape) == 1: items = [repr(v) if m else '_' for (v, m) in zip(values, mask)] else: items = [_masked_array_repr(v, m) for (v, m) in zip(values, mask)] retu...
9324e3343ceefeda6c9676b0303988faa5a35474
37,748
def concat(list_a: list, list_b: list) -> list: """ Concatenates two lists together into a new list Example: >>> concat([1, 2, 3], [4, 5, 6]) ... [1, 2, 3, 4, 5 6] :param list_a: First list to concatenate :param list_b: Second list to concatenate :return: Concatenated list "...
c4fd1bf4c579ed48c599699d2f76277d85b47264
37,750
def get_reading_level_from_flesch(flesch_score): """ Thresholds taken from https://en.wikipedia.org/wiki/Flesch%E2%80%93Kincaid_readability_tests :param flesch_score: :return: A reading level and difficulty for a given flesch score """ if flesch_score < 30: return "Very difficult to read...
54903df2bc4114de663fb85af8500fe1cb26ddc5
37,752
import json import requests import hashlib def get_wikidata_image(wikidata_id): """Return the image for the Wikidata item with *wikidata_id*. """ query_string = ("https://www.wikidata.org/wiki/Special:EntityData/%s.json" % wikidata_id) item = json.loads(requests.get(query_string).text)...
c946cd9b2b73cb6140cddf7197f7095ded71bd8f
37,754