text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def sent_tokenize(context): """ Cut the given context into sentences. Avoid a linebreak in between paried symbols, float numbers, and some abbrs. Nothing will be discard after sent_tokeinze, simply ''.join(sents) will get the original context. Evey whitespace, tab, linebreak will be kept. >>> c...
[ "def", "sent_tokenize", "(", "context", ")", ":", "# Define the regular expression", "paired_symbols", "=", "[", "(", "\"(\"", ",", "\")\"", ")", ",", "(", "\"[\"", ",", "\"]\"", ")", ",", "(", "\"{\"", ",", "\"}\"", ")", "]", "paired_patterns", "=", "[", ...
46.088235
24.441176
def boolParam(parameters, name): """ boolean parameter value. :param parameters: the parameters tree. :param name: the name of the parameter. """ value = _simple_string_value(parameters, 'BoolParam', name) if value not in {'true', 'false'}: raise ValueError('BoolParam Value has to be either...
[ "def", "boolParam", "(", "parameters", ",", "name", ")", ":", "value", "=", "_simple_string_value", "(", "parameters", ",", "'BoolParam'", ",", "name", ")", "if", "value", "not", "in", "{", "'true'", ",", "'false'", "}", ":", "raise", "ValueError", "(", ...
47.875
13.875
def build(opts=None): """ Build a new board using the given options. :param opts: dictionary mapping str->Opt :return: the new board, Board """ board = catan.board.Board() modify(board, opts) return board
[ "def", "build", "(", "opts", "=", "None", ")", ":", "board", "=", "catan", ".", "board", ".", "Board", "(", ")", "modify", "(", "board", ",", "opts", ")", "return", "board" ]
25.333333
9.555556
def connectQ2Q(self, fromAddress, toAddress, protocolName, protocolFactory, usePrivateCertificate=None, fakeFromDomain=None, chooser=None): """ Connect a named protocol factory from a resource@domain to a resource@domain. This is analagous to someth...
[ "def", "connectQ2Q", "(", "self", ",", "fromAddress", ",", "toAddress", ",", "protocolName", ",", "protocolFactory", ",", "usePrivateCertificate", "=", "None", ",", "fakeFromDomain", "=", "None", ",", "chooser", "=", "None", ")", ":", "if", "chooser", "is", ...
45.14433
26.402062
def console_get_default_foreground(con: tcod.console.Console) -> Color: """Return this consoles default foreground color. .. deprecated:: 8.5 Use :any:`Console.default_fg` instead. """ return Color._new_from_cdata( lib.TCOD_console_get_default_foreground(_console(con)) )
[ "def", "console_get_default_foreground", "(", "con", ":", "tcod", ".", "console", ".", "Console", ")", "->", "Color", ":", "return", "Color", ".", "_new_from_cdata", "(", "lib", ".", "TCOD_console_get_default_foreground", "(", "_console", "(", "con", ")", ")", ...
33.333333
17.555556
def add_tags(self, tags, afterwards=None, remove_rest=False): """ add `tags` to all messages in this thread .. note:: This only adds the requested operation to this objects :class:`DBManager's <alot.db.DBManager>` write queue. You need to call :meth:`DBManag...
[ "def", "add_tags", "(", "self", ",", "tags", ",", "afterwards", "=", "None", ",", "remove_rest", "=", "False", ")", ":", "def", "myafterwards", "(", ")", ":", "if", "remove_rest", ":", "self", ".", "_tags", "=", "set", "(", "tags", ")", "else", ":", ...
36.724138
18.034483
def get(self, request, *args, **kwargs): """ Catch protected relations and show to user. """ self.object = self.get_object() can_delete = True protected_objects = [] collector_message = None collector = Collector(using="default") try: c...
[ "def", "get", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "object", "=", "self", ".", "get_object", "(", ")", "can_delete", "=", "True", "protected_objects", "=", "[", "]", "collector_message", "=", ...
34.766667
12.5
def make_steam64(id=0, *args, **kwargs): """ Returns steam64 from various other representations. .. code:: python make_steam64() # invalid steamid make_steam64(12345) # accountid make_steam64('12345') make_steam64(id=12345, type='Invalid', universe='Invalid', instance=0) ...
[ "def", "make_steam64", "(", "id", "=", "0", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "accountid", "=", "id", "etype", "=", "EType", ".", "Invalid", "universe", "=", "EUniverse", ".", "Invalid", "instance", "=", "None", "if", "len", "(", ...
28.012195
18.158537
def _getClassifierInputRecord(self, inputRecord): """ inputRecord - dict containing the input to the sensor Return a 'ClassifierInput' object, which contains the mapped bucket index for input Record """ absoluteValue = None bucketIdx = None if self._predictedFieldName is not None and s...
[ "def", "_getClassifierInputRecord", "(", "self", ",", "inputRecord", ")", ":", "absoluteValue", "=", "None", "bucketIdx", "=", "None", "if", "self", ".", "_predictedFieldName", "is", "not", "None", "and", "self", ".", "_classifierInputEncoder", "is", "not", "Non...
36.75
21.25
def zremrangebyrank(self, name, min, max): """ Remove all elements in the sorted set ``name`` with ranks between ``min`` and ``max``. Values are 0-based, ordered from smallest score to largest. Values can be negative indicating the highest scores. Returns the number of elements r...
[ "def", "zremrangebyrank", "(", "self", ",", "name", ",", "min", ",", "max", ")", ":", "return", "self", ".", "execute_command", "(", "'ZREMRANGEBYRANK'", ",", "name", ",", "min", ",", "max", ")" ]
50.25
17.5
def make_regular_points_with_no_res(bounds, nb_points=10000): """ Return a regular grid of points within `bounds` with the specified number of points (or a close approximate value). Parameters ---------- bounds : 4-floats tuple The bbox of the grid, as xmin, ymin, xmax, ymax. nb_poi...
[ "def", "make_regular_points_with_no_res", "(", "bounds", ",", "nb_points", "=", "10000", ")", ":", "minlon", ",", "minlat", ",", "maxlon", ",", "maxlat", "=", "bounds", "minlon", ",", "minlat", ",", "maxlon", ",", "maxlat", "=", "bounds", "offset_lon", "=", ...
27.75
17.305556
def post_operations(self, mode=None): """ Return post-operations only for the mode asked """ version_mode = self._get_version_mode(mode=mode) return version_mode.post_operations
[ "def", "post_operations", "(", "self", ",", "mode", "=", "None", ")", ":", "version_mode", "=", "self", ".", "_get_version_mode", "(", "mode", "=", "mode", ")", "return", "version_mode", ".", "post_operations" ]
49.5
5.5
def get_range_selector(steps=['1m','1y'],bgcolor='rgba(150, 200, 250, 0.4)',x=0,y=0.9, visible=True,**kwargs): """ Returns a range selector Reference: https://plot.ly/python/reference/#layout-xaxis-rangeselector Parameters: ----------- steps : string or list(string) Steps for the range Examples: ...
[ "def", "get_range_selector", "(", "steps", "=", "[", "'1m'", ",", "'1y'", "]", ",", "bgcolor", "=", "'rgba(150, 200, 250, 0.4)'", ",", "x", "=", "0", ",", "y", "=", "0.9", ",", "visible", "=", "True", ",", "*", "*", "kwargs", ")", ":", "import", "str...
22.482759
21.471264
def AddNewSignature(self, pattern, offset=None): """Adds a signature. Args: pattern (bytes): pattern of the signature. offset (int): offset of the signature. None is used to indicate the signature has no offset. A positive offset is relative from the start of the data a negative...
[ "def", "AddNewSignature", "(", "self", ",", "pattern", ",", "offset", "=", "None", ")", ":", "self", ".", "signatures", ".", "append", "(", "Signature", "(", "pattern", ",", "offset", "=", "offset", ")", ")" ]
39.545455
20.181818
def allskyfinder(self, figsize=(14, 7), **kwargs): ''' Plot an all-sky finder chart. This *does* create a new figure. ''' plt.figure(figsize=figsize) scatter = self.plot(**kwargs) plt.xlabel(r'Right Ascension ($^\circ$)'); plt.ylabel(r'Declination ($^\circ$)') #p...
[ "def", "allskyfinder", "(", "self", ",", "figsize", "=", "(", "14", ",", "7", ")", ",", "*", "*", "kwargs", ")", ":", "plt", ".", "figure", "(", "figsize", "=", "figsize", ")", "scatter", "=", "self", ".", "plot", "(", "*", "*", "kwargs", ")", ...
35.916667
21.916667
def set_bit(bitmask, bit, is_on): """Set the value of a bit in a bitmask on or off. Uses the low bit is 1 and the high bit is 8. """ bitshift = bit - 1 if is_on: return bitmask | (1 << bitshift) return bitmask & (0xff & ~(1 << bitshift))
[ "def", "set_bit", "(", "bitmask", ",", "bit", ",", "is_on", ")", ":", "bitshift", "=", "bit", "-", "1", "if", "is_on", ":", "return", "bitmask", "|", "(", "1", "<<", "bitshift", ")", "return", "bitmask", "&", "(", "0xff", "&", "~", "(", "1", "<<"...
29.111111
11.777778
def add_tags(self, item, *tags): """ Add one or more tags to a retrieved item, then update it on the server Accepts a dict, and one or more tags to add to it Returns the updated item from the server """ # Make sure there's a tags field, or add one try: ...
[ "def", "add_tags", "(", "self", ",", "item", ",", "*", "tags", ")", ":", "# Make sure there's a tags field, or add one", "try", ":", "assert", "item", "[", "\"data\"", "]", "[", "\"tags\"", "]", "except", "AssertionError", ":", "item", "[", "\"data\"", "]", ...
36.058824
8.411765
def manifest(): """Guarantee the existence of a basic MANIFEST.in. manifest doc: http://docs.python.org/distutils/sourcedist.html#manifest `options.paved.dist.manifest.include`: set of files (or globs) to include with the `include` directive. `options.paved.dist.manifest.recursive_include`: set of fi...
[ "def", "manifest", "(", ")", ":", "prune", "=", "options", ".", "paved", ".", "dist", ".", "manifest", ".", "prune", "graft", "=", "set", "(", ")", "if", "options", ".", "paved", ".", "dist", ".", "manifest", ".", "include_sphinx_docroot", ":", "docroo...
40.861111
28.555556
def remove_first(ol,value,**kwargs): ''' from elist.jprint import pobj from elist.elist import * ol = [1,'a',3,'a',5,'a'] id(ol) new = remove_first(ol,'a') ol new id(ol) id(new) #### ol = [1,'a',3,'a',5,'a'] id(ol) ...
[ "def", "remove_first", "(", "ol", ",", "value", ",", "*", "*", "kwargs", ")", ":", "if", "(", "'mode'", "in", "kwargs", ")", ":", "mode", "=", "kwargs", "[", "\"mode\"", "]", "else", ":", "mode", "=", "\"new\"", "if", "(", "mode", "==", "\"new\"", ...
21.6875
19.75
def update(self, request, id): """Update an object.""" try: object = self.model.objects.get(id=id) except self.model.DoesNotExist: return self._render( request = request, template = '404', context = { 'er...
[ "def", "update", "(", "self", ",", "request", ",", "id", ")", ":", "try", ":", "object", "=", "self", ".", "model", ".", "objects", ".", "get", "(", "id", "=", "id", ")", "except", "self", ".", "model", ".", "DoesNotExist", ":", "return", "self", ...
27.266667
16.533333
def _load(self, url, verbose): """ Execute a request against the Salesking API to fetch the items :param url: url to fetch :return response :raises SaleskingException with the corresponding http errors """ msg = u"_load url: %s" % url self._last_query_str ...
[ "def", "_load", "(", "self", ",", "url", ",", "verbose", ")", ":", "msg", "=", "u\"_load url: %s\"", "%", "url", "self", ".", "_last_query_str", "=", "url", "log", ".", "debug", "(", "msg", ")", "if", "verbose", ":", "print", "msg", "response", "=", ...
31.857143
13
def get_lib_name(self): """ Parse Cargo.toml to get the name of the shared library. """ # We import in here to make sure the the setup_requires are already installed import toml cfg = toml.load(self.path) name = cfg.get("lib", {}).get("name") if name is None: ...
[ "def", "get_lib_name", "(", "self", ")", ":", "# We import in here to make sure the the setup_requires are already installed", "import", "toml", "cfg", "=", "toml", ".", "load", "(", "self", ".", "path", ")", "name", "=", "cfg", ".", "get", "(", "\"lib\"", ",", ...
39.470588
18.352941
def run_notebook(self, skip_exceptions=False, progress_callback=None): """ Run all the notebook cells in order and update the outputs in-place. If ``skip_exceptions`` is set, then if exceptions occur in a cell, the subsequent cells are run (by default, the notebook execution stops). ...
[ "def", "run_notebook", "(", "self", ",", "skip_exceptions", "=", "False", ",", "progress_callback", "=", "None", ")", ":", "for", "i", ",", "cell", "in", "enumerate", "(", "self", ".", "iter_code_cells", "(", ")", ")", ":", "try", ":", "self", ".", "ru...
39.733333
17.333333
def __init(self): """ inializes the properties """ params = { "f" : "json", } json_dict = self._get(self._url, params, securityHandler=self._securityHandler, proxy_url=self._proxy_url, ...
[ "def", "__init", "(", "self", ")", ":", "params", "=", "{", "\"f\"", ":", "\"json\"", ",", "}", "json_dict", "=", "self", ".", "_get", "(", "self", ".", "_url", ",", "params", ",", "securityHandler", "=", "self", ".", "_securityHandler", ",", "proxy_ur...
47.921053
16.236842
def is_manager(self, path): '''Is the node pointed to by @ref path a manager?''' node = self.get_node(path) if not node: return False return node.is_manager
[ "def", "is_manager", "(", "self", ",", "path", ")", ":", "node", "=", "self", ".", "get_node", "(", "path", ")", "if", "not", "node", ":", "return", "False", "return", "node", ".", "is_manager" ]
32.5
14.166667
def model_typedefs(vk, model): """Fill the model with typedefs model['typedefs'] = {'name': 'type', ...} """ model['typedefs'] = {} # bitmasks and basetypes bitmasks = [x for x in vk['registry']['types']['type'] if x.get('@category') == 'bitmask'] basetypes = [x for x in v...
[ "def", "model_typedefs", "(", "vk", ",", "model", ")", ":", "model", "[", "'typedefs'", "]", "=", "{", "}", "# bitmasks and basetypes", "bitmasks", "=", "[", "x", "for", "x", "in", "vk", "[", "'registry'", "]", "[", "'types'", "]", "[", "'type'", "]", ...
32.022727
18.977273
def update_firewall_rule(firewall_rule, protocol=None, action=None, name=None, description=None, ip_version=None, source_ip_address=None, destina...
[ "def", "update_firewall_rule", "(", "firewall_rule", ",", "protocol", "=", "None", ",", "action", "=", "None", ",", "name", "=", "None", ",", "description", "=", "None", ",", "ip_version", "=", "None", ",", "source_ip_address", "=", "None", ",", "destination...
51.604651
26.069767
def from_dict(cls, d): """ Reconstructs the VoronoiContainer object from a dict representation of the VoronoiContainer created using the as_dict method. :param d: dict representation of the VoronoiContainer object :return: VoronoiContainer object """ structure = S...
[ "def", "from_dict", "(", "cls", ",", "d", ")", ":", "structure", "=", "Structure", ".", "from_dict", "(", "d", "[", "'structure'", "]", ")", "voronoi_list2", "=", "from_bson_voronoi_list2", "(", "d", "[", "'bson_nb_voro_list2'", "]", ",", "structure", ")", ...
60.736842
27.052632
def freshenFocus(self): """ Did something which requires a new look. Move scrollbar up. This often needs to be delayed a bit however, to let other events in the queue through first. """ self.top.update_idletasks() self.top.after(10, self.setViewAtTop)
[ "def", "freshenFocus", "(", "self", ")", ":", "self", ".", "top", ".", "update_idletasks", "(", ")", "self", ".", "top", ".", "after", "(", "10", ",", "self", ".", "setViewAtTop", ")" ]
49.166667
9.5
def try_open (self, null_if_noexist=False, **kwargs): """Call :meth:`Path.open` on this path (passing *kwargs*) and return the result. If the file doesn't exist, the behavior depends on *null_if_noexist*. If it is false (the default), ``None`` is returned. Otherwise, :data:`os.devnull` i...
[ "def", "try_open", "(", "self", ",", "null_if_noexist", "=", "False", ",", "*", "*", "kwargs", ")", ":", "try", ":", "return", "self", ".", "open", "(", "*", "*", "kwargs", ")", "except", "IOError", "as", "e", ":", "if", "e", ".", "errno", "==", ...
39.0625
16
def prepare_queues(queues, lock): """Replaces queue._put() method in order to notify the waiting Condition.""" for queue in queues: queue._pebble_lock = lock with queue.mutex: queue._pebble_old_method = queue._put queue._put = MethodType(new_method, queue)
[ "def", "prepare_queues", "(", "queues", ",", "lock", ")", ":", "for", "queue", "in", "queues", ":", "queue", ".", "_pebble_lock", "=", "lock", "with", "queue", ".", "mutex", ":", "queue", ".", "_pebble_old_method", "=", "queue", ".", "_put", "queue", "."...
42.571429
9.714286
def read(self, size=-1): "Reads up to size bytes, but always completes the last line." buf = self.fin.read(size) if not buf: return '' lines = buf.splitlines() # Read the rest of the last line if necessary if not buf.endswith('\n'): last = lines.po...
[ "def", "read", "(", "self", ",", "size", "=", "-", "1", ")", ":", "buf", "=", "self", ".", "fin", ".", "read", "(", "size", ")", "if", "not", "buf", ":", "return", "''", "lines", "=", "buf", ".", "splitlines", "(", ")", "# Read the rest of the last...
38.714286
12.714286
def getconfig(): ''' Return the selinux mode from the config file CLI Example: .. code-block:: bash salt '*' selinux.getconfig ''' try: config = '/etc/selinux/config' with salt.utils.files.fopen(config, 'r') as _fp: for line in _fp: line = s...
[ "def", "getconfig", "(", ")", ":", "try", ":", "config", "=", "'/etc/selinux/config'", "with", "salt", ".", "utils", ".", "files", ".", "fopen", "(", "config", ",", "'r'", ")", "as", "_fp", ":", "for", "line", "in", "_fp", ":", "line", "=", "salt", ...
27.25
22.05
def enrich(self, expected=None, provided=None, path=None, validator=None): """ Enrich this error with additional information. This works with both Invalid and MultipleInvalid (thanks to `Invalid` being iterable): in the latter case, the defaults are applied to all collected errors. The...
[ "def", "enrich", "(", "self", ",", "expected", "=", "None", ",", "provided", "=", "None", ",", "path", "=", "None", ",", "validator", "=", "None", ")", ":", "for", "e", "in", "self", ":", "# defaults on fields", "if", "e", ".", "expected", "is", "Non...
36.96
22.26
def parse_response(fields, records): """Parse an API response into usable objects. Args: fields (list[str]): List of strings indicating the fields that are represented in the records, in the order presented in the records.:: [ ...
[ "def", "parse_response", "(", "fields", ",", "records", ")", ":", "data", "=", "[", "i", "[", "'values'", "]", "[", "'data'", "]", "for", "i", "in", "records", "]", "return", "[", "{", "fields", "[", "idx", "]", ":", "row", "for", "idx", ",", "ro...
32.235294
15.019608
def cornice_enable_openapi_explorer( config, api_explorer_path='/api-explorer', permission=NO_PERMISSION_REQUIRED, route_factory=None, **kwargs): """ :param config: Pyramid configurator object :param api_explorer_path: where to expose Swagger UI interf...
[ "def", "cornice_enable_openapi_explorer", "(", "config", ",", "api_explorer_path", "=", "'/api-explorer'", ",", "permission", "=", "NO_PERMISSION_REQUIRED", ",", "route_factory", "=", "None", ",", "*", "*", "kwargs", ")", ":", "config", ".", "add_route", "(", "'co...
36.043478
14.130435
def run_bump(args): """ Handle the bump subcommand :param args: Parsed command line arguments :return: None, output is written to console """ commit_id = args.commit_id image = args.image branch = args.branch try: print(version_bump(image, branch, commit_id)) except Dock...
[ "def", "run_bump", "(", "args", ")", ":", "commit_id", "=", "args", ".", "commit_id", "image", "=", "args", ".", "image", "branch", "=", "args", ".", "branch", "try", ":", "print", "(", "version_bump", "(", "image", ",", "branch", ",", "commit_id", ")"...
24.6
14.466667
def restore(self): """ This method constructs the restoring beam and then adds the convolution to the residual. """ clean_beam, beam_params = beam_fit(self.psf_data, self.cdelt1, self.cdelt2) if np.all(np.array(self.psf_data_shape)==2*np.array(self.dirty_data_shape)): ...
[ "def", "restore", "(", "self", ")", ":", "clean_beam", ",", "beam_params", "=", "beam_fit", "(", "self", ".", "psf_data", ",", "self", ".", "cdelt1", ",", "self", ".", "cdelt2", ")", "if", "np", ".", "all", "(", "np", ".", "array", "(", "self", "."...
53.125
34.875
def from_yaml(value, native_datetimes=True): """ Deserializes the given value from YAML. :param value: the value to deserialize :type value: str :param native_datetimes: whether or not strings that look like dates/times should be automatically cast to the native objects, or left as ...
[ "def", "from_yaml", "(", "value", ",", "native_datetimes", "=", "True", ")", ":", "if", "not", "yaml", ":", "raise", "NotImplementedError", "(", "'No supported YAML library available'", ")", "if", "native_datetimes", ":", "loader", "=", "NativeDatesYamlLoader", "els...
29.363636
17.272727
def _chooseBestSegmentPairPerColumn(self, matchingCellsInBurstingColumns, matchingBasalSegments, matchingApicalSegments, basalPotentialOverlaps, ...
[ "def", "_chooseBestSegmentPairPerColumn", "(", "self", ",", "matchingCellsInBurstingColumns", ",", "matchingBasalSegments", ",", "matchingApicalSegments", ",", "basalPotentialOverlaps", ",", "apicalPotentialOverlaps", ")", ":", "basalCandidateSegments", "=", "self", ".", "bas...
44.492063
21.507937
def containsUid(self, uid): ''' containsUid - Check if #uid is the uid (unique internal identifier) of any of the elements within this list, as themselves or as a child, any number of levels down. @param uid <uuid.UUID> - uuid of interest @return <...
[ "def", "containsUid", "(", "self", ",", "uid", ")", ":", "for", "node", "in", "self", ":", "if", "node", ".", "containsUid", "(", "uid", ")", ":", "return", "True", "return", "False" ]
31.6
27.733333
def override(self, config_params): """ Overrides parameters with new values from specified ConfigParams and returns a new ConfigParams object. :param config_params: ConfigMap with parameters to override the current values. :return: a new ConfigParams object. """ map = S...
[ "def", "override", "(", "self", ",", "config_params", ")", ":", "map", "=", "StringValueMap", ".", "from_maps", "(", "self", ",", "config_params", ")", "return", "ConfigParams", "(", "map", ")" ]
38.8
23.4
def loud(self, lang='englist'): """Speak loudly! FIVE! Use upper case!""" lang_method = getattr(self, lang, None) if lang_method: return lang_method().upper() else: return self.english().upper()
[ "def", "loud", "(", "self", ",", "lang", "=", "'englist'", ")", ":", "lang_method", "=", "getattr", "(", "self", ",", "lang", ",", "None", ")", "if", "lang_method", ":", "return", "lang_method", "(", ")", ".", "upper", "(", ")", "else", ":", "return"...
34.857143
8.714286
def receive_device_value(self, raw_value: int): """ Set a new value, called from within the joystick implementation class when parsing the event queue. :param raw_value: the raw value from the joystick hardware :internal: """ new_value = self._input_to_raw_value(raw_val...
[ "def", "receive_device_value", "(", "self", ",", "raw_value", ":", "int", ")", ":", "new_value", "=", "self", ".", "_input_to_raw_value", "(", "raw_value", ")", "if", "self", ".", "button", "is", "not", "None", ":", "if", "new_value", ">", "(", "self", "...
42.052632
20.368421
def redis_version(self): """Return the redis version as a tuple""" if not hasattr(self, '_redis_version'): self._redis_version = tuple( map(int, self.connection.info().get('redis_version').split('.')[:3]) ) return self._redis_version
[ "def", "redis_version", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'_redis_version'", ")", ":", "self", ".", "_redis_version", "=", "tuple", "(", "map", "(", "int", ",", "self", ".", "connection", ".", "info", "(", ")", ".", "g...
41.571429
14.285714
async def list_instances(self, project, page_size=100, instance_filter=None): """Fetch all instances in a GCE project. You can find the endpoint documentation `here <https://cloud. google.com/compute/docs/ref...
[ "async", "def", "list_instances", "(", "self", ",", "project", ",", "page_size", "=", "100", ",", "instance_filter", "=", "None", ")", ":", "url", "=", "(", "f'{self.BASE_URL}{self.api_version}/projects/{project}'", "'/aggregated/instances'", ")", "params", "=", "{"...
41.5
18
def train_epoch(self, epoch_info: EpochInfo, interactive=True): """ Train model on an epoch of a fixed number of batch updates """ epoch_info.on_epoch_begin() if interactive: iterator = tqdm.trange(epoch_info.batches_per_epoch, file=sys.stdout, desc="Training", unit="batch") ...
[ "def", "train_epoch", "(", "self", ",", "epoch_info", ":", "EpochInfo", ",", "interactive", "=", "True", ")", ":", "epoch_info", ".", "on_epoch_begin", "(", ")", "if", "interactive", ":", "iterator", "=", "tqdm", ".", "trange", "(", "epoch_info", ".", "bat...
37.333333
20.555556
def rotation(angle): """Rotation about the Z axis (in the XY plane)""" return N.array([[N.cos(angle),-N.sin(angle),0], [N.sin(angle), N.cos(angle),0], [0 , 0 ,1]])
[ "def", "rotation", "(", "angle", ")", ":", "return", "N", ".", "array", "(", "[", "[", "N", ".", "cos", "(", "angle", ")", ",", "-", "N", ".", "sin", "(", "angle", ")", ",", "0", "]", ",", "[", "N", ".", "sin", "(", "angle", ")", ",", "N"...
40.6
6.4
def matrix_element(ji, fi, mi, jj, fj, mj, II, reduced_matrix_element, q=None, numeric=True, convention=1): r"""Calculate a matrix element of the electric dipole (in the helicity basis). We calculate the matrix element for the cyclical transition of the D2 line in ...
[ "def", "matrix_element", "(", "ji", ",", "fi", ",", "mi", ",", "jj", ",", "fj", ",", "mj", ",", "II", ",", "reduced_matrix_element", ",", "q", "=", "None", ",", "numeric", "=", "True", ",", "convention", "=", "1", ")", ":", "if", "q", "is", "None...
29.333333
20.3125
def file_and_line(self): """Return the filename and line number where this rule originally appears, in the form "foo.scss:3". Used for error messages. """ ret = "%s:%d" % (self.source_file.path, self.lineno) if self.from_source_file: ret += " (%s:%d)" % (self.from_so...
[ "def", "file_and_line", "(", "self", ")", ":", "ret", "=", "\"%s:%d\"", "%", "(", "self", ".", "source_file", ".", "path", ",", "self", ".", "lineno", ")", "if", "self", ".", "from_source_file", ":", "ret", "+=", "\" (%s:%d)\"", "%", "(", "self", ".", ...
45.625
16.375
def get_consensus_tree(self, cutoff=0.0, best_tree=None): """ Returns an extended majority rule consensus tree as a Toytree object. Node labels include 'support' values showing the occurrence of clades in the consensus tree across trees in the input treelist. Clades with suppor...
[ "def", "get_consensus_tree", "(", "self", ",", "cutoff", "=", "0.0", ",", "best_tree", "=", "None", ")", ":", "if", "best_tree", ":", "raise", "NotImplementedError", "(", "\"best_tree option not yet supported.\"", ")", "cons", "=", "ConsensusTree", "(", "self", ...
49.08
23.4
def is_extent_valid(self, start_time, duration, flag=None): """Check if the duration contains any non-valid frames Parameters ---------- start_time: int Beginning of the duration to check in gps seconds duration: int Number of seconds after the start_time...
[ "def", "is_extent_valid", "(", "self", ",", "start_time", ",", "duration", ",", "flag", "=", "None", ")", ":", "sr", "=", "self", ".", "raw_buffer", ".", "sample_rate", "s", "=", "int", "(", "(", "start_time", "-", "self", ".", "raw_buffer", ".", "star...
34.956522
17.434783
def _groupby_and_aggregate(self, how, grouper=None, *args, **kwargs): """ Re-evaluate the obj with a groupby aggregation. """ if grouper is None: self._set_binner() grouper = self.grouper obj = self._selected_obj grouped = groupby(obj, by=None, ...
[ "def", "_groupby_and_aggregate", "(", "self", ",", "how", ",", "grouper", "=", "None", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "grouper", "is", "None", ":", "self", ".", "_set_binner", "(", ")", "grouper", "=", "self", ".", "groupe...
32.333333
20.703704
def _create_genetic_expander(problem, mutation_chance): ''' Creates an expander that expands the bests nodes of the population, crossing over them. ''' def _expander(fringe, iteration, viewer): fitness = [x.value for x in fringe] sampler = InverseTransformSampler(fitness, fringe) ...
[ "def", "_create_genetic_expander", "(", "problem", ",", "mutation_chance", ")", ":", "def", "_expander", "(", "fringe", ",", "iteration", ",", "viewer", ")", ":", "fitness", "=", "[", "x", ".", "value", "for", "x", "in", "fringe", "]", "sampler", "=", "I...
33.25641
19.25641
def parse_metadata(self, metadata_xml): """ Parse repomd.xml file :type metadata_xml: str :param metadata_xml: raw xml representation of repomd.xml """ try: metadata = dict() mdata = xmltodict.parse(metadata_xml)['metadata'] metadata['...
[ "def", "parse_metadata", "(", "self", ",", "metadata_xml", ")", ":", "try", ":", "metadata", "=", "dict", "(", ")", "mdata", "=", "xmltodict", ".", "parse", "(", "metadata_xml", ")", "[", "'metadata'", "]", "metadata", "[", "'revision'", "]", "=", "mdata...
41
20.055556
def convert_blocks_to_string(self): """ New method, only in MegaDatasetBlock class. :return: flattened data blocks as string """ taxa_ids = [[]] * int(self.data.number_taxa) sequences = [''] * int(self.data.number_taxa) for block in self._blocks: for...
[ "def", "convert_blocks_to_string", "(", "self", ")", ":", "taxa_ids", "=", "[", "[", "]", "]", "*", "int", "(", "self", ".", "data", ".", "number_taxa", ")", "sequences", "=", "[", "''", "]", "*", "int", "(", "self", ".", "data", ".", "number_taxa", ...
44
20.153846
def update_collections(self): """Try to determine which collections this record should belong to.""" for value in record_get_field_values(self.record, '980', code='a'): if 'NOTE' in value.upper(): self.collections.add('NOTE') if 'THESIS' in value.upper(): ...
[ "def", "update_collections", "(", "self", ")", ":", "for", "value", "in", "record_get_field_values", "(", "self", ".", "record", ",", "'980'", ",", "code", "=", "'a'", ")", ":", "if", "'NOTE'", "in", "value", ".", "upper", "(", ")", ":", "self", ".", ...
39.97619
14.690476
def __update_stack_with_isotopes_infos(self, stack: dict): """retrieve the isotopes, isotopes file names, mass and atomic_ratio from each element in stack""" for _key in stack: _elements = stack[_key]['elements'] for _element in _elements: _dict = _utilities.get_i...
[ "def", "__update_stack_with_isotopes_infos", "(", "self", ",", "stack", ":", "dict", ")", ":", "for", "_key", "in", "stack", ":", "_elements", "=", "stack", "[", "_key", "]", "[", "'elements'", "]", "for", "_element", "in", "_elements", ":", "_dict", "=", ...
48.7
17.3
def generate_traffic_chain(self, pages, loops=1): """ Similar to generate_referral_chain(), but for multiple loops. """ for loop in range(loops): self.generate_referral_chain(pages) time.sleep(0.05)
[ "def", "generate_traffic_chain", "(", "self", ",", "pages", ",", "loops", "=", "1", ")", ":", "for", "loop", "in", "range", "(", "loops", ")", ":", "self", ".", "generate_referral_chain", "(", "pages", ")", "time", ".", "sleep", "(", "0.05", ")" ]
46.8
7
def setup(cmd_args, suppress_output=False): """ Call a setup.py command or list of commands >>> result = setup('--name', suppress_output=True) >>> result.exitval 0 >>> result = setup('notreal') >>> result.exitval 1 """ if not funcy.is_list(cmd_args) and not funcy.is_tuple(cmd_args):...
[ "def", "setup", "(", "cmd_args", ",", "suppress_output", "=", "False", ")", ":", "if", "not", "funcy", ".", "is_list", "(", "cmd_args", ")", "and", "not", "funcy", ".", "is_tuple", "(", "cmd_args", ")", ":", "cmd_args", "=", "shlex", ".", "split", "(",...
33.928571
17.357143
def M(self, t, tips=None, gaps=None): """See docs for method in `Model` abstract base class.""" assert isinstance(t, float) and t > 0, "Invalid t: {0}".format(t) with scipy.errstate(under='ignore'): # don't worry if some values 0 if ('expD', t) not in self._cached: se...
[ "def", "M", "(", "self", ",", "t", ",", "tips", "=", "None", ",", "gaps", "=", "None", ")", ":", "assert", "isinstance", "(", "t", ",", "float", ")", "and", "t", ">", "0", ",", "\"Invalid t: {0}\"", ".", "format", "(", "t", ")", "with", "scipy", ...
51.727273
19.318182
def configure_logging(info=False, debug=False): """Configure logging The function configures log messages. By default, log messages are sent to stderr. Set the parameter `debug` to activate the debug mode. :param debug: set the debug mode """ if info: logging.basicConfig(level=loggin...
[ "def", "configure_logging", "(", "info", "=", "False", ",", "debug", "=", "False", ")", ":", "if", "info", ":", "logging", ".", "basicConfig", "(", "level", "=", "logging", ".", "INFO", ",", "format", "=", "LOG_FORMAT", ")", "logging", ".", "getLogger", ...
44.136364
16.636364
def get_config_status(): ''' Get the status of the current DSC Configuration Returns: dict: A dictionary representing the status of the current DSC Configuration on the machine CLI Example: .. code-block:: bash salt '*' dsc.get_config_status ''' cmd = 'Get-Dsc...
[ "def", "get_config_status", "(", ")", ":", "cmd", "=", "'Get-DscConfigurationStatus | '", "'Select-Object -Property HostName, Status, MetaData, '", "'@{Name=\"StartDate\";Expression={Get-Date ($_.StartDate) -Format g}}, '", "'Type, Mode, RebootRequested, NumberofResources'", "try", ":", "r...
32.083333
23
def flipcheck(content): """Checks a string for anger and soothes said anger Args: content (str): The message to be flipchecked Returns: putitback (str): The righted table or text """ # Prevent tampering with flip punct = """!"#$%&'*+,-./:;<=>?@[\]^_`{|}~ ━─""" tamperdict =...
[ "def", "flipcheck", "(", "content", ")", ":", "# Prevent tampering with flip", "punct", "=", "\"\"\"!\"#$%&'*+,-./:;<=>?@[\\]^_`{|}~ ━─\"\"\"", "tamperdict", "=", "str", ".", "maketrans", "(", "''", ",", "''", ",", "punct", ")", "tamperproof", "=", "content", ".", ...
27.254237
18.898305
def set_pos(self, pos): """ set the position of this column in the Table """ self.pos = pos if pos is not None and self.typ is not None: self.typ._v_pos = pos return self
[ "def", "set_pos", "(", "self", ",", "pos", ")", ":", "self", ".", "pos", "=", "pos", "if", "pos", "is", "not", "None", "and", "self", ".", "typ", "is", "not", "None", ":", "self", ".", "typ", ".", "_v_pos", "=", "pos", "return", "self" ]
34.833333
12.5
def contains(bank, key): ''' Checks if the specified bank contains the specified key. ''' if key is None: return True # any key could be a branch and a leaf at the same time in Consul else: try: c_key = '{0}/{1}'.format(bank, key) _, value = api.kv.get(c_key)...
[ "def", "contains", "(", "bank", ",", "key", ")", ":", "if", "key", "is", "None", ":", "return", "True", "# any key could be a branch and a leaf at the same time in Consul", "else", ":", "try", ":", "c_key", "=", "'{0}/{1}'", ".", "format", "(", "bank", ",", "k...
31.647059
20.470588
def get_channelstate_closed( chain_state: ChainState, payment_network_id: PaymentNetworkID, token_address: TokenAddress, ) -> List[NettingChannelState]: """Return the state of closed channels in a token network.""" return get_channelstate_filter( chain_state, payment_netw...
[ "def", "get_channelstate_closed", "(", "chain_state", ":", "ChainState", ",", "payment_network_id", ":", "PaymentNetworkID", ",", "token_address", ":", "TokenAddress", ",", ")", "->", "List", "[", "NettingChannelState", "]", ":", "return", "get_channelstate_filter", "...
36.166667
14.75
def __flush_data(self, data): """Flush `data` to a chunk. """ if not data: return defer.succeed(None) assert (len(data) <= self.chunk_size) chunk = {"files_id": self._file["_id"], "n": self._chunk_number, "data": Binary(data)} ...
[ "def", "__flush_data", "(", "self", ",", "data", ")", ":", "if", "not", "data", ":", "return", "defer", ".", "succeed", "(", "None", ")", "assert", "(", "len", "(", "data", ")", "<=", "self", ".", "chunk_size", ")", "chunk", "=", "{", "\"files_id\"",...
30.647059
14.176471
def create_calendar_event(self, calendar_event, **kwargs): """ Create a new Calendar Event. :calls: `POST /api/v1/calendar_events \ <https://canvas.instructure.com/doc/api/calendar_events.html#method.calendar_events_api.create>`_ :param calendar_event: The attributes of the cal...
[ "def", "create_calendar_event", "(", "self", ",", "calendar_event", ",", "*", "*", "kwargs", ")", ":", "from", "canvasapi", ".", "calendar_event", "import", "CalendarEvent", "if", "isinstance", "(", "calendar_event", ",", "dict", ")", "and", "'context_code'", "i...
35.814815
22.037037
def get_udc_and_token(runner) -> Tuple[Optional[ContractProxy], Optional[ContractProxy]]: """ Return contract proxies for the UserDepositContract and associated token """ from scenario_player.runner import ScenarioRunner assert isinstance(runner, ScenarioRunner) udc_config = runner.scenario.services.ge...
[ "def", "get_udc_and_token", "(", "runner", ")", "->", "Tuple", "[", "Optional", "[", "ContractProxy", "]", ",", "Optional", "[", "ContractProxy", "]", "]", ":", "from", "scenario_player", ".", "runner", "import", "ScenarioRunner", "assert", "isinstance", "(", ...
46.115385
24.884615
def to_cloudformation(self, **kwargs): """Returns the Lambda EventSourceMapping to which this pull event corresponds. Adds the appropriate managed policy to the function's execution role, if such a role is provided. :param dict kwargs: a dict containing the execution role generated for the func...
[ "def", "to_cloudformation", "(", "self", ",", "*", "*", "kwargs", ")", ":", "function", "=", "kwargs", ".", "get", "(", "'function'", ")", "if", "not", "function", ":", "raise", "TypeError", "(", "\"Missing required keyword argument: function\"", ")", "resources...
44.318182
26.772727
def init_runner(self, parser, tracers, projinfo): ''' initial some instances for preparing to run test case @note: should not override @param parser: instance of TestCaseParser @param tracers: dict type for the instance of Tracer. Such as {"":tracer_obj} or {"192.168.0.1:5555":trace...
[ "def", "init_runner", "(", "self", ",", "parser", ",", "tracers", ",", "projinfo", ")", ":", "self", ".", "parser", "=", "parser", "self", ".", "tracers", "=", "tracers", "self", ".", "proj_info", "=", "projinfo" ]
47.529412
23.411765
def add_number_widget(self, ref, x=1, value=1): """ Add Number Widget """ if ref not in self.widgets: widget = widgets.NumberWidget(screen=self, ref=ref, x=x, value=value) self.widgets[ref] = widget return self.widgets[ref]
[ "def", "add_number_widget", "(", "self", ",", "ref", ",", "x", "=", "1", ",", "value", "=", "1", ")", ":", "if", "ref", "not", "in", "self", ".", "widgets", ":", "widget", "=", "widgets", ".", "NumberWidget", "(", "screen", "=", "self", ",", "ref",...
38.571429
14.142857
def loadWeights(self, filename, mode='pickle'): """ Loads weights from a file in pickle, plain, or tlearn mode. """ # modes: pickle, plain/conx, tlearn if mode == 'pickle': import pickle fp = open(filename, "r") mylist = pickle.load(fp) ...
[ "def", "loadWeights", "(", "self", ",", "filename", ",", "mode", "=", "'pickle'", ")", ":", "# modes: pickle, plain/conx, tlearn", "if", "mode", "==", "'pickle'", ":", "import", "pickle", "fp", "=", "open", "(", "filename", ",", "\"r\"", ")", "mylist", "=", ...
46.794872
14.350427
def read(self): """Read stdout and stdout pipes if process is no longer running.""" if self._process and self._process.poll() is not None: ip = get_ipython() err = ip.user_ns['error'].read().decode() out = ip.user_ns['output'].read().decode() else: ...
[ "def", "read", "(", "self", ")", ":", "if", "self", ".", "_process", "and", "self", ".", "_process", ".", "poll", "(", ")", "is", "not", "None", ":", "ip", "=", "get_ipython", "(", ")", "err", "=", "ip", ".", "user_ns", "[", "'error'", "]", ".", ...
36.5
16.8
def on_queue_declareok(self, method_frame): """ Invoked by pika when the Queue.Declare RPC call made in setup_queue has completed. In this method we will bind the queue and exchange together with the routing key by issuing the Queue.Bind RPC command. When this command is complete...
[ "def", "on_queue_declareok", "(", "self", ",", "method_frame", ")", ":", "self", ".", "_logger", ".", "debug", "(", "'Binding %s to %s with %s'", ",", "self", ".", "_exchange", ",", "self", ".", "_queue", ",", "self", ".", "_routing_key", ")", "self", ".", ...
50.466667
21.4
def get_signing_serializer(self, app: 'Quart') -> Optional[URLSafeTimedSerializer]: """Return a serializer for the session that also signs data. This will return None if the app is not configured for secrets. """ if not app.secret_key: return None options = { ...
[ "def", "get_signing_serializer", "(", "self", ",", "app", ":", "'Quart'", ")", "->", "Optional", "[", "URLSafeTimedSerializer", "]", ":", "if", "not", "app", ".", "secret_key", ":", "return", "None", "options", "=", "{", "'key_derivation'", ":", "self", ".",...
36.866667
22.533333
def seek_to_beginning(self, topic_partition=None): """Seek to the oldest available offset for partitions. - ``topic_partition``: Optionally provide specific TopicPartitions, otherwise default to all assigned partitions. """ if isinstance(topic_partition, TopicPartitio...
[ "def", "seek_to_beginning", "(", "self", ",", "topic_partition", "=", "None", ")", ":", "if", "isinstance", "(", "topic_partition", ",", "TopicPartition", ")", ":", "self", ".", "consumer", ".", "seek_to_beginning", "(", "topic_partition", ")", "else", ":", "r...
46.636364
25.272727
def angles(self, zfill = 3): """ Returns the internal angles of all elements and the associated statistics """ elements = self.elements.sort_index(axis = 1) etypes = elements[("type", "argiope")].unique() out = [] for etype in etypes: etype_info = ELEMENTS[etype] angles_info = e...
[ "def", "angles", "(", "self", ",", "zfill", "=", "3", ")", ":", "elements", "=", "self", ".", "elements", ".", "sort_index", "(", "axis", "=", "1", ")", "etypes", "=", "elements", "[", "(", "\"type\"", ",", "\"argiope\"", ")", "]", ".", "unique", "...
45.166667
16.125
def get_calendar_events(self, calendar_id, params=None): """ `<>`_ :arg calendar_id: The ID of the calendar containing the events :arg end: Get events before this time :arg from_: Skips a number of events :arg job_id: Get events for the job. When this option is used ...
[ "def", "get_calendar_events", "(", "self", ",", "calendar_id", ",", "params", "=", "None", ")", ":", "if", "calendar_id", "in", "SKIP_IN_PATH", ":", "raise", "ValueError", "(", "\"Empty value passed for a required argument 'calendar_id'.\"", ")", "return", "self", "."...
39.947368
17.631579
def _join_list(lst, oxford=False): """Join a list of words in a gramatically correct way.""" if len(lst) > 2: s = ', '.join(lst[:-1]) if oxford: s += ',' s += ' and ' + lst[-1] elif len(lst) == 2: s = lst[0] + ' and ' + lst[1] elif len(lst) == 1: s = l...
[ "def", "_join_list", "(", "lst", ",", "oxford", "=", "False", ")", ":", "if", "len", "(", "lst", ")", ">", "2", ":", "s", "=", "', '", ".", "join", "(", "lst", "[", ":", "-", "1", "]", ")", "if", "oxford", ":", "s", "+=", "','", "s", "+=", ...
25
16.5
def gen_df_save(df_grid_group: pd.DataFrame)->pd.DataFrame: '''generate a dataframe for saving Parameters ---------- df_output_grid_group : pd.DataFrame an output dataframe of a single group and grid Returns ------- pd.DataFrame a dataframe with date time info prepended for...
[ "def", "gen_df_save", "(", "df_grid_group", ":", "pd", ".", "DataFrame", ")", "->", "pd", ".", "DataFrame", ":", "# generate df_datetime for prepending", "idx_dt", "=", "df_grid_group", ".", "index", "ser_year", "=", "pd", ".", "Series", "(", "idx_dt", ".", "y...
32.517241
20.931034
def bounding_cylinder(self): """ A minimum volume bounding cylinder for the current mesh. Returns -------- mincyl : trimesh.primitives.Cylinder Cylinder primitive containing current mesh """ from . import primitives, bounds kwargs = bounds.minim...
[ "def", "bounding_cylinder", "(", "self", ")", ":", "from", ".", "import", "primitives", ",", "bounds", "kwargs", "=", "bounds", ".", "minimum_cylinder", "(", "self", ")", "mincyl", "=", "primitives", ".", "Cylinder", "(", "mutable", "=", "False", ",", "*",...
31.461538
14.384615
def update(self, attributes=None): """Update this resource. Not all aspects of a resource can be updated. If the server rejects updates an error will be thrown. Keyword Arguments: attributes(dict): Attributes that are to be updated Returns: Resource: A ne...
[ "def", "update", "(", "self", ",", "attributes", "=", "None", ")", ":", "resource_type", "=", "self", ".", "_resource_type", "(", ")", "resource_path", "=", "self", ".", "_resource_path", "(", ")", "session", "=", "self", ".", "_session", "singleton", "=",...
36.038462
20.076923
def copy(self): """Create a copy. Examples: This example copies constraint :math:`a \\ne b` and tests a solution on the copied constraint. >>> import dwavebinarycsp >>> import operator >>> const = dwavebinarycsp.Constraint.from_func(operator....
[ "def", "copy", "(", "self", ")", ":", "# each object is itself immutable (except the function)", "return", "self", ".", "__class__", "(", "self", ".", "func", ",", "self", ".", "configurations", ",", "self", ".", "variables", ",", "self", ".", "vartype", ",", ...
34.6
20.9
def major_axis_endpoints(self): """Return the endpoints of the major axis.""" i = np.argmax(self.axlens) # find the major axis v = self.paxes[:, i] # vector from center to major axis endpoint return self.ctr - v, self.ctr + v
[ "def", "major_axis_endpoints", "(", "self", ")", ":", "i", "=", "np", ".", "argmax", "(", "self", ".", "axlens", ")", "# find the major axis", "v", "=", "self", ".", "paxes", "[", ":", ",", "i", "]", "# vector from center to major axis endpoint", "return", "...
36.428571
20
def check_status(self): """Check the output of the summary route until the experiment is complete, then we can stop monitoring Heroku subprocess output. """ self.out.log("Recruitment is complete. Waiting for experiment completion...") base_url = get_base_url() sta...
[ "def", "check_status", "(", "self", ")", ":", "self", ".", "out", ".", "log", "(", "\"Recruitment is complete. Waiting for experiment completion...\"", ")", "base_url", "=", "get_base_url", "(", ")", "status_url", "=", "base_url", "+", "\"/summary\"", "while", "not"...
44.428571
15.714286
def _set_number_of_plots(self, n): """ Adjusts number of plots & curves to the desired value the gui. """ # multi plot, right number of plots and curves = great! if self.button_multi.is_checked() \ and len(self._curves) == len(self.plot_widgets) \ a...
[ "def", "_set_number_of_plots", "(", "self", ",", "n", ")", ":", "# multi plot, right number of plots and curves = great!", "if", "self", ".", "button_multi", ".", "is_checked", "(", ")", "and", "len", "(", "self", ".", "_curves", ")", "==", "len", "(", "self", ...
33.656716
21.358209
def set_mode_px4(self, mode, custom_mode, custom_sub_mode): '''enter arbitrary mode''' if isinstance(mode, str): mode_map = self.mode_mapping() if mode_map is None or mode not in mode_map: print("Unknown mode '%s'" % mode) return # PX4 ...
[ "def", "set_mode_px4", "(", "self", ",", "mode", ",", "custom_mode", ",", "custom_sub_mode", ")", ":", "if", "isinstance", "(", "mode", ",", "str", ")", ":", "mode_map", "=", "self", ".", "mode_mapping", "(", ")", "if", "mode_map", "is", "None", "or", ...
54.272727
19.909091
def angle(self, deg=False): """Return the angle of the complex argument. Args: deg (bool, optional): Return angle in degrees if True, radians if False (default). Returns: angle (Timeseries): The counterclockwise angle from the positive real axis on ...
[ "def", "angle", "(", "self", ",", "deg", "=", "False", ")", ":", "if", "self", ".", "dtype", ".", "str", "[", "1", "]", "!=", "'c'", ":", "warnings", ".", "warn", "(", "'angle() is intended for complex-valued timeseries'", ",", "RuntimeWarning", ",", "1", ...
38.25
20.3125
def hexists(self): """ Call the hexists command to check if the redis hash key exists for the current field """ try: key = self.key except DoesNotExist: """ If the object doesn't exists anymore, its PK is deleted, so the "se...
[ "def", "hexists", "(", "self", ")", ":", "try", ":", "key", "=", "self", ".", "key", "except", "DoesNotExist", ":", "\"\"\"\n If the object doesn't exists anymore, its PK is deleted, so the\n \"self.key\" call will raise a DoesNotExist exception. We catch it\n ...
33.875
17.875
def get_distances(rupture, mesh, param): """ :param rupture: a rupture :param mesh: a mesh of points or a site collection :param param: the kind of distance to compute (default rjb) :returns: an array of distances from the given mesh """ if param == 'rrup': dist = rupture.surface.get...
[ "def", "get_distances", "(", "rupture", ",", "mesh", ",", "param", ")", ":", "if", "param", "==", "'rrup'", ":", "dist", "=", "rupture", ".", "surface", ".", "get_min_distance", "(", "mesh", ")", "elif", "param", "==", "'rx'", ":", "dist", "=", "ruptur...
38.448276
14.655172
def p_case_list(p): """ case_list : | CASE expr sep stmt_list_opt case_list | CASE expr error stmt_list_opt case_list | OTHERWISE stmt_list """ if len(p) == 1: p[0] = node.stmt_list() elif len(p) == 3: assert isinstance(p[2], node.stmt_list) ...
[ "def", "p_case_list", "(", "p", ")", ":", "if", "len", "(", "p", ")", "==", "1", ":", "p", "[", "0", "]", "=", "node", ".", "stmt_list", "(", ")", "elif", "len", "(", "p", ")", "==", "3", ":", "assert", "isinstance", "(", "p", "[", "2", "]"...
28.954545
14.318182
def ReadPreprocessingInformation(self, knowledge_base): """Reads preprocessing information. The preprocessing information contains the system configuration which contains information about various system specific configuration data, for example the user accounts. Args: knowledge_base (Knowle...
[ "def", "ReadPreprocessingInformation", "(", "self", ",", "knowledge_base", ")", ":", "generator", "=", "self", ".", "_GetAttributeContainers", "(", "self", ".", "_CONTAINER_TYPE_SYSTEM_CONFIGURATION", ")", "for", "stream_number", ",", "system_configuration", "in", "enum...
42.588235
20.470588
def _convert_to_internal(self, data): """From 'Column Title' to 'Column_x0020_Title'""" for _dict in data: keys = list(_dict.keys())[:] for key in keys: if key not in self._disp_cols: raise Exception(key + ' not a column in current List.') ...
[ "def", "_convert_to_internal", "(", "self", ",", "data", ")", ":", "for", "_dict", "in", "data", ":", "keys", "=", "list", "(", "_dict", ".", "keys", "(", ")", ")", "[", ":", "]", "for", "key", "in", "keys", ":", "if", "key", "not", "in", "self",...
49.625
14.75
def GetVShadowStoreByPathSpec(self, path_spec): """Retrieves a VSS store for a path specification. Args: path_spec (PathSpec): path specification. Returns: pyvshadow.store: a VSS store or None if not available. """ store_index = vshadow.VShadowPathSpecGetStoreIndex(path_spec) if st...
[ "def", "GetVShadowStoreByPathSpec", "(", "self", ",", "path_spec", ")", ":", "store_index", "=", "vshadow", ".", "VShadowPathSpecGetStoreIndex", "(", "path_spec", ")", "if", "store_index", "is", "None", ":", "return", "None", "return", "self", ".", "_vshadow_volum...
28.5
20.571429
def _insert_new_layers(self, new_layers, start_node_id, end_node_id): """Insert the new_layers after the node with start_node_id.""" new_node_id = self._add_node(deepcopy(self.node_list[end_node_id])) temp_output_id = new_node_id for layer in new_layers[:-1]: temp_output_id =...
[ "def", "_insert_new_layers", "(", "self", ",", "new_layers", ",", "start_node_id", ",", "end_node_id", ")", ":", "new_node_id", "=", "self", ".", "_add_node", "(", "deepcopy", "(", "self", ".", "node_list", "[", "end_node_id", "]", ")", ")", "temp_output_id", ...
55.272727
21.090909
def validate_structure(reference_intervals, reference_labels, estimated_intervals, estimated_labels): """Checks that the input annotations to a structure estimation metric (i.e. one that takes in both segment boundaries and their labels) look like valid segment times and labels, and t...
[ "def", "validate_structure", "(", "reference_intervals", ",", "reference_labels", ",", "estimated_intervals", ",", "estimated_labels", ")", ":", "for", "(", "intervals", ",", "labels", ")", "in", "[", "(", "reference_intervals", ",", "reference_labels", ")", ",", ...
42.8125
18.9375
def get_dict_for_forms(self): """ Build a dictionnary where searchable_fields are next to their model to be use in modelform_factory dico = { "str(model)" : { "model" : Model, "fields" = [] #searchable_fields which are attribut...
[ "def", "get_dict_for_forms", "(", "self", ")", ":", "magic_dico", "=", "field_to_dict", "(", "self", ".", "searchable_fields", ")", "dico", "=", "{", "}", "def", "dict_from_fields_r", "(", "mini_dict", ",", "dico", ",", "model", ")", ":", "\"\"\"\n ...
34.95
17.35
def avail_sizes(call=None): ''' Return available Packet sizes. CLI Example: .. code-block:: bash salt-cloud --list-sizes packet-provider salt-cloud -f avail_sizes packet-provider ''' if call == 'action': raise SaltCloudException( 'The avail_locations functi...
[ "def", "avail_sizes", "(", "call", "=", "None", ")", ":", "if", "call", "==", "'action'", ":", "raise", "SaltCloudException", "(", "'The avail_locations function must be called with -f or --function.'", ")", "vm_", "=", "get_configured_provider", "(", ")", "manager", ...
21
24.307692