text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def dd2dm(dd): """Convert decimal to degrees, decimal minutes """ d,m,s = dd2dms(dd) m = m + float(s)/3600 return d,m,s
[ "def", "dd2dm", "(", "dd", ")", ":", "d", ",", "m", ",", "s", "=", "dd2dms", "(", "dd", ")", "m", "=", "m", "+", "float", "(", "s", ")", "/", "3600", "return", "d", ",", "m", ",", "s" ]
22.333333
0.035971
def make_fout(fout='./tmp', fmt='pcap'): """Make root path for output. Positional arguments: * fout -- str, root path for output * fmt -- str, output format Returns: * output -- dumper of specified format """ if fmt == 'pcap': # output...
[ "def", "make_fout", "(", "fout", "=", "'./tmp'", ",", "fmt", "=", "'pcap'", ")", ":", "if", "fmt", "==", "'pcap'", ":", "# output PCAP file", "from", "pcapkit", ".", "dumpkit", "import", "PCAP", "as", "output", "elif", "fmt", "==", "'plist'", ":", "# out...
38.97561
0.002442
def get_nearby_stops(geo_stops, linestring, side, buffer=cs.BUFFER): """ Given a GeoDataFrame of stops, a Shapely LineString in the same coordinate system, a side of the LineString (string; 'left' = left hand side of LineString, 'right' = right hand side of LineString, or 'both' = both sides), a...
[ "def", "get_nearby_stops", "(", "geo_stops", ",", "linestring", ",", "side", ",", "buffer", "=", "cs", ".", "BUFFER", ")", ":", "b", "=", "buffer_side", "(", "linestring", ",", "side", ",", "buffer", ")", "# Collect stops", "return", "geo_stops", ".", "loc...
42.933333
0.00152
def plot_contpix(self, x, y, contpix_x, contpix_y, figname): """ Plot baseline spec with continuum pix overlaid Parameters ---------- """ fig, axarr = plt.subplots(2, sharex=True) plt.xlabel(r"Wavelength $\lambda (\AA)$") plt.xlim(min(x), max(x)) ax = ax...
[ "def", "plot_contpix", "(", "self", ",", "x", ",", "y", ",", "contpix_x", ",", "contpix_y", ",", "figname", ")", ":", "fig", ",", "axarr", "=", "plt", ".", "subplots", "(", "2", ",", "sharex", "=", "True", ")", "plt", ".", "xlabel", "(", "r\"Wavele...
42.4375
0.010079
def delta(self): """Duration (datetime.timedelta).""" end_time = self.end_time if self.end_time else dt.datetime.now() return end_time - self.start_time
[ "def", "delta", "(", "self", ")", ":", "end_time", "=", "self", ".", "end_time", "if", "self", ".", "end_time", "else", "dt", ".", "datetime", ".", "now", "(", ")", "return", "end_time", "-", "self", ".", "start_time" ]
43.25
0.011364
def close(self): """ Closes the database, releasing lock. """ super(LockingDatabase, self).close() if not self.readonly: self.release_lock()
[ "def", "close", "(", "self", ")", ":", "super", "(", "LockingDatabase", ",", "self", ")", ".", "close", "(", ")", "if", "not", "self", ".", "readonly", ":", "self", ".", "release_lock", "(", ")" ]
26.571429
0.010417
def chop_sequence(sequence, limit_length): """Input sequence is divided on smaller non-overlapping sequences with set length. """ return [sequence[i:i + limit_length] for i in range(0, len(sequence), limit_length)]
[ "def", "chop_sequence", "(", "sequence", ",", "limit_length", ")", ":", "return", "[", "sequence", "[", "i", ":", "i", "+", "limit_length", "]", "for", "i", "in", "range", "(", "0", ",", "len", "(", "sequence", ")", ",", "limit_length", ")", "]" ]
76.333333
0.017316
def handle_stop(self, signame, set_stop): """Set whether we stop or not when this signal is caught. If 'set_stop' is True your program will stop when this signal happens.""" if set_stop: self.sigs[signame].b_stop = True # stop keyword implies print AND nopas...
[ "def", "handle_stop", "(", "self", ",", "signame", ",", "set_stop", ")", ":", "if", "set_stop", ":", "self", ".", "sigs", "[", "signame", "]", ".", "b_stop", "=", "True", "# stop keyword implies print AND nopass", "self", ".", "sigs", "[", "signame", "]", ...
41.307692
0.009107
def box_model_domain(num_points=2, **kwargs): """Creates a box model domain (a single abstract axis). :param int num_points: number of boxes [default: 2] :returns: Domain with single axis of type ``'abstract'`` and ``self.domain_type = 'box'`` :rty...
[ "def", "box_model_domain", "(", "num_points", "=", "2", ",", "*", "*", "kwargs", ")", ":", "ax", "=", "Axis", "(", "axis_type", "=", "'abstract'", ",", "num_points", "=", "num_points", ")", "boxes", "=", "_Domain", "(", "axes", "=", "ax", ",", "*", "...
31.304348
0.001348
def print_pretty_command(env, command): """This is a hack for prettier printing. Rather than "{envpython} foo.py" we print "python foo.py". """ cmd = abbr_cmd = command[0] if cmd.startswith(env.envbindir): abbr_cmd = os.path.relpath(cmd, env.envbindir) if abbr_cmd == ".": ...
[ "def", "print_pretty_command", "(", "env", ",", "command", ")", ":", "cmd", "=", "abbr_cmd", "=", "command", "[", "0", "]", "if", "cmd", ".", "startswith", "(", "env", ".", "envbindir", ")", ":", "abbr_cmd", "=", "os", ".", "path", ".", "relpath", "(...
35
0.001546
def mm_rankings(n_items, data, initial_params=None, alpha=0.0, max_iter=10000, tol=1e-8): """Compute the ML estimate of model parameters using the MM algorithm. This function computes the maximum-likelihood (ML) estimate of model parameters given ranking data (see :ref:`data-rankings`), using the ...
[ "def", "mm_rankings", "(", "n_items", ",", "data", ",", "initial_params", "=", "None", ",", "alpha", "=", "0.0", ",", "max_iter", "=", "10000", ",", "tol", "=", "1e-8", ")", ":", "return", "_mm", "(", "n_items", ",", "data", ",", "initial_params", ",",...
34.628571
0.002408
def prompt_4_mfa_code(activate = False, input = None): """ Prompt for an MFA code :param activate: Set to true when prompting for the 2nd code when activating a new MFA device :param input: Used for unit testing :return: The MFA c...
[ "def", "prompt_4_mfa_code", "(", "activate", "=", "False", ",", "input", "=", "None", ")", ":", "while", "True", ":", "if", "activate", ":", "prompt_string", "=", "'Enter the next value: '", "else", ":", "prompt_string", "=", "'Enter your MFA code (or \\'q\\' to abo...
35.75
0.014756
def inspect(logdir='', event_file='', tag=''): """Main function for inspector that prints out a digest of event files. Args: logdir: A log directory that contains event files. event_file: Or, a particular event file path. tag: An optional tag name to query for. Raises: ValueError: If neither log...
[ "def", "inspect", "(", "logdir", "=", "''", ",", "event_file", "=", "''", ",", "tag", "=", "''", ")", ":", "print", "(", "PRINT_SEPARATOR", "+", "'Processing event files... (this can take a few minutes)\\n'", "+", "PRINT_SEPARATOR", ")", "inspection_units", "=", "...
37.551724
0.010743
def _build_story(self, all_rows): """ Builds and returns a list of stories (dicts) from the passed source. """ # list to hold all stories all_stories = [] for (info, detail) in all_rows: #-- Get the into about a story --# # split in 3 c...
[ "def", "_build_story", "(", "self", ",", "all_rows", ")", ":", "# list to hold all stories\r", "all_stories", "=", "[", "]", "for", "(", "info", ",", "detail", ")", "in", "all_rows", ":", "#-- Get the into about a story --#\r", "# split in 3 cells\r", "info_cells", ...
40.097561
0.001781
def create_logger(logger=None, loglevel=None, capture_warnings=True, add_paramiko_handler=True): """ Attach or create a new logger and add a console handler if not present Arguments: logger (Optional[logging.Logger]): :class:`loggin...
[ "def", "create_logger", "(", "logger", "=", "None", ",", "loglevel", "=", "None", ",", "capture_warnings", "=", "True", ",", "add_paramiko_handler", "=", "True", ")", ":", "logger", "=", "logger", "or", "logging", ".", "getLogger", "(", "'{0}.SSHTunnelForwarde...
33.684211
0.000506
def WriteMessageHandlerRequests(self, requests): """Writes a list of message handler requests to the database.""" now = rdfvalue.RDFDatetime.Now() for r in requests: flow_dict = self.message_handler_requests.setdefault(r.handler_name, {}) cloned_request = r.Copy() cloned_request.timestamp ...
[ "def", "WriteMessageHandlerRequests", "(", "self", ",", "requests", ")", ":", "now", "=", "rdfvalue", ".", "RDFDatetime", ".", "Now", "(", ")", "for", "r", "in", "requests", ":", "flow_dict", "=", "self", ".", "message_handler_requests", ".", "setdefault", "...
47.25
0.012987
def qrcode( cls, data, mode="base64", version=None, error_correction="L", box_size=10, border=0, fit=True, fill_color="black", back_color="white", **kwargs ): """Makes qr image using qrcode as qrc. See documentation ...
[ "def", "qrcode", "(", "cls", ",", "data", ",", "mode", "=", "\"base64\"", ",", "version", "=", "None", ",", "error_correction", "=", "\"L\"", ",", "box_size", "=", "10", ",", "border", "=", "0", ",", "fit", "=", "True", ",", "fill_color", "=", "\"bla...
32.859375
0.002308
def get_now(): """ Allows to access global request and read a timestamp from query. """ if not get_current_request: return datetime.datetime.now() request = get_current_request() if request: openinghours_now = request.GET.get('openinghours-now') if openinghours_now: ...
[ "def", "get_now", "(", ")", ":", "if", "not", "get_current_request", ":", "return", "datetime", ".", "datetime", ".", "now", "(", ")", "request", "=", "get_current_request", "(", ")", "if", "request", ":", "openinghours_now", "=", "request", ".", "GET", "....
34.833333
0.002331
def new_run(self): """Creates a new RunData object and increments pointers""" self.current_run += 1 self.runs.append(RunData(self.current_run + 1))
[ "def", "new_run", "(", "self", ")", ":", "self", ".", "current_run", "+=", "1", "self", ".", "runs", ".", "append", "(", "RunData", "(", "self", ".", "current_run", "+", "1", ")", ")" ]
42
0.011696
def tfms_from_stats(stats, sz, aug_tfms=None, max_zoom=None, pad=0, crop_type=CropType.RANDOM, tfm_y=None, sz_y=None, pad_mode=cv2.BORDER_REFLECT, norm_y=True, scale=None): """ Given the statistics of the training image sets, returns separate training and validation transform functions """ ...
[ "def", "tfms_from_stats", "(", "stats", ",", "sz", ",", "aug_tfms", "=", "None", ",", "max_zoom", "=", "None", ",", "pad", "=", "0", ",", "crop_type", "=", "CropType", ".", "RANDOM", ",", "tfm_y", "=", "None", ",", "sz_y", "=", "None", ",", "pad_mode...
73.153846
0.012461
def Package(env, target=None, source=None, **kw): """ Entry point for the package tool. """ # check if we need to find the source files ourself if not source: source = env.FindInstalledFiles() if len(source)==0: raise UserError("No source for Package() given") # decide which ty...
[ "def", "Package", "(", "env", ",", "target", "=", "None", ",", "source", "=", "None", ",", "*", "*", "kw", ")", ":", "# check if we need to find the source files ourself", "if", "not", "source", ":", "source", "=", "env", ".", "FindInstalledFiles", "(", ")",...
35.846154
0.018011
def get_raw_exception_record_list(self): """ Traverses the exception record linked list and builds a Python list. Nested exception records are received for nested exceptions. This happens when an exception is raised in the debugee while trying to handle a previous exception. ...
[ "def", "get_raw_exception_record_list", "(", "self", ")", ":", "# The first EXCEPTION_RECORD is contained in EXCEPTION_DEBUG_INFO.", "# The remaining EXCEPTION_RECORD structures are linked by pointers.", "nested", "=", "list", "(", ")", "record", "=", "self", ".", "raw", ".", "...
40.576923
0.001852
def posthoc_nemenyi(a, val_col=None, group_col=None, dist='chi', sort=True): '''Post hoc pairwise test for multiple comparisons of mean rank sums (Nemenyi's test). May be used after Kruskal-Wallis one-way analysis of variance by ranks to do pairwise comparisons [1]_. Parameters ---------- a :...
[ "def", "posthoc_nemenyi", "(", "a", ",", "val_col", "=", "None", ",", "group_col", "=", "None", ",", "dist", "=", "'chi'", ",", "sort", "=", "True", ")", ":", "def", "compare_stats_chi", "(", "i", ",", "j", ")", ":", "diff", "=", "np", ".", "abs", ...
33.953271
0.00214
def atlas_node_stop( atlas_state ): """ Stop the atlas node threads """ for component in atlas_state.keys(): log.debug("Stopping Atlas component '%s'" % component) atlas_state[component].ask_join() atlas_state[component].join() return True
[ "def", "atlas_node_stop", "(", "atlas_state", ")", ":", "for", "component", "in", "atlas_state", ".", "keys", "(", ")", ":", "log", ".", "debug", "(", "\"Stopping Atlas component '%s'\"", "%", "component", ")", "atlas_state", "[", "component", "]", ".", "ask_j...
27.5
0.010563
def gen_length_feats(self, e_set): """ Generates length based features from an essay set Generally an internal function called by gen_feats Returns an array of length features e_set - EssaySet object """ text = e_set._text lengths = [len(e) for e in text] ...
[ "def", "gen_length_feats", "(", "self", ",", "e_set", ")", ":", "text", "=", "e_set", ".", "_text", "lengths", "=", "[", "len", "(", "e", ")", "for", "e", "in", "text", "]", "word_counts", "=", "[", "max", "(", "len", "(", "t", ")", ",", "1", "...
45.26087
0.01223
def run(self): ''' Runs the DICOM conversion based on internal state. ''' self._log('Converting DICOM image.\n') try: self._log('PatientName: %s\n' % self._dcm.PatientName) except AttributeError: self._log('PatientNam...
[ "def", "run", "(", "self", ")", ":", "self", ".", "_log", "(", "'Converting DICOM image.\\n'", ")", "try", ":", "self", ".", "_log", "(", "'PatientName: %s\\n'", "%", "self", ".", "_dcm", ".", "PatientName", ")", "except", "Attribu...
52
0.01407
def checkout_with_fetch(git_folder, refspec, repository="origin"): """Fetch the refspec, and checkout FETCH_HEAD. Beware that you will ne in detached head mode. """ _LOGGER.info("Trying to fetch and checkout %s", refspec) repo = Repo(str(git_folder)) repo.git.fetch(repository, refspec) # FETCH_...
[ "def", "checkout_with_fetch", "(", "git_folder", ",", "refspec", ",", "repository", "=", "\"origin\"", ")", ":", "_LOGGER", ".", "info", "(", "\"Trying to fetch and checkout %s\"", ",", "refspec", ")", "repo", "=", "Repo", "(", "str", "(", "git_folder", ")", "...
47.666667
0.002288
def canonical_statistics_dtype(spanning_cluster=True): """ The NumPy Structured Array type for canonical statistics Helper function Parameters ---------- spanning_cluster : bool, optional Whether to detect a spanning cluster or not. Defaults to ``True``. Returns ------...
[ "def", "canonical_statistics_dtype", "(", "spanning_cluster", "=", "True", ")", ":", "fields", "=", "list", "(", ")", "if", "spanning_cluster", ":", "fields", ".", "extend", "(", "[", "(", "'percolation_probability'", ",", "'float64'", ")", ",", "]", ")", "f...
25.647059
0.001105
def stripped_lines(lines, ignore_comments, ignore_docstrings, ignore_imports): """return lines with leading/trailing whitespace and any ignored code features removed """ if ignore_imports: tree = astroid.parse("".join(lines)) node_is_import_by_lineno = ( (node.lineno, isinsta...
[ "def", "stripped_lines", "(", "lines", ",", "ignore_comments", ",", "ignore_docstrings", ",", "ignore_imports", ")", ":", "if", "ignore_imports", ":", "tree", "=", "astroid", ".", "parse", "(", "\"\"", ".", "join", "(", "lines", ")", ")", "node_is_import_by_li...
36.340909
0.001218
def scanABFfolder(abfFolder): """ scan an ABF directory and subdirectory. Try to do this just once. Returns ABF files, SWHLab files, and groups. """ assert os.path.isdir(abfFolder) filesABF=forwardSlash(sorted(glob.glob(abfFolder+"/*.*"))) filesSWH=[] if os.path.exists(abfFolder+"/swhlab...
[ "def", "scanABFfolder", "(", "abfFolder", ")", ":", "assert", "os", ".", "path", ".", "isdir", "(", "abfFolder", ")", "filesABF", "=", "forwardSlash", "(", "sorted", "(", "glob", ".", "glob", "(", "abfFolder", "+", "\"/*.*\"", ")", ")", ")", "filesSWH", ...
38.25
0.014894
def proj_archetypes(self, test_data, reverse_transform=False): """ Convert archetypes of the model into original feature space. :param H2OFrame test_data: The dataset upon which the model was trained. :param bool reverse_transform: Whether the transformation of the training data during ...
[ "def", "proj_archetypes", "(", "self", ",", "test_data", ",", "reverse_transform", "=", "False", ")", ":", "if", "test_data", "is", "None", "or", "test_data", ".", "nrow", "==", "0", ":", "raise", "ValueError", "(", "\"Must specify test data\"", ")", "j", "=...
62.285714
0.011299
def upload(self, num_iid, properties, session, id=None, image=None, position=None): '''taobao.item.propimg.upload 添加或修改属性图片 添加一张商品属性图片到num_iid指定的商品中 传入的num_iid所对应的商品必须属于当前会话的用户 图片的属性必须要是颜色的属性,这个在前台显示的时候需要和sku进行关联的 商品属性图片只有享有服务的卖家(如:淘宝大卖家、订购了淘宝多图服务的卖家)才能上传 商品属性图片有数量和大小上的限制,最多不能超过24张(每个颜色属性都有一张)。...
[ "def", "upload", "(", "self", ",", "num_iid", ",", "properties", ",", "session", ",", "id", "=", "None", ",", "image", "=", "None", ",", "position", "=", "None", ")", ":", "request", "=", "TOPRequest", "(", "'taobao.item.propimg.upload'", ")", "request", ...
47.666667
0.015089
def timing(self): """ Estimates timing information for the current setup. You should run a check on the instrument parameters before calling this. Returns: (expTime, deadTime, cycleTime, dutyCycle) expTime : exposure time per frame (seconds) deadTime : dead time per ...
[ "def", "timing", "(", "self", ")", ":", "# drift mode y/n?", "isDriftMode", "=", "self", ".", "isDrift", "(", ")", "# FF y/n?", "isFF", "=", "self", ".", "isFF", "(", ")", "# Set the readout speed", "readSpeed", "=", "self", ".", "readSpeed", "(", ")", "if...
39.127962
0.000827
def command_builder(self, string, value=None, default=None, disable=None): """Builds a command with keywords Notes: Negating a command string by overriding 'value' with None or an assigned value that evalutates to false has been deprecated. Please use 'disabl...
[ "def", "command_builder", "(", "self", ",", "string", ",", "value", "=", "None", ",", "default", "=", "None", ",", "disable", "=", "None", ")", ":", "if", "default", ":", "return", "'default %s'", "%", "string", "elif", "disable", ":", "return", "'no %s'...
39.181818
0.001509
def delete_sessions(self, uid): ''' a method to delete all session tokens associated with a user :param uid: string with id of user in bucket :return: integer with status code of delete operation ''' title = '%s.delete_session' % self.__clas...
[ "def", "delete_sessions", "(", "self", ",", "uid", ")", ":", "title", "=", "'%s.delete_session'", "%", "self", ".", "__class__", ".", "__name__", "# validate inputs", "input_fields", "=", "{", "'uid'", ":", "uid", "}", "for", "key", ",", "value", "in", "in...
29.307692
0.010165
def add_entity_errors( self, property_name, direct_errors=None, schema_errors=None ): """ Attach nested entity errors Accepts a list errors coming from validators attached directly, or a dict of errors produced by a nested schema. :param prope...
[ "def", "add_entity_errors", "(", "self", ",", "property_name", ",", "direct_errors", "=", "None", ",", "schema_errors", "=", "None", ")", ":", "if", "direct_errors", "is", "None", "and", "schema_errors", "is", "None", ":", "return", "self", "# direct errors", ...
34.053571
0.001529
def print_tree(graph, tails, node_id_map): """Print out a tree of blocks starting from the common ancestor.""" # Example: # | # | 5 # * a {0, 1, 2, 3, 4} # | # | 6 # |\ # * | b {0, 1, 2, 3} # | * n {4} # | | # | | 7 # * | c {0, 1, 2, 3} # | * o {4} # | | ...
[ "def", "print_tree", "(", "graph", ",", "tails", ",", "node_id_map", ")", ":", "# Example:", "# |", "# | 5", "# * a {0, 1, 2, 3, 4}", "# |", "# | 6", "# |\\", "# * | b {0, 1, 2, 3}", "# | * n {4}", "# | |", "# | | 7", "# * | c {0, 1, 2, 3}", "# | * o {4}", "# | |",...
21.270588
0.000529
def get_group(group_or_groupname): """Return Plone Group :param group_or_groupname: Plone group or the name of the group :type groupname: GroupData/str :returns: Plone GroupData """ if not group_or_groupname: return None if hasattr(group_or_groupname, "_getGroup"): return ...
[ "def", "get_group", "(", "group_or_groupname", ")", ":", "if", "not", "group_or_groupname", ":", "return", "None", "if", "hasattr", "(", "group_or_groupname", ",", "\"_getGroup\"", ")", ":", "return", "group_or_groupname", "gtool", "=", "get_tool", "(", "\"portal_...
29.5
0.002347
def _wait(self, args, now, cap, consumed_history, consumed_capacity): """ Check the consumed capacity against the limit and sleep """ for key in ['read', 'write']: if key in cap and cap[key] > 0: consumed_history[key].add(now, consumed_capacity[key]) consumed ...
[ "def", "_wait", "(", "self", ",", "args", ",", "now", ",", "cap", ",", "consumed_history", ",", "consumed_capacity", ")", ":", "for", "key", "in", "[", "'read'", ",", "'write'", "]", ":", "if", "key", "in", "cap", "and", "cap", "[", "key", "]", ">"...
55.733333
0.002353
def _DoParse(self): """Parse a file for history records yielding dicts. Yields: Dicts containing browser history """ get4 = lambda x: struct.unpack("<L", self.input_dat[x:x + 4])[0] filesize = get4(0x1c) offset = get4(0x20) coffset = offset while coffset < filesize: etype = ...
[ "def", "_DoParse", "(", "self", ")", ":", "get4", "=", "lambda", "x", ":", "struct", ".", "unpack", "(", "\"<L\"", ",", "self", ".", "input_dat", "[", "x", ":", "x", "+", "4", "]", ")", "[", "0", "]", "filesize", "=", "get4", "(", "0x1c", ")", ...
31.368421
0.009772
def create_model(model_folder, model_type, topology, override): """ Create a model if it doesn't exist already. Parameters ---------- model_folder : The path to the folder where the model is described with an `info.yml` model_type : MLP topology : Something like 160:...
[ "def", "create_model", "(", "model_folder", ",", "model_type", ",", "topology", ",", "override", ")", ":", "latest_model", "=", "utils", ".", "get_latest_in_folder", "(", "model_folder", ",", "\".json\"", ")", "if", "(", "latest_model", "==", "\"\"", ")", "or"...
36.689655
0.000916
def add_output_file(self, filename): """ Add filename as a output file for this DAG node. @param filename: output filename to add """ if filename not in self.__output_files: self.__output_files.append(filename) if not isinstance(self.job(), CondorDAGManJob): if self.job().get_un...
[ "def", "add_output_file", "(", "self", ",", "filename", ")", ":", "if", "filename", "not", "in", "self", ".", "__output_files", ":", "self", ".", "__output_files", ".", "append", "(", "filename", ")", "if", "not", "isinstance", "(", "self", ".", "job", "...
33.727273
0.010499
def _handle_log_rotations(self): ''' Rotate each handler's log file if necessary ''' for h in self.capture_handlers: if self._should_rotate_log(h): self._rotate_log(h)
[ "def", "_handle_log_rotations", "(", "self", ")", ":", "for", "h", "in", "self", ".", "capture_handlers", ":", "if", "self", ".", "_should_rotate_log", "(", "h", ")", ":", "self", ".", "_rotate_log", "(", "h", ")" ]
41.4
0.009479
def auth_string(self): ''' Authenticate based on username and token which is base64-encoded ''' username_token = '{username}:{token}'.format(username=self.username, token=self.token) b64encoded_string = b64encode(username_token) auth_string = 'Token {b64}'.format(b64=b64...
[ "def", "auth_string", "(", "self", ")", ":", "username_token", "=", "'{username}:{token}'", ".", "format", "(", "username", "=", "self", ".", "username", ",", "token", "=", "self", ".", "token", ")", "b64encoded_string", "=", "b64encode", "(", "username_token"...
35.4
0.008264
def roles_add(user, role): """Add user to role.""" user, role = _datastore._prepare_role_modify_args(user, role) if user is None: raise click.UsageError('Cannot find user.') if role is None: raise click.UsageError('Cannot find role.') if _datastore.add_role_to_user(user, role): ...
[ "def", "roles_add", "(", "user", ",", "role", ")", ":", "user", ",", "role", "=", "_datastore", ".", "_prepare_role_modify_args", "(", "user", ",", "role", ")", "if", "user", "is", "None", ":", "raise", "click", ".", "UsageError", "(", "'Cannot find user.'...
41.166667
0.00198
def basic_ack(self, delivery_tag, multiple=False): """Acknowledge one or more messages This method acknowledges one or more messages delivered via the Deliver or Get-Ok methods. The client can ask to confirm a single message or a set of messages up to and including a specific m...
[ "def", "basic_ack", "(", "self", ",", "delivery_tag", ",", "multiple", "=", "False", ")", ":", "args", "=", "AMQPWriter", "(", ")", "args", ".", "write_longlong", "(", "delivery_tag", ")", "args", ".", "write_bit", "(", "multiple", ")", "self", ".", "_se...
36.254902
0.001053
def lookup_language(languages, ranges): """ Look up a single language in the sequence `languages` using the lookup mechansim described in RFC4647. If no match is found, :data:`None` is returned. Otherwise, the first matching language is returned. `languages` must be a sequence of :class:`LanguageTa...
[ "def", "lookup_language", "(", "languages", ",", "ranges", ")", ":", "for", "language_range", "in", "ranges", ":", "while", "True", ":", "try", ":", "return", "next", "(", "iter", "(", "basic_filter_languages", "(", "languages", ",", "[", "language_range", "...
34.043478
0.001242
def qstd(x,quant=0.05,top=False,bottom=False): """returns std, ignoring outer 'quant' pctiles """ s = np.sort(x) n = np.size(x) lo = s[int(n*quant)] hi = s[int(n*(1-quant))] if top: w = np.where(x>=lo) elif bottom: w = np.where(x<=hi) else: w = np.where((x>=lo...
[ "def", "qstd", "(", "x", ",", "quant", "=", "0.05", ",", "top", "=", "False", ",", "bottom", "=", "False", ")", ":", "s", "=", "np", ".", "sort", "(", "x", ")", "n", "=", "np", ".", "size", "(", "x", ")", "lo", "=", "s", "[", "int", "(", ...
24.357143
0.025424
def getSkeletalBoneData(self, action, eTransformSpace, eMotionRange, unTransformArrayCount): """Reads the state of the skeletal bone data associated with this action and copies it into the given buffer.""" fn = self.function_table.getSkeletalBoneData pTransformArray = VRBoneTransform_t() ...
[ "def", "getSkeletalBoneData", "(", "self", ",", "action", ",", "eTransformSpace", ",", "eMotionRange", ",", "unTransformArrayCount", ")", ":", "fn", "=", "self", ".", "function_table", ".", "getSkeletalBoneData", "pTransformArray", "=", "VRBoneTransform_t", "(", ")"...
64.571429
0.010917
def nucmer(args): """ %prog nucmer mappings.bed MTR.fasta assembly.fasta chr1 3 Select specific chromosome region based on MTR mapping. The above command will extract chr1:2,000,001-3,000,000. """ p = OptionParser(nucmer.__doc__) opts, args = p.parse_args(args) if len(args) != 5: ...
[ "def", "nucmer", "(", "args", ")", ":", "p", "=", "OptionParser", "(", "nucmer", ".", "__doc__", ")", "opts", ",", "args", "=", "p", ".", "parse_args", "(", "args", ")", "if", "len", "(", "args", ")", "!=", "5", ":", "sys", ".", "exit", "(", "n...
28.75
0.001869
def barrier(self): """ .. note:: Experimental Sets a global barrier and waits until all tasks in this stage hit this barrier. Similar to `MPI_Barrier` function in MPI, this function blocks until all tasks in the same stage have reached this routine. .. warning:: In a ba...
[ "def", "barrier", "(", "self", ")", ":", "if", "self", ".", "_port", "is", "None", "or", "self", ".", "_secret", "is", "None", ":", "raise", "Exception", "(", "\"Not supported to call barrier() before initialize \"", "+", "\"BarrierTaskContext.\"", ")", "else", ...
42.368421
0.008505
def Arrow(startPoint, endPoint, s=None, c="r", alpha=1, res=12): """ Build a 3D arrow from `startPoint` to `endPoint` of section size `s`, expressed as the fraction of the window size. .. note:: If ``s=None`` the arrow is scaled proportionally to its length, otherwise it represents th...
[ "def", "Arrow", "(", "startPoint", ",", "endPoint", ",", "s", "=", "None", ",", "c", "=", "\"r\"", ",", "alpha", "=", "1", ",", "res", "=", "12", ")", ":", "axis", "=", "np", ".", "array", "(", "endPoint", ")", "-", "np", ".", "array", "(", "...
30.208333
0.002004
def lzs (inlist): """ Returns a list of z-scores, one for each score in the passed list. Usage: lzs(inlist) """ zscores = [] for item in inlist: zscores.append(z(inlist,item)) return zscores
[ "def", "lzs", "(", "inlist", ")", ":", "zscores", "=", "[", "]", "for", "item", "in", "inlist", ":", "zscores", ".", "append", "(", "z", "(", "inlist", ",", "item", ")", ")", "return", "zscores" ]
20.8
0.013825
def _generate_window_strategies(): """ Create all window and wsymm strategies """ for wnd_dict in window._content_generation_table: names = wnd_dict["names"] sname = wnd_dict["sname"] = names[0] wnd_dict.setdefault("params_def", "") for sdict in [window, wsymm]: docs_dict = window._doc_kwargs(...
[ "def", "_generate_window_strategies", "(", ")", ":", "for", "wnd_dict", "in", "window", ".", "_content_generation_table", ":", "names", "=", "wnd_dict", "[", "\"names\"", "]", "sname", "=", "wnd_dict", "[", "\"sname\"", "]", "=", "names", "[", "0", "]", "wnd...
49.058824
0.012941
def attributes(self): """List of attributes available for the dataset (cached).""" if self._attributes is None: self._filters, self._attributes = self._fetch_configuration() return self._attributes
[ "def", "attributes", "(", "self", ")", ":", "if", "self", ".", "_attributes", "is", "None", ":", "self", ".", "_filters", ",", "self", ".", "_attributes", "=", "self", ".", "_fetch_configuration", "(", ")", "return", "self", ".", "_attributes" ]
45.8
0.008584
def add_coconut_to_path(): """Adds coconut to sys.path if it isn't there already.""" try: import coconut # NOQA except ImportError: sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
[ "def", "add_coconut_to_path", "(", ")", ":", "try", ":", "import", "coconut", "# NOQA", "except", "ImportError", ":", "sys", ".", "path", ".", "insert", "(", "0", ",", "os", ".", "path", ".", "dirname", "(", "os", ".", "path", ".", "dirname", "(", "o...
39.166667
0.008333
def nguHanh(tenHanh): """ Args: tenHanh (string): Tên Hành trong ngũ hành, Kim hoặc K, Moc hoặc M, Thuy hoặc T, Hoa hoặc H, Tho hoặc O Returns: Dictionary: ID của Hành, tên đầy đủ của Hành, số Cục của Hành Raises: Exception: Description """ if tenHanh in ["Kim",...
[ "def", "nguHanh", "(", "tenHanh", ")", ":", "if", "tenHanh", "in", "[", "\"Kim\"", ",", "\"K\"", "]", ":", "return", "{", "\"id\"", ":", "1", ",", "\"tenHanh\"", ":", "\"Kim\"", ",", "\"cuc\"", ":", "4", ",", "\"tenCuc\"", ":", "\"Kim tứ Cục\",", "", ...
37.83871
0.000831
def load(file_obj): """ load contents from file_obj, returning a generator that yields one element at a time """ cur_elt = [] for line in file_obj: cur_elt.append(line) if line == '\n': pickled_elt_str = ''.join(cur_elt) cur_el...
[ "def", "load", "(", "file_obj", ")", ":", "cur_elt", "=", "[", "]", "for", "line", "in", "file_obj", ":", "cur_elt", ".", "append", "(", "line", ")", "if", "line", "==", "'\\n'", ":", "pickled_elt_str", "=", "''", ".", "join", "(", "cur_elt", ")", ...
25
0.008565
def circular(args): """ %prog circular fastafile startpos Make circular genome, startpos is the place to start the sequence. This can be determined by mapping to a reference. Self overlaps are then resolved. Startpos is 1-based. """ from jcvi.assembly.goldenpath import overlap p = Opti...
[ "def", "circular", "(", "args", ")", ":", "from", "jcvi", ".", "assembly", ".", "goldenpath", "import", "overlap", "p", "=", "OptionParser", "(", "circular", ".", "__doc__", ")", "p", ".", "add_option", "(", "\"--flip\"", ",", "default", "=", "False", ",...
27.755556
0.000773
def get_xmldoc_path(self, filepath): """Returns the full path to a possible XML documentation file for the specified code filepath.""" segs = filepath.split(".") segs.pop() return ".".join(segs) + ".xml"
[ "def", "get_xmldoc_path", "(", "self", ",", "filepath", ")", ":", "segs", "=", "filepath", ".", "split", "(", "\".\"", ")", "segs", ".", "pop", "(", ")", "return", "\".\"", ".", "join", "(", "segs", ")", "+", "\".xml\"" ]
39.666667
0.00823
def qhalf(self): """get the square root of the cofactor matrix attribute. Create the attribute if it has not yet been created Returns ------- qhalf : pyemu.Matrix """ if self.__qhalf != None: return self.__qhalf self.log("qhalf") self...
[ "def", "qhalf", "(", "self", ")", ":", "if", "self", ".", "__qhalf", "!=", "None", ":", "return", "self", ".", "__qhalf", "self", ".", "log", "(", "\"qhalf\"", ")", "self", ".", "__qhalf", "=", "self", ".", "obscov", "**", "(", "-", "0.5", ")", "...
26.133333
0.009852
def version(*names, **kwargs): ''' Common interface for obtaining the version of installed packages. CLI Example: .. code-block:: bash salt '*' pkg_resource.version vim salt '*' pkg_resource.version foo bar baz salt '*' pkg_resource.version 'python*' ''' ret = {} v...
[ "def", "version", "(", "*", "names", ",", "*", "*", "kwargs", ")", ":", "ret", "=", "{", "}", "versions_as_list", "=", "salt", ".", "utils", ".", "data", ".", "is_true", "(", "kwargs", ".", "pop", "(", "'versions_as_list'", ",", "False", ")", ")", ...
30.885714
0.000897
def scenario_risk(riskinputs, riskmodel, param, monitor): """ Core function for a scenario computation. :param riskinput: a of :class:`openquake.risklib.riskinput.RiskInput` object :param riskmodel: a :class:`openquake.risklib.riskinput.CompositeRiskModel` instance :param param: ...
[ "def", "scenario_risk", "(", "riskinputs", ",", "riskmodel", ",", "param", ",", "monitor", ")", ":", "E", "=", "param", "[", "'E'", "]", "L", "=", "len", "(", "riskmodel", ".", "loss_types", ")", "result", "=", "dict", "(", "agg", "=", "numpy", ".", ...
44.911111
0.000969
def hubbards(self): """ Hubbard U values used if a vasprun is a GGA+U run. {} otherwise. """ symbols = [s.split()[1] for s in self.potcar_symbols] symbols = [re.split(r"_", s)[0] for s in symbols] if not self.incar.get("LDAU", False): return {} us = se...
[ "def", "hubbards", "(", "self", ")", ":", "symbols", "=", "[", "s", ".", "split", "(", ")", "[", "1", "]", "for", "s", "in", "self", ".", "potcar_symbols", "]", "symbols", "=", "[", "re", ".", "split", "(", "r\"_\"", ",", "s", ")", "[", "0", ...
42.684211
0.002413
def change_group_name(self, group_jid: str, new_name: str): """ Changes the a group's name to something new :param group_jid: The JID of the group whose name should be changed :param new_name: The new name to give to the group """ log.info("[+] Requesting a group name ch...
[ "def", "change_group_name", "(", "self", ",", "group_jid", ":", "str", ",", "new_name", ":", "str", ")", ":", "log", ".", "info", "(", "\"[+] Requesting a group name change for JID {} to '{}'\"", ".", "format", "(", "group_jid", ",", "new_name", ")", ")", "retur...
51.666667
0.008457
def on_message(self, unused_channel, basic_deliver, properties, body): """Called on receipt of a message from a queue. Processes the message using the self._process method or function and positively acknowledges the queue if successful. If processing is not succesful, the message can ei...
[ "def", "on_message", "(", "self", ",", "unused_channel", ",", "basic_deliver", ",", "properties", ",", "body", ")", ":", "if", "self", ".", "check_tx_id", ":", "try", ":", "tx_id", "=", "self", ".", "tx_id", "(", "properties", ")", "logger", ".", "info",...
42.037037
0.002009
def completeness_score(self, reference_clusters): """ Calculates the completeness score w.r.t. the reference clusters (explicit evaluation) :param reference_clusters: Clusters that are to be used as reference :return: the resulting completeness score """ return completen...
[ "def", "completeness_score", "(", "self", ",", "reference_clusters", ")", ":", "return", "completeness_score", "(", "self", ".", "get_labels", "(", "self", ")", ",", "self", ".", "get_labels", "(", "reference_clusters", ")", ")" ]
47.75
0.010283
def hx2dp(string): """ Convert a string representing a double precision number in a base 16 scientific notation into its equivalent double precision number. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/hx2dp_c.html :param string: Hex form string to convert to double precision. :...
[ "def", "hx2dp", "(", "string", ")", ":", "string", "=", "stypes", ".", "stringToCharP", "(", "string", ")", "lenout", "=", "ctypes", ".", "c_int", "(", "80", ")", "errmsg", "=", "stypes", ".", "stringToCharP", "(", "lenout", ")", "number", "=", "ctypes...
33.5
0.001209
def indent_files(arguments): """ indent_files(fname : str) 1. Creates a backup of the source file(backup_source_file()) 2. Reads the files contents(read_file()) 3. Indents the code(indent_code()) 4. Writes the file or print the indented code(_after_indentation()) """ opts = parse_options(ar...
[ "def", "indent_files", "(", "arguments", ")", ":", "opts", "=", "parse_options", "(", "arguments", ")", "if", "not", "opts", ".", "files", ":", "# Indent from stdin", "code", "=", "sys", ".", "stdin", ".", "read", "(", ")", "indent_result", "=", "indent_co...
35.513514
0.001481
def hash(self): """Generate a hash value.""" h = hash_pandas_object(self, index=True) return hashlib.md5(h.values.tobytes()).hexdigest()
[ "def", "hash", "(", "self", ")", ":", "h", "=", "hash_pandas_object", "(", "self", ",", "index", "=", "True", ")", "return", "hashlib", ".", "md5", "(", "h", ".", "values", ".", "tobytes", "(", ")", ")", ".", "hexdigest", "(", ")" ]
39.25
0.0125
def send_message(message, pipe='public'): """ writes message to pipe """ if pipe not in ['public', 'private']: raise ValueError('pipe argument can be only "public" or "private"') else: pipe = pipe.upper() pipe_path = PUBLIC_PIPE if pipe == 'PUBLIC' else PRIVATE_PIPE # creat...
[ "def", "send_message", "(", "message", ",", "pipe", "=", "'public'", ")", ":", "if", "pipe", "not", "in", "[", "'public'", ",", "'private'", "]", ":", "raise", "ValueError", "(", "'pipe argument can be only \"public\" or \"private\"'", ")", "else", ":", "pipe", ...
27.5
0.002198
def create_widget(self): """ Create the underlying widget. """ d = self.declaration self.widget = Picker(self.get_context(), None, d.style or '@attr/numberPickerStyle')
[ "def", "create_widget", "(", "self", ")", ":", "d", "=", "self", ".", "declaration", "self", ".", "widget", "=", "Picker", "(", "self", ".", "get_context", "(", ")", ",", "None", ",", "d", ".", "style", "or", "'@attr/numberPickerStyle'", ")" ]
32
0.008696
def list_key_policies(key_id, limit=None, marker=None, region=None, key=None, keyid=None, profile=None): ''' List key_policies for the specified key. CLI example:: salt myminion boto_kms.list_key_policies 'alias/mykey' ''' conn = _get_conn(region=region, key=key, keyi...
[ "def", "list_key_policies", "(", "key_id", ",", "limit", "=", "None", ",", "marker", "=", "None", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "conn", "=", "_get_conn", "(", ...
31.16
0.001245
def description_director(**kwargs): """Direct which class should be used based on the director qualifier. """ description_type = {'physical': DCFormat} qualifier = kwargs.get('qualifier') # Determine the type of element needed, based on the qualifier. element_class = description_type.get(qu...
[ "def", "description_director", "(", "*", "*", "kwargs", ")", ":", "description_type", "=", "{", "'physical'", ":", "DCFormat", "}", "qualifier", "=", "kwargs", ".", "get", "(", "'qualifier'", ")", "# Determine the type of element needed, based on the qualifier.", "ele...
36.142857
0.001927
def cublasZhpr2(handle, uplo, n, alpha, x, inx, y, incy, AP): """ Rank-2 operation on Hermitian-packed matrix. """ status = _libcublas.cublasZhpr2_v2(handle, _CUBLAS_FILL_MODE[uplo], n, ctypes.byref(cuda.cuDoubleComple...
[ "def", "cublasZhpr2", "(", "handle", ",", "uplo", ",", "n", ",", "alpha", ",", "x", ",", "inx", ",", "y", ",", "incy", ",", "AP", ")", ":", "status", "=", "_libcublas", ".", "cublasZhpr2_v2", "(", "handle", ",", "_CUBLAS_FILL_MODE", "[", "uplo", "]",...
43.333333
0.013183
def pHYs(self): """ pHYs chunk in PNG image, or |None| if not present """ match = lambda chunk: chunk.type_name == PNG_CHUNK_TYPE.pHYs # noqa return self._find_first(match)
[ "def", "pHYs", "(", "self", ")", ":", "match", "=", "lambda", "chunk", ":", "chunk", ".", "type_name", "==", "PNG_CHUNK_TYPE", ".", "pHYs", "# noqa", "return", "self", ".", "_find_first", "(", "match", ")" ]
34.666667
0.014085
def load_data(self, filename, *args, **kwargs): """ Load text data from different sheets. """ # load text data data = super(MixedTextXLS, self).load_data(filename) # iterate through sheets in parameters for sheet_params in self.parameters.itervalues(): ...
[ "def", "load_data", "(", "self", ",", "filename", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# load text data", "data", "=", "super", "(", "MixedTextXLS", ",", "self", ")", ".", "load_data", "(", "filename", ")", "# iterate through sheets in param...
49.9375
0.001228
def whois(cls, whois_server, domain=None, timeout=None): # pragma: no cover """ Implementation of UNIX whois. :param whois_server: The WHOIS server to use to get the record. :type whois_server: str :param domain: The domain to get the whois record from. :type domain: s...
[ "def", "whois", "(", "cls", ",", "whois_server", ",", "domain", "=", "None", ",", "timeout", "=", "None", ")", ":", "# pragma: no cover", "if", "domain", "is", "None", ":", "# The domain is not given (localy).", "# We consider the domain as the domain or IP we are curre...
31.18018
0.0014
def DeleteNodeTags(r, node, tags, dry_run=False): """ Delete tags from a node. @type node: str @param node: node to remove tags from @type tags: list of str @param tags: tags to remove from the node @type dry_run: bool @param dry_run: whether to perform a dry run @rtype: int @r...
[ "def", "DeleteNodeTags", "(", "r", ",", "node", ",", "tags", ",", "dry_run", "=", "False", ")", ":", "query", "=", "{", "\"tag\"", ":", "tags", ",", "\"dry-run\"", ":", "dry_run", ",", "}", "return", "r", ".", "request", "(", "\"delete\"", ",", "\"/2...
22.047619
0.00207
def get_process_mapping(): """Try to look up the process tree via Linux's /proc """ with open('/proc/{0}/stat'.format(os.getpid())) as f: self_tty = f.read().split()[STAT_TTY] processes = {} for pid in os.listdir('/proc'): if not pid.isdigit(): continue try: ...
[ "def", "get_process_mapping", "(", ")", ":", "with", "open", "(", "'/proc/{0}/stat'", ".", "format", "(", "os", ".", "getpid", "(", ")", ")", ")", "as", "f", ":", "self_tty", "=", "f", ".", "read", "(", ")", ".", "split", "(", ")", "[", "STAT_TTY",...
36.64
0.001064
def strongest_match(cls, overlay, mode, backend=None): """ Returns the single strongest matching compositor operation given an overlay. If no matches are found, None is returned. The best match is defined as the compositor operation with the highest match value as returned by th...
[ "def", "strongest_match", "(", "cls", ",", "overlay", ",", "mode", ",", "backend", "=", "None", ")", ":", "match_strength", "=", "[", "(", "op", ".", "match_level", "(", "overlay", ")", ",", "op", ")", "for", "op", "in", "cls", ".", "definitions", "i...
54.384615
0.011127
def to_gds(self, multiplier): """ Convert this object to a series of GDSII elements. Parameters ---------- multiplier : number A number that multiplies all dimensions written in the GDSII elements. Returns ------- out : string ...
[ "def", "to_gds", "(", "self", ",", "multiplier", ")", ":", "data", "=", "[", "]", "for", "ii", "in", "range", "(", "len", "(", "self", ".", "polygons", ")", ")", ":", "if", "len", "(", "self", ".", "polygons", "[", "ii", "]", ")", ">", "4094", ...
39.411765
0.001457
def name(self, src=None): """Return string representing the name of this type.""" return " & ".join(_get_type_name(tt, src) for tt in self._types)
[ "def", "name", "(", "self", ",", "src", "=", "None", ")", ":", "return", "\" & \"", ".", "join", "(", "_get_type_name", "(", "tt", ",", "src", ")", "for", "tt", "in", "self", ".", "_types", ")" ]
53.333333
0.012346
def patch_namespaced_pod_disruption_budget(self, name, namespace, body, **kwargs): # noqa: E501 """patch_namespaced_pod_disruption_budget # noqa: E501 partially update the specified PodDisruptionBudget # noqa: E501 This method makes a synchronous HTTP request by default. To make an a...
[ "def", "patch_namespaced_pod_disruption_budget", "(", "self", ",", "name", ",", "namespace", ",", "body", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async_r...
64.64
0.00122
def get_privilege_information(): """ Get all privileges associated with the current process. """ # first call with zero length to determine what size buffer we need return_length = wintypes.DWORD() params = [ get_process_token(), privilege.TOKEN_INFORMATION_CLASS.TokenPrivileges, None, 0, return_length...
[ "def", "get_privilege_information", "(", ")", ":", "# first call with zero length to determine what size buffer we need", "return_length", "=", "wintypes", ".", "DWORD", "(", ")", "params", "=", "[", "get_process_token", "(", ")", ",", "privilege", ".", "TOKEN_INFORMATION...
25.517241
0.029948
def add_arrow(self, x1, y1, x2, y2, **kws): """add arrow to plot""" self.panel.add_arrow(x1, y1, x2, y2, **kws)
[ "def", "add_arrow", "(", "self", ",", "x1", ",", "y1", ",", "x2", ",", "y2", ",", "*", "*", "kws", ")", ":", "self", ".", "panel", ".", "add_arrow", "(", "x1", ",", "y1", ",", "x2", ",", "y2", ",", "*", "*", "kws", ")" ]
41.666667
0.015748
def adjuestSize(self, offsetWidth = 0, offsetHeight = 0): """! \~english Adjuest width and height of rectangles @param offsetWidth: adjust the width. Negative numbers are smaller, Positive number is increased @param offsetHeight: adjust the height. Negative numbers are smaller, ...
[ "def", "adjuestSize", "(", "self", ",", "offsetWidth", "=", "0", ",", "offsetHeight", "=", "0", ")", ":", "self", ".", "height", "+=", "offsetHeight", "self", ".", "width", "+=", "offsetWidth" ]
38.055556
0.019943
def unread_count(current): """ Number of unread messages for current user .. code-block:: python # request: { 'view':'_zops_unread_count', } # response: { 'status': 'OK', 'co...
[ "def", "unread_count", "(", "current", ")", ":", "unread_ntf", "=", "0", "unread_msg", "=", "0", "for", "sbs", "in", "current", ".", "user", ".", "subscriptions", ".", "objects", ".", "filter", "(", "is_visible", "=", "True", ")", ":", "try", ":", "if"...
26.289474
0.000965
def _output_stmt(self, stmt: Statement, sctx: SchemaContext) -> None: """Handle RPC or action output statement.""" self.get_child("output")._handle_substatements(stmt, sctx)
[ "def", "_output_stmt", "(", "self", ",", "stmt", ":", "Statement", ",", "sctx", ":", "SchemaContext", ")", "->", "None", ":", "self", ".", "get_child", "(", "\"output\"", ")", ".", "_handle_substatements", "(", "stmt", ",", "sctx", ")" ]
62.333333
0.010582
def retryable(a_func, retry_options, **kwargs): """Creates a function equivalent to a_func, but that retries on certain exceptions. Args: a_func (callable): A callable. retry_options (RetryOptions): Configures the exceptions upon which the callable should retry, and the parameters to th...
[ "def", "retryable", "(", "a_func", ",", "retry_options", ",", "*", "*", "kwargs", ")", ":", "delay_mult", "=", "retry_options", ".", "backoff_settings", ".", "retry_delay_multiplier", "max_delay_millis", "=", "retry_options", ".", "backoff_settings", ".", "max_retry...
40.328767
0.000663
def tag_kind(tag, default=consts.TAG_KIND_UNKNOWN): """\ Returns the TAG kind. `tag` A string. `default` A value to return if the TAG kind is unknown (set to ``constants.TAG_KIND_UNKNOWN`` by default) """ if len(tag) == 2: return consts.TAG_KIND_GEO if u',' i...
[ "def", "tag_kind", "(", "tag", ",", "default", "=", "consts", ".", "TAG_KIND_UNKNOWN", ")", ":", "if", "len", "(", "tag", ")", "==", "2", ":", "return", "consts", ".", "TAG_KIND_GEO", "if", "u','", "in", "tag", ":", "return", "consts", ".", "TAG_KIND_P...
26.681818
0.001645
def start(uri=None, tag_prefix='salt/engines/libvirt_events', filters=None): ''' Listen to libvirt events and forward them to salt. :param uri: libvirt URI to listen on. Defaults to None to pick the first available local hypervisor :param tag_prefix: the begining of ...
[ "def", "start", "(", "uri", "=", "None", ",", "tag_prefix", "=", "'salt/engines/libvirt_events'", ",", "filters", "=", "None", ")", ":", "if", "filters", "is", "None", ":", "filters", "=", "[", "'all'", "]", "try", ":", "libvirt", ".", "virEventRegisterDef...
37.116279
0.001221
def append(self, future): """Append a future to the queue.""" if future._ended() and future.index is None: self.inprogress.add(future) elif future._ended() and future.index is not None: self.ready.append(future) elif future.greenlet is not None: self.i...
[ "def", "append", "(", "self", ",", "future", ")", ":", "if", "future", ".", "_ended", "(", ")", "and", "future", ".", "index", "is", "None", ":", "self", ".", "inprogress", ".", "add", "(", "future", ")", "elif", "future", ".", "_ended", "(", ")", ...
45.736842
0.002255
def from_json(cls, json): """Instantiates an instance of this InputReader for the given shard spec.""" return cls(json[cls.BLOB_KEY_PARAM], json[cls.INITIAL_POSITION_PARAM], json[cls.END_POSITION_PARAM])
[ "def", "from_json", "(", "cls", ",", "json", ")", ":", "return", "cls", "(", "json", "[", "cls", ".", "BLOB_KEY_PARAM", "]", ",", "json", "[", "cls", ".", "INITIAL_POSITION_PARAM", "]", ",", "json", "[", "cls", ".", "END_POSITION_PARAM", "]", ")" ]
47.4
0.008299
def validate_config(raise_=True): """ Verifies that all configuration values have a valid setting """ ELIBConfig.check() known_paths = set() duplicate_values = set() missing_values = set() for config_value in ConfigValue.config_values: if config_value.path not in known_paths: ...
[ "def", "validate_config", "(", "raise_", "=", "True", ")", ":", "ELIBConfig", ".", "check", "(", ")", "known_paths", "=", "set", "(", ")", "duplicate_values", "=", "set", "(", ")", "missing_values", "=", "set", "(", ")", "for", "config_value", "in", "Con...
34.304348
0.001233
def fit(self, X, y, likelihood_args=()): r""" Learn the parameters of a Bayesian generalized linear model (GLM). Parameters ---------- X : ndarray (N, d) array input dataset (N samples, d dimensions). y : ndarray (N,) array targets (N samples) ...
[ "def", "fit", "(", "self", ",", "X", ",", "y", ",", "likelihood_args", "=", "(", ")", ")", ":", "X", ",", "y", "=", "check_X_y", "(", "X", ",", "y", ")", "# Batch magnification factor", "N", ",", "_", "=", "X", ".", "shape", "self", ".", "B_", ...
33.6
0.00089
def set_canvas(self, canvas, private_canvas=None): """Set the canvas object. Parameters ---------- canvas : `~ginga.canvas.types.layer.DrawingCanvas` Canvas object. private_canvas : `~ginga.canvas.types.layer.DrawingCanvas` or `None` Private canvas objec...
[ "def", "set_canvas", "(", "self", ",", "canvas", ",", "private_canvas", "=", "None", ")", ":", "self", ".", "canvas", "=", "canvas", "canvas", ".", "initialize", "(", "None", ",", "self", ",", "self", ".", "logger", ")", "canvas", ".", "add_callback", ...
35.05
0.002082
def feedback_form(context): """Template tag to render a feedback form.""" user = None url = None if context.get('request'): url = context['request'].path if context['request'].user.is_authenticated(): user = context['request'].user return { 'form': FeedbackForm(ur...
[ "def", "feedback_form", "(", "context", ")", ":", "user", "=", "None", "url", "=", "None", "if", "context", ".", "get", "(", "'request'", ")", ":", "url", "=", "context", "[", "'request'", "]", ".", "path", "if", "context", "[", "'request'", "]", "."...
33.071429
0.002101
def count(self): "Return a count of rows this Query would return." return self.rpc_model.search_count( self.domain, context=self.context )
[ "def", "count", "(", "self", ")", ":", "return", "self", ".", "rpc_model", ".", "search_count", "(", "self", ".", "domain", ",", "context", "=", "self", ".", "context", ")" ]
34
0.011494
def retrieve_by_id(self, id_): """Return a JSSObject for the element with ID id_""" items_with_id = [item for item in self if item.id == int(id_)] if len(items_with_id) == 1: return items_with_id[0].retrieve()
[ "def", "retrieve_by_id", "(", "self", ",", "id_", ")", ":", "items_with_id", "=", "[", "item", "for", "item", "in", "self", "if", "item", ".", "id", "==", "int", "(", "id_", ")", "]", "if", "len", "(", "items_with_id", ")", "==", "1", ":", "return"...
48.2
0.008163