text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def get_outputs(self, merge_multi_context=True, begin=0, end=None): """Get outputs of the previous forward computation. If begin or end is specified, return [begin, end)-th outputs, otherwise return all outputs. Parameters ---------- merge_multi_context : bool ...
[ "def", "get_outputs", "(", "self", ",", "merge_multi_context", "=", "True", ",", "begin", "=", "0", ",", "end", "=", "None", ")", ":", "if", "end", "is", "None", ":", "end", "=", "self", ".", "num_outputs", "outputs", "=", "[", "[", "exec_", ".", "...
42.3
22.433333
def iter_item_handles(self): """Return iterator over item handles.""" for abspath in self._ls_abspaths_with_cache(self._data_abspath): try: relpath = self._get_metadata_with_cache(abspath, "handle") yield relpath except IrodsNoMetaDataSetError: ...
[ "def", "iter_item_handles", "(", "self", ")", ":", "for", "abspath", "in", "self", ".", "_ls_abspaths_with_cache", "(", "self", ".", "_data_abspath", ")", ":", "try", ":", "relpath", "=", "self", ".", "_get_metadata_with_cache", "(", "abspath", ",", "\"handle\...
41.25
17
def webcam_detach(self, path): """Detaches the emulated USB webcam from the VM in path of type str The host path of the capture device to detach. """ if not isinstance(path, basestring): raise TypeError("path can only be an instance of type basestring") ...
[ "def", "webcam_detach", "(", "self", ",", "path", ")", ":", "if", "not", "isinstance", "(", "path", ",", "basestring", ")", ":", "raise", "TypeError", "(", "\"path can only be an instance of type basestring\"", ")", "self", ".", "_call", "(", "\"webcamDetach\"", ...
33.636364
16
def clear_knowledge_category(self): """Clears the knowledge category. raise: NoAccess - ``Metadata.isRequired()`` or ``Metadata.isReadOnly()`` is ``true`` *compliance: mandatory -- This method must be implemented.* """ # Implemented from template for osid.resou...
[ "def", "clear_knowledge_category", "(", "self", ")", ":", "# Implemented from template for osid.resource.ResourceForm.clear_avatar_template", "if", "(", "self", ".", "get_knowledge_category_metadata", "(", ")", ".", "is_read_only", "(", ")", "or", "self", ".", "get_knowledg...
46.230769
22.230769
def format(self, record): """ Calls the standard formatter, but will indent all of the log messages by our current indentation level. """ formatted = logging.Formatter.format(self, record) formatted = "".join([ (" " * get_indentation()) + line for ...
[ "def", "format", "(", "self", ",", "record", ")", ":", "formatted", "=", "logging", ".", "Formatter", ".", "format", "(", "self", ",", "record", ")", "formatted", "=", "\"\"", ".", "join", "(", "[", "(", "\" \"", "*", "get_indentation", "(", ")", ")"...
34.545455
12.909091
def get_subnets_count(context, filters=None): """Return the number of subnets. The result depends on the identity of the user making the request (as indicated by the context) as well as any filters. : param context: neutron api request context : param filters: a dictionary with keys that are valid ...
[ "def", "get_subnets_count", "(", "context", ",", "filters", "=", "None", ")", ":", "LOG", ".", "info", "(", "\"get_subnets_count for tenant %s with filters %s\"", "%", "(", "context", ".", "tenant_id", ",", "filters", ")", ")", "return", "db_api", ".", "subnet_c...
47.35
20.7
def _is_cp_helper(self, choi, atol, rtol): """Test if a channel is completely-positive (CP)""" if atol is None: atol = self._atol if rtol is None: rtol = self._rtol return is_positive_semidefinite_matrix(choi, rtol=rtol, atol=atol)
[ "def", "_is_cp_helper", "(", "self", ",", "choi", ",", "atol", ",", "rtol", ")", ":", "if", "atol", "is", "None", ":", "atol", "=", "self", ".", "_atol", "if", "rtol", "is", "None", ":", "rtol", "=", "self", ".", "_rtol", "return", "is_positive_semid...
40.142857
12.857143
def clean(): """Clear out any old screenshots""" screenshot_dir = settings.SELENIUM_SCREENSHOT_DIR if screenshot_dir and os.path.isdir(screenshot_dir): rmtree(screenshot_dir, ignore_errors=True)
[ "def", "clean", "(", ")", ":", "screenshot_dir", "=", "settings", ".", "SELENIUM_SCREENSHOT_DIR", "if", "screenshot_dir", "and", "os", ".", "path", ".", "isdir", "(", "screenshot_dir", ")", ":", "rmtree", "(", "screenshot_dir", ",", "ignore_errors", "=", "True...
45.2
15.8
def make_user_agent(component=None): """ create string suitable for HTTP User-Agent header """ packageinfo = pkg_resources.require("harvestingkit")[0] useragent = "{0}/{1}".format(packageinfo.project_name, packageinfo.version) if component is not None: useragent += " {0}".format(component) r...
[ "def", "make_user_agent", "(", "component", "=", "None", ")", ":", "packageinfo", "=", "pkg_resources", ".", "require", "(", "\"harvestingkit\"", ")", "[", "0", "]", "useragent", "=", "\"{0}/{1}\"", ".", "format", "(", "packageinfo", ".", "project_name", ",", ...
47
14
def copy_dir(self, path): """ Recursively copy directory """ for directory in path: if os.path.isdir(path): full_path = os.path.join(self.archive_dir, directory.lstrip('/')) logger.debug("Copying %s to %s", directory, full_path) ...
[ "def", "copy_dir", "(", "self", ",", "path", ")", ":", "for", "directory", "in", "path", ":", "if", "os", ".", "path", ".", "isdir", "(", "path", ")", ":", "full_path", "=", "os", ".", "path", ".", "join", "(", "self", ".", "archive_dir", ",", "d...
37.333333
15.5
def eval(self, cmd): """Evaluate a given command. The command is parsed and the output returned as a list of lines (strings). Raises a SCOCmdSyntaxError in case the command cannot be parsed. Parameters ---------- cmd : strings Command string Returns...
[ "def", "eval", "(", "self", ",", "cmd", ")", ":", "tokens", "=", "cmd", ".", "upper", "(", ")", ".", "split", "(", ")", "if", "len", "(", "tokens", ")", "==", "2", "and", "tokens", "[", "0", "]", "==", "'LIST'", ":", "if", "tokens", "[", "1",...
36.466667
19.2
def get_learning_curves(self, lc_extractor=extract_HBS_learning_curves, config_ids=None): """ extracts all learning curves from all run configurations Parameters ---------- lc_extractor: callable a function to return a list of learning_curves. defaults to hpbanster.HB_result.extract_HP_learning_curv...
[ "def", "get_learning_curves", "(", "self", ",", "lc_extractor", "=", "extract_HBS_learning_curves", ",", "config_ids", "=", "None", ")", ":", "config_ids", "=", "self", ".", "data", ".", "keys", "(", ")", "if", "config_ids", "is", "None", "else", "config_ids",...
25.357143
22.785714
def apply(self, X, ntree_limit=0): """Return the predicted leaf every tree for each sample. Parameters ---------- X : array_like, shape=[n_samples, n_features] Input features matrix. ntree_limit : int Limit number of trees in the prediction; defaults to ...
[ "def", "apply", "(", "self", ",", "X", ",", "ntree_limit", "=", "0", ")", ":", "test_dmatrix", "=", "DMatrix", "(", "X", ",", "missing", "=", "self", ".", "missing", ",", "nthread", "=", "self", ".", "n_jobs", ")", "return", "self", ".", "get_booster...
40.818182
22.954545
def get_base_url(self, force_http=False): """ Creates base URL path :param force_http: `True` if HTTP base URL should be used and `False` otherwise :type force_http: str :return: base url string :rtype: str """ base_url = SHConfig().aws_metadata_url.rstrip('/') i...
[ "def", "get_base_url", "(", "self", ",", "force_http", "=", "False", ")", ":", "base_url", "=", "SHConfig", "(", ")", ".", "aws_metadata_url", ".", "rstrip", "(", "'/'", ")", "if", "force_http", "else", "'s3:/'", "aws_bucket", "=", "SHConfig", "(", ")", ...
40.923077
22.153846
def delete_hit(self, hitid): ''' Delete HIT ''' if not self.connect_to_turk(): return False try: self.mtc.delete_hit(HITId=hitid) except Exception, e: print "Failed to delete of HIT %s. Make sure there are no "\ "assignments remaining t...
[ "def", "delete_hit", "(", "self", ",", "hitid", ")", ":", "if", "not", "self", ".", "connect_to_turk", "(", ")", ":", "return", "False", "try", ":", "self", ".", "mtc", ".", "delete_hit", "(", "HITId", "=", "hitid", ")", "except", "Exception", ",", "...
37.222222
15.888889
def fits_region_objects_to_table(regions): """ Converts list of regions to FITS region table. Parameters ---------- regions : list List of `regions.Region` objects Returns ------- region_string : `~astropy.table.Table` FITS region table Examples -------- >...
[ "def", "fits_region_objects_to_table", "(", "regions", ")", ":", "for", "reg", "in", "regions", ":", "if", "isinstance", "(", "reg", ",", "SkyRegion", ")", ":", "raise", "TypeError", "(", "'Every region must be a pixel region'", ".", "format", "(", "reg", ")", ...
27.757576
19.69697
def _generate_range_queries(self, fieldnames, operator_value_pairs): """Generates ElasticSearch range queries. Args: fieldnames (list): The fieldnames on which the search is the range query is targeted on, operator_value_pairs (dict): Contains (range_operator, value) pairs. ...
[ "def", "_generate_range_queries", "(", "self", ",", "fieldnames", ",", "operator_value_pairs", ")", ":", "if", "ElasticSearchVisitor", ".", "KEYWORD_TO_ES_FIELDNAME", "[", "'date'", "]", "==", "fieldnames", ":", "range_queries", "=", "[", "]", "for", "fieldname", ...
47.854167
29.229167
def get_iterator_from_config(config: dict, data: dict): """Create iterator (from config) for specified data.""" iterator_config = config['dataset_iterator'] iterator: Union[DataLearningIterator, DataFittingIterator] = from_params(iterator_config, ...
[ "def", "get_iterator_from_config", "(", "config", ":", "dict", ",", "data", ":", "dict", ")", ":", "iterator_config", "=", "config", "[", "'dataset_iterator'", "]", "iterator", ":", "Union", "[", "DataLearningIterator", ",", "DataFittingIterator", "]", "=", "fro...
60.166667
24
def _compute_ratio(top, bot): """ Make a map that is the ratio of two maps """ data = np.where(bot.data > 0, top.data / bot.data, 0.) return HpxMap(data, top.hpx)
[ "def", "_compute_ratio", "(", "top", ",", "bot", ")", ":", "data", "=", "np", ".", "where", "(", "bot", ".", "data", ">", "0", ",", "top", ".", "data", "/", "bot", ".", "data", ",", "0.", ")", "return", "HpxMap", "(", "data", ",", "top", ".", ...
38
7.4
def parse_config(self): """ Parse the xml file with remote servers and discover resources on each found server. """ tree = ElementTree.parse(self.file_xml) root = tree.getroot() for server in root.findall('server'): destination = server.text name =...
[ "def", "parse_config", "(", "self", ")", ":", "tree", "=", "ElementTree", ".", "parse", "(", "self", ".", "file_xml", ")", "root", "=", "tree", ".", "getroot", "(", ")", "for", "server", "in", "root", ".", "findall", "(", "'server'", ")", ":", "desti...
38.2
10.8
def return_file_objects(connection, container, prefix='database'): """Given connecton and container find database dumps """ options = [] meta_data = objectstore.get_full_container_list( connection, container, prefix='database') env = ENV.upper() for o_info in meta_data: expec...
[ "def", "return_file_objects", "(", "connection", ",", "container", ",", "prefix", "=", "'database'", ")", ":", "options", "=", "[", "]", "meta_data", "=", "objectstore", ".", "get_full_container_list", "(", "connection", ",", "container", ",", "prefix", "=", "...
25.269231
21.846154
def normalizeGlyphNote(value): """ Normalizes Glyph Note. * **value** must be a :ref:`type-string`. * Returned value is an unencoded ``unicode`` string """ if not isinstance(value, basestring): raise TypeError("Note must be a string, not %s." % type(value).__name...
[ "def", "normalizeGlyphNote", "(", "value", ")", ":", "if", "not", "isinstance", "(", "value", ",", "basestring", ")", ":", "raise", "TypeError", "(", "\"Note must be a string, not %s.\"", "%", "type", "(", "value", ")", ".", "__name__", ")", "return", "unicode...
30.818182
11.181818
def delete_plat_operator(operator, auth, url): """ Function to set the password of an existing operator :param operator: str Name of the operator account :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url f...
[ "def", "delete_plat_operator", "(", "operator", ",", "auth", ",", "url", ")", ":", "oper_id", "=", "None", "plat_oper_list", "=", "get_plat_operator", "(", "auth", ",", "url", ")", "for", "i", "in", "plat_oper_list", ":", "if", "operator", "==", "i", "[", ...
31.941176
23
def load_csv(file, shape=None, normalize=False): """ Load CSV file. :param file: CSV file. :type file: file like object :param shape : data array is reshape to this shape. :type shape: tuple of int :return: numpy array """ value_list = [] if six.PY2: for row in csv.read...
[ "def", "load_csv", "(", "file", ",", "shape", "=", "None", ",", "normalize", "=", "False", ")", ":", "value_list", "=", "[", "]", "if", "six", ".", "PY2", ":", "for", "row", "in", "csv", ".", "reader", "(", "file", ")", ":", "value_list", ".", "a...
28.909091
16.909091
def readInstance(self, key, makeGlyphs=True, makeKerning=True, makeInfo=True): """ Read a single instance element. key: an (attribute, value) tuple used to find the requested instance. :: <instance familyname="SuperFamily" filename="OutputNameInstance1.ufo" location="location-...
[ "def", "readInstance", "(", "self", ",", "key", ",", "makeGlyphs", "=", "True", ",", "makeKerning", "=", "True", ",", "makeInfo", "=", "True", ")", ":", "attrib", ",", "value", "=", "key", "for", "instanceElement", "in", "self", ".", "root", ".", "find...
46.1875
35.4375
def list_of_objects_from_api(url): ''' API only serves 20 pages by default This fetches info on all of items and return them as a list Assumption: limit of API is not less than 20 ''' response = requests.get(url) content = json.loads(response.content) count = content["meta"]["total_cou...
[ "def", "list_of_objects_from_api", "(", "url", ")", ":", "response", "=", "requests", ".", "get", "(", "url", ")", "content", "=", "json", ".", "loads", "(", "response", ".", "content", ")", "count", "=", "content", "[", "\"meta\"", "]", "[", "\"total_co...
31.125
19.125
def set_error(self, code, msg, data=None): """ Set an error on this request, which will prevent request execution. Should only be called from "pre" hook methods. If called from a post hook, this operation will be ignored. :Parameters: code Integer error co...
[ "def", "set_error", "(", "self", ",", "code", ",", "msg", ",", "data", "=", "None", ")", ":", "self", ".", "error", "=", "err_response", "(", "self", ".", "request", "[", "\"id\"", "]", ",", "code", ",", "msg", ",", "data", ")" ]
38.4375
21.4375
def getPixmap(page, matrix = None, colorspace = csRGB, clip = None, alpha = True): """Create pixmap of page. Args: matrix: Matrix for transformation (default: Identity). colorspace: (str/Colorspace) rgb, rgb, gray - case ignored, default csRGB. clip: (irect-like) restr...
[ "def", "getPixmap", "(", "page", ",", "matrix", "=", "None", ",", "colorspace", "=", "csRGB", ",", "clip", "=", "None", ",", "alpha", "=", "True", ")", ":", "CheckParent", "(", "page", ")", "# determine required colorspace", "cs", "=", "colorspace", "if", ...
29.971429
17.342857
def docker(gandi, vm, args): """ Manage docker instance """ if not [basedir for basedir in os.getenv('PATH', '.:/usr/bin').split(':') if os.path.exists('%s/docker' % basedir)]: gandi.echo("""'docker' not found in $PATH, required for this command \ to work See https://docs.docker.com/...
[ "def", "docker", "(", "gandi", ",", "vm", ",", "args", ")", ":", "if", "not", "[", "basedir", "for", "basedir", "in", "os", ".", "getenv", "(", "'PATH'", ",", "'.:/usr/bin'", ")", ".", "split", "(", "':'", ")", "if", "os", ".", "path", ".", "exis...
30.46875
19.40625
def columns_by_index(self) -> Dict[str, List[Well]]: """ Accessor function used to navigate through a labware by column name. With indexing one can treat it as a typical python dictionary. To access row A for example, simply write: labware.columns_by_index()['1'] This wi...
[ "def", "columns_by_index", "(", "self", ")", "->", "Dict", "[", "str", ",", "List", "[", "Well", "]", "]", ":", "col_dict", "=", "self", ".", "_create_indexed_dictionary", "(", "group", "=", "2", ")", "return", "col_dict" ]
38.923077
18.923077
def update_payload(self, fields=None): """Reset ``errata_id`` from DB ID to ``errata_id``.""" payload = super(ContentViewFilterRule, self).update_payload(fields) if 'errata_id' in payload: if not hasattr(self.errata, 'errata_id'): self.errata = self.errata.read() ...
[ "def", "update_payload", "(", "self", ",", "fields", "=", "None", ")", ":", "payload", "=", "super", "(", "ContentViewFilterRule", ",", "self", ")", ".", "update_payload", "(", "fields", ")", "if", "'errata_id'", "in", "payload", ":", "if", "not", "hasattr...
48.5
12.25
def render_field(field): """ 渲染字段验证代码 :param field: :type field: django.forms.Field :return: """ field = field.field if isinstance(field, forms.BoundField) else field validators = {} def no_compare_validator(): return not ('lessThan' in validators or 'greaterThan' in valida...
[ "def", "render_field", "(", "field", ")", ":", "field", "=", "field", ".", "field", "if", "isinstance", "(", "field", ",", "forms", ".", "BoundField", ")", "else", "field", "validators", "=", "{", "}", "def", "no_compare_validator", "(", ")", ":", "retur...
42.983051
17.423729
def display_hook(prompt, session, context, matches, longest_match_len): # type: (str, ShellSession, BundleContext, List[str], int) -> None """ Displays the available services matches and the service details :param prompt: Shell prompt string :param session: Current shell session...
[ "def", "display_hook", "(", "prompt", ",", "session", ",", "context", ",", "matches", ",", "longest_match_len", ")", ":", "# type: (str, ShellSession, BundleContext, List[str], int) -> None", "# Prepare a line pattern for each match (-1 for the trailing space)", "match_pattern", "=...
43.645161
19.645161
def madmedianrule(a): """Outlier detection based on the MAD-median rule. Parameters ---------- a : array-like Input array. Returns ------- outliers: boolean (same shape as a) Boolean array indicating whether each sample is an outlier (True) or not (False). Refe...
[ "def", "madmedianrule", "(", "a", ")", ":", "from", "scipy", ".", "stats", "import", "chi2", "a", "=", "np", ".", "asarray", "(", "a", ")", "k", "=", "np", ".", "sqrt", "(", "chi2", ".", "ppf", "(", "0.975", ",", "1", ")", ")", "return", "(", ...
27.516129
20.903226
def get_patch_from_uid(self, uid): """ Returns the patch with given uid. :param uid: Patch uid. :type uid: unicode :return: Patch. :rtype: Patch """ for name, patch in self: if patch.uid == uid: return patch
[ "def", "get_patch_from_uid", "(", "self", ",", "uid", ")", ":", "for", "name", ",", "patch", "in", "self", ":", "if", "patch", ".", "uid", "==", "uid", ":", "return", "patch" ]
22.230769
13.461538
def window(iterable, size=2, cast=tuple): # type: (Iterable, int, Callable) -> Iterable """ Yields iterms by bunch of a given size, but rolling only one item in and out at a time when iterating. >>> list(window([1, 2, 3])) [(1, 2), (2, 3)] By default, this will cast the...
[ "def", "window", "(", "iterable", ",", "size", "=", "2", ",", "cast", "=", "tuple", ")", ":", "# type: (Iterable, int, Callable) -> Iterable", "iterable", "=", "iter", "(", "iterable", ")", "d", "=", "deque", "(", "itertools", ".", "islice", "(", "iterable",...
33.171429
21.4
def delete_pre_shared_key(self, endpoint_name, **kwargs): # noqa: E501 """Remove a pre-shared key. # noqa: E501 Remove a pre-shared key. **Example usage:** ``` curl -H \"authorization: Bearer ${API_TOKEN}\" -X DELETE https://api.us-east-1.mbedcloud.com/v2/device-shared-keys/my-endpoint-0001 ``` #...
[ "def", "delete_pre_shared_key", "(", "self", ",", "endpoint_name", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'asynchronous'", ")", ":", "return", "self", ...
62.333333
38.52381
def dpt_groups_pseudotime(adata, color_map=None, palette=None, show=None, save=None): """Plot groups and pseudotime.""" pl.figure() pl.subplot(211) timeseries_subplot(adata.obs['dpt_groups'].cat.codes, time=adata.obs['dpt_order'].values, color=np.asarray(ada...
[ "def", "dpt_groups_pseudotime", "(", "adata", ",", "color_map", "=", "None", ",", "palette", "=", "None", ",", "show", "=", "None", ",", "save", "=", "None", ")", ":", "pl", ".", "figure", "(", ")", "pl", ".", "subplot", "(", "211", ")", "timeseries_...
53.590909
20.181818
def ping(self): """ Notify the queue that this task is still active. """ if self.finished is not None: raise AlreadyFinished() with self._db_conn() as conn: success = conn.query(''' UPDATE %s SET last_contact=%%(now)s, ...
[ "def", "ping", "(", "self", ")", ":", "if", "self", ".", "finished", "is", "not", "None", ":", "raise", "AlreadyFinished", "(", ")", "with", "self", ".", "_db_conn", "(", ")", "as", "conn", ":", "success", "=", "conn", ".", "query", "(", "'''\n ...
35.478261
12.086957
def from_array(array): """ Deserialize a new VideoNote from a given dictionary. :return: new VideoNote instance. :rtype: VideoNote """ if array is None or not array: return None # end if assert_type_or_raise(array, dict, parameter_name="array"...
[ "def", "from_array", "(", "array", ")", ":", "if", "array", "is", "None", "or", "not", "array", ":", "return", "None", "# end if", "assert_type_or_raise", "(", "array", ",", "dict", ",", "parameter_name", "=", "\"array\"", ")", "data", "=", "{", "}", "da...
37.5
20.3
async def is_ready(self): """Check if the multi-environment has been fully initialized. This calls each slave environment managers' :py:meth:`is_ready` and checks if the multi-environment itself is ready by calling :py:meth:`~creamas.mp.MultiEnvironment.check_ready`. .. seealso...
[ "async", "def", "is_ready", "(", "self", ")", ":", "async", "def", "slave_task", "(", "addr", ",", "timeout", ")", ":", "try", ":", "r_manager", "=", "await", "self", ".", "env", ".", "connect", "(", "addr", ",", "timeout", "=", "timeout", ")", "read...
32.931034
19.344828
def cmd(self): """ The command below covers most cases, if you need someting more complex subclass this. """ cmd = ( [self.compiler_binary] + self.flags + ['-U'+x for x in self.undef] + ['-D'+x for x in self.define] + ['...
[ "def", "cmd", "(", "self", ")", ":", "cmd", "=", "(", "[", "self", ".", "compiler_binary", "]", "+", "self", ".", "flags", "+", "[", "'-U'", "+", "x", "for", "x", "in", "self", ".", "undef", "]", "+", "[", "'-D'", "+", "x", "for", "x", "in", ...
36.925926
13
def __ProcessHttpResponse(self, method_config, http_response, request): """Process the given http response.""" if http_response.status_code not in (http_client.OK, http_client.CREATED, http_client.NO_CONTENT): ...
[ "def", "__ProcessHttpResponse", "(", "self", ",", "method_config", ",", "http_response", ",", "request", ")", ":", "if", "http_response", ".", "status_code", "not", "in", "(", "http_client", ".", "OK", ",", "http_client", ".", "CREATED", ",", "http_client", "....
52.956522
22.782609
def reportSuspiciousClient(self, clientName: str, reason): """ Report suspicion on a client and add it to this node's blacklist. :param clientName: name of the client to report suspicion on :param reason: the reason for suspicion """ logger.warning("{} raised suspicion o...
[ "def", "reportSuspiciousClient", "(", "self", ",", "clientName", ":", "str", ",", "reason", ")", ":", "logger", ".", "warning", "(", "\"{} raised suspicion on client {} for {}\"", ".", "format", "(", "self", ",", "clientName", ",", "reason", ")", ")", "self", ...
42.9
16.7
def ensure_dir_exists(directory): "Creates local directories if they don't exist." if directory.startswith('gs://'): return if not os.path.exists(directory): dbg("Making dir {}".format(directory)) os.makedirs(directory, exist_ok=True)
[ "def", "ensure_dir_exists", "(", "directory", ")", ":", "if", "directory", ".", "startswith", "(", "'gs://'", ")", ":", "return", "if", "not", "os", ".", "path", ".", "exists", "(", "directory", ")", ":", "dbg", "(", "\"Making dir {}\"", ".", "format", "...
37.142857
8.285714
def ReadAPIAuditEntries(self, username=None, router_method_names=None, min_timestamp=None, max_timestamp=None, cursor=None): """Returns audit entries stored in the database.""" quer...
[ "def", "ReadAPIAuditEntries", "(", "self", ",", "username", "=", "None", ",", "router_method_names", "=", "None", ",", "min_timestamp", "=", "None", ",", "max_timestamp", "=", "None", ",", "cursor", "=", "None", ")", ":", "query", "=", "\"\"\"SELECT details, t...
31.106383
17.914894
def melt(self, plot=False): """ Find and merge groups of polygons in the surface that meet the following criteria: * Are coplanars. * Are contiguous. * The result is convex. This method is very useful at reducing the num...
[ "def", "melt", "(", "self", ",", "plot", "=", "False", ")", ":", "from", "pyny3d", ".", "utils", "import", "bool2index", "from", "scipy", ".", "spatial", "import", "ConvexHull", "# First, coplanarity\r", "## Normalize parametric equations\r", "para", "=", "[", "...
38.611111
15.416667
def request(self, method, url, access_token=None, **kwargs): """ 向微信服务器发送请求 :param method: 请求方法 :param url: 请求地址 :param access_token: access token 值, 如果初始化时传入 conf 会自动获取, 如果没有传入则请提供此值 :param kwargs: 附加数据 :return: 微信服务器响应的 JSON 数据 """ access_token =...
[ "def", "request", "(", "self", ",", "method", ",", "url", ",", "access_token", "=", "None", ",", "*", "*", "kwargs", ")", ":", "access_token", "=", "self", ".", "__conf", ".", "access_token", "if", "self", ".", "__conf", "is", "not", "None", "else", ...
32.692308
17.615385
def hold(name, seconds): ''' Wait for a given period of time, then fire a result of True, requiring this state allows for an action to be blocked for evaluation based on time USAGE: .. code-block:: yaml hold_on_a_moment: timer.hold: - seconds: 30 ''' ret ...
[ "def", "hold", "(", "name", ",", "seconds", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'result'", ":", "False", ",", "'comment'", ":", "''", ",", "'changes'", ":", "{", "}", "}", "start", "=", "time", ".", "time", "(", ")", "if", "...
26.259259
20.037037
def get_project_root(): """ Determine location of `tasks.py`.""" try: tasks_py = sys.modules['tasks'] except KeyError: return None else: return os.path.abspath(os.path.dirname(tasks_py.__file__))
[ "def", "get_project_root", "(", ")", ":", "try", ":", "tasks_py", "=", "sys", ".", "modules", "[", "'tasks'", "]", "except", "KeyError", ":", "return", "None", "else", ":", "return", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "di...
28.5
18.5
def index_to_loc(self, index): """Convert a 1D index location to the 2D location on the plotting grid """ sz = int(self.shape[0] * self.shape[1]) idxs = np.array([i for i in range(sz)], dtype=int).reshape(self.shape) args = np.argwhere(idxs == index) if len(args) < 1: ...
[ "def", "index_to_loc", "(", "self", ",", "index", ")", ":", "sz", "=", "int", "(", "self", ".", "shape", "[", "0", "]", "*", "self", ".", "shape", "[", "1", "]", ")", "idxs", "=", "np", ".", "array", "(", "[", "i", "for", "i", "in", "range", ...
43.666667
12.222222
def thread_exception(self, raised_exception): """ Callback for handling exception, that are raised inside :meth:`.WThreadTask.thread_started` :param raised_exception: raised exception :return: None """ print('Thread execution was stopped by the exception. Exception: %s' % str(raised_exception)) print('Trac...
[ "def", "thread_exception", "(", "self", ",", "raised_exception", ")", ":", "print", "(", "'Thread execution was stopped by the exception. Exception: %s'", "%", "str", "(", "raised_exception", ")", ")", "print", "(", "'Traceback:'", ")", "print", "(", "traceback", ".",...
39.111111
17.333333
def dispatch(self, *args, **kwargs): """This decorator sets this view to have restricted permissions.""" return super(StrainDelete, self).dispatch(*args, **kwargs)
[ "def", "dispatch", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "super", "(", "StrainDelete", ",", "self", ")", ".", "dispatch", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
59
10
def _ipopo_class_field_property(name, value, methods_prefix): # type: (str, Any, str) -> property """ Sets up an iPOPO field property, using Python property() capabilities :param name: The property name :param value: The property default value :param methods_prefix: The common prefix of the get...
[ "def", "_ipopo_class_field_property", "(", "name", ",", "value", ",", "methods_prefix", ")", ":", "# type: (str, Any, str) -> property", "# The property lock", "lock", "=", "threading", ".", "RLock", "(", ")", "# Prepare the methods names", "getter_name", "=", "\"{0}{1}\"...
31.612245
15.163265
def findarp(device=None, interface=None, mac=None, ip=None, display=_DEFAULT_DISPLAY): # pylint: disable=invalid-name ''' Search for entries in the ARP tables using the following mine functions: - net.arp Optional arguments: device Return i...
[ "def", "findarp", "(", "device", "=", "None", ",", "interface", "=", "None", ",", "mac", "=", "None", ",", "ip", "=", "None", ",", "display", "=", "_DEFAULT_DISPLAY", ")", ":", "# pylint: disable=invalid-name", "labels", "=", "{", "'device'", ":", "'Device...
32.375
27.284091
def find_experiment_export(app_id): """Attempt to find a zipped export of an experiment with the ID provided and return its path. Returns None if not found. Search order: 1. local "data" subdirectory 2. user S3 bucket 3. Dallinger S3 bucket """ # Check locally first cwd...
[ "def", "find_experiment_export", "(", "app_id", ")", ":", "# Check locally first", "cwd", "=", "os", ".", "getcwd", "(", ")", "data_filename", "=", "\"{}-data.zip\"", ".", "format", "(", "app_id", ")", "path_to_data", "=", "os", ".", "path", ".", "join", "("...
28.45
18.775
def mapToPixel(mX, mY, geoTransform): """Convert map coordinates to pixel coordinates based on geotransform Accepts float or NumPy arrays GDAL model used here - upper left corner of upper left pixel for mX, mY (and in GeoTransform) """ mX = np.asarray(mX) mY = np.asarray(mY) if geoTran...
[ "def", "mapToPixel", "(", "mX", ",", "mY", ",", "geoTransform", ")", ":", "mX", "=", "np", ".", "asarray", "(", "mX", ")", "mY", "=", "np", ".", "asarray", "(", "mY", ")", "if", "geoTransform", "[", "2", "]", "+", "geoTransform", "[", "4", "]", ...
37.1875
20.4375
def extendedboldqc(auth, label, scan_ids=None, project=None, aid=None): ''' Get ExtendedBOLDQC data as a sequence of dictionaries. Example: >>> import yaxil >>> import json >>> auth = yaxil.XnatAuth(url='...', username='...', password='...') >>> for eqc in yaxil.extendedbold...
[ "def", "extendedboldqc", "(", "auth", ",", "label", ",", "scan_ids", "=", "None", ",", "project", "=", "None", ",", "aid", "=", "None", ")", ":", "if", "not", "aid", ":", "aid", "=", "accession", "(", "auth", ",", "label", ",", "project", ")", "pat...
34.97561
18.146341
def table_create(self, remove_existing=False): """Creates all tables. """ for engine in self.engines(): tables = self._get_tables(engine, create_drop=True) logger.info('Create all tables for %s', engine) try: self.metadata.create_all(engine, ta...
[ "def", "table_create", "(", "self", ",", "remove_existing", "=", "False", ")", ":", "for", "engine", "in", "self", ".", "engines", "(", ")", ":", "tables", "=", "self", ".", "_get_tables", "(", "engine", ",", "create_drop", "=", "True", ")", "logger", ...
38.2
12.1
def populations_diff_coeff(particles, populations): """Diffusion coefficients of the two specified populations. """ D_counts = particles.diffusion_coeff_counts if len(D_counts) == 1: pop_sizes = [pop.stop - pop.start for pop in populations] assert D_counts[0][1] >= sum(pop_sizes) ...
[ "def", "populations_diff_coeff", "(", "particles", ",", "populations", ")", ":", "D_counts", "=", "particles", ".", "diffusion_coeff_counts", "if", "len", "(", "D_counts", ")", "==", "1", ":", "pop_sizes", "=", "[", "pop", ".", "stop", "-", "pop", ".", "st...
38.705882
14.588235
def _transport_interceptor(self, callback): """Takes a callback function and returns a function that takes headers and messages and places them on the main service queue.""" def add_item_to_queue(header, message): queue_item = ( Priority.TRANSPORT, ne...
[ "def", "_transport_interceptor", "(", "self", ",", "callback", ")", ":", "def", "add_item_to_queue", "(", "header", ",", "message", ")", ":", "queue_item", "=", "(", "Priority", ".", "TRANSPORT", ",", "next", "(", "self", ".", "_transport_interceptor_counter", ...
38.117647
15.294118
def set_last_position(self, last_position): """ Called from the manager, it is in charge of updating the last position of data commited by the writer, in order to have resume support """ if last_position is None: self.last_position = {} for partition in se...
[ "def", "set_last_position", "(", "self", ",", "last_position", ")", ":", "if", "last_position", "is", "None", ":", "self", ".", "last_position", "=", "{", "}", "for", "partition", "in", "self", ".", "partitions", ":", "self", ".", "last_position", "[", "pa...
46.133333
15.2
def _maybe_create_resources(logging_task: Task = None): """Use heuristics to decide to possibly create resources""" def log(*args): if logging_task: logging_task.log(*args) else: util.log(*args) def should_create_resources(): """Check if gateway, keypair, vpc exist.""" prefix = u.get...
[ "def", "_maybe_create_resources", "(", "logging_task", ":", "Task", "=", "None", ")", ":", "def", "log", "(", "*", "args", ")", ":", "if", "logging_task", ":", "logging_task", ".", "log", "(", "*", "args", ")", "else", ":", "util", ".", "log", "(", "...
31.827586
20.482759
def inverse_deriv(self, z): ''' Derivative of the inverse of the negative binomial transform Parameters ----------- z : array-like Usually the linear predictor for a GLM or GEE model Returns ------- g^(-1)'(z) : array The value of...
[ "def", "inverse_deriv", "(", "self", ",", "z", ")", ":", "t", "=", "np", ".", "exp", "(", "z", ")", "return", "t", "/", "(", "self", ".", "alpha", "*", "(", "1", "-", "t", ")", "**", "2", ")" ]
26.647059
23.117647
def buildDPList(self): """Builds list of data products.""" updated = False dps = [] itemlist = self.getItemDPList() # first remove all items marked for removal, in case their names clash with new or renamed items for item, dp in itemlist: item._policy = item._...
[ "def", "buildDPList", "(", "self", ")", ":", "updated", "=", "False", "dps", "=", "[", "]", "itemlist", "=", "self", ".", "getItemDPList", "(", ")", "# first remove all items marked for removal, in case their names clash with new or renamed items", "for", "item", ",", ...
41
14.40625
def scalar_term(self, st): """Return a _ScalarTermS or _ScalarTermU from a string, to perform text and HTML substitutions""" if isinstance(st, binary_type): return _ScalarTermS(st, self._jinja_sub) elif isinstance(st, text_type): return _ScalarTermU(st, self._jinja_sub) ...
[ "def", "scalar_term", "(", "self", ",", "st", ")", ":", "if", "isinstance", "(", "st", ",", "binary_type", ")", ":", "return", "_ScalarTermS", "(", "st", ",", "self", ".", "_jinja_sub", ")", "elif", "isinstance", "(", "st", ",", "text_type", ")", ":", ...
42.6
11.7
def download_bundle_view(self, request, pk): """A view that allows the user to download a certificate bundle in PEM format.""" return self._download_response(request, pk, bundle=True)
[ "def", "download_bundle_view", "(", "self", ",", "request", ",", "pk", ")", ":", "return", "self", ".", "_download_response", "(", "request", ",", "pk", ",", "bundle", "=", "True", ")" ]
49.25
17
def in_path(self, new_path, old_path=None): """Temporarily enters a path.""" self.path = new_path try: yield finally: self.path = old_path
[ "def", "in_path", "(", "self", ",", "new_path", ",", "old_path", "=", "None", ")", ":", "self", ".", "path", "=", "new_path", "try", ":", "yield", "finally", ":", "self", ".", "path", "=", "old_path" ]
26.857143
14
def prepare_c3(data: Union[List[Tuple[str, int]], Mapping[str, int]], y_axis_label: str = 'y', x_axis_label: str = 'x', ) -> str: """Prepares C3 JSON for making a bar chart from a Counter :param data: A dictionary of {str: int} to display as bar chart :param y_a...
[ "def", "prepare_c3", "(", "data", ":", "Union", "[", "List", "[", "Tuple", "[", "str", ",", "int", "]", "]", ",", "Mapping", "[", "str", ",", "int", "]", "]", ",", "y_axis_label", ":", "str", "=", "'y'", ",", "x_axis_label", ":", "str", "=", "'x'...
35.625
18.041667
async def on_ctcp_version(self, by, target, contents): """ Built-in CTCP version as some networks seem to require it. """ import pydle version = '{name} v{ver}'.format(name=pydle.__name__, ver=pydle.__version__) self.ctcp_reply(by, 'VERSION', version)
[ "async", "def", "on_ctcp_version", "(", "self", ",", "by", ",", "target", ",", "contents", ")", ":", "import", "pydle", "version", "=", "'{name} v{ver}'", ".", "format", "(", "name", "=", "pydle", ".", "__name__", ",", "ver", "=", "pydle", ".", "__versio...
46.5
20.833333
def get_sari_score(source_ids, prediction_ids, list_of_targets, max_gram_size=4, beta_for_deletion=0): """Compute the SARI score for a single prediction and one or more targets. Args: source_ids: a list / np.array of SentencePiece IDs prediction_ids: a list / np.array of SentencePiece ID...
[ "def", "get_sari_score", "(", "source_ids", ",", "prediction_ids", ",", "list_of_targets", ",", "max_gram_size", "=", "4", ",", "beta_for_deletion", "=", "0", ")", ":", "addition_scores", "=", "[", "]", "keep_scores", "=", "[", "]", "deletion_scores", "=", "["...
46.979167
19.333333
def standings(self): """Returns a DataFrame containing standings information.""" doc = self.get_sub_doc('standings') east_table = doc('table#divs_standings_E') east_df = pd.DataFrame(sportsref.utils.parse_table(east_table)) east_df.sort_values('wins', ascending=False, inplace=Tr...
[ "def", "standings", "(", "self", ")", ":", "doc", "=", "self", ".", "get_sub_doc", "(", "'standings'", ")", "east_table", "=", "doc", "(", "'table#divs_standings_E'", ")", "east_df", "=", "pd", ".", "DataFrame", "(", "sportsref", ".", "utils", ".", "parse_...
45.555556
22.925926
def _get_log(self, limit=None): """Read log entries into a list of dictionaries.""" self.ui.pushbuffer() commands.log(self.ui, self.repo, limit=limit, date=None, rev=None, user=None) res = self.ui.popbuffer().strip() logList = [] for logentry in res.split("\n\n"): ...
[ "def", "_get_log", "(", "self", ",", "limit", "=", "None", ")", ":", "self", ".", "ui", ".", "pushbuffer", "(", ")", "commands", ".", "log", "(", "self", ".", "ui", ",", "self", ".", "repo", ",", "limit", "=", "limit", ",", "date", "=", "None", ...
40.55
14.2
def unapply(self): """Reset the current configuration to the previous state.""" for key, value in self._old_config.items(): _config[key] = value
[ "def", "unapply", "(", "self", ")", ":", "for", "key", ",", "value", "in", "self", ".", "_old_config", ".", "items", "(", ")", ":", "_config", "[", "key", "]", "=", "value" ]
42.25
10.25
def itermerged(self): """Iterate over all headers, merging duplicate ones together.""" for key in self: val = self._container[key.lower()] yield val[0], ', '.join(val[1:])
[ "def", "itermerged", "(", "self", ")", ":", "for", "key", "in", "self", ":", "val", "=", "self", ".", "_container", "[", "key", ".", "lower", "(", ")", "]", "yield", "val", "[", "0", "]", ",", "', '", ".", "join", "(", "val", "[", "1", ":", "...
41.4
9
def _get_buffers(self, job_id: str) -> Dict[str, np.ndarray]: """ Return the decoded result buffers for particular job_id. :param job_id: Unique identifier for the job in question :return: Decoded buffers or throw an error """ buffers = self.client.call('get_buffers', jo...
[ "def", "_get_buffers", "(", "self", ",", "job_id", ":", "str", ")", "->", "Dict", "[", "str", ",", "np", ".", "ndarray", "]", ":", "buffers", "=", "self", ".", "client", ".", "call", "(", "'get_buffers'", ",", "job_id", ",", "wait", "=", "True", ")...
43.666667
19
def _get_manifest_list(self, image): """try to figure out manifest list""" if image in self.manifest_list_cache: return self.manifest_list_cache[image] manifest_list = get_manifest_list(image, image.registry, insecure=self.parent_registry_in...
[ "def", "_get_manifest_list", "(", "self", ",", "image", ")", ":", "if", "image", "in", "self", ".", "manifest_list_cache", ":", "return", "self", ".", "manifest_list_cache", "[", "image", "]", "manifest_list", "=", "get_manifest_list", "(", "image", ",", "imag...
52.125
26.03125
def hex_timestamp_to_datetime(hex_timestamp): """Converts hex timestamp to a datetime object. >>> hex_timestamp_to_datetime('558BBCF9') datetime.datetime(2015, 6, 25, 8, 34, 1) >>> hex_timestamp_to_datetime('0x558BBCF9') datetime.datetime(2015, 6, 25, 8, 34, 1) >>> datetime.fromtimestamp(0x558B...
[ "def", "hex_timestamp_to_datetime", "(", "hex_timestamp", ")", ":", "if", "not", "hex_timestamp", ".", "startswith", "(", "'0x'", ")", ":", "hex_timestamp", "=", "'0x{0}'", ".", "format", "(", "hex_timestamp", ")", "return", "datetime", ".", "fromtimestamp", "("...
37.214286
10.214286
def serialize(self): """Return string representation for VCF""" if self.mate_chrom is None: remote_tag = "." else: if self.within_main_assembly: mate_chrom = self.mate_chrom else: mate_chrom = "<{}>".format(self.mate_chrom) ...
[ "def", "serialize", "(", "self", ")", ":", "if", "self", ".", "mate_chrom", "is", "None", ":", "remote_tag", "=", "\".\"", "else", ":", "if", "self", ".", "within_main_assembly", ":", "mate_chrom", "=", "self", ".", "mate_chrom", "else", ":", "mate_chrom",...
39.466667
14.133333
def is_instance_avg_req_latency_too_high(self, inst_id): """ Return whether the average request latency of an instance is greater than the acceptable threshold """ avg_lat, avg_lat_others = self.getLatencies() if not avg_lat or not avg_lat_others: return False...
[ "def", "is_instance_avg_req_latency_too_high", "(", "self", ",", "inst_id", ")", ":", "avg_lat", ",", "avg_lat_others", "=", "self", ".", "getLatencies", "(", ")", "if", "not", "avg_lat", "or", "not", "avg_lat_others", ":", "return", "False", "d", "=", "avg_la...
40.714286
19.285714
def get_fact(state, host, name): ''' Wrapper around ``get_facts`` returning facts for one host or a function that does. ''' # Expecting a function to return if callable(getattr(FACTS[name], 'command', None)): def wrapper(*args): fact_data = get_facts(state, name, args=args, ...
[ "def", "get_fact", "(", "state", ",", "host", ",", "name", ")", ":", "# Expecting a function to return", "if", "callable", "(", "getattr", "(", "FACTS", "[", "name", "]", ",", "'command'", ",", "None", ")", ")", ":", "def", "wrapper", "(", "*", "args", ...
28.15
23.35
def print_preview(self): """Print preview for current file""" from qtpy.QtPrintSupport import QPrintPreviewDialog editor = self.get_current_editor() printer = Printer(mode=QPrinter.HighResolution, header_font=self.get_plugin_font('printer_header')) ...
[ "def", "print_preview", "(", "self", ")", ":", "from", "qtpy", ".", "QtPrintSupport", "import", "QPrintPreviewDialog", "editor", "=", "self", ".", "get_current_editor", "(", ")", "printer", "=", "Printer", "(", "mode", "=", "QPrinter", ".", "HighResolution", "...
44.923077
15.615385
def _update_params(self): """ update params from response data """ if self.data.get('title'): self.params['title'] = self.data.get('title') if self.data.get('pageid'): self.params['pageid'] = self.data.get('pageid') if self.data.get('wikibase'): ...
[ "def", "_update_params", "(", "self", ")", ":", "if", "self", ".", "data", ".", "get", "(", "'title'", ")", ":", "self", ".", "params", "[", "'title'", "]", "=", "self", ".", "data", ".", "get", "(", "'title'", ")", "if", "self", ".", "data", "."...
37.2
8.8
def check_csrf_token(): """Checks that token is correct, aborting if not""" if request.method in ("GET",): # not exhaustive list return token = request.form.get("csrf_token") if token is None: app.logger.warning("Expected CSRF Token: not present") abort(400) if not safe_str_c...
[ "def", "check_csrf_token", "(", ")", ":", "if", "request", ".", "method", "in", "(", "\"GET\"", ",", ")", ":", "# not exhaustive list", "return", "token", "=", "request", ".", "form", ".", "get", "(", "\"csrf_token\"", ")", "if", "token", "is", "None", "...
36.727273
14.636364
def bandpass(self, flow, fhigh, gpass=2, gstop=30, fstop=None, type='iir', filtfilt=True, **kwargs): """Filter this `TimeSeries` with a band-pass filter. Parameters ---------- flow : `float` lower corner frequency of pass band fhigh : `float` ...
[ "def", "bandpass", "(", "self", ",", "flow", ",", "fhigh", ",", "gpass", "=", "2", ",", "gstop", "=", "30", ",", "fstop", "=", "None", ",", "type", "=", "'iir'", ",", "filtfilt", "=", "True", ",", "*", "*", "kwargs", ")", ":", "# design filter", ...
32.173077
22.230769
def id_to_did(did_id, method='op'): """Return an Ocean DID from given a hex id.""" if isinstance(did_id, bytes): did_id = Web3.toHex(did_id) # remove leading '0x' of a hex string if isinstance(did_id, str): did_id = remove_0x_prefix(did_id) else: raise TypeError("did id must...
[ "def", "id_to_did", "(", "did_id", ",", "method", "=", "'op'", ")", ":", "if", "isinstance", "(", "did_id", ",", "bytes", ")", ":", "did_id", "=", "Web3", ".", "toHex", "(", "did_id", ")", "# remove leading '0x' of a hex string", "if", "isinstance", "(", "...
30.8
13.466667
def ip_addrs(interface=None, include_loopback=False, cidr=None, type=None): ''' Returns a list of IPv4 addresses assigned to the host. interface Only IP addresses from that interface will be returned. include_loopback : False Include loopback 127.0.0.1 IPv4 address. cidr D...
[ "def", "ip_addrs", "(", "interface", "=", "None", ",", "include_loopback", "=", "False", ",", "cidr", "=", "None", ",", "type", "=", "None", ")", ":", "addrs", "=", "salt", ".", "utils", ".", "network", ".", "ip_addrs", "(", "interface", "=", "interfac...
30.195122
25.365854
def get_record(self, record_num): """ Get a Record by record number. @type record_num: int @param record_num: The record number of the the record to fetch. @rtype Record or None @return The record request by record number, or None if the record is not found. ...
[ "def", "get_record", "(", "self", ",", "record_num", ")", ":", "for", "chunk", "in", "self", ".", "chunks", "(", ")", ":", "first_record", "=", "chunk", ".", "log_first_record_number", "(", ")", "last_record", "=", "chunk", ".", "log_last_record_number", "("...
37.052632
13.684211
def parse_date(my_date): """Parse a date into canonical format of datetime.dateime. :param my_date: Either datetime.datetime or string in '%Y-%m-%dT%H:%M:%SZ' format. ~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~- :return: A datetime.datetime. ...
[ "def", "parse_date", "(", "my_date", ")", ":", "if", "isinstance", "(", "my_date", ",", "datetime", ".", "datetime", ")", ":", "result", "=", "my_date", "elif", "isinstance", "(", "my_date", ",", "str", ")", ":", "result", "=", "datetime", ".", "datetime...
35.68
22.92
def rank_all(self,roots,optimize=False): """Computes rank of all vertices. add provided roots to rank 0 vertices, otherwise update ranking from provided roots. The initial rank is based on precedence relationships, optimal ranking may be derived from network flow (simplex). ...
[ "def", "rank_all", "(", "self", ",", "roots", ",", "optimize", "=", "False", ")", ":", "self", ".", "_edge_inverter", "(", ")", "r", "=", "[", "x", "for", "x", "in", "self", ".", "g", ".", "sV", "if", "(", "len", "(", "x", ".", "e_in", "(", "...
43.916667
11.25
def add_class(self, cssclass): """Adds a css class to this element.""" if self.has_class(cssclass): return self return self.toggle_class(cssclass)
[ "def", "add_class", "(", "self", ",", "cssclass", ")", ":", "if", "self", ".", "has_class", "(", "cssclass", ")", ":", "return", "self", "return", "self", ".", "toggle_class", "(", "cssclass", ")" ]
35.6
6.6
def aggregate(self, aggregates=None, drilldowns=None, cuts=None, order=None, page=None, page_size=None, page_max=None): """Main aggregation function. This is used to compute a given set of aggregates, grouped by a given set of drilldown dimensions (i.e. dividers). The query can...
[ "def", "aggregate", "(", "self", ",", "aggregates", "=", "None", ",", "drilldowns", "=", "None", ",", "cuts", "=", "None", ",", "order", "=", "None", ",", "page", "=", "None", ",", "page_size", "=", "None", ",", "page_max", "=", "None", ")", ":", "...
36.275862
19.672414
def register_ipcluster(data): """ The name is a unique id that keeps this __init__ of ipyrad distinct from interfering with other ipcontrollers. Run statements are wrapped so that ipcluster will be killed on exit. """ ## check if this pid already has a running cluster data._ipcluster["cluste...
[ "def", "register_ipcluster", "(", "data", ")", ":", "## check if this pid already has a running cluster", "data", ".", "_ipcluster", "[", "\"cluster_id\"", "]", "=", "\"ipyrad-cli-\"", "+", "str", "(", "os", ".", "getpid", "(", ")", ")", "start_ipcluster", "(", "d...
39.2
16
def toPandas(self): """ Returns the contents of this :class:`DataFrame` as Pandas ``pandas.DataFrame``. This is only available if Pandas is installed and available. .. note:: This method should only be used if the resulting Pandas's DataFrame is expected to be small, as all...
[ "def", "toPandas", "(", "self", ")", ":", "from", "pyspark", ".", "sql", ".", "utils", "import", "require_minimum_pandas_version", "require_minimum_pandas_version", "(", ")", "import", "pandas", "as", "pd", "if", "self", ".", "sql_ctx", ".", "_conf", ".", "pan...
48.580357
26.991071
def _plugin_name(self, path): "Returns the plugin module name given the path" base = os.path.basename(path) name, ext = os.path.splitext(base) return name
[ "def", "_plugin_name", "(", "self", ",", "path", ")", ":", "base", "=", "os", ".", "path", ".", "basename", "(", "path", ")", "name", ",", "ext", "=", "os", ".", "path", ".", "splitext", "(", "base", ")", "return", "name" ]
36.4
10.4
def lookup_prefix(self, prefix, timestamp=timestamp_now): """ Returns lookup data of a Prefix Args: prefix (string): Prefix of a Amateur Radio callsign timestamp (datetime, optional): datetime in UTC (tzinfo=pytz.UTC) Returns: dict: Dictionary contai...
[ "def", "lookup_prefix", "(", "self", ",", "prefix", ",", "timestamp", "=", "timestamp_now", ")", ":", "prefix", "=", "prefix", ".", "strip", "(", ")", ".", "upper", "(", ")", "if", "self", ".", "_lookuptype", "==", "\"clublogxml\"", "or", "self", ".", ...
30.722222
25.574074
def iter_python_modules(tile): """Iterate over all python products in the given tile. This will yield tuples where the first entry is the path to the module containing the product the second entry is the appropriate import string to include in an entry point, and the third entry is the entry point ...
[ "def", "iter_python_modules", "(", "tile", ")", ":", "for", "product_type", "in", "tile", ".", "PYTHON_PRODUCTS", ":", "for", "product", "in", "tile", ".", "find_products", "(", "product_type", ")", ":", "entry_point", "=", "ENTRY_POINT_MAP", ".", "get", "(", ...
39.885714
23.4
def fcontext_policy_absent(name, filetype='a', sel_type=None, sel_user=None, sel_level=None): ''' .. versionadded:: 2017.7.0 Makes sure an SELinux file context policy for a given filespec (name), filetype and SELinux context type is absent. name filespec of the file or directory. Regex syn...
[ "def", "fcontext_policy_absent", "(", "name", ",", "filetype", "=", "'a'", ",", "sel_type", "=", "None", ",", "sel_user", "=", "None", ",", "sel_level", "=", "None", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'result'", ":", "False", ",", ...
34.122807
22.649123
def _add_header(self): """Add email header info.""" self.message["From"] = self.from_ self.message["Subject"] = self.subject if self.to: self.message["To"] = self.list_to_string(self.to) if self.cc: self.message["Cc"] = self.list_to_string(self.cc) ...
[ "def", "_add_header", "(", "self", ")", ":", "self", ".", "message", "[", "\"From\"", "]", "=", "self", ".", "from_", "self", ".", "message", "[", "\"Subject\"", "]", "=", "self", ".", "subject", "if", "self", ".", "to", ":", "self", ".", "message", ...
38.8
15.2
def doprinc(data): """ Gets principal components from data in form of a list of [dec,inc] data. Parameters ---------- data : nested list of dec, inc directions Returns ------- ppars : dictionary with the principal components dec : principal directiion declination inc : ...
[ "def", "doprinc", "(", "data", ")", ":", "ppars", "=", "{", "}", "rad", "=", "old_div", "(", "np", ".", "pi", ",", "180.", ")", "X", "=", "dir2cart", "(", "data", ")", "# for rec in data:", "# dir=[]", "# for c in rec: dir.append(c)", "# cart= (dir2...
27.035714
16.428571