text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def _glob(filenames): """Glob a filename or list of filenames but always return the original string if the glob didn't match anything so URLs for remote file access are not clobbered. """ if isinstance(filenames, string_types): filenames = [filenames] matches = [] for name in filenam...
[ "def", "_glob", "(", "filenames", ")", ":", "if", "isinstance", "(", "filenames", ",", "string_types", ")", ":", "filenames", "=", "[", "filenames", "]", "matches", "=", "[", "]", "for", "name", "in", "filenames", ":", "matched_names", "=", "glob", "(", ...
32.4375
0.001873
def showBindingsForActionSet(self, unSizeOfVRSelectedActionSet_t, unSetCount, originToHighlight): """Shows the current binding all the actions in the specified action sets""" fn = self.function_table.showBindingsForActionSet pSets = VRActiveActionSet_t() result = fn(byref(pSets), unSize...
[ "def", "showBindingsForActionSet", "(", "self", ",", "unSizeOfVRSelectedActionSet_t", ",", "unSetCount", ",", "originToHighlight", ")", ":", "fn", "=", "self", ".", "function_table", ".", "showBindingsForActionSet", "pSets", "=", "VRActiveActionSet_t", "(", ")", "resu...
56.857143
0.012376
def _validate_section(self, subject, coll, parts): """Validate one section of a spec. :param subject: Name of subject :type subject: str :param coll: The collection to validate :type coll: pymongo.Collection :param parts: Section parts :type parts: Validator.Sect...
[ "def", "_validate_section", "(", "self", ",", "subject", ",", "coll", ",", "parts", ")", ":", "cvgroup", "=", "ConstraintViolationGroup", "(", ")", "cvgroup", ".", "subject", "=", "subject", "# If the constraint is an 'import' of code, treat it differently here", "# if ...
42.660377
0.001297
def do_plot(self, arg): """Plots the current state of the shell's independent vs. dependent variables on the same set of axes. Give filename to save to as argument or leave blank to show. """ usable, filename, append = self._redirect_split(arg) self.curargs["xscale"] = None ...
[ "def", "do_plot", "(", "self", ",", "arg", ")", ":", "usable", ",", "filename", ",", "append", "=", "self", ".", "_redirect_split", "(", "arg", ")", "self", ".", "curargs", "[", "\"xscale\"", "]", "=", "None", "self", ".", "curargs", "[", "\"yscale\"",...
47.75
0.010283
def m(name='', **kwargs): """ Print out memory usage at this point in time http://docs.python.org/2/library/resource.html http://stackoverflow.com/a/15448600/5006 http://stackoverflow.com/questions/110259/which-python-memory-profiler-is-recommended """ with Reflect.context(**kwargs) as r: ...
[ "def", "m", "(", "name", "=", "''", ",", "*", "*", "kwargs", ")", ":", "with", "Reflect", ".", "context", "(", "*", "*", "kwargs", ")", "as", "r", ":", "kwargs", "[", "\"name\"", "]", "=", "name", "instance", "=", "M_CLASS", "(", "r", ",", "str...
33.666667
0.00241
def try_and_error(*funcs): """Apply multiple validation functions Parameters ---------- ``*funcs`` Validation functions to test Returns ------- function""" def validate(value): exc = None for func in funcs: try: return func(value) ...
[ "def", "try_and_error", "(", "*", "funcs", ")", ":", "def", "validate", "(", "value", ")", ":", "exc", "=", "None", "for", "func", "in", "funcs", ":", "try", ":", "return", "func", "(", "value", ")", "except", "(", "ValueError", ",", "TypeError", ")"...
20.4
0.002342
def goal_create(self, data, **kwargs): "https://developer.zendesk.com/rest_api/docs/chat/goals#create-goal" api_path = "/api/v2/goals" return self.call(api_path, method="POST", data=data, **kwargs)
[ "def", "goal_create", "(", "self", ",", "data", ",", "*", "*", "kwargs", ")", ":", "api_path", "=", "\"/api/v2/goals\"", "return", "self", ".", "call", "(", "api_path", ",", "method", "=", "\"POST\"", ",", "data", "=", "data", ",", "*", "*", "kwargs", ...
54.5
0.00905
def _ImageDimensions(images, dynamic_shape=False): """Returns the dimensions of an image tensor. Args: images: 4-D Tensor of shape [batch, height, width, channels] dynamic_shape: Whether the input image has undertermined shape. If set to `True`, shape information will be retrieved at run time. Default...
[ "def", "_ImageDimensions", "(", "images", ",", "dynamic_shape", "=", "False", ")", ":", "# A simple abstraction to provide names for each dimension. This abstraction", "# should make it simpler to switch dimensions in the future (e.g. if we ever", "# want to switch height and width.)", "if...
39.444444
0.009629
def do_header(self, node): """For a user defined section def a header field is present which should not be printed as such, so we comment it in the output.""" data = self.extract_text(node) self.add_text('\n/*\n %s \n*/\n' % data) # If our immediate sibling is a 'descript...
[ "def", "do_header", "(", "self", ",", "node", ")", ":", "data", "=", "self", ".", "extract_text", "(", "node", ")", "self", ".", "add_text", "(", "'\\n/*\\n %s \\n*/\\n'", "%", "data", ")", "# If our immediate sibling is a 'description' node then we", "# should comm...
43.833333
0.002481
def concat_multiple_inputs(data, sample): """ If multiple fastq files were appended into the list of fastqs for samples then we merge them here before proceeding. """ ## if more than one tuple in fastq list if len(sample.files.fastqs) > 1: ## create a cat command to append them all (d...
[ "def", "concat_multiple_inputs", "(", "data", ",", "sample", ")", ":", "## if more than one tuple in fastq list", "if", "len", "(", "sample", ".", "files", ".", "fastqs", ")", ">", "1", ":", "## create a cat command to append them all (doesn't matter if they ", "## are gz...
44.564103
0.010135
def get_job_info(current_job): """Get job information for current job.""" trials = TrialRecord.objects.filter(job_id=current_job.job_id) total_num = len(trials) running_num = sum(t.trial_status == Trial.RUNNING for t in trials) success_num = sum(t.trial_status == Trial.TERMINATED for t in trials) ...
[ "def", "get_job_info", "(", "current_job", ")", ":", "trials", "=", "TrialRecord", ".", "objects", ".", "filter", "(", "job_id", "=", "current_job", ".", "job_id", ")", "total_num", "=", "len", "(", "trials", ")", "running_num", "=", "sum", "(", "t", "."...
32.03125
0.000947
def positionedcrop(self,x,y,sheet_coord_system): """ Offset the bounds_template to this cf's location and store the result in the 'bounds' attribute. Also stores the input_sheet_slice for access by C. """ cf_row,cf_col = sheet_coord_system.sheet2matrixidx(x,y) bo...
[ "def", "positionedcrop", "(", "self", ",", "x", ",", "y", ",", "sheet_coord_system", ")", ":", "cf_row", ",", "cf_col", "=", "sheet_coord_system", ".", "sheet2matrixidx", "(", "x", ",", "y", ")", "bounds_x", ",", "bounds_y", "=", "self", ".", "compute_boun...
37.466667
0.022569
def sns(self): """ :rtype: SNSConnection """ if self.__sns is None: self.__sns = self.__aws_connect(sns) return self.__sns
[ "def", "sns", "(", "self", ")", ":", "if", "self", ".", "__sns", "is", "None", ":", "self", ".", "__sns", "=", "self", ".", "__aws_connect", "(", "sns", ")", "return", "self", ".", "__sns" ]
24
0.011494
def write_data(self): """Write data to a file.""" self.output_file.write(self.downloaded_file_buffer) self.output_file.close() self.finished_flag = True
[ "def", "write_data", "(", "self", ")", ":", "self", ".", "output_file", ".", "write", "(", "self", ".", "downloaded_file_buffer", ")", "self", ".", "output_file", ".", "close", "(", ")", "self", ".", "finished_flag", "=", "True" ]
36
0.01087
def timed_pipe(generator, seconds=3): ''' This is a time limited pipeline. If you have a infinite pipeline and want it to stop yielding after a certain amount of time, use this! ''' # grab the highest precision timer # when it started start = ts() # when it will stop end = start + second...
[ "def", "timed_pipe", "(", "generator", ",", "seconds", "=", "3", ")", ":", "# grab the highest precision timer", "# when it started", "start", "=", "ts", "(", ")", "# when it will stop", "end", "=", "start", "+", "seconds", "# iterate over the pipeline", "for", "i",...
30.055556
0.001792
def _parse_arg(valid_classifications): """ Command line parser for coco Parameters ---------- valid_classifications: list Available classifications, used for checking input parameters. Returns ------- args : ArgumentParser namespace """ parser = argparse.ArgumentParser( ...
[ "def", "_parse_arg", "(", "valid_classifications", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "(", "'The country converter (coco): a Python package for '", "'converting country names between '", "'different classifications schemes. '", "'...
44.457627
0.000373
def set_filters(self, filters): """ set and validate filters dict """ if not isinstance(filters, dict): raise Exception("filters must be a dict") self.filters = {} for key in filters.keys(): value = filters[key] self.add_filter(key,valu...
[ "def", "set_filters", "(", "self", ",", "filters", ")", ":", "if", "not", "isinstance", "(", "filters", ",", "dict", ")", ":", "raise", "Exception", "(", "\"filters must be a dict\"", ")", "self", ".", "filters", "=", "{", "}", "for", "key", "in", "filte...
31.3
0.009317
def MultiIter(*sequences): """ A generator for iterating over the elements of multiple sequences simultaneously. With N sequences given as input, the generator yields all possible distinct N-tuples that contain one element from each of the input sequences. Example: >>> x = MultiIter([0, 1, 2], [10, 11]) >>> ...
[ "def", "MultiIter", "(", "*", "sequences", ")", ":", "if", "len", "(", "sequences", ")", ">", "1", ":", "# FIXME: this loop is about 5% faster if done the other", "# way around, if the last list is iterated over in the", "# inner loop. but there is code, like snglcoinc.py in", ...
33.5
0.024862
def main(): cmd = sys.argv cmd.pop(0) """ parse arguments and make go """ parser = argparse.ArgumentParser() parser.add_argument( '-s', '--src', help='source folder to watch', default='.', dest='src', metavar='folder' ) parser.add_argum...
[ "def", "main", "(", ")", ":", "cmd", "=", "sys", ".", "argv", "cmd", ".", "pop", "(", "0", ")", "parser", "=", "argparse", ".", "ArgumentParser", "(", ")", "parser", ".", "add_argument", "(", "'-s'", ",", "'--src'", ",", "help", "=", "'source folder ...
22.705882
0.002484
def set_chat_title(self, *args, **kwargs): """See :func:`set_chat_title`""" return set_chat_title(*args, **self._merge_overrides(**kwargs)).run()
[ "def", "set_chat_title", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "set_chat_title", "(", "*", "args", ",", "*", "*", "self", ".", "_merge_overrides", "(", "*", "*", "kwargs", ")", ")", ".", "run", "(", ")" ]
53
0.012422
def download(supported_tags, date_array, tag, sat_id, ftp_site='cdaweb.gsfc.nasa.gov', data_path=None, user=None, password=None, fake_daily_files_from_monthly=False): """Routine to download NASA CDAWeb CDF data. This routine is intended to be used by pysat instrumen...
[ "def", "download", "(", "supported_tags", ",", "date_array", ",", "tag", ",", "sat_id", ",", "ftp_site", "=", "'cdaweb.gsfc.nasa.gov'", ",", "data_path", "=", "None", ",", "user", "=", "None", ",", "password", "=", "None", ",", "fake_daily_files_from_monthly", ...
37.330097
0.008361
def fetch_synchronize_status(): """ Returns the synchronization status information for the currently opened project """ r = Response() project = cd.project.get_internal_project() if not project: r.fail( code='NO_PROJECT', message='No open project on which to ...
[ "def", "fetch_synchronize_status", "(", ")", ":", "r", "=", "Response", "(", ")", "project", "=", "cd", ".", "project", ".", "get_internal_project", "(", ")", "if", "not", "project", ":", "r", ".", "fail", "(", "code", "=", "'NO_PROJECT'", ",", "message"...
28.074074
0.001276
def replace_f(self, path, arg_name=None): """Replace files""" root, file = os.path.split(path) pattern = re.compile(r'(\<\<\<)([A-Za-z_]+)(\>\>\>)') file_path = path fh, abs_path = mkstemp() with open(abs_path, 'w') as new_file: with open(file_path) as old_fi...
[ "def", "replace_f", "(", "self", ",", "path", ",", "arg_name", "=", "None", ")", ":", "root", ",", "file", "=", "os", ".", "path", ".", "split", "(", "path", ")", "pattern", "=", "re", ".", "compile", "(", "r'(\\<\\<\\<)([A-Za-z_]+)(\\>\\>\\>)'", ")", ...
39.478261
0.002151
def _new_cls_attr(self, clazz, name, cls=None, mult=MULT_ONE, cont=True, ref=False, bool_assignment=False, position=0): """Creates new meta attribute of this class.""" attr = MetaAttr(name, cls, mult, cont, ref, bool_assignment, position) clazz._tx_a...
[ "def", "_new_cls_attr", "(", "self", ",", "clazz", ",", "name", ",", "cls", "=", "None", ",", "mult", "=", "MULT_ONE", ",", "cont", "=", "True", ",", "ref", "=", "False", ",", "bool_assignment", "=", "False", ",", "position", "=", "0", ")", ":", "a...
50.142857
0.008403
def retrieve_dcnm_net_info(self, tenant_id, direc): """Retrieves the DCNM network info for a tenant. """ serv_obj = self.get_service_obj(tenant_id) net_dict = serv_obj.get_dcnm_net_dict(direc) return net_dict
[ "def", "retrieve_dcnm_net_info", "(", "self", ",", "tenant_id", ",", "direc", ")", ":", "serv_obj", "=", "self", ".", "get_service_obj", "(", "tenant_id", ")", "net_dict", "=", "serv_obj", ".", "get_dcnm_net_dict", "(", "direc", ")", "return", "net_dict" ]
47.2
0.008333
def can_approve(self, user, **data): """ Only sys admins can approve an organisation, or a reseller sending pre_verified=true :param user: a User :param data: data that the user wants to update """ is_admin = user.is_admin() is_reseller_preverifying = user.is_rese...
[ "def", "can_approve", "(", "self", ",", "user", ",", "*", "*", "data", ")", ":", "is_admin", "=", "user", ".", "is_admin", "(", ")", "is_reseller_preverifying", "=", "user", ".", "is_reseller", "(", ")", "and", "data", ".", "get", "(", "'pre_verified'", ...
45.888889
0.009501
def mine(tgt=None, tgt_type='glob', **kwargs): ''' .. versionchanged:: 2017.7.0 The ``expr_form`` argument has been renamed to ``tgt_type``, earlier releases must use ``expr_form``. Return cached mine data of the targeted minions CLI Example: .. code-block:: bash salt-run...
[ "def", "mine", "(", "tgt", "=", "None", ",", "tgt_type", "=", "'glob'", ",", "*", "*", "kwargs", ")", ":", "pillar_util", "=", "salt", ".", "utils", ".", "master", ".", "MasterPillarUtil", "(", "tgt", ",", "tgt_type", ",", "use_cached_grains", "=", "Fa...
38.090909
0.001164
def get(self, key): """ Get an entry from the cache by key. @raise KeyError: if the given key is not present in the cache. @raise CacheFault: (a L{KeyError} subclass) if the given key is present in the cache, but the value it points to is gone. """ o = self....
[ "def", "get", "(", "self", ",", "key", ")", ":", "o", "=", "self", ".", "data", "[", "key", "]", "(", ")", "if", "o", "is", "None", ":", "# On CPython, the weakref callback will always(?) run before any", "# other code has a chance to observe that the weakref is broke...
48.375
0.001689
def update(self, emailAddress=None, ttl=None, comment=None): """ Provides a way to modify the following attributes of a domain entry: - email address - ttl setting - comment """ return self.manager.update_domain(self, emailAddress=emailAddress,...
[ "def", "update", "(", "self", ",", "emailAddress", "=", "None", ",", "ttl", "=", "None", ",", "comment", "=", "None", ")", ":", "return", "self", ".", "manager", ".", "update_domain", "(", "self", ",", "emailAddress", "=", "emailAddress", ",", "ttl", "...
35.3
0.008287
def dvs_configured(name, dvs): ''' Configures a DVS. Creates a new DVS, if it doesn't exist in the provided datacenter or reconfigures it if configured differently. dvs DVS dict representations (see module sysdocs) ''' datacenter_name = _get_datacenter_name() dvs_name = dvs['na...
[ "def", "dvs_configured", "(", "name", ",", "dvs", ")", ":", "datacenter_name", "=", "_get_datacenter_name", "(", ")", "dvs_name", "=", "dvs", "[", "'name'", "]", "if", "dvs", ".", "get", "(", "'name'", ")", "else", "name", "log", ".", "info", "(", "'Ru...
48.013889
0.00085
def to_java_array(m): ''' to_java_array(m) yields to_java_ints(m) if m is an array of integers and to_java_doubles(m) if m is anything else. The numpy array m is tested via numpy.issubdtype(m.dtype, numpy.int64). ''' if not hasattr(m, '__iter__'): return m m = np.asarray(m) if np.issubdtype(...
[ "def", "to_java_array", "(", "m", ")", ":", "if", "not", "hasattr", "(", "m", ",", "'__iter__'", ")", ":", "return", "m", "m", "=", "np", ".", "asarray", "(", "m", ")", "if", "np", ".", "issubdtype", "(", "m", ".", "dtype", ",", "np", ".", "dty...
41.909091
0.010616
def upsert_pending_licensors(cursor, document_id): """Update or insert records for pending license acceptors.""" cursor.execute("""\ SELECT "uuid", "metadata" FROM pending_documents WHERE id = %s""", (document_id,)) uuid_, metadata = cursor.fetchone() acceptors = set([uid for uid, type_ in _dissect_role...
[ "def", "upsert_pending_licensors", "(", "cursor", ",", "document_id", ")", ":", "cursor", ".", "execute", "(", "\"\"\"\\\nSELECT \"uuid\", \"metadata\"\nFROM pending_documents\nWHERE id = %s\"\"\"", ",", "(", "document_id", ",", ")", ")", "uuid_", ",", "metadata", "=", ...
31.142857
0.000741
def channels_unarchive(self, room_id, **kwargs): """Unarchives a channel.""" return self.__call_api_post('channels.unarchive', roomId=room_id, kwargs=kwargs)
[ "def", "channels_unarchive", "(", "self", ",", "room_id", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "__call_api_post", "(", "'channels.unarchive'", ",", "roomId", "=", "room_id", ",", "kwargs", "=", "kwargs", ")" ]
57
0.017341
def setSenderKeyState(self, id, iteration, chainKey, signatureKey): """ :type id: int :type iteration: int :type chainKey: bytearray :type signatureKey: ECKeyPair """ del self.senderKeyStates[:] self.senderKeyStates.append(SenderKeyState(id, iteration, cha...
[ "def", "setSenderKeyState", "(", "self", ",", "id", ",", "iteration", ",", "chainKey", ",", "signatureKey", ")", ":", "del", "self", ".", "senderKeyStates", "[", ":", "]", "self", ".", "senderKeyStates", ".", "append", "(", "SenderKeyState", "(", "id", ","...
38.888889
0.00838
def _set_prompt(self): """Set prompt so it displays the current working directory.""" self.cwd = os.getcwd() self.prompt = Fore.CYAN + '{!r} $ '.format(self.cwd) + Fore.RESET
[ "def", "_set_prompt", "(", "self", ")", ":", "self", ".", "cwd", "=", "os", ".", "getcwd", "(", ")", "self", ".", "prompt", "=", "Fore", ".", "CYAN", "+", "'{!r} $ '", ".", "format", "(", "self", ".", "cwd", ")", "+", "Fore", ".", "RESET" ]
48.75
0.010101
def _reverse_annotations(old_record, new_record): """ Copy annotations form old_record to new_record, reversing any lists / tuples / strings. """ # Copy the annotations over for k, v in list(old_record.annotations.items()): # Trim if appropriate if isinstance(v, (tuple, list)) an...
[ "def", "_reverse_annotations", "(", "old_record", ",", "new_record", ")", ":", "# Copy the annotations over", "for", "k", ",", "v", "in", "list", "(", "old_record", ".", "annotations", ".", "items", "(", ")", ")", ":", "# Trim if appropriate", "if", "isinstance"...
38.388889
0.001412
def get_receptive_field(layers, img_size): """Get the real filter sizes of each layer involved in convoluation. See Xudong Cao: https://www.kaggle.com/c/datasciencebowl/forums/t/13166/happy-lantern-festival-report-and-code This does not yet take into consideration feature pooling, padding, striding ...
[ "def", "get_receptive_field", "(", "layers", ",", "img_size", ")", ":", "receptive_field", "=", "np", ".", "zeros", "(", "(", "len", "(", "layers", ")", ",", "2", ")", ")", "conv_mode", "=", "True", "first_conv_layer", "=", "True", "expon", "=", "np", ...
35.055556
0.000771
def click_link_text(self, link_text, timeout=settings.SMALL_TIMEOUT): """ This method clicks link text on a page """ # If using phantomjs, might need to extract and open the link directly if self.timeout_multiplier and timeout == settings.SMALL_TIMEOUT: timeout = self.__get_new_timeo...
[ "def", "click_link_text", "(", "self", ",", "link_text", ",", "timeout", "=", "settings", ".", "SMALL_TIMEOUT", ")", ":", "# If using phantomjs, might need to extract and open the link directly", "if", "self", ".", "timeout_multiplier", "and", "timeout", "==", "settings",...
41.828947
0.000615
def render_choicefield(field, attrs, choices=None): """ Render ChoiceField as 'div' dropdown rather than select for more customization. """ # Allow custom choice list, but if no custom choice list then wrap all # choices into the `wrappers.CHOICE_TEMPLATE` if not choices: choices = format_html_join("", wrapper...
[ "def", "render_choicefield", "(", "field", ",", "attrs", ",", "choices", "=", "None", ")", ":", "# Allow custom choice list, but if no custom choice list then wrap all", "# choices into the `wrappers.CHOICE_TEMPLATE`", "if", "not", "choices", ":", "choices", "=", "format_html...
38.363636
0.024277
def meanOmega(self,dangle,oned=False,offset_sign=None, tdisrupt=None): """ NAME: meanOmega PURPOSE: calculate the mean frequency as a function of angle, assuming a uniform time distribution up to a maximum time INPUT: dangle - angle...
[ "def", "meanOmega", "(", "self", ",", "dangle", ",", "oned", "=", "False", ",", "offset_sign", "=", "None", ",", "tdisrupt", "=", "None", ")", ":", "if", "offset_sign", "is", "None", ":", "offset_sign", "=", "self", ".", "_sigMeanSign", "if", "tdisrupt",...
30.02381
0.023041
def get_config_node(self): '''get_config_node High-level api: get_config_node returns an Element node in the config tree, which is corresponding to the URL in the Restconf GET reply. Returns ------- Element A config node. ''' default_ns = '...
[ "def", "get_config_node", "(", "self", ")", ":", "default_ns", "=", "''", "config_node", "=", "etree", ".", "Element", "(", "config_tag", ",", "nsmap", "=", "{", "'nc'", ":", "nc_url", "}", ")", "for", "index", ",", "url_piece", "in", "enumerate", "(", ...
45.194444
0.001203
def axes(self, offset = False): """returns measured value in miligauss""" reg, self._scale = self.SCALES[self._gauss] x = self.bus.read_int16_data(self.address, self.HMC5883L_DXRA) if x == -4096: x = OVERFLOW y = self.bus.read_int16_data(self.address, self.HMC5883L_DYRA) ...
[ "def", "axes", "(", "self", ",", "offset", "=", "False", ")", ":", "reg", ",", "self", ".", "_scale", "=", "self", ".", "SCALES", "[", "self", ".", "_gauss", "]", "x", "=", "self", ".", "bus", ".", "read_int16_data", "(", "self", ".", "address", ...
34.705882
0.023102
def list_upgrades(refresh=True, **kwargs): ''' List all available package upgrades on this system Args: refresh (bool): Refresh package metadata. Default ``True`` Kwargs: saltenv (str): Salt environment. Default ``base`` Returns: dict: A dictionary of packages with availab...
[ "def", "list_upgrades", "(", "refresh", "=", "True", ",", "*", "*", "kwargs", ")", ":", "saltenv", "=", "kwargs", ".", "get", "(", "'saltenv'", ",", "'base'", ")", "refresh", "=", "salt", ".", "utils", ".", "data", ".", "is_true", "(", "refresh", ")"...
32.105263
0.001591
def compare_stacks(cards_x, cards_y, sorted=False): """ Checks whether two given ``Stack``, ``Deck``, or ``list`` instances, contain the same cards (based on value & suit, not instance). Does not take into account the ordering. :arg cards_x: The first stack to check. Can be a ``Stack``, ``D...
[ "def", "compare_stacks", "(", "cards_x", ",", "cards_y", ",", "sorted", "=", "False", ")", ":", "if", "len", "(", "cards_x", ")", "==", "len", "(", "cards_y", ")", ":", "if", "not", "sorted", ":", "cards_x", "=", "sort_cards", "(", "cards_x", ",", "D...
32.4
0.000999
def read_geo(self, key, info): """Read angles. """ pairs = {('satellite_azimuth_angle', 'satellite_zenith_angle'): ("SatelliteAzimuthAngle", "SatelliteZenithAngle"), ('solar_azimuth_angle', 'solar_zenith_angle'): ("SolarAzimuthAngle", "SolarZeni...
[ "def", "read_geo", "(", "self", ",", "key", ",", "info", ")", ":", "pairs", "=", "{", "(", "'satellite_azimuth_angle'", ",", "'satellite_zenith_angle'", ")", ":", "(", "\"SatelliteAzimuthAngle\"", ",", "\"SatelliteZenithAngle\"", ")", ",", "(", "'solar_azimuth_ang...
47.365854
0.001009
def get_data(filename, subset, url): """Get a dataset with from a url with local caching. Parameters ---------- filename : str Name of the file, for caching. subset : str To what subset the file belongs (e.g. 'ray_transform'). Each subset is saved in a separate subfolder. ...
[ "def", "get_data", "(", "filename", ",", "subset", ",", "url", ")", ":", "# check if this data set has been already downloaded", "data_dir", "=", "join", "(", "get_data_dir", "(", ")", ",", "subset", ")", "if", "not", "exists", "(", "data_dir", ")", ":", "os",...
29.292683
0.000806
def sys_register_SDL_renderer(callback: Callable[[Any], None]) -> None: """Register a custom randering function with libtcod. Note: This callback will only be called by the SDL renderer. The callack will receive a :any:`CData <ffi-cdata>` void* to an SDL_Surface* struct. The callback is c...
[ "def", "sys_register_SDL_renderer", "(", "callback", ":", "Callable", "[", "[", "Any", "]", ",", "None", "]", ")", "->", "None", ":", "with", "_PropagateException", "(", ")", "as", "propagate", ":", "@", "ffi", ".", "def_extern", "(", "onerror", "=", "pr...
32.909091
0.001342
def variable(self): """ variable : variable Feature Type Array adds: variable : variable[expression] Feature Type Func adds: variable : variable(arg_list) """ var = Var(self.cur_token) self.eat(TokenTypes.VAR) if Features.TYPE_ARRA...
[ "def", "variable", "(", "self", ")", ":", "var", "=", "Var", "(", "self", ".", "cur_token", ")", "self", ".", "eat", "(", "TokenTypes", ".", "VAR", ")", "if", "Features", ".", "TYPE_ARRAY", "in", "self", ".", "features", ":", "while", "self", ".", ...
38.166667
0.00213
def _FilterExcludedFiles(filenames): """Filters out files listed in the --exclude command line switch. File paths in the switch are evaluated relative to the current working directory """ exclude_paths = [os.path.abspath(f) for f in _excludes] return [f for f in filenames if os.path.abspath(f) not in exclude_...
[ "def", "_FilterExcludedFiles", "(", "filenames", ")", ":", "exclude_paths", "=", "[", "os", ".", "path", ".", "abspath", "(", "f", ")", "for", "f", "in", "_excludes", "]", "return", "[", "f", "for", "f", "in", "filenames", "if", "os", ".", "path", "....
53.5
0.01227
def define_property(obj, name, fget=None, fset=None, fdel=None, doc=None): """Defines a @property dynamically for an instance rather than a class.""" if hasattr(fget, '__get__'): # can pass a property declaration too prop = fget else: prop = property(fget, fset, fdel, doc) cls = obj.__c...
[ "def", "define_property", "(", "obj", ",", "name", ",", "fget", "=", "None", ",", "fset", "=", "None", ",", "fdel", "=", "None", ",", "doc", "=", "None", ")", ":", "if", "hasattr", "(", "fget", ",", "'__get__'", ")", ":", "# can pass a property declara...
38.545455
0.002304
def walk(self, fn): """ Loops through all data elements and allows a function to interact with each data element. Uses a generator to improve iteration. :param fn: Function that interacts with each DICOM element """ if not hasattr(fn, "__call__"): raise TypeError("""walk_da...
[ "def", "walk", "(", "self", ",", "fn", ")", ":", "if", "not", "hasattr", "(", "fn", ",", "\"__call__\"", ")", ":", "raise", "TypeError", "(", "\"\"\"walk_dataset requires a\n function as its parameter\"\"\"", ")", "dataset", "=", "self", ".", "_data...
39.45
0.002475
def merge_dicts(dicts, deepcopy=False): """Merges dicts In case of key conflicts, the value kept will be from the latter dictionary in the list of dictionaries :param dicts: [dict, ...] :param deepcopy: deepcopy items within dicts """ assert isinstance(dicts, list) and all(isinstance(d, di...
[ "def", "merge_dicts", "(", "dicts", ",", "deepcopy", "=", "False", ")", ":", "assert", "isinstance", "(", "dicts", ",", "list", ")", "and", "all", "(", "isinstance", "(", "d", ",", "dict", ")", "for", "d", "in", "dicts", ")", "return", "dict", "(", ...
37.166667
0.002188
def finalize_response(self, request, response, *args, **kwargs): """ Returns the final response object. """ # Make the error obvious if a proper response is not returned assert isinstance(response, HttpResponseBase), ( 'Expected a `Response`, `HttpResponse` or `HttpSt...
[ "def", "finalize_response", "(", "self", ",", "request", ",", "response", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# Make the error obvious if a proper response is not returned", "assert", "isinstance", "(", "response", ",", "HttpResponseBase", ")", ","...
41.416667
0.001967
def set_network(ip, netmask, gateway, host=None, admin_username=None, admin_password=None): ''' Configure Network on the CMC or individual iDRAC. Use ``set_niccfg`` for blade and switch addresses. CLI Example: .. code-block:: bash salt dell dracr.set_network [DRAC IP] [NET...
[ "def", "set_network", "(", "ip", ",", "netmask", ",", "gateway", ",", "host", "=", "None", ",", "admin_username", "=", "None", ",", "admin_password", "=", "None", ")", ":", "return", "__execute_cmd", "(", "'setniccfg -s {0} {1} {2}'", ".", "format", "(", "ip...
36
0.001504
def speaker_registrations(request, form): ''' Shows registration status for speakers with a given proposal kind. ''' kinds = form.cleaned_data["kind"] presentations = schedule_models.Presentation.objects.filter( proposal_base__kind__in=kinds, ).exclude( cancelled=True, ) users...
[ "def", "speaker_registrations", "(", "request", ",", "form", ")", ":", "kinds", "=", "form", ".", "cleaned_data", "[", "\"kind\"", "]", "presentations", "=", "schedule_models", ".", "Presentation", ".", "objects", ".", "filter", "(", "proposal_base__kind__in", "...
28.294118
0.001005
def docker_image_ids(broker): """Command: docker_image_ids""" images = broker[DefaultSpecs.docker_list_images] try: result = set() for l in images.content[1:]: result.add(l.split(None)[3].strip()) except: raise ContentException("No dock...
[ "def", "docker_image_ids", "(", "broker", ")", ":", "images", "=", "broker", "[", "DefaultSpecs", ".", "docker_list_images", "]", "try", ":", "result", "=", "set", "(", ")", "for", "l", "in", "images", ".", "content", "[", "1", ":", "]", ":", "result",...
35.333333
0.009195
def sendall(self, s): """ Send data to the channel, without allowing partial results. Unlike `send`, this method continues to send data from the given string until either all data has been sent or an error occurs. Nothing is returned. :param str s: data to send. :rais...
[ "def", "sendall", "(", "self", ",", "s", ")", ":", "while", "s", ":", "sent", "=", "self", ".", "send", "(", "s", ")", "s", "=", "s", "[", "sent", ":", "]", "return", "None" ]
38.363636
0.002312
def _parse_w_comma_h(self, whstr, param): """Utility to parse "w,h" "w," or ",h" values. Returns (w,h) where w,h are either None or ineteger. Will throw a ValueError if there is a problem with one or both. """ try: (wstr, hstr) = whstr.split(',', 2) w = s...
[ "def", "_parse_w_comma_h", "(", "self", ",", "whstr", ",", "param", ")", ":", "try", ":", "(", "wstr", ",", "hstr", ")", "=", "whstr", ".", "split", "(", "','", ",", "2", ")", "w", "=", "self", ".", "_parse_non_negative_int", "(", "wstr", ",", "'w'...
41.315789
0.002491
def get_all_analytics(user, job_id): """Get all analytics of a job.""" args = schemas.args(flask.request.args.to_dict()) v1_utils.verify_existence_and_get(job_id, models.JOBS) query = v1_utils.QueryBuilder(_TABLE, args, _A_COLUMNS) # If not admin nor rh employee then restrict the view to the team ...
[ "def", "get_all_analytics", "(", "user", ",", "job_id", ")", ":", "args", "=", "schemas", ".", "args", "(", "flask", ".", "request", ".", "args", ".", "to_dict", "(", ")", ")", "v1_utils", ".", "verify_existence_and_get", "(", "job_id", ",", "models", "....
39.444444
0.001376
def tree_to_nodes(tree, context=None, metadata=None): """Assembles ``tree`` nodes into object models. If ``context`` is supplied, it will be used to contextualize the contents of the nodes. Metadata will pass non-node identifying values down to child nodes, if not overridden (license, timestamps, etc) ...
[ "def", "tree_to_nodes", "(", "tree", ",", "context", "=", "None", ",", "metadata", "=", "None", ")", ":", "nodes", "=", "[", "]", "for", "item", "in", "tree", "[", "'contents'", "]", ":", "if", "'contents'", "in", "item", ":", "sub_nodes", "=", "tree...
44.92
0.000436
def _parse_tree_structmap(self, tree, parent_elem, normative_parent_elem=None): """Recursively parse all the children of parent_elem, including amdSecs and dmdSecs. :param lxml._ElementTree tree: encodes the entire METS file. :param lxml._Element parent_elem: the element whose children w...
[ "def", "_parse_tree_structmap", "(", "self", ",", "tree", ",", "parent_elem", ",", "normative_parent_elem", "=", "None", ")", ":", "siblings", "=", "[", "]", "el_to_normative", "=", "self", ".", "_get_el_to_normative", "(", "parent_elem", ",", "normative_parent_el...
52.090909
0.001285
def _plot_completeness(ax, comw, start_time, end_time): ''' Adds completeness intervals to a plot ''' comw = np.array(comw) comp = np.column_stack([np.hstack([end_time, comw[:, 0], start_time]), np.hstack([comw[0, 1], comw[:, 1], comw[-1, 1]])]) ax.step(comp[:-1, 0], ...
[ "def", "_plot_completeness", "(", "ax", ",", "comw", ",", "start_time", ",", "end_time", ")", ":", "comw", "=", "np", ".", "array", "(", "comw", ")", "comp", "=", "np", ".", "column_stack", "(", "[", "np", ".", "hstack", "(", "[", "end_time", ",", ...
43.666667
0.002494
def credential_update(self, cred_id, **options): """credential_update cred_id **options Updates the specified values of the credential ID specified. """ payload = None # First we pull the credentials and populate the payload if we # find a match. for cred in self...
[ "def", "credential_update", "(", "self", ",", "cred_id", ",", "*", "*", "options", ")", ":", "payload", "=", "None", "# First we pull the credentials and populate the payload if we", "# find a match.", "for", "cred", "in", "self", ".", "credentials", "(", ")", "[", ...
39.957447
0.001559
def wait_for_edge(self, pin, edge): """Wait for an edge. Pin should be type IN. Edge must be RISING, FALLING or BOTH. """ self.bbio_gpio.wait_for_edge(pin, self._edge_mapping[edge])
[ "def", "wait_for_edge", "(", "self", ",", "pin", ",", "edge", ")", ":", "self", ".", "bbio_gpio", ".", "wait_for_edge", "(", "pin", ",", "self", ".", "_edge_mapping", "[", "edge", "]", ")" ]
42.6
0.013825
def hoys_int(self): """A sorted list of hours of year in this analysis period as integers.""" if self._timestamps_data is None: self._calculate_timestamps() return tuple(int(moy / 60.0) for moy in self._timestamps_data)
[ "def", "hoys_int", "(", "self", ")", ":", "if", "self", ".", "_timestamps_data", "is", "None", ":", "self", ".", "_calculate_timestamps", "(", ")", "return", "tuple", "(", "int", "(", "moy", "/", "60.0", ")", "for", "moy", "in", "self", ".", "_timestam...
50.2
0.011765
def silence_without_namespace(f): """Decorator to silence template tags if 'PROJECT_HOME_NAMESPACE' is not defined in settings. Usage Example: from django import template register = template.Library() @register.simple_tag @silence_without_namespace def a_template_...
[ "def", "silence_without_namespace", "(", "f", ")", ":", "@", "wraps", "(", "f", ")", "def", "wrapped", "(", "label", "=", "None", ")", ":", "if", "not", "home_namespace", ":", "return", "''", "if", "label", ":", "return", "f", "(", "label", ")", "els...
22.5
0.001776
def cont_moments_cv(cont, flt_epsilon=1.19209e-07, dbl_epsilon=2.2204460492503131e-16): """Compute the moments of a contour The moments are computed in the same way as they are computed in OpenCV's `contourMoments` in `moments.cpp`. Parameters ---------- ...
[ "def", "cont_moments_cv", "(", "cont", ",", "flt_epsilon", "=", "1.19209e-07", ",", "dbl_epsilon", "=", "2.2204460492503131e-16", ")", ":", "# Make sure we have no unsigned integers", "if", "np", ".", "issubdtype", "(", "cont", ".", "dtype", ",", "np", ".", "unsig...
29.352381
0.000314
def custom_auth(principal, credentials, realm, scheme, **parameters): """ Generate a basic auth token for a given user and password. :param principal: specifies who is being authenticated :param credentials: authenticates the principal :param realm: specifies the authentication provider :param sche...
[ "def", "custom_auth", "(", "principal", ",", "credentials", ",", "realm", ",", "scheme", ",", "*", "*", "parameters", ")", ":", "from", "neobolt", ".", "security", "import", "AuthToken", "return", "AuthToken", "(", "scheme", ",", "principal", ",", "credentia...
51.5
0.00159
def prefix_with_ns_if_necessary(name, name_ns, source_ns): # type: (typing.Text, ApiNamespace, ApiNamespace) -> typing.Text """ Returns a name that can be used to reference `name` in namespace `name_ns` from `source_ns`. If `source_ns` and `name_ns` are the same, that's just `name`. Otherwise i...
[ "def", "prefix_with_ns_if_necessary", "(", "name", ",", "name_ns", ",", "source_ns", ")", ":", "# type: (typing.Text, ApiNamespace, ApiNamespace) -> typing.Text", "if", "source_ns", "==", "name_ns", ":", "return", "name", "return", "'{}.{}'", ".", "format", "(", "fmt_na...
37.333333
0.002179
async def finish(self, *, chat: typing.Union[str, int, None] = None, user: typing.Union[str, int, None] = None): """ Finish conversation for user in chat. Chat or user is always required. If one of them is not provided, you have to set missing v...
[ "async", "def", "finish", "(", "self", ",", "*", ",", "chat", ":", "typing", ".", "Union", "[", "str", ",", "int", ",", "None", "]", "=", "None", ",", "user", ":", "typing", ".", "Union", "[", "str", ",", "int", ",", "None", "]", "=", "None", ...
34.214286
0.00813
def new_reservoir(reservoir_type='uniform', *reservoir_args, **reservoir_kwargs): """ Build a new reservoir """ try: reservoir_cls = RESERVOIR_TYPES[reservoir_type] except KeyError: raise InvalidMetricError("Unknown reservoir type: {}".format(reservoir_type)) return reservoir_c...
[ "def", "new_reservoir", "(", "reservoir_type", "=", "'uniform'", ",", "*", "reservoir_args", ",", "*", "*", "reservoir_kwargs", ")", ":", "try", ":", "reservoir_cls", "=", "RESERVOIR_TYPES", "[", "reservoir_type", "]", "except", "KeyError", ":", "raise", "Invali...
31.727273
0.008357
def listobs(vis): """Textually describe the contents of a measurement set. vis (str) The path to the dataset. Returns A generator of lines of human-readable output Errors can only be detected by looking at the output. Example:: from pwkit.environments.casa import tasks for li...
[ "def", "listobs", "(", "vis", ")", ":", "def", "inner_list", "(", "sink", ")", ":", "try", ":", "ms", "=", "util", ".", "tools", ".", "ms", "(", ")", "ms", ".", "open", "(", "vis", ")", "ms", ".", "summary", "(", "verbose", "=", "True", ")", ...
26.548387
0.002345
def writeString(self, s): """ Writes a string to the stream. It will be B{UTF-8} encoded. """ s = self.context.getBytesForString(s) self.writeBytes(s)
[ "def", "writeString", "(", "self", ",", "s", ")", ":", "s", "=", "self", ".", "context", ".", "getBytesForString", "(", "s", ")", "self", ".", "writeBytes", "(", "s", ")" ]
26.428571
0.010471
def send_document(self, *args, **kwargs): """See :func:`send_document`""" return send_document(*args, **self._merge_overrides(**kwargs)).run()
[ "def", "send_document", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "send_document", "(", "*", "args", ",", "*", "*", "self", ".", "_merge_overrides", "(", "*", "*", "kwargs", ")", ")", ".", "run", "(", ")" ]
52
0.012658
def to_none_or_dt(input): """Convert ``input`` to either None or a datetime object If the input is None, None will be returned. If the input is a datetime object, it will be converted to a datetime object with UTC timezone info. If the datetime object is naive, then this method will assume the obj...
[ "def", "to_none_or_dt", "(", "input", ")", ":", "if", "input", "is", "None", ":", "return", "input", "elif", "isinstance", "(", "input", ",", "datetime", ".", "datetime", ")", ":", "arrow_dt", "=", "arrow", ".", "Arrow", ".", "fromdatetime", "(", "input"...
41.846154
0.001797
def select_observations(self, name): """Returns nodes whose instrument-band matches 'name' """ return [n for n in self.get_obs_nodes() if n.obsname==name]
[ "def", "select_observations", "(", "self", ",", "name", ")", ":", "return", "[", "n", "for", "n", "in", "self", ".", "get_obs_nodes", "(", ")", "if", "n", ".", "obsname", "==", "name", "]" ]
43.75
0.016854
def _get_num_similar_objects(self, obj): """Get any statement lines which would be considered a duplicate of obj""" return StatementLine.objects.filter( date=obj.date, amount=obj.amount, description=obj.description ).count()
[ "def", "_get_num_similar_objects", "(", "self", ",", "obj", ")", ":", "return", "StatementLine", ".", "objects", ".", "filter", "(", "date", "=", "obj", ".", "date", ",", "amount", "=", "obj", ".", "amount", ",", "description", "=", "obj", ".", "descript...
51.2
0.011538
def list(self, storagemodel:object, modeldefinition = None, where=None) ->list: """ list blob messages in container """ try: blobnames = [] if where is None: generator = modeldefinition['blobservice'].list_blobs(modeldefinition['container']) else: ...
[ "def", "list", "(", "self", ",", "storagemodel", ":", "object", ",", "modeldefinition", "=", "None", ",", "where", "=", "None", ")", "->", "list", ":", "try", ":", "blobnames", "=", "[", "]", "if", "where", "is", "None", ":", "generator", "=", "model...
41.722222
0.013021
def extend_src(self, content, context): """Extend source list.""" self.extend_src_text(content, context, self.block_comments, 'block-comment') self.extend_src_text(content, context, self.line_comments, 'line-comment')
[ "def", "extend_src", "(", "self", ",", "content", ",", "context", ")", ":", "self", ".", "extend_src_text", "(", "content", ",", "context", ",", "self", ".", "block_comments", ",", "'block-comment'", ")", "self", ".", "extend_src_text", "(", "content", ",", ...
47.6
0.016529
def create_widget(self, place, type, file=None, **kwargs): ''' Create a widget object based on given arguments. If file object is provided, callable arguments will be resolved: its return value will be used after calling them with file as first parameter. All extra `kwa...
[ "def", "create_widget", "(", "self", ",", "place", ",", "type", ",", "file", "=", "None", ",", "*", "*", "kwargs", ")", ":", "widget_class", "=", "self", ".", "widget_types", ".", "get", "(", "type", ",", "self", ".", "widget_types", "[", "'base'", "...
38.973684
0.001318
def do_region(self, x, y, w, h): """Null implementation of region selection.""" if (x is not None): raise IIIFError(code=501, parameter="region", text="Null manipulator supports only region=/full/.")
[ "def", "do_region", "(", "self", ",", "x", ",", "y", ",", "w", ",", "h", ")", ":", "if", "(", "x", "is", "not", "None", ")", ":", "raise", "IIIFError", "(", "code", "=", "501", ",", "parameter", "=", "\"region\"", ",", "text", "=", "\"Null manipu...
50.2
0.011765
def get_instruction(self, idx, off=None): """ Get a particular instruction by using (default) the index of the address if specified :param idx: index of the instruction (the position in the list of the instruction) :type idx: int :param off: address of the instru...
[ "def", "get_instruction", "(", "self", ",", "idx", ",", "off", "=", "None", ")", ":", "if", "off", "!=", "None", ":", "idx", "=", "self", ".", "off_to_pos", "(", "off", ")", "return", "[", "i", "for", "i", "in", "self", ".", "get_instructions", "("...
37.357143
0.009328
def value_to_display(value, minmax=False, level=0): """Convert value for display purpose""" # To save current Numpy printoptions np_printoptions = FakeObject try: numeric_numpy_types = (int64, int32, int16, int8, uint64, uint32, uint16, uint8, ...
[ "def", "value_to_display", "(", "value", ",", "minmax", "=", "False", ",", "level", "=", "0", ")", ":", "# To save current Numpy printoptions", "np_printoptions", "=", "FakeObject", "try", ":", "numeric_numpy_types", "=", "(", "int64", ",", "int32", ",", "int16"...
39.259542
0.000948
def add_openmp_flags_if_available(extension): """ Add OpenMP compilation flags, if supported (if not a warning will be printed to the console and no flags will be added.) Returns `True` if the flags were added, `False` otherwise. """ if _ASTROPY_DISABLE_SETUP_WITH_OPENMP_: log.info("Op...
[ "def", "add_openmp_flags_if_available", "(", "extension", ")", ":", "if", "_ASTROPY_DISABLE_SETUP_WITH_OPENMP_", ":", "log", ".", "info", "(", "\"OpenMP support has been explicitly disabled.\"", ")", "return", "False", "openmp_flags", "=", "get_openmp_flags", "(", ")", "u...
36.269231
0.002066
def _dict_pprinter_factory(start, end, basetype=None): """ Factory that returns a pprint function used by the default pprint of dicts and dict proxies. """ def inner(obj, p, cycle): typ = type(obj) if basetype is not None and typ is not basetype and typ.__repr__ != basetype.__repr__:...
[ "def", "_dict_pprinter_factory", "(", "start", ",", "end", ",", "basetype", "=", "None", ")", ":", "def", "inner", "(", "obj", ",", "p", ",", "cycle", ")", ":", "typ", "=", "type", "(", "obj", ")", "if", "basetype", "is", "not", "None", "and", "typ...
30.758621
0.002174
def unpack_kinesis_event(kinesis_event, deserializer=None, unpacker=None, embed_timestamp=False): """Extracts events (a list of dicts) from a Kinesis event.""" records = kinesis_event["Records"] events = [] shard_ids = set() for rec in records: data = rec["kinesis"][...
[ "def", "unpack_kinesis_event", "(", "kinesis_event", ",", "deserializer", "=", "None", ",", "unpacker", "=", "None", ",", "embed_timestamp", "=", "False", ")", ":", "records", "=", "kinesis_event", "[", "\"Records\"", "]", "events", "=", "[", "]", "shard_ids",...
33.535714
0.001035
def update(self): """ Update all the switch values """ self.states = [bool(int(x)) for x in self.get('port list') or '0000']
[ "def", "update", "(", "self", ")", ":", "self", ".", "states", "=", "[", "bool", "(", "int", "(", "x", ")", ")", "for", "x", "in", "self", ".", "get", "(", "'port list'", ")", "or", "'0000'", "]" ]
34.5
0.014184
def get_value(self, key): # type: (str) -> Any """Get a value from the configuration. """ try: return self._dictionary[key] except KeyError: raise ConfigurationError("No such key - {}".format(key))
[ "def", "get_value", "(", "self", ",", "key", ")", ":", "# type: (str) -> Any", "try", ":", "return", "self", ".", "_dictionary", "[", "key", "]", "except", "KeyError", ":", "raise", "ConfigurationError", "(", "\"No such key - {}\"", ".", "format", "(", "key", ...
31.75
0.011494
def _aggregate(self, instanceId, container, value, subKey = None): """Performs stat aggregation.""" # Get the aggregator. if instanceId not in self._aggregators: self._aggregators[instanceId] = _Stats.getAggregator(instanceId, self.__name) aggregator = self._aggregators[instanceId] # If we a...
[ "def", "_aggregate", "(", "self", ",", "instanceId", ",", "container", ",", "value", ",", "subKey", "=", "None", ")", ":", "# Get the aggregator.", "if", "instanceId", "not", "in", "self", ".", "_aggregators", ":", "self", ".", "_aggregators", "[", "instance...
37.3125
0.013072
def max_lv_count(self): """ Returns the maximum allowed logical volume count. """ self.open() count = lvm_vg_get_max_lv(self.handle) self.close() return count
[ "def", "max_lv_count", "(", "self", ")", ":", "self", ".", "open", "(", ")", "count", "=", "lvm_vg_get_max_lv", "(", "self", ".", "handle", ")", "self", ".", "close", "(", ")", "return", "count" ]
25.875
0.009346
def clean(bld): '''removes the build files''' try: proj=Environment.Environment(Options.lockfile) except IOError: raise Utils.WafError('Nothing to clean (project not configured)') bld.load_dirs(proj[SRCDIR],proj[BLDDIR]) bld.load_envs() bld.is_install=0 bld.add_subdirs([os.path.split(Utils.g_module.root_path...
[ "def", "clean", "(", "bld", ")", ":", "try", ":", "proj", "=", "Environment", ".", "Environment", "(", "Options", ".", "lockfile", ")", "except", "IOError", ":", "raise", "Utils", ".", "WafError", "(", "'Nothing to clean (project not configured)'", ")", "bld",...
25.428571
0.04607
def newVersion(): """increments version counter in swhlab/version.py""" version=None fname='../swhlab/version.py' with open(fname) as f: raw=f.read().split("\n") for i,line in enumerate(raw): if line.startswith("__counter__"): if version is None: ...
[ "def", "newVersion", "(", ")", ":", "version", "=", "None", "fname", "=", "'../swhlab/version.py'", "with", "open", "(", "fname", ")", "as", "f", ":", "raw", "=", "f", ".", "read", "(", ")", ".", "split", "(", "\"\\n\"", ")", "for", "i", ",", "line...
37.857143
0.018416
def tripledes_cbc_pkcs5_decrypt(key, data, iv): """ Decrypts 3DES ciphertext in either 2 or 3 key mode :param key: The encryption key - a byte string 16 or 24 bytes long (2 or 3 key mode) :param data: The ciphertext - a byte string :param iv: The initialization vector used...
[ "def", "tripledes_cbc_pkcs5_decrypt", "(", "key", ",", "data", ",", "iv", ")", ":", "if", "len", "(", "key", ")", "!=", "16", "and", "len", "(", "key", ")", "!=", "24", ":", "raise", "ValueError", "(", "pretty_message", "(", "'''\n key must be 1...
27.953488
0.002412
def reduce(self, agg=operator.add, acc=None): """ Submit all tasks and reduce the results """ return self.submit_all().reduce(agg, acc)
[ "def", "reduce", "(", "self", ",", "agg", "=", "operator", ".", "add", ",", "acc", "=", "None", ")", ":", "return", "self", ".", "submit_all", "(", ")", ".", "reduce", "(", "agg", ",", "acc", ")" ]
32.6
0.011976
def predicted_state_vec(self): '''The predicted state vector for the next time point From Welch eqn 1.9 ''' if not self.has_cached_predicted_state_vec: self.p_state_vec = dot_n( self.translation_matrix, self.state_vec[:, :, np.newaxis])[:,:,0]...
[ "def", "predicted_state_vec", "(", "self", ")", ":", "if", "not", "self", ".", "has_cached_predicted_state_vec", ":", "self", ".", "p_state_vec", "=", "dot_n", "(", "self", ".", "translation_matrix", ",", "self", ".", "state_vec", "[", ":", ",", ":", ",", ...
34.3
0.011364
def plot_sfs_scaled(*args, **kwargs): """Plot a scaled site frequency spectrum. Parameters ---------- s : array_like, int, shape (n_chromosomes,) Site frequency spectrum. yscale : string, optional Y axis scale. bins : int or array_like, int, optional Allele count bins. ...
[ "def", "plot_sfs_scaled", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "kwargs", ".", "setdefault", "(", "'yscale'", ",", "'linear'", ")", "ax", "=", "plot_sfs", "(", "*", "args", ",", "*", "*", "kwargs", ")", "ax", ".", "set_ylabel", "(", ...
31.636364
0.000929
def _GenerateSummary(self): """Generate a summary of the warnings and errors. Returns: The generated HTML as a string. """ items = [] if self._notices: items.append('notices: %d' % self._notice_count) if self._dataset_errors: items.append('errors: %d' % self._error_count) ...
[ "def", "_GenerateSummary", "(", "self", ")", ":", "items", "=", "[", "]", "if", "self", ".", "_notices", ":", "items", ".", "append", "(", "'notices: %d'", "%", "self", ".", "_notice_count", ")", "if", "self", ".", "_dataset_errors", ":", "items", ".", ...
30.944444
0.010453
def check_response(self, response): """ Checks that a JSON response from the WebDriver does not have an error. :Args: - response - The JSON response from the WebDriver server as a dictionary object. :Raises: If the response contains an error message. """ ...
[ "def", "check_response", "(", "self", ",", "response", ")", ":", "status", "=", "response", ".", "get", "(", "'status'", ",", "None", ")", "if", "status", "is", "None", "or", "status", "==", "ErrorCode", ".", "SUCCESS", ":", "return", "value", "=", "No...
46.007407
0.000788
def load_config(self): """ Loads the config-file """ self.__config = {} # Parse sections, its options and put it in self.config. for section in self.sections: self.__config[section] = {} options = self.parser.options(section) # Parse...
[ "def", "load_config", "(", "self", ")", ":", "self", ".", "__config", "=", "{", "}", "# Parse sections, its options and put it in self.config.", "for", "section", "in", "self", ".", "sections", ":", "self", ".", "__config", "[", "section", "]", "=", "{", "}", ...
38.9
0.001881
def decrypt(source_text, passphrase, debug_stmt=None): """ Returns plain text from *source_text*, a base64 AES encrypted string as generated with openssl. $ echo '_source_text_' | openssl aes-256-cbc -a -k _passphrase_ -p salt=... key=... iv=... _full_encrypted_ ...
[ "def", "decrypt", "(", "source_text", ",", "passphrase", ",", "debug_stmt", "=", "None", ")", ":", "if", "debug_stmt", "is", "None", ":", "debug_stmt", "=", "\"decrypt\"", "full_encrypted", "=", "b64decode", "(", "source_text", ")", "salt", "=", "full_encrypte...
33.242424
0.001771