seed
stringlengths
1
14k
source
stringclasses
2 values
def parse_copy_availability(line): """Parses 'Status-'line for availability. :param line: Line string. :type line: str :return: Availability. :rtype: bool """ if 'Entliehen' in line: return False elif 'Verfügbar' in line: return True else: return False
bigcode/self-oss-instruct-sc2-concepts
def _get_location_extension_feeds(client, customer_id): """Gets the location extension feeds. Args: client: The Google Ads API client. customer_id: The Google Ads customer ID. Returns: The list of location extension feeds. """ googleads_service = client.get_service("GoogleAdsService") # Create the query. query = """ SELECT feed.resource_name, feed.status, feed.places_location_feed_data.email_address, feed.affiliate_location_feed_data.chain_ids FROM feed WHERE feed.status = ENABLED""" search_results = googleads_service.search( customer_id=customer_id, query=query ) # A location extension feed can be identified by checking whether the # PlacesLocationFeedData field is set (Location extensions feeds) or # AffiliateLocationFeedData field is set (Affiliate location extension # feeds) return [ row.feed for row in search_results if row.feed.places_location_feed_data or row.feed.affiliate_location_feed_data ]
bigcode/self-oss-instruct-sc2-concepts
def get_fastq_stats(fastq_filehandle): """Return some basic statistics for a fastq file.""" read_count, gc_count, total_base_count = 0, 0, 0 for i, line in enumerate(fastq_filehandle): if i != 1: # only process the reads from the fastq continue read_count += 1 for base in line.strip().upper(): total_base_count += 1 if base in ['G', 'C']: gc_count += 1 gc_fraction = gc_count / total_base_count return read_count, gc_fraction
bigcode/self-oss-instruct-sc2-concepts
def filter_rule_ids(all_keys, queries): """ From a set of queries (a comma separated list of queries, where a query is either a rule id or a substring thereof), return the set of matching keys from all_keys. When queries is the literal string "all", return all of the keys. """ if not queries: return set() if queries == 'all': return set(all_keys) # We assume that all_keys is much longer than queries; this allows us to do # len(all_keys) iterations of size len(query_parts) instead of len(query_parts) # queries of size len(all_keys) -- which hopefully should be a faster data access # pattern due to caches but in reality shouldn't matter. Note that we have to iterate # over the keys in all_keys either way, because we wish to check whether query is a # substring of a key, not whether query is a key. # # This does have the side-effect of not having the results be ordered according to # their order in query_parts, so we instead, we intentionally discard order by using # a set. This also guarantees that our results are unique. results = set() query_parts = queries.split(',') for key in all_keys: for query in query_parts: if query in key: results.add(key) return results
bigcode/self-oss-instruct-sc2-concepts
def is_quoted_retweet(text): """ Determines if the text begins with a quoted retweet :param text: The text to analyze (str) :return: true | false """ return int(text[:2] == '"@')
bigcode/self-oss-instruct-sc2-concepts
import re def lower_intradocument_links(rst): """Lowercase intra-document links Reference names are converted to lowercase when HTML is rendered from reST (https://bit.ly/2yXRPzL). Intra-document links must be lowercased in order to preserve linkage. `The Link <#Target-No.1>`__ -> `The Link <#target-no.1>`__ """ pattern = r'`%s <#%s>`__' rst = re.sub(pattern % (r'([^<]+)', r'([^>]+)'), lambda m: pattern % (m.group(1), m.group(2).lower()), rst) return rst
bigcode/self-oss-instruct-sc2-concepts
def mean_average(list_of_numbers): """Return the mean average of a list of numbers.""" return sum(list_of_numbers) / len(list_of_numbers)
bigcode/self-oss-instruct-sc2-concepts
import pathlib import json def read_lipids_topH(filenames): """Generate a list of lipid hydrogen topologies. This function read a list of json files containing the topology of a united-atom lipid for reconstructing the missing hydrogens. The list topologies is stored as dictionary were the key is "ForceField_lipidname" (e.g Berger_POPC, CHARMM_DMPC). If there is multiple lipid residue name in the key 'resname' of the json, it will create one dictionary for one element of this key. Parameters ---------- filenames : list of str List of json files containing topologies. Returns ------- dictionary of dictionary the lipid topologies. Raises ------ ValueError When a file doesn't have a correct format. """ lipids_tops = {} for filename in filenames: filenam_path = pathlib.Path(filename) with open(filenam_path) as json_file: try: topol = json.load(json_file) except Exception as e: raise ValueError(f"{filenam_path} is in a bad format.") from e # make sure at least 'resname' key exists if "resname" not in topol: raise ValueError(f"{filenam_path} is in a bad format.") # Retrieve forcefield and lipid name from the filename try: ff, lipid_name = filenam_path.stem.split("_") except ValueError as e: raise ValueError(f"{filenam_path} has an incorrect name. " "It should be Forcefield_LipidName.json") from e # Generate keys by combining forcefield, the lipid name from the filename # and the possibles others lipids names from the json 'resname' attribut. # set() remove duplicates resnames = set([lipid_name] + topol["resname"]) # Create distinct topology dictionaries for each resname supported in the json. for resname in resnames: data = topol.copy() data['resname'] = resname key = f"{ff}_{resname}" lipids_tops[key] = data return lipids_tops
bigcode/self-oss-instruct-sc2-concepts
def stringify_steamids(list_of_steamids): """ Args: list_of_steamids: list of steamids Returns: Single string with steamids separated by comma """ return ','.join(list(map(str, list_of_steamids)))
bigcode/self-oss-instruct-sc2-concepts
from typing import OrderedDict def create_epoch_dict(epochs): """ Creates an ordered dictionary of epoch keys and a list of lists, where the first list is the average flux of the bin, and second list the CTE loss slope. Parameters: epochs : list of ints/floats Returns: epoch_dict : dict of lists Keys of epoch. Values of empty lists. Outputs: nothing """ epoch_dict = OrderedDict() for epoch in epochs: epoch_dict[epoch] = [] return epoch_dict
bigcode/self-oss-instruct-sc2-concepts
def load_list_room_items(data, room_names): """ Loading each room respective list of items. Parameters: data(dict): Nested dictionaries containing all information of the game. room_names(list): List containg room names. Returns: items_list(list): Returns list of room items. """ items_list = [] for name in room_names: item_list = data['Rooms'][name]['Items'] items_list.append(item_list) return items_list
bigcode/self-oss-instruct-sc2-concepts
def convert_to_nvc(vertices, faces): """Convert into format expected by CUDA kernel. Nb of triangles x 3 (vertices) x 3 (xyz-coordinate/vertex) WARNING: Will destroy any resemblance of UVs Args: vertices (torch.Tensor): tensor of all vertices faces (torch.Tensor): tensor of all triangle faces """ mesh = vertices[faces.flatten()].reshape(faces.size()[0], 3, 3) return mesh.contiguous()
bigcode/self-oss-instruct-sc2-concepts
def update_docstring_references(obj, ref="ref"): """ Updates docstring reference names to strings including the function name. Decorator will return the same function with a modified docstring. Sphinx likes unique names - specifically for citations, not so much for footnotes. Parameters ----------- obj : :class:`func` | :class:`class` Class or function for which to update documentation references. ref : :class:`str` String to replace with the object name. Returns ------- :class:`func` | :class:`class` Object with modified docstring. """ name = obj.__name__ if hasattr(obj, "__module__"): name = obj.__module__ + "." + name obj.__doc__ = str(obj.__doc__).replace(ref, name) return obj
bigcode/self-oss-instruct-sc2-concepts
def is_dataclass_type(cls): """Returns whether cls is a dataclass.""" return isinstance(cls, type) and hasattr(cls, "__dataclass_fields__")
bigcode/self-oss-instruct-sc2-concepts
import pickle def _encode(o): """Encodes an object with cPickle""" return pickle.dumps(o, pickle.HIGHEST_PROTOCOL)
bigcode/self-oss-instruct-sc2-concepts
def get_signal_frame(l4e_data_frame, model_name): """ Converts a dataframe from an L4E style to a Seeq signal style PARAMS ====== l4e_data_frame: pandas.DataFrame (Required) A dataframe returned from lookout_equipment_utils.get_predictions_data_frame() model_name: string (Required) The model name that generated these predictions RETURNS ======= signal_frame: pandas.DataFrame A dataframe conforming to the SPy format for a signal dataframe """ cols = [] for value in list(l4e_data_frame): if value == 'prediction': cols.append(model_name + '.' + value) else: cols.append(model_name + '.' + value + ".contribution") l4e_data_frame.columns = cols return l4e_data_frame
bigcode/self-oss-instruct-sc2-concepts
from typing import Iterable from typing import List from typing import Optional def sorted_dedup(iterable: Iterable) -> List[Optional[int]]: """Sorted deduplication without removing the possibly duplicated `None` values.""" dedup: List[Optional[int]] = [] visited = set() for item in iterable: if item is None: dedup.append(item) elif item not in visited: dedup.append(item) visited.add(item) return dedup
bigcode/self-oss-instruct-sc2-concepts
def xor(a, b): """Return the XOR of two byte sequences. The length of the result is the length of the shortest.""" return bytes(x ^ y for (x, y) in zip(a, b))
bigcode/self-oss-instruct-sc2-concepts
import uuid def create_api_release( client, resource_group_name, service_name, api_id, api_revision, release_id=None, if_match=None, notes=None): """Creates a new Release for the API.""" if release_id is None: release_id = uuid.uuid4().hex api_id1 = "/apis/" + api_id + ";rev=" + api_revision return client.api_release.create_or_update( resource_group_name, service_name, api_id, release_id, "*" if if_match is None else if_match, api_id1, notes)
bigcode/self-oss-instruct-sc2-concepts
def cli_parse(parser): """Add method specific options to CLI parser. Parameters ---------- parser : argparse object Returns ---------- Updated argparse object """ parser.add_argument('-M', '--M', type=int, required=False, default=4, help='Inference parameter') parser.add_argument('-r', '--resamples', type=int, required=False, default=100, help='Number of bootstrap resamples for Sobol ' 'confidence intervals') return parser
bigcode/self-oss-instruct-sc2-concepts
def readme_contents_section_exists(path: str) -> bool: """ Given a README.md path, checks to see if there is a Contents section """ try: with open(path, 'r') as f: return '## Contents' in f.read() except FileNotFoundError: return False
bigcode/self-oss-instruct-sc2-concepts
import math def is_power_of_n(num:int,n :int) ->bool: """ Check whether a number is a power of n. Parameters: num: the number to be checked n: the number those power num is checked Returns: True if number is a power of n, otherwise False """ if num <= 0: raise ValueError else: if(math.ceil(math.log10(num)/math.log10(n))==math.floor(math.log10(num)/math.log10(n))): return True else: return False
bigcode/self-oss-instruct-sc2-concepts
def hours_to_days(hours): """ Convert the given amount of hours to a 2-tuple `(days, hours)`. """ days = int(hours // 8) hours_left = hours % 8 return days, hours_left
bigcode/self-oss-instruct-sc2-concepts
def get_primes(start, stop): """Return a list of prime numbers in ``range(start, stop)``.""" if start >= stop: return [] primes = [2] for n in range(3, stop + 1, 2): for p in primes: if n % p == 0: break else: primes.append(n) while primes and primes[0] < start: del primes[0] return primes
bigcode/self-oss-instruct-sc2-concepts
def format_number(number): """Format numbers for display. if < 1, return 2 decimal places if <10, return 1 decimal places otherwise, return comma formatted number with no decimal places Parameters ---------- number : float Returns ------- string """ if number == 0: return "0" if number < 0.01: return "< 0.01" if number < 1: round1 = int(number * 10) / 10 if round1 == number: return f"{round1:.1f}" else: number = int(number * 100) / 100 return f"{number:.2f}" if number < 10: if int(number) == number: return f"{number:.0f}" number = int(number * 10) / 10 if int(number) == number: return f"{number:.0f}" return f"{number:.1f}" return f"{number:,.0f}"
bigcode/self-oss-instruct-sc2-concepts
def filter_channels_by_server(channels, server): """Remove channels that are on the designated server""" chans = [] for channel in channels: sv, chan = channel.split(".", 1) if sv == server: chans.append(chan) return chans
bigcode/self-oss-instruct-sc2-concepts
def isFloat(string): """ is the given string a float? """ try: float(string) except ValueError: return 0 else: return 1
bigcode/self-oss-instruct-sc2-concepts
def transform(m, b, n): """ Given vector 'b', Calculate vector 'a' such that: 2*a-n*one == M * (2*b-n*one), where 'one' = (1, 1) --> a = M*b + (I-M)*one*n/2 M is the transformation matrix, the coordinates of 'a' and 'b' range from 0 to n-1. """ bb = [] for j in range(len(b)): bb.append(2*b[j]-n) a = [] for i in range(len(m)): x = 0 for j in range(len(b)): x += m[i][j]*(2*b[j]-n) a.append(x) aa = [] for j in range(len(a)): aa.append((a[j]+n)//2) return tuple(aa)
bigcode/self-oss-instruct-sc2-concepts
from typing import Optional from typing import IO def openfile(spec: Optional[str]) -> Optional[IO[str]]: """Open file helper. Args: spec: file/mode spec; for example: * ``file`` uses mode ``w`` * ``file+`` uses mode ``a`` * ``file+r`` uses mode ``r`` Returns: File object, or ``None`` if spec is ``None``. """ if spec is None: return None else: parts = spec.split('+', 1) name = parts[0] mode = parts[1] if len(parts) > 1 else 'w' mode = mode or 'a' return open(name, mode=mode, buffering=1)
bigcode/self-oss-instruct-sc2-concepts
from pathlib import Path def _get_file_dict(fp,fname): """ Find an image matching fname in the collection This function searches files in a FilePattern object to find the image dictionary that matches the file name, fname. Inputs: fp - A FilePattern object fname - The name of the file to find in fp Outputs: current_image - The image dictionary matching fname, None if no matches found """ current_image = None for f in fp.iterate(): if Path(f['file']).name == fname: current_image = f break return current_image
bigcode/self-oss-instruct-sc2-concepts
def index_fasta( f ): """ Makes a simple index for a FastA file :param f: an opened fasta file :return: a dict with the chromosomes as keys and the tell positions as values """ lpos = f.tell() rval = {} # for each line in the fasta l = f.readline() while l != "" : # remove the endline l = l.rstrip() # add the previous tell to the dict if we found a new identifier if l[0] == '>': rval[ l[1:] ] = lpos # prepare for the next line lpos = f.tell() l = f.readline() # returns the index return rval
bigcode/self-oss-instruct-sc2-concepts
from typing import Tuple def _get_output_pad(plain: bool) -> Tuple[int, int, int, int]: """Return the padding for outputs. Args: plain (bool): Only show plain style. No decorations such as boxes or execution counts. Returns: Tuple[int, int, int, int]: The padding for outputs. """ if plain: return (0, 0, 0, 0) else: return (0, 0, 0, 1)
bigcode/self-oss-instruct-sc2-concepts
def height(root): """Function to return the height of a binary tree Args: root (Node): The root node of the binary tree Returns: (int): The height of the binary tree """ left = 0 right = 0 if root.left: left = 1 + height(root.left) if root.right: right = 1 + height(root.right) return max(left, right)
bigcode/self-oss-instruct-sc2-concepts
def _to_iloc(data): """Get indexible attribute of array, so we can perform axis wise operations.""" return getattr(data, 'iloc', data)
bigcode/self-oss-instruct-sc2-concepts
def build_part_check(part, build_parts): """ check if only specific parts were specified to be build when parsing if the list build_parts is empty, then all parts will be parsed """ if not build_parts: return True return bool(part in build_parts)
bigcode/self-oss-instruct-sc2-concepts
import base64 def generate_aws_checksum(image_checksum: str) -> str: """ Takes an MD5 checksum provided by SciHub and generates a base64-encoded 128-bit version, which S3 will use to validate our file upload See https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/s3.html#S3.Client.put_object # Noqa for more information :param image_checksum: str representing the Hex MD5 checksum that SciHub provides :returns: str representing the base64-encoded checksum """ return base64.b64encode(bytearray.fromhex(image_checksum)).decode("utf-8")
bigcode/self-oss-instruct-sc2-concepts
def get_model_chain_ids(structure): """ Extracts model and chain ids from structure object. Parameters ---------- structure: Bio.PDB.Structure.Structure Returns ------- struct_id: tuple tuple of (modelid, chainid) """ modelnum = [] chainid = [] for model in structure: modelnum.append(model.get_id()) for chain in model: chainid.append(chain.get_id()) struct_id = (modelnum[0], chainid[0]) return struct_id
bigcode/self-oss-instruct-sc2-concepts
def stats_path(values): """ Return the stats path for the given Values object. """ # The filter() call here will remove any None values, so when we join() # these to get our stat path, only valid components will be joined. return '.'.join(filter(None, [ # plugin name values.plugin, # plugin instance, if any getattr(values, 'plugin_instance', None), # type, if any getattr(values, 'type', None), # The name of the type instance values.type_instance, ]))
bigcode/self-oss-instruct-sc2-concepts
def dedupe_n_flatten_list_of_lists(mega_list): """Flatten a list of lists and remove duplicates.""" return list(set([item for sublist in mega_list for item in sublist]))
bigcode/self-oss-instruct-sc2-concepts
def load_std_type(net, name, element): """ Loads standard type data from the data base. Issues a warning if stdtype is unknown. INPUT: **net** - The pandapipes network **name** - name of the standard type as string **element** - "pipe" OUTPUT: **typedata** - dictionary containing type data """ library = net.std_type[element] if name in library: return library[name] else: raise UserWarning("Unknown standard %s type %s" % (element, name))
bigcode/self-oss-instruct-sc2-concepts
def selection_sort(lst): """Implement selection sorting algorithm.""" if len(lst) < 2: return lst def smallest_index(lst): smallest = lst[0] sm_index = 0 for i in range(len(lst)): if lst[i] < smallest: smallest = lst[i] sm_index = i return sm_index result = [] for i in range(len(lst)): smallest = smallest_index(lst) result.append(lst.pop(smallest)) return result
bigcode/self-oss-instruct-sc2-concepts
import string def base_encode(number, alphabet=string.ascii_lowercase, fill=None): """Encode a number in an arbitrary base, by default, base 26. """ b = '' while number: number, i = divmod(number, len(alphabet)) b = alphabet[i] + b v = b or alphabet[0] if fill: return (alphabet[0]*(fill-len(v)))+v else: return v
bigcode/self-oss-instruct-sc2-concepts
def aXbXa(v1, v2): """ Performs v1 X v2 X v1 where X is the cross product. The input vectors are (x, y) and the cross products are performed in 3D with z=0. The output is the (x, y) component of the 3D cross product. """ x0 = v1[0] x1 = v1[1] x1y0 = x1 * v2[0] x0y1 = x0 * v2[1] return (x1 * (x1y0 - x0y1), x0 * (x0y1 - x1y0))
bigcode/self-oss-instruct-sc2-concepts
def epoch_init(M, i, j, w): """ Initialize epoch index from daily period, day of week and week of cycle. :param M: Model :param i: period of day :param j: day of week :param w: week of cycle :return: period of cycle in 1..n_prds_per_cycle """ return (w - 1) * M.n_days_per_week() * M.n_prds_per_day() + (j - 1) * M.n_prds_per_day() + i
bigcode/self-oss-instruct-sc2-concepts
def expose( func ): """ Decorator: mark a function as 'exposed' and thus web accessible """ func.exposed = True return func
bigcode/self-oss-instruct-sc2-concepts
def GetEndOfBlock(code, end_op): """Get the last line of block.""" """It returns -1 if it can't find.""" for i in code: if end_op in i: return code.index(i) else: return -1
bigcode/self-oss-instruct-sc2-concepts
def response(context): """Shortcut to the response in context""" return context.response
bigcode/self-oss-instruct-sc2-concepts
def street_address(anon, obj, field, val): """ Generates a random street address - the first line of a full address """ return anon.faker.street_address(field=field)
bigcode/self-oss-instruct-sc2-concepts
def ABCD_eq(b,c,d): """ Basic estimator formula for count in 'A' (signal domain) DEFINITION: A = B x C / D ^ |C | A |----- |D | B 0------> """ return b * c / d
bigcode/self-oss-instruct-sc2-concepts
def decode_text_from_webwx(text): """ 解码从 Web 微信获得到的中文乱码 :param text: 从 Web 微信获得到的中文乱码 """ if isinstance(text, str): try: text = text.encode('raw_unicode_escape').decode() except UnicodeDecodeError: pass return text
bigcode/self-oss-instruct-sc2-concepts
def nested(path, query, *args, **kwargs): """ Creates a nested query for use with nested documents Keyword arguments such as score_mode and others can be added. """ nested = { "path": path, "query": query } nested.update(kwargs) return { "nested": nested }
bigcode/self-oss-instruct-sc2-concepts
def __get_service_names(scenario_config): """ Gets the list of services from the scenario config. If no services are given, an empty list is returned. :param scenario_config: The scenario config. :return: A list of services. [] if no service names are found. """ if 'services' in scenario_config: service_names = scenario_config['services'] else: service_names = [] if not isinstance(service_names, list): raise Exception('"services" is not a list. It must be a list of services') return service_names
bigcode/self-oss-instruct-sc2-concepts
def float_range(start, stop=None, step=None): """Return a list containing an arithmetic progression of floats. Return a list of floats between 0.0 (or start) and stop with an increment of step. This is in functionality to python's range() built-in function but can accept float increments. As with range(), stop is omitted from the list. """ if stop is None: stop = float(start) start = 0.0 if step is None: step = 1.0 cur = float(start) l = [] while cur < stop: l.append(cur) cur += step return l
bigcode/self-oss-instruct-sc2-concepts
def attendance_numbers(brother, events, accepted_excuses): """ Returns the a of the row of the attendance csv containing information about the brother and his attendance at events :param Brother brother: the brother whose information you need the count for :param list[Event] events: the list of events whose attendance the brother attendance count we need :param list[Excuse] accepted_excuses: a list of excuses that have been accepted for the brother :returns: the attendance info/numbers and the list used to populate the brother's row with x, e, u, - to fill their attendance at each event :rtype: int, int, int, int, list[str] """ events_eligible = 0 events_attended = 0 events_excused = 0 events_unexcused = 0 event_attendance = [] # count the number of eligible events, events attended, events excused, and events unexcused for # this brother and append to their attendance list the appropriate marking for event in events: if event.eligible_attendees.filter(id=brother.id).exists(): events_eligible += 1 if event.attendees_brothers.filter(id=brother.id).exists(): event_attendance.append('x') events_attended += 1 elif accepted_excuses.filter(brother=brother, event=event).exists(): event_attendance.append('e') events_excused += 1 else: event_attendance.append('u') events_unexcused += 1 else: event_attendance.append('-') return events_eligible, events_attended, events_excused, events_unexcused, event_attendance
bigcode/self-oss-instruct-sc2-concepts
from typing import Optional def _find_month_number(name: str) -> Optional[int]: """Find a month number from its name. Name can be the full name (January) or its three letter abbreviation (jan). The casing does not matter. """ names = ['january', 'february', 'march', 'april', 'may', 'june', 'july', 'august', 'september', 'october', 'november', 'december'] names_abbr = [c[:3] for c in names] name = name.lower() if name in names: return names.index(name) if name in names_abbr: return names_abbr.index(name) return None
bigcode/self-oss-instruct-sc2-concepts
def move_down(rows, t): """ A method that takes number of rows in the matrix and coordinates of bomb's position and returns coordinates of neighbour located bellow the bomb. It returns None if there isn't such a neighbour """ x, y = t if x == rows: return None else: return (x + 1, y)
bigcode/self-oss-instruct-sc2-concepts
def get_domain(domain_table): """ A helper function to get the domain for the corresponding cdm domain table :param domain_table: the cdm domain table :return: the domains """ domain = domain_table.split('_')[0].capitalize() return domain
bigcode/self-oss-instruct-sc2-concepts
def _particular_antigen_comp(donor: int, recipient: int) -> tuple: """Returns a particalar antigen compatibility, where each tuple member marks a compatibility for a particular antigen (A, B, Rh-D). If tuple member is non-negative there is a compatibility. For red blood cell compatibility is required that all tuple members are non-negative (i.e. compatibility for all 3 antigens). 0- bloodtype is represented as 0 ; AB+ is represented as 7; see Bloodtype enum Examples: _particular_antigen_comp(0, 7) -> (1, 1, 1) 0- can donate to AB+ _particular_antigen_comp(1, 3) -> (0, 1, 0) 0+ can donate to B+ _particular_antigen_comp(2, 5) -> (1, -1, 1) B+ cannot donate to A+ _particular_antigen_comp(7, 0) -> (-1, -1, -1) AB+ cannot donate to 0- """ return ( ((recipient // 4) % 2) - ((donor // 4) % 2), ((recipient // 2) % 2) - ((donor // 2) % 2), (recipient % 2) - (donor % 2), )
bigcode/self-oss-instruct-sc2-concepts
def fmt_price(amt): """ Format price as string with 2 decimals """ return '{:,.2f}'.format(amt)
bigcode/self-oss-instruct-sc2-concepts
def adjust_data(code_list, noun=12, verb=2): """Set the computer to a desired state by adjusting the noun and verb parameters. Parameters ---------- code_list : list opcode as provided by advent of code noun : int, optional the first parameter (in position 1), by default 12 verb : int, optional the second parameter (in position 2), by default 2 """ code_list[1] = noun code_list[2] = verb return code_list
bigcode/self-oss-instruct-sc2-concepts
def computeblocksize(expectedrows, compoundsize, lowercompoundsize): """Calculate the optimum number of superblocks made from compounds blocks. This is useful for computing the sizes of both blocks and superblocks (using the PyTables terminology for blocks in indexes). """ nlowerblocks = (expectedrows // lowercompoundsize) + 1 if nlowerblocks > 2**20: # Protection against too large number of compound blocks nlowerblocks = 2**20 size = int(lowercompoundsize * nlowerblocks) # We *need* superblocksize to be an exact multiple of the actual # compoundblock size (a ceil must be performed here!) size = ((size // compoundsize) + 1) * compoundsize return size
bigcode/self-oss-instruct-sc2-concepts
def is_mirrored(rot): """ Return True if an eaglexml rotation is mirrored. """ return rot and rot.startswith('M')
bigcode/self-oss-instruct-sc2-concepts
def WritePacketRaw(header, data): """ Given two raw bytearrays, return a bytearray representing the entire packet """ return header + data
bigcode/self-oss-instruct-sc2-concepts
def total_velocity(vel_l, vel_r): """ calculate total velocity - given left and right velocity """ return (vel_l + vel_r) / 2
bigcode/self-oss-instruct-sc2-concepts
def get_role(obj, role_name): """Return a Role if the specified object has the specified role.""" for role in obj.roles: if role.name == role_name: return role return None
bigcode/self-oss-instruct-sc2-concepts
def parse_operand_subscripts(subscript, shape, op_label_dict): """Parse the subscripts for one operand into an output of 'ndim' labels Parameters ---------- subscript : string the subscript of the operand to be parsed. shape : tuple of int the shape of the input operand op_label_dict : dict a dict with pair (label<str>, dim_size<int>) Returns ------- op_labels : list of str/int The parsing results For Example: subscripts="abbcbc", ndim=6 -> op_labels=['a', 'b', 'b', 'c', 'b', 'c']. subscripts="ab...bc", ndim=6 -> op_labels=['a', 'b', '1', '0', 'b', 'c']. dimensions to be broadcast are labeled with number in decreasing order """ op_labels = [] ndim = len(shape) # Step 1: split the subscript by the ellipsis "@" subscript_break = subscript.split('@') assert len(subscript_break) <= 2, "einstein sum subscript string %s contains more than one ellipsis" % subscript sdim = 0 for s in subscript_break: sdim += len(s) num_implicit = ndim - sdim assert num_implicit >= 0, "einstein sum subscript string %s doesn't match the input shape." # Step 2: parse the subscript for label in subscript_break[0]: if label.isalpha(): op_labels.append(label) else: raise ValueError("'%s' is not valid for subscript %s" % (label, subscript)) if len(subscript_break) == 2: # the broadcast indices are labeled in decreasing order # as it requires matching of shape from right to left for n in range(num_implicit): op_labels.append('^%d' % (num_implicit - n - 1)) for label in subscript_break[1]: if label.isalpha(): op_labels.append(label) else: raise ValueError("'%s' is not valid for subscript %s" % (label, subscript)) # Step 3: bind the shape to the labels assert len(op_labels) == ndim for idx, label in enumerate(op_labels): if label in op_label_dict: if op_label_dict[label] != shape[idx]: if op_label_dict[label] == 1: op_label_dict[label] = shape[idx] else: assert shape[idx] == 1, "the dimenions labeled with the same subscript %s cannot be broadcasted" % label # assert op_label_dict[label] == shape[idx], "the dimenions labeled with the same subscript %s doesn't match in size" % label else: op_label_dict[label] = shape[idx] return op_labels
bigcode/self-oss-instruct-sc2-concepts
from typing import Union def atoi(text: str) -> Union[int, str]: """ Converts strings to integers if they're composed of digits; otherwise returns the strings unchanged. One way of sorting strings with numbers; it will mean that ``"11"`` is more than ``"2"``. """ return int(text) if text.isdigit() else text
bigcode/self-oss-instruct-sc2-concepts
def word_to_list(rw): """Convert the ran_word string into a list of letters""" word = list(rw) return word
bigcode/self-oss-instruct-sc2-concepts
import pickle def load_pickle(byte_file): """Loads a pickled object""" with open(byte_file, "rb") as f: return pickle.load(f)
bigcode/self-oss-instruct-sc2-concepts
def package(qualified_name): """Return the enclosing package name where qualified_name is located. `qualified_name` can be a module inside the package or even an object inside the module. If a package name itself is provided it is returned. """ try: module = __import__(qualified_name, fromlist=[""]) except ImportError: # qualified_name could name an object inside a module/package if "." in qualified_name: qualified_name, attr_name = qualified_name.rsplit(".", 1) module = __import__(qualified_name, fromlist=[attr_name]) else: raise if module.__package__ is not None: # the modules enclosing package return module.__package__ else: # 'qualified_name' is itself the package assert module.__name__ == qualified_name return qualified_name
bigcode/self-oss-instruct-sc2-concepts
def indent(text, chars=" ", first=None): """Return text string indented with the given chars >>> string = 'This is first line.\\nThis is second line\\n' >>> print(indent(string, chars="| ")) # doctest: +NORMALIZE_WHITESPACE | This is first line. | This is second line | >>> print(indent(string, first="- ")) # doctest: +NORMALIZE_WHITESPACE - This is first line. This is second line >>> string = 'This is first line.\\n\\nThis is second line' >>> print(indent(string, first="- ")) # doctest: +NORMALIZE_WHITESPACE - This is first line. <BLANKLINE> This is second line """ if first: first_line = text.split("\n")[0] rest = '\n'.join(text.split("\n")[1:]) return '\n'.join([(first + first_line).rstrip(), indent(rest, chars=chars)]) return '\n'.join([(chars + line).rstrip() for line in text.split('\n')])
bigcode/self-oss-instruct-sc2-concepts
def users_from_passwd(raw): """ Extracts a list of users from a passwd type file. """ users = list() for line in raw.split('\n'): tmp = line.split(':')[0] if len(tmp) > 0: users.append(tmp) return sorted(users)
bigcode/self-oss-instruct-sc2-concepts
def product(l1, l2): """returns the dot product of l1 and l2""" return sum([i1 * i2 for (i1, i2) in zip(l1, l2)])
bigcode/self-oss-instruct-sc2-concepts
import requests def analyzeImg(imgResp, apiKey): """ Sends encoded image through Microsoft computer vision API to get tags and categories. Args: imgResp: image response from urlopening webcam image apiKey: Computer Vision API key Returns: json object with 'categories' and 'tags' as keys """ headers = { 'content-type':'application/octet-stream', 'Ocp-Apim-Subscription-Key': apiKey } params = { 'visualFeatures': 'Categories,Tags,Description' } baseUrl = 'https://westcentralus.api.cognitive.microsoft.com/vision/v1.0/analyze' response = None try: response = requests.post(baseUrl, params=params, headers=headers, data=imgResp) except requests.exceptions.RequestException as e: print(e) return '' categories = response.json() return categories
bigcode/self-oss-instruct-sc2-concepts
def sum_items(a_list): """ @purpose Returns the sum of all items in a_list, and return 0 if empty list @param a_list: a list of items passed to this function to sum @complexity: Worst Case - O(N): When summing all values of a list with N items Best Case - O(1): when passing empty list or encounter error @precondition Passing a list with numerical values @postcondition Return the sum of those numerical values in list, or 0 if it's empty """ try: if len(a_list) > 0: sum = 0 for i in range(len(a_list)): sum += a_list[i] return sum else: return 0 except TypeError: return "Please only insert numerical type lists."
bigcode/self-oss-instruct-sc2-concepts
def parse_distance(distance): """parse comma delimited string returning (latitude, longitude, meters)""" latitude, longitude, meters = [float(n) for n in distance.split(',')] return (latitude, longitude, meters)
bigcode/self-oss-instruct-sc2-concepts
def find_pivot(array, high, low): """ Find the index of the pivot element """ if high < low: return -1 if high == low: return low mid = (high + low)/2 if mid < high and array[mid] > array[mid + 1]: return mid if mid > low and array[mid] < array[mid - 1]: return mid - 1 if array[low] >= array[mid]: return find_pivot(array, low, mid - 1) else: return find_pivot(array, mid + 1, high)
bigcode/self-oss-instruct-sc2-concepts
import requests import shutil def download_file(url, local_file, *, allow_redirects=True, decode=True): """ Download a file. Arguments: url (str): URL to download local_file (str): Local filename to store the downloaded file Keyword arguments (opt): allow_redirects (True/False): Allow request to redirect url default: True decode (True/False): Decode compressed responses like gzip default: True Return: Request response headers Example: >>> download_file("http://google.com/favicon.ico", # doctest: +SKIP "/tmp/google.ico") """ with requests.get(url, stream=True, allow_redirects=allow_redirects) as res: if res.status_code != 200: raise RuntimeError("Failed downloading url {}".format(url)) if decode: res.raw.decode_content = True with open(local_file, "wb") as fd: shutil.copyfileobj(res.raw, fd) return res.headers
bigcode/self-oss-instruct-sc2-concepts
def pdf2cte(terms_table, table_name): """Generate SQL code to represent Pandas DataFrame as a Common Table Expression""" quotify = lambda c: c # '[' + c + ']' row2tuple_str = lambda row: '(' + ', '.join([ f"'{x}'" if (isinstance(x, str) or isinstance(x, bool)) else str(x) for x in row ]) + ')' cte_strings = [] colnames_str = ', '.join([quotify(c) for c in terms_table.columns]) tuple_strings = terms_table.apply(row2tuple_str, axis=1) tuples = ',\n\t\t'.join([ts for ts in tuple_strings]) cte_strings.append( f"{table_name} ({colnames_str}) as\n\t(VALUES\n\t\t{tuples}\n\t)" ) return ',\n'.join(cte_strings)
bigcode/self-oss-instruct-sc2-concepts
def always_roll(n): """ Возвращает стратегию, по которой всегда происходит N бросков. >>> strategy = always_roll(5) >>> strategy(0, 0) 5 >>> strategy(99, 99) 5 """ def strategy(score, opponent_score): return n return strategy
bigcode/self-oss-instruct-sc2-concepts
def _get_stream_timestamps(stream: dict): """Retrieve the LSL timestamp array.""" return stream["time_stamps"]
bigcode/self-oss-instruct-sc2-concepts
def newline_space_fix(text): """Replace "newline-space" with "newline". This function was particularly useful when converting between Google Sheets and .xlsx format. Args: text (str): The string to work with Returns: The text with the appropriate fix. """ newline_space = '\n ' fix = '\n' while newline_space in text: text = text.replace(newline_space, fix) return text
bigcode/self-oss-instruct-sc2-concepts
def is_checkpoint_epoch(cfg, cur_epoch): """Determines if a checkpoint should be saved on current epoch.""" return (cur_epoch + 1) % cfg.TRAIN.CHECKPOINT_PERIOD == 0
bigcode/self-oss-instruct-sc2-concepts
def getCommand(gameCounter: int): """Allows the gamer to enter a command from the console.""" return input("Dynasty (" + str(gameCounter) + ") > ")
bigcode/self-oss-instruct-sc2-concepts
def hide_axis(ax, axis='x', axislabel=True, ticklabels=True, ticks=False, hide_everything=False): """ Hide axis features on an axes instance, including axis label, tick labels, tick marks themselves and everything. Careful: hiding the ticks will also hide grid lines if a grid is on! Parameters ---------- axis : 'x' or 'y' 'both' axislabel : True Hide the axis label ticklabels : True Hide the tick labels ticks : True Hide the tick markers hide_everything : False Hides labels, tick labels and axis labels. """ if axis not in ['x','y','both']: raise AttributeError('axis must be "x" or "y" or both') axis_to_modify = [] if hide_everything: ticks = True; axislabel=True; ticklabels=True # Set axis labels if axis == 'x' or axis == 'both': axis_to_modify.append(ax.get_xaxis()) if axislabel: ax.set_xlabel('') if axis == 'y' or axis == 'both': #not elif becuase "both" stipulation axis_to_modify.append(ax.get_yaxis()) if axislabel: ax.set_ylabel('') for an_axis in axis_to_modify: if ticklabels: an_axis.set_ticklabels([]) if ticks: an_axis.set_ticks([]) return ax
bigcode/self-oss-instruct-sc2-concepts
import math def roundup(x, to): """Rounding up to sertain value >>> roundup(7, 8) >>> 8 >>> roundup(8, 8) >>> 8 >>> roundup(9, 8) >>> 16 :param x: value to round :param to: value x will be rounded to :returns: rounded value of x :rtype: int """ return int(math.ceil(x / to)) * to
bigcode/self-oss-instruct-sc2-concepts
def getWaterYear(date): """ Returns the water year of a given date Parameters ---------- date : datetime-like A datetime or Timestamp object Returns ------- wateryear : string The water year of `date` Example ------- >>> import datetime >>> import wqio >>> x = datetime.datetime(2005, 11, 2) >>> print(wqio.utils.getWaterYear(x)) 2005/2006 """ year = date.year yearstring = "{}/{}" if date.month >= 10: return yearstring.format(year, year + 1) else: return yearstring.format(year - 1, year)
bigcode/self-oss-instruct-sc2-concepts
def find_collNames(output_list): """ Return list of collection names collected from refs in output_list. """ colls = [] for out in output_list: if out.kind in {"STEP", "ITEM"}: colls.append(out.collName) elif out.kind == "IF": colls.append(out.refs[0].collName) return colls
bigcode/self-oss-instruct-sc2-concepts
def session_new_user_fixture(session_base): """Load the new user session payload and return it.""" return session_base.format(user_id=1001)
bigcode/self-oss-instruct-sc2-concepts
def collator(batch_list): """ Collate a bunch of multichannel signals based on the size of the longest sample. The samples are cut at the center """ max_len = max([s[0].shape[-1] for s in batch_list]) n_batch = len(batch_list) n_channels_data = batch_list[0][0].shape[0] n_channels_target = batch_list[0][1].shape[0] data = batch_list[0][0].new_zeros((n_batch, n_channels_data, max_len)) target = batch_list[0][1].new_zeros((n_batch, n_channels_target, max_len)) offsets = [(max_len - s[0].shape[-1]) // 2 for s in batch_list] for b, ((d, t), o) in enumerate(zip(batch_list, offsets)): data[b, :, o : o + d.shape[-1]] = d target[b, :, o : o + t.shape[-1]] = t # handle when extra things are provided (e.g. transcripts) rest_of_items = [] for i in range(len(batch_list[0]) - 2): rest_of_items.append([b[i + 2] for b in batch_list]) return data, target, *rest_of_items
bigcode/self-oss-instruct-sc2-concepts
def _rel_approx_equal(x, y, rel=1e-7): """Relative test for equality. Example >>> _rel_approx_equal(1.23456, 1.23457) False >>> _rel_approx_equal(1.2345678, 1.2345679) True >>> _rel_approx_equal(0.0, 0.0) True >>> _rel_approx_equal(0.0, 0.1) False >>> _rel_approx_equal(0.0, 1e-9) False >>> _rel_approx_equal(1.0, 1.0+1e-9) True >>> _rel_approx_equal(1e8, 1e8+1e-3) True """ return abs(x-y) <= rel*max(abs(x), abs(y))
bigcode/self-oss-instruct-sc2-concepts
def get(obj: dict, path, default=None): """Gets the deep nested value from a dictionary Arguments: obj {dict} -- Dictionary to retrieve the value from path {list|str} -- List or . delimited string of path describing path. Keyword Arguments: default {mixed} -- default value to return if path does not exist (default: {None}) Returns: mixed -- Value of obj at path """ if isinstance(path, str): path = path.split(".") new_obj = { **obj } for key in path: if not new_obj: # for cases where key has null/none value return default if key in new_obj.keys(): new_obj = new_obj.get(key) else: return default return new_obj
bigcode/self-oss-instruct-sc2-concepts
def dict_is_song(info_dict): """Determine if a dictionary returned by youtube_dl is from a song (and not an album for example).""" if "full album" in info_dict["title"].lower(): return False if int(info_dict["duration"]) > 7200: return False return True
bigcode/self-oss-instruct-sc2-concepts
import socket import ipaddress def forward_lookup(hostname): """Perform a forward lookup of a hostname.""" ip_addresses = {} addresses = list( set(str(ip[4][0]) for ip in socket.getaddrinfo(hostname, None)) ) if addresses is None: return ip_addresses for address in addresses: if type(ipaddress.ip_address(address)) is ipaddress.IPv4Address: ip_addresses["ipv4"] = address if type(ipaddress.ip_address(address)) is ipaddress.IPv6Address: ip_addresses["ipv6"] = address return ip_addresses
bigcode/self-oss-instruct-sc2-concepts
def pots_to_volts(calibration_data): """Convert the potentiometer data units to volts. Parameters ---------- calibration_data : dict All of the digital (DIO) and analog data corresponding to the trodes files for the a calibration recording. For example, as returned by read_data(). Returns ------- calibration_data : dict Calibration data with potentiometer data convert to volts """ trodes_max_bits = 32767.0 trodes_max_volts = 10.0 for key in calibration_data['analog'].keys(): calibration_data['analog'][key] = ( calibration_data['analog'][key] / trodes_max_bits * trodes_max_volts ) return calibration_data
bigcode/self-oss-instruct-sc2-concepts
import re def walltime_seconds(walltime): """Given a walltime string, return the number of seconds it represents. Args: walltime (str): Walltime, eg. '01:00:00'. Returns: int: Number of seconds represented by the walltime. Raises: ValueError: If an unsupported walltime format is supplied. """ match = re.fullmatch(r"(\d{1,3}):(\d{1,2}):(\d{1,2})", walltime) if match is None: raise ValueError( f"Expected walltime like '02:30:40', but got {repr(walltime)}." ) hours, minutes, seconds = match.groups() return int(hours) * 60 * 60 + int(minutes) * 60 + int(seconds)
bigcode/self-oss-instruct-sc2-concepts
def arange(start, end, step=1): """ arange behaves just like np.arange(start, end, step). You only need to support positive values for step. >>> arange(1, 3) [1, 2] >>> arange(0, 25, 2) [0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24] >>> arange(0, 1231, 34) [0, 34, 68, 102, 136, 170, 204, 238, 272, 306, 340, 374, 408, 442, 476, 510, 544, 578, 612, 646, 680, 714, 748, 782, 816, 850, 884, 918, 952, 986, 1020, 1054, 1088, 1122, 1156, 1190, 1224] """ cur=list() for k in range(start,end,step): cur.append(k) return cur # def n: # while(n >=0 and r[n] < end): # r[n] = start + step*n # return r[n]
bigcode/self-oss-instruct-sc2-concepts
def get_domain_id(ks_client, domain_name): """Return domain ID. :param ks_client: Authenticated keystoneclient :type ks_client: keystoneclient.v3.Client object :param domain_name: Name of the domain :type domain_name: string :returns: Domain ID :rtype: string or None """ all_domains = ks_client.domains.list(name=domain_name) if all_domains: return all_domains[0].id return None
bigcode/self-oss-instruct-sc2-concepts
def clean_aliases(aliases): """ Removes unwanted characters from the alias name. This function replaces: -both '/' and '\\\\' with '_'. -# with "", as it is not allowed according to the schema. Can be called prior to registering a new alias if you know it may contain such unwanted characters. You would then need to update your payload with the new alias to submit. Args: aliases: `list`. One or more record alias names to submit to the Portal. Returns: `str`: The cleaned alias. Example:: clean_alias_name("michael-snyder:a/troublesome\alias") # Returns michael-snyder:a_troublesome_alias """ new = [] for alias in aliases: new.append(alias.replace("/", "_").replace("\\", "_").replace("#", "")) return new
bigcode/self-oss-instruct-sc2-concepts
import click def validate_fragment_type(ctx, param, value): """ Validate that a given fragment type exists. """ config = ctx.obj.config if value and not config.has_fragment_type(value): raise click.BadParameter( 'Missing or unknown fragment type: {}'.format(value)) return value
bigcode/self-oss-instruct-sc2-concepts