content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def get_routing_segmentation_security_policy( self, source_zone: str, destination_zone: str, ) -> dict: """Get all security policies configured on Orchestrator for a particular pair source and destination segments .. list-table:: :header-rows: 1 * - Swagger Section - ...
0506035b6de993bd6ca6ce9948f34eeb2fe6b54e
647,099
def or_(predicate1, predicate2): """DBC helper for disjunction of predicates""" def or_predicates(*args, **kwargs): return predicate1(*args, **kwargs) or predicate2(*args, **kwargs) return or_predicates
a8b3963823ab5780c914c203f5cc45edf19d6d68
647,100
from typing import Dict from typing import Any def reaction_data() -> Dict[str, Any]: """Get reaction_data to instantiate a Reaction.""" return dict(code="like")
7be822407f4cc364a57fac44b075ee0c8af9ea26
647,101
def sel_dou_1(input_data): """ Use hard-coded criteria to pre-select articles from DOU section 1. Input and output are Pandas DataFrames. """ identifica_regex = '(?:portaria|decreto|resolu|medida provisória|lei )' veto_orgao_regex = '(?:universidade|instituto federal|superintendência regional|su...
5f3f5d78ade1153d811ccd56c1f1d323fc1713ae
647,102
def correct_arithmetic(): """Solution to exercise C-1.26. Write a short program that takes as input three integers, a, b, and c, from the console and determines if they can be used in a correct arithmetic formula (in the given order), like “a + b = c,” “a = b − c,” or “a ∗ b = c.” ------------...
2b93955a88ee75cd8a62564247de56c1e3679f2a
647,104
import six def key_not_string(d): """Helper function to recursively determine if any key in a dictionary is not a string. """ for k, v in d.items(): if not isinstance(k, six.string_types) or (isinstance(v, dict) and key_not_string(v)): return True
5121fc184c2d0164dd9288652e8e586a746d5cde
647,105
def _get_truncated_setting_value(value, max_length=None): """ Returns the truncated form of a setting value. Returns: truncated_value (object): the possibly truncated version of the value. was_truncated (bool): returns true if the serialized value was truncated. """ if isinstance(va...
59d16f03e542e41fd4c62e986631c7c6e5211be7
647,106
def get_offset_map(doc, options): """Return mapping from original to cut document text offsets or None if the text is not cut.""" if options.cut == 'tiab': # restrict to title and abstract sections = doc.text.split('\t') if len(sections) <= 2: return None else: ...
2d639b1633486bfd3b0410a1dac9ca0ee9835612
647,107
def psmid_to_charge(psmid): """ Extract charge from Percolator PSMId. Expects the following formatted PSMId: `run` _ `SII` _ `MSGFPlus spectrum index` _ `PSM rank` _ `scan number` _ `MSGFPlus-assigned charge` _ `rank` See https://github.com/percolator/percolator/issues/147 """ psmid = ...
4695daabfd10f055c459239f4cc7e1bbb328aa50
647,108
import string def camel_to_snake(s: str) -> str: """Returns a new str in snake_case, given an str in camelCase. Raises: ValueError: When original str is not in camelCase Examples: >>> camel_to_snake('camelToSnake') 'camel_to_snake' >>> camel_to_snake('already_snake') ...
8b483ea0d4002b231076f0ff921eba6d745ee199
647,109
import subprocess def _get_latest_tag(): """Get the latest tag on a commit in branch or return None.""" try: # If the git command output is my-tag-14-g0aed65e, # then the return value will become my-tag. return ( subprocess.check_output(["git", "describe", "--tags", "--long...
76fad690c162451d972eba2071409c21d22fedd3
647,110
import re def object_id_from_uri(uri): """ from a sciety.org uri extract the DOI portion to be an id value e.g. from https://sciety.org/articles/activity/10.1101/865006 return 10.1101/865006 """ if uri: id_match_pattern = re.compile(r".*?/(10\..*)") matches = id_match_pattern.m...
79a0acb84da99c54206edcc3f33d224b764051f1
647,111
def is_same_pose(pose1, pose2): """ The "=" operator for AirSim poses """ pos_x_same = pose1.position.x_val == pose2.position.x_val pos_y_same = pose1.position.y_val == pose2.position.y_val pos_z_same = pose1.position.z_val == pose2.position.z_val ori_x_same = pose1.orientation.x_val == pose2.or...
77d513e4ece60108d646032ac3d7a35d8c9efc3d
647,112
def get_array_alpha(rgba): """Return alpha values of an RGBA 3D-array.""" return rgba[...,3]
e6a227c004497b3b346cdf627818289fb4c63a50
647,113
import re def get_version(): """ Extract the version from the module's root __init__.py file """ root_init_file = open("raspi_dev/__init__.py").read() match = re.search("__version__[ ]+=[ ]+[\"'](.+)[\"']", root_init_file) return match.group(1) if match is not None else "unknown"
b078cd95dec75f5c0ba8fbfcda95d64b2f0a1549
647,114
def _rotate(n, x, y, rx, ry): """Rotate and flip a quadrant appropriately Based on the implementation here: https://en.wikipedia.org/w/index.php?title=Hilbert_curve&oldid=797332503 """ if ry == 0: if rx == 1: x = n - 1 - x y = n - 1 - y return y, x r...
7e5ca83f3521f28abb6fd0c8a6d7363cea915e32
647,116
def productbuild_generator(target, source, env, for_signature): """The generator""" options = env['PRODUCTBUILD_OPTIONS'].value options_str = ' '.join( '--%s %s' % (key, value) for key, value in options.iteritems() ) if env['PRODUCTBUILD_RESOURCES']: options_str = options_s...
e68ea9c098a46c5dd77134143db94f3a472cb754
647,117
from typing import List import os def get_record_paths(root_dir: str) -> List[str]: """ For a given root directory, find all TFRecords in that structure """ record_path_names = [] for root, _, record_names in os.walk(root_dir): for record_name in record_names: if record_name.endswith("...
b20b3b6ac84cfe821d83261f94d04860b81c96d0
647,118
import sqlite3 def db(db_name): """Opens a new database connection""" rv = sqlite3.connect(db_name) rv.row_factory = sqlite3.Row return rv
6d6297a9a2b793cf8a51a9e01939a855738d925b
647,119
def replace_xml(content_list): """Replaces XML entities in notes with HTML tags.""" return [c.replace("extref", "a") for c in content_list]
c7780201e9cbd32f94c8c3ff71de5684dfd7eb4e
647,120
import os import stat def filesize (path) : """Return size of file `path` in bytes.""" return os.stat (path) [stat.ST_SIZE]
87268ec546935ae9f5c88f5c198a9e573c0f057a
647,121
from typing import Any def get_pitch(note: Any) -> float: """Get pitch for a given nbs note.""" key = note.key + note.pitch / 100 if key < 33: key -= 9 elif key > 57: key -= 57 else: key -= 33 return 2 ** (key / 12) / 2
6984ef56c1eb55c3de3dff95613171c38be7c156
647,122
def sample_sequentials(sequential_keys, exp, idx): """ Samples sequentially from the "from" values specified in each key of the experimental configuration which have sample == "sequential" Unlike `cartesian` sampling, `sequential` sampling iterates *independently* over each keys Args: s...
ce6d4a4e5238f1e10e26beae7898a79aca4c6268
647,123
def pascal_to_camel(string: str) -> str: """ Converts pascal-case to camel-case. >>> pascal_to_camel(string="HelloAndGoodMorning") # Returns "helloAndGoodMorning" """ return string[0].lower() + string[1:]
552d0525250030f00df1ae705dac3db458478661
647,125
import random def random_y(): """Return a random y-coordinate for use in default field values.""" return random.randint(0, 500)
ba023ad9f36e70cb55f23d79f0ba899a044d9730
647,127
def sum_cubes(n): """Sum the first N cubes of natural numbers. >>> sum_cubes(5) 225 """ total, k = 0, 1 while k <= n: total, k = total + pow(k, 3), k + 1 return total
8e0a2b89330358e9189c1d9f9bae7f5d404045a2
647,128
def match_test_cases(test_class, focal_class, test_cases, focal_methods, log): """ Map Test Case -> Focal Method It relies on two heuristics: - Name: Focal Method name is equal to Test Case name, except for "test" - Unique Method Call: Test Case invokes a single method call within the Focal Class """ #Mapped Tes...
29c85c012f036f5a709a273e22925f655c0a7afe
647,129
def getExceptions(compTupl): """Adds information to the main dictionary with the exceptions of what each person didn't consume""" compDic = compTupl[0] #Main Dict boughtItDic = compTupl[1] ans = input("Did everyone consume everything? (y/n): ").lower() if (ans == 'y'): return (compDic,compTu...
4d0bc4ccad4b3445cc5f2d8fba89b9520ac28b8e
647,130
import os def get_log(git_dir, commit_range): """ Return the set of lines corresponding to the git log for the specified commit range. """ os.chdir(git_dir) cmd = "git log --no-color '--pretty=format:%s' '" + commit_range + "'" return os.popen(cmd).readlines()
7155ce6ee19be29bec8753bfe8d3bb54157016af
647,131
def parse(string: str, delimiter: str = ' ', nest_open: str = '(', nest_close: str = ')') -> list: """ This function is for parsing a nested string structure into a nested list >>>parse("hello world") ["hello", "world"] >>>parse("a b (c d (e f)) g") ["a", "b", ["c", "d", ["e", "f"]], "g"] ...
e038a671e6ed30dfae2bb770e5c3d41d304bfee2
647,132
def executable(pytestconfig) -> str: """Returns the path to the lightgbm executable.""" return pytestconfig.getoption('execfile')
820ca9231810d6a8f17637e3f639f46dadb9260e
647,133
import os def get_system_info(): """Return system hz use SC_CLK_TCK.""" ncpus = float(os.sysconf(os.sysconf_names['SC_NPROCESSORS_ONLN'])) ticks = float(os.sysconf(os.sysconf_names['SC_CLK_TCK'])) if ticks == -1: ticks = 100 return (ticks, ncpus)
c31637f60f7f61251f05d9d131ee27409a2d25d9
647,134
def sql_name(raw_name): """ Cleaned column name. Args: raw_name: raw column name Returns: cleaned name suitable for SQL column """ sql_name = raw_name for to_replace in ['"', ' ', '\\', '/', '(', ')', '.']: sql_name = sql_name.replace(to_replace, '_') return...
faa72162ed8e048833972f93a155dc002f44a1a8
647,135
def _split(text): """Split a line of text into two similarly sized pieces. >>> _split("Hello, world!") ('Hello,', 'world!') >>> _split("This is a phrase that can be split.") ('This is a phrase', 'that can be split.') >>> _split("This_is_a_phrase_that_can_not_be_split.") ('This_is_a_phrase...
cc1ce276dad54a9b954bc6453d96adaeb2e85a64
647,136
import subprocess import json def _docker_inspect_network_json(unique_id: str): """Use docker network inspect to get the docker bridge interface. Parameters ---------- unique_id: str index ID of the current run Raises ------ ...
8dfee635a7a4e8a4ca9e0da23e573ba4e9ae283b
647,138
def get_bboxes_intersection(roiA, roiB): """ Computes the intersection area of two bboxes :param roiA: the first bbox :param roiB: the second bbox :return: the area of the intersection """ xInter = min(roiA[3], roiB[3]) - max(roiA[1], roiB[1]) yInter = min(roiA[2], roiB[2]) - max(roiA[0]...
85cde64b0b6d490aea5bf2c5fffda50fca502220
647,139
def linear(t0, t1, y0, y1, t): """ Helper function for linear interpolation between two points .. math:: z = \\frac{y_1-y_0}{t_1-t_0} \\left( t - t_0 \\right) Args: t0 (torch.tensor): first "x" point t1 (torch.tensor): second "x" point y0 (torch.tensor): first "y" ...
d4587bb3847acad076f6b2465c1b91009318e62f
647,140
def set_material(item, material): """Set the material on an item. Args: item (bpy.Object): The Blender object to assign the material to. material (bpy.Material): The material to assign. Returns: bpy.Material: The Blender material. """ # Don't bother if we can't ...
86c892f407faaa31988ac4f3491071f1826977d5
647,141
def ConvertModeToBase8(mode): """Converts a base-10 mode integer from os.stat to base-8.""" # Strip out unnecessary bits in the mode. Mode is given as a base-10 # integer. It must be converted to base-8. return int(oct(mode)[-3:])
12fc810e297f3fef6a1642460af751296e9664c7
647,142
def to_bytes( arg ): """Converts arg to a 'bytes' object.""" return bytes( bytearray( arg )) # if python2, 'bytes' is synonym for 'str'
993c9701a5b5fb737f033d227b5b0cf53c2f5672
647,144
def findSmallestInt(arr): """ find_smallest_int == PEP8 (forced mixedCase by CodeWars) """ return min(arr)
f01bea049ed902c057e7789d4b63904fab552ffa
647,145
def _buildArgOptName(functionName, keywordName): """Builds the argument name to be in the argparser help.""" return '--' + functionName + '-' + keywordName
3ba4b858cca6e2f5133181de83062cb2b81c9f87
647,146
def func3(args, a=None, b=1, c=2): """Some cool doc string.""" return (args, a, b, c)
ec110a28ef1ac2fed7a2e6da44eced0cfb01dbe0
647,147
def get_invalid_ticket_values(tickets, allowed_numbers): """Get values from tickets not matching any number in allowed_numbers.""" invalid = [] for ticket in tickets: ticket_set = set(ticket) - allowed_numbers if ticket_set: invalid.append(*ticket_set) return invalid
dc44c9b3a779d088dbc31d0b7c8352edb1e69fce
647,148
def flatten(l): """Return list `l` flattened.""" flat = [] for x in l: flat += flatten(x) if isinstance(x, list) else [x] return flat
042791c9f64dce1bca6ca8aceea8690fe56621ea
647,149
def __fix_misspelled_words__(text): """ Fixes the misspelled words in the specified text (uses predefined misspelled dictionary) :param text: The text to be fixed :return: the fixed text """ mispelled_dict = {'proflie': 'profile'} for word in mispelled_dict.keys(): text = text.r...
9666a4add08bc980c89e7353d62a92fbb9ccd779
647,151
def indent(s, n=1, indent_str=" "): """Inserts `n * indent_str` at the start of each non-empty line in `s`.""" p = n * indent_str return "".join((p + l) if l.lstrip() else l for l in s.splitlines(True))
d4e6816f1797dd71bbc0c67a9e8b83a9aa1e7b38
647,152
def get_attack_from_name(self, attack_name): """ Get the player's attack with the given name. Arguments --------- attack_name : str The name of the attack to get. Returns ------- Attack The corresponding attack. """ for attack in self.entity.attacks: ...
a09ca69ef3ff01b74cd20ffaac3c91dc4863c84a
647,153
def squared_loss(y_hat, y): """ 计算损失函数 :param y_hat: :param y: :return: """ return (y_hat - y.reshape(y_hat.shape)) ** 2 / 2
e3530034271c6e03fba871b31d9a97def039da56
647,154
from itertools import combinations def ME_PLB(P): """ Calculate the matrix element for g(p1) g(p2) --> g(p3) g(p4) g(p5) Using eq (18) in Berends et al, Phys Let B 103 (1981) p 124 ff. P ... list of 4 momentum vectors """ permutations= [ (0,1,2,3,4), (0,1,2,4,3), ...
ce3d64f7e174189e15a26234981a96badb15b52a
647,155
def clean_data(df2): """ Function to delete columns with 10% data missing :param df2: summarized dataframe :return: cleaned df """ num_rows = int(len(df2.index.values) - 1) # gets number of attributes for column in df2: if df2.loc['Total_Stat_Count'][column] < num_rows: #* .90): g...
bace92f702d0e47da16e18bc094637413a00fe3b
647,156
def a_test_filter(a, b): """Return a string containing both a and b.""" return f"{a}:{b}"
e7a0c140b35f1b98bae45cf742070e8486c7eeb2
647,157
def raw_connection_from(engine_or_conn): """Extract a raw_connection and determine if it should be automatically closed. Only connections opened by this package will be closed automatically. """ if hasattr(engine_or_conn, 'cursor'): return engine_or_conn, False if hasattr(engine_or_conn, 'c...
ed80eb11c43803136a43fe05ad296e6a167642a3
647,158
def is_valid_argument_group_model(arg_group, arguments): """ Validates CLI model at specified argument group level. With this validation, every argument group is mandated to have title, description and arguments that go as a group. Parameters ---------- arg_group(dict): A dictonary object wh...
2c42c7a1431887a758fa2c9e15dead8a0972519e
647,159
from typing import List from typing import Union def _unicode_def_src_to_str(srclist: List[Union[str, int]]) -> str: """ Used to create :data:`UNICODE_CATEGORY_STRINGS`. Args: srclist: list of integers or hex range strings like ``"0061-007A"`` Returns: a string with all characters de...
ca44283bc8cfd03db390874f84f31297d5f8f918
647,160
def lcs_to_delete(lcs,ref,Nb,Ne,dat,Mb,Me,delete): """This routine takes the snake list, the reference file, the data file, and the delete section from the tolerance file. Based on this information it merges any new tolerances into the delete tolerance data structure. The new delete tolerance data stru...
d27df144f985f8347cfa537984070c6478b889de
647,161
from pathlib import Path from typing import List import os def _get_labels_from_imagenet_like_folder(path:Path) -> List: """ Returns names of folders in the folder. """ result = [] for el in os.listdir(path): # if doesn't have extension - folder if len(el.split('.')) == 1: ...
9b7d557c3f828ae5f03d3737706e48018d1a8e14
647,162
def csum2(numlist): """ 3. Write a Python program of recursion list sum. Go to the editor Test Data: [1, 2, [3,4], [5,6]] Expected Result: 21 """ if len(numlist) == 1: return numlist[0] if isinstance(numlist[0], list): return csum2(numlist[0]) + csum2(numlist[1:]) else: ...
dc57f6830b559624b75bbb7e1bfd752b152622ec
647,163
import re def word_wrap(text, line_width=80): """ Word wrap long lines to ``line_width`` """ text = re.sub(r'\n', '\n\n', text) return re.sub(r'(.{1,%s})(\s+|$)' % line_width, r'\1\n', text).strip()
41ace0e91231228c340c0535e7785937ef840562
647,164
def _input_validation(func): """Wrapper that ensures that terminal char is not in pattern. Only works for unary functions whose single argument is pattern. """ def wrapped_input_validation(self, pattern: str): if self.terminal_char in pattern: raise Exception(f'Terminal_char {self.te...
785ef0dd2e3658081a7ca0515ce2da95de2f9c9a
647,165
import socket import re def is_ncar_host(): """Determine if host is an NCAR machine.""" hostname = socket.getfqdn() return any([re.compile(ncar_host).search(hostname) for ncar_host in ['cheyenne', 'casper', 'hobart']])
aaaac4c64f5babaceeaab70db61027f46771e0e7
647,166
def sumatorio_tope(tope): """ Va sumando números naturales hasta llegar al tope. Ejemplos -------- >>> sumatorio_tope(9) 6 # 1 + 2 + 3 >>> sumatorio_tope(10) 10 # 1 + 2 + 3 + 4 >>> sumatorio_tope(12) 10 # 1 + 2 + 3 + 4 >>> sumatorio_tope(16) 1...
c8a0307f5876b2eb641edc10a4dc93ad38270e95
647,167
def test_generator(*args, **kwargs): """ test generator :param args: :param kwargs: :return: """ list1 = (i for i in range(100000000)) print(sum(list1)) return True
2c2ea645f4d9dd2c67a07c0be6495fe98c0e9a87
647,168
def algorithm_3(arr: list) -> int: """ Algorithm 3 - Kadane’s Algorithm The idea is to calculate, for each array position, the maximum sum of a subarray that ends at that position. After this, the answer for the problem is the maximum of those sums. Consider the subproblem of finding the max...
06a8400e7b8d7f3a1fbb5df019702b3fdc08e292
647,169
from pathlib import Path import json def get_secrets_list(env: str) -> dict[str, set]: """Create a list of available app secrets, without their values.""" path = (Path() / "configuration").resolve() default_file = json.loads((path / "default.json").read_text()) env_file = json.loads((path / f"{env}.js...
f31905458529d1dae8ad6da7a4a60acc8aa9f3d8
647,170
from typing import OrderedDict def sortByKey(theDict): """ Return an OrderedDict from a dict sorted by keys """ return OrderedDict(sorted(theDict.items()))
275de502ce365efef966bbe9a4afa947ce315bde
647,171
def get_api_bool_string(api_bool): """Return KEMP restfull API version of a bool string""" return 'y' if api_bool else 'n'
a8811d6f06bd7a915adff3b7b6d5b968cf7fdcd9
647,172
from typing import Callable from typing import Any from typing import Dict import inspect def _dict_inputs_to_list(func: Callable[[Any], Any], inputs: Dict[str, str]): """Convert a dict representation of the node inputs to a list, ensuring the appropriate order for binding them to the node's function. """...
38fef2d51901c32edc2cf5f70375893246ee77f7
647,173
def split_extension(filename): """ Splits the extension off the filename and returns a tuple of the base filename and the extension (without the dot). :param str filename: The base filename string to split. :return: A tuple of the head (characters before the last '.') and the extension (characters after the ...
5c15426a38c13b7e746406a1f06b821110f12c1f
647,174
def string_SizeInBytes(size_in_bytes): """Make ``size in bytes`` human readable. Doesn"t support size greater than 1000PB. Usage:: >>> from __future__ import print_function >>> from weatherlab.lib.filesystem.windowsexplorer import string_SizeInBytes >>> print(string_SizeInBytes(100...
2ca967f9196b2f5a36ea83c4937d1cd8624467b9
647,175
import torch def shuffle_pytorch_tensor(x: torch.Tensor) -> torch.Tensor: """ Do not set torch.manual_seed(1) here, since we want to have a different random result each time. Args: - x: (N,M) tensor we wish to shuffle along dim=0 Returns: - x: (N,M) tensor represnetin...
2e1c490cad9575cc659e4cece1c83aff40a86e51
647,176
from typing import List import os def _get_lines_from_file_list(file_list: List[str], line_nos: List[int]) -> List[str]: """Given a list of string and a list on indexes, return a new list with all indexes from str_list Args: file_list (List[str]): List of str line_nos (List[int]): List of ind...
81768f6891017522d47690fa88921a7743da75ac
647,177
def encode_line_wordwise(line, vocab): """Given a string and vocab, return the word encoded version""" splited = line.split() sequence_input = [vocab.get(word, vocab['UNK']) for word in splited] sequence_input = [vocab['GOO']] + sequence_input + [vocab['EOS']] sequence_length = len(sequence_input) -...
a0742b7fba1963657a63a27045af2f9bf662422f
647,178
def get_urls(doc_names: list) -> list: """ :param doc_names: list of wiki url (the key word) :return: """ urls = [] for doc_name in doc_names: url = "https://en.wikipedia.org/wiki/" + doc_name urls.append(url) return urls
25233953a1f6f73315d68ad9b2e5144be8b4d74f
647,179
import re def parse_helper(attrs, attrs_name, alt_value=None): """Helper function to parse operator attributes in required format.""" tuple_re = re.compile('\([0-9L|,| ]+\)') if not attrs: return alt_value attrs_str = None if attrs.get(attrs_name) is None else str(attrs.get(attrs_name)) if...
8bb92a97dda747e3a41d10042a031b1ce28926e0
647,180
def streak_prev(values, i): """Given a list of numbers, skip backwards over consecutive streaks. See streak_next(); this works in the opposite direction. """ while i>0: i-=1 if i == 0: break next_val=values[i+1] curr_val=values[i] if next_val-curr...
68975209f7c417544f3920196fe9a217f40967ea
647,181
def format_runtime(runtime): """Formats the given running time (in seconds).""" if runtime < 60: # Just seconds. return '{:.2f}s'.format(runtime) # Minutes and seconds. return '{}m {}s'.format(int(runtime // 60), int(runtime % 60))
dc07f540215f5ceeb476056e75e91b760358ad68
647,182
import torch def softor(rasters: torch.Tensor, dim=1, keepdim=False) -> torch.Tensor: """Batched soft-or operation to combine rasters. Args: rasters: torch.Tensor of size [batch, *, nrasters, D*] representing stacks of nrasters images that will be composited into a single image dim...
7a2b37fb99feb4ea14c229b8454d21b4a8a8d880
647,184
import os def is_staging() -> bool: """ Check to see if the app is running with the Staging coniguration :return: boolean """ return os.environ['APP_SETTINGS'] == 'config.StagingConfig'
8804a15924be83c5d65ab8a676f0322f7c7f70fc
647,186
def get_endpoint(): """ This endpoint test if the API is working """ return {"response": "API is working"}
52739c684901236ab568ef0bf66b5f0a19c82335
647,187
def clean(s, isInt=False): """ This function takes the string input from the HTML text area field and converts those entries into a list of floating-point numbers or integers (for bitwise operations) which will be used to intialize the matrices. This function assumes the string only has number valu...
eb0076b2b1e93ba7239c770582fdfe204ff92e45
647,188
import math def deg_to_tilexy(lat_deg, lon_deg, zoom): """Converts geocoordinates to an x,y position on a tile.""" lat_rad = math.radians(lat_deg) n = 2.0 ** zoom x = ((lon_deg + 180.0) / 360.0 * n) y = ((1.0 - math.log(math.tan(lat_rad) + (1 / math.cos(lat_rad))) / math.pi) / 2.0 * n) ...
ff2129755675a8924ee9acc7af7d9aa4f628cd1d
647,189
def is_valid_four_digit_code(code): """Returns true if a code with 4 digits and at least one upper case letter was given :param `code`: String to test :returns: Validation result :rtype: bool """ if len(code) == 4: for char in code: if char.isupper(): ret...
37542819cc649e2ed1b86cfa6be219124728e160
647,190
def compute_relevant_fraction_accuracy(importance, relevant_residues): """ relevant_fraction** = $\sum_{x} / \sum_{\phi} $ where $x$ = relevance of truly relevant atoms and $\phi$ = relevance of all atoms :param importance: :param relevant_residues: :return: """ imp_sum = importance.sum() ...
0d5a96c5227653400722f42ea9438f8c719afdfc
647,191
def is_convertable(value, conv): """Convert a value :param value: :type value: :param conv: :type conv: :return: :rtype: """ try: return conv(value) except ValueError: return None
8a97726673be683a0f9a08256fd3597ec1fe7d1a
647,193
def optimal_pitch_center(step=1): """Given a step size, decide where to place the pitch center. Preference is given to extending the region downwards -- sounds better. """ assert 0 < step < 128 def _a_generator(): yield False yield True while True: yield False ...
7210cad8a65d28ff39178934bf6d6738353c7148
647,194
def Plateularity(lengths): """ A measure of how plate-like the molecule is. Larger the output the more 2D plate-like the molecule is. Plateularity = (Medium*Longest)/ Shortest """ return (lengths[1]*lengths[2])/(lengths[0])
814dcb8f413684f87af6abd4c5a4cd51b9c331d4
647,195
def alphabetize_ordinals(df, list_ordinals): """ Rename ordinal features of a dataframe based on their order in list_ordinals Example: dict_education = {"grad":"A_grad","undergrad":"B_undergrad","high-school":"C_high-school","others":"D_others"} list_ordinals: list of ordinal values that require sortin...
6ea5dcf2d84b4582f6734b8f843230fc8f373697
647,196
def register(name: str, registry: dict): """ Register a class or a function with name in registry. For example: CLS = {} @register("a", CLS) class A(object): def __init__(self, a=1): self.a = a cls_a = CLS['a'](1) In this way you can build...
b1238babbbbc986cee1b1eaae6468ab027081467
647,197
import argparse def parse_cmdargs(): """Parse command line arguments""" parser = argparse.ArgumentParser("Plot flat weights hist") parser.add_argument( 'outdir', help = 'Directory with saved models', metavar = 'OUTDIR', type = str, ) parser.add_argument( ...
76986fbc7703547a53a7812c479ec1c7b3765bac
647,198
import time def DosDateTimeToTimeTuple(dosDateTime): """Convert an MS-DOS format date time to a Python time tuple. """ dos_date = dosDateTime >> 16 dos_time = dosDateTime & 0xffff day = dos_date & 0x1f month = (dos_date >> 5) & 0xf year = 1980 + (dos_date >> 9) second = 2 * (dos_time &...
b39c1399c34e0349adc166136f3d46fca7ff5ef3
647,199
import re def detect_patient_age(info_par): """Returns age of patient described in paragraph of WHO assessment""" # Searches for "year-old" or 'year old' if re.findall('(\d{1,2}) ?(:?-?(year|month)(-| )old)',info_par) != []: age = re.findall('(\d{1,2}) ?(:?-?(year|month)(-| )old)',info_par)[0][0] ...
60f4027884753872c75814026e351eeaf7eedf3c
647,204
import pickle def size_of_object(obj): """ Calculate the memory space used on the disk of an object saved in pickle !!! Does not work with numpy arrays, ... :param obj: object :return: size in bytes of the object """ size = len(pickle.dumps(obj, protocol=pic...
cd8b38b01317f16c93a8baae56bbf5cf0cc03db5
647,205
def process(trackmate): """ Execute the full process BUT for the detection step. """ # Check settings. ok = trackmate.checkInput() # Compute spot features. print("Computing spot features") ok = ok and trackmate.computeSpotFeatures(True) # Track spots. print("Tracking") ok = o...
ab65983244222409ebd29345bd991313c89d6cbd
647,206
def validate(code): """src: https://ru.wikipedia.org/wiki/Алгоритм_Луна""" LOOKUP = (0, 2, 4, 6, 8, 1, 3, 5, 7, 9) code = ''.join([char for char in code if char.isdigit()]) evens = sum(int(i) for i in code[-1::-2]) odds = sum(LOOKUP[int(i)] for i in code[-2::-2]) return ((evens + odds) % 10 == 0...
e66c026a06e3108c74569648c5309fc5d4c82b53
647,207
def row(point): """ Given a point, return the row of the point. >>> row((0, 1)) 0 >>> row((1, 0)) 1 """ return point[0]
1e85f0b919907f6cf27b0448fc5a92c1047cfb97
647,208
def move_path(path, row): """ Moves to the next path in a tree. """ # Base case: If the row is 0, we can't move that one since its the top. # Should mean iteration is over. if row == 0: return False elif path[row] == path[row - 1]: path[row] += 1 # Make sure all sub rows mat...
48b80bef709a29a790e07093ad6b9c87d941d62b
647,209
import requests def num_stargates(sys_id): """ Returns the number of stargates in a specified system. :param sys_id: System ID (int) of the designated system to lookup :return: integer value of the number of gates in a system. Will always be >0 """ base_url = f"https://esi.evetech.net/latest/...
a0d988a3d03720249ce12b47ee7640eb43b527b5
647,210
def transpose(matrix): """ Transpose a matrix (defined as a list of lists, where each sub-list is a row in the matrix) """ # This feels dirty somewhow; but it does do exactly what I want return list(zip(*matrix))
a7ce276a812aa007424cb10fdd4ae84743871133
647,211
import asyncio async def simulation_timer(sim_duration, quit_app): """ stops the simulation after 'sim_duration' seconds have elapsed """ # loop = asyncio.get_running_loop() await asyncio.sleep(sim_duration) quit_app.set() return True
d0f79388023852d70a8cf3f3f8919476e5dffd2a
647,212