content
stringlengths
39
9.28k
sha1
stringlengths
40
40
id
int64
8
710k
def _format_list_items(list_items): """Generate an indented string out of a list of items.""" list_string = '' if list_items: for item in list_items: list_string = list_string + " '" + item + "',\n" list_string = "[\n {}\n]".format(list_string.strip()[:-1]) else: ...
dd677277650e5d3105c01f6636518b8bbd2a1bff
22,216
def organization_analytics_by_voter_doc_template_values(url_root): """ Show documentation about organizationAnalyticsByVoter """ required_query_parameter_list = [ { 'name': 'organization_we_vote_id', 'value': 'string', # boolean, integer, long, string ...
77dc6a9ce0e6cb3416f3eb75aed6302e8002fa23
91,665
def _get_interval_amount(recur_ent, money): """ Get the Salary Amount Based on a Recurring Period of Time param recur_ent (str): 'yearly', 'monthly', 'weely', 'daily', 'hourly' param money (float): Hourly Salary of an employee """ intv_mult = {"yearly": 12*4*5*8, "monthly": 4*5*8, "weekly": 5*8...
deed695b780edd9cb6f17e5465b1f522c649f6fb
368,010
from typing import List def _convert_tags_bio2plain(bio_tag_list: List[str]) -> List[str]: """ retrieve plain tags by removing bio prefixes Args: bio_tag_list: e.g. ['O', 'B-ORG', 'I-ORG'] Returns: tag_list: e.g. ['O', 'ORG', 'ORG'] """ return [elem.split("-")[-1] for...
d6419ed4f61fa4d46c6464b330cdeb17a37f58d1
209,279
def get_folder_overall_status(path, file_statuses, all_statuses): """Returns a 3-tuple of an IndexStatus, WorktreeStatus and MergeStatus, chosen based on the most severe of the corresponding statuses of the files. file_statuses should be a set of status tuples for individual files.""" if file_status...
b46a969c3f7d9f3c3e3145489b087a609767b636
495,978
from typing import List from typing import Dict from typing import Any def convert_list_to_comma_separated_string(values: List[Dict[str, Any]], key: str) -> str: """ Retrieve values of an attribute in comma separated manner from response to populate human readable output :param: values: list of attribute...
833254f3d95849016ee049fe4e76ee47db64e04a
617,021
def find_deltas(arr): """ Creates a new array that is the differences between consecutive elements in a numeric series. The new array is len(arr) - 1 """ return [j-i for i, j in zip(arr[:-1], arr[1:])]
fbd91938be06a62228a74422f4f4f86395b0080a
590,225
def convert_lut_init_to_hex(val: str) -> str: """Converts EDIF decimal and hexadecimal notation to hexadecimal for SpDE. Args: val (str): value in decimal or hexadecimal notation (i.e. ``16'hABCD``) Returns: str: string containing only hexadecimal number, without ``0x`` prefix ...
b4a8e2ecfb186ec7383f2902b7462bff1d6acc43
390,861
def getattr_recursive(variable, attribute): """ Get attributes recursively. """ if '.' in attribute: top, remaining = attribute.split('.', 1) return getattr_recursive(getattr(variable, top), remaining) else: return getattr(variable, attribute)
e91401be53c287f392a123ec3a88a19c0f4b8095
70,238
def has_active_network_in_vlan(vlan): """Check if there are any other active network in the vlan this is used because some equipments remove all the L3 config when applying some commands, so they can only be applyed at the first time or to remove interface vlan configuration :param vlan: vlan objec...
ab38e73ebbd402463d03b6f8d7ca3d918e970879
600,450
import random def generate_problems(number_of_problems=2, maximum_integer=50, problem_type='Addition', number_of_pages=1): """ Generates random example math problems in latex format for practicing Addition, Subtraction, or Multiplication :param number_of_problems: defines how many problems to generate ...
42220b90b46adf823fc0649b569d850f4a653305
140,495
def within_range(val, vrange): """ Check if a value is within a range. **Parameters**\n val: numeric Value to check within range. vrange: tuple/list Range of values. """ if (val >= vrange[0] and val <= vrange[-1]) or (val <= vrange[0] and val >= vrange[-1]): return ...
44b4089b581b07c91c56f289ac46d357b2fc87cc
567,711
def normalize(x): """ Helper function for normalizing the inputs. Normalization is an affine transformation such that the minimal element of x maps to 0, and maximal element of x maps to 1 Args: x (``np.ndarray``): the array to be normalized Returns: ``np.ndarray``: a normali...
62c18aeecaf0672fa1c73e380c96723e8373510f
574,933
def valid_sequence(sequences): """ Function that iterates through all protein sequences and validates that each sequence is made up of valid canonical amino acid letters. If no invalid values are found then None will be returned. If invalid letters are found in the sequence, the sequence index and t...
15974e8428857c988b971f12c9a666990d951d6f
543,701
def calculate_dis_travelled(speed, time): """Calculate the distance travelled(in Km) in a give amount of time(s).""" return (speed * time) / 3600.0
6f71e362109c930ca1e8a9ebd1a4cea9944da23d
266,819
def autolabel(ax, rects, xpos='center'): """ Attach a text label above each bar in *rects*, displaying its heightt. *xpos* indicates which side to place the text w.r.t. the center of the bar. It can be one of the following {'center', 'right', 'left'}. """ xpos = xpos.lower() # normalize the c...
49d8ed659491ac87bbffb12c8be6001bbd7cd541
541,725
def parse_print_dur(print_dur): """ Parse formatted string containing print duration to total seconds. >>> parse_print_dur(" 56m 47s") 3407 """ h_index = print_dur.find("h") hours = int(print_dur[h_index - 2 : h_index]) if h_index != -1 else 0 m_index = print_dur.find("m") min...
7b1a29f31ba38e7d25b4dca9600d4be96a1da3ac
7,797
import re def _remove_whitespace(string): """Return a version of the input string with whitespace removed""" whitespace_re = re.compile(r"\s+") return whitespace_re.sub('', string)
0da9083b1f4d4e4c8cb4a375b2e70cd3b70a4564
26,422
def get_ptr_from_memory_pointer(mem_ptr): """ Access the value associated with one of the attributes 'device_ptr', 'device_pointer', 'ptr'. """ attributes = ('device_ptr', 'device_pointer', 'ptr') for attr in attributes: if hasattr(mem_ptr, attr): return getattr(mem_ptr, attr) ...
1aa2ffdd3522632984230896506d0ce3ae9d0b07
444,761
def unique_records(df): """Checks that each date and FIPs combination is unique.""" return df[['date', 'fips']].drop_duplicates().shape[0] == df.shape[0]
418d1b81b3333df6ac0b1e288a44f95539c07347
524,705
def parse_logs(response): """Parse the Docker logs into stdout and stderr string lists""" # Parse each line into a log, skip the empty lines lines = list(filter(None, response.text.split('\n'))) stdout_logs = [] stderr_logs = [] for line in lines: # Byte format documentation # h...
006c7258477c20ecd96df2490155e8615d6313a3
282,956
def set_axes_vis(p, xlabel, ylabel): """ Set the visibility of axes""" if not xlabel: p.xaxis.visible = False if not ylabel: p.yaxis.visible = False return p
2a2632b1c041b4957bf08280eeffea9bbc2977f0
109,317
def has_index_together_changed(old_model_sig, new_model_sig): """Returns whether index_together has changed between signatures.""" old_meta = old_model_sig['meta'] new_meta = new_model_sig['meta'] old_index_together = old_meta.get('index_together', []) new_index_together = new_meta['index_together']...
b286c460ae06f8cca53326f46766a77c7c1b073c
337,256
def parse_speed(as_str: str) -> float: """Parses a speed in N.NNx format""" return float(as_str.rstrip("x"))
9855df3a53df20cd6a3ed196e5f77ade06fac888
264,387
def add_route_parts_into(failure, into): """ Adds route parts into the given list. Parameters ---------- failure : ``FailureBase`` The parent failure to get route of. into : `list` of `str` A list to put the string parts into. Returns ------- into : `list` o...
e8612711cce19b10ef67c3b8f3231481af24652b
525,444
def tryint(x): """ Used by numbered string comparison (to protect against unexpected letters in version number). :param x: possible int. :return: converted int or original value in case of ValueError. """ try: return int(x) except ValueError: return x
22c8cc0d57254040fb32a2111054dcbd68bcafe9
458,004
def clean_string(text: str): """Replace MS Office Special Characters from a String as well as double whitespace Args: text (str): Returns: str: Cleaned string """ result = ' '.join(text.split()) result = result.replace('\r', '').replace('.', '').replace( '\n', ' ').repl...
64990c668e7aa8507ed9c0bfa79ce8941d54b89e
61,249
def _get_bin_width(stdev, count): """Return the histogram's optimal bin width based on Sturges http://www.jstor.org/pss/2965501 """ w = int(round((3.5 * stdev) / (count ** (1.0 / 3)))) if w: return w else: return 1
77d818db7be992703ddab959d1054a261b39f6dc
369,354
import random def random_choice(gene): """ Randomly select a object, such as strings, from a list. Gene must have defined `choices` list. Args: gene (Gene): A gene with a set `choices` list. Returns: object: Selected choice. """ if not 'choices' in gene.__dict__: rais...
8a01a2039a04262aa4fc076bdd87dbf760f45253
2,817
def selection_sort(A, show_progress=False): """ The selection sort algorithm sorts an array by repeatedly finding the minimum element (considering ascending order) from unsorted part and putting it at the beginning. The algorithm maintains two subarrays in a given array. 1) The subarray which i...
c9ad4903bd2231557bccadd9352db89442634854
133,487
def hex_str_to_bytes_str(hex_str): """Converts the hex string to bytes string. :type hex_str: str :param hex_str: The hex tring representing trace_id or span_id. :rtype: str :returns: string representing byte array """ return bytes(bytearray.fromhex(hex_str))
5dc712fa9f42902feef25b2dbca0e524c192b8de
421,513
import re def word_substitute(expr, substitutions): """ Applies a dict of word substitutions. The dict ``substitutions`` consists of pairs ``(word, rep)`` where each word ``word`` appearing in ``expr`` is replaced by ``rep``. Here a 'word' means anything matching the regexp ``\\bword\\b``. ...
9800d0909769621d08b5831f0b9ebb9a315dbce2
381,882
def dip_percent_value(price: float, percent: float) -> float: """Return the value of the current price if it dips a certain percent Args: price: The price to check a dip percentage against percent: the dip percentage we care about Returns: dip_price: A float containing the price if we hit our ...
2b5a179f2ba7ed8a8dc64c5515855d869f4058b9
345,763
def is_public_function(function_name): """ Determine whether the Vim script function with the given name is a public function which should be included in the generated documentation (for example script-local functions are not included in the generated documentation). """ is_global_function =...
f807a159d66978426604ae9cad382505be55b2b7
607,124
def check_characters(text): """ Method used to check the digit and special character in a text. Parameters: ----------------- text (string): Text to clean Returns: ----------------- characters (dict): Dictionary with digit and special characters ...
c90f04849e0d40095e7eca00aaef98d4991749a3
553,158
import math def torsion_angle(c1, c2, c3, c4): """ float <- torsion_angle(a, b, c, d) returns the torsion angle in degrees between 3D pts a,b,c,d """ v1 = (c1[0]-c2[0], c1[1]-c2[1], c1[2]-c2[2]) v2 = (c2[0]-c3[0], c2[1]-c3[1], c2[2]-c3[2]) v3 = (c3[0]-c4[0], c3[1]-c4[1], c3[2]-c4[2]) ...
32eb380fd8e4d0645481ab816a32e01144fb3c7b
22,101
def count_bits(n): """Count number of ones in binary representation of decimal number.""" bits = 0 if n == 0 else 1 while n > 1: bits += n % 2 n //= 2 return bits
8acdeb6380cde0b0191de9b283af3d40d7388d39
170,517
def _congruent(a: int, b: int, n: int) -> bool: """ Returns true if a is congruent to b modulo n. """ assert type(a) is int return (a % n) == (b % n)
73e9ded677a042792f6458cff7ceffb5932b532c
105,050
async def some_async_function(value): """A demo async function. Does not do any actual I/O.""" return value
9324669acd9955095e12c28acc09cf0b7d68d767
22,613
def order_validation(order): """ Validate the order. If it's under 2 then raise a ValueError """ if order < 2: raise ValueError("An order lower than two is not allowed.") else: return order
ee9f9c64c30a9625246d5e139c94a53d144270db
37,247
import torch def get_pyg_edge_index(graph, both_dir=True): """ Get edge_index for an instance of torch_geometric.data.Data. Args: graph: networkx Graph both_dir: boolean; whether to include reverse edge from graph Return: torch.LongTensor of edge_index with size [2, num_e...
d0300a93a6e4a68302d04dfa8b646b92c7ac256b
660,279
def token_is(token_type): """Return a callable object that returns whether a token is of the given type `token_type`.""" def token_is_type(token): """Return whether a token is of a certain type or not.""" token = token[0] while token is not token_type and token.parent: t...
7f27c887a909180154cd4520286afdad88e18fb1
327,344
def emplace_kv(dictionary: dict, k, v) -> dict: """ Returns input dict with added k:v pair, overwriting if k already exists """ return {**dictionary, k: v}
191343ec1d588efb377e0c0a06ebc5544a2a8f84
122,367
def other_invoiceitem(faker): """Returns a dict for an `InvoiceItem` with `vat` = 0.""" full_item_dict = { "service": faker.sentence(nb_words=2), "qty": 1.0, "unit_price": 1.0, "vat": 0.0, "description": faker.sentence(nb_words=5), } return full_item_dict
5afd003360a455e553bfbc97fa4d72233bc2e4cf
254,720
import json def get_wordpools() -> dict: # Reads the json file and returns a dictionary containing the wordpools. Internal function """ Get the wordpools @return: A dictionary containing the information of the wordpools """ with open('data/wordpools.json') as file: wordpool_dict = json.lo...
b0a5ca50846487f3f68adcbb3e23440b2f2062c1
510,604
def lista_para_texto(lista): """ Transforma uma lista de palavras em texto. Parâmetros: ---------- lista : List - Lista de palavras. Retorno: ---------- texto : String - O texto contento todas as palavras da lista. """ texto = "" for palavra in lista: texto += palavra + " " return...
67feba7d09a98837834ec2cdf71786b6df906bdb
480,323
def _cliffs_delta(x, y): """ Calculates Cliff's delta. """ delta = 0 for x_val in x: result = 0 for y_val in y: if y_val > x_val: result -= 1 elif x_val > y_val: result += 1 delta += result / len(y) if abs(delta) < 1...
9748f6a5608ae4c74a122ba9256c77dc1f5a08ae
516,527
import math def similarity(di, dj): """Cos similarity. usage: >>> a = {0:2, 1:1, 2:1} >>> b = {0:1, 2:1} >>> print round(similarity(a, b), 5) 0.86603 """ inds = set(di.keys()) & set(dj.keys()) s = len(set(di.keys()) & set(dj.keys())) if s == 0: return 0.0 up ...
f1347b55a47150ba177b50e1668557b77f78a8e8
584,094
def _compare_two_tensor_shapes(t1, t2): """Compare tensor shapes.""" if t1.shape.as_list() != t2.shape.as_list(): raise RuntimeError("Compare shape fail: base {} {} vs gc {} {}".format(t1.name, t1.shape.as_list(), t2.name, t2.shape.as_list())) return True
69b27bcbc8524886b1709abb8eb17f030e3016a0
68,599
def _find_startswith(x, s): """Finds the index of a sequence that starts with s or returns -1. """ for i, elem in enumerate(x): if elem.startswith(s): return i return -1
d36bbc4b6005a1ee6f84f3f2dc51504564c6a147
180,685
def filter_active_particles(particles): """Filter active particles from particles dict.""" return {particle_number: particle for particle_number, particle in particles.items() if particle['active']}
68e7d028e4f8cc94fc003af0eff5bfaa90f451a4
654,562
def _calculate_to_transitions(trans_probs): """Calculate which 'to transitions' are allowed for each state This looks through all of the trans_probs, and uses this dictionary to determine allowed transitions. It converts this information into a dictionary, whose keys are destination states and whose va...
c56b17cd05def3117eebd0d93fc644bbf324fc76
417,055
def be32toh(buf): # named after the c library function """Convert big-endian 4byte int to a python numeric value.""" out = (ord(buf[0]) << 24) + (ord(buf[1]) << 16) + \ (ord(buf[2]) << 8) + ord(buf[3]) return out
bf87b8e4b42036fbb5e2526d53bc9469e66d3579
430,269
import math def include_integer(low, high): """Check if the range [low, high) includes integer.""" def _in_range(num, low, high): """check if num in [low, high)""" return low <= num < high if _in_range(math.ceil(low), low, high) or _in_range(math.floor(high), low, high): return Tr...
74bf89e314e3319bfb0b034c41ed78668442523d
511,222
def is_256_bit_imm(n): """Is n a 256-bit number?""" return type(n) == int and n >= 0 and 1 << 256 > n
eebc31bb8d9f53c98f9d930a4c6b2d70d4050dc0
149,400
import re def regex_match(key1, key2): """determines whether key1 matches the pattern of key2 in regular expression.""" res = re.match(key2, key1) if res: return True else: return False
76e3ff2ff8359078f0f17698043f24c0164392b3
158,000
def same_position(oldmethod): """Decorate `oldmethod` to also compare the `_v_pos` attribute.""" def newmethod(self, other): try: other_pos = other._v_pos except AttributeError: return False # not a column definition return self._v_pos == other._v_pos and oldmeth...
15752f5f397d45cab0aa750679e8f6fd6665b713
278,212
def union_crops(crop1, crop2): """Union two (x1, y1, x2, y2) rects.""" x11, y11, x21, y21 = crop1 x12, y12, x22, y22 = crop2 return min(x11, x12), min(y11, y12), max(x21, x22), max(y21, y22)
f32d15fbc8a30c3b431899c08cb7f7549108edf4
492,121
def get_uid(vobject_component): """UID value of an item if defined.""" return vobject_component.uid.value if hasattr(vobject_component, "uid") else None
3a86bbb96df0ac03e3a6c9b5c4f74e4e1e7bfad0
209,275
def is_app_code(code): """ Checks whether a code is part of the app range :param int code: input code :return: if `code` is in the app range or not :rtype: bool """ return 0 < code < 0x10
69b86297d6d7b85cf3e22a725bb10ea32c2bbdea
550,132
import re def is_line_all_header_1_or_2(line): """Returns True if the given line is all '=' or all '-'.""" match_obj = re.search("^[=]+$", line.rstrip()) if match_obj: return True match_obj = re.search("^[\\-]+$", line.rstrip()) if match_obj: return True return False
b0d1788f63b866a91f3b19ab26723aedba0ae008
343,249
def url_of_link(link): """ Extract the url of the link Parameters ---------- link : WebElement The link to inspect Returns ---------- url: str The url of the given link """ return link.get_attribute("href")
dcdd3ea4ecee84e1726e21ba574ea7be64f48459
271,664
def score_ap_from_ranks_1(ranks, nres): """ Compute the average precision of one search. ranks = ordered list of ranks of true positives nres = total number of positives in dataset """ # accumulate trapezoids in PR-plot ap = 0.0 # All have an x-size of: recall_step = 1.0 / nres f...
ad249838201c7ad1eb61f3b0b348a6e9db773563
616,773
def azLimit(az): """Limits azimuth to +/- 180""" azLim = (az + 180) % 360 if azLim < 0: azLim = azLim + 360 return azLim - 180
628a8c70f96039da1981ec79cffb115c1abddaa3
541,575
from datetime import datetime def str2datetime(s): """ Function that transforms a string datetime to a datetime object. Args: s: String datetime. Returns: A datetime object. """ return datetime.strptime(s, '%Y-%m-%d %H:%M:%S.%f')
1f8519d7b06be372bfc17f57ddf4d7237460b32f
189,835
def snake_to_camel(snake_case_string: str) -> str: """ Takes in a `snake_case` string and returns a `camelCase` string. :params str snake_case_string: The snake_case string to be converted into camelCase. :returns: camelCase string :rtype: str """ initial, *temp = snake_case_string.spli...
4ef8fa72580739dbedfbac5bf9f95247f5ea69c3
14,481
import socket def connect(host, port): """Connection Args: host(str): destination hostname port(int): destination port Returns: the created socket """ # IPv4 address family over TCP s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((host, por...
94aa6040a55489eb22e84f82809632e8c4c469ee
575,660
def tsv2table(text): """Parse a "tsv" (tab separated value) string into a list of lists of strings (a "table"). The input text is tabulated using tabulation characters to separate the fields of a row and newlines to separate columns. The output lines are padded with '' values to ensure that all li...
6f62a20882495ebfce71f3baa3121203dcc80f13
219,213
def is_valid_cubic_coord(x, y, z): """ Tests if the cubic coordinates sum to 0, a property of this hex coordinate system. """ return (x + y + z) == 0
eb0f1eb42c2d8f0ccb3e09fddcd5992c4d9eeac7
310,721
def minmaxrescale(x, a=0, b=1): """ Performs a MinMax Rescaling on an array `x` to a generic range :math:`[a,b]`. """ xresc = (b - a) * (x - x.min()) / (x.max() - x.min()) + a return xresc
114b8f3f67338be432af82ab36769618c3140c51
667,072
import select def _is_readable(socket): """Return True if there is data to be read on the socket.""" timeout = 0 (rlist, wlist, elist) = select.select( [socket.fileno()], [], [], timeout) return bool(rlist)
79b258987171e3a5e4d3bab51a9b8c9a59e2415e
24,922
import string import random def ctx_id_factory() -> str: """A factory method to give ctx id as 8 chars random string""" chars = string.ascii_letters + string.digits return ''.join(random.choice(chars) for _ in range(8))
8dd4a2e8ea1575a3b53901892ab0d4f4430ab5e9
387,140
def is_palindrome(word): """ Checks if the given word is a palindrome or not. A palindrome is string that reads the same if reversed like "madam" or "anna". Parameters ---------- word: str The word to be checked if it's a palindrome or not. Returns ------- bool: A ...
3fb0f7f58db56a27de6ce6375c6d7b68a6d525dd
123,788
def observatory_from_string(string): """If "jwst" or "hst" is in `string`, return it, otherwise return None.""" if "jwst" in string: return "jwst" elif "hst" in string: return "hst" else: return None
217cc3cf3c5b802799c0db73563f6d11b7ab4c4d
16,035
def double_with_docstring(arg): """Return 2 * arg.""" return 2 * arg
73a5bab13a8599ab06a51bb1ae8f386990b679fd
528,097
def prefix(txt, pref): """ Place a prefix in front of the text. """ return str(pref) + str(txt)
e9b4efd78f9132f7855cccba84c8a2d4b58ae8bb
699,912
def process_one_file(k, a, filename): """Return a set of species over thresholds.""" with open(filename) as f: f.readline() species = set() for line in f: tkns = [tkn.strip() for tkn in line.split('\t')] abund, _, _, kmers, _, _, _, rank, taxa_name = tkns ...
ec00bf57d67c9fe0b1b54e9644e32415da7855fc
638,493
from functools import reduce def count(l): """Count the number of elements in an iterator. (consumes the iterator)""" return reduce(lambda x,y: x+1, l)
c30519261dbd6e02cd41d4df07607087cb7a6374
32,698
from typing import List def validate_sequences_length(sequences: List[list]): """Returns True if all lists in `sequences` are the same length. Else returns False.""" for param in sequences: if len(param) != len(sequences[0]): return False return True
f6279b894f29713f69b793e198385c4186e29846
520,979
def sum_counts(fname, R1=False): """Collect the sum of all reads for all samples from a summary count file (e.g. from collect_counts)""" count = 0 with open(fname, 'r') as infh: for line in infh: l = line.split() if R1: if l[2] == "R1": cou...
6ce7e156e1100f3106836e0b34caf6750baa18e1
10,544
def _stupidize_dict(mydict): """Convert a dictionary to a list of ``{key: ..., value: ...}``""" return [ {'key': key, 'value': value} for key, value in mydict.iteritems() ]
1601d468f4387397eaa09fbd71b2c6cd0ae66915
195,361
def transitive_deps(lib_map, node): """Returns a list of transitive dependencies from node. Recursively iterate all dependent node in a depth-first fashion and list a result using a topological sorting. """ result = [] seen = set() start = node def recursive_helper(node): if no...
b2c5b6170a734b0e5ea2d0f40daf084739b0b65d
66,789
def null_distance_results(string1, string2, max_distance): """Determines the proper return value of an edit distance function when one or both strings are null. **Args**: * string_1 (str): Base string. * string_2 (str): The string to compare. * max_distance (int): The maximum distance allowed....
39a59478db858283d533ca0db69e2aaed4625945
542,782
def oct_to_decimal(oct_string: str) -> int: """ Convert a octal value to its decimal equivalent >>> oct_to_decimal("12") 10 >>> oct_to_decimal(" 12 ") 10 >>> oct_to_decimal("-45") -37 >>> oct_to_decimal("2-0Fm") Traceback (most recent call last): ... ValueError: Non-oc...
ef933850d533c499b126d024d1cae1f86944248e
34,209
def valid(bo, pos, num): """ Returns if the attempted move is valid :param bo: 2d list of ints :param pos: (row, col) :param num: int :return: bool """ # Check row for i in range(0, len(bo)): if bo[pos[0]][i] == num and pos[1] != i: return False # Check Col ...
3a7efec63644b0835019edcfd7c5fdcfe95dc5f3
502,149
def line_intersects_segment(line, line_segment): """Returns the intersection the Line and LineSegment or None if they do not intersect. This function is useful for splitting polygons by a straight line. """ linesegform = line_segment.to_line() if line.is_parallel_to(linesegform): retur...
90739c66a3fa9abd0d360fdaf1807a3c27713f0a
639,686
import math def find_line_through_point(center, theta, length): """Find the coordinates of the start and end of a line passing through the point center, at an angle theta to the x coordinate, extending a distance length from the center.""" r = length cx, cy = center xo = int(r * math.sin(th...
4595b5d6b2975bae33633586165dfb759dcd0c38
474,080
import copy def min_specializations(h,domains,x): """Implement a function min_specializations(h, domains, x) for a hypothesis h and an example x. The argument domains is a list of lists, in which the i-th sub-list contains the possible values of feature i. The function should return all minimal specializati...
fb0205ca1a25aa31bcc9ebb4eefbacbd2dce8800
688,401
def rescale_layout(Y, scale=1): """Return scaled position array to (-scale, scale) in all axes. The function acts on NumPy arrays which hold position information. Each position is one row of the array. The dimension of the space equals the number of columns. Each coordinate in one column. To resca...
97d297663a2848e469e021aa1e371535eda6636e
652,860
def LinInterp2(a, b, alpha): """Return the point alpha of the way from a to b.""" beta = 1 - alpha return (beta * a[0] + alpha * b[0], beta * a[1] + alpha * b[1])
e4aa1738d1f846f484eb071c5f04326f2b94c2e9
338,076
def get_fabric_ip_networks(cfmclient, fabric_uuid=None): """ Get a list of IP networks from the Composable Fabric. :param cfmclient: :param fabric_uuid: UUID of fabric :return: list of IP address dict objects :rtype: list """ path = 'v1/fabric_ip_networks' if fabric_uuid: pat...
7e9e5cbc5da247e8048c57a2aef18e887090a9c4
640,022
def has_single_count(metadata): """ Return True if the metadata dictionary has a single value for a "count" key. Written to improve readability, since this is used a lot in the annotation functions. """ return metadata.get("count") is not None and not isinstance(metadata["count"], list)
d4f639364e125d4880905e0a204f60e0b25f91ee
434,361
def update_log_level(logger, level): """Update the logging level. Args: logger (:class:`logging.Logger`): Logger to update. level (Union[str, int]): Level given either as a string corresponding to ``Logger`` levels, or their corresponding integers, ranging from 0 (``...
dede5ee698f4831853df7c98bd9927ebc86acfe1
645,285
def cubes_intersect(a, b): """ Find if two cubes intersect w/ each other :param a: cube a, tuple of min, max tuple of coords :param b: cube a, tuple of min, max tuple of coords :return: bool, if cubes intersect """ for i, j, k, l in zip(a[0], a[1], b[0], b[1]): if i >= l or k >= j: ...
8566f69a18285a98bb539bedd539184d29005ce3
252,213
def hash_response(r): """Hashes a request into a unique name.""" return "{}:{}:{}".format(r.method, r.uri, r.body)
a55915f6c201a54e1afa6a2ed214228b1feac279
97,624
def getFormat(path): """ Returns the file format of the translation. One of: gettext, xlf, properties and txt """ if path: if path.endswith(".po"): return "gettext" elif path.endswith(".xlf"): return "xlf" elif path.endswith(".properties"): re...
11bcd8b5bc153e0b94ab699db6a051856f344220
498,751
import re def _event_id_func(desc, event_id, trig_shift_by_type, dropped_desc): """Get integers from string description. This function can be passed as event_id to events_from_annotations function. Parameters ---------- desc : str The description of the event. event_id : dict ...
46c22ac4c05770c4d6fadbc9a858267d248d484a
486,015
def _normalize_version_number(version): """Turn a version representation into a tuple.""" # trim the v from a 'v2.0' or similar try: version = version.lstrip('v') except AttributeError: pass # if it's an integer or a numeric as a string then normalize it # to a string, this ens...
817bb95e2465fe4fdef293a6e5bc6f87a8145e80
618,019
def flip_edges(adj, edges): """ Flip the edges in the graph (A_ij=1 becomes A_ij=0, and A_ij=0 becomes A_ij=1). Parameters ---------- adj : sp.spmatrix, shape [n, n] Sparse adjacency matrix. edges : np.ndarray, shape [?, 2] Edges to flip. Returns ------- adj_flipped ...
0e163616ddb645e636424d673500f07aedabf336
695,466
def calcModDuration(duration, freq, ytm): """ Calculates the Modified Duration """ tmp = 1 + (ytm / freq) return duration / tmp
9ceb9c72c3d1b5b28b8ff86ab271a238d5ae962e
97,724