text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def typecast(type_, value): """ Tries to smartly typecast the given value with the given type. :param type_: The type to try to use for the given value :param value: The value to try and typecast to the given type :return: The typecasted value if possible, otherwise just the original value """ ...
[ "def", "typecast", "(", "type_", ",", "value", ")", ":", "# NOTE: does not do any special validation of types before casting", "# will just raise errors on type casting failures", "if", "is_builtin_type", "(", "type_", ")", "or", "is_collections_type", "(", "type_", ")", "or"...
37.478261
16.978261
def autoconf(self): """Implements Munin Plugin Auto-Configuration Option. @return: True if plugin can be auto-configured, False otherwise. """ opcinfo = OPCinfo(self._host, self._port, self._user, self._password, self._monpath, self....
[ "def", "autoconf", "(", "self", ")", ":", "opcinfo", "=", "OPCinfo", "(", "self", ".", "_host", ",", "self", ".", "_port", ",", "self", ".", "_user", ",", "self", ".", "_password", ",", "self", ".", "_monpath", ",", "self", ".", "_ssl", ")", "retur...
39.111111
18.222222
def owns_endpoint(self, endpoint): """Tests if an endpoint name (not path) belongs to this Api. Takes in to account the Blueprint name part of the endpoint name. :param endpoint: The name of the endpoint being checked :return: bool """ if self.blueprint: if...
[ "def", "owns_endpoint", "(", "self", ",", "endpoint", ")", ":", "if", "self", ".", "blueprint", ":", "if", "endpoint", ".", "startswith", "(", "self", ".", "blueprint", ".", "name", ")", ":", "endpoint", "=", "endpoint", ".", "split", "(", "self", ".",...
36.714286
18.285714
def write_array_empty(self, key, value): """ write a 0-len array """ # ugly hack for length 0 axes arr = np.empty((1,) * value.ndim) self._handle.create_array(self.group, key, arr) getattr(self.group, key)._v_attrs.value_type = str(value.dtype) getattr(self.group, key)._...
[ "def", "write_array_empty", "(", "self", ",", "key", ",", "value", ")", ":", "# ugly hack for length 0 axes", "arr", "=", "np", ".", "empty", "(", "(", "1", ",", ")", "*", "value", ".", "ndim", ")", "self", ".", "_handle", ".", "create_array", "(", "se...
42.5
13.875
def subs(self, path): """ Search the strings in a config file for a substitutable value, e.g. "morphologies_dir": "$COMPONENT_DIR/morphologies", """ #print_v('Checking for: \n %s, \n %s \n in %s'%(self.substitutes,self.init_substitutes,path)) if type(path) == ...
[ "def", "subs", "(", "self", ",", "path", ")", ":", "#print_v('Checking for: \\n %s, \\n %s \\n in %s'%(self.substitutes,self.init_substitutes,path))", "if", "type", "(", "path", ")", "==", "int", "or", "type", "(", "path", ")", "==", "float", ":", "return", "path...
42.117647
15.882353
def compose_layer(layer, force=False, **kwargs): """Compose a single layer with pixels.""" from PIL import Image, ImageChops assert layer.bbox != (0, 0, 0, 0), 'Layer bbox is (0, 0, 0, 0)' image = layer.topil(**kwargs) if image is None or force: texture = create_fill(layer) if textu...
[ "def", "compose_layer", "(", "layer", ",", "force", "=", "False", ",", "*", "*", "kwargs", ")", ":", "from", "PIL", "import", "Image", ",", "ImageChops", "assert", "layer", ".", "bbox", "!=", "(", "0", ",", "0", ",", "0", ",", "0", ")", ",", "'La...
34.830769
16.6
def main(): """Program entry point. """ global cf_verbose, cf_show_comment, cf_charset global cf_extract, cf_test_read, cf_test_unrar global cf_test_memory psw = None # parse args try: opts, args = getopt.getopt(sys.argv[1:], 'p:C:hvcxtRM') except getopt.error as ex: ...
[ "def", "main", "(", ")", ":", "global", "cf_verbose", ",", "cf_show_comment", ",", "cf_charset", "global", "cf_extract", ",", "cf_test_read", ",", "cf_test_unrar", "global", "cf_test_memory", "psw", "=", "None", "# parse args", "try", ":", "opts", ",", "args", ...
22.931034
19.137931
def from_json_path(path: str, check_version: bool = True) -> BELGraph: """Build a graph from a file containing Node-Link JSON.""" with open(os.path.expanduser(path)) as f: return from_json_file(f, check_version=check_version)
[ "def", "from_json_path", "(", "path", ":", "str", ",", "check_version", ":", "bool", "=", "True", ")", "->", "BELGraph", ":", "with", "open", "(", "os", ".", "path", ".", "expanduser", "(", "path", ")", ")", "as", "f", ":", "return", "from_json_file", ...
59.5
14
def SlideShapeFactory(shape_elm, parent): """ Return an instance of the appropriate shape proxy class for *shape_elm* on a slide. """ if shape_elm.has_ph_elm: return _SlidePlaceholderFactory(shape_elm, parent) return BaseShapeFactory(shape_elm, parent)
[ "def", "SlideShapeFactory", "(", "shape_elm", ",", "parent", ")", ":", "if", "shape_elm", ".", "has_ph_elm", ":", "return", "_SlidePlaceholderFactory", "(", "shape_elm", ",", "parent", ")", "return", "BaseShapeFactory", "(", "shape_elm", ",", "parent", ")" ]
34.625
12.125
def delete_sequence_rule(self, sequence_rule_id): """Deletes a ``SequenceRule``. arg: sequence_rule_id (osid.id.Id): the ``Id`` of the ``SequenceRule`` to remove raise: NotFound - ``sequence_rule_id`` not found raise: NullArgument - ``sequence_rule_id`` is ``null`` ...
[ "def", "delete_sequence_rule", "(", "self", ",", "sequence_rule_id", ")", ":", "# Implemented from template for", "# osid.resource.ResourceAdminSession.delete_resource_template", "collection", "=", "JSONClientValidated", "(", "'assessment_authoring'", ",", "collection", "=", "'Se...
51.8
22.72
def find_enclosing_bracket_left(self, left_ch, right_ch, start_pos=None): """ Find the left bracket enclosing current position. Return the relative position to the cursor position. When `start_pos` is given, don't look past the position. """ if self.current_char == left_...
[ "def", "find_enclosing_bracket_left", "(", "self", ",", "left_ch", ",", "right_ch", ",", "start_pos", "=", "None", ")", ":", "if", "self", ".", "current_char", "==", "left_ch", ":", "return", "0", "if", "start_pos", "is", "None", ":", "start_pos", "=", "0"...
27.321429
19.892857
def to_igraph(self, attribute="weight", **kwargs): """Convert to an igraph Graph Uses the igraph.Graph.Weighted_Adjacency constructor Parameters ---------- attribute : str, optional (default: "weight") kwargs : additional arguments for igraph.Graph.Weighted_Adjacency ...
[ "def", "to_igraph", "(", "self", ",", "attribute", "=", "\"weight\"", ",", "*", "*", "kwargs", ")", ":", "try", ":", "import", "igraph", "as", "ig", "except", "ImportError", ":", "raise", "ImportError", "(", "\"Please install igraph with \"", "\"`pip install --u...
35.608696
18.73913
def DbGetDeviceInfo(self, argin): """ Returns info from DbImportDevice and started/stopped dates. :param argin: Device name :type: tango.DevString :return: Str[0] = Device name Str[1] = CORBA IOR Str[2] = Device version Str[3] = Device Server name Str[4] ...
[ "def", "DbGetDeviceInfo", "(", "self", ",", "argin", ")", ":", "self", ".", "_log", ".", "debug", "(", "\"In DbGetDeviceInfo()\"", ")", "ret", ",", "dev_name", ",", "dfm", "=", "check_device_name", "(", "argin", ")", "if", "not", "ret", ":", "th_exc", "(...
39.32
14.68
def get_CrossCatClient(client_type, **kwargs): """Helper which instantiates the appropriate Engine and returns a Client""" client = None if client_type == 'local': import crosscat.LocalEngine as LocalEngine le = LocalEngine.LocalEngine(**kwargs) client = CrossCatClient(le) elif...
[ "def", "get_CrossCatClient", "(", "client_type", ",", "*", "*", "kwargs", ")", ":", "client", "=", "None", "if", "client_type", "==", "'local'", ":", "import", "crosscat", ".", "LocalEngine", "as", "LocalEngine", "le", "=", "LocalEngine", ".", "LocalEngine", ...
33.722222
20.111111
def transform_lattice(self, lattice): # type: (Lattice) -> Lattice """ Takes a Lattice object and transforms it. :param lattice: Lattice :return: """ return Lattice(np.matmul(lattice.matrix, self.P))
[ "def", "transform_lattice", "(", "self", ",", "lattice", ")", ":", "# type: (Lattice) -> Lattice", "return", "Lattice", "(", "np", ".", "matmul", "(", "lattice", ".", "matrix", ",", "self", ".", "P", ")", ")" ]
31.125
8.125
def plotlyviz( scomplex, colorscale=None, title="Kepler Mapper", graph_layout="kk", color_function=None, color_function_name=None, dashboard=False, graph_data=False, factor_size=3, edge_linewidth=1.5, node_linecolor="rgb(200,200,200)", width=600, height=5...
[ "def", "plotlyviz", "(", "scomplex", ",", "colorscale", "=", "None", ",", "title", "=", "\"Kepler Mapper\"", ",", "graph_layout", "=", "\"kk\"", ",", "color_function", "=", "None", ",", "color_function_name", "=", "None", ",", "dashboard", "=", "False", ",", ...
32.880795
23.993377
def serial_number(self, serial_number): """ Sets the serial_number of this DeviceDataPostRequest. The serial number of the device. :param serial_number: The serial_number of this DeviceDataPostRequest. :type: str """ if serial_number is not None and len(serial_nu...
[ "def", "serial_number", "(", "self", ",", "serial_number", ")", ":", "if", "serial_number", "is", "not", "None", "and", "len", "(", "serial_number", ")", ">", "64", ":", "raise", "ValueError", "(", "\"Invalid value for `serial_number`, length must be less than or equa...
39.5
21.5
def recv(self, timeout=None): """Receive, optionally with *timeout* in seconds. """ if timeout: timeout *= 1000. for sub in list(self.subscribers) + self._hooks: self.poller.register(sub, POLLIN) self._loop = True try: while self._loop...
[ "def", "recv", "(", "self", ",", "timeout", "=", "None", ")", ":", "if", "timeout", ":", "timeout", "*=", "1000.", "for", "sub", "in", "list", "(", "self", ".", "subscribers", ")", "+", "self", ".", "_hooks", ":", "self", ".", "poller", ".", "regis...
44.131579
19.078947
def register_listener(self, listener, interesting, active): """Register an event listener. To avoid system overload, the VirtualBox server process checks if passive event listeners call :py:func:`IEventSource.get_event` frequently enough. In the current implementation,...
[ "def", "register_listener", "(", "self", ",", "listener", ",", "interesting", ",", "active", ")", ":", "if", "not", "isinstance", "(", "listener", ",", "IEventListener", ")", ":", "raise", "TypeError", "(", "\"listener can only be an instance of type IEventListener\""...
52.95
27.225
def from_cli(cls, opts): """Loads a config file from the given options, with overrides and deletes applied. """ # read configuration file logging.info("Reading configuration file") if opts.config_overrides is not None: overrides = [override.split(":") ...
[ "def", "from_cli", "(", "cls", ",", "opts", ")", ":", "# read configuration file", "logging", ".", "info", "(", "\"Reading configuration file\"", ")", "if", "opts", ".", "config_overrides", "is", "not", "None", ":", "overrides", "=", "[", "override", ".", "spl...
39.5625
14.1875
def load(cls, context_id, persistence_engine=None): """Load and instantiate a Context from the persistence_engine.""" if not persistence_engine: from furious.config import get_default_persistence_engine persistence_engine = get_default_persistence_engine() if not persist...
[ "def", "load", "(", "cls", ",", "context_id", ",", "persistence_engine", "=", "None", ")", ":", "if", "not", "persistence_engine", ":", "from", "furious", ".", "config", "import", "get_default_persistence_engine", "persistence_engine", "=", "get_default_persistence_en...
44.454545
19.818182
def rgbmap_cb(self, rgbmap, channel): """ This method is called when the RGBMap is changed. We update the ColorBar to match. """ if not self.gui_up: return fitsimage = channel.fitsimage if fitsimage != self.fv.getfocus_fitsimage(): return ...
[ "def", "rgbmap_cb", "(", "self", ",", "rgbmap", ",", "channel", ")", ":", "if", "not", "self", ".", "gui_up", ":", "return", "fitsimage", "=", "channel", ".", "fitsimage", "if", "fitsimage", "!=", "self", ".", "fv", ".", "getfocus_fitsimage", "(", ")", ...
32.545455
10
def _set(self, data, version): """serialize and set data to self.path.""" self.zk.set(self.path, json.dumps(data), version)
[ "def", "_set", "(", "self", ",", "data", ",", "version", ")", ":", "self", ".", "zk", ".", "set", "(", "self", ".", "path", ",", "json", ".", "dumps", "(", "data", ")", ",", "version", ")" ]
34.25
16.75
def matches(self,string,fuzzy=90,fname_match=True,fuzzy_fragment=None,guess=False): '''Returns whether this :class:`Concept` matches ``string``''' matches = [] for item in self.examples: m = best_match_from_list(string,self.examples[item],fuzzy,fname_match,fuzzy_fragment,gue...
[ "def", "matches", "(", "self", ",", "string", ",", "fuzzy", "=", "90", ",", "fname_match", "=", "True", ",", "fuzzy_fragment", "=", "None", ",", "guess", "=", "False", ")", ":", "matches", "=", "[", "]", "for", "item", "in", "self", ".", "examples", ...
41.3125
15.9375
def set_cookie(self, name: str, value: str, *, expires: Optional[str]=None, domain: Optional[str]=None, max_age: Optional[Union[int, str]]=None, path: str='/', secure: Optional[str]=None, httponly: Optional...
[ "def", "set_cookie", "(", "self", ",", "name", ":", "str", ",", "value", ":", "str", ",", "*", ",", "expires", ":", "Optional", "[", "str", "]", "=", "None", ",", "domain", ":", "Optional", "[", "str", "]", "=", "None", ",", "max_age", ":", "Opti...
31.162791
14.883721
def validate_positive_float(option, value): """Validates that 'value' is a float, or can be converted to one, and is positive. """ errmsg = "%s must be an integer or float" % (option,) try: value = float(value) except ValueError: raise ValueError(errmsg) except TypeError: ...
[ "def", "validate_positive_float", "(", "option", ",", "value", ")", ":", "errmsg", "=", "\"%s must be an integer or float\"", "%", "(", "option", ",", ")", "try", ":", "value", "=", "float", "(", "value", ")", "except", "ValueError", ":", "raise", "ValueError"...
36
17.944444
def _set_view(self): """Assign a view to current graph""" if self.logarithmic: view_class = PolarThetaLogView else: view_class = PolarThetaView self.view = view_class( self.width - self.margin_box.x, self.height - self.margin_box.y, self._...
[ "def", "_set_view", "(", "self", ")", ":", "if", "self", ".", "logarithmic", ":", "view_class", "=", "PolarThetaLogView", "else", ":", "view_class", "=", "PolarThetaView", "self", ".", "view", "=", "view_class", "(", "self", ".", "width", "-", "self", ".",...
29.363636
17.909091
def merge(self, po_file, source_files): """从源码中获取所有条目,合并到 po_file 中。 :param string po_file: 待写入的 po 文件路径。 :param list source_files : 所有待处理的原文件路径 list。 """ # Create a temporary file to write pot file pot_file = tempfile.NamedTemporaryFile(mode='wb', prefix='rookout_', d...
[ "def", "merge", "(", "self", ",", "po_file", ",", "source_files", ")", ":", "# Create a temporary file to write pot file", "pot_file", "=", "tempfile", ".", "NamedTemporaryFile", "(", "mode", "=", "'wb'", ",", "prefix", "=", "'rookout_'", ",", "delete", "=", "Fa...
39.724138
12.586207
def annotate_rule_violation(self, rule: ValidationRule) -> None: """ Takes note of a rule validation failure by collecting its error message. :param rule: Rule that failed validation. :type rule: ValidationRule :return: None """ if self.errors.get(rule.label) is ...
[ "def", "annotate_rule_violation", "(", "self", ",", "rule", ":", "ValidationRule", ")", "->", "None", ":", "if", "self", ".", "errors", ".", "get", "(", "rule", ".", "label", ")", "is", "None", ":", "self", ".", "errors", "[", "rule", ".", "label", "...
38.272727
15.363636
def appendtextindex(table, index_or_dirname, indexname=None, merge=True, optimize=False): """ Load all rows from `table` into a Whoosh index, adding them to any existing data in the index. Keyword arguments: table A table container with the data to be loaded. index_...
[ "def", "appendtextindex", "(", "table", ",", "index_or_dirname", ",", "indexname", "=", "None", ",", "merge", "=", "True", ",", "optimize", "=", "False", ")", ":", "import", "whoosh", ".", "index", "# deal with polymorphic argument", "if", "isinstance", "(", "...
29.098039
20.980392
def execute(self): """Output environment name.""" # Disable other runway logging so the only response is the env name logging.getLogger('runway').setLevel(logging.ERROR) # This may be invoked from a module directory in an environment; # account for that here if necessary ...
[ "def", "execute", "(", "self", ")", ":", "# Disable other runway logging so the only response is the env name", "logging", ".", "getLogger", "(", "'runway'", ")", ".", "setLevel", "(", "logging", ".", "ERROR", ")", "# This may be invoked from a module directory in an environm...
40.333333
22.333333
def __update_interval(self): """ highlight the current line """ self.update() self.after_id = self.text.after(250, self.__update_interval)
[ "def", "__update_interval", "(", "self", ")", ":", "self", ".", "update", "(", ")", "self", ".", "after_id", "=", "self", ".", "text", ".", "after", "(", "250", ",", "self", ".", "__update_interval", ")" ]
39.75
14.75
def draw(self, X, y, **kwargs): """ Called from the fit method, this method creates the parallel coordinates canvas and draws each instance and vertical lines on it. Parameters ---------- X : ndarray of shape n x m A matrix of n instances with m features ...
[ "def", "draw", "(", "self", ",", "X", ",", "y", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "fast", ":", "return", "self", ".", "draw_classes", "(", "X", ",", "y", ",", "*", "*", "kwargs", ")", "return", "self", ".", "draw_instances", ...
30.25
19.75
def update(self, params, ignore_set=False, overwrite=False): """Set instance values from dictionary. :param dict params: Click context params. :param bool ignore_set: Skip already-set values instead of raising AttributeError. :param bool overwrite: Allow overwriting already-set values. ...
[ "def", "update", "(", "self", ",", "params", ",", "ignore_set", "=", "False", ",", "overwrite", "=", "False", ")", ":", "log", "=", "logging", ".", "getLogger", "(", "__name__", ")", "valid", "=", "{", "i", "[", "0", "]", "for", "i", "in", "self", ...
51.541667
19.791667
def _hexdecode(hexstring): """Convert a hex encoded string to a byte string. For example '4A' will return 'J', and '04' will return ``'\\x04'`` (which has length 1). Args: hexstring (str): Can be for example 'A3' or 'A3B4'. Must be of even length. Allowed characters are '0' to '9', 'a' to ...
[ "def", "_hexdecode", "(", "hexstring", ")", ":", "# Note: For Python3 the appropriate would be: raise TypeError(new_error_message) from err", "# but the Python2 interpreter will indicate SyntaxError.", "# Thus we need to live with this warning in Python3:", "# 'During handling of the above excepti...
39.205128
29.974359
async def async_get_image_names(self): """ Parse web server camera view for camera image names """ cookies = self.get_session_cookie() try: async with aiohttp.ClientSession(cookies=cookies) as session: resp = await session.get( ...
[ "async", "def", "async_get_image_names", "(", "self", ")", ":", "cookies", "=", "self", ".", "get_session_cookie", "(", ")", "try", ":", "async", "with", "aiohttp", ".", "ClientSession", "(", "cookies", "=", "cookies", ")", "as", "session", ":", "resp", "=...
43.757576
15.515152
def _write_to_graph(self): """Write the coverage results to a graph""" traces = [] for byte_code, trace_data in self.coverage.items(): traces += [list(trace_data.keys()), list(trace_data.values()), "r--"] plt.plot(*traces) plt.axis([0, self.end - self.begin, 0, 100])...
[ "def", "_write_to_graph", "(", "self", ")", ":", "traces", "=", "[", "]", "for", "byte_code", ",", "trace_data", "in", "self", ".", "coverage", ".", "items", "(", ")", ":", "traces", "+=", "[", "list", "(", "trace_data", ".", "keys", "(", ")", ")", ...
36.916667
17.666667
def find_proc_date(header): """Search the HISTORY fields of a header looking for the FLIPS processing date. """ import string, re for h in header.ascardlist(): if h.key=="HISTORY": g=h.value if ( string.find(g,'FLIPS 1.0 -:') ): result=re.search('imred...
[ "def", "find_proc_date", "(", "header", ")", ":", "import", "string", ",", "re", "for", "h", "in", "header", ".", "ascardlist", "(", ")", ":", "if", "h", ".", "key", "==", "\"HISTORY\"", ":", "g", "=", "h", ".", "value", "if", "(", "string", ".", ...
35.25
12.4375
async def save(self): """ Persists the model to the database. If the model holds no primary key, a new one will automatically created by RethinkDB. Otherwise it will overwrite the current model persisted to the database. """ if hasattr(self, "before_save"): s...
[ "async", "def", "save", "(", "self", ")", ":", "if", "hasattr", "(", "self", ",", "\"before_save\"", ")", ":", "self", ".", "before_save", "(", ")", "query", "=", "r", ".", "table", "(", "self", ".", "table_name", ")", "if", "self", ".", "_state", ...
29.861111
19.083333
def setup_tempdir(dir, models, wav, alphabet, lm_binary, trie, binaries): r''' Copy models, libs and binary to a directory (new one if dir is None) ''' if dir is None: dir = tempfile.mkdtemp(suffix='dsbench') sorted_models = all_files(models=models) if binaries is None: maybe_do...
[ "def", "setup_tempdir", "(", "dir", ",", "models", ",", "wav", ",", "alphabet", ",", "lm_binary", ",", "trie", ",", "binaries", ")", ":", "if", "dir", "is", "None", ":", "dir", "=", "tempfile", ".", "mkdtemp", "(", "suffix", "=", "'dsbench'", ")", "s...
38.078947
21.815789
def hil_state_encode(self, time_usec, roll, pitch, yaw, rollspeed, pitchspeed, yawspeed, lat, lon, alt, vx, vy, vz, xacc, yacc, zacc): ''' DEPRECATED PACKET! Suffers from missing airspeed fields and singularities due to Euler angles. Please use HIL_STATE_Q...
[ "def", "hil_state_encode", "(", "self", ",", "time_usec", ",", "roll", ",", "pitch", ",", "yaw", ",", "rollspeed", ",", "pitchspeed", ",", "yawspeed", ",", "lat", ",", "lon", ",", "alt", ",", "vx", ",", "vy", ",", "vz", ",", "xacc", ",", "yacc", ",...
77.481481
46.518519
def length(self, t0=0, t1=1, error=LENGTH_ERROR, min_depth=LENGTH_MIN_DEPTH): """Calculate the length of the path up to a certain position""" if t0 == 0 and t1 == 1: if self._length_info['bpoints'] == self.bpoints() \ and self._length_info['error'] >= error \ ...
[ "def", "length", "(", "self", ",", "t0", "=", "0", ",", "t1", "=", "1", ",", "error", "=", "LENGTH_ERROR", ",", "min_depth", "=", "LENGTH_MIN_DEPTH", ")", ":", "if", "t0", "==", "0", "and", "t1", "==", "1", ":", "if", "self", ".", "_length_info", ...
44.416667
18.541667
def get_immediate_children(self): """ Return all direct subsidiaries of this company. Excludes subsidiaries of subsidiaries """ ownership = Ownership.objects.filter(parent=self) subsidiaries = Company.objects.filter(child__in=ownership).distinct() return subsidiar...
[ "def", "get_immediate_children", "(", "self", ")", ":", "ownership", "=", "Ownership", ".", "objects", ".", "filter", "(", "parent", "=", "self", ")", "subsidiaries", "=", "Company", ".", "objects", ".", "filter", "(", "child__in", "=", "ownership", ")", "...
39.5
11.75
def log_fault_exc_str (exc, # pylint: disable=W0613 message = "", level = logging.CRITICAL, traceback = False): """Make a StringIO of the usual traceback information, followed by a listing of all the local variables in each frame. """ return log_fault_info_str (sys....
[ "def", "log_fault_exc_str", "(", "exc", ",", "# pylint: disable=W0613", "message", "=", "\"\"", ",", "level", "=", "logging", ".", "CRITICAL", ",", "traceback", "=", "False", ")", ":", "return", "log_fault_info_str", "(", "sys", ".", "exc_info", "(", ")", ",...
51.375
12
def maybe_automatically_publish_drafts_on_save(sender, instance, **kwargs): """ If automatic publishing is enabled, immediately publish a draft copy after it has been saved. """ # Skip processing if auto-publishing is not enabled if not is_automatic_publishing_enabled(sender): return ...
[ "def", "maybe_automatically_publish_drafts_on_save", "(", "sender", ",", "instance", ",", "*", "*", "kwargs", ")", ":", "# Skip processing if auto-publishing is not enabled", "if", "not", "is_automatic_publishing_enabled", "(", "sender", ")", ":", "return", "# Skip missing ...
35.473684
16.210526
def set_session(self, cookies): """ sets the cookies (should be a dictionary) """ self.__session.cookies = requests.utils.cookiejar_from_dict(cookies)
[ "def", "set_session", "(", "self", ",", "cookies", ")", ":", "self", ".", "__session", ".", "cookies", "=", "requests", ".", "utils", ".", "cookiejar_from_dict", "(", "cookies", ")" ]
35.6
10.8
def from_random(self, power, gm, r0, omega=None, function='geoid', lmax=None, normalization='4pi', csphase=1, exact_power=False): """ Initialize the class of gravitational potential spherical harmonic coefficients as random variables with a given spectrum....
[ "def", "from_random", "(", "self", ",", "power", ",", "gm", ",", "r0", ",", "omega", "=", "None", ",", "function", "=", "'geoid'", ",", "lmax", "=", "None", ",", "normalization", "=", "'4pi'", ",", "csphase", "=", "1", ",", "exact_power", "=", "False...
43.770701
22.356688
def check_load_privatekey_callback(self): """ Call the function with an encrypted PEM and a passphrase callback. """ for i in xrange(self.iterations * 10): load_privatekey( FILETYPE_PEM, self.ENCRYPTED_PEM, lambda *args: "hello, secret")
[ "def", "check_load_privatekey_callback", "(", "self", ")", ":", "for", "i", "in", "xrange", "(", "self", ".", "iterations", "*", "10", ")", ":", "load_privatekey", "(", "FILETYPE_PEM", ",", "self", ".", "ENCRYPTED_PEM", ",", "lambda", "*", "args", ":", "\"...
41.571429
13.285714
def on_menu_save_interpretation(self, event): ''' save interpretations to a redo file ''' thellier_gui_redo_file = open( os.path.join(self.WD, "thellier_GUI.redo"), 'w') #-------------------------------------------------- # write interpretations to thellier...
[ "def", "on_menu_save_interpretation", "(", "self", ",", "event", ")", ":", "thellier_gui_redo_file", "=", "open", "(", "os", ".", "path", ".", "join", "(", "self", ".", "WD", ",", "\"thellier_GUI.redo\"", ")", ",", "'w'", ")", "#---------------------------------...
37.666667
19.121212
def CMYK_to_CMY(cobj, *args, **kwargs): """ Converts CMYK to CMY. NOTE: CMYK and CMY values range from 0.0 to 1.0 """ cmy_c = cobj.cmyk_c * (1.0 - cobj.cmyk_k) + cobj.cmyk_k cmy_m = cobj.cmyk_m * (1.0 - cobj.cmyk_k) + cobj.cmyk_k cmy_y = cobj.cmyk_y * (1.0 - cobj.cmyk_k) + cobj.cmyk_k ...
[ "def", "CMYK_to_CMY", "(", "cobj", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "cmy_c", "=", "cobj", ".", "cmyk_c", "*", "(", "1.0", "-", "cobj", ".", "cmyk_k", ")", "+", "cobj", ".", "cmyk_k", "cmy_m", "=", "cobj", ".", "cmyk_m", "*", ...
31.454545
14.909091
def element_should_be_visible(self, locator, loglevel='INFO'): """Verifies that element identified with locator is visible. Key attributes for arbitrary elements are `id` and `name`. See `introduction` for details about locating elements. New in AppiumLibrary 1.4....
[ "def", "element_should_be_visible", "(", "self", ",", "locator", ",", "loglevel", "=", "'INFO'", ")", ":", "if", "not", "self", ".", "_element_find", "(", "locator", ",", "True", ",", "True", ")", ".", "is_displayed", "(", ")", ":", "self", ".", "log_sou...
46.75
18.166667
def click_on_label(step, label): """ Click on a label """ with AssertContextManager(step): elem = world.browser.find_element_by_xpath(str( '//label[normalize-space(text()) = "%s"]' % label)) elem.click()
[ "def", "click_on_label", "(", "step", ",", "label", ")", ":", "with", "AssertContextManager", "(", "step", ")", ":", "elem", "=", "world", ".", "browser", ".", "find_element_by_xpath", "(", "str", "(", "'//label[normalize-space(text()) = \"%s\"]'", "%", "label", ...
26.666667
14.444444
def send(token, title, **kwargs): """ Site: https://boxcar.io/ API: http://help.boxcar.io/knowledgebase/topics/48115-boxcar-api Desc: Best app for system administrators """ headers = { "Content-type": "application/x-www-form-urlencoded", "User-Agent": "DBMail/%s" % get_version(),...
[ "def", "send", "(", "token", ",", "title", ",", "*", "*", "kwargs", ")", ":", "headers", "=", "{", "\"Content-type\"", ":", "\"application/x-www-form-urlencoded\"", ",", "\"User-Agent\"", ":", "\"DBMail/%s\"", "%", "get_version", "(", ")", ",", "}", "data", ...
28
17.666667
def graph(data, src_lat, src_lon, dest_lat, dest_lon, linewidth=1, alpha=220, color='hot'): """Create a graph drawing a line between each pair of (src_lat, src_lon) and (dest_lat, dest_lon) :param data: data access object :param src_lat: field name of source latitude :param src_lon: field name of sourc...
[ "def", "graph", "(", "data", ",", "src_lat", ",", "src_lon", ",", "dest_lat", ",", "dest_lon", ",", "linewidth", "=", "1", ",", "alpha", "=", "220", ",", "color", "=", "'hot'", ")", ":", "from", "geoplotlib", ".", "layers", "import", "GraphLayer", "_gl...
49.785714
17.642857
def dump_json(self, pretty=True): """ Return a string representation of this CloudFormation template. """ # Build template t = {} t['AWSTemplateFormatVersion'] = '2010-09-09' if self.description is not None: t['Description'] = self.description ...
[ "def", "dump_json", "(", "self", ",", "pretty", "=", "True", ")", ":", "# Build template", "t", "=", "{", "}", "t", "[", "'AWSTemplateFormatVersion'", "]", "=", "'2010-09-09'", "if", "self", ".", "description", "is", "not", "None", ":", "t", "[", "'Descr...
37.307692
15.461538
def render(self, data, chart_type, chart_package='corechart', options=None, div_id="chart", head=""): """Render the data in HTML template.""" if not self.is_valid_name(div_id): raise ValueError( ...
[ "def", "render", "(", "self", ",", "data", ",", "chart_type", ",", "chart_package", "=", "'corechart'", ",", "options", "=", "None", ",", "div_id", "=", "\"chart\"", ",", "head", "=", "\"\"", ")", ":", "if", "not", "self", ".", "is_valid_name", "(", "d...
38.095238
15.47619
def _world_from_cwl(fn_name, fnargs, work_dir): """Reconstitute a bcbio world data object from flattened CWL-compatible inputs. Converts the flat CWL representation into a nested bcbio world dictionary. Handles single sample inputs (returning a single world object) and multi-sample runs (returning a l...
[ "def", "_world_from_cwl", "(", "fn_name", ",", "fnargs", ",", "work_dir", ")", ":", "parallel", "=", "None", "output_cwl_keys", "=", "None", "runtime", "=", "{", "}", "out", "=", "[", "]", "data", "=", "{", "}", "passed_keys", "=", "[", "]", "for", "...
42.06
24.78
def call_proxy(self, engine, payload, method, analyze_json_error_param, retry_request_substr_variants, stream=False): """ :param engine: Система :param payload: Данные для запроса :param method: string Может содержать native_call | tsv | json_newline :param ana...
[ "def", "call_proxy", "(", "self", ",", "engine", ",", "payload", ",", "method", ",", "analyze_json_error_param", ",", "retry_request_substr_variants", ",", "stream", "=", "False", ")", ":", "return", "self", ".", "__api_proxy_call", "(", "engine", ",", "payload"...
55.923077
29.461538
def _parse_arguments(): """Parses command line arguments. Returns: A Namespace of parsed arguments. """ # Handle version flag and exit if it was passed. param_util.handle_version_flag() parser = provider_base.create_parser(sys.argv[0]) parser.add_argument( '--version', '-v', default=False, he...
[ "def", "_parse_arguments", "(", ")", ":", "# Handle version flag and exit if it was passed.", "param_util", ".", "handle_version_flag", "(", ")", "parser", "=", "provider_base", ".", "create_parser", "(", "sys", ".", "argv", "[", "0", "]", ")", "parser", ".", "add...
31.849057
19.745283
def InputSplines(seq_length, n_bases=10, name=None, **kwargs): """Input placeholder for array returned by `encodeSplines` Wrapper for: `keras.layers.Input((seq_length, n_bases), name=name, **kwargs)` """ return Input((seq_length, n_bases), name=name, **kwargs)
[ "def", "InputSplines", "(", "seq_length", ",", "n_bases", "=", "10", ",", "name", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "Input", "(", "(", "seq_length", ",", "n_bases", ")", ",", "name", "=", "name", ",", "*", "*", "kwargs", ")"...
45.333333
20.5
def remove_child_repository(self, repository_id, child_id): """Removes a child from a repository. arg: repository_id (osid.id.Id): the ``Id`` of a repository arg: child_id (osid.id.Id): the ``Id`` of the new child raise: NotFound - ``repository_id`` not a parent of ...
[ "def", "remove_child_repository", "(", "self", ",", "repository_id", ",", "child_id", ")", ":", "# Implemented from template for", "# osid.resource.BinHierarchyDesignSession.remove_child_bin_template", "if", "self", ".", "_catalog_session", "is", "not", "None", ":", "return",...
50.894737
23.631579
def chartItems(self): """ Returns the chart items that are found within this scene. :return [<XChartWidgetItem>, ..] """ from projexui.widgets.xchartwidget import XChartWidgetItem return filter(lambda x: isinstance(x, XChartWidgetItem), self.items())
[ "def", "chartItems", "(", "self", ")", ":", "from", "projexui", ".", "widgets", ".", "xchartwidget", "import", "XChartWidgetItem", "return", "filter", "(", "lambda", "x", ":", "isinstance", "(", "x", ",", "XChartWidgetItem", ")", ",", "self", ".", "items", ...
38.875
18.125
def add_state_group(self, name, *states): """ Add a group of managed states. Groups can be specified directly in the :class:`~coaster.utils.classes.LabeledEnum`. This method is only useful for grouping a conditional state with existing states. It cannot be used to form a group of...
[ "def", "add_state_group", "(", "self", ",", "name", ",", "*", "states", ")", ":", "# See `_add_state_internal` for explanation of the following", "if", "hasattr", "(", "self", ",", "name", ")", ":", "raise", "AttributeError", "(", "\"State group name %s conflicts with e...
47.777778
18.555556
def run(self): """ this is the actual execution of the ReadProbes thread: continuously read values from the probes """ if self.probes is None: self._stop = True while True: if self._stop: break self.probes_values = { ...
[ "def", "run", "(", "self", ")", ":", "if", "self", ".", "probes", "is", "None", ":", "self", ".", "_stop", "=", "True", "while", "True", ":", "if", "self", ".", "_stop", ":", "break", "self", ".", "probes_values", "=", "{", "instrument_name", ":", ...
30.45
23.15
def two_gaussian(freq, freq0_1, freq0_2, sigma1, sigma2, amp1, amp2, offset, drift): """ A two-Gaussian model. This is simply the sum of two gaussian functions in some part of the spectrum. Each individual gaussian has its own peak frequency, sigma, and amp, but they share common offs...
[ "def", "two_gaussian", "(", "freq", ",", "freq0_1", ",", "freq0_2", ",", "sigma1", ",", "sigma2", ",", "amp1", ",", "amp2", ",", "offset", ",", "drift", ")", ":", "return", "(", "gaussian", "(", "freq", ",", "freq0_1", ",", "sigma1", ",", "amp1", ","...
39.333333
22
def mainloop(self): """ The main loop. """ if not self.args: self.parser.error("No metafiles given, nothing to do!") if 1 < sum(bool(i) for i in (self.options.no_ssl, self.options.reannounce, self.options.reannounce_all)): self.parser.error("Conflicting options -...
[ "def", "mainloop", "(", "self", ")", ":", "if", "not", "self", ".", "args", ":", "self", ".", "parser", ".", "error", "(", "\"No metafiles given, nothing to do!\"", ")", "if", "1", "<", "sum", "(", "bool", "(", "i", ")", "for", "i", "in", "(", "self"...
48.304813
24.331551
def do_failures(self, arg): """Prints a list of test cases that failed for the current unit test and analysis group settings. To only check failure on specific output files, set the list of files to check as arguments. """ usable, filename, append = self._redirect_split(arg) ...
[ "def", "do_failures", "(", "self", ",", "arg", ")", ":", "usable", ",", "filename", ",", "append", "=", "self", ".", "_redirect_split", "(", "arg", ")", "a", "=", "self", ".", "tests", "[", "self", ".", "active", "]", "args", "=", "self", ".", "cur...
37.05
16.65
def apply_weight_drop(block, local_param_regex, rate, axes=(), weight_dropout_mode='training'): """Apply weight drop to the parameter of a block. Parameters ---------- block : Block or HybridBlock The block whose parameter is to be applied weight-drop. local_param_rege...
[ "def", "apply_weight_drop", "(", "block", ",", "local_param_regex", ",", "rate", ",", "axes", "=", "(", ")", ",", "weight_dropout_mode", "=", "'training'", ")", ":", "if", "not", "rate", ":", "return", "existing_params", "=", "_find_params", "(", "block", ",...
49.886076
24.594937
def play(self, start_pos=0, end_pos=0, count=0): """Play internal color pattern :param start_pos: pattern line to start from :param end_pos: pattern line to end at :param count: number of times to play, 0=play forever """ if ( self.dev == None ): return '' buf = ...
[ "def", "play", "(", "self", ",", "start_pos", "=", "0", ",", "end_pos", "=", "0", ",", "count", "=", "0", ")", ":", "if", "(", "self", ".", "dev", "==", "None", ")", ":", "return", "''", "buf", "=", "[", "REPORT_ID", ",", "ord", "(", "'p'", "...
46.555556
12
def new_branch(self, branch, parent, parent_turn, parent_tick): """Declare that the ``branch`` is descended from ``parent`` at ``parent_turn``, ``parent_tick`` """ return self.sql('branches_insert', branch, parent, parent_turn, parent_tick, parent_turn, parent_tick)
[ "def", "new_branch", "(", "self", ",", "branch", ",", "parent", ",", "parent_turn", ",", "parent_tick", ")", ":", "return", "self", ".", "sql", "(", "'branches_insert'", ",", "branch", ",", "parent", ",", "parent_turn", ",", "parent_tick", ",", "parent_turn"...
49
22.166667
def _profile_package(self): """Runs statistical profiler on a package.""" with _StatProfiler() as prof: prof.base_frame = inspect.currentframe() try: runpy.run_path(self._run_object, run_name='__main__') except SystemExit: pass ...
[ "def", "_profile_package", "(", "self", ")", ":", "with", "_StatProfiler", "(", ")", "as", "prof", ":", "prof", ".", "base_frame", "=", "inspect", ".", "currentframe", "(", ")", "try", ":", "runpy", ".", "run_path", "(", "self", ".", "_run_object", ",", ...
34.833333
14
def validate_course_run_id(self, value): """ Validates that the course run id is part of the Enterprise Customer's catalog. """ enterprise_customer = self.context.get('enterprise_customer') if not enterprise_customer.catalog_contains_course(value): raise serializers....
[ "def", "validate_course_run_id", "(", "self", ",", "value", ")", ":", "enterprise_customer", "=", "self", ".", "context", ".", "get", "(", "'enterprise_customer'", ")", "if", "not", "enterprise_customer", ".", "catalog_contains_course", "(", "value", ")", ":", "...
39.3125
21.6875
def getOption(self, name): """ Get the current value of the specified option. If the option does not exist, returns None. Args: name: Option name. Returns: Value of the option. Raises: InvalidArgumet: if the option name is not val...
[ "def", "getOption", "(", "self", ",", "name", ")", ":", "try", ":", "value", "=", "lock_and_call", "(", "lambda", ":", "self", ".", "_impl", ".", "getOption", "(", "name", ")", ".", "value", "(", ")", ",", "self", ".", "_lock", ")", "except", "Runt...
25.310345
18
def check_outdated(package, version): """ Given the name of a package on PyPI and a version (both strings), checks if the given version is the latest version of the package available. Returns a 2-tuple (is_outdated, latest_version) where is_outdated is a boolean which is True if the given version i...
[ "def", "check_outdated", "(", "package", ",", "version", ")", ":", "from", "pkg_resources", "import", "parse_version", "parsed_version", "=", "parse_version", "(", "version", ")", "latest", "=", "None", "with", "utils", ".", "cache_file", "(", "package", ",", ...
33.833333
20.907407
def get_attribute_information_profile( url: str, profile: Optional[Tuple[str]]=None, categories: Optional[Tuple[str]]=None) -> Dict: """ Get the information content for a list of phenotypes and the annotation sufficiency simple and and categorical scores if categories are provied...
[ "def", "get_attribute_information_profile", "(", "url", ":", "str", ",", "profile", ":", "Optional", "[", "Tuple", "[", "str", "]", "]", "=", "None", ",", "categories", ":", "Optional", "[", "Tuple", "[", "str", "]", "]", "=", "None", ")", "->", "Dict"...
35.166667
18.75
def setOutputPoint(self, point): """ Sets the scene space point for where this connection should draw \ its output from. This value will only be used if no output \ node is defined. :param point | <QPointF> """ self._outputPoint = point ...
[ "def", "setOutputPoint", "(", "self", ",", "point", ")", ":", "self", ".", "_outputPoint", "=", "point", "self", ".", "setPath", "(", "self", ".", "rebuild", "(", ")", ")" ]
34
13.2
def _list(self): """List all the objects saved in the namespace. :param search_from: TBI :param search_to: TBI :param offset: TBI :param limit: max number of values to be shows. :return: list with transactions. """ all = self.driver.instance.metadata.get(...
[ "def", "_list", "(", "self", ")", ":", "all", "=", "self", ".", "driver", ".", "instance", ".", "metadata", ".", "get", "(", "search", "=", "self", ".", "namespace", ")", "list", "=", "[", "]", "for", "id", "in", "all", ":", "try", ":", "if", "...
29.421053
17
def run(self, node): """ Captures the use of locals() in render function. """ if self.get_call_name(node) != 'render': return issues = [] for arg in node.args: if isinstance(arg, ast.Call) and arg.func.id == 'locals': issues.append(...
[ "def", "run", "(", "self", ",", "node", ")", ":", "if", "self", ".", "get_call_name", "(", "node", ")", "!=", "'render'", ":", "return", "issues", "=", "[", "]", "for", "arg", "in", "node", ".", "args", ":", "if", "isinstance", "(", "arg", ",", "...
30.125
13.75
def get_filename(self, prefix, url): """ Creates a file path on the form: current-working-directory/prefix/cleaned-url.txt :param prefix: The prefix from the .get() and .put() methods. :param url: The url of the request. :return: The created path. """ return '{}....
[ "def", "get_filename", "(", "self", ",", "prefix", ",", "url", ")", ":", "return", "'{}.txt'", ".", "format", "(", "os", ".", "path", ".", "join", "(", "os", ".", "getcwd", "(", ")", ",", "prefix", ",", "self", ".", "clean_url", "(", "url", ")", ...
42.111111
19.666667
def compute_percentile(self, percentage): """ Returns a Position object that represents percentage%-far-of-the-way through the larger task, as specified by this query. @param percentage a number between 0 and 100. """ all_patches = self.get_all_patches() retur...
[ "def", "compute_percentile", "(", "self", ",", "percentage", ")", ":", "all_patches", "=", "self", ".", "get_all_patches", "(", ")", "return", "all_patches", "[", "int", "(", "len", "(", "all_patches", ")", "*", "percentage", "/", "100", ")", "]", ".", "...
36.545455
14.363636
def get_filtered_dfs(lib, expr): """ Main: Get all data frames that match the given expression :return dict: Filenames and data frames (filtered) """ logger_dataframes.info("enter get_filtered_dfs") dfs = {} tt = None # Process all lipds files or one lipds file? specific_files = _c...
[ "def", "get_filtered_dfs", "(", "lib", ",", "expr", ")", ":", "logger_dataframes", ".", "info", "(", "\"enter get_filtered_dfs\"", ")", "dfs", "=", "{", "}", "tt", "=", "None", "# Process all lipds files or one lipds file?", "specific_files", "=", "_check_expr_filenam...
37.527273
23.054545
def get_next_question(self, question_id, answered=None, reverse=False, honor_sequential=True): """Inspects question map to return the next available question. if answered == False: only return next unanswered question if answered == True: only return next answered question if answered i...
[ "def", "get_next_question", "(", "self", ",", "question_id", ",", "answered", "=", "None", ",", "reverse", "=", "False", ",", "honor_sequential", "=", "True", ")", ":", "self", ".", "_update_questions", "(", ")", "# Make sure questions list is current", "question_...
55.941176
24.235294
def _remove_prefix(name): """Strip the possible prefix 'Table: ' from one or more table names.""" if isinstance(name, str): return _do_remove_prefix(name) return [_do_remove_prefix(nm) for nm in name]
[ "def", "_remove_prefix", "(", "name", ")", ":", "if", "isinstance", "(", "name", ",", "str", ")", ":", "return", "_do_remove_prefix", "(", "name", ")", "return", "[", "_do_remove_prefix", "(", "nm", ")", "for", "nm", "in", "name", "]" ]
43.2
7.4
def request(self, endpoint, data=None, json=None, filename=None, save_to=None): """ Perform a REST API request to the backend H2O server. :param endpoint: (str) The endpoint's URL, for example "GET /4/schemas/KeyV4" :param data: data payload for POST (and sometimes GET) requests. This s...
[ "def", "request", "(", "self", ",", "endpoint", ",", "data", "=", "None", ",", "json", "=", "None", ",", "filename", "=", "None", ",", "save_to", "=", "None", ")", ":", "if", "self", ".", "_stage", "==", "0", ":", "raise", "H2OConnectionError", "(", ...
53.356322
30.275862
def scrape(self, url): ''' Execute Web-Scraping. The target dom objects are in self.__dom_object_list. Args: url: Web site url. Returns: The result. this is a string. @TODO(chimera0): check URLs format. ''' if isinstance(url, ...
[ "def", "scrape", "(", "self", ",", "url", ")", ":", "if", "isinstance", "(", "url", ",", "str", ")", "is", "False", ":", "raise", "TypeError", "(", "\"The type of url must be str.\"", ")", "if", "self", ".", "readable_web_pdf", "is", "not", "None", "and", ...
31.935484
22.83871
def add_section(self, section): """Create a new section in the configuration. Extends RawConfigParser.add_section by validating if the section name is a string.""" section, _, _ = self._validate_value_types(section=section) super(ConfigParser, self).add_section(section)
[ "def", "add_section", "(", "self", ",", "section", ")", ":", "section", ",", "_", ",", "_", "=", "self", ".", "_validate_value_types", "(", "section", "=", "section", ")", "super", "(", "ConfigParser", ",", "self", ")", ".", "add_section", "(", "section"...
51
13.666667
def _F(self, X): """ analytic solution of the projection integral :param x: R/Rs :type x: float >0 """ if isinstance(X, int) or isinstance(X, float): if X < 1 and X > 0: a = 1/(X**2-1)*(1-2/np.sqrt(1-X**2)*np.arctanh(np.sqrt((1-X)/(1+X)))) ...
[ "def", "_F", "(", "self", ",", "X", ")", ":", "if", "isinstance", "(", "X", ",", "int", ")", "or", "isinstance", "(", "X", ",", "float", ")", ":", "if", "X", "<", "1", "and", "X", ">", "0", ":", "a", "=", "1", "/", "(", "X", "**", "2", ...
33.15625
23.65625
def ipv6_acl_ipv6_access_list_standard_seq_action(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") ipv6_acl = ET.SubElement(config, "ipv6-acl", xmlns="urn:brocade.com:mgmt:brocade-ipv6-access-list") ipv6 = ET.SubElement(ipv6_acl, "ipv6") access_li...
[ "def", "ipv6_acl_ipv6_access_list_standard_seq_action", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "ipv6_acl", "=", "ET", ".", "SubElement", "(", "config", ",", "\"ipv6-acl\"", ",", "xmlns", "...
45.333333
13.277778
def get_all_client_properties(self, params=None): """ Get all contacts of client This will iterate over all pages until it gets all elements. So if the rate limit exceeded it will throw an Exception and you will get nothing :param params: search params :return: list ...
[ "def", "get_all_client_properties", "(", "self", ",", "params", "=", "None", ")", ":", "return", "self", ".", "_iterate_through_pages", "(", "get_function", "=", "self", ".", "get_client_properties_per_page", ",", "resource", "=", "CLIENT_PROPERTIES", ",", "*", "*...
35.928571
15.642857
def parse_networking( text = None ): """ Access address and port parameters via the builtins or __builtin__ module. Relish the nonsense. """ try: address = _builtins.address port = _builtins.port except: address = None port = None triggers = [...
[ "def", "parse_networking", "(", "text", "=", "None", ")", ":", "try", ":", "address", "=", "_builtins", ".", "address", "port", "=", "_builtins", ".", "port", "except", ":", "address", "=", "None", "port", "=", "None", "triggers", "=", "[", "]", "if", ...
37.7
21.8
def POST(self, **kwargs): ''' Send one or more Salt commands in the request body .. http:post:: / :reqheader X-Auth-Token: |req_token| :reqheader Accept: |req_accept| :reqheader Content-Type: |req_ct| :resheader Content-Type: |res_ct| ...
[ "def", "POST", "(", "self", ",", "*", "*", "kwargs", ")", ":", "return", "{", "'return'", ":", "list", "(", "self", ".", "exec_lowstate", "(", "token", "=", "cherrypy", ".", "session", ".", "get", "(", "'token'", ")", ")", ")", "}" ]
26.2
20.233333
def prediction_error(model, X, y=None, ax=None, alpha=0.75, **kwargs): """ Quick method: Plot the actual targets from the dataset against the predicted values generated by our model(s). This helper function is a quick wrapper to utilize the PredictionError ScoreVisualizer for one-off analysis....
[ "def", "prediction_error", "(", "model", ",", "X", ",", "y", "=", "None", ",", "ax", "=", "None", ",", "alpha", "=", "0.75", ",", "*", "*", "kwargs", ")", ":", "# Instantiate the visualizer", "visualizer", "=", "PredictionError", "(", "model", ",", "ax",...
37.702703
24.945946
def deprecated(since, message='', name='', alternative='', pending=False, addendum='', removal=''): """ Decorator to mark a function or a class as deprecated. Parameters ---------- since : str The release at which this API became deprecated. This is required. mess...
[ "def", "deprecated", "(", "since", ",", "message", "=", "''", ",", "name", "=", "''", ",", "alternative", "=", "''", ",", "pending", "=", "False", ",", "addendum", "=", "''", ",", "removal", "=", "''", ")", ":", "def", "deprecate", "(", "obj", ",",...
37.563107
18.553398
def get_area(self): """Calculate area of bounding box.""" return (self.p2.x-self.p1.x)*(self.p2.y-self.p1.y)
[ "def", "get_area", "(", "self", ")", ":", "return", "(", "self", ".", "p2", ".", "x", "-", "self", ".", "p1", ".", "x", ")", "*", "(", "self", ".", "p2", ".", "y", "-", "self", ".", "p1", ".", "y", ")" ]
40.666667
13
def shot2shot(insurvey, inshot, calculate_lrud=True): """Convert a PocketTopo `Shot` to a Compass `Shot`""" # FIXME: requires angles in degrees only, no grads splays = insurvey.splays[inshot['FROM']] if calculate_lrud and not inshot.is_splay and splays: # Try our best to convert PocketTopo spla...
[ "def", "shot2shot", "(", "insurvey", ",", "inshot", ",", "calculate_lrud", "=", "True", ")", ":", "# FIXME: requires angles in degrees only, no grads", "splays", "=", "insurvey", ".", "splays", "[", "inshot", "[", "'FROM'", "]", "]", "if", "calculate_lrud", "and",...
50.428571
27.157143
def _node(handler, single=None, multi=None): """Return an _AbstractSyntaxTreeNode with some elements defaulted.""" return _AbstractSyntaxTreeNode(handler=handler, single=(single if single else []), multi=(multi if multi else []))
[ "def", "_node", "(", "handler", ",", "single", "=", "None", ",", "multi", "=", "None", ")", ":", "return", "_AbstractSyntaxTreeNode", "(", "handler", "=", "handler", ",", "single", "=", "(", "single", "if", "single", "else", "[", "]", ")", ",", "multi"...
60.6
14
def on_complete(cls, req): """ Callback called when the request to REST is done. Handles the errors and if there is none, :class:`.OutputPicker` is shown. """ # handle http errors if not (req.status == 200 or req.status == 0): ViewController.log_view.add(req.t...
[ "def", "on_complete", "(", "cls", ",", "req", ")", ":", "# handle http errors", "if", "not", "(", "req", ".", "status", "==", "200", "or", "req", ".", "status", "==", "0", ")", ":", "ViewController", ".", "log_view", ".", "add", "(", "req", ".", "tex...
30.25
18.166667
def _write_value(value, path): """ Writes specified value into path. Note that the value is wrapped in single quotes in the command, to prevent injecting bash commands. :param value: The value to write (usually a number or string) :param path: A valid system path """ base_command = "echo '{0...
[ "def", "_write_value", "(", "value", ",", "path", ")", ":", "base_command", "=", "\"echo '{0}' > {1}\"", "# There is no common method for redirecting stderr to a null sink, so the", "# command string is platform-dependent", "if", "platform", "==", "'win32'", ":", "command", "="...
42.133333
14.666667
def annotations_from_file(filename): """Get a list of event annotations from an EDF (European Data Format file or EDF+ file, using edflib. Args: filename: EDF+ file Returns: list: annotation events, each in the form [start_time, duration, text] """ import edflib e = edflib.EdfR...
[ "def", "annotations_from_file", "(", "filename", ")", ":", "import", "edflib", "e", "=", "edflib", ".", "EdfReader", "(", "filename", ",", "annotations_mode", "=", "'all'", ")", "return", "e", ".", "read_annotations", "(", ")" ]
29.153846
19.461538
def include_revision(revision_num, skip_factor=1.1): """Decide whether to include a revision. If the number of revisions is large, we exclude some revisions to avoid a quadratic blowup in runtime, since the article is likely also large. We make the ratio between consecutive included revision numbers appprox...
[ "def", "include_revision", "(", "revision_num", ",", "skip_factor", "=", "1.1", ")", ":", "if", "skip_factor", "<=", "1.0", ":", "return", "True", "return", "(", "int", "(", "math", ".", "log1p", "(", "revision_num", ")", "/", "math", ".", "log", "(", ...
30.95
23.4