content
stringlengths
39
9.28k
sha1
stringlengths
40
40
id
int64
8
710k
import re def remove_indentation(content: str) -> str: """ Removes indentation from a given string that contains multiple lines. It removes spaces before new lines by the first line spaces at the beginning. Args: content(str): The sting that we want to clean from the indentation. Returns...
76419258643c80597f442b6f48dae8167e4a1cad
84,606
def adjacentDiag(x1, y1, x2, y2): """Adjacency including diagonals.""" if 1 >= x1 - x2 >= -1 and 1 >= y1 - y2 >= -1: return True return False
35a5120da9a423fad321b5576bdedde0ddd314af
610,807
import json def ExtractJQuery(jquery_raw): """Extract and return the data inside a JQuery as a dict object.""" data_part = u'' if not jquery_raw: return {} if '[' in jquery_raw: _, _, first_part = jquery_raw.partition('[') data_part, _, _ = first_part.partition(']') elif jquery_raw.startswith('...
09cc1061537f85824b77ff072b24dfa8672d19d3
597,900
def percent_nan(data_series): """ For data_series, calculate what proportion of rows are NaN. @param data_series: data to check for NaNs @type data_series: Series @return: A number representing the proportion of data in data_series that is NaN @rtype: Float """ nan_count = data_series.is...
f03998b0a7d98112566bc339ed118891d8d05a7e
612,333
def query_adapter(interface, request, context=None, view=None, name=''): """Registry adapter lookup helper If view is provided, this function is trying to find a multi-adapter to given interface for request, context and view; if not found, the lookup is done for request and context, and finally only fo...
81c164ab122717cb31d001f3cf632da49183da87
688,891
def split_by_pred(pred, iterable, constructor=list): """Sort elements of `iterable` into two lists based on predicate `pred`. Returns a tuple (l1, l2), where * l1: list of elements in `iterable` for which pred(elem) == True * l2: list of elements in `iterable` for which pred(elem) == False """ ...
dc0c43cd5d34869566f283d92038aaa4a53d5c62
25,689
def _slice_fn_tensor_pair(x, idxs): """ Slice function for tensors. Parameters ---------- x : `torch.Tensor`, `shape=(n_data, )` Input tensor. idxs : `List` of `int` Indices to be taken. Returns ------- x : `torch.Tensor`, `shape=(n_data_chosen, )` Output tenso...
78abca7437f214973afbbbeeab62949c35827b35
146,189
from typing import Optional def format_ipfs_cid(path: str) -> Optional[str]: """Format IPFS CID properly.""" if path.startswith('Qm'): return path elif path.startswith('ipfs://'): return path.replace('ipfs://', '')
eca4a79bc2ba4151495831b51bbd50df68f73025
15,667
def create_sloping_step_function(start_x, start_y, end_x, end_y): """ create sloping step function, returning start y-value for input values below starting x-value, ending y-value for input values above ending x-value and connecting slope through the middle :param start_x: float starting x-...
67c8778a9aaba03cb7847de59dd018e128876ba0
665,715
def merge_with(f, *dicts): """Returns a dict that consists of the rest of the dicts merged with the first. If a key occurs in more than one map, the value from the latter (left-to-right) will be the combined with the value in the former by calling f(former_val, latter_val). Calling with no dicts retur...
1ddb503b6a000932d115f8045676c409e05abe5c
678,119
import io def _read_bytes(fp, size, error_template="ran out of data"): """ Read from file-like object until size bytes are read. Raises ValueError if not EOF is encountered before size bytes are read. Non-blocking objects only supported if they derive from io objects. Required as e.g. ZipExtFile ...
388a244d26bf030db1fc18086c64779a34bf904e
680,993
def get_score(score): """ Get the score in the from the csv string """ # If you're having parsing problems I feel bad for you, son. # I got 99 problems, but regex ain't one. remove_these = ["(", "SO", "OT", ")"] for r in remove_these: score = score.replace(r, "") return int(score...
d6865d22eb33140b214720e5d0e4b1c198325140
495,309
def Q_distcooler(P_mass, Cp, t_coolwater_exit, tp): """ Calculates the heat load of distilliat cooler. Parameters ---------- W_mass : float The mass flow rate of distilliat, [kg/s] Cp : float The heat capacity of distilliat, [J/(kg * degrees C)] t_coolwater_exit: float ...
200a3fc54e81f1cb5cbd6179e6857b7a599be1e4
594,264
def first(iterable, default=None): """Return the first element of an iterable, or a default if there aren't any.""" try: return next(x for x in iter(iterable)) except StopIteration: return default
54d7e8aa01304a6ddde2e636e96a6ecb36791a15
538,385
import math def getChar(inputValue, chars): """ Return a character in the given char list, according to the given input value Parameters ---------- inputValue : float Value you want to tranform to char chars : str List of chars you will use to select a char to represent the i...
fa579ef5ff8b0f76a48b5b5d1cf29ebad43ecd53
467,827
from typing import Tuple def get_axis_collision_distances( p1: float, w1: float, v1: float, p2: float, w2: float ) -> Tuple[float, float]: """ Gets the distance to the entry and exit points of a collision on one axis. Parameters: p1: float - Position of first object w1: float - W...
8ff6e39e7426099ab29017f4b976867a9b2c375a
116,374
def _sample_distribution_over_matrix(rng): """Samples the config for a distribution over a matrix. Args: rng: np.random.RandomState Returns: A distribution over matrix config (containing a tuple with the name and extra args needed to create the distribution). """ # At this point, the choices her...
20c39319f217e62bd33e06f4f556030f133baff7
660,063
def listify(item): """ Check if an item is enclosed in a list and make it a list if not :param item: item to convert to a list :return: list containing the original item """ if not isinstance(item, list) and item is not None: return [item] else: return item
298e973eb2b285567131c2eb4b134be7cb3ffb09
536,375
def pass_bot(func): """This decorator is deprecated, and it does nothing""" # What this decorator did is now done by default return func
b8043b87b762db9f7b78617ad253aaca9dcd4369
659,205
import functools def qutip_callback(func, **kwargs): """Convert `func` into the correct form of a QuTiP time-dependent control QuTiP requires that "callback" functions that are used to express time-dependent controls take a parameter `t` and `args`. This function takes a function `func` that takes `t...
8d20a3fc75bd673a3b5576e2d147162d13ca19ba
663,755
def _pass(x): """Format text without changing it.""" return x
0357342fa3654343e0db3fd349c15e1596f2b77c
479,497
def NoTests(path, dent, is_dir): """Filter function that can be passed to FindCFiles in order to remove test sources.""" if is_dir: return dent != 'test' return 'test.' not in dent
ad9ce5a0a4df693a2fa2589808a393b8d30b7a23
52,873
def filter_rule_ids(all_keys, queries): """ From a set of queries (a comma separated list of queries, where a query is either a rule id or a substring thereof), return the set of matching keys from all_keys. When queries is the literal string "all", return all of the keys. """ if not queries: ...
daf5a40754c34342d0707c2334be2ad9de0444e0
677,518
import math def _map_tile_count(map_size: int, lod: int) -> int: """Return the number of map tiles for the given map. Args: map_size (int): The base map size in map units lod (int): The LOD level for which to calculate the tile count Returns: int: The number of tiles in the given...
8ced1676043098a3cfddc106b0aaab0e2745e5b2
677,397
def Fibonacci_digit(n): """Return the index of the first term in the Fibonacci sequence to contain n digits. The Fibonacci sequence is defined by the recurrence relation: F(n) = F(n-1) + F(n-2), where F(1) = F(2) = 1. Parameters ---------- n : int The resulting number of di...
de66f2d4f809051a8696d4b60828aee73bfa9681
483,396
def cu_mask_to_int(cu_mask): """ A utility function that takes an array of booleans and returns an integer with 1s wherever there was a "True" in the array. The value at index 0 is the least significant bit. """ n = 0 for b in reversed(cu_mask): n = n << 1 if b: n |= 1 ...
2ac11b0a7845771808cec3779edf975f6239632b
465,148
def encode_special_characters(user_string): """ Encode Special Characters for user's search Strings Args: user_string(string): raw string to encode Returns: Encode string for elasticsearch """ if user_string is None: return "" sp_chars = ['+', '-', '=', '|', '<', '...
00d31e32a823028a08333bd59000f52b64dafcf9
32,502
def get_second_validate_param(tel_num): """ Assemble param for get_second_validate :param tel_num: Tel number :return: Param in dict """ param_dict = dict() param_dict['act'] = '1' param_dict['source'] = 'wsyytpop' param_dict['telno'] = tel_num param_dict['password'] = '' par...
efbd31c56e3fdd4cb0e75bcae92cf51d996aac5d
22,146
def isValidChannelName(channelName): """ Determines whether the given channel name is in a valid format. """ if channelName[0] != "#": return False for char in "\x07 ,?*": # \x07, space, and comma are explicitly denied by RFC; * and ? make matching a channel name difficult if char in channelName: return Fal...
ea5ab661f117e9c91eff3b3a11cf6bc66f625dd9
442,514
import re def filter_tests(filters, test_ids): """Filter test_ids by the test_filters. :param list filters: A list of regex filters to apply to the test_ids. The output will contain any test_ids which have a re.search() match for any of the regexes in this list. If this is None all test_ids w...
d8ca31fddb052dde7eaaa21c777e2963e705a598
40,353
def temperature_over_total_temperature( mach, gamma=1.4 ): """ Gives T/T_t, the ratio of static temperature to total temperature. Args: mach: Mach number [-] gamma: The ratio of specific heats. 1.4 for air across most temperature ranges of interest. """ return (1 + (...
a1fea37f80df9eff21716f273b6270cfa7fcd302
37,882
import math def iterate_pagerank(corpus, damping_factor): """ Return PageRank values for each page by iteratively updating PageRank values until convergence. Return a dictionary where keys are page names, and values are their estimated PageRank value (a value between 0 and 1). All PageRa...
55ecbae0d470bd63d1f33c5d0f5bbdd2fe4806d7
230,771
def stripped(v): """Cleans string to remove quotes""" return v.strip('"').strip("'")
48514b274f9d0b1a884dd2a8add134ba5b82afbf
513,020
def gasfvf2(unit='unit1', z=0.8, temp=186, pressure=2000): """ Gas FVF calculated in other units unit: choice of units (unit1: RB/scf, unit2: res m3/std m3) for unit1, inputs temp in Rankine (Fahrenheit + 460), pressure in psia or psig for unit2, inputs temp in Kelvin, pressure in psia or psig """ if unit...
732270809bfef7760ec4fb71470653dcfcb2265e
362,379
def mean(lst): """Return the average of a float list.""" length = len(lst) return sum(lst)/float(length) if length != 0 else None
d9b669cb438afc66c4ccd8acfd10b63121c5f003
418,889
def prepare_args(args): """ Prepare arguments to be used as the API expects it :param args: demisto args :return: transformed args """ args = dict((k.replace("-", "_"), v) for k, v in list(args.items())) if "is_public" in args: args["is_public"] = args["is_public"] == "True" retu...
eaf0d7f7f30390d02481ff01e9eea4a7b3262ef2
626,969
def cast_no_data_value(no_data_value, dtype): """Handles casting nodata values to correct type""" int_types = ['uint8', 'uint16', 'int16', 'uint32', 'int32'] if dtype in int_types: return int(no_data_value) else: return float(no_data_value)
e5d4fab57ca00b154990890aafee5ebc8290207d
126,464
def max_length(tensor): """ Return max length of the tensor """ return max(len(t) for t in tensor)
ccf2bcaec70f20338396e9c7db5ab21233336f22
497,853
import requests def get_html(zipcode): """ Get the html to be parsed. :param zipcode: :return: html from web. """ url = f'https://www.wunderground.com/weather-forecast/{zipcode}' response = requests.get(url) return response.text
28cdb00b7746017b69e955a379eb2f248a675fe2
615,761
import collections def get_gt_distribution(experience, get_block): """ Get the ground-truth distribution of an experience buffer. :param experience: List of transitions. :param get_block: Function that returns the ground-truth state-action block for each transition. :return: ...
6dcba0e714d9d98a530c16fcfa12679980b46871
40,881
def getShortestPaths(paths): """ Returns a list containing only the shortest paths. The list may contain several shorters paths with the same length. """ shortestPaths = [] shortestLength = 99999 for path in paths: if len(path) < shortestLength: shortestLength = len(path) ...
679ce4d747291d00cdb4875bef9360e595fbdb64
288,396
import time import requests import uuid import webbrowser def _check_for_api(launch_browser=False, timeout=5): """Helper method to check for the API to be live for up to 15 seconds and then optionally launch a browser window Args: launch_browser(bool): flag indicating if the browser should be launche...
ffed20b56e7acb1625593f30cb452f9c9dea8681
590,235
def extract_layers_by_str(model, layers): """ Returns references to layers from model by name Parameters ---------- model : torch.nn.Module model where layers should be extracted from layers : iterable of str iterable which contains the names of the respective layers Return...
9c25579a129f45b16bf67f061497123dfd285f73
607,962
import random def slice_dir_to_int(slice_dir): """ Convert slice direction identifier to int. Args: slice_dir: x|y|z|xyz (string) Returns: 0|1|2 (int) """ if slice_dir == "xyz": slice_direction_int = int(round(random.uniform(0, 2))) elif slice_dir == "x": ...
b1a94b4cb2753128fc7403ceca99ffeb9591e810
204,811
def sdf_supported_property_non_string(property_name): """ Check to verify that this property is support natively in SDF (without modification) :param property_name name to check :return: boolean true/false """ supportedProperties = ["minimum", "maximum", "uniqueIte...
ccc8108dbcc1eb5cb665050b1a5874fcc2ec7b3a
601,900
from typing import Tuple import re def replace_code( begin_delim: str, end_delim: str, content: str, new_code: str ) -> Tuple[str, int]: """Replaces text delimited by `begin_delim` and `end_delim` appearing in `content`, with `new_code`. Returns new string and number of matches made.""" return re.subn...
ab7cfff3c3ae7b0356a1b3558b2fa36c1beb5401
683,657
def calibrate_2band(instr1, instr2, airmass1, airmass2, coeff1, coeff2, zero_key='zero', color_key='color', extinct_key='extinction'): """ This solves the set of equations: i_0 = i + A_i + C_i(i-z) + k_i X z_0 = z + A_z + C_z(z-i) + k_z X where i_0 and z_0 are the instrumental magnit...
df3d586646098b0c723032406a5ffbea8df11eb9
101,504
def rayleigh_vel(longitudinal_vel, transverse_vel): """ Approximate Rayleigh velocitiy. Parameters ---------- longitudinal_vel : float transverse_vel : float Returns ------- rayleigh_vel : float Notes ----- [Freund98] Freund, L. B.. 1998. `Dynamic Fracture Mechanics`. ...
d99c572eb38f03ae0d3fa8701a6e51ee45fb7533
287,332
def get_r(x,y,z): """Get density r""" den = x**2+z**2 return den
24a39524ee9e07aa23b19f5a030a1bf3f4c0f8ac
379,147
def list_sync(api, instance="", **params): # type (ApiClient, str) -> list[dict[str]] """ list all the communities of an instance. If no instance is provided , all the communities Args: api: the ApiClient instance to use for requests instance: the instance id **params: optional ...
4aa389c68d7d3a96da3bf552300661e3d5df6733
157,878
def center(map, object): """ Center an ee.Image or ee.Feature on the map. Args: map: The map to center the object on. object: The ee.Image or ee.Feature to center. Returns: The provided map. """ coordinates = object.geometry().bounds().coordinates().getInfo()[0] ...
60a2baa1c4f83b0e9b1221bcc474f109c35cbd7a
701,034
def burst(group): """ Returns the number of shots the fire mode will make. """ if group["fire_mode"] == "auto": shots = 3 else: shots = 1 return shots
8e46adbe3814103df7c3390f3c17368e4f391da0
193,310
def judgement(seed_a, seed_b): """Return amount of times last 16 binary digits of generators match.""" sample = 0 count = 0 while sample <= 40000000: new_a = seed_a * 16807 % 2147483647 new_b = seed_b * 48271 % 2147483647 bin_a = bin(new_a) bin_b = bin(new_b) la...
9d778909ba6b04e4ca3adbb542fce9ef89d7b2b7
3,698
def key_of_max(d): """Return key associated with maximum value in d. >>> key_of_max({'a':1, 'b':2}) 'b' """ keys = list(d.keys()) keys.sort() return max(keys, key=lambda x: d[x])
01ee05b37d8c8bbaa12c184aba422c2e3ac2e438
58,831
import glob def find_all_filetype(data_dir, extension): """ Finds all files in a directory, returns their path Args: data_dir (str): path to where your MitoGraph output data are extension (str): the extension to search for (e.g. ".gnet", ".mitograph") Returns: path_list (list of ...
90668bd0c8dbbcfcfc5b8a786d74b22fd76dd35c
296,162
def calculate_average_since(hrs_after_time): """ Calculate average heart rate after specified date This function first sums all of the heart rates after the specified date. It then divides the summed heart rates by the total number of heart rate entries. The result is the sum of the heart rates after t...
68c587200cfdcc0bd8607cb2a2485acf72c93681
355,232
def get_sentence_length(train_data_set, test_data_set): """ Acquire the longer of the maximum sentence lengths of training data and test data. :param train_data_set: Raw sentence for training data :param test_data_set: Raw sentence for testing data :return: Maximum sentence length """ if max...
7131158d9af35deeef2d7de07508ba6080931fbf
257,184
from typing import Dict import re def wikitext_detokenize(example: Dict[str, str]) -> Dict[str, str]: """ Wikitext is whitespace tokenized and we remove these whitespaces. Taken from https://github.com/NVIDIA/Megatron-LM/blob/main/tasks/zeroshot_gpt2/detokenizer.py """ # Contractions text = e...
ad06cc5c394684a265e6e91e29d3744466f18eb6
666,702
import yaml def dump_to_string(data)-> str: """ Dumps 'data' object to yaml string """ result = yaml.safe_dump(data, default_flow_style=False, default_style=None, explicit_start=None) return result
234927a81831d92820bf8599a7b27ee7e256793f
661,280
def coor_to_int(coor): """ Convert the latitude/longitute from float to integer by multiplying to 1e6, then rounding off """ return round(coor * 1000000)
b0ec7507887d492dc92e6b9452ac7091db558888
292,800
def decorate_if_staff(decorator): """ Returns decorated view if user is staff. Un-decorated otherwise (the inverse version of decorate_if_no_staff) """ def _decorator(view): decorated_view = decorator(view) # This holds the view with decorator def _view(request, *args, **kwargs):...
d0532dc935d2be3a296058f44d271acab72b790a
309,673
def toSet(hashes): """ converts the hashes (iterable) to a corresponding set of hashes """ s = set() for val in hashes: s.add(val) return s
7b5f5c86af52afa00ce2c8cf642826a7ecfa885f
182,118
import copy def merge_normalized_sequence_analyzers(sequence_analyzers): """Merges SequenceAnalyzers and returns the result SequenceAnalyzers copied and normalized setting their individual total frequency to one. The sum of all normalized SequenceAnalyzers is then returned. Args: sequence_analyzers: L...
adfb9290da867f19b43d04b9d51c84a630edc880
203,190
def get_identifier(commit_datetime, commit_hash, trt_version, branch): """ Returns an identifier that associates uploaded data with an ORT commit/date/branch and a TensorRT version. :param commit_datetime: The datetime of the ORT commit used to run the benchmarks. :param commit_hash: The hash of the OR...
a0c64a414caa057ba09dea15c888482eeeb31bc0
397,504
from typing import List import math def equal_split(s: str, width: int) -> List[str]: """ Split the string, each split has length `width` except the last one. """ num = int(math.ceil(len(s) / width)) # python3 return [s[i * width: (i + 1) * width] for i in range(num)]
46ae233f314136e36913834f40576a78fdab7bdf
683,464
import yaml def get_credentails_from_file(auth_file): """Read the vault credentials from the auth_file. :param auth_file: Path to file with credentials :type auth_file: str :returns: Token and keys :rtype: dict """ with open(auth_file, 'r') as stream: vault_creds = yaml.safe_load(...
75872999cccfc5b19edbb9bb250503a8d6b0c532
397,089
def get_gender_from_wiki_claims(clm_dict): """ From clim_dict produced by pywikibot from a page, tries to extract the gender of the object of the page If it fails returns None N.B. Wikidata's categories for transgender male and female are treated as male and female, respectively >>> from gender_nov...
dc85408e1680ed5acf066d5663e46ec805fdc0b9
268,505
def generate_prefixes(vocabulary): """Return a set of unique prefixes from the given list of strings.""" # Generate prefixes using the first half of each string return set(word[:len(word)//2] for word in vocabulary)
b5b2f46170ef21ff4b259ec19c9deb680a852c07
272,654
def find_children_by_type(component, target_type): """Recursively find all children of the component and it's decendents by type. :param component: Component instance to start seach from :type component: class instance :param target_type: class to match with instances :type target_type: class ...
98c2db35586878047c7c3523dd41142a1e044b55
488,465
async def handleIconBytes(response): """Handles returning of iconBytes response value. Args: response (aiohttp.ClientResponse): Request response Returns: bytes: Icon image in bytes """ return await response.read()
e219d8fe2c09a1b60cc890a18d8a4dc77ba665fd
530,737
def acquire_category(soup): """ Take a BeautifulSoup content of a book page. Return the category of the book. """ table = soup.ul.find_all('a') category = table[2].string return category
ce0f28cab0809959d89f684d1d1e5ba060abb51a
42,133
def get_bulk_download_links(page): """Extracts the bulk download links from the BeautifulSoup object. Parameters ---------- page : bs4.BeautifulSoup The bs4 representation for the bulk download page Returns ------- download_links : dict A dictionary containing the download ...
09459d6930d8966309217885328f7600d48d4e48
194,368
import typing def identifier_path(it: typing.Union[typing.Type[object], typing.Callable]) -> str: """Generate an identifier based on an object's module and qualified name. This can be useful such as for adding attributes to existing objects while minimizing odds of collisions and maximizing traceability ...
6702c0d98c93d5ffbccbef4bdbca9884302358f6
588,377
def epsilon(i, j, k): """ Return 1 if i,j,k is equal to (1,2,3), (2,3,1), or (3,1,2); -1 if i,j,k is equal to (1,3,2), (3,2,1), or (2,1,3); else return 0. This is used in the multiplication of Pauli matrices. Examples ======== >>> from sympy.physics.paulialgebra import epsilon >>>...
7e4bffa3898a727c697a47d9002021b886671a5d
501,960
import importlib def get_cls(module_name, class_name, relaxed=True): """ Small helper function to dynamically load classes""" try: module = importlib.import_module(module_name) except ImportError: if relaxed: return None else: raise ImportError("Cannot load ...
5c400001708d402951ec0e3353f93d795a15d82f
487,006
def Lsynch_murphy(sfr, nu): """ Synchrotron luminosity model, taken from Eq. 9 of Bonaldi et al. (arXiv:1805.05222). Parameters ---------- sfr : array_like Star-formation rate, in Msun/yr. nu : array_like Frequency, in GHz. Returns ------- L_synch ...
e5309f3d36040aa11a68ef9b67433909f59c281f
363,771
def _extract_comment(_comment): """ remove '#' at start of comment """ # if _comment is empty, do nothing if not _comment: return _comment # str_ = _comment.lstrip(" ") str_ = _comment.strip() str_ = str_.lstrip("#") return str_
ce4290e5534833b104c5e16874566562fa772b57
502,957
def _filter_keys(d, pred): """Filter the dict, keeping entries whose keys satisfy a predicate.""" return dict((k, v) for k, v in d.items() if pred(k))
de7afa9e635b3d2cf891edcf4e509c4f85fb9391
488,813
def askYesOrNo(msg): """ Asks a Yes/No question. Returns True/False. """ while True: edit = input('\n' + msg + ' (y/n): ') if edit == 'y': return True elif edit == 'n': return False else: print('Please enter Yes ("y") or No ("n").')
27bc05b508dfb635c32eec23677a2567ec3a3812
239,844
def Concrete01Funct(fc, ec, fpcu, ecu, discretized_eps): """ Function with the equation of the curve of the Concrete01 model. For more information, see Kent-Scott-Park concrete material object with degraded linear unloading/reloading stiffness according to the work of Karsan-Jirsa and no tensile str...
d2cde0730ca677c3ba710f64227ad6b658656d04
153,400
def from_saved_model(layer): """Returns whether the layer is loaded from a SavedModel.""" return layer.__module__.find('keras.saving.saved_model') != -1
2616dc31d2a6523304259664ce73f0f57a81ebd9
79,268
def format_states(states): """ Format logging states to prettify logging information Args: states: logging states Returns: - formated logging states """ formated_states = {} for key, val in states.items(): if isinstance(val, float): if val < 1e-3: ...
4612914f26813b9dd4cea527ec54f3d03ec5284f
664,209
def unprocess_image(image): """ Undo preprocess image. """ # Normalize image to [0, 1] image = (image / 2) + 0.5 image = image * 255.0 #[0,1] to [0,255] range return image
68b8bddfa0d33530687e753bc0f2a07c9be4e425
54,045
def set_spines(ax, plot_params): """ Sets spines of the shift graph to be invisible if chosen by the user Parameters ---------- ax: Matplotlib ax Current ax of the shift graph plot_parms: dict Dictionary of plotting parameters. Here `invisible_spines` is used """ spines ...
4e74ce30f52d465e9470f608cd8c909dfae4d0a5
704,069
def decimal_hours(timeobject, rise_or_set: str) -> float: """ Parameters ---------- timeobject : datetime object Sunrise or -set time rise_or_set: string 'sunrise' or 'sunset' specifiying which of the two timeobject is Returns ------- float time of timeobject in d...
44fe260abf8751cb78cf6e484dbf223d05233713
28,046
def is_capacity_empty(capacity): """ Check for an empty Capacity object to detect for empty Excel rows. :param capacity: Capacity :return: Boolean """ if capacity.ap is None \ and capacity.capacity is None: return True return False
e40374765f2266433fd1eed910d8cd686def41ef
580,746
def KtoF(tmp): """Standard Kelvin to Fahrenheit Temperature conversion""" tmp = tmp - 273.16 return 9. / 5. * tmp + 32.
92e8a2a3cc4b1c2f4cf9fb7cb3d2ec7681412d27
350,585
def build_sg_graph_dict(sg): """ Builds a dictionary of dependencies for each node, where each node can have either component or supplier dependents or both. If a node has no dependents of a certain type, the key is missing. A node with no dependents has an empty dictionary.""" def type_tag(node): ...
ecd8c1b0488b04a2cde4a1b030d96de5a78cc948
85,793
def GetLinkType(messages, link_type_arg): """Converts the link type flag to a message enum. Args: messages: The API messages holder. link_type_arg: The link type flag value. Returns: An LinkTypeValueValuesEnum of the flag value, or None if absent. """ if link_type_arg is None: return None e...
2200b02ec80beba4d5e0c90087487d82d2eb7c9e
450,443
def ids_to_sentence(ids, id2word): """ Converts a sequence of ids to a sequence of symbols. ids: a list, indices for the padded sequence. id2word: a dict, a mapping from ids to original symbols. result: a list of symbols. """ return [id2word[i] for i in ids]
6176bf4f2f9a46458a5b1b247c2e62afb3f1fa7e
377,514
def get_modified(raw): """ Extract last modification date of Libris post. To be used as 'published' date in reference note on Wikidata. @param raw: json object of a Libris edition @type raw: dictionary """ return raw["modified"]
10df4f9b81dc0c99f2181e6db2662d552ba9c595
376,600
def _is_hdf(fmt: str) -> bool: """ Check if format is of HDF type (this includes netcdf variants) """ fmt = fmt.lower() return any(f in fmt for f in ('netcdf', 'hdf'))
1c7f661970330ef3fb7e9070bf1a0abc5e9d1213
182,409
def sort_terms(terms): """ Returns a list of two sympy expressions where the expression is positive and the second expression is negative. Parameters ---------- terms : list of sympy expressions A list with length of 2 where one element is positive and the other is negative (sta...
c5ff1d091c6c76edc8a90a3fd0583cc5173016bf
296,019
import requests def get_bytes_from_url(url): # pragma: no cover """ Reads bytes from url. Args: url: the URL Returns: the bytes """ req = requests.get(url) return req.content
bf00ec24300167cea4f75df809d65f1991af4ea8
32,247
def transform_fn(transforms, params, invert=False): """ (EXPERIMENTAL INTERFACE) Callable that applies a transformation from the `transforms` dict to values in the `params` dict and returns the transformed values keyed on the same names. :param transforms: Dictionary of transforms keyed by names. N...
b7fdad98037bddc1de8243750d9352fe74f251d1
439,641
def evaluate_postfix(expression): """ Evaluates a postfix expression using a shift/stack """ def plus(x, y): return x+y def minus(x, y): return x - y def multiply(x, y): return x*y def div(x, y): return x / y operators = {'+': plus, '/...
8f0505218f9ea97489918ffa9a4320b33e06336d
278,862
from typing import Any def original_case(value: str, **kwargs: Any) -> str: """Return the input string without any modifications.""" return value
d56303b5774414da63f55cf38f174b7e78f932e3
207,623
def _is_special_name(name): """Determine whether or not *name* is a "__special__" name. :param str name: a name defined in a class ``__dict__`` :return: ``True`` if *name* is a "__special__" name, else ``False`` :rtype: bool """ return name.startswith("__") and name.endswith("__")
e4b4ce58e7df5b89677a1f45b9bc921d51116e78
527,081
def mk_outro(background='black'): """Generate the finishing code for a PyMol script.""" return """ # Viewing options bg_color black reset """
f17af141fb390e3c4a60c1f29f8c361b05910af2
385,191
def to_query(cols, vals): """Returns a query from a list of columns and values""" vals = ["'"+val+"'" if isinstance(val,str) else val for val in vals] query = ['{} == {}'.format(cols[i],vals[i]) for i,_ in enumerate(cols)] query = ' and '.join(query) return query
850235bff3ddd0bc188e087e398b4f12f14febd9
138,129