text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def customdata(self, lookup, default=None): """ Args: lookup: the custom data file default: the optional value to return if lookup failed; returns None if not set Returns: The custom data returned from the file 'lookup' or default/None if no match found """ try: if lookup in ...
[ "def", "customdata", "(", "self", ",", "lookup", ",", "default", "=", "None", ")", ":", "try", ":", "if", "lookup", "in", "EFConfig", ".", "CUSTOM_DATA", ":", "return", "EFConfig", ".", "CUSTOM_DATA", "[", "lookup", "]", "else", ":", "return", "default",...
30.266667
18.4
def get_type(obj, **kwargs): """Return the type of an object. Do some regex to remove the "<class..." bit.""" t = type(obj) s = extract_type(str(t)) return 'Type: {}'.format(s)
[ "def", "get_type", "(", "obj", ",", "*", "*", "kwargs", ")", ":", "t", "=", "type", "(", "obj", ")", "s", "=", "extract_type", "(", "str", "(", "t", ")", ")", "return", "'Type: {}'", ".", "format", "(", "s", ")" ]
26.857143
19.428571
def getcoef(self): """Get final coefficient map array.""" global mp_Z_Y1 return np.swapaxes(mp_Z_Y1, 0, self.xstep.cri.axisK+1)[0]
[ "def", "getcoef", "(", "self", ")", ":", "global", "mp_Z_Y1", "return", "np", ".", "swapaxes", "(", "mp_Z_Y1", ",", "0", ",", "self", ".", "xstep", ".", "cri", ".", "axisK", "+", "1", ")", "[", "0", "]" ]
30.2
21
def get_daemon_stats(self, details=False): # pylint: disable=unused-argument """Get state of modules and create a scheme for stats data of daemon This may be overridden in subclasses (and it is...) :return: A dict with the following structure :: { 'modules':...
[ "def", "get_daemon_stats", "(", "self", ",", "details", "=", "False", ")", ":", "# pylint: disable=unused-argument", "res", "=", "self", ".", "get_id", "(", ")", "res", ".", "update", "(", "{", "\"program_start\"", ":", "self", ".", "program_start", ",", "\"...
40.891304
23.782609
def weighted_random_choice(items): """ Returns a weighted random choice from a list of items. :param items: A list of tuples (object, weight) :return: A random object, whose likelihood is proportional to its weight. """ l = list(items) r = random.random() * sum([i[1] for i in l]) for x, ...
[ "def", "weighted_random_choice", "(", "items", ")", ":", "l", "=", "list", "(", "items", ")", "r", "=", "random", ".", "random", "(", ")", "*", "sum", "(", "[", "i", "[", "1", "]", "for", "i", "in", "l", "]", ")", "for", "x", ",", "p", "in", ...
29.615385
16.692308
def get_authserver(self, domainid, serverid): """Get an Authentication server""" return self.api_call( ENDPOINTS['authservers']['get'], dict(domainid=domainid, serverid=serverid))
[ "def", "get_authserver", "(", "self", ",", "domainid", ",", "serverid", ")", ":", "return", "self", ".", "api_call", "(", "ENDPOINTS", "[", "'authservers'", "]", "[", "'get'", "]", ",", "dict", "(", "domainid", "=", "domainid", ",", "serverid", "=", "ser...
43
7
def end(self): """Close the V interface. Args:: No argument Returns:: None C library equivalent : Vend """ # Note: Vend is just a macro; use 'Vfinish' instead # Note also the the same C function is ...
[ "def", "end", "(", "self", ")", ":", "# Note: Vend is just a macro; use 'Vfinish' instead", "# Note also the the same C function is used to end", "# the VS interface", "_checkErr", "(", "'vend'", ",", "_C", ".", "Vfinish", "(", "self", ".", "_hdf_inst", ".", "_id", ")", ...
23.85
22.65
def Assign(target, source): """Build an assignment statement""" if not isinstance(target, list): target = [target] if not isinstance(source, list): source.prefix = u" " source = [source] return Node(syms.atom, target + [Leaf(token.EQUAL, u"=", prefix=u" ")] + sou...
[ "def", "Assign", "(", "target", ",", "source", ")", ":", "if", "not", "isinstance", "(", "target", ",", "list", ")", ":", "target", "=", "[", "target", "]", "if", "not", "isinstance", "(", "source", ",", "list", ")", ":", "source", ".", "prefix", "...
31.5
15
def cleanup(self): """ Drops any existing work tables, as returned by :meth:`~giraffez.load.TeradataBulkLoad.tables`. :raises `giraffez.TeradataPTError`: if a Teradata error ocurred """ threads = [] for i, table in enumerate(filter(lambda x: self.mload.exists(x),...
[ "def", "cleanup", "(", "self", ")", ":", "threads", "=", "[", "]", "for", "i", ",", "table", "in", "enumerate", "(", "filter", "(", "lambda", "x", ":", "self", ".", "mload", ".", "exists", "(", "x", ")", ",", "self", ".", "tables", ")", ")", ":...
38.066667
21.533333
def scrape_hive_url(mc_url, num_tracks=sys.maxsize, folders=False, custom_path=''): """ Scrape a Hive.co download page. Returns: list: filenames to open """ try: data = get_hive_data(mc_url) except Exception as e: puts_safe(colored.red("Problem downloading ") + mc_url)...
[ "def", "scrape_hive_url", "(", "mc_url", ",", "num_tracks", "=", "sys", ".", "maxsize", ",", "folders", "=", "False", ",", "custom_path", "=", "''", ")", ":", "try", ":", "data", "=", "get_hive_data", "(", "mc_url", ")", "except", "Exception", "as", "e",...
32.536585
21.902439
def reply(request, message_id, form_class=ComposeForm, template_name='django_messages/compose.html', success_url=None, recipient_filter=None, quote_helper=format_quote, subject_template=_(u"Re: %(subject)s"),): """ Prepares the ``form_class`` form for writing a reply to a given message ...
[ "def", "reply", "(", "request", ",", "message_id", ",", "form_class", "=", "ComposeForm", ",", "template_name", "=", "'django_messages/compose.html'", ",", "success_url", "=", "None", ",", "recipient_filter", "=", "None", ",", "quote_helper", "=", "format_quote", ...
41.529412
20.588235
def get_name(self): """Name accessor""" if self.type is not None and self.name.endswith("." + self.type): return self.name[:len(self.name) - len(self.type) - 1] return self.name
[ "def", "get_name", "(", "self", ")", ":", "if", "self", ".", "type", "is", "not", "None", "and", "self", ".", "name", ".", "endswith", "(", "\".\"", "+", "self", ".", "type", ")", ":", "return", "self", ".", "name", "[", ":", "len", "(", "self", ...
41.8
19.2
def _normalize(esfilter): """ TODO: DO NOT USE Data, WE ARE SPENDING TOO MUCH TIME WRAPPING/UNWRAPPING REALLY, WE JUST COLLAPSE CASCADING `and` AND `or` FILTERS """ if esfilter == MATCH_ALL or esfilter == MATCH_NONE or esfilter.isNormal: return esfilter # Log.note("from: " + convert.val...
[ "def", "_normalize", "(", "esfilter", ")", ":", "if", "esfilter", "==", "MATCH_ALL", "or", "esfilter", "==", "MATCH_NONE", "or", "esfilter", ".", "isNormal", ":", "return", "esfilter", "# Log.note(\"from: \" + convert.value2json(esfilter))", "isDiff", "=", "True", "...
32.971429
13.471429
def task_search(self, task_str, **kwargs): """ Query for a subset of tasks by task_id. :param task_str: :return: """ self.prune() result = collections.defaultdict(dict) for task in self._state.get_active_tasks(): if task.id.find(task_str) != -...
[ "def", "task_search", "(", "self", ",", "task_str", ",", "*", "*", "kwargs", ")", ":", "self", ".", "prune", "(", ")", "result", "=", "collections", ".", "defaultdict", "(", "dict", ")", "for", "task", "in", "self", ".", "_state", ".", "get_active_task...
33.428571
14.571429
def copy_and_replace(file_in, file_out, mapping, **kwargs): ''' Copy a file and replace some placeholders with new values. ''' separator = '@@' if 'separator' in kwargs: separator = kwargs['separator'] file_in = open(file_in, 'r') file_out = open(file_out, 'w') s = file_in.read()...
[ "def", "copy_and_replace", "(", "file_in", ",", "file_out", ",", "mapping", ",", "*", "*", "kwargs", ")", ":", "separator", "=", "'@@'", "if", "'separator'", "in", "kwargs", ":", "separator", "=", "kwargs", "[", "'separator'", "]", "file_in", "=", "open", ...
33.733333
15.066667
def get_namespaces(self): """Get a list of namespaces""" cursor = self.cursor cursor.execute('SELECT DISTINCT namespace FROM gauged_statistics') return [namespace for namespace, in cursor]
[ "def", "get_namespaces", "(", "self", ")", ":", "cursor", "=", "self", ".", "cursor", "cursor", ".", "execute", "(", "'SELECT DISTINCT namespace FROM gauged_statistics'", ")", "return", "[", "namespace", "for", "namespace", ",", "in", "cursor", "]" ]
43.2
14.4
def get_email_context(self,**kwargs): ''' Overrides EmailRecipientMixin ''' context = super(TemporaryRegistration,self).get_email_context(**kwargs) context.update({ 'first_name': self.firstName, 'last_name': self.lastName, 'registrationComments': self.comments...
[ "def", "get_email_context", "(", "self", ",", "*", "*", "kwargs", ")", ":", "context", "=", "super", "(", "TemporaryRegistration", ",", "self", ")", ".", "get_email_context", "(", "*", "*", "kwargs", ")", "context", ".", "update", "(", "{", "'first_name'",...
40.117647
22
def GetValues(self, table_names, column_names, condition): """Retrieves values from a table. Args: table_names (list[str]): table names. column_names (list[str]): column names. condition (str): query condition such as "log_source == 'Application Error'". Yields: sqlite3.r...
[ "def", "GetValues", "(", "self", ",", "table_names", ",", "column_names", ",", "condition", ")", ":", "if", "not", "self", ".", "_connection", ":", "raise", "RuntimeError", "(", "'Cannot retrieve values database not opened.'", ")", "if", "condition", ":", "conditi...
29.625
20.375
def present( name, attributes, region=None, key=None, keyid=None, profile=None): ''' Ensure the cloudwatch alarm exists. name Name of the alarm attributes A dict of key/value cloudwatch alarm attributes. region Region to conn...
[ "def", "present", "(", "name", ",", "attributes", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'result'", ":", "True", ",", "'...
31.914286
20.733333
def closure(self): """ Returns a new `Independencies()`-object that additionally contains those `IndependenceAssertions` that are implied by the the current independencies (using with the `semi-graphoid axioms <https://en.wikipedia.org/w/index.php?title=Conditional_independence&oldid=708...
[ "def", "closure", "(", "self", ")", ":", "def", "single_var", "(", "var", ")", ":", "\"Checks if var represents a single variable\"", "if", "not", "hasattr", "(", "var", ",", "'__iter__'", ")", ":", "return", "True", "else", ":", "return", "len", "(", "var",...
38.019048
23.657143
def post_appeals_list(self, creator_id=None, creator_name=None, post_id=None): """Function to return list of appeals (Requires login). Parameters: creator_id (int): The user id of the appeal's creator. creator_name (str): The name of the appeal's creato...
[ "def", "post_appeals_list", "(", "self", ",", "creator_id", "=", "None", ",", "creator_name", "=", "None", ",", "post_id", "=", "None", ")", ":", "params", "=", "{", "'creator_id'", ":", "creator_id", ",", "'creator_name'", ":", "creator_name", ",", "'post_i...
38.866667
15.666667
def _space_in_headerblock(relative_path, contents, linter_options): """Check for space between the filename in a header block and description. like such: # /path/to/filename # # Description """ del relative_path del linter_options check_index = 1 if len(contents) > 0: ...
[ "def", "_space_in_headerblock", "(", "relative_path", ",", "contents", ",", "linter_options", ")", ":", "del", "relative_path", "del", "linter_options", "check_index", "=", "1", "if", "len", "(", "contents", ")", ">", "0", ":", "if", "_line_is_shebang", "(", "...
31.448276
18.62069
def course_modal(context, course=None): """ Django template tag that returns course information to display in a modal. You may pass in a particular course if you like. Otherwise, the modal will look for course context within the parent context. Usage: {% course_modal %} {% course_m...
[ "def", "course_modal", "(", "context", ",", "course", "=", "None", ")", ":", "if", "course", ":", "context", ".", "update", "(", "{", "'course_image_uri'", ":", "course", ".", "get", "(", "'course_image_uri'", ",", "''", ")", ",", "'course_title'", ":", ...
41.875
24.291667
def append(self, data, segment=0): """ Append a single row to an SFrame. Throws a RuntimeError if one or more column's type is incompatible with a type appended. Parameters ---------- data : iterable An iterable representation of a single row. ...
[ "def", "append", "(", "self", ",", "data", ",", "segment", "=", "0", ")", ":", "# Assume this case refers to an SFrame with a single column", "if", "not", "hasattr", "(", "data", ",", "'__iter__'", ")", ":", "data", "=", "[", "data", "]", "self", ".", "_buil...
35.181818
19.272727
def from_moy(cls, moy, leap_year=False): """Create Ladybug Datetime from a minute of the year. Args: moy: An integer value 0 <= and < 525600 """ if not leap_year: num_of_minutes_until_month = (0, 44640, 84960, 129600, 172800, 217440, ...
[ "def", "from_moy", "(", "cls", ",", "moy", ",", "leap_year", "=", "False", ")", ":", "if", "not", "leap_year", ":", "num_of_minutes_until_month", "=", "(", "0", ",", "44640", ",", "84960", ",", "129600", ",", "172800", ",", "217440", ",", "260640", ","...
43.870968
23.548387
def _generate_api_gateway_deployment(self): """ Generate the API Gateway Deployment/Stage, and add to self.tf_conf """ # finally, the deployment # this resource MUST come last dep_on = [] for rtype in sorted(self.tf_conf['resource'].keys()): for rname ...
[ "def", "_generate_api_gateway_deployment", "(", "self", ")", ":", "# finally, the deployment", "# this resource MUST come last", "dep_on", "=", "[", "]", "for", "rtype", "in", "sorted", "(", "self", ".", "tf_conf", "[", "'resource'", "]", ".", "keys", "(", ")", ...
42.842105
16.421053
def scale_image(self, in_fname, out_fname, max_width, max_height): """Scales an image with the same aspect ratio centered in an image with a given max_width and max_height if in_fname == out_fname the image can only be scaled down """ # local import to avoid testing depende...
[ "def", "scale_image", "(", "self", ",", "in_fname", ",", "out_fname", ",", "max_width", ",", "max_height", ")", ":", "# local import to avoid testing dependency on PIL:", "try", ":", "from", "PIL", "import", "Image", "except", "ImportError", ":", "import", "Image", ...
33.5
18.472222
def _update_hash(self, arg): """ Takes an argument and updates the hash. The argument can be an np.array, string, or list of things that are convertable to strings. """ if isinstance(arg, np.ndarray): self.ahash.update(arg.view(np.uint8)) elif isinstance(arg, ...
[ "def", "_update_hash", "(", "self", ",", "arg", ")", ":", "if", "isinstance", "(", "arg", ",", "np", ".", "ndarray", ")", ":", "self", ".", "ahash", ".", "update", "(", "arg", ".", "view", "(", "np", ".", "uint8", ")", ")", "elif", "isinstance", ...
39.454545
9.272727
def _other_endian(typ): """Return the type with the 'other' byte order. Simple types like c_int and so on already have __ctype_be__ and __ctype_le__ attributes which contain the types, for more complicated types only arrays are supported. """ try: return getattr(typ, _OTHER_ENDIAN) ...
[ "def", "_other_endian", "(", "typ", ")", ":", "try", ":", "return", "getattr", "(", "typ", ",", "_OTHER_ENDIAN", ")", "except", "AttributeError", ":", "if", "type", "(", "typ", ")", "==", "_array_type", ":", "return", "_other_endian", "(", "typ", ".", "_...
42.083333
15.166667
def tokenize(self, data, fit=False): """ :param data: a dataframe containing a column to be tokenized :param fit: if True, self.sequence_length will exactly accomodate the largest tokenized sequence length :return: 1D array of tokens with length = rows * sequence_length """ ...
[ "def", "tokenize", "(", "self", ",", "data", ",", "fit", "=", "False", ")", ":", "with", "timer", "(", "'tokenize %s'", "%", "self", ".", "name", ",", "logging", ".", "DEBUG", ")", ":", "cleaned", "=", "self", ".", "series", "(", "data", ")", ".", ...
61.470588
25.352941
def next_tuple(self, latency_in_ns): """Apply updates to the next tuple metrics""" self.update_reduced_metric(self.NEXT_TUPLE_LATENCY, latency_in_ns) self.update_count(self.NEXT_TUPLE_COUNT)
[ "def", "next_tuple", "(", "self", ",", "latency_in_ns", ")", ":", "self", ".", "update_reduced_metric", "(", "self", ".", "NEXT_TUPLE_LATENCY", ",", "latency_in_ns", ")", "self", ".", "update_count", "(", "self", ".", "NEXT_TUPLE_COUNT", ")" ]
49.75
9.5
def get_axis_padding(padding): """ Process a padding value supplied as a tuple or number and returns padding values for x-, y- and z-axis. """ if isinstance(padding, tuple): if len(padding) == 2: xpad, ypad = padding zpad = 0 elif len(padding) == 3: ...
[ "def", "get_axis_padding", "(", "padding", ")", ":", "if", "isinstance", "(", "padding", ",", "tuple", ")", ":", "if", "len", "(", "padding", ")", "==", "2", ":", "xpad", ",", "ypad", "=", "padding", "zpad", "=", "0", "elif", "len", "(", "padding", ...
36.666667
15.444444
def genstis(outname): """ Generate TestCases from cmdfile according to the pattern in patternfile""" pattern="""class stisS%d(countrateCase): def setUp(self): self.obsmode="%s" self.spectrum="%s" self.setglobal(__file__) self.runpy()\n""" speclist=['/grp/hst/cdbs/calspec...
[ "def", "genstis", "(", "outname", ")", ":", "pattern", "=", "\"\"\"class stisS%d(countrateCase):\n def setUp(self):\n self.obsmode=\"%s\"\n self.spectrum=\"%s\"\n self.setglobal(__file__)\n self.runpy()\\n\"\"\"", "speclist", "=", "[", "'/grp/hst/cdbs/calspec/g...
28.263158
17.763158
def _build_field_type_map(base_class): """Create mapping from all $type values to their respective Field classes""" mapping = {} for cls in _get_recursive_subclasses(base_class): if cls.field_type: if isinstance(cls.field_type, tuple): for field_type in cls.field_type: ...
[ "def", "_build_field_type_map", "(", "base_class", ")", ":", "mapping", "=", "{", "}", "for", "cls", "in", "_get_recursive_subclasses", "(", "base_class", ")", ":", "if", "cls", ".", "field_type", ":", "if", "isinstance", "(", "cls", ".", "field_type", ",", ...
38.555556
19
def normalize(self, timestamp, steps=0): ''' Normalize a timestamp according to the interval configuration. Optionally can be used to calculate the timestamp N steps away. ''' # So far, the only commonality with RelativeTime return self.from_bucket( self.to_bucket(timestamp, steps) )
[ "def", "normalize", "(", "self", ",", "timestamp", ",", "steps", "=", "0", ")", ":", "# So far, the only commonality with RelativeTime", "return", "self", ".", "from_bucket", "(", "self", ".", "to_bucket", "(", "timestamp", ",", "steps", ")", ")" ]
43.142857
22
def get_gradebook_form(self, *args, **kwargs): """Pass through to provider GradebookAdminSession.get_gradebook_form_for_update""" # Implemented from kitosid template for - # osid.resource.BinAdminSession.get_bin_form_for_update_template # This method might be a bit sketchy. Time will tel...
[ "def", "get_gradebook_form", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# Implemented from kitosid template for -", "# osid.resource.BinAdminSession.get_bin_form_for_update_template", "# This method might be a bit sketchy. Time will tell.", "if", "isinstance...
60.777778
21.222222
def get_existing_model(model_name): """ Try to find existing model class named `model_name`. :param model_name: String name of the model class. """ try: model_cls = engine.get_document_cls(model_name) log.debug('Model `{}` already exists. Using existing one'.format( model_na...
[ "def", "get_existing_model", "(", "model_name", ")", ":", "try", ":", "model_cls", "=", "engine", ".", "get_document_cls", "(", "model_name", ")", "log", ".", "debug", "(", "'Model `{}` already exists. Using existing one'", ".", "format", "(", "model_name", ")", "...
35.583333
17.833333
def __liftover_coordinates_genomic_indels(self, intersect_region): """ Lift a region that overlaps the genomic occurrence of the retrotransposon to consensus sequence coordinates using just the coordinates (not the full alignment), when they have differing length. This is an internal helper method. ...
[ "def", "__liftover_coordinates_genomic_indels", "(", "self", ",", "intersect_region", ")", ":", "# should never happen, but check anyway...", "consensus_match_length", "=", "self", ".", "consensus_end", "-", "self", ".", "consensus_start", "size_dif", "=", "consensus_match_le...
52.115385
27.884615
def add_handler(self, handler: Handler, group: int = 0): """Use this method to register an update handler. You can register multiple handlers, but at most one handler within a group will be used for a single update. To handle the same update more than once, register your handler using a...
[ "def", "add_handler", "(", "self", ",", "handler", ":", "Handler", ",", "group", ":", "int", "=", "0", ")", ":", "if", "isinstance", "(", "handler", ",", "DisconnectHandler", ")", ":", "self", ".", "disconnect_handler", "=", "handler", ".", "callback", "...
35.73913
22
def list_tokens(opts): ''' List all tokens in the store. :param opts: Salt master config options :returns: List of dicts (tokens) ''' ret = [] for (dirpath, dirnames, filenames) in salt.utils.path.os_walk(opts['token_dir']): for token in filenames: ret.append(token) ...
[ "def", "list_tokens", "(", "opts", ")", ":", "ret", "=", "[", "]", "for", "(", "dirpath", ",", "dirnames", ",", "filenames", ")", "in", "salt", ".", "utils", ".", "path", ".", "os_walk", "(", "opts", "[", "'token_dir'", "]", ")", ":", "for", "token...
26.583333
21.416667
def partial_page(self, page, used_labels): """Allows a page to be marked as already partially used so you can generate a PDF to print on the remaining labels. Parameters ---------- page: positive integer The page number to mark as partially used. The page must not ha...
[ "def", "partial_page", "(", "self", ",", "page", ",", "used_labels", ")", ":", "# Check the page number is valid.", "if", "page", "<=", "self", ".", "page_count", ":", "raise", "ValueError", "(", "\"Page {0:d} has already started, cannot mark used labels now.\"", ".", "...
42.057143
21.057143
def prg_rom(self): """Return the PRG ROM of the ROM file.""" try: return self.raw_data[self.prg_rom_start:self.prg_rom_stop] except IndexError: raise ValueError('failed to read PRG-ROM on ROM.')
[ "def", "prg_rom", "(", "self", ")", ":", "try", ":", "return", "self", ".", "raw_data", "[", "self", ".", "prg_rom_start", ":", "self", ".", "prg_rom_stop", "]", "except", "IndexError", ":", "raise", "ValueError", "(", "'failed to read PRG-ROM on ROM.'", ")" ]
39.5
19.333333
def append(self, value, key=''): """It allows to add child widgets to this. The key allows to access the specific child in this way widget.children[key]. The key have to be numeric and determines the children order in the layout. Args: value (Widget): Child instance to be ap...
[ "def", "append", "(", "self", ",", "value", ",", "key", "=", "''", ")", ":", "if", "type", "(", "value", ")", "in", "(", "list", ",", "tuple", ",", "dict", ")", ":", "if", "type", "(", "value", ")", "==", "dict", ":", "for", "k", "in", "value...
35.641026
19.358974
def delete_and_upload_images(client, image_type, language, base_dir): """ Delete and upload images with given image_type and language. Function will stage delete and stage upload all found images in matching folders. """ print('{0} {1}'.format(image_type, language)) files_in_dir = os.listdi...
[ "def", "delete_and_upload_images", "(", "client", ",", "image_type", ",", "language", ",", "base_dir", ")", ":", "print", "(", "'{0} {1}'", ".", "format", "(", "image_type", ",", "language", ")", ")", "files_in_dir", "=", "os", ".", "listdir", "(", "os", "...
39.833333
16.916667
def update(kernel=False): """ Upgrade all packages, skip obsoletes if ``obsoletes=0`` in ``yum.conf``. Exclude *kernel* upgrades by default. """ manager = MANAGER cmds = {'yum -y --color=never': {False: '--exclude=kernel* update', True: 'update'}} cmd = cmds[manager][kernel] run_as_root...
[ "def", "update", "(", "kernel", "=", "False", ")", ":", "manager", "=", "MANAGER", "cmds", "=", "{", "'yum -y --color=never'", ":", "{", "False", ":", "'--exclude=kernel* update'", ",", "True", ":", "'update'", "}", "}", "cmd", "=", "cmds", "[", "manager",...
34.5
17.7
def duplicated(self, subset=None, keep='first'): """ Return boolean Series denoting duplicate rows, optionally only considering certain columns. Parameters ---------- subset : column label or sequence of labels, optional Only consider certain columns for iden...
[ "def", "duplicated", "(", "self", ",", "subset", "=", "None", ",", "keep", "=", "'first'", ")", ":", "from", "pandas", ".", "core", ".", "sorting", "import", "get_group_index", "from", "pandas", ".", "_libs", ".", "hashtable", "import", "duplicated_int64", ...
37.211538
20.326923
def decode_unicode_string(string): """ Decode string encoded by `unicode_string` """ if string.startswith('[BASE64-DATA]') and string.endswith('[/BASE64-DATA]'): return base64.b64decode(string[len('[BASE64-DATA]'):-len('[/BASE64-DATA]')]) return string
[ "def", "decode_unicode_string", "(", "string", ")", ":", "if", "string", ".", "startswith", "(", "'[BASE64-DATA]'", ")", "and", "string", ".", "endswith", "(", "'[/BASE64-DATA]'", ")", ":", "return", "base64", ".", "b64decode", "(", "string", "[", "len", "("...
39.142857
16.857143
def _find_matching_collections_internally(collections, record): """Find matching collections with internal engine. :param collections: set of collections where search :param record: record to match """ for name, data in iteritems(collections): if _build_query(data['query']).match(record): ...
[ "def", "_find_matching_collections_internally", "(", "collections", ",", "record", ")", ":", "for", "name", ",", "data", "in", "iteritems", "(", "collections", ")", ":", "if", "_build_query", "(", "data", "[", "'query'", "]", ")", ".", "match", "(", "record"...
36.9
12.4
def run_mutation_aggregator(job, mutation_results, univ_options): """ Aggregate all the called mutations. :param dict mutation_results: Dict of dicts of the various mutation callers in a per chromosome format :param dict univ_options: Dict of universal options used by almost all tools :r...
[ "def", "run_mutation_aggregator", "(", "job", ",", "mutation_results", ",", "univ_options", ")", ":", "# Setup an input data structure for the merge function", "out", "=", "{", "}", "for", "chrom", "in", "mutation_results", "[", "'mutect'", "]", ".", "keys", "(", ")...
48.666667
24.777778
def iter(context, resource, **kwargs): """List all resources""" data = utils.sanitize_kwargs(**kwargs) id = data.pop('id', None) subresource = data.pop('subresource', None) data['limit'] = data.get('limit', 20) if subresource: uri = '%s/%s/%s/%s' % (context.dci_cs_api, resource, id, sub...
[ "def", "iter", "(", "context", ",", "resource", ",", "*", "*", "kwargs", ")", ":", "data", "=", "utils", ".", "sanitize_kwargs", "(", "*", "*", "kwargs", ")", "id", "=", "data", ".", "pop", "(", "'id'", ",", "None", ")", "subresource", "=", "data",...
31
17.454545
def resource_reaches_status(self, resource, resource_id, expected_stat='available', msg='resource', max_wait=120): """Wait for an openstack resources status to reach an expected status within a specified time. Useful to confirm that ...
[ "def", "resource_reaches_status", "(", "self", ",", "resource", ",", "resource_id", ",", "expected_stat", "=", "'available'", ",", "msg", "=", "'resource'", ",", "max_wait", "=", "120", ")", ":", "tries", "=", "0", "resource_stat", "=", "resource", ".", "get...
47.567568
22.702703
def get_messages(self, params={}): """ List messages http://dev.wheniwork.com/#listing-messages """ param_list = [(k, params[k]) for k in sorted(params)] url = "/2/messages/?%s" % urlencode(param_list) data = self._get_resource(url) messages = [] ...
[ "def", "get_messages", "(", "self", ",", "params", "=", "{", "}", ")", ":", "param_list", "=", "[", "(", "k", ",", "params", "[", "k", "]", ")", "for", "k", "in", "sorted", "(", "params", ")", "]", "url", "=", "\"/2/messages/?%s\"", "%", "urlencode...
28.066667
16.6
def reset(self): """ Resets the form. """ self.titleedit.set_edit_text("") self.sortedit.set_edit_text("") self.filteredit.set_edit_text("") self.relevantradio.set_state(True) self.pile.focus_item = 0
[ "def", "reset", "(", "self", ")", ":", "self", ".", "titleedit", ".", "set_edit_text", "(", "\"\"", ")", "self", ".", "sortedit", ".", "set_edit_text", "(", "\"\"", ")", "self", ".", "filteredit", ".", "set_edit_text", "(", "\"\"", ")", "self", ".", "r...
34.571429
5.142857
def check_lt(self): """ Check is the POSTed LoginTicket is valid, if yes invalide it :return: ``True`` if the LoginTicket is valid, ``False`` otherwise :rtype: bool """ # save LT for later check lt_valid = self.request.session.get('lt', []) lt...
[ "def", "check_lt", "(", "self", ")", ":", "# save LT for later check", "lt_valid", "=", "self", ".", "request", ".", "session", ".", "get", "(", "'lt'", ",", "[", "]", ")", "lt_send", "=", "self", ".", "request", ".", "POST", ".", "get", "(", "'lt'", ...
39.857143
19.095238
def get_api_required_params(self): """ List with required params :return: Dictionary with API parameters :raises ValueError: If value of __class__.required_params is not list :rtype: list """ result = self.required_params if type(result) != list: rais...
[ "def", "get_api_required_params", "(", "self", ")", ":", "result", "=", "self", ".", "required_params", "if", "type", "(", "result", ")", "!=", "list", ":", "raise", "ValueError", "(", "'{}.required_params should return list'", ".", "format", "(", "self", ".", ...
32.066667
15.133333
def reduce_to_cycles(self): """ Iteratively eliminate leafs to reduce the set of objects to only those that build cycles. Return the reduced graph. If there are no cycles, None is returned. """ if not self._reduced: reduced = copy(self) reduced.obj...
[ "def", "reduce_to_cycles", "(", "self", ")", ":", "if", "not", "self", ".", "_reduced", ":", "reduced", "=", "copy", "(", "self", ")", "reduced", ".", "objects", "=", "self", ".", "objects", "[", ":", "]", "reduced", ".", "metadata", "=", "[", "]", ...
37.090909
11.272727
def parse_value(self, querydict): """ extract value extarct value from querydict and convert it to native missing and empty values result to None """ value = self.field.get_value(querydict) if value in (None, fields.empty, ''): return None return self...
[ "def", "parse_value", "(", "self", ",", "querydict", ")", ":", "value", "=", "self", ".", "field", ".", "get_value", "(", "querydict", ")", "if", "value", "in", "(", "None", ",", "fields", ".", "empty", ",", "''", ")", ":", "return", "None", "return"...
34.2
11.4
def save(self): """ Saves changes made to the locally cached Document object's data structures to the remote database. If the document does not exist remotely then it is created in the remote database. If the object does exist remotely then the document is updated remotely. In...
[ "def", "save", "(", "self", ")", ":", "headers", "=", "{", "}", "headers", ".", "setdefault", "(", "'Content-Type'", ",", "'application/json'", ")", "if", "not", "self", ".", "exists", "(", ")", ":", "self", ".", "create", "(", ")", "return", "put_resp...
39.565217
18.695652
def extract_spans(html_string): """ Creates a list of the spanned cell groups of [row, column] pairs. Parameters ---------- html_string : str Returns ------- list of lists of lists of int """ try: from bs4 import BeautifulSoup except ImportError: print("ERRO...
[ "def", "extract_spans", "(", "html_string", ")", ":", "try", ":", "from", "bs4", "import", "BeautifulSoup", "except", "ImportError", ":", "print", "(", "\"ERROR: You must have BeautifulSoup to use html2data\"", ")", "return", "soup", "=", "BeautifulSoup", "(", "html_s...
25.147541
19.245902
def run(self): """Runs the sampler.""" if self.target_eff_nsamples and self.checkpoint_interval is None: raise ValueError("A checkpoint interval must be set if " "targetting an effective number of samples") # get the starting number of samples: # ...
[ "def", "run", "(", "self", ")", ":", "if", "self", ".", "target_eff_nsamples", "and", "self", ".", "checkpoint_interval", "is", "None", ":", "raise", "ValueError", "(", "\"A checkpoint interval must be set if \"", "\"targetting an effective number of samples\"", ")", "#...
52.410714
18.892857
def open(self, _file, target=DEFAULT_TARGET): """ Open the existing file for reading. @param _file : A filename of file descriptor. @param target: A user-specific BFD target name. @return : None """ # Close any existing BFD structure instance. self.clos...
[ "def", "open", "(", "self", ",", "_file", ",", "target", "=", "DEFAULT_TARGET", ")", ":", "# Close any existing BFD structure instance. ", "self", ".", "close", "(", ")", "#", "# STEP 1. Open the BFD pointer.", "#", "# Determine if the user passed a file-descriptor or a _fi...
36.846939
22.418367
def get_file_out(build_index, python_name, jenkin_name): """ This function will grab one log file from Jenkins and save it to local user directory :param g_jenkins_url: :param build_index: :param airline_java: :param airline_java_tail: :return: """ global g_log_base_dir global g_...
[ "def", "get_file_out", "(", "build_index", ",", "python_name", ",", "jenkin_name", ")", ":", "global", "g_log_base_dir", "global", "g_jenkins_url", "global", "g_log_base_dir", "directoryB", "=", "g_log_base_dir", "+", "'/Build'", "+", "str", "(", "build_index", ")",...
31.913043
21.304348
def textfsm_extractor(cls, template_name, raw_text): """ Applies a TextFSM template over a raw text and return the matching table. Main usage of this method will be to extract data form a non-structured output from a network device and return the values in a table format. :param cls: Instance of t...
[ "def", "textfsm_extractor", "(", "cls", ",", "template_name", ",", "raw_text", ")", ":", "textfsm_data", "=", "list", "(", ")", "cls", ".", "__class__", ".", "__name__", ".", "replace", "(", "'Driver'", ",", "''", ")", "current_dir", "=", "os", ".", "pat...
36.254902
21.980392
def check_output(*popenargs, **kwargs): r"""Run command with arguments and return its output as a byte string. If the exit code was non-zero it raises a CalledProcessError. The CalledProcessError object will have the return code in the returncode attribute and output in the output attribute. The ...
[ "def", "check_output", "(", "*", "popenargs", ",", "*", "*", "kwargs", ")", ":", "if", "'stdout'", "in", "kwargs", ":", "raise", "ValueError", "(", "'stdout argument not allowed, it will be overridden.'", ")", "process", "=", "Popen", "(", "stdout", "=", "PIPE",...
39.096774
19.516129
def run_matrix(self, matrix_definition, document): """ Running pipeline via a matrix. Args: matrix_definition (dict): one concrete matrix item. document (dict): spline document (complete) as loaded from yaml file. """ matrix = Matrix(matrix_definition, 'm...
[ "def", "run_matrix", "(", "self", ",", "matrix_definition", ",", "document", ")", ":", "matrix", "=", "Matrix", "(", "matrix_definition", ",", "'matrix(parallel)'", "in", "document", ")", "process_data", "=", "MatrixProcessData", "(", ")", "process_data", ".", "...
38
18.941176
def from_mpl(fig, savefig_kw=None): """Create a SVG figure from a ``matplotlib`` figure. Parameters ---------- fig : matplotlib.Figure instance savefig_kw : dict keyword arguments to be passed to matplotlib's `savefig` Returns ------- SVGFigure newly create...
[ "def", "from_mpl", "(", "fig", ",", "savefig_kw", "=", "None", ")", ":", "fid", "=", "StringIO", "(", ")", "if", "savefig_kw", "is", "None", ":", "savefig_kw", "=", "{", "}", "try", ":", "fig", ".", "savefig", "(", "fid", ",", "format", "=", "'svg'...
22.037037
23.277778
def measurement_key( val: Any, default: Any = RaiseTypeErrorIfNotProvided): """Get the measurement key for the given value. Args: val: The value which has the measurement key.. default: Determines the fallback behavior when `val` doesn't have a measurement key. If `d...
[ "def", "measurement_key", "(", "val", ":", "Any", ",", "default", ":", "Any", "=", "RaiseTypeErrorIfNotProvided", ")", ":", "getter", "=", "getattr", "(", "val", ",", "'_measurement_key_'", ",", "None", ")", "result", "=", "NotImplemented", "if", "getter", "...
39.305556
24.75
def tokens_create(name, user, scopes, internal): """Create a personal OAuth token.""" token = Token.create_personal( name, user.id, scopes=scopes, is_internal=internal) db.session.commit() click.secho(token.access_token, fg='blue')
[ "def", "tokens_create", "(", "name", ",", "user", ",", "scopes", ",", "internal", ")", ":", "token", "=", "Token", ".", "create_personal", "(", "name", ",", "user", ".", "id", ",", "scopes", "=", "scopes", ",", "is_internal", "=", "internal", ")", "db"...
41.666667
9.333333
def _reorient_3d(image): """ Reorganize the data for a 3d nifti """ # Create empty array where x,y,z correspond to LR (sagittal), PA (coronal), IS (axial) directions and the size # of the array in each direction is the same with the corresponding direction of the input image. new_image = numpy.z...
[ "def", "_reorient_3d", "(", "image", ")", ":", "# Create empty array where x,y,z correspond to LR (sagittal), PA (coronal), IS (axial) directions and the size", "# of the array in each direction is the same with the corresponding direction of the input image.", "new_image", "=", "numpy", ".", ...
58.090909
34.636364
def _ip_int_from_string(self, ip_str): """Turn an IPv6 ip_str into an integer. Args: ip_str: A string, the IPv6 ip_str. Returns: A long, the IPv6 ip_str. Raises: AddressValueError: if ip_str isn't a valid IPv6 Address. """ parts = i...
[ "def", "_ip_int_from_string", "(", "self", ",", "ip_str", ")", ":", "parts", "=", "ip_str", ".", "split", "(", "':'", ")", "# An IPv6 address needs at least 2 colons (3 parts).", "if", "len", "(", "parts", ")", "<", "3", ":", "raise", "AddressValueError", "(", ...
37.051282
18.74359
def get_child(self): """ Find file or folder at the remote_path :return: File|Folder """ path_parts = self.remote_path.split(os.sep) return self._get_child_recurse(path_parts, self.node)
[ "def", "get_child", "(", "self", ")", ":", "path_parts", "=", "self", ".", "remote_path", ".", "split", "(", "os", ".", "sep", ")", "return", "self", ".", "_get_child_recurse", "(", "path_parts", ",", "self", ".", "node", ")" ]
32.571429
10
def filter(self, criteria, applyto='measurement', ID=None): """ Filter measurements according to given criteria. Retain only Measurements for which criteria returns True. TODO: add support for multiple criteria Parameters ---------- criteria : callable ...
[ "def", "filter", "(", "self", ",", "criteria", ",", "applyto", "=", "'measurement'", ",", "ID", "=", "None", ")", ":", "fil", "=", "criteria", "new", "=", "self", ".", "copy", "(", ")", "if", "isinstance", "(", "applyto", ",", "collections", ".", "Ma...
37.97619
21.690476
def depends(self, offset=0, count=25): '''Return all the currently dependent jobs''' return self.client('jobs', 'depends', self.name, offset, count)
[ "def", "depends", "(", "self", ",", "offset", "=", "0", ",", "count", "=", "25", ")", ":", "return", "self", ".", "client", "(", "'jobs'", ",", "'depends'", ",", "self", ".", "name", ",", "offset", ",", "count", ")" ]
54
15.333333
def _on_timeout(): """Invoked periodically to ensure that metrics that have been collected are submitted to InfluxDB. :rtype: tornado.concurrent.Future or None """ global _buffer_size LOGGER.debug('No metrics submitted in the last %.2f seconds', _timeout_interval / 1000.0) ...
[ "def", "_on_timeout", "(", ")", ":", "global", "_buffer_size", "LOGGER", ".", "debug", "(", "'No metrics submitted in the last %.2f seconds'", ",", "_timeout_interval", "/", "1000.0", ")", "_buffer_size", "=", "_pending_measurements", "(", ")", "if", "_buffer_size", "...
28.4
16.533333
def post_status( app, user, status, visibility='public', media_ids=None, sensitive=False, spoiler_text=None, in_reply_to_id=None ): """ Posts a new status. https://github.com/tootsuite/documentation/blob/master/Using-the-API/API.md#posting-a-new-status """ # Idempote...
[ "def", "post_status", "(", "app", ",", "user", ",", "status", ",", "visibility", "=", "'public'", ",", "media_ids", "=", "None", ",", "sensitive", "=", "False", ",", "spoiler_text", "=", "None", ",", "in_reply_to_id", "=", "None", ")", ":", "# Idempotency ...
27.444444
19
def vminug(vin, ndim): """ Negate a double precision vector of arbitrary dimension. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/vminug_c.html :param vin: ndim-dimensional double precision vector to be negated. :type vin: Array of floats :param ndim: Dimension of vin. :type nd...
[ "def", "vminug", "(", "vin", ",", "ndim", ")", ":", "vin", "=", "stypes", ".", "toDoubleVector", "(", "vin", ")", "vout", "=", "stypes", ".", "emptyDoubleVector", "(", "ndim", ")", "ndim", "=", "ctypes", ".", "c_int", "(", "ndim", ")", "libspice", "....
33.222222
15.777778
def scan(backend, timeout=10): """Scan for miflora devices. Note: this must be run as root! """ result = [] for (mac, name) in backend.scan_for_devices(timeout): if (name is not None and name.lower() in VALID_DEVICE_NAMES) or \ mac is not None and mac.upper().startswith(DEVI...
[ "def", "scan", "(", "backend", ",", "timeout", "=", "10", ")", ":", "result", "=", "[", "]", "for", "(", "mac", ",", "name", ")", "in", "backend", ".", "scan_for_devices", "(", "timeout", ")", ":", "if", "(", "name", "is", "not", "None", "and", "...
34.363636
17.181818
def sort(args): """ %prog sort fastafile Sort a list of sequences and output with sorted IDs, etc. """ p = OptionParser(sort.__doc__) p.add_option("--sizes", default=False, action="store_true", help="Sort by decreasing size [default: %default]") opts, args = p.parse_args(a...
[ "def", "sort", "(", "args", ")", ":", "p", "=", "OptionParser", "(", "sort", ".", "__doc__", ")", "p", ".", "add_option", "(", "\"--sizes\"", ",", "default", "=", "False", ",", "action", "=", "\"store_true\"", ",", "help", "=", "\"Sort by decreasing size [...
28.567568
20.513514
def focus_next_unfolded(self): """focus next unfolded message in depth first order""" self.focus_property(lambda x: not x.is_collapsed(x.root), self._tree.next_position)
[ "def", "focus_next_unfolded", "(", "self", ")", ":", "self", ".", "focus_property", "(", "lambda", "x", ":", "not", "x", ".", "is_collapsed", "(", "x", ".", "root", ")", ",", "self", ".", "_tree", ".", "next_position", ")" ]
52.5
12
def _ReadStorageDataTypeDefinition( self, definitions_registry, definition_values, data_type_definition_class, definition_name, supported_attributes, is_member=False): """Reads a storage data type definition. Args: definitions_registry (DataTypeDefinitionsRegistry): data type definitions ...
[ "def", "_ReadStorageDataTypeDefinition", "(", "self", ",", "definitions_registry", ",", "definition_values", ",", "data_type_definition_class", ",", "definition_name", ",", "supported_attributes", ",", "is_member", "=", "False", ")", ":", "if", "is_member", ":", "suppor...
40.313725
23.509804
def to_dict(self, minimal=False): """Returns the representation for serialization""" data = collections.OrderedDict() if minimal: # In the minimal representation we just output the value data['value'] = self._to_python_type(self.value) else: # I...
[ "def", "to_dict", "(", "self", ",", "minimal", "=", "False", ")", ":", "data", "=", "collections", ".", "OrderedDict", "(", ")", "if", "minimal", ":", "# In the minimal representation we just output the value", "data", "[", "'value'", "]", "=", "self", ".", "_...
32.458333
28.041667
def Parse(self): """Parse program output.""" (start_line, lang) = self.ParseDesc() if start_line < 0: return if 'python' == lang: self.ParsePythonFlags(start_line) elif 'c' == lang: self.ParseCFlags(start_line) elif 'java' == lang: self.ParseJavaFlags(start_line)
[ "def", "Parse", "(", "self", ")", ":", "(", "start_line", ",", "lang", ")", "=", "self", ".", "ParseDesc", "(", ")", "if", "start_line", "<", "0", ":", "return", "if", "'python'", "==", "lang", ":", "self", ".", "ParsePythonFlags", "(", "start_line", ...
27.363636
12
def match(self, feature, gps_precision=None, profile='mapbox.driving'): """Match features to OpenStreetMap data.""" profile = self._validate_profile(profile) feature = self._validate_feature(feature) geojson_line_feature = json.dumps(feature) uri = URITemplate(self.baseuri + '/...
[ "def", "match", "(", "self", ",", "feature", ",", "gps_precision", "=", "None", ",", "profile", "=", "'mapbox.driving'", ")", ":", "profile", "=", "self", ".", "_validate_profile", "(", "profile", ")", "feature", "=", "self", ".", "_validate_feature", "(", ...
32.695652
22.913043
def loads_json_or_yaml(file_path, content): """ Load JSON or YAML depending on the file extension. Returns a dict """ if os.path.splitext(file_path)[1] == ".json": return json.loads(content) else: return inginious.common.custom_yaml.load(content)
[ "def", "loads_json_or_yaml", "(", "file_path", ",", "content", ")", ":", "if", "os", ".", "path", ".", "splitext", "(", "file_path", ")", "[", "1", "]", "==", "\".json\"", ":", "return", "json", ".", "loads", "(", "content", ")", "else", ":", "return",...
44.833333
11
def get_attrib(self, et_node, prefixed_attrib): """Get a prefixed attribute like 'rdf:resource' from ET node.""" prefix, attrib = prefixed_attrib.split(':') return et_node.get('{{{0}}}{1}'.format(self.namespaces[prefix], attrib))
[ "def", "get_attrib", "(", "self", ",", "et_node", ",", "prefixed_attrib", ")", ":", "prefix", ",", "attrib", "=", "prefixed_attrib", ".", "split", "(", "':'", ")", "return", "et_node", ".", "get", "(", "'{{{0}}}{1}'", ".", "format", "(", "self", ".", "na...
59.2
12.8
def xpat_gen(self, header, msgid_range, *pattern): """Generator for the XPAT command. """ args = " ".join( [header, utils.unparse_msgid_range(msgid_range)] + list(pattern) ) code, message = self.command("XPAT", args) if code != 221: raise NNTPRepl...
[ "def", "xpat_gen", "(", "self", ",", "header", ",", "msgid_range", ",", "*", "pattern", ")", ":", "args", "=", "\" \"", ".", "join", "(", "[", "header", ",", "utils", ".", "unparse_msgid_range", "(", "msgid_range", ")", "]", "+", "list", "(", "pattern"...
31.615385
17.384615
def tune(runner, kernel_options, device_options, tuning_options): """ Find the best performing kernel configuration in the parameter space :params runner: A runner from kernel_tuner.runners :type runner: kernel_tuner.runner :param kernel_options: A dictionary with all options for the kernel. :type...
[ "def", "tune", "(", "runner", ",", "kernel_options", ",", "device_options", ",", "tuning_options", ")", ":", "results", "=", "[", "]", "cache", "=", "{", "}", "method", "=", "tuning_options", ".", "method", "#scale variables in x to make 'eps' relevant for multiple ...
33.26
25.2
def set_current_canvas(canvas): """ Make a canvas active. Used primarily by the canvas itself. """ # Notify glir canvas.context._do_CURRENT_command = True # Try to be quick if canvasses and canvasses[-1]() is canvas: return # Make this the current cc = [c() for c in canvasses if...
[ "def", "set_current_canvas", "(", "canvas", ")", ":", "# Notify glir ", "canvas", ".", "context", ".", "_do_CURRENT_command", "=", "True", "# Try to be quick", "if", "canvasses", "and", "canvasses", "[", "-", "1", "]", "(", ")", "is", "canvas", ":", "return", ...
31.714286
12.214286
def resolve(self, symbol): """ Resolve a symbol using the entrypoint group. :param symbol: The symbol being resolved. :returns: The value of that symbol. If the symbol cannot be found, or if no entrypoint group was passed to the constructor, will re...
[ "def", "resolve", "(", "self", ",", "symbol", ")", ":", "# Search for a corresponding symbol", "if", "symbol", "not", "in", "self", ".", "_resolve_cache", ":", "result", "=", "None", "# Search through entrypoints only if we have a group", "if", "self", ".", "_group", ...
33.806452
18.83871
def cost(self, t_node, branch_length, multiplicity=2.0): ''' returns the cost associated with a branch starting at t_node t_node is time before present, the branch goes back in time Args: - t_node: time of the node - branch_length: branch length, det...
[ "def", "cost", "(", "self", ",", "t_node", ",", "branch_length", ",", "multiplicity", "=", "2.0", ")", ":", "merger_time", "=", "t_node", "+", "branch_length", "return", "self", ".", "integral_merger_rate", "(", "merger_time", ")", "-", "self", ".", "integra...
52
31.230769
def save_scenario(self, scenario_file_path=None): """Save current scenario to a text file. You can use the saved scenario with the batch runner. :param scenario_file_path: A path to the scenario file. :type scenario_file_path: str """ # Validate Input warning_ti...
[ "def", "save_scenario", "(", "self", ",", "scenario_file_path", "=", "None", ")", ":", "# Validate Input", "warning_title", "=", "tr", "(", "'InaSAFE Save Scenario Warning'", ")", "is_valid", ",", "warning_message", "=", "self", ".", "validate_input", "(", ")", "i...
39.255556
19.266667
def add_source(self, name, location, schedule='Daily', op=''): """ handles the data sources used in projects, mainly as an abstract to call the data sources in /lib and /dataTools """ if op == '': op = name + '.log' self.data_sources.append([name, location, s...
[ "def", "add_source", "(", "self", ",", "name", ",", "location", ",", "schedule", "=", "'Daily'", ",", "op", "=", "''", ")", ":", "if", "op", "==", "''", ":", "op", "=", "name", "+", "'.log'", "self", ".", "data_sources", ".", "append", "(", "[", ...
40.75
15.5
async def request_offline_members(self, *guilds): r"""|coro| Requests previously offline members from the guild to be filled up into the :attr:`.Guild.members` cache. This function is usually not called. It should only be used if you have the ``fetch_offline_members`` parameter ...
[ "async", "def", "request_offline_members", "(", "self", ",", "*", "guilds", ")", ":", "if", "any", "(", "not", "g", ".", "large", "or", "g", ".", "unavailable", "for", "g", "in", "guilds", ")", ":", "raise", "InvalidArgument", "(", "'An unavailable or non-...
39.962963
25.851852
def editContactItems(self, nickname, **edits): """ Update the information on the contact items associated with the wrapped L{Person}. @type nickname: C{unicode} @param nickname: New value to use for the I{name} attribute of the L{Person}. @param **edits: map...
[ "def", "editContactItems", "(", "self", ",", "nickname", ",", "*", "*", "edits", ")", ":", "submissions", "=", "[", "]", "for", "paramName", ",", "submission", "in", "edits", ".", "iteritems", "(", ")", ":", "contactType", "=", "self", ".", "contactTypes...
37
16.368421
def match_trailer(self, tokens, item): """Matches typedefs and as patterns.""" internal_assert(len(tokens) > 1 and len(tokens) % 2 == 1, "invalid trailer match tokens", tokens) match, trailers = tokens[0], tokens[1:] for i in range(0, len(trailers), 2): op, arg = trailers[i],...
[ "def", "match_trailer", "(", "self", ",", "tokens", ",", "item", ")", ":", "internal_assert", "(", "len", "(", "tokens", ")", ">", "1", "and", "len", "(", "tokens", ")", "%", "2", "==", "1", ",", "\"invalid trailer match tokens\"", ",", "tokens", ")", ...
49
16.352941
def store_work_results(self, results, collection, md5): """Store the output results of the worker. Args: results: a dictionary. collection: the database collection to store the results in. md5: the md5 of sample data to be updated. """ # Make sure t...
[ "def", "store_work_results", "(", "self", ",", "results", ",", "collection", ",", "md5", ")", ":", "# Make sure the md5 and time stamp is on the data before storing", "results", "[", "'md5'", "]", "=", "md5", "results", "[", "'__time_stamp'", "]", "=", "datetime", "...
46.222222
27.37037
def validate_attachment_location(self, location): """Validate a proposed attachment location. :arg location: String representing location to put attachment. ~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~- PURPOSE: Raises an exception if attachment location is bad. ...
[ "def", "validate_attachment_location", "(", "self", ",", "location", ")", ":", "if", "not", "re", ".", "compile", "(", "self", ".", "valid_attachment_loc_re", ")", ".", "match", "(", "location", ")", ":", "raise", "ValueError", "(", "'Bad chars in attachment loc...
41.3125
23.8125
def GetMetadataAttribute(self, attribute_name): """Retrieves the metadata attribute. Args: attribute_name (str): name of the metadata attribute. Returns: str: the metadata attribute or None. Raises: RuntimeError: if more than one value is found in the database. """ table_nam...
[ "def", "GetMetadataAttribute", "(", "self", ",", "attribute_name", ")", ":", "table_name", "=", "'metadata'", "has_table", "=", "self", ".", "_database_file", ".", "HasTable", "(", "table_name", ")", "if", "not", "has_table", ":", "return", "None", "column_names...
24.96875
21.9375
def _draw_ascii_graph(self, field): '''Draw graph from field double nested list, format field[x][y] = char''' row_strings = [] for y in range(len(field[0])): row = '' for x in range(len(field)): row += field[x][y] row_strings.insert(0, row) ...
[ "def", "_draw_ascii_graph", "(", "self", ",", "field", ")", ":", "row_strings", "=", "[", "]", "for", "y", "in", "range", "(", "len", "(", "field", "[", "0", "]", ")", ")", ":", "row", "=", "''", "for", "x", "in", "range", "(", "len", "(", "fie...
38.1
11.1
def log_request(self, code='-', size='-'): # pylint: disable=unused-argument """ This function is called during :meth:`send_response`. We override it to get a little more information logged in a somewhat better format. We do not use the size method argument. """ ...
[ "def", "log_request", "(", "self", ",", "code", "=", "'-'", ",", "size", "=", "'-'", ")", ":", "# pylint: disable=unused-argument", "self", ".", "log", "(", "'%s: HTTP status %s'", ",", "(", "self", ".", "_get_log_prefix", "(", ")", ",", "code", ")", ",",...
38.454545
13.181818