text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def get_all_direct_statements(self): """Get all directlyIncreases/Decreases BEL statements. This method stores the results of the query in self.all_direct_stmts as a list of strings. The SPARQL query used to find direct BEL statements searches for all statements whose predicate is eithe...
[ "def", "get_all_direct_statements", "(", "self", ")", ":", "logger", ".", "info", "(", "\"Getting all direct statements...\\n\"", ")", "q_stmts", "=", "prefixes", "+", "\"\"\"\n SELECT ?stmt\n WHERE {\n ?stmt a belvoc:Statement .\n ...
39.26087
19.521739
def card_names_and_ids(self): """Returns [(name, id), ...] pairs of cards from current board""" b = Board(self.client, self.board_id) cards = b.getCards() card_names_and_ids = [(unidecode(c.name), c.id) for c in cards] return card_names_and_ids
[ "def", "card_names_and_ids", "(", "self", ")", ":", "b", "=", "Board", "(", "self", ".", "client", ",", "self", ".", "board_id", ")", "cards", "=", "b", ".", "getCards", "(", ")", "card_names_and_ids", "=", "[", "(", "unidecode", "(", "c", ".", "name...
46.5
11
async def _handle_watermark_notification(self, watermark_notification): """Receive WatermarkNotification and update the conversation. Args: watermark_notification: hangouts_pb2.WatermarkNotification instance """ conv_id = watermark_notification.conversation_id.id res...
[ "async", "def", "_handle_watermark_notification", "(", "self", ",", "watermark_notification", ")", ":", "conv_id", "=", "watermark_notification", ".", "conversation_id", ".", "id", "res", "=", "parsers", ".", "parse_watermark_notification", "(", "watermark_notification", ...
42.111111
22.111111
def clear_end_timestamp(self): """stub""" if (self.get_end_timestamp_metadata().is_read_only() or self.get_end_timestamp_metadata().is_required()): raise NoAccess() self.my_osid_object_form._my_map['endTimestamp'] = \ self.get_end_timestamp_metadata().get_...
[ "def", "clear_end_timestamp", "(", "self", ")", ":", "if", "(", "self", ".", "get_end_timestamp_metadata", "(", ")", ".", "is_read_only", "(", ")", "or", "self", ".", "get_end_timestamp_metadata", "(", ")", ".", "is_required", "(", ")", ")", ":", "raise", ...
48.285714
17.714286
def validate_contents(file_contents): """Ensures that all ipynb files in FILE_CONTENTS are valid JSON files.""" for name, contents in file_contents.items(): if os.path.splitext(name)[1] != '.ipynb': continue if not contents: return False try: json_...
[ "def", "validate_contents", "(", "file_contents", ")", ":", "for", "name", ",", "contents", "in", "file_contents", ".", "items", "(", ")", ":", "if", "os", ".", "path", ".", "splitext", "(", "name", ")", "[", "1", "]", "!=", "'.ipynb'", ":", "continue"...
31.153846
12.384615
def addons(cls, recurse=True): """ Returns a dictionary containing all the available addons for this mixin class. If the optional recurse flag is set to True, then all the base classes will be searched for the given addon as well. :param recurse | <bool> ...
[ "def", "addons", "(", "cls", ",", "recurse", "=", "True", ")", ":", "cls", ".", "initAddons", "(", ")", "prop", "=", "'_{0}__addons'", ".", "format", "(", "cls", ".", "__name__", ")", "out", "=", "{", "}", "# lookup base classes", "if", "recurse", ":",...
33.434783
18.043478
def step(self, substeps=2): '''Step the world forward by one frame. Parameters ---------- substeps : int, optional Split the step into this many sub-steps. This helps to prevent the time delta for an update from being too large. ''' self.frame_no ...
[ "def", "step", "(", "self", ",", "substeps", "=", "2", ")", ":", "self", ".", "frame_no", "+=", "1", "dt", "=", "self", ".", "dt", "/", "substeps", "for", "_", "in", "range", "(", "substeps", ")", ":", "self", ".", "ode_contactgroup", ".", "empty",...
34.266667
16.8
def future_get_sensor(self, name, update=None): """Get the sensor object. Check if we have information for this sensor, if not connect to server and update (if allowed) to get information. Parameters ---------- name : string Name of the sensor. updat...
[ "def", "future_get_sensor", "(", "self", ",", "name", ",", "update", "=", "None", ")", ":", "obj", "=", "None", "exist", "=", "yield", "self", ".", "future_check_sensor", "(", "name", ",", "update", ")", "if", "exist", ":", "sensor_info", "=", "self", ...
35.444444
18.955556
def setAvatar(self, image): """ Update the profile picture for the current user. Args: image (file): a file-like object to read the image from """ self.conn("PUT", "{0}/users/{1}/profile/avatar".format(SkypeConnection.API_USER, self.userId), auth=Sk...
[ "def", "setAvatar", "(", "self", ",", "image", ")", ":", "self", ".", "conn", "(", "\"PUT\"", ",", "\"{0}/users/{1}/profile/avatar\"", ".", "format", "(", "SkypeConnection", ".", "API_USER", ",", "self", ".", "userId", ")", ",", "auth", "=", "SkypeConnection...
40.111111
24.333333
def get_net_imbalance(count_per_broker): """Calculate and return net imbalance based on given count of partitions or leaders per broker. Net-imbalance in case of partitions implies total number of extra partitions from optimal count over all brokers. This is also implies, the minimum number of part...
[ "def", "get_net_imbalance", "(", "count_per_broker", ")", ":", "net_imbalance", "=", "0", "opt_count", ",", "extra_allowed", "=", "compute_optimum", "(", "len", "(", "count_per_broker", ")", ",", "sum", "(", "count_per_broker", ")", ")", "for", "count", "in", ...
39.55
15.25
def models_list(self, api_url=None, offset=0, limit=-1, properties=None): """Get list of model resources from a SCO-API. Parameters ---------- api_url : string, optional Base Url of the SCO-API. Uses default API if argument not present. offset : int, optional ...
[ "def", "models_list", "(", "self", ",", "api_url", "=", "None", ",", "offset", "=", "0", ",", "limit", "=", "-", "1", ",", "properties", "=", "None", ")", ":", "# Get subject listing Url for given SCO-API and return the retrieved", "# resource listing", "return", ...
35.25
19.785714
def to_clipboard(self, excel=True, sep=None, **kwargs): r""" Copy object to the system clipboard. Write a text representation of object to the system clipboard. This can be pasted into Excel, for example. Parameters ---------- excel : bool, default True ...
[ "def", "to_clipboard", "(", "self", ",", "excel", "=", "True", ",", "sep", "=", "None", ",", "*", "*", "kwargs", ")", ":", "from", "pandas", ".", "io", "import", "clipboards", "clipboards", ".", "to_clipboard", "(", "self", ",", "excel", "=", "excel", ...
31.25
22.660714
def set_buf_size(fd): """Set up os pipe buffer size, if applicable""" if OS_PIPE_SZ and hasattr(fcntl, 'F_SETPIPE_SZ'): fcntl.fcntl(fd, fcntl.F_SETPIPE_SZ, OS_PIPE_SZ)
[ "def", "set_buf_size", "(", "fd", ")", ":", "if", "OS_PIPE_SZ", "and", "hasattr", "(", "fcntl", ",", "'F_SETPIPE_SZ'", ")", ":", "fcntl", ".", "fcntl", "(", "fd", ",", "fcntl", ".", "F_SETPIPE_SZ", ",", "OS_PIPE_SZ", ")" ]
45
11.75
def delete(self, *args, **kwargs): """ delete image when an image record is deleted """ try: os.remove(self.file.file.name) # image does not exist except (OSError, IOError): pass super(Image, self).delete(*args, **kwargs)
[ "def", "delete", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "os", ".", "remove", "(", "self", ".", "file", ".", "file", ".", "name", ")", "# image does not exist", "except", "(", "OSError", ",", "IOError", ")", ":...
34.75
10.75
def RSA(im: array, radius: int, volume_fraction: int = 1, mode: str = 'extended'): r""" Generates a sphere or disk packing using Random Sequential Addition This which ensures that spheres do not overlap but does not guarantee they are tightly packed. Parameters ---------- im : ND-a...
[ "def", "RSA", "(", "im", ":", "array", ",", "radius", ":", "int", ",", "volume_fraction", ":", "int", "=", "1", ",", "mode", ":", "str", "=", "'extended'", ")", ":", "# Note: The 2D vs 3D splitting of this just me being lazy...I can't be", "# bothered to figure it o...
37.893204
23.631068
def ToMilliseconds(self): """Converts a Duration to milliseconds.""" millis = _RoundTowardZero(self.nanos, _NANOS_PER_MILLISECOND) return self.seconds * _MILLIS_PER_SECOND + millis
[ "def", "ToMilliseconds", "(", "self", ")", ":", "millis", "=", "_RoundTowardZero", "(", "self", ".", "nanos", ",", "_NANOS_PER_MILLISECOND", ")", "return", "self", ".", "seconds", "*", "_MILLIS_PER_SECOND", "+", "millis" ]
47.25
13.25
def list_images(list_all=False, full_ids=False): """ Lists images on the Docker remote host, similar to ``docker images``. :param list_all: Lists all images (e.g. dependencies). Default is ``False``, only shows named images. :type list_all: bool :param full_ids: Shows the full ids. When ``False`` (...
[ "def", "list_images", "(", "list_all", "=", "False", ",", "full_ids", "=", "False", ")", ":", "images", "=", "docker_fabric", "(", ")", ".", "images", "(", "all", "=", "list_all", ")", "_format_output_table", "(", "images", ",", "IMAGE_COLUMNS", ",", "full...
45
24.090909
def md2tvd(self, kind='linear'): """ Provides an transformation and interpolation function that converts MD to TVD. Args: kind (str): The kind of interpolation to do, e.g. 'linear', 'cubic', 'nearest'. Returns: function. """ ...
[ "def", "md2tvd", "(", "self", ",", "kind", "=", "'linear'", ")", ":", "if", "self", ".", "position", "is", "None", ":", "return", "lambda", "x", ":", "x", "return", "interp1d", "(", "self", ".", "md", ",", "self", ".", "tvd", ",", "kind", "=", "k...
30.368421
15.315789
async def update_state(self, msg, _context): """Update the status of a service.""" name = msg.get('name') status = msg.get('new_status') await self.service_manager.update_state(name, status)
[ "async", "def", "update_state", "(", "self", ",", "msg", ",", "_context", ")", ":", "name", "=", "msg", ".", "get", "(", "'name'", ")", "status", "=", "msg", ".", "get", "(", "'new_status'", ")", "await", "self", ".", "service_manager", ".", "update_st...
31.142857
16.714286
def _save_pickle(self, filename): """Save sensors to pickle file.""" with open(filename, 'wb') as file_handle: pickle.dump(self._sensors, file_handle, pickle.HIGHEST_PROTOCOL) file_handle.flush() os.fsync(file_handle.fileno())
[ "def", "_save_pickle", "(", "self", ",", "filename", ")", ":", "with", "open", "(", "filename", ",", "'wb'", ")", "as", "file_handle", ":", "pickle", ".", "dump", "(", "self", ".", "_sensors", ",", "file_handle", ",", "pickle", ".", "HIGHEST_PROTOCOL", "...
45.5
10.5
def get_sw_dir(sw_dir=None): """ Returns the software directory defined in the ``config.software_dir`` config. When *sw_dir* is not *None*, it is expanded and returned instead. """ if sw_dir is None: sw_dir = Config.instance().get("core", "software_dir") sw_dir = os.path.expandvars(os.p...
[ "def", "get_sw_dir", "(", "sw_dir", "=", "None", ")", ":", "if", "sw_dir", "is", "None", ":", "sw_dir", "=", "Config", ".", "instance", "(", ")", ".", "get", "(", "\"core\"", ",", "\"software_dir\"", ")", "sw_dir", "=", "os", ".", "path", ".", "expan...
32
22.181818
def pylint(ctx, skip_tests=False, skip_root=False, reports=False): """Perform source code checks via pylint.""" cfg = config.load() add_dir2pypath(cfg.project_root) if not os.path.exists(cfg.testjoin('__init__.py')): add_dir2pypath(cfg.testjoin()) namelist = set() for package in cfg.pro...
[ "def", "pylint", "(", "ctx", ",", "skip_tests", "=", "False", ",", "skip_root", "=", "False", ",", "reports", "=", "False", ")", ":", "cfg", "=", "config", ".", "load", "(", ")", "add_dir2pypath", "(", "cfg", ".", "project_root", ")", "if", "not", "o...
38.339286
19.125
def projection(self, exprs): """ Like mutate, but do not include existing table columns """ w = self._get_window() windowed_exprs = [] exprs = self.table._resolve(exprs) for expr in exprs: expr = L.windowize_function(expr, w=w) windowed_exp...
[ "def", "projection", "(", "self", ",", "exprs", ")", ":", "w", "=", "self", ".", "_get_window", "(", ")", "windowed_exprs", "=", "[", "]", "exprs", "=", "self", ".", "table", ".", "_resolve", "(", "exprs", ")", "for", "expr", "in", "exprs", ":", "e...
34.363636
8.727273
def quit(self): """ This function quits PlanarRad, checking if PlanarRad is running before. """ """ Nothing programmed for displaying a message box when the user clicks on the window cross in order to quit. """ if self.is_running == True: warning_pla...
[ "def", "quit", "(", "self", ")", ":", "\"\"\"\n Nothing programmed for displaying a message box when the user clicks on the window cross in order to quit.\n \"\"\"", "if", "self", ".", "is_running", "==", "True", ":", "warning_planarrad_running", "=", "QtGui", ".", ...
45.35
29.55
def _gen_4spec(op, path, value, create_path=False, xattr=False, _expand_macros=False): """ Like `_gen_3spec`, but also accepts a mandatory value as its third argument :param bool _expand_macros: Whether macros in the value should be expanded. The macros themselves are defined at the s...
[ "def", "_gen_4spec", "(", "op", ",", "path", ",", "value", ",", "create_path", "=", "False", ",", "xattr", "=", "False", ",", "_expand_macros", "=", "False", ")", ":", "flags", "=", "0", "if", "create_path", ":", "flags", "|=", "_P", ".", "SDSPEC_F_MKD...
36.6
16.066667
def nf_step_to_process(step, out_handle): """Convert CWL step into a nextflow process. """ pprint.pprint(step) directives = [] for req in step["task_definition"]["requirements"]: if req["requirement_type"] == "docker": directives.append("container '%s'" % req["value"]) e...
[ "def", "nf_step_to_process", "(", "step", ",", "out_handle", ")", ":", "pprint", ".", "pprint", "(", "step", ")", "directives", "=", "[", "]", "for", "req", "in", "step", "[", "\"task_definition\"", "]", "[", "\"requirements\"", "]", ":", "if", "req", "[...
47.409091
20.272727
def api_key_post(params, request_path, _async=False): """ from 火币demo, 构造post请求并调用post方法 :param params: :param request_path: :return: """ method = 'POST' timestamp = datetime.datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S') params_to_sign = { 'AccessKeyId': ACCESS_KEY, ...
[ "def", "api_key_post", "(", "params", ",", "request_path", ",", "_async", "=", "False", ")", ":", "method", "=", "'POST'", "timestamp", "=", "datetime", ".", "datetime", ".", "utcnow", "(", ")", ".", "strftime", "(", "'%Y-%m-%dT%H:%M:%S'", ")", "params_to_si...
36.269231
18.346154
def set_prefix(self, prefix): """ Set the prefix for the node (see Leaf class). DEPRECATED; use the prefix property directly. """ warnings.warn("set_prefix() is deprecated; use the prefix property", DeprecationWarning, stacklevel=2) self.prefix = pr...
[ "def", "set_prefix", "(", "self", ",", "prefix", ")", ":", "warnings", ".", "warn", "(", "\"set_prefix() is deprecated; use the prefix property\"", ",", "DeprecationWarning", ",", "stacklevel", "=", "2", ")", "self", ".", "prefix", "=", "prefix" ]
35.111111
15.555556
def fit( self, durations, event_observed=None, timeline=None, entry=None, label="KM_estimate", left_censorship=False, alpha=None, ci_labels=None, weights=None, ): # pylint: disable=too-many-arguments,too-many-locals """ ...
[ "def", "fit", "(", "self", ",", "durations", ",", "event_observed", "=", "None", ",", "timeline", "=", "None", ",", "entry", "=", "None", ",", "label", "=", "\"KM_estimate\"", ",", "left_censorship", "=", "False", ",", "alpha", "=", "None", ",", "ci_labe...
48.113208
30.037736
def _merge_csv_column(table, csvs): """ Add csv data to each column in a list of columns :param dict table: Table metadata :param str crumbs: Hierarchy crumbs :param str pc: Paleo or Chron table type :return dict: Table metadata with csv "values" entry :return bool ensemble: Ensemble data o...
[ "def", "_merge_csv_column", "(", "table", ",", "csvs", ")", ":", "# Start putting CSV data into corresponding column \"values\" key", "try", ":", "ensemble", "=", "is_ensemble", "(", "table", "[", "\"columns\"", "]", ")", "if", "ensemble", ":", "# realization columns", ...
46.836735
21.734694
def setWorkingCollisionBoundsInfo(self, unQuadsCount): """Sets the Collision Bounds in the working copy.""" fn = self.function_table.setWorkingCollisionBoundsInfo pQuadsBuffer = HmdQuad_t() fn(byref(pQuadsBuffer), unQuadsCount) return pQuadsBuffer
[ "def", "setWorkingCollisionBoundsInfo", "(", "self", ",", "unQuadsCount", ")", ":", "fn", "=", "self", ".", "function_table", ".", "setWorkingCollisionBoundsInfo", "pQuadsBuffer", "=", "HmdQuad_t", "(", ")", "fn", "(", "byref", "(", "pQuadsBuffer", ")", ",", "un...
40.285714
14.285714
def _state_after_transition(self, current_state: int, target_state: int) -> int: """ Return the state reachable after a transition. Since the state for a gene can only change by 1, if the absolute value of the difference current_state - target_state is greater than 1, we lower it to 1 or...
[ "def", "_state_after_transition", "(", "self", ",", "current_state", ":", "int", ",", "target_state", ":", "int", ")", "->", "int", ":", "return", "current_state", "+", "(", "current_state", "<", "target_state", ")", "-", "(", "current_state", ">", "target_sta...
44.55
23.45
def from_structures(cls, structures, specie, temperature, time_step, step_skip, initial_disp=None, initial_structure=None, **kwargs): """ Convenient constructor that takes in a list of Structure objects to perform diffusion analysis. Args:...
[ "def", "from_structures", "(", "cls", ",", "structures", ",", "specie", ",", "temperature", ",", "time_step", ",", "step_skip", ",", "initial_disp", "=", "None", ",", "initial_structure", "=", "None", ",", "*", "*", "kwargs", ")", ":", "p", ",", "l", "="...
45.301587
20.190476
def _val_fs_regex(self, record, hist=None): """ Perform field-specific validation regex :param dict record: dictionary of values to validate :param dict hist: existing input of history values """ record, hist = self.data_regex_method(fields_list=self.fields, ...
[ "def", "_val_fs_regex", "(", "self", ",", "record", ",", "hist", "=", "None", ")", ":", "record", ",", "hist", "=", "self", ".", "data_regex_method", "(", "fields_list", "=", "self", ".", "fields", ",", "mongo_db_obj", "=", "self", ".", "mongo", ",", "...
42.285714
19.714286
def type(subtag, type): """ Get a :class:`language_tags.Subtag.Subtag` by subtag and type. Can be None if not exists. :param str subtag: subtag. :param str type: type of the subtag. :return: :class:`language_tags.Subtag.Subtag` if exists, otherwise None. """ subt...
[ "def", "type", "(", "subtag", ",", "type", ")", ":", "subtag", "=", "subtag", ".", "lower", "(", ")", "if", "subtag", "in", "index", ":", "types", "=", "index", "[", "subtag", "]", "if", "type", "in", "types", ":", "return", "Subtag", "(", "subtag"...
34.428571
16.285714
def get( table, session, version_id=None, t1=None, t2=None, fields=None, conds=None, include_deleted=True, page=1, page_size=100, ): """ :param table: the model class which inherits from :class:`~savage.models.user_table.SavageModelMixin` and specifies the model o...
[ "def", "get", "(", "table", ",", "session", ",", "version_id", "=", "None", ",", "t1", "=", "None", ",", "t2", "=", "None", ",", "fields", "=", "None", ",", "conds", "=", "None", ",", "include_deleted", "=", "True", ",", "page", "=", "1", ",", "p...
47.785714
27.957143
def create_jdbc_resource(name, server=None, **kwargs): ''' Create a JDBC resource ''' defaults = { 'description': '', 'enabled': True, 'id': name, 'poolName': '', 'target': 'server' } # Data = defaults + merge kwargs + poolname data = defaults dat...
[ "def", "create_jdbc_resource", "(", "name", ",", "server", "=", "None", ",", "*", "*", "kwargs", ")", ":", "defaults", "=", "{", "'description'", ":", "''", ",", "'enabled'", ":", "True", ",", "'id'", ":", "name", ",", "'poolName'", ":", "''", ",", "...
23.75
22.85
def read_jp2_image(filename): """ Read data from JPEG2000 file :param filename: name of JPEG2000 file to be read :type filename: str :return: data stored in JPEG2000 file """ # Other option: # return glymur.Jp2k(filename)[:] image = read_image(filename) with open(filename, 'rb') as...
[ "def", "read_jp2_image", "(", "filename", ")", ":", "# Other option:", "# return glymur.Jp2k(filename)[:]", "image", "=", "read_image", "(", "filename", ")", "with", "open", "(", "filename", ",", "'rb'", ")", "as", "file", ":", "bit_depth", "=", "get_jp2_bit_depth...
26.666667
13.4
def shift_coordinate_grid(self, x_shift, y_shift, pixel_unit=False): """ shifts the coordinate system :param x_shif: shift in x (or RA) :param y_shift: shift in y (or DEC) :param pixel_unit: bool, if True, units of pixels in input, otherwise RA/DEC :return: updated data c...
[ "def", "shift_coordinate_grid", "(", "self", ",", "x_shift", ",", "y_shift", ",", "pixel_unit", "=", "False", ")", ":", "self", ".", "_coords", ".", "shift_coordinate_grid", "(", "x_shift", ",", "y_shift", ",", "pixel_unit", "=", "pixel_unit", ")", "self", "...
51.9
18.5
def _inhibitColumnsLocal(self, overlaps, density): """ Performs local inhibition. Local inhibition is performed on a column by column basis. Each column observes the overlaps of its neighbors and is selected if its overlap score is within the top 'numActive' in its local neighborhood. At most half o...
[ "def", "_inhibitColumnsLocal", "(", "self", ",", "overlaps", ",", "density", ")", ":", "activeArray", "=", "numpy", ".", "zeros", "(", "self", ".", "_numColumns", ",", "dtype", "=", "\"bool\"", ")", "for", "column", ",", "overlap", "in", "enumerate", "(", ...
46.9
24.15
def fill_parameters(self, path, blocks, exclude_free_params=False, check_parameters=False): """ Load parameters from file to fill all blocks sequentially. :type blocks: list of deepy.layers.Block """ if not os.path.exists(path): raise Exception("model {} does not exis...
[ "def", "fill_parameters", "(", "self", ",", "path", ",", "blocks", ",", "exclude_free_params", "=", "False", ",", "check_parameters", "=", "False", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "raise", "Exception", "(",...
54.972973
22.918919
def max(x, axis=None, keepdims=False, with_index=False, only_index=False): """Reduce the input N-D array `x` along the given `axis` using the max operation. The `axis` argument may be a single integer to reduce over one axis, a tuple of integers to reduce over multiple axes, or ``None`` to reduce over a...
[ "def", "max", "(", "x", ",", "axis", "=", "None", ",", "keepdims", "=", "False", ",", "with_index", "=", "False", ",", "only_index", "=", "False", ")", ":", "from", ".", "function_bases", "import", "max", "as", "max_base", "if", "axis", "is", "None", ...
39.979167
22.208333
def setup_toolbar(self): """Setup toolbar""" load_button = create_toolbutton(self, text=_('Import data'), icon=ima.icon('fileimport'), triggered=lambda: self.import_data()) self.save_button = create_toolbutton(s...
[ "def", "setup_toolbar", "(", "self", ")", ":", "load_button", "=", "create_toolbutton", "(", "self", ",", "text", "=", "_", "(", "'Import data'", ")", ",", "icon", "=", "ima", ".", "icon", "(", "'fileimport'", ")", ",", "triggered", "=", "lambda", ":", ...
55.894737
22.315789
async def _check_subscriptions(self): """ Checks that all subscriptions are subscribed """ subscribed, url = await self._get_subscriptions() expect = set(settings.FACEBOOK_SUBSCRIPTIONS) if (expect - subscribed) or url != self.webhook_url: await self._set_su...
[ "async", "def", "_check_subscriptions", "(", "self", ")", ":", "subscribed", ",", "url", "=", "await", "self", ".", "_get_subscriptions", "(", ")", "expect", "=", "set", "(", "settings", ".", "FACEBOOK_SUBSCRIPTIONS", ")", "if", "(", "expect", "-", "subscrib...
36.769231
18.153846
def __set_frame_shift_status(self): """Check for frame shift and set the self.is_frame_shift flag.""" if 'fs' in self.hgvs_original: self.is_frame_shift = True self.is_non_silent = True elif re.search('[A-Z]\d+[A-Z]+\*', self.hgvs_original): # it looks like so...
[ "def", "__set_frame_shift_status", "(", "self", ")", ":", "if", "'fs'", "in", "self", ".", "hgvs_original", ":", "self", ".", "is_frame_shift", "=", "True", "self", ".", "is_non_silent", "=", "True", "elif", "re", ".", "search", "(", "'[A-Z]\\d+[A-Z]+\\*'", ...
44.25
9
def _record2card(self, record): """ when we add new records they don't have a card, this sort of fakes it up similar to what cfitsio does, just for display purposes. e.g. DBL = 23.299843 LNG = 3423432 KEYSNC = 'hello ...
[ "def", "_record2card", "(", "self", ",", "record", ")", ":", "name", "=", "record", "[", "'name'", "]", "value", "=", "record", "[", "'value'", "]", "v_isstring", "=", "isstring", "(", "value", ")", "if", "name", "==", "'COMMENT'", ":", "# card = 'COMMEN...
32.955224
16.865672
def get_mean(self, distribution_function): """Get the mean value for a distribution. If the distribution function is [normal, uniform,choice,triangular] the analytic value is being calculted. Else, the distribution is instantiated and then the mean is being calculated. :param distributi...
[ "def", "get_mean", "(", "self", ",", "distribution_function", ")", ":", "name", "=", "self", ".", "distribution_name", "params", "=", "self", ".", "random_function_params", "if", "name", "==", "'normal'", ":", "return", "params", "[", "0", "]", "if", "name",...
41.421053
13.947368
def string_class(cls): """Define __unicode__ and __str__ methods on the given class in Python 2. The given class must define a __str__ method returning a unicode string, otherwise a TypeError is raised. Under Python 3, the class is returned as is. """ if not PY3: if '__str__' not in cls...
[ "def", "string_class", "(", "cls", ")", ":", "if", "not", "PY3", ":", "if", "'__str__'", "not", "in", "cls", ".", "__dict__", ":", "raise", "TypeError", "(", "'the given class has no __str__ method'", ")", "cls", ".", "__unicode__", ",", "cls", ".", "__strin...
40
17.076923
def _getOverlay(self, readDataInstance, sectionHdrsInstance): """ Returns the overlay data from the PE file. @type readDataInstance: L{ReadData} @param readDataInstance: A L{ReadData} instance containing the PE file data. @type sectionHdrsInstance: L{SectionHead...
[ "def", "_getOverlay", "(", "self", ",", "readDataInstance", ",", "sectionHdrsInstance", ")", ":", "if", "readDataInstance", "is", "not", "None", "and", "sectionHdrsInstance", "is", "not", "None", ":", "# adjust the offset in readDataInstance to the RawOffset + RawSize of th...
51.740741
31.296296
def train(X_train, X_test, y_train, y_test, **kwargs): ''' >>> corpus = CorpusReader('annot.opcorpora.xml') >>> X_train, x_test, y_train, y_test = get_train_data(corpus, test_size=0.33, random_state=42) >>> crf = train(X_train, X_test, y_train, y_test) ''' crf = Trainer() crf.set_params({ ...
[ "def", "train", "(", "X_train", ",", "X_test", ",", "y_train", ",", "y_test", ",", "*", "*", "kwargs", ")", ":", "crf", "=", "Trainer", "(", ")", "crf", ".", "set_params", "(", "{", "'c1'", ":", "1.0", ",", "'c2'", ":", "0.001", ",", "'max_iteratio...
29.235294
22.647059
def async_decorator(func): """Asynchronous function decorator. Interprets the function as being asynchronous, so returns a function that will handle calling the Function asynchronously. Args: func (function): function to be called asynchronously Returns: The wrapped function. Rai...
[ "def", "async_decorator", "(", "func", ")", ":", "@", "functools", ".", "wraps", "(", "func", ")", "def", "async_wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "\"\"\"Wraps up the call to ``func``, so that it is called from a separate\n thread.\...
33.180556
21.25
def can_process_shell(self, entry): """:return: True when shell can be executed.""" count = 0 condition = render(entry['when'], variables=self.pipeline.variables, model=self.pipeline.model, env=self.get_merged_env(include_os=True)) if Condition.evaluate("" if ...
[ "def", "can_process_shell", "(", "self", ",", "entry", ")", ":", "count", "=", "0", "condition", "=", "render", "(", "entry", "[", "'when'", "]", ",", "variables", "=", "self", ".", "pipeline", ".", "variables", ",", "model", "=", "self", ".", "pipelin...
38.375
21.4375
def add_comment(self, comment): """ Adds a comment to a bug. If the bug object does not have a bug ID (ie you are creating a bug) then you will need to also call `put` on the :class:`Bugsy` class. >>> bug.add_comment("I like sausages") >>> bugzilla.pu...
[ "def", "add_comment", "(", "self", ",", "comment", ")", ":", "# If we have a key post immediately otherwise hold onto it until", "# put(bug) is called", "if", "'id'", "in", "self", ".", "_bug", ":", "self", ".", "_bugsy", ".", "request", "(", "'bug/{}/comment'", ".", ...
39.75
21.583333
def delete_acl_request(request): """Submission to remove an ACL.""" uuid_ = request.matchdict['uuid'] posted = request.json permissions = [(x['uid'], x['permission'],) for x in posted] with db_connect() as db_conn: with db_conn.cursor() as cursor: remove_acl(cursor, uuid_, permi...
[ "def", "delete_acl_request", "(", "request", ")", ":", "uuid_", "=", "request", ".", "matchdict", "[", "'uuid'", "]", "posted", "=", "request", ".", "json", "permissions", "=", "[", "(", "x", "[", "'uid'", "]", ",", "x", "[", "'permission'", "]", ",", ...
29.692308
15.384615
def bulk_insert(self, resource, docs, **kwargs): """Bulk insert documents.""" kwargs.update(self._es_args(resource)) parent_type = self._get_parent_type(resource) if parent_type: for doc in docs: if doc.get(parent_type.get('field')): doc['_...
[ "def", "bulk_insert", "(", "self", ",", "resource", ",", "docs", ",", "*", "*", "kwargs", ")", ":", "kwargs", ".", "update", "(", "self", ".", "_es_args", "(", "resource", ")", ")", "parent_type", "=", "self", ".", "_get_parent_type", "(", "resource", ...
41.416667
16.916667
def get_sendback(self, uuid, key): """ Return function for sending progress messages back to original caller. Args: uuid (str): UUID of the received message. key (str): Routing key. Returns: fn reference: Reference to function which takes only one da...
[ "def", "get_sendback", "(", "self", ",", "uuid", ",", "key", ")", ":", "def", "send_back_callback", "(", "data", ")", ":", "self", ".", "sendResponse", "(", "serializers", ".", "serialize", "(", "data", ")", ",", "uuid", ",", "key", ")", "return", "sen...
27.9
18.2
def setMood(self, mood): """ Update the activity message for the current user. Args: mood (str): new mood message """ self.conn("POST", "{0}/users/{1}/profile/partial".format(SkypeConnection.API_USER, self.userId), auth=SkypeConnection.Auth.SkypeTok...
[ "def", "setMood", "(", "self", ",", "mood", ")", ":", "self", ".", "conn", "(", "\"POST\"", ",", "\"{0}/users/{1}/profile/partial\"", ".", "format", "(", "SkypeConnection", ".", "API_USER", ",", "self", ".", "userId", ")", ",", "auth", "=", "SkypeConnection"...
42.4
24.8
def subcommand_not_found(self, command, string): """|maybecoro| A method called when a command did not have a subcommand requested in the help command. This is useful to override for i18n. Defaults to either: - ``'Command "{command.qualified_name}" has no subcommands.'`` ...
[ "def", "subcommand_not_found", "(", "self", ",", "command", ",", "string", ")", ":", "if", "isinstance", "(", "command", ",", "Group", ")", "and", "len", "(", "command", ".", "all_commands", ")", ">", "0", ":", "return", "'Command \"{0.qualified_name}\" has no...
42.862069
28.068966
def _from_pointer(pointer, incref): """Wrap an existing :c:type:`cairo_surface_t *` cdata pointer. :type incref: bool :param incref: Whether increase the :ref:`reference count <refcounting>` now. :return: A new instance of :class:`Surface` or one of its sub-class...
[ "def", "_from_pointer", "(", "pointer", ",", "incref", ")", ":", "if", "pointer", "==", "ffi", ".", "NULL", ":", "raise", "ValueError", "(", "'Null pointer'", ")", "if", "incref", ":", "cairo", ".", "cairo_surface_reference", "(", "pointer", ")", "self", "...
37.894737
18.157895
def g_step(self, gen_frames, fake_logits_stop): """Performs the generator step in computing the GAN loss. Args: gen_frames: Generated frames fake_logits_stop: Logits corresponding to the generated frames as per the discriminator. Assumed to have a stop-gradient term. Ret...
[ "def", "g_step", "(", "self", ",", "gen_frames", ",", "fake_logits_stop", ")", ":", "hparam_to_gen_loss", "=", "{", "\"least_squares\"", ":", "gan_losses", ".", "least_squares_generator_loss", ",", "\"cross_entropy\"", ":", "gan_losses", ".", "modified_generator_loss", ...
44.878788
21.242424
def tag_handler(self, cmd): """Process a TagCommand.""" # Keep tags if they indirectly reference something we kept cmd.from_ = self._find_interesting_from(cmd.from_) self.keep = cmd.from_ is not None
[ "def", "tag_handler", "(", "self", ",", "cmd", ")", ":", "# Keep tags if they indirectly reference something we kept", "cmd", ".", "from_", "=", "self", ".", "_find_interesting_from", "(", "cmd", ".", "from_", ")", "self", ".", "keep", "=", "cmd", ".", "from_", ...
45.4
11.6
def convert_datetext_to_dategui(datetext, ln=None, secs=False): """Convert: '2005-11-16 15:11:57' => '16 nov 2005, 15:11' Or optionally with seconds: '2005-11-16 15:11:57' => '16 nov 2005, 15:11:57' Month is internationalized """ assert ln is None, 'setting language is not supported' try: ...
[ "def", "convert_datetext_to_dategui", "(", "datetext", ",", "ln", "=", "None", ",", "secs", "=", "False", ")", ":", "assert", "ln", "is", "None", ",", "'setting language is not supported'", "try", ":", "datestruct", "=", "convert_datetext_to_datestruct", "(", "dat...
34.333333
16.714286
def generate_enums(basename, xml): '''generate main header per XML file''' directory = os.path.join(basename, '''enums''') mavparse.mkdir_p(directory) for en in xml.enum: f = open(os.path.join(directory, en.name+".java"), mode='w') t.write(f, ''' /* AUTO-GENERATED FILE. DO NOT MODIFY. ...
[ "def", "generate_enums", "(", "basename", ",", "xml", ")", ":", "directory", "=", "os", ".", "path", ".", "join", "(", "basename", ",", "'''enums'''", ")", "mavparse", ".", "mkdir_p", "(", "directory", ")", "for", "en", "in", "xml", ".", "enum", ":", ...
26.875
24.875
def _make_verb_helper(verb_func, add_groups=False): """ Create function that prepares verb for the verb function The functions created add expressions to be evaluated to the verb, then call the core verb function Parameters ---------- verb_func : function Core verb function. This i...
[ "def", "_make_verb_helper", "(", "verb_func", ",", "add_groups", "=", "False", ")", ":", "@", "wraps", "(", "verb_func", ")", "def", "_verb_func", "(", "verb", ")", ":", "verb", ".", "expressions", ",", "new_columns", "=", "build_expressions", "(", "verb", ...
29.272727
20.484848
def cmd_do_change_speed(self, args): '''speed value''' if ( len(args) != 1): print("Usage: setspeed SPEED_VALUE") return if (len(args) == 1): speed = float(args[0]) print("SPEED %s" % (str(speed))) self.master.mav.command_long_send( ...
[ "def", "cmd_do_change_speed", "(", "self", ",", "args", ")", ":", "if", "(", "len", "(", "args", ")", "!=", "1", ")", ":", "print", "(", "\"Usage: setspeed SPEED_VALUE\"", ")", "return", "if", "(", "len", "(", "args", ")", "==", "1", ")", ":", "speed...
35.428571
14.857143
def send(self, wallet_id, passcode, address, amount, message='', fee=None, fan_unspend=10): """ Send bitcoins to address :param wallet_id: bitgo wallet id :param address: bitcoin address :param amount: btc amount in satoshis :param split: create new outputs if needed ...
[ "def", "send", "(", "self", ",", "wallet_id", ",", "passcode", ",", "address", ",", "amount", ",", "message", "=", "''", ",", "fee", "=", "None", ",", "fan_unspend", "=", "10", ")", ":", "MINIMAL_FEE", "=", "20000", "MINIMAL_SPLIT", "=", "10000000", "w...
33.583333
19.37963
def forest(S=3, r1=4, r2=2, p=0.1, is_sparse=False): """Generate a MDP example based on a simple forest management scenario. This function is used to generate a transition probability (``A`` × ``S`` × ``S``) array ``P`` and a reward (``S`` × ``A``) matrix ``R`` that model the following problem. A fores...
[ "def", "forest", "(", "S", "=", "3", ",", "r1", "=", "4", ",", "r2", "=", "2", ",", "p", "=", "0.1", ",", "is_sparse", "=", "False", ")", ":", "assert", "S", ">", "1", ",", "\"The number of states S must be greater than 1.\"", "assert", "(", "r1", ">...
34.817518
20.861314
def id_to_extended_id(item_id, item_class): """Return the extended ID from an ID. :param item_id: The ID of the music library item :type item_id: str :param cls: The class of the music service item :type cls: Sub-class of :py:class:`soco.data_structures.MusicServiceI...
[ "def", "id_to_extended_id", "(", "item_id", ",", "item_class", ")", ":", "out", "=", "ID_PREFIX", "[", "item_class", "]", "if", "out", ":", "out", "+=", "item_id", "return", "out" ]
35.352941
17.705882
def map(self, fn): """Run a map function across all y points in the series""" return TimeSeries([(x, fn(y)) for x, y in self.points])
[ "def", "map", "(", "self", ",", "fn", ")", ":", "return", "TimeSeries", "(", "[", "(", "x", ",", "fn", "(", "y", ")", ")", "for", "x", ",", "y", "in", "self", ".", "points", "]", ")" ]
49
15
def actuator_on(self, service_location_id, actuator_id, duration=None): """ Turn actuator on Parameters ---------- service_location_id : int actuator_id : int duration : int, optional 300,900,1800 or 3600 , specifying the time in seconds the actuator ...
[ "def", "actuator_on", "(", "self", ",", "service_location_id", ",", "actuator_id", ",", "duration", "=", "None", ")", ":", "return", "self", ".", "_actuator_on_off", "(", "on_off", "=", "'on'", ",", "service_location_id", "=", "service_location_id", ",", "actuat...
32.5
19.2
def union(self, *queries): '''Return a new :class:`Query` obtained form the union of this :class:`Query` with one or more *queries*. For example, lets say we want to have the union of two queries obtained from the :meth:`filter` method:: query = session.query(MyModel) qs = query.filter(field1 = ...
[ "def", "union", "(", "self", ",", "*", "queries", ")", ":", "q", "=", "self", ".", "_clone", "(", ")", "q", ".", "unions", "+=", "queries", "return", "q" ]
35.833333
19.666667
def _import_module(self, s): """ Import a module. """ mod = __import__(s) parts = s.split('.') for part in parts[1:]: mod = getattr(mod, part) return mod
[ "def", "_import_module", "(", "self", ",", "s", ")", ":", "mod", "=", "__import__", "(", "s", ")", "parts", "=", "s", ".", "split", "(", "'.'", ")", "for", "part", "in", "parts", "[", "1", ":", "]", ":", "mod", "=", "getattr", "(", "mod", ",", ...
23.666667
9.888889
def transform_from_dual_quaternion(dq, from_frame='unassigned', to_frame='world'): """Create a RigidTransform from a DualQuaternion. Parameters ---------- dq : :obj:`DualQuaternion` The DualQuaternion to transform. from_frame : :obj:`str` A name for the ...
[ "def", "transform_from_dual_quaternion", "(", "dq", ",", "from_frame", "=", "'unassigned'", ",", "to_frame", "=", "'world'", ")", ":", "quaternion", "=", "dq", ".", "qr", "translation", "=", "2", "*", "dq", ".", "qd", "[", "1", ":", "]", "return", "Rigid...
33.583333
22.666667
def save_file(key, file_path, *refs): """Convert the given parameters to a special JSON object. JSON object is of the form: { key: {"file": file_path}}, or { key: {"file": file_path, "refs": [refs[0], refs[1], ... ]}} """ if not os.path.isfile(file_path): return error("Output '{}' set ...
[ "def", "save_file", "(", "key", ",", "file_path", ",", "*", "refs", ")", ":", "if", "not", "os", ".", "path", ".", "isfile", "(", "file_path", ")", ":", "return", "error", "(", "\"Output '{}' set to a missing file: '{}'.\"", ".", "format", "(", "key", ",",...
30.576923
20.653846
def sim(self, src, tar, threshold=0.25, max_mismatches=2): """Return the MLIPNS similarity of two strings. Parameters ---------- src : str Source string for comparison tar : str Target string for comparison threshold : float A number [...
[ "def", "sim", "(", "self", ",", "src", ",", "tar", ",", "threshold", "=", "0.25", ",", "max_mismatches", "=", "2", ")", ":", "if", "tar", "==", "src", ":", "return", "1.0", "if", "not", "src", "or", "not", "tar", ":", "return", "0.0", "mismatches",...
27.727273
20.090909
def service_create(auth=None, **kwargs): ''' Create a service CLI Example: .. code-block:: bash salt '*' keystoneng.service_create name=glance type=image salt '*' keystoneng.service_create name=glance type=image description="Image" ''' cloud = get_operator_cloud(auth) kwar...
[ "def", "service_create", "(", "auth", "=", "None", ",", "*", "*", "kwargs", ")", ":", "cloud", "=", "get_operator_cloud", "(", "auth", ")", "kwargs", "=", "_clean_kwargs", "(", "keep_name", "=", "True", ",", "*", "*", "kwargs", ")", "return", "cloud", ...
28.071429
23.785714
def update_stream(self): """ Restarts the stream with the current list of tracking terms. """ need_to_restart = False # If we think we are running, but something has gone wrong in the streaming thread # Restart it. if self.stream is not None and not self.stream....
[ "def", "update_stream", "(", "self", ")", ":", "need_to_restart", "=", "False", "# If we think we are running, but something has gone wrong in the streaming thread", "# Restart it.", "if", "self", ".", "stream", "is", "not", "None", "and", "not", "self", ".", "stream", ...
30.382353
19.088235
def format_value(_type, _data, lookup_string=lambda ix: "<string>"): """ Format a value based on type and data. By default, no strings are looked up and "<string>" is returned. You need to define `lookup_string` in order to actually lookup strings from the string table. :param _type: The numeri...
[ "def", "format_value", "(", "_type", ",", "_data", ",", "lookup_string", "=", "lambda", "ix", ":", "\"<string>\"", ")", ":", "# Function to prepend android prefix for attributes/references from the", "# android library", "fmt_package", "=", "lambda", "x", ":", "\"android:...
33.326923
23.326923
def _compare(cur_cmp, cur_struct): ''' Compares two objects and return a boolean value when there's a match. ''' if isinstance(cur_cmp, dict) and isinstance(cur_struct, dict): log.debug('Comparing dict to dict') for cmp_key, cmp_value in six.iteritems(cur_cmp): if cmp_key...
[ "def", "_compare", "(", "cur_cmp", ",", "cur_struct", ")", ":", "if", "isinstance", "(", "cur_cmp", ",", "dict", ")", "and", "isinstance", "(", "cur_struct", ",", "dict", ")", ":", "log", ".", "debug", "(", "'Comparing dict to dict'", ")", "for", "cmp_key"...
48.197368
19.723684
def _write_config(config, cfg_file): """ Write a config object to the settings.cfg file. :param config: A ConfigParser object to write to the settings.cfg file. """ directory = os.path.dirname(cfg_file) if not os.path.exists(directory): os.makedirs(directory) with open(cfg_file, "w+...
[ "def", "_write_config", "(", "config", ",", "cfg_file", ")", ":", "directory", "=", "os", ".", "path", ".", "dirname", "(", "cfg_file", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "directory", ")", ":", "os", ".", "makedirs", "(", "direc...
32.909091
10.545455
def _run_program(self, bin, fastafile, params=None): """ Run Posmo and predict motifs from a FASTA file. Parameters ---------- bin : str Command used to run the tool. fastafile : str Name of the FASTA input file. params : dict, o...
[ "def", "_run_program", "(", "self", ",", "bin", ",", "fastafile", ",", "params", "=", "None", ")", ":", "default_params", "=", "{", "}", "if", "params", "is", "not", "None", ":", "default_params", ".", "update", "(", "params", ")", "width", "=", "param...
31.69697
17.515152
def _set_mpls_traffic_bypasses(self, v, load=False): """ Setter method for mpls_traffic_bypasses, mapped from YANG variable /telemetry/profile/mpls_traffic_bypass/mpls_traffic_bypasses (list) If this variable is read-only (config: false) in the source YANG file, then _set_mpls_traffic_bypasses is consid...
[ "def", "_set_mpls_traffic_bypasses", "(", "self", ",", "v", ",", "load", "=", "False", ")", ":", "if", "hasattr", "(", "v", ",", "\"_utype\"", ")", ":", "v", "=", "v", ".", "_utype", "(", "v", ")", "try", ":", "t", "=", "YANGDynClass", "(", "v", ...
129
62.727273
def _get_stddevs(self, C, stddev_types, num_sites, mag, c1_rrup, log_phi_ss, mean_phi_ss): """ Return standard deviations """ phi_ss = _compute_phi_ss(C, mag, c1_rrup, log_phi_ss, mean_phi_ss) stddevs = [] for stddev_type in stddev_types: ...
[ "def", "_get_stddevs", "(", "self", ",", "C", ",", "stddev_types", ",", "num_sites", ",", "mag", ",", "c1_rrup", ",", "log_phi_ss", ",", "mean_phi_ss", ")", ":", "phi_ss", "=", "_compute_phi_ss", "(", "C", ",", "mag", ",", "c1_rrup", ",", "log_phi_ss", "...
37.956522
18.304348
def read_frame(self): """Reads a frame and converts the color if needed. In case no frame is available, i.e. self.capture.read() returns False as the first return value, the event_source of the TimedAnimation is stopped, and if possible the capture source released. Returns: ...
[ "def", "read_frame", "(", "self", ")", ":", "ret", ",", "frame", "=", "self", ".", "capture", ".", "read", "(", ")", "if", "not", "ret", ":", "self", ".", "event_source", ".", "stop", "(", ")", "try", ":", "self", ".", "capture", ".", "release", ...
36.954545
19
def _list_audio_files(self, root, skip_rows=0): """Populates synsets - a map of index to label for the data items. Populates the data in the dataset, making tuples of (data, label) """ self.synsets = [] self.items = [] if not self._train_csv: # The audio files...
[ "def", "_list_audio_files", "(", "self", ",", "root", ",", "skip_rows", "=", "0", ")", ":", "self", ".", "synsets", "=", "[", "]", "self", ".", "items", "=", "[", "]", "if", "not", "self", ".", "_train_csv", ":", "# The audio files are organized in folder ...
46.090909
18.136364
def get_raw_data(self): """Reads the raw red, green, blue and clear channel values. Will return a 4-tuple with the red, green, blue, clear color values (unsigned 16-bit numbers). """ # Read each color register. r = self._readU16LE(TCS34725_RDATAL) g = self._readU1...
[ "def", "get_raw_data", "(", "self", ")", ":", "# Read each color register.", "r", "=", "self", ".", "_readU16LE", "(", "TCS34725_RDATAL", ")", "g", "=", "self", ".", "_readU16LE", "(", "TCS34725_GDATAL", ")", "b", "=", "self", ".", "_readU16LE", "(", "TCS347...
45.615385
13.769231
def affine_coupling(name, x, mid_channels=512, activation="relu", reverse=False, dropout=0.0): """Reversible affine coupling layer. Args: name: variable scope. x: 4-D Tensor. mid_channels: number of channels in the coupling layer. activation: Can be either "relu" or "gatu". ...
[ "def", "affine_coupling", "(", "name", ",", "x", ",", "mid_channels", "=", "512", ",", "activation", "=", "\"relu\"", ",", "reverse", "=", "False", ",", "dropout", "=", "0.0", ")", ":", "with", "tf", ".", "variable_scope", "(", "name", ",", "reuse", "=...
31.948718
17.615385
def hook_point(self, hook_name, handle=None): """Used to call module function that may define a hook function for hook_name Available hook points: - `tick`, called on each daemon loop turn - `save_retention`; called by the scheduler when live state saving is to be done ...
[ "def", "hook_point", "(", "self", ",", "hook_name", ",", "handle", "=", "None", ")", ":", "full_hook_name", "=", "'hook_'", "+", "hook_name", "for", "module", "in", "self", ".", "modules_manager", ".", "instances", ":", "_ts", "=", "time", ".", "time", "...
50.121951
24.658537
def logpdf(self, mu): """ Log PDF for Poisson prior Parameters ---------- mu : float Latent variable for which the prior is being formed over Returns ---------- - log(p(mu)) """ if self.transform is not None: mu = ...
[ "def", "logpdf", "(", "self", ",", "mu", ")", ":", "if", "self", ".", "transform", "is", "not", "None", ":", "mu", "=", "self", ".", "transform", "(", "mu", ")", "return", "ss", ".", "poisson", ".", "logpmf", "(", "mu", ",", "self", ".", "lmd0", ...
23.4375
17.3125
def gt(self, other): """ Strictly greater than. Returns True if no part of this Interval extends lower than or into other. :raises ValueError: if either self or other is a null Interval :param other: Interval or point :return: True or False :rtype: bool ""...
[ "def", "gt", "(", "self", ",", "other", ")", ":", "self", ".", "_raise_if_null", "(", "other", ")", "if", "hasattr", "(", "other", ",", "'end'", ")", ":", "return", "self", ".", "begin", ">=", "other", ".", "end", "else", ":", "return", "self", "."...
33.714286
11.285714
def unused(self, _dict): """ Remove empty parameters from the dict """ for key, value in _dict.items(): if value is None: del _dict[key] return _dict
[ "def", "unused", "(", "self", ",", "_dict", ")", ":", "for", "key", ",", "value", "in", "_dict", ".", "items", "(", ")", ":", "if", "value", "is", "None", ":", "del", "_dict", "[", "key", "]", "return", "_dict" ]
26.25
7.75
def target_str(self): """Returns the string representation of the target property.""" if isinstance(self.target, tuple): return "({})".format(", ".join(self.target)) else: return self.target
[ "def", "target_str", "(", "self", ")", ":", "if", "isinstance", "(", "self", ".", "target", ",", "tuple", ")", ":", "return", "\"({})\"", ".", "format", "(", "\", \"", ".", "join", "(", "self", ".", "target", ")", ")", "else", ":", "return", "self", ...
34.833333
13
def parse_error(text: str) -> Any: """ Validate and parse the BMA answer from websocket :param text: the bma error :return: the json data """ try: data = json.loads(text) jsonschema.validate(data, ERROR_SCHEMA) except (TypeError, json.decoder.JSONDecodeError) as e: r...
[ "def", "parse_error", "(", "text", ":", "str", ")", "->", "Any", ":", "try", ":", "data", "=", "json", ".", "loads", "(", "text", ")", "jsonschema", ".", "validate", "(", "data", ",", "ERROR_SCHEMA", ")", "except", "(", "TypeError", ",", "json", ".",...
28.571429
18.428571
def find_file_match(folder_path, regex=''): """ Returns absolute paths of files that match the regex within folder_path and all its children folders. Note: The regex matching is done using the match function of the re module. Parameters ---------- folder_path: string regex: string...
[ "def", "find_file_match", "(", "folder_path", ",", "regex", "=", "''", ")", ":", "outlist", "=", "[", "]", "for", "root", ",", "dirs", ",", "files", "in", "os", ".", "walk", "(", "folder_path", ")", ":", "outlist", ".", "extend", "(", "[", "os", "....
22
23.36
def get_docstring(obj): """Extract the docstring from an object as individual lines. Parameters ---------- obj : object The Python object (class, function or method) to extract docstrings from. Returns ------- lines : `list` of `str` Individual docstring lines with ...
[ "def", "get_docstring", "(", "obj", ")", ":", "docstring", "=", "getdoc", "(", "obj", ",", "allow_inherited", "=", "True", ")", "if", "docstring", "is", "None", ":", "logger", "=", "getLogger", "(", "__name__", ")", "logger", ".", "warning", "(", "\"Obje...
32.607143
22
def compute_transformed(context): """Compute transformed key for opening database""" if context._._.transformed_key is not None: transformed_key = context._._transformed_key else: transformed_key = aes_kdf( context._.header.value.dynamic_header.transform_seed.data, c...
[ "def", "compute_transformed", "(", "context", ")", ":", "if", "context", ".", "_", ".", "_", ".", "transformed_key", "is", "not", "None", ":", "transformed_key", "=", "context", ".", "_", ".", "_transformed_key", "else", ":", "transformed_key", "=", "aes_kdf...
34.785714
18.071429
def weighted_sample_with_replacement(seq, weights, n): """Pick n samples from seq at random, with replacement, with the probability of each element in proportion to its corresponding weight.""" sample = weighted_sampler(seq, weights) return [sample() for s in range(n)]
[ "def", "weighted_sample_with_replacement", "(", "seq", ",", "weights", ",", "n", ")", ":", "sample", "=", "weighted_sampler", "(", "seq", ",", "weights", ")", "return", "[", "sample", "(", ")", "for", "s", "in", "range", "(", "n", ")", "]" ]
47.333333
7.333333
def remove_item(self, jid): """Remove item from the roster. :Parameters: - `jid`: JID of the item to remove :Types: - `jid`: `JID` """ if jid not in self._jids: raise KeyError(jid) index = self._jids[jid] for i in range(index, ...
[ "def", "remove_item", "(", "self", ",", "jid", ")", ":", "if", "jid", "not", "in", "self", ".", "_jids", ":", "raise", "KeyError", "(", "jid", ")", "index", "=", "self", ".", "_jids", "[", "jid", "]", "for", "i", "in", "range", "(", "index", ",",...
28.666667
12
def run(self): """Main thread function to maintain connection and receive remote status.""" _LOGGER.info("Started") while True: self._maybe_reconnect() line = '' try: # If someone is sending a command, we can lose our connection so grab a # copy beforehand. We don't need th...
[ "def", "run", "(", "self", ")", ":", "_LOGGER", ".", "info", "(", "\"Started\"", ")", "while", "True", ":", "self", ".", "_maybe_reconnect", "(", ")", "line", "=", "''", "try", ":", "# If someone is sending a command, we can lose our connection so grab a", "# copy...
35.045455
18.863636
def init_key_jar(public_path='', private_path='', key_defs='', owner='', read_only=True): """ A number of cases here: 1. A private path is given a. The file exists and a JWKS is found there. From that JWKS a KeyJar instance is built. b. If the private pat...
[ "def", "init_key_jar", "(", "public_path", "=", "''", ",", "private_path", "=", "''", ",", "key_defs", "=", "''", ",", "owner", "=", "''", ",", "read_only", "=", "True", ")", ":", "if", "private_path", ":", "if", "os", ".", "path", ".", "isfile", "("...
39.254386
18.289474