content
stringlengths
39
9.28k
sha1
stringlengths
40
40
id
int64
8
710k
def subset_on_taxonomy(dataframe, taxa_level, name): """ Return only rows of the datframe where the value in column taxa_level matches the specified name. :param dataframe: Pandas DataFrame with columns like 'Kingdom', 'Phylum', 'Class', ... :param taxa_level: a taxagenetic label such as "Genus" or "Order" :param name: taxa_level name to match :return: subset of Pandas DataFrame matching the selection """ #print(dataframe.columns) return dataframe[dataframe[taxa_level] == name]
a1d72a96b277791d677e2bf81073ed7f4daa423f
17,021
def translation_existed(target_lang, translations): """ Checks if the translation for a given key existed """ if target_lang in translations: return True return False
dffc81fd875ba134a34b35c587a43ab9af019f01
497,129
def nii_to_json(nii_fname): """ Replace Nifti extension ('.nii.gz' or '.nii') with '.json' :param nii_fname: :return: json_fname """ if '.nii.gz' in nii_fname: json_fname = nii_fname.replace('.nii.gz', '.json') elif 'nii' in nii_fname: json_fname = nii_fname.replace('.nii', '.json') else: print('* Unknown extension for %s' % nii_fname) json_fname = nii_fname + '.json' return json_fname
bcd5e6d6c24943fe1e32e05dc36e9011ce24ecfc
592,095
from typing import Dict from typing import Any def get_test_data() -> Dict[str, Any]: """ Auxiliary method to return test data args. :return: Test data. """ return { "root": { "branch1": {"number": 23, "string": "value"}, "branch2": {"object": object(), "boolean": True} } }
78b162e8f6b2b1b8f82e73f55bf0bc5f3425e829
621,664
import random def calc_pi(N): """ Estimates pi using Monte-Carlo """ M = 0 # Initialize the counter for i in range(N): # Simulate impact coordinates x = random.uniform(-1, 1) y = random.uniform(-1, 1) # True if impact happens inside the circle if x**2 + y**2 < 1.0: M += 1 return 4 * M / N
cdd56bfa5544dcf9850b06ca33dc13de046723ea
459,842
def _append(so_far, item): """ Appends an item to all items in a list of lists. """ for sub_list in so_far: sub_list.append(item) return so_far
19163d1c02a3a248100e5c49e09a71068ac10ce7
541,978
def deleteItemByName(folderID, itemName, token, communicator): """Delete an item from a folder based on its name folderID -- ID of the folder. itemName -- Name of the item to delete. token -- Authentication token. communicator -- Midas session communicator. Returns a boolean indicating success or failure.""" folderChildren = communicator.folder_children(token, folderID) folder_children_items = folderChildren["items"] for item in folder_children_items: if item["name"] == itemName: communicator.delete_item(token, item["item_id"]) return True return False
688a6c4eba13e13ab497afb07cb42f3fcff4eade
540,044
def get_min_max_landmarks(feature: list): """ Get minimum and maximum landmarks from training set :param feature: list of features :return: min/max landmarks """ return feature[-6:-3], feature[-3:]
604c9b947d67795fe9cfec25159b410b6a0f3453
128,674
def cutoff_depth(d: int): """A cutoff function that searches to depth d.""" return lambda game, state, depth: depth > d
af7396a92f1cd234263e8448a6d1d22b56f4a12c
705,354
def optimal_tuning_ratio(mass_ratio): """ Returns optimal tuning ratio (TMD freq / Mode freq) per eqn (7) in Warburton & Ayorinde (1980) """ return 1 / (1 + mass_ratio)
0f6070465a7d2249bdc990f435848c4fc42cf87c
129,628
def getPolygonBounds(polygon): """ :param polygon:多边形上经纬度列表,eg:[(127.23,39.12),(126.23,36.45)] :return:多边形外切矩形四个点的经纬度坐标信息元组,eg:(max_lng,min_lng,max_lat, min_lat) """ # 边界上的坐标列表化 lng_lst = [x[0] for x in polygon] lat_lst = [x[1] for x in polygon] # 将坐标进行处理,获得四个角落的坐标,构造一个矩形网络 max_lng, min_lng = max(lng_lst), min(lng_lst) max_lat, min_lat = max(lat_lst), min(lat_lst) return max_lng, min_lng, max_lat, min_lat
d317abf703b03c7e23af853ccd40a49f192fdce2
427,375
def separate_pauli(sigma): """Function Extract coefficient and pauli word from a single QubitOperator 'sigma' Args: sigma (QubitOperator): Returns: coef (complex): coefficient pauli (str): pauli word """ tmp = str(sigma).replace("]", "").split("[") return complex(tmp[0]), tmp[1]
3ef0f1f65a78c91d42f093e1a3ef3c2fea92ceb1
200,802
def fill_in_the_blanks(noun, verb, adjective): """Fill in the blanks and returns a completed story.""" story = "I never knew anyone that hadn't {1} at least once in their life, \ except for {2}, old Aunt Polly. She never {1}, not even when that {0} came to \ town.".format(noun, verb, adjective) return story
648b315f73493c95ded815acd676740f271e8476
465,699
def _GetGroupByKey(entity, property_names): """Computes a key value that uniquely identifies the 'group' of an entity. Args: entity: The entity_pb.EntityProto for which to create the group key. property_names: The names of the properties in the group by clause. Returns: A hashable value that uniquely identifies the entity's 'group'. """ return frozenset((prop.name(), prop.value().SerializeToString()) for prop in entity.property_list() if prop.name() in property_names)
c886168258b18c5cfd57d9c596df8bfd7608532a
275,410
def file_extension(path): """Get the file extension of a path/filename.""" return path.split('/')[-1].split('.')[-1]
fe43378040e752d81df7c6775bb66b2b2c650ccf
381,004
def get_source(source, provider): """ Returns `source` if given, otherwise `provider` """ if not source: source = provider return source
d84f1543ae9f31cec8709c6b2fbdc4c2e18142d0
582,297
def reference_vector_argument(arg): """ Determines a reference argument, so as not to duplicate arrays of reals, vectors and row vectors, which usually have the same implementation. :param arg: argument :return: reference argument """ if arg in ("array[] real", "row_vector"): return "vector" return arg
693d96b305a892ddaf9f7f97fe6f5270e63a4c59
532,656
def _localize(dt, tzinfo): """ :return: A localized datetime :paramd dt: Naive datetime :param tzinfo: A pytz or python time zone object Attempts to localize the datetime using pytz if possible. Falls back to the builtin timezone handling otherwise. """ try: return tzinfo.localize(dt) except AttributeError: return dt.replace(tzinfo=tzinfo)
f68588195197b250d88a710f01196d6dd701c2d1
637,518
import collections def group_locations_by(locations, attribute): """ Group locations into a dictionary of lists based on an attribute. :param list locations: A list of locations. :param str attribute: Attribute name. """ grouped = collections.defaultdict(list) for location in locations: value = getattr(location, attribute) grouped[value].append(location) return grouped
3734eb79af2252f5e8d06d8d9fcb7322ed32ab0e
325,100
import types def _type_repr(obj): """Return the repr() of an object, special-casing types (internal helper). If obj is a type, we return a shorter version than the default type.__repr__, based on the module and qualified name, which is typically enough to uniquely identify a type. For everything else, we fall back on repr(obj). """ if isinstance(obj, type): if obj.__module__ == 'builtins': return obj.__qualname__ return f'{obj.__module__}.{obj.__qualname__}' if obj is ...: return('...') if isinstance(obj, types.FunctionType): return obj.__name__ return repr(obj)
1da7d3af3a2fa31e909c2c00f59e92af32dfbf4e
583,234
import json def validateInputParametersFile(filename): """ Validates an input (json) file to check if it contains the required keys. It does not validate the values of the keys. :param filename: Is a "Path" object that contains the input model parameters for the simulation. :return: A dictionary loaded from the input file. :raises ValueError: if a keyword is missing from the file. """ # Import locally the json package. # Open the file in "Read Only" mode. with open(filename, 'r') as input_file: # Load the model parameters. model_params = json.load(input_file) # Required keys in the json file. required_keys = ("Trees", "Well_No", "Output_Name", "IC_Filename", "Data_Filename", "Water_Content", "Environmental", "Soil_Properties", "Site_Information", "Simulation_Flags", "Hydrological_Model", "Hydraulic_Conductivity") # Check the keywords for membership in the file. for k in required_keys: # The order in here doesn't matter. if k not in model_params: raise ValueError(f" Key: {k}, is not given.") # _end_if_ # _end_for_ # Show message. print(" Model parameters are given correctly.") # _end_with_ # The dictionary will contain all the input parameters. return model_params
adfc97191c56f32d16f5723a3a905736e2337046
184,089
def split_song_header(song_header): """Split the song title in half, to retrieve its artist an name. Examples:: >>> song_header = 'Daughter:Run Lyrics' >>> split_song_header(song_header) (Daughter, Run) Args: song_header (string): song header / title to split Returns: tuple: artist name and song name. """ song_parts = song_header.split(':') artist_name = song_parts[0].strip() song_name = song_parts[-1].replace(' Lyrics', '').strip() return artist_name, song_name
d6299960264e41c23d2ae107ed242a043dd01a57
509,294
import logging def get_logger_name(mylogger) -> str: """Find the name of the logger provided. This is useful when configuring logging. """ ld = logging.Logger.manager.loggerDict # ld = logman.loggerDict # print("loggernames {}".format(ld.keys())) for k, v in ld.items(): if v == mylogger: return k return 'not found'
757fdbd620d4707bf892adac4332dafd13420420
440,358
def char_size(c): """Get `UTF8` char size.""" value = ord(c) if value <= 0xffff: return 1 elif value <= 0x10ffff: return 2 raise ValueError('Invalid code point')
dd14e4e340697ce74472eefa55700a74c7029dce
219,615
def __build_variable_string(translation, variables) -> str: """ Takes two parameters. - translation: the string that will be used as the format in the translation string. - variables: a list of variables that are used as replacement strings in the translation string. Returns the translation string with the variables formatted in the correct way for the stringsdict file. __build_variable_string("This is an ${example}", ["${example}"]) -> "This is an %#@__example__@" """ for variable in variables: translation = translation.replace(variable, f"%#@{variable}@") translation = translation.replace("${", "__").replace("}", "__") return translation
3482b6a7f0e8f89ad610e4421de05847c07e2281
262,059
def transformToRGB(lst): """ Change representation from 0-255 to 0-1, for triples value corresponding to RGB. """ def normToOne(x): return float(x)/255. return [(normToOne(x), normToOne(y), normToOne(z)) for x, y, z in lst]
ec83893155bfaca7cbbec8281bd84ccb8401a48f
75,050
def find_error_line(view, after): """Returns the first error after the given point.""" error_linenumbers = view.find_by_selector("constant.numeric.linenumber.error") if not error_linenumbers: return None for region in error_linenumbers: if region.begin() > after: return region # Go back to the first error. return error_linenumbers[0]
94ba3966c0355e4ca3cdb0d4636a70e4c0764d6c
596,018
def user_enabled(client, username): """ Checks if user is enabled. Takes: * keystone client object * username Returns bool """ return client.users.list(name=username)[0].enabled
d6f264a670e3ad21954e55354a8a8e49bf47d12d
381,727
from datetime import datetime def is_datetime(string): """ Check if a string can be converted to a datetime object. :param string: the string :return: True if the string can be converted to a datetime object, False otherwise """ try: datetime.strptime(string, "%Y-%m-%d %H.%M.%S") except Exception: return False return True
d1fa368d1b7ac45b85661bd4b72771d088c4ac6f
38,309
def square_summation(limit): """ Returns the summation of all squared natural numbers from 0 to limit Uses the short form summation formula for summation of squares :param limit: {int} :return: {int} """ return (limit * (limit + 1) * (2 * limit + 1)) // 6 if limit >= 0 else 0
e12830d76c48b23e08a3fcbc4de89ebf4f8dba21
447,828
import re import uuid def extract_uuid(filename): """ Given a filename containing a kernel, extract the uuid in the kernel name. Parameters ---------- filename : str The name of the kernel-...-json file with the connection info. Returns ------- uuid : str or None The extracted uuid, or None if not found. """ extracted = re.match( ".*kernel-([0-9a-f]{8}-?[0-9a-f]{4}-?4[0-9a-f]{3}-" "?[89ab][0-9a-f]{3}-?[0-9a-f]{12}).json", filename, ) if extracted is not None: return uuid.UUID(extracted.group(1)) else: return None
eccad7b6eaef3e0f16b531baec6bf701db4a960d
595,122
def write_lines(new_lines, lines, edit_index): """ Inserts new lines where specified :param new_lines: the new lines to be added :param lines: holds all the current lines of output html file :param edit_index: the index to insert new lines :return: new contents of output html file """ lines[edit_index:edit_index] = new_lines edit_index += len(new_lines) return lines, edit_index
e89d374b22aed26e57401d2529733b352baf3b8e
215,869
def get_ont_query(predicate): """Return an ontology query based on the linking predicate.""" ont_query = """ SELECT ?sub ?res WHERE { ?sub <""" + predicate + """> ?res . } """ return ont_query
11d377d4ac80af6cdafb09aebedbfeb16fbba8ab
512,742
def one_hot_to_int(x): """ Parameters ---------- x: torch.tensor; (N samples X C classes) Returns ------- torch.tensor; (N samples) """ return x.argmax(dim=1)
64315136e1db137bb7638b0125bffbb6f4e94185
325,756
def str_to_int(s): """Convert binary strings (starting with 0b), hex strings (starting with 0x), decimal strings to int""" if s.startswith("0x"): return int(s, 16) elif s.startswith("0b"): return int(s, 2) else: return int(s)
47ac2e7755d9a4d10b1e0712ad23aabb2c0489f5
48,547
def indent_string (s): """Put two spaces before each line in s""" lines = s.split ("\n") lines = [" " + i for i in lines] lines = [("" if i == " " else i) for i in lines] return "\n".join (lines)
3b8edef2d454aabb31afdeeab9417a6b487d3c0e
310,302
def ordinal(n): """Return the ordinal for an int, eg 1st, 2nd, 3rd. From user Gareth on codegolf.stackexchange.com """ suffixes = {1: "st", 2: "nd", 3: "rd"} return str(n) + suffixes.get(n % 10 * (n % 100 not in [11, 12, 13]), "th")
daa87b1b43d7c89348a9034aff389feb3b0b14d5
286,500
def lower_first(string): """Return a new string with the first letter capitalized.""" if len(string) > 0: return string[0].lower() + string[1:] else: return string
fc6fba78d15633f1ab21105fbd46883797444fb1
700,609
def bartz_sigma_sanchez(T_e, T_avg, w=0.6): """Correction factor for the Bartz equation. Reference: [1] M. Martinez-Sanchez, "Convective Heat Transfer: Reynolds Analogy," MIT 16.512 Lecture 7. https://ocw.mit.edu/courses/aeronautics-and-astronautics/16-512-rocket-propulsion-fall-2005/lecture-notes/lecture_7.pdf Arguments: T_e (scalar): Static temperature of the fluid external to the boundary layer [units: kelvin]. T_avg (scalar): Average temperature through the boundary layer, used to adjust the effective density and viscosity of the boundary layer. Martinez-Sanchez suggests :math:`T_{avg} = (T_e - T_w)/2` for flow around Mach 1. w (scalar): Viscosity is assumed to vary as :math:`T^w`. Martinez-Sanchez suggests :math:`w = 0.6` [units: dimensionless]. Returns: scalar: The Bartz equation correction factor :math:`\sigma`. """ return (T_e / T_avg)**(0.8 - 0.2 * w)
9230d56ae5b33836a39c9272ca4996aa89126792
424,639
def _generate_stack_status_path(stack_path): """ Given a path to the stack configuration template JSON file, generates a path to where the deployment status JSON will be stored after successful deployment of the stack. :param stack_path: Path to the stack config template JSON file :return: The path to the stack status file. >>> self._generate_stack_status_path('./stack.json') './stack.deployed.json' """ stack_status_insert = 'deployed' stack_path_split = stack_path.split('.') stack_path_split.insert(-1, stack_status_insert) return '.'.join(stack_path_split)
b0573148565e8cf338d4bc6877151cbe4186ebf5
58,509
def is_color(im): """Returns True if the image is a color image (3 channels) and false if not.""" return len(im.shape) == 3
d598571ea5315fff8912f1f08e8c469dc76f1b75
153,137
def mk_filter_by_unk_ratio(vocab, max_unk_ratio=0.0, is_tbptt=False): """Return a filter function that takes a sentence, and returns True if a sentence meet a criterion (unk ratio is below max). NOTE: each sentence contains a bos and an eos, which are excluded for calculating unk ratio. If is_tbptt is True, offset is changed to 1 (since each sentence only contains eos). """ if max_unk_ratio == 0.0: return lambda sent: True offset = 1 if is_tbptt else 2 def filter(sent): cnt = len([w for w in sent if not vocab.contains(w)]) return cnt / (len(sent) - offset) < max_unk_ratio return filter
113242f681c195819e3ccc827997a8ba1b92082f
560,735
def _jinja2_filter_icon_style(value): """Formats the icon style for templates""" return 'ok' if value else 'remove'
11486e9f53bda2e340d3ae262abbed16fdc3fdb5
171,978
import typing def convert_value(dtype: typing.Any, value: typing.Any, default: typing.Any = None) -> typing.Union[typing.Any, None]: """ Return the passed value in the specified value if it is not None and does not raise an Exception while converting. Returns the passed default if the conversion failed :param dtype: The datatype the value should be returned :param value: The value that should be converted :param default: The default Value that should be returned if the conversion failed :return: The converted value or the default passed value """ try: if value is None: return default return dtype(value) except Exception: return default
3fd02525daf5db4b8761b3af3746004db9459429
58,451
def get_reddit_posts(subreddits, limit, score, num_comments): """Collect submissions related data, including title, link, current score, the number of comments, etc. Params: ------- subreddits: list a list of praw.Reddit.subreddit instances limit: int maximum number of submissions per subreddit score: int the minimal threshold of *score* num_comments: int the minimal threshold of *number of comments* Return: ------- data: dict all the submissions related data """ data = {} for subreddit in subreddits: data[subreddit.display_name] = [] for submission in subreddit.hot(limit=limit): if (submission.stickied is False) and (submission.score >= score or submission.num_comments >= num_comments): post = {} post['title'] = submission.title post['shortlink'] = submission.shortlink post['score'] = submission.score post['num_comments'] = submission.num_comments data[subreddit.display_name].append(post) return data
664720609116cdd4512cec225b18fbb51a1e7369
614,656
def get_label2id(labels): """ Get label2id mapping based on labels Args: labels: list of labels. Return: label2id map """ return {v: str(k) for k, v in enumerate(labels)}
644b9ce55a3df43eb8c85ed8086b2d10dbcc6951
84,592
def select_text_color(r, g, b): """ Choose a suitable color for the inverse text style. :param r: The amount of red (an integer between 0 and 255). :param g: The amount of green (an integer between 0 and 255). :param b: The amount of blue (an integer between 0 and 255). :returns: A CSS color in hexadecimal notation (a string). In inverse mode the color that is normally used for the text is instead used for the background, however this can render the text unreadable. The purpose of :func:`select_text_color()` is to make an effort to select a suitable text color. Based on http://stackoverflow.com/a/3943023/112731. """ return '#000' if (r * 0.299 + g * 0.587 + b * 0.114) > 186 else '#FFF'
a8663b261c0d6ae087d08e8ecb67a77d51935b10
678,960
import torch def reduce_sign_any(input_tensor, dim=-1): """A logical or of the signs of a tensor along an axis. Args: input_tensor: Tensor<float> of any shape. axis: the axis along which we want to compute a logical or of the signs of the values. Returns: A Tensor<float>, which as the same shape as the input tensor, but without the axis on which we reduced. """ boolean_sign = torch.any( ((torch.sign(input_tensor) + 1) / 2.0).bool(), dim=dim ) return boolean_sign.type(input_tensor.dtype) * 2.0 - 1.0
72dde84d97a8744c880bd7bbc92cb020cbe0d156
575,253
def _transform_interval( interval, first_domain_start, first_domain_end, second_domain_start, second_domain_end ): """ Transform an interval from one domain to another. The interval should be within the first domain [first_domain_start, first_domain_end] For example, _transform_interval((3, 5), 0, 10, 100, 200) would return (130, 150) """ def transform_value(value): position = (value - first_domain_start) / (first_domain_end - first_domain_start) return position * (second_domain_end - second_domain_start) + second_domain_start return [transform_value(value) for value in interval]
c1743f605ec7093ed3ceb42193251c12339c3bc6
454,726
def get_diff(df, column1, column2): """Get the difference between two column values. Args: df: Pandas DataFrame. column1: First column. column2: Second column. Returns: Value of summed columns. Usage: df['item_quantity_vs_mean'] = get_diff(df, 'item_quantity', 'item_code_item_quantity_mean') """ return df[column1] - df[column2]
1fc5ec361cfdd28775257980c28b4924fdab4eeb
24,810
def mime_to_pltfrm(mime_string): """ Translates MIME types to platform names used by tng-cat. Returns: 5gtango|osm|onap """ pattern = ["5gtango", "osm", "onap"] for p in pattern: if p in str(mime_string).lower(): return p return None
05d424fb1371466f3372bf8b052a0cb97b7852a8
437,904
import textwrap def _format_doc(docstring, prefix): """Use textwrap to format a docstring for markdown.""" initial_indent = prefix # subsequent_indent = " " * len(prefix) subsequent_indent = " " * 2 block = docstring.split("\n") fmt_block = [] for line in block: line = textwrap.fill( line, initial_indent=initial_indent, subsequent_indent=subsequent_indent, width=len(subsequent_indent) + 80, ) initial_indent = subsequent_indent fmt_block.append(line) return "\n".join(fmt_block)
1bf2bf0ee35f9b6e345eb8c70355d0a86bf74290
636,567
def sum_bbox(bbox1, bbox2): """Summarizes two bounding boxes. The result will be bounding box which contains both provided bboxes. :type bbox1: list :param bbox1: first bounding box :type bbox2: list :param bbox2: second bounding box :rtype: list :return: new bounding box """ if not bbox1 or not bbox2: return bbox1 + bbox2 x0, y0, x1, y1 = bbox1 _x0, _y0, _x1, _y1 = bbox2 new_x0 = min(x0, _x0, x1, _x1) new_x1 = max(x0, _x0, x1, _x1) new_y0 = min(y0, _y0, y1, _y1) new_y1 = max(y0, _y0, y1, _y1) return [new_x0, new_y0, new_x1, new_y1]
83c0eddfe03e66843cbbc6c7de21be6688905087
87,956
def convert_variable(datatype, variable): """ Convert variable to number (float/int) Used for dataset metadata and for query string :param datatype: type to convert to :param variable: value of variable :return: converted variable :raises: ValueError """ try: if variable and datatype == "int": variable = int(variable) elif variable and datatype == "float": variable = float(variable) return variable except ValueError: raise
adaf06dde50a3667ee72000f5e346e41415ca2e7
234,302
def is_ebx(line): """Determines whether the line of code is a part of the rolling key update (EBX register). Args: line (AsmBlock): one asm instruction with its operands """ return (len(line.args) >= 1 and str(line.args[0]) in ["EBX", "BX", "BL"] and not line.name == "MOV")
76301b0ae8a5d96de2e8794e62487325ebddadab
469,773
def diff21(n: int) -> int: """Absolute difference between n and 21. Returns abs(n-21) if n <= 21 and abs(n-21) * 2 if n > 21. """ diff = abs(n - 21) if n > 21: return diff * 2 return diff
8b6638a586ff2bf14cce4781bf7da0b9ae20c527
391,702
def add_commas(number): """1234567890 ---> 1,234,567,890""" return "{:,}".format(number)
3db1b2c73b2a65367458155745ba9f27f3e88917
140,483
import pickle def load_object(pathname): """Load an object from disk using pickle. Parameters ---------- pathname : str Full path of the file where the object is stored. Returns ------- obj : any type Object loaded from disk. """ with open(pathname, 'rb') as fid: obj = pickle.load(fid) return obj
3780e8ba607c35253bc22fff158e8ef09ca6d66e
203,808
def get_user_attribute_default(attribute, ctx): """Return the default value for the given attribute of the user passed in the context. :param attribute: attribute for which to get the current value :param ctx: click context which should contain the selected user :return: user attribute default value if set, or None """ default = getattr(ctx.params['user'], attribute) # None or empty string means there is no default if not default: return None return default
1fd290a391f2a2fd2bccc8437ad6b355495cc576
351,450
def cgi2dict(form, linelist): """Convert the form from cgi.FieldStorage to a python dictionary""" params = {'linelist': linelist.value} for key in form.keys(): if key != 'linelist': params[key] = form[key].value return params
c935c8f3393439a6632cd4a70c7a684c3ce42a85
634,683
def apply_function_on_axis_dataframe(df, func, axis=0): """Apply a function on a row/column basis of a DataFrame. Args: df (pd.DataFrame): Dataframe. func (function): The function to apply. axis (int): The axis of application (0=columns, 1=rows). Returns: pd.DataFrame: Dataframe with the applied function. Examples: >>> df = pd.DataFrame(np.array(range(12)).reshape(4, 3), columns=list('abc')) >>> f = lambda x: x.max() - x.min() >>> apply_function_on_axis_dataframe(df, f, 1) 0 2 1 2 2 2 3 2 dtype: int64 >>> apply_function_on_axis_dataframe(df, f, 0) a 9 b 9 c 9 dtype: int64 """ return df.apply(func, axis)
631a9e3e62f8fc382f26450a9d9399842a544bda
596,522
import requests def _prepare(*args, **kwargs): """ Return a prepared Request. """ return requests.Request(*args, **kwargs).prepare()
5762d24e340483516ca5aaad8911e43572274f05
219,225
def leapdays(y1, y2): """Return number of leap years in range [y1, y2). Assume y1 <= y2.""" y1 -= 1 y2 -= 1 return (y2//4 - y1//4) - (y2//100 - y1//100) + (y2//400 - y1//400)
d66a6ee4633bdcb3719805f404e60adfe2a7fa6d
229,810
def rec_fact(num): """rec_fact(int) -> int Recursive function which takes an integer and computes the factorial. >>> rec_fact(4) # 4*3*2*1 = 24 24 """ if not isinstance(num, int): raise TypeError("Must be a positive int") if num == 0: return 1 return num * rec_fact(num - 1)
636b81145ac424c1d680bb95470c91773d37e7bd
592,776
def content_loss(P, X, layer): """ Defines the content loss contribution from two images at a specific layer. Reasoning: If the content of two images is the same the response of a given layer for each image should be the same. Note that additionally there is a 1 / image size factor which was not in the original paper """ p = P[layer] x = X[layer] # slight change to cost function with respect to paper, which makes it independent of image size M = p.shape[2] * p.shape[3] loss = (1./(2*M)) * ((x - p)**2).sum() return loss
40acaf3b1f447a98e73eed17536a406b138c9b56
398,276
def tf_sched(cur_epoch,epochs,final_tf_ratio): """ modified teacher forcing ratio according to epoch counts Args: cur_epoch: (int) current epoch epochs: (int) total epochs final_tf_ration: (float) smallest teacher forcing ratio Returns: teacher forcing ratio for current epoch """ thres=int(0.2*epochs) if cur_epoch<thres: tf_ratio=1 else: tf_ratio=final_tf_ratio+(epochs-cur_epoch)*(1-final_tf_ratio)/(epochs-thres) if tf_ratio>1: tf_ratio=1 elif tf_ratio<final_tf_ratio: tf_ratio=final_tf_ratio return tf_ratio
f24f5efb9f5d570d8d3f9abde4ca371b9ad24d5f
513,306
import yaml def load(stream, is_safe=True): """Converts a YAML document to a Python object. :param stream: the YAML document to convert into a Python object. Accepts a byte string, a Unicode string, an open binary file object, or an open text file object. :param is_safe: Turn off safe loading. True by default and only load standard YAML. This option can be turned off by passing ``is_safe=False`` if you need to load not only standard YAML tags or if you need to construct an arbitrary python object. Stream specifications: * An empty stream contains no documents. * Documents are separated with ``---``. * Documents may optionally end with ``...``. * A single document may or may not be marked with ``---``. Parses the given stream and returns a Python object constructed from the first document in the stream. If there are no documents in the stream, it returns None. """ yaml_loader = yaml.Loader if is_safe: if hasattr(yaml, 'CSafeLoader'): yaml_loader = yaml.CSafeLoader else: yaml_loader = yaml.SafeLoader return yaml.load(stream, yaml_loader)
ddb6d38f637aa38b70e647ff0566ae765408da29
418,017
def result_to_dict(res): """ :param res: :any:`sqlalchemy.engine.ResultProxy` :return: a list of dicts where each dict represents a row in the query where the key \ is the column name and the value is the value of that column. """ keys = list(res.keys()) return [dict(zip(keys, row)) for row in res]
9c93c1e23db07cf14f4b3a3f9e353368bdb28e16
426,127
def gpib_control_ren(library, session, mode): """Controls the state of the GPIB Remote Enable (REN) interface line, and optionally the remote/local state of the device. Corresponds to viGpibControlREN function of the VISA library. :param library: the visa library wrapped by ctypes. :param session: Unique logical identifier to a session. :param mode: Specifies the state of the REN line and optionally the device remote/local state. (Constants.GPIB_REN*) :return: return value of the library call. :rtype: :class:`pyvisa.constants.StatusCode` """ return library.viGpibControlREN(session, mode)
4d9fc21bb3bca7cbd98c94c064500d0ce319e5cc
683,409
def read_minisat_result(result_path): """Read the output from minisat. Returs one of: None -- empty file 'UNSAT' -- unsatisfiable result dict containing the assignment -- satisfiable result """ with open(result_path) as f: s = f.read().rstrip() head = s.split()[0] if len(s) == 0: return None if s.startswith('UNSAT'): return 'UNSAT' elif s.startswith('INDET'): return 'INDET' elif s.startswith('SAT'): A = {} s = [int(e) for e in s.split()[1:]] for e in s: if e < 0: A[-e] = False else: A[e] = True return A else: raise Exception('Unknown result {}'.format(head))
a0462fad0dcbdb18cad33df479cdc7336bf07fbf
214,688
import calendar def millis(input_dt): """Convert datetime to milliseconds since epoch Parameters ---------- input_df : datetime Returns ------- int """ return 1000 * int(calendar.timegm(input_dt.timetuple()))
b395c419b78d7721f4d67acc7987491af447896b
461,396
def filter_columns(data,column_names): """Keep selected columns in the dataframe.""" selected_columns = data[column_names] return selected_columns
c6056aaff62201f6a6e666f82613aa5cd95de369
614,208
def str_to_bool(val): """ cast a string to a bool Parameters: val: the string to cast Returns: (casted_val, success) casted val: the casted value if successful, or None success: bool if casting was successful """ if val == 'True': return (True, True) elif val == 'False': return (False, True) else: return (None, False)
fdcedf41a136f14e13584a191985f120b5a637a2
487,064
import random def rand_int(start=1, end=10, seed=None): """ Returns a random integer number between the start and end number. .. versionadded:: 2015.5.3 start : 1 Any valid integer number end : 10 Any valid integer number seed : Optional hashable object .. versionchanged:: 2019.2.0 Added seed argument. Will return the same result when run with the same seed. CLI Example: .. code-block:: bash salt '*' random.rand_int 1 10 """ if seed is not None: random.seed(seed) return random.randint(start, end)
e7e56a2b3f6b7684fe75c26ac96b59215db953f0
641,172
def trim_keys(dict_): """remove dict keys with leading and trailing whitespace >>> trim_keys({' name': 'value'}) == {'name': 'value'} True """ return {k.strip(): v for k, v in dict_.items()}
67662f9e4636118dacf8595c1f4e2b6ea85fb2fa
498,469
def list_vm(client, resource_group_name=None): """ Returns a list of VMware virtual machines in the current subscription. If resource group is specified, only the virtual machines in that resource group would be listed. """ if resource_group_name is None: return client.list_by_subscription() return client.list_by_resource_group(resource_group_name)
12db2abd8ba4ffd7905a826ad5b56f7259cf6016
180,386
def restore_original_texture_name(filename: str) -> str: """Create original texture name from RSB filename""" newfilename = filename if filename.startswith("TGA"): #Strip TGA from front of filename newfilename = filename[3:] newfilename = newfilename[:-4] + ".tga" else: newfilename = newfilename[:-4] + ".bmp" return newfilename
a295a682af551982cf5d46f61c42325ba7ea9181
169,854
def _clear_bits(basis_state, apply_qubits): """ Set bits specified in apply_qubits to zero in the int basis_state. Example: basis_state = 6, apply_qubits = [0, 1] 6 == 0b0110 # number in binary representation calling this method returns sets the two right-most bits to zero: return -> 0b0100 == 4 >>> _clear_bits(6, [0, 1]) 4 :type basis_state: int :type apply_qubits: [int] :param basis_state: An arbitrary integer. :param apply_qubits: Bits to set to zero. :return: int """ return basis_state - (sum(1 << i for i in apply_qubits) & basis_state)
97f27fc0843c76bb05d98f3c62a52d09cfd3e9cc
302,626
def identity(image, *args, **kwargs): """Returns the first argument unmodified.""" return image
9330f42fa6d18465d7a081d6da3bf38669fb5e57
191,313
def get_progress_rate(k, c_species, v_reactants): """Returns the progress rate for a reaction of the form: va*A+vb*B --> vc*C. INPUTS ======= k: float Reaction rate coefficient c_species: 1D list of floats Concentration of all species v_reactants: 1D list of floats Stoichiometric coefficients of reactants RETURNS ======== w: float prgress rate of this reaction NOTES ===== PRE: - k, each entry of c_species and v_reactants have numeric type - c_species and v_reactants have the same length POST: - k, c_species and v_reactants are not changed by this function - raises a ValueError if k <= 0 - raises an Exception if c_species and v_reactants have different length - returns the prgress rate w for the reaction EXAMPLES ========= >>> get_progress_rate(10, [1.0, 2.0, 3.0], [2.0, 1.0, 0.0]) 20.0 """ if k <= 0: raise ValueError('k must be positive.') if len(c_species) != len(v_reactants): raise Exception('List c_species and list v_reactants must have same length.') w = k for c, v in zip(c_species, v_reactants): w *= pow(c, v) return w
6baaaa07fe0814dbc50516b29ba55087c4ec23fd
12,431
def query(field, op, value, type=''): """Assemble a dict representing a query filter. :param field: Field to query :type field: String :param op: Query operator :type op: String :param value: Value to query :type value: String :param type: Type of the value :type type: String :return: Query filter dict :rtype: Dict """ return { 'field': field, 'op': op, 'value': value, 'type': type }
9fa98cbfefc062782e8aa1e89bcaabcac926a49a
572,894
import json def get_json(content): """Decode the JSON records from the response. :param content: the content returned by the eBird API. :type content: http.client.HTTPResponse: :return: the records decoded from the JSON payload. :rtype: list """ return json.loads(content.decode("utf-8"))
3e2e88063ddc730170212e635e11e64aca474a47
650,737
def fuzzy_match_reference(fuzzy_matcher, reference): """ Args: fuzzy_matcher: instance of FuzzyMatcher, with index of publications in place. reference: reference Returns: matched reference (citations), including publication & doc id. """ return fuzzy_matcher.match(reference)
13041f6a7de1cdc67728174a3168b198fa252b12
478,872
def encode_headers(headers): """Encodes HTTP headers. Args: headers: Dictionary of HTTP headers. Returns: String containing encoded HTTP headers. """ return '\n'.join(["%s: %s"%(k,headers[k]) for k in sorted(headers.keys())])
21ce28af5fa62cc5be12b6543a078c5ca9890093
181,337
import torch def normalize(tensor, min=None, max=None): """ Normalize the tensor values between [0-1] Parameters ---------- tensor : Tensor the input tensor min : int or float (optional) the value to be considered zero. If None, min(tensor) will be used instead (default is None) max : int or float (optional) the value to be considered one. If None, max(tensor) will be used instead (default is None) Returns ------- Tensor a tensor with [min-max] retargeted in [0-1] """ if min is None: min = torch.min(tensor) if max is None: max = torch.max(tensor) return torch.div(torch.add(tensor, -min), (max-min))
46f413ffc1aacde12ab6f8d95bba105fc58f86d3
663,868
import locale def generate_sorted_sem_terms(sem_features): """ Generates 1, 2, 3, 4-grams of lexicographically sorted semantic terms according to UTF-8 order. Args: sem_features: list of semantic features. Returns: List of semantic terms in lexicographic order. """ terms = list() if len(sem_features) <= 0: return terms # Sort terms according to UTF-8 locale.setlocale(locale.LC_ALL, "") sem_features.sort(cmp=locale.strcoll) # 4 terms terms = [[sem_features[i] + '$' + sem_features[i + 1] + '$' + sem_features[i + 2] + '$' + sem_features[i + 3] for i in range(len(sem_features) - 3)]] # 3 terms terms += [[sem_features[i] + '$' + sem_features[i + 1] + '$' + sem_features[i + 2] for i in range(len(sem_features) - 2)]] # 2 terms terms += [[sem_features[i] + '$' + sem_features[i + 1] for i in range(len(sem_features) - 1)]] # 1 term terms += [[sem_features[i] for i in range(len(sem_features))]] return terms
5cb53b977acfb7c5f79444f455bd6b829aea4774
165,644
import functools def require_privilege(level, message=None): """Decorate a function to require at least the given channel permission. `level` can be one of the privilege levels defined in this module. If the user does not have the privilege, `message` will be said if given. If it is a private message, no checking will be done.""" def actual_decorator(function): @functools.wraps(function) def guarded(bot, trigger, *args, **kwargs): # If this is a privmsg, ignore privilege requirements if trigger.is_privmsg: return function(bot, trigger, *args, **kwargs) channel_privs = bot.channels[trigger.sender].privileges allowed = channel_privs.get(trigger.nick, 0) >= level if not trigger.is_privmsg and not allowed: if message and not callable(message): bot.say(message) else: return function(bot, trigger, *args, **kwargs) return guarded return actual_decorator
ec1e255f2c4bd91eed6d4f549c6f13baab7146e2
349,315
import hashlib def HashToCurve(curve, hash_oid, hv): """ Hash the provided input data into a curve point. The data (hv) is either raw unhashed data, or a hash value if the data was pre-hashed. 'hash_oid' identifies the hash function used for pre-hashing; use b'' (empty string) for raw unhashed data. Returned point can be any point on the group, including the neutral N. """ n = curve.K.encodedLen sh = hashlib.shake_256() sh.update(curve.bname) sh.update(b'-hash-to-curve:') sh.update(hash_oid) sh.update(b':') sh.update(hv) blob = sh.digest(2 * n) return curve.MapToCurve(blob[:n]) + curve.MapToCurve(blob[n:])
feb30406604a6f466a57e2c1c1a5da0a1d65b63d
217,531
def school2nation(id_num): """ Takes school id, returns nation id of the school. """ if id_num < 97100000: return id_num // 100000 * 10000 if id_num < 97200000: return 7240000 if id_num < 97400000: return 8400000 return 320100
74e7eb74b2adf1cd2c8855a1bcc35eddf38586e3
633,639
def _undo_op(arg, string, strict=False): """ Undo symbolic op if string is in str(op). Returns <arg> untouched if there was no symbolic op. Parameters ---------- arg : any symbolic variable. string : str String that specifies op. strict : bool Whether to force op undo or not (default False). """ if hasattr(arg.owner, 'op'): owner = arg.owner if string in str(owner.op): return owner.inputs[0] elif strict: raise ValueError(string + ' not found in op ' + str(owner.op) + '.') elif strict: raise ValueError(string + ' op not found in variable ' + str(arg) + '.') return arg
c2cd121ae2ebce49c921fff0f63e0dfd844565d9
614,543
def underline_filter(text): """Jinja2 filter adding =-underline to row of text >>> underline_filter("headline") "headline\n========" """ return text + "\n" + "=" * len(text)
417340cef3dce0348e197d7af9150b8407a8fa5e
65,423
def wind_dir(degrees): """Provide a nice little unicode character of the wind direction""" # Taken from jenni if degrees == 'VRB': degrees = '\u21BB' # ↻ elif (degrees <= 22.5) or (degrees > 337.5): degrees = '\u2B06' # ⬆ elif (degrees > 22.5) and (degrees <= 67.5): degrees = '\u2197' # ↗ elif (degrees > 67.5) and (degrees <= 112.5): degrees = '\u27A1' # → elif (degrees > 112.5) and (degrees <= 157.5): degrees = '\u2198' # ↘ elif (degrees > 157.5) and (degrees <= 202.5): degrees = '\u2B07' # ⬇ elif (degrees > 202.5) and (degrees <= 247.5): degrees = '\u2199' # ↙ elif (degrees > 247.5) and (degrees <= 292.5): degrees = '\u2B05' # ← elif (degrees > 292.5) and (degrees <= 337.5): degrees = '\u2196' # ↖ return degrees
2ddc9445d9da8607ca32ab6536b6c254be8e1bf2
177,598
def get_paren_substring(string: str) -> str | None: """Get the contents enclosed by the first pair of parenthesis Parameters ---------- string : str A string Returns ------- str | None The part of the string enclosed in parenthesis e.g. or None Examples -------- >>> get_paren_substring('some line(a, b, (c, d))') 'a, b, (c, d)' If the line has incomplete parenthesis however, ``None`` is returned >>> get_paren_substring('some line(a, b') is None True """ i1 = string.find("(") i2 = string.rfind(")") if -1 < i1 < i2: return string[i1 + 1 : i2] else: return None
20694128171cf17f9aa23f1cb049591424e0276f
200,704
def mocked_elasticsearch(mocked_elasticsearch_module_patcher): """ Fixture that resets all of the patched ElasticSearch API functions """ for mock in mocked_elasticsearch_module_patcher.patcher_mocks: mock.reset_mock() return mocked_elasticsearch_module_patcher
0dabc985d1dbcd7eda3d365447c1241f54143644
641,438
def xyz_to_zne(st): """ Convert channels in obspy stream from XYZ to ZNE. """ for tr in st: chan = tr.stats.channel if chan[-1] == 'X': tr.stats.channel = chan[:-1] + 'E' elif chan[-1] == 'Y': tr.stats.channel = chan[:-1] + 'N' return st
37c7b28ea81d41abc606c9b3ec1e1ce7788ff7f6
172,785
import collections def filter_dataframes(dfs, xs, ys, table_ys, args_list, valid_keys): """Process necessary information from dataframes in the Bokeh format. In the following explanation, N is assumed to be the number of experiments. For xs_dict and ys_dict: These are dictionary of list of list. To make it simple, we focus on particular `x` in `xs`. Everything is the same for `ys_dict`. `x` is usually a timescale values such as iteration or epoch. Here are some characteristics: 1. xs_dict[x] is list of list 2. len(xs_dict[x]) == N 3. xs_dict[x][i] is list. For example, if log is recorded every epoch and `x` is epoch, xs_dict[x][i] == [1, 2, 3, 4, ...]. For tables: This is a dictionary of list of scalars or strings. The keys correspond to the column keys of the data table. The keys are the combination of all `valid_keys` and `table_ys`. tables[key][i] is `key` value recorded in the i-th experiment. For example, if key=='main/loss', this is the minimum loss value during training time recorded for the i-th experiment. Args: dfs (list of pd.DataFrame) xs (list of strings) ys (list of strings) table_ys (dictionary) args_list (list of dictionaries) valid_keys (list of strings) """ # Descs: descriptions # ys_dict == {string (y): List(Serial Data)} xs_dict = {x: [] for x in xs} ys_dict = {y: [] for y in ys} tables = collections.OrderedDict( [(key, []) for key in ['index'] + valid_keys + list(table_ys.keys())]) for i, args in enumerate(args_list): # get df from a result tmp = dfs for key, val in args.items(): if val is None: tmp = tmp[tmp[key].isnull()] else: tmp = tmp[tmp[key] == val] for x in xs: xs_dict[x].append(tmp[x].values.tolist()) for y in ys: ys_dict[y].append(tmp[y].values.tolist()) for table_y, value_type in table_ys.items(): if value_type == 'min': tables[table_y].append(tmp[table_y].min()) elif value_type == 'max': tables[table_y].append(tmp[table_y].max()) else: raise ValueError for key in valid_keys: if key in args: tables[key].append(args[key]) else: tables[key].append(None) tables['index'] = list(range(len(args_list))) return xs_dict, ys_dict, tables
903ce855378d174370117d9cb729f1052c682ac4
695,596
def one_level_dict(res): """ Transforms nested dict to dictionary only one level deep """ configs = [] roots = [] iters = [] energies = [] waves = [] ints = [] for config in res: for root in res[config]: for iteration in res[config][root]["peaks"]: data = res[config][root]["peaks"][iteration] for val in data: energy, wave, intensity = val configs.append(config) roots.append(root) iters.append(iteration) energies.append(energy) waves.append(wave) ints.append(intensity) output = {} output["Config"] = configs output["Root"] = roots output["Iteration"] = iters output["Transition Energies (eV)"] = energies output["Wavelength (nm)"] = waves output["Intensity (au)"] = ints return output
a1657aff2e22eb9012a07f5a2bcb6ea1db264490
551,914
def get_lines(self): """The list returned contains all the Line of the SurRing Parameters ---------- self : SurfRing A SurfRing object Returns ------- line_list : list list of lines delimiting the surface """ line_list = self.out_surf.get_lines() line_list.extend(self.in_surf.get_lines()) return line_list
9a9966fa86ed8f4a5aebc996fa4252ad67d12ffb
640,200
def create_filename(ticker, interval, mmyy): """ Create a filename based on a set of given parameter values. :param ticker: the ticker symbol :param interval: the time interval of the data :param mmyy: the date (in mmyy format) for which data is being fetched :return: filename string """ return f"{ticker}_{interval}_{mmyy[2:]}{mmyy[0:2]}.DAT"
8ed5f59dacfc381748b19be3bdea6f255308c6cb
604,546
def collect_blocks(d_blocks, ayear, n): """ Collect a block of patents for a window of n years regarding a focus year. If n is possitive the patents are from the future. If n is possitive the patents are from the past. Parameters ---------- d_blocks : A dictionary of patent blocks, the key is the year, and the value is a list of indexes of the patents belongin to that year. ayear: The focus year n: The window size Returns ------- block : A list with all the patents in the window of n years (past or or future) """ inc = int(n/abs(n)) ayears = list(range(ayear+inc, ayear+n+inc, inc)) block = [] for i in ayears: if i in d_blocks: block.extend(d_blocks[i]) return block
ea7029092610a59e50c5ff9e59f06f16a43a3420
121,205