text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def insertCallSet(self, callSet): """ Inserts a the specified callSet into this repository. """ try: models.Callset.create( id=callSet.getId(), name=callSet.getLocalId(), variantsetid=callSet.getParentContainer().getId(), ...
[ "def", "insertCallSet", "(", "self", ",", "callSet", ")", ":", "try", ":", "models", ".", "Callset", ".", "create", "(", "id", "=", "callSet", ".", "getId", "(", ")", ",", "name", "=", "callSet", ".", "getLocalId", "(", ")", ",", "variantsetid", "=",...
38.692308
11.769231
def update_section(self, section_id, name, sis_section_id): """ Update a canvas section with the given section id. https://canvas.instructure.com/doc/api/sections.html#method.sections.update """ url = SECTIONS_API.format(section_id) body = {"course_section": {}} ...
[ "def", "update_section", "(", "self", ",", "section_id", ",", "name", ",", "sis_section_id", ")", ":", "url", "=", "SECTIONS_API", ".", "format", "(", "section_id", ")", "body", "=", "{", "\"course_section\"", ":", "{", "}", "}", "if", "name", ":", "body...
33
21.75
def xor(s, pad): '''XOR a given string ``s`` with the one-time-pad ``pad``''' from itertools import cycle s = bytearray(force_bytes(s, encoding='latin-1')) pad = bytearray(force_bytes(pad, encoding='latin-1')) return binary_type(bytearray(x ^ y for x, y in zip(s, cycle(pad))))
[ "def", "xor", "(", "s", ",", "pad", ")", ":", "from", "itertools", "import", "cycle", "s", "=", "bytearray", "(", "force_bytes", "(", "s", ",", "encoding", "=", "'latin-1'", ")", ")", "pad", "=", "bytearray", "(", "force_bytes", "(", "pad", ",", "enc...
48.666667
19.666667
def analyse(node, env, non_generic=None): """Computes the type of the expression given by node. The type of the node is computed in the context of the context of the supplied type environment env. Data types can be introduced into the language simply by having a predefined set of identifiers in the ini...
[ "def", "analyse", "(", "node", ",", "env", ",", "non_generic", "=", "None", ")", ":", "if", "non_generic", "is", "None", ":", "non_generic", "=", "set", "(", ")", "# expr", "if", "isinstance", "(", "node", ",", "gast", ".", "Name", ")", ":", "if", ...
37.733025
14.825617
def transform(self, matrix): """Modifies the current transformation matrix (CTM) by applying :obj:`matrix` as an additional transformation. The new transformation of user space takes place after any existing transformation. :param matrix: A transformation :class:`Mat...
[ "def", "transform", "(", "self", ",", "matrix", ")", ":", "cairo", ".", "cairo_transform", "(", "self", ".", "_pointer", ",", "matrix", ".", "_pointer", ")", "self", ".", "_check_status", "(", ")" ]
35.846154
15.384615
def write(self, symbol, data, prune_previous_version=True, metadata=None, **kwargs): """ Records a write request to be actioned on context exit. Takes exactly the same parameters as the regular library write call. """ if data is not None: # We only write data if exist...
[ "def", "write", "(", "self", ",", "symbol", ",", "data", ",", "prune_previous_version", "=", "True", ",", "metadata", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "data", "is", "not", "None", ":", "# We only write data if existing data is None or the ...
65.636364
36
def get_frequency_grid(times, samplesperpeak=5, nyquistfactor=5, minfreq=None, maxfreq=None, returnf0dfnf=False): '''This calculates a frequency grid for the period finding functions in this module...
[ "def", "get_frequency_grid", "(", "times", ",", "samplesperpeak", "=", "5", ",", "nyquistfactor", "=", "5", ",", "minfreq", "=", "None", ",", "maxfreq", "=", "None", ",", "returnf0dfnf", "=", "False", ")", ":", "baseline", "=", "times", ".", "max", "(", ...
25.533333
25.166667
def storage_volumes(self): """ :class:`~zhmcclient.StorageVolumeManager`: Access to the :term:`storage volumes <storage volume>` in this storage group. """ # We do here some lazy loading. if not self._storage_volumes: self._storage_volumes = StorageVolumeManag...
[ "def", "storage_volumes", "(", "self", ")", ":", "# We do here some lazy loading.", "if", "not", "self", ".", "_storage_volumes", ":", "self", ".", "_storage_volumes", "=", "StorageVolumeManager", "(", "self", ")", "return", "self", ".", "_storage_volumes" ]
39.666667
11
def get_jid(jid): ''' Return the information returned when the specified job id was executed ''' serv = _get_serv(ret=None) ret = {} for minion, data in six.iteritems(serv.hgetall('ret:{0}'.format(jid))): if data: ret[minion] = salt.utils.json.loads(data) return ret
[ "def", "get_jid", "(", "jid", ")", ":", "serv", "=", "_get_serv", "(", "ret", "=", "None", ")", "ret", "=", "{", "}", "for", "minion", ",", "data", "in", "six", ".", "iteritems", "(", "serv", ".", "hgetall", "(", "'ret:{0}'", ".", "format", "(", ...
30.5
25.9
def on_deleted(self, event): """ Event Handler when a file is deleted """ key = 'filesystem:file_deleted' data = { 'filepath': event.src_path, 'is_directory': event.is_directory, 'dirpath': os.path.dirname(event.src_path) } bms...
[ "def", "on_deleted", "(", "self", ",", "event", ")", ":", "key", "=", "'filesystem:file_deleted'", "data", "=", "{", "'filepath'", ":", "event", ".", "src_path", ",", "'is_directory'", ":", "event", ".", "is_directory", ",", "'dirpath'", ":", "os", ".", "p...
29.923077
11.153846
def _get_report(self, with_line_nums=True): """ Returns a report which includes each distinct error only once, together with a list of the input lines where the error occurs. The latter will be omitted if flag is set to False. Helper for the get_report method. """ templ = '{} ← {}' if with_line_nums else...
[ "def", "_get_report", "(", "self", ",", "with_line_nums", "=", "True", ")", ":", "templ", "=", "'{} ← {}' i", " w", "th_line_nums e", "se '", "}'", "return", "'\\n'", ".", "join", "(", "[", "templ", ".", "format", "(", "error", ".", "string", ",", "','",...
34.615385
16.615385
def CreateLibSymlinks(env, symlinks): """Physically creates symlinks. The symlinks argument must be a list in form [ (link, linktarget), ... ], where link and linktarget are SCons nodes. """ Verbose = False for link, linktgt in symlinks: linktgt = link.get_dir().rel_path(linktgt) ...
[ "def", "CreateLibSymlinks", "(", "env", ",", "symlinks", ")", ":", "Verbose", "=", "False", "for", "link", ",", "linktgt", "in", "symlinks", ":", "linktgt", "=", "link", ".", "get_dir", "(", ")", ".", "rel_path", "(", "linktgt", ")", "link", "=", "link...
43.291667
21.125
def predict_epitopes_from_args(args): """ Returns an epitope collection from the given commandline arguments. Parameters ---------- args : argparse.Namespace Parsed commandline arguments for Topiary """ mhc_model = mhc_binding_predictor_from_args(args) variants = variant_collect...
[ "def", "predict_epitopes_from_args", "(", "args", ")", ":", "mhc_model", "=", "mhc_binding_predictor_from_args", "(", "args", ")", "variants", "=", "variant_collection_from_args", "(", "args", ")", "gene_expression_dict", "=", "rna_gene_expression_dict_from_args", "(", "a...
40.555556
16.481481
def start_watching(self, cluster, callback): """ Initiates the "watching" of a cluster's associated znode. This is done via kazoo's ChildrenWatch object. When a cluster's znode's child nodes are updated, a callback is fired and we update the cluster's `nodes` attribute based on...
[ "def", "start_watching", "(", "self", ",", "cluster", ",", "callback", ")", ":", "logger", ".", "debug", "(", "\"starting to watch cluster %s\"", ",", "cluster", ".", "name", ")", "wait_on_any", "(", "self", ".", "connected", ",", "self", ".", "shutdown", ")...
35.548387
21.903226
def url_to_prefix(self, id): '''url_to_prefix High-level api: Convert an identifier from `{namespace}tagname` notation to `prefix:tagname` notation. If the identifier does not have a namespace, it is assumed that the whole identifier is a tag name. Parameters ----------...
[ "def", "url_to_prefix", "(", "self", ",", "id", ")", ":", "ret", "=", "re", ".", "search", "(", "'^{(.+)}(.+)$'", ",", "id", ")", "if", "ret", ":", "return", "self", ".", "urls", "[", "ret", ".", "group", "(", "1", ")", "]", "+", "':'", "+", "r...
25.8
26.84
def dangling(prune=False, force=False): ''' Return top-level images (those on which no other images depend) which do not have a tag assigned to them. These include: - Images which were once tagged but were later untagged, such as those which were superseded by committing a new copy of an existing...
[ "def", "dangling", "(", "prune", "=", "False", ",", "force", "=", "False", ")", ":", "all_images", "=", "images", "(", "all", "=", "True", ")", "dangling_images", "=", "[", "x", "[", ":", "12", "]", "for", "x", "in", "_get_top_level_images", "(", "al...
32.054545
26.2
def create_token_file(username=id_generator(), password=id_generator()): ''' Store the admins password for further retrieve ''' cozy_ds_uid = helpers.get_uid('cozy-data-system') if not os.path.isfile(LOGIN_FILENAME): with open(LOGIN_FILENAME, 'w+') as token_file: token_file....
[ "def", "create_token_file", "(", "username", "=", "id_generator", "(", ")", ",", "password", "=", "id_generator", "(", ")", ")", ":", "cozy_ds_uid", "=", "helpers", ".", "get_uid", "(", "'cozy-data-system'", ")", "if", "not", "os", ".", "path", ".", "isfil...
39.090909
25.636364
def ai(x, context=None): """ Return the Airy function of x. """ return _apply_function_in_current_context( BigFloat, mpfr.mpfr_ai, (BigFloat._implicit_convert(x),), context, )
[ "def", "ai", "(", "x", ",", "context", "=", "None", ")", ":", "return", "_apply_function_in_current_context", "(", "BigFloat", ",", "mpfr", ".", "mpfr_ai", ",", "(", "BigFloat", ".", "_implicit_convert", "(", "x", ")", ",", ")", ",", "context", ",", ")" ...
19.818182
15.454545
def _finalize_features(self): """Add/remove features and resolve dependencies between them""" # First, flag all the enabled items (and thus their dependencies) for name, feature in self.features.items(): enabled = self.feature_is_included(name) if enabled or (enabled is ...
[ "def", "_finalize_features", "(", "self", ")", ":", "# First, flag all the enabled items (and thus their dependencies)", "for", "name", ",", "feature", "in", "self", ".", "features", ".", "items", "(", ")", ":", "enabled", "=", "self", ".", "feature_is_included", "(...
47.8125
17.25
def sg_parallel(func): r"""Decorates function as multiple gpu support towers. Args: func: function to decorate """ @wraps(func) def wrapper(**kwargs): r"""Manages arguments of `tf.sg_opt`. Args: kwargs: keyword arguments. The wrapped function will be provided with ...
[ "def", "sg_parallel", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "wrapper", "(", "*", "*", "kwargs", ")", ":", "r\"\"\"Manages arguments of `tf.sg_opt`.\n\n Args:\n kwargs: keyword arguments. The wrapped function will be provided with gpu_inde...
30.033333
18
def _cache(self, key, val): """ Request that a key/value pair be considered for caching. """ cache_size = (1 if util.dimensionless_contents(self.streams, self.kdims) else self.cache_size) if len(self) >= cache_size: first_key = next(k for k in se...
[ "def", "_cache", "(", "self", ",", "key", ",", "val", ")", ":", "cache_size", "=", "(", "1", "if", "util", ".", "dimensionless_contents", "(", "self", ".", "streams", ",", "self", ".", "kdims", ")", "else", "self", ".", "cache_size", ")", "if", "len"...
38
11.6
def _find_convertable_object(self, data): """ Get the first instance of a `self.pod_types` """ data = list(data) convertable_object_idxs = [ idx for idx, obj in enumerate(data) if obj.get('kind') in self.pod_types.keys() ] ...
[ "def", "_find_convertable_object", "(", "self", ",", "data", ")", ":", "data", "=", "list", "(", "data", ")", "convertable_object_idxs", "=", "[", "idx", "for", "idx", ",", "obj", "in", "enumerate", "(", "data", ")", "if", "obj", ".", "get", "(", "'kin...
34.1875
13.8125
def pprint(walker): """Pretty printer for tree walkers Takes a TreeWalker instance and pretty prints the output of walking the tree. :arg walker: a TreeWalker instance """ output = [] indent = 0 for token in concatenateCharacterTokens(walker): type = token["type"] if type ...
[ "def", "pprint", "(", "walker", ")", ":", "output", "=", "[", "]", "indent", "=", "0", "for", "token", "in", "concatenateCharacterTokens", "(", "walker", ")", ":", "type", "=", "token", "[", "\"type\"", "]", "if", "type", "in", "(", "\"StartTag\"", ","...
37.92
19.186667
def http_request(self, verb, uri, data=None, headers=None, files=None, response_format=None, is_rdf = True, stream = False ): ''' Primary route for all HTTP requests to repository. Ability to set most parameters for requests library, with some additional convenience parameters as well....
[ "def", "http_request", "(", "self", ",", "verb", ",", "uri", ",", "data", "=", "None", ",", "headers", "=", "None", ",", "files", "=", "None", ",", "response_format", "=", "None", ",", "is_rdf", "=", "True", ",", "stream", "=", "False", ")", ":", "...
35.104478
26.895522
def accel_ES(q: np.ndarray): """ Compute the gravitational accelerations in the earth-sun system. q in row vector of 6 elements: sun (x, y, z), earth (x, y, z) """ # Number of celestial bodies num_bodies: int = 2 # Number of dimensions in arrays; 3 spatial dimensions times the number of bod...
[ "def", "accel_ES", "(", "q", ":", "np", ".", "ndarray", ")", ":", "# Number of celestial bodies", "num_bodies", ":", "int", "=", "2", "# Number of dimensions in arrays; 3 spatial dimensions times the number of bodies", "dims", "=", "3", "*", "num_bodies", "# Body 0 is the...
27.3
18.5
def cli(env, volume_id, lun_id): """Set the LUN ID on an existing block storage volume. The LUN ID only takes effect during the Host Authorization process. It is recommended (but not necessary) to de-authorize all hosts before using this method. See `block access-revoke`. VOLUME_ID - the volume ID...
[ "def", "cli", "(", "env", ",", "volume_id", ",", "lun_id", ")", ":", "block_storage_manager", "=", "SoftLayer", ".", "BlockStorageManager", "(", "env", ".", "client", ")", "res", "=", "block_storage_manager", ".", "create_or_update_lun_id", "(", "volume_id", ","...
38.086957
26.826087
def get_full_perm(perm, obj): """Join action with the content type of ``obj``. Permission is returned in the format of ``<action>_<object_type>``. """ ctype = ContentType.objects.get_for_model(obj) # Camel case class names are converted into a space-separated # content types, so spaces have to ...
[ "def", "get_full_perm", "(", "perm", ",", "obj", ")", ":", "ctype", "=", "ContentType", ".", "objects", ".", "get_for_model", "(", "obj", ")", "# Camel case class names are converted into a space-separated", "# content types, so spaces have to be removed.", "ctype", "=", ...
37.181818
15.818182
def urlopen(url, headers={}, data=None, retries=RETRIES, timeout=TIMEOUT): '''打开一个http连接, 并返回Request. headers 是一个dict. 默认提供了一些项目, 比如User-Agent, Referer等, 就 不需要重复加入了. 这个函数只能用于http请求, 不可以用于下载大文件. 如果服务器支持gzip压缩的话, 就会使用gzip对数据进行压缩, 然后在本地自动 解压. req.data 里面放着的是最终的http数据内容, 通常都是UTF-8编码的文本. ''...
[ "def", "urlopen", "(", "url", ",", "headers", "=", "{", "}", ",", "data", "=", "None", ",", "retries", "=", "RETRIES", ",", "timeout", "=", "TIMEOUT", ")", ":", "headers_merged", "=", "default_headers", ".", "copy", "(", ")", "for", "key", "in", "hea...
33.294118
19
def _srcRect_x(self, attr_name): """ Value of `p:blipFill/a:srcRect/@{attr_name}` or 0.0 if not present. """ srcRect = self.blipFill.srcRect if srcRect is None: return 0.0 return getattr(srcRect, attr_name)
[ "def", "_srcRect_x", "(", "self", ",", "attr_name", ")", ":", "srcRect", "=", "self", ".", "blipFill", ".", "srcRect", "if", "srcRect", "is", "None", ":", "return", "0.0", "return", "getattr", "(", "srcRect", ",", "attr_name", ")" ]
32.375
9.625
def bin(sample, options={}, **kwargs): """Draw a histogram in the current context figure. Parameters ---------- sample: numpy.ndarray, 1d The sample for which the histogram must be generated. options: dict (default: {}) Options for the scales to be created. If a scale labeled 'x' ...
[ "def", "bin", "(", "sample", ",", "options", "=", "{", "}", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'sample'", "]", "=", "sample", "scales", "=", "kwargs", ".", "pop", "(", "'scales'", ",", "{", "}", ")", "for", "xy", "in", "[", "'x'...
44.851852
16.888889
def is_valid(self, qstr=None): """Return True if string is valid""" if qstr is None: qstr = self.currentText() return osp.isfile(to_text_string(qstr))
[ "def", "is_valid", "(", "self", ",", "qstr", "=", "None", ")", ":", "if", "qstr", "is", "None", ":", "qstr", "=", "self", ".", "currentText", "(", ")", "return", "osp", ".", "isfile", "(", "to_text_string", "(", "qstr", ")", ")" ]
37.2
6.6
def enablePackrat(cache_size_limit=128): """Enables "packrat" parsing, which adds memoizing to the parsing logic. Repeated parse attempts at the same string location (which happens often in many complex grammars) can immediately return a cached value, instead of re-executing par...
[ "def", "enablePackrat", "(", "cache_size_limit", "=", "128", ")", ":", "if", "not", "ParserElement", ".", "_packratEnabled", ":", "ParserElement", ".", "_packratEnabled", "=", "True", "if", "cache_size_limit", "is", "None", ":", "ParserElement", ".", "packrat_cach...
49.151515
25.909091
def make_tone(freq, db, dur, risefall, samplerate, caldb=100, calv=0.1): """ Produce a pure tone signal :param freq: Frequency of the tone to be produced (Hz) :type freq: int :param db: Intensity of the tone in dB SPL :type db: int :param dur: duration (seconds) :type dur: float :p...
[ "def", "make_tone", "(", "freq", ",", "db", ",", "dur", ",", "risefall", ",", "samplerate", ",", "caldb", "=", "100", ",", "calv", "=", "0.1", ")", ":", "if", "risefall", ">", "dur", ":", "raise", "ValueError", "(", "'Duration must be greater than risefall...
39.02
24.78
def submit_async_work_chain(self, work_chain, workunit_parent, done_hook=None): """Submit work to be executed in the background. - work_chain: An iterable of Work instances. Will be invoked serially. Each instance may have a different cardinality. There is no output-input chaining: the argume...
[ "def", "submit_async_work_chain", "(", "self", ",", "work_chain", ",", "workunit_parent", ",", "done_hook", "=", "None", ")", ":", "def", "done", "(", ")", ":", "if", "done_hook", ":", "done_hook", "(", ")", "with", "self", ".", "_pending_workchains_cond", "...
40.3
25.975
def u2handlers(self): """ Get a collection of urllib handlers. @return: A list of handlers to be installed in the opener. @rtype: [Handler,...] """ handlers = [] handlers.append(u2.ProxyHandler(self.proxy)) return handlers
[ "def", "u2handlers", "(", "self", ")", ":", "handlers", "=", "[", "]", "handlers", ".", "append", "(", "u2", ".", "ProxyHandler", "(", "self", ".", "proxy", ")", ")", "return", "handlers" ]
30.888889
12
def getPublicIP(): """Get the IP that this machine uses to contact the internet. If behind a NAT, this will still be this computer's IP, and not the router's.""" try: # Try to get the internet-facing IP by attempting a connection # to a non-existent server and reading what IP was used. ...
[ "def", "getPublicIP", "(", ")", ":", "try", ":", "# Try to get the internet-facing IP by attempting a connection", "# to a non-existent server and reading what IP was used.", "with", "closing", "(", "socket", ".", "socket", "(", "socket", ".", "AF_INET", ",", "socket", ".",...
47
20.526316
def add_to_document(self, parent): """Adds an ``Argument`` object to this ElementTree document. Adds an <arg> subelement to the parent element, typically <args> and sets up its subelements with their respective text. :param parent: An ``ET.Element`` to be the parent of a new <arg> sube...
[ "def", "add_to_document", "(", "self", ",", "parent", ")", ":", "arg", "=", "ET", ".", "SubElement", "(", "parent", ",", "\"arg\"", ")", "arg", ".", "set", "(", "\"name\"", ",", "self", ".", "name", ")", "if", "self", ".", "title", "is", "not", "No...
36.59375
22.25
def create(self, subscription_id, name, parameters, type='analysis', service='facebook'): """ Create a PYLON task :param subscription_id: The ID of the recording to create the task for :type subscription_id: str :param name: The name of the new task :type name: s...
[ "def", "create", "(", "self", ",", "subscription_id", ",", "name", ",", "parameters", ",", "type", "=", "'analysis'", ",", "service", "=", "'facebook'", ")", ":", "params", "=", "{", "'subscription_id'", ":", "subscription_id", ",", "'name'", ":", "name", ...
40.666667
20.666667
def runSql(self, migrationName, version): """ Given a migration name and version lookup the sql file and run it. """ sys.stdout.write("Running migration %s to version %s: ..."%(migrationName, version)) sqlPath = os.path.join(self.migrationDirectory, migrationName) sql = o...
[ "def", "runSql", "(", "self", ",", "migrationName", ",", "version", ")", ":", "sys", ".", "stdout", ".", "write", "(", "\"Running migration %s to version %s: ...\"", "%", "(", "migrationName", ",", "version", ")", ")", "sqlPath", "=", "os", ".", "path", ".",...
39.173913
16.565217
def extend_access_token(self, app_id, app_secret): """ Extends the expiration time of a valid OAuth access token. See <https://developers.facebook.com/roadmap/offline-access-removal/ #extend_token> """ args = { "client_id": app_id, "client_secret"...
[ "def", "extend_access_token", "(", "self", ",", "app_id", ",", "app_secret", ")", ":", "args", "=", "{", "\"client_id\"", ":", "app_id", ",", "\"client_secret\"", ":", "app_secret", ",", "\"grant_type\"", ":", "\"fb_exchange_token\"", ",", "\"fb_exchange_token\"", ...
40
15.76
def _is_group(token): """ sqlparse 0.2.2 changed it from a callable to a bool property """ is_group = token.is_group if isinstance(is_group, bool): return is_group else: return is_group()
[ "def", "_is_group", "(", "token", ")", ":", "is_group", "=", "token", ".", "is_group", "if", "isinstance", "(", "is_group", ",", "bool", ")", ":", "return", "is_group", "else", ":", "return", "is_group", "(", ")" ]
24.333333
13.666667
def strduration_long (duration, do_translate=True): """Turn a time value in seconds into x hours, x minutes, etc.""" if do_translate: # use global translator functions global _, _n else: # do not translate _ = lambda x: x _n = lambda a, b, n: a if n==1 else b if d...
[ "def", "strduration_long", "(", "duration", ",", "do_translate", "=", "True", ")", ":", "if", "do_translate", ":", "# use global translator functions", "global", "_", ",", "_n", "else", ":", "# do not translate", "_", "=", "lambda", "x", ":", "x", "_n", "=", ...
31
13.954545
def get_templates(model): """ Return a list of templates usable by a model. """ for template_name, template in templates.items(): if issubclass(template.model, model): yield (template_name, template.layout._meta.verbose_name)
[ "def", "get_templates", "(", "model", ")", ":", "for", "template_name", ",", "template", "in", "templates", ".", "items", "(", ")", ":", "if", "issubclass", "(", "template", ".", "model", ",", "model", ")", ":", "yield", "(", "template_name", ",", "templ...
49.8
12.4
def sorted(cls, items, orders): '''Returns the elements in `items` sorted according to `orders`''' return sorted(items, cmp=cls.multipleOrderComparison(orders))
[ "def", "sorted", "(", "cls", ",", "items", ",", "orders", ")", ":", "return", "sorted", "(", "items", ",", "cmp", "=", "cls", ".", "multipleOrderComparison", "(", "orders", ")", ")" ]
55.333333
21.333333
def import_complex_gateway_to_graph(diagram_graph, process_id, process_attributes, element): """ Adds to graph the new element that represents BPMN complex gateway. In addition to attributes inherited from Gateway type, complex gateway has additional attribute default flow (default value...
[ "def", "import_complex_gateway_to_graph", "(", "diagram_graph", ",", "process_id", ",", "process_attributes", ",", "element", ")", ":", "element_id", "=", "element", ".", "getAttribute", "(", "consts", ".", "Consts", ".", "id", ")", "BpmnDiagramGraphImport", ".", ...
66.75
36.5
def _cldf2wld(dataset): """Make lingpy-compatible dictinary out of cldf main data.""" header = [f for f in dataset.dataset.lexeme_class.fieldnames() if f != 'ID'] D = {0: ['lid'] + [h.lower() for h in header]} for idx, row in enumerate(dataset.objects['FormTable']): row = deepcopy(row) r...
[ "def", "_cldf2wld", "(", "dataset", ")", ":", "header", "=", "[", "f", "for", "f", "in", "dataset", ".", "dataset", ".", "lexeme_class", ".", "fieldnames", "(", ")", "if", "f", "!=", "'ID'", "]", "D", "=", "{", "0", ":", "[", "'lid'", "]", "+", ...
47.444444
17.555556
def download_and_unpack(self, url, *paths, **kw): """ Download a zipfile and immediately unpack selected content. :param url: :param paths: :param kw: :return: """ with self.temp_download(url, 'ds.zip', log=kw.pop('log', None)) as zipp: with T...
[ "def", "download_and_unpack", "(", "self", ",", "url", ",", "*", "paths", ",", "*", "*", "kw", ")", ":", "with", "self", ".", "temp_download", "(", "url", ",", "'ds.zip'", ",", "log", "=", "kw", ".", "pop", "(", "'log'", ",", "None", ")", ")", "a...
38.2
19.133333
def run_before_script(script_file, cwd=None): """Function to wrap try/except for subprocess.check_call().""" try: proc = subprocess.Popen( shlex.split(str(script_file)), stderr=subprocess.PIPE, stdout=subprocess.PIPE, cwd=cwd, ) for line in...
[ "def", "run_before_script", "(", "script_file", ",", "cwd", "=", "None", ")", ":", "try", ":", "proc", "=", "subprocess", ".", "Popen", "(", "shlex", ".", "split", "(", "str", "(", "script_file", ")", ")", ",", "stderr", "=", "subprocess", ".", "PIPE",...
32.931034
18.37931
def dims_knight(self, move): '''Knight on the rim is dim''' if self.board.piece_type_at(move.from_square) == chess.KNIGHT: rim = SquareSet( chess.BB_RANK_1 | \ chess.BB_RANK_8 | \ chess.BB_FILE_A | \ chess.BB_FILE_H) return move.to_square in rim
[ "def", "dims_knight", "(", "self", ",", "move", ")", ":", "if", "self", ".", "board", ".", "piece_type_at", "(", "move", ".", "from_square", ")", "==", "chess", ".", "KNIGHT", ":", "rim", "=", "SquareSet", "(", "chess", ".", "BB_RANK_1", "|", "chess", ...
33
12.777778
def get_plugins(modules, classes): """Find all given (sub-)classes in all modules. @param modules: the modules to search @ptype modules: iterator of modules @return: found classes @rytpe: iterator of class objects """ for module in modules: for plugin in get_module_plugins(module, cl...
[ "def", "get_plugins", "(", "modules", ",", "classes", ")", ":", "for", "module", "in", "modules", ":", "for", "plugin", "in", "get_module_plugins", "(", "module", ",", "classes", ")", ":", "yield", "plugin" ]
34.3
7.3
def order_by(self, field_path, **kwargs): """Create an "order by" query with this collection as parent. See :meth:`~.firestore_v1beta1.query.Query.order_by` for more information on this method. Args: field_path (str): A field path (``.``-delimited list of ...
[ "def", "order_by", "(", "self", ",", "field_path", ",", "*", "*", "kwargs", ")", ":", "query", "=", "query_mod", ".", "Query", "(", "self", ")", "return", "query", ".", "order_by", "(", "field_path", ",", "*", "*", "kwargs", ")" ]
39.85
20.85
def setActiveCamera(self,name): """ Sets the active camera. This method also calls the :py:meth:`Camera.on_activate() <peng3d.camera.Camera.on_activate>` event handler if the camera is not already active. """ if name == self.activeCamera: return # Cam is alre...
[ "def", "setActiveCamera", "(", "self", ",", "name", ")", ":", "if", "name", "==", "self", ".", "activeCamera", ":", "return", "# Cam is already active", "if", "name", "not", "in", "self", ".", "world", ".", "cameras", ":", "raise", "ValueError", "(", "\"Un...
39.384615
15.692308
def _parse_string(self, line): """ Consume the complete string until next " or \n """ log.debug("*** parse STRING: >>>%r<<<", line) parts = self.regex_split_string.split(line, maxsplit=1) if len(parts) == 1: # end return parts[0], None pre, match, po...
[ "def", "_parse_string", "(", "self", ",", "line", ")", ":", "log", ".", "debug", "(", "\"*** parse STRING: >>>%r<<<\"", ",", "line", ")", "parts", "=", "self", ".", "regex_split_string", ".", "split", "(", "line", ",", "maxsplit", "=", "1", ")", "if", "l...
34.8125
11.1875
def create_model(name, *attributes, **params): '''Create a :class:`Model` class for objects requiring and interface similar to :class:`StdModel`. We refers to this type of models as :ref:`local models <local-models>` since instances of such models are not persistent on a :class:`stdnet.BackendDataServer`. :param n...
[ "def", "create_model", "(", "name", ",", "*", "attributes", ",", "*", "*", "params", ")", ":", "params", "[", "'register'", "]", "=", "False", "params", "[", "'attributes'", "]", "=", "attributes", "kwargs", "=", "{", "'manager_class'", ":", "params", "....
45.333333
19.333333
def _parse_json(s): ' parse str into JsonDict ' def _obj_hook(pairs): ' convert json object to python object ' o = JsonDict() for k, v in pairs.iteritems(): o[str(k)] = v return o return json.loads(s, object_hook=_obj_hook)
[ "def", "_parse_json", "(", "s", ")", ":", "def", "_obj_hook", "(", "pairs", ")", ":", "' convert json object to python object '", "o", "=", "JsonDict", "(", ")", "for", "k", ",", "v", "in", "pairs", ".", "iteritems", "(", ")", ":", "o", "[", "str", "("...
27.1
15.9
def _get_float_remainder(fvalue, signs=9): """ Get remainder of float, i.e. 2.05 -> '05' @param fvalue: input value @type fvalue: C{integer types}, C{float} or C{Decimal} @param signs: maximum number of signs @type signs: C{integer types} @return: remainder @rtype: C{str} @raise ...
[ "def", "_get_float_remainder", "(", "fvalue", ",", "signs", "=", "9", ")", ":", "check_positive", "(", "fvalue", ")", "if", "isinstance", "(", "fvalue", ",", "six", ".", "integer_types", ")", ":", "return", "\"0\"", "if", "isinstance", "(", "fvalue", ",", ...
30.87234
18.106383
def send_error_email(subject, message, additional_recipients=None): """ Sends an email to the configured error email, if it's configured. """ recipients = _email_recipients(additional_recipients) sender = email().sender send_email( subject=subject, message=message, sender...
[ "def", "send_error_email", "(", "subject", ",", "message", ",", "additional_recipients", "=", "None", ")", ":", "recipients", "=", "_email_recipients", "(", "additional_recipients", ")", "sender", "=", "email", "(", ")", ".", "sender", "send_email", "(", "subjec...
29.416667
17.25
def next(self): """Return the next transaction object. StopIteration will be propagated from self.csvreader.next() """ try: return self.dict_to_xn(self.csvreader.next()) except MetadataException: # row was metadata; proceed to next row return ...
[ "def", "next", "(", "self", ")", ":", "try", ":", "return", "self", ".", "dict_to_xn", "(", "self", ".", "csvreader", ".", "next", "(", ")", ")", "except", "MetadataException", ":", "# row was metadata; proceed to next row", "return", "next", "(", "self", ")...
32.1
16.6
def delete(instance_id, profile=None, **kwargs): ''' Delete an instance instance_id ID of the instance to be deleted CLI Example: .. code-block:: bash salt '*' nova.delete 1138 ''' conn = _auth(profile, **kwargs) return conn.delete(instance_id)
[ "def", "delete", "(", "instance_id", ",", "profile", "=", "None", ",", "*", "*", "kwargs", ")", ":", "conn", "=", "_auth", "(", "profile", ",", "*", "*", "kwargs", ")", "return", "conn", ".", "delete", "(", "instance_id", ")" ]
17.625
23.375
def get_value(self): """ Evaluate self.expr to get the parameter's value """ if (self._value is None) and (self.expr is not None): self._value = self.expr.get_value() return self._value
[ "def", "get_value", "(", "self", ")", ":", "if", "(", "self", ".", "_value", "is", "None", ")", "and", "(", "self", ".", "expr", "is", "not", "None", ")", ":", "self", ".", "_value", "=", "self", ".", "expr", ".", "get_value", "(", ")", "return",...
28.875
14.625
def _add_module(self, aModule): """ Private method to add a module object to the snapshot. @type aModule: L{Module} @param aModule: Module object. """ ## if not isinstance(aModule, Module): ## if hasattr(aModule, '__class__'): ## typename = aMod...
[ "def", "_add_module", "(", "self", ",", "aModule", ")", ":", "## if not isinstance(aModule, Module):", "## if hasattr(aModule, '__class__'):", "## typename = aModule.__class__.__name__", "## else:", "## typename = str(type(aModule))"...
37.9
10.7
def values(self): """Gets user inputs :returns: dict of inputs: | *'fontsz'*: int -- font size for text throughout the GUI | *'display_attributes'*: dict -- what attributes of stimuli to report as they are being presented """ result = {} result['fontsz'] = self.u...
[ "def", "values", "(", "self", ")", ":", "result", "=", "{", "}", "result", "[", "'fontsz'", "]", "=", "self", ".", "ui", ".", "fontszSpnbx", ".", "value", "(", ")", "result", "[", "'display_attributes'", "]", "=", "self", ".", "ui", ".", "detailWidge...
39.363636
23.181818
def _serialize_int(value, size=32, padding=0): """ Translates a signed python integral or a BitVec into a 32 byte string, MSB first """ if size <= 0 or size > 32: raise ValueError if not isinstance(value, (int, BitVec)): raise ValueError if issymbo...
[ "def", "_serialize_int", "(", "value", ",", "size", "=", "32", ",", "padding", "=", "0", ")", ":", "if", "size", "<=", "0", "or", "size", ">", "32", ":", "raise", "ValueError", "if", "not", "isinstance", "(", "value", ",", "(", "int", ",", "BitVec"...
39.904762
18.47619
def parse_neighbors(neighbors, vars=[]): """Convert a string of the form 'X: Y Z; Y: Z' into a dict mapping regions to neighbors. The syntax is a region name followed by a ':' followed by zero or more region names, followed by ';', repeated for each region name. If you say 'X: Y' you don't need 'Y: X'...
[ "def", "parse_neighbors", "(", "neighbors", ",", "vars", "=", "[", "]", ")", ":", "dict", "=", "DefaultDict", "(", "[", "]", ")", "for", "var", "in", "vars", ":", "dict", "[", "var", "]", "=", "[", "]", "specs", "=", "[", "spec", ".", "split", ...
39
13.894737
def pause(self, pause=0): """Insert a `pause`, in seconds.""" fr = self.frames[-1] n = int(self.fps * pause) for i in range(n): fr2 = "/tmp/vpvid/" + str(len(self.frames)) + ".png" self.frames.append(fr2) os.system("cp -f %s %s" % (fr, fr2))
[ "def", "pause", "(", "self", ",", "pause", "=", "0", ")", ":", "fr", "=", "self", ".", "frames", "[", "-", "1", "]", "n", "=", "int", "(", "self", ".", "fps", "*", "pause", ")", "for", "i", "in", "range", "(", "n", ")", ":", "fr2", "=", "...
37.75
10.625
def connect_bulk(self, si, logger, vcenter_data_model, request): """ :param si: :param logger: :param VMwarevCenterResourceModel vcenter_data_model: :param request: :return: """ self.logger = logger self.logger.info('Apply connectivity changes has...
[ "def", "connect_bulk", "(", "self", ",", "si", ",", "logger", ",", "vcenter_data_model", ",", "request", ")", ":", "self", ".", "logger", "=", "logger", "self", ".", "logger", ".", "info", "(", "'Apply connectivity changes has started'", ")", "self", ".", "l...
47.175
32.825
def _array_slice(array, index): """Slice or index `array` at `index`. Parameters ---------- index : int or ibis.expr.types.IntegerValue or slice Returns ------- sliced_array : ibis.expr.types.ValueExpr If `index` is an ``int`` or :class:`~ibis.expr.types.IntegerValue` then ...
[ "def", "_array_slice", "(", "array", ",", "index", ")", ":", "if", "isinstance", "(", "index", ",", "slice", ")", ":", "start", "=", "index", ".", "start", "stop", "=", "index", ".", "stop", "if", "(", "start", "is", "not", "None", "and", "start", ...
31.354839
21.290323
def get_qpimage(self, index): """Return a single QPImage of the series Parameters ---------- index: int or str Index or identifier of the QPImage Notes ----- Instead of ``qps.get_qpimage(index)``, it is possible to use the short-hand ``qps[in...
[ "def", "get_qpimage", "(", "self", ",", "index", ")", ":", "if", "isinstance", "(", "index", ",", "str", ")", ":", "# search for the identifier", "for", "ii", "in", "range", "(", "len", "(", "self", ")", ")", ":", "qpi", "=", "self", "[", "ii", "]", ...
34.410256
14.589744
def get_specificity(self, scalar=None): """True_Negative / (True_Negative + False_Positive)""" if ((not self._scalar_stats and not scalar and self._num_classes > 2) or ((scalar is False or self._scalar_stats is False) and self._num_classes > 1)): spec = PrettyDict() ...
[ "def", "get_specificity", "(", "self", ",", "scalar", "=", "None", ")", ":", "if", "(", "(", "not", "self", ".", "_scalar_stats", "and", "not", "scalar", "and", "self", ".", "_num_classes", ">", "2", ")", "or", "(", "(", "scalar", "is", "False", "or"...
57.5
18.357143
def find_vmrun(self): """ Searches for vmrun. :returns: path to vmrun """ # look for vmrun vmrun_path = self.config.get_section_config("VMware").get("vmrun_path") if not vmrun_path: if sys.platform.startswith("win"): vmrun_path = shut...
[ "def", "find_vmrun", "(", "self", ")", ":", "# look for vmrun", "vmrun_path", "=", "self", ".", "config", ".", "get_section_config", "(", "\"VMware\"", ")", ".", "get", "(", "\"vmrun_path\"", ")", "if", "not", "vmrun_path", ":", "if", "sys", ".", "platform",...
46.027027
25.540541
def loadsItem(self, data, contentType=None, version=None): ''' [OPTIONAL] Identical to :meth:`loadItem`, except the serialized form is provided as a string representation in `data` instead of as a stream. The default implementation just wraps :meth:`loadItem`. ''' buf = six.StringIO(data) ...
[ "def", "loadsItem", "(", "self", ",", "data", ",", "contentType", "=", "None", ",", "version", "=", "None", ")", ":", "buf", "=", "six", ".", "StringIO", "(", "data", ")", "return", "self", ".", "loadItem", "(", "buf", ",", "contentType", ",", "versi...
40.111111
21.666667
def parse_pubmed_url(pubmed_url): """Get PubMed ID (pmid) from PubMed URL.""" parse_result = urlparse(pubmed_url) pattern = re.compile(r'^/pubmed/(\d+)$') pmid = pattern.match(parse_result.path).group(1) return pmid
[ "def", "parse_pubmed_url", "(", "pubmed_url", ")", ":", "parse_result", "=", "urlparse", "(", "pubmed_url", ")", "pattern", "=", "re", ".", "compile", "(", "r'^/pubmed/(\\d+)$'", ")", "pmid", "=", "pattern", ".", "match", "(", "parse_result", ".", "path", ")...
41.666667
9.166667
def get_center_offset(self): """ Return x, y pair that will change world coords to screen coords :return: int, int """ return (-self.view_rect.centerx + self._half_width, -self.view_rect.centery + self._half_height)
[ "def", "get_center_offset", "(", "self", ")", ":", "return", "(", "-", "self", ".", "view_rect", ".", "centerx", "+", "self", ".", "_half_width", ",", "-", "self", ".", "view_rect", ".", "centery", "+", "self", ".", "_half_height", ")" ]
43
11
def _webdav_move_copy(self, remote_path_source, remote_path_target, operation): """Copies or moves a remote file or directory :param remote_path_source: source file or folder to copy / move :param remote_path_target: target file to which to copy / move :param ...
[ "def", "_webdav_move_copy", "(", "self", ",", "remote_path_source", ",", "remote_path_target", ",", "operation", ")", ":", "if", "operation", "!=", "\"MOVE\"", "and", "operation", "!=", "\"COPY\"", ":", "return", "False", "if", "remote_path_target", "[", "-", "1...
35.03125
22.09375
def parse_union_member_types(lexer: Lexer) -> List[NamedTypeNode]: """UnionMemberTypes""" types: List[NamedTypeNode] = [] if expect_optional_token(lexer, TokenKind.EQUALS): # optional leading pipe expect_optional_token(lexer, TokenKind.PIPE) append = types.append while True: ...
[ "def", "parse_union_member_types", "(", "lexer", ":", "Lexer", ")", "->", "List", "[", "NamedTypeNode", "]", ":", "types", ":", "List", "[", "NamedTypeNode", "]", "=", "[", "]", "if", "expect_optional_token", "(", "lexer", ",", "TokenKind", ".", "EQUALS", ...
38
14
def list_guests(self, host_id, tags=None, cpus=None, memory=None, hostname=None, domain=None, local_disk=None, nic_speed=None, public_ip=None, private_ip=None, **kwargs): """Retrieve a list of all virtual servers on the dedicated host. Example:: # Pr...
[ "def", "list_guests", "(", "self", ",", "host_id", ",", "tags", "=", "None", ",", "cpus", "=", "None", ",", "memory", "=", "None", ",", "hostname", "=", "None", ",", "domain", "=", "None", ",", "local_disk", "=", "None", ",", "nic_speed", "=", "None"...
38.3
22.311111
def variable_status(code: str, exclude_variable: Union[set, None] = None, jsonable_parameter: bool = True) -> tuple: """ Find the possible parameters and "global" variables from a python code. This is achieved by parsing the abstract syntax tree. Parameters ...
[ "def", "variable_status", "(", "code", ":", "str", ",", "exclude_variable", ":", "Union", "[", "set", ",", "None", "]", "=", "None", ",", "jsonable_parameter", ":", "bool", "=", "True", ")", "->", "tuple", ":", "if", "exclude_variable", "is", "None", ":"...
40.36
21.864
def bulk_delete(self, *filters_or_records): """Shortcut to bulk delete records .. versionadded:: 2.17.0 Args: *filters_or_records (tuple) or (Record): Either a list of Records, or a list of filters. Notes: Requires Swimlane 2.17+ ...
[ "def", "bulk_delete", "(", "self", ",", "*", "filters_or_records", ")", ":", "_type", "=", "validate_filters_or_records", "(", "filters_or_records", ")", "data_dict", "=", "{", "}", "# build record_id list", "if", "_type", "is", "Record", ":", "record_ids", "=", ...
33.709091
20.018182
def to_dict(self): """Convert instance to a serializable mapping.""" config = {} for attr in dir(self): if not attr.startswith('_'): value = getattr(self, attr) if not hasattr(value, '__call__'): config[attr] = value return ...
[ "def", "to_dict", "(", "self", ")", ":", "config", "=", "{", "}", "for", "attr", "in", "dir", "(", "self", ")", ":", "if", "not", "attr", ".", "startswith", "(", "'_'", ")", ":", "value", "=", "getattr", "(", "self", ",", "attr", ")", "if", "no...
35.333333
9.444444
def compute_hash(func, string): """compute hash of string using given hash function""" h = func() h.update(string) return h.hexdigest()
[ "def", "compute_hash", "(", "func", ",", "string", ")", ":", "h", "=", "func", "(", ")", "h", ".", "update", "(", "string", ")", "return", "h", ".", "hexdigest", "(", ")" ]
29.4
14.2
def update_entitlement(owner, repo, identifier, name, token, show_tokens): """Update an entitlement in a repository.""" client = get_entitlements_api() data = {} if name is not None: data["name"] = name if token is not None: data["token"] = token with catch_raise_api_exception...
[ "def", "update_entitlement", "(", "owner", ",", "repo", ",", "identifier", ",", "name", ",", "token", ",", "show_tokens", ")", ":", "client", "=", "get_entitlements_api", "(", ")", "data", "=", "{", "}", "if", "name", "is", "not", "None", ":", "data", ...
27.681818
19.863636
def build_mv_grid_district(self, poly_id, subst_id, grid_district_geo_data, station_geo_data): """Initiates single MV grid_district including station and grid Parameters ---------- poly_id: int ID of grid_district according to database table. Also use...
[ "def", "build_mv_grid_district", "(", "self", ",", "poly_id", ",", "subst_id", ",", "grid_district_geo_data", ",", "station_geo_data", ")", ":", "mv_station", "=", "MVStationDing0", "(", "id_db", "=", "subst_id", ",", "geo_data", "=", "station_geo_data", ")", "mv_...
38.361111
22.361111
def release_address(self, address, vpnid): """Release a specific lease, called after delete_client_entry""" query = address + "?action=releaseAddress&vpnId=" + vpnid request_url = self._build_url(['Lease', query]) return self._do_request('DELETE', request_url)
[ "def", "release_address", "(", "self", ",", "address", ",", "vpnid", ")", ":", "query", "=", "address", "+", "\"?action=releaseAddress&vpnId=\"", "+", "vpnid", "request_url", "=", "self", ".", "_build_url", "(", "[", "'Lease'", ",", "query", "]", ")", "retur...
57.6
11.2
def printdata(self) -> None: """ Prints data to stdout """ np.set_printoptions(threshold=np.nan) print(self.data) np.set_printoptions(threshold=1000)
[ "def", "printdata", "(", "self", ")", "->", "None", ":", "np", ".", "set_printoptions", "(", "threshold", "=", "np", ".", "nan", ")", "print", "(", "self", ".", "data", ")", "np", ".", "set_printoptions", "(", "threshold", "=", "1000", ")" ]
35.4
7.2
def copy(self): """ Deepcopy the parameter (with a new uniqueid). All other tags will remain the same... so some other tag should be changed before attaching back to a ParameterSet or Bundle. :return: the copied :class:`Parameter` object """ s = self.to_json() ...
[ "def", "copy", "(", "self", ")", ":", "s", "=", "self", ".", "to_json", "(", ")", "cpy", "=", "parameter_from_json", "(", "s", ")", "# TODO: may need to subclass for Parameters that require bundle by using this line instead:", "# cpy = parameter_from_json(s, bundle=self._bund...
39.928571
20.5
def read(cls, iprot): ''' Read a new object from the given input protocol and return the object. :type iprot: thryft.protocol._input_protocol._InputProtocol :rtype: pastpy.gen.database.impl.online.online_database_objects_list_item.OnlineDatabaseObjectsListItem ''' init_...
[ "def", "read", "(", "cls", ",", "iprot", ")", ":", "init_kwds", "=", "{", "}", "iprot", ".", "read_struct_begin", "(", ")", "while", "True", ":", "ifield_name", ",", "ifield_type", ",", "_ifield_id", "=", "iprot", ".", "read_field_begin", "(", ")", "if",...
37.5
21.633333
def stop_supporting_containers(get_container_name, extra_containers): """ Stop postgres and solr containers, along with any specified extra containers """ docker.remove_container(get_container_name('postgres')) docker.remove_container(get_container_name('solr')) for container in extra_containers...
[ "def", "stop_supporting_containers", "(", "get_container_name", ",", "extra_containers", ")", ":", "docker", ".", "remove_container", "(", "get_container_name", "(", "'postgres'", ")", ")", "docker", ".", "remove_container", "(", "get_container_name", "(", "'solr'", "...
47.125
15.875
def ask(self, question, default=False): """ Ask a y/n question to the user. """ choices = '[%s/%s]' % ('Y' if default else 'y', 'n' if default else 'N') while True: response = raw_input('%s %s' % (question, choices)).strip() if not response: return...
[ "def", "ask", "(", "self", ",", "question", ",", "default", "=", "False", ")", ":", "choices", "=", "'[%s/%s]'", "%", "(", "'Y'", "if", "default", "else", "'y'", ",", "'n'", "if", "default", "else", "'N'", ")", "while", "True", ":", "response", "=", ...
37.166667
12.5
def do_POST(self): """Handles the HTTP POST request. Attempts to interpret all HTTP POST requests as XML-RPC calls, which are forwarded to the server's _dispatch method for handling. """ # Check that the path is legal if not self.is_rpc_path_valid(): self.re...
[ "def", "do_POST", "(", "self", ")", ":", "# Check that the path is legal", "if", "not", "self", ".", "is_rpc_path_valid", "(", ")", ":", "self", ".", "report_404", "(", ")", "return", "try", ":", "# Get arguments by reading body of request.", "# We read this in chunks...
39.918367
17.632653
def load_and_save(path, output_path=None, use_nep8=True): """ Call `load_and_save` to load a Python file to be compiled to the .avm format and save the result. By default, the resultant .avm file is saved along side the source file. :param path: The path of the Python file to compile ...
[ "def", "load_and_save", "(", "path", ",", "output_path", "=", "None", ",", "use_nep8", "=", "True", ")", ":", "compiler", "=", "Compiler", ".", "load", "(", "os", ".", "path", ".", "abspath", "(", "path", ")", ",", "use_nep8", "=", "use_nep8", ")", "...
36.8
23.333333
def spin1_a(self): """Returns the dimensionless spin magnitude of mass 1.""" return coordinates.cartesian_to_spherical_rho( self.spin1x, self.spin1y, self.spin1z)
[ "def", "spin1_a", "(", "self", ")", ":", "return", "coordinates", ".", "cartesian_to_spherical_rho", "(", "self", ".", "spin1x", ",", "self", ".", "spin1y", ",", "self", ".", "spin1z", ")" ]
52.75
17.5
def init_command_set(self, scrapyd_url): """ Initialize command set by scrapyd_url,each element is a list such as ['command','supported http method type'] """ if scrapyd_url[-1:] != '/': scrapyd_url = scrapyd_url + '/' self['daemonstatus'] = [scrapyd_url + 'daemonst...
[ "def", "init_command_set", "(", "self", ",", "scrapyd_url", ")", ":", "if", "scrapyd_url", "[", "-", "1", ":", "]", "!=", "'/'", ":", "scrapyd_url", "=", "scrapyd_url", "+", "'/'", "self", "[", "'daemonstatus'", "]", "=", "[", "scrapyd_url", "+", "'daemo...
65.555556
33.777778
def sample(self, batch_size, batch_idxs=None): """Return a randomized batch of experiences # Argument batch_size (int): Size of the all batch batch_idxs (int): Indexes to extract # Returns A list of experiences randomly selected """ # It is no...
[ "def", "sample", "(", "self", ",", "batch_size", ",", "batch_idxs", "=", "None", ")", ":", "# It is not possible to tell whether the first state in the memory is terminal, because it", "# would require access to the \"terminal\" flag associated to the previous state. As a result", "# we ...
53.188406
24.695652
def _unpack_truisms(self, c): """ Given a constraint, _unpack_truisms() returns a set of constraints that must be True this constraint to be True. """ try: op = getattr(self, '_unpack_truisms_'+c.op) except AttributeError: return set() ret...
[ "def", "_unpack_truisms", "(", "self", ",", "c", ")", ":", "try", ":", "op", "=", "getattr", "(", "self", ",", "'_unpack_truisms_'", "+", "c", ".", "op", ")", "except", "AttributeError", ":", "return", "set", "(", ")", "return", "op", "(", "c", ")" ]
29
17.909091
def get_control_connection_host(self): """ Returns the control connection host metadata. """ connection = self.control_connection._connection endpoint = connection.endpoint if connection else None return self.metadata.get_host(endpoint) if endpoint else None
[ "def", "get_control_connection_host", "(", "self", ")", ":", "connection", "=", "self", ".", "control_connection", ".", "_connection", "endpoint", "=", "connection", ".", "endpoint", "if", "connection", "else", "None", "return", "self", ".", "metadata", ".", "ge...
42.857143
11.714286
def Get(self): """Return a GrrMessage instance from the transaction log or None.""" try: value, reg_type = winreg.QueryValueEx(_GetServiceKey(), "Transaction") except OSError: return if reg_type != winreg.REG_BINARY: return try: return rdf_flows.GrrMessage.FromSerializedStr...
[ "def", "Get", "(", "self", ")", ":", "try", ":", "value", ",", "reg_type", "=", "winreg", ".", "QueryValueEx", "(", "_GetServiceKey", "(", ")", ",", "\"Transaction\"", ")", "except", "OSError", ":", "return", "if", "reg_type", "!=", "winreg", ".", "REG_B...
25.428571
25
def get(self, request=None, timeout=1.0): """Get an NDEF message from the server. Temporarily connects to the default SNEP server if the client is not yet connected. .. deprecated:: 0.13 Use :meth:`get_records` or :meth:`get_octets`. """ if request is None: ...
[ "def", "get", "(", "self", ",", "request", "=", "None", ",", "timeout", "=", "1.0", ")", ":", "if", "request", "is", "None", ":", "request", "=", "nfc", ".", "ndef", ".", "Message", "(", "nfc", ".", "ndef", ".", "Record", "(", ")", ")", "if", "...
33.304348
18.391304
def backend_monitor(backend): """Monitor a single IBMQ backend. Args: backend (IBMQBackend): Backend to monitor. Raises: QiskitError: Input is not a IBMQ backend. """ if not isinstance(backend, IBMQBackend): raise QiskitError('Input variable is not of type IBMQBackend.') ...
[ "def", "backend_monitor", "(", "backend", ")", ":", "if", "not", "isinstance", "(", "backend", ",", "IBMQBackend", ")", ":", "raise", "QiskitError", "(", "'Input variable is not of type IBMQBackend.'", ")", "config", "=", "backend", ".", "configuration", "(", ")",...
34.225
18.325
def eni_absent( name, release_eip=False, region=None, key=None, keyid=None, profile=None): ''' Ensure the EC2 ENI is absent. .. versionadded:: 2016.3.0 name Name tag associated with the ENI. release_eip True/False - release any EIP a...
[ "def", "eni_absent", "(", "name", ",", "release_eip", "=", "False", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'result'", ":",...
36.195652
22.565217
def _enter_namespace(self, namespace_name): """ A namespace is usually an absolute file name of the grammar. A special namespace '__base__' is used for BASETYPE namespace. """ if namespace_name not in self.namespaces: self.namespaces[namespace_name] = {} ...
[ "def", "_enter_namespace", "(", "self", ",", "namespace_name", ")", ":", "if", "namespace_name", "not", "in", "self", ".", "namespaces", ":", "self", ".", "namespaces", "[", "namespace_name", "]", "=", "{", "}", "# BASETYPE namespace is imported in each namespace", ...
40.571429
16.142857