text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def image_encoder(image_feat, hparams, name="image_encoder", save_weights_to=None, make_image_summary=True): """A stack of self attention layers.""" x = image_feat image_hidden_size = hparams.image_hidden_size or hparams.hidden_size image_...
[ "def", "image_encoder", "(", "image_feat", ",", "hparams", ",", "name", "=", "\"image_encoder\"", ",", "save_weights_to", "=", "None", ",", "make_image_summary", "=", "True", ")", ":", "x", "=", "image_feat", "image_hidden_size", "=", "hparams", ".", "image_hidd...
45.153846
0.008337
def allow(self, role, method, resource, with_children=True): """Add allowing rules. :param role: Role of this rule. :param method: Method to allow in rule, include GET, POST, PUT etc. :param resource: Resource also view function. :param with_children: Allow role's children in ru...
[ "def", "allow", "(", "self", ",", "role", ",", "method", ",", "resource", ",", "with_children", "=", "True", ")", ":", "if", "with_children", ":", "for", "r", "in", "role", ".", "get_children", "(", ")", ":", "permission", "=", "(", "r", ".", "get_na...
43.05
0.002273
def git_sequence_editor_squash(fpath): r""" squashes wip messages CommandLine: python -m utool.util_git --exec-git_sequence_editor_squash Example: >>> # DISABLE_DOCTEST >>> # SCRIPT >>> import utool as ut >>> from utool.util_git import * # NOQA >>> fpat...
[ "def", "git_sequence_editor_squash", "(", "fpath", ")", ":", "# print(sys.argv)", "import", "utool", "as", "ut", "text", "=", "ut", ".", "read_from", "(", "fpath", ")", "# print('fpath = %r' % (fpath,))", "print", "(", "text", ")", "# Doesnt work because of fixed witd...
38.950355
0.000533
def search_references( self, reference_set_id, accession=None, md5checksum=None): """ Returns an iterator over the References fulfilling the specified conditions from the specified Dataset. :param str reference_set_id: The ReferenceSet to search. :param str accession...
[ "def", "search_references", "(", "self", ",", "reference_set_id", ",", "accession", "=", "None", ",", "md5checksum", "=", "None", ")", ":", "request", "=", "protocol", ".", "SearchReferencesRequest", "(", ")", "request", ".", "reference_set_id", "=", "reference_...
50.045455
0.001783
def find_note_names(self, notelist, string=0, maxfret=24): """Return a list [(fret, notename)] in ascending order. Notelist should be a list of Notes, note-strings or a NoteContainer. Example: >>> t = tunings.StringTuning('test', 'test', ['A-3', 'A-4']) >>> t.find_note_names(['...
[ "def", "find_note_names", "(", "self", ",", "notelist", ",", "string", "=", "0", ",", "maxfret", "=", "24", ")", ":", "n", "=", "notelist", "if", "notelist", "!=", "[", "]", "and", "type", "(", "notelist", "[", "0", "]", ")", "==", "str", ":", "n...
37.478261
0.002262
def bitset(name, members, base=bases.BitSet, list=False, tuple=False): """Return a new bitset class with given name and members. Args: name: Name of the class to be created. members: Hashable sequence of allowed bitset members. base: Base class to derive the returned class from. ...
[ "def", "bitset", "(", "name", ",", "members", ",", "base", "=", "bases", ".", "BitSet", ",", "list", "=", "False", ",", "tuple", "=", "False", ")", ":", "if", "not", "name", ":", "raise", "ValueError", "(", "'empty bitset name: %r'", "%", "name", ")", ...
41.222222
0.001317
def drdsph(r, colat, lon): """ This routine computes the Jacobian of the transformation from spherical to rectangular coordinates. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/drdsph_c.html :param r: Distance of a point from the origin. :type r: float :param colat: Angle of the ...
[ "def", "drdsph", "(", "r", ",", "colat", ",", "lon", ")", ":", "r", "=", "ctypes", ".", "c_double", "(", "r", ")", "colat", "=", "ctypes", ".", "c_double", "(", "colat", ")", "lon", "=", "ctypes", ".", "c_double", "(", "lon", ")", "jacobi", "=", ...
33.590909
0.001316
def stringify(value, encoding_default='utf-8', encoding=None): """Brute-force convert a given object to a string. This will attempt an increasingly mean set of conversions to make a given object into a unicode string. It is guaranteed to either return unicode or None, if all conversions failed (or the ...
[ "def", "stringify", "(", "value", ",", "encoding_default", "=", "'utf-8'", ",", "encoding", "=", "None", ")", ":", "if", "value", "is", "None", ":", "return", "None", "if", "not", "isinstance", "(", "value", ",", "six", ".", "text_type", ")", ":", "if"...
37.413793
0.000898
def backward(self, loss): """backward propagation with loss""" with mx.autograd.record(): if isinstance(loss, (tuple, list)): ls = [l * self._scaler.loss_scale for l in loss] else: ls = loss * self._scaler.loss_scale mx.autograd.backward(ls...
[ "def", "backward", "(", "self", ",", "loss", ")", ":", "with", "mx", ".", "autograd", ".", "record", "(", ")", ":", "if", "isinstance", "(", "loss", ",", "(", "tuple", ",", "list", ")", ")", ":", "ls", "=", "[", "l", "*", "self", ".", "_scaler"...
39.25
0.009346
def _values_for_rank(self): """ For correctly ranking ordered categorical data. See GH#15420 Ordered categorical data should be ranked on the basis of codes with -1 translated to NaN. Returns ------- numpy.array """ from pandas import Series ...
[ "def", "_values_for_rank", "(", "self", ")", ":", "from", "pandas", "import", "Series", "if", "self", ".", "ordered", ":", "values", "=", "self", ".", "codes", "mask", "=", "values", "==", "-", "1", "if", "mask", ".", "any", "(", ")", ":", "values", ...
30.75
0.002252
def present(name, acl_type, acl_name='', perms='', recurse=False, force=False): ''' Ensure a Linux ACL is present name The acl path acl_type The type of the acl is used for it can be 'user' or 'group' acl_name The user or group perms Set the permissions eg.: ...
[ "def", "present", "(", "name", ",", "acl_type", ",", "acl_name", "=", "''", ",", "perms", "=", "''", ",", "recurse", "=", "False", ",", "force", "=", "False", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'result'", ":", "True", ",", "'...
39.007246
0.001993
def retrieve_breadcrumbs(path, model_instance, root_name=''): """ Build a semi-hardcoded breadcrumbs based of the model's url handled by Zinnia. """ breadcrumbs = [] zinnia_root_path = reverse('zinnia:entry_archive_index') if root_name: breadcrumbs.append(Crumb(root_name, zinnia_roo...
[ "def", "retrieve_breadcrumbs", "(", "path", ",", "model_instance", ",", "root_name", "=", "''", ")", ":", "breadcrumbs", "=", "[", "]", "zinnia_root_path", "=", "reverse", "(", "'zinnia:entry_archive_index'", ")", "if", "root_name", ":", "breadcrumbs", ".", "app...
34.596154
0.000541
def publish_alias(self, func_data, alias): """Create or update an alias for the given function. """ if not alias: return func_data['FunctionArn'] func_name = func_data['FunctionName'] func_version = func_data['Version'] exists = resource_exists( s...
[ "def", "publish_alias", "(", "self", ",", "func_data", ",", "alias", ")", ":", "if", "not", "alias", ":", "return", "func_data", "[", "'FunctionArn'", "]", "func_name", "=", "func_data", "[", "'FunctionName'", "]", "func_version", "=", "func_data", "[", "'Ve...
38.851852
0.00186
def copy_path_flat(self): """Return a flattened copy of the current path This method is like :meth:`copy_path` except that any curves in the path will be approximated with piecewise-linear approximations, (accurate to within the current tolerance value, see :meth:`set_to...
[ "def", "copy_path_flat", "(", "self", ")", ":", "path", "=", "cairo", ".", "cairo_copy_path_flat", "(", "self", ".", "_pointer", ")", "result", "=", "list", "(", "_iter_path", "(", "path", ")", ")", "cairo", ".", "cairo_path_destroy", "(", "path", ")", "...
36.73913
0.002307
def schema(): """ All tables, columns, steps, injectables and broadcasts registered with Orca. Includes local columns on tables. """ tables = orca.list_tables() cols = {t: orca.get_table(t).columns for t in tables} steps = orca.list_steps() injectables = orca.list_injectables() broa...
[ "def", "schema", "(", ")", ":", "tables", "=", "orca", ".", "list_tables", "(", ")", "cols", "=", "{", "t", ":", "orca", ".", "get_table", "(", "t", ")", ".", "columns", "for", "t", "in", "tables", "}", "steps", "=", "orca", ".", "list_steps", "(...
30.933333
0.002092
def bounds(filename, start_re, end_re, encoding='utf8'): """ Compute chunk bounds from text file according to start_re and end_re: yields (start_match, Bounds) tuples. """ start_re, end_re = re.compile(start_re), re.compile(end_re) mo, line_start, line_end, byte_start, byte_end = [None]*5 of...
[ "def", "bounds", "(", "filename", ",", "start_re", ",", "end_re", ",", "encoding", "=", "'utf8'", ")", ":", "start_re", ",", "end_re", "=", "re", ".", "compile", "(", "start_re", ")", ",", "re", ".", "compile", "(", "end_re", ")", "mo", ",", "line_st...
38.409091
0.001155
def ac_viz(acdata): ''' Adapted from Gerry Harp at SETI. Slightly massages the autocorrelated calculation result for better visualization. In particular, the natural log of the data are calculated and the values along the subband edges are set to the maximum value of the data, and the t=0 delay of the ...
[ "def", "ac_viz", "(", "acdata", ")", ":", "acdata", "=", "np", ".", "log", "(", "acdata", "+", "0.000001", ")", "# log to reduce darkening on sides of spectrum, due to AC triangling", "acdata", "[", ":", ",", ":", ",", "acdata", ".", "shape", "[", "2", "]", ...
43.75
0.017897
def sample(img, coords): """ Args: img: bxhxwxc coords: bxh2xw2x2. each coordinate is (y, x) integer. Out of boundary coordinates will be clipped. Return: bxh2xw2xc image """ shape = img.get_shape().as_list()[1:] # h, w, c batch = tf.shape(img)[0] shape2...
[ "def", "sample", "(", "img", ",", "coords", ")", ":", "shape", "=", "img", ".", "get_shape", "(", ")", ".", "as_list", "(", ")", "[", "1", ":", "]", "# h, w, c", "batch", "=", "tf", ".", "shape", "(", "img", ")", "[", "0", "]", "shape2", "=", ...
37.583333
0.002162
def initWithDelegate_(self, cb_obj): """ Arguments: - cb_obj: An object that receives callbacks when events occur. This object should have: - a method '_handle_channeldata' which takes the related channel (a IOBluetoothRFCOMMChannel or IOBluetoothL2CAPChannel)...
[ "def", "initWithDelegate_", "(", "self", ",", "cb_obj", ")", ":", "self", "=", "super", "(", "_ChannelEventListener", ",", "self", ")", ".", "init", "(", ")", "if", "cb_obj", "is", "None", ":", "raise", "TypeError", "(", "\"callback object is None\"", ")", ...
46.851852
0.002324
def transaction_retry(max_retries=1): """Decorator for methods doing database operations. If the database operation fails, it will retry the operation at most ``max_retries`` times. """ def _outer(fun): @wraps(fun) def _inner(*args, **kwargs): _max_retries = kwargs.pop...
[ "def", "transaction_retry", "(", "max_retries", "=", "1", ")", ":", "def", "_outer", "(", "fun", ")", ":", "@", "wraps", "(", "fun", ")", "def", "_inner", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "_max_retries", "=", "kwargs", ".", "pop...
36.433333
0.000891
def get_objective_bank_ids_by_activity(self, activity_id): """Gets the list of ``ObjectiveBank Ids`` mapped to a ``Activity``. arg: activity_id (osid.id.Id): ``Id`` of a ``Activity`` return: (osid.id.IdList) - list of objective bank ``Ids`` raise: NotFound - ``activity_id`` is not f...
[ "def", "get_objective_bank_ids_by_activity", "(", "self", ",", "activity_id", ")", ":", "# Implemented from template for", "# osid.resource.ResourceBinSession.get_bin_ids_by_resource", "mgr", "=", "self", ".", "_get_provider_manager", "(", "'LEARNING'", ",", "local", "=", "Tr...
49.318182
0.001808
def _find_channels(note): """Find the channel names within a string. The channel names are stored in the .ent file. We can read the file with _read_ent and we can parse most of the notes (comments) with _read_notes however the note containing the montage cannot be read because it's too complex. So,...
[ "def", "_find_channels", "(", "note", ")", ":", "id_ch", "=", "note", ".", "index", "(", "'ChanNames'", ")", "chan_beg", "=", "note", ".", "index", "(", "'('", ",", "id_ch", ")", "chan_end", "=", "note", ".", "index", "(", "')'", ",", "chan_beg", ")"...
34.115385
0.001096
def get_arguments(): """Get the command line arguments""" import argparse parser = argparse.ArgumentParser( description='Plot spectral responses for a set of satellite imagers') parser.add_argument("--platform_name", '-p', nargs='*', help="The Platform name", ...
[ "def", "get_arguments", "(", ")", ":", "import", "argparse", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "'Plot spectral responses for a set of satellite imagers'", ")", "parser", ".", "add_argument", "(", "\"--platform_name\"", ",", "'-p'...
49.652174
0.001288
def self_insert(self, e): # (a, b, A, 1, !, ...) u"""Insert yourself. """ if e.char and ord(e.char)!=0: #don't insert null character in buffer, can happen with dead keys. self.insert_text(e.char) self.finalize()
[ "def", "self_insert", "(", "self", ",", "e", ")", ":", "# (a, b, A, 1, !, ...)\r", "if", "e", ".", "char", "and", "ord", "(", "e", ".", "char", ")", "!=", "0", ":", "#don't insert null character in buffer, can happen with dead keys.\r", "self", ".", "insert_text",...
49.4
0.027888
def _get_linewise_report(self): """ Returns a report each line of which comprises a pair of an input line and an error. Unlike in the standard report, errors will appear as many times as they occur. Helper for the get_report method. """ d = defaultdict(list) # line: [] of errors for error, lines in s...
[ "def", "_get_linewise_report", "(", "self", ")", ":", "d", "=", "defaultdict", "(", "list", ")", "# line: [] of errors", "for", "error", ",", "lines", "in", "self", ".", "errors", ".", "items", "(", ")", ":", "for", "line_num", "in", "lines", ":", "d", ...
27.833333
0.030888
def stop_image_acquisition(self): """ Stops image acquisition. :return: None. """ if self.is_acquiring_images: # self._is_acquiring_images = False # if self.thread_image_acquisition.is_running: # TODO self.thread_...
[ "def", "stop_image_acquisition", "(", "self", ")", ":", "if", "self", ".", "is_acquiring_images", ":", "#", "self", ".", "_is_acquiring_images", "=", "False", "#", "if", "self", ".", "thread_image_acquisition", ".", "is_running", ":", "# TODO", "self", ".", "t...
32.327869
0.000984
def Emulation_setVisibleSize(self, width, height): """ Function path: Emulation.setVisibleSize Domain: Emulation Method name: setVisibleSize WARNING: This function is marked 'Experimental'! Parameters: Required arguments: 'width' (type: integer) -> Frame width (DIP). 'height' (type: ...
[ "def", "Emulation_setVisibleSize", "(", "self", ",", "width", ",", "height", ")", ":", "assert", "isinstance", "(", "width", ",", "(", "int", ",", ")", ")", ",", "\"Argument 'width' must be of type '['int']'. Received type: '%s'\"", "%", "type", "(", "width", ")",...
38.48
0.041582
def scan_file(path): """ Scan `path` for viruses using ``clamscan`` program. Args: path (str): Relative or absolute path of file/directory you need to scan. Returns: dict: ``{filename: ("FOUND", "virus type")}`` or blank dict. Raises: AssertionError: Wh...
[ "def", "scan_file", "(", "path", ")", ":", "path", "=", "os", ".", "path", ".", "abspath", "(", "path", ")", "assert", "os", ".", "path", ".", "exists", "(", "path", ")", ",", "\"Unreachable file '%s'.\"", "%", "path", "result", "=", "sh", ".", "clam...
27.9
0.001733
def get_line_and_char(newline_positions, position): """Given a list of newline positions, and an offset from the start of the source code that newline_positions was pulled from, return a 2-tuple of (line, char) coordinates. """ if newline_positions: for line_no, nl_pos in enumerate(newline_positions): ...
[ "def", "get_line_and_char", "(", "newline_positions", ",", "position", ")", ":", "if", "newline_positions", ":", "for", "line_no", ",", "nl_pos", "in", "enumerate", "(", "newline_positions", ")", ":", "if", "nl_pos", ">=", "position", ":", "if", "line_no", "==...
41.142857
0.01528
def build_msg(self, event_type, data=None, date=None, time_spent=None, extra=None, stack=None, public_key=None, tags=None, fingerprint=None, **kwargs): """ Captures, processes and serializes an event into a dict object The result of ``build_msg`` should be a ...
[ "def", "build_msg", "(", "self", ",", "event_type", ",", "data", "=", "None", ",", "date", "=", "None", ",", "time_spent", "=", "None", ",", "extra", "=", "None", ",", "stack", "=", "None", ",", "public_key", "=", "None", ",", "tags", "=", "None", ...
33.847222
0.000997
def dump(o, f): """Writes out dict as toml to a file Args: o: Object to dump into toml f: File descriptor where the toml should be stored Returns: String containing the toml corresponding to dictionary Raises: TypeError: When anything other than file descriptor is pass...
[ "def", "dump", "(", "o", ",", "f", ")", ":", "if", "not", "f", ".", "write", ":", "raise", "TypeError", "(", "\"You can only dump an object to a file descriptor\"", ")", "d", "=", "dumps", "(", "o", ")", "f", ".", "write", "(", "d", ")", "return", "d" ...
23.894737
0.002119
def capacity_nzs_vm4_2011(sl, fd, h_l=0, h_b=0, vertical_load=1, slope=0, verbose=0, **kwargs): """ calculates the capacity according to Appendix B verification method 4 of the NZ building code :param sl: Soil object :param fd: Foundation object :param h_l: Horizontal load parallel to length ...
[ "def", "capacity_nzs_vm4_2011", "(", "sl", ",", "fd", ",", "h_l", "=", "0", ",", "h_b", "=", "0", ",", "vertical_load", "=", "1", ",", "slope", "=", "0", ",", "verbose", "=", "0", ",", "*", "*", "kwargs", ")", ":", "# Need to make adjustments if sand ...
35.024793
0.001836
def _ExtractPathSpecsFromFile(self, file_entry): """Extracts path specification from a file. Args: file_entry (dfvfs.FileEntry): file entry that refers to the file. Yields: dfvfs.PathSpec: path specification of a file entry found in the file. """ produced_main_path_spec = False for...
[ "def", "_ExtractPathSpecsFromFile", "(", "self", ",", "file_entry", ")", ":", "produced_main_path_spec", "=", "False", "for", "data_stream", "in", "file_entry", ".", "data_streams", ":", "# Make a copy so we don't make the changes on a path specification", "# directly. Otherwis...
34.083333
0.010702
def transfer(self): """ Returns a MappedObject containing the account's transfer pool data """ result = self.client.get('/account/transfer') if not 'used' in result: raise UnexpectedResponseError('Unexpected response when getting Transfer Pool!') return Mapp...
[ "def", "transfer", "(", "self", ")", ":", "result", "=", "self", ".", "client", ".", "get", "(", "'/account/transfer'", ")", "if", "not", "'used'", "in", "result", ":", "raise", "UnexpectedResponseError", "(", "'Unexpected response when getting Transfer Pool!'", "...
32.9
0.011834
def _x_tune_ok(self, channel_max, frame_max, heartbeat): """Negotiate connection tuning parameters This method sends the client's connection tuning parameters to the server. Certain fields are negotiated, others provide capability information. PARAMETERS: channel_ma...
[ "def", "_x_tune_ok", "(", "self", ",", "channel_max", ",", "frame_max", ",", "heartbeat", ")", ":", "args", "=", "AMQPWriter", "(", ")", "args", ".", "write_short", "(", "channel_max", ")", "args", ".", "write_long", "(", "frame_max", ")", "args", ".", "...
35.327273
0.001002
def del_membership(self, user, role): """ dismember user from a group """ if not self.has_membership(user, role): return True targetRecord = AuthMembership.objects(creator=self.client, user=user).first() if not targetRecord: return True for group in targe...
[ "def", "del_membership", "(", "self", ",", "user", ",", "role", ")", ":", "if", "not", "self", ".", "has_membership", "(", "user", ",", "role", ")", ":", "return", "True", "targetRecord", "=", "AuthMembership", ".", "objects", "(", "creator", "=", "self"...
37.916667
0.008584
def from_edgerc(rcinput, section='default'): """Returns an EdgeGridAuth object from the configuration from the given section of the given edgerc file. :param filename: path to the edgerc file :param section: the section to use (this is the [bracketed] part of the edgerc, ...
[ "def", "from_edgerc", "(", "rcinput", ",", "section", "=", "'default'", ")", ":", "from", ".", "edgerc", "import", "EdgeRc", "if", "isinstance", "(", "rcinput", ",", "EdgeRc", ")", ":", "rc", "=", "rcinput", "else", ":", "rc", "=", "EdgeRc", "(", "rcin...
37.227273
0.008333
def init(): """ Initialize synchronously. """ loop = asyncio.get_event_loop() if loop.is_running(): raise Exception("You must initialize the Ray async API by calling " "async_api.init() or async_api.as_future(obj) before " "the event loop start...
[ "def", "init", "(", ")", ":", "loop", "=", "asyncio", ".", "get_event_loop", "(", ")", "if", "loop", ".", "is_running", "(", ")", ":", "raise", "Exception", "(", "\"You must initialize the Ray async API by calling \"", "\"async_api.init() or async_api.as_future(obj) bef...
35.545455
0.002494
def _format(formatter, x): """ Helper to format and tidy up """ # For MPL to play nice formatter.create_dummy_axis() # For sensible decimal places formatter.set_locs([val for val in x if ~np.isnan(val)]) try: oom = int(formatter.orderOfMagnitude) except AttributeError: ...
[ "def", "_format", "(", "formatter", ",", "x", ")", ":", "# For MPL to play nice", "formatter", ".", "create_dummy_axis", "(", ")", "# For sensible decimal places", "formatter", ".", "set_locs", "(", "[", "val", "for", "val", "in", "x", "if", "~", "np", ".", ...
28.307692
0.001314
def deep_update_dict(default, options): """ Updates the values in a nested dict, while unspecified values will remain unchanged """ for key in options.keys(): default_setting = default.get(key) new_setting = options.get(key) if isinstance(default_setting, dict): d...
[ "def", "deep_update_dict", "(", "default", ",", "options", ")", ":", "for", "key", "in", "options", ".", "keys", "(", ")", ":", "default_setting", "=", "default", ".", "get", "(", "key", ")", "new_setting", "=", "options", ".", "get", "(", "key", ")", ...
33.916667
0.002392
def _check_useless_super_delegation(self, function): """Check if the given function node is an useless method override We consider it *useless* if it uses the super() builtin, but having nothing additional whatsoever than not implementing the method at all. If the method uses super() to...
[ "def", "_check_useless_super_delegation", "(", "self", ",", "function", ")", ":", "if", "(", "not", "function", ".", "is_method", "(", ")", "# With decorators is a change of use", "or", "function", ".", "decorators", ")", ":", "return", "body", "=", "function", ...
37.12381
0.001499
def Item(**kwargs): """Factory function for QAbstractListModel items Any class attributes are converted into pyqtProperties and must be declared with its type as value. Special keyword "parent" is not passed as object properties but instead passed to the QObject constructor. Usage: >>...
[ "def", "Item", "(", "*", "*", "kwargs", ")", ":", "parent", "=", "kwargs", ".", "pop", "(", "\"parent\"", ",", "None", ")", "cls", "=", "type", "(", "\"Item\"", ",", "(", "AbstractItem", ",", ")", ",", "kwargs", ".", "copy", "(", ")", ")", "self"...
27.394737
0.000928
def dict(self, **kwargs): """ Dictionary representation. """ return dict( time = self.timestamp, serial_number = self.serial_number, value = self.value, battery = self.battery, ...
[ "def", "dict", "(", "self", ",", "*", "*", "kwargs", ")", ":", "return", "dict", "(", "time", "=", "self", ".", "timestamp", ",", "serial_number", "=", "self", ".", "serial_number", ",", "value", "=", "self", ".", "value", ",", "battery", "=", "self"...
32.083333
0.042929
def safe_makedirs(fdir): """ Make an arbitrary directory. This is safe to call for Python 2 users. :param fdir: Directory path to make. :return: """ if os.path.isdir(fdir): pass # print 'dir already exists: %s' % str(dir) else: try: os.makedirs(fdir) ...
[ "def", "safe_makedirs", "(", "fdir", ")", ":", "if", "os", ".", "path", ".", "isdir", "(", "fdir", ")", ":", "pass", "# print 'dir already exists: %s' % str(dir)", "else", ":", "try", ":", "os", ".", "makedirs", "(", "fdir", ")", "except", "WindowsError", ...
28.157895
0.001808
def _with_primary(max_staleness, selection): """Apply max_staleness, in seconds, to a Selection with a known primary.""" primary = selection.primary sds = [] for s in selection.server_descriptions: if s.server_type == SERVER_TYPE.RSSecondary: # See max-staleness.rst for explanation ...
[ "def", "_with_primary", "(", "max_staleness", ",", "selection", ")", ":", "primary", "=", "selection", ".", "primary", "sds", "=", "[", "]", "for", "s", "in", "selection", ".", "server_descriptions", ":", "if", "s", ".", "server_type", "==", "SERVER_TYPE", ...
36.157895
0.001418
def asyncPipeExchangerate(context=None, _INPUT=None, conf=None, **kwargs): """A string module that asynchronously retrieves the current exchange rate for a given currency pair. Loopable. Parameters ---------- context : pipe2py.Context object _INPUT : twisted Deferred iterable of items or string...
[ "def", "asyncPipeExchangerate", "(", "context", "=", "None", ",", "_INPUT", "=", "None", ",", "conf", "=", "None", ",", "*", "*", "kwargs", ")", ":", "offline", "=", "conf", ".", "get", "(", "'offline'", ",", "{", "}", ")", ".", "get", "(", "'value...
38.615385
0.000972
def hyperbola(axes, **kwargs): """ Plots a hyperbola that opens along y axis """ opens_up = kwargs.pop('opens_up', True) center = kwargs.pop('center', defaults['center']) th = N.linspace(0,2*N.pi,kwargs.pop('n', 500)) vals = [N.tan(th),1/N.cos(th)] if not opens_up: vals = vals[:...
[ "def", "hyperbola", "(", "axes", ",", "*", "*", "kwargs", ")", ":", "opens_up", "=", "kwargs", ".", "pop", "(", "'opens_up'", ",", "True", ")", "center", "=", "kwargs", ".", "pop", "(", "'center'", ",", "defaults", "[", "'center'", "]", ")", "th", ...
23.333333
0.010292
def parse(parse_obj, agent=None, etag=None, modified=None, inject=False): """Parse a subscription list and return a dict containing the results. :param parse_obj: A file-like object or a string containing a URL, an absolute or relative filename, or an XML document. :type parse_obj: str or file ...
[ "def", "parse", "(", "parse_obj", ",", "agent", "=", "None", ",", "etag", "=", "None", ",", "modified", "=", "None", ",", "inject", "=", "False", ")", ":", "guarantees", "=", "common", ".", "SuperDict", "(", "{", "'bozo'", ":", "0", ",", "'feeds'", ...
37.824324
0.000348
def PrepareMatches(self, file_system): """Prepare find specification for matching. Args: file_system (FileSystem): file system. """ if self._location is not None: self._location_segments = self._SplitPath( self._location, file_system.PATH_SEPARATOR) elif self._location_regex ...
[ "def", "PrepareMatches", "(", "self", ",", "file_system", ")", ":", "if", "self", ".", "_location", "is", "not", "None", ":", "self", ".", "_location_segments", "=", "self", ".", "_SplitPath", "(", "self", ".", "_location", ",", "file_system", ".", "PATH_S...
33.761905
0.00823
def save_file(self, path=None, force_overwrite=False, just_settings=False, **kwargs): """ Saves the data in the databox to a file. Parameters ---------- path=None Path for output. If set to None, use a save dialog. force_overwrite=False Do not que...
[ "def", "save_file", "(", "self", ",", "path", "=", "None", ",", "force_overwrite", "=", "False", ",", "just_settings", "=", "False", ",", "*", "*", "kwargs", ")", ":", "# Update the binary mode", "if", "not", "'binary'", "in", "kwargs", ":", "kwargs", "[",...
39
0.011676
def publish(self, topic, payload=None, qos=0, retain=False): # type: (str, bytes, int, bool) -> Tuple[int, int] """ Send a message to the broker. :param topic: the topic that the message should be published on :param payload: the actual message to send. If not given, or set to ...
[ "def", "publish", "(", "self", ",", "topic", ",", "payload", "=", "None", ",", "qos", "=", "0", ",", "retain", "=", "False", ")", ":", "# type: (str, bytes, int, bool) -> Tuple[int, int]", "if", "not", "self", ".", "connected", ":", "self", ".", "client", ...
46.212121
0.001927
def show_network(self): """! @brief Shows structure of the network: neurons and connections between them. """ dimension = len(self.__location[0]) if (dimension != 3) and (dimension != 2): raise NameError('Network that is located in different ...
[ "def", "show_network", "(", "self", ")", ":", "dimension", "=", "len", "(", "self", ".", "__location", "[", "0", "]", ")", "if", "(", "dimension", "!=", "3", ")", "and", "(", "dimension", "!=", "2", ")", ":", "raise", "NameError", "(", "'Network that...
53.392857
0.015112
def apply_func_to_select_indices(self, axis, func, indices, keep_remaining=False): """Applies a function to select indices. Note: Your internal function must take a kwarg `internal_indices` for this to work correctly. This prevents information leakage of the internal index to th...
[ "def", "apply_func_to_select_indices", "(", "self", ",", "axis", ",", "func", ",", "indices", ",", "keep_remaining", "=", "False", ")", ":", "if", "self", ".", "partitions", ".", "size", "==", "0", ":", "return", "np", ".", "array", "(", "[", "[", "]",...
44.02521
0.001307
def processes_file(self, filename, outfile=None, errorfile=None): """Take a filename of a file containing plantuml text and processes it into a .png image. :param str filename: Text file containing plantuml markup :param str outfile: Filename to write the output image to. If not...
[ "def", "processes_file", "(", "self", ",", "filename", ",", "outfile", "=", "None", ",", "errorfile", "=", "None", ")", ":", "if", "outfile", "is", "None", ":", "outfile", "=", "os", ".", "path", ".", "splitext", "(", "filename", ")", "[", "0", "]", ...
44
0.002152
def decrease_reads_in_percent( current_provisioning, percent, min_provisioned_reads, log_tag): """ Decrease the current_provisioning with percent % :type current_provisioning: int :param current_provisioning: The current provisioning :type percent: int :param percent: How many percent shoul...
[ "def", "decrease_reads_in_percent", "(", "current_provisioning", ",", "percent", ",", "min_provisioned_reads", ",", "log_tag", ")", ":", "percent", "=", "float", "(", "percent", ")", "decrease", "=", "int", "(", "float", "(", "current_provisioning", ")", "*", "(...
35.794118
0.0008
def km3h5concat(input_files, output_file, n_events=None, **kwargs): """Concatenate KM3HDF5 files via pipeline.""" from km3pipe import Pipeline # noqa from km3pipe.io import HDF5Pump, HDF5Sink # noqa pipe = Pipeline() pipe.attach(HDF5Pump, filenames=input_files, **kwargs) pipe.attach(Statu...
[ "def", "km3h5concat", "(", "input_files", ",", "output_file", ",", "n_events", "=", "None", ",", "*", "*", "kwargs", ")", ":", "from", "km3pipe", "import", "Pipeline", "# noqa", "from", "km3pipe", ".", "io", "import", "HDF5Pump", ",", "HDF5Sink", "# noqa", ...
41
0.002387
def parse_case(config): """Parse case information from config or PED files. Args: config (dict): case config with detailed information Returns: dict: parsed case data """ if 'owner' not in config: raise ConfigError("A case has to have a owner") if 'family' not in confi...
[ "def", "parse_case", "(", "config", ")", ":", "if", "'owner'", "not", "in", "config", ":", "raise", "ConfigError", "(", "\"A case has to have a owner\"", ")", "if", "'family'", "not", "in", "config", ":", "raise", "ConfigError", "(", "\"A case has to have a 'famil...
39.068966
0.001722
def RegisterBuiltin(cls, arg): '''register a builtin, create a new wrapper. ''' if arg in cls.types_dict: raise RuntimeError, '%s already registered' %arg class _Wrapper(arg): 'Wrapper for builtin %s\n%s' %(arg, cls.__doc__) _Wrapper.__name__ = '_%sWrapper...
[ "def", "RegisterBuiltin", "(", "cls", ",", "arg", ")", ":", "if", "arg", "in", "cls", ".", "types_dict", ":", "raise", "RuntimeError", ",", "'%s already registered'", "%", "arg", "class", "_Wrapper", "(", "arg", ")", ":", "'Wrapper for builtin %s\\n%s'", "%", ...
40.666667
0.018717
def _finalize_axis(self, key, element=None, title=None, dimensions=None, ranges=None, xticks=None, yticks=None, zticks=None, xlabel=None, ylabel=None, zlabel=None): """ Applies all the axis settings before the axis or figure is returned. Only plots with zorder 0 get to app...
[ "def", "_finalize_axis", "(", "self", ",", "key", ",", "element", "=", "None", ",", "title", "=", "None", ",", "dimensions", "=", "None", ",", "ranges", "=", "None", ",", "xticks", "=", "None", ",", "yticks", "=", "None", ",", "zticks", "=", "None", ...
41.569767
0.002459
def _unstack(self, unstacker_func, new_columns, n_rows, fill_value): """Return a list of unstacked blocks of self Parameters ---------- unstacker_func : callable Partially applied unstacker. new_columns : Index All columns of the unstacked BlockManager. ...
[ "def", "_unstack", "(", "self", ",", "unstacker_func", ",", "new_columns", ",", "n_rows", ",", "fill_value", ")", ":", "unstacker", "=", "unstacker_func", "(", "self", ".", "values", ".", "T", ")", "new_items", "=", "unstacker", ".", "get_new_columns", "(", ...
33.1875
0.00183
def union_fill_gap(self, i): '''Like union, but ignores whether the two intervals intersect or not''' return Interval(min(self.start, i.start), max(self.end, i.end))
[ "def", "union_fill_gap", "(", "self", ",", "i", ")", ":", "return", "Interval", "(", "min", "(", "self", ".", "start", ",", "i", ".", "start", ")", ",", "max", "(", "self", ".", "end", ",", "i", ".", "end", ")", ")" ]
59.666667
0.016575
def _query(action=None, command=None, args=None, method='GET', header_dict=None, data=None, url='https://api.linode.com/'): ''' Make a web call to the Linode API. ''' global LASTCALL vm_ = get_configured_provider() ratelimit_slee...
[ "def", "_query", "(", "action", "=", "None", ",", "command", "=", "None", ",", "args", "=", "None", ",", "method", "=", "'GET'", ",", "header_dict", "=", "None", ",", "data", "=", "None", ",", "url", "=", "'https://api.linode.com/'", ")", ":", "global"...
26.74359
0.000925
def get_dependencies(self): """ Retrieve the set of all dependencies for a given configuration. Returns: utils.utils.OrderedSet: The set of all dependencies for the tracked configuration. """ all_deps = OrderedSet() for key, _ in list(self.__c...
[ "def", "get_dependencies", "(", "self", ")", ":", "all_deps", "=", "OrderedSet", "(", ")", "for", "key", ",", "_", "in", "list", "(", "self", ".", "__config", ".", "items", "(", ")", ")", ":", "if", "key", "in", "self", ".", "__cli", ":", "continue...
33.296296
0.002162
def _update_params(param_arrays, grad_arrays, updater, num_device, kvstore=None, param_names=None): """Perform update of param_arrays from grad_arrays not on kvstore.""" updates = [[] for _ in range(num_device)] for i, pair in enumerate(zip(param_arrays, grad_arrays)): arg_list, g...
[ "def", "_update_params", "(", "param_arrays", ",", "grad_arrays", ",", "updater", ",", "num_device", ",", "kvstore", "=", "None", ",", "param_names", "=", "None", ")", ":", "updates", "=", "[", "[", "]", "for", "_", "in", "range", "(", "num_device", ")",...
45.576923
0.000826
def setChargingStationStop(self, vehID, stopID, duration=2**31 - 1, until=-1, flags=tc.STOP_DEFAULT): """setChargingStationStop(string, string, integer, integer, integer) -> None Adds or modifies a stop at a chargingStation with the given parameters. The duration and the until attribute are in ...
[ "def", "setChargingStationStop", "(", "self", ",", "vehID", ",", "stopID", ",", "duration", "=", "2", "**", "31", "-", "1", ",", "until", "=", "-", "1", ",", "flags", "=", "tc", ".", "STOP_DEFAULT", ")", ":", "self", ".", "setStop", "(", "vehID", "...
58.375
0.010549
def create_convert_sbml_id_function( compartment_prefix='C_', reaction_prefix='R_', compound_prefix='M_', decode_id=entry_id_from_cobra_encoding): """Create function for converting SBML IDs. The returned function will strip prefixes, decode the ID using the provided function. These prefixes...
[ "def", "create_convert_sbml_id_function", "(", "compartment_prefix", "=", "'C_'", ",", "reaction_prefix", "=", "'R_'", ",", "compound_prefix", "=", "'M_'", ",", "decode_id", "=", "entry_id_from_cobra_encoding", ")", ":", "def", "convert_sbml_id", "(", "entry", ")", ...
36.076923
0.001038
def mark_job_as_errored(job_id, error_object): """Mark a job as failed with an error. :param job_id: the job_id of the job to be updated :type job_id: unicode :param error_object: the error returned by the job :type error_object: either a string or a dict with a "message" key whose value i...
[ "def", "mark_job_as_errored", "(", "job_id", ",", "error_object", ")", ":", "update_dict", "=", "{", "\"status\"", ":", "\"error\"", ",", "\"error\"", ":", "error_object", ",", "\"finished_timestamp\"", ":", "datetime", ".", "datetime", ".", "now", "(", ")", "...
29.352941
0.001942
def suspend(self, instance_id): ''' Suspend a server ''' nt_ks = self.compute_conn response = nt_ks.servers.suspend(instance_id) return True
[ "def", "suspend", "(", "self", ",", "instance_id", ")", ":", "nt_ks", "=", "self", ".", "compute_conn", "response", "=", "nt_ks", ".", "servers", ".", "suspend", "(", "instance_id", ")", "return", "True" ]
26
0.010638
def rule_generator(*funcs): """ Constructor for creating multivariate quadrature generator. Args: funcs (:py:data:typing.Callable): One dimensional integration rule where each rule returns ``abscissas`` and ``weights`` as one dimensional arrays. They must take on...
[ "def", "rule_generator", "(", "*", "funcs", ")", ":", "dim", "=", "len", "(", "funcs", ")", "tensprod_rule", "=", "create_tensorprod_function", "(", "funcs", ")", "assert", "hasattr", "(", "tensprod_rule", ",", "\"__call__\"", ")", "mv_rule", "=", "create_mv_r...
42.078947
0.000611
def write_char_delay(self, ctl, delay): """ Write the formatted format pieces in order, applying a delay between characters for the text only. """ for i, fmt in enumerate(self.fmt): if '{text' in fmt: # The text will use a write delay. ctl....
[ "def", "write_char_delay", "(", "self", ",", "ctl", ",", "delay", ")", ":", "for", "i", ",", "fmt", "in", "enumerate", "(", "self", ".", "fmt", ")", ":", "if", "'{text'", "in", "fmt", ":", "# The text will use a write delay.", "ctl", ".", "text", "(", ...
39.32
0.001986
def polygon(self): '''return a polygon for the fence''' points = [] for fp in self.points[1:]: points.append((fp.lat, fp.lng)) return points
[ "def", "polygon", "(", "self", ")", ":", "points", "=", "[", "]", "for", "fp", "in", "self", ".", "points", "[", "1", ":", "]", ":", "points", ".", "append", "(", "(", "fp", ".", "lat", ",", "fp", ".", "lng", ")", ")", "return", "points" ]
33.833333
0.014423
def _CopyFromDateTimeString(self, time_string): """Copies a POSIX timestamp from a date and time string. Args: time_string (str): date and time value formatted as: YYYY-MM-DD hh:mm:ss.######[+-]##:## Where # are numeric digits ranging from 0 to 9 and the seconds fraction ca...
[ "def", "_CopyFromDateTimeString", "(", "self", ",", "time_string", ")", ":", "date_time_values", "=", "self", ".", "_CopyDateTimeFromString", "(", "time_string", ")", "year", "=", "date_time_values", ".", "get", "(", "'year'", ",", "0", ")", "month", "=", "dat...
38.1875
0.002394
def _unquote_c_string(s): """replace C-style escape sequences (\n, \", etc.) with real chars.""" # doing a s.encode('utf-8').decode('unicode_escape') can return an # incorrect output with unicode string (both in py2 and py3) the safest way # is to match the escape sequences and decoding them alone....
[ "def", "_unquote_c_string", "(", "s", ")", ":", "# doing a s.encode('utf-8').decode('unicode_escape') can return an", "# incorrect output with unicode string (both in py2 and py3) the safest way", "# is to match the escape sequences and decoding them alone.", "def", "decode_match", "(", "mat...
42.533333
0.02454
def server_inspect_exception(self, req_event, rep_event, task_ctx, exc_info): """ Called when an exception has been raised in the code run by ZeroRPC """ # Hide the zerorpc internal frames for readability, for a REQ/REP or # REQ/STREAM server the frames to hide are: # - c...
[ "def", "server_inspect_exception", "(", "self", ",", "req_event", ",", "rep_event", ",", "task_ctx", ",", "exc_info", ")", ":", "# Hide the zerorpc internal frames for readability, for a REQ/REP or", "# REQ/STREAM server the frames to hide are:", "# - core.ServerBase._async_task", ...
42.8
0.001523
def _finalize(self, chain=-1): """Finalize the chain for all tallyable objects.""" chain = range(self.chains)[chain] for name in self.trace_names[chain]: self._traces[name]._finalize(chain) self.commit()
[ "def", "_finalize", "(", "self", ",", "chain", "=", "-", "1", ")", ":", "chain", "=", "range", "(", "self", ".", "chains", ")", "[", "chain", "]", "for", "name", "in", "self", ".", "trace_names", "[", "chain", "]", ":", "self", ".", "_traces", "[...
40.333333
0.008097
def typelogged_func(func): """Works like typelogged, but is only applicable to functions, methods and properties. """ if not pytypes.typelogging_enabled: return func if hasattr(func, 'do_logging'): func.do_logging = True return func elif hasattr(func, 'do_typecheck'): ...
[ "def", "typelogged_func", "(", "func", ")", ":", "if", "not", "pytypes", ".", "typelogging_enabled", ":", "return", "func", "if", "hasattr", "(", "func", ",", "'do_logging'", ")", ":", "func", ".", "do_logging", "=", "True", "return", "func", "elif", "hasa...
33.214286
0.002092
def process_item_nodes(app, doctree, fromdocname): """ This function should be triggered upon ``doctree-resolved event`` Replace all item_list nodes with a list of the collected items. Augment each item with a backlink to the original location. """ env = app.builder.env all_items = sorted...
[ "def", "process_item_nodes", "(", "app", ",", "doctree", ",", "fromdocname", ")", ":", "env", "=", "app", ".", "builder", ".", "env", "all_items", "=", "sorted", "(", "env", ".", "traceability_all_items", ",", "key", "=", "naturalsortkey", ")", "# Item matri...
40.617021
0.000256
def _generate_sequences_for_ngram(self, t1, t2, ngram, covered_spans): """Generates aligned sequences for the texts `t1` and `t2`, based around `ngram`. Does not generate sequences that occur within `covered_spans`. :param t1: text content of first witness :type t1: `str` ...
[ "def", "_generate_sequences_for_ngram", "(", "self", ",", "t1", ",", "t2", ",", "ngram", ",", "covered_spans", ")", ":", "self", ".", "_logger", ".", "debug", "(", "'Generating sequences for n-gram \"{}\"'", ".", "format", "(", "ngram", ")", ")", "pattern", "=...
42.555556
0.001276
def lines_from_file(path, as_interned=False, encoding=None): """ Create a list of file lines from a given filepath. Args: path (str): File path as_interned (bool): List of "interned" strings (default False) Returns: strings (list): File line list """ lines = None wi...
[ "def", "lines_from_file", "(", "path", ",", "as_interned", "=", "False", ",", "encoding", "=", "None", ")", ":", "lines", "=", "None", "with", "io", ".", "open", "(", "path", ",", "encoding", "=", "encoding", ")", "as", "f", ":", "if", "as_interned", ...
28.555556
0.001883
def plot_filter_transmissions(log, filterList): """ *Plot the filters on a single plot* **Key Arguments:** - ``log`` -- logger - ``filterList`` -- list of absolute paths to plain text files containing filter transmission profiles **Return:** - None """ ################ ...
[ "def", "plot_filter_transmissions", "(", "log", ",", "filterList", ")", ":", "################ > IMPORTS ################", "## STANDARD LIB ##", "## THIRD PARTY ##", "import", "matplotlib", ".", "pyplot", "as", "plt", "import", "numpy", "as", "np", "## LOCAL APPLICATION ##...
26.692308
0.011127
def load_and_process_igor_model(self, marginals_file_name): """Set attributes by reading a generative model from IGoR marginal file. Sets attributes PV, PdelV_given_V, PDJ, PdelJ_given_J, PdelDldelDr_given_D, PinsVD, PinsDJ, Rvd, and Rdj. Parameters ---------- ...
[ "def", "load_and_process_igor_model", "(", "self", ",", "marginals_file_name", ")", ":", "raw_model", "=", "read_igor_marginals_txt", "(", "marginals_file_name", ")", "self", ".", "PV", "=", "raw_model", "[", "0", "]", "[", "'v_choice'", "]", "self", ".", "PinsV...
56.039216
0.015131
def _get_platform_name(ncattr): """Determine name of the platform""" match = re.match(r'G-(\d+)', ncattr) if match: return SPACECRAFTS.get(int(match.groups()[0])) return None
[ "def", "_get_platform_name", "(", "ncattr", ")", ":", "match", "=", "re", ".", "match", "(", "r'G-(\\d+)'", ",", "ncattr", ")", "if", "match", ":", "return", "SPACECRAFTS", ".", "get", "(", "int", "(", "match", ".", "groups", "(", ")", "[", "0", "]",...
30.428571
0.009132
def CreateMuskingumKfacFile(in_drainage_line, river_id, length_id, slope_id, celerity, formula_type, in_connectivity_file, o...
[ "def", "CreateMuskingumKfacFile", "(", "in_drainage_line", ",", "river_id", ",", "length_id", ",", "slope_id", ",", "celerity", ",", "formula_type", ",", "in_connectivity_file", ",", "out_kfac_file", ",", "length_units", "=", "\"km\"", ",", "slope_percentage", "=", ...
37.825871
0.000128
def computeCapacity(results, threshold): """Returns largest number of objects with accuracy above threshold.""" closestBelow = None closestAbove = None for numObjects, accuracy in sorted(results): if accuracy >= threshold: if closestAbove is None or closestAbove[0] < numObjects: closestAbove =...
[ "def", "computeCapacity", "(", "results", ",", "threshold", ")", ":", "closestBelow", "=", "None", "closestAbove", "=", "None", "for", "numObjects", ",", "accuracy", "in", "sorted", "(", "results", ")", ":", "if", "accuracy", ">=", "threshold", ":", "if", ...
38.5
0.015209
def range_compress(ol): ''' #only support sorted-ints or sorted-ascii l = [1,5,6,7,8,13,14,18,30,31,32,33,34] range_compress(l) l = [1,5,6,7,8,13,14,18,30,31,32,33,34,40] range_compress(l) l = ['a','b','c','d','j','k','l','m','n','u','y','z'] range_compress(l)...
[ "def", "range_compress", "(", "ol", ")", ":", "T", "=", "(", "type", "(", "ol", "[", "0", "]", ")", "==", "type", "(", "0", ")", ")", "if", "(", "T", ")", ":", "l", "=", "ol", "else", ":", "l", "=", "array_map", "(", "ol", ",", "ord", ")"...
22.265306
0.009658
def load_raw_arrays(self, fields, start_dt, end_dt, sids): """ Parameters ---------- fields : list of str 'open', 'high', 'low', 'close', or 'volume' start_dt: Timestamp Beginning of the window range. end_dt: Timestamp End of the window ra...
[ "def", "load_raw_arrays", "(", "self", ",", "fields", ",", "start_dt", ",", "end_dt", ",", "sids", ")", ":", "start_idx", "=", "self", ".", "_find_position_of_minute", "(", "start_dt", ")", "end_idx", "=", "self", ".", "_find_position_of_minute", "(", "end_dt"...
36.741935
0.000855
def x_rolls(self, number, count=0): '''Iterator of number dice rolls. :param count: [0] Return list of ``count`` sums ''' for x in range(number): yield super(FuncRoll, self).roll(count, self._func)
[ "def", "x_rolls", "(", "self", ",", "number", ",", "count", "=", "0", ")", ":", "for", "x", "in", "range", "(", "number", ")", ":", "yield", "super", "(", "FuncRoll", ",", "self", ")", ".", "roll", "(", "count", ",", "self", ".", "_func", ")" ]
39.333333
0.008299
def build_flags(library, type_, path): """Return separated build flags from pkg-config output""" pkg_config_path = [path] if "PKG_CONFIG_PATH" in os.environ: pkg_config_path.append(os.environ['PKG_CONFIG_PATH']) if "LIB_DIR" in os.environ: pkg_config_path.append(os.environ['LIB_DIR']) ...
[ "def", "build_flags", "(", "library", ",", "type_", ",", "path", ")", ":", "pkg_config_path", "=", "[", "path", "]", "if", "\"PKG_CONFIG_PATH\"", "in", "os", ".", "environ", ":", "pkg_config_path", ".", "append", "(", "os", ".", "environ", "[", "'PKG_CONFI...
30.333333
0.002367
def __audioread_load(path, offset, duration, dtype): '''Load an audio buffer using audioread. This loads one block at a time, and then concatenates the results. ''' y = [] with audioread.audio_open(path) as input_file: sr_native = input_file.samplerate n_channels = input_file.chann...
[ "def", "__audioread_load", "(", "path", ",", "offset", ",", "duration", ",", "dtype", ")", ":", "y", "=", "[", "]", "with", "audioread", ".", "audio_open", "(", "path", ")", "as", "input_file", ":", "sr_native", "=", "input_file", ".", "samplerate", "n_c...
26.62963
0.000671
def _compute_k(self, tau): r"""Evaluate the kernel directly at the given values of `tau`. Parameters ---------- tau : :py:class:`Matrix`, (`M`, `D`) `M` inputs with dimension `D`. Returns ------- k : :py:class:`Array`, (`M`,) ...
[ "def", "_compute_k", "(", "self", ",", "tau", ")", ":", "y", "=", "self", ".", "_compute_y", "(", "tau", ")", "return", "y", "**", "(", "-", "self", ".", "params", "[", "1", "]", ")" ]
30.2
0.008565
def write(self, fname, append=True): """ Write detection to csv formatted file. Will append if append==True and file exists :type fname: str :param fname: Full path to file to open and write to. :type append: bool :param append: Set to true to append to an exist...
[ "def", "write", "(", "self", ",", "fname", ",", "append", "=", "True", ")", ":", "mode", "=", "'w'", "if", "append", "and", "os", ".", "path", ".", "isfile", "(", "fname", ")", ":", "mode", "=", "'a'", "header", "=", "'; '", ".", "join", "(", "...
44.25
0.00158
def to_dict(obj): """ Create a filtered dict from the given object. Note: This function is currently specific to the FailureLine model. """ if not isinstance(obj.test, str): # TODO: can we handle this in the DB? # Reftests used to use tuple indicies, which we can't support. ...
[ "def", "to_dict", "(", "obj", ")", ":", "if", "not", "isinstance", "(", "obj", ".", "test", ",", "str", ")", ":", "# TODO: can we handle this in the DB?", "# Reftests used to use tuple indicies, which we can't support.", "# This is fixed upstream, but we also need to handle it ...
26.185185
0.001364
def stream_replicate(): """Monitor changes in approximately real-time and replicate them""" stream = primary.stream(SomeDataBlob, "trim_horizon") next_heartbeat = pendulum.now() while True: now = pendulum.now() if now >= next_heartbeat: stream.heartbeat() next_hea...
[ "def", "stream_replicate", "(", ")", ":", "stream", "=", "primary", ".", "stream", "(", "SomeDataBlob", ",", "\"trim_horizon\"", ")", "next_heartbeat", "=", "pendulum", ".", "now", "(", ")", "while", "True", ":", "now", "=", "pendulum", ".", "now", "(", ...
32.058824
0.001783
def randpos(self): '''random initial position''' self.setpos(gen_settings.home_lat, gen_settings.home_lon) self.move(random.uniform(0, 360), random.uniform(0, gen_settings.region_width))
[ "def", "randpos", "(", "self", ")", ":", "self", ".", "setpos", "(", "gen_settings", ".", "home_lat", ",", "gen_settings", ".", "home_lon", ")", "self", ".", "move", "(", "random", ".", "uniform", "(", "0", ",", "360", ")", ",", "random", ".", "unifo...
51.75
0.014286
def make_tex_table(inputlist, outputfilename, fmt=None, **kwargs): """ Do make_tex_table and pass all arguments args: inputlist: list outputfilename: string fmt: dictionary key: integer column index starting with 0 ...
[ "def", "make_tex_table", "(", "inputlist", ",", "outputfilename", ",", "fmt", "=", "None", ",", "*", "*", "kwargs", ")", ":", "outputfilepath", "=", "FILEPATHSTR", ".", "format", "(", "root_dir", "=", "ROOT_DIR", ",", "os_sep", "=", "os", ".", "sep", ","...
38.166667
0.00213
def plot_ic_ts(ic, ax=None): """ Plots Spearman Rank Information Coefficient and IC moving average for a given factor. Parameters ---------- ic : pd.DataFrame DataFrame indexed by date, with IC for each forward return. ax : matplotlib.Axes, optional Axes upon which to plot. ...
[ "def", "plot_ic_ts", "(", "ic", ",", "ax", "=", "None", ")", ":", "ic", "=", "ic", ".", "copy", "(", ")", "num_plots", "=", "len", "(", "ic", ".", "columns", ")", "if", "ax", "is", "None", ":", "f", ",", "ax", "=", "plt", ".", "subplots", "("...
30.111111
0.000596
def _get_loader(config): """Determine which config file type and loader to use based on a filename. :param config str: filename to config file :return: a tuple of the loader type and callable to load :rtype: (str, Callable) """ if config.endswith('.yml') or config.endswith('.yaml'): if ...
[ "def", "_get_loader", "(", "config", ")", ":", "if", "config", ".", "endswith", "(", "'.yml'", ")", "or", "config", ".", "endswith", "(", "'.yaml'", ")", ":", "if", "not", "yaml", ":", "LOGGER", ".", "error", "(", "\"pyyaml must be installed to use the YAML ...
36.133333
0.001799
def _apply_sub_frames(cls, documents, subs): """Convert embedded documents to sub-frames for one or more documents""" # Dereference each reference for path, projection in subs.items(): # Get the SubFrame class we'll use to wrap the embedded document sub = None ...
[ "def", "_apply_sub_frames", "(", "cls", ",", "documents", ",", "subs", ")", ":", "# Dereference each reference", "for", "path", ",", "projection", "in", "subs", ".", "items", "(", ")", ":", "# Get the SubFrame class we'll use to wrap the embedded document", "sub", "="...
37.070175
0.002305
def network_start(name, **kwargs): ''' Start a defined virtual network. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults ...
[ "def", "network_start", "(", "name", ",", "*", "*", "kwargs", ")", ":", "conn", "=", "__get_conn", "(", "*", "*", "kwargs", ")", "try", ":", "net", "=", "conn", ".", "networkLookupByName", "(", "name", ")", "return", "not", "bool", "(", "net", ".", ...
25.391304
0.00165
def delete(self, eid): """ Removes the entity with the given eid """ result = self._http_req('connections/%u' % eid, method='DELETE') status = result['status'] if not status == 302: raise ServiceRegistryError(status, "Could not delete entity %u: %u" % (eid,status)) self.debug(0x01,result) return res...
[ "def", "delete", "(", "self", ",", "eid", ")", ":", "result", "=", "self", ".", "_http_req", "(", "'connections/%u'", "%", "eid", ",", "method", "=", "'DELETE'", ")", "status", "=", "result", "[", "'status'", "]", "if", "not", "status", "==", "302", ...
29.454545
0.041916