text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def int_check(*args, func=None): """Check if arguments are integrals.""" func = func or inspect.stack()[2][3] for var in args: if not isinstance(var, numbers.Integral): name = type(var).__name__ raise ComplexError( f'Function {func} expected integral number, {...
[ "def", "int_check", "(", "*", "args", ",", "func", "=", "None", ")", ":", "func", "=", "func", "or", "inspect", ".", "stack", "(", ")", "[", "2", "]", "[", "3", "]", "for", "var", "in", "args", ":", "if", "not", "isinstance", "(", "var", ",", ...
41.625
11.25
def calculate(self, where, calcExpression, sqlFormat="standard"): """ The calculate operation is performed on a feature service layer resource. It updates the values of one or more fields in an existing feature service layer based on SQL expressions or scalar values. The calculat...
[ "def", "calculate", "(", "self", ",", "where", ",", "calcExpression", ",", "sqlFormat", "=", "\"standard\"", ")", ":", "url", "=", "self", ".", "_url", "+", "\"/calculate\"", "params", "=", "{", "\"f\"", ":", "\"json\"", ",", "\"where\"", ":", "where", "...
50.186441
20.864407
def create_bmi_config_file(self, filename: str = "bmi_config.txt") -> None: """ Create a BMI config file to initialize the model. Args: filename: The filename with which the config file should be saved. """ s0 = self.construct_default_initial_state() s0.to_csv(filena...
[ "def", "create_bmi_config_file", "(", "self", ",", "filename", ":", "str", "=", "\"bmi_config.txt\"", ")", "->", "None", ":", "s0", "=", "self", ".", "construct_default_initial_state", "(", ")", "s0", ".", "to_csv", "(", "filename", ",", "index_label", "=", ...
42.5
20.25
def serialize_operator_match(self, op): """ Serializer for :meth:`SpiffWorkflow.operators.NotEqual`. Example:: <matches> <value>text</value> <value><attribute>foobar</attribute></value> </matches> """ elem = etree.Element(...
[ "def", "serialize_operator_match", "(", "self", ",", "op", ")", ":", "elem", "=", "etree", ".", "Element", "(", "'matches'", ")", "return", "self", ".", "serialize_value_list", "(", "elem", ",", "op", ".", "args", ")" ]
28.769231
15.846154
def perform_command(self): """ Perform command and return the appropriate exit code. :rtype: int """ if len(self.actual_arguments) < 2: return self.print_help() input_file_path = self.actual_arguments[0] output_file_path = self.actual_arguments[1] ...
[ "def", "perform_command", "(", "self", ")", ":", "if", "len", "(", "self", ".", "actual_arguments", ")", "<", "2", ":", "return", "self", ".", "print_help", "(", ")", "input_file_path", "=", "self", ".", "actual_arguments", "[", "0", "]", "output_file_path...
46.671875
20.515625
def now(cls, tzinfo=None): """[tz] -> new datetime with tz's local day and time.""" obj = cls.utcnow() if tzinfo is None: tzinfo = localtz() return obj.astimezone(tzinfo)
[ "def", "now", "(", "cls", ",", "tzinfo", "=", "None", ")", ":", "obj", "=", "cls", ".", "utcnow", "(", ")", "if", "tzinfo", "is", "None", ":", "tzinfo", "=", "localtz", "(", ")", "return", "obj", ".", "astimezone", "(", "tzinfo", ")" ]
31.166667
12.166667
def print_loopy(self, as_url=True): """Return Parameters ---------- out_file : Optional[str] A file name in which the Loopy network is saved. Returns ------- full_str : str The string representing the Loopy network. """ i...
[ "def", "print_loopy", "(", "self", ",", "as_url", "=", "True", ")", ":", "init_str", "=", "''", "node_id", "=", "1", "node_list", "=", "{", "}", "for", "node", ",", "data", "in", "self", ".", "graph", ".", "nodes", "(", "data", "=", "True", ")", ...
30.325581
16.023256
def _read_bands(self): """ Reads a band with rasterio """ bands = [] try: for i, band in enumerate(self.bands): bands.append(rasterio.open(self.bands_path[i]).read_band(1)) except IOError as e: exit(e.message, 1) return bands
[ "def", "_read_bands", "(", "self", ")", ":", "bands", "=", "[", "]", "try", ":", "for", "i", ",", "band", "in", "enumerate", "(", "self", ".", "bands", ")", ":", "bands", ".", "append", "(", "rasterio", ".", "open", "(", "self", ".", "bands_path", ...
27
21.363636
async def kickban(self, channel, target, reason=None, range=0): """ Kick and ban user from channel. """ await self.ban(channel, target, range) await self.kick(channel, target, reason)
[ "async", "def", "kickban", "(", "self", ",", "channel", ",", "target", ",", "reason", "=", "None", ",", "range", "=", "0", ")", ":", "await", "self", ".", "ban", "(", "channel", ",", "target", ",", "range", ")", "await", "self", ".", "kick", "(", ...
36.333333
6.333333
def _set_global_defaults(xmlglobals): """Sets the default attributes on tags that were specified in <global> tags in the XML file.""" for key, val in xmlglobals.items(): if key != "defaults": for name, tag in val.items(): _update_from_globals(tag, xmlglobals, None)
[ "def", "_set_global_defaults", "(", "xmlglobals", ")", ":", "for", "key", ",", "val", "in", "xmlglobals", ".", "items", "(", ")", ":", "if", "key", "!=", "\"defaults\"", ":", "for", "name", ",", "tag", "in", "val", ".", "items", "(", ")", ":", "_upda...
43.857143
5
def _compute(self, inputs, outputs): """ Run one iteration of TMRegion's compute """ #if self.topDownMode and (not 'topDownIn' in inputs): # raise RuntimeError("The input topDownIn must be linked in if " # "topDownMode is True") if self._tfdr is None: raise Runtime...
[ "def", "_compute", "(", "self", ",", "inputs", ",", "outputs", ")", ":", "#if self.topDownMode and (not 'topDownIn' in inputs):", "# raise RuntimeError(\"The input topDownIn must be linked in if \"", "# \"topDownMode is True\")", "if", "self", ".", "_tfdr", "is",...
36.558442
20.220779
def complete_func(self, findstart, base): """Handle omni completion.""" self.log.debug('complete_func: in %s %s', findstart, base) def detect_row_column_start(): row, col = self.editor.cursor() start = col line = self.editor.getline() while start ...
[ "def", "complete_func", "(", "self", ",", "findstart", ",", "base", ")", ":", "self", ".", "log", ".", "debug", "(", "'complete_func: in %s %s'", ",", "findstart", ",", "base", ")", "def", "detect_row_column_start", "(", ")", ":", "row", ",", "col", "=", ...
39.2
15.628571
def from_unknown_text(text, strict=False): """ Detect crs string format and parse into crs object with appropriate function. Arguments: - *text*: The crs text representation of unknown type. - *strict* (optional): When True, the parser is strict about names having to match exactly with up...
[ "def", "from_unknown_text", "(", "text", ",", "strict", "=", "False", ")", ":", "if", "text", ".", "startswith", "(", "\"+\"", ")", ":", "crs", "=", "from_proj4", "(", "text", ",", "strict", ")", "elif", "text", ".", "startswith", "(", "(", "\"PROJCS[\...
28.222222
24.222222
def trace_grad(fn, args): """Trace a function, and return a VJP and the function's output.""" from tensorflow.python.eager.backprop import make_vjp result, vjp = make_vjp(fn)(*args) return result, vjp
[ "def", "trace_grad", "(", "fn", ",", "args", ")", ":", "from", "tensorflow", ".", "python", ".", "eager", ".", "backprop", "import", "make_vjp", "result", ",", "vjp", "=", "make_vjp", "(", "fn", ")", "(", "*", "args", ")", "return", "result", ",", "v...
40.8
11
def get_label_set(self, type_str=None): """Get a set of label_str for the tree rooted at this node. Args: type_str: SUBJECT_NODE_TAG, TYPE_NODE_TAG or None. If set, only include information from nodes of that type. Returns: set: The label...
[ "def", "get_label_set", "(", "self", ",", "type_str", "=", "None", ")", ":", "return", "{", "v", ".", "label_str", "for", "v", "in", "self", ".", "node_gen", "if", "type_str", "in", "(", "None", ",", "v", ".", "type_str", ")", "}" ]
35.384615
24.923077
def index_firstnot(ol,value): ''' from elist.elist import * ol = [1,'a',3,'a',4,'a',5] index_firstnot(ol,'a') ####index_firstnot, array_indexnot, indexOfnot are the same array_indexnot(ol,'a') indexOfnot(ol,'a') ''' length = ol.__len__() for i in range(0,...
[ "def", "index_firstnot", "(", "ol", ",", "value", ")", ":", "length", "=", "ol", ".", "__len__", "(", ")", "for", "i", "in", "range", "(", "0", ",", "length", ")", ":", "if", "(", "value", "==", "ol", "[", "i", "]", ")", ":", "pass", "else", ...
25.6875
17.8125
def prep_jid(nocache=False, passed_jid=None, recurse_count=0): ''' Return a job id and prepare the job id directory. This is the function responsible for making sure jids don't collide (unless it is passed a jid). So do what you have to do to make sure that stays the case ''' if recurse_cou...
[ "def", "prep_jid", "(", "nocache", "=", "False", ",", "passed_jid", "=", "None", ",", "recurse_count", "=", "0", ")", ":", "if", "recurse_count", ">=", "5", ":", "err", "=", "'prep_jid could not store a jid after {0} tries.'", ".", "format", "(", "recurse_count"...
36.488372
24.581395
def getOverlayAutoCurveDistanceRangeInMeters(self, ulOverlayHandle): """ For high-quality curved overlays only, gets the distance range in meters from the overlay used to automatically curve the surface around the viewer. Min is distance is when the surface will be most curved. Max is when lea...
[ "def", "getOverlayAutoCurveDistanceRangeInMeters", "(", "self", ",", "ulOverlayHandle", ")", ":", "fn", "=", "self", ".", "function_table", ".", "getOverlayAutoCurveDistanceRangeInMeters", "pfMinDistanceInMeters", "=", "c_float", "(", ")", "pfMaxDistanceInMeters", "=", "c...
60.727273
33.272727
def generate_folder_names(name, project): """Creates sensible folder names.""" out_data_dir = prms.Paths.outdatadir project_dir = os.path.join(out_data_dir, project) batch_dir = os.path.join(project_dir, name) raw_dir = os.path.join(batch_dir, "raw_data") return out_data_dir, project_dir, batch...
[ "def", "generate_folder_names", "(", "name", ",", "project", ")", ":", "out_data_dir", "=", "prms", ".", "Paths", ".", "outdatadir", "project_dir", "=", "os", ".", "path", ".", "join", "(", "out_data_dir", ",", "project", ")", "batch_dir", "=", "os", ".", ...
40.75
10.75
def centered(coordinates): """ Centers coordinate distribution with respect to its mean on all three axes. This is used as the input to the regression model, so it can be converted easily into radial coordinates. """ coordinates = N.array(coordinates) means = N.mean(coordinates,axis=0) ...
[ "def", "centered", "(", "coordinates", ")", ":", "coordinates", "=", "N", ".", "array", "(", "coordinates", ")", "means", "=", "N", ".", "mean", "(", "coordinates", ",", "axis", "=", "0", ")", "return", "coordinates", "-", "means" ]
34
8.6
def quit(self): """Restore previous stdout/stderr and destroy the window.""" sys.stdout = self._oldstdout sys.stderr = self._oldstderr self.destroy()
[ "def", "quit", "(", "self", ")", ":", "sys", ".", "stdout", "=", "self", ".", "_oldstdout", "sys", ".", "stderr", "=", "self", ".", "_oldstderr", "self", ".", "destroy", "(", ")" ]
35.4
10.2
def cBurkPot(self, R, Rs, rho0, r_core): """ :param R: projected distance :param Rs: scale radius :param rho0: central core density :param r_core: core radius """ x = R * Rs ** -1 p = Rs * r_core ** -1 hx = self._H(x, p) return 2 * rho0 *...
[ "def", "cBurkPot", "(", "self", ",", "R", ",", "Rs", ",", "rho0", ",", "r_core", ")", ":", "x", "=", "R", "*", "Rs", "**", "-", "1", "p", "=", "Rs", "*", "r_core", "**", "-", "1", "hx", "=", "self", ".", "_H", "(", "x", ",", "p", ")", "...
24.692308
11
def on_event(self, evt, is_final): """ this is invoked from in response to COM PumpWaitingMessages - different thread """ for msg in XmlHelper.message_iter(evt): for node, error in XmlHelper.security_iter(msg.GetElement('securityData')): if error: self.sec...
[ "def", "on_event", "(", "self", ",", "evt", ",", "is_final", ")", ":", "for", "msg", "in", "XmlHelper", ".", "message_iter", "(", "evt", ")", ":", "for", "node", ",", "error", "in", "XmlHelper", ".", "security_iter", "(", "msg", ".", "GetElement", "(",...
47.428571
16
def _loop_use_cache(self, helper_function, num, fragment): """ Synthesize all fragments using the cache """ self.log([u"Examining fragment %d (cache)...", num]) fragment_info = (fragment.language, fragment.filtered_text) if self.cache.is_cached(fragment_info): self.log(u"Frag...
[ "def", "_loop_use_cache", "(", "self", ",", "helper_function", ",", "num", ",", "fragment", ")", ":", "self", ".", "log", "(", "[", "u\"Examining fragment %d (cache)...\"", ",", "num", "]", ")", "fragment_info", "=", "(", "fragment", ".", "language", ",", "f...
50.916667
21.875
def commit_input_confirm_timeout(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") commit = ET.Element("commit") config = commit input = ET.SubElement(commit, "input") confirm_timeout = ET.SubElement(input, "confirm-timeout") confir...
[ "def", "commit_input_confirm_timeout", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "commit", "=", "ET", ".", "Element", "(", "\"commit\"", ")", "config", "=", "commit", "input", "=", "ET", ...
37.166667
12.416667
def default_filename_decoder(): """ Creates a decoder which parses CWR filenames following the old or the new convention. :return: a CWR filename decoder for the old and the new conventions """ factory = default_filename_grammar_factory() grammar_old = factory.get_rule('filename_old') ...
[ "def", "default_filename_decoder", "(", ")", ":", "factory", "=", "default_filename_grammar_factory", "(", ")", "grammar_old", "=", "factory", ".", "get_rule", "(", "'filename_old'", ")", "grammar_new", "=", "factory", ".", "get_rule", "(", "'filename_new'", ")", ...
31.384615
20.153846
def _add_plugin_options(self, available_plugins: Set[Type[Plugin]]) -> None: """Recovers the list of command line options implemented by the available plugins and adds them to the command line parser. """ for plugin_class in available_plugins: # Add the current plugin's comma...
[ "def", "_add_plugin_options", "(", "self", ",", "available_plugins", ":", "Set", "[", "Type", "[", "Plugin", "]", "]", ")", "->", "None", ":", "for", "plugin_class", "in", "available_plugins", ":", "# Add the current plugin's commands to the parser", "group", "=", ...
58.5
17.6
def loads(s, encoding=None, cls=JSONTreeDecoder, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kargs): """JSON load from string function that defaults the loading class to be JSONTreeDecoder """ return json.loads(s, encoding, cls, ob...
[ "def", "loads", "(", "s", ",", "encoding", "=", "None", ",", "cls", "=", "JSONTreeDecoder", ",", "object_hook", "=", "None", ",", "parse_float", "=", "None", ",", "parse_int", "=", "None", ",", "parse_constant", "=", "None", ",", "object_pairs_hook", "=", ...
45.333333
10.666667
def remote_file_size(self, remote_cmd="", remote_file=None): """Get the file size of the remote file.""" return self._remote_file_size_unix( remote_cmd=remote_cmd, remote_file=remote_file )
[ "def", "remote_file_size", "(", "self", ",", "remote_cmd", "=", "\"\"", ",", "remote_file", "=", "None", ")", ":", "return", "self", ".", "_remote_file_size_unix", "(", "remote_cmd", "=", "remote_cmd", ",", "remote_file", "=", "remote_file", ")" ]
44.2
14.4
def convert_bb_to_faces(voxel_grid): """ Converts a voxel grid defined by min and max coordinates to a voxel grid defined by faces. :param voxel_grid: voxel grid defined by the bounding box of all voxels :return: voxel grid with face data """ new_vg = [] for v in voxel_grid: # Vertices ...
[ "def", "convert_bb_to_faces", "(", "voxel_grid", ")", ":", "new_vg", "=", "[", "]", "for", "v", "in", "voxel_grid", ":", "# Vertices", "p1", "=", "v", "[", "0", "]", "p2", "=", "[", "v", "[", "1", "]", "[", "0", "]", ",", "v", "[", "0", "]", ...
35.703704
10.481481
def decode_and_filter(line: bytes, context: RunContext) -> typing.Optional[str]: """ Decodes a line that was captured from the running process using a given encoding (defaults to UTF8) Runs that line into the filters, and output the decoded line back if no filter catches it. :param line: line to parse...
[ "def", "decode_and_filter", "(", "line", ":", "bytes", ",", "context", ":", "RunContext", ")", "->", "typing", ".", "Optional", "[", "str", "]", ":", "line_str", ":", "str", "=", "line", ".", "decode", "(", "context", ".", "console_encoding", ",", "error...
34.789474
25.315789
def scan(self, func, sequences=None, outputs=None, non_sequences=None, block=None, **kwargs): """ A loop function, the usage is identical with the theano one. :type block: deepy.layers.Block """ results, updates = Scanner(func, sequences, outputs, non_sequences, neural_computatio...
[ "def", "scan", "(", "self", ",", "func", ",", "sequences", "=", "None", ",", "outputs", "=", "None", ",", "non_sequences", "=", "None", ",", "block", "=", "None", ",", "*", "*", "kwargs", ")", ":", "results", ",", "updates", "=", "Scanner", "(", "f...
46.818182
18.090909
def digest_auth_user(self, realm, user_name, environ): """Computes digest hash A1 part.""" user = self._get_realm_entry(realm, user_name) if user is None: return False password = user.get("password") environ["wsgidav.auth.roles"] = user.get("roles", []) return...
[ "def", "digest_auth_user", "(", "self", ",", "realm", ",", "user_name", ",", "environ", ")", ":", "user", "=", "self", ".", "_get_realm_entry", "(", "realm", ",", "user_name", ")", "if", "user", "is", "None", ":", "return", "False", "password", "=", "use...
46.25
14.125
def _cwl_workflow_template(inputs, top_level=False): """Retrieve CWL inputs shared amongst different workflows. """ ready_inputs = [] for inp in inputs: cur_inp = copy.deepcopy(inp) for attr in ["source", "valueFrom", "wf_duplicate"]: cur_inp.pop(attr, None) if top_le...
[ "def", "_cwl_workflow_template", "(", "inputs", ",", "top_level", "=", "False", ")", ":", "ready_inputs", "=", "[", "]", "for", "inp", "in", "inputs", ":", "cur_inp", "=", "copy", ".", "deepcopy", "(", "inp", ")", "for", "attr", "in", "[", "\"source\"", ...
41.590909
14.363636
def apply_option(self, cmd, option, active=True): """Apply a command-line option.""" return re.sub(r'{{{}\:(?P<option>[^}}]*)}}'.format(option), '\g<option>' if active else '', cmd)
[ "def", "apply_option", "(", "self", ",", "cmd", ",", "option", ",", "active", "=", "True", ")", ":", "return", "re", ".", "sub", "(", "r'{{{}\\:(?P<option>[^}}]*)}}'", ".", "format", "(", "option", ")", ",", "'\\g<option>'", "if", "active", "else", "''", ...
54
13.5
def compile_dictionary(self, lang, wordlists, encoding, output): """Compile user dictionary.""" cmd = [ self.binary, '--lang', lang, '--encoding', codecs.lookup(filters.PYTHON_ENCODING_NAMES.get(encoding, encoding).lower()).name, 'create', 'ma...
[ "def", "compile_dictionary", "(", "self", ",", "lang", ",", "wordlists", ",", "encoding", ",", "output", ")", ":", "cmd", "=", "[", "self", ".", "binary", ",", "'--lang'", ",", "lang", ",", "'--encoding'", ",", "codecs", ".", "lookup", "(", "filters", ...
33.954545
19.363636
def make_request(url, method='GET', headers=None, timeout=30, **kwargs): """A wrapper around requests to set defaults & call raise_for_status().""" headers = headers or {} headers['User-Agent'] = 'treeherder/{}'.format(settings.SITE_HOSTNAME) # Work around bug 1305768. if 'queue.taskcluster.net' in ...
[ "def", "make_request", "(", "url", ",", "method", "=", "'GET'", ",", "headers", "=", "None", ",", "timeout", "=", "30", ",", "*", "*", "kwargs", ")", ":", "headers", "=", "headers", "or", "{", "}", "headers", "[", "'User-Agent'", "]", "=", "'treeherd...
39.652174
17.652174
def resolve_absolute_name(self, name): ''' Resolve a field from an absolute name. An absolute name is just like unix absolute path, starts with '/' and each name component is separated by '/'. :param name: absolute name, e.g. "/container/subcontainer/field" :return: fiel...
[ "def", "resolve_absolute_name", "(", "self", ",", "name", ")", ":", "current", "=", "self", "while", "current", ".", "enclosing", ":", "current", "=", "current", ".", "enclosing", "if", "name", "!=", "'/'", ":", "components", "=", "name", ".", "split", "...
38.611111
16.611111
def update_preference_communication_channel_id(self, notification, communication_channel_id, notification_preferences_frequency): """ Update a preference. Change the preference for a single notification for a single communication channel """ path = {} data = {} ...
[ "def", "update_preference_communication_channel_id", "(", "self", ",", "notification", ",", "communication_channel_id", ",", "notification_preferences_frequency", ")", ":", "path", "=", "{", "}", "data", "=", "{", "}", "params", "=", "{", "}", "# REQUIRED - PATH - com...
50.875
36.875
def get_rendered_transform_path(self): """ Generates a rendered transform path that is calculated from all parents. :return: """ path = self.transform_path parent = self.parent while parent is not None: path = "{0}/{1}".format(parent.transform...
[ "def", "get_rendered_transform_path", "(", "self", ")", ":", "path", "=", "self", ".", "transform_path", "parent", "=", "self", ".", "parent", "while", "parent", "is", "not", "None", ":", "path", "=", "\"{0}/{1}\"", ".", "format", "(", "parent", ".", "tran...
26.785714
13.5
def yaml_to_param(obj, name): """ Return the top-level element of a document sub-tree containing the YAML serialization of a Python object. """ return from_pyvalue(u"yaml:%s" % name, unicode(yaml.dump(obj)))
[ "def", "yaml_to_param", "(", "obj", ",", "name", ")", ":", "return", "from_pyvalue", "(", "u\"yaml:%s\"", "%", "name", ",", "unicode", "(", "yaml", ".", "dump", "(", "obj", ")", ")", ")" ]
34.5
10.5
def get_athlete(self, athlete_id=None): """ Gets the specified athlete; if athlete_id is None then retrieves a detail-level representation of currently authenticated athlete; otherwise summary-level representation returned of athlete. http://strava.github.io/api/v3/athlete/#get-...
[ "def", "get_athlete", "(", "self", ",", "athlete_id", "=", "None", ")", ":", "if", "athlete_id", "is", "None", ":", "raw", "=", "self", ".", "protocol", ".", "get", "(", "'/athlete'", ")", "else", ":", "raise", "NotImplementedError", "(", "\"The /athletes/...
41.818182
26.090909
def create_index(self, cardinality): """ Create an index for the table with the given cardinality. Parameters ---------- cardinality : int The cardinality to create a index for. """ DatabaseConnector.create_index(self, cardinality) query = "C...
[ "def", "create_index", "(", "self", ",", "cardinality", ")", ":", "DatabaseConnector", ".", "create_index", "(", "self", ",", "cardinality", ")", "query", "=", "\"CREATE INDEX idx_{0}_gram_varchar ON _{0}_gram(word varchar_pattern_ops);\"", ".", "format", "(", "cardinalit...
37.371429
30.571429
def regex(regex): """Return strategy that generates strings that match given regex. Regex can be either a string or compiled regex (through `re.compile()`). You can use regex flags (such as `re.IGNORECASE`, `re.DOTALL` or `re.UNICODE`) to control generation. Flags can be passed either in compiled rege...
[ "def", "regex", "(", "regex", ")", ":", "if", "not", "hasattr", "(", "regex", ",", "'pattern'", ")", ":", "regex", "=", "re", ".", "compile", "(", "regex", ")", "pattern", "=", "regex", ".", "pattern", "flags", "=", "regex", ".", "flags", "codes", ...
40.166667
28
def cache(self, value): """Enable or disable caching of pages/frames. Clear cache if False.""" value = bool(value) if self._cache and not value: self._clear() self._cache = value
[ "def", "cache", "(", "self", ",", "value", ")", ":", "value", "=", "bool", "(", "value", ")", "if", "self", ".", "_cache", "and", "not", "value", ":", "self", ".", "_clear", "(", ")", "self", ".", "_cache", "=", "value" ]
36.166667
10.166667
def sample(self, signum, frame): #pylint: disable=unused-argument """Samples current stack and adds result in self._stats. Args: signum: Signal that activates handler. frame: Frame on top of the stack when signal is handled. """ stack = [] while frame an...
[ "def", "sample", "(", "self", ",", "signum", ",", "frame", ")", ":", "#pylint: disable=unused-argument", "stack", "=", "[", "]", "while", "frame", "and", "frame", "!=", "self", ".", "base_frame", ":", "stack", ".", "append", "(", "(", "frame", ".", "f_co...
38.75
13.5625
def as_list_data(self): """Return an Element to be used in a list. Most lists want an element with tag of list_type, and subelements of id and name. Returns: Element: list representation of object. """ element = ElementTree.Element(self.list_type) id...
[ "def", "as_list_data", "(", "self", ")", ":", "element", "=", "ElementTree", ".", "Element", "(", "self", ".", "list_type", ")", "id_", "=", "ElementTree", ".", "SubElement", "(", "element", ",", "\"id\"", ")", "id_", ".", "text", "=", "self", ".", "id...
32.133333
15.933333
def rotate(self, n): '''Rotate Sequence by n bases. :param n: Number of bases to rotate. :type n: int :returns: The current sequence reoriented at `index`. :rtype: coral.sequence._sequence.Sequence :raises: ValueError if applied to linear sequence or `index` is ...
[ "def", "rotate", "(", "self", ",", "n", ")", ":", "if", "not", "self", ".", "circular", "and", "n", "!=", "0", ":", "raise", "ValueError", "(", "'Cannot rotate a linear sequence'", ")", "else", ":", "rotated", "=", "self", "[", "-", "n", ":", "]", "+...
33.6875
17.6875
def remove_state(self, state): """ Remove this conversation from the given state, and potentially deactivate the state if no more conversations are in it. The relation name will be interpolated in the state name, and it is recommended that it be included to avoid conflicts with ...
[ "def", "remove_state", "(", "self", ",", "state", ")", ":", "state", "=", "state", ".", "format", "(", "relation_name", "=", "self", ".", "relation_name", ")", "value", "=", "_get_flag_value", "(", "state", ")", "if", "not", "value", ":", "return", "if",...
39.88
20.12
def set(self, section, option, value=None): """Set an option.""" if value: value = self._interpolation.before_set(self, section, option, value) if not section or section == self.default_section: sectdict = self._defaults ...
[ "def", "set", "(", "self", ",", "section", ",", "option", ",", "value", "=", "None", ")", ":", "if", "value", ":", "value", "=", "self", ".", "_interpolation", ".", "before_set", "(", "self", ",", "section", ",", "option", ",", "value", ")", "if", ...
40.461538
15.076923
def get_token_data(self): """ Get token and data from keystone """ token_data = self._keystone_auth.conn.auth_ref token = token_data['auth_token'] self.set_token(token) if self.cache.is_redis_ok(): try: self.cache.set_cache_token(token_data) ...
[ "def", "get_token_data", "(", "self", ")", ":", "token_data", "=", "self", ".", "_keystone_auth", ".", "conn", ".", "auth_ref", "token", "=", "token_data", "[", "'auth_token'", "]", "self", ".", "set_token", "(", "token", ")", "if", "self", ".", "cache", ...
28
18.947368
def _fetch(self, key): """Helper function to fetch values from owning section. Returns a 2-tuple: the value, and the section where it was found. """ # switch off interpolation before we try and fetch anything ! save_interp = self.section.main.interpolation self.section.m...
[ "def", "_fetch", "(", "self", ",", "key", ")", ":", "# switch off interpolation before we try and fetch anything !", "save_interp", "=", "self", ".", "section", ".", "main", ".", "interpolation", "self", ".", "section", ".", "main", ".", "interpolation", "=", "Fal...
40.65625
16.34375
def deaccent(text): """ Remove accentuation from the given string. """ norm = unicodedata.normalize("NFD", text) result = "".join(ch for ch in norm if unicodedata.category(ch) != 'Mn') return unicodedata.normalize("NFC", result)
[ "def", "deaccent", "(", "text", ")", ":", "norm", "=", "unicodedata", ".", "normalize", "(", "\"NFD\"", ",", "text", ")", "result", "=", "\"\"", ".", "join", "(", "ch", "for", "ch", "in", "norm", "if", "unicodedata", ".", "category", "(", "ch", ")", ...
35.142857
10.571429
def _maybe_decode(self, value, encoding='utf-8'): """If a bytes object is passed in, in the Python 3 environment, decode it using the specified encoding to turn it to a str instance. :param mixed value: The value to possibly decode :param str encoding: The encoding to use :rtype...
[ "def", "_maybe_decode", "(", "self", ",", "value", ",", "encoding", "=", "'utf-8'", ")", ":", "if", "_PYTHON3", "and", "isinstance", "(", "value", ",", "bytes", ")", ":", "try", ":", "return", "value", ".", "decode", "(", "encoding", ")", "except", "Ex...
39.176471
16.705882
def all( self, count=500, offset=0, type=None, inactive=None, emailFilter=None, tag=None, messageID=None, fromdate=None, todate=None, ): """ Returns many bounces. :param int count: Number of bounces to return pe...
[ "def", "all", "(", "self", ",", "count", "=", "500", ",", "offset", "=", "0", ",", "type", "=", "None", ",", "inactive", "=", "None", ",", "emailFilter", "=", "None", ",", "tag", "=", "None", ",", "messageID", "=", "None", ",", "fromdate", "=", "...
32
19.268293
def set_hostname(hostname=None, **kwargs): ''' Set the device's hostname hostname The name to be set comment Provide a comment to the commit dev_timeout : 30 The NETCONF RPC timeout (in seconds) confirm Provide time in minutes for commit confirmation. If this op...
[ "def", "set_hostname", "(", "hostname", "=", "None", ",", "*", "*", "kwargs", ")", ":", "conn", "=", "__proxy__", "[", "'junos.conn'", "]", "(", ")", "ret", "=", "{", "}", "if", "hostname", "is", "None", ":", "ret", "[", "'message'", "]", "=", "'Pl...
27.28
22.453333
def read_and_save_data(info_df, raw_dir, sep=";", force_raw=False, force_cellpy=False, export_cycles=False, shifted_cycles=False, export_raw=True, export_ica=False, save=True, use_cellpy_stat_file=False, p...
[ "def", "read_and_save_data", "(", "info_df", ",", "raw_dir", ",", "sep", "=", "\";\"", ",", "force_raw", "=", "False", ",", "force_cellpy", "=", "False", ",", "export_cycles", "=", "False", ",", "shifted_cycles", "=", "False", ",", "export_raw", "=", "True",...
41.657895
21.184211
def GetExpirationTime(self): """Computes the timestamp at which this breakpoint will expire.""" # TODO(emrekultursay): Move this to a common method. if '.' not in self.definition['createTime']: fmt = '%Y-%m-%dT%H:%M:%S%Z' else: fmt = '%Y-%m-%dT%H:%M:%S.%f%Z' create_datetime = datetime.s...
[ "def", "GetExpirationTime", "(", "self", ")", ":", "# TODO(emrekultursay): Move this to a common method.", "if", "'.'", "not", "in", "self", ".", "definition", "[", "'createTime'", "]", ":", "fmt", "=", "'%Y-%m-%dT%H:%M:%S%Z'", "else", ":", "fmt", "=", "'%Y-%m-%dT%H...
39.454545
13.818182
def tab(self, netloc=None, url=None, extra_id=None, use_tid=False): ''' Get a chromium tab from the pool, optionally one that has an association with a specific netloc/URL. If no url or netloc is specified, the per-thread identifier will be used. If `extra_id` is specified, it's stringified value will be mixed...
[ "def", "tab", "(", "self", ",", "netloc", "=", "None", ",", "url", "=", "None", ",", "extra_id", "=", "None", ",", "use_tid", "=", "False", ")", ":", "assert", "self", ".", "alive", ",", "\"Chrome has been shut down! Cannot continue!\"", "if", "not", "netl...
39.822222
27.733333
def get(self, nb=0): """Get the history as a dict of list""" return {i: self.stats_history[i].history_raw(nb=nb) for i in self.stats_history}
[ "def", "get", "(", "self", ",", "nb", "=", "0", ")", ":", "return", "{", "i", ":", "self", ".", "stats_history", "[", "i", "]", ".", "history_raw", "(", "nb", "=", "nb", ")", "for", "i", "in", "self", ".", "stats_history", "}" ]
51.666667
22.666667
def case(self, case_id): """Fetch a case from the database.""" case_obj = self.query(Case).filter_by(case_id=case_id).first() return case_obj
[ "def", "case", "(", "self", ",", "case_id", ")", ":", "case_obj", "=", "self", ".", "query", "(", "Case", ")", ".", "filter_by", "(", "case_id", "=", "case_id", ")", ".", "first", "(", ")", "return", "case_obj" ]
40.5
15.75
def allow_migrate(self, db, model): """ Make sure self._apps go to their own db """ if model._meta.app_label in self._apps: return getattr(model, '_db_alias', model._meta.app_label) == db return None
[ "def", "allow_migrate", "(", "self", ",", "db", ",", "model", ")", ":", "if", "model", ".", "_meta", ".", "app_label", "in", "self", ".", "_apps", ":", "return", "getattr", "(", "model", ",", "'_db_alias'", ",", "model", ".", "_meta", ".", "app_label",...
35
10.714286
def supports_card_actions(channel_id: str, button_cnt: int = 100) -> bool: """Determine if a number of Card Actions are supported by a Channel. Args: channel_id (str): The Channel to check if the Card Actions are supported in. button_cnt (int, optional): Defaults to 100. The num...
[ "def", "supports_card_actions", "(", "channel_id", ":", "str", ",", "button_cnt", ":", "int", "=", "100", ")", "->", "bool", ":", "max_actions", "=", "{", "Channels", ".", "facebook", ":", "3", ",", "Channels", ".", "skype", ":", "3", ",", "Channels", ...
41.652174
25.695652
def load_cov(name): '''Load a datafile with coverage file structure. ''' content = np.genfromtxt(name, skip_header=1, skip_footer=1, usecols=([2])) return content
[ "def", "load_cov", "(", "name", ")", ":", "content", "=", "np", ".", "genfromtxt", "(", "name", ",", "skip_header", "=", "1", ",", "skip_footer", "=", "1", ",", "usecols", "=", "(", "[", "2", "]", ")", ")", "return", "content" ]
29
27.666667
def intercept_(self): """ Intercept (bias) property .. note:: Intercept is defined only for linear learners Intercept (bias) is only defined when the linear model is chosen as base learner (`booster=gblinear`). It is not defined for other base learner types, such ...
[ "def", "intercept_", "(", "self", ")", ":", "if", "getattr", "(", "self", ",", "'booster'", ",", "None", ")", "is", "not", "None", "and", "self", ".", "booster", "!=", "'gblinear'", ":", "raise", "AttributeError", "(", "'Intercept (bias) is not defined for Boo...
41.684211
26.421053
def stop(self): """Stop the background emulation loop.""" if self._started is False: raise ArgumentError("EmulationLoop.stop() called without calling start()") self.verify_calling_thread(False, "Cannot call EmulationLoop.stop() from inside the event loop") if self._thread....
[ "def", "stop", "(", "self", ")", ":", "if", "self", ".", "_started", "is", "False", ":", "raise", "ArgumentError", "(", "\"EmulationLoop.stop() called without calling start()\"", ")", "self", ".", "verify_calling_thread", "(", "False", ",", "\"Cannot call EmulationLoo...
40.454545
29.636364
def no_intersection(to_validate, constraint, violation_cfg): """ Returns violation message if validated and constraint sets have no intersection :param to_validate: :param constraint: :param violation_cfg: :return: """ if len(constraint) == 0 or len(set(constraint).intersection(to_valida...
[ "def", "no_intersection", "(", "to_validate", ",", "constraint", ",", "violation_cfg", ")", ":", "if", "len", "(", "constraint", ")", "==", "0", "or", "len", "(", "set", "(", "constraint", ")", ".", "intersection", "(", "to_validate", ")", ")", ">", "0",...
37.769231
24.692308
def new_noncomment(self, start_lineno, end_lineno): """ We are transitioning from a noncomment to a comment. """ block = NonComment(start_lineno, end_lineno) self.blocks.append(block) self.current_block = block
[ "def", "new_noncomment", "(", "self", ",", "start_lineno", ",", "end_lineno", ")", ":", "block", "=", "NonComment", "(", "start_lineno", ",", "end_lineno", ")", "self", ".", "blocks", ".", "append", "(", "block", ")", "self", ".", "current_block", "=", "bl...
40.833333
6
def or_fault(a, b, out, fault): """Returns True if OR(a, b) == out and fault == 0 or OR(a, b) != out and fault == 1.""" if (a or b) == out: return fault == 0 else: return fault == 1
[ "def", "or_fault", "(", "a", ",", "b", ",", "out", ",", "fault", ")", ":", "if", "(", "a", "or", "b", ")", "==", "out", ":", "return", "fault", "==", "0", "else", ":", "return", "fault", "==", "1" ]
34
14.5
def known_author_patterns(self, val): ''' val must be a dictionary or list of dictionaries e.g., {'attrribute': 'name', 'value': 'my-pubdate', 'content': 'datetime'} or [{'attrribute': 'name', 'value': 'my-pubdate', 'content': 'datetime'}, {'attrribute': 'property...
[ "def", "known_author_patterns", "(", "self", ",", "val", ")", ":", "def", "create_pat_from_dict", "(", "val", ")", ":", "'''Helper function used to create an AuthorPatterns from a dictionary\n '''", "if", "\"tag\"", "in", "val", ":", "pat", "=", "AuthorPattern"...
45.617647
21.558824
def incr_obj(obj, **attrs): """Increments context variables """ for name, value in attrs.iteritems(): v = getattr(obj, name, None) if not hasattr(obj, name) or v is None: v = 0 setattr(obj, name, v + value)
[ "def", "incr_obj", "(", "obj", ",", "*", "*", "attrs", ")", ":", "for", "name", ",", "value", "in", "attrs", ".", "iteritems", "(", ")", ":", "v", "=", "getattr", "(", "obj", ",", "name", ",", "None", ")", "if", "not", "hasattr", "(", "obj", ",...
30.875
6.375
def issueBatchJob(self, jobNode): """ Issues the following command returning a unique jobID. Command is the string to run, memory is an int giving the number of bytes the job needs to run in and cores is the number of cpus needed for the job and error-file is the path of the file to plac...
[ "def", "issueBatchJob", "(", "self", ",", "jobNode", ")", ":", "localID", "=", "self", ".", "handleLocalJob", "(", "jobNode", ")", "if", "localID", ":", "return", "localID", "self", ".", "checkResourceRequest", "(", "jobNode", ".", "memory", ",", "jobNode", ...
46.222222
21.037037
def register_routes(app): """Register routes.""" from . import controllers from flask.blueprints import Blueprint for module in _import_submodules_from_package(controllers): bp = getattr(module, 'bp') if bp and isinstance(bp, Blueprint): app.register_blueprint(bp)
[ "def", "register_routes", "(", "app", ")", ":", "from", ".", "import", "controllers", "from", "flask", ".", "blueprints", "import", "Blueprint", "for", "module", "in", "_import_submodules_from_package", "(", "controllers", ")", ":", "bp", "=", "getattr", "(", ...
33.444444
11.444444
def serialize(self, dt): """ Converts the date to a string using the :py:attr:`~_DateParameterBase.date_format`. """ if dt is None: return str(dt) return dt.strftime(self.date_format)
[ "def", "serialize", "(", "self", ",", "dt", ")", ":", "if", "dt", "is", "None", ":", "return", "str", "(", "dt", ")", "return", "dt", ".", "strftime", "(", "self", ".", "date_format", ")" ]
32.714286
14.714286
def get_pubmed_citation_response(pubmed_identifiers: Iterable[str]): """Get the response from PubMed E-Utils for a given list of PubMed identifiers. :param pubmed_identifiers: :rtype: dict """ pubmed_identifiers = list(pubmed_identifiers) url = EUTILS_URL_FMT.format(','.join( pubmed_ide...
[ "def", "get_pubmed_citation_response", "(", "pubmed_identifiers", ":", "Iterable", "[", "str", "]", ")", ":", "pubmed_identifiers", "=", "list", "(", "pubmed_identifiers", ")", "url", "=", "EUTILS_URL_FMT", ".", "format", "(", "','", ".", "join", "(", "pubmed_id...
33
14.714286
def _create_column(values, dtype): "Creates a column from values with dtype" if str(dtype) == "tensor(int64)": return numpy.array(values, dtype=numpy.int64) elif str(dtype) == "tensor(float)": return numpy.array(values, dtype=numpy.float32) else: raise OnnxRuntimeAssertionError("...
[ "def", "_create_column", "(", "values", ",", "dtype", ")", ":", "if", "str", "(", "dtype", ")", "==", "\"tensor(int64)\"", ":", "return", "numpy", ".", "array", "(", "values", ",", "dtype", "=", "numpy", ".", "int64", ")", "elif", "str", "(", "dtype", ...
46.625
16.875
def find_max_and_min_frequencies(name, mass_range_params, freqs): """ ADD DOCS """ cutoff_fns = pnutils.named_frequency_cutoffs if name not in cutoff_fns.keys(): err_msg = "%s not recognized as a valid cutoff frequency choice." %name err_msg += "Recognized choices: " + " ".join(cuto...
[ "def", "find_max_and_min_frequencies", "(", "name", ",", "mass_range_params", ",", "freqs", ")", ":", "cutoff_fns", "=", "pnutils", ".", "named_frequency_cutoffs", "if", "name", "not", "in", "cutoff_fns", ".", "keys", "(", ")", ":", "err_msg", "=", "\"%s not rec...
43.454545
18.727273
def failover(self, name): """Force a failover of a named master.""" fut = self.execute(b'FAILOVER', name) return wait_ok(fut)
[ "def", "failover", "(", "self", ",", "name", ")", ":", "fut", "=", "self", ".", "execute", "(", "b'FAILOVER'", ",", "name", ")", "return", "wait_ok", "(", "fut", ")" ]
36.5
8.25
def _open_for_write(self): """open the file in write mode""" def put_request(body): """ :param body: """ ownerid, datasetid = parse_dataset_key(self._dataset_key) response = requests.put( "{}/uploads/{}/{}/files/{}".format( ...
[ "def", "_open_for_write", "(", "self", ")", ":", "def", "put_request", "(", "body", ")", ":", "\"\"\"\n\n :param body:\n \"\"\"", "ownerid", ",", "datasetid", "=", "parse_dataset_key", "(", "self", ".", "_dataset_key", ")", "response", "=", "re...
36.045455
15.272727
def fit_transform(self, X, y=None): """ Fit the imputer and then transform input `X` Note: all imputations should have a `fit_transform` method, but only some (like IterativeImputer) also support inductive mode using `fit` or `fit_transform` on `X_train` and then `transform` ...
[ "def", "fit_transform", "(", "self", ",", "X", ",", "y", "=", "None", ")", ":", "X_original", ",", "missing_mask", "=", "self", ".", "prepare_input_data", "(", "X", ")", "observed_mask", "=", "~", "missing_mask", "X", "=", "X_original", ".", "copy", "(",...
40.709677
15.806452
def extract_views_from_urlpatterns(self, urlpatterns, base='', namespace=None): """ Return a list of views from a list of urlpatterns. Each object in the returned list is a three-tuple: (view_func, regex, name) """ views = [] for p in urlpatterns: if isinstan...
[ "def", "extract_views_from_urlpatterns", "(", "self", ",", "urlpatterns", ",", "base", "=", "''", ",", "namespace", "=", "None", ")", ":", "views", "=", "[", "]", "for", "p", "in", "urlpatterns", ":", "if", "isinstance", "(", "p", ",", "(", "URLPattern",...
46.6
20.72
def surround_parse(self, node, pre_char, post_char): """Parse the subnodes of a given node. Subnodes with tags in the `ignore` list are ignored. Prepend `pre_char` and append `post_char` to the output in self.pieces.""" self.add_text(pre_char) self.subnode_parse(node) sel...
[ "def", "surround_parse", "(", "self", ",", "node", ",", "pre_char", ",", "post_char", ")", ":", "self", ".", "add_text", "(", "pre_char", ")", "self", ".", "subnode_parse", "(", "node", ")", "self", ".", "add_text", "(", "post_char", ")" ]
47.857143
10.857143
def decompress(self, value: bytes, max_length: int = 0) -> bytes: """Decompress a chunk, returning newly-available data. Some data may be buffered for later processing; `flush` must be called when there is no more input data to ensure that all data was processed. If ``max_lengt...
[ "def", "decompress", "(", "self", ",", "value", ":", "bytes", ",", "max_length", ":", "int", "=", "0", ")", "->", "bytes", ":", "return", "self", ".", "decompressobj", ".", "decompress", "(", "value", ",", "max_length", ")" ]
47.5
22.916667
def get_name(self): """Get name based on 4 class attributes Each attribute is substituted by '' if attribute does not exist :return: dependent_host_name/dependent_service_description..host_name/service_description :rtype: str TODO: Clean this function (use format for string) ...
[ "def", "get_name", "(", "self", ")", ":", "return", "getattr", "(", "self", ",", "'dependent_host_name'", ",", "''", ")", "+", "'/'", "+", "getattr", "(", "self", ",", "'dependent_service_description'", ",", "''", ")", "+", "'..'", "+", "getattr", "(", "...
46.833333
22.333333
def merge_lines(top, bot, icod="top"): """ Merges two lines (top and bot) in the way that the overlapping make senses. Args: top (str): the top line bot (str): the bottom line icod (top or bot): in case of doubt, which line should have priority? Default: "top"...
[ "def", "merge_lines", "(", "top", ",", "bot", ",", "icod", "=", "\"top\"", ")", ":", "ret", "=", "\"\"", "for", "topc", ",", "botc", "in", "zip", "(", "top", ",", "bot", ")", ":", "if", "topc", "==", "botc", ":", "ret", "+=", "topc", "elif", "t...
37.196078
14.45098
def merge(self, base, head, message=''): """Perform a merge from ``head`` into ``base``. :param str base: (required), where you're merging into :param str head: (required), where you're merging from :param str message: (optional), message to be used for the commit :returns: :cla...
[ "def", "merge", "(", "self", ",", "base", ",", "head", ",", "message", "=", "''", ")", ":", "url", "=", "self", ".", "_build_url", "(", "'merges'", ",", "base_url", "=", "self", ".", "_api", ")", "data", "=", "{", "'base'", ":", "base", ",", "'he...
46.571429
16.285714
def get_implicit_depends_on(input_hash, depends_on): ''' Add DNAnexus links to non-closed data objects in input_hash to depends_on ''' q = [] for field in input_hash: possible_dep = get_nonclosed_data_obj_link(input_hash[field]) if possible_dep is not None: depends_on.ap...
[ "def", "get_implicit_depends_on", "(", "input_hash", ",", "depends_on", ")", ":", "q", "=", "[", "]", "for", "field", "in", "input_hash", ":", "possible_dep", "=", "get_nonclosed_data_obj_link", "(", "input_hash", "[", "field", "]", ")", "if", "possible_dep", ...
41.103448
19.931034
def _set_is_address_family_v4(self, v, load=False): """ Setter method for is_address_family_v4, mapped from YANG variable /isis_state/router_isis_config/is_address_family_v4 (container) If this variable is read-only (config: false) in the source YANG file, then _set_is_address_family_v4 is considered as...
[ "def", "_set_is_address_family_v4", "(", "self", ",", "v", ",", "load", "=", "False", ")", ":", "if", "hasattr", "(", "v", ",", "\"_utype\"", ")", ":", "v", "=", "v", ".", "_utype", "(", "v", ")", "try", ":", "t", "=", "YANGDynClass", "(", "v", "...
80.083333
38.875
def search(self): """ Construct the Search object. """ s = Search(doc_type=self.doc_types, using=es.client, index=es.index_name) # don't return any fields, just the metadata s = s.fields([]) # Sort from parameters s = s.sort(*self.sorts)...
[ "def", "search", "(", "self", ")", ":", "s", "=", "Search", "(", "doc_type", "=", "self", ".", "doc_types", ",", "using", "=", "es", ".", "client", ",", "index", "=", "es", ".", "index_name", ")", "# don't return any fields, just the metadata", "s", "=", ...
38.375
10.625
def convert_compartment_entry(self, compartment, adjacencies): """Convert compartment entry to YAML dict. Args: compartment: :class:`psamm.datasource.entry.CompartmentEntry`. adjacencies: Sequence of IDs or a single ID of adjacent compartments (or None). ...
[ "def", "convert_compartment_entry", "(", "self", ",", "compartment", ",", "adjacencies", ")", ":", "d", "=", "OrderedDict", "(", ")", "d", "[", "'id'", "]", "=", "compartment", ".", "id", "if", "adjacencies", "is", "not", "None", ":", "d", "[", "'adjacen...
37.333333
17.571429
def create_rectangular_prism(origin, size): ''' Return a Mesh which is an axis-aligned rectangular prism. One vertex is `origin`; the diametrically opposite vertex is `origin + size`. size: 3x1 array. ''' from lace.topology import quads_to_tris lower_base_plane = np.array([ # Lowe...
[ "def", "create_rectangular_prism", "(", "origin", ",", "size", ")", ":", "from", "lace", ".", "topology", "import", "quads_to_tris", "lower_base_plane", "=", "np", ".", "array", "(", "[", "# Lower base plane", "origin", ",", "origin", "+", "np", ".", "array", ...
28.806452
19.709677
def visitInlineShapeAtomNodeConstraint(self, ctx: ShExDocParser.InlineShapeAtomNodeConstraintContext): """ inlineShapeAtomNodeConstraint: nodeConstraint inlineShapeOrRef? # inlineShapeAtomShapeOrRef """ nc = ShexNodeExpressionParser(self.context, self.label) nc.visit(ctx.nodeConstraint()) ...
[ "def", "visitInlineShapeAtomNodeConstraint", "(", "self", ",", "ctx", ":", "ShExDocParser", ".", "InlineShapeAtomNodeConstraintContext", ")", ":", "nc", "=", "ShexNodeExpressionParser", "(", "self", ".", "context", ",", "self", ".", "label", ")", "nc", ".", "visit...
58.428571
21.5
def _set_new_object(self, new_obj, inherited_obj, new_class, superclass, qualifier_repo, propagated, type_str): """ Set the object attributes for a single object and resolve the qualifiers. This sets attributes for Properties, Methods, and Parameters. """ ...
[ "def", "_set_new_object", "(", "self", ",", "new_obj", ",", "inherited_obj", ",", "new_class", ",", "superclass", ",", "qualifier_repo", ",", "propagated", ",", "type_str", ")", ":", "assert", "isinstance", "(", "new_obj", ",", "(", "CIMMethod", ",", "CIMPrope...
40.133333
16.066667
def fpy_interface(fpy, static, interface, typedict): """Splices the full list of subroutines and the module procedure list into the static.f90 file. :arg static: the string contents of the static.f90 file. :arg interface: the name of the interface *field* being replaced. :arg typedict: the dictiona...
[ "def", "fpy_interface", "(", "fpy", ",", "static", ",", "interface", ",", "typedict", ")", ":", "modprocs", "=", "[", "]", "subtext", "=", "[", "]", "for", "dtype", ",", "combos", "in", "list", "(", "typedict", ".", "items", "(", ")", ")", ":", "fo...
43.478261
19.304348
def system(*args, **kwargs): """Execute the given bash command""" kwargs.setdefault('stdout', subprocess.PIPE) proc = subprocess.Popen(args, **kwargs) out, _ = proc.communicate() if proc.returncode: raise SystemExit(proc.returncode) return out.decode('utf-8')
[ "def", "system", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "kwargs", ".", "setdefault", "(", "'stdout'", ",", "subprocess", ".", "PIPE", ")", "proc", "=", "subprocess", ".", "Popen", "(", "args", ",", "*", "*", "kwargs", ")", "out", ",",...
35.5
7.5
def check_data(cls, name, dims, is_unstructured): """ A validation method for the data shape Parameters ---------- name: str or list of str The variable names (one variable per array) dims: list with length 1 or list of lists with length 1 The dim...
[ "def", "check_data", "(", "cls", ",", "name", ",", "dims", ",", "is_unstructured", ")", ":", "if", "isinstance", "(", "name", ",", "six", ".", "string_types", ")", "or", "not", "is_iterable", "(", "name", ")", ":", "name", "=", "[", "name", "]", "dim...
40.538462
17.076923
def _rate_limit_status(self, api=None, mode=None): """ Verifying the API limits """ if api == None: api = self.connectToAPI() if mode == None: print json.dumps(api.rate_limit_status(), indent=2) raw_input("<Press ENTER>") else: ...
[ "def", "_rate_limit_status", "(", "self", ",", "api", "=", "None", ",", "mode", "=", "None", ")", ":", "if", "api", "==", "None", ":", "api", "=", "self", ".", "connectToAPI", "(", ")", "if", "mode", "==", "None", ":", "print", "json", ".", "dumps"...
52
22.307692
def update_config( self, filename="MAGTUNE_PYMAGICC.CFG", top_level_key="nml_allcfgs", **kwargs ): """Updates a configuration file for MAGICC Updates the contents of a fortran namelist in the run directory, creating a new namelist if none exists. Parameters --------...
[ "def", "update_config", "(", "self", ",", "filename", "=", "\"MAGTUNE_PYMAGICC.CFG\"", ",", "top_level_key", "=", "\"nml_allcfgs\"", ",", "*", "*", "kwargs", ")", ":", "kwargs", "=", "self", ".", "_format_config", "(", "kwargs", ")", "fname", "=", "join", "(...
27.578947
21.394737
def reload_core(host=None, core_name=None): ''' MULTI-CORE HOSTS ONLY Load a new core from the same configuration as an existing registered core. While the "new" core is initializing, the "old" one will continue to accept requests. Once it has finished, all new request will go to the "new" core, ...
[ "def", "reload_core", "(", "host", "=", "None", ",", "core_name", "=", "None", ")", ":", "ret", "=", "_get_return_dict", "(", ")", "if", "not", "_check_for_cores", "(", ")", ":", "err", "=", "[", "'solr.reload_core can only be called by \"multi-core\" minions'", ...
34.888889
22.533333
def call_workflow_event(instance, event, after=True): """Calls the instance's workflow event """ if not event.transition: return False portal_type = instance.portal_type wf_module = _load_wf_module('{}.events'.format(portal_type.lower())) if not wf_module: return False # In...
[ "def", "call_workflow_event", "(", "instance", ",", "event", ",", "after", "=", "True", ")", ":", "if", "not", "event", ".", "transition", ":", "return", "False", "portal_type", "=", "instance", ".", "portal_type", "wf_module", "=", "_load_wf_module", "(", "...
31.090909
18.318182