text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def update_fallbackserver(self, serverid, data): """Update Fallback server""" return self.api_call( ENDPOINTS['fallbackservers']['update'], dict(serverid=serverid), body=data)
[ "def", "update_fallbackserver", "(", "self", ",", "serverid", ",", "data", ")", ":", "return", "self", ".", "api_call", "(", "ENDPOINTS", "[", "'fallbackservers'", "]", "[", "'update'", "]", ",", "dict", "(", "serverid", "=", "serverid", ")", ",", "body", ...
37
8.666667
def _extractReporterIons(ionArrays, reporterMz, mzTolerance): """Find and a list of reporter ions and return mz and intensity values. Expected reporter mz values are searched in "ionArray['mz']" and reported if the observed relative deviation is less than specified by "mzTolerance". In the case of mult...
[ "def", "_extractReporterIons", "(", "ionArrays", ",", "reporterMz", ",", "mzTolerance", ")", ":", "reporterIons", "=", "{", "'mz'", ":", "[", "]", ",", "'i'", ":", "[", "]", "}", "for", "reporterMzValue", "in", "reporterMz", ":", "limHi", "=", "reporterMzV...
48.266667
21.066667
def add_chapter(self, title): ''' Adds a new chapter to the report. :param str title: Title of the chapter. ''' chap_id = 'chap%s' % self.chap_counter self.chap_counter += 1 self.sidebar += '<a href="#%s" class="list-group-item">%s</a>\n' % ( chap_id,...
[ "def", "add_chapter", "(", "self", ",", "title", ")", ":", "chap_id", "=", "'chap%s'", "%", "self", ".", "chap_counter", "self", ".", "chap_counter", "+=", "1", "self", ".", "sidebar", "+=", "'<a href=\"#%s\" class=\"list-group-item\">%s</a>\\n'", "%", "(", "cha...
34.636364
18.636364
def items(self, limit=10000): """ Return all of the Items and Collections for this search """ _limit = 500 if 'ids' in self.kwargs: col = self.kwargs.get('query', {}).get('collection', {}).get('eq', None) if col is None: raise SatSearchError('Collection re...
[ "def", "items", "(", "self", ",", "limit", "=", "10000", ")", ":", "_limit", "=", "500", "if", "'ids'", "in", "self", ".", "kwargs", ":", "col", "=", "self", ".", "kwargs", ".", "get", "(", "'query'", ",", "{", "}", ")", ".", "get", "(", "'coll...
39.631579
20.815789
def _start_primary(self): """Start as the primary""" self.em.start() self.em.set_secondary_state(_STATE_RUNNING) self._set_shared_instances()
[ "def", "_start_primary", "(", "self", ")", ":", "self", ".", "em", ".", "start", "(", ")", "self", ".", "em", ".", "set_secondary_state", "(", "_STATE_RUNNING", ")", "self", ".", "_set_shared_instances", "(", ")" ]
33.8
9.4
async def process_graph_input(graph, stream, value, rpc_executor): """Process an input through this sensor graph. The tick information in value should be correct and is transfered to all results produced by nodes acting on this tick. This coroutine is an asyncio compatible version of SensorGraph.proce...
[ "async", "def", "process_graph_input", "(", "graph", ",", "stream", ",", "value", ",", "rpc_executor", ")", ":", "graph", ".", "sensor_log", ".", "push", "(", "stream", ",", "value", ")", "# FIXME: This should be specified in our device model", "if", "stream", "."...
40.829268
23.536585
def update_event_hub(self, hub_name, hub=None): ''' Updates an Event Hub. hub_name: Name of event hub. hub: Optional. Event hub properties. Instance of EventHub class. hub.message_retention_in_days: Number of days to retain the events for this...
[ "def", "update_event_hub", "(", "self", ",", "hub_name", ",", "hub", "=", "None", ")", ":", "_validate_not_none", "(", "'hub_name'", ",", "hub_name", ")", "request", "=", "HTTPRequest", "(", ")", "request", ".", "method", "=", "'PUT'", "request", ".", "hos...
41.956522
22.130435
def dof(self, index=None): """The number of degrees of freedom""" if index is None: dof = 0 for i in range(self.len): dof += self.A[i].shape[0] * self.F[i].shape[1] return dof else: return self.A[index].shape[0] * self.F[index].shap...
[ "def", "dof", "(", "self", ",", "index", "=", "None", ")", ":", "if", "index", "is", "None", ":", "dof", "=", "0", "for", "i", "in", "range", "(", "self", ".", "len", ")", ":", "dof", "+=", "self", ".", "A", "[", "i", "]", ".", "shape", "["...
35.111111
16.222222
def read(self, input_buffer, kmip_version=enums.KMIPVersion.KMIP_1_0): """ Read the data encoding the GetAttributes response payload and decode it into its constituent parts. Args: input_buffer (stream): A data stream containing encoded object data, supportin...
[ "def", "read", "(", "self", ",", "input_buffer", ",", "kmip_version", "=", "enums", ".", "KMIPVersion", ".", "KMIP_1_0", ")", ":", "super", "(", "GetAttributesResponsePayload", ",", "self", ")", ".", "read", "(", "input_buffer", ",", "kmip_version", "=", "km...
43.811321
22
async def send_message(self, segments, image_file=None, image_id=None, image_user_id=None): """Send a message to this conversation. A per-conversation lock is acquired to ensure that messages are sent in the correct order when this method is called multiple times ...
[ "async", "def", "send_message", "(", "self", ",", "segments", ",", "image_file", "=", "None", ",", "image_id", "=", "None", ",", "image_user_id", "=", "None", ")", ":", "async", "with", "self", ".", "_send_message_lock", ":", "if", "image_file", ":", "try"...
47.823529
22.490196
def get_clan(self, tag: crtag, timeout: int=None): """Get inforamtion about a clan Parameters ---------- tag: str A valid tournament tag. Minimum length: 3 Valid characters: 0289PYLQGRJCUV timeout: Optional[int] = None Custom timeout that over...
[ "def", "get_clan", "(", "self", ",", "tag", ":", "crtag", ",", "timeout", ":", "int", "=", "None", ")", ":", "url", "=", "self", ".", "api", ".", "CLAN", "+", "'/'", "+", "tag", "return", "self", ".", "_get_model", "(", "url", ",", "FullClan", ",...
34.153846
13.692308
def get_object(self, pid=None, type=None, create=None): """ Initialize a single object from Fedora, or create a new one, with the same Fedora configuration and credentials. :param pid: pid of the object to request, or a function that can be called to get one. if not ...
[ "def", "get_object", "(", "self", ",", "pid", "=", "None", ",", "type", "=", "None", ",", "create", "=", "None", ")", ":", "objtype", "=", "type", "or", "self", ".", "default_object_type", "if", "pid", "is", "None", ":", "if", "create", "is", "None",...
41.666667
21.166667
def sum(self): """Summary Returns: TYPE: Description """ return GroupedDataFrameWeld( grizzly_impl.groupby_sum( self.columns, self.column_types, self.grouping_columns, self.grouping_column_types ...
[ "def", "sum", "(", "self", ")", ":", "return", "GroupedDataFrameWeld", "(", "grizzly_impl", ".", "groupby_sum", "(", "self", ".", "columns", ",", "self", ".", "column_types", ",", "self", ".", "grouping_columns", ",", "self", ".", "grouping_column_types", ")",...
25.777778
11.611111
def _init_dates(self): """Initialize all dates properties """ if self.total_transactions == 0: return None self.epoch_start = Result.select(Result.epoch).order_by(Result.epoch.asc()).limit(1).get().epoch self.epoch_finish = Result.select(Result.epoch).order_by(Result....
[ "def", "_init_dates", "(", "self", ")", ":", "if", "self", ".", "total_transactions", "==", "0", ":", "return", "None", "self", ".", "epoch_start", "=", "Result", ".", "select", "(", "Result", ".", "epoch", ")", ".", "order_by", "(", "Result", ".", "ep...
60.666667
31.444444
def _iter(self): """Generate (name, est, weight) tuples excluding None transformers """ get_weight = (self.transformer_weights or {}).get return ((name, trans, get_weight(name)) for name, trans in self.transformer_list if trans is not None)
[ "def", "_iter", "(", "self", ")", ":", "get_weight", "=", "(", "self", ".", "transformer_weights", "or", "{", "}", ")", ".", "get", "return", "(", "(", "name", ",", "trans", ",", "get_weight", "(", "name", ")", ")", "for", "name", ",", "trans", "in...
42.571429
9.571429
def showImage(layout, imagePath="", imageObj=None, offset=(0, 0), bgcolor=COLORS.Off, brightness=255): """Display an image on the matrix""" if not isinstance(layout, Matrix): raise RuntimeError("Must use Matrix with showImage!") layout.all_off() return show_image(layout.set, layo...
[ "def", "showImage", "(", "layout", ",", "imagePath", "=", "\"\"", ",", "imageObj", "=", "None", ",", "offset", "=", "(", "0", ",", "0", ")", ",", "bgcolor", "=", "COLORS", ".", "Off", ",", "brightness", "=", "255", ")", ":", "if", "not", "isinstanc...
40.7
21.1
def save(self, request, connect=False): """ Saves a new account. Note that while the account is new, the user may be an existing one (when connecting accounts) """ assert not self.is_existing user = self.user user.save() self.account.user = user se...
[ "def", "save", "(", "self", ",", "request", ",", "connect", "=", "False", ")", ":", "assert", "not", "self", ".", "is_existing", "user", "=", "self", ".", "user", "user", ".", "save", "(", ")", "self", ".", "account", ".", "user", "=", "user", "sel...
34.944444
14.5
def get_raw(self, url: str, _attempt=1) -> requests.Response: """Downloads a file anonymously. :raises QueryReturnedNotFoundException: When the server responds with a 404. :raises QueryReturnedForbiddenException: When the server responds with a 403. :raises ConnectionException: When dow...
[ "def", "get_raw", "(", "self", ",", "url", ":", "str", ",", "_attempt", "=", "1", ")", "->", "requests", ".", "Response", ":", "with", "self", ".", "get_anonymous_session", "(", ")", "as", "anonymous_session", ":", "resp", "=", "anonymous_session", ".", ...
49.047619
21.809524
def blit_2x( self, console: tcod.console.Console, dest_x: int, dest_y: int, img_x: int = 0, img_y: int = 0, img_width: int = -1, img_height: int = -1, ) -> None: """Blit onto a Console with double resolution. Args: console ...
[ "def", "blit_2x", "(", "self", ",", "console", ":", "tcod", ".", "console", ".", "Console", ",", "dest_x", ":", "int", ",", "dest_y", ":", "int", ",", "img_x", ":", "int", "=", "0", ",", "img_y", ":", "int", "=", "0", ",", "img_width", ":", "int"...
32.909091
19.606061
def cache_files(db, aid: int, anime_files: AnimeFiles) -> None: """Cache files for anime.""" with db: cache_status(db, aid) db.cursor().execute( """UPDATE cache_anime SET anime_files=? WHERE aid=?""", (anime_files.to_json(), aid))
[ "def", "cache_files", "(", "db", ",", "aid", ":", "int", ",", "anime_files", ":", "AnimeFiles", ")", "->", "None", ":", "with", "db", ":", "cache_status", "(", "db", ",", "aid", ")", "db", ".", "cursor", "(", ")", ".", "execute", "(", "\"\"\"UPDATE c...
32.666667
9.555556
def _chunk(self, response, size=4096): """ downloads a web response in pieces """ method = response.headers.get("content-encoding") if method == "gzip": d = zlib.decompressobj(16+zlib.MAX_WBITS) b = response.read(size) while b: data = d.decompr...
[ "def", "_chunk", "(", "self", ",", "response", ",", "size", "=", "4096", ")", ":", "method", "=", "response", ".", "headers", ".", "get", "(", "\"content-encoding\"", ")", "if", "method", "==", "\"gzip\"", ":", "d", "=", "zlib", ".", "decompressobj", "...
34.3125
10.4375
def get_floating_ip(self, ip): """ Returns a of FloatingIP object by its IP address. """ return FloatingIP.get_object(api_token=self.token, ip=ip)
[ "def", "get_floating_ip", "(", "self", ",", "ip", ")", ":", "return", "FloatingIP", ".", "get_object", "(", "api_token", "=", "self", ".", "token", ",", "ip", "=", "ip", ")" ]
35.6
11.2
def png_as_base64_str(self, scale=1, module_color=(0, 0, 0, 255), background=(255, 255, 255, 255), quiet_zone=4): """This method uses the png render and returns the PNG image encoded as base64 string. This can be useful for creating dynamic PNG images for web developmen...
[ "def", "png_as_base64_str", "(", "self", ",", "scale", "=", "1", ",", "module_color", "=", "(", "0", ",", "0", ",", "0", ",", "255", ")", ",", "background", "=", "(", "255", ",", "255", ",", "255", ",", "255", ")", ",", "quiet_zone", "=", "4", ...
45.703704
27.259259
def action_stats(self, hostname=None): "Shows stats (possibly limited by hostname)" format = "%-35s %-11s %-11s %-11s %-11s" print format % ("HOST", "OPEN", "COMPLETED", "BYTES IN", "BYTES OUT") for host, details in sorted(self.client.stats(hostname).items()): print format % ...
[ "def", "action_stats", "(", "self", ",", "hostname", "=", "None", ")", ":", "format", "=", "\"%-35s %-11s %-11s %-11s %-11s\"", "print", "format", "%", "(", "\"HOST\"", ",", "\"OPEN\"", ",", "\"COMPLETED\"", ",", "\"BYTES IN\"", ",", "\"BYTES OUT\"", ")", "for",...
45.416667
15.416667
def debug_application(self, environ, start_response): """Run the application and preserve the traceback frames. :param environ: The environment which is passed into the wsgi application :type environ: dict[str, object] :param start_response: The start_response function of the wsgi appli...
[ "def", "debug_application", "(", "self", ",", "environ", ",", "start_response", ")", ":", "adapter", "=", "self", ".", "_debug_map", ".", "bind_to_environ", "(", "environ", ")", "if", "adapter", ".", "test", "(", ")", ":", "_", ",", "args", "=", "adapter...
47.111111
23.222222
def directions(self, origin, destination, mode=None, alternatives=None, waypoints=None, optimize_waypoints=False, avoid=None, language=None, units=None, region=None, departure_time=None, arrival_time=None, sensor=None): """Get direction...
[ "def", "directions", "(", "self", ",", "origin", ",", "destination", ",", "mode", "=", "None", ",", "alternatives", "=", "None", ",", "waypoints", "=", "None", ",", "optimize_waypoints", "=", "False", ",", "avoid", "=", "None", ",", "language", "=", "Non...
57.648148
26.574074
def load_reference(name, element_type, version): """ Look for an element of the given type, name and version and return its reference structure :type element_type: ``str`` :param element_type: the element type to look for (e.g. 'Segment') :type name: ``str`` :param name: the element name to loo...
[ "def", "load_reference", "(", "name", ",", "element_type", ",", "version", ")", ":", "lib", "=", "load_library", "(", "version", ")", "ref", "=", "lib", ".", "get", "(", "name", ",", "element_type", ")", "return", "ref" ]
43.046512
22.767442
def find_node_group_membership(self, node): """ Identifies the group for which a node belongs to. """ for group, nodelist in self.nodes.items(): if node in nodelist: return group
[ "def", "find_node_group_membership", "(", "self", ",", "node", ")", ":", "for", "group", ",", "nodelist", "in", "self", ".", "nodes", ".", "items", "(", ")", ":", "if", "node", "in", "nodelist", ":", "return", "group" ]
33.142857
7.142857
def work_once(self, free_pool_slots=1, max_jobs=None): """ Does one lookup for new jobs, inside the inner work loop """ dequeued_jobs = 0 available_queues = [ queue for queue in self.queues if queue.root_id not in self.paused_queues and queue.id not in self....
[ "def", "work_once", "(", "self", ",", "free_pool_slots", "=", "1", ",", "max_jobs", "=", "None", ")", ":", "dequeued_jobs", "=", "0", "available_queues", "=", "[", "queue", "for", "queue", "in", "self", ".", "queues", "if", "queue", ".", "root_id", "not"...
35.679245
24.320755
def apply_vcc(self,vcc): """ Applies velocity contrast curve constraint to each population See :func:`vespa.stars.StarPopulation.apply_vcc`; all arguments passed to that function for each population. """ if 'secondary spectrum' not in self.constraints: self....
[ "def", "apply_vcc", "(", "self", ",", "vcc", ")", ":", "if", "'secondary spectrum'", "not", "in", "self", ".", "constraints", ":", "self", ".", "constraints", ".", "append", "(", "'secondary spectrum'", ")", "for", "pop", "in", "self", ".", "poplist", ":",...
36.6875
18.8125
def compile(manager, path, allow_naked_names, allow_nested, disallow_unqualified_translocations, no_identifier_validation, no_citation_clearing, required_annotations, skip_tqdm, verbose): """Compile a BEL script to a graph.""" if verbose: logging.basicConfig(level=logging.DEBUG) log....
[ "def", "compile", "(", "manager", ",", "path", ",", "allow_naked_names", ",", "allow_nested", ",", "disallow_unqualified_translocations", ",", "no_identifier_validation", ",", "no_citation_clearing", ",", "required_annotations", ",", "skip_tqdm", ",", "verbose", ")", ":...
37.935484
20.516129
def check_version(version): """Takes a version string or tuple and raises ValueError in case the passed version is newer than the current version of pgi. Keep in mind that the pgi version is different from the pygobject one. """ if isinstance(version, string_types): version = tuple(map(int...
[ "def", "check_version", "(", "version", ")", ":", "if", "isinstance", "(", "version", ",", "string_types", ")", ":", "version", "=", "tuple", "(", "map", "(", "int", ",", "version", ".", "split", "(", "\".\"", ")", ")", ")", "if", "version", ">", "ve...
38.285714
19.071429
def resolve_config_file_path(self, config_filepath): """ Determines whether given path is valid, and if so uses it. Otherwise searches both the working directory and nomenclate/core for the specified config file. :param config_filepath: str, file path or relative file name within package ...
[ "def", "resolve_config_file_path", "(", "self", ",", "config_filepath", ")", ":", "search_paths", "=", "[", "config_filepath", ",", "os", ".", "path", ".", "normpath", "(", "os", ".", "path", ".", "join", "(", "os", ".", "getcwd", "(", ")", ",", "config_...
48.95
26.8
def rule_index(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") rule = ET.SubElement(config, "rule", xmlns="urn:brocade.com:mgmt:brocade-aaa") index = ET.SubElement(rule, "index") index.text = kwargs.pop('index') callback = kwargs.pop('ca...
[ "def", "rule_index", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "rule", "=", "ET", ".", "SubElement", "(", "config", ",", "\"rule\"", ",", "xmlns", "=", "\"urn:brocade.com:mgmt:brocade-aaa\"...
36.7
12.8
def get_at(self, root_node, key): """ Get value of a key when the root node was `root_node` :param root_node: :param key: :return: """ return self._get(root_node, bin_to_nibbles(to_string(key)))
[ "def", "get_at", "(", "self", ",", "root_node", ",", "key", ")", ":", "return", "self", ".", "_get", "(", "root_node", ",", "bin_to_nibbles", "(", "to_string", "(", "key", ")", ")", ")" ]
30.375
14.375
def register(self, metadata): """ Register a distribution on PyPI, using the provided metadata. :param metadata: A :class:`Metadata` instance defining at least a name and version number for the distribution to be registered. :return: The...
[ "def", "register", "(", "self", ",", "metadata", ")", ":", "self", ".", "check_credentials", "(", ")", "metadata", ".", "validate", "(", ")", "d", "=", "metadata", ".", "todict", "(", ")", "d", "[", "':action'", "]", "=", "'verify'", "request", "=", ...
39.157895
14.947368
def _exec(self, globals_dict=None): """exec compiled code""" globals_dict = globals_dict or {} globals_dict.setdefault('__builtins__', {}) exec(self._code, globals_dict) return globals_dict
[ "def", "_exec", "(", "self", ",", "globals_dict", "=", "None", ")", ":", "globals_dict", "=", "globals_dict", "or", "{", "}", "globals_dict", ".", "setdefault", "(", "'__builtins__'", ",", "{", "}", ")", "exec", "(", "self", ".", "_code", ",", "globals_d...
37.333333
5.333333
def _convert_sam_function_resource(name, resource_properties, layers): """ Converts a AWS::Serverless::Function resource to a Function configuration usable by the provider. :param string name: LogicalID of the resource NOTE: This is *not* the function name because not all functions ...
[ "def", "_convert_sam_function_resource", "(", "name", ",", "resource_properties", ",", "layers", ")", ":", "codeuri", "=", "SamFunctionProvider", ".", "_extract_sam_function_codeuri", "(", "name", ",", "resource_properties", ",", "\"CodeUri\"", ")", "LOG", ".", "debug...
45.36
28.96
def receive(self, data): """ Create and return a message from data, also triggers the **receive** event Returns: - Message: message object """ self.log_debug("Received: %s" % (data)) message = self.make_message(data) self.trigger("receive", ...
[ "def", "receive", "(", "self", ",", "data", ")", ":", "self", ".", "log_debug", "(", "\"Received: %s\"", "%", "(", "data", ")", ")", "message", "=", "self", ".", "make_message", "(", "data", ")", "self", ".", "trigger", "(", "\"receive\"", ",", "data",...
27.538462
16
def CreateAllStaticRAPIDFiles(in_drainage_line, river_id, length_id, slope_id, next_down_id, rapid_output_folder, kfac_celerity=1000.0/3600....
[ "def", "CreateAllStaticRAPIDFiles", "(", "in_drainage_line", ",", "river_id", ",", "length_id", ",", "slope_id", ",", "next_down_id", ",", "rapid_output_folder", ",", "kfac_celerity", "=", "1000.0", "/", "3600.0", ",", "kfac_formula_type", "=", "3", ",", "kfac_lengt...
41.582677
15.88189
def c_metadata(api, args, verbose=False): """ Set or get metadata associated with an object:: usage: cdstar metadata <URL> [<JSON>] <JSON> Path to metadata in JSON, or JSON literal. """ obj = api.get_object(args['<URL>'].split('/')[-1]) if not set_metadata(args['<JSON>'], obj): return jso...
[ "def", "c_metadata", "(", "api", ",", "args", ",", "verbose", "=", "False", ")", ":", "obj", "=", "api", ".", "get_object", "(", "args", "[", "'<URL>'", "]", ".", "split", "(", "'/'", ")", "[", "-", "1", "]", ")", "if", "not", "set_metadata", "("...
31.636364
12.545455
def _compute_standard_dev(self, rup, imt, C): """ Compute the the standard deviation in terms of magnitude described on page 744, eq. 4 """ sigma_mean = 0. if imt.name in "SA PGA": psi = -6.898E-3 else: psi = -3.054E-5 if rup.mag <=...
[ "def", "_compute_standard_dev", "(", "self", ",", "rup", ",", "imt", ",", "C", ")", ":", "sigma_mean", "=", "0.", "if", "imt", ".", "name", "in", "\"SA PGA\"", ":", "psi", "=", "-", "6.898E-3", "else", ":", "psi", "=", "-", "3.054E-5", "if", "rup", ...
31.6
12
def extract(self, zip_archive, font_files): """ Extract files to install """ # Get a temp directory tmp_container = tempfile.mkdtemp(prefix='icomoon-tmp') self._debug("* Temporary dir for extracted archive: {}", tmp_container) # Extract manifest to temp directory...
[ "def", "extract", "(", "self", ",", "zip_archive", ",", "font_files", ")", ":", "# Get a temp directory", "tmp_container", "=", "tempfile", ".", "mkdtemp", "(", "prefix", "=", "'icomoon-tmp'", ")", "self", ".", "_debug", "(", "\"* Temporary dir for extracted archive...
36.576923
17.5
def build_reply_markup(self, buttons, inline_only=False): """ Builds a :tl`ReplyInlineMarkup` or :tl:`ReplyKeyboardMarkup` for the given buttons, or does nothing if either no buttons are provided or the provided argument is already a reply markup. This will add any event handler...
[ "def", "build_reply_markup", "(", "self", ",", "buttons", ",", "inline_only", "=", "False", ")", ":", "if", "buttons", "is", "None", ":", "return", "None", "try", ":", "if", "buttons", ".", "SUBCLASS_OF_ID", "==", "0xe2e10ef2", ":", "return", "buttons", "#...
36.441176
18.117647
def add_ace(path, objectType, user, permission, acetype, propagation): r''' add an ace to an object path: path to the object (i.e. c:\\temp\\file, HKEY_LOCAL_MACHINE\\SOFTWARE\\KEY, etc) user: user to add permission: permissions for the user acetype: either allow/deny for each user/permissio...
[ "def", "add_ace", "(", "path", ",", "objectType", ",", "user", ",", "permission", ",", "acetype", ",", "propagation", ")", ":", "ret", "=", "{", "'result'", ":", "None", ",", "'changes'", ":", "{", "}", ",", "'comment'", ":", "''", "}", "if", "(", ...
42.2
24.457143
def execute(self): """ Execute the actions necessary to prepare the instances and returns None. :return: None """ self.print_info() if (self._config.state.prepared and not self._config.command_args.get('force')): msg = 'Skipping, inst...
[ "def", "execute", "(", "self", ")", ":", "self", ".", "print_info", "(", ")", "if", "(", "self", ".", "_config", ".", "state", ".", "prepared", "and", "not", "self", ".", "_config", ".", "command_args", ".", "get", "(", "'force'", ")", ")", ":", "m...
29
20.545455
def add(self, key, content, **metadata): """ :param key: Document unique identifier. :param str content: Content to store and index for search. :param metadata: Arbitrary key/value pairs to store for document. Add a document to the search index. """ self.members....
[ "def", "add", "(", "self", ",", "key", ",", "content", ",", "*", "*", "metadata", ")", ":", "self", ".", "members", ".", "add", "(", "key", ")", "document_hash", "=", "self", ".", "_get_hash", "(", "key", ")", "document_hash", ".", "update", "(", "...
37.533333
14.333333
def getEmptyCells(self): """return a (x, y) pair for each empty cell""" return [(x, y) for x in self.__size_range for y in self.__size_range if self.getCell(x, y) == 0]
[ "def", "getEmptyCells", "(", "self", ")", ":", "return", "[", "(", "x", ",", "y", ")", "for", "x", "in", "self", ".", "__size_range", "for", "y", "in", "self", ".", "__size_range", "if", "self", ".", "getCell", "(", "x", ",", "y", ")", "==", "0",...
42.4
13.2
def move_transition_point(self, fragment_index, value): """ Change the transition point between fragment ``fragment_index`` and the next fragment to the time value ``value``. This method fails silently (without changing the fragment list) if at least one of the following...
[ "def", "move_transition_point", "(", "self", ",", "fragment_index", ",", "value", ")", ":", "self", ".", "log", "(", "u\"Called move_transition_point with\"", ")", "self", ".", "log", "(", "[", "u\" fragment_index %d\"", ",", "fragment_index", "]", ")", "self", ...
45.052632
19.421053
def uid_something_colon(self, node): """ Creates op_pos for node from uid to colon """ node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] position = (node.body[0].first_line, node.body[0].first_col) last, first = self.operators[':'].find_p...
[ "def", "uid_something_colon", "(", "self", ",", "node", ")", ":", "node", ".", "op_pos", "=", "[", "NodeWithPosition", "(", "node", ".", "uid", ",", "(", "node", ".", "first_line", ",", "node", ".", "first_col", ")", ")", "]", "position", "=", "(", "...
45.222222
19.555556
def list(self, status=values.unset, unique_name=values.unset, date_created_after=values.unset, date_created_before=values.unset, limit=None, page_size=None): """ Lists RoomInstance records from the API as a list. Unlike stream(), this operation is eager and will load `l...
[ "def", "list", "(", "self", ",", "status", "=", "values", ".", "unset", ",", "unique_name", "=", "values", ".", "unset", ",", "date_created_after", "=", "values", ".", "unset", ",", "date_created_before", "=", "values", ".", "unset", ",", "limit", "=", "...
55.933333
29.066667
def sparse_svd(sparse_matrix, num_values, max_iter): """Wrapper around SciPy's Singular Value Decomposition for sparse matrices. Args: sparse_matrix: a SciPy sparse matrix (typically large). num_values: the number of largest singular values to compute. max_iter: maximum number of iterations (>= 0) in t...
[ "def", "sparse_svd", "(", "sparse_matrix", ",", "num_values", ",", "max_iter", ")", ":", "if", "num_values", "<=", "0", ":", "raise", "ValueError", "(", "\"num_values should be > 0 but instead is %d.\"", "%", "num_values", ")", "if", "max_iter", "is", "not", "None...
35.84375
24.78125
def draw_route(self, df_route, cr, color=None, line_width=None): ''' Draw a line between electrodes listed in a route. Arguments --------- - `df_route`: * A `pandas.DataFrame` containing a column named `electrode_i`. * For each row, `electrode_i` corr...
[ "def", "draw_route", "(", "self", ",", "df_route", ",", "cr", ",", "color", "=", "None", ",", "line_width", "=", "None", ")", ":", "df_route_centers", "=", "(", "self", ".", "canvas", ".", "df_shape_centers", ".", "ix", "[", "df_route", ".", "electrode_i...
41.166667
20.5
def popen(self, cmd): """Execute an external command and return (rc, output). """ process = Popen(cmd, shell=True, stdout=PIPE, env=self.env) stdoutdata, stderrdata = process.communicate() return process.returncode, stdoutdata
[ "def", "popen", "(", "self", ",", "cmd", ")", ":", "process", "=", "Popen", "(", "cmd", ",", "shell", "=", "True", ",", "stdout", "=", "PIPE", ",", "env", "=", "self", ".", "env", ")", "stdoutdata", ",", "stderrdata", "=", "process", ".", "communic...
43.5
10.833333
def inconsistent(self): r""" Perform some consistency tests on the graph represented by this object Returns ------- consistent : bool or list False if consistent, else a list of inconsistency messages. Notes ----- This check i...
[ "def", "inconsistent", "(", "self", ")", ":", "messages", "=", "[", "]", "for", "node", "in", "list", "(", "self", ".", "__tweights", ".", "keys", "(", ")", ")", ":", "if", "not", "node", "<=", "self", ".", "__nodes", ":", "messages", ".", "append"...
48.448276
30.137931
def print_fold(column_to_fold, total_columns, skips): """Print a row that removes the given column and shifts all the following columns.""" format_str = '{:<2}' * (total_columns - 1) cols = [] for i in range(column_to_fold): # print(i) if i in skips: cols.append(" ") ...
[ "def", "print_fold", "(", "column_to_fold", ",", "total_columns", ",", "skips", ")", ":", "format_str", "=", "'{:<2}'", "*", "(", "total_columns", "-", "1", ")", "cols", "=", "[", "]", "for", "i", "in", "range", "(", "column_to_fold", ")", ":", "# print(...
30.555556
13.777778
def remove_elaborated(type_): """removes type-declaration class-binder :class:`elaborated_t` from the `type_` If `type_` is not :class:`elaborated_t`, it will be returned as is """ nake_type = remove_alias(type_) if not is_elaborated(nake_type): return type_ else: if isinsta...
[ "def", "remove_elaborated", "(", "type_", ")", ":", "nake_type", "=", "remove_alias", "(", "type_", ")", "if", "not", "is_elaborated", "(", "nake_type", ")", ":", "return", "type_", "else", ":", "if", "isinstance", "(", "type_", ",", "cpptypes", ".", "elab...
30
16.307692
def get_length(alt_len, ref_len, category, pos, end, svtype=None, svlen=None): """Return the length of a variant Args: alt_len(int) ref_len(int) category(str) svtype(str) svlen(int) """ # -1 would indicate uncertain length length = -1 if category in ('snv...
[ "def", "get_length", "(", "alt_len", ",", "ref_len", ",", "category", ",", "pos", ",", "end", ",", "svtype", "=", "None", ",", "svlen", "=", "None", ")", ":", "# -1 would indicate uncertain length", "length", "=", "-", "1", "if", "category", "in", "(", "...
26.758621
17.172414
def _raw_object_cache_notify(self, data): """ Low-level notify hook. """ if self._object_cache_notify is None: return module_ptr = data.contents.module_ptr buf_ptr = data.contents.buf_ptr buf_len = data.contents.buf_len buf = string_at(buf_ptr,...
[ "def", "_raw_object_cache_notify", "(", "self", ",", "data", ")", ":", "if", "self", ".", "_object_cache_notify", "is", "None", ":", "return", "module_ptr", "=", "data", ".", "contents", ".", "module_ptr", "buf_ptr", "=", "data", ".", "contents", ".", "buf_p...
39.529412
10.235294
def _print_map_dict(self, argkey, filename, append): """Prints a dictionary that has variable => value mappings.""" result = [] skeys = list(sorted(self.curargs[argkey].keys())) for key in skeys: result.append("'{}' => {}".format(key, self.curargs[argkey][key])) self....
[ "def", "_print_map_dict", "(", "self", ",", "argkey", ",", "filename", ",", "append", ")", ":", "result", "=", "[", "]", "skeys", "=", "list", "(", "sorted", "(", "self", ".", "curargs", "[", "argkey", "]", ".", "keys", "(", ")", ")", ")", "for", ...
53.857143
19.857143
def sleep(self, seconds): """Lock the connection for a given number of seconds. :param seconds: Length of time to lock the connection. :type seconds: int """ try: self.lock() time.sleep(seconds) except compat.TimeoutException: _logger....
[ "def", "sleep", "(", "self", ",", "seconds", ")", ":", "try", ":", "self", ".", "lock", "(", ")", "time", ".", "sleep", "(", "seconds", ")", "except", "compat", ".", "TimeoutException", ":", "_logger", ".", "debug", "(", "\"Connection %r timed out while wa...
33.769231
19.307692
def get_comment_form_for_create(self, reference_id, comment_record_types): """Gets the comment form for creating new comments. A new form should be requested for each create transaction. arg: reference_id (osid.id.Id): the ``Id`` for the reference object arg: comm...
[ "def", "get_comment_form_for_create", "(", "self", ",", "reference_id", ",", "comment_record_types", ")", ":", "# Implemented from template for", "# osid.relationship.CommentAdminSession.get_comment_form_for_create_template", "# These really need to be in module imports:", "if", "not", ...
48.183673
18.22449
def tf_loss(self, states, internals, actions, terminal, reward, next_states, next_internals, update, reference=None): """ Creates the TensorFlow operations for calculating the full loss of a batch. Args: states: Dict of state tensors. internals: List of prior internal st...
[ "def", "tf_loss", "(", "self", ",", "states", ",", "internals", ",", "actions", ",", "terminal", ",", "reward", ",", "next_states", ",", "next_internals", ",", "update", ",", "reference", "=", "None", ")", ":", "# Mean loss per instance", "loss_per_instance", ...
42.867925
23.962264
def search(self, query, nid=None): """Search for posts with ``query`` :type nid: str :param nid: This is the ID of the network to get the feed from. This is optional and only to override the existing `network_id` entered when created the class :type query: str ...
[ "def", "search", "(", "self", ",", "query", ",", "nid", "=", "None", ")", ":", "r", "=", "self", ".", "request", "(", "method", "=", "\"network.search\"", ",", "nid", "=", "nid", ",", "data", "=", "dict", "(", "query", "=", "query", ")", ")", "re...
37.388889
16.555556
def faulty(): ''' Display list of faulty resources CLI Example: .. code-block:: bash salt '*' fmadm.faulty ''' fmadm = _check_fmadm() cmd = '{cmd} faulty'.format( cmd=fmadm, ) res = __salt__['cmd.run_all'](cmd) result = {} if res['stdout'] == '': re...
[ "def", "faulty", "(", ")", ":", "fmadm", "=", "_check_fmadm", "(", ")", "cmd", "=", "'{cmd} faulty'", ".", "format", "(", "cmd", "=", "fmadm", ",", ")", "res", "=", "__salt__", "[", "'cmd.run_all'", "]", "(", "cmd", ")", "result", "=", "{", "}", "i...
17.818182
23.181818
def do_denyaccess(self, line): """denyaccess <subject> Remove subject from access policy.""" subject, = self._split_args(line, 1, 0) self._command_processor.get_session().get_access_control().remove_allowed_subject( subject ) self._print_info_if_verbose( '...
[ "def", "do_denyaccess", "(", "self", ",", "line", ")", ":", "subject", ",", "=", "self", ".", "_split_args", "(", "line", ",", "1", ",", "0", ")", "self", ".", "_command_processor", ".", "get_session", "(", ")", ".", "get_access_control", "(", ")", "."...
42
20.333333
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
def check_version(dstore): """ :param dstore: a DataStore instance :returns: a message if the stored version is different from the current version """ ds_version = dstore.hdf5.attrs['engine_version'] if ds_version != __version__: return (': the datastore is at version %s, but the...
[ "def", "check_version", "(", "dstore", ")", ":", "ds_version", "=", "dstore", ".", "hdf5", ".", "attrs", "[", "'engine_version'", "]", "if", "ds_version", "!=", "__version__", ":", "return", "(", "': the datastore is at version %s, but the exporter at '", "'version %s...
34.083333
16.75
def explain(self, index, doc_type, id, body=None, **query_params): """ The explain api computes a score explanation for a query and a specific document. This can give useful feedback whether a document matches or didn't match a specific query. `<http://www.elastic.co/guide/en/ela...
[ "def", "explain", "(", "self", ",", "index", ",", "doc_type", ",", "id", ",", "body", "=", "None", ",", "*", "*", "query_params", ")", ":", "self", ".", "_es_parser", ".", "is_not_empty_params", "(", "index", ",", "doc_type", ",", "id", ")", "path", ...
53.333333
21.422222
def _fuzzily_matches(response, candidate): '''return True if response fuzzily matches candidate''' r_words = response.split() c_words = candidate.split() # match whole words first for word in r_words: if word in c_words: r_words.remove(word) c_words.remove(word) #...
[ "def", "_fuzzily_matches", "(", "response", ",", "candidate", ")", ":", "r_words", "=", "response", ".", "split", "(", ")", "c_words", "=", "candidate", ".", "split", "(", ")", "# match whole words first", "for", "word", "in", "r_words", ":", "if", "word", ...
46.542857
16.942857
def extract(self, file_path, is_drum=False): ''' Extract MIDI file. Args: file_path: File path of MIDI. is_drum: Extract drum data or not. Returns: pd.DataFrame(columns=["program", "start", "end", "pitch", "velocity", "dur...
[ "def", "extract", "(", "self", ",", "file_path", ",", "is_drum", "=", "False", ")", ":", "midi_data", "=", "pretty_midi", ".", "PrettyMIDI", "(", "file_path", ")", "note_tuple_list", "=", "[", "]", "for", "instrument", "in", "midi_data", ".", "instruments", ...
44.909091
27.909091
def _send(self): """ Send data to Influxdb. Data that can not be sent will be kept in queued. """ # Check to see if we have a valid socket. If not, try to connect. try: if self.influx is None: self.log.debug("InfluxdbHandler: Socket is not connected. "...
[ "def", "_send", "(", "self", ")", ":", "# Check to see if we have a valid socket. If not, try to connect.", "try", ":", "if", "self", ".", "influx", "is", "None", ":", "self", ".", "log", ".", "debug", "(", "\"InfluxdbHandler: Socket is not connected. \"", "\"Reconnecti...
38.846154
14.487179
def state_subpattern(self, value): """Parse subpatterns.""" num, *_, parsed = value if num in self.groups: return (yield required(self.groups[num])) yield from Traverser(parsed, groups=self.groups)
[ "def", "state_subpattern", "(", "self", ",", "value", ")", ":", "num", ",", "", "*", "_", ",", "parsed", "=", "value", "if", "num", "in", "self", ".", "groups", ":", "return", "(", "yield", "required", "(", "self", ".", "groups", "[", "num", "]", ...
33.714286
13.428571
def _tokenize_chinese_chars(self, text): """Adds whitespace around any CJK character.""" output = [] for char in text: cp = ord(char) if self._is_chinese_char(cp): output.append(" ") output.append(char) output.append(" ") ...
[ "def", "_tokenize_chinese_chars", "(", "self", ",", "text", ")", ":", "output", "=", "[", "]", "for", "char", "in", "text", ":", "cp", "=", "ord", "(", "char", ")", "if", "self", ".", "_is_chinese_char", "(", "cp", ")", ":", "output", ".", "append", ...
32.583333
8.833333
def download_sample_and_align(job, sample, inputs, ids): """ Downloads the sample and runs BWA-kit :param JobFunctionWrappingJob job: Passed by Toil automatically :param tuple(str, list) sample: UUID and URLS for sample :param Namespace inputs: Contains input arguments :param dict ids: FileStor...
[ "def", "download_sample_and_align", "(", "job", ",", "sample", ",", "inputs", ",", "ids", ")", ":", "uuid", ",", "urls", "=", "sample", "r1_url", ",", "r2_url", "=", "urls", "if", "len", "(", "urls", ")", "==", "2", "else", "(", "urls", "[", "0", "...
54.805556
28.527778
def default_content_filter(sender, instance, **kwargs): # pylint: disable=unused-argument """ Set default value for `EnterpriseCustomerCatalog.content_filter` if not already set. """ if kwargs['created'] and not instance.content_filter: instance.content_filter = get_default_catalog_content_f...
[ "def", "default_content_filter", "(", "sender", ",", "instance", ",", "*", "*", "kwargs", ")", ":", "# pylint: disable=unused-argument", "if", "kwargs", "[", "'created'", "]", "and", "not", "instance", ".", "content_filter", ":", "instance", ".", "content_filter",...
49.285714
23.571429
def _fill_instance_child(xmldoc, element_name, return_type): '''Converts a child of the current dom element to the specified type. ''' element = xmldoc.find(_get_serialization_name(element_name)) if element is None: return None return_obj = return_type() _ETr...
[ "def", "_fill_instance_child", "(", "xmldoc", ",", "element_name", ",", "return_type", ")", ":", "element", "=", "xmldoc", ".", "find", "(", "_get_serialization_name", "(", "element_name", ")", ")", "if", "element", "is", "None", ":", "return", "None", "return...
36.272727
25.363636
def _append_seed(self, seed_type: str, data: Any) -> 'Seeding': """Add a seeding method and returns self. :returns: self for fluid API """ self.append({ SEED_METHOD: seed_type, SEED_DATA: data, }) return self
[ "def", "_append_seed", "(", "self", ",", "seed_type", ":", "str", ",", "data", ":", "Any", ")", "->", "'Seeding'", ":", "self", ".", "append", "(", "{", "SEED_METHOD", ":", "seed_type", ",", "SEED_DATA", ":", "data", ",", "}", ")", "return", "self" ]
27.2
15.4
def tsv(self, path, features, filtered=True, override=False): """Export the data of the current instance to a .tsv file Parameters ---------- path: str Path to a .tsv file. The ending .tsv is added automatically. features: list of str The features in the ...
[ "def", "tsv", "(", "self", ",", "path", ",", "features", ",", "filtered", "=", "True", ",", "override", "=", "False", ")", ":", "features", "=", "[", "c", ".", "lower", "(", ")", "for", "c", "in", "features", "]", "path", "=", "pathlib", ".", "Pa...
40.113208
17.471698
def destroy_domain_record(self, domain_id, record_id): """ This method deletes the specified domain record. Required parameters domain_id: Integer or Domain Name (e.g. domain.com), specifies the domain for which to destroy a record. reco...
[ "def", "destroy_domain_record", "(", "self", ",", "domain_id", ",", "record_id", ")", ":", "json", "=", "self", ".", "request", "(", "'/domains/%s/records/%s/destroy'", "%", "(", "domain_id", ",", "record_id", ")", ",", "method", "=", "'GET'", ")", "status", ...
33.529412
19.647059
def namedb_state_transition_sanity_check( opcode, op_data, history_id, cur_record, record_table ): """ Sanity checks: make sure that: * the opcode and op_data are consistent with one another. * the history_id, cur_record, and record_table are consistent with one another. Return True if so. Rais...
[ "def", "namedb_state_transition_sanity_check", "(", "opcode", ",", "op_data", ",", "history_id", ",", "cur_record", ",", "record_table", ")", ":", "namedb_op_sanity_check", "(", "opcode", ",", "op_data", ",", "cur_record", ")", "if", "opcode", "in", "OPCODE_NAME_STA...
65.837838
46.756757
def venv_has_script(script): """ :param script: script to look for in bin folder """ def f(venv): path=os.path.join(venv, 'bin', script) if os.path.isfile(path): return True return f
[ "def", "venv_has_script", "(", "script", ")", ":", "def", "f", "(", "venv", ")", ":", "path", "=", "os", ".", "path", ".", "join", "(", "venv", ",", "'bin'", ",", "script", ")", "if", "os", ".", "path", ".", "isfile", "(", "path", ")", ":", "re...
24.666667
11.777778
def set_attributes(self, attr_obj=None, ns_uri=None, **attr_dict): """ Add or update this element's attributes, where attributes can be specified in a number of ways. :param attr_obj: a dictionary or list of attribute name/value pairs. :type attr_obj: dict, list, tuple, or None ...
[ "def", "set_attributes", "(", "self", ",", "attr_obj", "=", "None", ",", "ns_uri", "=", "None", ",", "*", "*", "attr_dict", ")", ":", "self", ".", "_set_element_attributes", "(", "self", ".", "impl_node", ",", "attr_obj", "=", "attr_obj", ",", "ns_uri", ...
45.857143
19.142857
def get_live_data_flat_binary(self): """ Gets the live data packet in flatbuffer binary format. You'll need to do something like GameTickPacket.GetRootAsGameTickPacket(binary, 0) to get the data out. This is a temporary method designed to keep the integration test working. It returns th...
[ "def", "get_live_data_flat_binary", "(", "self", ")", ":", "byte_buffer", "=", "self", ".", "game", ".", "UpdateLiveDataPacketFlatbuffer", "(", ")", "if", "byte_buffer", ".", "size", ">=", "4", ":", "# GetRootAsGameTickPacket gets angry if the size is less than 4", "# W...
61.352941
31
def send(self, request, socket, context, *args): """ When an event is sent, run all relevant handlers. Relevant handlers are those without a channel pattern when the given socket is not subscribed to any particular channel, or the handlers with a channel pattern that matches any ...
[ "def", "send", "(", "self", ",", "request", ",", "socket", ",", "context", ",", "*", "args", ")", ":", "for", "handler", ",", "pattern", "in", "self", ".", "handlers", ":", "no_channel", "=", "not", "pattern", "and", "not", "socket", ".", "channels", ...
48.210526
17.894737
def jsonarrindex(self, name, path, scalar, start=0, stop=-1): """ Returns the index of ``scalar`` in the JSON array under ``path`` at key ``name``. The search can be limited using the optional inclusive ``start`` and exclusive ``stop`` indices. """ return self.execute_com...
[ "def", "jsonarrindex", "(", "self", ",", "name", ",", "path", ",", "scalar", ",", "start", "=", "0", ",", "stop", "=", "-", "1", ")", ":", "return", "self", ".", "execute_command", "(", "'JSON.ARRINDEX'", ",", "name", ",", "str_path", "(", "path", ")...
56
24.285714
def get_character(self, position, offset=0): """Return character at *position* with the given offset.""" position = self.get_position(position) + offset cursor = self.textCursor() cursor.movePosition(QTextCursor.End) if position < cursor.position(): cursor.setPo...
[ "def", "get_character", "(", "self", ",", "position", ",", "offset", "=", "0", ")", ":", "position", "=", "self", ".", "get_position", "(", "position", ")", "+", "offset", "cursor", "=", "self", ".", "textCursor", "(", ")", "cursor", ".", "movePosition",...
44.166667
10.166667
def embed(self, name, data=None): """Attach an image file and prepare for HTML embedding. This method should only be used to embed images. :param name: Path to the image to embed if data is None, or the name of the file if the ``data`` argument is given :param data: Contents of the image to embed, or No...
[ "def", "embed", "(", "self", ",", "name", ",", "data", "=", "None", ")", ":", "if", "data", "is", "None", ":", "with", "open", "(", "name", ",", "'rb'", ")", "as", "fp", ":", "data", "=", "fp", ".", "read", "(", ")", "name", "=", "os", ".", ...
31.826087
18.347826
def get_transform(self): """ Get a new object to perform the scaling transformation. """ return _InterpolatedInverseTransform(transform=self._transform, smin=0, smax=self._transform._M)
[ "def", "get_transform", "(", "self", ")", ":", "return", "_InterpolatedInverseTransform", "(", "transform", "=", "self", ".", "_transform", ",", "smin", "=", "0", ",", "smax", "=", "self", ".", "_transform", ".", "_M", ")" ]
37.625
18.875
def publish_proto_metadata_update(self): """ Publish protobuf model in ipfs and update existing metadata file """ metadata = load_mpe_service_metadata(self.args.metadata_file) ipfs_hash_base58 = utils_ipfs.publish_proto_in_ipfs(self._get_ipfs_client(), self.args.protodir) metadata.set_si...
[ "def", "publish_proto_metadata_update", "(", "self", ")", ":", "metadata", "=", "load_mpe_service_metadata", "(", "self", ".", "args", ".", "metadata_file", ")", "ipfs_hash_base58", "=", "utils_ipfs", ".", "publish_proto_in_ipfs", "(", "self", ".", "_get_ipfs_client",...
69.333333
22.666667
def _remove_alone_endif(self): """ Can occur on: if(..){ return } else{ return } Iterate until a fix point to remove the ENDIF node creates on the following pattern if(){ ...
[ "def", "_remove_alone_endif", "(", "self", ")", ":", "prev_nodes", "=", "[", "]", "while", "set", "(", "prev_nodes", ")", "!=", "set", "(", "self", ".", "nodes", ")", ":", "prev_nodes", "=", "self", ".", "nodes", "to_remove", "=", "[", "]", "for", "n...
29.066667
15.933333
def find_all(self, node_type): """Find all the nodes of a given type. If the type is a tuple, the check is performed for any of the tuple items. """ for child in self.iter_child_nodes(): if isinstance(child, node_type): yield child for result in c...
[ "def", "find_all", "(", "self", ",", "node_type", ")", ":", "for", "child", "in", "self", ".", "iter_child_nodes", "(", ")", ":", "if", "isinstance", "(", "child", ",", "node_type", ")", ":", "yield", "child", "for", "result", "in", "child", ".", "find...
40.666667
8.222222
def get_attribute_by_name_and_dimension(name, dimension_id=None,**kwargs): """ Get a specific attribute by its name. dimension_id can be None, because in attribute the dimension_id is not anymore mandatory """ try: attr_i = db.DBSession.query(Attr).filter(and_(Attr.name==name, Attr.d...
[ "def", "get_attribute_by_name_and_dimension", "(", "name", ",", "dimension_id", "=", "None", ",", "*", "*", "kwargs", ")", ":", "try", ":", "attr_i", "=", "db", ".", "DBSession", ".", "query", "(", "Attr", ")", ".", "filter", "(", "and_", "(", "Attr", ...
41.090909
22.909091
def columns_used(self): """ Columns from any table used in the model. May come from either the choosers or alternatives tables. """ return list(tz.unique(tz.concatv( self.choosers_columns_used(), self.alts_columns_used(), self.interaction_colu...
[ "def", "columns_used", "(", "self", ")", ":", "return", "list", "(", "tz", ".", "unique", "(", "tz", ".", "concatv", "(", "self", ".", "choosers_columns_used", "(", ")", ",", "self", ".", "alts_columns_used", "(", ")", ",", "self", ".", "interaction_colu...
32.4
10.2
def update_devices(self, devices): """Update values from response of URL_DEVICES, callback if changed.""" for qspacket in devices: try: qsid = qspacket[QS_ID] except KeyError: _LOGGER.debug("Device without ID: %s", qspacket) continu...
[ "def", "update_devices", "(", "self", ",", "devices", ")", ":", "for", "qspacket", "in", "devices", ":", "try", ":", "qsid", "=", "qspacket", "[", "QS_ID", "]", "except", "KeyError", ":", "_LOGGER", ".", "debug", "(", "\"Device without ID: %s\"", ",", "qsp...
40.958333
15.875
def start(self, context): """Initialize the database connection.""" self.config['alias'] = self.alias safe_config = dict(self.config) del safe_config['host'] log.info("Connecting MongoEngine database layer.", extra=dict( uri = redact_uri(self.config['host']), config = self.config, )) sel...
[ "def", "start", "(", "self", ",", "context", ")", ":", "self", ".", "config", "[", "'alias'", "]", "=", "self", ".", "alias", "safe_config", "=", "dict", "(", "self", ".", "config", ")", "del", "safe_config", "[", "'host'", "]", "log", ".", "info", ...
26.538462
18
def find_suggestions(self, sentence): """ Search all possible suggestions. Suggestions returned always have at least one document matching. Arguments: sentence --- keywords (single strings) for which we want suggestions Return: An array of...
[ "def", "find_suggestions", "(", "self", ",", "sentence", ")", ":", "if", "not", "isinstance", "(", "sentence", ",", "str", ")", ":", "sentence", "=", "str", "(", "sentence", ")", "keywords", "=", "sentence", ".", "split", "(", "\" \"", ")", "query_parser...
38.391304
18.173913
def set_bgcolor(self, color): """set color for background of plot""" self.bgcolor = color for ax in self.canvas.figure.get_axes(): if matplotlib.__version__ < '2.0': ax.set_axis_bgcolor(color) else: ax.set_facecolor(color) if callab...
[ "def", "set_bgcolor", "(", "self", ",", "color", ")", ":", "self", ".", "bgcolor", "=", "color", "for", "ax", "in", "self", ".", "canvas", ".", "figure", ".", "get_axes", "(", ")", ":", "if", "matplotlib", ".", "__version__", "<", "'2.0'", ":", "ax",...
39.2
8
def get_item(filename, uuid): """ Read entry from JSON file """ with open(os.fsencode(str(filename)), "r") as f: data = json.load(f) results = [i for i in data if i["uuid"] == str(uuid)] if results: return results return None
[ "def", "get_item", "(", "filename", ",", "uuid", ")", ":", "with", "open", "(", "os", ".", "fsencode", "(", "str", "(", "filename", ")", ")", ",", "\"r\"", ")", "as", "f", ":", "data", "=", "json", ".", "load", "(", "f", ")", "results", "=", "[...
27.6
12.4
def fmt_tag(cur_namespace, tag, val): """ Processes a documentation reference. """ if tag == 'type': fq_val = val if '.' not in val and cur_namespace is not None: fq_val = cur_namespace.name + '.' + fq_val return fq_val elif tag == 'route': if ':' in val: ...
[ "def", "fmt_tag", "(", "cur_namespace", ",", "tag", ",", "val", ")", ":", "if", "tag", "==", "'type'", ":", "fq_val", "=", "val", "if", "'.'", "not", "in", "val", "and", "cur_namespace", "is", "not", "None", ":", "fq_val", "=", "cur_namespace", ".", ...
33.392857
15.107143