text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def scheduled_sample_count(ground_truth_x, generated_x, batch_size, scheduled_sample_var): """Sample batch with specified mix of groundtruth and generated data points. Args: ground_truth_x: tensor of ground-truth data points. ...
[ "def", "scheduled_sample_count", "(", "ground_truth_x", ",", "generated_x", ",", "batch_size", ",", "scheduled_sample_var", ")", ":", "num_ground_truth", "=", "scheduled_sample_var", "idx", "=", "tf", ".", "random_shuffle", "(", "tf", ".", "range", "(", "batch_size"...
41.655172
19.275862
def QA_util_send_mail(msg, title, from_user, from_password, to_addr, smtp): """邮件发送 Arguments: msg {[type]} -- [description] title {[type]} -- [description] from_user {[type]} -- [description] from_password {[type]} -- [description] to_addr {[type]} -- [description] ...
[ "def", "QA_util_send_mail", "(", "msg", ",", "title", ",", "from_user", ",", "from_password", ",", "to_addr", ",", "smtp", ")", ":", "msg", "=", "MIMEText", "(", "msg", ",", "'plain'", ",", "'utf-8'", ")", "msg", "[", "'Subject'", "]", "=", "Header", "...
33.105263
13.210526
def install_importer(): """ If in a virtualenv then load spec files to decide which modules can be imported from system site-packages and install path hook. """ logging.debug('install_importer') if not in_venv(): logging.debug('No virtualenv active py:[%s]', sys.executable) r...
[ "def", "install_importer", "(", ")", ":", "logging", ".", "debug", "(", "'install_importer'", ")", "if", "not", "in_venv", "(", ")", ":", "logging", ".", "debug", "(", "'No virtualenv active py:[%s]'", ",", "sys", ".", "executable", ")", "return", "False", "...
30.566667
17.1
def _rule_block(self): """ Parses the production rule:: block : NAME '{' option* '}' Returns tuple (name, options_list). """ name = self._get_token(self.RE_NAME) self._expect_token('{') # consume additional options if available options =...
[ "def", "_rule_block", "(", "self", ")", ":", "name", "=", "self", ".", "_get_token", "(", "self", ".", "RE_NAME", ")", "self", ".", "_expect_token", "(", "'{'", ")", "# consume additional options if available", "options", "=", "[", "]", "while", "self", ".",...
27.352941
15.411765
def to_grayscale(img, num_output_channels=1): """Convert image to grayscale version of image. Args: img (PIL Image): Image to be converted to grayscale. Returns: PIL Image: Grayscale version of the image. if num_output_channels = 1 : returned image is single channel ...
[ "def", "to_grayscale", "(", "img", ",", "num_output_channels", "=", "1", ")", ":", "if", "not", "_is_pil_image", "(", "img", ")", ":", "raise", "TypeError", "(", "'img should be PIL Image. Got {}'", ".", "format", "(", "type", "(", "img", ")", ")", ")", "i...
33
21.538462
def getargnames(argspecs, with_unbox=False): """Resembles list of arg-names as would be seen in a function signature, including var-args, var-keywords and keyword-only args. """ # todo: We can maybe make use of inspect.formatargspec args = argspecs.args vargs = argspecs.varargs try: ...
[ "def", "getargnames", "(", "argspecs", ",", "with_unbox", "=", "False", ")", ":", "# todo: We can maybe make use of inspect.formatargspec", "args", "=", "argspecs", ".", "args", "vargs", "=", "argspecs", ".", "varargs", "try", ":", "kw", "=", "argspecs", ".", "k...
30.16
14.68
def TriArea(v_init, f, normalize): """ Returns a Ch object whose only attribute "v" represents the flattened vertices.""" if normalize: nm = lambda x : NormalizedNx3(x) else: nm = lambda x : x result = Ch(lambda v : (Sum3xN(CrossProduct(TriEdges(f,1,0,nm(v)), TriEdges(f,2,0, nm(v)))...
[ "def", "TriArea", "(", "v_init", ",", "f", ",", "normalize", ")", ":", "if", "normalize", ":", "nm", "=", "lambda", "x", ":", "NormalizedNx3", "(", "x", ")", "else", ":", "nm", "=", "lambda", "x", ":", "x", "result", "=", "Ch", "(", "lambda", "v"...
37.1
22.7
def _build_tree_by_level(self, time_qualifier, collection_name, since): """ method iterated thru all documents in all job collections and builds a tree of known system state""" invalid_tree_records = dict() invalid_tq_records = dict() try: job_records = self.job_dao.get_all(...
[ "def", "_build_tree_by_level", "(", "self", ",", "time_qualifier", ",", "collection_name", ",", "since", ")", ":", "invalid_tree_records", "=", "dict", "(", ")", "invalid_tq_records", "=", "dict", "(", ")", "try", ":", "job_records", "=", "self", ".", "job_dao...
48.8
27.8
def build_arch(self, arch): """simple shared compile""" env = self.get_recipe_env(arch, with_flags_in_cc=False) for path in ( self.get_build_dir(arch.arch), join(self.ctx.python_recipe.get_build_dir(arch.arch), 'Lib'), join(self.ctx.python_recipe.g...
[ "def", "build_arch", "(", "self", ",", "arch", ")", ":", "env", "=", "self", ".", "get_recipe_env", "(", "arch", ",", "with_flags_in_cc", "=", "False", ")", "for", "path", "in", "(", "self", ".", "get_build_dir", "(", "arch", ".", "arch", ")", ",", "...
48.076923
16.961538
def calculate_marginal_likelihoods(tree, feature, frequencies): """ Calculates marginal likelihoods for each tree node by multiplying state frequencies with their bottom-up and top-down likelihoods. :param tree: ete3.Tree, the tree of interest :param feature: str, character for which the likelihood...
[ "def", "calculate_marginal_likelihoods", "(", "tree", ",", "feature", ",", "frequencies", ")", ":", "bu_lh_feature", "=", "get_personalized_feature_name", "(", "feature", ",", "BU_LH", ")", "bu_lh_sf_feature", "=", "get_personalized_feature_name", "(", "feature", ",", ...
53.428571
24.5
def get_command(arguments): """Extract the first argument from arguments parsed by docopt. :param arguments parsed by docopt: :return: command """ return [k for k, v in arguments.items() if not k.startswith('-') and v is True][0]
[ "def", "get_command", "(", "arguments", ")", ":", "return", "[", "k", "for", "k", ",", "v", "in", "arguments", ".", "items", "(", ")", "if", "not", "k", ".", "startswith", "(", "'-'", ")", "and", "v", "is", "True", "]", "[", "0", "]" ]
31.875
11.5
def _protobuf_value_type(value): """Returns the type of the google.protobuf.Value message as an api.DataType. Returns None if the type of 'value' is not one of the types supported in api_pb2.DataType. Args: value: google.protobuf.Value message. """ if value.HasField("number_value"): return api_pb2...
[ "def", "_protobuf_value_type", "(", "value", ")", ":", "if", "value", ".", "HasField", "(", "\"number_value\"", ")", ":", "return", "api_pb2", ".", "DATA_TYPE_FLOAT64", "if", "value", ".", "HasField", "(", "\"string_value\"", ")", ":", "return", "api_pb2", "."...
29.9375
14.625
def create_from_template(self, client_id, subject, name, from_name, from_email, reply_to, list_ids, segment_ids, template_id, template_content): """Creates a new campaign for a client, from a template. :param client_id: String representing the ID of the client for whom the ...
[ "def", "create_from_template", "(", "self", ",", "client_id", ",", "subject", ",", "name", ",", "from_name", ",", "from_email", ",", "reply_to", ",", "list_ids", ",", "segment_ids", ",", "template_id", ",", "template_content", ")", ":", "body", "=", "{", "\"...
53.567568
21
def getViews(self, path, year=None, month=None, day=None, hour=None): """Use this method to get the number of views for a Telegraph article. :param path: Required. Path to the Telegraph page (in the format Title-12-31, where 12 is the month and 31 the day the article was first published). ...
[ "def", "getViews", "(", "self", ",", "path", ",", "year", "=", "None", ",", "month", "=", "None", ",", "day", "=", "None", ",", "hour", "=", "None", ")", ":", "if", "path", "is", "None", ":", "raise", "TelegraphAPIException", "(", "\"Error while execut...
40.918919
24.675676
def node_label_folder_absent(name, node, **kwargs): ''' Ensures the label folder doesn't exist on the specified node. name The name of label folder node The name of the node ''' ret = {'name': name, 'changes': {}, 'result': False, 'comment': ''...
[ "def", "node_label_folder_absent", "(", "name", ",", "node", ",", "*", "*", "kwargs", ")", ":", "ret", "=", "{", "'name'", ":", "name", ",", "'changes'", ":", "{", "}", ",", "'result'", ":", "False", ",", "'comment'", ":", "''", "}", "labels", "=", ...
24.807692
21.153846
def _get_doc_by_raw_offset(self, doc_id): """ Load document from xml using bytes offset information. XXX: this is not tested under Windows. """ bounds = self._get_meta()[str(doc_id)].bounds return xml_utils.load_chunk(self.filename, bounds)
[ "def", "_get_doc_by_raw_offset", "(", "self", ",", "doc_id", ")", ":", "bounds", "=", "self", ".", "_get_meta", "(", ")", "[", "str", "(", "doc_id", ")", "]", ".", "bounds", "return", "xml_utils", ".", "load_chunk", "(", "self", ".", "filename", ",", "...
40.285714
8.571429
def _get_site_amplification(self, C_AMP, vs30, pga_rock): """ Gets the site amplification term based on equations 7 and 8 of Atkinson & Boore (2006) """ # Get nonlinear term bnl = self._get_bnl(C_AMP, vs30) # f_nl_coeff = np.log(60.0 / 100.0) * np.ones_lik...
[ "def", "_get_site_amplification", "(", "self", ",", "C_AMP", ",", "vs30", ",", "pga_rock", ")", ":", "# Get nonlinear term", "bnl", "=", "self", ".", "_get_bnl", "(", "C_AMP", ",", "vs30", ")", "#", "f_nl_coeff", "=", "np", ".", "log", "(", "60.0", "/", ...
37.571429
13.714286
def __load_asset_class(self, ac_id: int): """ Loads Asset Class entity """ # open database db = self.__get_session() entity = db.query(dal.AssetClass).filter(dal.AssetClass.id == ac_id).first() return entity
[ "def", "__load_asset_class", "(", "self", ",", "ac_id", ":", "int", ")", ":", "# open database", "db", "=", "self", ".", "__get_session", "(", ")", "entity", "=", "db", ".", "query", "(", "dal", ".", "AssetClass", ")", ".", "filter", "(", "dal", ".", ...
40.333333
14.666667
def _read_routine_metadata(self): """ Returns the metadata of stored routines. :rtype: dict """ metadata = {} if os.path.isfile(self._metadata_filename): with open(self._metadata_filename, 'r') as file: metadata = json.load(file) retu...
[ "def", "_read_routine_metadata", "(", "self", ")", ":", "metadata", "=", "{", "}", "if", "os", ".", "path", ".", "isfile", "(", "self", ".", "_metadata_filename", ")", ":", "with", "open", "(", "self", ".", "_metadata_filename", ",", "'r'", ")", "as", ...
26.666667
15.333333
def get_sized_root_folder(self): """Return the location where sized images are stored.""" folder, filename = os.path.split(self.name) return os.path.join(VERSATILEIMAGEFIELD_SIZED_DIRNAME, folder, '')
[ "def", "get_sized_root_folder", "(", "self", ")", ":", "folder", ",", "filename", "=", "os", ".", "path", ".", "split", "(", "self", ".", "name", ")", "return", "os", ".", "path", ".", "join", "(", "VERSATILEIMAGEFIELD_SIZED_DIRNAME", ",", "folder", ",", ...
55.25
13.25
def setAttribute(values, value): """ Takes the values of an attribute value list and attempts to append attributes of the proper type, inferred from their Python type. """ if isinstance(value, int): values.add().int32_value = value elif isinstance(value, float): values.add().doub...
[ "def", "setAttribute", "(", "values", ",", "value", ")", ":", "if", "isinstance", "(", "value", ",", "int", ")", ":", "values", ".", "add", "(", ")", ".", "int32_value", "=", "value", "elif", "isinstance", "(", "value", ",", "float", ")", ":", "value...
36.083333
10.25
def create_and_start_migration( self, resource_group_name, namespace_name, target_namespace, post_migration_name, custom_headers=None, raw=False, polling=True, **operation_config): """Creates Migration configuration and starts migration of entities from Standard to Premium namespace. ...
[ "def", "create_and_start_migration", "(", "self", ",", "resource_group_name", ",", "namespace_name", ",", "target_namespace", ",", "post_migration_name", ",", "custom_headers", "=", "None", ",", "raw", "=", "False", ",", "polling", "=", "True", ",", "*", "*", "o...
49.105263
24.140351
def _aix_loadavg(): ''' Return the load average on AIX ''' # 03:42PM up 9 days, 20:41, 2 users, load average: 0.28, 0.47, 0.69 uptime = __salt__['cmd.run']('uptime') ldavg = uptime.split('load average') load_avg = ldavg[1].split() return {'1-min': load_avg[1].strip(','), ...
[ "def", "_aix_loadavg", "(", ")", ":", "# 03:42PM up 9 days, 20:41, 2 users, load average: 0.28, 0.47, 0.69", "uptime", "=", "__salt__", "[", "'cmd.run'", "]", "(", "'uptime'", ")", "ldavg", "=", "uptime", ".", "split", "(", "'load average'", ")", "load_avg", "="...
34.454545
14.090909
def _handle_list_marker(self): """Handle a list marker at the head (``#``, ``*``, ``;``, ``:``).""" markup = self._read() if markup == ";": self._context |= contexts.DL_TERM self._emit(tokens.TagOpenOpen(wiki_markup=markup)) self._emit_text(get_html_tag(markup)) ...
[ "def", "_handle_list_marker", "(", "self", ")", ":", "markup", "=", "self", ".", "_read", "(", ")", "if", "markup", "==", "\";\"", ":", "self", ".", "_context", "|=", "contexts", ".", "DL_TERM", "self", ".", "_emit", "(", "tokens", ".", "TagOpenOpen", ...
44.25
8.75
def nextCmd(snmpEngine, authData, transportTarget, contextData, *varBinds, **options): """Creates a generator to perform one or more SNMP GETNEXT queries. On each iteration, new SNMP GETNEXT request is send (:RFC:`1905#section-4.2.2`). The iterator blocks waiting for response to arrive or e...
[ "def", "nextCmd", "(", "snmpEngine", ",", "authData", ",", "transportTarget", ",", "contextData", ",", "*", "varBinds", ",", "*", "*", "options", ")", ":", "# noinspection PyShadowingNames", "def", "cbFun", "(", "snmpEngine", ",", "sendRequestHandle", ",", "erro...
39.081081
25.513514
def check_arguments(self): """Sanity check the arguments passed in. Uses the boolean functions specified in the subclasses in the _valid_arguments dictionary to determine if an argument is valid or invalid. """ for k, v in self.Parameters.iteritems(): if self...
[ "def", "check_arguments", "(", "self", ")", ":", "for", "k", ",", "v", "in", "self", ".", "Parameters", ".", "iteritems", "(", ")", ":", "if", "self", ".", "Parameters", "[", "k", "]", ".", "isOn", "(", ")", ":", "if", "k", "in", "self", ".", "...
46.857143
19.071429
def retrieve_connection(self, session=None): """ Retrieves the dynamically created connection from the Connection table. :param session: Session of the SQL Alchemy ORM (automatically generated with decorator). """ self.log.info("Retrieving connection %s",...
[ "def", "retrieve_connection", "(", "self", ",", "session", "=", "None", ")", ":", "self", ".", "log", ".", "info", "(", "\"Retrieving connection %s\"", ",", "self", ".", "db_conn_id", ")", "connections", "=", "session", ".", "query", "(", "Connection", ")", ...
39.846154
16.923077
def get_default_config(self): """ Returns default configuration options. """ config = super(SmartCollector, self).get_default_config() config.update({ 'path': 'smart', 'bin': 'smartctl', 'use_sudo': False, 'sudo_cmd': ...
[ "def", "get_default_config", "(", "self", ")", ":", "config", "=", "super", "(", "SmartCollector", ",", "self", ")", ".", "get_default_config", "(", ")", "config", ".", "update", "(", "{", "'path'", ":", "'smart'", ",", "'bin'", ":", "'smartctl'", ",", "...
32.076923
12.076923
def on_success(self, retval, task_id, args, kwargs): """on_success http://docs.celeryproject.org/en/latest/reference/celery.app.task.html :param retval: return value :param task_id: celery task id :param args: arguments passed into task :param kwargs: keyword arguments ...
[ "def", "on_success", "(", "self", ",", "retval", ",", "task_id", ",", "args", ",", "kwargs", ")", ":", "log", ".", "info", "(", "(", "\"{} SUCCESS - retval={} task_id={} \"", "\"args={} kwargs={}\"", ")", ".", "format", "(", "self", ".", "log_label", ",", "r...
31.789474
14.947368
def new(self, lits=[], ubound=1, top_id=None): """ The actual constructor of :class:`ITotalizer`. Invoked from ``self.__init__()``. Creates an object of :class:`ITotalizer` given a list of literals in the sum, the largest potential bound to consider, as well as th...
[ "def", "new", "(", "self", ",", "lits", "=", "[", "]", ",", "ubound", "=", "1", ",", "top_id", "=", "None", ")", ":", "self", ".", "lits", "=", "list", "(", "lits", ")", "self", ".", "ubound", "=", "ubound", "self", ".", "top_id", "=", "max", ...
39.62069
22.655172
def write_membership(filename,config,srcfile,section=None): """ Top level interface to write the membership from a config and source model. """ source = Source() source.load(srcfile,section=section) loglike = createLoglike(config,source) loglike.write_membership(filename)
[ "def", "write_membership", "(", "filename", ",", "config", ",", "srcfile", ",", "section", "=", "None", ")", ":", "source", "=", "Source", "(", ")", "source", ".", "load", "(", "srcfile", ",", "section", "=", "section", ")", "loglike", "=", "createLoglik...
36.625
10.125
def stonith_create(stonith_id, stonith_device_type, stonith_device_options=None, cibfile=None): ''' Create a stonith resource via pcs command stonith_id name for the stonith resource stonith_device_type name of the stonith agent fence_eps, fence_xvm f.e. stonith_device_options ...
[ "def", "stonith_create", "(", "stonith_id", ",", "stonith_device_type", ",", "stonith_device_options", "=", "None", ",", "cibfile", "=", "None", ")", ":", "return", "item_create", "(", "item", "=", "'stonith'", ",", "item_id", "=", "stonith_id", ",", "item_type"...
44.44
33.08
def lock(self, request, *args, **kwargs): """ Locks the considered topic and retirects the user to the success URL. """ self.object = self.get_object() success_url = self.get_success_url() self.object.status = Topic.TOPIC_LOCKED self.object.save() messages.success(self.re...
[ "def", "lock", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "object", "=", "self", ".", "get_object", "(", ")", "success_url", "=", "self", ".", "get_success_url", "(", ")", "self", ".", "object", "...
48.75
6.875
def hidden_tags(self): """ Returns a list of tags to be hidden from the 'ls' output. """ hidden_tags = self.cp.get('ls', 'hide_tags') # pylint: disable=no-member return [] if hidden_tags == '' else [tag.strip() for tag in hidden_tags.split(','...
[ "def", "hidden_tags", "(", "self", ")", ":", "hidden_tags", "=", "self", ".", "cp", ".", "get", "(", "'ls'", ",", "'hide_tags'", ")", "# pylint: disable=no-member", "return", "[", "]", "if", "hidden_tags", "==", "''", "else", "[", "tag", ".", "strip", "(...
52.833333
15
def get_anchor_labels(anchors, gt_boxes, crowd_boxes): """ Label each anchor as fg/bg/ignore. Args: anchors: Ax4 float gt_boxes: Bx4 float, non-crowd crowd_boxes: Cx4 float Returns: anchor_labels: (A,) int. Each element is {-1, 0, 1} anchor_boxes: Ax4. Contains t...
[ "def", "get_anchor_labels", "(", "anchors", ",", "gt_boxes", ",", "crowd_boxes", ")", ":", "# This function will modify labels and return the filtered inds", "def", "filter_box_label", "(", "labels", ",", "value", ",", "max_num", ")", ":", "curr_inds", "=", "np", ".",...
44.594203
19.521739
def create(configs): """Creates AndroidDevice controller objects. Args: configs: A list of dicts, each representing a configuration for an Android device. Returns: A list of AndroidDevice objects. """ if not configs: raise Error(ANDROID_DEVICE_EMPTY_CONFIG_MSG) ...
[ "def", "create", "(", "configs", ")", ":", "if", "not", "configs", ":", "raise", "Error", "(", "ANDROID_DEVICE_EMPTY_CONFIG_MSG", ")", "elif", "configs", "==", "ANDROID_DEVICE_PICK_ALL_TOKEN", ":", "ads", "=", "get_all_instances", "(", ")", "elif", "not", "isins...
35.4375
17.34375
def run_job(job_ini, log_level='info', log_file=None, exports='', username=getpass.getuser(), **kw): """ Run a job using the specified config file and other options. :param str job_ini: Path to calculation config (INI-style) files. :param str log_level: 'debug', 'info', 'war...
[ "def", "run_job", "(", "job_ini", ",", "log_level", "=", "'info'", ",", "log_file", "=", "None", ",", "exports", "=", "''", ",", "username", "=", "getpass", ".", "getuser", "(", ")", ",", "*", "*", "kw", ")", ":", "job_id", "=", "logs", ".", "init"...
38.777778
17
def lock(self): """Returns a JSON representation of the Pipfile.""" data = self.data data['_meta']['hash'] = {"sha256": self.hash} data['_meta']['pipfile-spec'] = 6 return json.dumps(data, indent=4, separators=(',', ': '))
[ "def", "lock", "(", "self", ")", ":", "data", "=", "self", ".", "data", "data", "[", "'_meta'", "]", "[", "'hash'", "]", "=", "{", "\"sha256\"", ":", "self", ".", "hash", "}", "data", "[", "'_meta'", "]", "[", "'pipfile-spec'", "]", "=", "6", "re...
42.833333
13.333333
def check_message(message, **kwargs): """Check the message format. Rules: - the first line must start by a component name - and a short description (52 chars), - then bullet points are expected - and finally signatures. :param components: compontents, e.g. ``('auth', 'utils', 'misc')`` ...
[ "def", "check_message", "(", "message", ",", "*", "*", "kwargs", ")", ":", "if", "kwargs", ".", "pop", "(", "\"allow_empty\"", ",", "False", ")", ":", "if", "not", "message", "or", "message", ".", "isspace", "(", ")", ":", "return", "[", "]", "lines"...
37.681818
18.659091
def _format(self, format): """ Performs strftime(), always returning a unicode string :param format: A strftime() format string :return: A unicode string of the formatted datetime """ format = format.replace('%Y', '0000') # Year 0 is 1BC...
[ "def", "_format", "(", "self", ",", "format", ")", ":", "format", "=", "format", ".", "replace", "(", "'%Y'", ",", "'0000'", ")", "# Year 0 is 1BC and a leap year. Leap years repeat themselves", "# every 28 years. Because of adjustments and the proleptic gregorian", "# calend...
33.157895
16
def _storage_get_key_names(bucket, pattern): """ Get names of all storage keys in a specified bucket that match a pattern. """ return [item.metadata.name for item in _storage_get_keys(bucket, pattern)]
[ "def", "_storage_get_key_names", "(", "bucket", ",", "pattern", ")", ":", "return", "[", "item", ".", "metadata", ".", "name", "for", "item", "in", "_storage_get_keys", "(", "bucket", ",", "pattern", ")", "]" ]
67.666667
13.333333
def killProcess(self, pid): """ Kills the process with the specified PID (if possible) """ SYNCHRONIZE = 0x00100000 PROCESS_TERMINATE = 0x0001 hProcess = self._kernel32.OpenProcess(SYNCHRONIZE|PROCESS_TERMINATE, True, pid) result = self._kernel32.TerminateProcess(hProcess, 0) ...
[ "def", "killProcess", "(", "self", ",", "pid", ")", ":", "SYNCHRONIZE", "=", "0x00100000", "PROCESS_TERMINATE", "=", "0x0001", "hProcess", "=", "self", ".", "_kernel32", ".", "OpenProcess", "(", "SYNCHRONIZE", "|", "PROCESS_TERMINATE", ",", "True", ",", "pid",...
50.714286
14.142857
def allocate_map_coloring(self, tolerance, threshold_steps = 10): """! @brief Returns list of color indexes that are assigned to each object from input data space accordingly. @param[in] tolerance (double): Tolerance level that define maximal difference between outputs of oscillators in...
[ "def", "allocate_map_coloring", "(", "self", ",", "tolerance", ",", "threshold_steps", "=", "10", ")", ":", "clusters", "=", "self", ".", "allocate_clusters", "(", "tolerance", ",", "threshold_steps", ")", "coloring_map", "=", "[", "0", "]", "*", "len", "(",...
50.48
34.28
def photo(self, args): """ Retrieves metadata for a specific photo. flickr:(credsfile),photo,(photo_id) """ rsp = self._load_rsp(self.flickr.photos_getInfo(photo_id=args[0])) p = rsp['photo'] yield self._prep(p)
[ "def", "photo", "(", "self", ",", "args", ")", ":", "rsp", "=", "self", ".", "_load_rsp", "(", "self", ".", "flickr", ".", "photos_getInfo", "(", "photo_id", "=", "args", "[", "0", "]", ")", ")", "p", "=", "rsp", "[", "'photo'", "]", "yield", "se...
28.888889
14.666667
def get_callee_address( global_state: GlobalState, dynamic_loader: DynLoader, symbolic_to_address: Expression, ): """Gets the address of the callee. :param global_state: state to look in :param dynamic_loader: dynamic loader to use :param symbolic_to_address: The (symbolic) callee address ...
[ "def", "get_callee_address", "(", "global_state", ":", "GlobalState", ",", "dynamic_loader", ":", "DynLoader", ",", "symbolic_to_address", ":", "Expression", ",", ")", ":", "environment", "=", "global_state", ".", "environment", "try", ":", "callee_address", "=", ...
33.906977
21.604651
def version(bin_env=None): ''' .. versionadded:: 0.17.0 Returns the version of pip. Use ``bin_env`` to specify the path to a virtualenv and get the version of pip in that virtualenv. If unable to detect the pip version, returns ``None``. CLI Example: .. code-block:: bash salt '*...
[ "def", "version", "(", "bin_env", "=", "None", ")", ":", "contextkey", "=", "'pip.version'", "if", "bin_env", "is", "not", "None", ":", "contextkey", "=", "'{0}.{1}'", ".", "format", "(", "contextkey", ",", "bin_env", ")", "if", "contextkey", "in", "__cont...
25.361111
23.75
def _add_partition(self, connection, partition): """ Creates FDW for the partition. Args: connection: partition (orm.Partition): """ logger.debug('Creating foreign table for partition.\n partition: {}'.format(partition.name)) with connection.cursor() ...
[ "def", "_add_partition", "(", "self", ",", "connection", ",", "partition", ")", ":", "logger", ".", "debug", "(", "'Creating foreign table for partition.\\n partition: {}'", ".", "format", "(", "partition", ".", "name", ")", ")", "with", "connection", ".", "cur...
36.545455
21.909091
def spot_from_dummy(self, dummy): """Make a real place and its spot from a dummy spot. Create a new :class:`board.Spot` instance, along with the underlying :class:`LiSE.Place` instance, and give it the name, position, and imagery of the provided dummy. """ (x, y) = self...
[ "def", "spot_from_dummy", "(", "self", ",", "dummy", ")", ":", "(", "x", ",", "y", ")", "=", "self", ".", "to_local", "(", "*", "dummy", ".", "pos_up", ")", "x", "/=", "self", ".", "board", ".", "width", "y", "/=", "self", ".", "board", ".", "h...
32.181818
15.590909
def _valid_table_name(self, table_name): """Check if the table name is obviously invalid. """ if table_name is None or not len(table_name.strip()): raise ValueError("Invalid table name: %r" % table_name) return table_name.strip()
[ "def", "_valid_table_name", "(", "self", ",", "table_name", ")", ":", "if", "table_name", "is", "None", "or", "not", "len", "(", "table_name", ".", "strip", "(", ")", ")", ":", "raise", "ValueError", "(", "\"Invalid table name: %r\"", "%", "table_name", ")",...
44.666667
9.166667
def get_playlist_songs(self, playlist_id, limit=1000): """Get a playlists's all songs. :params playlist_id: playlist id. :params limit: length of result returned by weapi. :return: a list of Song object. """ url = 'http://music.163.com/weapi/v3/playlist/detail?csrf_toke...
[ "def", "get_playlist_songs", "(", "self", ",", "playlist_id", ",", "limit", "=", "1000", ")", ":", "url", "=", "'http://music.163.com/weapi/v3/playlist/detail?csrf_token='", "csrf", "=", "''", "params", "=", "{", "'id'", ":", "playlist_id", ",", "'offset'", ":", ...
37.470588
18.529412
def collect_by_typename(obj_sequence, cache=None): """ collects objects from obj_sequence and stores them into buckets by type name. cache is an optional dict into which we collect the results. """ if cache is None: cache = {} for val in obj_sequence: key = type(val).__name...
[ "def", "collect_by_typename", "(", "obj_sequence", ",", "cache", "=", "None", ")", ":", "if", "cache", "is", "None", ":", "cache", "=", "{", "}", "for", "val", "in", "obj_sequence", ":", "key", "=", "type", "(", "val", ")", ".", "__name__", "bucket", ...
23.35
19.95
def SNR_hinken(imgs, bg=0, roi=None): ''' signal-to-noise ratio (SNR) as mean(images) / std(images) as defined in Hinken et.al. 2011 (DOI: 10.1063/1.3541766) works on unloaded images no memory overload if too many images are given ''' mean = None M = len(imgs) if bg is...
[ "def", "SNR_hinken", "(", "imgs", ",", "bg", "=", "0", ",", "roi", "=", "None", ")", ":", "mean", "=", "None", "M", "=", "len", "(", "imgs", ")", "if", "bg", "is", "not", "0", ":", "bg", "=", "imread", "(", "bg", ")", "[", "roi", "]", "if",...
26.162162
16.864865
def connect(servers=None, framed_transport=False, timeout=None, retry_time=60, recycle=None, round_robin=None, max_retries=3): """ Constructs a single ElasticSearch connection. Connects to a randomly chosen server on the list. If the connection fails, it will attempt to connect to each serv...
[ "def", "connect", "(", "servers", "=", "None", ",", "framed_transport", "=", "False", ",", "timeout", "=", "None", ",", "retry_time", "=", "60", ",", "recycle", "=", "None", ",", "round_robin", "=", "None", ",", "max_retries", "=", "3", ")", ":", "if",...
38.948718
27.051282
def _shallow_copy_with_infer(self, values, **kwargs): """ Create a new Index inferring the class with passed value, don't copy the data, use the same object attributes with passed in attributes taking precedence. *this is an internal non-public method* Parameters ...
[ "def", "_shallow_copy_with_infer", "(", "self", ",", "values", ",", "*", "*", "kwargs", ")", ":", "attributes", "=", "self", ".", "_get_attributes_dict", "(", ")", "attributes", ".", "update", "(", "kwargs", ")", "attributes", "[", "'copy'", "]", "=", "Fal...
36.916667
16.083333
def size(ctx, dataset, kwargs): "Show dataset size" kwargs = parse_kwargs(kwargs) (print)(data(dataset, **ctx.obj).get(**kwargs).complete_set.size)
[ "def", "size", "(", "ctx", ",", "dataset", ",", "kwargs", ")", ":", "kwargs", "=", "parse_kwargs", "(", "kwargs", ")", "(", "print", ")", "(", "data", "(", "dataset", ",", "*", "*", "ctx", ".", "obj", ")", ".", "get", "(", "*", "*", "kwargs", "...
31.2
20.4
def _complete(self): """ Performs completion at the current cursor location. """ context = self._get_context() if context: # Send the completion request to the kernel msg_id = self.kernel_manager.shell_channel.complete( '.'.join(context), ...
[ "def", "_complete", "(", "self", ")", ":", "context", "=", "self", ".", "_get_context", "(", ")", "if", "context", ":", "# Send the completion request to the kernel", "msg_id", "=", "self", ".", "kernel_manager", ".", "shell_channel", ".", "complete", "(", "'.'"...
48.5
15.214286
def run(data): """Proxy function to run the tool""" sample = data[0][0] work_dir = dd.get_work_dir(sample) out_dir = os.path.join(work_dir, "mirge") lib = _find_lib(sample) mirge = _find_mirge(sample) bowtie = _find_bowtie(sample) sps = dd.get_species(sample) species = SPS.get(sps, "...
[ "def", "run", "(", "data", ")", ":", "sample", "=", "data", "[", "0", "]", "[", "0", "]", "work_dir", "=", "dd", ".", "get_work_dir", "(", "sample", ")", "out_dir", "=", "os", ".", "path", ".", "join", "(", "work_dir", ",", "\"mirge\"", ")", "lib...
40.863636
17.590909
def init_bn_weight(layer): '''initilize batch norm layer weight. ''' n_filters = layer.num_features new_weights = [ add_noise(np.ones(n_filters, dtype=np.float32), np.array([0, 1])), add_noise(np.zeros(n_filters, dtype=np.float32), np.array([0, 1])), add_noise(np.zeros(n_filters,...
[ "def", "init_bn_weight", "(", "layer", ")", ":", "n_filters", "=", "layer", ".", "num_features", "new_weights", "=", "[", "add_noise", "(", "np", ".", "ones", "(", "n_filters", ",", "dtype", "=", "np", ".", "float32", ")", ",", "np", ".", "array", "(",...
42.181818
23.090909
def service_info(self, short_name): """Get static information about a service. Args: short_name (string): The short name of the service to query Returns: dict: A dictionary with the long_name and preregistered info on this service. """ i...
[ "def", "service_info", "(", "self", ",", "short_name", ")", ":", "if", "short_name", "not", "in", "self", ".", "services", ":", "raise", "ArgumentError", "(", "\"Unknown service name\"", ",", "short_name", "=", "short_name", ")", "info", "=", "{", "}", "info...
32.4
24.25
def _enqueue_capture(build, release, run, url, config_data, baseline=False): """Enqueues a task to run a capture process.""" # Validate the JSON config parses. try: config_dict = json.loads(config_data) except Exception, e: abort(utils.jsonify_error(e)) # Rewrite the config JSON to ...
[ "def", "_enqueue_capture", "(", "build", ",", "release", ",", "run", ",", "url", ",", "config_data", ",", "baseline", "=", "False", ")", ":", "# Validate the JSON config parses.", "try", ":", "config_dict", "=", "json", ".", "loads", "(", "config_data", ")", ...
32
19
def MultimodeCombine(pupils): """ Return the instantaneous coherent fluxes and photometric fluxes for a multiway multimode combiner (no spatial filtering) """ fluxes=[np.vdot(pupils[i],pupils[i]).real for i in range(len(pupils))] coherentFluxes=[np.vdot(pupils[i],pupils[j]) f...
[ "def", "MultimodeCombine", "(", "pupils", ")", ":", "fluxes", "=", "[", "np", ".", "vdot", "(", "pupils", "[", "i", "]", ",", "pupils", "[", "i", "]", ")", ".", "real", "for", "i", "in", "range", "(", "len", "(", "pupils", ")", ")", "]", "coher...
41.1
11.9
def delete_token(): ''' Delete current token, file & CouchDB admin user ''' username = get_admin()[0] admins = get_couchdb_admins() # Delete current admin if exist if username in admins: print 'I delete {} CouchDB user'.format(username) delete_couchdb_admin(username) ...
[ "def", "delete_token", "(", ")", ":", "username", "=", "get_admin", "(", ")", "[", "0", "]", "admins", "=", "get_couchdb_admins", "(", ")", "# Delete current admin if exist", "if", "username", "in", "admins", ":", "print", "'I delete {} CouchDB user'", ".", "for...
29.375
17.25
def generate(env): """Add Builders and construction variables for cyglink to an Environment.""" gnulink.generate(env) env['LINKFLAGS'] = SCons.Util.CLVar('-Wl,-no-undefined') env['SHLINKCOM'] = shlib_action env['LDMODULECOM'] = ldmod_action env.Append(SHLIBEMITTER = [shlib_emitter]) env....
[ "def", "generate", "(", "env", ")", ":", "gnulink", ".", "generate", "(", "env", ")", "env", "[", "'LINKFLAGS'", "]", "=", "SCons", ".", "Util", ".", "CLVar", "(", "'-Wl,-no-undefined'", ")", "env", "[", "'SHLINKCOM'", "]", "=", "shlib_action", "env", ...
43.121951
24.585366
def indication(self, pdu): """Client requests are queued for delivery.""" if _debug: UDPDirector._debug("indication %r", pdu) # get the destination addr = pdu.pduDestination # get the peer peer = self.peers.get(addr, None) if not peer: peer = self.ac...
[ "def", "indication", "(", "self", ",", "pdu", ")", ":", "if", "_debug", ":", "UDPDirector", ".", "_debug", "(", "\"indication %r\"", ",", "pdu", ")", "# get the destination", "addr", "=", "pdu", ".", "pduDestination", "# get the peer", "peer", "=", "self", "...
27.428571
17.285714
def elixir_decode(elixir_filename): """ Takes an elixir style file name and decodes it's content. Values returned as a dictionary. Elixir filenames have the format RUNID.TYPE.FILTER/EXPTIME.CHIPID.VERSION.fits """ import re, pyfits parts_RE=re.compile(r'([^\.\s]+)') dataset_name =...
[ "def", "elixir_decode", "(", "elixir_filename", ")", ":", "import", "re", ",", "pyfits", "parts_RE", "=", "re", ".", "compile", "(", "r'([^\\.\\s]+)'", ")", "dataset_name", "=", "parts_RE", ".", "findall", "(", "elixir_filename", ")", "### check that this was a va...
33.319149
17.191489
def lines_from_tree(tree, nodes_and_set:bool=False) -> iter: """Yield lines of bubble describing given BubbleTree""" NODE = 'NODE\t{}' INCL = 'IN\t{}\t{}' EDGE = 'EDGE\t{}\t{}\t1.0' SET = 'SET\t{}' if nodes_and_set: for node in tree.nodes(): yield NODE.format(node) ...
[ "def", "lines_from_tree", "(", "tree", ",", "nodes_and_set", ":", "bool", "=", "False", ")", "->", "iter", ":", "NODE", "=", "'NODE\\t{}'", "INCL", "=", "'IN\\t{}\\t{}'", "EDGE", "=", "'EDGE\\t{}\\t{}\\t1.0'", "SET", "=", "'SET\\t{}'", "if", "nodes_and_set", "...
29.190476
15.428571
def get_pages(url): """ Return the 'pages' from the starting url Technically, look for the 'next 50' link, yield and download it, repeat """ while True: yield url doc = html.parse(url).find("body") links = [a for a in doc.findall(".//a") if a.text and a.text.startswith("next...
[ "def", "get_pages", "(", "url", ")", ":", "while", "True", ":", "yield", "url", "doc", "=", "html", ".", "parse", "(", "url", ")", ".", "find", "(", "\"body\"", ")", "links", "=", "[", "a", "for", "a", "in", "doc", ".", "findall", "(", "\".//a\""...
33.5
17.5
def get_safe_redirect_target(arg='next'): """Get URL to redirect to and ensure that it is local.""" for target in request.args.get(arg), request.referrer: if not target: continue if is_local_url(target): return target return None
[ "def", "get_safe_redirect_target", "(", "arg", "=", "'next'", ")", ":", "for", "target", "in", "request", ".", "args", ".", "get", "(", "arg", ")", ",", "request", ".", "referrer", ":", "if", "not", "target", ":", "continue", "if", "is_local_url", "(", ...
34.25
13.125
def site_symbols(self): """ Sequence of symbols associated with the Xdatcar. Similar to 6th line in vasp 5+ Xdatcar. """ syms = [site.specie.symbol for site in self.structures[0]] return [a[0] for a in itertools.groupby(syms)]
[ "def", "site_symbols", "(", "self", ")", ":", "syms", "=", "[", "site", ".", "specie", ".", "symbol", "for", "site", "in", "self", ".", "structures", "[", "0", "]", "]", "return", "[", "a", "[", "0", "]", "for", "a", "in", "itertools", ".", "grou...
38.285714
16
def set_attribute(self, name, value): """ Default handler for those not explicitly defined """ if value is True: self.widget.set(name, name) elif value is False: del self.widget.attrib[name] else: self.widget.set(name, str(value))
[ "def", "set_attribute", "(", "self", ",", "name", ",", "value", ")", ":", "if", "value", "is", "True", ":", "self", ".", "widget", ".", "set", "(", "name", ",", "name", ")", "elif", "value", "is", "False", ":", "del", "self", ".", "widget", ".", ...
36.375
7.875
def get_default_configs(self): """ returns default configs list, from /etc, home dir and package_data""" # initialize basic defaults configs = [resource_filename(__name__, 'config/00-base.ini')] try: conf_files = sorted(os.listdir(self.baseconfigs_location)) for f...
[ "def", "get_default_configs", "(", "self", ")", ":", "# initialize basic defaults", "configs", "=", "[", "resource_filename", "(", "__name__", ",", "'config/00-base.ini'", ")", "]", "try", ":", "conf_files", "=", "sorted", "(", "os", ".", "listdir", "(", "self",...
42.833333
18.333333
def load(self, service_name, api_version=None, cached=True): """ Loads the desired JSON for a service. (uncached) This will fall back through all the ``data_dirs`` provided to the constructor, returning the **first** one it finds. :param service_name: The name of the desired se...
[ "def", "load", "(", "self", ",", "service_name", ",", "api_version", "=", "None", ",", "cached", "=", "True", ")", ":", "# Fetch from the cache first if it's there.", "if", "cached", ":", "if", "service_name", "in", "self", ".", "_loaded_data", ":", "if", "api...
34.659091
20.840909
def state(self): """Compute and return the device state. :returns: Device state. """ # Check if device is disconnected. if not self.available: return STATE_UNKNOWN # Check if device is off. if not self.screen_on: return STATE_OFF #...
[ "def", "state", "(", "self", ")", ":", "# Check if device is disconnected.", "if", "not", "self", ".", "available", ":", "return", "STATE_UNKNOWN", "# Check if device is off.", "if", "not", "self", ".", "screen_on", ":", "return", "STATE_OFF", "# Check if screen saver...
31.090909
9.545455
def forward_committor(T, A, B): r"""Forward committor between given sets. The forward committor u(x) between sets A and B is the probability for the chain starting in x to reach B before reaching A. Parameters ---------- T : (M, M) scipy.sparse matrix Transition matrix A : array_li...
[ "def", "forward_committor", "(", "T", ",", "A", ",", "B", ")", ":", "X", "=", "set", "(", "range", "(", "T", ".", "shape", "[", "0", "]", ")", ")", "A", "=", "set", "(", "A", ")", "B", "=", "set", "(", "B", ")", "AB", "=", "A", ".", "in...
24.985075
21.089552
def setRti(self, rti): """ Updates the current VisItem from the contents of the repo tree item. Is a slot but the signal is usually connected to the Collector, which then calls this function directly. """ check_class(rti, BaseRti) #assert rti.isSliceable, "RTI mu...
[ "def", "setRti", "(", "self", ",", "rti", ")", ":", "check_class", "(", "rti", ",", "BaseRti", ")", "#assert rti.isSliceable, \"RTI must be sliceable\" # TODO: maybe later", "self", ".", "_rti", "=", "rti", "self", ".", "_updateWidgets", "(", ")", "self", ".", "...
35.833333
19.75
def initialize( # type: ignore self, max_clients: int = 10, hostname_mapping: Dict[str, str] = None, max_buffer_size: int = 104857600, resolver: Resolver = None, defaults: Dict[str, Any] = None, max_header_size: int = None, max_body_size: int = None, ...
[ "def", "initialize", "(", "# type: ignore", "self", ",", "max_clients", ":", "int", "=", "10", ",", "hostname_mapping", ":", "Dict", "[", "str", ",", "str", "]", "=", "None", ",", "max_buffer_size", ":", "int", "=", "104857600", ",", "resolver", ":", "Re...
43.391304
20.84058
def reload_(name): ''' Reload the named service CLI Example: .. code-block:: bash salt '*' service.reload <service name> ''' cmd = '/usr/sbin/svcadm refresh {0}'.format(name) if not __salt__['cmd.retcode'](cmd, python_shell=False): # calling reload doesn't clear maintenanc...
[ "def", "reload_", "(", "name", ")", ":", "cmd", "=", "'/usr/sbin/svcadm refresh {0}'", ".", "format", "(", "name", ")", "if", "not", "__salt__", "[", "'cmd.retcode'", "]", "(", "cmd", ",", "python_shell", "=", "False", ")", ":", "# calling reload doesn't clear...
25.8125
23.0625
def on_user_init(target, args, kwargs): """Provide hook on :class:`~invenio_accounts.models.User` initialization. Automatically convert a dict to a :class:`~.UserProfile` instance. This is needed during e.g. user registration where Flask-Security will initialize a user model with all the form data ...
[ "def", "on_user_init", "(", "target", ",", "args", ",", "kwargs", ")", ":", "profile", "=", "kwargs", ".", "pop", "(", "'profile'", ",", "None", ")", "if", "profile", "is", "not", "None", "and", "not", "isinstance", "(", "profile", ",", "UserProfile", ...
47.875
15.25
def hide_tool(self, context_name, tool_name): """Hide a tool so that it is not exposed in the suite. Args: context_name (str): Context containing the tool. tool_name (str): Name of tool to hide. """ data = self._context(context_name) hidden_tools = data["...
[ "def", "hide_tool", "(", "self", ",", "context_name", ",", "tool_name", ")", ":", "data", "=", "self", ".", "_context", "(", "context_name", ")", "hidden_tools", "=", "data", "[", "\"hidden_tools\"", "]", "if", "tool_name", "not", "in", "hidden_tools", ":", ...
37.923077
10.307692
def set_meta(mcs, bases, attr): """ Get all of the ``Meta`` classes from bases and combine them with this class. Pops or creates ``Meta`` from attributes, combines all bases, adds ``_meta`` to attributes with all meta :param bases: bases of this class :param att...
[ "def", "set_meta", "(", "mcs", ",", "bases", ",", "attr", ")", ":", "# pop the meta class from the attributes", "meta", "=", "attr", ".", "pop", "(", "mcs", ".", "_meta_cls", ",", "types", ".", "ClassType", "(", "mcs", ".", "_meta_cls", ",", "(", ")", ",...
40.483871
15.774194
def get_loginclass(name): ''' Get the login class of the user name User to get the information .. note:: This function only applies to OpenBSD systems. CLI Example: .. code-block:: bash salt '*' user.get_loginclass foo ''' if __grains__['kernel'] != 'OpenBSD'...
[ "def", "get_loginclass", "(", "name", ")", ":", "if", "__grains__", "[", "'kernel'", "]", "!=", "'OpenBSD'", ":", "return", "False", "userinfo", "=", "__salt__", "[", "'cmd.run_stdout'", "]", "(", "[", "'userinfo'", ",", "name", "]", ",", "python_shell", "...
22.032258
19.580645
def evaluate(data_eval, model, nsp_loss, mlm_loss, vocab_size, ctx, log_interval, dtype): """Evaluation function.""" mlm_metric = MaskedAccuracy() nsp_metric = MaskedAccuracy() mlm_metric.reset() nsp_metric.reset() eval_begin_time = time.time() begin_time = time.time() step_num = 0 ...
[ "def", "evaluate", "(", "data_eval", ",", "model", ",", "nsp_loss", ",", "mlm_loss", ",", "vocab_size", ",", "ctx", ",", "log_interval", ",", "dtype", ")", ":", "mlm_metric", "=", "MaskedAccuracy", "(", ")", "nsp_metric", "=", "MaskedAccuracy", "(", ")", "...
45.280702
20.157895
def maps_get_default_rules_output_rules_rbridgeid(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") maps_get_default_rules = ET.Element("maps_get_default_rules") config = maps_get_default_rules output = ET.SubElement(maps_get_default_rules, "output...
[ "def", "maps_get_default_rules_output_rules_rbridgeid", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "maps_get_default_rules", "=", "ET", ".", "Element", "(", "\"maps_get_default_rules\"", ")", "confi...
42.384615
13.538462
def conv_to_json(obj, fields=None): """ return cdx as json dictionary string if ``fields`` is ``None``, output will include all fields in order stored, otherwise only specified fields will be included :param fields: list of field names to output """ if fi...
[ "def", "conv_to_json", "(", "obj", ",", "fields", "=", "None", ")", ":", "if", "fields", "is", "None", ":", "return", "json_encode", "(", "OrderedDict", "(", "(", "(", "x", ",", "obj", "[", "x", "]", ")", "for", "x", "in", "obj", "if", "not", "x"...
35.933333
24.066667
def file_rows(self, fo): """Return the lines in the file as a list. fo is the open file object.""" rows = [] for i in range(NUMROWS): line = fo.readline() if not line: break rows += [line] return rows
[ "def", "file_rows", "(", "self", ",", "fo", ")", ":", "rows", "=", "[", "]", "for", "i", "in", "range", "(", "NUMROWS", ")", ":", "line", "=", "fo", ".", "readline", "(", ")", "if", "not", "line", ":", "break", "rows", "+=", "[", "line", "]", ...
21.769231
18.846154
def get_thin_interval(self): """Gets the thin interval to use. If ``max_samples_per_chain`` is set, this will figure out what thin interval is needed to satisfy that criteria. In that case, the thin interval used must be a multiple of the currently used thin interval. """ ...
[ "def", "get_thin_interval", "(", "self", ")", ":", "if", "self", ".", "max_samples_per_chain", "is", "not", "None", ":", "# the extra factor of 2 is to account for the fact that the thin", "# interval will need to be at least twice as large as a previously", "# used interval", "thi...
49.47619
21.380952
def set_options(self, option_type, option_dict, force_options=False): """set plot options """ if force_options: self.options[option_type].update(option_dict) elif (option_type == 'yAxis' or option_type == 'xAxis') and isinstance(option_dict, list): # For multi-Axis ...
[ "def", "set_options", "(", "self", ",", "option_type", ",", "option_dict", ",", "force_options", "=", "False", ")", ":", "if", "force_options", ":", "self", ".", "options", "[", "option_type", "]", ".", "update", "(", "option_dict", ")", "elif", "(", "opti...
54.333333
22.533333
def list_fonts_with_info(self, pattern, max_names): """Return a list of fonts matching pattern. No more than max_names will be returned. Each list item represents one font and has the following properties: name The name of the font. min_bounds max_bounds ...
[ "def", "list_fonts_with_info", "(", "self", ",", "pattern", ",", "max_names", ")", ":", "return", "request", ".", "ListFontsWithInfo", "(", "display", "=", "self", ".", "display", ",", "max_names", "=", "max_names", ",", "pattern", "=", "pattern", ")" ]
32.1875
18.59375
def contribute_to_class(self, cls, name): """ Makes sure thumbnail gets set when image field initialized. """ super(SizedImageField, self).contribute_to_class(cls, name) signals.post_init.connect(self._set_thumbnail, sender=cls)
[ "def", "contribute_to_class", "(", "self", ",", "cls", ",", "name", ")", ":", "super", "(", "SizedImageField", ",", "self", ")", ".", "contribute_to_class", "(", "cls", ",", "name", ")", "signals", ".", "post_init", ".", "connect", "(", "self", ".", "_se...
43.833333
13.5
def trending(params): """gets trending content values """ # get params try: series = params.get("site", [DEFAULT_SERIES])[0] offset = params.get("offset", [DEFAULT_GROUP_BY])[0] limit = params.get("limit", [20])[0] except Exception as e: LOGGER.exception(e) re...
[ "def", "trending", "(", "params", ")", ":", "# get params", "try", ":", "series", "=", "params", ".", "get", "(", "\"site\"", ",", "[", "DEFAULT_SERIES", "]", ")", "[", "0", "]", "offset", "=", "params", ".", "get", "(", "\"offset\"", ",", "[", "DEFA...
31.294118
20.941176
def read_actions(): """Yields actions for pressed keys.""" while True: key = get_key() # Handle arrows, j/k (qwerty), and n/e (colemak) if key in (const.KEY_UP, const.KEY_CTRL_N, 'k', 'e'): yield const.ACTION_PREVIOUS elif key in (const.KEY_DOWN, const.KEY_CTRL_P, 'j...
[ "def", "read_actions", "(", ")", ":", "while", "True", ":", "key", "=", "get_key", "(", ")", "# Handle arrows, j/k (qwerty), and n/e (colemak)", "if", "key", "in", "(", "const", ".", "KEY_UP", ",", "const", ".", "KEY_CTRL_N", ",", "'k'", ",", "'e'", ")", "...
36.071429
13.5
def browse( plugins, parent = None, default = None ): """ Prompts the user to browse the wizards based on the inputed plugins \ allowing them to launch any particular wizard of choice. :param plugins | [<XWizardPlugin>, ..] parent | <QWidget> ...
[ "def", "browse", "(", "plugins", ",", "parent", "=", "None", ",", "default", "=", "None", ")", ":", "dlg", "=", "XWizardBrowserDialog", "(", "parent", ")", "dlg", ".", "setPlugins", "(", "plugins", ")", "dlg", ".", "setCurrentPlugin", "(", "default", ")"...
34.823529
13.882353
def fill_dcnm_net_info(self, tenant_id, direc, vlan_id=0, segmentation_id=0): """Fill DCNM network parameters. Function that fills the network parameters for a tenant required by DCNM. """ serv_obj = self.get_service_obj(tenant_id) fw_dict = se...
[ "def", "fill_dcnm_net_info", "(", "self", ",", "tenant_id", ",", "direc", ",", "vlan_id", "=", "0", ",", "segmentation_id", "=", "0", ")", ":", "serv_obj", "=", "self", ".", "get_service_obj", "(", "tenant_id", ")", "fw_dict", "=", "serv_obj", ".", "get_fw...
46.0625
17.90625
def from_bytes(TxIn, byte_string): ''' byte_string -> TxIn parses a TxIn from a byte-like object ''' outpoint = Outpoint.from_bytes(byte_string[:36]) script_sig_len = VarInt.from_bytes(byte_string[36:45]) script_start = 36 + len(script_sig_len) script_end...
[ "def", "from_bytes", "(", "TxIn", ",", "byte_string", ")", ":", "outpoint", "=", "Outpoint", ".", "from_bytes", "(", "byte_string", "[", ":", "36", "]", ")", "script_sig_len", "=", "VarInt", ".", "from_bytes", "(", "byte_string", "[", "36", ":", "45", "]...
34.826087
17.086957
def refreshUserMembership(self, users): """ This operation iterates over every enterprise group configured in the portal and determines if the input user accounts belong to any of the configured enterprise groups. If there is any change in membership, the database and the indexes...
[ "def", "refreshUserMembership", "(", "self", ",", "users", ")", ":", "params", "=", "{", "\"f\"", ":", "\"json\"", ",", "\"users\"", ":", "users", "}", "url", "=", "self", ".", "_url", "+", "\"/users/refreshMembership\"", "return", "self", ".", "_post", "(...
43.26087
18.73913
def predict(self, X, with_noise=True): """ Predictions with the model. Returns posterior means and standard deviations at X. Note that this is different in GPy where the variances are given. Parameters: X (np.ndarray) - points to run the prediction for. with_noise (bool)...
[ "def", "predict", "(", "self", ",", "X", ",", "with_noise", "=", "True", ")", ":", "m", ",", "v", "=", "self", ".", "_predict", "(", "X", ",", "False", ",", "with_noise", ")", "# We can take the square root because v is just a diagonal matrix of variances", "ret...
49.818182
28.727273
def implements_storage(self): """ True if combination of field access properties imply that the field implements a storage element. """ # 9.4.1, Table 12 sw = self.get_property('sw') hw = self.get_property('hw') if sw in (rdltypes.AccessType.rw, rdltypes....
[ "def", "implements_storage", "(", "self", ")", ":", "# 9.4.1, Table 12", "sw", "=", "self", ".", "get_property", "(", "'sw'", ")", "hw", "=", "self", ".", "get_property", "(", "'hw'", ")", "if", "sw", "in", "(", "rdltypes", ".", "AccessType", ".", "rw", ...
35.75
22.0625
def dict_copy(func): "copy dict keyword args, to avoid modifying caller's copy" @functools.wraps(func) def wrapper(*args, **kwargs): copied_kwargs = copy.deepcopy(kwargs) return func(*args, **copied_kwargs) return wrapper
[ "def", "dict_copy", "(", "func", ")", ":", "@", "functools", ".", "wraps", "(", "func", ")", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "copied_kwargs", "=", "copy", ".", "deepcopy", "(", "kwargs", ")", "return", "func", ...
35.285714
13.285714
def gen_mu(K, delta, c): """The Robust Soliton Distribution on the degree of transmitted blocks """ S = c * log(K/delta) * sqrt(K) tau = gen_tau(S, K, delta) rho = gen_rho(K) normalizer = sum(rho) + sum(tau) return [(rho[d] + tau[d])/normalizer for d in range(K)]
[ "def", "gen_mu", "(", "K", ",", "delta", ",", "c", ")", ":", "S", "=", "c", "*", "log", "(", "K", "/", "delta", ")", "*", "sqrt", "(", "K", ")", "tau", "=", "gen_tau", "(", "S", ",", "K", ",", "delta", ")", "rho", "=", "gen_rho", "(", "K"...
28.9
13.2
def run_in_background(coroutine: "Callable[[concurrent.futures.Future[T], Coroutine[Any, Any, None]]", *, debug: bool = False, _policy_lock: threading.Lock = threading.Lock()) -> T: """ Runs ``coroutine(future)`` in a new event loop on a background thread. Blocks and returns the *future* result as soon as ...
[ "def", "run_in_background", "(", "coroutine", ":", "\"Callable[[concurrent.futures.Future[T], Coroutine[Any, Any, None]]\"", ",", "*", ",", "debug", ":", "bool", "=", "False", ",", "_policy_lock", ":", "threading", ".", "Lock", "=", "threading", ".", "Lock", "(", ")...
36.234043
23.765957