content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def uptime_seconds(uptime_list): """ Convert a list of the following form: [years, weeks, days, hours, minutes] To an uptime in seconds """ years = uptime_list[0] weeks = uptime_list[1] days = uptime_list[2] hours = uptime_list[3] minutes = uptime_list[4] # No leap day calculation days = years*365 + weeks*7 + days minutes = days*24*60 + hours*60 + minutes seconds = minutes*60 return seconds
abf29658193ab373c8e7e8c722fe308d3642c176
40,835
def _load_coverage_exclusion_list(path): """Load modules excluded from per-file coverage checks. Args: path: str. Path to file with exclusion list. File should have one dotted module name per line. Blank lines and lines starting with `#` are ignored. Returns: list(str). Dotted names of excluded modules. """ exclusion_list = [] with open(path, 'r', encoding='utf-8') as exclusion_file: for line in exclusion_file: line = line.strip() if line.startswith('#') or not line: continue exclusion_list.append(line) return exclusion_list
da20f154a3ad754c344a378889ce913760743d5a
40,837
def avg(rows: list, index: int): """ This is used to calculate the skill average and the slayer average of the whole guild :param (list) rows: A list containing more lists which are used to calculate the average :param (index) index: The index in the list of the value to calculate :returns (str): The rounded guild average """ total = 0 for row in rows: if type(row[index]) in (int, float): total += row[index] result = total / len(rows) return str(round(float(result), 1))
e4a0dbb81e911c114b99e411c7d81209a8d0728f
40,843
from typing import Iterable def const_col(dims: Iterable[int]) -> str: """ Name of an constant columns. Parameters ---------- dims Dimensions, that describe the column content. Returns ------- name: str Column name. Example ------- >>> from rle_array.testing import const_col >>> const_col([1, 2]) 'const_1_2' >>> const_col([2, 1]) 'const_1_2' """ dims = sorted(dims) dims_str = [str(d) for d in dims] return f"const_{'_'.join(dims_str)}"
52aecf5872f6444bf0155f0556ce39b2250ce758
40,847
import re def file_id (s): """Return a conventional file name from a pseudo-file name. (ast/FooBar.hh -> ast/foo-bar.hh).""" return re.sub ("([a-z])([A-Z])", "\\1-\\2", s).lower ()
316248c3cb701466ba9189b1a8bf24ee21384042
40,848
def GetDefaultPanelBorder(self): """ Default panel border is set to 0 by default as the child control will set their borders. """ return 0
abbe52bd59c73ed92a278336c6dd38c1ce0c927e
40,851
def get_service_state_name(state): """ Translate a Windows service run state number to a friendly service run state name. """ return { 1: 'Stopped', 2: 'Start Pending', 3: 'Stop Pending', 4: 'Running', 5: 'Continue Pending', 6: 'Pause Pending', 7: 'Paused' }.get(state, 'Unknown')
153bfb340ca20335aa476021d31a9918fb00f1f4
40,856
def mkdown_p(text): """ Generates the markdown syntax for a paragraph. """ return '\n'.join([line.strip() for line in text.splitlines()]) + '\n'
ac511acb8bb81ad37aac7897763584d062662d99
40,859
def get_first_selected_text(view): """Gets a copy of the given view's first buffer selection""" first_selected_region = view.sel()[0] buffer_text = view.substr(first_selected_region) return buffer_text, first_selected_region
74b4508f900c87789ebf41b66f31f5a3d41157b1
40,871
def create_transcript_objects(refseq_db, nms_in_refseq): """Retrieve Transcript objects from RefSeq db""" transcripts = [] for id in nms_in_refseq: t = refseq_db.by_id(id) transcripts.append(t) return transcripts
f1422ebd14eccc1b1f26cefefad1c734e06cb81b
40,872
def check_params(params): """ Checks if the parameters are defined in the domain [0, 1]. :param params: parameters (u, v, w) :type params: list, tuple :raises ValueError: input parameters are outside of the domain [0, 1] """ tol = 10e-8 # Check parameters for prm in params: if prm is not None: if not (0.0 - tol) <= prm <= (1.0 + tol): raise ValueError("Parameters should be between 0 and 1") return True
a0b8225addd1d499719d26461b2ada79b4d27a8c
40,874
def apply_tf(data, tf): """Apply function `tf` (transformation function) if specified and return result. Return unmodified data in other case""" if tf: return tf(data) else: return data
86d381f5df2362cd614ec252fd2650f2e0086d0d
40,878
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: Number of samples for each state-action block. """ dist = collections.defaultdict(lambda: 0) for transition in experience: key = get_block(transition.state, transition.reward, transition.next_state) dist[key] += 1 dist = dict(dist) return dist
6dcba0e714d9d98a530c16fcfa12679980b46871
40,881
import math def cost_to_time(cost, avg_seek_time=8, avg_latency=4): """ Converts a disk I/O metric to a milliseconds. :param cost: The disk I/O metric to convert. :param avg_seek_time: The average seek time in milliseconds. :param avg_latency: The average latency in milliseconds. :return: A disk I/O in milliseconds. """ return int( math.ceil( cost * ((avg_seek_time/1000) + (avg_latency/1000)) ) )
9ec86fef8b1b76260bbb2fe58b539d1dc8164b52
40,882
def VLerp(startv, endv, t=0.5): """ Linear interpolation between 2 vectors. """ if t <= 0.0 or t > 1.0: raise ValueError("E: t must satisfy 0<t<1, but is %f" % t) return (startv + (t * (endv - startv)))
c64dec9b0b966c0b25f6da00392239389e714a30
40,883
def get_next_deriv(xi, step, n, deriv, func): """ (d_theta/d_xi)i+1 = (d_theta/d_xi)i - ([ (2 /xi)i . (d_theta/d_xi)i ] + theta^n ) * d_xi """ return deriv - step * ((2./xi)*deriv + func**n)
9393131ff5872c8da2fc519611d6fc075ef4ffa5
40,885
def read_emojis(emojis): """ Returns a dictionary of emojis in the format of name: url. """ items = [] for k, v in emojis['emoji'].items(): if v.startswith('http'): items.append((k, v)) return items
b8e80fc07cc287f3eff547b111aaaa16989309ce
40,886
def _prepare_cov_source(cov_source): """ Prepare cov_source so that: --cov --cov=foobar is equivalent to --cov (cov_source=None) --cov=foo --cov=bar is equivalent to cov_source=['foo', 'bar'] """ return None if True in cov_source else [path for path in cov_source if path is not True]
8287d28c5d82568ee226d89250524b75e81b69d8
40,900
import time def last_hour(unixtime, hours=1): """Check if a given epochtime is within the last hour(s). Args: unixtime: epoch time hours (int): number of hours Returns: True/False """ seconds = hours * 3600 # sometimes bash histories do not contain the `time` column return int(time.time()) - int(unixtime) <= seconds if unixtime else False
1ce3ddb73f0316cf36979c1ee7f1269ae55d0d4c
40,904
def format_stats(stats): """Given a dictionary following this layout: { 'encoded:label': 'Encoded', 'encoded:value': 'Yes', 'encoded:description': 'Indicates if the column is encoded', 'encoded:include': True, 'size:label': 'Size', 'size:value': 128, 'size:description': 'Size of the table in MB', 'size:include': True, } format_stats will convert the dict into this structure: { 'encoded': { 'id': 'encoded', 'label': 'Encoded', 'value': 'Yes', 'description': 'Indicates if the column is encoded', 'include': True }, 'size': { 'id': 'size', 'label': 'Size', 'value': 128, 'description': 'Size of the table in MB', 'include': True } } """ stats_collector = {} for stat_key, stat_value in stats.items(): stat_id, stat_field = stat_key.split(":") stats_collector.setdefault(stat_id, {"id": stat_id}) stats_collector[stat_id][stat_field] = stat_value # strip out all the stats we don't want stats_collector = { stat_id: stats for stat_id, stats in stats_collector.items() if stats.get('include', False) } # we always have a 'has_stats' field, it's never included has_stats = { 'id': 'has_stats', 'label': 'Has Stats?', 'value': len(stats_collector) > 0, 'description': 'Indicates whether there are statistics for this table', 'include': False, } stats_collector['has_stats'] = has_stats return stats_collector
38b0f19f216d85f57c48a2e4b35a00dfa784d962
40,907
def get_customer_events(customerId, transcript): """ Get all the customer event rows from transcript dataframe Parameters ---------- customerId: Customer Id. transcript : The transcript dataframe containing events of all customers Returns ------- A dataframe with only rows for customer Id """ return transcript[transcript.person == customerId]
bf925440e1f43fe715f498e824ebf98180a23858
40,916
def get_valid_step(current_step: int, max_step: int) -> int: """ Checks if the current step is within boundaries and returns a corrected step. :param current_step: The current step to check. :param max_step: The maximum allowed step. :return: A corrected step between 1 and the maximum step. """ if current_step < 1: current_step = 1 elif current_step > max_step: current_step = max_step return current_step
aa668ef490bce37ac890c767b604e14f4b5d5ed9
40,920
def phaseplot_values(species): """ A convenience function to get a dictionary of values, to allow generalization of the PhasePlot class. The keys you can pull for phase plots are `x`, `v_x`, `v_y` and `v_z`. Parameters ---------- species : Species A species to draw data from Returns ------- A dictionary of phase plot values. """ return {"x": species.position_history, "v_x": species.velocity_history[:, :, 0], "v_y": species.velocity_history[:, :, 1], "v_z": species.velocity_history[:, :, 2], }
9b7458eb4634bbd7e6b337ecadc0a3db20911d45
40,925
def get_pagination(current_page_number, total_number_pages): """ Generate a pagination dictionary given a page number :param current_page_number: current page to paginate :param total_number_pages: total number of pages in the current model :return: dictionary of pagination """ previous_page = current_page_number - 1 next_page = current_page_number + 1 displayed_previous_page = None displayed_next_page = None if previous_page > 0: displayed_previous_page = previous_page if next_page < total_number_pages: displayed_next_page = next_page return { "first-page": 0, "previous-page": displayed_previous_page, "current-page": current_page_number, "next-page": displayed_next_page, "last-page": total_number_pages }
cbe5052fead77f1b034452841ae2468373cd4860
40,926
def assort_values(d): """ Collect every values stored in dictionary, then return them as a set :param d: :return: """ values = set() for key in d.keys(): values |= set(d[key]) return values
b9cf4a705d92aa414bd38e05204764b71bf2e683
40,928
import struct def read_vary(stream, data_size_type="B"): """! @brief Read variable length data from stream. @param stream Data stream. @param data_size_type Type of data size in Python's struct module representation. @return Data in byte array. """ # Read data size data_size_size = struct.calcsize(data_size_type) data_size = struct.unpack(data_size_type, stream.read(data_size_size))[0] # Read data return bytearray(stream.read(data_size))
9aa8a29470dad880b3f9b718a34c80eb28e2110e
40,931
from typing import Optional from enum import Enum def enum_parse(enum_cls: type, value: str) -> Optional[Enum]: """Try to parse a string value to an Enum member.""" if not issubclass(enum_cls, Enum): raise TypeError("Can only be used with classes derived from enum.Enum.") if value in enum_cls.__members__: return enum_cls.__members__[value] val_lc = value.casefold() val_map = {name.casefold(): name for name in enum_cls.__members__} if val_lc in val_map: return enum_cls.__members__[val_map[val_lc]] return None
f932e9d941daed3a970273c91a2d45abf0261e17
40,932
def strip_trailing_zero(value): """Like builtin "floatformat" but strips trailing zeros from the right (12.5 does not become 12.50)""" value = str(value) if "." in value: return value.rstrip("0").rstrip(".") return value
201c3ee4014db53a613d23131f8d4caad4cab638
40,933
def get_company(company_id, company_dict): """ Get the entry for a key from the company table """ return company_dict[company_id]
b2f682cf702dbd6877e46cf98b106b9e058fe4fb
40,936
def find_list_index(a_list, item): """ Finds the index of an item in a list. :param a_list: A list to find the index in. :type a_list: list :param item: The item to find the index for. :type item: str :return: The index of the item, or None if not in the list. :rtype: int | None """ if item in a_list: for i, value in enumerate(a_list): if value == item: return i
c9eb862b4af3eb113cca9ee55edda05b9fbfa8fe
40,940
def horizontal_flip(img): """Flip the image along the horizontal axis.""" return img[:, ::-1, :]
7aa0defa82efc835848f5f8d2b73191d63476a74
40,944
def clip_zero_formatter(tick_val, tick_pos): """Tick formatter that returns empty string for zero values.""" if tick_val == 0: return '' return tick_val
263cd9104f8f8e2332c55454e3fee274afe2ec4a
40,945
def uri_scheme_behind_proxy(request, url): """ Fix uris with forwarded protocol. When behind a proxy, django is reached in http, so generated urls are using http too. """ if request.META.get("HTTP_X_FORWARDED_PROTO", "http") == "https": url = url.replace("http:", "https:", 1) return url
873ac1c70627fc8e8dd0cb2b86dec99246bb9344
40,949
def remove_last_cycles_from_summary(s, last=None): """Remove last rows after given cycle number """ if last is not None: s = s.loc[s.index <= last, :] return s
811c73cce5d107a6a3c8fcae71c320c548ee6755
40,952
def list_all_regions(session): """Returns all regions where Lambda is currently supported""" return session.get_available_regions("lambda")
6368a3a357826f49978a06705270bc0124f64b0e
40,958
def get_center_indices(data, centers): """ Outputs the indices of the given centroids in the original dataset. In case multiple similar arrays are present in the dataset, the first match is returned. Required since K++ initializer outputs the actual centroid arrays while the kmedoids implementation needs indices. data: input matrix, list of arrays centroids: list of centroid arrays """ indices = list() for medoid in centers: indices.append([i for i, m in enumerate(data) if list(m) == list(medoid)][0]) return indices
78521413a8272a6fb6ce4dcd69b0b7418b937efa
40,968
async def get_pr_for_commit(gh, sha): """Find the PR containing the specific commit hash.""" prs_for_commit = await gh.getitem( f"/search/issues?q=type:pr+repo:python/cpython+sha:{sha}" ) if prs_for_commit["total_count"] > 0: # there should only be one return prs_for_commit["items"][0] return None
c8abfbc613748d88b224db2523b15535169da118
40,969
def underlying_function(thing): """Original function underlying a distribution wrapper.""" return getattr(thing, '__wrapped__', thing)
c83ce77b08b1eec84f13b9ba439203fcc045f098
40,972
def get_factor(units, unit_id): """ Returns the factor of a Unit-Config """ if not units: return None for unit in units: if unit.id == unit_id: if unit.to_base_function: return unit.to_base_function return unit.factor
c941556cba4baa08569c89c9c90edc5f620b5346
40,973
def write(scope, filename, lines, mode=['a']): """ Writes the given string into the given file. The following modes are supported: - 'a': Append to the file if it already exists. - 'w': Replace the file if it already exists. :type filename: string :param filename: A filename. :type lines: string :param lines: The data that is written into the file. :type mode: string :param mode: Any of the above listed modes. """ with open(filename[0], mode[0]) as fp: fp.writelines(['%s\n' % line.rstrip() for line in lines]) return True
4c5b905dabd35211a95d6af1ea82967a8ae6ae44
40,974
def get_direction_per_spike(df, cells, value_query, threshold=1): """ For a list of cells in a dataframe, return a list of values that are associated with spiking activity. :param df: Dataframe containing the spiking activity, and the values to be queried :param cells: List of cells (dataframe column headings) :param value_query: Dataframe column heading containing values :param threshold: Spiking threshold to be reached. Default: 1 spike per bin :return: List of values, and their weights (if there are >1 spike per temporal bin) """ value_list = [] weights = [] for cell in cells: values = df[value_query][(df[cell] >= threshold)] weights_cell = df[cell][(df[cell] >= threshold)] value_list.append(values) weights.append(weights_cell) return value_list, weights
18ebb4992df35b58106bbe85b883c7a13e8ff73f
40,976
def calculate(power): """Returns the sum of the digits of the number 2 to the power of the specified number""" answer = sum(list(map(int, str((2 ** power))))) return answer
5f0146e2c885c8c4636a6765a2b8e567e758928a
40,981
from bs4 import BeautifulSoup def is_html_text(txt): """ Check is input text is html or not Args: txt (str): input text Returns: bool: Returns True if html else False. """ return bool( BeautifulSoup(txt, "html.parser").find() )
1fb303e79bf1fd8773bc4cc03aaee304e9987aca
40,987
import random def mod_hosts_map(cloud_map, n, **kwargs): """ Selects n random hosts for the given stack and modifies/adds the map entry for those hosts with the kwargs. """ population = cloud_map.keys() # randomly select n hosts hosts = random.sample(population, n) # modify the hosts for host in hosts: cloud_map[host].update(kwargs) return cloud_map
87f766df9701a9da4988aae0ac272cd32c31b011
40,988
def dist(v1, v2): """ distance between two vectors. """ d = ((v2.x - v1.x)**2 + (v2.y - v1.y)**2) ** 0.5 return d
d06b3fb6543a1531d71db7345912153008e7e7d1
40,990
def array_shape(x) -> tuple[int, ...]: """Return the shape of 'x'.""" try: return tuple(map(int, x.shape)) except AttributeError: raise TypeError(f"No array shape defined for type {type(x)}")
efceb1a84ff05b94d2aa2e89c7956a96e4337090
40,995
def reset_slider(modal_open, selected_confidence): """ Reset the confidence slider range value to [0, 60] after closing the modal component. Parameters ---------- modal_open : bool A boolean that describes if the modal component is open or not selected_confidence : list of float The selected minimum and maximum values of the confidence slider Returns ------- list of float The default minimum and maximum values of the confidence slider """ # The modal window is closed so reset the slider values. if not modal_open: return [0, 60] # The modal window is open so return the current slider values. return selected_confidence
e6a43415eb56e8a77ef8cb3a1b58f71e4bf9443c
40,996
def get_type_check(expected_type): """ Any -> (Any -> bool) :param expected_type: type that will be used in the generated boolean check :return: a function that will do a boolean check against new types """ return lambda x: type(x) is expected_type
3e16e7fdf7461702cef4835d0bcfb2ed4131dac8
40,998
def fmt(x, pos): """ Format color bar labels """ if abs(x) > 1e4 or (abs(x) < 1e-2 and abs(x) > 0): a, b = f"{x:.2e}".split("e") b = int(b) return fr"${a} \cdot 10^{{{b}}}$" elif abs(x) > 1e2 or (float(abs(x))).is_integer(): return fr"${int(x):d}$" elif abs(x) > 1e1: return fr"${x:.1f}$" elif abs(x) == 0.0: return fr"${x:.1f}$" else: return fr"${x:.2f}$"
02e5c2ecbcbfcd50d40b06ee7792275aa4e32ae3
41,000
def is_binarystring(s): """Return true if an object is a binary string (not unicode)""" return isinstance(s, bytes)
9d4950b7c11b4055460236076200c13a6d51127a
41,001
def is_superset(token, tokens): """If a token is a superset of another one, don't include it.""" for other in tokens: if other == token: continue if other in token: return True return False
c9530f43ab9f9c123b3cff10b043376a280c57f5
41,002
import torch def mu_inverse(y): """ Inverse operation of mu-law transform for 16-bit integers. """ assert y.min() >= -1 and y.max() <= 1 return torch.sign(y) / 32768. * ((1 + 32768.) ** torch.abs(y) - 1)
d4af6953e6770d52597cf49e40bda1abbbbf057f
41,005
def spherical(h, r, sill, nugget=0): """ Spherical variogram model function. Calculates the dependent variable for a given lag (h). The nugget (b) defaults to be 0. Parameters ---------- h : float The lag at which the dependent variable is calculated at. r : float Effective range of autocorrelation. sill : float The sill of the variogram, where the semivariance begins to saturate. nugget : float, default=0 The nugget of the variogram. This is the value of independent variable at the distance of zero. Returns ------- gamma : numpy float Coefficients that describe effective range of spatial autocorrelation """ a = r / 1. if h <= r: return nugget + sill * ((1.5 * (h / a)) - (0.5 * ((h / a) ** 3.0))) else: return nugget + sill
074575957faf3a047c649fa31e6f0cc4ff7c4fdf
41,011
def get_from_session(request): """ Get user from request's session. """ return request.environ['beaker.session'].get('user')
30ad13274797fe3cb183ae1a11e6d07fa83fdf12
41,014
def S_convolute_values(_data_list, _transformer): """ Returns new data samples where values are transformed by transformer values. """ c_data = [] ds = len(_data_list) ts = len(_transformer) if ds != ts: return [] for i in range(ds): c_data.append(_data_list[i] + _transformer[i]) return c_data
c13a2750999e4aa144f610a905f96d845b6dbfcc
41,023
def get_valid_entries(board, row, col): """Checks valid entries for given cell in sudoku params : board : list (sudoku 9 X 9) : row : int : col : int returns : list (list of valid entries) """ used_entries = [0] * 10 used_entries[0] = 1 block_row = row // 3 block_col = col // 3 # Row and Column for m in range(9): used_entries[board[m][col]] = 1 used_entries[board[row][m]] = 1 # Square for m in range(3): for n in range(3): used_entries[board[m + block_row * 3][n + block_col * 3]] = 1 valid_entries = [i for i in range(1, 10) if used_entries[i] == 0] return valid_entries
4c9178cf4c859dbfc8957c19cbf0ba5f60df5786
41,027
import json def get_error_msg(exception) -> str: """ Parse the http response body to get relevant error message """ http_response_body = json.loads(exception.body.decode("utf-8")) exception_msg = http_response_body["message"] return exception_msg
6a98431a163ef6f6ec453182fe68b0ebdad41969
41,029
import six def _add_simplify(SingleActionType, BulkActionType): """ Add .simplify method to "Bulk" actions, which returns None for no rows, non-Bulk version for a single row, and the original action otherwise. """ if len(SingleActionType._fields) < 3: def get_first(self): return SingleActionType(self.table_id, self.row_ids[0]) else: def get_first(self): return SingleActionType(self.table_id, self.row_ids[0], { key: col[0] for key, col in six.iteritems(self.columns)}) def simplify(self): return None if not self.row_ids else (get_first(self) if len(self.row_ids) == 1 else self) BulkActionType.simplify = simplify
b67d24d63df7ee8de56cc9c47ae64150373fef3b
41,030
import json def read_inputs(jpath): """ read_inputs reads the input json file and stores it information in a dictionary Parameters ---------- jpath : string the input JSON file Returns ------- paths: dict Returns a dictionary of the json file """ with open(jpath) as file: paths = json.load(file) return paths
f3f91db4a60d8267df0b6a8ff0e3b722864c4055
41,031
def get_author_name(pypi_pkg): """Get author's name""" author_name = pypi_pkg["pypi_data"]["info"]["author"] return author_name
7c4ff935af36824a954605846d8a91bd927470c4
41,033
def _cleanup_frame(frame): """Rename and re-order columns.""" frame = frame.rename(columns={'Non- Hispanic white': 'White'}) frame = frame.reindex(['Asian', 'Black', 'Hispanic', 'White'], axis=1) return frame
7a25ee47e726314de57dc80d103a0189d3583024
41,037
def frmt_db_lctn(location): """ Formats the database location into nicer, more readable style :param location: sms deposit location :returns: Formated sms deposit location """ if location: return location.replace("_", " ").replace('-', ' ').title()
709b77c96eaa6aa43211445cc03279a28f84cd56
41,039
import pkg_resources def riptide_assets_dir() -> str: """ Path to the assets directory of riptide_lib. """ return pkg_resources.resource_filename('riptide', 'assets')
6c82e359d46bb6a82cbf01559574c07629acc23b
41,040
def signal_to_noise_limit_tag_from_signal_to_noise_limit(signal_to_noise_limit): """Generate a signal to noise limit tag, to customize phase names based on limiting the signal to noise ratio of the dataset being fitted. This changes the phase name 'phase_name' as follows: signal_to_noise_limit = None -> phase_name signal_to_noise_limit = 2 -> phase_name_snr_2 signal_to_noise_limit = 10 -> phase_name_snr_10 """ if signal_to_noise_limit is None: return "" else: return "__snr_" + str(signal_to_noise_limit)
b659aac99a4c728219818d8a5dc9f0fd14defcfd
41,046
import re def check_rules(rules, text_list, current_labels, fallback_label): """Finds rule's match in a text and returns list of labels to attach. If no rule matches returns False for match and fallback label will be attached. Args: rules (list): List of rules text_list (list): List of strings to search in current_labels (list): List of already attached labels fallback_label (str): Label to attach if no rule matches Returns: tuple: (match, labels) match (bool): True if any rule matches, False otherwise labels (list): List of labels to attach """ labels = set() match = False for rule in rules: for text in text_list: result = re.search(rule["pattern"], text) if result is not None: match = True if rule["label"] not in current_labels: labels.add(rule["label"]) # fallback label if not match: if fallback_label not in current_labels: labels.add(fallback_label) return match, labels
5a244532510e1898bef9a6f98d556e4c2e4b7b09
41,047
def Base_setTextValue(self, param): """ - name: input username setTextValue: text: | multi line text1 multi line text2 id: elementid1 """ txt = self.getvalue(param) if txt is None: raise Exception("text not set: param=%s" % (param)) elem = self.findmany2one(param) self.driver.execute_script("arguments[0].value = arguments[1];", elem, txt) return self.return_element(param, elem)
3030ed2241364002246f0c8c1fadf3c244658eff
41,048
from datetime import datetime def get_Mk_global(date): """ Based on the script BackRuns_OneSite_ByDay.ksh, calculating the globalMetMk value :param date: datetime object :return: integer representing the globalMetMk value """ seconds = int(datetime.strftime(date, "%s")) if seconds < 1136073600: return 0 elif seconds < 1230768000: return 3 elif seconds < 1257811200: return 4 elif seconds < 1268092800: return 5 elif seconds < 1367280000: return 6 elif seconds < 1405382400: return 7 elif seconds < 1440460800: return 8 elif seconds < 1499731200: return 9 else: return 10
c05e5dffb2219358147184be28123349071994fc
41,050
def tf_b(tf, _): """Boolean term frequency.""" return 1.0 if tf > 0.0 else 0.0
fddd407e4e04f9d3a890303431e462731a79cb3c
41,051
def dump_netrc(self): """Dump the class data in the format of a .netrc file.""" rep = '' for host in self.hosts.keys(): attrs = self.hosts[host] rep = rep + 'machine ' + host + '\n\tlogin ' + str(attrs[0]) + '\n' if attrs[1]: rep = rep + 'account ' + str(attrs[1]) rep = rep + '\tpassword ' + str(attrs[2]) + '\n' for macro in self.macros.keys(): rep = rep + 'macdef ' + macro + '\n' for line in self.macros[macro]: rep = rep + line rep = rep + '\n' return rep
08cb24400c7857006f2d2ae226a002485e0cc975
41,054
import torch def image_positional_encoding(shape): """Generates *per-channel* positional encodings for 2d images. The positional encoding is a Tensor of shape (N, 2*C, H, W) of (x, y) pixel coordinates scaled to be between -.5 and .5. Args: shape: NCHW shape of image for which to generate positional encodings. Returns: The positional encodings. """ n, c, h, w = shape zeros = torch.zeros(n, c, h, w) return torch.cat(( (torch.arange(-.5, .5, 1 / h)[None, None, :, None] + zeros), (torch.arange(-.5, .5, 1 / w)[None, None, None, :] + zeros)), dim=1)
b5187f9a97ade7fdad06d54e7a308e7ede8fcf9a
41,055
def list_keys(client, bucket, prefix, token=None): """ Recursive function used to retrieve all the object keys that match with a given prefix in the given S3 bucket. :param client: Client for the Amazon S3 service. :param bucket: The S3 bucket name. :param prefix: The prefix used for filtering. :param token: The continuation token returned by a previous call. :return: The found keys matching the prefix. """ keys = list() response = client.list_objects_v2( Bucket=bucket, Prefix=prefix, ContinuationToken=token ) if token else client.list_objects_v2( Bucket=bucket, Prefix=prefix ) if 'Contents' in response: for item in response['Contents']: keys.append(item['Key']) if 'NextContinuationToken' in response: keys += list_keys(client, bucket, prefix, response['NextContinuationToken']) return keys
3fa42dccf36dd3c2c8e76a71a1add0d28b0abe98
41,057
def RepairMissingData(time_series, first_value): """Given a list of time series value in a string format, replace missing values. If the first time point is missing, set it to first_value. This should be 1 if the log transform will be taken or 0 otherwise. If later time points are missing, set them to the previous observed time point. """ if time_series[0] == '': time_series[0] = first_value for i in range(1, len(time_series)): if time_series[i] == '': time_series[i] = time_series[i-1] return time_series
c2075048c662ecba2c37a95ea12513b105a05d16
41,059
def replace_stop(sequence): """ For a string, replace all '_' characters with 'X's Args: sequence (string) Returns: string: '_' characters replaced with 'X's """ return sequence.replace('_', 'X')
e4f0356b5b6b8c2101540c275215e0527ba909c4
41,060
from pathlib import Path def tmpfile(tmpdir, request): """Path to an empty temporary file.""" path = Path(tmpdir / 'temp.' + request.param) path.touch() return path
14194a46b8799f967a2ad6ac89cea3f4a3ddbddc
41,062
def test_function(a:int, b:int) -> int: """Adds two numbers together Args: a (int): Number 1 b (int): Number 2 Returns: int: Sum of both numbers """ return a + b
76d76743c02600f665b7c0ee28a08bc4e0784238
41,063
def check_abc_lec_status(output): """ Reads abc_lec output and determines if the files were equivelent and if there were errors when preforming lec. """ equivalent = None errored = False for line in output: if "Error: The network has no latches." in line: errored = True if line.startswith("Networks are NOT EQUIVALENT"): equivalent = False elif line.startswith("Networks are equivalent"): equivalent = True # Returns None if could not determine LEC status return equivalent, errored
5c2c17e91fed34d46bf911d404e16efe40adebdf
41,064
from typing import List from typing import Any import random def get_random_sample(items: List[Any], k: int) -> List[Any]: """ Thin wrapper around ``random.sample`` that takes the min of ``k`` and ``len(items)`` when sampling, so as to avoid a ``ValueError``. """ return random.sample(items, min(k, len(items)))
6fe2c5df8a2d8fa34a8f694e1108ce096c91dd4c
41,068
import math def projectionVolume(R1, R2, y1, y2): """Return the projected volume of a shell of radius R1->R2 onto an annulus on the sky of y1->y2. this is the integral: Int(y=y1,y2) Int(x=sqrt(R1^2-y^2),sqrt(R2^2-y^2)) 2*pi*y dx dy = Int(y=y1,y2) 2*pi*y*( sqrt(R2^2-y^2) - sqrt(R1^2-y^2) ) dy This is half the total volume (front only) """ def truncSqrt(x): if x > 0: return math.sqrt(x) else: return 0. p1 = truncSqrt(R1**2 - y2**2) p2 = truncSqrt(R1**2 - y1**2) p3 = truncSqrt(R2**2 - y2**2) p4 = truncSqrt(R2**2 - y1**2) return (2./3.) * math.pi * ((p1**3 - p2**3) + (p4**3 - p3**3))
fc09c74fdb6c80d76df1dd996357b5f8cd9eab83
41,075
def prepend(value: str, char="_"): """Prepend a string to a value if the value doesn't already start with that string Examples: >>> prepend('a') '_a' >>> prepend('_a') '_a' >>> prepend('my_str', '--') '--my_str' >>> prepend('---my_str', '-') '---my_str' """ if value.strip() == "": return "" return value if value.startswith(char) else f"{char}{value}"
05a82a8d6dbedb550069610ba47eb0a6f545f925
41,078
def _is_right(a, b, p): """given a line (defined by points a and b) and a point (p), return true if p is to the right of the line and false otherwise raises a ValueError if p lies is colinear with a and b """ ax, ay = a[0], a[1] bx, by = b[0], b[1] px, py = p[0], p[1] value = (bx - ax) * (py - ay) - (by - ay) * (px - ax) if value == 0: raise ValueError( "p is colinear with a and b, 'tis neither right nor left.") return value < 0
6d630eadc77587de60ef6aefff3cac01d9ba3191
41,085
def boundary(info, error, otype, oslots, rank): """Computes boundary data. For each slot, the nodes that start at that slot and the nodes that end at that slot are collected. Boundary data is used by the API functions `tf.core.locality.Locality.p`. and `tf.core.locality.Locality.n`. Parameters ---------- info: function Method to write informational messages to the console. error: function Method to write error messages to the console. otype: iterable The data of the *otype* feature. oslots: iterable The data of the *oslots* feature. rank: tuple The data of the *rank* precompute step. Returns ------- tuple * first: tuple of tuple The *n*-th member is the tuple of nodes that start at slot *n*, ordered in *reversed* canonical order (`tf.core.nodes`); * last: tuple of tuple The *n*-th member is the tuple of nodes that end at slot *n*, ordered in canonical order; Notes ----- !!! hint "why reversed canonical order?" Just for symmetry. """ (otype, maxSlot, maxNode, slotType) = otype oslots = oslots[0] firstSlotsD = {} lastSlotsD = {} for (node, slots) in enumerate(oslots): realNode = node + 1 + maxSlot firstSlotsD.setdefault(slots[0], []).append(realNode) lastSlotsD.setdefault(slots[-1], []).append(realNode) firstSlots = tuple( tuple(sorted(firstSlotsD.get(n, []), key=lambda node: -rank[node - 1])) # array("I", sorted(firstSlotsD.get(n, []), key=lambda node: -rank[node - 1])) for n in range(1, maxSlot + 1) ) lastSlots = tuple( tuple(sorted(lastSlotsD.get(n, []), key=lambda node: rank[node - 1])) # array("I", sorted(lastSlotsD.get(n, []), key=lambda node: rank[node - 1])) for n in range(1, maxSlot + 1) ) return (firstSlots, lastSlots)
b6927dc374fa638b42fb7e85742f074cba7ab88a
41,087
def standard_x(x_train, x_test=None): """ Data normalization (centering and variance normalization). :param x_train: training data :type x_train: np.ndarray :param x_test: testing data :type x_test: np.ndarray | None :return: normalized data :rtype: np.ndarray | (np.ndarray, np.ndarray) """ x_mean = x_train.mean(axis=0) x_std = x_train.std(axis=0) x_train1 = ((x_train - x_mean) / x_std).values if x_test is not None: x_test1 = ((x_test - x_mean) / x_std).values return x_train1, x_test1 return x_train1
181ae9a64b0ed444a4ef49f933cf1d2490763fe5
41,088
def _offset(offset, size): """Calculate the start of a member of `size` after `offset` within a struct.""" return ((size - (offset % size)) % size) + offset
97e277def96dab568d6f2cbe1fd7111d0cac6427
41,091
def precision_to_string(precision): """Translates a precision number (represented as Python string) into a descriptive string""" if precision == "16": return "Half" elif precision == "32": return "Single" elif precision == "64": return "Double" elif precision == "3232": return "ComplexSingle" elif precision == "6464": return "ComplexDouble" else: raise("Unknown precision: " + precision)
7f7d9b099091944d4fae1c007d83c375770a6b20
41,094
def get_ideological_topic_means(objective_topic_loc, objective_topic_scale, ideological_topic_loc, ideological_topic_scale): """Returns neutral and ideological topics from variational parameters. For each (k,v), we want to evaluate E[beta_kv], E[beta_kv * exp(eta_kv)], and E[beta_kv * exp(-eta_kv)], where the expectations are with respect to the variational distributions. Like the paper, beta refers to the obective topic and eta refers to the ideological topic. Dropping the indices and denoting by mu_b the objective topic location and sigma_b the objective topic scale, we have E[beta] = exp(mu + sigma_b^2 / 2), using the mean of a lognormal distribution. Denoting by mu_e the ideological topic location and sigma_e the ideological topic scale, we have E[beta * exp(eta)] = E[beta]E[exp(eta)] by the mean-field assumption. exp(eta) is lognormal distributed, so E[exp(eta)] = exp(mu_e + sigma_e^2 / 2). Thus, E[beta * exp(eta)] = exp(mu_b + mu_e + (sigma_b^2 + sigma_e^2) / 2). Finally, E[beta * exp(-eta)] = exp(mu_b - mu_e + (sigma_b^2 + sigma_e^2) / 2). Because we only care about the orderings of topics, we can drop the exponents from the means. Args: objective_topic_loc: Variational lognormal location parameter for the objective topic (beta). Should be shape [num_topics, num_words]. objective_topic_scale: Variational lognormal scale parameter for the objective topic (beta). Should be positive, with shape [num_topics, num_words]. ideological_topic_loc: Variational Gaussian location parameter for the ideological topic (eta). Should be shape [num_topics, num_words]. ideological_topic_scale: Variational Gaussian scale parameter for the ideological topic (eta). Should be positive, with shape [num_topics, num_words]. Returns: neutral_mean: A matrix with shape [num_topics, num_words] denoting the variational mean for the neutral topics. positive_mean: A matrix with shape [num_topics, num_words], denoting the variational mean for the ideological topics with an ideal point of +1. negative_mean: A matrix with shape [num_topics, num_words], denoting the variational mean for the ideological topics with an ideal point of -1. """ neutral_mean = objective_topic_loc + objective_topic_scale ** 2 / 2 positive_mean = (objective_topic_loc + ideological_topic_loc + (objective_topic_scale ** 2 + ideological_topic_scale ** 2) / 2) negative_mean = (objective_topic_loc - ideological_topic_loc + (objective_topic_scale ** 2 + ideological_topic_scale ** 2) / 2) return neutral_mean, positive_mean, negative_mean
3c0681e4b2834a34b0a0c97e5638bf0237d5272c
41,098
def get_gamma_function(gamma): """ :param gamma: desired factor gamma :return: Returns the lambda function of the gamma adjust operation """ return lambda x: pow(x / 255, gamma) * 255
48175cacc3c41fcac4da9dfdf7bc475c2f813bb6
41,099
import re def replace_initials(s): """ For a string s, find all occurrences of A. B. etc and replace them with A B etc :param s: :return: string with replacements made """ def repl_function(m): """ Helper function for re.sub """ return m.group(0)[0] t = re.sub('[A-Z]\.', repl_function, s) return t
da08a0d154e683b9e3ffa4ebd1332a8a855b05be
41,100
def me_check(pr, fa, ma, ref_count=False): """ Simplest possible way to check ME -1 for skipped sites ('.' or hom-ref in all samples 0 for consistent 1 for inconsistent """ pr = pr.split(':')[0].split('/') fa = fa.split(':')[0].split('/') ma = ma.split(':')[0].split('/') if '.' in pr + fa + ma: return -1 null = ["0", "0"] if not ref_count and pr == null and fa == null and ma == null: return -1 if pr[0] in fa and pr[1] in ma: return 0 if pr[1] in fa and pr[0] in ma: return 0 return 1
c133b42140c36c1ad5dcffa252dc939048493e6f
41,101
def get_model_queue_data(job): """ Formats the queued model data to return to the server :return: [(id:int, model_id:int, title:str, progress:int, max_progress:int), ...] """ return (job.get_id(), job.get_info().get("model_id"), job.get_title(), job.get_progress(), job.get_max_progress())
07aad5c6c5b20b66a4cad585069739b058b96d44
41,102
import random def roll_unweighted_die(weights=None): """Returns the result of an unweighted die. This uses a fair Args: weights: (integer array) a collection of the percentage chances each result of the die has. The number of sides is determined by the number of provided weights, and the sum of the weights must be 1.0 (100%) Raises: ValueError: Provided weights did not add up to 1 (100%) """ if weights is None or sum(weights) != 1: raise ValueError('Weight (%s) do not add to 1.0' % (weights)) # Roll the die fair_roll = random.random() # Which range did the selected value fall into? res = 0 for weight in weights: res = res + 1 if fair_roll <= weight: return res # If weights are [0.3, 0.2, 0.5], and 0.45 is rolled, removing the # weight from the roll allows us to compare it to that section the # range, compared to the previous possible values fair_roll -= weight # This can happen because of floating point inaccuracies. Just use the # last value if we leave the loop return res
34a8502677b21b59c380bf7fa62eab8aac67959a
41,108
import hashlib def md5checksum(afilepath): """ md5checksum Calculates the MD5 checksum for afilepath """ with open(afilepath, 'rb') as filehandler: calc_md5 = hashlib.md5() while True: data = filehandler.read(8192) if not data: break calc_md5.update(data) return calc_md5.hexdigest()
d8d4711e4657514672e455a3374e3ec400636259
41,109
def move_to_end(x, dim): """ Moves a specified dimension to the end. """ N = len(x.shape) if dim < 0: dim = N + dim permute_indices = list(range(N)) permute_indices.remove(dim) permute_indices.append(dim) return x.permute(permute_indices)
dad4bbceb2c6e5519afee2a3d94e5b06cec222bb
41,112
def _find_t(e, annotations): """ Given an "E" annotation from an .ann file, find the "T" annotation. Because "E" annotations can be nested, the search should be done on deeper levels. :param e: (string) the "E" annotation we want to find the target of. :param annotations: (dict) the dict of annotations. :return: the keys of "T" annotations this e annotation points to. """ e = e.split() keys = [] if len(e) > 1: targetkeys = [y for y in [x.split(":")[1] for x in e[1:]]] for key in targetkeys: if key[0] == "E": keys.append(annotations['E'][key[1:]].split()[0].split(":")[1]) if key[0] == "T": keys.append(key) return keys
b10c097ed98548d6a51447e3dd23140deef44818
41,117
def screenRegion(gfx, region=(0.0, 0.0, 1.0, 1.0)): """(gfx, 4-tuple of floats) -> (4-tuple of ints) Determine the absolute coordinates of a screen region from its relative coordinates (coordinates from 0.0 to 1.0) """ w, h = gfx.getSize() x1 = (w - 1) * region[0] y1 = (h - 1) * region[1] x2 = (w - 1) * region[2] y2 = (h - 1) * region[3] if type(w) == type(1): x1 = int(x1 + 0.5) y1 = int(y1 + 0.5) x2 = int(x2 + 0.5) y2 = int(y2 + 0.5) return (x1, y1, x2, y2)
35ef5e208bc1cd6279adaf2fef6b7dfc74830dfe
41,119
def split(iterable, function): """ Split an iterable into two lists according to test function :param iterable iterable: iterable of values to be split :param function function: decision function ``value => bool`` :returns: tuple( list with values for which function is `True`, list with values for which function is `False`,) Example _______ >>> split([1,2,3,4,5,6], lambda x: x<3) ([1, 2], [3, 4, 5, 6]) """ match = [] unmatch = [] for value in iterable: if function(value): match.append(value) else: unmatch.append(value) return match, unmatch
ede20fcc80bd126410a8417d1e91dee2e530c9af
41,121
def split_dictionary(output_dict): """Splits a dictionary into two lists for IDs and its full file paths Parameters ---------- output_dict : dictionary A dictionary with keys: 'id_llamado' and 'fullpath' Returns ------- Two lists Two lists of 'id_llamado' and 'fullpath' """ id_llamado = output_dict['id_llamado'] filenames = output_dict['fullpath'] return filenames, id_llamado
33958b60a0e7ca02595c688b1cf7642b6d8a56cb
41,125
def get_content(html_code): """ Separates the message section from the content section and returns the for further process :parameters html_code (str) html code of the downloaded :returns tuple (lists) the tuple returned contains two lists of strings. Each list item is a line """ message_list, content_list = [], [] for line in html_code.split('\n'): if line.startswith('#') and not line.endswith('#'): message_list.append(line) elif not line.endswith('#'): content_list.append(line) return message_list, content_list
debaab77f55d9328cd037d6fffc51c8a7f67758a
41,130
def read_words_from_file(path): """ Reads the content of a file and returns the content, split by space-character. :param path: The path of the file. :return: A list of words in this file. """ file_obj = open(path, "r") content = file_obj.read() return content.split(" ")
960ff1d54b0c37211fc06879a74124ff2e60872a
41,132
def should_trade(strategy, date, previous_trade_date): """Determines whether a trade is happening for the strategy.""" # We invest the whole value, so we can only trade once a day. if (previous_trade_date and previous_trade_date.replace(hour=0, minute=0, second=0) == date.replace(hour=0, minute=0, second=0)): return False # The strategy needs to be active. if strategy["action"] == "hold": return False # We need to know the stock price. if not strategy["price_at"] or not strategy["price_eod"]: return False return True
8c52eb554673bb0badff4a55c8e3a11cf9392a47
41,140
import random def form_batches(batch_size, idx): """Shuffles idx list into minibatches each of size batch_size""" idxs = [i for i in idx] random.shuffle(idxs) return [idxs[i:(i+batch_size)] for i in range(0,len(idxs),batch_size)]
2afdc93202f553b29a8f4c68dcf6e226816d9de0
41,145