text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def header_echo(cls, request, api_key: (Ptypes.header, String('API key'))) -> [ (200, 'Ok', String)]: '''Echo the header parameter.''' log.info('Echoing header param, value is: {}'.format(api_key)) for i in range(randint(0, MAX_LOOP_DURATION)): yield ...
[ "def", "header_echo", "(", "cls", ",", "request", ",", "api_key", ":", "(", "Ptypes", ".", "header", ",", "String", "(", "'API key'", ")", ")", ")", "->", "[", "(", "200", ",", "'Ok'", ",", "String", ")", "]", ":", "log", ".", "info", "(", "'Echo...
43.444444
15.888889
def determine_context(device_ids: List[int], use_cpu: bool, disable_device_locking: bool, lock_dir: str, exit_stack: ExitStack) -> List[mx.Context]: """ Determine the MXNet context to run on (CPU or GPU). :param device_...
[ "def", "determine_context", "(", "device_ids", ":", "List", "[", "int", "]", ",", "use_cpu", ":", "bool", ",", "disable_device_locking", ":", "bool", ",", "lock_dir", ":", "str", ",", "exit_stack", ":", "ExitStack", ")", "->", "List", "[", "mx", ".", "Co...
42.37037
18.148148
def persistent_load(self, pid): """ Reconstruct a GLC object using the persistent ID. This method should not be used externally. It is required by the unpickler super class. Parameters ---------- pid : The persistent ID used in pickle file to save the GLC object. ...
[ "def", "persistent_load", "(", "self", ",", "pid", ")", ":", "if", "len", "(", "pid", ")", "==", "2", ":", "# Pre GLC-1.3 release behavior, without memorization", "type_tag", ",", "filename", "=", "pid", "abs_path", "=", "_os", ".", "path", ".", "join", "(",...
38.551724
22.62069
def show(self, n=10, headers=(), tablefmt="simple", floatfmt="g", numalign="decimal", stralign="left", missingval=""): """ Pretty print first n rows of sequence as a table. See https://bitbucket.org/astanin/python-tabulate for details on tabulate parameters :param n: Number...
[ "def", "show", "(", "self", ",", "n", "=", "10", ",", "headers", "=", "(", ")", ",", "tablefmt", "=", "\"simple\"", ",", "floatfmt", "=", "\"g\"", ",", "numalign", "=", "\"decimal\"", ",", "stralign", "=", "\"left\"", ",", "missingval", "=", "\"\"", ...
47.777778
16.777778
def resample_from_array( in_raster=None, in_affine=None, out_tile=None, in_crs=None, resampling="nearest", nodataval=0 ): """ Extract and resample from array to target tile. Parameters ---------- in_raster : array in_affine : ``Affine`` out_tile : ``BufferedTile`` ...
[ "def", "resample_from_array", "(", "in_raster", "=", "None", ",", "in_affine", "=", "None", ",", "out_tile", "=", "None", ",", "in_crs", "=", "None", ",", "resampling", "=", "\"nearest\"", ",", "nodataval", "=", "0", ")", ":", "# TODO rename function", "if",...
30.271429
17.014286
def filter_(*permissions, **kwargs): """ Constructs a clause to filter all bearers or targets for a given berarer or target. """ bearer = kwargs['bearer'] target = kwargs.get('target') bearer_cls = type_for(bearer) # We need a query object. There are many ways to get one, Either we ca...
[ "def", "filter_", "(", "*", "permissions", ",", "*", "*", "kwargs", ")", ":", "bearer", "=", "kwargs", "[", "'bearer'", "]", "target", "=", "kwargs", ".", "get", "(", "'target'", ")", "bearer_cls", "=", "type_for", "(", "bearer", ")", "# We need a query ...
33.319149
21.06383
def draw_image(image, x1, y1, x2 = None, y2 = None): '''Draw an image. The image's top-left corner is drawn at ``(x1, y1)``, and its lower-left at ``(x2, y2)``. If ``x2`` and ``y2`` are omitted, they are calculated to render the image at its native resoultion. Note that images can be flipped and scal...
[ "def", "draw_image", "(", "image", ",", "x1", ",", "y1", ",", "x2", "=", "None", ",", "y2", "=", "None", ")", ":", "if", "x2", "is", "None", ":", "x2", "=", "x1", "+", "image", ".", "width", "if", "y2", "is", "None", ":", "y2", "=", "y1", "...
37.6
29.2
def files(self): """ Yield relative file paths specified in :attr:`metainfo` Each paths starts with :attr:`name`. Note that the paths may not exist. See :attr:`filepaths` for existing files. """ info = self.metainfo['info'] if 'length' in info: # Sing...
[ "def", "files", "(", "self", ")", ":", "info", "=", "self", ".", "metainfo", "[", "'info'", "]", "if", "'length'", "in", "info", ":", "# Singlefile", "yield", "info", "[", "'name'", "]", "elif", "'files'", "in", "info", ":", "# Multifile torrent", "rootd...
34.125
16.875
def remove_terms(self, terms, ignore_absences=False): '''Non destructive term removal. Parameters ---------- terms : list list of terms to remove ignore_absences : bool, False by default if term does not appear, don't raise an error, just move on. ...
[ "def", "remove_terms", "(", "self", ",", "terms", ",", "ignore_absences", "=", "False", ")", ":", "idx_to_delete_list", "=", "self", ".", "_build_term_index_list", "(", "ignore_absences", ",", "terms", ")", "return", "self", ".", "remove_terms_by_indices", "(", ...
33.8125
22.3125
def make_bindings_type(filenames,color_input,colorkey,file_dictionary,sidebar,bounds): # instantiating string the main string block for the javascript block of html code string = '' ''' # logic for instantiating variable colorkey input if not colorkeyfields == False: colorkey = 'selectedText' ''' # iteratin...
[ "def", "make_bindings_type", "(", "filenames", ",", "color_input", ",", "colorkey", ",", "file_dictionary", ",", "sidebar", ",", "bounds", ")", ":", "# instantiating string the main string block for the javascript block of html code", "string", "=", "''", "# iterating through...
31.538462
21.650888
def connect(host=DEFAULT_HOST, port=DEFAULT_PORT, base=DEFAULT_BASE, chunk_size=multipart.default_chunk_size, **defaults): """Create a new :class:`~ipfsapi.Client` instance and connect to the daemon to validate that its version is supported. Raises ------ ~ipfsapi.exceptions.VersionMism...
[ "def", "connect", "(", "host", "=", "DEFAULT_HOST", ",", "port", "=", "DEFAULT_PORT", ",", "base", "=", "DEFAULT_BASE", ",", "chunk_size", "=", "multipart", ".", "default_chunk_size", ",", "*", "*", "defaults", ")", ":", "# Create client instance", "client", "...
29.965517
19.793103
def image(random=random, width=800, height=600, https=False, *args, **kwargs): """ Generate the address of a placeholder image. >>> mock_random.seed(0) >>> image(random=mock_random) 'http://dummyimage.com/800x600/292929/e3e3e3&text=mighty poop' >>> image(random=mock_random, width=60, height=60)...
[ "def", "image", "(", "random", "=", "random", ",", "width", "=", "800", ",", "height", "=", "600", ",", "https", "=", "False", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "target_fn", "=", "noun", "if", "width", "+", "height", ">", "300"...
35.911765
24.852941
def create(domain_name, years, **kwargs): ''' Try to register the specified domain name domain_name The domain name to be registered years Number of years to register Returns the following information: - Whether or not the domain was renewed successfully - Whether or not ...
[ "def", "create", "(", "domain_name", ",", "years", ",", "*", "*", "kwargs", ")", ":", "idn_codes", "=", "(", "'afr'", ",", "'alb'", ",", "'ara'", ",", "'arg'", ",", "'arm'", ",", "'asm'", ",", "'ast'", ",", "'ave'", ",", "'awa'", ",", "'aze'", ",",...
46.942529
32.689655
def _jgezerou8(ins): """ Jumps if top of the stack (8bit) is >= 0 to arg(1) Always TRUE for unsigned """ output = [] value = ins.quad[1] if not is_int(value): output = _8bit_oper(value) output.append('jp %s' % str(ins.quad[2])) return output
[ "def", "_jgezerou8", "(", "ins", ")", ":", "output", "=", "[", "]", "value", "=", "ins", ".", "quad", "[", "1", "]", "if", "not", "is_int", "(", "value", ")", ":", "output", "=", "_8bit_oper", "(", "value", ")", "output", ".", "append", "(", "'jp...
25.090909
14.454545
def convert_magicc6_to_magicc7_variables(variables, inverse=False): """ Convert MAGICC6 variables to MAGICC7 variables Parameters ---------- variables : list_like, str Variables to convert inverse : bool If True, convert the other way i.e. convert MAGICC7 variables to MAGICC6 ...
[ "def", "convert_magicc6_to_magicc7_variables", "(", "variables", ",", "inverse", "=", "False", ")", ":", "if", "isinstance", "(", "variables", ",", "(", "list", ",", "pd", ".", "Index", ")", ")", ":", "return", "[", "_apply_convert_magicc6_to_magicc7_variables", ...
32.878788
27.121212
def update_links(self, request, admin_site=None): """ Called to update the widget's urls. Tries to find the bundle for the model that this foreign key points to and then asks it for the urls for adding and listing and sets them on this widget instance. The urls are only set if re...
[ "def", "update_links", "(", "self", ",", "request", ",", "admin_site", "=", "None", ")", ":", "if", "admin_site", ":", "bundle", "=", "admin_site", ".", "get_bundle_for_model", "(", "self", ".", "model", ".", "to", ")", "if", "bundle", ":", "self", ".", ...
49.190476
23.380952
async def redirect_async(self, redirect, auth): """Redirect the client endpoint using a Link DETACH redirect response. :param redirect: The Link DETACH redirect details. :type redirect: ~uamqp.errors.LinkRedirect :param auth: Authentication credentials to the redirected endpoint...
[ "async", "def", "redirect_async", "(", "self", ",", "redirect", ",", "auth", ")", ":", "if", "self", ".", "_ext_connection", ":", "raise", "ValueError", "(", "\"Clients with a shared connection cannot be \"", "\"automatically redirected.\"", ")", "if", "self", ".", ...
41.045455
13.909091
def confusion_matrix(predicted_essential, expected_essential, predicted_nonessential, expected_nonessential): """ Compute a representation of the confusion matrix. Parameters ---------- predicted_essential : set expected_essential : set predicted_nonessential : set ...
[ "def", "confusion_matrix", "(", "predicted_essential", ",", "expected_essential", ",", "predicted_nonessential", ",", "expected_nonessential", ")", ":", "true_positive", "=", "predicted_essential", "&", "expected_essential", "tp", "=", "len", "(", "true_positive", ")", ...
27.805556
18.888889
def _get_axial_shifts(ndim=2, include_diagonals=False): r''' Helper function to generate the axial shifts that will be performed on the image to identify bordering pixels/voxels ''' if ndim == 2: if include_diagonals: neighbors = square(3) else: neighbors = di...
[ "def", "_get_axial_shifts", "(", "ndim", "=", "2", ",", "include_diagonals", "=", "False", ")", ":", "if", "ndim", "==", "2", ":", "if", "include_diagonals", ":", "neighbors", "=", "square", "(", "3", ")", "else", ":", "neighbors", "=", "diamond", "(", ...
27.192308
17.269231
def optional(validator): """ A validator that makes an attribute optional. An optional attribute is one which can be set to ``None`` in addition to satisfying the requirements of the sub-validator. :param validator: A validator (or a list of validators) that is used for non-``None`` values...
[ "def", "optional", "(", "validator", ")", ":", "if", "isinstance", "(", "validator", ",", "list", ")", ":", "return", "_OptionalValidator", "(", "_AndValidator", "(", "validator", ")", ")", "return", "_OptionalValidator", "(", "validator", ")" ]
38.375
20.375
def get(self, request, *args, **kwargs): """ Method for handling GET requests. Calls the `render` method with the following items in context: * **queryset** - Objects to perform action on """ queryset = self.get_selected(request) return self.render(reque...
[ "def", "get", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "queryset", "=", "self", ".", "get_selected", "(", "request", ")", "return", "self", ".", "render", "(", "request", ",", "queryset", "=", "queryset", ")" ...
30.363636
12.909091
def _ExportEvents( self, storage_reader, output_module, deduplicate_events=True, event_filter=None, time_slice=None, use_time_slicer=False): """Exports events using an output module. Args: storage_reader (StorageReader): storage reader. output_module (OutputModule): output module. ...
[ "def", "_ExportEvents", "(", "self", ",", "storage_reader", ",", "output_module", ",", "deduplicate_events", "=", "True", ",", "event_filter", "=", "None", ",", "time_slice", "=", "None", ",", "use_time_slicer", "=", "False", ")", ":", "self", ".", "_status", ...
37.631068
21.223301
def parse_fields(self, response, fields_dict, net_start=None, net_end=None, dt_format=None, field_list=None): """ The function for parsing whois fields from a data input. Args: response (:obj:`str`): The response from the whois/rwhois server. fields_...
[ "def", "parse_fields", "(", "self", ",", "response", ",", "fields_dict", ",", "net_start", "=", "None", ",", "net_end", "=", "None", ",", "dt_format", "=", "None", ",", "field_list", "=", "None", ")", ":", "ret", "=", "{", "}", "if", "not", "field_list...
29.087719
24.736842
def _build_row(padded_cells, colwidths, colaligns, rowfmt): "Return a string which represents a row of data cells." if not rowfmt: return None if hasattr(rowfmt, "__call__"): return rowfmt(padded_cells, colwidths, colaligns) else: return _build_simple_row(padded_cells, rowfmt)
[ "def", "_build_row", "(", "padded_cells", ",", "colwidths", ",", "colaligns", ",", "rowfmt", ")", ":", "if", "not", "rowfmt", ":", "return", "None", "if", "hasattr", "(", "rowfmt", ",", "\"__call__\"", ")", ":", "return", "rowfmt", "(", "padded_cells", ","...
38.75
18.5
def _build_late_dispatcher(func_name): """Return a function that calls method 'func_name' on objects. This is useful for building late-bound dynamic dispatch. Arguments: func_name: The name of the instance method that should be called. Returns: A function that ...
[ "def", "_build_late_dispatcher", "(", "func_name", ")", ":", "def", "_late_dynamic_dispatcher", "(", "obj", ",", "*", "args", ")", ":", "method", "=", "getattr", "(", "obj", ",", "func_name", ",", "None", ")", "if", "not", "callable", "(", "method", ")", ...
37.958333
20.25
def scons_subst(strSubst, env, mode=SUBST_RAW, target=None, source=None, gvars={}, lvars={}, conv=None): """Expand a string or list containing construction variable substitutions. This is the work-horse function for substitutions in file names and the like. The companion scons_subst_list() function (b...
[ "def", "scons_subst", "(", "strSubst", ",", "env", ",", "mode", "=", "SUBST_RAW", ",", "target", "=", "None", ",", "source", "=", "None", ",", "gvars", "=", "{", "}", ",", "lvars", "=", "{", "}", ",", "conv", "=", "None", ")", ":", "if", "isinsta...
42.415459
18.072464
def powernodes_containing(self, name, directly=False) -> iter: """Yield all power nodes containing (power) node of given *name*. If *directly* is True, will only yield the direct parent of given name. """ if directly: yield from (node for node in self.all_in(name) ...
[ "def", "powernodes_containing", "(", "self", ",", "name", ",", "directly", "=", "False", ")", "->", "iter", ":", "if", "directly", ":", "yield", "from", "(", "node", "for", "node", "in", "self", ".", "all_in", "(", "name", ")", "if", "name", "in", "s...
43.92
18.48
def calculate_single_terms(self): """Apply all methods stored in the hidden attribute `PART_ODE_METHODS`. >>> from hydpy.models.test_v1 import * >>> parameterstep() >>> k(0.25) >>> states.s = 1.0 >>> model.calculate_single_terms() >>> fluxes.q q(0...
[ "def", "calculate_single_terms", "(", "self", ")", ":", "self", ".", "numvars", ".", "nmb_calls", "=", "self", ".", "numvars", ".", "nmb_calls", "+", "1", "for", "method", "in", "self", ".", "PART_ODE_METHODS", ":", "method", "(", "self", ")" ]
30
13.2
async def stop(self, **kwargs): """Stop pairing process.""" if not self._pin_code: raise Exception('no pin given') # TODO: new exception self.service.device_credentials = \ await self.pairing_procedure.finish_pairing(self._pin_code)
[ "async", "def", "stop", "(", "self", ",", "*", "*", "kwargs", ")", ":", "if", "not", "self", ".", "_pin_code", ":", "raise", "Exception", "(", "'no pin given'", ")", "# TODO: new exception", "self", ".", "service", ".", "device_credentials", "=", "await", ...
39.428571
17
def get_cassandra_connection(alias=None, name=None): """ :return: cassandra connection matching alias or name or just first found. """ for _alias, connection in get_cassandra_connections(): if alias is not None: if alias == _alias: return connection elif name...
[ "def", "get_cassandra_connection", "(", "alias", "=", "None", ",", "name", "=", "None", ")", ":", "for", "_alias", ",", "connection", "in", "get_cassandra_connections", "(", ")", ":", "if", "alias", "is", "not", "None", ":", "if", "alias", "==", "_alias", ...
32.5
14.642857
def _get_ansi_code(color=None, style=None): """return ansi escape code corresponding to color and style :type color: str or None :param color: the color name (see `ANSI_COLORS` for available values) or the color number when 256 colors are available :type style: str or None :param style...
[ "def", "_get_ansi_code", "(", "color", "=", "None", ",", "style", "=", "None", ")", ":", "ansi_code", "=", "[", "]", "if", "style", ":", "style_attrs", "=", "utils", ".", "_splitstrip", "(", "style", ")", "for", "effect", "in", "style_attrs", ":", "ans...
31.34375
19.03125
def match(self, *command_tokens, **command_env): """ :meth:`.WCommandProto.match` implementation """ mutated_command_tokens = self.mutate_command_tokens(*command_tokens) if mutated_command_tokens is None: return False return self.selector().select(*mutated_command_tokens, **command_env) is not None
[ "def", "match", "(", "self", ",", "*", "command_tokens", ",", "*", "*", "command_env", ")", ":", "mutated_command_tokens", "=", "self", ".", "mutate_command_tokens", "(", "*", "command_tokens", ")", "if", "mutated_command_tokens", "is", "None", ":", "return", ...
43.714286
15.714286
def is_valid_assignment(self, mtf_dimension_name, mesh_dimension_name): """Whether this MTF dimension may be assigned to this mesh dimension. Args: mtf_dimension_name: string, the name of a Mesh TensorFlow dimension. mesh_dimension_name: string, the name of a mesh dimension. Returns: A b...
[ "def", "is_valid_assignment", "(", "self", ",", "mtf_dimension_name", ",", "mesh_dimension_name", ")", ":", "return", "(", "(", "mtf_dimension_name", "in", "self", ".", "_splittable_mtf_dimension_names", ")", "and", "(", "self", ".", "_mtf_dimension_name_to_size_gcd", ...
45.384615
26.769231
def classic_administrators(self): """Instance depends on the API version: * 2015-06-01: :class:`ClassicAdministratorsOperations<azure.mgmt.authorization.v2015_06_01.operations.ClassicAdministratorsOperations>` """ api_version = self._get_api_version('classic_administrators') ...
[ "def", "classic_administrators", "(", "self", ")", ":", "api_version", "=", "self", ".", "_get_api_version", "(", "'classic_administrators'", ")", "if", "api_version", "==", "'2015-06-01'", ":", "from", ".", "v2015_06_01", ".", "operations", "import", "ClassicAdmini...
62.909091
38.545455
def describe_addresses(self, *addresses): """ List the elastic IPs allocated in this account. @param addresses: if specified, the addresses to get information about. @return: a C{list} of (address, instance_id). If the elastic IP is not associated currently, C{instance_id} ...
[ "def", "describe_addresses", "(", "self", ",", "*", "addresses", ")", ":", "address_set", "=", "{", "}", "for", "pos", ",", "address", "in", "enumerate", "(", "addresses", ")", ":", "address_set", "[", "\"PublicIp.%d\"", "%", "(", "pos", "+", "1", ")", ...
41.882353
18.823529
def create_dash_stream(self, localStreamNames, targetFolder, **kwargs): """ Create Dynamic Adaptive Streaming over HTTP (DASH) out of an existing H.264/AAC stream. DASH was developed by the Moving Picture Experts Group (MPEG) to establish a standard for HTTP adaptive-bitrate stre...
[ "def", "create_dash_stream", "(", "self", ",", "localStreamNames", ",", "targetFolder", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "protocol", ".", "execute", "(", "'createdashstream'", ",", "localStreamNames", "=", "localStreamNames", ",", "targe...
43.863014
25.424658
def gene_features(self): """ return a list of features for the gene features of this object. This would include exons, introns, utrs, etc. """ nm, strand = self.gene_name, self.strand feats = [(self.chrom, self.start, self.end, nm, strand, 'gene')] for feat in ('i...
[ "def", "gene_features", "(", "self", ")", ":", "nm", ",", "strand", "=", "self", ".", "gene_name", ",", "self", ".", "strand", "feats", "=", "[", "(", "self", ".", "chrom", ",", "self", ".", "start", ",", "self", ".", "end", ",", "nm", ",", "stra...
44.761905
19.714286
def content_type_snapshots(self, space_id, environment_id, content_type_id): """ Provides access to content type snapshot management methods. API reference: https://www.contentful.com/developers/docs/references/content-management-api/#/reference/snapshots :return: :class:`SnapshotsProx...
[ "def", "content_type_snapshots", "(", "self", ",", "space_id", ",", "environment_id", ",", "content_type_id", ")", ":", "return", "SnapshotsProxy", "(", "self", ",", "space_id", ",", "environment_id", ",", "content_type_id", ",", "'content_types'", ")" ]
48.8125
40.6875
def get_item_sh(self, item, roles=None, date_field=None): """ Add sorting hat enrichment fields for different roles If there are no roles, just add the author fields. """ eitem_sh = {} # Item enriched author_field = self.get_field_author() if not roles: ...
[ "def", "get_item_sh", "(", "self", ",", "item", ",", "roles", "=", "None", ",", "date_field", "=", "None", ")", ":", "eitem_sh", "=", "{", "}", "# Item enriched", "author_field", "=", "self", ".", "get_field_author", "(", ")", "if", "not", "roles", ":", ...
33.557692
23.826923
def _operators_replace(self, string: str) -> str: """ Searches for first unary or binary operator (via self.op_regex that has only one group that contain operator) then replaces it (or escapes it if brackets do not match). Everything until: * space ' ' * begin...
[ "def", "_operators_replace", "(", "self", ",", "string", ":", "str", ")", "->", "str", ":", "# noinspection PyShadowingNames", "def", "replace", "(", "string", ":", "str", ",", "start", ":", "int", ",", "end", ":", "int", ",", "substring", ":", "str", ")...
43.2
20.421053
def returner(ret): ''' Log outcome to sentry. The returner tries to identify errors and report them as such. All other messages will be reported at info level. Failed states will be appended as separate list for convenience. ''' try: _connect_sentry(_get_message(ret), ret) except Ex...
[ "def", "returner", "(", "ret", ")", ":", "try", ":", "_connect_sentry", "(", "_get_message", "(", "ret", ")", ",", "ret", ")", "except", "Exception", "as", "err", ":", "log", ".", "error", "(", "'Can\\'t run connect_sentry: %s'", ",", "err", ",", "exc_info...
36
27.272727
def extension(filename): '''Properly extract the extension from filename''' filename = os.path.basename(filename) extension = None while '.' in filename: filename, ext = os.path.splitext(filename) if ext.startswith('.'): ext = ext[1:] extension = ext if not extension...
[ "def", "extension", "(", "filename", ")", ":", "filename", "=", "os", ".", "path", ".", "basename", "(", "filename", ")", "extension", "=", "None", "while", "'.'", "in", "filename", ":", "filename", ",", "ext", "=", "os", ".", "path", ".", "splitext", ...
29.833333
18.833333
def ismounted(device): """ Check if partition is mounted Example:: from burlap.disk import ismounted if ismounted('/dev/sda1'): print ("disk sda1 is mounted") """ # Check filesystem with settings(hide('running', 'stdout')): res = run_as_root('mount') for...
[ "def", "ismounted", "(", "device", ")", ":", "# Check filesystem", "with", "settings", "(", "hide", "(", "'running'", ",", "'stdout'", ")", ")", ":", "res", "=", "run_as_root", "(", "'mount'", ")", "for", "line", "in", "res", ".", "splitlines", "(", ")",...
23.071429
15.428571
def _tffunc(*argtypes): '''Helper that transforms TF-graph generating function into a regular one. See `_resize` function below. ''' placeholders = list(map(tf.placeholder, argtypes)) def wrap(f): out = f(*placeholders) def wrapper(*args, **kw): ...
[ "def", "_tffunc", "(", "*", "argtypes", ")", ":", "placeholders", "=", "list", "(", "map", "(", "tf", ".", "placeholder", ",", "argtypes", ")", ")", "def", "wrap", "(", "f", ")", ":", "out", "=", "f", "(", "*", "placeholders", ")", "def", "wrapper"...
39.636364
20.181818
def parse_input(): """Parses command line input.""" parser = argparse.ArgumentParser( description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument('-c', '--config', type=str, help="Specify a configuration file") return parser.pars...
[ "def", "parse_input", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "__doc__", ",", "formatter_class", "=", "argparse", ".", "RawDescriptionHelpFormatter", ")", "parser", ".", "add_argument", "(", "'-c'", ",", "'--conf...
40.125
12.375
async def send_script(self, conn_id, data): """Send a a script to a device. See :meth:`AbstractDeviceAdapter.send_script`. """ progress_callback = functools.partial(_on_progress, self, 'script', conn_id) resp = await self._execute(self._adapter.send_script_sync, conn_id, data,...
[ "async", "def", "send_script", "(", "self", ",", "conn_id", ",", "data", ")", ":", "progress_callback", "=", "functools", ".", "partial", "(", "_on_progress", ",", "self", ",", "'script'", ",", "conn_id", ")", "resp", "=", "await", "self", ".", "_execute",...
37.8
24.8
def linear_rref(A, b, Matrix=None, S=None): """ Transform a linear system to reduced row-echelon form Transforms both the matrix and right-hand side of a linear system of equations to reduced row echelon form Parameters ---------- A : Matrix-like Iterable of rows. b : iterable ...
[ "def", "linear_rref", "(", "A", ",", "b", ",", "Matrix", "=", "None", ",", "S", "=", "None", ")", ":", "if", "Matrix", "is", "None", ":", "from", "sympy", "import", "Matrix", "if", "S", "is", "None", ":", "from", "sympy", "import", "S", "mat_rows",...
25.269231
19.730769
def filtered(self, feature_filter, x=None): # type: (Callable, Any) -> Tuple[FeatureNames, List[int]] """ Return feature names filtered by a regular expression ``feature_re``, and indices of filtered elements. """ indices = [] filtered_feature_names = [] indexed_...
[ "def", "filtered", "(", "self", ",", "feature_filter", ",", "x", "=", "None", ")", ":", "# type: (Callable, Any) -> Tuple[FeatureNames, List[int]]", "indices", "=", "[", "]", "filtered_feature_names", "=", "[", "]", "indexed_names", "=", "None", "# type: Optional[Iter...
40.790698
15.697674
def get_form(self, request, obj=None, **kwargs): """ Returns a Form class for use in the admin add view. This is used by add_view and change_view. """ parent_id = request.REQUEST.get('parent_id', None) if parent_id: return FolderForm else: ...
[ "def", "get_form", "(", "self", ",", "request", ",", "obj", "=", "None", ",", "*", "*", "kwargs", ")", ":", "parent_id", "=", "request", ".", "REQUEST", ".", "get", "(", "'parent_id'", ",", "None", ")", "if", "parent_id", ":", "return", "FolderForm", ...
41.103448
15.517241
def getDatabaseFileSize(self): """ Return the file size of the database as a pretty string. """ if DISABLE_PERSISTENT_CACHING: return "?" size = os.path.getsize(self.__db_filepath) if size > 1000000000: size = "%0.3fGB" % (size / 1000000000) elif size > 1000000: size = "%0.2fMB" % ...
[ "def", "getDatabaseFileSize", "(", "self", ")", ":", "if", "DISABLE_PERSISTENT_CACHING", ":", "return", "\"?\"", "size", "=", "os", ".", "path", ".", "getsize", "(", "self", ".", "__db_filepath", ")", "if", "size", ">", "1000000000", ":", "size", "=", "\"%...
31.142857
12.428571
def AddAdapter(self, device_name, system_name): '''Convenience method to add a Bluetooth adapter You have to specify a device name which must be a valid part of an object path, e. g. "hci0", and an arbitrary system name (pretty hostname). Returns the new object path. ''' path = '/org/bluez/' +...
[ "def", "AddAdapter", "(", "self", ",", "device_name", ",", "system_name", ")", ":", "path", "=", "'/org/bluez/'", "+", "device_name", "adapter_properties", "=", "{", "'UUIDs'", ":", "dbus", ".", "Array", "(", "[", "'00001000-0000-1000-8000-00805f9b34fb'", ",", "...
44.590909
21.560606
def data(place): """get forecast data.""" lat, lon = place url = "https://api.forecast.io/forecast/%s/%s,%s?solar" % (APIKEY, lat, lon) w_data = json.loads(urllib2.urlopen(url).read()) return w_data
[ "def", "data", "(", "place", ")", ":", "lat", ",", "lon", "=", "place", "url", "=", "\"https://api.forecast.io/forecast/%s/%s,%s?solar\"", "%", "(", "APIKEY", ",", "lat", ",", "lon", ")", "w_data", "=", "json", ".", "loads", "(", "urllib2", ".", "urlopen",...
39.285714
20.142857
def format_spec_to_regex(field_name, format_spec): """Make an attempt at converting a format spec to a regular expression.""" # NOTE: remove escaped backslashes so regex matches regex_match = fmt_spec_regex.match(format_spec.replace('\\', '')) if regex_match is None: raise Va...
[ "def", "format_spec_to_regex", "(", "field_name", ",", "format_spec", ")", ":", "# NOTE: remove escaped backslashes so regex matches", "regex_match", "=", "fmt_spec_regex", ".", "match", "(", "format_spec", ".", "replace", "(", "'\\\\'", ",", "''", ")", ")", "if", "...
45.783784
16.594595
def requirements_for_changes(self, changes): """ Parse changes for requirements :param list changes: """ requirements = [] reqs_set = set() if isinstance(changes, str): changes = changes.split('\n') if not changes or changes[0].startswith('-...
[ "def", "requirements_for_changes", "(", "self", ",", "changes", ")", ":", "requirements", "=", "[", "]", "reqs_set", "=", "set", "(", ")", "if", "isinstance", "(", "changes", ",", "str", ")", ":", "changes", "=", "changes", ".", "split", "(", "'\\n'", ...
33.236842
20.657895
def select_regex_in(pl,regex): ''' regex = re.compile("^x.*x$") pl = ['bcd','xabcxx','xx','y'] select_regex_in(pl,'abc') ''' def cond_func(ele,index,regex): if(type(ele)==type([])): cond = regex_in(ele,regex) else: m = regex.search(ele) ...
[ "def", "select_regex_in", "(", "pl", ",", "regex", ")", ":", "def", "cond_func", "(", "ele", ",", "index", ",", "regex", ")", ":", "if", "(", "type", "(", "ele", ")", "==", "type", "(", "[", "]", ")", ")", ":", "cond", "=", "regex_in", "(", "el...
28.722222
15.944444
def add_cli_to_bel_namespace(main: click.Group) -> click.Group: # noqa: D202 """Add a ``upload_bel_namespace`` command to main :mod:`click` function.""" @main.command() @click.option('-u', '--update', is_flag=True) @click.pass_obj def upload(manager: BELNamespaceManagerMixin, update): """U...
[ "def", "add_cli_to_bel_namespace", "(", "main", ":", "click", ".", "Group", ")", "->", "click", ".", "Group", ":", "# noqa: D202", "@", "main", ".", "command", "(", ")", "@", "click", ".", "option", "(", "'-u'", ",", "'--update'", ",", "is_flag", "=", ...
42.25
21.833333
def h3(data, *args, **kwargs): """Facade function to create 3D histograms. Parameters ---------- data : array_like or list[array_like] or tuple[array_like] Can be a single array (with three columns) or three different arrays (for each component) Returns ------- physt.histog...
[ "def", "h3", "(", "data", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "import", "numpy", "as", "np", "if", "data", "is", "not", "None", "and", "isinstance", "(", "data", ",", "(", "list", ",", "tuple", ")", ")", "and", "not", "np", "."...
34.045455
24.318182
def seek(self, offset, from_what=os.SEEK_SET): ''' :param offset: Position in the file to seek to :type offset: integer Seeks to *offset* bytes from the beginning of the file. This is a no-op if the file is open for writing. The position is computed from adding *offset* to a r...
[ "def", "seek", "(", "self", ",", "offset", ",", "from_what", "=", "os", ".", "SEEK_SET", ")", ":", "if", "from_what", "==", "os", ".", "SEEK_SET", ":", "reference_pos", "=", "0", "elif", "from_what", "==", "os", ".", "SEEK_CUR", ":", "reference_pos", "...
45.793103
24.068966
def _append_string(self, value, _file): # pylint: disable=no-self-use """Call this function to write string contents. Keyword arguments: * value - dict, content to be dumped * _file - FileIO, output file """ _text = str(value).replace('"', '\\"') _labs ...
[ "def", "_append_string", "(", "self", ",", "value", ",", "_file", ")", ":", "# pylint: disable=no-self-use", "_text", "=", "str", "(", "value", ")", ".", "replace", "(", "'\"'", ",", "'\\\\\"'", ")", "_labs", "=", "' \"{text}\"'", ".", "format", "(", "text...
33.545455
14.454545
def LoadFromXml(self, node): """ Method updates the object from the xml. """ import os self.classId = node.localName metaClassId = UcsUtils.FindClassIdInMoMetaIgnoreCase(self.classId) if metaClassId: self.classId = metaClassId if node.hasAttribute(NamingPropertyId.DN): self.dn = node.getAttribute(N...
[ "def", "LoadFromXml", "(", "self", ",", "node", ")", ":", "import", "os", "self", ".", "classId", "=", "node", ".", "localName", "metaClassId", "=", "UcsUtils", ".", "FindClassIdInMoMetaIgnoreCase", "(", "self", ".", "classId", ")", "if", "metaClassId", ":",...
28.96875
19.1875
def _check_flag_masks(self, ds, name): ''' Check a variable's flag_masks attribute for compliance under CF - flag_masks exists as an array - flag_masks is the same dtype as the variable - variable's dtype can support bit-field - flag_masks is the same length as flag_mean...
[ "def", "_check_flag_masks", "(", "self", ",", "ds", ",", "name", ")", ":", "variable", "=", "ds", ".", "variables", "[", "name", "]", "flag_masks", "=", "variable", ".", "flag_masks", "flag_meanings", "=", "getattr", "(", "ds", ",", "'flag_meanings'", ",",...
43.348837
26.976744
def SendKey(self, key: int, waitTime: float = OPERATION_WAIT_TIME) -> None: """ Make control have focus first and type a key. `self.SetFocus` may not work for some controls, you may need to click it to make it have focus. key: int, a key code value in class Keys. waitTime: float....
[ "def", "SendKey", "(", "self", ",", "key", ":", "int", ",", "waitTime", ":", "float", "=", "OPERATION_WAIT_TIME", ")", "->", "None", ":", "self", ".", "SetFocus", "(", ")", "SendKey", "(", "key", ",", "waitTime", ")" ]
42.111111
18.111111
def create(self, request, desc, files, public=False): """Creates a gist Arguments: request: an initial request object desc: the gist description files: a list of files to add to the gist public: a flag to indicate whether the gist is public or not ...
[ "def", "create", "(", "self", ",", "request", ",", "desc", ",", "files", ",", "public", "=", "False", ")", ":", "request", ".", "data", "=", "json", ".", "dumps", "(", "{", "\"description\"", ":", "desc", ",", "\"public\"", ":", "public", ",", "\"fil...
31
15.736842
def prefixedDec(nstr, schema): """ !~~prefixedDec corresponding strings in documents must begin with the associated string in the schema, and the right part of strings in documents must be decimal. """ if not nstr.startswith(schema): return False postfix = nstr[len(sc...
[ "def", "prefixedDec", "(", "nstr", ",", "schema", ")", ":", "if", "not", "nstr", ".", "startswith", "(", "schema", ")", ":", "return", "False", "postfix", "=", "nstr", "[", "len", "(", "schema", ")", ":", "]", "try", ":", "int", "(", "postfix", ")"...
26.866667
15.666667
def get_method_by_idx(self, idx): """ Return a specific method by using an index :param idx: the index of the method :type idx: int :rtype: None or an :class:`EncodedMethod` object """ if self.__cached_methods_idx == None: self.__cached_method...
[ "def", "get_method_by_idx", "(", "self", ",", "idx", ")", ":", "if", "self", ".", "__cached_methods_idx", "==", "None", ":", "self", ".", "__cached_methods_idx", "=", "{", "}", "for", "i", "in", "self", ".", "classes", ".", "class_def", ":", "for", "j", ...
32.388889
13.833333
def put( self, item: _T, timeout: Union[float, datetime.timedelta] = None ) -> "Future[None]": """Put an item into the queue, perhaps waiting until there is room. Returns a Future, which raises `tornado.util.TimeoutError` after a timeout. ``timeout`` may be a number denotin...
[ "def", "put", "(", "self", ",", "item", ":", "_T", ",", "timeout", ":", "Union", "[", "float", ",", "datetime", ".", "timedelta", "]", "=", "None", ")", "->", "\"Future[None]\"", ":", "future", "=", "Future", "(", ")", "# type: Future[None]", "try", ":...
35.454545
19.909091
def available_input_formats(): """ Return all available input formats. Returns ------- formats : list all available input formats """ input_formats = [] for v in pkg_resources.iter_entry_points(DRIVERS_ENTRY_POINT): logger.debug("driver found: %s", v) driver_ = v...
[ "def", "available_input_formats", "(", ")", ":", "input_formats", "=", "[", "]", "for", "v", "in", "pkg_resources", ".", "iter_entry_points", "(", "DRIVERS_ENTRY_POINT", ")", ":", "logger", ".", "debug", "(", "\"driver found: %s\"", ",", "v", ")", "driver_", "...
30.625
17.75
def get_series_by_name(self, name): """Returns the first :py:class:`.Series` of a given name, or ``None``. :param str name: The name to search by.""" if not isinstance(name, str): raise TypeError( "Can only search series by str name, not '%s'" % str(name) )...
[ "def", "get_series_by_name", "(", "self", ",", "name", ")", ":", "if", "not", "isinstance", "(", "name", ",", "str", ")", ":", "raise", "TypeError", "(", "\"Can only search series by str name, not '%s'\"", "%", "str", "(", "name", ")", ")", "for", "series", ...
34.833333
14.333333
def add_device(self, device, container): """Add a device to a group. Wraps JSSObject.add_object_to_path. Args: device: A JSSObject to add (as list data), to this object. location: Element or a string path argument to find() """ # There is a size tag which the JSS...
[ "def", "add_device", "(", "self", ",", "device", ",", "container", ")", ":", "# There is a size tag which the JSS manages for us, so we can", "# ignore it.", "if", "self", ".", "findtext", "(", "\"is_smart\"", ")", "==", "\"false\"", ":", "self", ".", "add_object_to_p...
45.333333
20.4
def set_iprouting(self, value=None, default=False, disable=False): """Configures the state of global ip routing EosVersion: 4.13.7M Args: value(bool): True if ip routing should be enabled or False if ip routing should be disabled default (boo...
[ "def", "set_iprouting", "(", "self", ",", "value", "=", "None", ",", "default", "=", "False", ",", "disable", "=", "False", ")", ":", "if", "value", "is", "False", ":", "disable", "=", "True", "cmd", "=", "self", ".", "command_builder", "(", "'ip routi...
36.75
22.3
def get(self, user_name: str) -> User: """ Gets the User Resource. """ user = current_user() if user.is_admin or user.name == user_name: return self._get_or_abort(user_name) else: abort(403)
[ "def", "get", "(", "self", ",", "user_name", ":", "str", ")", "->", "User", ":", "user", "=", "current_user", "(", ")", "if", "user", ".", "is_admin", "or", "user", ".", "name", "==", "user_name", ":", "return", "self", ".", "_get_or_abort", "(", "us...
28.222222
9.555556
def search_accounts(self, **kwargs): """ Return a list of up to 5 matching account domains. Partial matches on name and domain are supported. :calls: `GET /api/v1/accounts/search \ <https://canvas.instructure.com/doc/api/account_domain_lookups.html#method.account_domain_lookups....
[ "def", "search_accounts", "(", "self", ",", "*", "*", "kwargs", ")", ":", "response", "=", "self", ".", "__requester", ".", "request", "(", "'GET'", ",", "'accounts/search'", ",", "_kwargs", "=", "combine_kwargs", "(", "*", "*", "kwargs", ")", ")", "retu...
33.0625
19.0625
def check_version(cls): """Checks server version against minimum required version.""" super(SimpleCpnrDriver, cls).check_version() model.configure_pnr() cls.recover_networks() ver = model.get_version() if ver < cls.MIN_VERSION: LOG.warning("CPNR version does n...
[ "def", "check_version", "(", "cls", ")", ":", "super", "(", "SimpleCpnrDriver", ",", "cls", ")", ".", "check_version", "(", ")", "model", ".", "configure_pnr", "(", ")", "cls", ".", "recover_networks", "(", ")", "ver", "=", "model", ".", "get_version", "...
44.363636
15.181818
def as_csv(self): """Return a CSV representation as a string""" from io import StringIO s = StringIO() w = csv.writer(s) for row in self.rows: w.writerow(row) return s.getvalue()
[ "def", "as_csv", "(", "self", ")", ":", "from", "io", "import", "StringIO", "s", "=", "StringIO", "(", ")", "w", "=", "csv", ".", "writer", "(", "s", ")", "for", "row", "in", "self", ".", "rows", ":", "w", ".", "writerow", "(", "row", ")", "ret...
21
20.181818
def get_count(self,name): """ get the latest counter for a certain parameter type. Parameters ---------- name : str the parameter type Returns ------- count : int the latest count for a parameter type Note ---- ca...
[ "def", "get_count", "(", "self", ",", "name", ")", ":", "if", "name", "not", "in", "self", ".", "mlt_counter", ":", "self", ".", "mlt_counter", "[", "name", "]", "=", "1", "c", "=", "0", "else", ":", "c", "=", "self", ".", "mlt_counter", "[", "na...
23.037037
19.444444
def from_stream(cls, stream_rdr, offset): """ Return an |_IfdEntry| subclass instance containing the tag and value of the tag parsed from *stream_rdr* at *offset*. Note this method is common to all subclasses. Override the ``_parse_value()`` method to provide distinctive behavior...
[ "def", "from_stream", "(", "cls", ",", "stream_rdr", ",", "offset", ")", ":", "tag_code", "=", "stream_rdr", ".", "read_short", "(", "offset", ",", "0", ")", "value_count", "=", "stream_rdr", ".", "read_long", "(", "offset", ",", "4", ")", "value_offset", ...
45.642857
15.928571
def load(self, elem): """ Converts the inputted string tag to Python. :param elem | <xml.etree.ElementTree> :return <str> """ self.testTag(elem, 'str') return elem.text if elem.text is not None else ''
[ "def", "load", "(", "self", ",", "elem", ")", ":", "self", ".", "testTag", "(", "elem", ",", "'str'", ")", "return", "elem", ".", "text", "if", "elem", ".", "text", "is", "not", "None", "else", "''" ]
27.5
14.3
def _get_images_dir(): ''' Extract the images dir from the configuration. First attempts to find legacy virt.images, then tries virt:images. ''' img_dir = __salt__['config.option']('virt.images') if img_dir: salt.utils.versions.warn_until( 'Sodium', '\'virt.images...
[ "def", "_get_images_dir", "(", ")", ":", "img_dir", "=", "__salt__", "[", "'config.option'", "]", "(", "'virt.images'", ")", "if", "img_dir", ":", "salt", ".", "utils", ".", "versions", ".", "warn_until", "(", "'Sodium'", ",", "'\\'virt.images\\' has been deprec...
34.5
20.166667
def add_batch(self, table, keys, attributes_to_get=None): """ Add a Batch to this BatchList. :type table: :class:`boto.dynamodb.table.Table` :param table: The Table object in which the items are contained. :type keys: list :param keys: A list of scalar or tuple ...
[ "def", "add_batch", "(", "self", ",", "table", ",", "keys", ",", "attributes_to_get", "=", "None", ")", ":", "self", ".", "append", "(", "Batch", "(", "table", ",", "keys", ",", "attributes_to_get", ")", ")" ]
47.5
22.136364
def make_confidence_report(filepath, train_start=TRAIN_START, train_end=TRAIN_END, test_start=TEST_START, test_end=TEST_END, batch_size=BATCH_SIZE, which_set=WHICH_SET, mc_batch_size=MC_BATCH_SIZE, ...
[ "def", "make_confidence_report", "(", "filepath", ",", "train_start", "=", "TRAIN_START", ",", "train_end", "=", "TRAIN_END", ",", "test_start", "=", "TEST_START", ",", "test_end", "=", "TEST_END", ",", "batch_size", "=", "BATCH_SIZE", ",", "which_set", "=", "WH...
37.007576
19.810606
def addLayerNode(self, layerName, bias = None, weights = {}): """ Adds a new node to a layer, and puts in new weights. Adds node on the end. Weights will be random, unless specified. bias = the new node's bias weight weights = dict of {connectedLayerName: [weights], ...} ...
[ "def", "addLayerNode", "(", "self", ",", "layerName", ",", "bias", "=", "None", ",", "weights", "=", "{", "}", ")", ":", "self", ".", "changeLayerSize", "(", "layerName", ",", "self", "[", "layerName", "]", ".", "size", "+", "1", ")", "if", "bias", ...
46.76
20.28
def as_uni_field(field): """ Renders a form field like a django-uni-form field:: {% load uni_form_tags %} {{ form.field|as_uni_field }} """ template = get_template('uni_form/field.html') c = Context({'field':field}) return template.render(c)
[ "def", "as_uni_field", "(", "field", ")", ":", "template", "=", "get_template", "(", "'uni_form/field.html'", ")", "c", "=", "Context", "(", "{", "'field'", ":", "field", "}", ")", "return", "template", ".", "render", "(", "c", ")" ]
27.3
11.1
def fallback(cache): """ Caches content retrieved by the client, thus allowing the cached content to be used later if the live content cannot be retrieved. """ log_filter = ThrottlingFilter(cache=cache) logger.filters = [] logger.addFilter(log_filter) def get_cache_response(cache_key)...
[ "def", "fallback", "(", "cache", ")", ":", "log_filter", "=", "ThrottlingFilter", "(", "cache", "=", "cache", ")", "logger", ".", "filters", "=", "[", "]", "logger", ".", "addFilter", "(", "log_filter", ")", "def", "get_cache_response", "(", "cache_key", "...
39.076923
18.384615
def get_model(self): ''' `object` of model as a function approximator, which has `cnn` whose type is `pydbm.cnn.pydbm.cnn.convolutional_neural_network.ConvolutionalNeuralNetwork`. ''' class Model(object): def __init__(self, cnn): self.cnn = cn...
[ "def", "get_model", "(", "self", ")", ":", "class", "Model", "(", "object", ")", ":", "def", "__init__", "(", "self", ",", "cnn", ")", ":", "self", ".", "cnn", "=", "cnn", "return", "Model", "(", "self", ".", "__cnn", ")" ]
31.363636
19.363636
def plot_vxx(self, colorbar=True, cb_orientation='vertical', cb_label=None, ax=None, show=True, fname=None, **kwargs): """ Plot the Vxx component of the tensor. Usage ----- x.plot_vxx([tick_interval, xlabel, ylabel, ax, colorbar, cb_orientati...
[ "def", "plot_vxx", "(", "self", ",", "colorbar", "=", "True", ",", "cb_orientation", "=", "'vertical'", ",", "cb_label", "=", "None", ",", "ax", "=", "None", ",", "show", "=", "True", ",", "fname", "=", "None", ",", "*", "*", "kwargs", ")", ":", "i...
40.679245
18.830189
def data( self, previous_data=False, prompt=False, console_row=False, console_row_to_cursor=False, console_row_from_cursor=False ): """ Return output data. Flags specifies what data to append. If no flags was specified nul-length string returned :param previous_data: If True, then previous output appends ...
[ "def", "data", "(", "self", ",", "previous_data", "=", "False", ",", "prompt", "=", "False", ",", "console_row", "=", "False", ",", "console_row_to_cursor", "=", "False", ",", "console_row_from_cursor", "=", "False", ")", ":", "result", "=", "''", "if", "p...
37.029412
24.235294
def _read_lines(filepath): """Read a req file to a list to support nested requirement files.""" with open(filepath, 'rt', encoding='utf8') as fh: for line in fh: line = line.strip() if line.startswith("-r"): logger.debug("Reading deps from nested requirement file:...
[ "def", "_read_lines", "(", "filepath", ")", ":", "with", "open", "(", "filepath", ",", "'rt'", ",", "encoding", "=", "'utf8'", ")", "as", "fh", ":", "for", "line", "in", "fh", ":", "line", "=", "line", ".", "strip", "(", ")", "if", "line", ".", "...
44.444444
17.111111
def predict(self, dataset, output_type='class', missing_value_action='auto'): """ A flexible and advanced prediction API. The target column is provided during :func:`~turicreate.decision_tree.create`. If the target column is in the `dataset` it will be ignored. Paramete...
[ "def", "predict", "(", "self", ",", "dataset", ",", "output_type", "=", "'class'", ",", "missing_value_action", "=", "'auto'", ")", ":", "_check_categorical_option_type", "(", "'output_type'", ",", "output_type", ",", "[", "'class'", ",", "'margin'", ",", "'prob...
43.290323
26.064516
def get_enabled_features(self, user_id, attributes=None): """ Returns the list of features that are enabled for the user. Args: user_id: ID for user. attributes: Dict representing user attributes. Returns: A list of the keys of the features that are enabled for the user. """ ena...
[ "def", "get_enabled_features", "(", "self", ",", "user_id", ",", "attributes", "=", "None", ")", ":", "enabled_features", "=", "[", "]", "if", "not", "self", ".", "is_valid", ":", "self", ".", "logger", ".", "error", "(", "enums", ".", "Errors", ".", "...
31.714286
22.5
def density_dir(CIJ): ''' Density is the fraction of present connections to possible connections. Parameters ---------- CIJ : NxN np.ndarray directed weighted/binary connection matrix Returns ------- kden : float density N : int number of vertices k : in...
[ "def", "density_dir", "(", "CIJ", ")", ":", "n", "=", "len", "(", "CIJ", ")", "k", "=", "np", ".", "size", "(", "np", ".", "where", "(", "CIJ", ".", "flatten", "(", ")", ")", ")", "kden", "=", "k", "/", "(", "n", "*", "n", "-", "n", ")", ...
20.333333
24.185185
def fillNullValues(col, rows): 'Fill null cells in col with the previous non-null value' lastval = None nullfunc = isNullFunc() n = 0 rowsToFill = list(rows) for r in Progress(col.sheet.rows, 'filling'): # loop over all rows try: val = col.getValue(r) except Exceptio...
[ "def", "fillNullValues", "(", "col", ",", "rows", ")", ":", "lastval", "=", "None", "nullfunc", "=", "isNullFunc", "(", ")", "n", "=", "0", "rowsToFill", "=", "list", "(", "rows", ")", "for", "r", "in", "Progress", "(", "col", ".", "sheet", ".", "r...
26.428571
19
def fetch_all(self, api_client, fetchstatuslogger, q, targets): ''' Make all API calls as defined in metadata.json :param api_client: :param fetchstatuslogger: :param q: :param targets: :return: ''' self.fetchstatuslogger = fetchstatuslogger ...
[ "def", "fetch_all", "(", "self", ",", "api_client", ",", "fetchstatuslogger", ",", "q", ",", "targets", ")", ":", "self", ".", "fetchstatuslogger", "=", "fetchstatuslogger", "if", "targets", "!=", "None", ":", "# Ensure targets is a tuple", "if", "type", "(", ...
33.631579
15.421053
def is_excluded(root, excludes): """Check if the directory is in the exclude list. Note: by having trailing slashes, we avoid common prefix issues, like e.g. an exlude "foo" also accidentally excluding "foobar". """ root = os.path.normpath(root) for exclude in excludes: if root ==...
[ "def", "is_excluded", "(", "root", ",", "excludes", ")", ":", "root", "=", "os", ".", "path", ".", "normpath", "(", "root", ")", "for", "exclude", "in", "excludes", ":", "if", "root", "==", "exclude", ":", "return", "True", "return", "False" ]
32.727273
16.545455
def _load_manifest_interpret_source(manifest, source, username=None, password=None, verify_certificate=True, do_inherit=True): """ Interpret the <source>, and load the results into <manifest> """ try: if isinstance(source, string_types): if source.startswith("http"): # if man...
[ "def", "_load_manifest_interpret_source", "(", "manifest", ",", "source", ",", "username", "=", "None", ",", "password", "=", "None", ",", "verify_certificate", "=", "True", ",", "do_inherit", "=", "True", ")", ":", "try", ":", "if", "isinstance", "(", "sour...
53
20.75
def _accumulate(sequence, func): """ Python2 accumulate implementation taken from https://docs.python.org/3/library/itertools.html#itertools.accumulate """ iterator = iter(sequence) total = next(iterator) yield total for element in iterator: total = func(total, element) y...
[ "def", "_accumulate", "(", "sequence", ",", "func", ")", ":", "iterator", "=", "iter", "(", "sequence", ")", "total", "=", "next", "(", "iterator", ")", "yield", "total", "for", "element", "in", "iterator", ":", "total", "=", "func", "(", "total", ",",...
29.090909
12.363636
def _smallest_integer_by_dtype(dt): """Helper returning the smallest integer exactly representable by dtype.""" if not _is_known_dtype(dt): raise TypeError("Unrecognized dtype: {}".format(dt.name)) if _is_known_unsigned_by_dtype(dt): return 0 return -1 * _largest_integer_by_dtype(dt)
[ "def", "_smallest_integer_by_dtype", "(", "dt", ")", ":", "if", "not", "_is_known_dtype", "(", "dt", ")", ":", "raise", "TypeError", "(", "\"Unrecognized dtype: {}\"", ".", "format", "(", "dt", ".", "name", ")", ")", "if", "_is_known_unsigned_by_dtype", "(", "...
42
10.142857
def open_interface_async(self, conn_id, interface, callback, connection_string=None): """Asynchronously connect to a device.""" future = self._loop.launch_coroutine(self._adapter.open_interface(conn_id, interface)) future.add_done_callback(lambda x: self._callback_future(conn_id, x, callback))
[ "def", "open_interface_async", "(", "self", ",", "conn_id", ",", "interface", ",", "callback", ",", "connection_string", "=", "None", ")", ":", "future", "=", "self", ".", "_loop", ".", "launch_coroutine", "(", "self", ".", "_adapter", ".", "open_interface", ...
63
37.2
def session_check_name(session_name): """ Raises exception session name invalid, modeled after tmux function. tmux(1) session names may not be empty, or include periods or colons. These delimiters are reserved for noting session, window and pane. Parameters ---------- session_name : str ...
[ "def", "session_check_name", "(", "session_name", ")", ":", "if", "not", "session_name", "or", "len", "(", "session_name", ")", "==", "0", ":", "raise", "exc", ".", "BadSessionName", "(", "\"tmux session names may not be empty.\"", ")", "elif", "'.'", "in", "ses...
30.888889
22.148148
def compute_layout_properties( width, height, frame_width, frame_height, explicit_width, explicit_height, aspect, data_aspect, responsive, size_multiplier, logger=None): """ Utility to compute the aspect, plot width/height and sizing_mode behavior. Args: width (int): Plot ...
[ "def", "compute_layout_properties", "(", "width", ",", "height", ",", "frame_width", ",", "frame_height", ",", "explicit_width", ",", "explicit_height", ",", "aspect", ",", "data_aspect", ",", "responsive", ",", "size_multiplier", ",", "logger", "=", "None", ")", ...
37.943038
16.056962
def create(ctx): """ Create default config file """ import shutil this_dir, this_filename = os.path.split(__file__) default_config_file = os.path.join(this_dir, "apis/example-config.yaml") config_file = ctx.obj["configfile"] shutil.copyfile(default_config_file, config_file) print_messag...
[ "def", "create", "(", "ctx", ")", ":", "import", "shutil", "this_dir", ",", "this_filename", "=", "os", ".", "path", ".", "split", "(", "__file__", ")", "default_config_file", "=", "os", ".", "path", ".", "join", "(", "this_dir", ",", "\"apis/example-confi...
35.9
17.4