text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def nt2codon_rep(ntseq): """Represent nucleotide sequence by sequence of codon symbols. 'Translates' the nucleotide sequence into a symbolic representation of 'amino acids' where each codon gets its own unique character symbol. These characters should be reserved only for representing the 64 individua...
[ "def", "nt2codon_rep", "(", "ntseq", ")", ":", "#", "nt2num", "=", "{", "'A'", ":", "0", ",", "'C'", ":", "1", ",", "'G'", ":", "2", ",", "'T'", ":", "3", ",", "'a'", ":", "0", ",", "'c'", ":", "1", ",", "'g'", ":", "2", ",", "'t'", ":", ...
48.763158
0.008995
def produce_context(namespace, context_id, max_delay=None): """Produce event context.""" try: context_obj = get_context(namespace, context_id) logger.info("Found context '%s:%s'", namespace, context_id) except ContextError: logger.info("Context '%s:%s' not found", namespace, context_...
[ "def", "produce_context", "(", "namespace", ",", "context_id", ",", "max_delay", "=", "None", ")", ":", "try", ":", "context_obj", "=", "get_context", "(", "namespace", ",", "context_id", ")", "logger", ".", "info", "(", "\"Found context '%s:%s'\"", ",", "name...
40.714286
0.001143
async def forward(self, chat_id, disable_notification=None) -> Message: """ Forward this message :param chat_id: :param disable_notification: :return: """ return await self.bot.forward_message(chat_id, self.chat.id, self.message_id, disable_notification)
[ "async", "def", "forward", "(", "self", ",", "chat_id", ",", "disable_notification", "=", "None", ")", "->", "Message", ":", "return", "await", "self", ".", "bot", ".", "forward_message", "(", "chat_id", ",", "self", ".", "chat", ".", "id", ",", "self", ...
33.666667
0.009646
def import_by_path(path): """Append the path to sys.path, then attempt to import module with path's basename, finally making certain to remove appended path. http://stackoverflow.com/questions/1096216/override-namespace-in-python""" sys.path.append(os.path.dirname(path)) try: return __imp...
[ "def", "import_by_path", "(", "path", ")", ":", "sys", ".", "path", ".", "append", "(", "os", ".", "path", ".", "dirname", "(", "path", ")", ")", "try", ":", "return", "__import__", "(", "os", ".", "path", ".", "basename", "(", "path", ")", ")", ...
32.5
0.002137
def _ContinueReportCompilation(self): """Determines if the plugin should continue trying to compile the report. Returns: bool: True if the plugin should continue, False otherwise. """ analyzer_alive = self._analyzer.is_alive() hash_queue_has_tasks = self.hash_queue.unfinished_tasks > 0 an...
[ "def", "_ContinueReportCompilation", "(", "self", ")", ":", "analyzer_alive", "=", "self", ".", "_analyzer", ".", "is_alive", "(", ")", "hash_queue_has_tasks", "=", "self", ".", "hash_queue", ".", "unfinished_tasks", ">", "0", "analysis_queue", "=", "not", "self...
39.75
0.002049
def get_index_declaration_sql(self, name, index): """ Obtains DBMS specific SQL code portion needed to set an index declaration to be used in statements like CREATE TABLE. :param name: The name of the index. :type name: str :param index: The index definition :ty...
[ "def", "get_index_declaration_sql", "(", "self", ",", "name", ",", "index", ")", ":", "columns", "=", "index", ".", "get_quoted_columns", "(", "self", ")", "name", "=", "Identifier", "(", "name", ")", "if", "not", "columns", ":", "raise", "DBALException", ...
32.769231
0.002281
def analyze(self, id): # pylint: disable=invalid-name,redefined-builtin """Get a list of tests that will be skipped for a package. :param id: Package ID as an int. :return: :class:`packages.Analysis <packages.Analysis>` object :rtype: packages.Analysis """ schema = Analy...
[ "def", "analyze", "(", "self", ",", "id", ")", ":", "# pylint: disable=invalid-name,redefined-builtin", "schema", "=", "AnalysisSchema", "(", ")", "resp", "=", "self", ".", "service", ".", "post", "(", "self", ".", "base", "+", "str", "(", "id", ")", "+", ...
45.8
0.008565
def draw_triangles(tile_x, tile_y, tile_size, split, top_color, bottom_color, draw): """Draws a triangle on each half of the tile with the given coordinates and size. """ assert split in ('right', 'left') # The four corners of this tile nw = (tile_x, tile_y) ne = (tile_x ...
[ "def", "draw_triangles", "(", "tile_x", ",", "tile_y", ",", "tile_size", ",", "split", ",", "top_color", ",", "bottom_color", ",", "draw", ")", ":", "assert", "split", "in", "(", "'right'", ",", "'left'", ")", "# The four corners of this tile", "nw", "=", "(...
33.869565
0.001248
def keep_absolute_impute__roc_auc(X, y, model_generator, method_name, num_fcounts=11): """ Keep Absolute (impute) xlabel = "Max fraction of features kept" ylabel = "ROC AUC" transform = "identity" sort_order = 19 """ return __run_measure(measures.keep_mask, X, y, model_generator, method_name...
[ "def", "keep_absolute_impute__roc_auc", "(", "X", ",", "y", ",", "model_generator", ",", "method_name", ",", "num_fcounts", "=", "11", ")", ":", "return", "__run_measure", "(", "measures", ".", "keep_mask", ",", "X", ",", "y", ",", "model_generator", ",", "m...
45.125
0.008152
def to_array(self, channels=2): """Generate the array of volume multipliers for the dynamic""" if self.fade_type == "linear": return np.linspace(self.in_volume, self.out_volume, self.duration * channels)\ .reshape(self.duration, channels) elif self.fad...
[ "def", "to_array", "(", "self", ",", "channels", "=", "2", ")", ":", "if", "self", ".", "fade_type", "==", "\"linear\"", ":", "return", "np", ".", "linspace", "(", "self", ".", "in_volume", ",", "self", ".", "out_volume", ",", "self", ".", "duration", ...
50.5
0.008639
def fixup_paths(): """ Fixup paths added in .pth file that point to the virtualenv instead of the system site packages. In depth: .PTH can execute arbitrary code, which might manipulate the PATH or sys.path :return: """ original_paths = os.environ.get('PATH', "").split(os.path.pathsep...
[ "def", "fixup_paths", "(", ")", ":", "original_paths", "=", "os", ".", "environ", ".", "get", "(", "'PATH'", ",", "\"\"", ")", ".", "split", "(", "os", ".", "path", ".", "pathsep", ")", "original_dirs", "=", "set", "(", "added_dirs", ")", "yield", "#...
35.878049
0.001324
def words(query): """lines(query) -- print the number of words in a given file """ filename = support.get_file_name(query) if(os.path.isfile(filename)): with open(filename) as openfile: print len(openfile.read().split()) else: print 'File not found : ' + filename
[ "def", "words", "(", "query", ")", ":", "filename", "=", "support", ".", "get_file_name", "(", "query", ")", "if", "(", "os", ".", "path", ".", "isfile", "(", "filename", ")", ")", ":", "with", "open", "(", "filename", ")", "as", "openfile", ":", "...
29.666667
0.032727
def tarjan_recursif(graph): """Strongly connected components by Tarjan, recursive implementation :param graph: directed graph in listlist format, cannot be listdict :returns: list of lists for each component :complexity: linear """ global sccp, waiting, dfs_time, dfs_num sccp = [] waiti...
[ "def", "tarjan_recursif", "(", "graph", ")", ":", "global", "sccp", ",", "waiting", ",", "dfs_time", ",", "dfs_num", "sccp", "=", "[", "]", "waiting", "=", "[", "]", "waits", "=", "[", "False", "]", "*", "len", "(", "graph", ")", "dfs_time", "=", "...
35.275
0.00069
def magphase(D, power=1): """Separate a complex-valued spectrogram D into its magnitude (S) and phase (P) components, so that `D = S * P`. Parameters ---------- D : np.ndarray [shape=(d, t), dtype=complex] complex-valued spectrogram power : float > 0 Exponent for the magnitude ...
[ "def", "magphase", "(", "D", ",", "power", "=", "1", ")", ":", "mag", "=", "np", ".", "abs", "(", "D", ")", "mag", "**=", "power", "phase", "=", "np", ".", "exp", "(", "1.j", "*", "np", ".", "angle", "(", "D", ")", ")", "return", "mag", ","...
34.47541
0.001849
def get_layer(self, image_id, repo_name, download_folder=None): '''download an image layer (.tar.gz) to a specified download folder. Parameters ========== download_folder: download to this folder. If not set, uses temp. repo_name: the image name (library/ubuntu) to retrieve ''' ...
[ "def", "get_layer", "(", "self", ",", "image_id", ",", "repo_name", ",", "download_folder", "=", "None", ")", ":", "url", "=", "self", ".", "_get_layerLink", "(", "repo_name", ",", "image_id", ")", "bot", ".", "verbose", "(", "\"Downloading layers from %s\"", ...
32.030303
0.000918
def insert( self, obj=None, overwrite=False, partition=None, values=None, validate=True, ): """ Insert into Impala table. Wraps ImpalaClient.insert Parameters ---------- obj : TableExpr or pandas DataFrame overwrite : b...
[ "def", "insert", "(", "self", ",", "obj", "=", "None", ",", "overwrite", "=", "False", ",", "partition", "=", "None", ",", "values", "=", "None", ",", "validate", "=", "True", ",", ")", ":", "if", "isinstance", "(", "obj", ",", "pd", ".", "DataFram...
33.055556
0.001224
def _solve_pkg(main_globals): ''' Find parent python path of __main__. From there solve the package containing __main__, import it and set __package__ variable. :param main_globals: globals dictionary in __main__ ''' # find __main__'s file directory and search path main_dir, search_path = _...
[ "def", "_solve_pkg", "(", "main_globals", ")", ":", "# find __main__'s file directory and search path", "main_dir", ",", "search_path", "=", "_try_search_paths", "(", "main_globals", ")", "if", "not", "search_path", ":", "_log_debug", "(", "'Could not solve parent python pa...
44.645833
0.000457
def _request(self, function, params, method='POST', headers={}): """Builds a request object.""" if method is 'POST': params = urllib.parse.urlencode(params) headers = { "Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain" } path = ...
[ "def", "_request", "(", "self", ",", "function", ",", "params", ",", "method", "=", "'POST'", ",", "headers", "=", "{", "}", ")", ":", "if", "method", "is", "'POST'", ":", "params", "=", "urllib", ".", "parse", ".", "urlencode", "(", "params", ")", ...
41.181818
0.017279
def add_net32string(self, string): """ >>> r = b'\\x00\\x00\\x00\\x01x' >>> OutBuffer().add_net32string(b"x").getvalue() == r True @type string: bytes @param string: maximum length must fit in a 32bit integer @returns: self @raises OmapiSizeLimitError: """ if len(string) >= (1 << 32): raise Valu...
[ "def", "add_net32string", "(", "self", ",", "string", ")", ":", "if", "len", "(", "string", ")", ">=", "(", "1", "<<", "32", ")", ":", "raise", "ValueError", "(", "\"string too long\"", ")", "return", "self", ".", "add_net32int", "(", "len", "(", "stri...
27.428571
0.035264
def generic(query): """ generic(query) -- process a generic user query using the Stanford NLTK NER and duckduckgo api. """ try: response = unirest.post("https://textanalysis.p.mashape.com/nltk-stanford-ner", headers={ "X-Mashape-Key": "E7WffsNDbNmshj4aVC4NUwj9dT9ep1S2cc3jsnFp5wSCzNBiaP", "Cont...
[ "def", "generic", "(", "query", ")", ":", "try", ":", "response", "=", "unirest", ".", "post", "(", "\"https://textanalysis.p.mashape.com/nltk-stanford-ner\"", ",", "headers", "=", "{", "\"X-Mashape-Key\"", ":", "\"E7WffsNDbNmshj4aVC4NUwj9dT9ep1S2cc3jsnFp5wSCzNBiaP\"", ",...
26.928571
0.056338
def run(self): """ Calls the defined action every $interval seconds. Optionally calls an action before the main loop, and an action when stopping, if these are defined. Exceptions in the main loop will NOT cause the thread to die. """ self.logger.debug("Thread {0} is entering main loop".format(self.name)) ...
[ "def", "run", "(", "self", ")", ":", "self", ".", "logger", ".", "debug", "(", "\"Thread {0} is entering main loop\"", ".", "format", "(", "self", ".", "name", ")", ")", "if", "hasattr", "(", "self", ",", "\"init_action\"", ")", ":", "self", ".", "logger...
38.419355
0.022932
def get_cards(self, list_id): """ Returns an iterator for the cards in a given list, filtered according to configuration values of trello.only_if_assigned and trello.also_unassigned """ params = {'fields': 'name,idShort,shortLink,shortUrl,url,labels,due'} member = self.config.get...
[ "def", "get_cards", "(", "self", ",", "list_id", ")", ":", "params", "=", "{", "'fields'", ":", "'name,idShort,shortLink,shortUrl,url,labels,due'", "}", "member", "=", "self", ".", "config", ".", "get", "(", "'only_if_assigned'", ",", "None", ")", "unassigned", ...
48.055556
0.002268
def check_message(message, **kwargs): """Check the message format. Rules: - the first line must start by a component name - and a short description (52 chars), - then bullet points are expected - and finally signatures. :param components: compontents, e.g. ``('auth', 'utils', 'misc')`` ...
[ "def", "check_message", "(", "message", ",", "*", "*", "kwargs", ")", ":", "if", "kwargs", ".", "pop", "(", "\"allow_empty\"", ",", "False", ")", ":", "if", "not", "message", "or", "message", ".", "isspace", "(", ")", ":", "return", "[", "]", "lines"...
37.681818
0.000588
def parse_instance_count(instance_count, speaker_total_count): """This parses the instance count dictionary (that may contain floats from 0.0 to 1.0 representing a percentage) and converts it to actual instance count. """ # Use all the instances of a speaker unless specified result = copy.copy(...
[ "def", "parse_instance_count", "(", "instance_count", ",", "speaker_total_count", ")", ":", "# Use all the instances of a speaker unless specified", "result", "=", "copy", ".", "copy", "(", "speaker_total_count", ")", "for", "speaker_id", ",", "count", "in", "instance_cou...
35.315789
0.001451
def cdrom_image(self, cdrom_image): """ Sets the cdrom image for this QEMU VM. :param cdrom_image: QEMU cdrom image path """ self._cdrom_image = self.manager.get_abs_image_path(cdrom_image) log.info('QEMU VM "{name}" [{id}] has set the QEMU cdrom image path to {cdrom_ima...
[ "def", "cdrom_image", "(", "self", ",", "cdrom_image", ")", ":", "self", ".", "_cdrom_image", "=", "self", ".", "manager", ".", "get_abs_image_path", "(", "cdrom_image", ")", "log", ".", "info", "(", "'QEMU VM \"{name}\" [{id}] has set the QEMU cdrom image path to {cd...
58.6
0.008403
def parse_source_file(file_name): """ Parses the AST of Python file for lines containing references to the argparse module. returns the collection of ast objects found. Example client code: 1. parser = ArgumentParser(desc="My help Message") 2. parser.add_argument('filename', help="Name of the file ...
[ "def", "parse_source_file", "(", "file_name", ")", ":", "nodes", "=", "ast", ".", "parse", "(", "_openfile", "(", "file_name", ")", ")", "module_imports", "=", "get_nodes_by_instance_type", "(", "nodes", ",", "_ast", ".", "Import", ")", "specific_imports", "="...
38.095238
0.012797
def _generate_a_indptr(num_states, s_indices, out): """ Generate `a_indptr`; stored in `out`. `s_indices` is assumed to be in sorted order. Parameters ---------- num_states : scalar(int) s_indices : ndarray(int, ndim=1) out : ndarray(int, ndim=1) Length must be num_states+1. ...
[ "def", "_generate_a_indptr", "(", "num_states", ",", "s_indices", ",", "out", ")", ":", "idx", "=", "0", "out", "[", "0", "]", "=", "0", "for", "s", "in", "range", "(", "num_states", "-", "1", ")", ":", "while", "(", "s_indices", "[", "idx", "]", ...
22
0.00198
def add_webhook(self, policy, name, metadata=None): """ Adds a webhook to the specified policy. """ return self.manager.add_webhook(self, policy, name, metadata=metadata)
[ "def", "add_webhook", "(", "self", ",", "policy", ",", "name", ",", "metadata", "=", "None", ")", ":", "return", "self", ".", "manager", ".", "add_webhook", "(", "self", ",", "policy", ",", "name", ",", "metadata", "=", "metadata", ")" ]
39.6
0.009901
def get_url_from_entry(entry): """Get a usable URL from a pybtex entry. Parameters ---------- entry : `pybtex.database.Entry` A pybtex bibliography entry. Returns ------- url : `str` Best available URL from the ``entry``. Raises ------ NoEntryUrlError R...
[ "def", "get_url_from_entry", "(", "entry", ")", ":", "if", "'url'", "in", "entry", ".", "fields", ":", "return", "entry", ".", "fields", "[", "'url'", "]", "elif", "entry", ".", "type", ".", "lower", "(", ")", "==", "'docushare'", ":", "return", "'http...
23.945946
0.001085
def security_group(self, vpc): """Create and configure a new security group. Allows all ICMP in, all TCP and UDP in within VPC. This security group is very open. It allows all incoming ping requests on all ports. It also allows all outgoing traffic on all ports. This can be limited by ...
[ "def", "security_group", "(", "self", ",", "vpc", ")", ":", "sg", "=", "vpc", ".", "create_security_group", "(", "GroupName", "=", "\"private-subnet\"", ",", "Description", "=", "\"security group for remote executors\"", ")", "ip_ranges", "=", "[", "{", "'CidrIp'"...
29.102564
0.00213
def delete(name, timeout=90): ''' Delete the named service Args: name (str): The name of the service to delete timeout (int): The time in seconds to wait for the service to be deleted before returning. This is necessary because a service must be stopped ...
[ "def", "delete", "(", "name", ",", "timeout", "=", "90", ")", ":", "handle_scm", "=", "win32service", ".", "OpenSCManager", "(", "None", ",", "None", ",", "win32service", ".", "SC_MANAGER_CONNECT", ")", "try", ":", "handle_svc", "=", "win32service", ".", "...
30.166667
0.001189
def com_google_fonts_check_whitespace_ink(ttFont): """Whitespace glyphs have ink?""" from fontbakery.utils import get_glyph_name, glyph_has_ink # code-points for all "whitespace" chars: WHITESPACE_CHARACTERS = [ 0x0009, 0x000A, 0x000B, 0x000C, 0x000D, 0x0020, 0x0085, 0x00A0, 0x1680, 0x2000, 0x2001,...
[ "def", "com_google_fonts_check_whitespace_ink", "(", "ttFont", ")", ":", "from", "fontbakery", ".", "utils", "import", "get_glyph_name", ",", "glyph_has_ink", "# code-points for all \"whitespace\" chars:", "WHITESPACE_CHARACTERS", "=", "[", "0x0009", ",", "0x000A", ",", "...
40.285714
0.011547
def make_fileitem_fullpath(fullpath, condition='contains', negate=False, preserve_case=False): """ Create a node for FileItem/FullPath :return: A IndicatorItem represented as an Element node """ document = 'FileItem' search = 'FileItem/FullPath' content_type = 'string' content = ful...
[ "def", "make_fileitem_fullpath", "(", "fullpath", ",", "condition", "=", "'contains'", ",", "negate", "=", "False", ",", "preserve_case", "=", "False", ")", ":", "document", "=", "'FileItem'", "search", "=", "'FileItem/FullPath'", "content_type", "=", "'string'", ...
40
0.009398
def Create(name,alias=None,location=None,session=None): """Creates a new anti-affinity policy within a given account. https://t3n.zendesk.com/entries/45042770-Create-Anti-Affinity-Policy *TODO* Currently returning 400 error: clc.APIFailedResponse: Response code 400. . POST https://api.tier3.com/v2/antiAffinit...
[ "def", "Create", "(", "name", ",", "alias", "=", "None", ",", "location", "=", "None", ",", "session", "=", "None", ")", ":", "if", "not", "alias", ":", "alias", "=", "clc", ".", "v2", ".", "Account", ".", "GetAlias", "(", "session", "=", "session"...
41.941176
0.035665
def _rpc(http, project, method, base_url, request_pb, response_pb_cls): """Make a protobuf RPC request. :type http: :class:`requests.Session` :param http: HTTP object to make requests. :type project: str :param project: The project to connect to. This is usually your project na...
[ "def", "_rpc", "(", "http", ",", "project", ",", "method", ",", "base_url", ",", "request_pb", ",", "response_pb_cls", ")", ":", "req_data", "=", "request_pb", ".", "SerializeToString", "(", ")", "response", "=", "_request", "(", "http", ",", "project", ",...
37
0.000878
def put_values_into_data(self, values): """ Take the (col, value) in 'values', append value into 'col' in self.data[] """ for col, value in values.items(): if col in self.column_csv_map: out_csv = self.column_csv_map[col] else: out_csv = self.get_csv(col) # column_csv_map[]...
[ "def", "put_values_into_data", "(", "self", ",", "values", ")", ":", "for", "col", ",", "value", "in", "values", ".", "items", "(", ")", ":", "if", "col", "in", "self", ".", "column_csv_map", ":", "out_csv", "=", "self", ".", "column_csv_map", "[", "co...
38.363636
0.011574
def partial_fit(self, X, Y): '''Partial-fit the OLDA model Parameters ---------- X : array-like, shape [n_samples] Training data: each example is an n_features-by-* data array Y : array-like, shape [n_samples] Training labels: each label is an array of c...
[ "def", "partial_fit", "(", "self", ",", "X", ",", "Y", ")", ":", "for", "(", "xi", ",", "yi", ")", "in", "itertools", ".", "izip", "(", "X", ",", "Y", ")", ":", "prev_mean", "=", "None", "prev_length", "=", "None", "if", "self", ".", "scatter_wit...
37.492063
0.011964
def setFilled(self, polygonID, filled): """setFilled(string) -> bool Returns whether the polygon is filled """ self._connection._sendUByteCmd( tc.CMD_SET_POLYGON_VARIABLE, tc.VAR_FILL, polygonID, (1 if filled else 0))
[ "def", "setFilled", "(", "self", ",", "polygonID", ",", "filled", ")", ":", "self", ".", "_connection", ".", "_sendUByteCmd", "(", "tc", ".", "CMD_SET_POLYGON_VARIABLE", ",", "tc", ".", "VAR_FILL", ",", "polygonID", ",", "(", "1", "if", "filled", "else", ...
42.666667
0.011494
def lower_brkpts(a,b,c,e,f,p_min,p_max,n): """lower_brkpts: lower approximation of the cost function Parameters: - a,...,p_max: cost parameters - n: number of breakpoints' intervals to insert between valve points Returns: list of breakpoints in the form [(x0,y0),...,(xK,yK)] """ EPS ...
[ "def", "lower_brkpts", "(", "a", ",", "b", ",", "c", ",", "e", ",", "f", ",", "p_min", ",", "p_max", ",", "n", ")", ":", "EPS", "=", "1.e-12", "# for avoiding round-off errors", "if", "f", "==", "0", ":", "f", "=", "math", ".", "pi", "/", "(", ...
36.363636
0.028015
def download_bundle_view(self, request, pk): """A view that allows the user to download a certificate bundle in PEM format.""" return self._download_response(request, pk, bundle=True)
[ "def", "download_bundle_view", "(", "self", ",", "request", ",", "pk", ")", ":", "return", "self", ".", "_download_response", "(", "request", ",", "pk", ",", "bundle", "=", "True", ")" ]
49.25
0.015
def raise_from(exc, cause): """ Does the same as ``raise LALALA from BLABLABLA`` does in Python 3. But works in Python 2 also! Please checkout README on https://github.com/9seconds/pep3134 to get an idea about possible pitfals. But short story is: please be pretty carefull with tracebacks. If i...
[ "def", "raise_from", "(", "exc", ",", "cause", ")", ":", "context_tb", "=", "sys", ".", "exc_info", "(", ")", "[", "2", "]", "incorrect_cause", "=", "not", "(", "(", "isinstance", "(", "cause", ",", "type", ")", "and", "issubclass", "(", "cause", ","...
31.902439
0.000742
def initialize(self): """Initialize the corresponding DXclass from the data. class = DXInitObject.initialize() """ return self.DXclasses[self.type](self.id,**self.args)
[ "def", "initialize", "(", "self", ")", ":", "return", "self", ".", "DXclasses", "[", "self", ".", "type", "]", "(", "self", ".", "id", ",", "*", "*", "self", ".", "args", ")" ]
32.666667
0.014925
def get_distance(self, node, type_measurement): """! @brief Calculates distance between nodes in line with specified type measurement. @param[in] node (cfnode): CF-node that is used for calculation distance to the current node. @param[in] type_measurement (measurement_type)...
[ "def", "get_distance", "(", "self", ",", "node", ",", "type_measurement", ")", ":", "return", "self", ".", "feature", ".", "get_distance", "(", "node", ".", "feature", ",", "type_measurement", ")" ]
44.833333
0.018215
def stroke(self,*args): '''Set a stroke color, applying it to new paths.''' self._strokecolor = self.color(*args) return self._strokecolor
[ "def", "stroke", "(", "self", ",", "*", "args", ")", ":", "self", ".", "_strokecolor", "=", "self", ".", "color", "(", "*", "args", ")", "return", "self", ".", "_strokecolor" ]
39.75
0.018519
def flush(self): """Flushes the event file to disk.""" if self._num_outstanding_events == 0 or self._recordio_writer is None: return self._recordio_writer.flush() if self._logger is not None: self._logger.info('wrote %d %s to disk', self._num_outstanding_events, ...
[ "def", "flush", "(", "self", ")", ":", "if", "self", ".", "_num_outstanding_events", "==", "0", "or", "self", ".", "_recordio_writer", "is", "None", ":", "return", "self", ".", "_recordio_writer", ".", "flush", "(", ")", "if", "self", ".", "_logger", "is...
49
0.008909
async def timeout(source, timeout): """Raise a time-out if an element of the asynchronous sequence takes too long to arrive. Note: the timeout is not global but specific to each step of the iteration. """ async with streamcontext(source) as streamer: while True: try: ...
[ "async", "def", "timeout", "(", "source", ",", "timeout", ")", ":", "async", "with", "streamcontext", "(", "source", ")", "as", "streamer", ":", "while", "True", ":", "try", ":", "item", "=", "await", "wait_for", "(", "anext", "(", "streamer", ")", ","...
31.2
0.002075
def validate(self, payload, required=None, strict=None): ''' Validates a given JSON payload according to the rules defiined for all the fields/keys in the sub-class. :param dict payload: deserialized JSON object. :param bool required: if every field/key is required and must be ...
[ "def", "validate", "(", "self", ",", "payload", ",", "required", "=", "None", ",", "strict", "=", "None", ")", ":", "# replace datatypes.Function.func if not already replaced", "self", ".", "_replace_string_args", "(", ")", "required", "=", "required", "if", "requ...
40.518519
0.000892
def first_solar_spectral_correction(pw, airmass_absolute, module_type=None, coefficients=None): r""" Spectral mismatch modifier based on precipitable water and absolute (pressure corrected) airmass. Estimates a spectral mismatch modifier M representing the effect on ...
[ "def", "first_solar_spectral_correction", "(", "pw", ",", "airmass_absolute", ",", "module_type", "=", "None", ",", "coefficients", "=", "None", ")", ":", "# --- Screen Input Data ---", "# *** Pwat ***", "# Replace Pwat Values below 0.1 cm with 0.1 cm to prevent model from", "#...
42.3625
0.000144
def option_changed(self, option, value): """Option has changed""" setattr(self, to_text_string(option), value) self.shellwidget.set_namespace_view_settings() self.refresh_table()
[ "def", "option_changed", "(", "self", ",", "option", ",", "value", ")", ":", "setattr", "(", "self", ",", "to_text_string", "(", "option", ")", ",", "value", ")", "self", ".", "shellwidget", ".", "set_namespace_view_settings", "(", ")", "self", ".", "refre...
42
0.009346
def add_attribute(self, tag, name, value): """ add an attribute (nam, value pair) to the named tag """ self.add_tag(tag) d = self._tags[tag] d[name] = value
[ "def", "add_attribute", "(", "self", ",", "tag", ",", "name", ",", "value", ")", ":", "self", ".", "add_tag", "(", "tag", ")", "d", "=", "self", ".", "_tags", "[", "tag", "]", "d", "[", "name", "]", "=", "value" ]
36.8
0.010638
def pause(self): """Pause the music""" mixer.music.pause() self.pause_time = self.get_time() self.paused = True
[ "def", "pause", "(", "self", ")", ":", "mixer", ".", "music", ".", "pause", "(", ")", "self", ".", "pause_time", "=", "self", ".", "get_time", "(", ")", "self", ".", "paused", "=", "True" ]
27.8
0.013986
def get_bets(self, type=None, order_by=None, state=None, project_id=None, page=None, page_size=None): """Return bets with given filters and ordering. :param type: return bets only with this type. Use None to include all (default). :param order_by: '-last_st...
[ "def", "get_bets", "(", "self", ",", "type", "=", "None", ",", "order_by", "=", "None", ",", "state", "=", "None", ",", "project_id", "=", "None", ",", "page", "=", "None", ",", "page_size", "=", "None", ")", ":", "if", "page", "is", "None", ":", ...
39.810811
0.001988
def calcOffset(self, x, y): """Calculate offset into data array. Only uses to test correctness of the formula.""" # Datalayout # X = longitude # Y = latitude # Sample for size 1201x1201 # ( 0/1200) ( 1/1200) ... (1199/1200) (1200/1200) ...
[ "def", "calcOffset", "(", "self", ",", "x", ",", "y", ")", ":", "# Datalayout", "# X = longitude", "# Y = latitude", "# Sample for size 1201x1201", "# ( 0/1200) ( 1/1200) ... (1199/1200) (1200/1200)", "# ( 0/1199) ( 1/1199) ... (1199/1199) (1200/1199)", ...
42.2
0.002317
def fits_recarray_to_dict(table): """Convert a FITS recarray to a python dictionary.""" cols = {} for icol, col in enumerate(table.columns.names): col_data = table.data[col] if type(col_data[0]) == np.float32: cols[col] = np.array(col_data, dtype=float) elif type(col_da...
[ "def", "fits_recarray_to_dict", "(", "table", ")", ":", "cols", "=", "{", "}", "for", "icol", ",", "col", "in", "enumerate", "(", "table", ".", "columns", ".", "names", ")", ":", "col_data", "=", "table", ".", "data", "[", "col", "]", "if", "type", ...
37.25
0.001091
def _flatten_list(x): """Flatten an arbitrarily nested list into a new list. This can be useful to select pandas DataFrame columns. From https://stackoverflow.com/a/16176969/10581531 Examples -------- >>> from pingouin.utils import _flatten_list >>> x = ['X1', ['M1', 'M2'], 'Y1', ['Y2']] ...
[ "def", "_flatten_list", "(", "x", ")", ":", "result", "=", "[", "]", "# Remove None", "x", "=", "list", "(", "filter", "(", "None", ".", "__ne__", ",", "x", ")", ")", "for", "el", "in", "x", ":", "x_is_iter", "=", "isinstance", "(", "x", ",", "co...
27
0.001277
def takeChild(self, index): """ Removes the child at the given index from this item. :param index | <int> """ item = super(XGanttWidgetItem, self).takeChild(index) if item: item.removeFromScene() return it...
[ "def", "takeChild", "(", "self", ",", "index", ")", ":", "item", "=", "super", "(", "XGanttWidgetItem", ",", "self", ")", ".", "takeChild", "(", "index", ")", "if", "item", ":", "item", ".", "removeFromScene", "(", ")", "return", "item" ]
25.916667
0.015528
def set_hook(fn, key, **kwargs): """Mark decorated function as a hook to be picked up later. .. note:: Currently only works with functions and instance methods. Class and static methods are not supported. :return: Decorated function if supplied, else this decorator with its args bo...
[ "def", "set_hook", "(", "fn", ",", "key", ",", "*", "*", "kwargs", ")", ":", "# Allow using this as either a decorator or a decorator factory.", "if", "fn", "is", "None", ":", "return", "functools", ".", "partial", "(", "set_hook", ",", "key", "=", "key", ",",...
35.96
0.001083
def update_security_group(self, security_group, body=None): """Updates a security group.""" return self.put(self.security_group_path % security_group, body=body)
[ "def", "update_security_group", "(", "self", ",", "security_group", ",", "body", "=", "None", ")", ":", "return", "self", ".", "put", "(", "self", ".", "security_group_path", "%", "security_group", ",", "body", "=", "body", ")" ]
49.5
0.00995
def decode(self, packet): ''' Decode a PUBLISH control packet. ''' self.encoded = packet lenLen = 1 while packet[lenLen] & 0x80: lenLen += 1 packet_remaining = packet[lenLen+1:] self.dup = (packet[0] & 0x08) == 0x08 self.qos = (p...
[ "def", "decode", "(", "self", ",", "packet", ")", ":", "self", ".", "encoded", "=", "packet", "lenLen", "=", "1", "while", "packet", "[", "lenLen", "]", "&", "0x80", ":", "lenLen", "+=", "1", "packet_remaining", "=", "packet", "[", "lenLen", "+", "1"...
37.1
0.013141
def notifyOnSignal(self, signalName, callback, interface=None): """ Informs the DBus daemon of the process's interest in the specified signal and registers the callback function to be called when the signal arrives. Multiple callbacks may be registered. @type signalName: C{strin...
[ "def", "notifyOnSignal", "(", "self", ",", "signalName", ",", "callback", ",", "interface", "=", "None", ")", ":", "iface", "=", "None", "signal", "=", "None", "for", "i", "in", "self", ".", "interfaces", ":", "if", "interface", "and", "not", "i", ".",...
31.735294
0.000899
def backend_from_fobj(f): """Determine backend module object from a file object.""" if magic is None: warn("magic lib is not installed; assuming mime type %r" % ( DEFAULT_MIME)) return backend_from_mime(DEFAULT_MIME) else: offset = f.tell() try: f.seek...
[ "def", "backend_from_fobj", "(", "f", ")", ":", "if", "magic", "is", "None", ":", "warn", "(", "\"magic lib is not installed; assuming mime type %r\"", "%", "(", "DEFAULT_MIME", ")", ")", "return", "backend_from_mime", "(", "DEFAULT_MIME", ")", "else", ":", "offse...
33.133333
0.001957
def binary_to_int(binary_list, lower_bound=0, upper_bound=None): """Return the base 10 integer corresponding to a binary list. The maximum value is determined by the number of bits in binary_list, and upper_bound. The greater allowed by the two. Args: binary_list: list<int>; List of 0s and 1s. ...
[ "def", "binary_to_int", "(", "binary_list", ",", "lower_bound", "=", "0", ",", "upper_bound", "=", "None", ")", ":", "# Edge case for empty binary_list", "if", "binary_list", "==", "[", "]", ":", "# With 0 bits, only one value can be represented,", "# and we default to lo...
40.026316
0.000642
def append_from_list(self, content, fill_title=False): """ Appends rows created from the data contained in the provided list of tuples of strings. The first tuple of the list can be set as table title. Args: content (list): list of tuples of strings. Each tuple is a ...
[ "def", "append_from_list", "(", "self", ",", "content", ",", "fill_title", "=", "False", ")", ":", "row_index", "=", "0", "for", "row", "in", "content", ":", "tr", "=", "TableRow", "(", ")", "column_index", "=", "0", "for", "item", "in", "row", ":", ...
37.041667
0.002193
def mlem(op, x, data, niter, callback=None, **kwargs): """Maximum Likelihood Expectation Maximation algorithm. Attempts to solve:: max_x L(x | data) where ``L(x | data)`` is the Poisson likelihood of ``x`` given ``data``. The likelihood depends on the forward operator ``op`` such that (a...
[ "def", "mlem", "(", "op", ",", "x", ",", "data", ",", "niter", ",", "callback", "=", "None", ",", "*", "*", "kwargs", ")", ":", "osmlem", "(", "[", "op", "]", ",", "x", ",", "[", "data", "]", ",", "niter", "=", "niter", ",", "callback", "=", ...
30.155172
0.000554
def violinplot(self, n=1000, **kwargs): """Plot violins of each distribution in the model family Parameters ---------- n : int Number of random variables to generate kwargs : dict or keywords Any keyword arguments to seaborn.violinplot Returns ...
[ "def", "violinplot", "(", "self", ",", "n", "=", "1000", ",", "*", "*", "kwargs", ")", ":", "kwargs", ".", "setdefault", "(", "'palette'", ",", "'Purples'", ")", "dfs", "=", "[", "]", "for", "rv", "in", "self", ".", "rvs", ":", "psi", "=", "rv", ...
30.923077
0.001608
def is_all_field_none(self): """ :rtype: bool """ if self._id_ is not None: return False if self._time_responded is not None: return False if self._time_expiry is not None: return False if self._monetary_account_id is not No...
[ "def", "is_all_field_none", "(", "self", ")", ":", "if", "self", ".", "_id_", "is", "not", "None", ":", "return", "False", "if", "self", ".", "_time_responded", "is", "not", "None", ":", "return", "False", "if", "self", ".", "_time_expiry", "is", "not", ...
21.376812
0.001296
def listDatasets(self, dataset="", parent_dataset="", is_dataset_valid=1, release_version="", pset_hash="", app_name="", output_module_label="", global_tag="", processing_version=0, acquisition_era="", run_num=-1, physics_group_name="", ...
[ "def", "listDatasets", "(", "self", ",", "dataset", "=", "\"\"", ",", "parent_dataset", "=", "\"\"", ",", "is_dataset_valid", "=", "1", ",", "release_version", "=", "\"\"", ",", "pset_hash", "=", "\"\"", ",", "app_name", "=", "\"\"", ",", "output_module_labe...
61.119048
0.019555
def _make_cell_set_template_code(): """Get the Python compiler to emit LOAD_FAST(arg); STORE_DEREF Notes ----- In Python 3, we could use an easier function: .. code-block:: python def f(): cell = None def _stub(value): nonlocal cell cell...
[ "def", "_make_cell_set_template_code", "(", ")", ":", "def", "inner", "(", "value", ")", ":", "lambda", ":", "cell", "# make ``cell`` a closure so that we get a STORE_DEREF", "cell", "=", "value", "co", "=", "inner", ".", "__code__", "# NOTE: we are marking the cell var...
27.382353
0.000518
def calculate_order_parameter(self, start_iteration = None, stop_iteration = None): """! @brief Calculates level of global synchorization (order parameter). @details This parameter is tend 1.0 when the oscillatory network close to global synchronization and it tend to 0.0 when ...
[ "def", "calculate_order_parameter", "(", "self", ",", "start_iteration", "=", "None", ",", "stop_iteration", "=", "None", ")", ":", "(", "start_iteration", ",", "stop_iteration", ")", "=", "self", ".", "__get_start_stop_iterations", "(", "start_iteration", ",", "s...
55
0.016558
def put(self, item, **kwargs): """Put an item into the queue.""" if self.full(): raise Full() self._append(item)
[ "def", "put", "(", "self", ",", "item", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "full", "(", ")", ":", "raise", "Full", "(", ")", "self", ".", "_append", "(", "item", ")" ]
28.8
0.013514
def ParseYAMLAuthorizationsList(yaml_data): """Parses YAML data into a list of APIAuthorization objects.""" try: raw_list = yaml.ParseMany(yaml_data) except (ValueError, pyyaml.YAMLError) as e: raise InvalidAPIAuthorization("Invalid YAML: %s" % e) result = [] for auth_src in raw_list: ...
[ "def", "ParseYAMLAuthorizationsList", "(", "yaml_data", ")", ":", "try", ":", "raw_list", "=", "yaml", ".", "ParseMany", "(", "yaml_data", ")", "except", "(", "ValueError", ",", "pyyaml", ".", "YAMLError", ")", "as", "e", ":", "raise", "InvalidAPIAuthorization...
32.888889
0.014778
def get_throttled_write_event_count( table_name, gsi_name, lookback_window_start=15, lookback_period=5): """ Returns the number of throttled write events during a given time frame :type table_name: str :param table_name: Name of the DynamoDB table :type gsi_name: str :param gsi_name: Name o...
[ "def", "get_throttled_write_event_count", "(", "table_name", ",", "gsi_name", ",", "lookback_window_start", "=", "15", ",", "lookback_period", "=", "5", ")", ":", "try", ":", "metrics", "=", "__get_aws_metric", "(", "table_name", ",", "gsi_name", ",", "lookback_wi...
34.34375
0.000885
def listenQ2Q(self, fromAddress, protocolsToFactories, serverDescription): """ Right now this is really only useful in the client implementation, since it is transient. protocolFactoryFactory is used for persistent listeners. """ myDomain = fromAddress.domainAddress() ...
[ "def", "listenQ2Q", "(", "self", ",", "fromAddress", ",", "protocolsToFactories", ",", "serverDescription", ")", ":", "myDomain", "=", "fromAddress", ".", "domainAddress", "(", ")", "D", "=", "self", ".", "getSecureConnection", "(", "fromAddress", ",", "myDomain...
41.906977
0.002169
def save(self, *args, **kwargs): '''The slug field is auto-populated during the save from the name field.''' if not self.id: self.slug = slugify(self.name) super(Cohort, self).save(*args, **kwargs)
[ "def", "save", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "not", "self", ".", "id", ":", "self", ".", "slug", "=", "slugify", "(", "self", ".", "name", ")", "super", "(", "Cohort", ",", "self", ")", ".", "save", "...
45.8
0.012876
def xpathNextDescendant(self, ctxt): """Traversal function for the "descendant" direction the descendant axis contains the descendants of the context node in document order; a descendant is a child or a child of a child and so on. """ if ctxt is None: ctxt__o = None ...
[ "def", "xpathNextDescendant", "(", "self", ",", "ctxt", ")", ":", "if", "ctxt", "is", "None", ":", "ctxt__o", "=", "None", "else", ":", "ctxt__o", "=", "ctxt", ".", "_o", "ret", "=", "libxml2mod", ".", "xmlXPathNextDescendant", "(", "ctxt__o", ",", "self...
48.272727
0.011091
def train(params, dtrain, num_boost_round=10, evals=(), obj=None, feval=None, maximize=False, early_stopping_rounds=None, evals_result=None, verbose_eval=True, learning_rates=None, xgb_model=None): # pylint: disable=too-many-statements,too-many-branches, attribute-defined-outside-init """Tra...
[ "def", "train", "(", "params", ",", "dtrain", ",", "num_boost_round", "=", "10", ",", "evals", "=", "(", ")", ",", "obj", "=", "None", ",", "feval", "=", "None", ",", "maximize", "=", "False", ",", "early_stopping_rounds", "=", "None", ",", "evals_resu...
41.569061
0.002207
def add(self, objs): """ Adds the given `objs` to this `LinkCollection`. - **objs** can be a list of :py:class:`.PanoptesObject` instances, a list of object IDs, a single :py:class:`.PanoptesObject` instance, or a single object ID. Examples:: organizati...
[ "def", "add", "(", "self", ",", "objs", ")", ":", "if", "self", ".", "readonly", ":", "raise", "NotImplementedError", "(", "'{} links can\\'t be modified'", ".", "format", "(", "self", ".", "_slug", ")", ")", "if", "not", "self", ".", "_parent", ".", "id...
32.166667
0.001676
def column(self, index_or_label): """Return the values of a column as an array. table.column(label) is equivalent to table[label]. >>> tiles = Table().with_columns( ... 'letter', make_array('c', 'd'), ... 'count', make_array(2, 4), ... ) >>> list(tiles...
[ "def", "column", "(", "self", ",", "index_or_label", ")", ":", "if", "(", "isinstance", "(", "index_or_label", ",", "str", ")", "and", "index_or_label", "not", "in", "self", ".", "labels", ")", ":", "raise", "ValueError", "(", "'The column \"{}\" is not in the...
33.025
0.001471
def totals(report, total_roles, role_name_length): """ Print the totals for each role's stats. """ roles_len_string = len(str(total_roles)) roles_label_len = 6 # "r" "o" "l" "e" "s" " " if clr.has_colors: roles_count_offset = 22 else: roles_count_offset = 13 roles_coun...
[ "def", "totals", "(", "report", ",", "total_roles", ",", "role_name_length", ")", ":", "roles_len_string", "=", "len", "(", "str", "(", "total_roles", ")", ")", "roles_label_len", "=", "6", "# \"r\" \"o\" \"l\" \"e\" \"s\" \" \"", "if", "clr", ".", "has_colors", ...
35.233333
0.000921
def acp_users(): """List all users.""" if not current_user.is_admin: return error("Not authorized to edit users.", 401) if not db: return error('The ACP is not available in single-user mode.', 500) alert = '' alert_status = '' if request.args.get('status') == 'deleted': ...
[ "def", "acp_users", "(", ")", ":", "if", "not", "current_user", ".", "is_admin", ":", "return", "error", "(", "\"Not authorized to edit users.\"", ",", "401", ")", "if", "not", "db", ":", "return", "error", "(", "'The ACP is not available in single-user mode.'", "...
38.115385
0.001969
def follow_model(self, model): """ Follow a particular model class, updating associated Activity objects automatically. """ if model: self.models_by_name[model.__name__.lower()] = model signals.post_save.connect(create_or_update, sender=model) signals.post_d...
[ "def", "follow_model", "(", "self", ",", "model", ")", ":", "if", "model", ":", "self", ".", "models_by_name", "[", "model", ".", "__name__", ".", "lower", "(", ")", "]", "=", "model", "signals", ".", "post_save", ".", "connect", "(", "create_or_update",...
45.125
0.016304
def map_to_precursor_biopython(seqs, names, loci, args): """map the sequences using biopython package""" precursor = precursor_sequence(loci, args.ref).upper() dat = dict() for s, n in itertools.izip(seqs, names): res = _align(str(s), precursor) if res: dat[n] = res logge...
[ "def", "map_to_precursor_biopython", "(", "seqs", ",", "names", ",", "loci", ",", "args", ")", ":", "precursor", "=", "precursor_sequence", "(", "loci", ",", "args", ".", "ref", ")", ".", "upper", "(", ")", "dat", "=", "dict", "(", ")", "for", "s", "...
39.3
0.002488
async def get_playback_settings(self) -> List[Setting]: """Get playback settings such as shuffle and repeat.""" return [ Setting.make(**x) for x in await self.services["avContent"]["getPlaybackModeSettings"]({}) ]
[ "async", "def", "get_playback_settings", "(", "self", ")", "->", "List", "[", "Setting", "]", ":", "return", "[", "Setting", ".", "make", "(", "*", "*", "x", ")", "for", "x", "in", "await", "self", ".", "services", "[", "\"avContent\"", "]", "[", "\"...
42.666667
0.011494
def calibrate(args): """ %prog calibrate calibrate.JPG boxsize Calibrate pixel-inch ratio and color adjustment. - `calibrate.JPG` is the photo containig a colorchecker - `boxsize` is the measured size for the boxes on printed colorchecker, in squared centimeter (cm2) units """ xargs =...
[ "def", "calibrate", "(", "args", ")", ":", "xargs", "=", "args", "[", "2", ":", "]", "p", "=", "OptionParser", "(", "calibrate", ".", "__doc__", ")", "opts", ",", "args", ",", "iopts", "=", "add_seeds_options", "(", "p", ",", "args", ")", "if", "le...
33.565789
0.001904
def main(): """ need to add http://sphinx-doc.org/ """ parser = argparse.ArgumentParser() sub_parser = parser.add_subparsers() lint_parser = sub_parser.add_parser('lint') lint_parser.set_defaults(func=lint) unit_test_parser = sub_parser.add_parser('unit-test') unit_test_parser.set_...
[ "def", "main", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", ")", "sub_parser", "=", "parser", ".", "add_subparsers", "(", ")", "lint_parser", "=", "sub_parser", ".", "add_parser", "(", "'lint'", ")", "lint_parser", ".", "set_defaults...
25.727273
0.001704
def parse_stats_file(self, file_name): """ Read and parse given file_name, return config as a dictionary """ stats = {} try: with open(file_name, "r") as fhandle: fbuffer = [] save_buffer = False for line in fhandle: ...
[ "def", "parse_stats_file", "(", "self", ",", "file_name", ")", ":", "stats", "=", "{", "}", "try", ":", "with", "open", "(", "file_name", ",", "\"r\"", ")", "as", "fhandle", ":", "fbuffer", "=", "[", "]", "save_buffer", "=", "False", "for", "line", "...
39.190476
0.001186
def to_dict(self): """Dump show to a dictionary. :return: Show dictionary :rtype: :class:`~python:dict` """ result = self.to_identifier() result['seasons'] = [ season.to_dict() for season in self.seasons.values() ] result['in_wa...
[ "def", "to_dict", "(", "self", ")", ":", "result", "=", "self", ".", "to_identifier", "(", ")", "result", "[", "'seasons'", "]", "=", "[", "season", ".", "to_dict", "(", ")", "for", "season", "in", "self", ".", "seasons", ".", "values", "(", ")", "...
25.90625
0.001743
def get_negative_cycle(self): ''' API: get_negative_cycle(self) Description: Finds and returns negative cost cycle using 'cost' attribute of arcs. Return value is a list of nodes representing cycle it is in the following form; n_1-n_2-...-n_k, when...
[ "def", "get_negative_cycle", "(", "self", ")", ":", "nl", "=", "self", ".", "get_node_list", "(", ")", "i", "=", "nl", "[", "0", "]", "(", "valid", ",", "distance", ",", "nextn", ")", "=", "self", ".", "floyd_warshall", "(", ")", "if", "not", "vali...
35.636364
0.002484
def insert(self, task, args=[], kwargs={}, delay_seconds=0): """ Insert a task into an existing queue. """ body = { "payload": task.payload(), "queueName": self._queue_name, "groupByTag": True, "tag": task.__class__.__name__ } def cloud_insertion(api): api.insert(b...
[ "def", "insert", "(", "self", ",", "task", ",", "args", "=", "[", "]", ",", "kwargs", "=", "{", "}", ",", "delay_seconds", "=", "0", ")", ":", "body", "=", "{", "\"payload\"", ":", "task", ".", "payload", "(", ")", ",", "\"queueName\"", ":", "sel...
22
0.008715
def check_weather(self): ''' Fetches the current weather from wxdata.weather.com service. ''' if self.units not in ('imperial', 'metric'): raise Exception("units must be one of (imperial, metric)!") if self.location_code is None: self.logger.error( ...
[ "def", "check_weather", "(", "self", ")", ":", "if", "self", ".", "units", "not", "in", "(", "'imperial'", ",", "'metric'", ")", ":", "raise", "Exception", "(", "\"units must be one of (imperial, metric)!\"", ")", "if", "self", ".", "location_code", "is", "Non...
44.463087
0.000886
def get_data(url, gallery_dir): """Persistent dictionary usage to retrieve the search indexes""" # shelve keys need to be str in python 2 if sys.version_info[0] == 2 and isinstance(url, unicode): url = url.encode('utf-8') cached_file = os.path.join(gallery_dir, 'searchindex') search_index ...
[ "def", "get_data", "(", "url", ",", "gallery_dir", ")", ":", "# shelve keys need to be str in python 2", "if", "sys", ".", "version_info", "[", "0", "]", "==", "2", "and", "isinstance", "(", "url", ",", "unicode", ")", ":", "url", "=", "url", ".", "encode"...
29.764706
0.001916
def local_walk(self, basedir): '''Walk through local directories from root basedir''' result = [] for root, dirs, files in os.walk(basedir): for f in files: result.append(os.path.join(root, f)) return result
[ "def", "local_walk", "(", "self", ",", "basedir", ")", ":", "result", "=", "[", "]", "for", "root", ",", "dirs", ",", "files", "in", "os", ".", "walk", "(", "basedir", ")", ":", "for", "f", "in", "files", ":", "result", ".", "append", "(", "os", ...
28.875
0.008403
def enforce_type(cls, jobject, intf_or_class): """ Raises an exception if the object does not implement the specified interface or is not a subclass. :param jobject: the Java object to check :type jobject: JB_Object :param intf_or_class: the classname in Java notation (eg "weka...
[ "def", "enforce_type", "(", "cls", ",", "jobject", ",", "intf_or_class", ")", ":", "if", "not", "cls", ".", "check_type", "(", "jobject", ",", "intf_or_class", ")", ":", "raise", "TypeError", "(", "\"Object does not implement or subclass \"", "+", "intf_or_class",...
49.909091
0.010733
def evtx_file_xml_view(file_header): """ Generate XML representations of the records in an EVTX file. Does not include the XML <?xml... header. Records are ordered by file_header.chunks(), and then by chunk.records() Args: chunk (Evtx.FileHeader): the file header to render. Yields: ...
[ "def", "evtx_file_xml_view", "(", "file_header", ")", ":", "for", "chunk", "in", "file_header", ".", "chunks", "(", ")", ":", "for", "record", "in", "chunk", ".", "records", "(", ")", ":", "record_str", "=", "evtx_record_xml_view", "(", "record", ")", "yie...
32.529412
0.001757
def request_update(self, context): """Requests a sink info update (sink_info_cb is called)""" pa_operation_unref(pa_context_get_sink_info_by_name( context, self.current_sink.encode(), self._sink_info_cb, None))
[ "def", "request_update", "(", "self", ",", "context", ")", ":", "pa_operation_unref", "(", "pa_context_get_sink_info_by_name", "(", "context", ",", "self", ".", "current_sink", ".", "encode", "(", ")", ",", "self", ".", "_sink_info_cb", ",", "None", ")", ")" ]
58.75
0.008403
async def _check_resolver_ans( self, dns_answer_list, record_name, record_data_list, record_ttl, record_type_code): """Check if resolver answer is equal to record data. Args: dns_answer_list (list): DNS answer list contains record objects. record_name (st...
[ "async", "def", "_check_resolver_ans", "(", "self", ",", "dns_answer_list", ",", "record_name", ",", "record_data_list", ",", "record_ttl", ",", "record_type_code", ")", ":", "type_filtered_list", "=", "[", "ans", "for", "ans", "in", "dns_answer_list", "if", "ans"...
37.055556
0.001461
def evaluate_classifier(model, data, target='target', verbose=False): """ Evaluate a CoreML classifier model and compare against predictions from the original framework (for testing correctness of conversion). Use this evaluation for models that don't deal with probabilities. Parameters -------...
[ "def", "evaluate_classifier", "(", "model", ",", "data", ",", "target", "=", "'target'", ",", "verbose", "=", "False", ")", ":", "model", "=", "_get_model", "(", "model", ")", "if", "verbose", ":", "print", "(", "\"\"", ")", "print", "(", "\"Other Framew...
26.322034
0.001862
def upload_model(self, ndex_cred=None, private=True, style='default'): """Creates a new NDEx network of the assembled CX model. To upload the assembled CX model to NDEx, you need to have a registered account on NDEx (http://ndexbio.org/) and have the `ndex` python package installed. The...
[ "def", "upload_model", "(", "self", ",", "ndex_cred", "=", "None", ",", "private", "=", "True", ",", "style", "=", "'default'", ")", ":", "cx_str", "=", "self", ".", "print_cx", "(", ")", "if", "not", "ndex_cred", ":", "username", ",", "password", "=",...
41.948718
0.001195
def print_new(ctx, name, migration_type): """Prints filename of a new migration""" click.echo(ctx.obj.repository.generate_migration_name(name, migration_type))
[ "def", "print_new", "(", "ctx", ",", "name", ",", "migration_type", ")", ":", "click", ".", "echo", "(", "ctx", ".", "obj", ".", "repository", ".", "generate_migration_name", "(", "name", ",", "migration_type", ")", ")" ]
55
0.011976
def _write_config(self, memory): """Write the configuration for this gate to memory.""" memory.seek(0) memory.write(struct.pack("<5I", # sim_length self._simulator.length, # input_a_key ...
[ "def", "_write_config", "(", "self", ",", "memory", ")", ":", "memory", ".", "seek", "(", "0", ")", "memory", ".", "write", "(", "struct", ".", "pack", "(", "\"<5I\"", ",", "# sim_length", "self", ".", "_simulator", ".", "length", ",", "# input_a_key", ...
49.611111
0.002198