text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def cleanup(): """Delete standard installation directories.""" for install_dir in linters.INSTALL_DIRS: try: shutil.rmtree(install_dir, ignore_errors=True) except Exception: print( "{0}\nFailed to delete {1}".format( ...
[ "def", "cleanup", "(", ")", ":", "for", "install_dir", "in", "linters", ".", "INSTALL_DIRS", ":", "try", ":", "shutil", ".", "rmtree", "(", "install_dir", ",", "ignore_errors", "=", "True", ")", "except", "Exception", ":", "print", "(", "\"{0}\\nFailed to de...
36
15.916667
def _percent_to_integer(percent): """ Internal helper for converting a percentage value to an integer between 0 and 255 inclusive. """ num = float(percent.split('%')[0]) / 100.0 * 255 e = num - math.floor(num) return e < 0.5 and int(math.floor(num)) or int(math.ceil(num))
[ "def", "_percent_to_integer", "(", "percent", ")", ":", "num", "=", "float", "(", "percent", ".", "split", "(", "'%'", ")", "[", "0", "]", ")", "/", "100.0", "*", "255", "e", "=", "num", "-", "math", ".", "floor", "(", "num", ")", "return", "e", ...
32.555556
14.555556
def get_environmental_configuration(self): """ Gets the settings that describe the environmental configuration (supported feature set, calibrated minimum & maximum power, location & dimensions, ...) of the enclosure resource. Returns: Settings that describe the environmental...
[ "def", "get_environmental_configuration", "(", "self", ")", ":", "uri", "=", "'{}/environmentalConfiguration'", ".", "format", "(", "self", ".", "data", "[", "'uri'", "]", ")", "return", "self", ".", "_helper", ".", "do_get", "(", "uri", ")" ]
44.9
23.7
def from_name(cls, name): "Imports a mass table from a file" filename = os.path.join(package_dir, 'data', name + '.txt') return cls.from_file(filename, name)
[ "def", "from_name", "(", "cls", ",", "name", ")", ":", "filename", "=", "os", ".", "path", ".", "join", "(", "package_dir", ",", "'data'", ",", "name", "+", "'.txt'", ")", "return", "cls", ".", "from_file", "(", "filename", ",", "name", ")" ]
44.5
12
def to_json(self, X, y): ''' Reads dataset to csv. :param X: dataset as list of dict. :param y: labels. ''' with gzip.open('%s.gz' % self.path, 'wt') if self.gz else open( self.path, 'w') as file: json.dump(list(zip(y, X)), file)
[ "def", "to_json", "(", "self", ",", "X", ",", "y", ")", ":", "with", "gzip", ".", "open", "(", "'%s.gz'", "%", "self", ".", "path", ",", "'wt'", ")", "if", "self", ".", "gz", "else", "open", "(", "self", ".", "path", ",", "'w'", ")", "as", "f...
29.7
17.7
def _load_id_or_insert(self, session): """Load the id of the temporary context if it exists or return insert args. As a side effect, this also inserts the Context object for the stableid. :return: The record of the temporary context to insert. :rtype: dict """ if self.i...
[ "def", "_load_id_or_insert", "(", "self", ",", "session", ")", ":", "if", "self", ".", "id", "is", "None", ":", "stable_id", "=", "self", ".", "get_stable_id", "(", ")", "# Check if exists", "id", "=", "session", ".", "execute", "(", "select", "(", "[", ...
37.346154
16.5
def refresh(self): """Refresh the cache by deleting the old one and creating a new one. """ if self.exists: self.delete() self.populate() self.open()
[ "def", "refresh", "(", "self", ")", ":", "if", "self", ".", "exists", ":", "self", ".", "delete", "(", ")", "self", ".", "populate", "(", ")", "self", ".", "open", "(", ")" ]
24.375
16.5
def mdae(simulated_array, observed_array, replace_nan=None, replace_inf=None, remove_neg=False, remove_zero=False): """ Compute the median absolute error (MdAE) between the simulated and observed data. .. image:: /pictures/MdAE.png **Range** 0 ≤ MdAE < inf, closer to zero is better. **No...
[ "def", "mdae", "(", "simulated_array", ",", "observed_array", ",", "replace_nan", "=", "None", ",", "replace_inf", "=", "None", ",", "remove_neg", "=", "False", ",", "remove_zero", "=", "False", ")", ":", "# Checking and cleaning the data", "simulated_array", ",",...
35.027778
28.388889
def draw_diagram_nodes(graph, pos=None, nodelist=None, node_size=.7, node_color='k', style='solid', alpha=1.0, cmap=None, vmin=None, vmax=None, ax=None, label=None): """ Draw nodes of graph. This draws only the nodes of graph as horizontal lines at each ``y...
[ "def", "draw_diagram_nodes", "(", "graph", ",", "pos", "=", "None", ",", "nodelist", "=", "None", ",", "node_size", "=", ".7", ",", "node_color", "=", "'k'", ",", "style", "=", "'solid'", ",", "alpha", "=", "1.0", ",", "cmap", "=", "None", ",", "vmin...
39.356522
20.765217
def create_missing(self): """Automatically populate additional instance attributes. When a new lifecycle environment is created, it must either: * Reference a parent lifecycle environment in the tree of lifecycle environments via the ``prior`` field, or * have a name of "Libr...
[ "def", "create_missing", "(", "self", ")", ":", "# We call `super` first b/c it populates `self.organization`, and we", "# need that field to perform a search a little later.", "super", "(", "LifecycleEnvironment", ",", "self", ")", ".", "create_missing", "(", ")", "if", "(", ...
47.53125
25.28125
def parse(self, text): """Create entries from catalog text Normally the text comes from the file at self.path via the ``_load()`` method, but could be explicitly set instead. A copy of the text is kept in attribute ``.text`` . Parameters ---------- text : str ...
[ "def", "parse", "(", "self", ",", "text", ")", ":", "self", ".", "text", "=", "text", "data", "=", "yaml_load", "(", "self", ".", "text", ")", "if", "data", "is", "None", ":", "raise", "exceptions", ".", "CatalogException", "(", "'No YAML data in file'",...
34.945946
20.405405
def check_classes(self, scope=-1): """ Check if pending identifiers are defined or not. If not, returns a syntax error. If no scope is given, the current one is checked. """ for entry in self[scope].values(): if entry.class_ is None: syntax_error(entry...
[ "def", "check_classes", "(", "self", ",", "scope", "=", "-", "1", ")", ":", "for", "entry", "in", "self", "[", "scope", "]", ".", "values", "(", ")", ":", "if", "entry", ".", "class_", "is", "None", ":", "syntax_error", "(", "entry", ".", "lineno",...
45.125
12
def getColorMapAsDiscreetSLD(self, uniqueValues, nodata=-9999): """ Create the color map SLD format from a list of values. :rtype: str """ colorMap = ET.Element('ColorMap', type='values') # Add a line for the no-data values (nv) ET.SubElement(colorMap, 'ColorMapEn...
[ "def", "getColorMapAsDiscreetSLD", "(", "self", ",", "uniqueValues", ",", "nodata", "=", "-", "9999", ")", ":", "colorMap", "=", "ET", ".", "Element", "(", "'ColorMap'", ",", "type", "=", "'values'", ")", "# Add a line for the no-data values (nv)", "ET", ".", ...
43.444444
23.444444
def getTypeFunc(self, data): """ Returns a callable that will encode C{data} to C{self.stream}. If C{data} is unencodable, then C{None} is returned. """ if data is None: return self.writeNull t = type(data) # try types that we know will work ...
[ "def", "getTypeFunc", "(", "self", ",", "data", ")", ":", "if", "data", "is", "None", ":", "return", "self", ".", "writeNull", "t", "=", "type", "(", "data", ")", "# try types that we know will work", "if", "t", "is", "str", "or", "issubclass", "(", "t",...
33.517857
11.946429
def _generate_autoscaling_metadata(self, cls, args): """ Provides special handling for the autoscaling.Metadata object """ assert isinstance(args, Mapping) init_config = self._create_instance( cloudformation.InitConfig, args['AWS::CloudFormation::Init']['config']) ...
[ "def", "_generate_autoscaling_metadata", "(", "self", ",", "cls", ",", "args", ")", ":", "assert", "isinstance", "(", "args", ",", "Mapping", ")", "init_config", "=", "self", ".", "_create_instance", "(", "cloudformation", ".", "InitConfig", ",", "args", "[", ...
44.95
13.7
def dmail_list(self, message_matches=None, to_name=None, to_id=None, from_name=None, from_id=None, read=None): """Return list of Dmails. You can only view dmails you own (Requires login). Parameters: message_matches (str): The message body contains the given terms...
[ "def", "dmail_list", "(", "self", ",", "message_matches", "=", "None", ",", "to_name", "=", "None", ",", "to_id", "=", "None", ",", "from_name", "=", "None", ",", "from_id", "=", "None", ",", "read", "=", "None", ")", ":", "params", "=", "{", "'searc...
40.681818
13.545455
def cpuinfo(): ''' .. versionchanged:: 2016.3.2 Return the CPU info for this minion .. versionchanged:: 2016.11.4 Added support for AIX .. versionchanged:: 2018.3.0 Added support for NetBSD and OpenBSD CLI Example: .. code-block:: bash salt '*' status.cpuinfo...
[ "def", "cpuinfo", "(", ")", ":", "def", "linux_cpuinfo", "(", ")", ":", "'''\n linux specific cpuinfo implementation\n '''", "ret", "=", "{", "}", "try", ":", "with", "salt", ".", "utils", ".", "files", ".", "fopen", "(", "'/proc/cpuinfo'", ",", ...
40.087379
20.31068
def on_pubmsg(self, c, e): """ This function runs when the bot receives a public message. """ text = e.arguments[0] metadata = self.set_metadata(e) metadata['is_private_message'] = False message = Message(text=text, metadata=metadata).__dict__ self.basepla...
[ "def", "on_pubmsg", "(", "self", ",", "c", ",", "e", ")", ":", "text", "=", "e", ".", "arguments", "[", "0", "]", "metadata", "=", "self", ".", "set_metadata", "(", "e", ")", "metadata", "[", "'is_private_message'", "]", "=", "False", "message", "=",...
36.444444
9.555556
def s(cls: Type[C], *args, **kwargs) -> Partial[C]: """ Create an unbound prototype of this class, partially applying arguments .. code:: python controller = Controller.s(interval=20) pipeline = controller(rate=10) >> pool """ return Partial(cls, *args,...
[ "def", "s", "(", "cls", ":", "Type", "[", "C", "]", ",", "*", "args", ",", "*", "*", "kwargs", ")", "->", "Partial", "[", "C", "]", ":", "return", "Partial", "(", "cls", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
29.090909
19.090909
def email_message(self): """ compose complete email message text """ url = settings.SITE_URL hello_text = __("Hi %s," % self.to_user.get_full_name()) action_text = __("\n\nMore details here: %s") % url explain_text = __( "This is an automatic notification sent from fr...
[ "def", "email_message", "(", "self", ")", ":", "url", "=", "settings", ".", "SITE_URL", "hello_text", "=", "__", "(", "\"Hi %s,\"", "%", "self", ".", "to_user", ".", "get_full_name", "(", ")", ")", "action_text", "=", "__", "(", "\"\\n\\nMore details here: %...
51.090909
24.454545
def get_bucket_location(self, bucket): """ Get the location (region) of a bucket. @param bucket: The name of the bucket. @return: A C{Deferred} that will fire with the bucket's region. """ details = self._details( method=b"GET", url_context=self._...
[ "def", "get_bucket_location", "(", "self", ",", "bucket", ")", ":", "details", "=", "self", ".", "_details", "(", "method", "=", "b\"GET\"", ",", "url_context", "=", "self", ".", "_url_context", "(", "bucket", "=", "bucket", ",", "object_name", "=", "\"?lo...
35.142857
16.285714
def recursive_insert(self, node, coord, data, start, end): """Recursively inserts id data into nodes""" if node[0] != -1: left = (start, node[0]) right = (node[0], end) #if left is totally within coord if self.is_within(left, coord): node[...
[ "def", "recursive_insert", "(", "self", ",", "node", ",", "coord", ",", "data", ",", "start", ",", "end", ")", ":", "if", "node", "[", "0", "]", "!=", "-", "1", ":", "left", "=", "(", "start", ",", "node", "[", "0", "]", ")", "right", "=", "(...
41.125
13.625
def getServerSSLContext(self, hostname=None): ''' Returns an ssl.SSLContext appropriate to listen on a socket Args: hostname: if None, the value from socket.gethostname is used to find the key in the servers directory. This name should match the not-suffixed part of two...
[ "def", "getServerSSLContext", "(", "self", ",", "hostname", "=", "None", ")", ":", "sslctx", "=", "ssl", ".", "create_default_context", "(", "ssl", ".", "Purpose", ".", "CLIENT_AUTH", ")", "if", "hostname", "is", "None", ":", "hostname", "=", "socket", "."...
39.772727
27.136364
def clean_value(self): """ Populates json serialization ready data. This is the method used to serialize and store the object data in to DB Returns: List of dicts. """ result = [] for mdl in self: result.append(super(ListNode, mdl).clean_v...
[ "def", "clean_value", "(", "self", ")", ":", "result", "=", "[", "]", "for", "mdl", "in", "self", ":", "result", ".", "append", "(", "super", "(", "ListNode", ",", "mdl", ")", ".", "clean_value", "(", ")", ")", "return", "result" ]
28.166667
18.333333
def index2qindexc(self, index): """ from a buffer index, get the QIndex (row/column coordinate system) of the char pane """ r = (index // 0x10) c = index % 0x10 + 0x11 return self.index(r, c)
[ "def", "index2qindexc", "(", "self", ",", "index", ")", ":", "r", "=", "(", "index", "//", "0x10", ")", "c", "=", "index", "%", "0x10", "+", "0x11", "return", "self", ".", "index", "(", "r", ",", "c", ")" ]
43.8
8
def updateEvolution(self): ''' Updates the "population punk proportion" evolution array. Fasion victims believe that the proportion of punks in the subsequent period is a linear function of the proportion of punks this period, subject to a uniform shock. Given attributes of sel...
[ "def", "updateEvolution", "(", "self", ")", ":", "self", ".", "pEvolution", "=", "np", ".", "zeros", "(", "(", "self", ".", "pCount", ",", "self", ".", "pNextCount", ")", ")", "for", "j", "in", "range", "(", "self", ".", "pCount", ")", ":", "pNow",...
42.458333
28.708333
def unwrap_raw(content): """ unwraps the callback and returns the raw content """ starting_symbol = get_start_symbol(content) ending_symbol = ']' if starting_symbol == '[' else '}' start = content.find(starting_symbol, 0) end = content.rfind(ending_symbol) return content[start:end+1]
[ "def", "unwrap_raw", "(", "content", ")", ":", "starting_symbol", "=", "get_start_symbol", "(", "content", ")", "ending_symbol", "=", "']'", "if", "starting_symbol", "==", "'['", "else", "'}'", "start", "=", "content", ".", "find", "(", "starting_symbol", ",",...
38.125
7
def raise_check_result(self): """Raise ACTIVE CHECK RESULT entry Example : "ACTIVE HOST CHECK: server;DOWN;HARD;1;I don't know what to say..." :return: None """ if not self.__class__.log_active_checks: return log_level = 'info' if self.state == 'DOWN...
[ "def", "raise_check_result", "(", "self", ")", ":", "if", "not", "self", ".", "__class__", ".", "log_active_checks", ":", "return", "log_level", "=", "'info'", "if", "self", ".", "state", "==", "'DOWN'", ":", "log_level", "=", "'error'", "elif", "self", "....
34.947368
19
def bulk_overwrite(self, entities_and_kinds): """ Update the group to the given entities and sub-entity groups. After this operation, the only members of this EntityGroup will be the given entities, and sub-entity groups. :type entities_and_kinds: List of (Entity, EntityKind) p...
[ "def", "bulk_overwrite", "(", "self", ",", "entities_and_kinds", ")", ":", "EntityGroupMembership", ".", "objects", ".", "filter", "(", "entity_group", "=", "self", ")", ".", "delete", "(", ")", "return", "self", ".", "bulk_add_entities", "(", "entities_and_kind...
47.733333
22.266667
def setPageCount( self, pageCount ): """ Sets the number of pages that this widget holds. :param pageCount | <int> """ if ( pageCount == self._pageCount ): return pageCount = max(1, pageCount) self._pageCount ...
[ "def", "setPageCount", "(", "self", ",", "pageCount", ")", ":", "if", "(", "pageCount", "==", "self", ".", "_pageCount", ")", ":", "return", "pageCount", "=", "max", "(", "1", ",", "pageCount", ")", "self", ".", "_pageCount", "=", "pageCount", "self", ...
33.269231
14.961538
def pyramid( input_raster, output_dir, pyramid_type=None, output_format=None, resampling_method=None, scale_method=None, zoom=None, bounds=None, overwrite=False, debug=False ): """Create tile pyramid out of input raster.""" bounds = bounds if bounds else None options ...
[ "def", "pyramid", "(", "input_raster", ",", "output_dir", ",", "pyramid_type", "=", "None", ",", "output_format", "=", "None", ",", "resampling_method", "=", "None", ",", "scale_method", "=", "None", ",", "zoom", "=", "None", ",", "bounds", "=", "None", ",...
24.125
17.375
def tf_observe_timestep(self, states, internals, actions, terminal, reward): """ Creates and returns the op that - if frequency condition is hit - pulls a batch from the memory and does one optimization step. """ # Store timestep in memory stored = self.memory.store( ...
[ "def", "tf_observe_timestep", "(", "self", ",", "states", ",", "internals", ",", "actions", ",", "terminal", ",", "reward", ")", ":", "# Store timestep in memory", "stored", "=", "self", ".", "memory", ".", "store", "(", "states", "=", "states", ",", "intern...
42.617284
20.765432
def root_node(self, value): """ Setter for **self.__root_node** attribute. :param value: Attribute value. :type value: AbstractCompositeNode """ if value is not None: assert issubclass(value.__class__, AbstractCompositeNode), \ "'{0}' attribu...
[ "def", "root_node", "(", "self", ",", "value", ")", ":", "if", "value", "is", "not", "None", ":", "assert", "issubclass", "(", "value", ".", "__class__", ",", "AbstractCompositeNode", ")", ",", "\"'{0}' attribute: '{1}' is not a '{2}' subclass!\"", ".", "format", ...
35.076923
17.076923
def dist_monge_elkan(src, tar, sim_func=sim_levenshtein, symmetric=False): """Return the Monge-Elkan distance between two strings. This is a wrapper for :py:meth:`MongeElkan.dist`. Parameters ---------- src : str Source string for comparison tar : str Target string for comparis...
[ "def", "dist_monge_elkan", "(", "src", ",", "tar", ",", "sim_func", "=", "sim_levenshtein", ",", "symmetric", "=", "False", ")", ":", "return", "MongeElkan", "(", ")", ".", "dist", "(", "src", ",", "tar", ",", "sim_func", ",", "symmetric", ")" ]
24.588235
21.411765
def area_orifice(Height, RatioVCOrifice, FlowRate): """Return the area of the orifice.""" #Checking input validity ut.check_range([Height, ">0", "Height"], [FlowRate, ">0", "Flow rate"], [RatioVCOrifice, "0-1, >0", "VC orifice ratio"]) return FlowRate / (RatioVCOrifice * np.sqrt(2 * g...
[ "def", "area_orifice", "(", "Height", ",", "RatioVCOrifice", ",", "FlowRate", ")", ":", "#Checking input validity", "ut", ".", "check_range", "(", "[", "Height", ",", "\">0\"", ",", "\"Height\"", "]", ",", "[", "FlowRate", ",", "\">0\"", ",", "\"Flow rate\"", ...
57
20.833333
def _start(self): """Start the user's pod""" # load user options (including profile) yield self.load_user_options() # record latest event so we don't include old # events from previous pods in self.events # track by order and name instead of uid # so we get even...
[ "def", "_start", "(", "self", ")", ":", "# load user options (including profile)", "yield", "self", ".", "load_user_options", "(", ")", "# record latest event so we don't include old", "# events from previous pods in self.events", "# track by order and name instead of uid", "# so we ...
41.208333
21.375
def get_gradebook_column_lookup_session(self, proxy): """Gets the ``OsidSession`` associated with the gradebook column lookup service. arg: proxy (osid.proxy.Proxy): a proxy return: (osid.grading.GradebookColumnLookupSession) - a ``GradebookColumnLookupSession`` raise...
[ "def", "get_gradebook_column_lookup_session", "(", "self", ",", "proxy", ")", ":", "if", "not", "self", ".", "supports_gradebook_column_lookup", "(", ")", ":", "raise", "errors", ".", "Unimplemented", "(", ")", "# pylint: disable=no-member", "return", "sessions", "....
48.166667
17.888889
def register(self, make_public=False, cloud=None, api_key=None, version=None, **kwargs): """ This API endpoint allows you to register you collection in order to share read or write access to the collection with another user. Inputs: api_key (optional) - String: Your API key, req...
[ "def", "register", "(", "self", ",", "make_public", "=", "False", ",", "cloud", "=", "None", ",", "api_key", "=", "None", ",", "version", "=", "None", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'make_public'", "]", "=", "make_public", "url_para...
65.294118
36.352941
def do_dirty(self, subcmd, opts): """${cmd_name}: check if any components have unreleased changes ${cmd_usage} ${cmd_option_list} """ for comp_name, comp in components.comp_names.items(): releases = get_released_versions(comp_name) if len(releases) == 0:...
[ "def", "do_dirty", "(", "self", ",", "subcmd", ",", "opts", ")", ":", "for", "comp_name", ",", "comp", "in", "components", ".", "comp_names", ".", "items", "(", ")", ":", "releases", "=", "get_released_versions", "(", "comp_name", ")", "if", "len", "(", ...
38.8125
18.3125
def parse_global_section(config_obj, section): """ Parse GLOBAL section in the config to return global settings :param config_obj: ConfigParser object :param section: Section name :return: ts_start and ts_end time """ ts_start = None ts_end = None if config_obj.has_option(section, 'ts_start'): ts_...
[ "def", "parse_global_section", "(", "config_obj", ",", "section", ")", ":", "ts_start", "=", "None", "ts_end", "=", "None", "if", "config_obj", ".", "has_option", "(", "section", ",", "'ts_start'", ")", ":", "ts_start", "=", "get_standardized_timestamp", "(", ...
39.625
13.75
def _ordinal_metric(_v1, _v2, i1, i2, n_v): """Metric for ordinal data.""" if i1 > i2: i1, i2 = i2, i1 return (np.sum(n_v[i1:(i2 + 1)]) - (n_v[i1] + n_v[i2]) / 2) ** 2
[ "def", "_ordinal_metric", "(", "_v1", ",", "_v2", ",", "i1", ",", "i2", ",", "n_v", ")", ":", "if", "i1", ">", "i2", ":", "i1", ",", "i2", "=", "i2", ",", "i1", "return", "(", "np", ".", "sum", "(", "n_v", "[", "i1", ":", "(", "i2", "+", ...
36.6
14.6
def aes_decrypt(base64_encryption_key, base64_data): """Verify HMAC-SHA256 signature and decrypt data with AES-CBC Arguments: encryption_key (str): a base64-encoded string containing an AES encryption key and HMAC signing key as generated by generate_encryption_key() data (str): a b...
[ "def", "aes_decrypt", "(", "base64_encryption_key", ",", "base64_data", ")", ":", "data", "=", "from_base64", "(", "base64_data", ")", "aes_key_bytes", ",", "hmac_key_bytes", "=", "_extract_keys", "(", "base64_encryption_key", ")", "data", ",", "hmac_signature", "="...
43.84
26.8
def import_records(self, to_import, overwrite='normal', format='json', return_format='json', return_content='count', date_format='YMD', force_auto_number=False): """ Import data into the RedCap Project Parameters ---------- to_import : array of dicts, csv/xml str...
[ "def", "import_records", "(", "self", ",", "to_import", ",", "overwrite", "=", "'normal'", ",", "format", "=", "'json'", ",", "return_format", "=", "'json'", ",", "return_content", "=", "'count'", ",", "date_format", "=", "'YMD'", ",", "force_auto_number", "="...
46.30137
18.082192
def diameter_ratio_wedge_meter(D, H): r'''Calculates the diameter ratio `beta` used to characterize a wedge flow meter as given in [1]_ and [2]_. .. math:: \beta = \left(\frac{1}{\pi}\left\{\arccos\left[1 - \frac{2H}{D} \right] - 2 \left[1 - \frac{2H}{D} \right]\left(\frac{H}{D...
[ "def", "diameter_ratio_wedge_meter", "(", "D", ",", "H", ")", ":", "H_D", "=", "H", "/", "D", "t0", "=", "1.0", "-", "2.0", "*", "H_D", "t1", "=", "acos", "(", "t0", ")", "t2", "=", "2.0", "*", "(", "t0", ")", "t3", "=", "(", "H_D", "-", "H...
30.617021
24.361702
def invite_by_email(self, email, sender=None, request=None, **kwargs): """Creates an inactive user with the information we know and then sends an invitation email for that user to complete registration. If your project uses email in a different way then you should make to extend this me...
[ "def", "invite_by_email", "(", "self", ",", "email", ",", "sender", "=", "None", ",", "request", "=", "None", ",", "*", "*", "kwargs", ")", ":", "try", ":", "user", "=", "self", ".", "user_model", ".", "objects", ".", "get", "(", "email", "=", "ema...
44.296296
19.481481
def M(self, k, t, tips=None, gaps=None): """See docs for `DistributionModel` abstract base class.""" assert 0 <= k < self.ncats return self._models[k].M(t, tips=tips, gaps=gaps)
[ "def", "M", "(", "self", ",", "k", ",", "t", ",", "tips", "=", "None", ",", "gaps", "=", "None", ")", ":", "assert", "0", "<=", "k", "<", "self", ".", "ncats", "return", "self", ".", "_models", "[", "k", "]", ".", "M", "(", "t", ",", "tips"...
49.5
5.75
def fullversion(): ''' Return all version info from lvm version CLI Example: .. code-block:: bash salt '*' lvm.fullversion ''' ret = {} cmd = 'lvm version' out = __salt__['cmd.run'](cmd).splitlines() for line in out: comps = line.split(':') ret[comps[0].str...
[ "def", "fullversion", "(", ")", ":", "ret", "=", "{", "}", "cmd", "=", "'lvm version'", "out", "=", "__salt__", "[", "'cmd.run'", "]", "(", "cmd", ")", ".", "splitlines", "(", ")", "for", "line", "in", "out", ":", "comps", "=", "line", ".", "split"...
20.176471
22.058824
def startup_config_content(self): """ Returns the content of the current startup-config file. """ config_file = self.startup_config_file if config_file is None: return None try: with open(config_file, "rb") as f: return f.read().d...
[ "def", "startup_config_content", "(", "self", ")", ":", "config_file", "=", "self", ".", "startup_config_file", "if", "config_file", "is", "None", ":", "return", "None", "try", ":", "with", "open", "(", "config_file", ",", "\"rb\"", ")", "as", "f", ":", "r...
32.928571
18.928571
def auto_open(self, state=None): """Get or set automatic TCP connect mode :param state: auto_open state or None for get value :type state: bool or None :returns: auto_open state or None if set fail :rtype: bool or None """ if state is None: return sel...
[ "def", "auto_open", "(", "self", ",", "state", "=", "None", ")", ":", "if", "state", "is", "None", ":", "return", "self", ".", "__auto_open", "self", ".", "__auto_open", "=", "bool", "(", "state", ")", "return", "self", ".", "__auto_open" ]
32.75
10.833333
def _stop_processes(paths): """ Scans process list trying to terminate processes matching paths specified. Uses checksums to identify processes that are duplicates of those specified to terminate. `paths` List of full paths to executables for processes to terminate. """ ...
[ "def", "_stop_processes", "(", "paths", ")", ":", "def", "cache_checksum", "(", "path", ")", ":", "\"\"\" Checksum provided path, cache, and return value.\n \"\"\"", "if", "not", "path", ":", "return", "None", "if", "not", "path", "in", "_process_checksums", ...
29.388889
19.972222
def print_help(self): """ Print the help menu. """ print('\n %s %s' % (self._title or self._name, self._version or '')) if self._usage: print('\n %s' % self._usage) else: cmd = self._name if hasattr(self, '_parent') and isinstance(s...
[ "def", "print_help", "(", "self", ")", ":", "print", "(", "'\\n %s %s'", "%", "(", "self", ".", "_title", "or", "self", ".", "_name", ",", "self", ".", "_version", "or", "''", ")", ")", "if", "self", ".", "_usage", ":", "print", "(", "'\\n %s'", ...
30.511111
20.644444
def download_as_pdf(self, target_dir=None, pdf_filename=None, paper_size=PaperSize.A4, paper_orientation=PaperOrientation.PORTRAIT, include_appendices=False): """ Retrieve the PDF of the Activity. .. versionadded:: 2.1 :param target_dir: (optional) directory pat...
[ "def", "download_as_pdf", "(", "self", ",", "target_dir", "=", "None", ",", "pdf_filename", "=", "None", ",", "paper_size", "=", "PaperSize", ".", "A4", ",", "paper_orientation", "=", "PaperOrientation", ".", "PORTRAIT", ",", "include_appendices", "=", "False", ...
44.90411
24.958904
def read_contents(self, schema, name, conn): '''Read table columns''' sql = ''' with schemas as (select n.oid, n.nspname as name from pg_catalog.pg_namespace n), tables as (select c.oid, c.relnamespace as schema_oid, c.relname as name from pg_catalog.pg_class c where c.relkin...
[ "def", "read_contents", "(", "self", ",", "schema", ",", "name", ",", "conn", ")", ":", "sql", "=", "'''\nwith schemas as\n(select n.oid,\n n.nspname as name\n from pg_catalog.pg_namespace n),\ntables as\n(select c.oid,\n c.relnamespace as schema_oid,\n c.relname as...
32.368421
15.526316
def getAllConfig(self, fmt='json'): """ return all element configurations as json string file. could be further processed by beamline.Lattice class :param fmt: 'json' (default) or 'dict' """ for e in self.getCtrlConf(msgout=False): self._lattice_c...
[ "def", "getAllConfig", "(", "self", ",", "fmt", "=", "'json'", ")", ":", "for", "e", "in", "self", ".", "getCtrlConf", "(", "msgout", "=", "False", ")", ":", "self", ".", "_lattice_confdict", ".", "update", "(", "e", ".", "dumpConfig", "(", "type", "...
39.285714
15.857143
def infer_data_type(data_container): """ For a given container of data, infer the type of data as one of continuous, categorical, or ordinal. For now, it is a one-to-one mapping as such: - str: categorical - int: ordinal - float: continuous There may be better ways that are not cu...
[ "def", "infer_data_type", "(", "data_container", ")", ":", "# Defensive programming checks.", "# 0. Ensure that we are dealing with lists or tuples, and nothing else.", "assert", "isinstance", "(", "data_container", ",", "list", ")", "or", "isinstance", "(", "data_container", "...
32.927273
20.163636
def lock_file(path, maxdelay=.1, lock_cls=LockFile, timeout=10.0): """Cooperative file lock. Uses `lockfile.LockFile` polling under the hood. `maxdelay` defines the interval between individual polls. """ lock = lock_cls(path) max_t = time.time() + timeout while True: if time.time() >= ...
[ "def", "lock_file", "(", "path", ",", "maxdelay", "=", ".1", ",", "lock_cls", "=", "LockFile", ",", "timeout", "=", "10.0", ")", ":", "lock", "=", "lock_cls", "(", "path", ")", "max_t", "=", "time", ".", "time", "(", ")", "+", "timeout", "while", "...
31.857143
20.761905
def register_frame(self, frame): """ Register the Frame that owns this Widget. :param frame: The owning Frame. """ self._frame = frame self.string_len = wcswidth if self._frame.canvas.unicode_aware else len
[ "def", "register_frame", "(", "self", ",", "frame", ")", ":", "self", ".", "_frame", "=", "frame", "self", ".", "string_len", "=", "wcswidth", "if", "self", ".", "_frame", ".", "canvas", ".", "unicode_aware", "else", "len" ]
31
13.75
def anglesep_meeus(lon0: float, lat0: float, lon1: float, lat1: float, deg: bool = True) -> float: """ Parameters ---------- lon0 : float or numpy.ndarray of float longitude of first point lat0 : float or numpy.ndarray of float latitude of first point lon1 : f...
[ "def", "anglesep_meeus", "(", "lon0", ":", "float", ",", "lat0", ":", "float", ",", "lon1", ":", "float", ",", "lat1", ":", "float", ",", "deg", ":", "bool", "=", "True", ")", "->", "float", ":", "if", "deg", ":", "lon0", "=", "radians", "(", "lo...
27.5625
22.270833
def guess_depth(self, root_dir): """ Try to guess the depth of a directory repository (i.e. whether it has sub-folders for multiple subjects or visits, depending on where files and/or derived label files are found in the hierarchy of sub-directories under the root dir. P...
[ "def", "guess_depth", "(", "self", ",", "root_dir", ")", ":", "deepest", "=", "-", "1", "for", "path", ",", "dirs", ",", "files", "in", "os", ".", "walk", "(", "root_dir", ")", ":", "depth", "=", "self", ".", "path_depth", "(", "path", ")", "filter...
44.708333
17.833333
def _prepare_model_data(packages, linked, pip=None, private_packages=None): """Prepare model data for the packages table model.""" pip = pip if pip else [] private_packages = private_packages if private_packages else {} data = [] if private_packages ...
[ "def", "_prepare_model_data", "(", "packages", ",", "linked", ",", "pip", "=", "None", ",", "private_packages", "=", "None", ")", ":", "pip", "=", "pip", "if", "pip", "else", "[", "]", "private_packages", "=", "private_packages", "if", "private_packages", "e...
40.770833
16.708333
def update(self, eid, data, token): """ Update a given Library Entry. :param eid str: Entry ID :param data dict: Attributes :param token str: OAuth token :return: True or ServerError :rtype: Bool or Exception """ final_dict = {"data": {"id": eid, ...
[ "def", "update", "(", "self", ",", "eid", ",", "data", ",", "token", ")", ":", "final_dict", "=", "{", "\"data\"", ":", "{", "\"id\"", ":", "eid", ",", "\"type\"", ":", "\"libraryEntries\"", ",", "\"attributes\"", ":", "data", "}", "}", "final_headers", ...
33.2
18.9
def local_filename( self, url=None, filename=None, decompress=False): """ What local filename will we use within the cache directory for the given URL/filename/decompress options. """ return common.build_local_filename(url, filename...
[ "def", "local_filename", "(", "self", ",", "url", "=", "None", ",", "filename", "=", "None", ",", "decompress", "=", "False", ")", ":", "return", "common", ".", "build_local_filename", "(", "url", ",", "filename", ",", "decompress", ")" ]
32.4
15.6
def get_color_data(self, condition): ''' Disambiguate similarly-named weather conditions, and return the icon and color that match. ''' if condition not in self.color_icons: # Check for similarly-named conditions if no exact match found condition_lc = cond...
[ "def", "get_color_data", "(", "self", ",", "condition", ")", ":", "if", "condition", "not", "in", "self", ".", "color_icons", ":", "# Check for similarly-named conditions if no exact match found", "condition_lc", "=", "condition", ".", "lower", "(", ")", "if", "'clo...
42.096774
12.806452
def validate_token_age(callback_token): """ Returns True if a given token is within the age expiration limit. """ try: token = CallbackToken.objects.get(key=callback_token, is_active=True) seconds = (timezone.now() - token.created_at).total_seconds() token_expiry_time = api_setti...
[ "def", "validate_token_age", "(", "callback_token", ")", ":", "try", ":", "token", "=", "CallbackToken", ".", "objects", ".", "get", "(", "key", "=", "callback_token", ",", "is_active", "=", "True", ")", "seconds", "=", "(", "timezone", ".", "now", "(", ...
31.2
18.1
def read_config(filename): """Reads and flattens a configuration file into a single dictionary for ease of use. Works with both ``.config`` and ``.yaml`` files. Files should look like this:: search_rules: from-date: 2017-06-01 to-date: 2017-09-01 01:01 pt-rule: k...
[ "def", "read_config", "(", "filename", ")", ":", "file_type", "=", "\"yaml\"", "if", "filename", ".", "endswith", "(", "\".yaml\"", ")", "else", "\"config\"", "config", "=", "configparser", ".", "ConfigParser", "(", ")", "if", "file_type", "==", "\"yaml\"", ...
30.014286
20.285714
def copy(self, extra=None): """ Creates a copy of this instance with a randomly generated uid and some extra params. This copies creates a deep copy of the embedded paramMap, and copies the embedded and extra parameters over. :param extra: Extra parameters to copy to the new ins...
[ "def", "copy", "(", "self", ",", "extra", "=", "None", ")", ":", "if", "extra", "is", "None", ":", "extra", "=", "dict", "(", ")", "newTVS", "=", "Params", ".", "copy", "(", "self", ",", "extra", ")", "if", "self", ".", "isSet", "(", "self", "....
40.5
15.611111
def init_nautilus(method): """Initialize nautilus method Parameters ---------- method Interactive method used for the process Returns ------- PreferenceInformation subclass to be initialized """ print("Preference elicitation options:") print("\t1 - Percentages") ...
[ "def", "init_nautilus", "(", "method", ")", ":", "print", "(", "\"Preference elicitation options:\"", ")", "print", "(", "\"\\t1 - Percentages\"", ")", "print", "(", "\"\\t2 - Relative ranks\"", ")", "print", "(", "\"\\t3 - Direct\"", ")", "PREFCLASSES", "=", "[", "...
23.9375
22.520833
def binary_erosion(x, radius=3): """Return binary morphological erosion of an image, see `skimage.morphology.binary_erosion <http://scikit-image.org/docs/dev/api/skimage.morphology.html#skimage.morphology.binary_erosion>`__. Parameters ----------- x : 2D array A binary image. radius : i...
[ "def", "binary_erosion", "(", "x", ",", "radius", "=", "3", ")", ":", "mask", "=", "disk", "(", "radius", ")", "x", "=", "_binary_erosion", "(", "x", ",", "selem", "=", "mask", ")", "return", "x" ]
24.75
24.65
def generate_transit_lightcurve( times, mags=None, errs=None, paramdists={'transitperiod':sps.uniform(loc=0.1,scale=49.9), 'transitdepth':sps.uniform(loc=1.0e-4,scale=2.0e-2), 'transitduration':sps.uniform(loc=0.01,scale=0.29)}, magsareflux...
[ "def", "generate_transit_lightcurve", "(", "times", ",", "mags", "=", "None", ",", "errs", "=", "None", ",", "paramdists", "=", "{", "'transitperiod'", ":", "sps", ".", "uniform", "(", "loc", "=", "0.1", ",", "scale", "=", "49.9", ")", ",", "'transitdept...
36.550388
24.116279
def _compute_example(self, label): """ From the "raw example," resolves references to examples of other data types to compute the final example. Returns an Example object. The `value` attribute contains a JSON-serializable representation of the example. """ if la...
[ "def", "_compute_example", "(", "self", ",", "label", ")", ":", "if", "label", "in", "self", ".", "_raw_examples", ":", "example", "=", "self", ".", "_raw_examples", "[", "label", "]", "def", "deref_example_ref", "(", "dt", ",", "val", ")", ":", "dt", ...
40.772727
19.742424
def _set_types(self): """Make sure that x, y have consistent types and set dtype.""" # If we given something that is not an int or a float we raise # a RuntimeError as we do not want to have to guess if the given # input should be interpreted as an int or a float, for example the ...
[ "def", "_set_types", "(", "self", ")", ":", "# If we given something that is not an int or a float we raise", "# a RuntimeError as we do not want to have to guess if the given", "# input should be interpreted as an int or a float, for example the", "# interpretation of the string \"1\" vs the inte...
47.333333
21.666667
def display_charts(df, chart_type="default", render_to=None, **kwargs): """Display you DataFrame with Highcharts. df: DataFrame chart_type: str 'default' or 'stock' render_to: str div id for plotting your data """ if chart_type not in ("default", "stock"): raise ValueErr...
[ "def", "display_charts", "(", "df", ",", "chart_type", "=", "\"default\"", ",", "render_to", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "chart_type", "not", "in", "(", "\"default\"", ",", "\"stock\"", ")", ":", "raise", "ValueError", "(", "\"W...
42.055556
16.722222
def on_header(self, name: bytes, value: bytes) -> None: """ header 回调 """ name_ = decode_bytes(name).casefold() val = decode_bytes(value) if name_ == "cookie": # 加载上次的 cookie self._cookies.load(val) if name_ in self._headers: # ...
[ "def", "on_header", "(", "self", ",", "name", ":", "bytes", ",", "value", ":", "bytes", ")", "->", "None", ":", "name_", "=", "decode_bytes", "(", "name", ")", ".", "casefold", "(", ")", "val", "=", "decode_bytes", "(", "value", ")", "if", "name_", ...
30.277778
9.722222
def _dict_rpartition( in_dict, keys, delimiter=DEFAULT_TARGET_DELIM, ordered_dict=False): ''' Helper function to: - Ensure all but the last key in `keys` exist recursively in `in_dict`. - Return the dict at the one-to-last key, and the last key :param dict in_dict: T...
[ "def", "_dict_rpartition", "(", "in_dict", ",", "keys", ",", "delimiter", "=", "DEFAULT_TARGET_DELIM", ",", "ordered_dict", "=", "False", ")", ":", "if", "delimiter", "in", "keys", ":", "all_but_last_keys", ",", "_", ",", "last_key", "=", "keys", ".", "rpart...
39.375
21
def tasks(self): """ :class:`~zhmcclient.TaskManager`: Access to the :term:`Tasks <Task>` in this Console. """ # We do here some lazy loading. if not self._tasks: self._tasks = TaskManager(self) return self._tasks
[ "def", "tasks", "(", "self", ")", ":", "# We do here some lazy loading.", "if", "not", "self", ".", "_tasks", ":", "self", ".", "_tasks", "=", "TaskManager", "(", "self", ")", "return", "self", ".", "_tasks" ]
30.333333
12.555556
def html(self, data=None, template=None): """ Send html document to user. Args: - data: Dict to render template, or string with rendered HTML. - template: Name of template to render HTML document with passed data. """ if data is None: data = {} ...
[ "def", "html", "(", "self", ",", "data", "=", "None", ",", "template", "=", "None", ")", ":", "if", "data", "is", "None", ":", "data", "=", "{", "}", "if", "template", ":", "return", "render", "(", "self", ".", "request", ",", "template", ",", "d...
31.692308
16.769231
def options(self, *args, **kwargs): """Applies simplified option definition returning a new object. Applies options on an object or nested group of objects in a flat format returning a new object with the options applied. If the options are to be set directly on the object a sim...
[ "def", "options", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "backend", "=", "kwargs", ".", "get", "(", "'backend'", ",", "None", ")", "clone", "=", "kwargs", ".", "pop", "(", "'clone'", ",", "True", ")", "if", "len", "(", ...
44.012658
23.683544
def iter_chat_members( self, chat_id: Union[int, str], limit: int = 0, query: str = "", filter: str = Filters.ALL ) -> Generator["pyrogram.ChatMember", None, None]: """Use this method to iterate through the members of a chat sequentially. This convenience met...
[ "def", "iter_chat_members", "(", "self", ",", "chat_id", ":", "Union", "[", "int", ",", "str", "]", ",", "limit", ":", "int", "=", "0", ",", "query", ":", "str", "=", "\"\"", ",", "filter", ":", "str", "=", "Filters", ".", "ALL", ")", "->", "Gene...
34
21.804348
def log_fail(self, item: str) -> None: """ Log a failed action for an item. If the fail count for this item reaches the threshold, the item is moved to the blacklist. :param str item: The item to log """ assert item is not None item = self._encode_item(item) ...
[ "def", "log_fail", "(", "self", ",", "item", ":", "str", ")", "->", "None", ":", "assert", "item", "is", "not", "None", "item", "=", "self", ".", "_encode_item", "(", "item", ")", "if", "self", ".", "is_blocked", "(", "item", ")", ":", "return", "c...
42.851852
18.925926
def get(self, name): """Get the attribute with the given *name*. The returned object is a :class:`.Attribute` instance. Raises :exc:`ValueError` if no attribute has this name. Since multiple attributes can have the same name, we'll return the last match, since all but the last a...
[ "def", "get", "(", "self", ",", "name", ")", ":", "for", "attr", "in", "reversed", "(", "self", ".", "attributes", ")", ":", "if", "attr", ".", "name", "==", "name", ".", "strip", "(", ")", ":", "return", "attr", "raise", "ValueError", "(", "name",...
42
17.333333
def dbsize(host=None, port=None, db=None, password=None): ''' Return the number of keys in the selected database CLI Example: .. code-block:: bash salt '*' redis.dbsize ''' server = _connect(host, port, db, password) return server.dbsize()
[ "def", "dbsize", "(", "host", "=", "None", ",", "port", "=", "None", ",", "db", "=", "None", ",", "password", "=", "None", ")", ":", "server", "=", "_connect", "(", "host", ",", "port", ",", "db", ",", "password", ")", "return", "server", ".", "d...
22.25
24.083333
def _api_limits(self, plugin): """Glances API RESTful implementation. Return the JSON limits of a given plugin HTTP/200 if OK HTTP/400 if plugin is not found HTTP/404 if others error """ response.content_type = 'application/json; charset=utf-8' if plugin...
[ "def", "_api_limits", "(", "self", ",", "plugin", ")", ":", "response", ".", "content_type", "=", "'application/json; charset=utf-8'", "if", "plugin", "not", "in", "self", ".", "plugins_list", ":", "abort", "(", "400", ",", "\"Unknown plugin %s (available plugins: %...
33.227273
20.181818
def do_lmfit(data, params, B=None, errs=None, dojac=True): """ Fit the model to the data data may contain 'flagged' or 'masked' data with the value of np.NaN Parameters ---------- data : 2d-array Image data params : lmfit.Parameters Initial model guess. B : 2d-array ...
[ "def", "do_lmfit", "(", "data", ",", "params", ",", "B", "=", "None", ",", "errs", "=", "None", ",", "dojac", "=", "True", ")", ":", "# copy the params so as not to change the initial conditions", "# in case we want to use them elsewhere", "params", "=", "copy", "."...
25.929577
23.169014
def capture(self): """ Capture the payment of an existing, uncaptured, charge. This is the second half of the two-step payment flow, where first you created a charge with the capture option set to False. See https://stripe.com/docs/api#capture_charge """ captured_charge = self.api_retrieve().capture() ...
[ "def", "capture", "(", "self", ")", ":", "captured_charge", "=", "self", ".", "api_retrieve", "(", ")", ".", "capture", "(", ")", "return", "self", ".", "__class__", ".", "sync_from_stripe_data", "(", "captured_charge", ")" ]
33.727273
18.636364
def list(self, request): """ Retrieve logged in user info """ serializer = self.get_serializer(request.user) return Response(serializer.data, status=status.HTTP_200_OK)
[ "def", "list", "(", "self", ",", "request", ")", ":", "serializer", "=", "self", ".", "get_serializer", "(", "request", ".", "user", ")", "return", "Response", "(", "serializer", ".", "data", ",", "status", "=", "status", ".", "HTTP_200_OK", ")" ]
33.833333
10.166667
def identity_kernel_initializer(shape, dtype=tf.float32, partition_info=None): """An initializer for constructing identity convolution kernels. Constructs a convolution kernel such that applying it is the same as an identity operation on the input. Formally, the kernel has entry [i, j, in, out] = 1 if in equal...
[ "def", "identity_kernel_initializer", "(", "shape", ",", "dtype", "=", "tf", ".", "float32", ",", "partition_info", "=", "None", ")", ":", "if", "len", "(", "shape", ")", "!=", "4", ":", "raise", "ValueError", "(", "\"Convolution kernels must be rank 4.\"", ")...
41.088889
24.488889
def series_keys(self, flow_id, cache=True): ''' Get an empty dataset with all possible series keys. Return a pandas DataFrame. Each column represents a dimension, each row a series key of datasets of the given dataflow. ''' # Check if requested series ke...
[ "def", "series_keys", "(", "self", ",", "flow_id", ",", "cache", "=", "True", ")", ":", "# Check if requested series keys are already cached", "cache_id", "=", "'series_keys_'", "+", "flow_id", "if", "cache_id", "in", "self", ".", "cache", ":", "return", "self", ...
38.714286
16.619048
def parse_args(options={}, *args, **kwds): """ Parser of arguments. dict options { int min_items: Min of required items to fold one tuple. (default: 1) int max_items: Count of items in one tuple. Last `max_items-min_items` items is by default set to None. (default: 1) bo...
[ "def", "parse_args", "(", "options", "=", "{", "}", ",", "*", "args", ",", "*", "*", "kwds", ")", ":", "parser_options", "=", "ParserOptions", "(", "options", ")", "parser_input", "=", "ParserInput", "(", "args", ",", "kwds", ")", "parser", "=", "Parse...
39.916667
21.027778
def make_filled_array(shp, dtype, order, r, g, b, a): """Return a filled array with a color value. order defines the color planes in the array. (r, g, b, a) are expected to be in the range 0..1 and are scaled to the appropriate values. shp can define a 2D or 3D array. """ # TODO: can we make t...
[ "def", "make_filled_array", "(", "shp", ",", "dtype", ",", "order", ",", "r", ",", "g", ",", "b", ",", "a", ")", ":", "# TODO: can we make this more efficient?", "maxv", "=", "np", ".", "iinfo", "(", "dtype", ")", ".", "max", "bgval", "=", "dict", "(",...
42.95
12.7
def _single_replace(self, to_replace, method, inplace, limit): """ Replaces values in a Series using the fill method specified when no replacement value is given in the replace method """ if self.ndim != 1: raise TypeError('cannot replace {0} with method {1} on a {2}' ...
[ "def", "_single_replace", "(", "self", ",", "to_replace", ",", "method", ",", "inplace", ",", "limit", ")", ":", "if", "self", ".", "ndim", "!=", "1", ":", "raise", "TypeError", "(", "'cannot replace {0} with method {1} on a {2}'", ".", "format", "(", "to_repl...
31.407407
21.333333
def calc_search_range(url, match_type, surt_ordered=True, url_canon=None): """ Canonicalize a url (either with custom canonicalizer or standard canonicalizer with or without surt) Then, compute a start and end search url search range for a given match type. Support match types: * exact ...
[ "def", "calc_search_range", "(", "url", ",", "match_type", ",", "surt_ordered", "=", "True", ",", "url_canon", "=", "None", ")", ":", "def", "inc_last_char", "(", "x", ")", ":", "return", "x", "[", "0", ":", "-", "1", "]", "+", "chr", "(", "ord", "...
31.436975
22.663866
def down_alpha_beta(returns, factor_returns, **kwargs): """ Computes alpha and beta for periods when the benchmark return is negative. Parameters ---------- see documentation for `alpha_beta`. Returns ------- alpha : float beta : float """ return down(returns, factor_return...
[ "def", "down_alpha_beta", "(", "returns", ",", "factor_returns", ",", "*", "*", "kwargs", ")", ":", "return", "down", "(", "returns", ",", "factor_returns", ",", "function", "=", "alpha_beta_aligned", ",", "*", "*", "kwargs", ")" ]
24.857143
23.571429
def use_tsig(self, keyring, keyname=None, algorithm=dns.tsig.default_algorithm): """Add a TSIG signature to the query. @param keyring: The TSIG keyring to use; defaults to None. @type keyring: dict @param keyname: The name of the TSIG key to use; defaults to None. ...
[ "def", "use_tsig", "(", "self", ",", "keyring", ",", "keyname", "=", "None", ",", "algorithm", "=", "dns", ".", "tsig", ".", "default_algorithm", ")", ":", "self", ".", "keyring", "=", "keyring", "if", "keyname", "is", "None", ":", "self", ".", "keynam...
47.428571
18.333333
def dvd_lists(self, **kwargs): """Gets the dvd lists available from the API. Returns: A dict respresentation of the JSON returned from the API. """ path = self._get_path('dvd_lists') response = self._GET(path, kwargs) self._set_attrs_to_values(response) ...
[ "def", "dvd_lists", "(", "self", ",", "*", "*", "kwargs", ")", ":", "path", "=", "self", ".", "_get_path", "(", "'dvd_lists'", ")", "response", "=", "self", ".", "_GET", "(", "path", ",", "kwargs", ")", "self", ".", "_set_attrs_to_values", "(", "respon...
29.727273
15
def compute_information_gain(ann_inter, est_inter, est_file, bins): """Computes the information gain of the est_file from the annotated intervals and the estimated intervals.""" ann_times = utils.intervals_to_times(ann_inter) est_times = utils.intervals_to_times(est_inter) return mir_eval.beat.infor...
[ "def", "compute_information_gain", "(", "ann_inter", ",", "est_inter", ",", "est_file", ",", "bins", ")", ":", "ann_times", "=", "utils", ".", "intervals_to_times", "(", "ann_inter", ")", "est_times", "=", "utils", ".", "intervals_to_times", "(", "est_inter", ")...
59.833333
13.833333
def outgoing(cls, hostport, process_name=None, serve_hostport=None, handler=None, tchannel=None): """Initiate a new connection to the given host. :param hostport: String in the form ``$host:$port`` specifying the target host :param process_name: Process ...
[ "def", "outgoing", "(", "cls", ",", "hostport", ",", "process_name", "=", "None", ",", "serve_hostport", "=", "None", ",", "handler", "=", "None", ",", "tchannel", "=", "None", ")", ":", "host", ",", "port", "=", "hostport", ".", "rsplit", "(", "\":\""...
39.26
21.54
def _ReadStructureDataTypeDefinition( self, definitions_registry, definition_values, definition_name, is_member=False): """Reads a structure data type definition. Args: definitions_registry (DataTypeDefinitionsRegistry): data type definitions registry. definition_values (dict[...
[ "def", "_ReadStructureDataTypeDefinition", "(", "self", ",", "definitions_registry", ",", "definition_values", ",", "definition_name", ",", "is_member", "=", "False", ")", ":", "if", "is_member", ":", "error_message", "=", "'data type not supported as member'", "raise", ...
38.037037
23.259259
def get_package_list(self): """ Returns a list of all required packages. """ os_version = self.os_version # OS(type=LINUX, distro=UBUNTU, release='14.04') self.vprint('os_version:', os_version) # Lookup legacy package list. # OS: [package1, package2, ...], ...
[ "def", "get_package_list", "(", "self", ")", ":", "os_version", "=", "self", ".", "os_version", "# OS(type=LINUX, distro=UBUNTU, release='14.04')", "self", ".", "vprint", "(", "'os_version:'", ",", "os_version", ")", "# Lookup legacy package list.", "# OS: [package1, packag...
38.8
16.25
def _get_search_result(self, query_url, **query_params): """ Get search results helper. """ param_q = query_params.get('q') param_query = query_params.get('query') # Either q or query parameter is required if bool(param_q) == bool(param_query): raise CloudantArgumentE...
[ "def", "_get_search_result", "(", "self", ",", "query_url", ",", "*", "*", "query_params", ")", ":", "param_q", "=", "query_params", ".", "get", "(", "'q'", ")", "param_query", "=", "query_params", ".", "get", "(", "'query'", ")", "# Either q or query paramete...
43.217391
14.086957
def make_file_exist(self, filename=None): """Make the directory exist, then touch the file If the filename is None, then use self.name as filename """ if filename is None: path_to_file = FilePath(self) path_to_file.make_file_exist() return path_to_fil...
[ "def", "make_file_exist", "(", "self", ",", "filename", "=", "None", ")", ":", "if", "filename", "is", "None", ":", "path_to_file", "=", "FilePath", "(", "self", ")", "path_to_file", ".", "make_file_exist", "(", ")", "return", "path_to_file", "else", ":", ...
35.230769
9.923077