text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def from_object(cls, o, base_uri=None, parent_curies=None, draft=AUTO): """Returns a new ``Document`` based on a JSON object or array. Arguments: - ``o``: a dictionary holding the deserializated JSON for the new ``Document``, or a ``list`` of such documents. - ``base_u...
[ "def", "from_object", "(", "cls", ",", "o", ",", "base_uri", "=", "None", ",", "parent_curies", "=", "None", ",", "draft", "=", "AUTO", ")", ":", "if", "isinstance", "(", "o", ",", "list", ")", ":", "return", "[", "cls", ".", "from_object", "(", "x...
45.791667
0.001783
def add_tcp_firewall_rule(project, access_token, name, tag, port): """Adds a TCP firewall rule. TODO: docstring""" headers = { 'Authorization': 'Bearer %s' % access_token.access_token } payload = { "name": name, "kind": "compute#firewall", "sourceRanges": [...
[ "def", "add_tcp_firewall_rule", "(", "project", ",", "access_token", ",", "name", ",", "tag", ",", "port", ")", ":", "headers", "=", "{", "'Authorization'", ":", "'Bearer %s'", "%", "access_token", ".", "access_token", "}", "payload", "=", "{", "\"name\"", "...
30.285714
0.014857
def setup_logging(log_filename=None, log_level="DEBUG", str_format=None, date_format=None, log_file_level="DEBUG", log_stdout_level=None, log_restart=False, log_history=False, formatter=None, silence_modules=None, log_filter=None): """ This will setup loggin...
[ "def", "setup_logging", "(", "log_filename", "=", "None", ",", "log_level", "=", "\"DEBUG\"", ",", "str_format", "=", "None", ",", "date_format", "=", "None", ",", "log_file_level", "=", "\"DEBUG\"", ",", "log_stdout_level", "=", "None", ",", "log_restart", "=...
52.820513
0.000477
def get_decoded_tile(codec, stream, imagep, tile_index): """get the decoded tile from the codec Wraps the openjp2 library function opj_get_decoded_tile. Parameters ---------- codec : CODEC_TYPE The jpeg2000 codec. stream : STREAM_TYPE_P The input stream. image : ImageType ...
[ "def", "get_decoded_tile", "(", "codec", ",", "stream", ",", "imagep", ",", "tile_index", ")", ":", "OPENJP2", ".", "opj_get_decoded_tile", ".", "argtypes", "=", "[", "CODEC_TYPE", ",", "STREAM_TYPE_P", ",", "ctypes", ".", "POINTER", "(", "ImageType", ")", "...
31.607143
0.001096
def get_sorted_dependencies(service_model): """ Returns list of application models in topological order. It is used in order to correctly delete dependent resources. """ app_models = list(service_model._meta.app_config.get_models()) dependencies = {model: set() for model in app_models} relat...
[ "def", "get_sorted_dependencies", "(", "service_model", ")", ":", "app_models", "=", "list", "(", "service_model", ".", "_meta", ".", "app_config", ".", "get_models", "(", ")", ")", "dependencies", "=", "{", "model", ":", "set", "(", ")", "for", "model", "...
39.25
0.001555
def csstext_to_pairs(csstext): """ csstext_to_pairs takes css text and make it to list of tuple of key,value. """ # The lock is required to avoid ``cssutils`` concurrency # issues documented in issue #65 with csstext_to_pairs._lock: return sorted( [ (prop....
[ "def", "csstext_to_pairs", "(", "csstext", ")", ":", "# The lock is required to avoid ``cssutils`` concurrency", "# issues documented in issue #65", "with", "csstext_to_pairs", ".", "_lock", ":", "return", "sorted", "(", "[", "(", "prop", ".", "name", ".", "strip", "(",...
30.133333
0.002146
def query_subcellular_location(): """ Returns list of subcellular locations by query parameters --- tags: - Query functions parameters: - name: location in: query type: string required: false description: Subcellular location default: 'Clathrin-...
[ "def", "query_subcellular_location", "(", ")", ":", "args", "=", "get_args", "(", "request_args", "=", "request", ".", "args", ",", "allowed_str_args", "=", "[", "'location'", ",", "'entry_name'", "]", ",", "allowed_int_args", "=", "[", "'limit'", "]", ")", ...
21.473684
0.001172
def _stdout_level(self): """Returns the level that stdout runs at""" for level, consumer in self.consumers: if consumer is sys.stdout: return level return self.FATAL
[ "def", "_stdout_level", "(", "self", ")", ":", "for", "level", ",", "consumer", "in", "self", ".", "consumers", ":", "if", "consumer", "is", "sys", ".", "stdout", ":", "return", "level", "return", "self", ".", "FATAL" ]
35.333333
0.009217
def get_dirinfo(self, name: str): ''' get a `DirectoryInfo` for a directory (without create actual directory). ''' return DirectoryInfo(os.path.join(self._path, name))
[ "def", "get_dirinfo", "(", "self", ",", "name", ":", "str", ")", ":", "return", "DirectoryInfo", "(", "os", ".", "path", ".", "join", "(", "self", ".", "_path", ",", "name", ")", ")" ]
39
0.015075
def set_idle_params(self, timeout=None, exit=None): """Activate idle mode - put uWSGI in cheap mode after inactivity timeout. :param int timeout: Inactivity timeout in seconds. :param bool exit: Shutdown uWSGI when idle. """ self._set('idle', timeout) self._set('die-on...
[ "def", "set_idle_params", "(", "self", ",", "timeout", "=", "None", ",", "exit", "=", "None", ")", ":", "self", ".", "_set", "(", "'idle'", ",", "timeout", ")", "self", ".", "_set", "(", "'die-on-idle'", ",", "exit", ",", "cast", "=", "bool", ")", ...
30.25
0.008021
def add_density_option_group(parser): """Adds the options needed to configure contours and density colour map. Parameters ---------- parser : object ArgumentParser instance. """ density_group = parser.add_argument_group("Options for configuring the " ...
[ "def", "add_density_option_group", "(", "parser", ")", ":", "density_group", "=", "parser", ".", "add_argument_group", "(", "\"Options for configuring the \"", "\"contours and density color map\"", ")", "density_group", ".", "add_argument", "(", "\"--density-cmap\"", ",", "...
39.6
0.000986
def folders(self, ann_id=None): '''Yields an unordered generator for all available folders. By default (with ``ann_id=None``), folders are shown for all anonymous users. Optionally, ``ann_id`` can be set to a username, which restricts the list to only folders owned by that user. ...
[ "def", "folders", "(", "self", ",", "ann_id", "=", "None", ")", ":", "ann_id", "=", "self", ".", "_annotator", "(", "ann_id", ")", "if", "len", "(", "self", ".", "prefix", ")", ">", "0", ":", "prefix", "=", "'|'", ".", "join", "(", "[", "urllib",...
44.526316
0.002315
def _generate_noise_temporal_task(stimfunction_tr, motion_noise='gaussian', ): """Generate the signal dependent noise Create noise specific to the signal, for instance there is variability in how the signal manifests on each event Par...
[ "def", "_generate_noise_temporal_task", "(", "stimfunction_tr", ",", "motion_noise", "=", "'gaussian'", ",", ")", ":", "# Make the noise to be added", "stimfunction_tr", "=", "stimfunction_tr", "!=", "0", "if", "motion_noise", "==", "'gaussian'", ":", "noise", "=", "s...
30
0.000787
def create_network_interface(name, subnet_id=None, subnet_name=None, private_ip_address=None, description=None, groups=None, region=None, key=None, keyid=None, profile=None): ''' Create an Elastic Network Interface. .. v...
[ "def", "create_network_interface", "(", "name", ",", "subnet_id", "=", "None", ",", "subnet_name", "=", "None", ",", "private_ip_address", "=", "None", ",", "description", "=", "None", ",", "groups", "=", "None", ",", "region", "=", "None", ",", "key", "="...
38.433333
0.000846
def copy(self, target=None, name=None): """ Asynchronously creates a copy of this DriveItem and all it's child elements. :param target: target location to move to. If it's a drive the item will be moved to the root folder. :type target: drive.Folder or Drive :param name...
[ "def", "copy", "(", "self", ",", "target", "=", "None", ",", "name", "=", "None", ")", ":", "if", "target", "is", "None", "and", "name", "is", "None", ":", "raise", "ValueError", "(", "'Must provide a target or a name (or both)'", ")", "if", "isinstance", ...
35.698413
0.000865
def render(template, saltenv='base', sls='', tmplpath=None, **kws): ''' Render the python module's components :rtype: string ''' template = tmplpath if not os.path.isfile(template): raise SaltRenderError('Template {0} is not a file!'.format(template)) tmp_data = salt.utils.template...
[ "def", "render", "(", "template", ",", "saltenv", "=", "'base'", ",", "sls", "=", "''", ",", "tmplpath", "=", "None", ",", "*", "*", "kws", ")", ":", "template", "=", "tmplpath", "if", "not", "os", ".", "path", ".", "isfile", "(", "template", ")", ...
28.387097
0.002198
def performFirmwareUpdate(self, unDeviceIndex): """ Performs the actual firmware update if applicable. The following events will be sent, if VRFirmwareError_None was returned: VREvent_FirmwareUpdateStarted, VREvent_FirmwareUpdateFinished Use the properties Prop_Firmware_UpdateAvailable...
[ "def", "performFirmwareUpdate", "(", "self", ",", "unDeviceIndex", ")", ":", "fn", "=", "self", ".", "function_table", ".", "performFirmwareUpdate", "result", "=", "fn", "(", "unDeviceIndex", ")", "return", "result" ]
60.666667
0.012179
def _resample_residual(self, star, epsf): """ Compute a normalized residual image in the oversampled ePSF grid. A normalized residual image is calculated by subtracting the normalized ePSF model from the normalized star at the location of the star in the undersampled gri...
[ "def", "_resample_residual", "(", "self", ",", "star", ",", "epsf", ")", ":", "# find the integer index of EPSFStar pixels in the oversampled", "# ePSF grid", "x", "=", "epsf", ".", "_oversampling", "[", "0", "]", "*", "star", ".", "_xidx_centered", "y", "=", "eps...
38.660377
0.001428
def _get_observation(self): """ Returns an OrderedDict containing observations [(name_string, np.array), ...]. Important keys: robot-state: contains robot-centric information. object-state: requires @self.use_object_obs to be True. contains object...
[ "def", "_get_observation", "(", "self", ")", ":", "di", "=", "super", "(", ")", ".", "_get_observation", "(", ")", "# camera observations", "if", "self", ".", "use_camera_obs", ":", "camera_obs", "=", "self", ".", "sim", ".", "render", "(", "camera_name", ...
35.265625
0.002155
def lattice_from_sites_file( site_file, cell_lengths ): """ Generate a lattice from a sites file. Args: site_file (Str): Filename for the file containing the site information. cell_lengths (List(Float,Float,Float)): A list containing the [ x, y, z ] cell lengths. Returns: (Latt...
[ "def", "lattice_from_sites_file", "(", "site_file", ",", "cell_lengths", ")", ":", "sites", "=", "[", "]", "site_re", "=", "re", ".", "compile", "(", "'site:\\s+([-+]?\\d+)'", ")", "r_re", "=", "re", ".", "compile", "(", "'cent(?:er|re):\\s+([-\\d\\.e]+)\\s+([-\\d...
45.191489
0.036406
def delete(self, account_id, user_id): """ Only the primary on the account can add or remove user's access to an account :param account_id: int of the account_id for the account :param user_id: int of the user_id to grant access :return: Access dict """ retur...
[ "def", "delete", "(", "self", ",", "account_id", ",", "user_id", ")", ":", "return", "self", ".", "connection", ".", "delete", "(", "'account/access'", ",", "account_id", "=", "account_id", ",", "user_id", "=", "user_id", ")" ]
56.571429
0.00995
def put(self, file_path, upload_path = ''): """PUT Args: file_path: Full path for a file you want to upload upload_path: Ndrive path where you want to upload file ex) /Picture/ Returns: True: Upload success False: Upload failed ...
[ "def", "put", "(", "self", ",", "file_path", ",", "upload_path", "=", "''", ")", ":", "f", "=", "open", "(", "file_path", ",", "\"r\"", ")", "c", "=", "f", ".", "read", "(", ")", "file_name", "=", "os", ".", "path", ".", "basename", "(", "file_pa...
29.83871
0.011518
def _encode_str(self, obj, escape_quotes=True): """Return an ASCII-only JSON representation of a Python string""" def replace(match): s = match.group(0) try: if escape_quotes: return ESCAPE_DCT[s] else: retur...
[ "def", "_encode_str", "(", "self", ",", "obj", ",", "escape_quotes", "=", "True", ")", ":", "def", "replace", "(", "match", ")", ":", "s", "=", "match", ".", "group", "(", "0", ")", "try", ":", "if", "escape_quotes", ":", "return", "ESCAPE_DCT", "[",...
37.826087
0.002242
def get_throttled_by_consumed_read_percent( table_name, lookback_window_start=15, lookback_period=5): """ Returns the number of throttled read events in percent of consumption :type table_name: str :param table_name: Name of the DynamoDB table :type lookback_window_start: int :param lookbac...
[ "def", "get_throttled_by_consumed_read_percent", "(", "table_name", ",", "lookback_window_start", "=", "15", ",", "lookback_period", "=", "5", ")", ":", "try", ":", "metrics1", "=", "__get_aws_metric", "(", "table_name", ",", "lookback_window_start", ",", "lookback_pe...
35.75
0.000681
def _activate(self, token): """Activate this node for the given token.""" info = token.to_info() activation = Activation( self.rule, frozenset(info.data), {k: v for k, v in info.context if isinstance(k, str)}) if token.is_valid(): if inf...
[ "def", "_activate", "(", "self", ",", "token", ")", ":", "info", "=", "token", ".", "to_info", "(", ")", "activation", "=", "Activation", "(", "self", ".", "rule", ",", "frozenset", "(", "info", ".", "data", ")", ",", "{", "k", ":", "v", "for", "...
30.703704
0.002339
def dropbox_submission(dropbox, request): """ handles the form submission, redirects to the dropbox's status page.""" try: data = dropbox_schema.deserialize(request.POST) except Exception: return HTTPFound(location=request.route_url('dropbox_form')) # set the message dropbox.message...
[ "def", "dropbox_submission", "(", "dropbox", ",", "request", ")", ":", "try", ":", "data", "=", "dropbox_schema", ".", "deserialize", "(", "request", ".", "POST", ")", "except", "Exception", ":", "return", "HTTPFound", "(", "location", "=", "request", ".", ...
38.12
0.002047
def validate_frequencies(frequencies, max_freq, min_freq, allow_negatives=False): """Checks that a 1-d frequency ndarray is well-formed, and raises errors if not. Parameters ---------- frequencies : np.ndarray, shape=(n,) Array of frequency values max_freq : flo...
[ "def", "validate_frequencies", "(", "frequencies", ",", "max_freq", ",", "min_freq", ",", "allow_negatives", "=", "False", ")", ":", "# If flag is true, map frequencies to their absolute value.", "if", "allow_negatives", ":", "frequencies", "=", "np", ".", "abs", "(", ...
46.459459
0.00057
def forward_ad(node, wrt, preserve_result=False, check_dims=True): """Perform forward-mode AD on an AST. This function analyses the AST to determine which variables are active and proceeds by taking the naive derivative. Before returning the primal and adjoint it annotates push and pop statements as such. A...
[ "def", "forward_ad", "(", "node", ",", "wrt", ",", "preserve_result", "=", "False", ",", "check_dims", "=", "True", ")", ":", "if", "not", "isinstance", "(", "node", ",", "gast", ".", "FunctionDef", ")", ":", "raise", "TypeError", "# Activity analysis", "c...
35.512195
0.010027
def _get_user_new_args(args): """ PRECONDITION: `_validate_new_user_input()` has been called on `args`. """ user_new_args = {"username": args.username, "email": args.email} if args.first is not None: user_new_args["first"] = args.first if args.last is not None: ...
[ "def", "_get_user_new_args", "(", "args", ")", ":", "user_new_args", "=", "{", "\"username\"", ":", "args", ".", "username", ",", "\"email\"", ":", "args", ".", "email", "}", "if", "args", ".", "first", "is", "not", "None", ":", "user_new_args", "[", "\"...
39.956522
0.001063
def point_rotate(pt, ax, theta): """ Rotate a 3-D point around a 3-D axis through the origin. Handedness is a counter-clockwise rotation when viewing the rotation axis as pointing at the observer. Thus, in a right-handed x-y-z frame, a 90deg rotation of (1,0,0) around the z-axis (0,0,1) yields a point...
[ "def", "point_rotate", "(", "pt", ",", "ax", ",", "theta", ")", ":", "# Imports", "import", "numpy", "as", "np", "# Ensure pt is reducible to 3-D vector.", "pt", "=", "make_nd_vec", "(", "pt", ",", "nd", "=", "3", ",", "t", "=", "np", ".", "float64", ","...
28.75
0.001202
def peep_port(paths): """Convert a peep requirements file to one compatble with pip-8 hashing. Loses comments and tromps on URLs, so the result will need a little manual massaging, but the hard part--the hash conversion--is done for you. """ if not paths: print('Please specify one or more ...
[ "def", "peep_port", "(", "paths", ")", ":", "if", "not", "paths", ":", "print", "(", "'Please specify one or more requirements files so I have '", "'something to port.\\n'", ")", "return", "COMMAND_LINE_ERROR", "comes_from", "=", "None", "for", "req", "in", "chain", "...
36.84375
0.002479
def Emulation_setDefaultBackgroundColorOverride(self, **kwargs): """ Function path: Emulation.setDefaultBackgroundColorOverride Domain: Emulation Method name: setDefaultBackgroundColorOverride WARNING: This function is marked 'Experimental'! Parameters: Optional arguments: 'color' (type: ...
[ "def", "Emulation_setDefaultBackgroundColorOverride", "(", "self", ",", "*", "*", "kwargs", ")", ":", "expected", "=", "[", "'color'", "]", "passed_keys", "=", "list", "(", "kwargs", ".", "keys", "(", ")", ")", "assert", "all", "(", "[", "(", "key", "in"...
40.863636
0.033696
def format_full_name(first_name: str, last_name: str, max_length: int = 20): """ Limits name length to specified length. Tries to keep name as human-readable an natural as possible. :param first_name: First name :param last_name: Last name :param max_length: Maximum length :return: Full name of ...
[ "def", "format_full_name", "(", "first_name", ":", "str", ",", "last_name", ":", "str", ",", "max_length", ":", "int", "=", "20", ")", ":", "# dont allow commas in limited names", "first_name", "=", "first_name", ".", "replace", "(", "','", ",", "' '", ")", ...
34.928571
0.001326
def rank(self, n, mu, sigma, crit=.5, upper=10000, xtol=1): """%(super)s Additional Parameters ---------------------- {0} """ return _make_rank(self, n, mu, sigma, crit=crit, upper=upper, xtol=xtol)
[ "def", "rank", "(", "self", ",", "n", ",", "mu", ",", "sigma", ",", "crit", "=", ".5", ",", "upper", "=", "10000", ",", "xtol", "=", "1", ")", ":", "return", "_make_rank", "(", "self", ",", "n", ",", "mu", ",", "sigma", ",", "crit", "=", "cri...
26.454545
0.009967
def to_source(node, indentation=' ' * 4): """Return source code of a given AST.""" if isinstance(node, gast.AST): node = gast.gast_to_ast(node) generator = SourceWithCommentGenerator(indentation, False, astor.string_repr.pretty_string) generator.visit(node) generat...
[ "def", "to_source", "(", "node", ",", "indentation", "=", "' '", "*", "4", ")", ":", "if", "isinstance", "(", "node", ",", "gast", ".", "AST", ")", ":", "node", "=", "gast", ".", "gast_to_ast", "(", "node", ")", "generator", "=", "SourceWithCommentGene...
44.666667
0.017073
def is_changed_uses(cp): ''' .. versionadded:: 2015.8.0 Uses portage for determine if the use flags of installed package is compatible with use flags in portage configs. @type cp: string @param cp: eg cat/pkg ''' cpv = _get_cpv(cp) i_flags, conf_flags = get_cleared_flags(cpv) f...
[ "def", "is_changed_uses", "(", "cp", ")", ":", "cpv", "=", "_get_cpv", "(", "cp", ")", "i_flags", ",", "conf_flags", "=", "get_cleared_flags", "(", "cpv", ")", "for", "i", "in", "i_flags", ":", "try", ":", "conf_flags", ".", "remove", "(", "i", ")", ...
25.388889
0.00211
def get_poll_option_formset(self, formset_class): """ Returns an instance of the poll option formset to be used in the view. """ if self.request.forum_permission_handler.can_create_polls( self.get_forum(), self.request.user, ): return formset_class(**self.get_poll_option_...
[ "def", "get_poll_option_formset", "(", "self", ",", "formset_class", ")", ":", "if", "self", ".", "request", ".", "forum_permission_handler", ".", "can_create_polls", "(", "self", ".", "get_forum", "(", ")", ",", "self", ".", "request", ".", "user", ",", ")"...
55.333333
0.008902
def add_response_headers(h): """ Add HTTP-headers to response. Example: @add_response_headers({'Refresh': '10', 'X-Powered-By': 'Django'}) def view(request): .... """ def headers_wrapper(fun): def wrapped_function(*args, **kwargs): response = fun(*args...
[ "def", "add_response_headers", "(", "h", ")", ":", "def", "headers_wrapper", "(", "fun", ")", ":", "def", "wrapped_function", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "response", "=", "fun", "(", "*", "args", ",", "*", "*", "kwargs", ")",...
29.625
0.002045
def fatal(self, msg, exc=None): """ Exit on a fatal error. """ if exc is not None: self.LOG.fatal("%s (%s)" % (msg, exc)) if self.options.debug: return # let the caller re-raise it else: self.LOG.fatal(msg) sys.exit(error.EX_SOF...
[ "def", "fatal", "(", "self", ",", "msg", ",", "exc", "=", "None", ")", ":", "if", "exc", "is", "not", "None", ":", "self", ".", "LOG", ".", "fatal", "(", "\"%s (%s)\"", "%", "(", "msg", ",", "exc", ")", ")", "if", "self", ".", "options", ".", ...
31.7
0.009202
def updateDynamics(self): ''' Calculates a new "aggregate dynamic rule" using the history of variables named in track_vars, and distributes this rule to AgentTypes in agents. Parameters ---------- none Returns ------- dynamics : instance ...
[ "def", "updateDynamics", "(", "self", ")", ":", "# Make a dictionary of inputs for the dynamics calculator", "history_vars_string", "=", "''", "arg_names", "=", "list", "(", "getArgNames", "(", "self", ".", "calcDynamics", ")", ")", "if", "'self'", "in", "arg_names", ...
38.870968
0.008097
def addObject(self, object, name=None): """ Adds an object to the Machine. Objects should be PhysicalObjects. """ if name is None: name = len(self.objects) self.objects[name] = object
[ "def", "addObject", "(", "self", ",", "object", ",", "name", "=", "None", ")", ":", "if", "name", "is", "None", ":", "name", "=", "len", "(", "self", ".", "objects", ")", "self", ".", "objects", "[", "name", "]", "=", "object" ]
20.6
0.009302
async def install_mediaroom_protocol(responses_callback, box_ip=None): """Install an asyncio protocol to process NOTIFY messages.""" from . import version _LOGGER.debug(version) loop = asyncio.get_event_loop() mediaroom_protocol = MediaroomProtocol(responses_callback, box_ip) sock = create_so...
[ "async", "def", "install_mediaroom_protocol", "(", "responses_callback", ",", "box_ip", "=", "None", ")", ":", "from", ".", "import", "version", "_LOGGER", ".", "debug", "(", "version", ")", "loop", "=", "asyncio", ".", "get_event_loop", "(", ")", "mediaroom_p...
30.285714
0.002288
def set(self, subname, value): ''' Set the data ignoring the sign, ie set("test", -1) will set "test" exactly to -1 (not decrement it by 1) See https://github.com/etsy/statsd/blob/master/docs/metric_types.md "Adding a sign to the gauge value will change the value, rather ...
[ "def", "set", "(", "self", ",", "subname", ",", "value", ")", ":", "assert", "isinstance", "(", "value", ",", "compat", ".", "NUM_TYPES", ")", "if", "value", "<", "0", ":", "self", ".", "_send", "(", "subname", ",", "0", ")", "return", "self", ".",...
32.642857
0.002125
def do_config_discovery(config, modules): '''Let modules detect additional configuration values. `config` is the initial dictionary with command-line and file-derived values, but nothing else, filled in. This calls :meth:`yakonfig.configurable.Configurable.discover_config` on every configuration m...
[ "def", "do_config_discovery", "(", "config", ",", "modules", ")", ":", "def", "work_in", "(", "config", ",", "module", ",", "name", ")", ":", "f", "=", "getattr", "(", "module", ",", "'discover_config'", ",", "None", ")", "if", "f", ":", "f", "(", "c...
40.55
0.001205
def has_commit(self): """ :return: :rtype: boolean """ current_revision = self.history.current_revision revision_id = self.state.revision_id return current_revision.revision_id != revision_id
[ "def", "has_commit", "(", "self", ")", ":", "current_revision", "=", "self", ".", "history", ".", "current_revision", "revision_id", "=", "self", ".", "state", ".", "revision_id", "return", "current_revision", ".", "revision_id", "!=", "revision_id" ]
26.666667
0.008065
def show_homecoming(request): """Show homecoming ribbon / scores """ return {'show_homecoming': settings.HOCO_START_DATE < datetime.date.today() and datetime.date.today() < settings.HOCO_END_DATE}
[ "def", "show_homecoming", "(", "request", ")", ":", "return", "{", "'show_homecoming'", ":", "settings", ".", "HOCO_START_DATE", "<", "datetime", ".", "date", ".", "today", "(", ")", "and", "datetime", ".", "date", ".", "today", "(", ")", "<", "settings", ...
67.333333
0.009804
def corrmtx(x_input, m, method='autocorrelation'): r"""Correlation matrix This function is used by PSD estimator functions. It generates the correlation matrix from a correlation data set and a maximum lag. :param array x: autocorrelation samples (1D) :param int m: the maximum lag Depending o...
[ "def", "corrmtx", "(", "x_input", ",", "m", ",", "method", "=", "'autocorrelation'", ")", ":", "valid_methods", "=", "[", "'autocorrelation'", ",", "'prewindowed'", ",", "'postwindowed'", ",", "'covariance'", ",", "'modified'", "]", "if", "method", "not", "in"...
30.361446
0.002305
def plotConvergenceByObjectMultiColumn(results, objectRange, columnRange): """ Plots the convergence graph: iterations vs number of objects. Each curve shows the convergence for a given number of columns. """ ######################################################################## # # Accumulate all the r...
[ "def", "plotConvergenceByObjectMultiColumn", "(", "results", ",", "objectRange", ",", "columnRange", ")", ":", "########################################################################", "#", "# Accumulate all the results per column in a convergence array.", "#", "# Convergence[c,o] = ho...
32.981132
0.022778
def classic_administrators(self): """Instance depends on the API version: * 2015-06-01: :class:`ClassicAdministratorsOperations<azure.mgmt.authorization.v2015_06_01.operations.ClassicAdministratorsOperations>` """ api_version = self._get_api_version('classic_administrators') ...
[ "def", "classic_administrators", "(", "self", ")", ":", "api_version", "=", "self", ".", "_get_api_version", "(", "'classic_administrators'", ")", "if", "api_version", "==", "'2015-06-01'", ":", "from", ".", "v2015_06_01", ".", "operations", "import", "ClassicAdmini...
62.909091
0.008547
def _parse_settings_source(opts, iface_type, enabled, iface): ''' Filters given options and outputs valid settings for a network interface. ''' adapters = salt.utils.odict.OrderedDict() adapters[iface] = salt.utils.odict.OrderedDict() adapters[iface]['type'] = iface_type adapters[iface...
[ "def", "_parse_settings_source", "(", "opts", ",", "iface_type", ",", "enabled", ",", "iface", ")", ":", "adapters", "=", "salt", ".", "utils", ".", "odict", ".", "OrderedDict", "(", ")", "adapters", "[", "iface", "]", "=", "salt", ".", "utils", ".", "...
30.333333
0.002132
def convert_activation(builder, layer, input_names, output_names, keras_layer): """ Convert an activation layer from keras to coreml. Parameters ---------- keras_layer: layer A keras layer object. builder: NeuralNetworkBuilder A neural network builder object. """ # Get ...
[ "def", "convert_activation", "(", "builder", ",", "layer", ",", "input_names", ",", "output_names", ",", "keras_layer", ")", ":", "# Get input and output names", "input_name", ",", "output_name", "=", "(", "input_names", "[", "0", "]", ",", "output_names", "[", ...
37.635135
0.013296
def eval_mean_error_functions(act,ang,n_vec,toy_aa,timeseries,withplot=False): """ Calculates sqrt(mean(E)) and sqrt(mean(F)) """ Err = np.zeros(6) NT = len(timeseries) size = len(ang[6:])/3 UA = ua(toy_aa.T[3:].T,np.ones(3)) fig,axis=None,None if(withplot): fig,axis=plt.subplots(3,...
[ "def", "eval_mean_error_functions", "(", "act", ",", "ang", ",", "n_vec", ",", "toy_aa", ",", "timeseries", ",", "withplot", "=", "False", ")", ":", "Err", "=", "np", ".", "zeros", "(", "6", ")", "NT", "=", "len", "(", "timeseries", ")", "size", "=",...
35.75
0.017021
def parse(self, parser, xml): """Parses the rawtext to extract contents and references.""" #We can only process references if the XML tag has inner-XML if xml.text is not None: matches = parser.RE_REFS.finditer(xml.text) if matches: for match in matches: ...
[ "def", "parse", "(", "self", ",", "parser", ",", "xml", ")", ":", "#We can only process references if the XML tag has inner-XML", "if", "xml", ".", "text", "is", "not", "None", ":", "matches", "=", "parser", ".", "RE_REFS", ".", "finditer", "(", "xml", ".", ...
47.153846
0.0096
def cmd_arp_ping(ip, iface, verbose): """ Send ARP packets to check if a host it's alive in the local network. Example: \b # habu.arp.ping 192.168.0.1 Ether / ARP is at a4:08:f5:19:17:a4 says 192.168.0.1 / Padding """ if verbose: logging.basicConfig(level=logging.INFO, format=...
[ "def", "cmd_arp_ping", "(", "ip", ",", "iface", ",", "verbose", ")", ":", "if", "verbose", ":", "logging", ".", "basicConfig", "(", "level", "=", "logging", ".", "INFO", ",", "format", "=", "'%(message)s'", ")", "conf", ".", "verb", "=", "False", "if",...
22.038462
0.001672
def plot_dict(self, flags, label='key', known='x', **kwargs): """Plot a `~gwpy.segments.DataQualityDict` onto these axes Parameters ---------- flags : `~gwpy.segments.DataQualityDict` data-quality dict to display label : `str`, optional labelling system ...
[ "def", "plot_dict", "(", "self", ",", "flags", ",", "label", "=", "'key'", ",", "known", "=", "'x'", ",", "*", "*", "kwargs", ")", ":", "out", "=", "[", "]", "for", "lab", ",", "flag", "in", "flags", ".", "items", "(", ")", ":", "if", "label", ...
36.04878
0.001318
def create_identity_from_private_key(self, label: str, pwd: str, private_key: str) -> Identity: """ This interface is used to create identity based on given label, password and private key. :param label: a label for identity. :param pwd: a password which will be used to encrypt and decr...
[ "def", "create_identity_from_private_key", "(", "self", ",", "label", ":", "str", ",", "pwd", ":", "str", ",", "private_key", ":", "str", ")", "->", "Identity", ":", "salt", "=", "get_random_hex_str", "(", "16", ")", "identity", "=", "self", ".", "__create...
50.583333
0.008091
def plot_eq_cont(fignum, DIblock, color_map='coolwarm'): """ plots dec inc block as a color contour Parameters __________________ Input: fignum : figure number DIblock : nested pairs of [Declination, Inclination] color_map : matplotlib color map [default is coolwarm] Out...
[ "def", "plot_eq_cont", "(", "fignum", ",", "DIblock", ",", "color_map", "=", "'coolwarm'", ")", ":", "import", "random", "plt", ".", "figure", "(", "num", "=", "fignum", ")", "plt", ".", "axis", "(", "\"off\"", ")", "XY", "=", "[", "]", "centres", "=...
42.606061
0.001158
def _mpfr_get_str2(base, ndigits, op, rounding_mode): """ Variant of mpfr_get_str, for internal use: simply splits off the '-' sign from the digit string, and returns a triple (sign, digits, exp) Also converts the byte-string produced by mpfr_get_str to Unicode. """ digits, exp = mpf...
[ "def", "_mpfr_get_str2", "(", "base", ",", "ndigits", ",", "op", ",", "rounding_mode", ")", ":", "digits", ",", "exp", "=", "mpfr", ".", "mpfr_get_str", "(", "base", ",", "ndigits", ",", "op", ",", "rounding_mode", ")", "negative", "=", "digits", ".", ...
31.333333
0.002066
def join_path_prefix(path, pre_path=None): """ If path set and not absolute, append it to pre path (if used) :param path: path to append :type path: str | None :param pre_path: Base path to append to (default: None) :type pre_path: None | str :return: Path or appended path :rtype: str |...
[ "def", "join_path_prefix", "(", "path", ",", "pre_path", "=", "None", ")", ":", "if", "not", "path", ":", "return", "path", "if", "pre_path", "and", "not", "os", ".", "path", ".", "isabs", "(", "path", ")", ":", "return", "os", ".", "path", ".", "j...
25.555556
0.002096
def read(self): """Return the value. If necessary, the value is built.""" self.build() if not hasattr(self, 'built_value'): self.built_value = self.value return self.built_value
[ "def", "read", "(", "self", ")", ":", "self", ".", "build", "(", ")", "if", "not", "hasattr", "(", "self", ",", "'built_value'", ")", ":", "self", ".", "built_value", "=", "self", ".", "value", "return", "self", ".", "built_value" ]
36
0.00905
def delete_file(self, secure_data_path): """Delete a file at the given secure data path""" secret_resp = delete_with_retry(self.cerberus_url + '/v1/secure-file/' + secure_data_path, headers=self.HEADERS) throw_if_bad_response(secret_resp) return secr...
[ "def", "delete_file", "(", "self", ",", "secure_data_path", ")", ":", "secret_resp", "=", "delete_with_retry", "(", "self", ".", "cerberus_url", "+", "'/v1/secure-file/'", "+", "secure_data_path", ",", "headers", "=", "self", ".", "HEADERS", ")", "throw_if_bad_res...
53.666667
0.012232
def setClockShowDate(kvalue, **kwargs): ''' Set whether the date is visible in the clock CLI Example: .. code-block:: bash salt '*' gnome.setClockShowDate <True|False> user=<username> ''' if kvalue is not True and kvalue is not False: return False _gsession = _GSettings(u...
[ "def", "setClockShowDate", "(", "kvalue", ",", "*", "*", "kwargs", ")", ":", "if", "kvalue", "is", "not", "True", "and", "kvalue", "is", "not", "False", ":", "return", "False", "_gsession", "=", "_GSettings", "(", "user", "=", "kwargs", ".", "get", "("...
28
0.002033
def move_to(self, destination_filename: str, alter_if_clash: bool = True) -> None: """ Move the file to which this class refers to a new location. The function will not overwrite existing files (but offers the option to rename files slightly to avoid a clash). Ar...
[ "def", "move_to", "(", "self", ",", "destination_filename", ":", "str", ",", "alter_if_clash", ":", "bool", "=", "True", ")", "->", "None", ":", "if", "not", "self", ".", "src_filename", ":", "return", "if", "alter_if_clash", ":", "counter", "=", "0", "w...
43.840909
0.001521
def columns_dataset(self): """ Generate the columns and the whole dataset. """ data = {} words_total = {} for instance, words in self.raw_dataset.items(): words_item_total = {} for word in words: words_total.setdefault(word, 0) ...
[ "def", "columns_dataset", "(", "self", ")", ":", "data", "=", "{", "}", "words_total", "=", "{", "}", "for", "instance", ",", "words", "in", "self", ".", "raw_dataset", ".", "items", "(", ")", ":", "words_item_total", "=", "{", "}", "for", "word", "i...
34.36
0.002265
def is_scalar_nan(x): """Tests if x is NaN This function is meant to overcome the issue that np.isnan does not allow non-numerical types as input, and that np.nan is not np.float('nan'). Parameters ---------- x : any type Returns ------- boolean Examples -------- >>> is_s...
[ "def", "is_scalar_nan", "(", "x", ")", ":", "# convert from numpy.bool_ to python bool to ensure that testing", "# is_scalar_nan(x) is True does not fail.", "# Redondant np.floating is needed because numbers can't match np.float32", "# in python 2.", "return", "bool", "(", "isinstance", ...
26.724138
0.001245
def ir_instrs(self): """Get gadgets IR instructions. """ ir_instrs = [] for asm_instr in self._instrs: ir_instrs += asm_instr.ir_instrs return ir_instrs
[ "def", "ir_instrs", "(", "self", ")", ":", "ir_instrs", "=", "[", "]", "for", "asm_instr", "in", "self", ".", "_instrs", ":", "ir_instrs", "+=", "asm_instr", ".", "ir_instrs", "return", "ir_instrs" ]
22
0.009709
def from_image(cls, image, partname): """ Return an |ImagePart| instance newly created from *image* and assigned *partname*. """ return ImagePart(partname, image.content_type, image.blob, image)
[ "def", "from_image", "(", "cls", ",", "image", ",", "partname", ")", ":", "return", "ImagePart", "(", "partname", ",", "image", ".", "content_type", ",", "image", ".", "blob", ",", "image", ")" ]
38.166667
0.008547
def unserialize(cls, string, secret_key): """Load the secure cookie from a serialized string. :param string: the cookie value to unserialize. :param secret_key: the secret key used to serialize the cookie. :return: a new :class:`SecureCookie`. """ if isinstance(string, t...
[ "def", "unserialize", "(", "cls", ",", "string", ",", "secret_key", ")", ":", "if", "isinstance", "(", "string", ",", "text_type", ")", ":", "string", "=", "string", ".", "encode", "(", "'utf-8'", ",", "'replace'", ")", "if", "isinstance", "(", "secret_k...
38.339623
0.00144
def getChild(self, name, ns=None, default=None): """ Get a child by (optional) name and/or (optional) namespace. @param name: The name of a child element (may contain prefix). @type name: basestring @param ns: An optional namespace used to match the child. @type ns: (I{pr...
[ "def", "getChild", "(", "self", ",", "name", ",", "ns", "=", "None", ",", "default", "=", "None", ")", ":", "if", "self", ".", "__root", "is", "None", ":", "return", "default", "if", "ns", "is", "None", ":", "prefix", ",", "name", "=", "splitPrefix...
36.541667
0.002222
def disk_cache(basename, directory, method=False): """ Function decorator for caching pickleable return values on disk. Uses a hash computed from the function arguments for invalidation. If 'method', skip the first argument, usually being self or cls. The cache filepath is 'directory/basename-hash.p...
[ "def", "disk_cache", "(", "basename", ",", "directory", ",", "method", "=", "False", ")", ":", "directory", "=", "os", ".", "path", ".", "expanduser", "(", "directory", ")", "ensure_directory", "(", "directory", ")", "def", "wrapper", "(", "func", ")", "...
38.827586
0.000867
def _param_fields(kwargs, fields): """ Normalize the "fields" argument to most find methods """ if fields is None: return if type(fields) in [list, set, frozenset, tuple]: fields = {x: True for x in fields} if type(fields) == dict: fields.setdefault("_id", False) kwargs["projection"] = field...
[ "def", "_param_fields", "(", "kwargs", ",", "fields", ")", ":", "if", "fields", "is", "None", ":", "return", "if", "type", "(", "fields", ")", "in", "[", "list", ",", "set", ",", "frozenset", ",", "tuple", "]", ":", "fields", "=", "{", "x", ":", ...
28.272727
0.018692
def on(self): """ Turn all the output devices on. """ for device in self: if isinstance(device, (OutputDevice, CompositeOutputDevice)): device.on()
[ "def", "on", "(", "self", ")", ":", "for", "device", "in", "self", ":", "if", "isinstance", "(", "device", ",", "(", "OutputDevice", ",", "CompositeOutputDevice", ")", ")", ":", "device", ".", "on", "(", ")" ]
28.714286
0.009662
def strip_ansi(text, c1=False, osc=False): ''' Strip ANSI escape sequences from a portion of text. https://stackoverflow.com/a/38662876/450917 Arguments: line: str osc: bool - include OSC commands in the strippage. c1: bool - include C1 commands in the strippa...
[ "def", "strip_ansi", "(", "text", ",", "c1", "=", "False", ",", "osc", "=", "False", ")", ":", "text", "=", "ansi_csi0_finder", ".", "sub", "(", "''", ",", "text", ")", "if", "osc", ":", "text", "=", "ansi_osc0_finder", ".", "sub", "(", "''", ",", ...
36.608696
0.001157
def subst_dict(target, source): """Create a dictionary for substitution of special construction variables. This translates the following special arguments: target - the target (object or array of objects), used to generate the TARGET and TARGETS construction variables so...
[ "def", "subst_dict", "(", "target", ",", "source", ")", ":", "dict", "=", "{", "}", "if", "target", ":", "def", "get_tgt_subst_proxy", "(", "thing", ")", ":", "try", ":", "subst_proxy", "=", "thing", ".", "get_subst_proxy", "(", ")", "except", "Attribute...
35.546875
0.000855
def import_rsakey_from_public_pem(pem, scheme='rsassa-pss-sha256'): """ <Purpose> Generate an RSA key object from 'pem'. In addition, a keyid identifier for the RSA key is generated. The object returned conforms to 'securesystemslib.formats.RSAKEY_SCHEMA' and has the form: {'keytype': 'rsa', ...
[ "def", "import_rsakey_from_public_pem", "(", "pem", ",", "scheme", "=", "'rsassa-pss-sha256'", ")", ":", "# Does 'pem' have the correct format?", "# This check will ensure arguments has the appropriate number", "# of objects and object types, and that all dict keys are properly named.", "#...
36.470588
0.010678
def export_cairo(self, filepath, filetype): """Exports grid to the PDF file filepath Parameters ---------- filepath: String \tPath of file to export filetype in ["pdf", "svg"] \tType of file to export """ if cairo is None: return ...
[ "def", "export_cairo", "(", "self", ",", "filepath", ",", "filetype", ")", ":", "if", "cairo", "is", "None", ":", "return", "export_info", "=", "self", ".", "main_window", ".", "interfaces", ".", "get_cairo_export_info", "(", "filetype", ")", "if", "export_i...
30.430769
0.000979
def set_value(value_proto, value, exclude_from_indexes=None): """Set the corresponding datastore.Value _value field for the given arg. Args: value_proto: datastore.Value proto message. value: python object or datastore.Value. (unicode value will set a datastore string value, str value will set a bl...
[ "def", "set_value", "(", "value_proto", ",", "value", ",", "exclude_from_indexes", "=", "None", ")", ":", "value_proto", ".", "Clear", "(", ")", "if", "isinstance", "(", "value", ",", "(", "list", ",", "tuple", ")", ")", ":", "for", "sub_value", "in", ...
37.282609
0.009091
def _roc_multi(y_true, y_score, ax=None): """ Plot ROC curve for multi classification. Parameters ---------- y_true : array-like, shape = [n_samples, n_classes] Correct target values (ground truth). y_score : array-like, shape = [n_samples, n_classes] Target scores (estimator pr...
[ "def", "_roc_multi", "(", "y_true", ",", "y_score", ",", "ax", "=", "None", ")", ":", "# Compute micro-average ROC curve and ROC area", "fpr", ",", "tpr", ",", "_", "=", "roc_curve", "(", "y_true", ".", "ravel", "(", ")", ",", "y_score", ".", "ravel", "(",...
27.733333
0.001161
def jcrop_css(css_url=None): """Load jcrop css file. :param css_url: The custom CSS URL. """ if css_url is None: if current_app.config['AVATARS_SERVE_LOCAL']: css_url = url_for('avatars.static', filename='jcrop/css/jquery.Jcrop.min.css') else: ...
[ "def", "jcrop_css", "(", "css_url", "=", "None", ")", ":", "if", "css_url", "is", "None", ":", "if", "current_app", ".", "config", "[", "'AVATARS_SERVE_LOCAL'", "]", ":", "css_url", "=", "url_for", "(", "'avatars.static'", ",", "filename", "=", "'jcrop/css/j...
43.363636
0.008214
def jsonxs(data, expr, action=ACTION_GET, value=None, default=None): """ Get, set, delete values in a JSON structure. `expr` is a JSONpath-like expression pointing to the desired value. `action` determines the action to perform. See the module-level `ACTION_*` constants. `value` should be given if a...
[ "def", "jsonxs", "(", "data", ",", "expr", ",", "action", "=", "ACTION_GET", ",", "value", "=", "None", ",", "default", "=", "None", ")", ":", "tokens", "=", "tokenize", "(", "expr", ")", "# Walk through the list of tokens to reach the correct path in the data", ...
36
0.002404
def read(self, *args): """Handles raw client requests and distributes them to the appropriate components""" self.log("Beginning new transaction: ", args, lvl=network) try: sock, msg = args[0], args[1] user = password = client = clientuuid = useruuid = requestdata...
[ "def", "read", "(", "self", ",", "*", "args", ")", ":", "self", ".", "log", "(", "\"Beginning new transaction: \"", ",", "args", ",", "lvl", "=", "network", ")", "try", ":", "sock", ",", "msg", "=", "args", "[", "0", "]", ",", "args", "[", "1", "...
39.353535
0.001502
def prompt_for_value(self, ctx): """This is an alternative flow that can be activated in the full value processing if a value does not exist. It will prompt the user until a valid value exists and then returns the processed value as result. """ # Calculate the default be...
[ "def", "prompt_for_value", "(", "self", ",", "ctx", ")", ":", "# Calculate the default before prompting anything to be stable.", "default", "=", "self", ".", "get_default", "(", "ctx", ")", "if", "isinstance", "(", "default", ",", "AutoDefault", ")", ":", "return", ...
44.6
0.002195
def Dir(self, name, directory = None, create = True): """Look up or create a Dir node with the specified name. If the name is a relative path (begins with ./, ../, or a file name), then it is looked up relative to the supplied directory node, or to the top level directory of the FS (sup...
[ "def", "Dir", "(", "self", ",", "name", ",", "directory", "=", "None", ",", "create", "=", "True", ")", ":", "return", "self", ".", "_lookup", "(", "name", ",", "directory", ",", "Dir", ",", "create", ")" ]
49.363636
0.01085
def image(self): r""" Tuple with a CAPTCHA text and a Image object. Images are generated on the fly, using given text source, TTF font and other parameters passable through __init__. All letters in used text are morphed. Also a line is morphed and pased onto CAPTCHA text. ...
[ "def", "image", "(", "self", ")", ":", "text", "=", "self", ".", "text", "w", ",", "h", "=", "self", ".", "font", ".", "getsize", "(", "text", ")", "margin_x", "=", "round", "(", "self", ".", "margin_x", "*", "w", "/", "self", ".", "w", ")", ...
33.210526
0.00154
def visit_FromImport(self, node, frame): """Visit named imports.""" self.newline(node) self.write('included_template = %senvironment.get_template(' % (self.environment.is_async and 'await ' or '')) self.visit(node.template, frame) self.write(', %r).' % self.nam...
[ "def", "visit_FromImport", "(", "self", ",", "node", ",", "frame", ")", ":", "self", ".", "newline", "(", "node", ")", "self", ".", "write", "(", "'included_template = %senvironment.get_template('", "%", "(", "self", ".", "environment", ".", "is_async", "and",...
43.758621
0.001541
def _parse_allow(allow): ''' Convert firewall rule allowed user-string to specified REST API format. ''' # input=> tcp:53,tcp:80,tcp:443,icmp,tcp:4201,udp:53 # output<= [ # {"IPProtocol": "tcp", "ports": ["53","80","443","4201"]}, # {"IPProtocol": "icmp"}, # {"IPProtocol": "u...
[ "def", "_parse_allow", "(", "allow", ")", ":", "# input=> tcp:53,tcp:80,tcp:443,icmp,tcp:4201,udp:53", "# output<= [", "# {\"IPProtocol\": \"tcp\", \"ports\": [\"53\",\"80\",\"443\",\"4201\"]},", "# {\"IPProtocol\": \"icmp\"},", "# {\"IPProtocol\": \"udp\", \"ports\": [\"53\"]},", ...
34.285714
0.00081
def scripttag(self, url, path, filename, context): """ Renders a <script> tag for the JS file(s). """ if msettings['DOCTYPE'] == 'html5': markup = """<script src="%s"></script>""" else: markup = """<script type="text/javascript" charset="utf-8" src="%s"></...
[ "def", "scripttag", "(", "self", ",", "url", ",", "path", ",", "filename", ",", "context", ")", ":", "if", "msettings", "[", "'DOCTYPE'", "]", "==", "'html5'", ":", "markup", "=", "\"\"\"<script src=\"%s\"></script>\"\"\"", "else", ":", "markup", "=", "\"\"\...
45.888889
0.009501
def _get_reverse_relationships(opts): """ Returns an `OrderedDict` of field names to `RelationInfo`. """ # Note that we have a hack here to handle internal API differences for # this internal API across Django 1.7 -> Django 1.8. # See: https://code.djangoproject.com/ticket/24208 reverse_rel...
[ "def", "_get_reverse_relationships", "(", "opts", ")", ":", "# Note that we have a hack here to handle internal API differences for", "# this internal API across Django 1.7 -> Django 1.8.", "# See: https://code.djangoproject.com/ticket/24208", "reverse_relations", "=", "OrderedDict", "(", ...
38.918919
0.000678
def _eb_env_tags(envs, session_factory, retry): """Augment ElasticBeanstalk Environments with their tags.""" client = local_session(session_factory).client('elasticbeanstalk') def process_tags(eb_env): try: eb_env['Tags'] = retry( client.list_tags_for_resource, ...
[ "def", "_eb_env_tags", "(", "envs", ",", "session_factory", ",", "retry", ")", ":", "client", "=", "local_session", "(", "session_factory", ")", ".", "client", "(", "'elasticbeanstalk'", ")", "def", "process_tags", "(", "eb_env", ")", ":", "try", ":", "eb_en...
35.529412
0.001613
def copy(self, source_path, destination_path, threads=DEFAULT_THREADS, start_time=None, end_time=None, part_size=DEFAULT_PART_SIZE, **kwargs): """ Copy object(s) from one S3 location to another. Works for individual keys or entire directories. When files are larger than `part_size`,...
[ "def", "copy", "(", "self", ",", "source_path", ",", "destination_path", ",", "threads", "=", "DEFAULT_THREADS", ",", "start_time", "=", "None", ",", "end_time", "=", "None", ",", "part_size", "=", "DEFAULT_PART_SIZE", ",", "*", "*", "kwargs", ")", ":", "#...
61.68
0.009579
def create_shortcuts(self): """Create shortcuts for this file explorer.""" # Configurable copy_clipboard_file = config_shortcut(self.copy_file_clipboard, context='explorer', name='copy file', parent=...
[ "def", "create_shortcuts", "(", "self", ")", ":", "# Configurable\r", "copy_clipboard_file", "=", "config_shortcut", "(", "self", ".", "copy_file_clipboard", ",", "context", "=", "'explorer'", ",", "name", "=", "'copy file'", ",", "parent", "=", "self", ")", "pa...
62.315789
0.001664
def _init_map(self): """stub""" self.my_osid_object_form._my_map['confusedLearningObjectiveIds'] = \ self._confused_learning_objectives_metadata['default_list_values'][0] self.my_osid_object_form._my_map['feedback'] = \ self._feedback_metadata['default_string_values'][0]
[ "def", "_init_map", "(", "self", ")", ":", "self", ".", "my_osid_object_form", ".", "_my_map", "[", "'confusedLearningObjectiveIds'", "]", "=", "self", ".", "_confused_learning_objectives_metadata", "[", "'default_list_values'", "]", "[", "0", "]", "self", ".", "m...
52.333333
0.009404
def get_random_user(self): """ Gets a random user from the provider :returns: Dictionary """ from provider.models import User u = User.objects.order_by('?')[0] return {"username": u.username, "password": u.password, "fullname": u.fullname}
[ "def", "get_random_user", "(", "self", ")", ":", "from", "provider", ".", "models", "import", "User", "u", "=", "User", ".", "objects", ".", "order_by", "(", "'?'", ")", "[", "0", "]", "return", "{", "\"username\"", ":", "u", ".", "username", ",", "\...
32
0.010135
def pluck(self, value, key=None): """ Get a list with the values of a given key. :rtype: Collection """ if key: return dict(map(lambda x: (data_get(x, key), data_get(x, value)), self.items)) else: results = list(map(lambda x: data_get(x, value), s...
[ "def", "pluck", "(", "self", ",", "value", ",", "key", "=", "None", ")", ":", "if", "key", ":", "return", "dict", "(", "map", "(", "lambda", "x", ":", "(", "data_get", "(", "x", ",", "key", ")", ",", "data_get", "(", "x", ",", "value", ")", "...
30
0.008086
def addActionFinish(self): """ Indicates all callbacks that should run within the action's context have been added, and that the action should therefore finish once those callbacks have fired. @return: The wrapped L{Deferred}. @raises AlreadyFinished: L{DeferredContext....
[ "def", "addActionFinish", "(", "self", ")", ":", "if", "self", ".", "_finishAdded", ":", "raise", "AlreadyFinished", "(", ")", "self", ".", "_finishAdded", "=", "True", "def", "done", "(", "result", ")", ":", "if", "isinstance", "(", "result", ",", "Fail...
31.68
0.002451
def as_tuple(self): """ :rtype: (str, object) """ if self._as_tuple is None: self._as_tuple = self.converted.items()[0] return self._as_tuple
[ "def", "as_tuple", "(", "self", ")", ":", "if", "self", ".", "_as_tuple", "is", "None", ":", "self", ".", "_as_tuple", "=", "self", ".", "converted", ".", "items", "(", ")", "[", "0", "]", "return", "self", ".", "_as_tuple" ]
26.714286
0.010363
def _extract_reason(kw): """ Internal helper. Extracts a reason (possibly both reasons!) from the kwargs for a circuit failed or closed event. """ try: # we "often" have a REASON reason = kw['REASON'] try: # ...and sometimes even have a REMOTE_REASON r...
[ "def", "_extract_reason", "(", "kw", ")", ":", "try", ":", "# we \"often\" have a REASON", "reason", "=", "kw", "[", "'REASON'", "]", "try", ":", "# ...and sometimes even have a REMOTE_REASON", "reason", "=", "'{}, {}'", ".", "format", "(", "reason", ",", "kw", ...
32.25
0.001883
def _create_controller_info_record(self, controller_module_name): """Creates controller info record for a particular controller type. Info is retrieved from all the controller objects spawned from the specified module, using the controller module's `get_info` function. Args: ...
[ "def", "_create_controller_info_record", "(", "self", ",", "controller_module_name", ")", ":", "module", "=", "self", ".", "_controller_modules", "[", "controller_module_name", "]", "controller_info", "=", "None", "try", ":", "controller_info", "=", "module", ".", "...
44.71875
0.001368
def _bottleneck_residual(self, x, in_filter, out_filter, stride, activate_before_residual=False): """Bottleneck residual unit with 3 sub layers.""" if activate_before_residual: with tf.variable_scope('common_bn_relu'): x = self._layer_norm('init_bn', x) x = self....
[ "def", "_bottleneck_residual", "(", "self", ",", "x", ",", "in_filter", ",", "out_filter", ",", "stride", ",", "activate_before_residual", "=", "False", ")", ":", "if", "activate_before_residual", ":", "with", "tf", ".", "variable_scope", "(", "'common_bn_relu'", ...
35.583333
0.009878
def do(self, resource, method, params=None, data=None, json=None, headers=None): """Does the request job Args: resource(str): resource uri(relative path) method(str): HTTP method params(dict): uri quer...
[ "def", "do", "(", "self", ",", "resource", ",", "method", ",", "params", "=", "None", ",", "data", "=", "None", ",", "json", "=", "None", ",", "headers", "=", "None", ")", ":", "uri", "=", "\"{0}/{1}\"", ".", "format", "(", "self", ".", "_api_base"...
24.675676
0.00843