content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
async def get_chains(self, symbol, info='expiration_dates'): """Returns the chain information of an option. :param symbol: The ticker of the stock. :type symbol: str :param info: Will data_filter the results to get a specific value. :type info: Optional[str] :returns: Returns a dictionary of ke...
2756d4c9f36d81968305c15c77cb613f68440dd8
638,033
def message_warning(msg, *a, **kwargs): """Ignore everything except the message.""" return str(msg) + '\n'
a39440007b6e07c4810e73a9c16edd06316962e4
638,035
def regrid_get_operator_method(operator, method): """Return the regridding method of a regridding operator. :Parameters: operator: `RegridOperator` The regridding operator. method: `str` or `None` A regridding method. If `None` then ignored. If a `str` then...
59b728fc74d89cf3daee34dff668d62a6d1fe5b0
638,039
def is_affiliation(item: str) -> bool: """Return true if a string contains an affiliation.""" return item.startswith('(')
64823607277c632c8b2f08c1865ebade42ec6832
638,040
def RelationshipLengthProperty(relationship_name): """Return a property representing number of objects in relationship.""" def getter(self): relationship = getattr(self._object, relationship_name) try: return relationship.countObjects() except Exception: return le...
8550a6374d5d7bc405352bbee11bb3b40684711c
638,044
def pad_to(x, k=8): """Pad int value up to divisor of k. Examples: >>> pad_to(31, 8) 32 """ return x + (x % k > 0) * (k - x % k)
d31bc75de96f941ef77afd5e8e909c4174709b77
638,047
import types def argument(name, type): """ Set the type of a command argument at runtime. This is useful for more specific types such as mitmproxy.types.Choice, which we cannot annotate directly as mypy does not like that. """ def decorator(f: types.FunctionType) -> types.FunctionT...
9c80425bf08336d064a44564b7b16aecfe06f109
638,048
from typing import List import bisect def get_bin(pred_prob: float, bins: List[float]) -> int: """Get the index of the bin that pred_prob belongs in.""" assert 0.0 <= pred_prob <= 1.0 assert bins[-1] == 1.0 return bisect.bisect_left(bins, pred_prob)
9924212bd9d6ae364d1c432cfd5a7927a4645719
638,049
import sympy def det(x): """ Symbolic determinant :param m: matrix :type x: ndarray with symbolic elements :return: determinant :rtype: ndarray with symbolic elements .. runblock:: pycon >>> from spatialmath.base.symbolic import * >>> from spatialmath.base import rot2 ...
dab990c333eeb2adff1ee8f1389df5e88d87ddf5
638,050
def transpose2(lists, defval=0): """ Transpose a list of list. defval is used instead of None for uneven lengthed lists. """ if not lists: return [] return map(lambda *row: [elem or defval for elem in row], *lists)
8d75ed2fc88cb33ce30b692c1bd22a873d6da7b2
638,051
def unslug(_input): """Convert slugs back into normal strings""" return _input.replace('-', ' ').replace('_', ' ')
675b6ac50e8f09d54617429886c69e070b36054c
638,052
def pages_to_edges(wiki_linked_pages): """ Create edges linking to (inbound) and from (outbound) a page """ page = wiki_linked_pages["title"] in_edges = [(in_page, page) for in_page in wiki_linked_pages["inbound_pages"]] out_edges = [(page, out_page) for out_page in wiki_linked_pages["outbound_p...
2380e2a7179df0640d418727dfee04786a2c2989
638,054
def create_summary_document_for_es(data): """ This function will create document structure appropriate for es :param data: data to parse :return: part of document to be inserted into es """ results = list() for k, v in data.items(): results.append({ "name": k, ...
5708c1c5d72717101e2c8ad72afaabe9f138a01b
638,055
import re def format_indeed_post_date(post_date): """ Format a Posted date to a numeric string of the recorded days Arguments : posted date string Return : Numeric string """ if ("Publiée à l'instant" in post_date) or ("Aujourd'hui" in post_date): return str(0) else: temp...
e13474dff9474a69e8e823d270a262f1c2bed597
638,058
import requests import json def post(base_url, action_url, params): """ 发送post请求 :param base_url: :param action_url: :param params: :return: """ full_url = base_url + action_url # 请求头 headers = { "Content-type": "application/json", 'Upgrade': 'HTTP/1.1' } ...
7367abf7470dca93944458865ee23e49ee413e45
638,059
def sequence_sum(begin_number, end_number, step): """ Goes through a loop and finds the sum of the sequence specified by three integer inputs. :param begin_number: the starting integer value. :param end_number: the ending integer value. :param step: integer of how many numbers to increase each step....
03c9b86a823b59558105c6d4d769e4c6b18c2c28
638,062
def decompose_column_name(col_name): """Returns separate parts of a hobo column name Argument: - col_name (str): the column name Returns: - tuple: (variable_name, unit_name, serial_text) """ x=col_name.split('(') try: serial_text=x[1].split(')...
2084d02d9ec3e5a2fe4bf7cc153bacd763d308fe
638,063
def _get_key(dict_like, key): """ Examples -------- >>> a = dict(b=1) >>> _get_key(a, 'b') 1 >>> _get_key(a, 'c') == "" True """ try: return dict_like[key] except KeyError: return ""
036e7d5b9767af333937a2cd5afef792136bfe16
638,064
import csv def into_list2(fIn,**kwargs): """ Read data from file into a 2D list. Lines with '#' are not read. Parameters ---------- fIn : str Path to input file delimeter : str (optional) Delimeter for parsing lines in file. (default is ',') type : str (optional) ...
788d93e448670dc86fba92653a26d6ba36f1641f
638,066
def w(q2: float, m_parent: float, m_daughter: float) -> float: """ Calculates the recoil variable w, which runs from 1 (zero recoil) to the maximum value (depends on daughter). :param q2: Momentum transfer to the lepton-neutrino system. :param m_parent: Mass of the parent meson, e.g. the B meson. :p...
c7b20722df49224db567681667664e687f506743
638,073
def is_valid_project_type(type): """ Validates supported project types; currently only maven is supported; hopefully gradle in the future """ if not type: return False if "maven" != type: return False return True
b450423c06d778701c639c3175b87b271ddfb5d9
638,075
def train_test_split(tokenized): """Returns a train, test tuple of dataframes""" train = tokenized.query("category != 'title'") test = tokenized.query("category == 'title'") return train, test
749d4c57087422fb2b610bf74ba2909229ef4e12
638,079
def scrapeSymbol(soup): """ Scrapes ICO symbol from ICODrops listing """ li = soup.findAll("li") for idx, yeah in enumerate(li): span = yeah.find("span", attrs = { "class" : "grey" }) if span and "Ticker:" in span.text: # Return only first match return li[idx] \ .text \ .repl...
9ea86b4396fe6317301241b78ee4ca1f4629cd27
638,080
import torch def logits_to_label(logits): """ Converts predicted logits from extended binary format to integer class labels Parameters ---------- logits : torch.tensor, shape(n_examples, n_labels-1) Torch tensor consisting of probabilities returned by ORCA model. Examples ---...
5e8f06c6562ea70c73629b97fc3798484e9d4a3c
638,081
import random def get_random_delay(min_time=0.01, max_time=0.1): """ Random sleep time between min and max time. Defaults to between 10 and 100ms :param min_time: minimum time (s) :param max_time: maximum time (s) :return: time in seconds """ return random.uniform(min_time, max_time)
6626ebad19a945713e01b6e594ea24e8681f0669
638,083
def parse_charoffset(charoffset): """ Parse charoffset to a tuple containing start and end indices. Example: charoffset = '3-7;8-9' [[3, 7], [8, 9]] """ # try split by ';' charoffsets = charoffset.split(';') return [[int(x.strip()) for x in offset.split('-')] for off...
17d1308b7b50748aa8898f434a8f16083f7e4368
638,084
def none_to_empty(val): """Convert None to empty string. Necessary for fields that are required POST but have no logical value. """ if val is None: return "" return val
bac9f6e6a5411615500e4ef6d08d654600e2fe62
638,090
def parse(exc): """Takes in an exception and returns the boto `Message, Code` properties if they exist - else `None, None` """ if exc is not None and hasattr(exc, 'response') and exc.response is not None: error = exc.response.get('Error', {}) code = error.get('Code', None) message = er...
8f0a31ebcc41e4aa11232df1241ec10f498a7342
638,099
def override(config, overrides): """Update a config dictionary with overrides, merging dictionaries. Where both sides have a dictionary, the override is done recursively. Where `overrides` contains a value of `None`, the corresponding entry is deleted from the return value. .. note:: this does not...
e9b37c3b661b2f152d568fea6121f1c0564d6e71
638,100
def get_most_visible_camera_annotation(camera_data_dict: dict) -> dict: """ Get the most visibile camera's annotation. :param camera_data_dict: Dictionary of form: { 'CAM_BACK': {'attribute_tokens': ['cb5118da1ab342aa947717dc53544259'], 'bbox_corners': [600.8315617945755, 4...
f91976008585513dbba34546385dcf4a1bd13eb6
638,101
import json def _to_json(self, fp=None, indent=4): """ Converts the object to JSON :param fp=None: an open file_like object to write the json to. If it is None, then a string with the JSON will be returned as a string :param indent=4: The indentation level des...
247ad11f573db8cff601f29ef5c1e8174c833377
638,102
def give_color_to_direction_static(dir): """ Assigns a color to the direction (static-defined colors) Parameters -------------- dir Direction Returns -------------- col Color """ direction_colors = [[-0.5, "#4444FF"], [-0.1, "#AAAAFF"], [0.0, "#CCCCCC"], [0.5, "...
5f8713edd8a0ce75bc20a38cf2e714e992dbda49
638,104
def onset_attributes_to_onset(o_beat, o_subdiv): """ Convert arrays of o_bt and o_sub to o. - See eq. (1) of the paper. """ def o_bt_o_sub_to_o(o_bt, o_sub): def convert_sub(x): """ o_sub from its 2's complement representation to exact value.""" return (x + 3) % 7 -...
43e9660f5a55ed8bf203f3b62276f55f3de6aece
638,107
def sanitize(string): """ sanitize a string before JSON-ize it """ return string.strip().replace("\\", "") # slash replace is only needed on Windows
618617a29342da284a98b855ac46b20bc2269870
638,111
import yaml def parse_config(config_file): """ Helper function to parse the Yaml config file. Args: config_file (str): yml configuration file Returns: dict: parsed dictionary object """ with open(config_file, "rb") as f: config = yaml.safe_load(f) return config
d3e66bb120aee5f39a6b90e8965c82ab9612abde
638,112
def convert_index_to_lab(batch, ind2lab): """Convert a batch of integer IDs to string labels. Arguments --------- batch : list List of lists, a batch of sequences. ind2lab : dict Mapping from integer IDs to labels. Returns ------- list List of lists, same size a...
b1ed85eee7d0c72bb6b6fdb61ad99147ba0c1abf
638,116
def get_time_field(da): """Get name of time coordinate.""" default_time_names = ['time', 'initial_time0_hours'] for d in default_time_names: if d in da.dims: return d raise RuntimeError('Could not deduce time coordinate for given data')
aa5e2dc1ef7ca5f9d9adb5e1e41cf7f81cf7c213
638,117
import requests def getSunriseSunsetDataLatLong(latitude: str, longitude: str, daysFromNow: int = 0): """Fetches data from sunrise-sunset API. Args: latitude: Latitude in degrees. longitude: Longitude in degrees. daysFromNow: Specify fetching data for a date N days in the future...
47bb10e14151b8e3ba7ced03b025918c9acd93ab
638,119
def of_type(ts): """ >>> of_type({'kind': 'OBJECT', 'name': 'User', 'ofType': None}) 'User' >>> of_type({'kind': 'NON_NULL', 'name': None, 'ofType': {'kind': 'SCALAR', 'name': 'String', 'ofType': None}}) 'String' >>> of_type({"kind": "ENUM", "name": "ProjectState"}) 'ProjectState' """ ...
40464c0f0d985fde7c3cb939958ea1bb349bcbfd
638,120
def get_position_from_periods(iteration, cumulative_period): """Get the position from a period list. It will return the index of the right-closest number in the period list. For example, the cumulative_period = [100, 200, 300, 400], if iteration == 50, return 0; if iteration == 210, return 2; i...
f103be219adba611e2aee4985116d64c1995a090
638,121
def timeStamp(list_time): """ Format time stam into `00h00m00s` into the dictionary :param list_time: float list of time stamp in second :return format_time: dictionary of format time """ format_time = dict() i = 0 for time in list_time: m, s = divmod(time, 60) h, m = div...
bbb777c43667922582725e60720a13408d27682b
638,123
import torch def bloom_gelu_forward(x): """ Custom bias GELU function. Adapted from Megatron-DeepSpeed code. Here we use a simple implementation (inference) to make the model jitable. Args: x (`torch.tensor`, *required*): input hidden states """ return x * 0.5 * (1.0 + tor...
6808c15488d19b65035a1209174f573ca21a5290
638,125
def calc_p_ratio(hps, nhps, total_hps, total_nhps): """ Returns a ratio between the proportion hps/nhps to the proportion nhps/hps. The larger proportion will be the numerator and the lower proportion will be the denominator (and thus the p-ratio>=1). This corrects for the total_hps/total_nhps imbalance...
c39727d485e94ce57ec56ff0d8bab9d85aceb241
638,126
def state2dict(Primes, State): """ Converts the string representation of a state into the dictionary representation of a state. If *State* is already of type *dict* it is simply returned. **arguments** * *Primes*: prime implicants or a list of names * *State* (str): string representatio...
4207b1e018cb503898aa0aaf840a551a06ab7f8f
638,130
def _get_name(soup) -> str: """Get the work name.""" return soup.find(id='work_name').a.contents[-1].strip()
3114445dedc91802a7a23c42ddf77e1d3e7bf3c7
638,132
def extract_mg_h(sai): """ Given an SAI, this find the most general pattern that will generate a match. E.g., ('sai', ('name', '?foa0'), 'UpdateTable', ('value', '?foa1')) will yield: {('name', '?foa0'), ('value', '?foa1')} """ return frozenset({tuple(list(elem) + ['?constraint-val%i' % i])...
0a1dd85f5fde1c3aeda4762483cfb87cbbc3d58e
638,133
def bool_flag(s): """Helper function to make argparse work with the input True and False. Otherwise it reads it as a string and is always set to True. :param s: string input :return: the boolean equivalent of the string s """ if s == '1' or s == 'True': return True elif s == '0' or s ...
89603008f3daa0411ca3c9dc537e5032bd52bc95
638,138
def statistics(prediction, ground_truth, beta=1): """Computes performance statistics for classifiers. Parameters ---------- prediction : set Set of objects predicted to be labeled positive. ground_truth : set Set of objects actually labeled positive. beta : float, optional ...
4b937a98a76431b979f7be33e732de82a46320bf
638,143
def IsNodeOSL(node): """ Determines if the given node has an OSL source type. """ return node.GetSourceType() == "OSL"
cbda361dfb0c244f7f2baa52af6992c84509c290
638,144
def join_tagblock(tagblock, nmea): """ Join a tagblock to an AIVDM message that does not already have a tagblock """ if tagblock and nmea: return "\\{}\\{}".format(tagblock.lstrip('\\'), nmea.lstrip('\\')) else: return "{}{}".format(tagblock, nmea)
011dc58a3a4342ea048f1f97e8fb5c5c47027c6d
638,146
import re def _parse_minimap_log(log_filename): """Parses minimap log file and returns i string) version, float ii) peak RAM""" version = "" RAM = 0.0 try: logfile = open(log_filename) except OSError as error: print("# ERROR: cannot open/read file:", log_filename, error) ...
3b932a0fef7c3dad7c26db0d1bc28c21e3a634fc
638,148
def get_broadcast_shape(x_shape, y_shape, prim_name): """ Doing broadcast between tensor x and tensor y. Args: x_shape (list): The shape of tensor x. y_shape (list): The shape of tensor y. prim_name (str): Primitive name. Returns: List, the shape that broadcast between ...
583f7f8e626d6cc9fa6941071b887b39e588aa13
638,151
def wn2wl(wavenumber): """Convert wavenumber (cm-1) to wavelength (um).""" return 10000 / wavenumber
55aeee52dca6b36e0ddee6a7176d0deaaeb7c552
638,154
def get_unique_sublist(inlist): """return a copy of inlist, but where elements are unique""" newlist = [] for val in inlist: if not val in newlist: newlist.append(val) return newlist
bc45dda0fd87d0c1b72f05db4fe72e3b312fe40c
638,160
def sig_indicator(pvalue): """Return a significance indicator string for the result of a t-test. Parameters ---------- pvalue: float the p-value Returns ------- str `***` if p<0.001, `**` if p<0.01, `*` if p<0.05, `ns` otherwise. """ return ( '***' if p...
51798d74afc6284c633d65a5ca89a9a421cab76b
638,162
import socket def hostname_to_ip(servers): """ Given (hostname, port) return (ip_address, port) """ reply = [] for server, port in servers: ip_address = socket.gethostbyname(server) reply.append((ip_address, port)) return reply
b9630d08e3f8daca280831230d65d2b5ec03d98c
638,165
def next_exon(variant_position, coding_exon_starts): """ get location of next coding exon after variant :param coding_exon_starts: coding exon start positions, Pandas Series. :param variant_position: chromosomal position, int :return: chromosomal position of start of next coding exon, int """ ...
92d875d90852491ccab66a503543d996aa90d48f
638,173
def transpose(G): """Transpose graph.""" V, E = G; ET = {} for u in V: ET[u] = [] for u, vs in E.items(): for v in vs: ET[v].append(u) return (V, ET)
2a7d3768569778275e4e64d62ae2eda02d5c080c
638,174
from datetime import datetime def get_week_of_month(year, month, day): """ 获取指定的某天是某个月中的第几周 周一作为一周的开始 """ end = int(datetime(year, month, day).strftime("%W")) begin = int(datetime(year, month, 1).strftime("%W")) star_date = end - begin + 1 if star_date == 1: week_of = '# 第一周' ...
b119ab45bf08bea17e2ecfafa88db3438de64e94
638,176
import math def numberOfDigits(tickSpacing): """Returns the number of digits to display for text label. :param float tickSpacing: Step between ticks in data space. :return: Number of digits to show for labels. :rtype: int """ nfrac = int(-math.floor(math.log10(tickSpacing))) if nfrac < 0:...
95b2c16342b45616194a0c799cc02b5259093b18
638,177
def IsNumeric(value): """ * Determine if string is numeric. """ if not isinstance(value, str): raise Exception('value must be a string.') try: valtxt = value value = int(valtxt) value = float(valtxt) return True except: return False
64e20550a237e60413d91ae25f22246a70035ef8
638,179
def get_A_sp_sh_JIS_A_4111(A): """太陽熱集熱部の有効集熱面積(IS A 4111) Args: A(float): 太陽熱集熱部総面積 Returns: float: 太陽熱集熱部の有効集熱面積 """ return A * 0.85
c6bf8d615a4a3b838e012d79543fb5a7f33aad81
638,181
import torch import math def relative_position_bucket(relative_position, bidirectional=True, num_buckets=32, max_distance=128): """ Adapted from Mesh Tensorflow: https://github.com/tensorflow/mesh/blob/0cb87fe07da627bf0b7e60475d59f95ed6b5be3d/mesh_tensorflow/transformer/transformer_layers.py#L593 Tran...
0b339513421c572d82d3ae4d8e06a1aed9d6bae3
638,182
def add_group(inventory, groupname, hostname=None): """Add a group to inventory, optionally add it with hostname.""" all_group = inventory["all"] group = {} if hostname: group["hosts"] = {hostname: {}} all_group["children"][groupname] = group return group
0332462667621dc4850eca045965d2ec9e7d587b
638,185
import re def alphanum_sort(l): """Sort the given list in ascending order the way that humans expect. i.e For a list l containing `["5", "24", "10"]`, the function sorts it as `["5", "10", "24"]` instead of `["10", "24", "5"]` as would Python List sort() method. """ # key to use for the sort ...
15b0c5dc44d841538896b4ec841c33ce54d7fdcb
638,188
def _format_optname(value): """Format the name of an option in the configuration file to a more readable option in the command-line.""" return value.replace('_', '-').replace(' ', '-')
e12d0d27ed744d45d789f3e9e0207f04be9f5024
638,190
def check_sentence_ending(sentence: str) -> bool: """Check if the sentence ends with a full stop. :param sentence: str - a sentence to check. :return: bool - True if punctuated correctly with period, False otherwise. """ return sentence.endswith(".")
7350ea9e9a6ff9c9760ef1e200134771d33a3e32
638,193
def html_escape(t): """Convert special HTML characters ('&', '<', '>', '"', "'") in string to HTML-safe sequences. >>> html_escape('<>"&') '&lt;&gt;&quot;&amp;' >>> """ html_escape_table = { "&": "&amp;", '"': "&quot;", "'": "&#039;", ">": "&gt;", "<": "&...
1a4409b8bb68364400819bcdbf7d05626be0a297
638,194
def sort_index(list): """ Return the *indices* of the elements in an array in order from smallest element to largest, e.g sort_index([3, -1, 1]) gives [1, 2, 0]. """ x = zip(list, range(0, len(list))) x = sorted(x, key=lambda x: x[0]) return map(lambda x: x[1], x)
1ab35611dc0808602966fe4f33f06f9652c32762
638,198
def c_to_f(c): """ Convert celcius to fahrenheit """ return c * 1.8 + 32.0
d96ee54e50b8fa8da348a6895e7da0b5b35e7c5f
638,199
def format_locations(location : str): """ Takes string describing location and returns nicely formatted tuple :param location: location string in the format 123..1234 :return: location tuple (123, 1234) """ return location.split("..")
5fe299d68eddcd51ba5fc70b39d6b03c290928fd
638,201
def parm_is_time_dependent(parm): """Checks if parm is time-dependent. """ return parm.isTimeDependent()
3166ad8ea301f208a8255e0658c091af102e1dc4
638,204
def num_swaps(A): """Given an array of integers from 0 to N-1, return number of swaps to sort.""" N = len(A) seen = [False] * N ct = 0 for i in range(N): if not seen[i]: idx = i num = 0 while not seen[idx]: num += 1 seen[id...
8d83e12408b957fdd706b8217043937160614df8
638,205
from typing import Optional from typing import Callable from typing import Dict def get_on_fit_config_fn( lr_initial: float, timeout: Optional[int], partial_updates: bool ) -> Callable[[int], Dict[str, str]]: """Return a function which returns training configurations.""" def fit_config(rnd: int) -> Dict[...
f8e12b3bb3fb0eba56910a15d1778c113111f5fa
638,206
import torch def jvp(y, x, v, create_graph=False): """Jacobian-vector product dy/dx @ v. Pass `create_graph=True` to allow backprop on output. """ return torch.autograd.grad(y.flatten(), x, v.flatten(), retain_graph=True, create_graph=create_graph, only_inputs =True)[0]
72268f65d450c389fcc5e78f2d9a8e3b84e45044
638,212
def extract_weeks_offset(tokens, end=None, key_tokens=( 'next', 'previous', 'last', 'upcoming', 'past', 'prev')): """Extract the number of week offsets needed. >>> extract_weeks_offset(['next', 'next', 'week']) (0, ['week'], 2) >>> extract_weeks_offset(['upcoming', 'Monday']) (0, ['Monday']...
3bab6f12ec8ad94da6556e974694d0ca3335a6c5
638,213
from typing import OrderedDict def bytes_as_dict(msg): """Parse CAM message to OrderedDict based on format /key:val. Parameters ---------- msg : bytes Sequence of /key:val. Returns ------- collections.OrderedDict With /key:val => dict[key] = val. """ # decode byte...
9ec86c892fcb8ae3078bca30b3e20e515d630f94
638,214
def extend(s, var, val): """ Given a dictionary s and a variable and value, this returns a new dict with var:val added to the original dictionary. >>> extend({'a': 'b'}, 'c', 'd') {'a': 'b', 'c': 'd'} """ s2 = {a: s[a] for a in s} s2[var] = val return s2
edeb7e151c50916c0b5e1a543a30a2b01cc6c5ab
638,215
def compose_ngrams_regex(emoji_regex): """ Compose a regex expression to parse out Ngrams :param emoji_regex: a regular expression that matches emojis :return: a compiled regular expression that matches ngrams """ pattern = '(' + emoji_regex pattern += r"|(&\S+;)" pattern += r"|(https?:\/\/\...
fb5a138286bf4d9717da01d6fc6053901e7c6bd9
638,224
import pickle def load_dispatch_results(iteration, year, scenario): """Load scenario results""" with open(f'output/dispatch_plan/uc-results_{iteration}_{year}_{scenario}.pickle', 'rb') as f: results = pickle.load(f) return results
e5267d8410cdda7e39815cfecd7010789661c768
638,229
def isSymbolNumber(command, sortedSymbols): """ isSymbolNumber checks whether given command has Stock Symbol number and it is in the loaded Stock Symbols. """ return ((len(command.strip()) > 0) and command.strip().isdigit() and int(command.strip()) < len(sortedSymbols))
815bbc2b03ffa38f0a0a4f89c0d07166506da751
638,230
def matsub(a, b): """ Subtracts one array from another. :param a: (ndarray) :param b: (ndarray) :return: (ndarray) product of a - b """ return a - b
7751fa1bf79a9e2c85cd458e7c729b7eebbb8cbb
638,231
def nested_map(f, obj): """Maps `f` recursively inside any dicts/lists/tuples in `obj`. Args: f: A function taking a single object as input. f's input must NOT be a dict, list, or tuple, or any subclass of those. obj: Either an input object to f or some nested structure of collections of (c...
9f7075f1fc132fbb933c7e2370b6f21f6eeb72ac
638,233
def intersect_shapes(shapes_a, shapes_b, shapes_b_sindex=None): """Find intersections between shapes in two lists Parameters ---------- shapes_a : list of Shapely geometries List of geometries to be intersected with those in shapes_b shapes_b : list of Shapely geometries List of geo...
3b91a54302a732c2c98bba44d6617cf4eea52b92
638,235
import re def match(regEx, text): """ Try to match the regular expression @regEx in the text at @text. If match is found, all occurrences are returned, otherwise empty list is returned """ _regEx = re.compile(regEx) res = _regEx.search(text) if res: return list(res.groups()) else: return []
d6eb2251b579f6e2546b32785e1e11983488d601
638,238
def get_energies(filename): """ Returns a dictionary with heats of formation for each xyz-file. """ f = open(filename, "r") lines = f.readlines() f.close() energies = dict() for line in lines: tokens = line.split() xyz_name = tokens[0] hof = float(tokens[1]) ...
1e4be956bba367167d8cd6d97114e83e9df489c4
638,241
def str_mask(str): """指定文字列をマスク置き換えする Replace the specified character string with a mask Args: str (str): 文字列 string Returns: str: 置き換え文字列 afeter string """ # 1文字以上の入力があれば置き換えする If there is more than one character input, replace it if len(str) > 0: ret = '*' * len(str)...
5d01f9b9c8d5fa9c95e1b4925300ecab852cd9dc
638,243
def mutlireplace(string, replacements): """ Replaces multiple substrings in a string. Parameters ---------- string : str The string to be modified. replacements : dict A dictionary of the form {old: new}. """ for key, value in replacements.items(): string = ...
ac6898d393a1841a8578913b371fe79bcb2b4c5a
638,247
def get_datetime_range(start_date, end_date, time_delta): """ :param start_date: (datetime.datetime) First date (included) :param end_date: (datetime.datetime) Last date (not included) :param time_delta: (datetime.timedelta) Increment :returns ([datetime.datetime]) All datetimes from start_date up t...
5bba18dafdf01957ab991a4c72eed93c76ea2c88
638,250
def roc(tests=[]): """ Returns the ROC curve as an iterator of (x, y)-points, for the given list of (TP, TN, FP, FN)-tuples. The x-axis represents FPR = the false positive rate (1 - specificity). The y-axis represents TPR = the true positive rate. """ x = FPR = lambda TP, TN, FP, FN:...
cff775657e93545573da91ecff5327e729992ed0
638,251
def roundToNearest(value, roundValue=1000): """ Return the value, rounded to nearest roundValue (defaults to 1000). Args: value (float): Value to be rounded. roundValue (float): Number to which the value should be rounded. Returns: float: Rounded value. """ if roundValu...
41eeb16cdcfc9a0081693ac3000b49a9f8598db4
638,258
def get_mqtt_field(p_message, p_field): """ Get the given field from a JSON message. @param p_message: The json message @param p_field: the 'field_name' to extract @return: the value of the field or None if missing. """ try: l_ret = p_message[p_field] except (KeyError, TypeError): ...
e95912a6381013fcc955f29f9518efb479def209
638,261
def _make_constraint_name(tname, *cnames, suffix=''): """Returns a constraint name from the given components.""" constraint_name = f'{tname}_' + '_'.join(cnames) return constraint_name[:63 - len(suffix)] + f'_{suffix}'
55b0be29556250ba188532b6505278201d59fb41
638,262
def xor(stream: bytes, key: int) -> bytes: """Apply XOR cipher to ``stream`` with ``key``. Applying this operation twice decodes ``stream`` back to the initial state. Parameters ---------- stream: :class:`bytes` Data to apply XOR on. key: :class:`int` Key to use. Type ``u8`` (o...
35a5978243ab39882ad257438780eb5ed5d44e45
638,264
import copy def mutate_dropped(record, rule): """Mutate a record for a "DROPPED" action. """ if rule['filters'](record): r = copy.copy(record) c = [] if 'column_filters' not in rule: return None for column in r['columns']: c_filters = rule.get('colum...
ed9937993ff042fe1a9038d3fb0efa0fbdf6086c
638,265
def get_r( x, y = 0, z = 1): """Makes r (length between origin and point) for x, y, z Returns r (scalar or array, depending on inputs)""" r = ( x **2 + y **2 + z **2 ) **0.5 return r
f99faa53e17fa11378cffb381cb41070b89e2ee0
638,267
import re def string_to_float(s: str) -> float: """ Double precision float in Fortran file will have form 'x.ydz' or 'x.yDz', this cannot be convert directly to float by Python ``float`` function, so I wrote this function to help conversion. For example, :param s: a string denoting a double precision...
833c159aabbc8f3bce467914bc26cddc199ce0af
638,268
def time(match, player_num, word_index): """A utility function for the time it took player_num to type the word at word_index""" assert word_index < len(match["words"]), "word_index out of range of words" assert player_num < len(match["times"]), "player_num out of range of players" return match["times"]...
b012ba5d4d033a65fc5177cb154df79d402dfa83
638,271
def parse_po(text): """ Parse 'po' format produced by xgettext. Return a list of (msgid,msgstr) tuples. """ messages = [] msgid = [] msgstr = [] in_msgid = False in_msgstr = False for line in text.split('\n'): line = line.rstrip('\r') if line.startswith('msgid ')...
d8fbb605e934cfed3b96cd98b6420cafda028974
638,272
def to_list(item): """ Make a list contains item if item is not a list :param item: item to convert :return: a list """ if item is not None and not isinstance(item, list): return [item] return item
0863ecbcb4ae7c429695df7b775f510efc15b994
638,277