text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def _get_cookie(self, mgmt_ip, config, refresh=False): """Performs authentication and retries cookie.""" if mgmt_ip not in self.credentials: return None security_data = self.credentials[mgmt_ip] verify = security_data[const.HTTPS_CERT_TUPLE] if not verify: ...
[ "def", "_get_cookie", "(", "self", ",", "mgmt_ip", ",", "config", ",", "refresh", "=", "False", ")", ":", "if", "mgmt_ip", "not", "in", "self", ".", "credentials", ":", "return", "None", "security_data", "=", "self", ".", "credentials", "[", "mgmt_ip", "...
39.888889
18.533333
def list(keystore, passphrase, alias=None, return_cert=False): ''' Lists certificates in a keytool managed keystore. :param keystore: The path to the keystore file to query :param passphrase: The passphrase to use to decode the keystore :param alias: (Optional) If found, displays details on only t...
[ "def", "list", "(", "keystore", ",", "passphrase", ",", "alias", "=", "None", ",", "return_cert", "=", "False", ")", ":", "ASN1", "=", "OpenSSL", ".", "crypto", ".", "FILETYPE_ASN1", "PEM", "=", "OpenSSL", ".", "crypto", ".", "FILETYPE_PEM", "decoded_certs...
35.508475
26.389831
def _respawn(self): """ Pick a random location for the star making sure it does not overwrite an existing piece of text. """ self._cycle = randint(0, len(self._star_chars)) (height, width) = self._screen.dimensions while True: self._x = randint(0, widt...
[ "def", "_respawn", "(", "self", ")", ":", "self", ".", "_cycle", "=", "randint", "(", "0", ",", "len", "(", "self", ".", "_star_chars", ")", ")", "(", "height", ",", "width", ")", "=", "self", ".", "_screen", ".", "dimensions", "while", "True", ":"...
38.538462
14.230769
def process_topology(self, old_top): """ Processes the sections returned by get_instances :param ConfigObj old_top: old topology as processed by :py:meth:`read_topology` :returns: tuple of dicts containing hypervisors, devices and artwork :rtype...
[ "def", "process_topology", "(", "self", ",", "old_top", ")", ":", "sections", "=", "self", ".", "get_sections", "(", "old_top", ")", "topo", "=", "LegacyTopology", "(", "sections", ",", "old_top", ")", "for", "instance", "in", "sorted", "(", "sections", ")...
43.372093
18.069767
def index_firstnot(ol,value): ''' from elist.elist import * ol = [1,'a',3,'a',4,'a',5] index_firstnot(ol,'a') ####index_firstnot, array_indexnot, indexOfnot are the same array_indexnot(ol,'a') indexOfnot(ol,'a') ''' length = ol.__len__() for i in range(0,...
[ "def", "index_firstnot", "(", "ol", ",", "value", ")", ":", "length", "=", "ol", ".", "__len__", "(", ")", "for", "i", "in", "range", "(", "0", ",", "length", ")", ":", "if", "(", "value", "==", "ol", "[", "i", "]", ")", ":", "pass", "else", ...
25.6875
17.8125
def _significant_pathways_dataframe(pvalue_information, side_information, alpha): """Create the significant pathways pandas.DataFrame. Given the p-values corresponding to each pathway in a feature, apply the FDR correction for multiple ...
[ "def", "_significant_pathways_dataframe", "(", "pvalue_information", ",", "side_information", ",", "alpha", ")", ":", "significant_pathways", "=", "pd", ".", "concat", "(", "[", "pvalue_information", ",", "side_information", "]", ",", "axis", "=", "1", ")", "# fdr...
51.869565
16.347826
def get_url(client, name, version, wheel=False, hashed_format=False): """Retrieves list of package URLs using PyPI's XML-RPC. Chooses URL of prefered archive and md5_digest. """ try: release_urls = client.release_urls(name, version) release_data = client.release_data(name, version) e...
[ "def", "get_url", "(", "client", ",", "name", ",", "version", ",", "wheel", "=", "False", ",", "hashed_format", "=", "False", ")", ":", "try", ":", "release_urls", "=", "client", ".", "release_urls", "(", "name", ",", "version", ")", "release_data", "=",...
39.148148
17.074074
def read_header(filename, return_idxs=False): """ Read blimpy header and return a Python dictionary of key:value pairs Args: filename (str): name of file to open Optional args: return_idxs (bool): Default False. If true, returns the file offset indexes for value...
[ "def", "read_header", "(", "filename", ",", "return_idxs", "=", "False", ")", ":", "with", "open", "(", "filename", ",", "'rb'", ")", "as", "fh", ":", "header_dict", "=", "{", "}", "header_idxs", "=", "{", "}", "# Check this is a blimpy file", "keyword", "...
26.486486
20.135135
def RZToverticalPotential(RZPot,R): """ NAME: RZToverticalPotential PURPOSE: convert a RZPotential to a vertical potential at a given R INPUT: RZPot - RZPotential instance or list of such instances R - Galactocentric radius at which to evaluate the vertical potential (c...
[ "def", "RZToverticalPotential", "(", "RZPot", ",", "R", ")", ":", "RZPot", "=", "flatten", "(", "RZPot", ")", "if", "_APY_LOADED", "and", "isinstance", "(", "R", ",", "units", ".", "Quantity", ")", ":", "if", "hasattr", "(", "RZPot", ",", "'_ro'", ")",...
31.882353
24.980392
def extract_files(self, resource): """ :param resource str|iterable files, a file or a directory @return: iterable """ if hasattr(resource, "__iter__"): files = [file for file in resource if self.can_be_extracted(file)] elif os.path.isfile(resource): ...
[ "def", "extract_files", "(", "self", ",", "resource", ")", ":", "if", "hasattr", "(", "resource", ",", "\"__iter__\"", ")", ":", "files", "=", "[", "file", "for", "file", "in", "resource", "if", "self", ".", "can_be_extracted", "(", "file", ")", "]", "...
36.615385
17.384615
def create_cluster_set(self, vcl): """ For a given catalogue and list of cluster IDs this function splits the catalogue into a dictionary containing an individual catalogue of events within each cluster :param numpy.ndarray vcl: Cluster ID list :returns: ...
[ "def", "create_cluster_set", "(", "self", ",", "vcl", ")", ":", "num_clust", "=", "np", ".", "max", "(", "vcl", ")", "cluster_set", "=", "[", "]", "for", "clid", "in", "range", "(", "0", ",", "num_clust", "+", "1", ")", ":", "idx", "=", "np", "."...
38.857143
13.52381
def encode_all_features(dataset, vocabulary): """Encode all features. Args: dataset: a tf.data.Dataset vocabulary: a vocabulary.Vocabulary Returns: a tf.data.Dataset """ def my_fn(features): ret = {} for k, v in features.items(): v = vocabulary.encode_tf(v) v = tf.concat([tf.t...
[ "def", "encode_all_features", "(", "dataset", ",", "vocabulary", ")", ":", "def", "my_fn", "(", "features", ")", ":", "ret", "=", "{", "}", "for", "k", ",", "v", "in", "features", ".", "items", "(", ")", ":", "v", "=", "vocabulary", ".", "encode_tf",...
25.529412
17.058824
def multi_conv_res(x, padding, name, layers, hparams, mask=None, source=None): """A stack of separable convolution blocks with residual connections.""" with tf.variable_scope(name): padding_bias = None if mask is not None: padding_bias = (1.0 - mask) * -1e9 # Bias to not attend to padding. if p...
[ "def", "multi_conv_res", "(", "x", ",", "padding", ",", "name", ",", "layers", ",", "hparams", ",", "mask", "=", "None", ",", "source", "=", "None", ")", ":", "with", "tf", ".", "variable_scope", "(", "name", ")", ":", "padding_bias", "=", "None", "i...
41.932203
16.847458
def export(self, nidm_version, export_dir): """ Create prov entities and activities. """ self.add_attributes({ PROV['type']: self.type, NIDM_DIMENSIONS_IN_VOXELS: json.dumps(self.dimensions.tolist()), NIDM_NUMBER_OF_DIMENSIONS: self.number_of_dimension...
[ "def", "export", "(", "self", ",", "nidm_version", ",", "export_dir", ")", ":", "self", ".", "add_attributes", "(", "{", "PROV", "[", "'type'", "]", ":", "self", ".", "type", ",", "NIDM_DIMENSIONS_IN_VOXELS", ":", "json", ".", "dumps", "(", "self", ".", ...
45.285714
11.714286
def _update_tokens(self): '''Present the client with authentication flow to get tokens from code. This simply updates the client _response to be used to get tokens for auth and transfer (both use access_token as index). We call this not on client initialization, but when the cli...
[ "def", "_update_tokens", "(", "self", ")", ":", "self", ".", "_client", ".", "oauth2_start_flow", "(", "refresh_tokens", "=", "True", ")", "authorize_url", "=", "self", ".", "_client", ".", "oauth2_get_authorize_url", "(", ")", "print", "(", "'Please go to this ...
48.181818
31.090909
def save(self, data, dtype_out_time, dtype_out_vert=False, save_files=True, write_to_tar=False): """Save aospy data to data_out attr and to an external file.""" self._update_data_out(data, dtype_out_time) if save_files: self._save_files(data, dtype_out_time) if w...
[ "def", "save", "(", "self", ",", "data", ",", "dtype_out_time", ",", "dtype_out_vert", "=", "False", ",", "save_files", "=", "True", ",", "write_to_tar", "=", "False", ")", ":", "self", ".", "_update_data_out", "(", "data", ",", "dtype_out_time", ")", "if"...
51.777778
12.333333
def save_params(self, fname): """Saves model parameters to file. Parameters ---------- fname : str Path to output param file. Examples -------- >>> # An example of saving module parameters. >>> mod.save_params('myfile') """ ar...
[ "def", "save_params", "(", "self", ",", "fname", ")", ":", "arg_params", ",", "aux_params", "=", "self", ".", "get_params", "(", ")", "save_dict", "=", "{", "(", "'arg:%s'", "%", "k", ")", ":", "v", ".", "as_in_context", "(", "cpu", "(", ")", ")", ...
33.823529
20.235294
def _loop_timeout_cb(self, main_loop): """Stops the loop after the time specified in the `loop` call. """ self._anything_done = True logger.debug("_loop_timeout_cb() called") main_loop.quit()
[ "def", "_loop_timeout_cb", "(", "self", ",", "main_loop", ")", ":", "self", ".", "_anything_done", "=", "True", "logger", ".", "debug", "(", "\"_loop_timeout_cb() called\"", ")", "main_loop", ".", "quit", "(", ")" ]
37.666667
5.5
async def _publish(self, model, path): """Publish notebook model to the path""" if model['type'] != 'notebook': raise web.HTTPError(400, "bookstore only publishes notebooks") content = model['content'] full_s3_path = s3_path( self.bookstore_settings.s3_bucket, se...
[ "async", "def", "_publish", "(", "self", ",", "model", ",", "path", ")", ":", "if", "model", "[", "'type'", "]", "!=", "'notebook'", ":", "raise", "web", ".", "HTTPError", "(", "400", ",", "\"bookstore only publishes notebooks\"", ")", "content", "=", "mod...
37.95
24.15
def save_vault(self, vault_form, *args, **kwargs): """Pass through to provider VaultAdminSession.update_vault""" # Implemented from kitosid template for - # osid.resource.BinAdminSession.update_bin if vault_form.is_for_update(): return self.update_vault(vault_form, *args, **k...
[ "def", "save_vault", "(", "self", ",", "vault_form", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# Implemented from kitosid template for -", "# osid.resource.BinAdminSession.update_bin", "if", "vault_form", ".", "is_for_update", "(", ")", ":", "return", "s...
49.875
13.5
def add_sequences(self, sequences, cla) -> bool: """Create a tree.Seq""" if not hasattr(sequences, 'parser_tree'): # forward sublevel of sequence as is sequences.parser_tree = cla.parser_tree else: oldnode = sequences if isinstance(oldnode.parser_tree, parsing.Seq): ...
[ "def", "add_sequences", "(", "self", ",", "sequences", ",", "cla", ")", "->", "bool", ":", "if", "not", "hasattr", "(", "sequences", ",", "'parser_tree'", ")", ":", "# forward sublevel of sequence as is", "sequences", ".", "parser_tree", "=", "cla", ".", "pars...
37.071429
12.142857
def _fromScopeXpathToRefsDecl(self, scope, xpath): """ Update xpath and scope property when refsDecl is updated """ if scope is not None and xpath is not None: _xpath = scope + xpath i = _xpath.find("?") ii = 1 while i >= 0: _xpath...
[ "def", "_fromScopeXpathToRefsDecl", "(", "self", ",", "scope", ",", "xpath", ")", ":", "if", "scope", "is", "not", "None", "and", "xpath", "is", "not", "None", ":", "_xpath", "=", "scope", "+", "xpath", "i", "=", "_xpath", ".", "find", "(", "\"?\"", ...
34.461538
12.692308
def findAll(self, pattern): """ Searches for an image pattern in the given region Returns ``Match`` object if ``pattern`` exists, empty array otherwise (does not throw exception). Sikuli supports OCR search with a text parameter. This does not (yet). """ find_time = time.time() ...
[ "def", "findAll", "(", "self", ",", "pattern", ")", ":", "find_time", "=", "time", ".", "time", "(", ")", "r", "=", "self", ".", "clipRegionToScreen", "(", ")", "if", "r", "is", "None", ":", "raise", "ValueError", "(", "\"Region outside all visible screens...
44.9375
21.395833
def frequency_app(parser, cmd, args): # pragma: no cover """ perform frequency analysis on a value. """ parser.add_argument('value', help='the value to analyse, read from stdin if omitted', nargs='?') args = parser.parse_args(args) data = frequency(six.iterbytes(pwnypack.main.binary_value_or_s...
[ "def", "frequency_app", "(", "parser", ",", "cmd", ",", "args", ")", ":", "# pragma: no cover", "parser", ".", "add_argument", "(", "'value'", ",", "help", "=", "'the value to analyse, read from stdin if omitted'", ",", "nargs", "=", "'?'", ")", "args", "=", "pa...
38.714286
18.142857
def all_to_annot(self, annot, names=['TPd', 'TPs', 'FP', 'FN']): """Convenience function to write all events to XML by category, showing overlapping TP detection and TP standard.""" self.to_annot(annot, 'tp_det', names[0]) self.to_annot(annot, 'tp_std', names[1]) self.to_annot(an...
[ "def", "all_to_annot", "(", "self", ",", "annot", ",", "names", "=", "[", "'TPd'", ",", "'TPs'", ",", "'FP'", ",", "'FN'", "]", ")", ":", "self", ".", "to_annot", "(", "annot", ",", "'tp_det'", ",", "names", "[", "0", "]", ")", "self", ".", "to_a...
54.142857
6.857143
def toStr(self): """ Produce a string representation of the pathogen summary. @return: A C{str} suitable for printing. """ # Note that the string representation contains much less # information than the HTML summary. E.g., it does not contain the # unique (de-dup...
[ "def", "toStr", "(", "self", ")", ":", "# Note that the string representation contains much less", "# information than the HTML summary. E.g., it does not contain the", "# unique (de-duplicated, by id) read count, since that is only computed", "# when we are making combined FASTA files of reads ma...
41.926829
19.04878
def make_article_info_footnotes_other(self, article_info_div): """ This will catch all of the footnotes of type 'other' in the <fn-group> of the <back> element. """ other_fn_expr = "./back/fn-group/fn[@fn-type='other']" other_fns = self.article.root.xpath(other_fn_expr) ...
[ "def", "make_article_info_footnotes_other", "(", "self", ",", "article_info_div", ")", ":", "other_fn_expr", "=", "\"./back/fn-group/fn[@fn-type='other']\"", "other_fns", "=", "self", ".", "article", ".", "root", ".", "xpath", "(", "other_fn_expr", ")", "if", "other_f...
46.230769
16.076923
def html_serialize(self, attributes, max_length=None): """Returns concatenated HTML code with SPAN tag. Args: attributes (dict): A map of name-value pairs for attributes of output SPAN tags. max_length (:obj:`int`, optional): Maximum length of span enclosed chunk. Returns: The ...
[ "def", "html_serialize", "(", "self", ",", "attributes", ",", "max_length", "=", "None", ")", ":", "doc", "=", "ET", ".", "Element", "(", "'span'", ")", "for", "chunk", "in", "self", ":", "if", "(", "chunk", ".", "has_cjk", "(", ")", "and", "not", ...
33.921053
16.842105
def update(self, cache): """ Update self cache from other. """ self.cache['delims'] = cache.get('delims') self.cache['opts'].update(cache.get('opts')) self.cache['rset'].update(cache.get('rset')) self.cache['mix'].update(cache.get('mix')) map(self.set_var, cache['...
[ "def", "update", "(", "self", ",", "cache", ")", ":", "self", ".", "cache", "[", "'delims'", "]", "=", "cache", ".", "get", "(", "'delims'", ")", "self", ".", "cache", "[", "'opts'", "]", ".", "update", "(", "cache", ".", "get", "(", "'opts'", ")...
41
8.5
def interpolate(features, hparams, decode_hp): """Interpolate between the first input frame and last target frame. Args: features: dict of tensors hparams: HParams, training hparams. decode_hp: HParams, decode hparams. Returns: images: interpolated images, 4-D Tensor, shape=(num_interp, H, W, C) ...
[ "def", "interpolate", "(", "features", ",", "hparams", ",", "decode_hp", ")", ":", "inputs", ",", "targets", "=", "features", "[", "\"inputs\"", "]", ",", "features", "[", "\"targets\"", "]", "inputs", "=", "tf", ".", "unstack", "(", "inputs", ",", "axis...
40.02381
16.833333
def _upstart_enable(name): ''' Enable an Upstart service. ''' if _upstart_is_enabled(name): return _upstart_is_enabled(name) override = '/etc/init/{0}.override'.format(name) files = ['/etc/init/{0}.conf'.format(name), override] for file_name in filter(os.path.isfile, files): ...
[ "def", "_upstart_enable", "(", "name", ")", ":", "if", "_upstart_is_enabled", "(", "name", ")", ":", "return", "_upstart_is_enabled", "(", "name", ")", "override", "=", "'/etc/init/{0}.override'", ".", "format", "(", "name", ")", "files", "=", "[", "'/etc/init...
36.12
15.32
def tolocal(self): """ Convert to local mode. """ from thunder.images.readers import fromarray if self.mode == 'local': logging.getLogger('thunder').warn('images already in local mode') pass return fromarray(self.toarray())
[ "def", "tolocal", "(", "self", ")", ":", "from", "thunder", ".", "images", ".", "readers", "import", "fromarray", "if", "self", ".", "mode", "==", "'local'", ":", "logging", ".", "getLogger", "(", "'thunder'", ")", ".", "warn", "(", "'images already in loc...
26.090909
17.545455
def get_assessment_parts_by_item(self, item_id): """Gets the assessment parts containing the given item. In plenary mode, the returned list contains all known assessment parts or an error results. Otherwise, the returned list may contain only those assessment parts that are accessible t...
[ "def", "get_assessment_parts_by_item", "(", "self", ",", "item_id", ")", ":", "# Implemented from template for", "# osid.repository.AssetCompositionSession.get_compositions_by_asset", "collection", "=", "JSONClientValidated", "(", "'assessment_authoring'", ",", "collection", "=", ...
50
21.111111
def _revoked_to_list(revs): ''' Turn the mess of OrderedDicts and Lists into a list of dicts for use in the CRL module. ''' list_ = [] for rev in revs: for rev_name, props in six.iteritems( rev): # pylint: disable=unused-variable dict_ = {} ...
[ "def", "_revoked_to_list", "(", "revs", ")", ":", "list_", "=", "[", "]", "for", "rev", "in", "revs", ":", "for", "rev_name", ",", "props", "in", "six", ".", "iteritems", "(", "rev", ")", ":", "# pylint: disable=unused-variable", "dict_", "=", "{", "}", ...
31.526316
21
def jhk_to_sdssi(jmag,hmag,kmag): '''Converts given J, H, Ks mags to an SDSS i magnitude value. Parameters ---------- jmag,hmag,kmag : float 2MASS J, H, Ks mags of the object. Returns ------- float The converted SDSS i band magnitude. ''' return convert_constant...
[ "def", "jhk_to_sdssi", "(", "jmag", ",", "hmag", ",", "kmag", ")", ":", "return", "convert_constants", "(", "jmag", ",", "hmag", ",", "kmag", ",", "SDSSI_JHK", ",", "SDSSI_JH", ",", "SDSSI_JK", ",", "SDSSI_HK", ",", "SDSSI_J", ",", "SDSSI_H", ",", "SDSSI...
22.47619
24
def setup_parser_common(parser): """Parser setup common to both rez-build and rez-release.""" from rez.build_process_ import get_build_process_types from rez.build_system import get_valid_build_systems process_types = get_build_process_types() parser.add_argument( "--process", type=str, cho...
[ "def", "setup_parser_common", "(", "parser", ")", ":", "from", "rez", ".", "build_process_", "import", "get_build_process_types", "from", "rez", ".", "build_system", "import", "get_valid_build_systems", "process_types", "=", "get_build_process_types", "(", ")", "parser"...
40.285714
21.857143
def sync(queryset, model_objs, unique_fields, update_fields=None, **kwargs): """ Performs a sync operation on a queryset, making the contents of the queryset match the contents of model_objs. This function calls bulk_upsert underneath the hood with sync=True. :type model_objs: list of :class:`Mode...
[ "def", "sync", "(", "queryset", ",", "model_objs", ",", "unique_fields", ",", "update_fields", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "bulk_upsert", "(", "queryset", ",", "model_objs", ",", "unique_fields", ",", "update_fields", "=", "upda...
46.333333
29.25
def render(self, template, **data): """Renders the template using Jinja2 with given data arguments. """ if(type(template) != str): raise TypeError("String expected") env = Environment( loader=FileSystemLoader(os.getcwd() + '/View'), autoescap...
[ "def", "render", "(", "self", ",", "template", ",", "*", "*", "data", ")", ":", "if", "(", "type", "(", "template", ")", "!=", "str", ")", ":", "raise", "TypeError", "(", "\"String expected\"", ")", "env", "=", "Environment", "(", "loader", "=", "Fil...
31.071429
14.928571
def from_tuples(*tuples): """ Creates a new DependencyResolver from a list of key-value pairs called tuples where key is dependency name and value the depedency locator (descriptor). :param tuples: a list of values where odd elements are dependency name and the following even el...
[ "def", "from_tuples", "(", "*", "tuples", ")", ":", "result", "=", "DependencyResolver", "(", ")", "if", "tuples", "==", "None", "or", "len", "(", "tuples", ")", "==", "0", ":", "return", "result", "index", "=", "0", "while", "index", "<", "len", "("...
32.307692
20.615385
def check(self): "Checks EPUB integrity" config = self.load_config() if not check_dependency_epubcheck(): sys.exit(error('Unavailable command.')) epub_file = u"%s.epub" % config['fileroot'] epub_path = join(CWD, 'build', epub_file) print success("Starting to c...
[ "def", "check", "(", "self", ")", ":", "config", "=", "self", ".", "load_config", "(", ")", "if", "not", "check_dependency_epubcheck", "(", ")", ":", "sys", ".", "exit", "(", "error", "(", "'Unavailable command.'", ")", ")", "epub_file", "=", "u\"%s.epub\"...
39.857143
9.714286
def find(self, path, all=False): """ Work out the uncached name of the file and look that up instead """ try: start, _, extn = path.rsplit('.', 2) except ValueError: return [] path = '.'.join((start, extn)) return find(path, all=all) or []
[ "def", "find", "(", "self", ",", "path", ",", "all", "=", "False", ")", ":", "try", ":", "start", ",", "_", ",", "extn", "=", "path", ".", "rsplit", "(", "'.'", ",", "2", ")", "except", "ValueError", ":", "return", "[", "]", "path", "=", "'.'",...
31
11
def to_url(request): """Serialize as a URL for a GET request.""" scheme, netloc, path, query, fragment = urlsplit(to_utf8(request.url)) query = parse_qs(query) for key, value in request.data_and_params.iteritems(): query.setdefault(key, []).append(value) query = url...
[ "def", "to_url", "(", "request", ")", ":", "scheme", ",", "netloc", ",", "path", ",", "query", ",", "fragment", "=", "urlsplit", "(", "to_utf8", "(", "request", ".", "url", ")", ")", "query", "=", "parse_qs", "(", "query", ")", "for", "key", ",", "...
40.4
21.1
def record_event(self, event: Event) -> None: """ Record the event async. """ from polyaxon.celery_api import celery_app from polyaxon.settings import EventsCeleryTasks if not event.ref_id: event.ref_id = self.get_ref_id() serialized_event = event.ser...
[ "def", "record_event", "(", "self", ",", "event", ":", "Event", ")", "->", "None", ":", "from", "polyaxon", ".", "celery_api", "import", "celery_app", "from", "polyaxon", ".", "settings", "import", "EventsCeleryTasks", "if", "not", "event", ".", "ref_id", ":...
50.684211
24.368421
def bresenham(coords_a, coords_b): ''' Given the start and end coordinates, return all the coordinates lying on the line formed by these coordinates, based on Bresenham's algorithm. http://en.wikipedia.org/wiki/Bresenham's_line_algorithm#Simplification ''' line = [] x0, y0 = coords_a x1,...
[ "def", "bresenham", "(", "coords_a", ",", "coords_b", ")", ":", "line", "=", "[", "]", "x0", ",", "y0", "=", "coords_a", "x1", ",", "y1", "=", "coords_b", "dx", "=", "abs", "(", "x1", "-", "x0", ")", "dy", "=", "abs", "(", "y1", "-", "y0", ")...
25.285714
22.071429
def banlist(self, channel): """ Get the channel banlist. Required arguments: * channel - Channel of which to get the banlist for. """ with self.lock: self.is_in_channel(channel) self.send('MODE %s b' % channel) bans = [] w...
[ "def", "banlist", "(", "self", ",", "channel", ")", ":", "with", "self", ".", "lock", ":", "self", ".", "is_in_channel", "(", "channel", ")", "self", ".", "send", "(", "'MODE %s b'", "%", "channel", ")", "bans", "=", "[", "]", "while", "self", ".", ...
33.904762
15.428571
def set_permissions(username, permissions, uid=None): ''' Configure users permissions CLI Example: .. code-block:: bash salt dell drac.set_permissions [USERNAME] [PRIVILEGES] [USER INDEX - optional] salt dell drac.set_permissions diana login,test_alerts,clear_logs 4 DRAC Privileg...
[ "def", "set_permissions", "(", "username", ",", "permissions", ",", "uid", "=", "None", ")", ":", "privileges", "=", "{", "'login'", ":", "'0x0000001'", ",", "'drac'", ":", "'0x0000002'", ",", "'user_management'", ":", "'0x0000004'", ",", "'clear_logs'", ":", ...
34.979167
19.770833
def _finished_callback(self, batch_fut, todo): """Passes exception along. Args: batch_fut: the batch future returned by running todo_tasklet. todo: (fut, option) pair. fut is the future return by each add() call. If the batch fut was successful, it has already called fut.set_result() on ot...
[ "def", "_finished_callback", "(", "self", ",", "batch_fut", ",", "todo", ")", ":", "self", ".", "_running", ".", "remove", "(", "batch_fut", ")", "err", "=", "batch_fut", ".", "get_exception", "(", ")", "if", "err", "is", "not", "None", ":", "tb", "=",...
35
17.833333
def _bytes_to_str(lines): """ Convert all lines from byte string to unicode string, if necessary """ if len(lines) >= 1 and hasattr(lines[0], 'decode'): return [line.decode('utf-8') for line in lines] else: return lines
[ "def", "_bytes_to_str", "(", "lines", ")", ":", "if", "len", "(", "lines", ")", ">=", "1", "and", "hasattr", "(", "lines", "[", "0", "]", ",", "'decode'", ")", ":", "return", "[", "line", ".", "decode", "(", "'utf-8'", ")", "for", "line", "in", "...
31
15.75
def DtypeToType(self, dtype): """Converts a Numpy dtype to the FeatureNameStatistics.Type proto enum.""" if dtype.char in np.typecodes['AllFloat']: return self.fs_proto.FLOAT elif (dtype.char in np.typecodes['AllInteger'] or dtype == np.bool or np.issubdtype(dtype, np.datetime64) or ...
[ "def", "DtypeToType", "(", "self", ",", "dtype", ")", ":", "if", "dtype", ".", "char", "in", "np", ".", "typecodes", "[", "'AllFloat'", "]", ":", "return", "self", ".", "fs_proto", ".", "FLOAT", "elif", "(", "dtype", ".", "char", "in", "np", ".", "...
42.6
12.2
def stop_loop(self): """stop QUERY thread.""" hub.kill(self._querier_thread) self._querier_thread = None self._datapath = None self.logger.info("stopped a querier.")
[ "def", "stop_loop", "(", "self", ")", ":", "hub", ".", "kill", "(", "self", ".", "_querier_thread", ")", "self", ".", "_querier_thread", "=", "None", "self", ".", "_datapath", "=", "None", "self", ".", "logger", ".", "info", "(", "\"stopped a querier.\"", ...
33.333333
7.333333
def _make_concept(self, entity): """Return Concept from a Hume entity.""" # Use the canonical name as the name of the Concept by default name = self._sanitize(entity['canonicalName']) # But if there is a trigger head text, we prefer that since # it almost always results in a clea...
[ "def", "_make_concept", "(", "self", ",", "entity", ")", ":", "# Use the canonical name as the name of the Concept by default", "name", "=", "self", ".", "_sanitize", "(", "entity", "[", "'canonicalName'", "]", ")", "# But if there is a trigger head text, we prefer that since...
42.782609
12.521739
def get_not_num(self, seq, num=0): '''Find the index of first non num element''' ind = next((i for i, x in enumerate(seq) if x != num), None) if ind == None: return self.board_size else: return ind
[ "def", "get_not_num", "(", "self", ",", "seq", ",", "num", "=", "0", ")", ":", "ind", "=", "next", "(", "(", "i", "for", "i", ",", "x", "in", "enumerate", "(", "seq", ")", "if", "x", "!=", "num", ")", ",", "None", ")", "if", "ind", "==", "N...
35.285714
16.428571
def create(self, table_id, schema): """ Create a table in Google BigQuery given a table and schema Parameters ---------- table : str Name of table to be written schema : str Use the generate_bq_schema to generate your table schema from a dataf...
[ "def", "create", "(", "self", ",", "table_id", ",", "schema", ")", ":", "from", "google", ".", "cloud", ".", "bigquery", "import", "SchemaField", "from", "google", ".", "cloud", ".", "bigquery", "import", "Table", "if", "self", ".", "exists", "(", "table...
32.456522
18.73913
def verify(self, data, require_x509=True, x509_cert=None, cert_subject_name=None, ca_pem_file=None, ca_path=None, hmac_key=None, validate_schema=True, parser=None, uri_resolver=None, id_attribute=None, expect_references=1): """ Verify the XML signature supplied in the data ...
[ "def", "verify", "(", "self", ",", "data", ",", "require_x509", "=", "True", ",", "x509_cert", "=", "None", ",", "cert_subject_name", "=", "None", ",", "ca_pem_file", "=", "None", ",", "ca_path", "=", "None", ",", "hmac_key", "=", "None", ",", "validate_...
58.266304
34.86413
def check_and_log_tp_activation_change(self): """Raise log for timeperiod change (useful for debug) :return: None """ for timeperiod in self.conf.timeperiods: brok = timeperiod.check_and_log_activation_change() if brok: self.add(brok)
[ "def", "check_and_log_tp_activation_change", "(", "self", ")", ":", "for", "timeperiod", "in", "self", ".", "conf", ".", "timeperiods", ":", "brok", "=", "timeperiod", ".", "check_and_log_activation_change", "(", ")", "if", "brok", ":", "self", ".", "add", "("...
33.222222
13.888889
def kml_region(map_source, z, x, y): """KML region fetched by a Google Earth network link. """ map = app.config["mapsources"][map_source] kml_doc = KMLRegion(app.config["url_formatter"], map, app.config["LOG_TILES_PER_ROW"], z, x, y) return kml_response(kml_doc)
[ "def", "kml_region", "(", "map_source", ",", "z", ",", "x", ",", "y", ")", ":", "map", "=", "app", ".", "config", "[", "\"mapsources\"", "]", "[", "map_source", "]", "kml_doc", "=", "KMLRegion", "(", "app", ".", "config", "[", "\"url_formatter\"", "]",...
49.5
12.666667
def _get_os_environ_dict(keys): """Return a dictionary of key/values from os.environ.""" return {k: os.environ.get(k, _UNDEFINED) for k in keys}
[ "def", "_get_os_environ_dict", "(", "keys", ")", ":", "return", "{", "k", ":", "os", ".", "environ", ".", "get", "(", "k", ",", "_UNDEFINED", ")", "for", "k", "in", "keys", "}" ]
48.666667
8.666667
def sign_sha256(key, msg): """ Generate an SHA256 HMAC, encoding msg to UTF-8 if not already encoded. key -- signing key. bytes. msg -- message to sign. unicode or bytes. """ if isinstance(msg, text_type): msg = msg.encode('utf-8') return hma...
[ "def", "sign_sha256", "(", "key", ",", "msg", ")", ":", "if", "isinstance", "(", "msg", ",", "text_type", ")", ":", "msg", "=", "msg", ".", "encode", "(", "'utf-8'", ")", "return", "hmac", ".", "new", "(", "key", ",", "msg", ",", "hashlib", ".", ...
29.083333
14.083333
def remove(self, username, user_api, filename=None, force=False): """Remove specified SSH public key from specified user.""" self.keys = API.__get_keys(filename) self.username = username user = user_api.find(username)[0] if not force: # pragma: no cover self.__confi...
[ "def", "remove", "(", "self", ",", "username", ",", "user_api", ",", "filename", "=", "None", ",", "force", "=", "False", ")", ":", "self", ".", "keys", "=", "API", ".", "__get_keys", "(", "filename", ")", "self", ".", "username", "=", "username", "u...
40.416667
14.916667
def nextChild(hotmap, index): ''' Return the next sibling of the node indicated by index. ''' nextChildIndex = min(index + 1, len(hotmap) - 1) return hotmap[nextChildIndex][1]
[ "def", "nextChild", "(", "hotmap", ",", "index", ")", ":", "nextChildIndex", "=", "min", "(", "index", "+", "1", ",", "len", "(", "hotmap", ")", "-", "1", ")", "return", "hotmap", "[", "nextChildIndex", "]", "[", "1", "]" ]
49
14.5
def equal(self, value_a, value_b): #pylint: disable=no-self-use """Check if two valid Property values are equal .. note:: This method assumes that :code:`None` and :code:`properties.undefined` are never passed in as values """ ...
[ "def", "equal", "(", "self", ",", "value_a", ",", "value_b", ")", ":", "#pylint: disable=no-self-use", "equal", "=", "value_a", "==", "value_b", "if", "hasattr", "(", "equal", ",", "'__iter__'", ")", ":", "return", "all", "(", "equal", ")", "return", "equa...
35.833333
20.666667
def _to_blockdev_map(thing): ''' Convert a string, or a json payload, or a dict in the right format, into a boto.ec2.blockdevicemapping.BlockDeviceMapping as needed by instance_present(). The following YAML is a direct representation of what is expected by the underlying boto EC2 code. YAML ex...
[ "def", "_to_blockdev_map", "(", "thing", ")", ":", "if", "not", "thing", ":", "return", "None", "if", "isinstance", "(", "thing", ",", "BlockDeviceMapping", ")", ":", "return", "thing", "if", "isinstance", "(", "thing", ",", "six", ".", "string_types", ")"...
36.607843
20.333333
def publish(self, payload, **kwargs): """ Publish a message. """ publish_kwargs = self.publish_kwargs.copy() # merge headers from when the publisher was instantiated # with any provided now; "extra" headers always win headers = publish_kwargs.pop('headers', {}).copy() ...
[ "def", "publish", "(", "self", ",", "payload", ",", "*", "*", "kwargs", ")", ":", "publish_kwargs", "=", "self", ".", "publish_kwargs", ".", "copy", "(", ")", "# merge headers from when the publisher was instantiated", "# with any provided now; \"extra\" headers always wi...
40.206349
15.047619
def get_bank_form(self, *args, **kwargs): """Pass through to provider BankAdminSession.get_bank_form_for_update""" # Implemented from kitosid template for - # osid.resource.BinAdminSession.get_bin_form_for_update_template # This method might be a bit sketchy. Time will tell. if i...
[ "def", "get_bank_form", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# Implemented from kitosid template for -", "# osid.resource.BinAdminSession.get_bin_form_for_update_template", "# This method might be a bit sketchy. Time will tell.", "if", "isinstance", ...
57.444444
19
def mouseMoved(self, viewPos): """ Updates the probe text with the values under the cursor. Draws a vertical line and a symbol at the position of the probe. """ try: check_class(viewPos, QtCore.QPointF) self.crossLineVerShadow.setVisible(False) sel...
[ "def", "mouseMoved", "(", "self", ",", "viewPos", ")", ":", "try", ":", "check_class", "(", "viewPos", ",", "QtCore", ".", "QPointF", ")", "self", ".", "crossLineVerShadow", ".", "setVisible", "(", "False", ")", "self", ".", "crossLineVertical", ".", "setV...
48.731707
22.902439
def defend_file_methods(coro): """ Decorator. Raises exception when file methods called with wrapped by :py:class:`aioftp.AsyncPathIOContext` file object. """ @functools.wraps(coro) async def wrapper(self, file, *args, **kwargs): if isinstance(file, AsyncPathIOContext): raise...
[ "def", "defend_file_methods", "(", "coro", ")", ":", "@", "functools", ".", "wraps", "(", "coro", ")", "async", "def", "wrapper", "(", "self", ",", "file", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "isinstance", "(", "file", ",", "...
41.5
14.666667
def get_qword_from_offset(self, offset): """Return the quad-word value at the given file offset. (little endian)""" if offset+8 > len(self.__data__): return None return self.get_qword_from_data(self.__data__[offset:offset+8], 0)
[ "def", "get_qword_from_offset", "(", "self", ",", "offset", ")", ":", "if", "offset", "+", "8", ">", "len", "(", "self", ".", "__data__", ")", ":", "return", "None", "return", "self", ".", "get_qword_from_data", "(", "self", ".", "__data__", "[", "offset...
37.142857
18.857143
def get_metrics_data_topic(self, name, topic_name, metric, rollup, filter_expresssion): ''' Retrieves the list of supported metrics for this namespace and topic name: Name of the service bus namespace. topic_name: Name of the service bus queue in this namespace. ...
[ "def", "get_metrics_data_topic", "(", "self", ",", "name", ",", "topic_name", ",", "metric", ",", "rollup", ",", "filter_expresssion", ")", ":", "response", "=", "self", ".", "_perform_get", "(", "self", ".", "_get_get_metrics_data_topic_path", "(", "name", ",",...
35.730769
24.730769
def generate_data_key(key_id, encryption_context=None, number_of_bytes=None, key_spec=None, grant_tokens=None, region=None, key=None, keyid=None, profile=None): ''' Generate a secure data key. CLI example:: salt myminion boto_kms.generate_data_key 'alias...
[ "def", "generate_data_key", "(", "key_id", ",", "encryption_context", "=", "None", ",", "number_of_bytes", "=", "None", ",", "key_spec", "=", "None", ",", "grant_tokens", "=", "None", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", ...
33.16
23.64
def remove_vectored_io_slice_suffix_from_name(name, slice): # type: (str, int) -> str """Remove vectored io (stripe) slice suffix from a given name :param str name: entity name :param int slice: slice num :rtype: str :return: name without suffix """ suffix = '.bxslice-{}'.format(slice) ...
[ "def", "remove_vectored_io_slice_suffix_from_name", "(", "name", ",", "slice", ")", ":", "# type: (str, int) -> str", "suffix", "=", "'.bxslice-{}'", ".", "format", "(", "slice", ")", "if", "name", ".", "endswith", "(", "suffix", ")", ":", "return", "name", "[",...
30.846154
11.461538
def media(self): """ TagAutoComplete's Media. """ def static(path): return staticfiles_storage.url( 'zinnia/admin/select2/%s' % path) return Media( css={'all': (static('css/select2.css'),)}, js=(static('js/select2.js'),) ...
[ "def", "media", "(", "self", ")", ":", "def", "static", "(", "path", ")", ":", "return", "staticfiles_storage", ".", "url", "(", "'zinnia/admin/select2/%s'", "%", "path", ")", "return", "Media", "(", "css", "=", "{", "'all'", ":", "(", "static", "(", "...
28.363636
11.272727
def get_payments_of_credit_note_per_page(self, credit_note_id, per_page=1000, page=1): """ Get payments of credit note per page :param credit_note_id: the credit note id :param per_page: How many objects per page. Default: 1000 :param page: Which page. Default: 1 :return...
[ "def", "get_payments_of_credit_note_per_page", "(", "self", ",", "credit_note_id", ",", "per_page", "=", "1000", ",", "page", "=", "1", ")", ":", "return", "self", ".", "_get_resource_per_page", "(", "resource", "=", "CREDIT_NOTE_PAYMENTS", ",", "per_page", "=", ...
35.333333
14.933333
def oai_bucket_policy_present(name, Bucket, OAI, Policy, region=None, key=None, keyid=None, profile=None): ''' Ensure the given policy exists on an S3 bucket, granting access for the given origin access identity to do the things specified in the policy. name The na...
[ "def", "oai_bucket_policy_present", "(", "name", ",", "Bucket", ",", "OAI", ",", "Policy", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "ret", "=", "{", "'name'", ":", "name", ...
43.127119
25.940678
def get_timestamps_part(self, name): """Return matching (timestamps, particles) pytables arrays. """ par_name = name + '_par' timestamps = self.ts_store.h5file.get_node('/timestamps', name) particles = self.ts_store.h5file.get_node('/timestamps', par_name) return timestam...
[ "def", "get_timestamps_part", "(", "self", ",", "name", ")", ":", "par_name", "=", "name", "+", "'_par'", "timestamps", "=", "self", ".", "ts_store", ".", "h5file", ".", "get_node", "(", "'/timestamps'", ",", "name", ")", "particles", "=", "self", ".", "...
46.714286
11.571429
def do_setup(self, arg, arguments): """ :: Usage: setup init [--force] Copies a cmd3.yaml file into ~/.cloudmesh/cmd3.yaml """ if arguments["init"]: Console.ok("Initialize cmd3.yaml file") from cmd3.yaml_setup import create...
[ "def", "do_setup", "(", "self", ",", "arg", ",", "arguments", ")", ":", "if", "arguments", "[", "\"init\"", "]", ":", "Console", ".", "ok", "(", "\"Initialize cmd3.yaml file\"", ")", "from", "cmd3", ".", "yaml_setup", "import", "create_cmd3_yaml_file", "force"...
27.266667
17
def shorten_line(tokens, source, indentation, indent_word, max_line_length, aggressive=False, experimental=False, previous_line=''): """Separate line at OPERATOR. Multiple candidates will be yielded. """ for candidate in _shorten_line(tokens=tokens, ...
[ "def", "shorten_line", "(", "tokens", ",", "source", ",", "indentation", ",", "indent_word", ",", "max_line_length", ",", "aggressive", "=", "False", ",", "experimental", "=", "False", ",", "previous_line", "=", "''", ")", ":", "for", "candidate", "in", "_sh...
35.611111
16.888889
def partitioned_iterator(self, partition_size, shuffle=True, seed=None): """ Return a partitioning :class:`audiomate.feeding.FrameIterator` for the dataset. Args: partition_size (str): Size of the partitions in bytes. The units ``k`` (kibibytes), ``m`` ...
[ "def", "partitioned_iterator", "(", "self", ",", "partition_size", ",", "shuffle", "=", "True", ",", "seed", "=", "None", ")", ":", "return", "iterator", ".", "FrameIterator", "(", "self", ".", "utt_ids", ",", "self", ".", "containers", ",", "partition_size"...
55.5
35.5
def generate_pipeline_code(pipeline_tree, operators): """Generate code specific to the construction of the sklearn Pipeline. Parameters ---------- pipeline_tree: list List of operators in the current optimized pipeline Returns ------- Source code for the sklearn pipeline """ ...
[ "def", "generate_pipeline_code", "(", "pipeline_tree", ",", "operators", ")", ":", "steps", "=", "_process_operator", "(", "pipeline_tree", ",", "operators", ")", "pipeline_text", "=", "\"make_pipeline(\\n{STEPS}\\n)\"", ".", "format", "(", "STEPS", "=", "_indent", ...
29.8125
22.625
def _StopMonitoringProcesses(self): """Stops monitoring all processes.""" # We need to make a copy of the list of pids since we are changing # the dict in the loop. for pid in list(self._process_information_per_pid.keys()): self._RaiseIfNotRegistered(pid) process = self._processes_per_pid[pi...
[ "def", "_StopMonitoringProcesses", "(", "self", ")", ":", "# We need to make a copy of the list of pids since we are changing", "# the dict in the loop.", "for", "pid", "in", "list", "(", "self", ".", "_process_information_per_pid", ".", "keys", "(", ")", ")", ":", "self"...
39.777778
13.222222
def processArgs(): """check out the arguments and figure out what to do.""" if len(sys.argv)<2: print("\n\nERROR:") print("this script requires arguments!") print('try "python command.py info"') return if sys.argv[1]=='info': print("import paths:\n ","\n ".join(sys.p...
[ "def", "processArgs", "(", ")", ":", "if", "len", "(", "sys", ".", "argv", ")", "<", "2", ":", "print", "(", "\"\\n\\nERROR:\"", ")", "print", "(", "\"this script requires arguments!\"", ")", "print", "(", "'try \"python command.py info\"'", ")", "return", "if...
38
15.571429
def ListRecursivelyViaWalking(top): """Walks a directory tree, yielding (dir_path, file_paths) tuples. For each of `top` and its subdirectories, yields a tuple containing the path to the directory and the path to each of the contained files. Note that unlike os.Walk()/tf.io.gfile.walk()/ListRecursivelyViaGlob...
[ "def", "ListRecursivelyViaWalking", "(", "top", ")", ":", "for", "dir_path", ",", "_", ",", "filenames", "in", "tf", ".", "io", ".", "gfile", ".", "walk", "(", "top", ",", "topdown", "=", "True", ")", ":", "yield", "(", "dir_path", ",", "(", "os", ...
39.55
24.4
def addConnector(self, wire1, wire2): """Add a connector between wire1 and wire2 in the network.""" if wire1 == wire2: return if wire1 > wire2: wire1, wire2 = wire2, wire1 try: last_level = self[-1] except IndexError: ...
[ "def", "addConnector", "(", "self", ",", "wire1", ",", "wire2", ")", ":", "if", "wire1", "==", "wire2", ":", "return", "if", "wire1", ">", "wire2", ":", "wire1", ",", "wire2", "=", "wire2", ",", "wire1", "try", ":", "last_level", "=", "self", "[", ...
30
15.285714
def _set_uplink_switch(self, v, load=False): """ Setter method for uplink_switch, mapped from YANG variable /uplink_switch (container) If this variable is read-only (config: false) in the source YANG file, then _set_uplink_switch is considered as a private method. Backends looking to populate this v...
[ "def", "_set_uplink_switch", "(", "self", ",", "v", ",", "load", "=", "False", ")", ":", "if", "hasattr", "(", "v", ",", "\"_utype\"", ")", ":", "v", "=", "v", ".", "_utype", "(", "v", ")", "try", ":", "t", "=", "YANGDynClass", "(", "v", ",", "...
84.772727
39.227273
def idf2txt(txt): """convert the idf text to a simple text""" astr = nocomment(txt) objs = astr.split(';') objs = [obj.split(',') for obj in objs] objs = [[line.strip() for line in obj] for obj in objs] objs = [[_tofloat(line) for line in obj] for obj in objs] objs = [tuple(obj) for obj in o...
[ "def", "idf2txt", "(", "txt", ")", ":", "astr", "=", "nocomment", "(", "txt", ")", "objs", "=", "astr", ".", "split", "(", "';'", ")", "objs", "=", "[", "obj", ".", "split", "(", "','", ")", "for", "obj", "in", "objs", "]", "objs", "=", "[", ...
29.470588
16.235294
def continue_task(cls, logger=None, task_id=_TASK_ID_NOT_SUPPLIED): """ Start a new action which is part of a serialized task. @param logger: The L{eliot.ILogger} to which to write messages, or C{None} if the default one should be used. @param task_id: A serialized task ide...
[ "def", "continue_task", "(", "cls", ",", "logger", "=", "None", ",", "task_id", "=", "_TASK_ID_NOT_SUPPLIED", ")", ":", "if", "task_id", "is", "_TASK_ID_NOT_SUPPLIED", ":", "raise", "RuntimeError", "(", "\"You must supply a task_id keyword argument.\"", ")", "if", "...
39.304348
18.695652
def _colourise(text: str, colour: str) -> str: """Colour text, if possible. Args: text: Text to colourise colour: Colour to display text in Returns: Colourised text, if possible """ if COLOUR: text = style(text, fg=colour, bold=True) return text
[ "def", "_colourise", "(", "text", ":", "str", ",", "colour", ":", "str", ")", "->", "str", ":", "if", "COLOUR", ":", "text", "=", "style", "(", "text", ",", "fg", "=", "colour", ",", "bold", "=", "True", ")", "return", "text" ]
24.25
14.833333
def write_lammps_inputs(output_dir, script_template, settings=None, data=None, script_filename="in.lammps", make_dir_if_not_present=True, **kwargs): """ Writes input files for a LAMMPS run. Input script is constructed from a str template with placeholders to b...
[ "def", "write_lammps_inputs", "(", "output_dir", ",", "script_template", ",", "settings", "=", "None", ",", "data", "=", "None", ",", "script_filename", "=", "\"in.lammps\"", ",", "make_dir_if_not_present", "=", "True", ",", "*", "*", "kwargs", ")", ":", "vari...
38.4375
20.354167
def ProcessListDirectory(self, responses): """Processes the results of the ListDirectory client action. Args: responses: a flow Responses object. """ if not responses.success: raise flow.FlowError("Unable to list directory.") with data_store.DB.GetMutationPool() as pool: for resp...
[ "def", "ProcessListDirectory", "(", "self", ",", "responses", ")", ":", "if", "not", "responses", ".", "success", ":", "raise", "flow", ".", "FlowError", "(", "\"Unable to list directory.\"", ")", "with", "data_store", ".", "DB", ".", "GetMutationPool", "(", "...
34.4
13.666667
def submit_response(self, question_id, answer_form=None): """Updates assessmentParts map to insert an item response. answer_form is None indicates that the current response is to be cleared """ if answer_form is None: response = {'missingResponse': NULL_RESPONSE, ...
[ "def", "submit_response", "(", "self", ",", "question_id", ",", "answer_form", "=", "None", ")", ":", "if", "answer_form", "is", "None", ":", "response", "=", "{", "'missingResponse'", ":", "NULL_RESPONSE", ",", "'itemId'", ":", "str", "(", "question_id", ")...
48
24.12
def execute(self, operation, parameters=()): """ Wraps execute method to record the query, execution duration and stackframe. """ __traceback_hide__ = True # NOQ # Time the exection of the query start = time.time() try: return self.cursor.ex...
[ "def", "execute", "(", "self", ",", "operation", ",", "parameters", "=", "(", ")", ")", ":", "__traceback_hide__", "=", "True", "# NOQ", "# Time the exection of the query", "start", "=", "time", ".", "time", "(", ")", "try", ":", "return", "self", ".", "cu...
26.043478
16.391304
def t_ID(self, token): r'[a-zA-Z_][a-zA-Z0-9_-]*' if token.value in self.KEYWORDS: token.type = self.KEYWORDS[token.value] return token else: return token
[ "def", "t_ID", "(", "self", ",", "token", ")", ":", "if", "token", ".", "value", "in", "self", ".", "KEYWORDS", ":", "token", ".", "type", "=", "self", ".", "KEYWORDS", "[", "token", ".", "value", "]", "return", "token", "else", ":", "return", "tok...
29.714286
13.428571
def part_specs(self, part): ''' returns the specifications of the given part. If multiple parts are matched, only the first one will be output. part: the productname or sku prints the results on stdout ''' result = self._e.parts_match( queries=[{'mpn...
[ "def", "part_specs", "(", "self", ",", "part", ")", ":", "result", "=", "self", ".", "_e", ".", "parts_match", "(", "queries", "=", "[", "{", "'mpn_or_sku'", ":", "part", "}", "]", ",", "exact_only", "=", "True", ",", "show_mpn", "=", "True", ",", ...
48.076923
19.102564
def __recursive_parser(self, onlysymbol, data, production, showerrors = False): """ Aux function. helps check_word""" LOG.debug("__recursive_parser: Begin ") if not data: return [] from pydsl.grammar.symbol import TerminalSymbol, NullSymbol, NonTerminalSymbol if isins...
[ "def", "__recursive_parser", "(", "self", ",", "onlysymbol", ",", "data", ",", "production", ",", "showerrors", "=", "False", ")", ":", "LOG", ".", "debug", "(", "\"__recursive_parser: Begin \"", ")", "if", "not", "data", ":", "return", "[", "]", "from", "...
56.779221
21.571429
def getUsersEnterpriseGroups(self, username, searchFilter, maxCount=100): """ This operation lists the groups assigned to a user account in the configured enterprise group store. You can use the filter parameter to narrow down the search results. Inputs: username - na...
[ "def", "getUsersEnterpriseGroups", "(", "self", ",", "username", ",", "searchFilter", ",", "maxCount", "=", "100", ")", ":", "params", "=", "{", "\"f\"", ":", "\"json\"", ",", "\"username\"", ":", "username", ",", "\"filter\"", ":", "searchFilter", ",", "\"m...
38.681818
15.590909
def del_big_nodes(self, grater_than=215): """Delete big nodes with many connections from the graph.""" G = self._graph it = G.nodes_iter() node_paths = [] node_names = [] del_nodes = [] summe = 1 count = 1 for node in it: l = len(G[node...
[ "def", "del_big_nodes", "(", "self", ",", "grater_than", "=", "215", ")", ":", "G", "=", "self", ".", "_graph", "it", "=", "G", ".", "nodes_iter", "(", ")", "node_paths", "=", "[", "]", "node_names", "=", "[", "]", "del_nodes", "=", "[", "]", "summ...
29.5
13.25
def by_issn(issn): """ Query aleph for records with given `issn`. The lookup is directed to the NTK's Aleph. Args: issn (str): ISSN of the periodical. Returns: obj: :class:`Model` instances for each record. """ # monkeypatched to allow search in NTK's Aleph old_url = al...
[ "def", "by_issn", "(", "issn", ")", ":", "# monkeypatched to allow search in NTK's Aleph", "old_url", "=", "aleph", ".", "ALEPH_URL", "aleph", ".", "ALEPH_URL", "=", "NTK_ALEPH_URL", "records", "=", "aleph", ".", "getISSNsXML", "(", "issn", ",", "base", "=", "\"...
30.73
16.71
def parse_device_disk(token): """Parse a single disk from the header line. Each disks has at least a device name and a unique number in its array, after that could follow a list of special flags: (W) write-mostly (S) spare disk (F) faulty disk (R) replacement disk So...
[ "def", "parse_device_disk", "(", "token", ")", ":", "name", ",", "token", "=", "token", ".", "split", "(", "\"[\"", ",", "1", ")", "number", ",", "flags", "=", "token", ".", "split", "(", "\"]\"", ",", "1", ")", "return", "name", ",", "{", "\"numbe...
29.090909
16.318182
def recgen_enumerate(gen,n=tuple(), fix_type_errors=True): """ Iterates through generators recursively and flattens them. (see `recgen`) This function adds a tuple with enumerators on each generator visited. """ if not hasattr(gen,'__iter__'): yield (n,gen) else: try: ...
[ "def", "recgen_enumerate", "(", "gen", ",", "n", "=", "tuple", "(", ")", ",", "fix_type_errors", "=", "True", ")", ":", "if", "not", "hasattr", "(", "gen", ",", "'__iter__'", ")", ":", "yield", "(", "n", ",", "gen", ")", "else", ":", "try", ":", ...
32.058824
17.705882
def hold_sync(self): """Hold syncing any state until the outermost context manager exits""" if self._holding_sync is True: yield else: try: self._holding_sync = True yield finally: self._holding_sync = False ...
[ "def", "hold_sync", "(", "self", ")", ":", "if", "self", ".", "_holding_sync", "is", "True", ":", "yield", "else", ":", "try", ":", "self", ".", "_holding_sync", "=", "True", "yield", "finally", ":", "self", ".", "_holding_sync", "=", "False", "self", ...
33.583333
12.916667
def get_can_edit(self, obj): """ returns true if user has permission to edit, false otherwise """ view = self.context.get('view') request = copy(self.context.get('request')) request._method = 'PUT' try: view.check_object_permissions(request, obj) except (Permi...
[ "def", "get_can_edit", "(", "self", ",", "obj", ")", ":", "view", "=", "self", ".", "context", ".", "get", "(", "'view'", ")", "request", "=", "copy", "(", "self", ".", "context", ".", "get", "(", "'request'", ")", ")", "request", ".", "_method", "...
36.727273
13.454545