content
stringlengths
39
9.28k
sha1
stringlengths
40
40
id
int64
8
710k
def string(obj): """ Returns the string representation of the object :param obj: any object :return: string """ return str(obj)
190ff4e0a1b75ff428119989fa60d657a641aa71
556,786
def align(items, attr, strength='weak'): """ Helper function to generate alignment constraints Parameters ---------- items: a list of rects to align. attr: which attribute to align. Returns ------- cons: list of constraints describing the alignment """ cons = [] for i in items[1:]: cons.append((getattr(items[0], attr) == getattr(i, attr)) | strength) return cons
2358285f1a4bd9b8f7d7464ee9ef41f9027cefe6
362,519
def status(prog_comp, obs_comp): """ Compute weighting factor representative of observation and program status. - 1.0 if observation and program have not been observed - 1.5 if program has been partially observed - 2.0 if observation has been partially observed Parameters ---------- prog_comp : float fraction of program completed. obs_comp : float fraction of observation completed. Returns ------- wstatus : float program status weighting factor """ if prog_comp > 0.0: wstatus = 1.5 if obs_comp > 0.0: wstatus = 2.0 else: wstatus = 1. return wstatus
cec07dca621ac402fe9260b12a063c9c0291c164
594,265
def filter_type(type): """Filter the type of the node.""" if "[" in type or "]" in type: return "arrayType" elif "(" in type or ")" in type: return "fnType" elif "int" in type: return "intType" elif "float" in type: return "floatType" else: return "type"
bf9e55f70d2f16c7ac67066659deb8b9822c8457
430,842
def mapValues( d, f ): """Return a new dict, with each value mapped by the given function""" return dict([ ( k, f( v ) ) for k, v in d.items() ])
0e0c7281be3a8b6e4c7725f879ae1636b4216e1d
499,467
def get_width(image): """get_width(image) -> integer width of the image (number of columns). Input image must be rectangular list of lists. The width is taken to be the length of the first row of pixels. If the image is empty, then the width is defined to be 0. """ if len(image) == 0: return 0 else: return len(image[0])
6532d7e543735e4a0991f52bc0c65d1cc820738f
107,896
import hashlib def is_placeholder_image(img_data): """ Checks for the placeholder image. If an imgur url is not valid (such as http//i.imgur.com/12345.jpg), imgur returns a blank placeholder image. @param: img_data (bytes) - bytes representing the image. @return: (boolean) True if placeholder image otherwise False """ sha256_placeholder = "9b5936f4006146e4e1e9025b474c02863c0b5614132ad40db4b925a10e8bfbb9" m = hashlib.sha256() m.update(img_data) return m.hexdigest() == sha256_placeholder
59d92b6cbde9e72d6de19a300ce90f684cf6ca69
661,562
from typing import Tuple import re def exception_matches(e: Exception, patterns: Tuple[Exception, ...]) -> bool: """ Whether an exception matches one of the pattern exceptions Parameters ---------- e: The exception to check patterns: Instances of an Exception type to catch, where ``str(exception_pattern)`` is a regex pattern to match against ``str(e)``. """ e_type = type(e) e_msg = str(e) for pattern in patterns: if issubclass(e_type, type(pattern)): if re.match(str(pattern), e_msg): return True return False
4c3515eb83c06c9749b85e567769a979405610df
216,954
def grow_capacity(capacity): # type: (int) -> int """Calculates new capacity based on given current capacity.""" if capacity < 8: return 8 return capacity * 2
d4b3cdcdfc97627428ce1ac430d7b8943db0abf8
475,352
def sanity_check_args(args): """ Check that command-line arguments are self-consistent. """ if args.weeks_ahead and (args.gw_start or args.gw_end): raise RuntimeError("Please only specify weeks_ahead OR gw_start/end") elif (args.gw_start and not args.gw_end) or (args.gw_end and not args.gw_start): raise RuntimeError("Need to specify both gw_start and gw_end") if args.num_free_transfers and args.num_free_transfers not in range(1, 3): raise RuntimeError("Number of free transfers must be 1 or 2") return True
da4d9333f79eb923dcadd2023a4756f562e35f7a
595,962
def contains_unquoted_target(x: str, quote: str = '"', target: str = '&') -> bool: """ Checks if ``target`` exists in ``x`` outside quotes (as defined by ``quote``). Principal use: from :func:`contains_unquoted_ampersand_dangerous_to_windows`. """ in_quote = False for c in x: if c == quote: in_quote = not in_quote elif c == target: if not in_quote: return True return False
2e66a4d06a1401407f62c938bd82fc1f42426247
91,286
def even_or_odd(num): """Returns the string even, odd, or unknown""" if num % 2 == 0: return "even" elif num % 2 == 1: return "odd" else: return "UNKNOWN"
7a7bacc139e426c6c08e32f6c2744037f26603a2
286,455
def copyAttrs(srcobj, destobj): """ Copies attributes from one HDF5 object to another, overwriting any conflicts """ for k in srcobj.attrs.keys(): destobj.attrs[k] = srcobj.attrs[k] return True
b4fc98a1f1c6076283d6782b8623a9fcd9d32450
183,022
def string_concatenation(a: str, b: str, c: str) -> str: """ Concatenate the strings given as parameter and return the concatenation :param a: parameter :param b: parameter :param c: parameter :return: string concatenation """ return a + b + c
8e503035facd9cee3d65790b36e9e8f2143e9d6d
341,353
def cat_and_mouse(x, y, z): """Hackerrank Problem: https://www.hackerrank.com/challenges/cats-and-a-mouse/problem Two cats and a mouse are at various positions on a line. You will be given their starting positions. Your task is to determine which cat will reach the mouse first, assuming the mouse doesn't move and the cats travel at equal speed. If the cats arrive at the same time, the mouse will be allowed to move and it will escape while they fight. Determine which cat catches the mouse of if the mouse escapes. If the distance between the mouse and the cats is the same, it escapes. Otherwise, the cat that is closer to the mouse will catch it first. Args: x (int): Cat A's position y (int): Cat B's position z (int): Mouse C's position Returns: string: The cat that catches the mouse or the mouse if it escapes """ if abs(z - x) == abs(z - y): return "Mouse C" elif abs(z - x) > abs(z - y): return "Cat B" else: return "Cat A"
3a4e7f3b60fd11d5488156d40c4968c7da81be45
283,820
import copy def merge_dicts(dict1, dict2): """Recursively merge two dictionaries. Values in dict2 override values in dict1. If dict1 and dict2 contain a dictionary as a value, this will call itself recursively to merge these dictionaries. This does not modify the input dictionaries (creates an internal copy). Parameters ---------- dict1: dict First dict. dict2: dict Second dict. Values in dict2 will override values from dict1 in case they share the same key. Returns ------- return_dict: dict Merged dictionaries. """ if not isinstance(dict1, dict): raise ValueError(f"Expecting dict1 to be dict, found {type(dict1)}.") if not isinstance(dict2, dict): raise ValueError(f"Expecting dict2 to be dict, found {type(dict2)}.") return_dict = copy.deepcopy(dict1) for k, v in dict2.items(): if k not in dict1: return_dict[k] = v else: if isinstance(v, dict) and isinstance(dict1[k], dict): return_dict[k] = merge_dicts(dict1[k], dict2[k]) else: return_dict[k] = dict2[k] return return_dict
b3dccd6301be21a096bb3d299793b4cf1461c3d9
699,686
def lower_keys(x): """Recursively make all keys lower-case""" if isinstance(x, list): return [lower_keys(v) for v in x] if isinstance(x, dict): return dict((k.lower(), lower_keys(v)) for k, v in x.items()) return x
f7c4537e09f3900c369a7c67a307b8b064e9e9ba
64,046
def merge_resources(resource1, resource2): """ Updates a copy of resource1 with resource2 values and returns the merged dictionary. Args: resource1: original resource resource2: resource to update resource1 Returns: dict: merged resource """ merged = resource1.copy() merged.update(resource2) return merged
e3b2f27e29fb773b119ad22ab89b297e0425a65d
695,178
def with_lock(lock, fn): """ Call fn with lock acquired. Guarantee that lock is released upon the return of fn. Returns the value returned by fn, or raises the exception raised by fn. (Lock can actually be anything responding to acquire() and release().) """ lock.acquire() try: return fn() finally: lock.release()
d8ed4c4a933483ac0aa5291c815b8afa64ca3957
665,311
def adjust_index_pair(index_pair, increment): """Returns pair of indices incremented by given number.""" return [i + increment for i in index_pair]
43968980998f6d12457e922c3c70d2ceba6d6b2e
14,750
import collections def product_counter_v3(products): """Get count of products in descending order.""" return collections.Counter(products)
22c57d50dc36d3235e6b8b642a4add95c9266687
704,745
def _get_union_pressures(pressures): """ get list of pressured where rates are defined for both mechanisms """ [pr1, pr2] = pressures return list(set(pr1) & set(pr2))
d25d2be0ce8703c79514ce46f6c86b911b2df19d
559,735
def create_test_results(suite_name, test_name, timestamp, command_args_printable, rc): """ Create a minimal test results object for test cases that did not produce their own :param suite_name: the name of the subdirectory for the suite this test was run in :param test_name: the name of the subdirectory for this test case :param timestamp: the timestamp when the test case was run :param command_args_printable: the command line args with sensitive args like password obscured :param rc: the return of the test (zero for success, non-zero for fail) :return: the results object that can be converted to JSON """ failed, passed = 0, 0 if rc == 0: passed = 1 else: failed = 1 results = { "ToolName": "Suite: {}, Test case: {}".format(suite_name, test_name), "Timestamp": { "DateTime": "{:%Y-%m-%dT%H:%M:%SZ}".format(timestamp) }, "CommandLineArgs": command_args_printable, "TestResults": { test_name: { "fail": failed, "pass": passed } }, "ServiceRoot": {} } return results
2af568e094b64a08a8b32afb702492e17c1f8fcb
689,474
import re def _parse_url_token(url_token): """Given activation token from url, parse into expected components.""" match = re.fullmatch( '^([0-9A-Za-z_\-]+)/([0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})$', url_token ) if match: return match.group(1), match.group(2) return None, None
48a3c4cd3aeada3b4c07fbfe6646e5d96441d920
235,815
def double(f): """ Return a function that applies f twice. f -- a function that takes one argument >>> def square(x): ... return x**2 >>> double(square)(2) 16 """ def repeated(x): return f(f(x)) return repeated
88e48a069a031590a4de8efa873bd4efec931bcd
340,804
def strip_prefix(prefix, string): """Strip prefix from a string if it exists. :param prefix: The prefix to strip. :param string: The string to process. """ if string.startswith(prefix): return string[len(prefix):] return string
07dd3cc154dde290d77bfbf4028e8be34179a128
676,253
def equals(field, value): """Return function where input ``field`` value is equal to ``value``""" return lambda x: x.get(field) == value
2b49e8b1c803e22cc9f236f35d6498f3bb2a0189
93,974
import toml def readToml(filename): """Read a single TOML configuration file, or return an empty dict if it doesn't exist. """ try: with open(filename, encoding='utf-8') as fp: return toml.load(fp) except OSError: return {} except toml.TomlDecodeError as err: raise RuntimeError( f'could not read NICOS config file at {filename!r},' f' please make sure it is valid TOML: {err}') from None
b5d0761015cd1fbeb94bfb771a7ac30fb2c35d3d
18,165
import tempfile def get_temp_file_name(format): """ Gets a temporary file name for the image Parameters ------------ format Format of the target image """ filename = tempfile.NamedTemporaryFile(suffix='.' + format) return filename.name
2ade2cbdb9f013c3e631290a50dd153f5cb28a74
505,320
import re def is_mixed_case(s): """ >>> is_mixed_case('HiThere') True >>> is_mixed_case('Hi There') True >>> is_mixed_case('hi there') False >>> is_mixed_case('h') False >>> is_mixed_case('H') False >>> is_mixed_case(None) False """ if not isinstance(s, (str,)): return False mo_lo = re.search(r'[a-z]', s) mo_hi = re.search(r'[A-Z]', s) if ((mo_lo is None) or (mo_hi is None)): return False return True
9f7244597fc0823e70db584f32d5e3d66df759b0
616,196
def _format_paths(paths, indent_level=1): """Format paths for inclusion in a script.""" separator = ',\n' + indent_level * ' ' return separator.join(paths)
aa51a16d1f9574d32272465f02de93744d896cea
190,762
from typing import OrderedDict def task_list_table_format(result): """Format task list as a table.""" table_output = [] for item in result: table_row = OrderedDict() table_row['Task Id'] = item['id'] table_row['State'] = item['state'] table_row['Exit Code'] = str(item['executionInfo']['exitCode']) \ if item['executionInfo'] else "" table_row['Node Id'] = item['nodeInfo']['nodeId'] if item['nodeInfo'] else "" table_row['Command Line'] = item['commandLine'] table_output.append(table_row) return table_output
9aad66622ad228f941e367d0b0e6b9e4db03f255
327,588
def get_object(arr, str_card): """ Get Card Object using its User Input string representation Args: arr: array of Card objects str_card: Card descriptor as described by user input, that is a 2 character string of Rank and Suit of the Card. For example, KH for King of Hearts. Returns: object pointer corresponding to string, from the arr """ # Make sure the str_card has only a RANK letter and SUIT letter # for example KH for King of Hearts. if len(str_card) != 2: return None for item in arr: if item.rank == str_card[0] and item.suit[0] == str_card[1]: return item return None
94666c1b6415a1b167f7d0b50591efe193cf5ca8
617,426
def _convert_native_shape_to_list(dims): """ Takes a list of `neuropod_native.Dimension` objects and converts to a list of python types """ out = [] for dim in dims: if dim.value == -2: # It's a symbol out.append(dim.symbol) elif dim.value == -1: # Any shape is okay out.append(None) else: out.append(dim.value) return out
dd2db666a19600a1bb7ad48cc78bf9765ec373d8
227,240
def _sumround(i): """sum all values in iterable `i`, and round the result to the 5th decimal place """ return round(sum([n for n in i if n]), 5)
ffa244c6be363efb80888186e4f19fc0b6fd0b5e
355,949
def last_scan_for_person(scan_set, person): """Return the last scan in the set for the given person.""" scans_found = [s for s in scan_set if s.person == person] return scans_found[-1]
5174d9255ce4b836e885e04f68a35fe13c11808e
514,778
def get_facts(cat_file="facts.txt"): """Returns a list of facts about cats from the cat file (one fact per line)""" with open(cat_file, "r") as cat_file: return [line for line in cat_file]
b2e9666bc1a833d25e73e61529c256f43bfb5c3b
44,498
def snapToGround(world, location, blueprint): """Mutates @location to have the same z-coordinate as the nearest waypoint in @world.""" waypoint = world.get_map().get_waypoint(location) # patch to avoid the spawn error issue with vehicles and walkers. z_offset = 0 if blueprint is not None and ("vehicle" in blueprint or "walker" in blueprint): z_offset = 0.5 location.z = waypoint.transform.location.z + z_offset return location
19c8cfe080aa96a01819f26c3bdcae8bb6a4c3be
233,913
import torch def evaluate_ece(confidences: torch.Tensor, true_labels: torch.Tensor, n_bins: int = 15) -> float: """ Args: confidences (Tensor): a tensor of shape [N, K] of predicted confidences. true_labels (Tensor): a tensor of shape [N,] of ground truth labels. n_bins (int): the number of bins used by the histrogram binning. Returns: ece (float): expected calibration error of predictions. """ # predicted labels and its confidences pred_confidences, pred_labels = torch.max(confidences, dim=1) # fixed binning (n_bins) ticks = torch.linspace(0, 1, n_bins + 1) bin_lowers = ticks[:-1] bin_uppers = ticks[ 1:] # compute ECE across bins accuracies = pred_labels.eq(true_labels) ece = torch.zeros(1, device=confidences.device) avg_accuracies = [] avg_confidences = [] for bin_lower, bin_upper in zip(bin_lowers, bin_uppers): in_bin = pred_confidences.gt( bin_lower.item() ) * pred_confidences.le( bin_upper.item() ) prop_in_bin = in_bin.float().mean() if prop_in_bin.item() > 0: accuracy_in_bin = accuracies[in_bin].float().mean() avg_confidence_in_bin = pred_confidences[in_bin].mean() ece += torch.abs( avg_confidence_in_bin - accuracy_in_bin ) * prop_in_bin avg_accuracies.append(accuracy_in_bin.item()) avg_confidences.append(avg_confidence_in_bin.item()) else: avg_accuracies.append(None) avg_confidences.append(None) return ece.item()
052ca3804019bd319ec9c6b7451c088aa47e9f62
572,257
def tracks_of_artist(df, column=str, artist=str): """ Calcula las caciones del artista seleccionado :param df: dataframe a analizar :param column: columna a selccionar con el nombre del artista :param artist: nombre del artista :return: int, la cantidad de canciones que tiene el artita """ # Seleccionamos al artista, como cada fila es una canción # contamos la filas para saber cuantas canciones tiene return len(df[df[column] == artist])
eb7b0b597fc8948d4efe5ae20ab59bcf49c74c1a
146,614
def filter_and_drop_frame(df): """ Select in-frame sequences and then drop that column. """ return df.query('frame_type == "In"').drop('frame_type', axis=1)
57745b684271772f00cf43e5eb5a6393b91fcb73
143,372
def get_last_month(month, year): """ Get last month of given month and year :param month: given month :param year: given year :return: last month and it's year """ if month == 1: last_month = 12 last_year = year - 1 else: last_month = month - 1 last_year = year return last_month, last_year
a78de7164ee652903712f02d8c71a262eeb2e4f4
585,779
def get_cmdb_detail(cmdb_details): """ Iterate over CMDB details from response and convert them into RiskSense context. :param cmdb_details: CMDB details from response :return: List of CMDB elements which includes required fields from resp. """ return [{ 'Order': cmdb_detail.get('order', ''), 'Key': cmdb_detail.get('key', ''), 'Value': cmdb_detail.get('value', ''), 'Label': cmdb_detail.get('label', '') } for cmdb_detail in cmdb_details]
aa2750b3754d2a776d847cfa22ff2b84f53bb351
20,932
def gcd(a,b): """Return greatest common divisor using Euclid's Algorithm.""" while b: a, b = b, a % b return a
59e7afdb04968c9d63ab0fce69fa75e2834eeebb
508,641
def nbr(b8, b12): """ Normalized Burn Ratio \ (García and Caselles, 1991. Named by Key and Benson, 1999). .. math:: NBR = (b8 - b12) / (b8 + b12) :param b8: NIR. :type b8: numpy.ndarray or float :param b12: SWIR 2. :type b12: numpy.ndarray or float :returns NBR: Index value .. Tip:: García, M. J. L., Caselles, V. 1991. Mapping burns and natural \ reforestation using thematic Mapper data. Geocarto International \ 6(1), 31-37. doi:10.1080/10106049109354290. Key, C.H., Benson, N., 1999. The Normalized Burn Ratio (NBR): A \ Landsat TM Radiometric Measure of Burn Severity. United States \ Geological Survey, Northern Rocky Mountain Science Center. """ NBR = (b8 - b12) / (b8 + b12) return NBR
7679148b18da62834f05c48e69536037f5ba40a3
386,338
def _get_caption(table): """ Get the caption of the associated wiki table. Parameters ---------- table: BeautifulSoup Returns ------- str """ caption_text = None caption = table.find("caption") if caption: caption_text = caption.text.strip() return caption_text
552925afb8e788e2f6cf03ff84ca1a4062f085ff
69,189
def nir_mean(msarr,nir_band=7): """ Calculate the mean of the (unmasked) values of the NIR (near infrared) band of an image array. The default `nir_band` value of 7 selects the NIR2 band in WorldView-2 imagery. If you're working with a different type of imagery, you will need figure out the appropriate value to use instead. Parameters ---------- msarr : numpy array (RxCxBands shape) The multispectral image array. See `OpticalRS.RasterDS` for more info. nir_band : int (Default value = 7) The default `nir_band` value of 7 selects the NIR2 band in WorldView-2 imagery. If you're working with a different type of imagery, you will need figure out the appropriate value to use instead. This is a zero indexed number (the first band is 0, not 1). Returns ------- float The mean radiance in the NIR band. """ return msarr[...,nir_band].mean()
7ba6ea8b7d51b8942a0597f2f89a05ecbee9f46e
709,610
def dict_to_string(d, order=[], exclude=[], entry_sep="_", kv_sep=""): """ Turn a dictionary into a string by concatenating all key and values together, separated by specified delimiters. d: a dictionary. It is expected that key and values are simple literals e.g., strings, float, integers, not structured objects. order: a list of keys in the dictionary. Keys with low indices appear first in the output. exclude: a list of keys to exclude entry_sep: separator between key-value entries (a string) kv_sep: separator between a key and its value """ # dict_keys = dict( (ordered_keys[i], i) for i in range(len(ordered_keys)) ) keys = set(d.keys()) - set(exclude) list_out = [] for k in order: if k in keys: entry = k + kv_sep + str(d[k]) list_out.append(entry) keys.discard(k) # process the rest of the keys for k in sorted(list(keys)): entry = k + kv_sep + str(d[k]) list_out.append(entry) s = entry_sep.join(list_out) return s
55a11507dc6dacbaadcfca736839a74ecc45622a
333,448
def parse_datetime_component(name, obj): """Parse datetime accessor arrays. The `datetime accessors`_ of :obj:`xarray.DataArray` objects are treated in semantique as a component of the temporal dimension. Parsing them includes adding :attr:`value_type <semantique.processor.structures.Cube.value_type>` and :attr:`value_label <semantique.processor.structures.Cube.value_labels>` properties as well as in some cases re-organize the values in the array. Parameters ----------- name : :obj:`str` Name of the datetime component. obj : :obj:`xarray.DataArray` Xarray datetime accessor. Returns -------- :obj:`xarray.DataArray` Parsed datetime accessor. .. _datetime accessors: https://xarray.pydata.org/en/stable/user-guide/time-series.html#datetime-components """ if name in ["dayofweek", "weekday"]: obj.sq.value_type = "ordinal" obj.sq.value_labels = { 0: "Monday", 1: "Tuesday", 2: "Wednesday", 3: "Thursday", 4: "Friday", 5: "Saturday", 6: "Sunday" } elif name == "month": obj.sq.value_type = "ordinal" obj.sq.value_labels = { 1: "January", 2: "February", 3: "March", 4: "April", 5: "May", 6: "June", 7: "July", 8: "August", 9: "September", 10: "October", 11: "November", 12: "December" } elif name == "quarter": obj.sq.value_type = "ordinal" obj.sq.value_labels = { 1: "January, February, March", 2: "May, April, June", 3: "July, August, September", 4: "October, November, December" } elif name == "season": # In xarray seasons get stored as strings. # We want to store them as integers instead. for k, v in zip(["MAM", "JJA", "SON", "DJF"], [1, 2, 3, 4]): obj = obj.str.replace(k, str(v)) obj = obj.astype(int) obj.sq.value_type = "ordinal" obj.sq.value_labels = { 1: "March, April, May", 2: "June, July, August", 3: "September, October, November", 4: "December, January, February" } else: obj.sq.value_type = "numerical" return obj
590f23d1acbba9cb568b9ee5fb30419cceeec954
193,060
def relu(x): """ ReLU function (maximum of input and zero). """ return (0 < x).if_else(x, 0)
773fc17688d00537f45d586a6f8ad316b29165e2
475,602
def get_combined_keys(dicts): """ >>> sorted(get_combined_keys([{'foo': 'egg'}, {'bar': 'spam'}])) ['bar', 'foo'] """ seen_keys = set() for dct in dicts: seen_keys.update(dct.keys()) return seen_keys
d737c034237959881ad6e46ddaf21617700fee1f
138,325
import pickle def load(infile): """ Load a pickle file. """ filename = infile.split('.')[0]+'.pickle' with open(filename, 'rb') as f: return pickle.load(f)
6d7b0e60620ba40f00976c91c1b7eeffa59451d3
457,151
from typing import Sequence def is_blank(value): """Returns True if a value is considered empty or blank.""" return value in (None, "") or (isinstance(value, Sequence) and len(value) == 0)
c5d7afba76a367b67a0586d5624b02de8ba9b904
478,851
import json def writeJson(file_name, data): """ Writes given dict data to given file_name as json. Args: file_name (string): Path to write data to. data (dict): dict to write to given file_name. Returns: (string): full path where json file is. """ with open(file_name, 'w') as open_file: json.dump(data, open_file, indent=4) return file_name
e17092d15ae1988ea9b34045834b23a8bef82219
569,665
def get_seasons(df): """ Changes months into season Parameters ---------- df : dataframe the forest fire dataframe Returns ------- Array Seasons the months are associated with """ seasons = ["NONE"] * len(df) for x in range(0, len(df)): m = df.loc[x, "month"] if m in ["dec", "jan", "feb"]: seasons[x] = "winter" elif m in ["mar", "apr", "may"]: seasons[x] = "spring" elif m in ["jun", "jul", "aug"]: seasons[x] = "summer" elif m in ["sep", "oct", "nov"]: seasons[x] = "fall" return seasons
bee62e066ee8439fb04ada471e3ebebe16d27365
102,015
def add_chars() -> bytes: """Returns list of all possible bytes for testing bad characters""" # bad_chars: \x00 chars = b"" chars += b"\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f" chars += b"\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f" chars += b"\x20\x21\x22\x23\x24\x25\x26\x27\x28\x29\x2a\x2b\x2c\x2d\x2e\x2f" chars += b"\x30\x31\x32\x33\x34\x35\x36\x37\x38\x39\x3a\x3b\x3c\x3d\x3e\x3f" chars += b"\x40\x41\x42\x43\x44\x45\x46\x47\x48\x49\x4a\x4b\x4c\x4d\x4e\x4f" chars += b"\x50\x51\x52\x53\x54\x55\x56\x57\x58\x59\x5a\x5b\x5c\x5d\x5e\x5f" chars += b"\x60\x61\x62\x63\x64\x65\x66\x67\x68\x69\x6a\x6b\x6c\x6d\x6e\x6f" chars += b"\x70\x71\x72\x73\x74\x75\x76\x77\x78\x79\x7a\x7b\x7c\x7d\x7e\x7f" chars += b"\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8a\x8b\x8c\x8d\x8e\x8f" chars += b"\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9a\x9b\x9c\x9d\x9e\x9f" chars += b"\xa0\xa1\xa2\xa3\xa4\xa5\xa6\xa7\xa8\xa9\xaa\xab\xac\xad\xae\xaf" chars += b"\xb0\xb1\xb2\xb3\xb4\xb5\xb6\xb7\xb8\xb9\xba\xbb\xbc\xbd\xbe\xbf" chars += b"\xc0\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf" chars += b"\xd0\xd1\xd2\xd3\xd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf" chars += b"\xe0\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef" chars += b"\xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff" return chars
cce8008085e6480642dad23b8e3a11728912d9ae
669,826
def skipdoc(func_or_class): """Instruct Sphinx not to generate documentation for ``func_or_class`` Parameters ---------- func_or_class : function or class Function or class not to document Returns ------- object Wrapped function or class """ func_or_class.plastid_skipdoc = True return func_or_class
cfb3b543ac104d3d803091459a59f22c19efb0fd
269,084
def read_group_list_text_file(group_list_text_file): """Read in the group-level analysis participant-session list text file.""" with open(group_list_text_file, "r") as f: group_list = f.readlines() # each item here includes both participant and session, and this also will # become the main ID column in the written design matrix CSV group_list = [str(x).rstrip("\n") for x in group_list if x != ""] return group_list
02cd5b76b6e3b2a7a30a6b0e277f48f2a1f313e7
239,442
def jsModuleDeclaration(name): """ Generate Javascript for a module declaration. """ var = '' if '.' not in name: var = 'var ' return '%s%s = {"__name__": "%s"};' % (var, name, name)
e53119d96fe87edbc7e52766b46c9ed2a33fa4ae
391,337
def _int_endf(s): """Convert string to int. Used for INTG records where blank entries indicate a 0. Parameters ---------- s : str Integer or spaces Returns ------- integer The number or 0 """ s = s.strip() return int(s) if s else 0
63150eed7d9f968d323bfc870b348191163e4401
235,217
def get_status(result): """ Given a CheckResult, return its status ID. """ return result.value["status"]
2f105326f02e514dfb8cae7edeff66bf1e15da6d
244,437
def find_containers(bag, bag_rules): """Find the bags that can contain a specified bag.""" allowed = [] for n, item in bag_rules.items(): if bag in item.keys(): allowed.append(n) return allowed
8c0d2dd33f2ea8ce8aa60c4ba6e0af005022754f
616,531
import json def get_local_facts_from_file(filename): """ Retrieve local facts from fact file Args: filename (str): local facts file Returns: dict: the retrieved facts """ try: with open(filename, 'r') as facts_file: local_facts = json.load(facts_file) except (ValueError, IOError): local_facts = {} return local_facts
b566fb622ed92f01fe04393ba49116756da84efa
429,106
def pentad_to_jday(pentad, pmin=0, day=3): """ Returns day of year for a pentad (indexed from pmin). Input day determines which day (1-5) in the pentad to return. Usage: jday = pentad_to_jday(pentad, pmin) """ if day not in range(1, 6): raise ValueError('Invalid day ' + str(day)) jday = 5*(pentad - pmin) + day return jday
6582c2710f2694a887b57c761586c5fda79601c7
399,050
def is_empty(node): """Checks whether the :code:`node` is empty.""" return node == []
08dca99334a08c979df52d48ce9ef1c767f544e6
50,514
import inspect def get_first_nondeprecated_class(cls): """Get the first non-deprecated class in class hierarchy. For internal use only, no backwards compatibility guarantees. Args: cls: A class which may be marked as a deprecated alias. Returns: First class in the given class's class hierarchy (traversed in MRO order) that is not a deprecated alias. """ for mro_class in inspect.getmro(cls): if mro_class.__name__ != '_NewDeprecatedClass': return mro_class
ecff9a233e6c591fa3d7f64e4c01f519e4f7d38b
275,805
def process_small_clause(graph, cycle, cut=True): """ Match a cycle if there is a small clause relationship: verb with outgoing edge ARG3/H to a preposition node, the preposition node has an outgoing edge ARG1/NEQ, and 1) an outgoing edge ARG2/NEQ, or 2) an outgoing edge ARG2/EQ to a noun; ARG2/NEQ or ARG2/EQ edge is removed if cut is set to True. :param graph: DmrsGraph object :param cycle: Set of Node objects in the cycle :param cut: If True and cycle is matched, the cycle is broken by removing a target edge :return: True if cycle is matched, otherwise False """ verb_nodes = [node for node in cycle if node.pos == 'v'] if len(verb_nodes) == 0: return False for verb_node in verb_nodes: outgoing_edges = [edge for edge in graph.get_outgoing_node_edges(verb_node) if edge.to_node in cycle] outgoing_labels = dict((edge.label, edge.to_node) for edge in outgoing_edges) if 'ARG3_H' not in outgoing_labels: continue prep_node = outgoing_labels['ARG3_H'] if prep_node.pos != 'p': continue prep_outgoing_labels = [edge.label for edge in graph.get_outgoing_node_edges(prep_node) if edge.to_node in cycle] if 'ARG1_NEQ' not in prep_outgoing_labels: continue if 'ARG2_NEQ' in outgoing_labels: if cut: arg2_neq_edge = [edge for edge in outgoing_edges if edge.label == 'ARG2_NEQ'][0] graph.edges.remove(arg2_neq_edge) return True if 'ARG2_EQ' in outgoing_labels and outgoing_labels['ARG2_EQ'].pos == 'n': if cut: arg2_eq_edge = [edge for edge in outgoing_edges if edge.label == 'ARG2_EQ'][0] graph.edges.remove(arg2_eq_edge) return True return False
4cc714838efc47b2de8c35821763249286039299
26,216
def parent_directory(path): """ Get parent directory. If root, return None "" => None "foo/" => "/" "foo/bar/" => "foo/" """ if path == '': return None prefix = '/'.join(path.split('/')[:-2]) if prefix != '': prefix += '/' return prefix
261943945531fc348c46c49f5d3081cbd815bfdb
21,083
def second(items): """ Gets the second item from a collection. """ return items[1]
fae12532263ff519f22dffe721eaebfb39186c08
356,953
def payload_string(nibble1, nibble2, nibble3, nibble4): """Returns the string representation of a payload.""" return'0x{:X}{:X}{:X}{:X}'.format(nibble1, nibble2, nibble3, nibble4)
aa80620ebcaec8bebb087fb953d065f9165cc2c0
47,804
def remove_comments(s): """ Examples -------- >>> code = ''' ... # comment 1 ... # comment 2 ... echo foo ... ''' >>> remove_comments(code) 'echo foo' """ return "\n".join(l for l in s.strip().split("\n") if not l.strip().startswith("#"))
1d3e1468c06263d01dd204c5ac89235a17f50972
3,840
import grp def getgid(group): """Get gid for group """ if type(group) is str: gid = grp.getgrnam(group).gr_gid return gid elif type(group) is int: gid = grp.getgrgid(group).gr_gid return gid
3ee267aecd13df48d655a566c9679aca6af1fb97
352,214
def get_task_id_from_name(task_name, project_tasks): """ get task_id from task_name """ result = None if project_tasks is not None: for task in project_tasks: if task["name"] == task_name: result = task["id"] if result is None: raise RuntimeError("Task %s not found." % (task_name)) return result
22a72889576dcec998f51a67b0229c0b43e05bf7
509,366
from typing import List import shlex def split(string: str) -> List[str]: """ Split string (which represents a command) into a list. This allows us to just copy/paste command prefixes without having to define a full list. """ return shlex.split(string)
360fceeba7d6280e27068f61d2420cfd9fbfbcc2
706,133
def get_txt_text_from_path(filepath : str) -> str: """Extract text in a txt file Arguments: filepath {str} -- path to the txt file Returns: str -- text in the txt file """ with open(filepath, 'r') as f: text = f.read() return text.strip()
f3c0318cb994144214bc5c61e4b52bc194c83ecd
309,592
def Mw_Mw_Generic(MagSize, MagError): """ Generic 1:1 conversion """ return (MagSize, MagError)
23fad6e7cd1af221be25066cf3ce3f3a644e193e
403,970
def is_scalar(x): """ >>> is_scalar(1) True >>> is_scalar(1.1) True >>> is_scalar([1, 2, 3]) False >>> is_scalar((1, 2, 3)) False >>> is_scalar({'a': 1}) False >>> is_scalar({1, 2, 3}) False >>> is_scalar('spam') True """ try: len(x) except TypeError: return True else: return isinstance(x, (str, bytes))
b8ee1536df04dda1e071a6e84dce66e4c576e42e
623,998
def rgb_to_hex(rgb): """ Translates a RGB color to its hex format. """ return '#%02x%02x%02x' % rgb
48ff35a4522e51b88e97800510ecc91e7d4840fa
136,495
def adamant_code(aiida_local_code_factory): """Get a adamant code. """ executable = '/home/fmoitzi/CLionProjects/mEMTO/cmake-build-release' \ '-gcc-8/kgrn/source_lsf/kgrn' adamant_code = aiida_local_code_factory(executable=executable, entry_point='adamant') return adamant_code
7a0069960d1c7b265695ff1bd3074ea6943c62cc
238,025
def get_x_y_values(tg, num_words=50): """ Gets a list of most frequently occurring words, with the specific number of occurrences :param tg: (TermGenerator) Object with the parsed sentences. :param num_words: (int) Number of words to be processed for the top occurring terms. :return: (List) List of the top N words in terms of occurrence and the respective occurrence number, """ # get the most frequently occurring words top_occurring_words = tg.term_count.most_common(num_words) x = [el[0] for el in top_occurring_words] y = [el[1] for el in top_occurring_words] return x, y
9584851d7261f4c5d8d279fa721fbe281e40e5b6
650,188
import re def increment(s): """ look for the last sequence of number(s) in a string and increment """ lastNum = re.compile(r'(?:[^\d]*(\d+)[^\d]*)+') m = lastNum.search(s) if m: next = str(int(m.group(1))+1) start, end = m.span(1) s = s[:max(end-len(next), start)] + next + s[end:] return s
918c72990f04fcc36884deeb1e1d5a846b86ea12
689,101
from typing import ChainMap def merge_dict(dicts): """Merge a list of dicts into a single dict """ return dict(ChainMap(*dicts))
fdc3d2301c787235f5c8252190b290d1a8368e2b
403,807
def avg(nums): """Returns the average (arithmetic mean) of a list of numbers""" return float(sum(nums)) / len(nums)
58fee328732c51e4355c29dd0489d163fdeaa4d1
327,028
def _find_file_type(file_names, extension): """ Returns files that end with the given extension from a list of file names. """ return [f for f in file_names if f.lower().endswith(extension)]
d18c84b1d76d25dc3e71cb70c4c5717b6a1ed6de
417,207
def get_assign_default_value_rule(variable_name: str, default_value_parameter_name: str): """ Returns a rule that sets a default value for a variable. @param variable_name: The name of the variable whose default should be set (as a string) @param default_value_parameter_name: The name of the parameter that stores the default values (as a string) @returns A rule that can be passed to a BuildAction(..., rule=<>) object. Example: mod.BuildGen_assign_default_value = BuildAction( mod.PREDETERMINED_GEN_BLD_YRS, rule=rule_assign_default_value("BuildGen", "gen_predetermined_cap") ) The code above will iterate over BuildGen for all the elements in PREDETERMINED_GEN_BLD_YRS and will set BuildGen's default value to the respective value in gen_predetermined_cap. """ def rule(m, *args): """ The rule that is returned by the parent function. This inner function is called by pyomo when pyomo runs the rule. """ # First retrieve the variable we want to set a default value for variable_to_set = getattr(m, variable_name) # Then retrieve the default value default_value = getattr(m, default_value_parameter_name)[args] # If the variable has the attribute, then we need to make two changes. if hasattr(variable_to_set, "scaled_var_name"): # First the default needs to be set on the _ScaledVariable not # the unscaled expression. variable_to_set = getattr(m, variable_to_set.scaled_var_name) # Second the default value needs to be scaled accordingly. default_value *= variable_to_set.scaling_factor # Set the variable to the default value variable_to_set[args] = default_value return rule
4423374980c32c18c8dc6f49eadcf058c49ac31b
617,270
def d_opt(param,value,extra_q=0): """ Create string "-D param=value" """ sym_q="" if extra_q==1: sym_q="\"" return("-D "+param+"="+sym_q+value+sym_q+" ")
04daa34d3eca92e60651e763ee08553acd9cf331
665,058
def strip_spaces(s): """ Strip excess spaces from a string """ return u" ".join([c for c in s.split(u' ') if c])
b3b02fb01887b48b6a94d0181cb777ccab6db1f5
446,200
def _non_executed_cells_count(cell_list): """The function takes a list of cells and returns the number of non-executed cells Args: cell_list(list): list of dictionary objects representing the notebook cells Returns: non_exec_cells: number of non-executed cells in the list The function is used in: - count_non-executed_cells(nb) - count_bottom_non-executed_cells(nb, bottom_size=4) """ non_exec_cells = 0 for cell in cell_list: if cell["cell_type"] == 'code': if cell['execution_count'] is None and cell['source'] != []: non_exec_cells = non_exec_cells + 1 # This is a not executed Python Cell containing actual code return non_exec_cells
06de43b45dd8880e4d193df6d4c8cd364f10dd29
445,735
import requests import json def get_invoice(amt: int, memo: str) -> str: """ Returns a Lightning Invoice from the Tallycoin API """ tallydata = {'type': 'fundraiser', 'id': 'zfxqtu', 'satoshi_amount': str(amt), 'payment_method': 'ln', 'message': memo} response = requests.post('https://api.tallyco.in/v1/payment/request/', data=tallydata).text dict = json.loads(response) return dict["lightning_pay_request"]
777d4d4fa39d91cf9ddace89716a1ae96acc5e80
114,069
def device_get_from_facts(module, device_name): """ Get device information from CVP facts. Parameters ---------- module : AnsibleModule Ansible module. device_name : string Hostname to search in facts. Returns ------- dict Device facts if found, else None. """ for device in module.params["cvp_facts"]["devices"]: if device["hostname"] == device_name: return device return None
55549b178f14f665f3c48a4e750be39ca70d61ab
650,143
def city_state(city, state, population=0): """Return a string representing a city-state pair.""" output_string = city.title() + ", " + state.title() if population: output_string += ' - population ' + str(population) return output_string
ae958598a57128cf36f63ff6bfb8181f9d07db31
22,028
import random def generate_name(start, markov_chain, max_words=2): """Generate a new town name, given a start syllable and a Markov chain. This function takes a single start syllable or a list of start syllables, one of which is then chosen randomly, and a corresponding Markov chain to generate a new fictional town name. The number of words in the name can optionally be passed in as an argument and defaults to 2 otherwise. Note that it is possible that the generated name already exists. To avoid that, one should check whether the name exists against the set of input names. """ while True: if isinstance(start, list): # If start is a list choose a syllable randomly next_syllable = random.choice(start) else: next_syllable = start # Initialise new name new_name = next_syllable while True: # Choose next syllable from the Markov chain next_syllable = random.choice(markov_chain[next_syllable]) # Return if end of word has been reached if next_syllable == 0: break else: new_name += next_syllable # Remove leading and trailing spaces new_name = new_name.strip() # Make sure name has less words than max_words, otherwise start over if len(new_name.split(" ")) <= max_words: break # Capitalise every word in the new name new_name = " ".join([word.capitalize() for word in new_name.split(" ")]) return new_name
dd40e0ad715bf8957d9bfcfc701997883766f7ca
691,775
def extract_vulnerabilities(debian_data, base_release='jessie'): """ Return a sequence of mappings for each existing combination of package and vulnerability from a mapping of Debian vulnerabilities data. """ package_vulnerabilities = [] for package_name, vulnerabilities in debian_data.items(): if not vulnerabilities or not package_name: continue for cve_id, details in vulnerabilities.items(): releases = details.get('releases') if not releases: continue release = releases.get(base_release) if not release: continue status = release.get('status') if status not in ('open', 'resolved'): continue # the latest version of this package in base_release version = release.get('repositories', {}).get(base_release, '') package_vulnerabilities.append({ 'package_name': package_name, 'cve_id': cve_id, 'description': details.get('description', ''), 'status': status, 'urgency': release.get('urgency', ''), 'version': version, 'fixed_version': release.get('fixed_version', '') }) return package_vulnerabilities
f22cc3507388b768363d4c4f2efd8054b5331113
169,771
def response(code, description): """ Decorates a function with a set of possible HTTP response codes that it can return. Args: code: The HTTP code (i.e 404) description: A human readable description """ def response_inner(function): if not hasattr(function, 'doc_responses'): setattr(function, 'doc_responses', []) function.doc_responses.append((code, description)) return function return response_inner
4912d09c2e7bb30ebba7c2f6989160be4d124e8d
117,007
def get_column_as_list(matrix, column_no): """ Retrieves a column from a matrix as a list """ column = [] num_rows = len(matrix) for row in range(num_rows): column.append(matrix[row][column_no]) return column
0f8f234fa9c68852d1c2f88049e2d0fea0df746d
682,637
def get_lemmas(synset): """ Look up and return all lemmas of a given synset. """ lemmas = synset.lemma_names() return lemmas
e24decdd2af6b65f5c495d9949ef8ff9aaa5c8da
83,928
def module_exists(course, module_name): """ Tests whether a module exists for a course Looks for an existing module of the same name. Returns the 'items_url' of the existing module or an empty string if it does not yet exists. """ for module in course.get_modules(): if module.name == module_name: return module.items_url return ''
cab676aa703120f6234492b93e19640b23e6bd49
360,050
from datetime import datetime def to_time(s): """ Captures time from image name and convert to time variable """ s = s.replace('/Users/lucasosouza/Documents/CarND/P3-final/IMG/center_', '') s = s.replace('.jpg', '') s = datetime.strptime(s, '%Y_%m_%d_%H_%M_%S_%f') return s
0225aff50916537e5c68607cc37c93d20dd76e1f
85,620
def _parse_endpoint_url(urlish): """ If given a URL, return the URL and None. If given a URL with a string and "::" prepended to it, return the URL and the prepended string. This is meant to give one a means to supply a region name via arguments and variables that normally only accept URLs. """ if '::' in urlish: region, url = urlish.split('::', 1) else: region = None url = urlish return url, region
bf3defcf9aeaca43d8aa8d7ba645cd0ba11b99f6
696,785
def port_in_rule(port, rule): """ Return True or False if port is covered by a security group rule. :param port: port to check :type port: int :param rule: security group rule to check :return: True or False if port is covered by a security group rule. :rtype: bool """ try: return port in range(rule["FromPort"], rule["ToPort"] + 1) except KeyError: return False
9e3f8ac5eb8d3506b5cf8bff06ed0b59a46400d8
320,839