content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def gamma_estimates_to_stable_partitions(gamma_estimates): """Computes the stable partitions (i.e. those whose gamma estimates are within their domains of optimality), given domains of optimality and gamma estimates from :meth:`ranges_to_gamma_estimates`. See **[CITATION FORTHCOMING]** for more details. ...
0dff12adcfc9013b3c2f5b75f5e903ffd84911a7
594,410
import csv def read_dbpedia_prefix(file_path="data/prefixes.csv"): """ Read prefixes from DBpedia """ result = {} with open(file_path) as csvfile: reader = csv.reader(csvfile, delimiter='\t') for row in reader: result[row[0]] = row[1] # Or we can use pandas to read...
75dcad26b9efc0aa2d292faea80153faa2967145
594,415
def chop_dst(dt): """ Returns a datetime object with the DST offset removed. """ return dt.replace('-04:00', '').replace('-05:00', '') # return dt.replace(tzinfo=None)
d9c4db069cb63520a764422a66d21de3bb31ab30
594,420
def _num_samples(x): """Return number of samples in array-like x.""" if not hasattr(x, '__len__') and not hasattr(x, 'shape'): raise TypeError("Expected sequence or array-like, got %r" % x) return x.shape[0] if hasattr(x, 'shape') else len(x)
d431b75e16db1a54b445c2391183a0abfa5bd42a
594,425
def sum_matrix(n): """ Returns a sum of all elements in a given matrix """ return sum([sum(x) for x in n])
8974bae937673364a12f965b7bbe97f16aed65d8
594,429
def ipset_to_range_list(ip_set_from): """Convert an IP Set into a list of ip ranges. Args: ipSetFrom (IPSet): The IPSet to convert from Returns: list: List of IP Ranges """ to_list = [] for ip_range in ip_set_from.iter_ipranges(): to_list.append(str(ip_range)) retu...
04da37768c40b9585c8a17b9f43e8518225ea131
594,431
import torch from typing import Tuple def unsqueeze_as(x: torch.Tensor, shape: Tuple[int, ...]) -> torch.Tensor: """ Add trailing dimensions onto `x` until it matches the rank of a second tensor whose shape is given. e.g) x = torch.randn(3) y = torch.randn(3, 4, 1) x = unsqueeze_as(x, y.sh...
94268657590358e46fd5c8aded505fe8ab42e305
594,432
import requests def http_test_client(application_settings): """ Returns an HTTP client that can send requests to local server.""" class HTTPClient(): def post(self, path, data=None): return requests.post( 'http://localhost:%s%s' % (application_settings['APP_PORT'], path), ...
336b08252e97b66a0ad46224d24779d648d5440a
594,433
def format_range(var_middle, var_end, minimum, maximum, exclusiveMinimum, exclusiveMaximum): """ Formats an mathematical description of a range, for example, ``0 ≤ x ≤ 2``. Parameters ---------- var_middle : str or None The string to put in the middle of an expression, ...
84d7db0b501bfe25cf4f09bfdeebcfea513738ba
594,436
def remove_small_boxes(proposal, min_size): """ Arguments: proposal (tensor): (N, 5) xc,yc,w,h,theta min_size (int) """ _, _, ws, hs, _ = proposal.unbind(dim=1) keep = ( (ws >= min_size) & (hs >= min_size) ).nonzero().squeeze(1) return keep
298b8337e0df3b5ad5dc5efc42b485333c89a5e1
594,437
def PV(fv:float, c:float, r:float, n:float, m = 1): """ PV(): A function to calculate Present Value. :param fv: Future Value :type fv: float :param c: Coupon rate (in decimals eg: 0.05 for 5%) :type c: float :param r: Rate of Interest/Discount Rate (in decimals eg: 0.05 for 5%) :type r: float :param ...
d4f0ba970accc4a950f23bbcab846ecccf6d13d2
594,439
def reduce_loss(loss, reduction): """Reduce loss as specified. Args: loss (Tensor): Elementwise loss tensor. reduction (str): Options are "none", "mean", "valid_mean" and "sum". Return: Tensor: Reduced loss tensor. """ if reduction == 'mean': return loss.mean() ...
8468ad46c2e9d89dc01e672473a48dfcd5a19f9c
594,442
def threshold_counts(s, threshold=0): """Minimum number of unique values in a pandas column Args: s (pandas series): Column to check threshold: Minimum number of unique values in percentage Returns: boolean: If threshold is reached or not """ counts = s.value_counts(normal...
e20a0d2d492ac236e2648dac05e95a6c5263dda9
594,443
import re def convert_word_to_pos(word): """Retrieves the part of speech, if given, from the word.""" match = re.search("(/.*$)", word) if match: return match.group(1).replace("/", "") return ""
64deb651800ca98fb33c72f1604a2c6a45984c63
594,445
def compute_mse(y, tx, w): """ Compute the Mean Square Error as defined in class. Takes as input the targeted y, the sample matrix X and the feature fector w. """ e = y - tx@w mse = e.T.dot(e) /(2*len(e)) return mse
43906e3fa6c009b990e120344b0ec3fc915efd38
594,449
import dataclasses from typing import Any def _is_optional(field: "dataclasses.Field[Any]") -> bool: """Determine if the given :class:`dataclasses.Field` is optional. :param field: Field to determine if it is optional. :return: True if the `field` is optional, otherwise False. """ ...
76b62fef085890606ee9982668803c22664e39f3
594,451
import re def build_speaker_id(speaker_name): """Builds the id of the speaker from its name. Parameters ---------- speaker_name: str The name of the speaker. Returns ------- speaker_id: str The id of the speaker. """ canonical_name = re.sub(r'\s+', '-', speaker_na...
dc1063b04bcd31e462bbc9488dce16d1e8be496a
594,453
import sqlite3 def get_ratings(prof_id, course_name): """ Returns rating of a particular course+instructor tuple """ conn = sqlite3.connect('./db.sqlite3') cursor = conn.cursor() cursor.execute("""SELECT rating.workload, rating.learning, rating.grading FROM review ...
3c09f7aee88ed9f444cf2e80b9b1eb601cd4c69e
594,454
def _tag_to_snake(name: str) -> str: """Conversts string to snake representation. 1. Converts the string to the lower case. 2. Converts all spaces to underscore. Parameters ---------- name: string The name to convert. Returns ------- str: The name converted to the snake rep...
6839dd226f9c2710ab9a531f7f14d033810d0cbb
594,456
def min_max(num1, num2) -> tuple: """ Gets the min and max of the provided values :param num1: first number :param num2: second number :return: -> (min, max) """ return (min(num1, num2), max(num1, num2))
8a7b4c6fd3c249d17ea479e020c2b1dd148c590c
594,457
def bounded_exponential(x, bounds=[1/10,10], base=2): """ Bounded exponential function Computes an exponential function where when x is 0, the output is bounds[0], and when x is 1, the output is bounds[1]. The relative probability of outputting bounds[0[ over bounds[1] is base. Usefu...
41a3b1ce6d712815f9c794ff1c2f3e4fa11f69c6
594,459
def kewley_sf_sii(log_sii_ha): """Star forming classification line for log([SII]/Ha).""" return 0.72 / (log_sii_ha - 0.32) + 1.3
19518424bee2b93354710f2868ba14eaf2881793
594,460
def assert_type(value, class_or_type_or_tuple): """ Ensure the type of the value is as expected, then return the value. :param value: value of any type :param class_or_type_or_tuple: expected type :return: value of expected type """ s = "%r must be %r, not %s." if not isinstance(value, ...
682df2e925990524b331e8e7a7dd8a5783a8ea8b
594,461
def _validRow(row, where): """ Returns True if row matches where - where is a 2d array of index, value tuples ex: [(0, 'cats'), (1, 230)] """ for index, value in where: if row[index] != value: return False return True
35990a6e31cf3ced450cdf6de942aea5e2d0a136
594,462
from typing import List def parse_config_lines(raw: str) -> List[str]: """Returns the lines in a config section.""" return [x for x in raw.split("\n") if x]
960381e362dc7e0743e4526fb772bae62c5ffe0e
594,464
def dict_to_table(dictionary): """Return a string table from the supplied dictionary. Note that the table should start on a new line and will insert a blank line at the start of itself and at the end. e.g. good: "hello\n" + dict_to_table({"a": "b"}) e.g. bad: "hello" + dict_to_tab...
da46f7fcb9f4f6fcc510a403c309b04d9e9e86ee
594,465
def _find_human_readable_labels(synsets, synset_to_human): """Build a list of human-readable labels. Args: synsets: list of strings; each string is a unique WordNet ID. synset_to_human: dict of synset to human labels, e.g., 'n02119022' --> 'red fox, Vulpes vulpes' Returns: List o...
764ce801651fbbcbfd66fd028427c3f65fd7e16d
594,467
def distance_between_nodes(x, y): """ Return the distance between two pynodes. """ ax, ay, az = x.getTranslation(space="world") bx, b, bz = y.getTranslation(space="world") return ((ax - bx) ** 2 + (ay - b) ** 2 + (az - bz) ** 2) ** 0.5
d0da0a526d8b6b777dda56359bc45a7e068e5ae9
594,470
def read_input(input_path: str) -> str: """take input file path and return a str with the file's content""" with open(input_path, 'r') as input_file: input_data = input_file.read() return input_data
07a6dbd0083e22aabdac596cfa8e62edf0885260
594,471
import re def get_hashtags(text): """ It will return hashtags from the text i.e #something :param text: string :return: list example >>> get_hashtags('my first code #programmer #python #awesome #grepsr') ['programmer','python','awesome','grepsr'] """ result = re.fi...
379dc4c561cce9a253a53a659dbb01d3c4e381ae
594,473
def _field_object_metadata(field_object): """Return dictionary of metadata from ArcPy field object.""" meta = { 'arc_object': field_object, 'name': getattr(field_object, 'name'), 'alias_name': getattr(field_object, 'aliasName'), 'base_name': getattr(field_object, 'baseName'), ...
5a850c473b9f231e3706569f33b4ec36e7086443
594,476
def And(*criteria): """ A criterion used to search for records that verfies all the specified criteria. For example * search for observables flagged as IOC and having TLP <= 2 * search for closed cases related to customFields.customer "Company" and having a WHITE tlp Arguments: criteria (A...
35e1bb71f9a5a10a79b270f0626fc5dbe3ad1fa6
594,477
def spaces2tabs(line, tabwidth=4): """ Replaces sequence of tabwidth-spaces with tabs. """ nspaces = 0 while line[nspaces] == ' ': nspaces = nspaces + 1 ntabs = nspaces // tabwidth return ('\t' * ntabs) + line[ntabs * tabwidth:]
96f3c20179c79f0202b59ddb52def3392aabb6f0
594,478
def _lcp(lst): """Returns the longest common prefix from a list.""" if not lst: return "" cleanlst = list(map(lambda x: x.replace("[", "").replace("]", ""), lst)) s1 = min(cleanlst) s2 = max(cleanlst) for i, c in enumerate(s1): if c != s2[i]: return s1[:i] return ...
885b8ebba24003299054151743e692ec6eca5526
594,480
def make_rule_key(prefix, rule, group_id, cidr_ip): """Creates a unique key for an individual group rule""" if isinstance(rule, dict): proto, from_port, to_port = [rule.get(x, None) for x in ('proto', 'from_port', 'to_port')] else: # isinstance boto.ec2.securitygroup.IPPermissions proto, fr...
8d7d440b802ac4f34e5531c0680d3183795a4f73
594,482
def is_correct(grading_results): """The grading protocol provides grading_results, a dictionary which provides the count of tests passed, failed or locked for a single question. Return True if all tests have passed. """ if grading_results['locked'] > 0: return False return sum(grading_re...
e49e1dfac7b4f6fd57ed2f2ffe42481c8d241ea1
594,483
from typing import List def _process_common_input_params(processing_func, params: dict) -> List[str]: """Converts provided arguments and their values. Conversion is entirely dependent on the passed 'processing_func' that processes individual arguments. The output is a list of parameters with their va...
a976725456c98070e194b5adea7bd2f74f72d1b8
594,485
def find(series, search_for): """ Retrieves the indices of a pandas Series which have a specified value. Args: series: pandas.Series The series to search and retrieve indices from. search_for: Either a single value to search for, or a list of several values to search...
5e49871ed02df52e13a88d89f0147451a2f231bb
594,486
def get_or_create_project(group, project_label): """Return a project if it exists, if not create it. Args: group (flywheel.models.group.Group): The group the project is/should be in project_label (str): The label of the project Returns: project (flywheel.models.project.Project): Th...
f58d9270bcf8757c38f0cc0d5b3b4f61089fc712
594,491
def bench2(x): """A benchmark function for test purposes. f(x) = x ** 2 if x < 0 (x-5) ** 2 - 5 otherwise. It has a global minima with f(x*) = -5 at x* = 5. """ if x[0] < 0: return x[0] ** 2 else: return (x[0] - 5) ** 2 - 5
c43d48526b3f10a426f63ea8efc1fcc359af020a
594,492
def heading_count(phrase,char='~'): """Returns the number of negating prefixes in <phrase> and the <phrase> shorn of prefixes.""" count = 0 for x in phrase: if x != char: break count+=1 return count,phrase[count:]
e97e3ac668885e3d208721776b4a43031074ae1f
594,493
def merge_single_batch(batch): """Merges batched input examples to proper batch format.""" batch_size = len(batch) result = {} for idx, example in enumerate(batch): for feature in example: if feature not in result: # New feature. Initialize the list with None. result[feature] = [None] ...
f2383267016f14acbaa9553ed6fb58fca9b2aa4a
594,499
def black_pins(guess, code): """guess, code: 4-element lists of strings from COLORS Returns the number of black pins, determined by the standard Mastermind rules """ pins = 0 for i in range(min(len(guess), len(code))): if guess[i] == code[i]: pins += 1 return pins
662099d521a3bdef1eba723f7cf07b56a73cee4d
594,500
import collections def sort_dict(dictionary): """ Return a dictionary as an OrderedDict sorted by keys. """ items = sorted(dictionary.items()) return collections.OrderedDict(items)
2e7e7be0e94ead309cb6ae7194f2172e94371e40
594,501
def target_config(targets, **labels): """ Create a Prometheus target configuration. A target configuration describes a collection endpoint. The labels will be applied to data from the target (endpoint) on ingest. Args: targets (list of str): IP address and port of each target. **labels: Key/value pa...
d370839c4e6529ae1caecbd41050b04c40f8bb0d
594,505
def ms_to_htk(ms_time): """ Convert time in ms to HTK (100 ns) units """ if type(ms_time)==type("string"): ms_time = float(ms_time) return int(ms_time * 10000.0)
fe3854dedddbed8ddb31cd4f5a8b8f77c9afb1e2
594,507
def heuristic_function_1(game_state, move): """Give a heuristic evaluation in form of a number of how good it would be to make "move" to "game_state". The value is higher the better the move, regardless of the player to make it. This function give higher values to more central columns. """ retu...
d4adf1448a5c69264f8f0fb6cb3fb365df685176
594,513
def separate_dashed_words(token): """Separates dashed words and returns the list of all words. :param token: string :return: list """ return token.split('-')
5387e7ea8cc6fe340ed72bd33f7c0b5146e7a08f
594,516
from bs4 import BeautifulSoup def blast_parser(blasted_file): """Creates a soup item for the blasted_file and finds also the "iterations" in here. :param blasted_file: Blasted file in xml format return: unparsed Bs4 object of "Iteration" """ # creates Bs4 item from xml file soup = Beautiful...
c4b6bcbb374911aad68d71d597329e56acd1ada1
594,517
def bpstr(ts, accum): """Make a string representation of this breakpoint and accumulation""" # Need four decimals for accurate reproduction return f"{ts.hour:02.0f}.{(ts.minute / 60. * 10000.):04.0f} {accum:.2f}"
fbf7ae85de049198704d304322834af005411499
594,520
def get_state(cell_id): """ Gets the state from a state identification number. :param cell_id: Natural number identifying the state :return: Two dimensional array containing the state """ state = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]] binary = '{0:09b}'.format(cell_id) ...
0256f89ae7dc1455d2bfad89c4ec2192762b4719
594,521
def split_url_for_query(url): """ Given a URL pattern, split it into two components: url_optimised: URL and domain name in the el_index format (https://www.mediawiki.org/wiki/Manual:Externallinks_table#el_index) url_pattern_end: Anything following the domain name """ url = url.strip() # Cat...
9aa71a7b0c756241dc1399b229ea16621c15f623
594,527
def cmake_cache_option(name, boolean_value, comment=""): """Generate a string for a cmake configuration option""" value = "ON" if boolean_value else "OFF" return 'set(%s %s CACHE BOOL "%s")\n\n' % (name, value, comment)
b00e202d499b3faa9bc1623994f733456c542b40
594,528
def hash_fn(x): """Hash function for examples.""" x_str = str(x) return hash(x_str)
a2ba1364c57b10ceb90f771ab43e25bdfea05928
594,530
def or_field_filters(field_name, field_values): """OR filter returns documents that contain a field matching any of the values. Returns a list containing a single Elasticsearch "terms" filter. "terms" filter matches the given field with any of the values. "bool" execution generates a term filter (whic...
bc721e20f57a5f7110985e4f117b2f0559a8642e
594,531
def normalize_text(w): """Normalize the text in a node.""" return str(w, "utf-8").lower().replace("-", "")
9bec2f88e906c8b60b4e912363f889a05f1d7b8d
594,534
def check_if_pack_on_hand(hand): """ Function used to check if player have a pack of cards on hand. :param hand: list of cards on player hand :return: list of cards values which can be played as pack """ tmp = {} for card in hand: if card[1] in tmp.keys(): tmp[card[1]] +=...
4302b36395cb229119af0e279f4d9180b25e9d3d
594,535
def last_home_loss_road_win(games): """ Given a list of games, returns the most recent home loss and road win. """ try: last_home_loss = games.filter(t1_game_type='H', t1_result='L')[0] except: last_home_loss = None try: last_road_win = games.filter(t1_game_type='A', ...
6a18309793aebba0baee79e02e7833d5adf6fc27
594,536
import json def load_json(filename): """Reads json file into dictionary""" with open(filename, 'r') as f: data = json.load(f) return data
d0287c340aa878295d70efe760534c22ae21bf5f
594,538
def fitness_basic(individual, environment): """ Determines how good each solution is, this is what that is minimized In this case, minimize the displacement in the x direction. Parameters ---------- individual : Naturalize Indivdual The input indivdual. environment : Naturalize Env...
0e48032bed353cd5d063a6b22fe7bf29fed804dd
594,543
import typing def _simple_valid_json_dict() -> dict[str, typing.Any]: """create a minimal valid json document as a dict.""" return { "characters": [{ "name": "rogue", "initiative": 9, "initiative2": 10, "x": 10, "y": 10, }], "...
4331f2a04c90c1cc0345e2666b5e6d18d685187b
594,544
def format_venue(venue): """Format a venue for tweeting""" if venue.twitter_handle: if venue.twitter_short_location_description: return f'@{venue.twitter_handle} {venue.twitter_short_location_description}' return f'@{venue.twitter_handle}' return venue.name
ba62a027298208ed8618361689fb3c706b706aeb
594,547
def duration_parse(durstr): """Parse a duration of the form [[hh:]mm:]ss[.sss] and return a float with the duration or None for failure to parse. Enter: durstr: string with the duration. Exit: duration: duration in seconds.""" try: durstr = durstr.strip().split(":") dur = 0 ...
d7e9b97513023e22a0a3bd2d1b08fbef6f3a4825
594,549
def resize_coordinate(cor_list, FACTOR): """Given a list of coordinate and resizing factor, adjust the scale.""" return [cor_list[i]//FACTOR for i in range(len(cor_list))]
bd7c7318bf27cc09a8e441d2360954bd8306d1fd
594,552
import hashlib def get_id(SRC): """Return a unique ID for the SRC file. For simplicity and robustness we just content hash it""" with open(SRC,"rb") as F: return hashlib.sha1(F.read()).hexdigest();
b7dd7adaec4cbba441de3fa81d7cc5f5440852bf
594,553
def _get_admin_route_name(model_or_instance): """ Get the base name of the admin route for a model or model instance. For use with :func:`django.urls.reverse`, although it still needs the specific route suffix appended, for example ``_changelist``. """ model = model_or_instance if isinstance(mo...
30299dead972ebe815ae58f342b35f9270059186
594,554
def first_item(list_or_dict): """ If passed a list, this returns the first item of the list. If passed a dict, this returns the value of the first key of the dict. :param < list | dict > list_or_dict: A list or a dict. :rtype obj: The first item of the list, or the first value of the dict """ ...
4567861cd44bca76c9336eceef09c593cfdfe3b7
594,559
def safe_setattr(obj, name, value): """Attempt to setattr but catch AttributeErrors.""" try: setattr(obj, name, value) return True except AttributeError: return False
fda9fc74cd0a85d6ce83c1e316b79a3f23449512
594,561
def text2bin(text): """ Takes in a string text, returns the encoded text in bin.""" bin_string = " ".join(format(ord(x), 'b') for x in text) return bin_string
8e11f86f1fa50d3a93191e1f736524adff73b164
594,562
def create_padding_mask(x): """ Creates a mask to denote padding locations. The mask contains value 1.0 if the value in the given sequence is zero. Other values are set to 0. :param x: A sequence of shape (batch_size, seq_len) :return: A padding mask of shape (batch_size, 1, 1, seq_len) """...
f453932595e43ac1830b287c59e6107ebd59c6a4
594,564
def get_boxes(rows, cols): """ Gets a list of box labels for a row and column pair Input: rows and column strings Output: a list of box identifiers in string format """ return [s + t for s in rows for t in cols]
132a4c6763a03206f1cfa96276874a5db9c36aba
594,566
def parse_gerber_value(value, format=(2, 5), zero_suppression='trailing'): """ Convert gerber/excellon formatted string to floating-point number .. note:: Format and zero suppression are configurable. Note that the Excellon and Gerber formats use opposite terminology with respect to leading ...
b52375ba6e9ccef2fa11a74d309cd932385224cd
594,567
import string def rotN(text, n, alphabet=string.ascii_lowercase): """Rotate text by N positions, based on given alphabet. If a character is not in the alphabet it is kept as is. """ rotated = '' for c in text: try: rotated += alphabet[(alphabet.index(c) + n) % len(alphabet...
f9541505988282848782b47ee8b251b48205b07c
594,569
def GetContentForTemplate(api_query): """Prepares and returns the template value for an API Query response. Args: api_query: The API Query for which to prepare the response content template value. Returns: A dict containing the template value to use for the Response content. """ conten...
738a7a2e85d58c4a566ba6cd86a83b6f3470d5c8
594,570
import re def remove_non_words(line): """ Takes a string and removes characters that serve no purpose for our task. This includes puncuation, digits and special characters. """ non_word = [ '`', '!', '"', '£', '$', '%', '^', '&', '*', '(', ')', '?', '1', '2', '3', '4', '5', '6', '7...
fb1b710427e67b34664ef774d81c7963aef36673
594,571
import unicodedata def asciify(string): """Convert unicode string to ascii, normalizing with NFKD Strips away all non-ascii symbols""" string = unicodedata.normalize('NFKD', string) return string.encode('ascii', 'ignore').decode('ascii')
e6f61d09e865b3f240a17b66158de68c2dbfc378
594,572
def hasCycle(head): """ Use two pointers(one slow, one fast) to traverse the list. Two pointers are bound to meet if there is a cycle; otherwise, fast pointer will reach the end eventually. """ slow = head fast = head while fast and fast.next: # note the condition slow = slow.ne...
ab518c35d44bf86d75e6a1cc1f631b8acadc9795
594,578
def type_to_node(type_name): """ Convert an Avro type name (with dots) to a GraphViz node identifier. """ # First double underscores type_name = type_name.replace("_", "__") # Then turn dots into underscores type_name = type_name.replace(".", "_") return type_name
129f03f5f9a8e3eaa50dfc9cb12b2b818908f3d4
594,579
def _alpha(rgb, a): """ Add alpha channel to a hex color. :param str rgb: hex color. :param float a: alpha channel (float between 0 and 1) """ a = int(a * 255) return "{}{:02x}".format(rgb, a)
c4090d9fb793e3273da3557d470b262fc17f80df
594,580
from typing import Any def safe_text(text: Any) -> str: """Process text of any type to ensure it can be saved in the DB.""" # Ensure bytes get decoded, no matter what, to unicode. if isinstance(text, bytes): text = text.decode('UTF-8', errors='replace') elif not isinstance(text, str): ...
8df2ce87c87136776b709baee152130157536490
594,588
def get_nodata_value(scene_name): """ Get nodata value based on dataset scene name. """ if 'urbanscape' in scene_name.lower() or 'naturescape' in scene_name.lower(): nodata_value = -1 else: raise NotImplementedError return nodata_value
8cc666082d674128546ac6cc08fcb2062ff86342
594,589
def size_all_files(repo): """Total filesize of all files in the repo.""" return sum(size for size in repo._calc('all_file_sizes').itervalues())
ccf099ffd00a47810011031950abca2abd00063d
594,592
from pathlib import Path def get_fasta_headers(fasta: Path) -> list: """ Pulls headers from any fasta file (e.g. lines starting with >) and returns them as a list """ fasta_headers = [] with open(str(fasta)) as f: for line in f.readlines(): if line.startswith(">"): line...
aa0da695e4a55b72ac6dec3cf98112eb20cbb307
594,595
def count_layers(model, trainable_only=True): """Count the number of layers in a Keras model. Parameters ---------- model : keras.engine.training.Model A Keras model. trainable_only : bool, optional Whether to count only trainable layers. Returns ------- int Nu...
3ccd5cf44fba0883454096c2aab5e9d7db389631
594,597
from datetime import datetime def within_time_range(start_time, end_time, now_time=None): # pylint: disable=unused-variable """Check whether time is in a specific time range.""" now_time = now_time or datetime.utcnow().time() if start_time < end_time: return start_time <= now_time <= end_time ...
0657d43048ef4c9e1a7b98a3a3e3822bc4994be8
594,601
import copy import random def shuffle_prompt(prompt, items, item_number, item_order): """ Shuffles the previoisly queried items to avoid recency bias. Parameters ---------- prompt : Str The initial prompt where the items are added. items : List A list of items to be shuffled. ...
eebfc42fb37ab80fb3ae3a9cd525d0df5517416f
594,604
def _get_ipynb_code_cell_idx(ipynb_dict): """ Get the index of the code cell. Parameters ---------- ipynb_dict : dict Dictionary of notebook data. Returns ------- idx : int The index of the code cell. """ idx = 0 cells_list = ipynb_dict['cells'] for cell...
9b7586697f0f7debdca076921f9a3fcc71b5cc00
594,615
import pathlib def in_directory( file: pathlib.Path, directory: pathlib.Path) -> bool: """Check if a path is a subpath of a directory.""" assert directory != file, f"Can't check {directory} is in itself" assert file.is_file(), f"Expected {file} to be a file" assert directory.is_dir(), ...
08ab779d1df6e2ce3c9e0c45a985bc1ac91f1292
594,620
def readWord (file): """ Read a 16 bit word from file. """ return ord (file.read (1)) << 8 | ord (file.read (1))
d05ca2ad97b2a146f0cf39641eb597024d85dd6a
594,621
def split_all(s, chars): """Split on multiple character values. >>> split_all('a_b_c_d', '_. ') ['a', 'b', 'c', 'd'] >>> split_all('a b c d', '_. ') ['a', 'b', 'c', 'd'] >>> split_all('a.b.c.d', '_. ') ['a', 'b', 'c', 'd'] >>> split_all('a_b.c d', '_. ') ['a', 'b', 'c', 'd'] >>>...
76cd3d5823dec479984ddd570b4162ab11bffec1
594,624
import io def requirements(filename="requirements.txt"): """Read the requirements file""" with io.open(filename, "r") as f: return [line.strip() for line in f if line and line[0] != "#"]
989b11676153c8bbe5b68c4be6e73f91cca1922d
594,628
def augment(matlist, column, K): """ Augments a matrix and a column. Examples ======== >>> from sympy.matrices.densetools import augment >>> from sympy import ZZ >>> a = [ ... [ZZ(3), ZZ(7), ZZ(4)], ... [ZZ(2), ZZ(4), ZZ(5)], ... [ZZ(6), ZZ(2), ZZ(3)]] >>> b = [ ... [ZZ...
df6a978ce08a390898b8b226fef7e0a18668c2bd
594,631
def get_machines(graph): """ Return list of physical machines in the landscape :param graph: Networkx graph :return: List of physical machines """ machines = {} for node, node_data in graph.nodes(data=True): if node_data["type"] == "machine": machines[node] = node re...
524e12412f5ebe3a717ccfba01eb15bd021eb877
594,632
def est_equilateral(longueur1, longueur2, longueur3): """Renvoie si un triangle est équilatéral.""" return longueur1 == longueur2 and longueur2 == longueur3 # ou, comme python le permet: # return longueur1 == longueur2 == longueur3
cfdc09adf8804acb082c2fb5a30810bd0299d982
594,638
def removesuffix(in_str: str, suffix: str) -> str: """removes suffix from a string.""" # suffix='' should not call self[:-0]. if suffix and in_str.endswith(suffix): return in_str[:-len(suffix)] return in_str[:]
12307730566c3f5b0228989b7a3a75c93039a30c
594,640
import yaml def load_config(name): """ Load YAML configuration file. Parameters ---------- name : str Path of the configuration file. Returns ------- cfg : dict Dictionary containing all the configuration information. """ try: with open(name, "r") as ...
29523284b49bb720df8296857c7c97987e1656a5
594,644
import json def extract_from_json(json_path): """ :param json_path: String, a valid path to a real readable .json file :return: Dictionary, the contents of the file at json_path """ with open(json_path, 'r') as infile: return json.load(infile)
b38755412d59eeb9fe98bfca24cf33289935e242
594,646
import json def load_extraction(json_file): """Load data from a PDF Extraction JSON file. Parameters: json_file (str): Filename, incl. path, to the PDF extraction JSON file Returns: dict: Dictionary representation of the loaded object. """ with open(json_file, "r") as read_file: extraction ...
177da1b15572724c1842c96a2fd2c39b1a219c27
594,647
from typing import List def sql_insert_rows_not_in_table(insert_table_name: str, reference_table_name: str, id_column_names: List[str], column_names: List[str]) -> str: """Create SQL to insert rows into a table, but only if those rows don't already exist in a reference table.""" ...
a5aa7103aaf71322e73f15b978b0b6837a5d9432
594,652
def PieceWiseOptimalityFunction(Min, Optimal, Max, X_in): """ A piecewise function of X_in, with parameters of Min, Max, and Optimal, that will return a number between 0 and 1. A linear increase from 0 to 1 across the X_in range of (Min, Optimal]. A linear decrease from 1 to 0 across the X_in range of (...
b6a5e544fe64dbf0be59a01d039724246260b232
594,654