text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def make_quadratic(poly, strength, vartype=None, bqm=None): """Create a binary quadratic model from a higher order polynomial. Args: poly (dict): Polynomial as a dict of form {term: bias, ...}, where `term` is a tuple of variables and `bias` the associated bias. strengt...
[ "def", "make_quadratic", "(", "poly", ",", "strength", ",", "vartype", "=", "None", ",", "bqm", "=", "None", ")", ":", "if", "bqm", "is", "None", ":", "if", "vartype", "is", "None", ":", "raise", "ValueError", "(", "\"one of vartype and bqm must be provided\...
35.823529
25.411765
def add_item(self, item, replace = False): """ Add an item to the roster. This will not automatically update the roster on the server. :Parameters: - `item`: the item to add - `replace`: if `True` then existing item will be replaced, otherwise a `V...
[ "def", "add_item", "(", "self", ",", "item", ",", "replace", "=", "False", ")", ":", "if", "item", ".", "jid", "in", "self", ".", "_jids", ":", "if", "replace", ":", "self", ".", "remove_item", "(", "item", ".", "jid", ")", "else", ":", "raise", ...
32.545455
14.727273
def _reinit_daq_daemons(sender, instance, **kwargs): """ update the daq daemon configuration when changes be applied in the models """ if type(instance) is VISADevice: post_save.send_robust(sender=Device, instance=instance.visa_device) elif type(instance) is VISAVariable: post_save.s...
[ "def", "_reinit_daq_daemons", "(", "sender", ",", "instance", ",", "*", "*", "kwargs", ")", ":", "if", "type", "(", "instance", ")", "is", "VISADevice", ":", "post_save", ".", "send_robust", "(", "sender", "=", "Device", ",", "instance", "=", "instance", ...
48
20.133333
def get_requester(self): """ Returns an object to make authenticated requests. See python `requests` for the API. """ # TODO(abrahms): Perhaps pull this out into a factory function for # generating an EdxApi instance with the proper requester & credentials. session = requ...
[ "def", "get_requester", "(", "self", ")", ":", "# TODO(abrahms): Perhaps pull this out into a factory function for", "# generating an EdxApi instance with the proper requester & credentials.", "session", "=", "requests", ".", "session", "(", ")", "session", ".", "headers", ".", ...
35.428571
19.52381
def filter(self, cls_or_collection, query, raw = False,only = None,include = None): """ Filter objects from the database that correspond to a given set of properties. See :py:meth:`blitzdb.backends.base.Backend.filter` for documentation of individual parameters .. note:: T...
[ "def", "filter", "(", "self", ",", "cls_or_collection", ",", "query", ",", "raw", "=", "False", ",", "only", "=", "None", ",", "include", "=", "None", ")", ":", "if", "not", "isinstance", "(", "cls_or_collection", ",", "six", ".", "string_types", ")", ...
59.095522
31.322388
def _memoize(self, name, getter, *args, **kwargs): """ Cache a stable expensive-to-get item value for later (optimized) retrieval. """ field = "custom_m_" + name cached = self.fetch(field) if cached: value = cached else: value = getter(*args, **kwa...
[ "def", "_memoize", "(", "self", ",", "name", ",", "getter", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "field", "=", "\"custom_m_\"", "+", "name", "cached", "=", "self", ".", "fetch", "(", "field", ")", "if", "cached", ":", "value", "=", ...
39.583333
14.083333
def on_pytoml_dumps(self, pytoml, config, dictionary, **kwargs): """ The `pytoml <https://pypi.org/project/pytoml/>`_ dumps method. :param module pytoml: The ``pytoml`` module :param class config: The instance's config class :param dict dictionary: The dictionary to serialize :r...
[ "def", "on_pytoml_dumps", "(", "self", ",", "pytoml", ",", "config", ",", "dictionary", ",", "*", "*", "kwargs", ")", ":", "inline_tables", "=", "set", "(", "kwargs", ".", "get", "(", "\"inline_tables\"", ",", "[", "]", ")", ")", "if", "len", "(", "i...
41.714286
16.785714
def run_all(logdir, verbose=False): """Generate waves of the shapes defined above. Arguments: logdir: the directory into which to store all the runs' data verbose: if true, print out each run's name as it begins """ waves = [sine_wave, square_wave, triangle_wave, bisine_wave, bisine_wahwah_w...
[ "def", "run_all", "(", "logdir", ",", "verbose", "=", "False", ")", ":", "waves", "=", "[", "sine_wave", ",", "square_wave", ",", "triangle_wave", ",", "bisine_wave", ",", "bisine_wahwah_wave", "]", "for", "(", "i", ",", "wave_constructor", ")", "in", "enu...
37.666667
12.533333
def track_event(self, name: str, properties: Dict[str, object] = None, measurements: Dict[str, object] = None) -> None: """ Send information about a single event that has occurred in the context of the application. :param name: the data to associate to this event. :...
[ "def", "track_event", "(", "self", ",", "name", ":", "str", ",", "properties", ":", "Dict", "[", "str", ",", "object", "]", "=", "None", ",", "measurements", ":", "Dict", "[", "str", ",", "object", "]", "=", "None", ")", "->", "None", ":", "pass" ]
63.777778
36.333333
def getConfig(self): """Returns dictionary of config entries for Munin Graph. @return: Dictionary of config entries. """ return {'graph': self._graphAttrDict, 'fields': [(field_name, self._fieldAttrDict.get(field_name)) for fi...
[ "def", "getConfig", "(", "self", ")", ":", "return", "{", "'graph'", ":", "self", ".", "_graphAttrDict", ",", "'fields'", ":", "[", "(", "field_name", ",", "self", ".", "_fieldAttrDict", ".", "get", "(", "field_name", ")", ")", "for", "field_name", "in",...
38.333333
17.555556
def __unset_binding(self, dependency, service, reference): # type: (Any, Any, ServiceReference) -> None """ Removes a service from the component :param dependency: The dependency handler :param service: The injected service :param reference: The reference of the injected...
[ "def", "__unset_binding", "(", "self", ",", "dependency", ",", "service", ",", "reference", ")", ":", "# type: (Any, Any, ServiceReference) -> None", "# Call the component back", "self", ".", "__safe_field_callback", "(", "dependency", ".", "get_field", "(", ")", ",", ...
33.625
18.041667
def b58ToC32(b58check, version=-1): """ >>> b58ToC32('1FzTxL9Mxnm2fdmnQEArfhzJHevwbvcH6d') 'SP2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKNRV9EJ7' >>> b58ToC32('3GgUssdoWh5QkoUDXKqT6LMESBDf8aqp2y') 'SM2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQVX8X0G' >>> b58ToC32('mvWRFPELmpCHSkFQ7o9EVdCd9eXeUTa9T8') 'ST2J6ZY48G...
[ "def", "b58ToC32", "(", "b58check", ",", "version", "=", "-", "1", ")", ":", "addr_version_byte", ",", "addr_bin", ",", "addr_checksum", "=", "keylib", ".", "b58check", ".", "b58check_unpack", "(", "b58check", ")", "addr_version", "=", "ord", "(", "addr_vers...
42.081081
14.837838
def _fully_random_weights(n_features, lam_scale, prng): """Generate a symmetric random matrix with zeros along the diagonal.""" weights = np.zeros((n_features, n_features)) n_off_diag = int((n_features ** 2 - n_features) / 2) weights[np.triu_indices(n_features, k=1)] = 0.1 * lam_scale * prng.randn( ...
[ "def", "_fully_random_weights", "(", "n_features", ",", "lam_scale", ",", "prng", ")", ":", "weights", "=", "np", ".", "zeros", "(", "(", "n_features", ",", "n_features", ")", ")", "n_off_diag", "=", "int", "(", "(", "n_features", "**", "2", "-", "n_feat...
43.4
15.3
def merge(self, other): """ We can merge unless the merge results in an empty set -- a contradiction """ other = self.coerce(other) if self.is_equal(other): # pick among dependencies return self elif other.is_entailed_by(self): ...
[ "def", "merge", "(", "self", ",", "other", ")", ":", "other", "=", "self", ".", "coerce", "(", "other", ")", "if", "self", ".", "is_equal", "(", "other", ")", ":", "# pick among dependencies", "return", "self", "elif", "other", ".", "is_entailed_by", "("...
34.666667
11.583333
def get_metrics(self, name=None): """Get metrics for this operator. Args: name(str, optional): Only return metrics matching `name`, where `name` can be a regular expression. If `name` is not supplied, then all metrics for this operator are returned. Returns: ...
[ "def", "get_metrics", "(", "self", ",", "name", "=", "None", ")", ":", "return", "self", ".", "_get_elements", "(", "self", ".", "metrics", ",", "'metrics'", ",", "Metric", ",", "name", "=", "name", ")" ]
44.684211
27.421053
def visitMembersDef(self, ctx: jsgParser.MembersDefContext): """ membersDef: COMMA | member+ (BAR altMemberDef)* (BAR lastComma)? ; altMemberDef: member* ; member: pairDef COMMA? lastComma: COMMA ; """ if not self._name: self._name = self._context....
[ "def", "visitMembersDef", "(", "self", ",", "ctx", ":", "jsgParser", ".", "MembersDefContext", ")", ":", "if", "not", "self", ".", "_name", ":", "self", ".", "_name", "=", "self", ".", "_context", ".", "anon_id", "(", ")", "if", "ctx", ".", "COMMA", ...
41.190476
13.238095
def setModelData( self, editor, model, index ): """ Sets the data for the given index from the editor's value. :param editor | <QWidget> model | <QAbstractItemModel> index | <QModelIndex> """ tree = self.paren...
[ "def", "setModelData", "(", "self", ",", "editor", ",", "model", ",", "index", ")", ":", "tree", "=", "self", ".", "parent", "(", ")", "querywidget", "=", "tree", ".", "parent", "(", ")", "factory", "=", "querywidget", ".", "factory", "(", ")", "item...
34.933333
9.733333
def p_common_scalar_magic_method(p): 'common_scalar : METHOD_C' p[0] = ast.MagicConstant(p[1].upper(), None, lineno=p.lineno(1))
[ "def", "p_common_scalar_magic_method", "(", "p", ")", ":", "p", "[", "0", "]", "=", "ast", ".", "MagicConstant", "(", "p", "[", "1", "]", ".", "upper", "(", ")", ",", "None", ",", "lineno", "=", "p", ".", "lineno", "(", "1", ")", ")" ]
44.666667
14
def terminate_ex(self, nodes, threads=False, attempts=3): """Wrapper method for terminate. :param nodes: Nodes to be destroyed. :type nodes: ``list`` :param attempts: The amount of attempts for retrying to terminate failed instances. :type attempts: ``int`` :...
[ "def", "terminate_ex", "(", "self", ",", "nodes", ",", "threads", "=", "False", ",", "attempts", "=", "3", ")", ":", "while", "nodes", "and", "attempts", ">", "0", ":", "if", "threads", ":", "nodes", "=", "self", ".", "terminate_with_threads", "(", "no...
34.227273
20.363636
def normalize(self, inplace=False, **kwargs): """Normalize data to a given value. Currently only supports normalizing to a specific time. Parameters ---------- inplace: bool, default False if True, do operation inplace and return None kwargs: the values on wh...
[ "def", "normalize", "(", "self", ",", "inplace", "=", "False", ",", "*", "*", "kwargs", ")", ":", "if", "len", "(", "kwargs", ")", ">", "1", "or", "self", ".", "time_col", "not", "in", "kwargs", ":", "raise", "ValueError", "(", "'Only time(year)-based ...
39.090909
15.181818
def create_rst(self, nb, in_dir, odir): """Create the rst file from the notebook node""" raw_rst, resources = nbconvert.export_by_name('rst', nb) # remove ipython magics rst_content = '' i0 = 0 m = None # HACK: we insert the bokeh style sheets here as well, since ...
[ "def", "create_rst", "(", "self", ",", "nb", ",", "in_dir", ",", "odir", ")", ":", "raw_rst", ",", "resources", "=", "nbconvert", ".", "export_by_name", "(", "'rst'", ",", "nb", ")", "# remove ipython magics", "rst_content", "=", "''", "i0", "=", "0", "m...
44.038462
16.346154
def send_signature_request(self, test_mode=False, files=None, file_urls=None, title=None, subject=None, message=None, signing_redirect_url=None, signers=None, cc_email_addresses=None, form_fields_per_document=None, use_text_tags=False, hide_text_tags=False, metadata=None, ux_version=None, allow_decline=False): ...
[ "def", "send_signature_request", "(", "self", ",", "test_mode", "=", "False", ",", "files", "=", "None", ",", "file_urls", "=", "None", ",", "title", "=", "None", ",", "subject", "=", "None", ",", "message", "=", "None", ",", "signing_redirect_url", "=", ...
49.227848
41.835443
def getRoom(self, _id): """ Retrieve a room from it's id """ if SockJSRoomHandler._room.has_key(self._gcls() + _id): return SockJSRoomHandler._room[self._gcls() + _id] return None
[ "def", "getRoom", "(", "self", ",", "_id", ")", ":", "if", "SockJSRoomHandler", ".", "_room", ".", "has_key", "(", "self", ".", "_gcls", "(", ")", "+", "_id", ")", ":", "return", "SockJSRoomHandler", ".", "_room", "[", "self", ".", "_gcls", "(", ")",...
42.2
16.6
def _gtu8(ins): """ Compares & pops top 2 operands out of the stack, and checks if the 1st operand > 2nd operand (top of the stack). Pushes 0 if False, 1 if True. 8 bit unsigned version """ output = _8bit_oper(ins.quad[2], ins.quad[3], reversed_=True) output.append('cp h') o...
[ "def", "_gtu8", "(", "ins", ")", ":", "output", "=", "_8bit_oper", "(", "ins", ".", "quad", "[", "2", "]", ",", "ins", ".", "quad", "[", "3", "]", ",", "reversed_", "=", "True", ")", "output", ".", "append", "(", "'cp h'", ")", "output", ".", "...
29.230769
17.230769
def _extract_remote_exception(self, pantsd_pid, nailgun_error): """Given a NailgunError, returns a Terminated exception with additional info (where possible). This method will include the entire exception log for either the `pid` in the NailgunError, or failing that, the `pid` of the pantsd instance. "...
[ "def", "_extract_remote_exception", "(", "self", ",", "pantsd_pid", ",", "nailgun_error", ")", ":", "sources", "=", "[", "pantsd_pid", "]", "if", "nailgun_error", ".", "pid", "is", "not", "None", ":", "sources", "=", "[", "abs", "(", "nailgun_error", ".", ...
43.05
22.8
def ping(self, id): """ Pings the motor with the specified id. .. note:: The motor id should always be included in [0, 253]. 254 is used for broadcast. """ pp = self._protocol.DxlPingPacket(id) try: self._send_packet(pp, error_handler=None) retu...
[ "def", "ping", "(", "self", ",", "id", ")", ":", "pp", "=", "self", ".", "_protocol", ".", "DxlPingPacket", "(", "id", ")", "try", ":", "self", ".", "_send_packet", "(", "pp", ",", "error_handler", "=", "None", ")", "return", "True", "except", "DxlTi...
28.615385
22.230769
def write(self, fptr): """Write a Palette box to file. """ self._validate(writing=True) bytes_per_row = sum(self.bits_per_component) / 8 bytes_per_palette = bytes_per_row * self.palette.shape[0] box_length = 8 + 3 + self.palette.shape[1] + bytes_per_palette # Wri...
[ "def", "write", "(", "self", ",", "fptr", ")", ":", "self", ".", "_validate", "(", "writing", "=", "True", ")", "bytes_per_row", "=", "sum", "(", "self", ".", "bits_per_component", ")", "/", "8", "bytes_per_palette", "=", "bytes_per_row", "*", "self", "....
37.64
19.08
def _metrics_get_endpoints(options): """ Determine the start and end dates based on user-supplied options. """ if bool(options.start) ^ bool(options.end): log.error('--start and --end must be specified together') sys.exit(1) if options.start and options.end: start = options.start ...
[ "def", "_metrics_get_endpoints", "(", "options", ")", ":", "if", "bool", "(", "options", ".", "start", ")", "^", "bool", "(", "options", ".", "end", ")", ":", "log", ".", "error", "(", "'--start and --end must be specified together'", ")", "sys", ".", "exit"...
31.5
16.428571
def as_dict(self): """ Returns a dictionary representation of the ChemicalEnvironments object :return: """ return {"@module": self.__class__.__module__, "@class": self.__class__.__name__, "coord_geoms": jsanitize(self.coord_geoms)}
[ "def", "as_dict", "(", "self", ")", ":", "return", "{", "\"@module\"", ":", "self", ".", "__class__", ".", "__module__", ",", "\"@class\"", ":", "self", ".", "__class__", ".", "__name__", ",", "\"coord_geoms\"", ":", "jsanitize", "(", "self", ".", "coord_g...
37
15.75
def get_rules_from_disk(self): ''' Recursively traverse the yara/rules directory for rules ''' # Try to find the yara rules directory relative to the worker my_dir = os.path.dirname(os.path.realpath(__file__)) yara_rule_path = os.path.join(my_dir, 'yara/rules') if not os.path.ex...
[ "def", "get_rules_from_disk", "(", "self", ")", ":", "# Try to find the yara rules directory relative to the worker", "my_dir", "=", "os", ".", "path", ".", "dirname", "(", "os", ".", "path", ".", "realpath", "(", "__file__", ")", ")", "yara_rule_path", "=", "os",...
41.375
25.375
def polyline(*points): """Converts a list of points to a Path composed of lines connecting those points (i.e. a linear spline or polyline). See also `polygon()`.""" return Path(*[Line(points[i], points[i+1]) for i in range(len(points) - 1)])
[ "def", "polyline", "(", "*", "points", ")", ":", "return", "Path", "(", "*", "[", "Line", "(", "points", "[", "i", "]", ",", "points", "[", "i", "+", "1", "]", ")", "for", "i", "in", "range", "(", "len", "(", "points", ")", "-", "1", ")", "...
53.8
7
def energy(q, v): """Compute the kinetic and potential energy of the planetary system""" # Number of points N: int = len(q) # Initialize arrays to zero of the correct size T: np.ndarray = np.zeros(N) U: np.ndarray = np.zeros(N) # Add up kinetic energy of each body for ...
[ "def", "energy", "(", "q", ",", "v", ")", ":", "# Number of points", "N", ":", "int", "=", "len", "(", "q", ")", "# Initialize arrays to zero of the correct size", "T", ":", "np", ".", "ndarray", "=", "np", ".", "zeros", "(", "N", ")", "U", ":", "np", ...
27.621622
16.162162
def from_meta(cls, meta, meta_all=None): """Copy DocstringMeta from another instance.""" if len(meta.args) == 2: name = meta.args[1] meta_type = None for x in meta_all: if x.args[1] == name and x.args[0] == 'type': meta_type = x.des...
[ "def", "from_meta", "(", "cls", ",", "meta", ",", "meta_all", "=", "None", ")", ":", "if", "len", "(", "meta", ".", "args", ")", "==", "2", ":", "name", "=", "meta", ".", "args", "[", "1", "]", "meta_type", "=", "None", "for", "x", "in", "meta_...
39.307692
16.923077
def read_values(target_usage): """read feature report values""" # browse all devices all_devices = hid.HidDeviceFilter().get_devices() if not all_devices: print("Can't find any non system HID device connected") else: # search for our target usage usage_found = False...
[ "def", "read_values", "(", "target_usage", ")", ":", "# browse all devices\r", "all_devices", "=", "hid", ".", "HidDeviceFilter", "(", ")", ".", "get_devices", "(", ")", "if", "not", "all_devices", ":", "print", "(", "\"Can't find any non system HID device connected\"...
39.730769
15.615385
def network_start(name, **kwargs): ''' Start a defined virtual network. :param name: virtual network name :param connection: libvirt connection URI, overriding defaults :param username: username to connect with, overriding defaults :param password: password to connect with, overriding defaults ...
[ "def", "network_start", "(", "name", ",", "*", "*", "kwargs", ")", ":", "conn", "=", "__get_conn", "(", "*", "*", "kwargs", ")", "try", ":", "net", "=", "conn", ".", "networkLookupByName", "(", "name", ")", "return", "not", "bool", "(", "net", ".", ...
25.391304
22
def glsl_type(self): """ GLSL declaration strings required for a variable to hold this data. """ if self.dtype is None: return None dtshape = self.dtype[0].shape n = dtshape[0] if dtshape else 1 if n > 1: dtype = 'vec%d' % n else: ...
[ "def", "glsl_type", "(", "self", ")", ":", "if", "self", ".", "dtype", "is", "None", ":", "return", "None", "dtshape", "=", "self", ".", "dtype", "[", "0", "]", ".", "shape", "n", "=", "dtshape", "[", "0", "]", "if", "dtshape", "else", "1", "if",...
33.833333
12.333333
def delete_cloud_integration(self, id, **kwargs): # noqa: E501 """Delete a specific cloud integration # 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.delete_c...
[ "def", "delete_cloud_integration", "(", "self", ",", "id", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async_req'", ")", ":", "return", "self", ".", "del...
43.238095
20.047619
def close(self): """ Closes connection to database. """ if getattr(self, '_connection', None): logger.debug('Closing postgresql connection.') self._connection.close() self._connection = None if getattr(self, '_engine', None): self._engine.dispose()
[ "def", "close", "(", "self", ")", ":", "if", "getattr", "(", "self", ",", "'_connection'", ",", "None", ")", ":", "logger", ".", "debug", "(", "'Closing postgresql connection.'", ")", "self", ".", "_connection", ".", "close", "(", ")", "self", ".", "_con...
39.125
8.125
def count(self, **kwargs): """ Performs a COUNT statement on the model's table in the replica database. :param select: Column to be counted. :type select: string :param where: WHERE clause of the SELECT statement. This can be a plain string, a dict or an array. :type whe...
[ "def", "count", "(", "self", ",", "*", "*", "kwargs", ")", ":", "if", "'select'", "in", "kwargs", ":", "kwargs", "[", "'select'", "]", "=", "{", "'cnt'", ":", "'COUNT(%s)'", "%", "kwargs", "[", "'select'", "]", "}", "else", ":", "kwargs", "[", "'se...
39.75
21
def _fsync_files(filenames): """Call fsync() a list of file names The filenames should be absolute paths already. """ touched_directories = set() mode = os.O_RDONLY # Windows if hasattr(os, 'O_BINARY'): mode |= os.O_BINARY for filename in filenames: fd = os.open(file...
[ "def", "_fsync_files", "(", "filenames", ")", ":", "touched_directories", "=", "set", "(", ")", "mode", "=", "os", ".", "O_RDONLY", "# Windows", "if", "hasattr", "(", "os", ",", "'O_BINARY'", ")", ":", "mode", "|=", "os", ".", "O_BINARY", "for", "filenam...
26.148148
18.62963
def iso_to_gregorian(iso_year, iso_week, iso_day): "Gregorian calendar date for the given ISO year, week and day" year_start = iso_year_start(iso_year) return year_start + datetime.timedelta(days=iso_day - 1, weeks=iso_week - 1)
[ "def", "iso_to_gregorian", "(", "iso_year", ",", "iso_week", ",", "iso_day", ")", ":", "year_start", "=", "iso_year_start", "(", "iso_year", ")", "return", "year_start", "+", "datetime", ".", "timedelta", "(", "days", "=", "iso_day", "-", "1", ",", "weeks", ...
59.25
19.25
def project_from_files( files, func_wrapper=_astroid_wrapper, project_name="no name", black_list=("CVS",) ): """return a Project from a list of files or modules""" # build the project representation astroid_manager = manager.AstroidManager() project = Project(project_name) for something in files...
[ "def", "project_from_files", "(", "files", ",", "func_wrapper", "=", "_astroid_wrapper", ",", "project_name", "=", "\"no name\"", ",", "black_list", "=", "(", "\"CVS\"", ",", ")", ")", ":", "# build the project representation", "astroid_manager", "=", "manager", "."...
42.59375
16.65625
def _step(self, model: TrainingModel, batch: mx.io.DataBatch, checkpoint_interval: int, metric_train: mx.metric.EvalMetric, metric_loss: Optional[mx.metric.EvalMetric] = None): """ Performs an update to model given a batch and updates...
[ "def", "_step", "(", "self", ",", "model", ":", "TrainingModel", ",", "batch", ":", "mx", ".", "io", ".", "DataBatch", ",", "checkpoint_interval", ":", "int", ",", "metric_train", ":", "mx", ".", "metric", ".", "EvalMetric", ",", "metric_loss", ":", "Opt...
40.95082
22.918033
def get_integrator(integrator): """Return the scipy.integrator indicated by an index, name, or integrator_function >> get_integrator(0) """ integrator_types = set(['trapz', 'cumtrapz', 'simps', 'romb']) integrator_funcs = [integrate.trapz, integrate.cumtrapz, integrate.simps, integrate.romb] i...
[ "def", "get_integrator", "(", "integrator", ")", ":", "integrator_types", "=", "set", "(", "[", "'trapz'", ",", "'cumtrapz'", ",", "'simps'", ",", "'romb'", "]", ")", "integrator_funcs", "=", "[", "integrate", ".", "trapz", ",", "integrate", ".", "cumtrapz",...
45
23.473684
def get_section_metrics(cls): """ Get the mapping between metrics and sections in Manuscripts report :return: a dict with the mapping between metrics and sections in Manuscripts report """ return { "overview": { "activity_metrics": [Commits], ...
[ "def", "get_section_metrics", "(", "cls", ")", ":", "return", "{", "\"overview\"", ":", "{", "\"activity_metrics\"", ":", "[", "Commits", "]", ",", "\"author_metrics\"", ":", "[", "Authors", "]", ",", "\"bmi_metrics\"", ":", "[", "]", ",", "\"time_to_close_met...
35.444444
13.833333
def cielab_to_msh (cielab): """Convert CIE L*a*b* to Moreland's Msh colorspace. *cielab* should be of shape (*, 3). Return value will have same shape. """ msh = np.empty_like (cielab) msh[...,M] = np.sqrt ((cielab**2).sum (axis=-1)) msh[...,S] = np.arccos (cielab[...,L] / msh[...,M]) ...
[ "def", "cielab_to_msh", "(", "cielab", ")", ":", "msh", "=", "np", ".", "empty_like", "(", "cielab", ")", "msh", "[", "...", ",", "M", "]", "=", "np", ".", "sqrt", "(", "(", "cielab", "**", "2", ")", ".", "sum", "(", "axis", "=", "-", "1", ")...
29
16.538462
def add_conditional_clause(self, clause): """ Adds a iff clause to this statement :param clause: The clause that will be added to the iff statement :type clause: ConditionalClause """ clause.set_context_id(self.context_counter) self.context_counter += clause.get_...
[ "def", "add_conditional_clause", "(", "self", ",", "clause", ")", ":", "clause", ".", "set_context_id", "(", "self", ".", "context_counter", ")", "self", ".", "context_counter", "+=", "clause", ".", "get_context_size", "(", ")", "self", ".", "conditionals", "....
36.6
10.6
def _wrap_value_with_context(self, tokens: List[Token], start: int, end: int) -> Extraction: """Wraps the final result""" return Extraction(' '.join([x.orth_ if isinstance(x, Token) else x for x in tokens[start:end]]), self.name, start_token=start, ...
[ "def", "_wrap_value_with_context", "(", "self", ",", "tokens", ":", "List", "[", "Token", "]", ",", "start", ":", "int", ",", "end", ":", "int", ")", "->", "Extraction", ":", "return", "Extraction", "(", "' '", ".", "join", "(", "[", "x", ".", "orth_...
70.4
34.2
def angle(v1, v2): """Return the angle in radians between vectors 'v1' and 'v2'.""" v1_u = unit_vector(v1) v2_u = unit_vector(v2) return np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))
[ "def", "angle", "(", "v1", ",", "v2", ")", ":", "v1_u", "=", "unit_vector", "(", "v1", ")", "v2_u", "=", "unit_vector", "(", "v2", ")", "return", "np", ".", "arccos", "(", "np", ".", "clip", "(", "np", ".", "dot", "(", "v1_u", ",", "v2_u", ")",...
39.6
14
def send(self, request, socket, context, *args): """ When an event is sent, run all relevant handlers. Relevant handlers are those without a channel pattern when the given socket is not subscribed to any particular channel, or the handlers with a channel pattern that matches any ...
[ "def", "send", "(", "self", ",", "request", ",", "socket", ",", "context", ",", "*", "args", ")", ":", "for", "handler", ",", "pattern", "in", "self", ".", "handlers", ":", "no_channel", "=", "not", "pattern", "and", "not", "socket", ".", "channels", ...
48.210526
17.894737
def send_spyder_msg(self, spyder_msg_type, content=None, data=None): """ Publish custom messages to the Spyder frontend. Parameters ---------- spyder_msg_type: str The spyder message type content: dict The (JSONable) content of the message ...
[ "def", "send_spyder_msg", "(", "self", ",", "spyder_msg_type", ",", "content", "=", "None", ",", "data", "=", "None", ")", ":", "import", "cloudpickle", "if", "content", "is", "None", ":", "content", "=", "{", "}", "content", "[", "'spyder_msg_type'", "]",...
31
18.5
def _index_keys_for(self, idx_name, *ids_and_fcs): '''Returns a generator of index triples. Returns a generator of index keys for the ``ids_and_fcs`` pairs given. The index keys have the form ``(idx_name, idx_val, content_id)``. :type idx_name: unicode :type ids_and_fcs...
[ "def", "_index_keys_for", "(", "self", ",", "idx_name", ",", "*", "ids_and_fcs", ")", ":", "idx", "=", "self", ".", "_index", "(", "idx_name", ")", "icreate", ",", "itrans", "=", "idx", "[", "'create'", "]", ",", "idx", "[", "'transform'", "]", "if", ...
39.769231
18.384615
def optimal_reroot(self, force_positive=True, slope=None): """ determine the best root and reroot the tree to this value. Note that this can change the parent child relations of the tree and values associated with branches rather than nodes (e.g. confidence) might need to be re-e...
[ "def", "optimal_reroot", "(", "self", ",", "force_positive", "=", "True", ",", "slope", "=", "None", ")", ":", "best_root", "=", "self", ".", "find_best_root", "(", "force_positive", "=", "force_positive", ",", "slope", "=", "slope", ")", "best_node", "=", ...
36.433962
20.886792
def broadcast_event(self, event, *args): """ This is sent to all in the sockets in this particular Namespace, including itself. """ pkt = dict(type="event", name=event, args=args, endpoint=self.ns_name) for sessid,...
[ "def", "broadcast_event", "(", "self", ",", "event", ",", "*", "args", ")", ":", "pkt", "=", "dict", "(", "type", "=", "\"event\"", ",", "name", "=", "event", ",", "args", "=", "args", ",", "endpoint", "=", "self", ".", "ns_name", ")", "for", "sess...
33.166667
12.833333
def get(self, split_id: str) -> Split: """ load transaction by id """ query = ( self.query .filter(Split.guid == split_id) ) return query.one()
[ "def", "get", "(", "self", ",", "split_id", ":", "str", ")", "->", "Split", ":", "query", "=", "(", "self", ".", "query", ".", "filter", "(", "Split", ".", "guid", "==", "split_id", ")", ")", "return", "query", ".", "one", "(", ")" ]
27.571429
13
def _merge_wf_outputs(new, cur, parallel): """Merge outputs for a sub-workflow, replacing variables changed in later steps. ignore_ids are those used internally in a sub-workflow but not exposed to subsequent steps """ new_ids = set([]) out = [] for v in new: outv = {} outv["sou...
[ "def", "_merge_wf_outputs", "(", "new", ",", "cur", ",", "parallel", ")", ":", "new_ids", "=", "set", "(", "[", "]", ")", "out", "=", "[", "]", "for", "v", "in", "new", ":", "outv", "=", "{", "}", "outv", "[", "\"source\"", "]", "=", "v", "[", ...
36.181818
17.681818
def main(): """The main entry """ args = getArguments() try: if args.action == 'init': # Ask for init while True: print 'Initialize the path [%s] will cause any files or dirs be removed, continue?[y/n]' % args.basePath, text = raw_input() ...
[ "def", "main", "(", ")", ":", "args", "=", "getArguments", "(", ")", "try", ":", "if", "args", ".", "action", "==", "'init'", ":", "# Ask for init", "while", "True", ":", "print", "'Initialize the path [%s] will cause any files or dirs be removed, continue?[y/n]'", ...
38.25
16.634615
def get_application(self, id=None, name=None): """ Get application object by name or id. """ log.info("Picking application: %s (%s)" % (name, id)) return self.applications[id or name]
[ "def", "get_application", "(", "self", ",", "id", "=", "None", ",", "name", "=", "None", ")", ":", "log", ".", "info", "(", "\"Picking application: %s (%s)\"", "%", "(", "name", ",", "id", ")", ")", "return", "self", ".", "applications", "[", "id", "or...
42.2
6.2
def GetCellStyle (self, column, row = None): """ get the "style" of a cell note: this merges default, column, row and the cell's style into the actual style for you returning a dictionary of styles The values directly from excel with the relavent XML el...
[ "def", "GetCellStyle", "(", "self", ",", "column", ",", "row", "=", "None", ")", ":", "if", "row", "==", "None", ":", "(", "row", ",", "column", ")", "=", "ParseCellSpec", "(", "column", ")", "style", "=", "{", "}", "# get style for cell\r", "if", "r...
52.935484
18.741935
def browserify_file(entry_point, output_file, babelify=False, export_as=None): """ Browserify a single javascript entry point plus non-external dependencies into a single javascript file. Generates source maps in debug mode. Minifies the output in release mode. By default, it is not possible to ``r...
[ "def", "browserify_file", "(", "entry_point", ",", "output_file", ",", "babelify", "=", "False", ",", "export_as", "=", "None", ")", ":", "from", ".", "modules", "import", "browserify", "if", "not", "isinstance", "(", "entry_point", ",", "str", ")", ":", "...
38.423077
22.192308
def _generate_ffmpeg_cmd( self, cmd: List[str], input_source: Optional[str], output: Optional[str], extra_cmd: Optional[str] = None, ) -> None: """Generate ffmpeg command line.""" self._argv = [self._ffmpeg] # start command init if input_sourc...
[ "def", "_generate_ffmpeg_cmd", "(", "self", ",", "cmd", ":", "List", "[", "str", "]", ",", "input_source", ":", "Optional", "[", "str", "]", ",", "output", ":", "Optional", "[", "str", "]", ",", "extra_cmd", ":", "Optional", "[", "str", "]", "=", "No...
27.761905
13.904762
def _ensure_sparse_format(spmatrix, accept_sparse, dtype, order, copy, force_all_finite): """Convert a sparse matrix to a given format. Checks the sparse format of spmatrix and converts if necessary. Parameters ---------- spmatrix : scipy sparse matrix Input to va...
[ "def", "_ensure_sparse_format", "(", "spmatrix", ",", "accept_sparse", ",", "dtype", ",", "order", ",", "copy", ",", "force_all_finite", ")", ":", "if", "accept_sparse", "is", "None", ":", "raise", "TypeError", "(", "'A sparse matrix was passed, but dense '", "'data...
36.873016
19.984127
def copy(self, name, exclude_from_current=False, deep_copy=False): """ Creates a copy of this cell. Parameters ---------- name : string The name of the cell. exclude_from_current : bool If ``True``, the cell will not be included in the global ...
[ "def", "copy", "(", "self", ",", "name", ",", "exclude_from_current", "=", "False", ",", "deep_copy", "=", "False", ")", ":", "new_cell", "=", "Cell", "(", "name", ",", "exclude_from_current", ")", "if", "deep_copy", ":", "new_cell", ".", "elements", "=", ...
34.625
16.8125
def add_parser_arguments(parser, args, group=None, prefix=DATA_PREFIX): """ Helper method that populates parser arguments. The argument values can be later retrieved with `extract_arguments` method. The `args` argument to this method should be a dict with strings as keys and dicts as values. The ke...
[ "def", "add_parser_arguments", "(", "parser", ",", "args", ",", "group", "=", "None", ",", "prefix", "=", "DATA_PREFIX", ")", ":", "if", "group", ":", "parser", "=", "parser", ".", "add_argument_group", "(", "group", ")", "for", "arg", ",", "kwargs", "in...
44.375
19.791667
def closeEvent(self, event): """save the name of the last open dataset.""" max_dataset_history = self.value('max_dataset_history') keep_recent_datasets(max_dataset_history, self.info) settings.setValue('window/geometry', self.saveGeometry()) settings.setValue('window/state', sel...
[ "def", "closeEvent", "(", "self", ",", "event", ")", ":", "max_dataset_history", "=", "self", ".", "value", "(", "'max_dataset_history'", ")", "keep_recent_datasets", "(", "max_dataset_history", ",", "self", ".", "info", ")", "settings", ".", "setValue", "(", ...
38.888889
21.888889
def api_server(connection, server_class): """ Establishes an API Server on the supplied connection Arguments: - connection (xbahn.connection.Connection) - server_class (xbahn.api.Server) Returns: - server_class: server instance """ # run api server on connection re...
[ "def", "api_server", "(", "connection", ",", "server_class", ")", ":", "# run api server on connection", "return", "server_class", "(", "link", "=", "xbahn", ".", "connection", ".", "link", ".", "Link", "(", "# use the connection to receive messages", "receive", "=", ...
26.47619
16.47619
def object_path(self, key): '''return the object path for `key`.''' return os.path.join(self.root_path, self.relative_object_path(key))
[ "def", "object_path", "(", "self", ",", "key", ")", ":", "return", "os", ".", "path", ".", "join", "(", "self", ".", "root_path", ",", "self", ".", "relative_object_path", "(", "key", ")", ")" ]
47
15.666667
def _make_inputnode(self, frequency): """ Generates an input node for the given frequency. It also adds implicit file format conversion nodes to the pipeline. Parameters ---------- frequency : str The frequency (i.e. 'per_session', 'per_visit', 'per_subject' ...
[ "def", "_make_inputnode", "(", "self", ",", "frequency", ")", ":", "# Check to see whether there are any outputs for the given frequency", "inputs", "=", "list", "(", "self", ".", "frequency_inputs", "(", "frequency", ")", ")", "# Get list of input names for the requested fre...
52.757143
20.414286
def smart_url(url, obj=None): """ URLs that start with @ are reversed, using the passed in arguments. Otherwise a straight % substitution is applied. """ if url.find("@") >= 0: (args, value) = url.split('@') if args: val = getattr(obj, args, None) return rev...
[ "def", "smart_url", "(", "url", ",", "obj", "=", "None", ")", ":", "if", "url", ".", "find", "(", "\"@\"", ")", ">=", "0", ":", "(", "args", ",", "value", ")", "=", "url", ".", "split", "(", "'@'", ")", "if", "args", ":", "val", "=", "getattr...
25.052632
16.631579
async def response_writer(self, stream, response_queue): """ :py:func:`asyncio.coroutine` Worker for write_response with current connection. Get data to response from queue, this is for right order of responses. Exits if received :py:class:`None`. :param stream: command...
[ "async", "def", "response_writer", "(", "self", ",", "stream", ",", "response_queue", ")", ":", "while", "True", ":", "args", "=", "await", "response_queue", ".", "get", "(", ")", "try", ":", "await", "self", ".", "write_response", "(", "stream", ",", "*...
33.85
18.15
def __process_by_python(self): """! @brief Performs processing using python implementation. """ for amount in range(self.__kmin, self.__kmax): centers = self.__initializer(self.__data, amount).initialize() instance = kmeans(self.__data, centers, ccore=True...
[ "def", "__process_by_python", "(", "self", ")", ":", "for", "amount", "in", "range", "(", "self", ".", "__kmin", ",", "self", ".", "__kmax", ")", ":", "centers", "=", "self", ".", "__initializer", "(", "self", ".", "__data", ",", "amount", ")", ".", ...
33.857143
18.5
def post_create_app(cls, app, **settings): """Init the extension for our chosen ORM Backend, if possible. This method will ensure that the ``db`` proxy is set to the right extension and that that extension is properly created and configured. Since it needs to call ``init_app`` it MUST b...
[ "def", "post_create_app", "(", "cls", ",", "app", ",", "*", "*", "settings", ")", ":", "global", "_SELECTED_BACKEND", "backend", "=", "settings", ".", "pop", "(", "'orm_backend'", ",", "None", ")", "backend", "=", "_discover_ideal_backend", "(", "backend", "...
44.583333
23.231481
def merge_cookies(cookiejar, cookies): """Add cookies to cookiejar and returns a merged CookieJar. :param cookiejar: CookieJar object to add the cookies to. :param cookies: Dictionary or CookieJar object to be added. :rtype: CookieJar """ if not isinstance(cookiejar, cookielib.CookieJar): ...
[ "def", "merge_cookies", "(", "cookiejar", ",", "cookies", ")", ":", "if", "not", "isinstance", "(", "cookiejar", ",", "cookielib", ".", "CookieJar", ")", ":", "raise", "ValueError", "(", "'You can only merge into CookieJar'", ")", "if", "isinstance", "(", "cooki...
35.238095
15.619048
def check_restructuredtext(self): """ Checks if the long string fields are reST-compliant. """ # Warn that this command is deprecated # Don't use self.warn() because it will cause the check to fail. Command.warn( self, "This command has been deprec...
[ "def", "check_restructuredtext", "(", "self", ")", ":", "# Warn that this command is deprecated", "# Don't use self.warn() because it will cause the check to fail.", "Command", ".", "warn", "(", "self", ",", "\"This command has been deprecated. Use `twine check` instead: \"", "\"https:...
37.454545
21.454545
def set_pointer0d(subseqs): """Set_pointer function for 0-dimensional link sequences.""" print(' . set_pointer0d') lines = Lines() lines.add(1, 'cpdef inline set_pointer0d' '(self, str name, pointerutils.PDouble value):') for seq in subseqs: ...
[ "def", "set_pointer0d", "(", "subseqs", ")", ":", "print", "(", "' . set_pointer0d'", ")", "lines", "=", "Lines", "(", ")", "lines", ".", "add", "(", "1", ",", "'cpdef inline set_pointer0d'", "'(self, str name, pointerutils.PDouble value):'", ")", "for", ...
44.4
14.2
def store(self, value, l, dir_only): """Group patterns by literals and potential magic patterns.""" if l and value in (b'', ''): return globstar = value in (b'**', '**') and self.globstar magic = self.is_magic(value) if magic: value = compile(value, self...
[ "def", "store", "(", "self", ",", "value", ",", "l", ",", "dir_only", ")", ":", "if", "l", "and", "value", "in", "(", "b''", ",", "''", ")", ":", "return", "globstar", "=", "value", "in", "(", "b'**'", ",", "'**'", ")", "and", "self", ".", "glo...
34.818182
17
def _parse_ip_stats_link_show(raw_result): """ Parse the 'ip -s link show dev <dev>' command raw output. :param str raw_result: vtysh raw result string. :rtype: dict :return: The parsed result of the show interface command in a \ dictionary of the form: :: { 'rx_b...
[ "def", "_parse_ip_stats_link_show", "(", "raw_result", ")", ":", "show_re", "=", "(", "r'.+?RX:.*?\\n'", "r'\\s*(?P<rx_bytes>\\d+)\\s+(?P<rx_packets>\\d+)\\s+(?P<rx_errors>\\d+)\\s+'", "r'(?P<rx_dropped>\\d+)\\s+(?P<rx_overrun>\\d+)\\s+(?P<rx_mcast>\\d+)'", "r'.+?TX:.*?\\n'", "r'\\s*(?P<tx...
27.0625
20.6875
def inline_css(self, html): """Inlines CSS defined in external style sheets. """ premailer = Premailer(html) inlined_html = premailer.transform(pretty_print=True) return inlined_html
[ "def", "inline_css", "(", "self", ",", "html", ")", ":", "premailer", "=", "Premailer", "(", "html", ")", "inlined_html", "=", "premailer", ".", "transform", "(", "pretty_print", "=", "True", ")", "return", "inlined_html" ]
36.166667
8.666667
def create_toggle_view_action(self): """Associate a toggle view action with each plugin""" title = self.get_plugin_title() if self.CONF_SECTION == 'editor': title = _('Editor') if self.shortcut is not None: action = create_action(self, title, ...
[ "def", "create_toggle_view_action", "(", "self", ")", ":", "title", "=", "self", ".", "get_plugin_title", "(", ")", "if", "self", ".", "CONF_SECTION", "==", "'editor'", ":", "title", "=", "_", "(", "'Editor'", ")", "if", "self", ".", "shortcut", "is", "n...
49.285714
14.071429
def run(namespace=None, action_prefix='action_', args=None): """Run the script. Participating actions are looked up in the caller's namespace if no namespace is given, otherwise in the dict provided. Only items that start with action_prefix are processed as actions. If you want to use all items in the...
[ "def", "run", "(", "namespace", "=", "None", ",", "action_prefix", "=", "'action_'", ",", "args", "=", "None", ")", ":", "if", "namespace", "is", "None", ":", "namespace", "=", "sys", ".", "_getframe", "(", "1", ")", ".", "f_locals", "actions", "=", ...
36.6625
17.4375
def delete(self): """Extend to the delete the session from storage """ self.clear() if os.path.isfile(self._filename): os.unlink(self._filename) else: LOGGER.debug('Session file did not exist: %s', self._filename)
[ "def", "delete", "(", "self", ")", ":", "self", ".", "clear", "(", ")", "if", "os", ".", "path", ".", "isfile", "(", "self", ".", "_filename", ")", ":", "os", ".", "unlink", "(", "self", ".", "_filename", ")", "else", ":", "LOGGER", ".", "debug",...
30
16.555556
def __conn_listener(self, state): """ Connection event listener :param state: The new connection state """ if state == KazooState.CONNECTED: self.__online = True if not self.__connected: self.__connected = True self._logger...
[ "def", "__conn_listener", "(", "self", ",", "state", ")", ":", "if", "state", "==", "KazooState", ".", "CONNECTED", ":", "self", ".", "__online", "=", "True", "if", "not", "self", ".", "__connected", ":", "self", ".", "__connected", "=", "True", "self", ...
37
13.538462
def convertTime(self, time): """Convert a datetime object representing a time into a human-ready string that can be read, spoken aloud, etc. Args: time (datetime.date): A datetime object to be converted into text. Returns: A string representation of the input ti...
[ "def", "convertTime", "(", "self", ",", "time", ")", ":", "# if ':00', ignore reporting minutes", "m_format", "=", "\"\"", "if", "time", ".", "minute", ":", "m_format", "=", "\":%M\"", "timeString", "=", "time", ".", "strftime", "(", "\"%I\"", "+", "m_format",...
29.73913
20.173913
def _on_watermark_notification(self, notif): """Handle a watermark notification.""" # Update the conversation: if self.get_user(notif.user_id).is_self: logger.info('latest_read_timestamp for {} updated to {}' .format(self.id_, notif.read_timestamp)) ...
[ "def", "_on_watermark_notification", "(", "self", ",", "notif", ")", ":", "# Update the conversation:", "if", "self", ".", "get_user", "(", "notif", ".", "user_id", ")", ".", "is_self", ":", "logger", ".", "info", "(", "'latest_read_timestamp for {} updated to {}'",...
50.565217
19.521739
def gerrymanderNodeFilenames(self): ''' When creating nodes, the filename needs to be relative to ``conf.py``, so it will include ``self.root_directory``. However, when generating the API, the file we are writing to is in the same directory as the generated node files so we need...
[ "def", "gerrymanderNodeFilenames", "(", "self", ")", ":", "for", "node", "in", "self", ".", "all_nodes", ":", "node", ".", "file_name", "=", "os", ".", "path", ".", "basename", "(", "node", ".", "file_name", ")", "if", "node", ".", "kind", "==", "\"fil...
55.083333
27.25
def register_parser_callback(self, func): """ Register a callback function that is called after self.iocs and self.ioc_name is populated. This is intended for use by subclasses that may have additional parsing requirements. :param func: A callable function. This should accept a singl...
[ "def", "register_parser_callback", "(", "self", ",", "func", ")", ":", "if", "hasattr", "(", "func", ",", "'__call__'", ")", ":", "self", ".", "parser_callback", "=", "func", "log", ".", "debug", "(", "'Set callback to {}'", ".", "format", "(", "func", ")"...
43.071429
26.5
def requirements(self): """Process requirements.""" class dotdict(dict): # pylint: disable=invalid-name """Dot notation access to dictionary attributes.""" def __getattr__(self, attr): value = self.get(attr) return dotdict(value) if isinstance(va...
[ "def", "requirements", "(", "self", ")", ":", "class", "dotdict", "(", "dict", ")", ":", "# pylint: disable=invalid-name", "\"\"\"Dot notation access to dictionary attributes.\"\"\"", "def", "__getattr__", "(", "self", ",", "attr", ")", ":", "value", "=", "self", "....
39
17
def cookbook_statement(cookbook_name, metadata=None): """Return a valid Ruby 'cookbook' statement for the Berksfile.""" line = "cookbook '%s'" % cookbook_name if metadata: if not isinstance(metadata, dict): raise TypeError("Berksfile dependency hash for %s " ...
[ "def", "cookbook_statement", "(", "cookbook_name", ",", "metadata", "=", "None", ")", ":", "line", "=", "\"cookbook '%s'\"", "%", "cookbook_name", "if", "metadata", ":", "if", "not", "isinstance", "(", "metadata", ",", "dict", ")", ":", "raise", "TypeError", ...
49.071429
13.142857
def get_all_chats(self): """ Fetches all chats :return: List of chats :rtype: list[Chat] """ chats = self.wapi_functions.getAllChats() if chats: return [factory_chat(chat, self) for chat in chats] else: return []
[ "def", "get_all_chats", "(", "self", ")", ":", "chats", "=", "self", ".", "wapi_functions", ".", "getAllChats", "(", ")", "if", "chats", ":", "return", "[", "factory_chat", "(", "chat", ",", "self", ")", "for", "chat", "in", "chats", "]", "else", ":", ...
24.166667
16.333333
def _count_spaces_startswith(line): ''' Count the number of spaces before the first character ''' if line.split('#')[0].strip() == "": return None spaces = 0 for i in line: if i.isspace(): spaces += 1 else: return spaces
[ "def", "_count_spaces_startswith", "(", "line", ")", ":", "if", "line", ".", "split", "(", "'#'", ")", "[", "0", "]", ".", "strip", "(", ")", "==", "\"\"", ":", "return", "None", "spaces", "=", "0", "for", "i", "in", "line", ":", "if", "i", ".", ...
21.615385
21
def getExceptionMessage(exception, frame=-1, filename=None): """ Return a short message based on an exception, useful for debugging. Tries to find where the exception was triggered. """ stack = traceback.extract_tb(sys.exc_info()[2]) if filename: stack = [f for f in stack if f[0].find(fi...
[ "def", "getExceptionMessage", "(", "exception", ",", "frame", "=", "-", "1", ",", "filename", "=", "None", ")", ":", "stack", "=", "traceback", ".", "extract_tb", "(", "sys", ".", "exc_info", "(", ")", "[", "2", "]", ")", "if", "filename", ":", "stac...
35
19.75
def to_gremlin(self): """Return a unicode object with the Gremlin representation of this block.""" self.validate() if len(self.start_class) == 1: # The official Gremlin documentation claims that this approach # is generally faster than the one below, since it makes using ...
[ "def", "to_gremlin", "(", "self", ")", ":", "self", ".", "validate", "(", ")", "if", "len", "(", "self", ".", "start_class", ")", "==", "1", ":", "# The official Gremlin documentation claims that this approach", "# is generally faster than the one below, since it makes us...
60.083333
27.25
def process_certificates(service_name, relation_id, unit, custom_hostname_link=None, user='root', group='root'): """Process the certificates supplied down the relation :param service_name: str Name of service the certifcates are for. :param relation_id: str Relation id providing th...
[ "def", "process_certificates", "(", "service_name", ",", "relation_id", ",", "unit", ",", "custom_hostname_link", "=", "None", ",", "user", "=", "'root'", ",", "group", "=", "'root'", ")", ":", "data", "=", "relation_get", "(", "rid", "=", "relation_id", ","...
41.483871
19
def has_permission(self, request): """Check if user has permission""" if not self.object and not self.permission: return True if not self.permission: return request.user.has_perm('{}_{}'.format( self.model_permission, self.object.__class__...
[ "def", "has_permission", "(", "self", ",", "request", ")", ":", "if", "not", "self", ".", "object", "and", "not", "self", ".", "permission", ":", "return", "True", "if", "not", "self", ".", "permission", ":", "return", "request", ".", "user", ".", "has...
34.083333
17.416667
def policy_definitions_list(hide_builtin=False, **kwargs): ''' .. versionadded:: 2019.2.0 List all policy definitions for a subscription. :param hide_builtin: Boolean which will filter out BuiltIn policy definitions from the result. CLI Example: .. code-block:: bash salt-call azurea...
[ "def", "policy_definitions_list", "(", "hide_builtin", "=", "False", ",", "*", "*", "kwargs", ")", ":", "result", "=", "{", "}", "polconn", "=", "__utils__", "[", "'azurearm.get_client'", "]", "(", "'policy'", ",", "*", "*", "kwargs", ")", "try", ":", "p...
30.392857
28.75
def readline(self, size=-1): "The size is ignored since a complete line must be read." line = self.fin.readline() if not line: return '' return self.process_line(line.rstrip('\n'))
[ "def", "readline", "(", "self", ",", "size", "=", "-", "1", ")", ":", "line", "=", "self", ".", "fin", ".", "readline", "(", ")", "if", "not", "line", ":", "return", "''", "return", "self", ".", "process_line", "(", "line", ".", "rstrip", "(", "'...
36.5
15.5
def training_pass(self, input_data, targets): """ Perform a full forward and backward pass through the model. **Parameters:** input_data : GPUArray Data to train the model with. targets : GPUArray Training targets. **Returns:** loss : float ...
[ "def", "training_pass", "(", "self", ",", "input_data", ",", "targets", ")", ":", "# Forward pass", "loss", ",", "hidden_cache", ",", "logistic_cache", "=", "self", ".", "evaluate", "(", "input_data", ",", "targets", ",", "return_cache", "=", "True", ",", "p...
30.76
21
def signal(*args, **kwargs): from .core import Signal """A signal decorator designed to work both in the simpler way, like: .. code:: python @signal def validation_function(arg1, ...): '''Some doc''' and also as a double-called decorator, like .. code:: python @signa...
[ "def", "signal", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "from", ".", "core", "import", "Signal", "if", "len", "(", "args", ")", "==", "1", "and", "len", "(", "kwargs", ")", "==", "0", "and", "callable", "(", "args", "[", "0", "]",...
25.37037
17.962963
def best_policy(mdp, U): """Given an MDP and a utility function U, determine the best policy, as a mapping from state to action. (Equation 17.4)""" pi = {} for s in mdp.states: pi[s] = argmax(mdp.actions(s), lambda a:expected_utility(a, s, U, mdp)) return pi
[ "def", "best_policy", "(", "mdp", ",", "U", ")", ":", "pi", "=", "{", "}", "for", "s", "in", "mdp", ".", "states", ":", "pi", "[", "s", "]", "=", "argmax", "(", "mdp", ".", "actions", "(", "s", ")", ",", "lambda", "a", ":", "expected_utility", ...
40
18.142857
def get_settings(self, integration_id): """Return settings for given integration as a dictionary.""" try: integration = self.get(integration_id=integration_id) return json.loads(integration.settings) except (self.model.DoesNotExist, ValueError): return {}
[ "def", "get_settings", "(", "self", ",", "integration_id", ")", ":", "try", ":", "integration", "=", "self", ".", "get", "(", "integration_id", "=", "integration_id", ")", "return", "json", ".", "loads", "(", "integration", ".", "settings", ")", "except", ...
38.625
17.125