text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def set_time(self, time): ''' Update the length of the buffer in seconds :param time: number of seconds :return: self ''' self.length = int(time*self.sample_rate) return self
[ "def", "set_time", "(", "self", ",", "time", ")", ":", "self", ".", "length", "=", "int", "(", "time", "*", "self", ".", "sample_rate", ")", "return", "self" ]
27.875
0.008696
def regular_half(circuit: circuits.Circuit) -> circuits.Circuit: """Return only the Clifford part of a circuit. See convert_and_separate_circuit(). Args: circuit: A Circuit with the gate set {SingleQubitCliffordGate, PauliInteractionGate, PauliStringPhasor}. Returns: A Cir...
[ "def", "regular_half", "(", "circuit", ":", "circuits", ".", "Circuit", ")", "->", "circuits", ".", "Circuit", ":", "return", "circuits", ".", "Circuit", "(", "ops", ".", "Moment", "(", "op", "for", "op", "in", "moment", ".", "operations", "if", "not", ...
36.888889
0.001468
def Stop(self): """Stops the process status RPC server.""" self._Close() if self._rpc_thread.isAlive(): self._rpc_thread.join() self._rpc_thread = None
[ "def", "Stop", "(", "self", ")", ":", "self", ".", "_Close", "(", ")", "if", "self", ".", "_rpc_thread", ".", "isAlive", "(", ")", ":", "self", ".", "_rpc_thread", ".", "join", "(", ")", "self", ".", "_rpc_thread", "=", "None" ]
24
0.011494
def score_function(self, x, W): # need refector ''' Score function to calculate score ''' score = self.theta(np.inner(x, W)) return score
[ "def", "score_function", "(", "self", ",", "x", ",", "W", ")", ":", "# need refector", "score", "=", "self", ".", "theta", "(", "np", ".", "inner", "(", "x", ",", "W", ")", ")", "return", "score" ]
17.9
0.015957
async def _resin_supervisor_restart(): """ Execute a container restart by requesting it from the supervisor. Note that failures here are returned but most likely will not be sent back to the caller, since this is run in a separate workthread. If the system is not responding, look for these log messages...
[ "async", "def", "_resin_supervisor_restart", "(", ")", ":", "supervisor", "=", "os", ".", "environ", ".", "get", "(", "'RESIN_SUPERVISOR_ADDRESS'", ",", "'http://127.0.0.1:48484'", ")", "restart_url", "=", "supervisor", "+", "'/v1/restart'", "api", "=", "os", ".",...
49.666667
0.000941
def parse_branches(self, branchset_node, branchset, validate): """ Create and attach branches at ``branchset_node`` to ``branchset``. :param branchset_node: Same as for :meth:`parse_branchset`. :param branchset: An instance of :class:`BranchSet`. :param v...
[ "def", "parse_branches", "(", "self", ",", "branchset_node", ",", "branchset", ",", "validate", ")", ":", "weight_sum", "=", "0", "branches", "=", "branchset_node", ".", "nodes", "values", "=", "[", "]", "for", "branchnode", "in", "branches", ":", "weight", ...
44.016667
0.000741
def on_timer(self, evt): """ Keep watching the mouse displacement via timer Needed since EVT_MOVE doesn't happen once the mouse gets outside the frame """ ctrl_is_down = wx.GetKeyState(wx.WXK_CONTROL) shift_is_down = wx.GetKeyState(wx.WXK_SHIFT) ms = wx.GetMouseState() new_pos = None...
[ "def", "on_timer", "(", "self", ",", "evt", ")", ":", "ctrl_is_down", "=", "wx", ".", "GetKeyState", "(", "wx", ".", "WXK_CONTROL", ")", "shift_is_down", "=", "wx", ".", "GetKeyState", "(", "wx", ".", "WXK_SHIFT", ")", "ms", "=", "wx", ".", "GetMouseSt...
37.876712
0.012337
def stratify_by_features(features, n_strata, **kwargs): """Stratify by clustering the items in feature space Parameters ---------- features : array-like, shape=(n_items,n_features) feature matrix for the pool, where rows correspond to items and columns correspond to features. n_str...
[ "def", "stratify_by_features", "(", "features", ",", "n_strata", ",", "*", "*", "kwargs", ")", ":", "n_items", "=", "features", ".", "shape", "[", "0", "]", "km", "=", "KMeans", "(", "n_clusters", "=", "n_strata", ",", "*", "*", "kwargs", ")", "allocat...
26.434783
0.001587
def get_right_axes(self): "create, if needed, and return right-hand y axes" if len(self.fig.get_axes()) < 2: ax = self.axes.twinx() return self.fig.get_axes()[1]
[ "def", "get_right_axes", "(", "self", ")", ":", "if", "len", "(", "self", ".", "fig", ".", "get_axes", "(", ")", ")", "<", "2", ":", "ax", "=", "self", ".", "axes", ".", "twinx", "(", ")", "return", "self", ".", "fig", ".", "get_axes", "(", ")"...
32.166667
0.010101
def init_app(self, app, **kwargs): """Initialize application object. :param app: An instance of :class:`~flask.Flask`. """ # Init the configuration self.init_config(app) # Enable Rate limiter self.limiter = Limiter(app, key_func=get_ipaddr) # Enable secur...
[ "def", "init_app", "(", "self", ",", "app", ",", "*", "*", "kwargs", ")", ":", "# Init the configuration", "self", ".", "init_config", "(", "app", ")", "# Enable Rate limiter", "self", ".", "limiter", "=", "Limiter", "(", "app", ",", "key_func", "=", "get_...
37.361702
0.00111
def get_cv_idxs(n, cv_idx=0, val_pct=0.2, seed=42): """ Get a list of index values for Validation set from a dataset Arguments: n : int, Total number of elements in the data set. cv_idx : int, starting index [idx_start = cv_idx*int(val_pct*n)] val_pct : (int, float), validation set...
[ "def", "get_cv_idxs", "(", "n", ",", "cv_idx", "=", "0", ",", "val_pct", "=", "0.2", ",", "seed", "=", "42", ")", ":", "np", ".", "random", ".", "seed", "(", "seed", ")", "n_val", "=", "int", "(", "val_pct", "*", "n", ")", "idx_start", "=", "cv...
33.705882
0.010187
def srem(self, name, *values): """ send raw (source) values here. Right functioning with other values not guaranteed (and even worse). """ return self.storage.srem(name, *self.dump(values, False))
[ "def", "srem", "(", "self", ",", "name", ",", "*", "values", ")", ":", "return", "self", ".", "storage", ".", "srem", "(", "name", ",", "*", "self", ".", "dump", "(", "values", ",", "False", ")", ")" ]
38.5
0.008475
def overload(fn): """ Overload a given callable object to be used with ``|`` operator overloading. This is especially used for composing a pipeline of transformation over a single data set. Arguments: fn (function): target function to decorate. Raises: TypeError: if functi...
[ "def", "overload", "(", "fn", ")", ":", "if", "not", "isfunction", "(", "fn", ")", ":", "raise", "TypeError", "(", "'paco: fn must be a callable object'", ")", "spec", "=", "getargspec", "(", "fn", ")", "args", "=", "spec", ".", "args", "if", "not", "spe...
27.352941
0.001038
def _load_users(self): """Default implentation requires users from DB. Should setup `users` attribute""" r = sql.abstractRequetesSQL.get_users()() self.users = {d["id"]: dict(d) for d in r}
[ "def", "_load_users", "(", "self", ")", ":", "r", "=", "sql", ".", "abstractRequetesSQL", ".", "get_users", "(", ")", "(", ")", "self", ".", "users", "=", "{", "d", "[", "\"id\"", "]", ":", "dict", "(", "d", ")", "for", "d", "in", "r", "}" ]
43.4
0.00905
def member_create(self, params, member_id): """start new mongod instances as part of replica set Args: params - member params member_id - member index return member config """ member_config = params.get('rsParams', {}) server_id = params.pop('serv...
[ "def", "member_create", "(", "self", ",", "params", ",", "member_id", ")", ":", "member_config", "=", "params", ".", "get", "(", "'rsParams'", ",", "{", "}", ")", "server_id", "=", "params", ".", "pop", "(", "'server_id'", ",", "None", ")", "version", ...
38.034483
0.001768
def crypto_pwhash_scryptsalsa208sha256_str_verify(passwd_hash, passwd): """ Verifies the ``passwd`` against the ``passwd_hash`` that was generated. Returns True or False depending on the success :param passwd_hash: bytes :param passwd: bytes :rtype: boolean """ ensure(len(passwd_hash) ...
[ "def", "crypto_pwhash_scryptsalsa208sha256_str_verify", "(", "passwd_hash", ",", "passwd", ")", ":", "ensure", "(", "len", "(", "passwd_hash", ")", "==", "SCRYPT_STRBYTES", "-", "1", ",", "'Invalid password hash'", ",", "raising", "=", "exc", ".", "ValueError", ")...
35.047619
0.001323
def do_indent( s, width=4, first=False, blank=False, indentfirst=None ): """Return a copy of the string with each line indented by 4 spaces. The first line and blank lines are not indented by default. :param width: Number of spaces to indent by. :param first: Don't skip indenting the first line. ...
[ "def", "do_indent", "(", "s", ",", "width", "=", "4", ",", "first", "=", "False", ",", "blank", "=", "False", ",", "indentfirst", "=", "None", ")", ":", "if", "indentfirst", "is", "not", "None", ":", "warnings", ".", "warn", "(", "DeprecationWarning", ...
28.102564
0.000882
def _assemble_and_send_request(self): """ Fires off the Fedex request. @warning: NEVER CALL THIS METHOD DIRECTLY. CALL send_request(), WHICH RESIDES ON FedexBaseService AND IS INHERITED. """ # Fire off the query. return self.client.service.createPickup( ...
[ "def", "_assemble_and_send_request", "(", "self", ")", ":", "# Fire off the query.", "return", "self", ".", "client", ".", "service", ".", "createPickup", "(", "WebAuthenticationDetail", "=", "self", ".", "WebAuthenticationDetail", ",", "ClientDetail", "=", "self", ...
39.458333
0.002062
def get_checksum_by_target(self, target): """ returns a checksum of a specific kind """ for csum in self.checksums: if csum.target == target: return csum return None
[ "def", "get_checksum_by_target", "(", "self", ",", "target", ")", ":", "for", "csum", "in", "self", ".", "checksums", ":", "if", "csum", ".", "target", "==", "target", ":", "return", "csum", "return", "None" ]
35.333333
0.009217
def vbd_list(name=None, call=None): ''' Get a list of VBDs on a VM **requires**: the name of the vm with the vbd definition .. code-block:: bash salt-cloud -a vbd_list xenvm01 ''' if call == 'function': raise SaltCloudSystemExit( 'This function must be called with...
[ "def", "vbd_list", "(", "name", "=", "None", ",", "call", "=", "None", ")", ":", "if", "call", "==", "'function'", ":", "raise", "SaltCloudSystemExit", "(", "'This function must be called with -a, --action argument.'", ")", "if", "name", "is", "None", ":", "retu...
25.875
0.001164
def add_mag_drifts(inst): """Adds ion drifts in magnetic coordinates using ion drifts in S/C coordinates along with pre-calculated unit vectors for magnetic coordinates. Note ---- Requires ion drifts under labels 'iv_*' where * = (x,y,z) along with unit vectors labels 'unit_zonal_*'...
[ "def", "add_mag_drifts", "(", "inst", ")", ":", "inst", "[", "'iv_zon'", "]", "=", "{", "'data'", ":", "inst", "[", "'unit_zon_x'", "]", "*", "inst", "[", "'iv_x'", "]", "+", "inst", "[", "'unit_zon_y'", "]", "*", "inst", "[", "'iv_y'", "]", "+", "...
51.492958
0.014224
def ngram_count(text,N=1,keep_punct=False): ''' if N=1, return a dict containing each letter along with how many times the letter occurred. if N=2, returns a dict containing counts of each bigram (pair of letters) etc. There is an option to remove all spaces and punctuation prior to processi...
[ "def", "ngram_count", "(", "text", ",", "N", "=", "1", ",", "keep_punct", "=", "False", ")", ":", "if", "not", "keep_punct", ":", "text", "=", "re", ".", "sub", "(", "'[^A-Z]'", ",", "''", ",", "text", ".", "upper", "(", ")", ")", "count", "=", ...
44.583333
0.020147
def build_grouped_ownership_map(table, key_from_row, value_from_row, group_key): """ Builds a dict mapping group keys to maps of keys to to lists of OwnershipPeriods, from a db table. """ grouped_rows = g...
[ "def", "build_grouped_ownership_map", "(", "table", ",", "key_from_row", ",", "value_from_row", ",", "group_key", ")", ":", "grouped_rows", "=", "groupby", "(", "group_key", ",", "sa", ".", "select", "(", "table", ".", "c", ")", ".", "execute", "(", ")", "...
28.7
0.001686
def _estimate_2dhist_shift(imgxy, refxy, searchrad=3.0): """ Create a 2D matrix-histogram which contains the delta between each XY position and each UV position. Then estimate initial offset between catalogs. """ print("Computing initial guess for X and Y shifts...") # create ZP matrix ...
[ "def", "_estimate_2dhist_shift", "(", "imgxy", ",", "refxy", ",", "searchrad", "=", "3.0", ")", ":", "print", "(", "\"Computing initial guess for X and Y shifts...\"", ")", "# create ZP matrix", "zpmat", "=", "_xy_2dhist", "(", "imgxy", ",", "refxy", ",", "r", "="...
35.9
0.000452
def visit_functiondef(self, node): """check function name, docstring, arguments, redefinition, variable names, max locals """ # init branch and returns counters self._returns.append(0) # check number of arguments args = node.args.args ignored_argument_name...
[ "def", "visit_functiondef", "(", "self", ",", "node", ")", ":", "# init branch and returns counters", "self", ".", "_returns", ".", "append", "(", "0", ")", "# check number of arguments", "args", "=", "node", ".", "args", ".", "args", "ignored_argument_names", "="...
37.060606
0.00239
def writeConflicts(self): """Extract ntoreturn counter if available (lazy).""" if not self._counters_calculated: self._counters_calculated = True self._extract_counters() return self._writeConflicts
[ "def", "writeConflicts", "(", "self", ")", ":", "if", "not", "self", ".", "_counters_calculated", ":", "self", ".", "_counters_calculated", "=", "True", "self", ".", "_extract_counters", "(", ")", "return", "self", ".", "_writeConflicts" ]
34.428571
0.008097
def _to_swagger(base=None, description=None, resource=None, options=None): # type: (Dict[str, str], str, Resource, Dict[str, str]) -> Dict[str, str] """ Common to swagger definition. :param base: The base dict. :param description: An optional description. :param resource: An optional resource. ...
[ "def", "_to_swagger", "(", "base", "=", "None", ",", "description", "=", "None", ",", "resource", "=", "None", ",", "options", "=", "None", ")", ":", "# type: (Dict[str, str], str, Resource, Dict[str, str]) -> Dict[str, str]", "definition", "=", "dict_filter", "(", ...
30.041667
0.001344
def mnist(training): """Downloads MNIST and loads it into numpy arrays.""" if training: data_filename = 'train-images-idx3-ubyte.gz' labels_filename = 'train-labels-idx1-ubyte.gz' count = 60000 else: data_filename = 't10k-images-idx3-ubyte.gz' labels_filename = 't10k-labels-idx1-ubyte.gz' ...
[ "def", "mnist", "(", "training", ")", ":", "if", "training", ":", "data_filename", "=", "'train-images-idx3-ubyte.gz'", "labels_filename", "=", "'train-labels-idx1-ubyte.gz'", "count", "=", "60000", "else", ":", "data_filename", "=", "'t10k-images-idx3-ubyte.gz'", "labe...
36.666667
0.012411
def write(message, priority=Priority.INFO): """ Write message into systemd journal :type priority: Priority :type message: str """ priority = int(Priority(int(priority))) send(priority=priority, message=message)
[ "def", "write", "(", "message", ",", "priority", "=", "Priority", ".", "INFO", ")", ":", "priority", "=", "int", "(", "Priority", "(", "int", "(", "priority", ")", ")", ")", "send", "(", "priority", "=", "priority", ",", "message", "=", "message", ")...
25.555556
0.008403
def _traverse_toc(pdf_base, visitor_fn, log): """ Walk the table of contents, calling visitor_fn() at each node The /Outlines data structure is a messy data structure, but rather than navigating hierarchically we just track unique nodes. Enqueue nodes when we find them, and never visit them again....
[ "def", "_traverse_toc", "(", "pdf_base", ",", "visitor_fn", ",", "log", ")", ":", "visited", "=", "set", "(", ")", "queue", "=", "set", "(", ")", "link_keys", "=", "(", "'/Parent'", ",", "'/First'", ",", "'/Last'", ",", "'/Prev'", ",", "'/Next'", ")", ...
34.52381
0.001341
def add_class(cls, *args): """Add classes to the group. Parameters ---------- *args : `type` Classes to add. """ for cls2 in args: cls.classes[cls2.__name__] = cls2
[ "def", "add_class", "(", "cls", ",", "*", "args", ")", ":", "for", "cls2", "in", "args", ":", "cls", ".", "classes", "[", "cls2", ".", "__name__", "]", "=", "cls2" ]
22.8
0.008439
def log(*args, level=INFO): """ Write the sequence of args, with no separators, to the console and output files (if you've configured an output file). """ Logger.CURRENT.log(*args, level=level)
[ "def", "log", "(", "*", "args", ",", "level", "=", "INFO", ")", ":", "Logger", ".", "CURRENT", ".", "log", "(", "*", "args", ",", "level", "=", "level", ")" ]
41
0.009569
def fetch( self, request: Union[str, "HTTPRequest"], raise_error: bool = True, **kwargs: Any ) -> Awaitable["HTTPResponse"]: """Executes a request, asynchronously returning an `HTTPResponse`. The request may be either a string URL or an `HTTPRequest` object. ...
[ "def", "fetch", "(", "self", ",", "request", ":", "Union", "[", "str", ",", "\"HTTPRequest\"", "]", ",", "raise_error", ":", "bool", "=", "True", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "Awaitable", "[", "\"HTTPResponse\"", "]", ":", "if", "s...
43.949153
0.001509
def separate_trailing_comments(lines: List[str]) -> List[Tuple[int, str]]: """Given a list of numbered Fortran source code lines, i.e., pairs of the form (n, code_line) where n is a line number and code_line is a line of code, separate_trailing_comments() behaves as follows: for each pair (n, c...
[ "def", "separate_trailing_comments", "(", "lines", ":", "List", "[", "str", "]", ")", "->", "List", "[", "Tuple", "[", "int", ",", "str", "]", "]", ":", "enumerated_lines", "=", "list", "(", "enumerate", "(", "lines", ",", "1", ")", ")", "i", "=", ...
48.956522
0.000871
def delimitedList( expr, delim=",", combine=False ): """Helper to define a delimited list of expressions - the delimiter defaults to ','. By default, the list elements and delimiters can have intervening whitespace, and comments, but this can be overridden by passing ``combine=True`` in the constructor....
[ "def", "delimitedList", "(", "expr", ",", "delim", "=", "\",\"", ",", "combine", "=", "False", ")", ":", "dlName", "=", "_ustr", "(", "expr", ")", "+", "\" [\"", "+", "_ustr", "(", "delim", ")", "+", "\" \"", "+", "_ustr", "(", "expr", ")", "+", ...
50.55
0.015534
def cmap_d_pal(name=None, lut=None): """ Create a discrete palette using an MPL Listed colormap Parameters ---------- name : str Name of colormap lut : None | int This is the number of entries desired in the lookup table. Default is ``None``, leave it up Matplotlib. ...
[ "def", "cmap_d_pal", "(", "name", "=", "None", ",", "lut", "=", "None", ")", ":", "colormap", "=", "get_cmap", "(", "name", ",", "lut", ")", "if", "not", "isinstance", "(", "colormap", ",", "mcolors", ".", "ListedColormap", ")", ":", "raise", "ValueErr...
30.42
0.000637
def _get_environ_overrides() -> Dict[str, str]: """ Pull any overrides for the config elements from the environ and return a mapping from the names to the values (as strings). Config elements that are not overridden will not be in the mapping. """ return { ce.name: os.environ['OT_API_' + ce....
[ "def", "_get_environ_overrides", "(", ")", "->", "Dict", "[", "str", ",", "str", "]", ":", "return", "{", "ce", ".", "name", ":", "os", ".", "environ", "[", "'OT_API_'", "+", "ce", ".", "name", ".", "upper", "(", ")", "]", "for", "ce", "in", "CON...
45.888889
0.002375
def perform(self, event): """ Perform the action. """ wizard = NewDotGraphWizard(parent=self.window.control, window=self.window, title="New Graph") # Open the wizard if wizard.open() == OK: wizard.finished = True
[ "def", "perform", "(", "self", ",", "event", ")", ":", "wizard", "=", "NewDotGraphWizard", "(", "parent", "=", "self", ".", "window", ".", "control", ",", "window", "=", "self", ".", "window", ",", "title", "=", "\"New Graph\"", ")", "# Open the wizard", ...
29.888889
0.01083
def resistance(self): """ Return resistance of the vehicle. :return: newton the resistance of the ship """ self.total_resistance_coef = frictional_resistance_coef(self.length, self.speed) + \ residual_resistance_coef(self.slenderness_coefficient, ...
[ "def", "resistance", "(", "self", ")", ":", "self", ".", "total_resistance_coef", "=", "frictional_resistance_coef", "(", "self", ".", "length", ",", "self", ".", "speed", ")", "+", "residual_resistance_coef", "(", "self", ".", "slenderness_coefficient", ",", "s...
50.083333
0.013072
def error_statistics(target_scores, decoy_scores, parametric, pfdr, pi0_lambda, pi0_method = "smoother", pi0_smooth_df = 3, pi0_smooth_log_pi0 = False, compute_lfdr = False, lfdr_trunc = True, lfdr_monotone = True, lfdr_transf = "probit", lfdr_adj = 1.5, lfdr_eps = np.power(10.0,-8)): """ Takes list of decoy and ta...
[ "def", "error_statistics", "(", "target_scores", ",", "decoy_scores", ",", "parametric", ",", "pfdr", ",", "pi0_lambda", ",", "pi0_method", "=", "\"smoother\"", ",", "pi0_smooth_df", "=", "3", ",", "pi0_smooth_log_pi0", "=", "False", ",", "compute_lfdr", "=", "F...
48.147059
0.01497
def _codec_fails_on_encode_surrogates(codec, _cache={}): """Returns if a codec fails correctly when passing in surrogates with a surrogatepass/surrogateescape error handler. Some codecs were broken in Python <3.4 """ try: return _cache[codec] except KeyError: try: u"...
[ "def", "_codec_fails_on_encode_surrogates", "(", "codec", ",", "_cache", "=", "{", "}", ")", ":", "try", ":", "return", "_cache", "[", "codec", "]", "except", "KeyError", ":", "try", ":", "u\"\\uD800\\uDC01\"", ".", "encode", "(", "codec", ")", "except", "...
29.8125
0.002033
def _form_pages(self, message_no, content, out, height, width): """ Form the pages """ self.pages[message_no] = [] page_height = height - 4 # 2-3 for menu, 1 for cursor outline = u'' no_lines_page = 0 for original, formatted in zip(content.split('\n'), out.split('\n')): ...
[ "def", "_form_pages", "(", "self", ",", "message_no", ",", "content", ",", "out", ",", "height", ",", "width", ")", ":", "self", ".", "pages", "[", "message_no", "]", "=", "[", "]", "page_height", "=", "height", "-", "4", "# 2-3 for menu, 1 for cursor", ...
41.404762
0.001124
def on_touch_move(self, touch): """If an entity is selected, drag it.""" if hasattr(self, '_lasttouch') and self._lasttouch == touch: return if self.app.selection in self.selection_candidates: self.selection_candidates.remove(self.app.selection) if self.app.select...
[ "def", "on_touch_move", "(", "self", ",", "touch", ")", ":", "if", "hasattr", "(", "self", ",", "'_lasttouch'", ")", "and", "self", ".", "_lasttouch", "==", "touch", ":", "return", "if", "self", ".", "app", ".", "selection", "in", "self", ".", "selecti...
43
0.002395
def publish(self, load): ''' This method sends out publications to the minions, it can only be used by the LocalClient. ''' extra = load.get('kwargs', {}) publisher_acl = salt.acl.PublisherACL(self.opts['publisher_acl_blacklist']) if publisher_acl.user_is_blackl...
[ "def", "publish", "(", "self", ",", "load", ")", ":", "extra", "=", "load", ".", "get", "(", "'kwargs'", ",", "{", "}", ")", "publisher_acl", "=", "salt", ".", "acl", ".", "PublisherACL", "(", "self", ".", "opts", "[", "'publisher_acl_blacklist'", "]",...
38.712821
0.001421
def create(callback=None, path=None, method=Method.POST, resource=None, tags=None, summary="Create a new resource", middleware=None): # type: (Callable, Path, Methods, Resource, Tags, str, List[Any]) -> Operation """ Decorator to configure an operation that creates a resource. """ def inn...
[ "def", "create", "(", "callback", "=", "None", ",", "path", "=", "None", ",", "method", "=", "Method", ".", "POST", ",", "resource", "=", "None", ",", "tags", "=", "None", ",", "summary", "=", "\"Create a new resource\"", ",", "middleware", "=", "None", ...
54
0.009105
def run(): """Fetches changes and applies them to VIFs periodically Process as of RM11449: * Get all groups from redis * Fetch ALL VIFs from Xen * Walk ALL VIFs and partition them into added, updated and removed * Walk the final "modified" VIFs list and apply flows to each """ groups_cl...
[ "def", "run", "(", ")", ":", "groups_client", "=", "sg_cli", ".", "SecurityGroupsClient", "(", ")", "xapi_client", "=", "xapi", ".", "XapiClient", "(", ")", "interfaces", "=", "set", "(", ")", "while", "True", ":", "try", ":", "interfaces", "=", "xapi_cl...
41.702128
0.000499
def count_funs(self) -> int: """ Count function define by this scope """ n = 0 for s in self._hsig.values(): if hasattr(s, 'is_fun') and s.is_fun: n += 1 return n
[ "def", "count_funs", "(", "self", ")", "->", "int", ":", "n", "=", "0", "for", "s", "in", "self", ".", "_hsig", ".", "values", "(", ")", ":", "if", "hasattr", "(", "s", ",", "'is_fun'", ")", "and", "s", ".", "is_fun", ":", "n", "+=", "1", "re...
30.857143
0.009009
def info(self, exp_path=False, project_path=False, global_path=False, config_path=False, complete=False, no_fix=False, on_projects=False, on_globals=False, projectname=None, return_dict=False, insert_id=True, only_keys=False, archives=False, **kwargs): """ ...
[ "def", "info", "(", "self", ",", "exp_path", "=", "False", ",", "project_path", "=", "False", ",", "global_path", "=", "False", ",", "config_path", "=", "False", ",", "complete", "=", "False", ",", "no_fix", "=", "False", ",", "on_projects", "=", "False"...
39.632813
0.001154
def calculateValues(self): """ Overloads the calculate values method to calculate the values for this axis based on the minimum and maximum values, and the number of steps desired. :return [<variant>, ..] """ if self.maximum() <= self.minimum(...
[ "def", "calculateValues", "(", "self", ")", ":", "if", "self", ".", "maximum", "(", ")", "<=", "self", ".", "minimum", "(", ")", ":", "return", "[", "]", "max_labels", "=", "self", ".", "maximumLabelCount", "(", ")", "seconds", "=", "(", "self", ".",...
33
0.008032
def _check_middleware_dependencies(concerned_object, required_middleware): """ Check required middleware dependencies exist and in the correct order. Args: concerned_object (object): The object for which the required middleware is being checked. This is used for error messages only. ...
[ "def", "_check_middleware_dependencies", "(", "concerned_object", ",", "required_middleware", ")", ":", "declared_middleware", "=", "getattr", "(", "settings", ",", "'MIDDLEWARE'", ",", "None", ")", "if", "declared_middleware", "is", "None", ":", "declared_middleware", ...
41.216216
0.001922
def cached_read(self, kind): """Cache stats calls to prevent hammering the API""" if not kind in self.cache: self.pull_stats(kind) if self.epochnow() - self.cache[kind]['lastcall'] > self.cache_timeout: self.pull_stats(kind) return self.cache[kind]['lastvalue']
[ "def", "cached_read", "(", "self", ",", "kind", ")", ":", "if", "not", "kind", "in", "self", ".", "cache", ":", "self", ".", "pull_stats", "(", "kind", ")", "if", "self", ".", "epochnow", "(", ")", "-", "self", ".", "cache", "[", "kind", "]", "["...
44.428571
0.009464
def multi_index(idx, dim): """ Single to multi-index using graded reverse lexicographical notation. Parameters ---------- idx : int Index in interger notation dim : int The number of dimensions in the multi-index notation Returns ------- out : tuple Multi-in...
[ "def", "multi_index", "(", "idx", ",", "dim", ")", ":", "def", "_rec", "(", "idx", ",", "dim", ")", ":", "idxn", "=", "idxm", "=", "0", "if", "not", "dim", ":", "return", "(", ")", "if", "idx", "==", "0", ":", "return", "(", "0", ",", ")", ...
19.6
0.000972
def get_attribute_selected(self, attribute): """ Performs search of selected item from Web List Return attribute of selected item @params attribute - string attribute name """ items_list = self.get_options() return next(iter([item.get_attribute(attribute) for ite...
[ "def", "get_attribute_selected", "(", "self", ",", "attribute", ")", ":", "items_list", "=", "self", ".", "get_options", "(", ")", "return", "next", "(", "iter", "(", "[", "item", ".", "get_attribute", "(", "attribute", ")", "for", "item", "in", "items_lis...
39.777778
0.008197
def _pos(self, idx): """Convert an index into a pair (alpha, beta) that can be used to access the corresponding _lists[alpha][beta] position. Most queries require the index be built. Details of the index are described in self._build_index. Indexing requires traversing the tree ...
[ "def", "_pos", "(", "self", ",", "idx", ")", ":", "if", "idx", "<", "0", ":", "last_len", "=", "len", "(", "self", ".", "_lists", "[", "-", "1", "]", ")", "if", "(", "-", "idx", ")", "<=", "last_len", ":", "return", "len", "(", "self", ".", ...
32.528736
0.001372
def rubberstamp(rest): "Approve something" parts = ["Bad credit? No credit? Slow credit?"] rest = rest.strip() if rest: parts.append("%s is" % rest) karma.Karma.store.change(rest, 1) parts.append("APPROVED!") return " ".join(parts)
[ "def", "rubberstamp", "(", "rest", ")", ":", "parts", "=", "[", "\"Bad credit? No credit? Slow credit?\"", "]", "rest", "=", "rest", ".", "strip", "(", ")", "if", "rest", ":", "parts", ".", "append", "(", "\"%s is\"", "%", "rest", ")", "karma", ".", "Kar...
25.888889
0.037344
def request(method, url, params=None, data=None, headers=None, cookies=None, files=None, auth=None, timeout=None, allow_redirects=False, proxies=None, hooks=None, return_response=True, prefetch=False, config=None): """Constructs and sends a :class:`Request <Reques...
[ "def", "request", "(", "method", ",", "url", ",", "params", "=", "None", ",", "data", "=", "None", ",", "headers", "=", "None", ",", "cookies", "=", "None", ",", "files", "=", "None", ",", "auth", "=", "None", ",", "timeout", "=", "None", ",", "a...
37.2
0.012048
def getOrphanParticleInfos(self, swarmId, genIdx): """Return a list of particleStates for all particles in the given swarm generation that have been orphaned. Parameters: --------------------------------------------------------------------- swarmId: A string representation of the sorted list of en...
[ "def", "getOrphanParticleInfos", "(", "self", ",", "swarmId", ",", "genIdx", ")", ":", "entryIdxs", "=", "range", "(", "len", "(", "self", ".", "_allResults", ")", ")", "if", "len", "(", "entryIdxs", ")", "==", "0", ":", "return", "(", "[", "]", ",",...
33.457627
0.00935
def get_etags_and_matchers(self, request): """Get the etags from the header and perform a validation against the required preconditions.""" # evaluate the preconditions, raises 428 if condition is not met self.evaluate_preconditions(request) # alright, headers are present, extract the va...
[ "def", "get_etags_and_matchers", "(", "self", ",", "request", ")", ":", "# evaluate the preconditions, raises 428 if condition is not met", "self", ".", "evaluate_preconditions", "(", "request", ")", "# alright, headers are present, extract the values and match the conditions", "retu...
70.166667
0.00939
def reload(self): """ Reloads the contents for this box. """ enum = self._enum if not enum: return self.clear() if not self.isRequired(): self.addItem('') if self.sortByKey(): sel...
[ "def", "reload", "(", "self", ")", ":", "enum", "=", "self", ".", "_enum", "if", "not", "enum", ":", "return", "self", ".", "clear", "(", ")", "if", "not", "self", ".", "isRequired", "(", ")", ":", "self", ".", "addItem", "(", "''", ")", "if", ...
24.8
0.015534
def print_detailed_traceback(self, space=None, file=None): """NOT_RPYTHON: Dump a nice detailed interpreter- and application-level traceback, useful to debug the interpreter.""" if file is None: file = sys.stderr f = io.StringIO() for i in range(len(self.debug_excs)-1...
[ "def", "print_detailed_traceback", "(", "self", ",", "space", "=", "None", ",", "file", "=", "None", ")", ":", "if", "file", "is", "None", ":", "file", "=", "sys", ".", "stderr", "f", "=", "io", ".", "StringIO", "(", ")", "for", "i", "in", "range",...
45
0.002418
def bitsetxor(b1, b2): """ If b1 and b2 would be ``int`` s this would be ``b1 ^ b2`` : >>> from py_register_machine2.engine_tools.operations import bitsetxor >>> b1 = [1, 1, 1, 1] >>> b2 = [1, 1, 0, 1] >>> bitsetxor(b1, b2) [0, 0, 1, 0] >>> bin(0b1111 ^ 0b1101) '0b10' """ res = [] for bit1, bit2 in zip(b1,...
[ "def", "bitsetxor", "(", "b1", ",", "b2", ")", ":", "res", "=", "[", "]", "for", "bit1", ",", "bit2", "in", "zip", "(", "b1", ",", "b2", ")", ":", "res", ".", "append", "(", "bit1", "^", "bit2", ")", "return", "res" ]
21.8125
0.043956
def two_way(cells): """ Two-way chi-square test of independence. Takes a 3D array as input: N(voxels) x 2 x 2, where the last two dimensions are the contingency table for each of N voxels. Returns an array of p-values. """ # Mute divide-by-zero warning for bad voxels since we account for that ...
[ "def", "two_way", "(", "cells", ")", ":", "# Mute divide-by-zero warning for bad voxels since we account for that", "# later", "warnings", ".", "simplefilter", "(", "\"ignore\"", ",", "RuntimeWarning", ")", "cells", "=", "cells", ".", "astype", "(", "'float64'", ")", ...
45.181818
0.000985
def parse(filename, format=u"Jæren Sparebank", encoding="latin1"): """Parses bank CSV file and returns Transactions instance. Args: filename: Path to CSV file to read. format: CSV format; one of the entries in `elv.formats`. encoding: The CSV file encoding. Returns: A ``Tra...
[ "def", "parse", "(", "filename", ",", "format", "=", "u\"Jæren Sparebank\",", " ", "ncoding=", "\"", "latin1\")", ":", "", "Class", "=", "formats", "[", "format", ".", "lower", "(", ")", "]", "if", "PY3", ":", "kw", "=", "{", "\"encoding\"", ":", "enco...
26.3
0.001835
def ecdsa_sign(private_key, data, hash_algorithm): """ Generates an ECDSA signature :param private_key: The PrivateKey to generate the signature with :param data: A byte string of the data the signature is for :param hash_algorithm: A unicode string of "md5", "sha1", "sha2...
[ "def", "ecdsa_sign", "(", "private_key", ",", "data", ",", "hash_algorithm", ")", ":", "if", "private_key", ".", "algorithm", "!=", "'ec'", ":", "raise", "ValueError", "(", "'The key specified is not an EC private key'", ")", "return", "_sign", "(", "private_key", ...
29.576923
0.001259
def revise_buffer_size(info, settings): ''' This function is used to revise buffer size, use byte as its unit, instead of data item. This is only used for nnb, not for csrc. When settings contains user customized data type, not pure FLOAT32, it affects the memory consumption. ''' size_ma...
[ "def", "revise_buffer_size", "(", "info", ",", "settings", ")", ":", "size_mapping", "=", "{", "'FLOAT32'", ":", "4", ",", "'FIXED16'", ":", "2", ",", "'FIXED8'", ":", "1", "}", "var_dict", "=", "settings", "[", "'variables'", "]", "buffer_index", "=", "...
36.636364
0.000806
def _modified_shepp_logan_ellipsoids(ellipsoids): """Modify ellipsoids to give the modified Shepp-Logan phantom. Works for both 2d and 3d. """ intensities = [1.0, -0.8, -0.2, -0.2, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1] # Add minimal numbers to ensure that the result is nowhere negative. # This is need...
[ "def", "_modified_shepp_logan_ellipsoids", "(", "ellipsoids", ")", ":", "intensities", "=", "[", "1.0", ",", "-", "0.8", ",", "-", "0.2", ",", "-", "0.2", ",", "0.1", ",", "0.1", ",", "0.1", ",", "0.1", ",", "0.1", ",", "0.1", "]", "# Add minimal numbe...
33.25
0.001828
def _replace_file(path, content): """Writes a file if it doesn't already exist with the same content. This is useful because cargo uses timestamps to decide whether to compile things.""" if os.path.exists(path): with open(path, 'r') as f: if content == f.read(): print("Not overwriting {} becaus...
[ "def", "_replace_file", "(", "path", ",", "content", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "with", "open", "(", "path", ",", "'r'", ")", "as", "f", ":", "if", "content", "==", "f", ".", "read", "(", ")", ":", ...
35.333333
0.016092
def normalize(string: str) -> str: """ Normalizes whitespace. Strips leading and trailing blank lines, dedents, and removes trailing whitespace from the result. """ string = string.replace("\t", " ") lines = string.split("\n") while lines and (not lines[0] or lines[0].isspace()): ...
[ "def", "normalize", "(", "string", ":", "str", ")", "->", "str", ":", "string", "=", "string", ".", "replace", "(", "\"\\t\"", ",", "\" \"", ")", "lines", "=", "string", ".", "split", "(", "\"\\n\"", ")", "while", "lines", "and", "(", "not", "line...
30.833333
0.001748
def has_add_permission(self, request): """ Returns True if the given request has permission to add an object. Can be overriden by the user in subclasses. """ opts = self.opts return request.user.has_perm(opts.app_label + '.' + opts.get_add_permission())
[ "def", "has_add_permission", "(", "self", ",", "request", ")", ":", "opts", "=", "self", ".", "opts", "return", "request", ".", "user", ".", "has_perm", "(", "opts", ".", "app_label", "+", "'.'", "+", "opts", ".", "get_add_permission", "(", ")", ")" ]
42.142857
0.009967
def remove(self, nodes): """Remove a node and its edges.""" nodes = nodes if isinstance(nodes, list) else [nodes] for node in nodes: k = self.id(node) self.edges = list(filter(lambda e: e[0] != k and e[1] != k, self.edges)) del self.nodes[k]
[ "def", "remove", "(", "self", ",", "nodes", ")", ":", "nodes", "=", "nodes", "if", "isinstance", "(", "nodes", ",", "list", ")", "else", "[", "nodes", "]", "for", "node", "in", "nodes", ":", "k", "=", "self", ".", "id", "(", "node", ")", "self", ...
42.142857
0.009967
def prune_by_work_count(self, minimum=None, maximum=None, label=None): """Removes results rows for n-grams that are not attested in a number of works in the range specified by `minimum` and `maximum`. Work here encompasses all witnesses, so that the same n-gram appearing in mult...
[ "def", "prune_by_work_count", "(", "self", ",", "minimum", "=", "None", ",", "maximum", "=", "None", ",", "label", "=", "None", ")", ":", "self", ".", "_logger", ".", "info", "(", "'Pruning results by work count'", ")", "count_fieldname", "=", "'tmp_count'", ...
43.868421
0.001174
def html_override_tool(): ''' Bypass the normal handler and serve HTML for all URLs The ``app_path`` setting must be non-empty and the request must ask for ``text/html`` in the ``Accept`` header. ''' apiopts = cherrypy.config['apiopts'] request = cherrypy.request url_blacklist = ( ...
[ "def", "html_override_tool", "(", ")", ":", "apiopts", "=", "cherrypy", ".", "config", "[", "'apiopts'", "]", "request", "=", "cherrypy", ".", "request", "url_blacklist", "=", "(", "apiopts", ".", "get", "(", "'app_path'", ",", "'/app'", ")", ",", "apiopts...
25.060606
0.001164
def add(self, entries, table=None, columns=None, ignore=False): """Add entries to a table. The *entries* variable should be an iterable.""" # Default table and columns # if table is None: table = self.main_table if columns is None: columns = self.get_columns_of_table(table) ...
[ "def", "add", "(", "self", ",", "entries", ",", "table", "=", "None", ",", "columns", "=", "None", ",", "ignore", "=", "False", ")", ":", "# Default table and columns #", "if", "table", "is", "None", ":", "table", "=", "self", ".", "main_table", "if", ...
50.692308
0.008191
def _unpack_index(i): """Unpack index and return exactly four elements. If index is more shallow than 4, return None for trailing dimensions. If index is deeper than 4, raise a KeyError. """ if len(i) > 4: raise KeyError( "Tried to index history with {} indices but only " ...
[ "def", "_unpack_index", "(", "i", ")", ":", "if", "len", "(", "i", ")", ">", "4", ":", "raise", "KeyError", "(", "\"Tried to index history with {} indices but only \"", "\"4 indices are possible.\"", ".", "format", "(", "len", "(", "i", ")", ")", ")", "# fill ...
35.5
0.000857
def biases(self, vector_id=0): """ Return the frame for the respective bias vector. :param: vector_id: an integer, ranging from 0 to number of layers, that specifies the bias vector to return. :returns: an H2OFrame which represents the bias vector identified by vector_id """ ...
[ "def", "biases", "(", "self", ",", "vector_id", "=", "0", ")", ":", "return", "{", "model", ".", "model_id", ":", "model", ".", "biases", "(", "vector_id", ")", "for", "model", "in", "self", ".", "models", "}" ]
48.875
0.012563
def set_identify(on=True, duration=600, **kwargs): ''' Request identify light Request the identify light to turn off, on for a duration, or on indefinitely. Other than error exceptions, :param on: Set to True to force on or False to force off :param duration: Set if wanting to request turn on...
[ "def", "set_identify", "(", "on", "=", "True", ",", "duration", "=", "600", ",", "*", "*", "kwargs", ")", ":", "with", "_IpmiCommand", "(", "*", "*", "kwargs", ")", "as", "s", ":", "return", "s", ".", "set_identify", "(", "on", "=", "on", ",", "d...
27.72
0.001395
def from_dataframe(cls, dataframe, column, offset=0): """ Creates and return a Series from a DataFrame and specific column :param dataframe: raccoon DataFrame :param column: column name :param offset: offset value must be provided as there is no equivalent for a DataFrame ...
[ "def", "from_dataframe", "(", "cls", ",", "dataframe", ",", "column", ",", "offset", "=", "0", ")", ":", "return", "cls", "(", "data", "=", "dataframe", ".", "get_entire_column", "(", "column", ",", "as_list", "=", "True", ")", ",", "index", "=", "data...
49.363636
0.009042
def update_vertices(self, vertices): """ Update the triangle vertices. """ vertices = np.array(vertices, dtype=np.float32) self._vbo_v.set_data(vertices)
[ "def", "update_vertices", "(", "self", ",", "vertices", ")", ":", "vertices", "=", "np", ".", "array", "(", "vertices", ",", "dtype", "=", "np", ".", "float32", ")", "self", ".", "_vbo_v", ".", "set_data", "(", "vertices", ")" ]
26.857143
0.010309
def refresh_access_token(credential): """Use a refresh token to request a new access token. Not suported for access tokens obtained via Implicit Grant. Parameters credential (OAuth2Credential) An authorized user's OAuth 2.0 credentials. Returns (Session) A new Ses...
[ "def", "refresh_access_token", "(", "credential", ")", ":", "if", "credential", ".", "grant_type", "==", "auth", ".", "AUTHORIZATION_CODE_GRANT", ":", "response", "=", "request_access_token", "(", "grant_type", "=", "auth", ".", "REFRESH_TOKEN", ",", "client_id", ...
36
0.00053
def fit(self, train_X, train_Y, val_X=None, val_Y=None, graph=None): """Fit the model to the data. Parameters ---------- train_X : array_like, shape (n_samples, n_features) Training data. train_Y : array_like, shape (n_samples, n_classes) Training label...
[ "def", "fit", "(", "self", ",", "train_X", ",", "train_Y", ",", "val_X", "=", "None", ",", "val_Y", "=", "None", ",", "graph", "=", "None", ")", ":", "if", "len", "(", "train_Y", ".", "shape", ")", "!=", "1", ":", "num_classes", "=", "train_Y", "...
33.954545
0.001301
def read(self, buffer_size, window_size, x, y, p, address, length_bytes): """Read a bytestring from an address in memory. ..note:: This method is included here to maintain API compatibility with an `alternative implementation of SCP <https://github.com/project-rig/ri...
[ "def", "read", "(", "self", ",", "buffer_size", ",", "window_size", ",", "x", ",", "y", ",", "p", ",", "address", ",", "length_bytes", ")", ":", "# Prepare the buffer to receive the incoming data", "data", "=", "bytearray", "(", "length_bytes", ")", "mem", "="...
38.753846
0.000774
def _crop_pad_default(x, size, padding_mode='reflection', row_pct:uniform = 0.5, col_pct:uniform = 0.5): "Crop and pad tfm - `row_pct`,`col_pct` sets focal point." padding_mode = _pad_mode_convert[padding_mode] size = tis2hw(size) if x.shape[1:] == torch.Size(size): return x rows,cols = size row...
[ "def", "_crop_pad_default", "(", "x", ",", "size", ",", "padding_mode", "=", "'reflection'", ",", "row_pct", ":", "uniform", "=", "0.5", ",", "col_pct", ":", "uniform", "=", "0.5", ")", ":", "padding_mode", "=", "_pad_mode_convert", "[", "padding_mode", "]",...
48.266667
0.01897
def json_dumps(self, obj): """Serializer for consistency""" return json.dumps(obj, sort_keys=True, indent=4, separators=(',', ': '))
[ "def", "json_dumps", "(", "self", ",", "obj", ")", ":", "return", "json", ".", "dumps", "(", "obj", ",", "sort_keys", "=", "True", ",", "indent", "=", "4", ",", "separators", "=", "(", "','", ",", "': '", ")", ")" ]
48.666667
0.02027
def makeShockHistory(self): ''' Makes a pre-specified history of shocks for the simulation. Shock variables should be named in self.shock_vars, a list of strings that is subclass-specific. This method runs a subset of the standard simulation loop by simulating only mortality and shocks...
[ "def", "makeShockHistory", "(", "self", ")", ":", "# Make sure time is flowing forward and re-initialize the simulation", "orig_time", "=", "self", ".", "time_flow", "self", ".", "timeFwd", "(", ")", "self", ".", "initializeSim", "(", ")", "# Make blank history arrays for...
43.292683
0.009917
def create(name, grid, spacing, diameter, depth, volume=0): """ Creates a labware definition based on a rectangular gird, depth, diameter, and spacing. Note that this function can only create labware with regularly spaced wells in a rectangular format, of equal height, depth, and radius. Irregular l...
[ "def", "create", "(", "name", ",", "grid", ",", "spacing", ",", "diameter", ",", "depth", ",", "volume", "=", "0", ")", ":", "columns", ",", "rows", "=", "grid", "col_spacing", ",", "row_spacing", "=", "spacing", "custom_container", "=", "Container", "("...
46.105263
0.000559
def _format_command(ctx, show_nested, commands=None): """Format the output of `click.Command`.""" # the hidden attribute is part of click 7.x only hence use of getattr if getattr(ctx.command, 'hidden', False): return # description for line in _format_description(ctx): yield line ...
[ "def", "_format_command", "(", "ctx", ",", "show_nested", ",", "commands", "=", "None", ")", ":", "# the hidden attribute is part of click 7.x only hence use of getattr", "if", "getattr", "(", "ctx", ".", "command", ",", "'hidden'", ",", "False", ")", ":", "return",...
21.492754
0.000645
def coerce(value): """ coerce takes a value and attempts to convert it to a float, or int. If none of the conversions are successful, the original value is returned. >>> coerce('3') 3 >>> coerce('3.0') 3.0 >>> coerce('foo') 'foo' >>> coerce({}) {} >>> coerce('{}') '{}' """ with contextlib2.suppre...
[ "def", "coerce", "(", "value", ")", ":", "with", "contextlib2", ".", "suppress", "(", "Exception", ")", ":", "loaded", "=", "json", ".", "loads", "(", "value", ")", "assert", "isinstance", "(", "loaded", ",", "numbers", ".", "Number", ")", "return", "l...
14.642857
0.050343
def _construct_axes_dict(self, axes=None, **kwargs): """Return an axes dictionary for myself.""" d = {a: self._get_axis(a) for a in (axes or self._AXIS_ORDERS)} d.update(kwargs) return d
[ "def", "_construct_axes_dict", "(", "self", ",", "axes", "=", "None", ",", "*", "*", "kwargs", ")", ":", "d", "=", "{", "a", ":", "self", ".", "_get_axis", "(", "a", ")", "for", "a", "in", "(", "axes", "or", "self", ".", "_AXIS_ORDERS", ")", "}",...
42.8
0.009174
def histogram_bin_edges_minwidth(min_width, bins): r''' Merge bins with right-neighbour until each bin has a minimum width. :arguments: **bins** (``<array_like>``) The bin-edges. **min_width** (``<float>``) The minimum bin width. ''' # escape if min_width is None : return bins if min_width is ...
[ "def", "histogram_bin_edges_minwidth", "(", "min_width", ",", "bins", ")", ":", "# escape", "if", "min_width", "is", "None", ":", "return", "bins", "if", "min_width", "is", "False", ":", "return", "bins", "# keep removing where needed", "while", "True", ":", "id...
22.321429
0.033742
def gaussian_smear(self, r): """ Applies an isotropic Gaussian smear of width (standard deviation) r to the potential field. This is necessary to avoid finding paths through narrow minima or nodes that may exist in the field (although any potential or charge distribution generate...
[ "def", "gaussian_smear", "(", "self", ",", "r", ")", ":", "# Since scaling factor in fractional coords is not isotropic, have to", "# have different radii in 3 directions", "a_lat", "=", "self", ".", "__s", ".", "lattice", ".", "a", "b_lat", "=", "self", ".", "__s", "...
48.333333
0.001803
def event_return(events): ''' Send the events to a mattermost room. :param events: List of events :return: Boolean if messages were sent successfully. ''' _options = _get_options() api_url = _options.get('api_url') channel = _options.get('channel') username = _optio...
[ "def", "event_return", "(", "events", ")", ":", "_options", "=", "_get_options", "(", ")", "api_url", "=", "_options", ".", "get", "(", "'api_url'", ")", "channel", "=", "_options", ".", "get", "(", "'channel'", ")", "username", "=", "_options", ".", "ge...
30
0.001076
def _en_to_enth(energy,concs,A,B,C): """Converts an energy to an enthalpy. Converts energy to enthalpy using the following formula: Enthalpy = energy - (energy contribution from A) - (energy contribution from B) - (energy contribution from C) An absolute value is taken afterward for convenience...
[ "def", "_en_to_enth", "(", "energy", ",", "concs", ",", "A", ",", "B", ",", "C", ")", ":", "enth", "=", "abs", "(", "energy", "-", "concs", "[", "0", "]", "*", "A", "-", "concs", "[", "1", "]", "*", "B", "-", "concs", "[", "2", "]", "*", ...
25.62069
0.011673
def factor_kkt(S_LU, R, d): """ Factor the U22 block that we can only do after we know D. """ nBatch, nineq = d.size() neq = S_LU[1].size(1) - nineq # TODO: There's probably a better way to add a batched diagonal. global factor_kkt_eye if factor_kkt_eye is None or factor_kkt_eye.size() != d.size...
[ "def", "factor_kkt", "(", "S_LU", ",", "R", ",", "d", ")", ":", "nBatch", ",", "nineq", "=", "d", ".", "size", "(", ")", "neq", "=", "S_LU", "[", "1", "]", ".", "size", "(", "1", ")", "-", "nineq", "# TODO: There's probably a better way to add a batche...
37.756757
0.001396
def rpm_name(self, name, python_version=None, pkg_name=False): """Checks if name converted using superclass rpm_name_method match name of package in the query. Searches for correct name if it doesn't. Args: name: name to convert python_version: python version for which to...
[ "def", "rpm_name", "(", "self", ",", "name", ",", "python_version", "=", "None", ",", "pkg_name", "=", "False", ")", ":", "if", "pkg_name", ":", "return", "super", "(", "DandifiedNameConvertor", ",", "self", ")", ".", "rpm_name", "(", "name", ",", "pytho...
43.777778
0.000993
def text(self, data): """Generates SpaceCharacters and Characters tokens Depending on what's in the data, this generates one or more ``SpaceCharacters`` and ``Characters`` tokens. For example: >>> from html5lib.treewalkers.base import TreeWalker >>> # Give it a...
[ "def", "text", "(", "self", ",", "data", ")", ":", "data", "=", "data", "middle", "=", "data", ".", "lstrip", "(", "spaceCharacters", ")", "left", "=", "data", "[", ":", "len", "(", "data", ")", "-", "len", "(", "middle", ")", "]", "if", "left", ...
35.972973
0.001463
def _dims2shape(*dims): """Convert input dimensions to a shape.""" if not dims: raise ValueError("expected at least one dimension spec") shape = list() for dim in dims: if isinstance(dim, int): dim = (0, dim) if isinstance(dim, tuple) and len(dim) == 2: if...
[ "def", "_dims2shape", "(", "*", "dims", ")", ":", "if", "not", "dims", ":", "raise", "ValueError", "(", "\"expected at least one dimension spec\"", ")", "shape", "=", "list", "(", ")", "for", "dim", "in", "dims", ":", "if", "isinstance", "(", "dim", ",", ...
37.95
0.001285
def list_files(directory): """Returns all files in a given directory """ return [f for f in pathlib.Path(directory).iterdir() if f.is_file() and not f.name.startswith('.')]
[ "def", "list_files", "(", "directory", ")", ":", "return", "[", "f", "for", "f", "in", "pathlib", ".", "Path", "(", "directory", ")", ".", "iterdir", "(", ")", "if", "f", ".", "is_file", "(", ")", "and", "not", "f", ".", "name", ".", "startswith", ...
45.25
0.01087
def empty_dir_list(saltenv='base', backend=None): ''' .. versionadded:: 2015.5.0 Return a list of empty directories in the given environment saltenv : base The salt fileserver environment to be listed backend Narrow fileserver backends to a subset of the enabled ones. If all ...
[ "def", "empty_dir_list", "(", "saltenv", "=", "'base'", ",", "backend", "=", "None", ")", ":", "fileserver", "=", "salt", ".", "fileserver", ".", "Fileserver", "(", "__opts__", ")", "load", "=", "{", "'saltenv'", ":", "saltenv", ",", "'fsbackend'", ":", ...
35.771429
0.000778
def simple_memoize(callable_object): """Simple memoization for functions without keyword arguments. This is useful for mapping code objects to module in this context. inspect.getmodule() requires a number of system calls, which may slow down the tracing considerably. Caching the mapping from code objec...
[ "def", "simple_memoize", "(", "callable_object", ")", ":", "cache", "=", "dict", "(", ")", "def", "wrapper", "(", "*", "rest", ")", ":", "if", "rest", "not", "in", "cache", ":", "cache", "[", "rest", "]", "=", "callable_object", "(", "*", "rest", ")"...
34.333333
0.00135
def count(self, with_limit_and_skip=False): ''' Execute a count on the number of results this query would return. :param with_limit_and_skip: Include ``.limit()`` and ``.skip()`` arguments in the count? ''' return self.__get_query_result().cursor.count(with_limit_and_skip=with_limit...
[ "def", "count", "(", "self", ",", "with_limit_and_skip", "=", "False", ")", ":", "return", "self", ".", "__get_query_result", "(", ")", ".", "cursor", ".", "count", "(", "with_limit_and_skip", "=", "with_limit_and_skip", ")" ]
54.166667
0.012121