seed
stringlengths
1
14k
source
stringclasses
2 values
def scope_contains_scope(sdict, node, other_node): """ Returns true iff scope of `node` contains the scope of `other_node`. """ curnode = other_node nodescope = sdict[node] while curnode is not None: curnode = sdict[curnode] if curnode == nodescope: return True return False
bigcode/self-oss-instruct-sc2-concepts
def radio_text(route): """Returns a short representation of a Route Args: route: a Route object Returns: str: a string containing the route summary and duration """ text = " ".join([ "via " + route.summary, f"({max(1, round(route.duration / 60))} minutes)" ]) return text
bigcode/self-oss-instruct-sc2-concepts
def snitch_last_contained(metadata): """Return the frame when snitch was last contained.""" last_contain = 0 for _, movements in metadata['movements'].items(): contain_start = False for movement in movements: if movement[0] == '_contain' and movement[1] == 'Spl_0': # Should not be containing anything already contain_start = True elif contain_start and movement[0] == '_pick_place': last_contain = max(movement[-2], last_contain) contain_start = False if contain_start: # It never ended last_contain = 300 # Max frames return last_contain
bigcode/self-oss-instruct-sc2-concepts
def dict_factory(cursor, row): """Returns a sqlite row factory that returns a dictionary""" d = {} for idx, col in enumerate(cursor.description): d[col[0]] = row[idx] return d
bigcode/self-oss-instruct-sc2-concepts
import torch def gram_matrix(tensor): """ Calculate the Gram Matrix of a given tensor Gram Matrix: https://en.wikipedia.org/wiki/Gramian_matrix """ # get the batch_size, depth, height, and width of the Tensor _, d, h, w = tensor.size() # reshape so we're multiplying the features for each channel tensor = tensor.view(d, h * w) # calculate the gram matrix gram = torch.mm(tensor, tensor.t()) return gram
bigcode/self-oss-instruct-sc2-concepts
def isOnCorner(x, y): """Returns True if the position is in one of the four corners.""" return ((x == 0 and y == 0) or (x == 7 and y == 0) or (x == 0 and y == 7) or (x == 7 and y == 7))
bigcode/self-oss-instruct-sc2-concepts
def is_paired(cursor, imei_norm): """ Method to check if an IMEI is paired. :param cursor: db cursor :param imei_norm: normalized imei :return: bool """ cursor.execute("""SELECT EXISTS(SELECT 1 FROM pairing_list WHERE imei_norm = %(imei_norm)s AND virt_imei_shard = calc_virt_imei_shard(%(imei_norm)s))""", {'imei_norm': imei_norm}) return cursor.fetchone()[0]
bigcode/self-oss-instruct-sc2-concepts
def get_P_v(X_ex): """外気の水蒸気圧 式(2) Args: X_ex(ndarray): 絶湿[g/kg'] Returns: ndarray: 外気の水蒸気圧 """ return 101325 * (X_ex / (622 + X_ex))
bigcode/self-oss-instruct-sc2-concepts
import re def remove_digits(string): """Removes digits from a string""" return re.sub(r"\d+", "", string)
bigcode/self-oss-instruct-sc2-concepts
def _trim_css_to_bounds(css, image_shape): """ Make sure a tuple in (top, right, bottom, left) order is within the bounds of the image. :param css: plain tuple representation of the rect in (top, right, bottom, left) order :param image_shape: numpy shape of the image array :return: a trimmed plain tuple representation of the rect in (top, right, bottom, left) order """ return max(css[0], 0), min(css[1], image_shape[1]), min(css[2], image_shape[0]), max(css[3], 0)
bigcode/self-oss-instruct-sc2-concepts
import math def log(*args): """ Evaluate a logarithm Args: *args (:obj:`list` of :obj:`float`): value optional proceeded by a base; otherwise the logarithm is calculated in base 10 Returns: :obj:`float` """ value = args[-1] if len(args) > 1: base = args[0] else: base = 10. return math.log(value, base)
bigcode/self-oss-instruct-sc2-concepts
import socket import contextlib def has_dual_stack(sock=None): """Return True if kernel allows creating a socket which is able to listen for both IPv4 and IPv6 connections. If *sock* is provided the check is made against it. """ try: socket.AF_INET6; socket.IPPROTO_IPV6; socket.IPV6_V6ONLY except AttributeError: return False try: if sock is not None: return not sock.getsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY) else: sock = socket.socket(socket.AF_INET6, socket.SOCK_STREAM) with contextlib.closing(sock): sock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, False) return True except socket.error: return False
bigcode/self-oss-instruct-sc2-concepts
from typing import Dict from typing import Any from typing import List from functools import reduce def traverse_dict(obj: Dict[Any, Any], properties: List[str]) -> Any: """ Traverse a dictionary for a given list of properties. This is useful for traversing a deeply nested dictionary. Instead of recursion, we are using reduce to update the `dict`. Missing properties will lead to KeyErrors. .. ipython:: python :okexcept: from dialogy.utils import traverse_dict input_ = { "planets": { "mars": [{ "name": "", "languages": [{ "beep": {"speakers": 11}, }, { "bop": {"speakers": 30}, }] }] } } traverse_dict(input_, ["planets", "mars", 0 , "languages", 1, "bop"]) # element with index 3 doesn't exist! traverse_dict(input_, ["planets", "mars", 0 , "languages", 3, "bop"]) :param obj: The `dict` to traverse. :type obj: Dict[Any, Any] :param properties: List of properties to be parsed as a path to be navigated in the `dict`. :type properties: List[int] :return: A value within a deeply nested dict. :rtype: Any :raises KeyError: Missing property in the dictionary. :raises TypeError: Properties don't describe a path due to possible type error. """ try: return reduce(lambda o, k: o[k], properties, obj) except KeyError as key_error: raise KeyError( f"Missing property {key_error} in {obj}. Check the types. Failed for path {properties}" ) from key_error except TypeError as type_error: raise TypeError( f"The properties aren't describing path within a dictionary. | {type_error}. Failed for path {properties}" ) from type_error
bigcode/self-oss-instruct-sc2-concepts
def _BuildRestrictionChoices(freq_restrictions, actions, custom_permissions): """Return a list of autocompletion choices for restriction labels. Args: freq_restrictions: list of (action, perm, doc) tuples for restrictions that are frequently used. actions: list of strings for actions that are relevant to the current artifact. custom_permissions: list of strings with custom permissions for the project. Returns: A list of dictionaries [{'name': 'perm name', 'doc': 'docstring'}, ...] suitable for use in a JSON feed to our JS autocompletion functions. """ choices = [] for action, perm, doc in freq_restrictions: choices.append({ 'name': 'Restrict-%s-%s' % (action, perm), 'doc': doc, }) for action in actions: for perm in custom_permissions: choices.append({ 'name': 'Restrict-%s-%s' % (action, perm), 'doc': 'Permission %s needed to use %s' % (perm, action), }) return choices
bigcode/self-oss-instruct-sc2-concepts
import hashlib def get_sha_digest(s, strip=True): """Generate digest for s. Convert to byte string. Produce digest. """ if strip: s = s.rstrip() s = s.encode("utf-8") return hashlib.sha256(s).hexdigest()
bigcode/self-oss-instruct-sc2-concepts
import hashlib def hash_(list_): """Generate sha1 hash from the given list.""" return hashlib.sha1(str(tuple(sorted(list_))).encode("utf-8")).hexdigest()
bigcode/self-oss-instruct-sc2-concepts
def get_by_name(ast, name): """ Returns an object from the AST by giving its name. """ for token in ast.declarations: if token.name == name: return token return None
bigcode/self-oss-instruct-sc2-concepts
def _ecdf_y(data, complementary=False): """Give y-values of an ECDF for an unsorted column in a data frame. Parameters ---------- data : Pandas Series Series (or column of a DataFrame) from which to generate ECDF values complementary : bool, default False If True, give the ECCDF values. Returns ------- output : Pandas Series Corresponding y-values for an ECDF when plotted with dots. Notes ----- This only works for plotting an ECDF with points, not for staircase ECDFs """ if complementary: return 1 - data.rank(method="first") / len(data) + 1 / len(data) else: return data.rank(method="first") / len(data)
bigcode/self-oss-instruct-sc2-concepts
def _calculate_bsize(stat): """ Calculate the actual disk allocation for a file. This works at least on OS X and Linux, but may not work on other systems with 1024-byte blocks (apparently HP-UX?) From pubs.opengroup.org: The unit for the st_blocks member of the stat structure is not defined within IEEE Std 1003.1-2001 / POSIX.1-2008. In some implementations it is 512 bytes. It may differ on a file system basis. There is no correlation between values of the st_blocks and st_blksize, and the f_bsize (from <sys/statvfs.h>) structure members. """ return 512 * stat.st_blocks
bigcode/self-oss-instruct-sc2-concepts
def vcum(self, key="", **kwargs): """Allows array parameter results to add to existing results. APDL Command: *VCUM Parameters ---------- key Accumulation key: Overwrite results. - Add results to the current value of the results parameter. Notes ----- Allows results from certain *VXX and *MXX operations to overwrite or add to existing results. The cumulative operation is of the form: ParR = ParR + ParR(Previous) The cumulative setting is reset to the default (overwrite) after each *VXX or *MXX operation. Use *VSTAT to list settings. This command is valid in any processor. """ command = f"*VCUM,{key}" return self.run(command, **kwargs)
bigcode/self-oss-instruct-sc2-concepts
def brightness_to_percentage(byt): """Convert brightness from absolute 0..255 to percentage.""" return round((byt * 100.0) / 255.0)
bigcode/self-oss-instruct-sc2-concepts
def ensure_bool(val): """ Converts query arguments to boolean value. If None is provided, it will be returned. Otherwise, value is lowered and compared to 'true'. If comparison is truthful, True is returned, otherwise False. :param val: Value to convert to boolean. :return: boolean value """ if val is None: return None return val.lower() == 'true'
bigcode/self-oss-instruct-sc2-concepts
from typing import Tuple def get_word_from_cursor(s: str, pos: int) -> Tuple[str, int, int]: """ Return the word from a string on a given cursor. :param s: String :param pos: Position to check the string :return: Word, position start, position end """ assert 0 <= pos < len(s) pos += 1 s = ' ' + s p = 0 # Check if pos is an empty character, find the following word if s[pos].strip() == '': found = False for k in range(pos, len(s)): # First if s[k].strip() != '' and not found: p = k found = True elif s[k].strip() == '' and found: return s[p:k].strip(), p, k - 1 else: for w in range(pos): # Find prev j = pos - w - 1 if s[j].strip() == '': p = j break elif s[j].strip() == '>': p = j + 1 break for j in range(pos + 1, len(s)): # Find next if s[j].strip() in ('', '<'): return s[p:j].strip(), p, j - 1 return '', -1, -1
bigcode/self-oss-instruct-sc2-concepts
import math def geometric_progression(a, r, n): """Returns a list [a, ar, ar^2, ar^3, ... , ar^(n-1)]""" comp = [] for num in range(n): comp.append(a*math.pow(r, num)) return(comp)
bigcode/self-oss-instruct-sc2-concepts
def lifetime_high(m): """Compute the lifetime of a high mass star (M > 6.6 Msun) Args: m (array): stellar mass. Returns: array: stellar lifetimes. """ return (1.2 * m**(-1.85) + 0.003) * 1000.
bigcode/self-oss-instruct-sc2-concepts
def replace_subset(lo, hi, arr, new_values, unique_resort=False): """ Replace a subset of a sorted arr with new_values. Can also ensure the resulting outcome is unique and sorted with the unique_resort option. :param lo: :param hi: :param arr: :param new_values: :param unique_resort: :return: """ result = arr[:lo] + new_values + arr[hi + 1:] if unique_resort: result = sorted(set(result)) return result
bigcode/self-oss-instruct-sc2-concepts
def remove_comment(command): """ Return the contents of *command* appearing before #. """ return command.split('#')[0].strip()
bigcode/self-oss-instruct-sc2-concepts
def getdefaultencoding(space): """Return the current default string encoding used by the Unicode implementation.""" return space.newtext(space.sys.defaultencoding)
bigcode/self-oss-instruct-sc2-concepts
def seconds_to_str(value): """Convert seconds to a simple simple string describing the amount of time.""" if value < 60: return "%s seconds" % round(value, 2) elif value < 3600: return "%s minutes" % round(value / 60, 2) else: return "%s hours and %s minutes" % (round(value / 3600, 2), round((value % 3600) / 60, 2))
bigcode/self-oss-instruct-sc2-concepts
def get_mask(k: int, c: int) -> int: """Returns the mask value to copy bits inside a single byte. :param k: The start bit index in the byte. :param c: The number of bits to copy. Examples of returned mask: Returns Arguments 00001111 k=0, c=4 01111100 k=2, c=5 00111100 k=2, c=4 """ if k == 0: return (1 << c) - 1 return (1 << ((k + 1 + c) - 1)) - (1 << ((k + 1) - 1))
bigcode/self-oss-instruct-sc2-concepts
def _hoist_track_info(track): """Mutates track with artist and album info at top level.""" track['album_name'] = track['album']['name'] artist = track['artists'][0] track['artist_name'] = artist['name'] return track
bigcode/self-oss-instruct-sc2-concepts
import time def isDSTTime(timestamp): """Helper function for determining whether the local time currently uses daylight saving time.""" local_time = time.localtime(timestamp) return time.daylight > 0 and local_time.tm_isdst > 0
bigcode/self-oss-instruct-sc2-concepts
def get_endpoints(astute_config): """Returns services endpoints :returns: dict where key is the a name of endpoint value is dict with host, port and authentication information """ master_ip = astute_config['ADMIN_NETWORK']['ipaddress'] # Set default user/password because in # 5.0.X releases we didn't have this data # in astute file fuel_access = astute_config.get( 'FUEL_ACCESS', {'user': 'admin', 'password': 'admin'}) rabbitmq_access = astute_config.get( 'astute', {'user': 'naily', 'password': 'naily'}) rabbitmq_mcollective_access = astute_config.get( 'mcollective', {'user': 'mcollective', 'password': 'marionette'}) keystone_credentials = { 'username': fuel_access['user'], 'password': fuel_access['password'], 'auth_url': 'http://{0}:5000/v2.0/tokens'.format(master_ip), 'tenant_name': 'admin'} return { 'nginx_nailgun': { 'port': 8000, 'host': '0.0.0.0', 'keystone_credentials': keystone_credentials}, 'nginx_repo': { 'port': 8080, 'host': '0.0.0.0'}, 'ostf': { 'port': 8777, 'host': '127.0.0.1', 'keystone_credentials': keystone_credentials}, 'cobbler': { 'port': 80, 'host': '127.0.0.1'}, 'postgres': { 'port': 5432, 'host': '127.0.0.1'}, 'rsync': { 'port': 873, 'host': '127.0.0.1'}, 'rsyslog': { 'port': 514, 'host': '127.0.0.1'}, 'keystone': { 'port': 5000, 'host': '127.0.0.1'}, 'keystone_admin': { 'port': 35357, 'host': '127.0.0.1'}, 'rabbitmq': { 'user': rabbitmq_access['user'], 'password': rabbitmq_access['password'], 'port': 15672, 'host': '127.0.0.1'}, 'rabbitmq_mcollective': { 'port': 15672, 'host': '127.0.0.1', 'user': rabbitmq_mcollective_access['user'], 'password': rabbitmq_mcollective_access['password']}}
bigcode/self-oss-instruct-sc2-concepts
def single_child(node): """ The single child node or None. """ result = None if node.nodes is not None and len(node.nodes) == 1: result = node.nodes[0] return result
bigcode/self-oss-instruct-sc2-concepts
def count_paras(paras): """Count the trainable parameters of the model. """ return sum(p.numel() for p in paras if p.requires_grad)
bigcode/self-oss-instruct-sc2-concepts
import re def _has_no_hashtag(href): """ Remove sub chapters :Param href: tags with the `href` attribute :Return: True if `href` exists and does not contain a hashtag else return False """ return href and not re.compile("#").search(href)
bigcode/self-oss-instruct-sc2-concepts
def orm_query_keys(query): """Given a SQLAlchemy ORM query, extract the list of column keys expected in the result.""" return [c["name"] for c in query.column_descriptions]
bigcode/self-oss-instruct-sc2-concepts
def ParsePrimitiveArgs(args, arg_name, current_value_thunk): """Parse the modification to the given repeated field. To be used in combination with AddPrimitiveArgs; see module docstring. Args: args: argparse.Namespace of parsed arguments arg_name: string, the (plural) suffix of the argument (snake_case). current_value_thunk: zero-arg function that returns the current value of the attribute to be updated. Will be called lazily if required. Raises: ValueError: if more than one arg is set. Returns: List of str: the new value for the field, or None if no change is required. """ remove = getattr(args, 'remove_' + arg_name) add = getattr(args, 'add_' + arg_name) clear = getattr(args, 'clear_' + arg_name) set_ = getattr(args, 'set_' + arg_name) if sum(map(bool, (remove, add, clear, set_))) > 1: raise ValueError('At most one arg may be set.') if remove is not None: current_value = current_value_thunk() new_value = [x for x in current_value if x not in remove] elif add is not None: current_value = current_value_thunk() new_value = current_value + [x for x in add if x not in current_value] elif clear: return [] elif set_ is not None: return set_ else: return None if new_value != current_value: return new_value else: return None
bigcode/self-oss-instruct-sc2-concepts
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'
bigcode/self-oss-instruct-sc2-concepts
def point_to_geojson(lat, lng): """ Converts a single x-y point to a GeoJSON dictionary object of coordinates :param lat: latitude of point :param lng: longitude of point :return: dictionary appropriate for conversion to JSON """ feature = { 'type': 'Feature', 'geometry': { 'type': 'Point', 'coordinates': [lat, lng] } } return feature
bigcode/self-oss-instruct-sc2-concepts
from typing import Mapping def nop(string: str, _: Mapping[str, str]) -> str: """No operation parser, returns given string unchanged. This exists primarily as a default for when no parser is given as the use of `lift(str)` is recommended when the parsed value is supposed to be a string. :param string: String to return. :param _: Mapping of tag attributes. Not used by this function. :return: The given `string`. """ return string
bigcode/self-oss-instruct-sc2-concepts
import socket def authenticate(port, password): """ Authentication function used in all testcases to authenticate with server """ s = socket.socket(family=socket.AF_INET, type=socket.SOCK_DGRAM) s.sendto(b"AUTH %s" % password, ("127.0.0.1", port)) msg, addr = s.recvfrom(1024) return (s, msg.strip())
bigcode/self-oss-instruct-sc2-concepts
import grp def groupmembers(name): """Return the list of members of the group with the given name, KeyError if the group does not exist. """ return list(grp.getgrnam(name).gr_mem)
bigcode/self-oss-instruct-sc2-concepts
import math def rotate_point(angle, point, origin): """ Rotates a point about the origin. Used from http://stackoverflow.com/q/8948001/1817465 mramazingguy asked Jan 20 '12 at 21:20 :param angle: cw from E, in degrees :param point: [x, y] :param origin: [x0, y0] :return: The point, rotated about the origin. """ sinT = math.sin(math.radians(angle)) cosT = math.cos(math.radians(angle)) return (origin[0] + (cosT * (point[0] - origin[0]) - sinT * (point[1] - origin[1])), origin[1] + (sinT * (point[0] - origin[0]) + cosT * (point[1] - origin[1])))
bigcode/self-oss-instruct-sc2-concepts
def did_to_dirname(did: str): """ Takes a Rucio dataset DID and returns a dirname like used by strax.FileSystemBackend """ # make sure it's a DATASET did, not e.g. a FILE if len(did.split('-')) != 2: raise RuntimeError(f"The DID {did} does not seem to be a dataset DID. " f"Is it possible you passed a file DID?") dirname = did.replace(':', '-').replace('xnt_', '') return dirname
bigcode/self-oss-instruct-sc2-concepts
def parse_genome_size(txt_file): """Pull out the genome size used for analysis.""" with open(txt_file, 'rt') as txt_fh: return txt_fh.readline().rstrip()
bigcode/self-oss-instruct-sc2-concepts
async def present( hub, ctx, name, lock_level, resource_group=None, notes=None, owners=None, connection_auth=None, **kwargs, ): """ .. versionadded:: 2.0.0 .. versionchanged:: 4.0.0 Ensure a management lock exists. By default this module ensures that the management lock exists at the subscription level. If you would like to ensure that the management lock exists at the resource group level instead, you can specify a resource group using the resource_group parameter. :param name: The name of the lock. The lock name can be a maximum of 260 characters. It cannot contain <, > %, &, :, ?, /, or any control characters. :param lock_level: The level of the lock. Possible values are: 'CanNotDelete' and 'ReadOnly'. CanNotDelete means authorized users are able to read and modify the resources, but not delete. ReadOnly means authorized users can only read from a resource, but they can't modify or delete it. :param resource_group: The name of the resource group. :param notes: A string representing notes about the lock. Maximum of 512 characters. :param owners: A list of strings representing owners of the lock. Each string represents the application id of the lock owner. :param connection_auth: A dict with subscription and authentication parameters to be used in connecting to the Azure Resource Manager API. Example usage: .. code-block:: yaml Ensure management lock exists: azurerm.resource.management_lock.present: - name: my_lock - lock_level: 'ReadOnly' """ ret = {"name": name, "result": False, "comment": "", "changes": {}} action = "create" if not isinstance(connection_auth, dict): if ctx["acct"]: connection_auth = ctx["acct"] else: ret[ "comment" ] = "Connection information must be specified via acct or connection_auth dictionary!" return ret if resource_group: lock = await hub.exec.azurerm.resource.management_lock.get_at_resource_group_level( ctx, name, resource_group, azurerm_log_level="info", **connection_auth ) else: lock = await hub.exec.azurerm.resource.management_lock.get_at_subscription_level( ctx, name, azurerm_log_level="info", **connection_auth ) if "error" not in lock: action = "update" if lock_level != lock.get("level"): ret["changes"]["level"] = {"old": lock.get("level"), "new": lock_level} if notes != lock.get("notes"): ret["changes"]["notes"] = {"old": lock.get("notes"), "new": notes} if owners: new_owners = owners.sort() lock_owners = lock.get("owners", []) if lock_owners: # Extracts the application_id value from each dictionary that represents a ManagementLockOwner object old_owners = [owner.get("application_id") for owner in lock_owners] old_owners = old_owners.sort() else: old_owners = [] if old_owners != new_owners: ret["changes"]["owners"] = {"old": old_owners, "new": new_owners} if not ret["changes"]: ret["result"] = True ret["comment"] = "Management lock {0} is already present.".format(name) return ret if ctx["test"]: ret["result"] = None ret["comment"] = "Management lock {0} would be updated.".format(name) return ret if ctx["test"]: ret["comment"] = "Management lock {0} would be created.".format(name) ret["result"] = None return ret lock_kwargs = kwargs.copy() lock_kwargs.update(connection_auth) if resource_group: lock = await hub.exec.azurerm.resource.management_lock.create_or_update_at_resource_group_level( ctx=ctx, name=name, resource_group=resource_group, lock_level=lock_level, notes=notes, owners=owners, **lock_kwargs, ) else: lock = await hub.exec.azurerm.resource.management_lock.create_or_update_at_subscription_level( ctx=ctx, name=name, lock_level=lock_level, notes=notes, owners=owners, **lock_kwargs, ) if action == "create": ret["changes"] = {"old": {}, "new": lock} if "error" not in lock: ret["result"] = True ret["comment"] = f"Management lock {name} has been {action}d." return ret ret["comment"] = "Failed to {0} management lock {1}! ({2})".format( action, name, lock.get("error") ) if not ret["result"]: ret["changes"] = {} return ret
bigcode/self-oss-instruct-sc2-concepts
def sort_set_by_list(s, l, keep_duplicates=True): """ Convert the set `s` into a list ordered by a list `l`. Elements in `s` which are not in `l` are omitted. If ``keep_duplicates==True``, keep duplicate occurrences in `l` in the result; otherwise, only keep the first occurrence. """ if keep_duplicates: return [e for e in l if e in s] else: res=[] s=s.copy() for e in l: if e in s: res.append(e) s.remove(e) return res
bigcode/self-oss-instruct-sc2-concepts
import pytz def IsValidTimezone(timezone): """ Checks the validity of a timezone string value: - checks whether the timezone is in the pytz common_timezones list - assumes the timezone to be valid if the pytz module is not available """ try: return timezone in pytz.common_timezones except ImportError: # no pytz print("Timezone not checked " "(install pytz package for timezone validation)") return True
bigcode/self-oss-instruct-sc2-concepts
def xp_to_level(level: int): """Returns the amount of EXP needed for a level. Parameters ---------- level: int The level to find the amount of EXP needed for. Returns ------- int: The amount of EXP required for the level. """ return (level ** 3) // 2
bigcode/self-oss-instruct-sc2-concepts
def gpu_size(wildcards, attempt): """Return model size in gb based on {prot} and {model}""" prot = wildcards.get('prot', 'V3') model = wildcards.get('model', 'protbert') if 'bert' not in model: return 0 if prot == 'V3': return 9*attempt return 12*attempt
bigcode/self-oss-instruct-sc2-concepts
def is_prime(P): """ Method to check if a number is prime or composite. Parameters: P (int): number to be checked, must be greater than 1 Returns: bool: True if prime, False if composite """ for i in range(2, P): j = P % i if j == 0: return False return True
bigcode/self-oss-instruct-sc2-concepts
def h(number): """ convert a number to a hex representation, with no leading '0x'. Example:: assert h(16) == '10' assert hex(16) == '0x10' """ return "%02x" % number
bigcode/self-oss-instruct-sc2-concepts
def add_feature_transaction_completed_ratio(profile_updated_df): """ Create feature transcation count to offer completed ratio to avoid np.inf as a result of division, a 0.1 number was added to the denominator """ profile_updated = profile_updated_df.copy() profile_updated['transaction_completed_ratio'] = \ profile_updated.transaction_count / (profile_updated.offer_completed_total + 0.1) return profile_updated
bigcode/self-oss-instruct-sc2-concepts
from typing import Sequence def max_len( row: Sequence) \ -> int: """ Max `len` of 1d array. """ return max(len(str(x)) for x in row)
bigcode/self-oss-instruct-sc2-concepts
def calculate_air_density(pressure, temperature): """ Calculates air density from ideal gas law. :param pressure: Air pressure in Pascals :param temp: Air temperature in Kelvins :return density: Air density in kg/m^2 """ R = 286.9 # specific gas constant for air [J/(kg*K)] density = pressure/(R*temperature) return density
bigcode/self-oss-instruct-sc2-concepts
import pprint def api_message_to_javadoc(api_message): """ Converts vpe.api message description to javadoc """ str = pprint.pformat(api_message, indent=4, width=120, depth=None) return " * " + str.replace("\n", "\n * ")
bigcode/self-oss-instruct-sc2-concepts
def set_ranks(taxonomy): """Set ranks for species/subspecies creation.""" default_ranks = [ "genus", "family", "order", "class", "subphylum", "phylum", ] taxon_rank = None if "subspecies" in taxonomy: ranks = ["species"] + default_ranks taxon_rank = "subspecies" else: ranks = default_ranks for rank in ["species"] + default_ranks: if rank in taxonomy: taxon_rank = rank break return ranks, taxon_rank
bigcode/self-oss-instruct-sc2-concepts
def read_xyz(filepath): """ Reads coordinates from an xyz file. Parameters ---------- filepath : str The path to the xyz file to be processed. Returns ------- atomic_coordinates : list A two dimensional list containing atomic coordinates """ with open(filepath) as f: box_length = float(f.readline().split()[0]) num_atoms = float(f.readline()) coordinates = f.readlines() atomic_coordinates = [] for atom in coordinates: split_atoms = atom.split() float_coords = [] # We split this way to get rid of the atom label. for coord in split_atoms[1:]: float_coords.append(float(coord)) atomic_coordinates.append(float_coords) return atomic_coordinates, box_length
bigcode/self-oss-instruct-sc2-concepts
def get_adaptive_eval_interval(cur_dev_size, thres_dev_size, base_interval): """ Adjust the evaluation interval adaptively. If cur_dev_size <= thres_dev_size, return base_interval; else, linearly increase the interval (round to integer times of base interval). """ if cur_dev_size <= thres_dev_size: return base_interval else: alpha = round(cur_dev_size / thres_dev_size) return base_interval * alpha
bigcode/self-oss-instruct-sc2-concepts
def convert88to256(n): """ 88 (4x4x4) color cube to 256 (6x6x6) color cube values """ if n < 16: return n elif n > 79: return 234 + (3 * (n - 80)) else: def m(n): "0->0, 1->1, 2->3, 3->5" return n and n + n-1 or n b = n - 16 x = b % 4 y = (b // 4) % 4 z = b // 16 return 16 + m(x) + (6 * m(y) + 36 * m(z))
bigcode/self-oss-instruct-sc2-concepts
def standard(X): """ standard : This function makes data ragbe between 0 and 1. Arguments: X (numoy array) : input data. -------- Returns: standard data. """ xmin = X.min() X = X-xmin xmax = X.max() X = X/xmax return X
bigcode/self-oss-instruct-sc2-concepts
def list_to_sql_in_list(l): """Convert a python list into a string that can be used in an SQL query with operator "in" """ return '(' + ','.join(f"'{e}'" for e in l) + ')'
bigcode/self-oss-instruct-sc2-concepts
def any(seq, pred=None): """Returns True if pred(x) is true for at least one element in the iterable""" for elem in filter(pred, seq): return True return False
bigcode/self-oss-instruct-sc2-concepts
def vectorize(tokens, vocab): """ Covert array of tokens, to array of ids Args: tokens (list): list of tokens vocab (Vocab): Returns: list of ids """ ids = [] for token in tokens: if token in vocab.tok2id: ids.append(vocab.tok2id[token]) else: ids.append(vocab.tok2id[vocab.UNK]) return ids
bigcode/self-oss-instruct-sc2-concepts
def generate_symbol_definitions_direct(symbols, prefix): """Generate a listing of definitions to point to real symbols.""" ret = [] for ii in symbols: ret += [ii.generate_rename_direct(prefix)] return "\n".join(ret)
bigcode/self-oss-instruct-sc2-concepts
import re def cleanOfSpaces(myString): """Clean a string of trailing spaces""" myString = re.sub("^( )+", "", myString) myString = re.sub("( )+$", "", myString) return myString
bigcode/self-oss-instruct-sc2-concepts
def get_build_os_arch(conanfile): """ Returns the value for the 'os' and 'arch' settings for the build context """ if hasattr(conanfile, 'settings_build'): return conanfile.settings_build.get_safe('os'), conanfile.settings_build.get_safe('arch') else: return conanfile.settings.get_safe('os_build'), conanfile.settings.get_safe('arch_build')
bigcode/self-oss-instruct-sc2-concepts
def observe_rate(rate, redshift): """Returns observable burst rate (per day) from given local rate """ return rate / redshift
bigcode/self-oss-instruct-sc2-concepts
from typing import Counter def find_occurrences(number_list): """Finds how many times every number in a list occurs.""" counter = Counter(number_list) occurrences = counter.most_common() return occurrences
bigcode/self-oss-instruct-sc2-concepts
def add_vectors(v1, v2): """ Adds 2 vector :param v1: vector 1 :param v2: vector 2 :return: v1 + v2 """ return tuple([v1[i] + v2[i] for i in range(0, len(v1))])
bigcode/self-oss-instruct-sc2-concepts
def _get_issue_tracker(obj): """Get issue_tracker dict from obj if dict is based on existing tracker""" if not obj: return None ret = obj.issue_tracker if not ret.get('_is_stub'): return ret return None
bigcode/self-oss-instruct-sc2-concepts
import random def ordered(parent1, parent2, point=None): """Return a new chromosome using ordered crossover (OX). This crossover method, also called order-based crossover, is suitable for permutation encoding. Ordered crossover respects the relative position of alleles. Args: parent1 (List): A parent chromosome. parent2 (List): A parent chromosome. points (int): The point at which to cross over. Returns: List[List]: Two new chromosomes descended from the given parents. """ if point is None: point = random.randint(0, len(parent1) - 1) def fill(child, parent): for value in parent2: if value not in child: child.append(value) child1 = parent1[0:point] child2 = parent2[0:point] fill(child1, parent2) fill(child2, parent1) return [child1, child2]
bigcode/self-oss-instruct-sc2-concepts
def _weighted_sum(*args): """Returns a weighted sum of [(weight, element), ...] for weights > 0.""" # Note: some losses might be ill-defined in some scenarios (e.g. they may # have inf/NaN gradients), in those cases we don't apply them on the total # auxiliary loss, by setting their weights to zero. return sum(x * w for w, x in args if w > 0)
bigcode/self-oss-instruct-sc2-concepts
def rh_from_avp_svp(avp, sat_vp): """ Calculate relative humidity as the ratio of actual vapour pressure to saturation vapour pressure at the same temperature. See Allen et al (1998), page 67 for details. :param avp: Actual vapour pressure [units do not matter so long as they are the same as for *svp*]. Can be estimated using functions whose name begins with 'avp_from'. :param sat_vp: Saturated vapour pressure [units do not matter so long as they are the same as for *avp*]. Can be estimated using ``svp_from_t()``. :return: Relative humidity [%]. :rtype: float """ return 100.0 * avp / sat_vp
bigcode/self-oss-instruct-sc2-concepts
from datetime import datetime def str_to_timestamp(time_as_str, time_format) -> float: """转换时间字符串为unix时间戳 Args: time_as_str: 时间字符串, 比如: 2019-09-10 15:20:25 time_format: 时间格式, 比如: %Y-%m-%d %H:%M:%S Returns: unix时间戳, 类型: float """ datetime_ = datetime.strptime(time_as_str, time_format) return datetime_.timestamp()
bigcode/self-oss-instruct-sc2-concepts
from typing import OrderedDict def remove_signature_parameters(s, *param_names): """ Removes the provided parameters from the signature s (returns a new signature instance). :param s: :param param_names: a list of parameter names to remove :return: """ params = OrderedDict(s.parameters.items()) for param_name in param_names: del params[param_name] return s.replace(parameters=params.values())
bigcode/self-oss-instruct-sc2-concepts
def frequencies_imp(word_list): """ Takes a list of words and returns a dictionary associating words with frequencies of occurrence """ word_freqs = {} for w in word_list: if w in word_freqs: word_freqs[w] += 1 else: word_freqs[w] = 1 return word_freqs
bigcode/self-oss-instruct-sc2-concepts
def transforms_are_applied(obj): """ Check that the object is at 0,0,0 and has scale 1,1,1 """ if ( obj.location.x != 0 or obj.location.y != 0 or obj.location.z != 0 ): return False if ( obj.rotation_euler.x != 0 or obj.rotation_euler.y != 0 or obj.rotation_euler.z != 0 ): return False if ( obj.scale.x != 1 or obj.scale.y != 1 or obj.scale.z != 1 ): return False return True
bigcode/self-oss-instruct-sc2-concepts
def get_distinct_values(df, key): """Get the distinct values that are present in a given column.""" return sorted(list(df[key].value_counts().index.values))
bigcode/self-oss-instruct-sc2-concepts
def get_path_array(node): """ Takes an end node and gives you every node (in order) for the shortest path to it. PARAMS: node (node): end node RETURNS: array[nodes]: every note you need to visit (in order) """ if node.shortest_path_via == None: return [node] else: return get_path_array(node.shortest_path_via) + [node]
bigcode/self-oss-instruct-sc2-concepts
def decode_prefix(byte): """Decode a byte according to the Field Prefix encoding scheme. Arguments: byte: the encoded representation of the prefix Return: fixedwidth: Is the field fixed width (bool) variablewidth: if not fixed width, the number of bytes needed to encode the value width (1, 2 or 4) has_ordinal: The field has an ordinal encoded (bool) has_name: This field has a name encoded (bool) """ fixedwidth = (byte & 0x80) != 0 has_name = (byte & 0x08) != 0 has_ordinal = (byte & 0x10) != 0 variablewidth = (byte & 0x60) >>5 if variablewidth == 3: variablewidth = 4 return fixedwidth, variablewidth, has_ordinal, has_name
bigcode/self-oss-instruct-sc2-concepts
import requests def ct_get_lists(api_token=""): """Retrieve the lists, saved searches and saved post lists of the dashboard associated with the token sent in Args: api_token (str, optional): you can locate your API token via your crowdtangle dashboard under Settings > API Access. Returns: [dict]: The Response contains both a status code and a result. The status will always be 200 if there is no error. The result contains an array of a lists objects Example: ct_get_lists(api_token="AKJHXDFYTGEBKRJ6535") """ # api-endpoint URL_BASE = "https://api.crowdtangle.com/lists" # defining a params dict for the parameters to be sent to the API PARAMS = {'token': api_token} # sending get request and saving the response as response object r = requests.get(url=URL_BASE, params=PARAMS) if r.status_code != 200: out = r.json() print(f"status: {out['status']}") print(f"Code error: {out['code']}") print(f"Message: {out['message']}") return r.json()
bigcode/self-oss-instruct-sc2-concepts
def build_endpoint_description_strings( host=None, port=None, unix_socket=None, file_descriptor=None ): """ Build a list of twisted endpoint description strings that the server will listen on. This is to streamline the generation of twisted endpoint description strings from easier to use command line args such as host, port, unix sockets etc. """ socket_descriptions = [] if host and port is not None: host = host.strip("[]").replace(":", r"\:") socket_descriptions.append("tcp:port=%d:interface=%s" % (int(port), host)) elif any([host, port]): raise ValueError("TCP binding requires both port and host kwargs.") if unix_socket: socket_descriptions.append("unix:%s" % unix_socket) if file_descriptor is not None: socket_descriptions.append("fd:fileno=%d" % int(file_descriptor)) return socket_descriptions
bigcode/self-oss-instruct-sc2-concepts
def force_charge_fit(mol, current_rule, match): """ Forces the formal charges of a rule to match the formal charges of a molecule. Parameters ---------- mol: rdkit.Chem.Mol RDKit molecule object. current_rule: rdkit.Chem.Mol RDKit molecule object of rule match: tuple Indices of matching atoms in current_rule and mol. Returns ------- current_rule: rdkit.Chem.Mol RDKit molecule object of rule with updated formal charges. """ for idx in range(len(match)): current_rule.GetAtomWithIdx(idx).SetFormalCharge( mol.GetAtomWithIdx(match[idx]).GetFormalCharge() ) return current_rule
bigcode/self-oss-instruct-sc2-concepts
def dataframe_map_module_to_weight(row) -> int: """ Return the weight of a given module from a dataframe row based on the module level and the module name (since the final project is worth more). Args: row (dataframe row): A row from a dataframe containing at least two columns, `Level` and `Module name`. Returns: int: Integer value corresponding to the weight of a module. """ if row["Level"] == 4: return 1 if row["Level"] == 5: return 3 if row["Level"] == 6 and row["Module name"] != "Final Project": return 5 return 10
bigcode/self-oss-instruct-sc2-concepts
def is_foreign_key(col): """Check if a column is a foreign key.""" if col.foreign_keys: return True return False
bigcode/self-oss-instruct-sc2-concepts
def _build_body(res): """ Build the body of the Exchange appointment for a given Reservation. :type res: resources.models.Reservation :return: str """ return res.event_description or ''
bigcode/self-oss-instruct-sc2-concepts
def mm_as_m(mm_value): """Turn a given mm value into a m value.""" if mm_value == 'None': return None return float(mm_value) / 1000
bigcode/self-oss-instruct-sc2-concepts
def verify_positive(value): """Throws exception if value is not positive""" if not value > 0: raise ValueError("expected positive integer") return value
bigcode/self-oss-instruct-sc2-concepts
def get_devices_dict(version, image=None, arch=None, feature=None): """Based on version and image, returns a dictionary containing the folder location and the patterns of the installation files for each device type :param version: build version, e.g. 6.2.3-623 :param image: optional, 'Autotest' or 'Restore', required for M3, M4, S3 (FMC and Sensor) :param arch: optional, device architecture, required for S3 (FMC and Sensor) - e.g x86_64 :param feature: optional, whether the build is on a feature branch (e.g. MARIADB) :return: a dictionary """ if feature is None: feature = '' else: feature = ".{}".format(feature) devices = { 'kenton': {'patterns': ['ftd-[\d\.-]+{}.pkg'.format(feature), 'ftd-boot-[\d.]+lfbff'], 'subdir': ['installers', 'installers/doNotRelease'], }, 'saleen': {'patterns': ['ftd-[\d\.-]+{}.pkg'.format(feature), 'ftd-boot-[\d.]+cdisk'], 'subdir': ['installers', 'installers/doNotRelease'], }, 'elektra': {'patterns': ['asasfr-sys-[\d.-]+.pkg', 'asasfr-5500x-boot-[\d.-]+img'], 'subdir': ['installers', 'installers/doNotRelease'], }, 'm3': {'patterns': ['Sourcefire_Defense_Center_S3-{}{}-{}.iso'.format(version, feature, image), 'Sourcefire_Defense_Center-{}{}-{}.iso'.format(version, feature, image), 'Cisco_Firepower_Mgmt_Center-{}{}-{}.iso'.format(version, feature, image)], 'subdir': ['iso', 'iso/doNotRelease'], }, 'm4': {'patterns': ['Sourcefire_Defense_Center_M4-{}{}-{}.iso'.format(version, feature, image), 'Cisco_Firepower_Mgmt_Center-{}{}-{}.iso'.format(version, feature, image), 'Sourcefire_Defense_Center-{}{}-{}.iso'.format(version, feature, image)], 'subdir': ['iso', 'iso/doNotRelease'], }, 'm5': {'patterns': ['Sourcefire_Defense_Center-{}{}-{}.iso'.format(version, feature, image), 'Cisco_Firepower_Mgmt_Center-{}{}-{}.iso'.format(version, feature, image)], 'subdir': ['iso', 'iso/doNotRelease'], }, 's3fmc': {'patterns': ['Sourcefire_Defense_Center_S3-{}{}-{}.iso'.format(version, feature, image), 'Cisco_Firepower_Mgmt_Center-{}{}-{}.iso'.format(version, feature, image)], 'subdir': ['iso', 'iso/doNotRelease'], 'boot_images': {'os/{}/boot'.format(arch): 'bzImage.*', 'os/{}/ramdisks'.format(arch): 'usb-ramdisk*'} }, 's3': {'patterns': ['Sourcefire_3D_Device_S3-{}{}-{}.iso'.format(version, feature, image), 'Cisco_Firepower_NGIPS_Appliance-{}{}-{}.iso'.format(version, feature, image)], 'subdir': ['iso', 'iso/doNotRelease'], 'boot_images': {'os/{}/boot'.format(arch): 'bzImage.*', 'os/{}/ramdisks'.format(arch): 'usb-ramdisk*'} }, 'kp': {'patterns': ['cisco-ftd-fp2k[\d.-]+[a-zA-Z]{3}', 'fxos-k8-fp2k-lfbff[\w.-]+[a-zA-Z]{3}', 'fxos-k8-lfbff[\w.-]+[a-zA-Z]{3}'], 'subdir': ['installers', 'installers/doNotRelease'], }, 'ssp': {'patterns': ['cisco-ftd[\d.-]+[a-zA-Z]{3}.csp'], 'subdir': ['installers', 'installers/doNotRelease'], } } return devices
bigcode/self-oss-instruct-sc2-concepts
def close_enough(v1,v2): """ Helper function for testing if two values are "close enough" to be considered equal. """ return abs(v1-v2) <= 0.0001
bigcode/self-oss-instruct-sc2-concepts
def map_onto_scale(p1, p2, s1, s2, v): """Map value v from original scale [p1, p2] onto standard scale [s1, s2]. Parameters ---------- p1, p2 : number Minimum and maximum percentile scores. s1, s2 : number Minimum and maximum intensities on the standard scale. v : number Value to map. Returns ------- r : float Mapped value. """ assert p1 <= p2, (p1, p2) assert s1 <= s2, (s1, s2) if p1 == p2: assert s1 == s2, (p1, p2, s1, s2) return s1 f = (v-p1) / (p2-p1) r = f * (s2-s1) + s1 return r
bigcode/self-oss-instruct-sc2-concepts
def _read_phone(text_path): """Read phone-level transcripts. Args: text_path (string): path to a transcript text file Returns: transcript (string): a text of transcript """ # Read ground truth labels phone_list = [] with open(text_path, 'r') as f: for line in f: line = line.strip().split(' ') phone_list.append(line[-1]) transcript = ' '.join(phone_list) return transcript
bigcode/self-oss-instruct-sc2-concepts
def pytorch_array_to_scalar(v): """Implementation of array_to_scalar for pytorch.""" if v.is_cuda: v = v.cpu() return v.detach().numpy()
bigcode/self-oss-instruct-sc2-concepts
def create_tagging_decorator(tag_name): """ Creates a new decorator which adds arbitrary tags to the decorated functions and methods, enabling these to be listed in a registry :param tag_name: :return: """ def tagging_decorator(*args, **kwargs): # here we can receive the parameters handed over on the decorator (@decorator(a=b)) def wrapper(method): method.member_tag = (tag_name, {'args': args, 'kwargs': kwargs}) return method return wrapper return tagging_decorator
bigcode/self-oss-instruct-sc2-concepts
def incr(num): """ Increment its argument by 1. :param num: number :return: number """ return num + 1
bigcode/self-oss-instruct-sc2-concepts
from datetime import datetime def convertDateToUnix(dstr): """ Convert a given string with MM/DD/YYYY format to millis since epoch """ d = datetime.strptime(dstr, '%m/%d/%Y') return int((d - datetime.utcfromtimestamp(0)).total_seconds() * 1000)
bigcode/self-oss-instruct-sc2-concepts
def split_text(txt, trunc=None): """Split text into sentences/words Args: txt(str): text, as a single str trunc(int): if not None, stop splitting text after `trunc` words and ignore sentence containing `trunc`-th word (i.e. each sentence has len <= trunc) Returns: sentences(list): list of sentences (= list of lists of words) """ n_words = 0 sentence_break = [".", "?", "!"] sentences = [] cur_sentence = [] for word in txt.split(): if word in sentence_break: if len(cur_sentence) != 0: cur_sentence.append(word) sentences.append(cur_sentence) cur_sentence = [] else: pass else: n_words += 1 cur_sentence.append(word) if trunc is not None and n_words > trunc: cur_sentence = [] break if len(cur_sentence) != 0: sentences.append(cur_sentence) return sentences
bigcode/self-oss-instruct-sc2-concepts
def get_auth_dict(auth_string): """ Splits WWW-Authenticate and HTTP_AUTHORIZATION strings into a dictionaries, e.g. { nonce : "951abe58eddbb49c1ed77a3a5fb5fc2e"', opaque : "34de40e4f2e4f4eda2a3952fd2abab16"', realm : "realm1"', qop : "auth"' } """ amap = {} for itm in auth_string.split(", "): (k, v) = [s.strip() for s in itm.split("=", 1)] amap[k] = v.replace('"', '') return amap
bigcode/self-oss-instruct-sc2-concepts