content
stringlengths
39
14.9k
sha1
stringlengths
40
40
id
int64
0
710k
def get_min_key_for_max_value(d): """ For a dictionary d, get the key for the largest value. If largest value is attained several times, get the smallest respective key. """ sorted_keys = sorted([key for key in d.keys()]) values = [d[key] for key in sorted_keys] max_value = max(val...
af5dfb5f9471e3b4757e129cc81eb0f89579c7fc
671,634
def find_subtree(tree, node_id): """ Recurse through the tree until the node is found Then return the node Args: tree: Node containing full tree node_id: string id directing which nodes to traverse Returns: Node containing full tree """ # We have reached the correct...
a899d00d25eac865c29b2d0926fb5e9cec85deae
671,636
def one_step_integrator(state, ders, I, dt): """RK4 integrates state with derivative and input for one step of dt :param state: state of the variables :param ders: derivative functions :param I: input :param dt: time step :return: state after one integration step""" D = len(state) # 1 k1 = [ders[i](state,I) ...
f78fdf108c0ca82b5c93f36eab9c5f2da1d8ad5a
671,637
def fraction_of_contacts(cm, ref_cm): """ Given two contact matices of equal dimensions, computes the fraction of entries which are equal. This is comonoly refered to as the fraction of contacts and in the case where ref_cm represents the native state this is the fraction of native contacts. ...
0c49d72c196d78e6be6a6c1903b250d668bdb96a
671,639
def get_students(selection_db, aws_db, applicants_sql, student_fields_sql): """ Calls the database and gets student information. Input: database connection object, SQL query, dict of fields name/ID Returns: dictionary of student information, key=student ID """ students = {} with selection_d...
5295e1564f60f07eebaa0e1ae8654522c21db1c9
671,640
def find_closest_smaller_value(find_value, list_of_values): """ Returns the closest value from a list of values that is smaller than find_value :param find_value: The value we are searching for :param list_of_values: The list of values :return: The index of the closes value in the list. Returns -1 i...
e221b3c55f330c3e884fcc2ebcfe7363527effb0
671,642
def test_function_attributes(cache): """ Simple tests for attribute preservation. """ def tfunc(a, b): """test function docstring.""" return a + b cfunc = cache()(tfunc) assert cfunc.__doc__ == tfunc.__doc__ assert hasattr(cfunc, 'cache_info') assert hasattr(cfunc, 'cache_clear'...
591e0148a5fbeb2cece1114f728a34ed6c453b9c
671,644
import re def FillParagraph(text,width=70,indentLinesBy=0): """ >>> txt = "123 567 90 123\\n456 89\\n" >>> print FillParagraph(txt,width=10) 123 567 90 123 456 89 >>> print FillParagraph(txt,width=10,indentLinesBy=3) 123 567 90 123 456 89 >>> txt = '123 567 \\n' >>> print FillParagraph...
d5cbc05c090ecca5f64fa519e2772b2154b029bd
671,646
def get_fbonds(graph, key): """Get all the possible forming bonds of a certain type Arguments: graph (nx.Graph): graph object of a molecule key (str): string representing the bond type to be examined Returns: list: list of bonds that can be made of this type """ possible_fb...
e3fa72362fc7d3b0d48693c9bf932223a0305458
671,647
def _get_prop(title): """Get property name from plot title. Parameters: title (str): Plot title. Returns: str """ if 'vel' in title: return 'vel' elif 'sigma' in title: return 'sigma' else: return 'default'
fad17861a3d3520682adae6d825ef552ae6ab0da
671,649
def bind(instance, func, as_name=None): """ Bind the function *func* to *instance*, with either provided name *as_name* or the existing name of *func*. The provided *func* should accept the instance as the first argument, i.e. "self". """ if as_name is None: as_name = func.__name__ ...
ee7bf95abaf0fdb1751f96a3982784e762203f29
671,650
def fill_in_particular_status(response, ids, template_to_fill, object="harvester"): """Replaces `template_to_fill` (e.g. `FULL_IDS`) in templated response to objects with given `ids` """ if len(ids) == 0: response = response.replace(f"{object} {template_to_fill} is", "none is") elif len(ids) == ...
cc5a88dbbfc5415dcc96843c37f1e50410a94aad
671,656
def n_process(data, L, R): """ Apply panning gains based on chosen pan law. Params ------- data : ndarrary Input audio data. (samples, channels) currently only support max of 2 channels Returns ------- output_buffer : ndarray Panned input audio. (samples, channels) ...
92e8543e1b794fbc3b700f54ce20131cc85f12f7
671,658
def CollectionToResourceType(collection): """Converts a collection to a resource type: 'compute.disks' -> 'disks'.""" return collection.split('.', 1)[1]
6b98b7c84e4cfea7f4733bd46e623c16d2f00409
671,662
def find_last_break(times, last_time, break_time): """Return the last index in times after which there is a gap >= break_time. If the last entry in times is further than signal_separation from last_time, that last index in times is returned. Returns -1 if no break exists anywhere in times. """ i...
01d883bc0c67022a32397f87703acf109f95bd55
671,665
import torch def inner_product(this, that, keepdim=True): """ Calculate the inner product of two tensors along the last dimension Inputs: this, that ...xD torch.tensors containing the vectors Outputs: result ... torch.tensor containing the inner products ...
221ab83e11d96e542099be7db8abe4d53640bf38
671,667
def displayhtml (public_key): """Gets the HTML to display for reCAPTCHA public_key -- The public api key""" return """<script src='https://www.google.com/recaptcha/api.js'></script> <div class="g-recaptcha" data-sitekey="%(PublicKey)s"></div>""" % { 'PublicKey' : public_key }
84e4bf8c5ef36c1c4213e9eefa35882638578fc4
671,671
def prod(xs): """Computes the product along the elements in an iterable. Returns 1 for empty iterable. Args: xs: Iterable containing numbers. Returns: Product along iterable. """ p = 1 for x in xs: p *= x return p
563aad9e60e8c214ff7c1af4fb1f9549868927b4
671,672
def root_url() -> str: """Root API route. No functions. Returns ------- str Error and message about API usage. """ return "Folder data microservice.\nWrong request. Use /api/meta/<folder> to get folder list."
942189c25e488ea15ddcd9805aca24d7c9e4cce4
671,673
def measureDistance(pointA, pointB): """ Determines the distance pointB - pointA :param pointA: dict Point A :param pointB: dict Point B :return: int Distance """ if (pointA['chromosome'] != pointB['chromosome']): distance = float('inf'); if ('position...
baf35b72d4d502af89792790e334c30ec4d5cadd
671,674
from typing import Union def maybe_int(string: str) -> Union[int, str]: """Try to cast string to int. Args: string: Input string. Returns: Maybe an int. Pass on input string otherwise. Example: >>> maybe_int('123') 123 >>> maybe_int(' 0x7b') 123 ...
79c7a6d852a8f68effc3a0180ff25f751d49df37
671,675
def args_to_dict(args): """ Convert template tag args to dict Format {% suit_bc 1.5 'x' 1.6 'y' %} to { '1.5': 'x', '1.6': 'y' } """ return dict(zip(args[0::2], args[1::2]))
b7a3fc75ff4f4df4060d189c42e3c54c9b518f36
671,678
def get_image_frames(content_tree, namespaces): """find all draw frames that must be converted to draw:image """ xpath_expr = "//draw:frame[starts-with(@draw:name, 'py3o.image')]" return content_tree.xpath( xpath_expr, namespaces=namespaces )
cd849487dd9f3ddbf03ec63b3630285323ae3866
671,680
def is_structure_line(line): """Returns True if line is a structure line""" return line.startswith('#=GC SS_cons ')
78017b53de123141f9263a3a34e2c125bb585d88
671,681
def _align_interval(interval): """ Flip inverted intervals so the lower number is first. """ (bound_one, bound_two) = interval return (min(bound_one, bound_two), max(bound_one, bound_two))
4e6d510bb489127d842b2ef917e234c90cd032ab
671,685
def graphql_custom_class_field(field_func): """Decorator that annotates a class exposing a field in GraphQL. The field appears in the GraphQL types for any of the class's subclasses that are annotated with graphql_object or graphql_interface. It is not useful to decorate a function with graphql_cu...
ab3d2d3a6896f61ccfc35caf3519975d593898d0
671,686
def select(ds, **selection): """ Returns a new dataset with each array indexed by tick labels along the specified dimension(s) Parameters ---------- ds : xarray Dataset A dataset to select from selection : dict A dict with keys matching dimensions and values given by scalars...
9bea1a7d9f61c707bc0b733e42620e7f4a4779d7
671,690
def vector_dot(vector1, vector2): """ Computes the dot-product of the input vectors. :param vector1: input vector 1 :type vector1: list, tuple :param vector2: input vector 2 :type vector2: list, tuple :return: result of the dot product :rtype: float """ try: if vector1 is No...
76b00e34480cede3c9b94de4612bd2c3aa64567c
671,695
def accuracy_score(data): """ Given a set of (predictions, truth labels), return the accuracy of the predictions. :param data: [List[Tuple]] -- A list of predictions with truth labels :returns: [Float] -- Accuracy metric of the prediction data """ return 100 * sum([1 if p == t else 0 for p, ...
7170b9e60905736321b7300903a19661c8508380
671,698
def prune_graph(adj_lists, relations): """The function is used to prune graph based on the relations that are present in the training Arguments: adj_lists {dict} -- dictionary containing the graph relations {set} -- list of relation ids Returns: dict -- pruned graph """ ...
15db50339284f7e303d2ed0cc8466207dad366e7
671,700
def as_time(arg): """Defines the custom argument type TIME. Converts its input into an integer if it lacks a unit suffix, otherwise a float. Args: arg (str): A command line argument. Returns: Value of arg converted to a float (duration) or integer (integrations). Raises: ...
78bc63378e17850da505ca383fe96986cd86630d
671,704
import requests import json def put_item(client, item) -> tuple[int, str]: """PUT updated item to FOLIO inventory Args: client: FolioClient item: JSON representation of item as a dictionary Returns: Tuple of HTTP status code and message if error. """ url = f"{client.okap...
874eaae3f33daf04529e1048b6b1c19082ca0ead
671,705
def convert_html_tags_to_jats(xml_etree): """ This methods receives an etree node and replace all "html tags" to jats compliant tags. """ tags = ( ('strong', 'bold'), ('i', 'italic'), ('u', 'underline'), ('small', 'sc') ) for from_tag, to_tag in tags...
eb250aa247ab4aee95378d12cc106ec6630f33af
671,711
def _is_valid_input_row(row, conf): """ Filters blank rows and applies the optional configuration filter argument if necessary. :param row: the input row :param config: the configuration :return: whether the row should be converted """ # Filter blank rows. if all(value == None for v...
cff8797e32a74f5144f4705db14e604618a26136
671,713
def accuracy(labels, predictions): """ Returns the percentage of correct predictions in the set (labels, predictions). """ acc = 0 for label, pred in zip(labels, predictions): if label == pred: acc += 1 return acc / labels.shape[0]
b4f9f1c7273d8dc6894452fe6328e23f8df76b51
671,716
def _generate_line(club, name_column_width): """ Generates a single line of output. :param Organization club: object holding information about club :param int name_column_width: width of name column :return: nicely formatted line of output :rtype: str """ name_column = str(club.name) + ":"...
a62417b4dcd339cc824a6c3a8a4f79dd19abb4c8
671,719
def __metro(soup): """ Gets the most read news from the Metropoles DF page :param soup: the BeautifulSoup object :return: a list with the most read news from the Metropoles DF Page """ news = [] container = soup.select('.m-title') for item in container: a = item.a title...
987514c2d82f568090f6edfda9538b12c98a50cb
671,720
def get_base_image(version_map, version): """Selects the appropriate base image from the version map. This function takes into account the .NET Core versioning story to determine the appropriate base image for the given version. It will select from within the same major version and only if the mino...
3641f3f6f1b86aab920f3a4ef7d292e219de94aa
671,721
import copy def extend_object_field(base_obj, client_obj, field_name): """ :param base_obj: an object which has a property `field_name` that is a list :param client_obj: an object which has a property `field_name` that is a list. A copy of this object is returned with `field_name` modified :pa...
72cd1a7cb842f8536b1af809804950f8ffa9eb3a
671,727
def is_linux(repository_ctx): """Returns true if the host operating system is linux.""" os_name = repository_ctx.os.name.lower() return os_name.find("linux") != -1
0a5aa6bce37e745402366c268a065c6a291f9636
671,730
import math def get_auto_embedding_dim(num_classes): """ Calculate the dim of embedding vector according to number of classes in the category emb_dim = [6 * (num_classes)^(1/4)] ref: Ruoxi Wang, Bin Fu, Gang Fu, and Mingliang Wang. 2017. Deep & Cross Network for Ad Click Predictions. In Proceedings o...
9c91c8bf2d775d029349849c7efa56ba51714448
671,734
def convert_retention_to_seconds(desired_retention, retention_unit): """Convert desired retention to seconds. :param desired_retention: The desired retention for snapshot schedule :param retention_unit: The retention unit for snapshot schedule :return: The integer value in seconds ...
40a6284faf85d005b96ae5aa55429259eafc6324
671,737
from typing import List def _split(a: List[bytes], n: int) -> List[List[bytes]]: """ Splits a list into a list of n sub-lists. Assumes that len(a) % n == 0 :param a: the list to split :param n: number of parts to split the list into :return: a list containing the parts of the source list """ ...
922eebb3af3f578a7f5f957679519e2f138fb8be
671,741
def is_equal_to_as_set(l1, l2): """ return true if two lists contain the same content :param l1: first list :param l2: second list :return: whether lists match """ # Note specifically that set(l1) == set(l2) does not work as expected. return len(set(l1).symmetric_difference(set(l2))) == 0
6e6e39de2c175610eb556b7b2fc586343f0bea76
671,743
def possible_mine_limits(tallies): """return the total minimum and maximum possible # of mines across all tallied fronts returns (min, max)""" return (sum(f(tally) for tally in tallies) for f in (lambda tally: tally.min_mines(), lambda tally: tally.max_mines()))
40c87233c36e4dca9604ffc76fa667579ecce106
671,745
def line_goes_through_border(pos1, pos2, dest1, dest2, border, lower, upper): """ Test if the line from (pos1, pos2) to (dest1, dest2) goes through the border between lower and upper. """ try: m = (border - pos1) / (dest1 - pos1) except ZeroDivisionError: return False wall_closer...
aca4dae17f0e33dd3d643798cd289b598e8152be
671,747
def build_path(node): """ Builds a path going backward from a node Args: node: node to start from Returns: path from root to ``node`` """ path = [] while node.parent is not None: path.append(node.state) node = node.parent return tuple(reversed(path))
412810adeb21b58d2af88f4b700ee8c0cb11d899
671,748
def constant(wait_time): """ Returns a function that just returns the number specified by the wait_time argument Example:: class MyUser(User): wait_time = constant(3) """ return lambda instance: wait_time
cfd77e79770f79837bb5d2b05233b7581b825e5f
671,749
def api_handler(*, name=None): """ Decorator for API handlers with method names not matching their command names. :param name: Command name for the function :return: Wrapper function to set the name """ def predicate(func): func.__api_name__ = name if name else func.__name__...
5b33422ef82583606d3000940495c7beb91b92c6
671,751
import pickle def load_sneden(whichdata): """ Loading the r-process isotopes from Sneden et al. 2008 (pickled in SMHR) """ assert whichdata in ['rproc','sproc','sneden'], whichdata _datadir = "/Users/alexji/smhr/smh/data/isotopes" datamap = {'rproc':'sneden08_rproc_isotopes.pkl', 'sproc...
24131465a9cee01bfb8385a5de31e524a0df0c47
671,757
def fetchUserPubKeys(conn): """ Returns array containing (discord_id, stellar_public_key) tuples """ c = conn.cursor() c.execute("SELECT user_id, stellar_account FROM users") return c.fetchall()
6411f14712643e38846600e8aa1de09a211f88f3
671,758
def plot_shape(ax, xaxis, yaxis, zaxis, plot_3d, data, linewidth): """Plot shape and return line. Args: ax (matplotlib.axes.Axes): axis xaxis (int): indicate which data to plot on the x-axis (0 for x, 1 for y, 2 for z) yaxis (int): indicate which data to plot on the y-axis (0 for x, 1 f...
11a782d8035d7d0d931c94a189c9c261d33f8c3e
671,760
def _quote(expr: str) -> str: """Quote a string, if not already quoted.""" if expr.startswith("'") and expr.endswith("'"): return expr return f"'{expr}'"
345871b1e64dde937088da3aadb636e4fd54c2c1
671,761
def is_not_none(sample): """ Returns True if sample is not None and constituents are not none. """ if sample is None: return False if isinstance(sample, (list, tuple)): if any(s is None for s in sample): return False if isinstance(sample, dict): if any(s is ...
92a662f98021b0b50efb98565e43bce7f50e0775
671,762
def user_can_comment(user): """check if user has permission to comment :user: user to be check :returns: boolean """ return user.is_authenticated and user.has_perm('restaurants.can_comment')
a2a682092441a99b5763040bfa5bf0b9563651c5
671,765
def getEnrichementFractionFromDelta(desired_delta, reference_ratio = 0.011115): """ Calculates the enrichment fraction given a desired delta value using a reference ratio. """ ratio = (desired_delta / 1000. + 1) * reference_ratio fraction = ratio / (1 + ratio) return fraction
2bab2a5a532d7f4110e9eb88fbceffd2797074da
671,767
def typeddict(expected_k, expected_v): """Return a dictionary that enforces a key/value type signature. >>> tdict = typeddict(int, str) >>> mydict = tdict() >>> mydict[3] = 'three' But this fails: >>> mydict['3'] = 'three' """ class TypedDict(dict): def __setitem__(self, k, v)...
49360b914627aa26b5044f92a9a7fe2afd9aca01
671,768
def find_header_row(sheet, header_start): """ Finds the header row number in a sheet of an XLRD Workbook. :param sheet: Input sheet :param header_start: Header pattern (a substring of the first header) :return: Row number for the header row """ row_number = 0 for row in sheet.get_rows()...
5e8ab021884037dc87b8bc3d10f96da76a4e9c4f
671,769
from pathlib import Path from typing import Optional from typing import Dict import json def find_maybe_info_json(absolute_directory_path: Path) -> Optional[Dict]: """ Recursively search parent folders to find the closest info.json file. """ possible_info_json_path = absolute_directory_path.joinpath(...
3f738651d63bee17a76e4de7424893066f080d45
671,770
import hmac import hashlib def sign(key, msg): """Make sha256 signature""" return hmac.new(key, msg.encode('utf-8'), hashlib.sha256).digest()
e675801328df0ca9eb56cb9428896248112f730f
671,773
def get_dir(xy): """ |NW|N |NE| +--+--+--+ |W |C |E | +--+--+--+ |SW|S |SE| """ if xy == (0, 0): return "NW" elif xy == (0, 1): return "N" elif xy == (0, 2): return "NE" elif xy == (1, 0): return "W" elif xy == (1, 1): return "C" ...
4274dd1a381e0a790a47ed87586f6941ac6551ca
671,774
def format_qnode(qnode: str) -> str: """Formats a qnode with the required prefix. "wd:" is prepended for qnodes and "wdt:" is prepended for pnodes. Args: qnode: Unformatted qnode. Returns: Formatted qnode. """ return f"wd:{qnode}" if qnode.startswith("Q") else f"wdt:{qnode}"
67a21c7c57d1c9bc657e336607f1b623d2203af3
671,778
def address(corporation): """Get billing address of Apple subsidiary with given handle""" if corporation == 'AU': return """Apple Pty Limited Level 3 20 Martin Place Sydney South 2000 Australia""" elif corporation == 'CA': return """Apple Canada Inc. 120 Bremner Boulevard, Suite 1600 Toronto...
14975bf859e9daefc7fdc1997a58008ff07f738d
671,781
def get_note_freq(note: int) -> float: """Return the frequency of a note value in Hz (C2=0).""" return 440 * 2 ** ((note - 33) / 12)
d4b03d5b474d9d7f79dcb3cf374148d4a1ccbf18
671,782
def process_single_text(raw_text, max_seq_length, encoder, BOS_token, EOS_token, PAD_token): """Processes a single piece of text. Performs BPE encoding, converting to indexes, truncation, and padding, etc. """ # BPE tokens = encoder.encode(raw_text) # Truncate max_le...
e311da299ebf947354ac1d5e2ac9ee383076357f
671,788
import re def parse_show_spanning_tree(raw_result): """ Parse the 'show spanning-tree' command raw output. :param str raw_result: vtysh raw result string. :rtype: dict :return: The parsed result of the show spanning-tree \ command in a dictionary of the form: :: { ...
804e50a5cbc35d9db93b3d769921925b55ee360c
671,790
def propfind_mock(url, request): """Simulate a PROPFIND request.""" content = b""" <d:multistatus xmlns:d="DAV:" xmlns:cs="http://calendarserver.org/ns/"> <d:response> <d:href>/radicale/user@test.com/contacts/</d:href> <d:propstat> <d:prop> <d:sync-token>http://mo...
e7c73f5566274414e63d7b7dc58e761647c80ab3
671,793
def make_rand_vector(dims, random_state): """ Generate a random unit vector. This works by first generating a vector each of whose elements is a random Gaussian and then normalizing the resulting vector. """ vec = random_state.normal(0, 1, dims) mag = sum(vec ** 2) ** .5 return vec / ma...
55228763c7457fecaf261b7af974f8187d249ccc
671,800
def _ExpandTabs(text, column, tabsize, mark_tabs=False): """Expand tab characters in a string into spaces. Args: text: a string containing tab characters. column: the initial column for the first character in text tabsize: tab stops occur at columns that are multiples of tabsize mark_tabs: if true,...
f921e362dfda42117ac925a836cca778ca9aeb87
671,801
def find_in_dict(obj, key): """ Recursively find an entry in a dictionary Parameters ---------- obj : dict The dictionary to search key : str The key to find in the dictionary Returns ------- item : obj The value from the dictionary """ if key...
408a972b02780f19f9b01f35922c231032d798ee
671,805
def verify_dlg_sdk_proj_env_directory(path): """ Drive letter is not allowed to be project environment. Script checks in parent of 'path': a drive letter like C: doesn't have a parent. """ if(path.find(":\\")+2 >= len(path)): # If no more characters after drive letter (f.e. "C:\\"). return False else: return ...
a03d518124d874b6421ccc652da283302208a207
671,807
def tagsDict_toLineProtocolString(pTagsDict:dict): """Converts a tags dictionnary to a valid LineProtocol string.""" retval = '' for lTagName in pTagsDict: lTagValue = pTagsDict[lTagName] # See https://docs.influxdata.com/influxdb/v1.7/write_protocols/line_protocol_tutorial/#special-characters if type(lTagV...
e2ab2972e62b9baede20977730ab250b279ddfb5
671,809
def clean_refvar(refvar: str) -> str: """Cleans refvar string of characters that cause issues for filenames. Args: refvar: A string representing a refvar. Returns: A cleaned string. """ refvar = refvar.replace(" ", "_") refvar = refvar.replace("/", "_") return refvar
b7f47f42f3db8b8af2cc7d08e68dc6f6b5a285e7
671,810
def make_markdown_links(config): """Make Markdown links table from configuration.""" if not config.links_data: return "" return "\n\n" + "\n".join( f"[{ln['key']}]: {ln['url']}" for ln in config.links_data )
7d0dba32b78ac234a16b5c2151625d13647eb0c9
671,820
def split_list(alist, wanted_parts=1): """Split a list to the given number of parts.""" length = len(alist) # alist[a:b:step] is used to get only a subsection of the list 'alist'. # alist[a:b] is the same as [a:b:1]. # '//' is an integer division. # Without 'from __future__ import division' '/' ...
dcb1ebc57f4291a81ae6af114fc262bc15a748cd
671,821
from pathlib import Path from typing import Dict def ploidy_file_to_dict(ploidy_file: Path) -> Dict[str, int]: """ Generates a dictionary from a ploidy tsv file :param ploidy_file: :return: A dictionary of contigs and their ploidy """ ploidy_dict = dict() with ploidy_file.open("r") as file...
94af8c95438dc4c0612b7cf6135f09298609d7d4
671,829
def cube_contains_coords(cube, *coords): """Check whether the given cube contains all the requested coordinates.""" for coord in coords: if not cube.coords(coord): return False return True
6b7d0f40c2c7d941149334f0496aa23a3ff5645f
671,831
def find_argmax(topics_list): """ returns the maximum probability topic id in a [(topic_id, topic_prob)...] topics distribution """ m = -1. r_tid = -1 for tid, tprob in topics_list: if tprob > m: m = tprob r_tid = tid return r_tid
9f00f79004c9e3aac48dd14c03f9f418e2dc4e02
671,835
def _gtn_get_all_leaves(self): """ Get all the leaves under this node """ if '_children' not in self.__dict__: return [self] l = [] for n in self.children: l.extend(n.get_all_leaves()) return l
1327c9ff51d4ccde0f71c004f3c075b551c08ea8
671,838
def get_unique_movienames(theater_chain): """ Given a 'cadena' data structure, returns a set of (unique) movie names. """ data = set() # We just need unique movie names, in no particular order for theater in theater_chain.theaters: for movie in theater.movies: # print '-- %s'% movie.name data.add(mov...
b49121a96c91eb2088a59808bcf6bb1246d22fe4
671,839
from bs4 import BeautifulSoup def html_fragment(source): """ Parse an HTML string representing a single element, and return that element """ return BeautifulSoup(source, 'html.parser').contents[0]
f41f349f82e376b7780a5d875aa0b7a98e13dd87
671,840
def work_grid(grid, fig): """Take a two dimensional grid, add subplots to a figure for each cell and do layer work. Parameters: ----------- grid: a two dimensional grid of layers fig: matplotlib figure to draw on Returns: -------- axes: a two dimensional list of matplotlib axes """...
f1cf6dc59e75f7d50c9aff8651c12ba6e9f5bee5
671,842
def get_bookmarks_slug_for(instance): """Returns the slug for a bookmark menu valid for the given model instance. """ kls = instance.__class__ return "%s_%d_bookmarks" % (kls.__name__.lower(), instance.pk)
dd7838048db49d12aa3b6614a616137fdb875660
671,843
def count_bags(bags, bag): """Recursively count the bags of each type.""" if not bags.get(bag): return 1 else: counter = 0 for bag_a in bags[bag]: counter += count_bags(bags, bag_a) * bags[bag][bag_a] return counter + 1
85d0c6d58df7d177c01fef6ba35d0128aaa7c9ed
671,846
def get_taxon_id(page): """Get the taxon ID from the page.""" taxon_id = page.select_one('#carregaTaxonGrupoIdDadosListaBrasil') taxon_id = taxon_id['value'] return taxon_id
684f3fae4a9488f10a6720b48ef525d74da6cd97
671,851
def yen(value): """Format value as YEN.""" return f"¥{value:,}"
c4c0571b81c693da6268e4d0788fa484c2053148
671,856
import torch def batch_lookup(M, idx, vector_output=True): """ Perform batch lookup on matrix M using indices idx. :param M: (Variable) [batch_size, seq_len] Each row of M is an independent population. :param idx: (Variable) [batch_size, sample_size] Each row of idx is a list of sample indices. :p...
6201d7e72cbbe8608675d13f0581f349f18c1665
671,859
def least_common(column): """ >>> least_common(["0", "0", "1"]) '1' >>> least_common(["1", "1", "0", "0", "1"]) '0' """ occurs = {} for bit in column: occurs[bit] = occurs.get(bit, 0) + 1 if occurs["0"] == occurs["1"]: return "0" return min(occurs, key=lambda v: o...
7f58ec3d505e0ab049d96c41e7596f54c81c2a75
671,860
def soft_capitalize(string: str): """Capitalizes string without affecting other chars""" return f"{string[0].upper()}{string[1:]}"
9cfadc1b5fb51e88625eaad2f64fe3812d226a10
671,861
def add_prefix(dic, prefix): """Adds a prefix to every key in given dictionary.""" return {f'{prefix}_{key}': value for key, value in dic.items()}
612bf97a3ced88e2e26d11b97f640ec14f38273c
671,862
from re import match def introspect_file(file_path, re_term): """ Takes a (str) file_path and (str) re_term in regex format Will introspect file_path for the existance of re_term and return True if found, False if not found """ try: ifile = open(file_path, "r") except: retu...
68db079119639afc3de2f7c84e35df044310c513
671,863
from typing import Type from typing import List from typing import Tuple def get_required_class_field(class_type: Type) -> List[Tuple[str, Type]]: """Gets all the (valid) class fields which are mandatory. Args: class_type (Type): [description] Returns: List[Tuple[str, Type]]: [descriptio...
6ff5878238877b011b7366dbfa4e530547c01d2c
671,871
import re def IsJunk(contig): """returns true, if contigs is likely to be junk. This is done by name matching. Junk contigs contain either one of the following: random, unknown, chrU, chU. """ c = contig.lower() negative_list = "random", "unknown", "chru", "chu" for x in negative_l...
8c34dae8bfb235259d679018fb37e177435ddd34
671,876
def gateway(arg): """Return a regex that captures gateway name""" assert isinstance(arg, str) return r"(?P<%s>[\w_\-@\' \.]+)" % (arg,)
0f8dddac685b5396da25134b8ce08094f51b6945
671,877
def last_posted_user_name(ticket): """ Get the username of the last post created :param ticket: The requested ticket to get last post for :return: username of last post """ last_post = ticket.posts.all().order_by('created_at').last() return last_post.user.username
904f35f8923422f35c970a5efc452394a7deb12b
671,879
def email_delete(imap, uid): """Flag an email for deletion. """ status, response = imap.store(str(uid), '+FLAGS', '\Deleted') return status, response
8d086d36722985b8631a6b6a70f5511357df65ef
671,881
def backup_policy_filename(name): """ Generate a .old file from a policy name or path """ return '{0}.old'.format(name)
9ea5df32be0d834726ad646ea5d696dda22fffb7
671,882
def countRun(s, c, maxRun, count): """parameter s: a string parameter c: what we're counting parameter maxRun: maximum length of run returns: the number of times that string occurs in a row""" """ trial: def countRunHelp(s,c,maxRun, count): if count == maxRun: return...
c0c71ef86055cd93294a3898bbd23c72df846b6a
671,883
def _tensors_names_set(tensor_sequence): """Converts tensor sequence to a set of tensor references.""" # Tensor name stands as a proxy for the uniqueness of the tensors. # In TensorFlow 2.x one can use the `experimental_ref` method, but it is not # available in older TF versions. return {t.name for t in tenso...
3e4356b3779ffcb60559e396843aeae29420f1d3
671,886
def compute_loss_ref_gen(generation, reflection): """ Compute loss percentage based on a generation count and a reflection count. """ if generation != 0: loss = (1.0 - reflection / generation)*100 else: loss = (1.0 - reflection / (generation+0.1))*100 return loss if loss >=0 el...
8c3f7acc1d4b5d5a6892e53bb6fee6960d378356
671,887