text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def main_loop_iteration(timeout=None): """Return the number of RemoteDispatcher.handle_read() calls made by this iteration""" prev_nr_read = nr_handle_read asyncore.loop(count=1, timeout=timeout, use_poll=True) return nr_handle_read - prev_nr_read
[ "def", "main_loop_iteration", "(", "timeout", "=", "None", ")", ":", "prev_nr_read", "=", "nr_handle_read", "asyncore", ".", "loop", "(", "count", "=", "1", ",", "timeout", "=", "timeout", ",", "use_poll", "=", "True", ")", "return", "nr_handle_read", "-", ...
43.666667
4.5
def poisson_dist(p1, p2): """ Calculates the Poisson distance between two vectors. p1 can be a sparse matrix, while p2 has to be a dense matrix. """ # ugh... p1_ = p1 + eps p2_ = p2 + eps return np.dot(p1_-p2_, np.log(p1_/p2_))
[ "def", "poisson_dist", "(", "p1", ",", "p2", ")", ":", "# ugh...", "p1_", "=", "p1", "+", "eps", "p2_", "=", "p2", "+", "eps", "return", "np", ".", "dot", "(", "p1_", "-", "p2_", ",", "np", ".", "log", "(", "p1_", "/", "p2_", ")", ")" ]
25.1
17.1
def load_tree(self): """ method iterates thru all objects older than synergy_start_timeperiod parameter in job collections and loads them into this timetable""" timeperiod = settings.settings['synergy_start_timeperiod'] yearly_timeperiod = time_helper.cast_to_time_qualifier(QUALIFIER_YEA...
[ "def", "load_tree", "(", "self", ")", ":", "timeperiod", "=", "settings", ".", "settings", "[", "'synergy_start_timeperiod'", "]", "yearly_timeperiod", "=", "time_helper", ".", "cast_to_time_qualifier", "(", "QUALIFIER_YEARLY", ",", "timeperiod", ")", "monthly_timeper...
77.230769
40.769231
def set_source_tags(self, id, **kwargs): # noqa: E501 """Set all tags associated with a specific source # noqa: E501 # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.set_so...
[ "def", "set_source_tags", "(", "self", ",", "id", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async_req'", ")", ":", "return", "self", ".", "set_source_t...
40.772727
17.772727
def read_token(fd): """ Read a single token (sequence of non-whitespace characters) from the given file object. Notes ----- Consumes the first whitespace character after the token. """ out = '' # Skip initial whitespace. while 1: ch = fd.read(1) if ch.isspace():...
[ "def", "read_token", "(", "fd", ")", ":", "out", "=", "''", "# Skip initial whitespace.", "while", "1", ":", "ch", "=", "fd", ".", "read", "(", "1", ")", "if", "ch", ".", "isspace", "(", ")", ":", "continue", "elif", "len", "(", "ch", ")", "==", ...
20.291667
21.291667
def update_app(id, config): ''' Update the specified app with the given configuration. CLI Example: .. code-block:: bash salt marathon-minion-id marathon.update_app my-app '<config yaml>' ''' if 'id' not in config: config['id'] = id config.pop('version', None) # mirror...
[ "def", "update_app", "(", "id", ",", "config", ")", ":", "if", "'id'", "not", "in", "config", ":", "config", "[", "'id'", "]", "=", "id", "config", ".", "pop", "(", "'version'", ",", "None", ")", "# mirror marathon-ui handling for uris deprecation (see", "# ...
29.763158
19.657895
def calibrate_data(params, raw_data, calib_data): """'Calibrate' raw data, using a user-supplied function.""" start = calib_data.before(datetime.max) if start is None: start = datetime.min start = raw_data.after(start + SECOND) if start is None: return start del calib_data[start:...
[ "def", "calibrate_data", "(", "params", ",", "raw_data", ",", "calib_data", ")", ":", "start", "=", "calib_data", ".", "before", "(", "datetime", ".", "max", ")", "if", "start", "is", "None", ":", "start", "=", "datetime", ".", "min", "start", "=", "ra...
37.107143
13.035714
def get_algorithm(self, name): """ Gets a single algorithm by its unique name. :param str name: Either a fully-qualified XTCE name or an alias in the format ``NAMESPACE/NAME``. :rtype: .Algorithm """ name = adapt_name_for_rest(name) url =...
[ "def", "get_algorithm", "(", "self", ",", "name", ")", ":", "name", "=", "adapt_name_for_rest", "(", "name", ")", "url", "=", "'/mdb/{}/algorithms{}'", ".", "format", "(", "self", ".", "_instance", ",", "name", ")", "response", "=", "self", ".", "_client",...
38
12.285714
def compute_vis_noise(msname, sefd, spw_id=0): """Computes nominal per-visibility noise""" from pyrap.tables import table tab = table(msname) spwtab = table(msname + "/SPECTRAL_WINDOW") freq0 = spwtab.getcol("CHAN_FREQ")[spw_id, 0] wavelength = 300e+6/freq0 bw = spwtab.getcol("CHAN_WIDTH")...
[ "def", "compute_vis_noise", "(", "msname", ",", "sefd", ",", "spw_id", "=", "0", ")", ":", "from", "pyrap", ".", "tables", "import", "table", "tab", "=", "table", "(", "msname", ")", "spwtab", "=", "table", "(", "msname", "+", "\"/SPECTRAL_WINDOW\"", ")"...
39.045455
26.454545
def _append(self, menu): '''append this menu item to a menu''' from MAVProxy.modules.lib.wx_loader import wx submenu = wx.Menu() for i in range(len(self.items)): submenu.AppendRadioItem(self.id()+i, self.items[i], self.description) if self.items[i] == self.initial...
[ "def", "_append", "(", "self", ",", "menu", ")", ":", "from", "MAVProxy", ".", "modules", ".", "lib", ".", "wx_loader", "import", "wx", "submenu", "=", "wx", ".", "Menu", "(", ")", "for", "i", "in", "range", "(", "len", "(", "self", ".", "items", ...
45.444444
11.888889
def doolittle(matrix_a): """ Doolittle's Method for LU-factorization. :param matrix_a: Input matrix (must be a square matrix) :type matrix_a: list, tuple :return: a tuple containing matrices (L,U) :rtype: tuple """ # Initialize L and U matrices matrix_u = [[0.0 for _ in range(len(matrix...
[ "def", "doolittle", "(", "matrix_a", ")", ":", "# Initialize L and U matrices", "matrix_u", "=", "[", "[", "0.0", "for", "_", "in", "range", "(", "len", "(", "matrix_a", ")", ")", "]", "for", "_", "in", "range", "(", "len", "(", "matrix_a", ")", ")", ...
39.551724
19.172414
def draw(self): """ 使用draw方法将图形绘制在窗口里 """ self.update_all() self.vertex_list.draw(self.gl) pyglet.gl.glLoadIdentity()
[ "def", "draw", "(", "self", ")", ":", "self", ".", "update_all", "(", ")", "self", ".", "vertex_list", ".", "draw", "(", "self", ".", "gl", ")", "pyglet", ".", "gl", ".", "glLoadIdentity", "(", ")" ]
29
9.6
def get_custom_label_attribute(self, attribute): """ Get a list of the custom_labels attribute. ie. label_store, symbol, or description. The custom_labels variable could be in a number of formats """ if attribute not in ann_label_fields: raise ValueE...
[ "def", "get_custom_label_attribute", "(", "self", ",", "attribute", ")", ":", "if", "attribute", "not", "in", "ann_label_fields", ":", "raise", "ValueError", "(", "'Invalid attribute specified'", ")", "if", "isinstance", "(", "self", ".", "custom_labels", ",", "pd...
40.393939
17.121212
def visit_and_update(self, visitor_fn): """Create an updated version (if needed) of TernaryConditional via the visitor pattern.""" new_predicate = self.predicate.visit_and_update(visitor_fn) new_if_true = self.if_true.visit_and_update(visitor_fn) new_if_false = self.if_false.visit_and_up...
[ "def", "visit_and_update", "(", "self", ",", "visitor_fn", ")", ":", "new_predicate", "=", "self", ".", "predicate", ".", "visit_and_update", "(", "visitor_fn", ")", "new_if_true", "=", "self", ".", "if_true", ".", "visit_and_update", "(", "visitor_fn", ")", "...
51.916667
19.25
def _read_para_esp_transform(self, code, cbit, clen, *, desc, length, version): """Read HIP ESP_TRANSFORM parameter. Structure of HIP ESP_TRANSFORM parameter [RFC 7402]: 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2...
[ "def", "_read_para_esp_transform", "(", "self", ",", "code", ",", "cbit", ",", "clen", ",", "*", ",", "desc", ",", "length", ",", "version", ")", ":", "if", "clen", "%", "2", "!=", "0", ":", "raise", "ProtocolError", "(", "f'HIPv{version}: [Parano {code}] ...
46.565217
27.5
def date_factory(value, datatype_cls, validation_level=None): """ Creates a :class:`DT <hl7apy.base_datatypes.DT>` object The value in input must be a string parsable with :meth:`datetime.strptime`. The date format is chosen according to the length of the value as stated in this table: +-------+--...
[ "def", "date_factory", "(", "value", ",", "datatype_cls", ",", "validation_level", "=", "None", ")", ":", "dt_value", ",", "fmt", "=", "get_date_info", "(", "value", ")", "return", "datatype_cls", "(", "dt_value", ",", "fmt", ")" ]
34.583333
21.916667
def create_dir(path, dir_dict={}): ''' Tries to create a new directory in the given path. **create_dir** can also create subfolders according to the dictionnary given as second argument. Parameters ---------- path : string string giving the path of the location to create the directory, ...
[ "def", "create_dir", "(", "path", ",", "dir_dict", "=", "{", "}", ")", ":", "folders", "=", "path", ".", "split", "(", "'/'", ")", "folders", "=", "[", "i", "for", "i", "in", "folders", "if", "i", "!=", "''", "]", "rootPath", "=", "''", "if", "...
30.266667
22.733333
def populate_fabfile(): """ Automatically includes all submodules and role selectors in the top-level fabfile using spooky-scary black magic. This allows us to avoid manually declaring imports for every module, e.g. import burlap.pip import burlap.vm import burlap... which...
[ "def", "populate_fabfile", "(", ")", ":", "stack", "=", "inspect", ".", "stack", "(", ")", "fab_frame", "=", "None", "for", "frame_obj", ",", "script_fn", ",", "line", ",", "_", ",", "_", ",", "_", "in", "stack", ":", "if", "'fabfile.py'", "in", "scr...
33.653846
21.153846
def toLocalIterator(self): """ Returns an iterator that contains all of the rows in this :class:`DataFrame`. The iterator will consume as much memory as the largest partition in this DataFrame. >>> list(df.toLocalIterator()) [Row(age=2, name=u'Alice'), Row(age=5, name=u'Bob')] ...
[ "def", "toLocalIterator", "(", "self", ")", ":", "with", "SCCallSiteSync", "(", "self", ".", "_sc", ")", "as", "css", ":", "sock_info", "=", "self", ".", "_jdf", ".", "toPythonIterator", "(", ")", "return", "_load_from_socket", "(", "sock_info", ",", "Batc...
45.636364
21.090909
def _run_grid_multithread(self, func, iterables): ''' running case with mutil process to support selenium grid-mode(multiple web) and appium grid-mode(multiple devices). @param func: function object @param iterables: iterable objects ''' f = lambda x: threading....
[ "def", "_run_grid_multithread", "(", "self", ",", "func", ",", "iterables", ")", ":", "f", "=", "lambda", "x", ":", "threading", ".", "Thread", "(", "target", "=", "func", ",", "args", "=", "(", "x", ",", ")", ")", "threads", "=", "map", "(", "f", ...
41.833333
19.666667
def stream_buckets(self, bucket_type=None, timeout=None): """ Streams the list of buckets. This is a generator method that should be iterated over. .. warning:: Do not use this in production, as it requires traversing through all keys stored in a cluster. The caller ...
[ "def", "stream_buckets", "(", "self", ",", "bucket_type", "=", "None", ",", "timeout", "=", "None", ")", ":", "if", "not", "riak", ".", "disable_list_exceptions", ":", "raise", "ListError", "(", ")", "_validate_timeout", "(", "timeout", ")", "if", "bucket_ty...
36.648148
18.907407
def read(cls, read, has_name=True): """ Read the tag in using the reader `rd`. If `has_name` is `False`, skip reading the tag name. """ name = cls._read_utf8(read) if has_name else None if cls is TAG_Compound: # A TAG_Compound is almost identical to Python's ...
[ "def", "read", "(", "cls", ",", "read", ",", "has_name", "=", "True", ")", ":", "name", "=", "cls", ".", "_read_utf8", "(", "read", ")", "if", "has_name", "else", "None", "if", "cls", "is", "TAG_Compound", ":", "# A TAG_Compound is almost identical to Python...
42.859155
12.971831
def get_ancestor_class_names(mention): """Return the HTML classes of the Mention's ancestors. If a candidate is passed in, only the ancestors of its first Mention are returned. :param mention: The Mention to evaluate :rtype: list of strings """ span = _to_span(mention) class_names = []...
[ "def", "get_ancestor_class_names", "(", "mention", ")", ":", "span", "=", "_to_span", "(", "mention", ")", "class_names", "=", "[", "]", "i", "=", "_get_node", "(", "span", ".", "sentence", ")", "while", "i", "is", "not", "None", ":", "class_names", ".",...
28.9375
16.25
def validate(self, *args, **kwargs): """ Validates the form by calling `validate` on each field, passing any extra `Form.validate_<fieldname>` validators to the field validator. also calls `validate_ldap` """ valid = FlaskForm.validate(self, *args, **kwargs) if ...
[ "def", "validate", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "valid", "=", "FlaskForm", ".", "validate", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", "if", "not", "valid", ":", "logging", ".", "debug", "(",...
35.466667
22
def __register_services(api_name_version_map, api_config_registry): """Register & return a list of each URL and class that handles that URL. This finds every service class in api_name_version_map, registers it with the given ApiConfigRegistry, builds the URL for that class, and adds the URL and its fac...
[ "def", "__register_services", "(", "api_name_version_map", ",", "api_config_registry", ")", ":", "generator", "=", "api_config", ".", "ApiConfigGenerator", "(", ")", "protorpc_services", "=", "[", "]", "for", "service_factories", "in", "api_name_version_map", ".", "it...
45.487805
22.926829
def trigger_edit(request, trigger_id, edit_what): """ edit the provider :param request: request object :param trigger_id: ID of the trigger to edit :param edit_what: edit a 'Provider' or 'Consumer' ? :type request: HttpRequest object :type trigger_id: int :typ...
[ "def", "trigger_edit", "(", "request", ",", "trigger_id", ",", "edit_what", ")", ":", "if", "edit_what", "not", "in", "(", "'Provider'", ",", "'Consumer'", ")", ":", "# bad request", "return", "redirect", "(", "'base'", ")", "form_name", "=", "edit_what", "+...
33.703704
19.407407
def get_span_char_height(span, row_heights): """ Get the height of a span in the number of newlines it fills. Parameters ---------- span : list of list of int A list of [row, column] pairs that make up the span row_heights : list of int A list of the number of newlines for each ...
[ "def", "get_span_char_height", "(", "span", ",", "row_heights", ")", ":", "start_row", "=", "span", "[", "0", "]", "[", "0", "]", "row_count", "=", "get_span_row_count", "(", "span", ")", "total_height", "=", "0", "for", "i", "in", "range", "(", "start_r...
26.52
18.68
def write_multiple_coils(self, starting_address, values): """ Write multiple coils to Master device (Function code 15) starting_address : First coil to be written values: Coil Values [0..quantity-1] to be written """ self.__transactionIdentifier+=1 if (self.__se...
[ "def", "write_multiple_coils", "(", "self", ",", "starting_address", ",", "values", ")", ":", "self", ".", "__transactionIdentifier", "+=", "1", "if", "(", "self", ".", "__ser", "is", "not", "None", ")", ":", "if", "(", "self", ".", "__ser", ".", "closed...
48.489796
20.734694
def load_and_init(self, modules): """Import, instantiate & "init" the modules we manage :param modules: list of the managed modules :return: True if no errors """ self.load(modules) self.get_instances() return len(self.configuration_errors) == 0
[ "def", "load_and_init", "(", "self", ",", "modules", ")", ":", "self", ".", "load", "(", "modules", ")", "self", ".", "get_instances", "(", ")", "return", "len", "(", "self", ".", "configuration_errors", ")", "==", "0" ]
29.4
14
def _create_credentials(self, n): """ Create security credentials, if necessary. """ if not n: return n elif isinstance(n, SecurityCreds): return n elif isinstance(n, dict): return SecurityCreds(**n) else: raise Type...
[ "def", "_create_credentials", "(", "self", ",", "n", ")", ":", "if", "not", "n", ":", "return", "n", "elif", "isinstance", "(", "n", ",", "SecurityCreds", ")", ":", "return", "n", "elif", "isinstance", "(", "n", ",", "dict", ")", ":", "return", "Secu...
30.384615
11.615385
def to_file( Class, dict, file, is_little_endian=True ): """ For constructing a CDB structure in a file. Able to calculate size on disk and write to a file """ io = BinaryFileWriter( file, is_little_endian=is_little_endian ) start_offset = io.tell() # Header is of...
[ "def", "to_file", "(", "Class", ",", "dict", ",", "file", ",", "is_little_endian", "=", "True", ")", ":", "io", "=", "BinaryFileWriter", "(", "file", ",", "is_little_endian", "=", "is_little_endian", ")", "start_offset", "=", "io", ".", "tell", "(", ")", ...
45.207547
12.301887
def positive_integer(anon, obj, field, val): """ Returns a random positive integer (for a Django PositiveIntegerField) """ return anon.faker.positive_integer(field=field)
[ "def", "positive_integer", "(", "anon", ",", "obj", ",", "field", ",", "val", ")", ":", "return", "anon", ".", "faker", ".", "positive_integer", "(", "field", "=", "field", ")" ]
36.4
9.6
def resize(self, image, size): """ Resizes the image :param image: The image object :param size: size is PIL tuple (width, heigth, force) ex: (200,100,True) """ (width, height, force) = size if image.size[0] > width or image.size[1] > height: ...
[ "def", "resize", "(", "self", ",", "image", ",", "size", ")", ":", "(", "width", ",", "height", ",", "force", ")", "=", "size", "if", "image", ".", "size", "[", "0", "]", ">", "width", "or", "image", ".", "size", "[", "1", "]", ">", "height", ...
32
19.444444
async def stop_listen_notifications(self): """Stop listening on notifications.""" _LOGGER.debug("Stopping listening for notifications..") for serv in self.services.values(): await serv.stop_listen_notifications() return True
[ "async", "def", "stop_listen_notifications", "(", "self", ")", ":", "_LOGGER", ".", "debug", "(", "\"Stopping listening for notifications..\"", ")", "for", "serv", "in", "self", ".", "services", ".", "values", "(", ")", ":", "await", "serv", ".", "stop_listen_no...
37.571429
14.142857
def _do_layout(self): """Sizer hell, returns a sizer that contains all widgets""" sizer_csvoptions = wx.FlexGridSizer(5, 4, 5, 5) # Adding parameter widgets to sizer_csvoptions leftpos = wx.LEFT | wx.ADJUST_MINSIZE rightpos = wx.RIGHT | wx.EXPAND current_label_margin =...
[ "def", "_do_layout", "(", "self", ")", ":", "sizer_csvoptions", "=", "wx", ".", "FlexGridSizer", "(", "5", ",", "4", ",", "5", ",", "5", ")", "# Adding parameter widgets to sizer_csvoptions", "leftpos", "=", "wx", ".", "LEFT", "|", "wx", ".", "ADJUST_MINSIZE...
36.304348
22
def timed(name, tags=None): """Function decorator for tracking timing information on a function's invocation. >>> from statsdecor.decorators import timed >>> @timed('my.metric') >>> def my_func(): >>> pass """ def wrap(f): @wraps(f) def decorator(*args, **kwargs): ...
[ "def", "timed", "(", "name", ",", "tags", "=", "None", ")", ":", "def", "wrap", "(", "f", ")", ":", "@", "wraps", "(", "f", ")", "def", "decorator", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "stats", "=", "client", "(", ")", "with"...
27.058824
13.647059
def inspect_image(self, image_name, image_tag=''): ''' a method to retrieve the settings of an image :param image_name: string with name or id of image :param image_tag: [optional] string with tag associated with image :return: dictionary of settings of imag...
[ "def", "inspect_image", "(", "self", ",", "image_name", ",", "image_tag", "=", "''", ")", ":", "title", "=", "'%s.inspect_image'", "%", "self", ".", "__class__", ".", "__name__", "# validate inputs\r", "input_fields", "=", "{", "'image_name'", ":", "image_name",...
31.194444
20.805556
def combinefiles(filepath): """ Joins first and second read file names """ ## unpack seq files in filepath fastqs = glob.glob(filepath) firsts = [i for i in fastqs if "_R1_" in i] ## check names if not firsts: raise IPyradWarningExit("First read files names must contain '_R1_'.") #...
[ "def", "combinefiles", "(", "filepath", ")", ":", "## unpack seq files in filepath", "fastqs", "=", "glob", ".", "glob", "(", "filepath", ")", "firsts", "=", "[", "i", "for", "i", "in", "fastqs", "if", "\"_R1_\"", "in", "i", "]", "## check names", "if", "n...
32.153846
18.461538
def print_figure(fig, fmt='png'): """Convert a figure to svg or png for inline display.""" # When there's an empty figure, we shouldn't return anything, otherwise we # get big blank areas in the qt console. if not fig.axes and not fig.lines: return fc = fig.get_facecolor() ec = fig.get_...
[ "def", "print_figure", "(", "fig", ",", "fmt", "=", "'png'", ")", ":", "# When there's an empty figure, we shouldn't return anything, otherwise we", "# get big blank areas in the qt console.", "if", "not", "fig", ".", "axes", "and", "not", "fig", ".", "lines", ":", "ret...
32.210526
16.842105
def GetLayerFromFeatureService(self, fs, layerName="", returnURLOnly=False): """Obtains a layer from a feature service by feature service reference. Args: fs (FeatureService): The feature service from which to obtain the layer. layerName (str): The name of the layer. Defaults to...
[ "def", "GetLayerFromFeatureService", "(", "self", ",", "fs", ",", "layerName", "=", "\"\"", ",", "returnURLOnly", "=", "False", ")", ":", "layers", "=", "None", "table", "=", "None", "layer", "=", "None", "sublayer", "=", "None", "try", ":", "layers", "=...
38.634921
18.285714
def make_classifier(output_nonlin=nn.Softmax(dim=-1), **kwargs): """Return a multi-layer perceptron to be used with NeuralNetClassifier. Parameters ---------- input_units : int (default=20) Number of input units. output_units : int (default=2) Number of output units. hidden_un...
[ "def", "make_classifier", "(", "output_nonlin", "=", "nn", ".", "Softmax", "(", "dim", "=", "-", "1", ")", ",", "*", "*", "kwargs", ")", ":", "return", "partial", "(", "MLPModule", ",", "output_nonlin", "=", "output_nonlin", ",", "*", "*", "kwargs", ")...
27.038462
19.769231
def unpack_args(classfun, nth=0): """ args 갯수가 nth + 1 개 일때, 그게 만약 tuple이면, unpack :param classfun: :param nth: nth = 0, 일반 함수, nth = 1: 클래스 함수 1이 self니깐. :return: """ if classfun: nth = 1 def deco(fn): def wrapped(*args, **kwargs): if len(args) == nth + 1 an...
[ "def", "unpack_args", "(", "classfun", ",", "nth", "=", "0", ")", ":", "if", "classfun", ":", "nth", "=", "1", "def", "deco", "(", "fn", ")", ":", "def", "wrapped", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "len", "(", "args", ...
26.85
17.75
def login(*args, **kwargs): """ Prompt user for login information (domain/email/password). Domain, email and password are used to get the user's API key. Always updates the stored credentials file. """ if args and args[0].api_key: # Handle command-line arguments if provided. sol...
[ "def", "login", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "args", "and", "args", "[", "0", "]", ".", "api_key", ":", "# Handle command-line arguments if provided.", "solvebio", ".", "login", "(", "api_key", "=", "args", "[", "0", "]", ...
30.857143
18
def _from_dict(cls, _dict): """Initialize a MetricTokenResponse object from a json dictionary.""" args = {} if 'aggregations' in _dict: args['aggregations'] = [ MetricTokenAggregation._from_dict(x) for x in (_dict.get('aggregations')) ] ...
[ "def", "_from_dict", "(", "cls", ",", "_dict", ")", ":", "args", "=", "{", "}", "if", "'aggregations'", "in", "_dict", ":", "args", "[", "'aggregations'", "]", "=", "[", "MetricTokenAggregation", ".", "_from_dict", "(", "x", ")", "for", "x", "in", "(",...
37.222222
12.222222
def get_cached_commit_times(root_folder, parent_dir, sorted_relpaths): """ Get the cached commit times for the combination of this parent_dir and relpaths Return the commit assigned to this combination and the actual times! """ result = get_all_cached_commit_times(root_folder) for item in resu...
[ "def", "get_cached_commit_times", "(", "root_folder", ",", "parent_dir", ",", "sorted_relpaths", ")", ":", "result", "=", "get_all_cached_commit_times", "(", "root_folder", ")", "for", "item", "in", "result", ":", "if", "sorted", "(", "item", ".", "get", "(", ...
39.076923
28.461538
def get_grid(self): """ Standardize the layout of the table into grids """ mentions, lines = _split_text_n_lines(self.elems) # Sort mentions in reading order where y values are snapped to half # height-sized grid mentions.sort(key=lambda m: (m.yc_grid, m.xc)) ...
[ "def", "get_grid", "(", "self", ")", ":", "mentions", ",", "lines", "=", "_split_text_n_lines", "(", "self", ".", "elems", ")", "# Sort mentions in reading order where y values are snapped to half", "# height-sized grid", "mentions", ".", "sort", "(", "key", "=", "lam...
33.545455
16.090909
def update_group_admin(self, group_id, users=[]): """ Update the group's admins :type group_id: int :param group_id: Group ID Number :type users: list of str :param users: List of emails :rtype: dict :return: dictionary of group information """ ...
[ "def", "update_group_admin", "(", "self", ",", "group_id", ",", "users", "=", "[", "]", ")", ":", "data", "=", "{", "'groupId'", ":", "group_id", ",", "'users'", ":", "users", ",", "}", "return", "_fix_group", "(", "self", ".", "post", "(", "'updateGro...
25.166667
15.944444
def parse_name(name): """ Split a query name into field name, operator and whether it is inverted. """ inverted, op = False, OP_EQ if name is not None: for op_ in (OP_NIN, OP_IN, OP_NOT, OP_LIKE): if name.endswith(op_): op = op_ name = name[:len(name) ...
[ "def", "parse_name", "(", "name", ")", ":", "inverted", ",", "op", "=", "False", ",", "OP_EQ", "if", "name", "is", "not", "None", ":", "for", "op_", "in", "(", "OP_NIN", ",", "OP_IN", ",", "OP_NOT", ",", "OP_LIKE", ")", ":", "if", "name", ".", "e...
32.714286
10.785714
def requisite_in(self, high): ''' Extend the data reference with requisite_in arguments ''' req_in = {'require_in', 'watch_in', 'onfail_in', 'onchanges_in', 'use', 'use_in', 'prereq', 'prereq_in'} req_in_all = req_in.union({'require', 'watch', 'onfail', 'onfail_stop', 'onchanges'...
[ "def", "requisite_in", "(", "self", ",", "high", ")", ":", "req_in", "=", "{", "'require_in'", ",", "'watch_in'", ",", "'onfail_in'", ",", "'onchanges_in'", ",", "'use'", ",", "'use_in'", ",", "'prereq'", ",", "'prereq_in'", "}", "req_in_all", "=", "req_in",...
59.960177
22.384956
def _yield_children(rec): # type: (dr.DirectoryRecord) -> Generator ''' An internal function to gather and yield all of the children of a Directory Record. Parameters: rec - The Directory Record to get all of the children from (must be a directory) Yields: Children of this ...
[ "def", "_yield_children", "(", "rec", ")", ":", "# type: (dr.DirectoryRecord) -> Generator", "if", "not", "rec", ".", "is_dir", "(", ")", ":", "raise", "pycdlibexception", ".", "PyCdlibInvalidInput", "(", "'Record is not a directory!'", ")", "last", "=", "b''", "for...
41.833333
29.214286
def get_form(): """ Return the form to use for commenting. """ global form_class from fluent_comments import appsettings if form_class is None: if appsettings.FLUENT_COMMENTS_FORM_CLASS: from django.utils.module_loading import import_string form_class = import_str...
[ "def", "get_form", "(", ")", ":", "global", "form_class", "from", "fluent_comments", "import", "appsettings", "if", "form_class", "is", "None", ":", "if", "appsettings", ".", "FLUENT_COMMENTS_FORM_CLASS", ":", "from", "django", ".", "utils", ".", "module_loading",...
32.866667
16.466667
def process_anchor_start(regions_fn, to_count_fn, anchor_to=ANCHOR_START, normalize=False, verbose=False): """ :return: list where each element is the number of hits at that location relative to the start of the regions. """ res = [] possible = [] ...
[ "def", "process_anchor_start", "(", "regions_fn", ",", "to_count_fn", ",", "anchor_to", "=", "ANCHOR_START", ",", "normalize", "=", "False", ",", "verbose", "=", "False", ")", ":", "res", "=", "[", "]", "possible", "=", "[", "]", "trees", "=", "intervalTre...
30.147059
18.147059
def make_pmml_pipeline(obj, active_fields = None, target_fields = None): """Translates a regular Scikit-Learn estimator or pipeline to a PMML pipeline. Parameters: ---------- obj: BaseEstimator The object. active_fields: list of strings, optional Feature names. If missing, "x1", "x2", .., "xn" are assumed. ...
[ "def", "make_pmml_pipeline", "(", "obj", ",", "active_fields", "=", "None", ",", "target_fields", "=", "None", ")", ":", "steps", "=", "_filter_steps", "(", "_get_steps", "(", "obj", ")", ")", "pipeline", "=", "PMMLPipeline", "(", "steps", ")", "if", "acti...
29.727273
18.590909
def _init_map(self): """stub""" QuestionTextFormRecord._init_map(self) self.my_osid_object_form._my_map['choices'] = \ self._choices_metadata['default_object_values'][0]
[ "def", "_init_map", "(", "self", ")", ":", "QuestionTextFormRecord", ".", "_init_map", "(", "self", ")", "self", ".", "my_osid_object_form", ".", "_my_map", "[", "'choices'", "]", "=", "self", ".", "_choices_metadata", "[", "'default_object_values'", "]", "[", ...
40.2
12.6
def set_wheel_mode(self, ids): """ Sets the specified motors to wheel mode. """ self.set_control_mode(dict(zip(ids, itertools.repeat('wheel'))))
[ "def", "set_wheel_mode", "(", "self", ",", "ids", ")", ":", "self", ".", "set_control_mode", "(", "dict", "(", "zip", "(", "ids", ",", "itertools", ".", "repeat", "(", "'wheel'", ")", ")", ")", ")" ]
52.666667
14
def enforcement_action(self, column=None, value=None, **kwargs): """ A disciplinary action taken against a permit facility. The action may be applicable to one or more violations. >>> PCS().enforcement_action('ea_code', '09') """ return self._resolve_call('PCS_ENFOR_A...
[ "def", "enforcement_action", "(", "self", ",", "column", "=", "None", ",", "value", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_resolve_call", "(", "'PCS_ENFOR_ACTION'", ",", "column", ",", "value", ",", "*", "*", "kwargs", ...
43.125
20.375
def set_on_level(self, val): """Set on level for the button/group.""" on_cmd = self._create_set_property_msg("_on_level", 0x06, val) self._send_method(on_cmd, self._property_set) self._send_method(on_cmd, self._on_message_received)
[ "def", "set_on_level", "(", "self", ",", "val", ")", ":", "on_cmd", "=", "self", ".", "_create_set_property_msg", "(", "\"_on_level\"", ",", "0x06", ",", "val", ")", "self", ".", "_send_method", "(", "on_cmd", ",", "self", ".", "_property_set", ")", "self"...
50.833333
13.5
def _identifier_filtered_iterator(graph): """Iterate over names in the given namespace.""" for data in graph: for pair in _get_node_names(data): yield pair for member in data.get(MEMBERS, []): for pair in _get_node_names(member): yield pair for ((_, ...
[ "def", "_identifier_filtered_iterator", "(", "graph", ")", ":", "for", "data", "in", "graph", ":", "for", "pair", "in", "_get_node_names", "(", "data", ")", ":", "yield", "pair", "for", "member", "in", "data", ".", "get", "(", "MEMBERS", ",", "[", "]", ...
37.393939
19.454545
def create_single(cls, value, idx='default'): """ Create a label-list with a single label containing the given value. """ return LabelList(idx=idx, labels=[ Label(value=value) ])
[ "def", "create_single", "(", "cls", ",", "value", ",", "idx", "=", "'default'", ")", ":", "return", "LabelList", "(", "idx", "=", "idx", ",", "labels", "=", "[", "Label", "(", "value", "=", "value", ")", "]", ")" ]
35
14.5
def configure_root_iam_credentials(self, access_key, secret_key, region=None, iam_endpoint=None, sts_endpoint=None, max_retries=-1, mount_point=DEFAULT_MOUNT_POINT): """Configure the root IAM credentials to communicate with AWS. There are multiple ways to pass roo...
[ "def", "configure_root_iam_credentials", "(", "self", ",", "access_key", ",", "secret_key", ",", "region", "=", "None", ",", "iam_endpoint", "=", "None", ",", "sts_endpoint", "=", "None", ",", "max_retries", "=", "-", "1", ",", "mount_point", "=", "DEFAULT_MOU...
49.019231
25.615385
def get_instance(self, payload): """ Build an instance of ThisMonthInstance :param dict payload: Payload response from the API :returns: twilio.rest.api.v2010.account.usage.record.this_month.ThisMonthInstance :rtype: twilio.rest.api.v2010.account.usage.record.this_month.ThisMon...
[ "def", "get_instance", "(", "self", ",", "payload", ")", ":", "return", "ThisMonthInstance", "(", "self", ".", "_version", ",", "payload", ",", "account_sid", "=", "self", ".", "_solution", "[", "'account_sid'", "]", ",", ")" ]
43.5
26.9
def one_of(these): """Returns the current token if is found in the collection provided. Fails otherwise. """ ch = peek() try: if (ch is EndOfFile) or (ch not in these): fail(list(these)) except TypeError: if ch != these: fail([these]) next() r...
[ "def", "one_of", "(", "these", ")", ":", "ch", "=", "peek", "(", ")", "try", ":", "if", "(", "ch", "is", "EndOfFile", ")", "or", "(", "ch", "not", "in", "these", ")", ":", "fail", "(", "list", "(", "these", ")", ")", "except", "TypeError", ":",...
22.5
18.857143
def strnum(prefix: str, num: int, suffix: str = "") -> str: """ Makes a string of the format ``<prefix><number><suffix>``. """ return "{}{}{}".format(prefix, num, suffix)
[ "def", "strnum", "(", "prefix", ":", "str", ",", "num", ":", "int", ",", "suffix", ":", "str", "=", "\"\"", ")", "->", "str", ":", "return", "\"{}{}{}\"", ".", "format", "(", "prefix", ",", "num", ",", "suffix", ")" ]
36.4
9.6
def _getStateAnomalyVector(self, state): """ Returns a state's anomaly vertor converting it from spare to dense """ vector = numpy.zeros(self._anomalyVectorLength) vector[state.anomalyVector] = 1 return vector
[ "def", "_getStateAnomalyVector", "(", "self", ",", "state", ")", ":", "vector", "=", "numpy", ".", "zeros", "(", "self", ".", "_anomalyVectorLength", ")", "vector", "[", "state", ".", "anomalyVector", "]", "=", "1", "return", "vector" ]
32.428571
9.857143
def create_session_engine(uri=None, cfg=None): """ Create an sqlalchemy session and engine. :param str uri: The database URI to connect to :param cfg: The configuration object with database URI info. :return: The session and the engine as a list (in that order) """ if uri is not None: ...
[ "def", "create_session_engine", "(", "uri", "=", "None", ",", "cfg", "=", "None", ")", ":", "if", "uri", "is", "not", "None", ":", "eng", "=", "sa", ".", "create_engine", "(", "uri", ")", "elif", "cfg", "is", "not", "None", ":", "eng", "=", "sa", ...
34.5
15
def _pickUpIteration(self, searchAnchor, objectsToSkip): """ Picks up iteration from a previously provided page token. There are two different phases here: 1) We are iterating over the initial set of intervals in which start is < the search start coorindate. 2) We are ite...
[ "def", "_pickUpIteration", "(", "self", ",", "searchAnchor", ",", "objectsToSkip", ")", ":", "self", ".", "_searchAnchor", "=", "searchAnchor", "self", ".", "_distanceFromAnchor", "=", "objectsToSkip", "self", ".", "_searchIterator", "=", "self", ".", "_search", ...
47.882353
13.764706
def ignore_token(self): """Determine if we should ignore current token""" def get_next_ignore(remove=False): """Get next ignore from ignore_next and remove from ignore_next""" next_ignore = self.ignore_next # Just want to return it, don't want to remove yet ...
[ "def", "ignore_token", "(", "self", ")", ":", "def", "get_next_ignore", "(", "remove", "=", "False", ")", ":", "\"\"\"Get next ignore from ignore_next and remove from ignore_next\"\"\"", "next_ignore", "=", "self", ".", "ignore_next", "# Just want to return it, don't want to ...
43.647059
18.647059
def _add_encrypted(self, other): """Returns E(a + b) given E(a) and E(b). Args: other (EncryptedNumber): an `EncryptedNumber` to add to self. Returns: EncryptedNumber: E(a + b), calculated by taking the product of E(a) and E(b) modulo :attr:`~PaillierPublicKey.n...
[ "def", "_add_encrypted", "(", "self", ",", "other", ")", ":", "if", "self", ".", "public_key", "!=", "other", ".", "public_key", ":", "raise", "ValueError", "(", "\"Attempted to add numbers encrypted against \"", "\"different public keys!\"", ")", "# In order to add two...
38.730769
23.076923
def post_file(self, uri, body, files, **kwargs): """POST a file""" # requests doesn't actually need us to open the files but we do anyway because # if we don't then the filename isn't preserved, so we assume each string # value is a filepath for key in files.keys(): i...
[ "def", "post_file", "(", "self", ",", "uri", ",", "body", ",", "files", ",", "*", "*", "kwargs", ")", ":", "# requests doesn't actually need us to open the files but we do anyway because", "# if we don't then the filename isn't preserved, so we assume each string", "# value is a ...
39.55
19.5
def merge(self, grid=None, merge_points=True, inplace=False, main_has_priority=True): """ Join one or many other grids to this grid. Grid is updated in-place by default. Can be used to merge points of adjcent cells when no grids are input. Parameters ...
[ "def", "merge", "(", "self", ",", "grid", "=", "None", ",", "merge_points", "=", "True", ",", "inplace", "=", "False", ",", "main_has_priority", "=", "True", ")", ":", "append_filter", "=", "vtk", ".", "vtkAppendFilter", "(", ")", "append_filter", ".", "...
31.220339
18.576271
def push(h, x): """Push a new value into heap.""" h.push(x) up(h, h.size()-1)
[ "def", "push", "(", "h", ",", "x", ")", ":", "h", ".", "push", "(", "x", ")", "up", "(", "h", ",", "h", ".", "size", "(", ")", "-", "1", ")" ]
21.5
17.75
def _set_fills_in_color_layer(self, svg_string, color): """replaces fill colors in ``<g inkscape:label="color" inkscape:groupmode="layer">`` with :paramref:`color` :param color: a color fill the objects in the layer with """ structure = xmltodict.parse(svg_string) if col...
[ "def", "_set_fills_in_color_layer", "(", "self", ",", "svg_string", ",", "color", ")", ":", "structure", "=", "xmltodict", ".", "parse", "(", "svg_string", ")", "if", "color", "is", "None", ":", "return", "structure", "layers", "=", "structure", "[", "\"svg\...
45.882353
14.264706
def finished(self): """ Must be called to print final progress label. """ self.progress_bar.set_state(ProgressBar.STATE_DONE) self.progress_bar.show()
[ "def", "finished", "(", "self", ")", ":", "self", ".", "progress_bar", ".", "set_state", "(", "ProgressBar", ".", "STATE_DONE", ")", "self", ".", "progress_bar", ".", "show", "(", ")" ]
30.833333
10.166667
def draw_text(stdscr, text, color=0, fallback=None, title=None): """ Draws text in the given color. Duh. """ if fallback is None: fallback = text y, x = stdscr.getmaxyx() if title: title = pad_to_size(title, x, 1) if "\n" in title.rstrip("\n"): # hack to get m...
[ "def", "draw_text", "(", "stdscr", ",", "text", ",", "color", "=", "0", ",", "fallback", "=", "None", ",", "title", "=", "None", ")", ":", "if", "fallback", "is", "None", ":", "fallback", "=", "text", "y", ",", "x", "=", "stdscr", ".", "getmaxyx", ...
34
18.384615
def reset(self): """ Put all LEDs back to their default color """ if not self.leds: return self.animate_stop() for group in self.led_groups: self.set_color(group, LED_DEFAULT_COLOR)
[ "def", "reset", "(", "self", ")", ":", "if", "not", "self", ".", "leds", ":", "return", "self", ".", "animate_stop", "(", ")", "for", "group", "in", "self", ".", "led_groups", ":", "self", ".", "set_color", "(", "group", ",", "LED_DEFAULT_COLOR", ")" ]
20.416667
18.083333
def to_representation(self, instance): """ Return the updated program data dictionary. Arguments: instance (dict): The program data. Returns: dict: The updated program data. """ updated_program = copy.deepcopy(instance) enterprise_custome...
[ "def", "to_representation", "(", "self", ",", "instance", ")", ":", "updated_program", "=", "copy", ".", "deepcopy", "(", "instance", ")", "enterprise_customer_catalog", "=", "self", ".", "context", "[", "'enterprise_customer_catalog'", "]", "updated_program", "[", ...
41.090909
21.909091
def _apply_worksheet_template_duplicate_analyses(self, wst): """Add duplicate analyses to worksheet according to the worksheet template layout passed in w/o overwrite slots that are already filled. If the slot where the duplicate must be located is available, but the slot where the rout...
[ "def", "_apply_worksheet_template_duplicate_analyses", "(", "self", ",", "wst", ")", ":", "wst_layout", "=", "wst", ".", "getLayout", "(", ")", "for", "row", "in", "wst_layout", ":", "if", "row", "[", "'type'", "]", "!=", "'d'", ":", "continue", "src_pos", ...
36.333333
19.904762
def parse(self, parsable): ''' High-level parsing: determines the data format and combines parent-children outputs NB: this is the PUBLIC method @returns tilde_obj, error ''' calc, error = None, None try: f = open(parsable, 'rb') ...
[ "def", "parse", "(", "self", ",", "parsable", ")", ":", "calc", ",", "error", "=", "None", ",", "None", "try", ":", "f", "=", "open", "(", "parsable", ",", "'rb'", ")", "if", "is_binary_string", "(", "f", ".", "read", "(", "2048", ")", ")", ":", ...
34.321429
21.964286
def _process_yes_work(self, yes_work, no_catalogue, maybe_works, output_dir): """Returns statistics of how `yes_work` compares with the other works in `no_catalogue` and the "maybe" works. :param yes_work: name of work being processed :type yes_work: `str` ...
[ "def", "_process_yes_work", "(", "self", ",", "yes_work", ",", "no_catalogue", ",", "maybe_works", ",", "output_dir", ")", ":", "self", ".", "_logger", ".", "info", "(", "'Processing \"maybe\" work {} as \"yes\".'", ".", "format", "(", "yes_work", ")", ")", "sta...
45.035714
16.678571
def check_for_cores(self): """! @brief Init task: verify that at least one core was discovered.""" if not len(self.cores): # Allow the user to override the exception to enable uses like chip bringup. if self.session.options.get('allow_no_cores', False): logging.er...
[ "def", "check_for_cores", "(", "self", ")", ":", "if", "not", "len", "(", "self", ".", "cores", ")", ":", "# Allow the user to override the exception to enable uses like chip bringup.", "if", "self", ".", "session", ".", "options", ".", "get", "(", "'allow_no_cores'...
54.5
21.125
def num_decodings(s): """ :type s: str :rtype: int """ if not s or s[0] == "0": return 0 wo_last, wo_last_two = 1, 1 for i in range(1, len(s)): x = wo_last if s[i] != "0" else 0 y = wo_last_two if int(s[i-1:i+1]) < 27 and s[i-1] != "0" else 0 wo_last_two = wo_...
[ "def", "num_decodings", "(", "s", ")", ":", "if", "not", "s", "or", "s", "[", "0", "]", "==", "\"0\"", ":", "return", "0", "wo_last", ",", "wo_last_two", "=", "1", ",", "1", "for", "i", "in", "range", "(", "1", ",", "len", "(", "s", ")", ")",...
25.142857
14.857143
def end_of(self, unit): """ Returns a copy of the instance with the time reset with the following rules: * second: microsecond set to 999999 * minute: second set to 59 and microsecond set to 999999 * hour: minute and second set to 59 and microsecond set to 999999 ...
[ "def", "end_of", "(", "self", ",", "unit", ")", ":", "if", "unit", "not", "in", "self", ".", "_MODIFIERS_VALID_UNITS", ":", "raise", "ValueError", "(", "'Invalid unit \"%s\" for end_of()'", "%", "unit", ")", "return", "getattr", "(", "self", ",", "\"_end_of_%s...
40.875
21.541667
def phenotype_data(self): """Get the phenotype data for each of the sample.""" if self._phenotype_data is None: pheno_data = {} for gsm_name, gsm in iteritems(self.gsms): tmp = {} for key, value in iteritems(gsm.metadata): if le...
[ "def", "phenotype_data", "(", "self", ")", ":", "if", "self", ".", "_phenotype_data", "is", "None", ":", "pheno_data", "=", "{", "}", "for", "gsm_name", ",", "gsm", "in", "iteritems", "(", "self", ".", "gsms", ")", ":", "tmp", "=", "{", "}", "for", ...
47.571429
12.809524
def anoteElements(ax, anotelist, showAccName=False, efilter=None, textypos=None, **kwargs): """ annotate elements to axes :param ax: matplotlib axes object :param anotelist: element annotation object list :param showAccName: tag name for accelerator tubes? defaul...
[ "def", "anoteElements", "(", "ax", ",", "anotelist", ",", "showAccName", "=", "False", ",", "efilter", "=", "None", ",", "textypos", "=", "None", ",", "*", "*", "kwargs", ")", ":", "defaultstyle", "=", "{", "'alpha'", ":", "0.8", ",", "'arrowprops'", "...
54.346154
24.269231
def vm_diskstats(vm_=None): ''' Return disk usage counters used by the vms on this hyper in a list of dicts: .. code-block:: python [ 'your-vm': { 'io_read_kbs' : 0, 'io_write_kbs' : 0 }, ... ] If you p...
[ "def", "vm_diskstats", "(", "vm_", "=", "None", ")", ":", "with", "_get_xapi_session", "(", ")", "as", "xapi", ":", "def", "_info", "(", "vm_", ")", ":", "ret", "=", "{", "}", "vm_uuid", "=", "_get_label_uuid", "(", "xapi", ",", "'VM'", ",", "vm_", ...
26.577778
21.911111
def size_filter(labeled_grid, min_size): """ Remove labeled objects that do not meet size threshold criteria. Args: labeled_grid: 2D output from label method. min_size: minimum size of object in pixels. Returns: labeled grid with smaller objects remo...
[ "def", "size_filter", "(", "labeled_grid", ",", "min_size", ")", ":", "out_grid", "=", "np", ".", "zeros", "(", "labeled_grid", ".", "shape", ",", "dtype", "=", "int", ")", "slices", "=", "find_objects", "(", "labeled_grid", ")", "j", "=", "1", "for", ...
35.714286
17.714286
def mygenerator(n=5, n_edges=5): ''' Just a simple generator that creates a network with n nodes and n_edges edges. Edges are assigned randomly, only avoiding self loops. ''' G = nx.Graph() for i in range(n): G.add_node(i) for i in range(n_edges): nodes = list(G.nodes) ...
[ "def", "mygenerator", "(", "n", "=", "5", ",", "n_edges", "=", "5", ")", ":", "G", "=", "nx", ".", "Graph", "(", ")", "for", "i", "in", "range", "(", "n", ")", ":", "G", ".", "add_node", "(", "i", ")", "for", "i", "in", "range", "(", "n_edg...
26.411765
20.764706
def key(self, id_num): """Get the specified deploy key. :param int id_num: (required), id of the key :returns: :class:`Key <github3.users.Key>` if successful, else None """ json = None if int(id_num) > 0: url = self._build_url('keys', str(id_num), base_url=se...
[ "def", "key", "(", "self", ",", "id_num", ")", ":", "json", "=", "None", "if", "int", "(", "id_num", ")", ">", "0", ":", "url", "=", "self", ".", "_build_url", "(", "'keys'", ",", "str", "(", "id_num", ")", ",", "base_url", "=", "self", ".", "_...
38
17.363636
def _format_value(self, val): """ formats a value to be good for textmode printing val must be unicode """ name = self.name + ":" if not self.multiline or "\n" not in val: val = u"{0} {1}".format(name.ljust(self._text_prefix_len), val) else: ...
[ "def", "_format_value", "(", "self", ",", "val", ")", ":", "name", "=", "self", ".", "name", "+", "\":\"", "if", "not", "self", ".", "multiline", "or", "\"\\n\"", "not", "in", "val", ":", "val", "=", "u\"{0} {1}\"", ".", "format", "(", "name", ".", ...
35.461538
18.846154
def get_predicted_structure(self, structure, ref_structure): """ Given a structure, returns back the structure scaled to predicted volume. Args: structure (Structure): structure w/unknown volume ref_structure (Structure): A reference structure with a similar ...
[ "def", "get_predicted_structure", "(", "self", ",", "structure", ",", "ref_structure", ")", ":", "new_structure", "=", "structure", ".", "copy", "(", ")", "new_structure", ".", "scale_lattice", "(", "self", ".", "predict", "(", "structure", ",", "ref_structure",...
38.533333
19.466667
def format(self, record): """ Modified from logging/__init__.py in python 2.7 lib Format the specified record as text. The record's attribute dictionary is used as the operand to a string formatting operation which yields the returned string. Before formatting the dicti...
[ "def", "format", "(", "self", ",", "record", ")", ":", "record", ".", "message", "=", "record", ".", "getMessage", "(", ")", "if", "self", ".", "usesTime", "(", ")", ":", "record", ".", "asctime", "=", "self", ".", "formatTime", "(", "record", ",", ...
43.652174
21.217391
def decorate_instance_methods(obj, decorator, includes=None, excludes=None): """Decorator instance methods of an object. :param obj: Python object whose instance methods have to be decorated :param decorator: instance method decorator. >>> def decorate(name, f): >>> def __wrap(*args, **...
[ "def", "decorate_instance_methods", "(", "obj", ",", "decorator", ",", "includes", "=", "None", ",", "excludes", "=", "None", ")", ":", "class", "InstanceMethodDecorator", "(", "object", ")", ":", "def", "__getattribute__", "(", "self", ",", "name", ")", ":"...
40.032258
15
def _renorm(self): """ Remake the pixel dictionary, merging groups of pixels at level N into a single pixel at level N-1 """ self.demoted = set() # convert all to lowest level self._demote_all() # now promote as needed for d in range(self.maxdepth,...
[ "def", "_renorm", "(", "self", ")", ":", "self", ".", "demoted", "=", "set", "(", ")", "# convert all to lowest level", "self", ".", "_demote_all", "(", ")", "# now promote as needed", "for", "d", "in", "range", "(", "self", ".", "maxdepth", ",", "2", ",",...
39.285714
15.47619
def check_path(self, path): """ turns path into an absolute path and checks that it exists, then returns it as a string. """ path = os.path.abspath(path) if os.path.exists(path): return path else: utils.die("input file does not exists:\n {...
[ "def", "check_path", "(", "self", ",", "path", ")", ":", "path", "=", "os", ".", "path", ".", "abspath", "(", "path", ")", "if", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "return", "path", "else", ":", "utils", ".", "die", "(", "...
32.7
14.1
def get_source_scanner(self, node): """Fetch the source scanner for the specified node NOTE: "self" is the target being built, "node" is the source file for which we want to fetch the scanner. Implies self.has_builder() is true; again, expect to only be called from locations w...
[ "def", "get_source_scanner", "(", "self", ",", "node", ")", ":", "scanner", "=", "None", "try", ":", "scanner", "=", "self", ".", "builder", ".", "source_scanner", "except", "AttributeError", ":", "pass", "if", "not", "scanner", ":", "# The builder didn't have...
38.44
19.76
def _check_expiration(self, url: str, data: 'SavedEndpoint') -> 'SavedEndpoint': """Checks the expiration time for data for a url. If the data has expired, it is deleted from the cache. Args: url: url to check data: page of data for that url Returns: ...
[ "def", "_check_expiration", "(", "self", ",", "url", ":", "str", ",", "data", ":", "'SavedEndpoint'", ")", "->", "'SavedEndpoint'", ":", "if", "data", ".", "expires_after", "<", "time", ".", "time", "(", ")", ":", "del", "self", ".", "data", "[", "url"...
30.75
20.25
def commit_analyzer(commits, label_pattern, label_position="footer"): """Analyzes a list of :class:`~braulio.git.Commit` objects searching for messages that match a given message convention and extract metadata from them. A message convention is determined by ``label_pattern``, which is not a regul...
[ "def", "commit_analyzer", "(", "commits", ",", "label_pattern", ",", "label_position", "=", "\"footer\"", ")", ":", "# Internally, a real regular expression pattern is used", "pattern_string", "=", "re", ".", "escape", "(", "label_pattern", ")", "# Capturing group patterns"...
31.472973
24.243243
def default_error_handler(exception): """ Default error handler Will display an error page with the corresponding error code from template directory, for example, a not found will load a 404.html etc. Will first look in userland app templates and if not found, fallback to boiler templates to dis...
[ "def", "default_error_handler", "(", "exception", ")", ":", "http_exception", "=", "isinstance", "(", "exception", ",", "exceptions", ".", "HTTPException", ")", "code", "=", "exception", ".", "code", "if", "http_exception", "else", "500", "# log exceptions only (app...
36.961538
18.346154
def _get_action(self, action): """ Utility function that consolidates actions if necessary. """ return_action = action if self.partial_update_is_update and action == 'partial_update': return_action = 'update' return return_action
[ "def", "_get_action", "(", "self", ",", "action", ")", ":", "return_action", "=", "action", "if", "self", ".", "partial_update_is_update", "and", "action", "==", "'partial_update'", ":", "return_action", "=", "'update'", "return", "return_action" ]
35.25
11.5
def to_python(self, value: Union[Dict[str, int], int, None]) -> LocalizedIntegerValue: """Converts the value from a database value into a Python value.""" db_value = super().to_python(value) return self._convert_localized_value(db_value)
[ "def", "to_python", "(", "self", ",", "value", ":", "Union", "[", "Dict", "[", "str", ",", "int", "]", ",", "int", ",", "None", "]", ")", "->", "LocalizedIntegerValue", ":", "db_value", "=", "super", "(", ")", ".", "to_python", "(", "value", ")", "...
51.6
20.6