seed
stringlengths
1
14k
source
stringclasses
2 values
import re def is_mac_address(mac): """ Test for valid mac address :type mac: ``str`` :param mac: MAC address in the form of AA:BB:CC:00:11:22 :return: True/False :rtype: ``bool`` """ if re.search(r'([0-9A-F]{2}[:]){5}([0-9A-F]){2}', mac.upper()) is not None: return True ...
bigcode/self-oss-instruct-sc2-concepts
import json def create_label(name, color, repos, session, origin): """ Creates label :param name: name of the label :param color: color of the label :param repos: repository where label is created :param session: session for communication :param origin: repository where the label came fro...
bigcode/self-oss-instruct-sc2-concepts
def num_leading_spaces(str): """ Return the number of leading whitespaces of given string """ for i, c in enumerate(str): if c != ' ': return i return len(str)
bigcode/self-oss-instruct-sc2-concepts
def memoize(f): """A simple memoize decorator for functions.""" cache= {} def memf(*x): if x not in cache: cache[x] = f(*x) return cache[x] return memf
bigcode/self-oss-instruct-sc2-concepts
import json def parse_json_file(file_path: str): """utility method to read a json file and return json object Parameters ---------- file_path : str full path to json file that needs to be parsed Returns ------- [type] json object parsed from the file """ with open...
bigcode/self-oss-instruct-sc2-concepts
def to_int(x): """Convert bytes to an integer.""" return int(x.hex(), 16)
bigcode/self-oss-instruct-sc2-concepts
from typing import OrderedDict def custom_sort_exps(exps): """ Sort the experiments according to JIRA LCLSECSD-210 Active first, OPS next and then descending run period/alphabetical within that run period """ # Python's sort is stable; so we sort multiple times lowest attr first exps = Ordered...
bigcode/self-oss-instruct-sc2-concepts
def _match_some(regexes, line, n_line, n_col): """Match patterns in order. Returns a tuple of match and token type or raises SyntaxError.""" for regex, token in regexes: match = regex.match(line, n_col) if match is not None: return match, token error = "No rules to match inpu...
bigcode/self-oss-instruct-sc2-concepts
def seconds_for_analysis(duration, measurement_type, selector): """Get duration for specified measurement type and selector.""" if measurement_type in duration: data = duration[measurement_type] if selector in data: return data[selector].duration_seconds return 0
bigcode/self-oss-instruct-sc2-concepts
def duplicates_checker(source, new): """ Checking for duplicates in existing list of contacts """ for item in source: if new == item['phone']: return False return True
bigcode/self-oss-instruct-sc2-concepts
def _multiplot_interval(from_date, to_date, points): """ Computes the size of the interval between points in a multiplot. :return: the multiplot interval size. :rtype: ``float`` """ if points < 2: return 0.0 return (to_date - from_date) / (points - 1)
bigcode/self-oss-instruct-sc2-concepts
def wma(df, price, wma, n): """ The Weighted Moving Average calculates a weight for each value in the series. The more recent values are assigned greater weights. The Weighted Moving Average is similar to a Simple Moving average in that it is not cumulative, that is, it only includes values in the t...
bigcode/self-oss-instruct-sc2-concepts
def recurse_combine(combo_items: list, idx: int = 0) -> list: """Recursively expands 'combo_items' into a list of permutations. For example recurse_combine([[A, B, C], [D, E], [F]]) returns [[A, D, F], [A, E, F], [B, D, F], [B, E, F], [C, D, F], [C, E, F]] """ result = [] if i...
bigcode/self-oss-instruct-sc2-concepts
def _ask_yes_no(prompt: str) -> bool: """Simple function that prompts user until they answer 'y' or 'n'""" answer = input(prompt).lower() while answer not in ("y", "n"): answer = input("Please enter 'y' or 'n': ").lower() if answer == "y": return True else: return False
bigcode/self-oss-instruct-sc2-concepts
def to_upper(string): """:yaql:toUpper Returns a string with all case-based characters uppercase. :signature: string.toUpper() :receiverArg string: value to uppercase :argType string: string :returnType: string .. code:: yaql> "aB1c".toUpper() "AB1C" """ return st...
bigcode/self-oss-instruct-sc2-concepts
def linspace(a, b, num_chunks): """Returns equidistant steps in [a, b] whose number matches num_chunks.""" assert isinstance(num_chunks, int) and num_chunks > 0, 'Number of chunks must be a natural number!' h = (b - a) / num_chunks return [a + i * h for i in range(num_chunks + 1)]
bigcode/self-oss-instruct-sc2-concepts
def safe_hasattr(item: object, member: str) -> bool: """Safe version of ``hasattr()``.""" try: # some sketchy implementation (like paste.registry) of # __getattr__ cause hasattr() to throw an error. return hasattr(item, member) except Exception: return False
bigcode/self-oss-instruct-sc2-concepts
import fnmatch def _get_pprint_include_names(table): """Get the set of names to show in pprint from the table pprint_include_names and pprint_exclude_names attributes. These may be fnmatch unix-style globs. """ def get_matches(name_globs, default): match_names = set() if name_glob...
bigcode/self-oss-instruct-sc2-concepts
def _recall(conf_mat): """ Compute the recall score, i.e. the ratio of true positives to true positives and false negatives. Answers the question: "Which share of the pixels that are actually slum was identified by the model as such?" :param conf_mat: Confusion matrix produced by conf_mat(). :retu...
bigcode/self-oss-instruct-sc2-concepts
def recursive_lookup(dict_object, keys): """ Given a dict object and list of keys, nest into those keys. Raises KeyError if the path isn't found. >>> recursive_lookup({'foo': 1}, ['foo']) 1 >>> recursive_lookup({'foo': {'bar': 1}}, ['foo']) {'bar': 1} >>> recursive_lookup({'foo': {'bar':...
bigcode/self-oss-instruct-sc2-concepts
def get_table_id(current_page, objects_per_page, loop_counter): """ Calculate correct id for table in project page. This function is used only for pagination purposes. """ return ((current_page - 1) * objects_per_page) + loop_counter
bigcode/self-oss-instruct-sc2-concepts
def get_kp_labels(bands_node, kpoints_node=None): """ Get Kpoint labels with their x-positions in matplotlib compatible format. A KpointsData node can optionally be given to fall back to if no labels are found on the BandsData node. The caller is responsible for ensuring the nodes match. This shou...
bigcode/self-oss-instruct-sc2-concepts
def IndexOfMin(inputList): """ Return the index of the min value in the supplied list """ assert(len(inputList) > 0) index = 0 minVal = inputList[0] for i, val in enumerate(inputList[1:]): if val < minVal: minVal = val index = i + 1 return index
bigcode/self-oss-instruct-sc2-concepts
def filter_profile(data, profile): """ Take a dataframe after it has been processed by merge_data, and a profile and returns a filtered dataframe of players with that profile. Valid profiles are 'long_inaccurate', 'long_accurate', 'short_inaccurate', 'short_inaccurate'. """ player_aggregates = d...
bigcode/self-oss-instruct-sc2-concepts
def mat_like_array(start, end, step=1): """ Generate a matlab-like array start:end Subtract 1 from start to account for 0-indexing """ return list(range(start-1, end, step))
bigcode/self-oss-instruct-sc2-concepts
def rotate(pos, vel, matrix): """ Rotate. Applies the rotation `matrix` to a set of particles positions `pos` and velocities `vel` Parameters ---------- pos : `np.ndarray`, shape = (N_part, 3) Positions of particles vel : `np.ndarray`, shape = (N_part, 3) Velocities of ...
bigcode/self-oss-instruct-sc2-concepts
def generate_public(private, generator, modulus): """Calculates the public Diffie-Hellman key given g, p, and the private key""" return pow(generator, private, modulus)
bigcode/self-oss-instruct-sc2-concepts
import base64 def custom_jinja2_filter(string): """encodes a string using base64 schema""" return base64.b64encode(string.encode("UTF-8")).decode("UTF-8")
bigcode/self-oss-instruct-sc2-concepts
def assume_role_response_to_session_kwargs(assume_role_resp): """Convert assume role response to kwargs for boto3.Session Also useful for creating AWS credentials file. """ return dict(aws_access_key_id=assume_role_resp['Credentials']['AccessKeyId'], aws_secret_access_key=assume_role_r...
bigcode/self-oss-instruct-sc2-concepts
def join_ints(*ints): """Given a list of ints, return a underscore separated strings with them. >>> join_ints(1, 2, 3) '1_2_3' """ return '_'.join(map(str, ints))
bigcode/self-oss-instruct-sc2-concepts
import math def make_multiple(x, number): """ Increases x to be the smallest multiple of number """ return int(math.ceil(float(x) / float(number)) * number)
bigcode/self-oss-instruct-sc2-concepts
def zones2list(zones, type="power"): """Convert zones Strava response into a list Parameters ---------- zones : dict Strava API zones response type : {"power", "heart_rate"} Returns ------- y : list Zones boundaries with left edge set to -1 and right to 10000 """ ...
bigcode/self-oss-instruct-sc2-concepts
def retrieve_commands(commands): """ Retrieve context needed for a set of commit actions """ config_commands = commands['config'] support_commit = commands.get('support_commit') config_verify = commands['config_verification'] return (config_commands, support_commit, config_verify)
bigcode/self-oss-instruct-sc2-concepts
import re def RemoveFrameShiftsFromAlignment(row_ali, col_ali, gap_char="-"): """remove frame shifts in an alignment. Frameshifts are gaps are 1, 2, 4, or 5 residues long. >>> RemoveFrameShiftsFromAlignment("ABC-EFG", "AB-DEFG") ('ABEFG', 'ABEFG') Arguments --------- row_ali : string ...
bigcode/self-oss-instruct-sc2-concepts
async def headers_middleware(req, handler): """ Middleware that adds the current version of the API to the response. """ resp = await handler(req) resp.headers["X-Virtool-Version"] = req.app["version"] resp.headers["Server"] = "Virtool" return resp
bigcode/self-oss-instruct-sc2-concepts
def loantovalue(purchaseprice, financedamount): """Return ratio of financed amount to purchase price. :param purchaseprice: Contract price of property. :type purchaseprice: double :param financedamount: Amount of money borrowed. :type financedamount: double :return: double """ return f...
bigcode/self-oss-instruct-sc2-concepts
def squeeze(array): """Return array contents if array contains only one element. Otherwise, return the full array. """ if len(array) == 1: array = array[0] return array
bigcode/self-oss-instruct-sc2-concepts
def to_label(name, capitalize=True): """Converts `name` into label by replacing underscores by spaces. If `capitalize` is ``True`` (default) then the first letter of the label is capitalized.""" label = name.replace("_", " ") if capitalize: label = label.capitalize() return label
bigcode/self-oss-instruct-sc2-concepts
from functools import reduce from typing import cast def cast_schema(df, schema): """Enforce the schema on the data frame. Args: df (DataFrame): The dataframe. schema (list): The simple schema to be applied. Returns: A data frame converted to the schema. """ spark_schema ...
bigcode/self-oss-instruct-sc2-concepts
def get_social_auths_for_user(user, provider=None): """Get UserSocialAuths for given `user` Filter by specific `provider` if set Returns a QuerySet of UserSocialAuth objects """ social_users = user.social_auth if provider is None: social_users = social_users.all() else: soc...
bigcode/self-oss-instruct-sc2-concepts
def get_sub_series(sub_cats): """ Gets the series IDs of all the subseries that are in UTC time associated with a given load balancing station """ series = [] for category in sub_cats['category']['childseries']: if "UTC time" in category['name']: series.append(category['series_id']) ...
bigcode/self-oss-instruct-sc2-concepts
from typing import Union from pathlib import Path def guess_format(filename: Union[str, Path]): """ Guess the output format from a given filename and return the corrected format. Any names not in the dict get passed through. """ extension = str(filename).rsplit(".", 1)[-1].lower() format_map ...
bigcode/self-oss-instruct-sc2-concepts
def sub(num1, num2): """ Subtract two numbers """ return num1 - num2
bigcode/self-oss-instruct-sc2-concepts
import re def remove_links(text: str) -> str: """ Removes links from a text. Args: text (:obj:`str`): Text to process. Returns: :obj:`str`: Text without links. """ # add empty character between two paragraph html tags to make processing easier te...
bigcode/self-oss-instruct-sc2-concepts
from typing import List def _validate_counts(counts: List[int]) -> bool: """ Validates the counts parameter. Parameters ---------- counts : List[integers] A list of counts. Raises ------ TypeError The ``counts`` parameter is not a list or one of the elements of this ...
bigcode/self-oss-instruct-sc2-concepts
def get_max_width(text_array): """Get the maximum width of a bunch of rows of text.""" width = 0 # Figure out the maximum width for row in text_array: if len(row) > width: width = len(row) return width
bigcode/self-oss-instruct-sc2-concepts
import torch def generate_proposals(anchors, offsets, method="YOLO"): """ Generate all proposals from anchors given offsets. @Params: ------- anchors (tensor): Tensor of shape [B, A, H', W', 4] returned by `generate_anchors()`. Anchors are parameterized by the coordinates (x_tl, y...
bigcode/self-oss-instruct-sc2-concepts
def constrain(value, lowest, highest): """Test whether `value` is within the range `(highest, lowest)`. Return `value` if it is inside the range, otherwise return `highest` if the value is *above* the range or `lowest` it the value is *below* the range. >>> constrain(-1, 2, 5) 2 >>> constra...
bigcode/self-oss-instruct-sc2-concepts
def first(mention): """ Compute the first token of a mention. Args: mention (Mention): A mention. Returns: The tuple ('first', TOKEN), where TOKEN is the (lowercased) first token of the mention. """ return "first", mention.attributes["tokens"][0].lower()
bigcode/self-oss-instruct-sc2-concepts
def convert_velocity(val, old_scale="km/h", new_scale="m/s"): """ Convert from a velocity scale to another one among km/h, and m/s. Parameters ---------- val: float or int Value of the velocity to be converted expressed in the original scale. old_scale: str Original scale from ...
bigcode/self-oss-instruct-sc2-concepts
import calendar def get_month_dispatch_intervals(year, month): """Get all dispatch interval IDs for a given month""" days = range(1, calendar.monthrange(year, month)[1] + 1) intervals = range(1, 289) return [f'{year}{month:02}{d:02}{i:03}' for d in days for i in intervals]
bigcode/self-oss-instruct-sc2-concepts
from pkg_resources import iter_entry_points def mock_iter_entry_points_factory(data, mocked_group): """Create a mock iter_entry_points function.""" def entrypoints(group, name=None): if group == mocked_group: for entrypoint in data: yield entrypoint else: ...
bigcode/self-oss-instruct-sc2-concepts
def isprime(number): """ Check if a number is a prime number number: The number to check """ if number == 1: return False for i in range(2, int(number**0.5) + 1): if number % i == 0: return False return True
bigcode/self-oss-instruct-sc2-concepts
def import_class_by_path(class_path): """Import a class by its <module>.<name> path. Args: class_path: <module>.<name> for a class. Returns: Class object for the given class_path. """ classname = class_path.split('.')[-1] modulename = '.'.join(class_path.split('.')[0:-1]) mod = __import__(module...
bigcode/self-oss-instruct-sc2-concepts
def avg(l): """Returns the average of a list of numbers.""" if not l: return None return sum(l)/len(l)
bigcode/self-oss-instruct-sc2-concepts
import re def clean_str(text: str) -> str: """ Args: text: A unicode string Returns: str: lowercased, sans punctuation, non-English letters """ RE_PREPROCESS = r'\W+|\d+' text = re.sub( RE_PREPROCESS, ' ', text.lower() ) text = re.sub(r"[^A-Za-z0...
bigcode/self-oss-instruct-sc2-concepts
def NetworkSetSFANodeClass(sfa_node_class, network): """Replaces the field sfa_node_class of all layers with a specific node class. This function is useful, for example, to transform an SFA network into a PCA network. """ for i, layer in enumerate(network.layers): layer.sfa_node_class = sfa_node_cl...
bigcode/self-oss-instruct-sc2-concepts
import math import random def optimizar(dominio, temperatura = 10e32, tasa_enfriamiento = 0.95): """Algoritmo de optimización estocástica simulated annealing. Entradas: dominio (Dominio) Un objeto que modela el dominio del problema que se quiere aproximar. temperatura (float/int) Tem...
bigcode/self-oss-instruct-sc2-concepts
import torch def collate_fn(samples): """ collate_fn for SequentialMNIST. Args: samples: a list of samples. Each item is a (imgs, nums) pair. Where - imgs: shape (T, 1, C, H, W) - nums: shape (T, 1) And len(samples) is the batch size. ...
bigcode/self-oss-instruct-sc2-concepts
def utf8_encode(s: str) -> bytes: """Encodes a string with utf-8 and returns its byte sequence. Invalid surrogates will be replaced with U+FFFD. Args: s: A string to encode with utf-8. Returns: A utf-8 encoded byte sequence. """ s = s.encode("utf-16", "surrogatepass").decode("...
bigcode/self-oss-instruct-sc2-concepts
def subdirs(folderpath, pattern="*"): """ returns all sub folders in a given folder matching a pattern """ return [f for f in folderpath.glob(pattern) if f.is_dir()]
bigcode/self-oss-instruct-sc2-concepts
def extract_keywords(lst_dict, kw): """Extract the value associated to a specific keyword in a list of dictionaries. Returns the list of values extracted from the keywords. Parameters ---------- lst_dict : python list of dictionaries list to extract keywords from kw : string keywo...
bigcode/self-oss-instruct-sc2-concepts
def flatten_dict(input_dict): """Returns flattened dictionary given an input dictionary with maximum depth of 2 Args: input_dict (dict): `str → number` key-value pairs, where value can be a number or a dictionary with `str → number` key-value paris. Returns: dict: F...
bigcode/self-oss-instruct-sc2-concepts
import re def remove_vowels(string=''): """ Removes the vowels from the given string. According to the rules the letters A, E, I, O, U are considered vowels. :param string: The input to remove vowels from :return: The given string without vowels """ return re.sub('a|e|i|o|u|y', '', string,...
bigcode/self-oss-instruct-sc2-concepts
def header_check(file): """Checks whether the file has a header or not. Parameters ---------- file : str Filename or filepath of file to check Returns ------- int 1 if header is present 0 if not """ with open(file, "r", encoding="utf-8") as to_check: result ...
bigcode/self-oss-instruct-sc2-concepts
def build_parms(args): """Helper function to parse command line arguments into dictionary input: ArgumentParser class object output: dictionary of expected parameters """ readDir=args.dir outdir=args.outdir parms = {"readDir":readDir, "outdir":outdir} return(p...
bigcode/self-oss-instruct-sc2-concepts
import re def strip_config_header(config): """Normalize items that should not show up in IOS-XR compare_config.""" config = re.sub(r"^Building config.*\n!! IOS.*", "", config, flags=re.M) config = config.strip() config = re.sub(r"^!!.*", "", config) config = re.sub(r"end$", "", config) return ...
bigcode/self-oss-instruct-sc2-concepts
def get_item_relative_limit(page, per_page): """Get the maximum possible number of items on one page.""" return per_page
bigcode/self-oss-instruct-sc2-concepts
def p1(range_max, factor_list): """Problem 1 If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000. """ range_min = 0 sum_multiples = 0 for num in range(...
bigcode/self-oss-instruct-sc2-concepts
import re def regex_search_list(data, regex): """ Allows you to search across a list with regex returns True if any match in the list. :param data: The element to search :param regex: The regex search string :return: True if any elements match, false if none match """ # Create the data int...
bigcode/self-oss-instruct-sc2-concepts
from typing import Union def convert_strike(strike: Union[int, float]) -> Union[int, float]: """ Convert the type of the strike to an integer if it is an integer or float to 2 points if it is a float Note ---- This is only a type conversion """ if (strike - int(strike)) == 0: retur...
bigcode/self-oss-instruct-sc2-concepts
def string_is_equal_case_insensitive(subject: str, value: str) -> bool: """Case insensitive string is equal""" return subject.strip().lower() == value.strip().lower()
bigcode/self-oss-instruct-sc2-concepts
def find_odd_occurred_number_sol2(nums): """ You are given an array of repeating numbers. All numbers repeat in even way, except for one. Find the odd occurring number. - This solution takes less space. - More details: https://youtu.be/bMF2fG9eY0A - Time: O(len(nums)) - Space: worst: O(len...
bigcode/self-oss-instruct-sc2-concepts
from typing import List def route_ranks(scores: List[float]) -> List[int]: """ Compute the rank of route scores. Rank starts at 1 :param scores: the route scores :return: a list of ranks for each route """ ranks = [1] for idx in range(1, len(scores)): if abs(scores[idx] - scores[i...
bigcode/self-oss-instruct-sc2-concepts
def transformer(y, func=None): """Transforms target variable and prediction""" if func is None: return y else: return func(y)
bigcode/self-oss-instruct-sc2-concepts
import torch def split_stack(x, split_sizes, split_dim, stack_dim): """Split x along dimension split_dim and stack again at dimension stack_dim""" t = torch.stack(torch.split(x, split_sizes, dim=split_dim), dim=stack_dim) return t
bigcode/self-oss-instruct-sc2-concepts
import re def parse_int_sprintf_pattern(patt): """Parses the integer sprintf pattern and returns a function that can detect whether a string matches the pattern. Args: patt: a sprintf pattern like "%05d", "%4d", or "%d" Returns: a function that returns True/False whether a given stri...
bigcode/self-oss-instruct-sc2-concepts
import re def getSender(email): """ Returns the best-guess sender of an email. Arguments: email -- the email whose sender is desired Returns: Sender of the email. """ sender = email['From'] m = re.match(r'(.*)\s<.*>', sender) if m: return m.group(1...
bigcode/self-oss-instruct-sc2-concepts
def signed2unsigned(value, width=32): """ convert a signed value to it's 2 complement unsigned encoding """ if value >= 0: return int(value) else: return int(value + 2**(width) )
bigcode/self-oss-instruct-sc2-concepts
import struct def read_binary(fileObj, byteType='uint8', size=1): """A helper function to readin values from a binary file Parameters: ----------- fileObj : object a binary file object byteType : string, optional, default 'uint8' the type of readin values size : int, option...
bigcode/self-oss-instruct-sc2-concepts
def is_external_plugin(module_path): """ Returns true when the given module is an external plugin. Implementation note: does a simple check on the name to see if it's not prefixed with "kolibri.". If so, we know it's not an internal plugin. """ return not module_path.startswith("kolibri.")
bigcode/self-oss-instruct-sc2-concepts
def intersect(lst1, lst2): """intersection of two lists """ lst3 = [value for value in lst1 if value in lst2] return lst3
bigcode/self-oss-instruct-sc2-concepts
from typing import Dict def prettify_data_filtering_rule(rule: Dict) -> Dict: """ Prettify the data filtering rule to be compatible to our standard. Args: rule: The profile rule to prettify Returns: rule dictionary compatible to our standards. """ pretty_rule = { 'Name': rule...
bigcode/self-oss-instruct-sc2-concepts
def identity(x): """Identity activation function. Input equals output. Args: x (ndarray): weighted sum of inputs. """ return x
bigcode/self-oss-instruct-sc2-concepts
def _recipe_name(raw_configuration): """ Given a raw repository configuration, returns its recipe name. :param raw_configuration: configuration as returned by the SCRIPT_NAME_GET groovy script. :type raw_configuration: dict :return: name of the recipe ("format") """ name = raw_confi...
bigcode/self-oss-instruct-sc2-concepts
import itertools def color_repeats(n=1): """Set up a cycle through default Plotly colors, repeating each n times""" color_list = ( ["#1f77b4"] * n # muted blue + ["#ff7f0e"] * n # safety orange + ["#2ca02c"] * n # cooked asparagus green + ["#d62728"] * n # brick red ...
bigcode/self-oss-instruct-sc2-concepts
def pybb_editable_by(post, user): """ Check if the post could be edited by the user. """ return post.is_editable_by(user)
bigcode/self-oss-instruct-sc2-concepts
def mean_squared_error_loss(inputs, targets): """ 平方差损失 Examples: >>> i = torch.randn(3, 5) >>> t = torch.randn(3, 5) # 与官方结果比较 >>> my_ret = mean_squared_error_loss(i, t) >>> official_ret = F.mse_loss(i, t, reduction='none') >>> assert torch.allclose(my_ret, off...
bigcode/self-oss-instruct-sc2-concepts
def _get_cost (route, solution, dists): """ This method is used to calculate the total distance associated to a route, once the sequence of its nodes has been changed using the 2-OPT algorithm. :param route: The interested route. :param solution: The nodesin the order in which they are visited....
bigcode/self-oss-instruct-sc2-concepts
def no_data_extractor(node, user): """Dummy function that collects no data for the NodeDataRegistry.""" return []
bigcode/self-oss-instruct-sc2-concepts
def camel_case_from_underscores(string): """generate a CamelCase string from an underscore_string.""" components = string.split('_') string = '' for component in components: string += component[0].upper() + component[1:] return string
bigcode/self-oss-instruct-sc2-concepts
def easy_helloname(a): """Takes in a string representing a name and returns a new string saying hello in a very specific format, e.g., if the name is 'Dave', it should return 'Hello, Dave!'""" return 'Hello, {}!'.format(a)
bigcode/self-oss-instruct-sc2-concepts
import mimetypes def _GuessMimeType(magic_obj, file_name): """Guess a file's mimetype base on its extension and content. File extension is favored over file content to reduce noise. Args: magic_obj: A loaded magic instance. file_name: A path to the file. Returns: A mime type of |file_name|. "...
bigcode/self-oss-instruct-sc2-concepts
def convert_headers_to_environ(headers): """ Converts HTTP headers into WSGI environ variables. """ return { 'HTTP_' + key.replace('-', '_').upper(): value.strip() for key, value in headers.items() }
bigcode/self-oss-instruct-sc2-concepts
def expand_iterable(choices): """ Expands an iterable into a list. We use this to expand generators/etc. """ return [i for i in choices] if hasattr(choices, "__iter__") else None
bigcode/self-oss-instruct-sc2-concepts
def int2list(num,listlen=0,base=2): """Return a list of the digits of num, zero padding to produce a list of length at least listlen, to the given base (default binary)""" digits = []; temp = num while temp>0: digits.append(temp % base) temp = temp // base digits.extend((listlen-len(digits))*[0]...
bigcode/self-oss-instruct-sc2-concepts
def rate(e0, e1, n0, n1, nr, p): """ This equation is solved for p to determine the convergence rate when the reference solution is used to measure the error. y(p) = 0 determines the convergence rate. e0, n0 : Error and grid number for grid "0" e1, n1 : Error and grid number for grid "1" n...
bigcode/self-oss-instruct-sc2-concepts
from typing import Iterable from typing import Hashable from typing import Counter def major_vote(all_votes: Iterable[Iterable[Hashable]]) -> Iterable[Hashable]: """ For the given iterable of object iterations, return an iterable of the most common object at each position of the inner iterations. E.g...
bigcode/self-oss-instruct-sc2-concepts
def get_embedded(result_object, link_relation): """ Given a result_object (returned by a previous API call), return the embedded object for link_relation. The returned object can be treated as a result object in its own right. 'result_object' a JSON object returned by a previous API call. The ...
bigcode/self-oss-instruct-sc2-concepts
def make_album(artist, title, tracks=0): """Build a dictionary containing information about an album.""" album_dict = { 'artist': artist.title(), 'title': title.title(), } if tracks: album_dict['tracks'] = tracks return album_dict
bigcode/self-oss-instruct-sc2-concepts