text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def color_from_rgb(red, green, blue): """ Takes your standard rgb color and converts it to a proper hue value """ r = min(red, 255) g = min(green, 255) b = min(blue, 255) if r > 1 or g > 1 or b > 1: r = r / 255.0 g = g / 255.0 b = b / 255.0 return color_fro...
[ "def", "color_from_rgb", "(", "red", ",", "green", ",", "blue", ")", ":", "r", "=", "min", "(", "red", ",", "255", ")", "g", "=", "min", "(", "green", ",", "255", ")", "b", "=", "min", "(", "blue", ",", "255", ")", "if", "r", ">", "1", "or"...
25.615385
0.014493
def VAR_DECL(self, cursor): """Handles Variable declaration.""" # get the name name = self.get_unique_name(cursor) log.debug('VAR_DECL: name: %s', name) # Check for a previous declaration in the register if self.is_registered(name): return self.get_registered(...
[ "def", "VAR_DECL", "(", "self", ",", "cursor", ")", ":", "# get the name", "name", "=", "self", ".", "get_unique_name", "(", "cursor", ")", "log", ".", "debug", "(", "'VAR_DECL: name: %s'", ",", "name", ")", "# Check for a previous declaration in the register", "i...
43.2
0.002265
def mediation_analysis(data=None, x=None, m=None, y=None, covar=None, alpha=0.05, n_boot=500, seed=None, return_dist=False): """Mediation analysis using a bias-correct non-parametric bootstrap method. Parameters ---------- data : pd.DataFrame Dataframe. x : str ...
[ "def", "mediation_analysis", "(", "data", "=", "None", ",", "x", "=", "None", ",", "m", "=", "None", ",", "y", "=", "None", ",", "covar", "=", "None", ",", "alpha", "=", "0.05", ",", "n_boot", "=", "500", ",", "seed", "=", "None", ",", "return_di...
43.898246
0.000078
def add_int(self,oid,value,label=None): """Short helper to add an integer value to the MIB subtree.""" self.add_oid_entry(oid,'INTEGER',value,label=label)
[ "def", "add_int", "(", "self", ",", "oid", ",", "value", ",", "label", "=", "None", ")", ":", "self", ".", "add_oid_entry", "(", "oid", ",", "'INTEGER'", ",", "value", ",", "label", "=", "label", ")" ]
52
0.063291
def xml(self): """ :rtype: str """ if six.PY3: data = ElementTree.tostring(self.et, encoding="unicode") else: data = ElementTree.tostring(self.et) return data
[ "def", "xml", "(", "self", ")", ":", "if", "six", ".", "PY3", ":", "data", "=", "ElementTree", ".", "tostring", "(", "self", ".", "et", ",", "encoding", "=", "\"unicode\"", ")", "else", ":", "data", "=", "ElementTree", ".", "tostring", "(", "self", ...
24.666667
0.008696
async def on_date(self, date: datetime.date) -> dict: """Get statistics for a certain date.""" return await self._request( 'get', 'dailystats/{0}'.format(date.strftime('%Y-%m-%d')))
[ "async", "def", "on_date", "(", "self", ",", "date", ":", "datetime", ".", "date", ")", "->", "dict", ":", "return", "await", "self", ".", "_request", "(", "'get'", ",", "'dailystats/{0}'", ".", "format", "(", "date", ".", "strftime", "(", "'%Y-%m-%d'", ...
51.5
0.009569
def get_attachment_formset(self, formset_class): """ Returns an instance of the attachment formset to be used in the view. """ if ( self.request.forum_permission_handler.can_attach_files( self.get_forum(), self.request.user, ) ): return formset...
[ "def", "get_attachment_formset", "(", "self", ",", "formset_class", ")", ":", "if", "(", "self", ".", "request", ".", "forum_permission_handler", ".", "can_attach_files", "(", "self", ".", "get_forum", "(", ")", ",", "self", ".", "request", ".", "user", ",",...
44.875
0.008197
def get_values(self, variables = None, table = None, lowercase = False, rename_ident = True): """ Get values Parameters ---------- variables : list of strings, default None list of variables names, if None return the whole table table : string, defaul...
[ "def", "get_values", "(", "self", ",", "variables", "=", "None", ",", "table", "=", "None", ",", "lowercase", "=", "False", ",", "rename_ident", "=", "True", ")", ":", "assert", "self", ".", "hdf5_file_path", "is", "not", "None", "assert", "os", ".", "...
39.134615
0.011505
def run(self, address, port, unix_path): """ Starts the Daemon, handling commands until interrupted. @return False if error. Runs indefinitely otherwise. """ assert address or unix_path if unix_path: sock = bind_unix_socket(unix_path) else: sock =...
[ "def", "run", "(", "self", ",", "address", ",", "port", ",", "unix_path", ")", ":", "assert", "address", "or", "unix_path", "if", "unix_path", ":", "sock", "=", "bind_unix_socket", "(", "unix_path", ")", "else", ":", "sock", "=", "bind_socket", "(", "add...
38.540541
0.001368
def nothread_quit(self, arg): """ quit command when there's just one thread. """ self.debugger.core.stop() self.debugger.core.execution_status = 'Quit command' raise Mexcept.DebuggerQuit
[ "def", "nothread_quit", "(", "self", ",", "arg", ")", ":", "self", ".", "debugger", ".", "core", ".", "stop", "(", ")", "self", ".", "debugger", ".", "core", ".", "execution_status", "=", "'Quit command'", "raise", "Mexcept", ".", "DebuggerQuit" ]
35.666667
0.009132
def write_bibtex_dict(stream, entries): """bibtexparser.write converts the entire database to one big string and writes it out in one go. I'm sure it will always all fit in RAM but some things just will not stand. """ from bibtexparser.bwriter import BibTexWriter writer = BibTexWriter() wr...
[ "def", "write_bibtex_dict", "(", "stream", ",", "entries", ")", ":", "from", "bibtexparser", ".", "bwriter", "import", "BibTexWriter", "writer", "=", "BibTexWriter", "(", ")", "writer", ".", "indent", "=", "' '", "writer", ".", "entry_separator", "=", "''", ...
28.947368
0.001761
def parse_macro_params(token): """ Common parsing logic for both use_macro and macro_block """ try: bits = token.split_contents() tag_name, macro_name, values = bits[0], bits[1], bits[2:] except IndexError: raise template.TemplateSyntaxError( "{0} tag requires at ...
[ "def", "parse_macro_params", "(", "token", ")", ":", "try", ":", "bits", "=", "token", ".", "split_contents", "(", ")", "tag_name", ",", "macro_name", ",", "values", "=", "bits", "[", "0", "]", ",", "bits", "[", "1", "]", ",", "bits", "[", "2", ":"...
35.232558
0.000642
def better_exec_command(ssh, command, msg): """Uses paramiko to execute a command but handles failure by raising a ParamikoError if the command fails. Note that unlike paramiko.SSHClient.exec_command this is not asynchronous because we wait until the exit status is known :Parameter ssh: a paramiko SSH Client...
[ "def", "better_exec_command", "(", "ssh", ",", "command", ",", "msg", ")", ":", "chan", "=", "ssh", ".", "get_transport", "(", ")", ".", "open_session", "(", ")", "chan", ".", "exec_command", "(", "command", ")", "exit_status", "=", "chan", ".", "recv_ex...
39.148148
0.01108
def set_all_vlan_states(self, nexus_host, vlanid_range): """Set the VLAN states to active.""" starttime = time.time() if not vlanid_range: LOG.warning("Exiting set_all_vlan_states: " "No vlans to configure") return # Eliminate possible w...
[ "def", "set_all_vlan_states", "(", "self", ",", "nexus_host", ",", "vlanid_range", ")", ":", "starttime", "=", "time", ".", "time", "(", ")", "if", "not", "vlanid_range", ":", "LOG", ".", "warning", "(", "\"Exiting set_all_vlan_states: \"", "\"No vlans to configur...
36.837838
0.00143
def dispatch_request(self, view, view_args): """ View dispatcher that calls before_request, the view, and then after_request. Subclasses may override this to provide a custom flow. :class:`ModelView` does this to insert a model loading phase. :param view: View method wrapped in ...
[ "def", "dispatch_request", "(", "self", ",", "view", ",", "view_args", ")", ":", "# Call the :meth:`before_request` method", "resp", "=", "self", ".", "before_request", "(", ")", "if", "resp", ":", "return", "self", ".", "after_request", "(", "make_response", "(...
49.1875
0.008728
def compute_ld(cur_geno, other_genotypes, r2=False): """Compute LD between a marker and a list of markers. Args: cur_geno (Genotypes): The genotypes of the marker. other_genotypes (list): A list of genotypes. Returns: numpy.array: An array containing the r or r**2 values between cu...
[ "def", "compute_ld", "(", "cur_geno", ",", "other_genotypes", ",", "r2", "=", "False", ")", ":", "# Normalizing the current genotypes", "norm_cur", "=", "normalize_genotypes", "(", "cur_geno", ")", "# Normalizing and creating the matrix for the other genotypes", "norm_others"...
27.66
0.000698
def describe(df, dtype=None): """ Print a description of a Pandas dataframe. Parameters ---------- df : Pandas.DataFrame dtype : dict Maps column names to types """ if dtype is None: dtype = {} print('Number of datapoints: {datapoints}'.format(datapoints=len(df))) ...
[ "def", "describe", "(", "df", ",", "dtype", "=", "None", ")", ":", "if", "dtype", "is", "None", ":", "dtype", "=", "{", "}", "print", "(", "'Number of datapoints: {datapoints}'", ".", "format", "(", "datapoints", "=", "len", "(", "df", ")", ")", ")", ...
28.702703
0.000911
def get_params(self): """ Get an odict of the parameter names and values """ return odict([(key,param.value) for key,param in self.params.items()])
[ "def", "get_params", "(", "self", ")", ":", "return", "odict", "(", "[", "(", "key", ",", "param", ".", "value", ")", "for", "key", ",", "param", "in", "self", ".", "params", ".", "items", "(", ")", "]", ")" ]
53.666667
0.02454
def segment_messages_from_magnitudes(magnitudes: np.ndarray, noise_threshold: float): """ Get the list of start, end indices of messages :param magnitudes: Magnitudes of samples :param noise_threshold: Threshold for noise :return: """ return c_auto_interpretation.segment_messages_from_magni...
[ "def", "segment_messages_from_magnitudes", "(", "magnitudes", ":", "np", ".", "ndarray", ",", "noise_threshold", ":", "float", ")", ":", "return", "c_auto_interpretation", ".", "segment_messages_from_magnitudes", "(", "magnitudes", ",", "noise_threshold", ")" ]
38.444444
0.008475
def add_post(self, *args, **kwargs): """ Shortcut for add_route with method POST """ return self.add_route(hdrs.METH_POST, *args, **kwargs)
[ "def", "add_post", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "add_route", "(", "hdrs", ".", "METH_POST", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
33.4
0.011696
def write(self, output_buffer, kmip_version=enums.KMIPVersion.KMIP_1_0): """ Write the data encoding the GetAttributeList request payload to a stream. Args: output_buffer (stream): A data stream in which to encode object data, supporting a write method; usual...
[ "def", "write", "(", "self", ",", "output_buffer", ",", "kmip_version", "=", "enums", ".", "KMIPVersion", ".", "KMIP_1_0", ")", ":", "local_buffer", "=", "utils", ".", "BytearrayStream", "(", ")", "if", "self", ".", "_unique_identifier", ":", "self", ".", ...
36.111111
0.001998
def solarReturn(self, year): """ Returns this chart's solar return for a given year. """ sun = self.getObject(const.SUN) date = Datetime('{0}/01/01'.format(year), '00:00', self.date.utcoffset) srDate = ephem.nextS...
[ "def", "solarReturn", "(", "self", ",", "year", ")", ":", "sun", "=", "self", ".", "getObject", "(", "const", ".", "SUN", ")", "date", "=", "Datetime", "(", "'{0}/01/01'", ".", "format", "(", "year", ")", ",", "'00:00'", ",", "self", ".", "date", "...
35.454545
0.0125
def ImportFile(store, filename, start): """Import hashes from 'filename' into 'store'.""" with io.open(filename, "r") as fp: reader = csv.Reader(fp.read()) i = 0 current_row = None product_code_list = [] op_system_code_list = [] for row in reader: # Skip first row. i += 1 i...
[ "def", "ImportFile", "(", "store", ",", "filename", ",", "start", ")", ":", "with", "io", ".", "open", "(", "filename", ",", "\"r\"", ")", "as", "fp", ":", "reader", "=", "csv", ".", "Reader", "(", "fp", ".", "read", "(", ")", ")", "i", "=", "0...
32.363636
0.01636
def format_requirement(ireq): """ Generic formatter for pretty printing InstallRequirements to the terminal in a less verbose way than using its `__str__` method. """ if ireq.editable: line = "-e {}".format(ireq.link) else: line = _requirement_to_str_lowercase_name(ireq.req) ...
[ "def", "format_requirement", "(", "ireq", ")", ":", "if", "ireq", ".", "editable", ":", "line", "=", "\"-e {}\"", ".", "format", "(", "ireq", ".", "link", ")", "else", ":", "line", "=", "_requirement_to_str_lowercase_name", "(", "ireq", ".", "req", ")", ...
31.3
0.00155
async def post_heartbeat(self, msg, _context): """Update the status of a service.""" name = msg.get('name') await self.service_manager.send_heartbeat(name)
[ "async", "def", "post_heartbeat", "(", "self", ",", "msg", ",", "_context", ")", ":", "name", "=", "msg", ".", "get", "(", "'name'", ")", "await", "self", ".", "service_manager", ".", "send_heartbeat", "(", "name", ")" ]
29.333333
0.01105
def get(self, sid): """ Constructs a VerificationContext :param sid: The unique string that identifies the resource :returns: twilio.rest.verify.v2.service.verification.VerificationContext :rtype: twilio.rest.verify.v2.service.verification.VerificationContext """ ...
[ "def", "get", "(", "self", ",", "sid", ")", ":", "return", "VerificationContext", "(", "self", ".", "_version", ",", "service_sid", "=", "self", ".", "_solution", "[", "'service_sid'", "]", ",", "sid", "=", "sid", ",", ")" ]
40.8
0.009592
def import_wp(filepath): """Imports A WordPress export and converts it to a Blended site""" print("\nBlended: Static Website Generator -\n") checkConfig() print("Importing from WordPress...") wp = parseXML(filepath) wname = wp.rss.channel.title.cdata wdesc = wp.rss.channel.description.cd...
[ "def", "import_wp", "(", "filepath", ")", ":", "print", "(", "\"\\nBlended: Static Website Generator -\\n\"", ")", "checkConfig", "(", ")", "print", "(", "\"Importing from WordPress...\"", ")", "wp", "=", "parseXML", "(", "filepath", ")", "wname", "=", "wp", ".", ...
33.555556
0.002146
def public_point(self): """The public point (x, y).""" if self._public_point is None: self._public_point = Point(*public_key_to_coords(self._public_key)) return self._public_point
[ "def", "public_point", "(", "self", ")", ":", "if", "self", ".", "_public_point", "is", "None", ":", "self", ".", "_public_point", "=", "Point", "(", "*", "public_key_to_coords", "(", "self", ".", "_public_key", ")", ")", "return", "self", ".", "_public_po...
42.2
0.009302
def _flatten_beam_dim(tensor): """Reshapes first two dimensions in to single dimension. Args: tensor: Tensor to reshape of shape [A, B, ...] Returns: Reshaped tensor of shape [A*B, ...] """ shape = _shape_list(tensor) shape[0] *= shape[1] shape.pop(1) # Remove beam dim return tf.reshape(tenso...
[ "def", "_flatten_beam_dim", "(", "tensor", ")", ":", "shape", "=", "_shape_list", "(", "tensor", ")", "shape", "[", "0", "]", "*=", "shape", "[", "1", "]", "shape", ".", "pop", "(", "1", ")", "# Remove beam dim", "return", "tf", ".", "reshape", "(", ...
24.384615
0.018237
def run(self, args): """Runs the emulator command. Args: self (EmulatorCommand): the ``EmulatorCommand`` instance args (Namespace): arguments to parse Returns: ``None`` """ jlink = pylink.JLink() if args.test: if jlink.test(): ...
[ "def", "run", "(", "self", ",", "args", ")", ":", "jlink", "=", "pylink", ".", "JLink", "(", ")", "if", "args", ".", "test", ":", "if", "jlink", ".", "test", "(", ")", ":", "print", "(", "'Self-test succeeded.'", ")", "else", ":", "print", "(", "...
38.135593
0.000867
def optimizer(name): """Get pre-registered optimizer keyed by name. `name` should be snake case, though SGD -> sgd, RMSProp -> rms_prop and UpperCamelCase -> snake_case conversions included for legacy support. Args: name: name of optimizer used in registration. This should be a snake case identifier...
[ "def", "optimizer", "(", "name", ")", ":", "warn_msg", "=", "(", "\"Please update `registry.optimizer` callsite \"", "\"(likely due to a `HParams.optimizer` value)\"", ")", "if", "name", "==", "\"SGD\"", ":", "name", "=", "\"sgd\"", "tf", ".", "logging", ".", "warning...
34.448276
0.008763
def standings(self): '''Get standings from the community's account''' headers = {"Content-type": "application/x-www-form-urlencoded","Accept": "text/plain","User-Agent": user_agent} req = self.session.get('http://'+self.domain+'/standings.phtml',headers=headers).content soup = BeautifulS...
[ "def", "standings", "(", "self", ")", ":", "headers", "=", "{", "\"Content-type\"", ":", "\"application/x-www-form-urlencoded\"", ",", "\"Accept\"", ":", "\"text/plain\"", ",", "\"User-Agent\"", ":", "user_agent", "}", "req", "=", "self", ".", "session", ".", "g...
72.555556
0.022693
def _get_ports(port_opts): """ Generate a list of ports using the given options. port options supported: - Opt.empty -> - Opt.random -> - Opt.preset -> ports are in default locations - Opt.debug -> alias for Opt.preset :param port_opts: Opt :return: list(Port) """ if port_o...
[ "def", "_get_ports", "(", "port_opts", ")", ":", "if", "port_opts", "in", "[", "Opt", ".", "preset", ",", "Opt", ".", "debug", "]", ":", "_preset_ports", "=", "[", "(", "1", ",", "'NW'", ",", "catan", ".", "board", ".", "PortType", ".", "any3", ")"...
40.928571
0.000853
def get_conn(): ''' Return a conn object for the passed VM data ''' vm_ = get_configured_provider() driver = get_driver(Provider.DIMENSIONDATA) region = config.get_cloud_config_value( 'region', vm_, __opts__ ) user_id = config.get_cloud_config_value( 'user_id', vm_, __...
[ "def", "get_conn", "(", ")", ":", "vm_", "=", "get_configured_provider", "(", ")", "driver", "=", "get_driver", "(", "Provider", ".", "DIMENSIONDATA", ")", "region", "=", "config", ".", "get_cloud_config_value", "(", "'region'", ",", "vm_", ",", "__opts__", ...
21.192308
0.001736
def _Summarize(user_info): """Returns a string with summary info for a user.""" return "Username: %s\nIs Admin: %s" % ( user_info.username, user_info.user_type == api_user.ApiGrrUser.UserType.USER_TYPE_ADMIN)
[ "def", "_Summarize", "(", "user_info", ")", ":", "return", "\"Username: %s\\nIs Admin: %s\"", "%", "(", "user_info", ".", "username", ",", "user_info", ".", "user_type", "==", "api_user", ".", "ApiGrrUser", ".", "UserType", ".", "USER_TYPE_ADMIN", ")" ]
44
0.013393
def merge_templates(self, replacements, separator): """ Duplicate template. Creates a copy of the template, does a merge, and separates them by a new paragraph, a new break or a new section break. separator must be : - page_break : Page Break. - column_break : Column Break. ONLY...
[ "def", "merge_templates", "(", "self", ",", "replacements", ",", "separator", ")", ":", "#TYPE PARAM CONTROL AND SPLIT", "valid_separators", "=", "{", "'page_break'", ",", "'column_break'", ",", "'textWrapping_break'", ",", "'continuous_section'", ",", "'evenPage_section'...
51.8
0.010768
def solve_sweep_structure( self, structures, sweep_param_list, filename="structure_n_effs.dat", plot=True, x_label="Structure number", fraction_mode_list=[], ): """ Find the modes of many structures. Args: structures (list)...
[ "def", "solve_sweep_structure", "(", "self", ",", "structures", ",", "sweep_param_list", ",", "filename", "=", "\"structure_n_effs.dat\"", ",", "plot", "=", "True", ",", "x_label", "=", "\"Structure number\"", ",", "fraction_mode_list", "=", "[", "]", ",", ")", ...
38.50495
0.001003
def _upgradeTableOid(store, table, createTable, postCreate=lambda: None): """ Upgrade a table to have an explicit oid. Must be called in a transaction to avoid corrupting the database. """ if _hasExplicitOid(store, table): return store.executeSchemaSQL( 'ALTER TABLE *DATABASE*.{...
[ "def", "_upgradeTableOid", "(", "store", ",", "table", ",", "createTable", ",", "postCreate", "=", "lambda", ":", "None", ")", ":", "if", "_hasExplicitOid", "(", "store", ",", "table", ")", ":", "return", "store", ".", "executeSchemaSQL", "(", "'ALTER TABLE ...
36.375
0.001675
def validate_generations(self): ''' Make sure that the descendent depth is valid. ''' nodes = self.arc_root_node.get_descendants() for node in nodes: logger.debug("Checking parent for node of type %s" % node.arc_element_type) parent = ArcElementNode.object...
[ "def", "validate_generations", "(", "self", ")", ":", "nodes", "=", "self", ".", "arc_root_node", ".", "get_descendants", "(", ")", "for", "node", "in", "nodes", ":", "logger", ".", "debug", "(", "\"Checking parent for node of type %s\"", "%", "node", ".", "ar...
59.2
0.008869
def _chunks(self, items, limit): """ Yield successive chunks from list \a items with a minimum size \a limit """ for i in range(0, len(items), limit): yield items[i:i + limit]
[ "def", "_chunks", "(", "self", ",", "items", ",", "limit", ")", ":", "for", "i", "in", "range", "(", "0", ",", "len", "(", "items", ")", ",", "limit", ")", ":", "yield", "items", "[", "i", ":", "i", "+", "limit", "]" ]
35.666667
0.009132
def _isbn_cleanse(isbn, checksum=True): """Check ISBN is a string, and passes basic sanity checks. Args: isbn (str): SBN, ISBN-10 or ISBN-13 checksum (bool): ``True`` if ``isbn`` includes checksum character Returns: ``str``: ISBN with hyphenation removed, including when called with...
[ "def", "_isbn_cleanse", "(", "isbn", ",", "checksum", "=", "True", ")", ":", "if", "not", "isinstance", "(", "isbn", ",", "string_types", ")", ":", "raise", "TypeError", "(", "'ISBN must be a string, received %r'", "%", "isbn", ")", "if", "PY2", "and", "isin...
35.533333
0.000456
def connect(self, *args, **kwargs): """ Connect to a sqlite database only if no connection exists. Isolation level for the connection is automatically set to autocommit """ self.db = sqlite3.connect(*args, **kwargs) self.db.isolation_level = None
[ "def", "connect", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "db", "=", "sqlite3", ".", "connect", "(", "*", "args", ",", "*", "*", "kwargs", ")", "self", ".", "db", ".", "isolation_level", "=", "None" ]
41.142857
0.010204
def read_galaxy_amqp_config(galaxy_config, base_dir): """Read connection information on the RabbitMQ server from Galaxy config. """ galaxy_config = add_full_path(galaxy_config, base_dir) config = six.moves.configparser.ConfigParser() config.read(galaxy_config) amqp_config = {} for option in ...
[ "def", "read_galaxy_amqp_config", "(", "galaxy_config", ",", "base_dir", ")", ":", "galaxy_config", "=", "add_full_path", "(", "galaxy_config", ",", "base_dir", ")", "config", "=", "six", ".", "moves", ".", "configparser", ".", "ConfigParser", "(", ")", "config"...
42.8
0.002288
def _build_mask_ds(mask, mask_offset): """Build the mask dataset to indicate which element to skip. Args: mask: `tf.Tensor`, binary mask to apply to all following elements. This mask should have a length 100. mask_offset: `tf.Tensor`, Integer specifying from how much the mask should be shifted ...
[ "def", "_build_mask_ds", "(", "mask", ",", "mask_offset", ")", ":", "mask_ds", "=", "tf", ".", "data", ".", "Dataset", ".", "from_tensor_slices", "(", "mask", ")", "mask_ds", "=", "mask_ds", ".", "repeat", "(", ")", "mask_ds", "=", "mask_ds", ".", "skip"...
35.117647
0.009788
def ui_iiif_image_url(obj, version='v2', region='full', size='full', rotation=0, quality='default', image_format='png'): """Generate IIIF image URL from the UI application.""" return u'{prefix}{version}/{identifier}/{region}/{size}/{rotation}/' \ u'{quality}.{image_format}'.format(...
[ "def", "ui_iiif_image_url", "(", "obj", ",", "version", "=", "'v2'", ",", "region", "=", "'full'", ",", "size", "=", "'full'", ",", "rotation", "=", "0", ",", "quality", "=", "'default'", ",", "image_format", "=", "'png'", ")", ":", "return", "u'{prefix}...
42.733333
0.001527
def visit_Set(self, node: AST, dfltChaining: bool = True) -> str: """Return set representation of `node`s elements.""" return '{' + ', '.join([self.visit(elt) for elt in node.elts]) + '}'
[ "def", "visit_Set", "(", "self", ",", "node", ":", "AST", ",", "dfltChaining", ":", "bool", "=", "True", ")", "->", "str", ":", "return", "'{'", "+", "', '", ".", "join", "(", "[", "self", ".", "visit", "(", "elt", ")", "for", "elt", "in", "node"...
67
0.009852
def process_model(model): """Returns a BiopaxProcessor for a BioPAX model object. Parameters ---------- model : org.biopax.paxtools.model.Model A BioPAX model object. Returns ------- bp : BiopaxProcessor A BiopaxProcessor containing the obtained BioPAX model in bp.model. ...
[ "def", "process_model", "(", "model", ")", ":", "bp", "=", "BiopaxProcessor", "(", "model", ")", "bp", ".", "get_modifications", "(", ")", "bp", ".", "get_regulate_activities", "(", ")", "bp", ".", "get_regulate_amounts", "(", ")", "bp", ".", "get_activity_m...
24.708333
0.001623
def bulk_upsert(self, docs, namespace, timestamp): """Insert multiple documents into Elasticsearch.""" def docs_to_upsert(): doc = None for doc in docs: # Remove metadata and redundant _id index, doc_type = self._index_and_mapping(namespace) ...
[ "def", "bulk_upsert", "(", "self", ",", "docs", ",", "namespace", ",", "timestamp", ")", ":", "def", "docs_to_upsert", "(", ")", ":", "doc", "=", "None", "for", "doc", "in", "docs", ":", "# Remove metadata and redundant _id", "index", ",", "doc_type", "=", ...
38.306122
0.001039
def can_pull(self, initial, scheduled): """ Determines if pull requests should be created :return: bool """ if not initial and self.config.is_valid_schedule(): # if the config has a valid schedule, return True if this is a scheduled run return scheduled ...
[ "def", "can_pull", "(", "self", ",", "initial", ",", "scheduled", ")", ":", "if", "not", "initial", "and", "self", ".", "config", ".", "is_valid_schedule", "(", ")", ":", "# if the config has a valid schedule, return True if this is a scheduled run", "return", "schedu...
36.555556
0.008902
def transformer_ae_small_noatt(): """Set of hyperparameters.""" hparams = transformer_ae_small() hparams.reshape_method = "slice" hparams.bottleneck_kind = "dvq" hparams.hidden_size = 512 hparams.num_blocks = 1 hparams.num_decode_blocks = 1 hparams.z_size = 12 hparams.do_attend_decompress = False re...
[ "def", "transformer_ae_small_noatt", "(", ")", ":", "hparams", "=", "transformer_ae_small", "(", ")", "hparams", ".", "reshape_method", "=", "\"slice\"", "hparams", ".", "bottleneck_kind", "=", "\"dvq\"", "hparams", ".", "hidden_size", "=", "512", "hparams", ".", ...
29.272727
0.033133
def unwrap(msmt): """Convert the value into the most basic representation that we can do math on: float if possible, then Uval, then Lval.""" if np.isscalar(msmt): return float(msmt) if isinstance(msmt, (Uval, Lval)): return msmt if isinstance(msmt, Textual): return msmt.unw...
[ "def", "unwrap", "(", "msmt", ")", ":", "if", "np", ".", "isscalar", "(", "msmt", ")", ":", "return", "float", "(", "msmt", ")", "if", "isinstance", "(", "msmt", ",", "(", "Uval", ",", "Lval", ")", ")", ":", "return", "msmt", "if", "isinstance", ...
35.545455
0.002494
def beginGroup(self, prefix): """ Starts a new group for the given prefix. :param prefix | <str> """ curr = self._xstack[-1] next = curr.find(prefix) if next is None: next = ElementTree.SubElement(curr, prefix) self._xst...
[ "def", "beginGroup", "(", "self", ",", "prefix", ")", ":", "curr", "=", "self", ".", "_xstack", "[", "-", "1", "]", "next", "=", "curr", ".", "find", "(", "prefix", ")", "if", "next", "is", "None", ":", "next", "=", "ElementTree", ".", "SubElement"...
29.636364
0.008929
def _unpack_dict(example): """ Input data format standardization """ try: x = example['data'] y = example['target'] meta = example.get('metadata', {}) return x, y, meta except KeyError: raise IndicoError( "Invalid input data. Please ensure input d...
[ "def", "_unpack_dict", "(", "example", ")", ":", "try", ":", "x", "=", "example", "[", "'data'", "]", "y", "=", "example", "[", "'target'", "]", "meta", "=", "example", ".", "get", "(", "'metadata'", ",", "{", "}", ")", "return", "x", ",", "y", "...
30.533333
0.002119
def update_fitness(objective_function, particle): """ Calculates and updates the fitness and best_fitness of a particle. Fitness is calculated using the 'problem.fitness' function. Args: problem: The optimization problem encapsulating the fitness function and optimization type. ...
[ "def", "update_fitness", "(", "objective_function", ",", "particle", ")", ":", "fitness", "=", "objective_function", "(", "particle", ".", "position", ")", "best_fitness", "=", "particle", ".", "best_fitness", "cmp", "=", "comparator", "(", "fitness", ")", "if",...
37.48
0.001041
def to_planar(self, to_2D=None, normal=None, check=True): """ Check to see if current vectors are all coplanar. If they are, return a Path2D and a transform which will transform the 2D representation back into 3 dimensions P...
[ "def", "to_planar", "(", "self", ",", "to_2D", "=", "None", ",", "normal", "=", "None", ",", "check", "=", "True", ")", ":", "# which vertices are actually referenced", "referenced", "=", "self", ".", "referenced_vertices", "# if nothing is referenced return an empty ...
36.465347
0.001322
def check_if_needs_inversion(tomodir): """check of we need to run CRTomo in a given tomodir """ required_files = ( 'grid' + os.sep + 'elem.dat', 'grid' + os.sep + 'elec.dat', 'exe' + os.sep + 'crtomo.cfg', ) needs_inversion = True for filename in required_files: ...
[ "def", "check_if_needs_inversion", "(", "tomodir", ")", ":", "required_files", "=", "(", "'grid'", "+", "os", ".", "sep", "+", "'elem.dat'", ",", "'grid'", "+", "os", ".", "sep", "+", "'elec.dat'", ",", "'exe'", "+", "os", ".", "sep", "+", "'crtomo.cfg'"...
32.966667
0.000982
def first(self, rows: List[Row]) -> List[Row]: """ Takes an expression that evaluates to a list of rows, and returns the first one in that list. """ if not rows: logger.warning("Trying to get first row from an empty list") return [] return [rows[0]...
[ "def", "first", "(", "self", ",", "rows", ":", "List", "[", "Row", "]", ")", "->", "List", "[", "Row", "]", ":", "if", "not", "rows", ":", "logger", ".", "warning", "(", "\"Trying to get first row from an empty list\"", ")", "return", "[", "]", "return",...
34.777778
0.009346
def dt_cluster(dt_list, dt_thresh=16.0): """Find clusters of similar datetimes within datetime list """ if not isinstance(dt_list[0], float): o_list = dt2o(dt_list) else: o_list = dt_list o_list_sort = np.sort(o_list) o_list_sort_idx = np.argsort(o_list) d = np.diff(o_list_so...
[ "def", "dt_cluster", "(", "dt_list", ",", "dt_thresh", "=", "16.0", ")", ":", "if", "not", "isinstance", "(", "dt_list", "[", "0", "]", ",", "float", ")", ":", "o_list", "=", "dt2o", "(", "dt_list", ")", "else", ":", "o_list", "=", "dt_list", "o_list...
36.428571
0.009167
def cartesian(self,subsets=None,step_pixels=100,max_distance_pixels=150,*args,**kwargs): """ Return a class that can be used to create honeycomb plots Args: subsets (list): list of SubsetLogic objects step_pixels (int): distance between hexagons max_distance_...
[ "def", "cartesian", "(", "self", ",", "subsets", "=", "None", ",", "step_pixels", "=", "100", ",", "max_distance_pixels", "=", "150", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "n", "=", "Cartesian", ".", "read_cellframe", "(", "self", ",", ...
55.684211
0.021375
def convert_to_scl(spec, scl_options): """Convert spec into SCL-style spec file using `spec2scl`. Args: spec: (str) a spec file scl_options: (dict) SCL options provided Returns: A converted spec file """ scl_options['skip_functions'] = scl_options['skip_functions'].split(','...
[ "def", "convert_to_scl", "(", "spec", ",", "scl_options", ")", ":", "scl_options", "[", "'skip_functions'", "]", "=", "scl_options", "[", "'skip_functions'", "]", ".", "split", "(", "','", ")", "scl_options", "[", "'meta_spec'", "]", "=", "None", "convertor", ...
33.461538
0.002237
def parsePositionFile(filename): """ Parses Android GPS logger csv file and returns list of dictionaries """ l=[] with open( filename, "rb" ) as theFile: reader = csv.DictReader( theFile ) for line in reader: # Convert the time string to something # a bit more...
[ "def", "parsePositionFile", "(", "filename", ")", ":", "l", "=", "[", "]", "with", "open", "(", "filename", ",", "\"rb\"", ")", "as", "theFile", ":", "reader", "=", "csv", ".", "DictReader", "(", "theFile", ")", "for", "line", "in", "reader", ":", "#...
34.214286
0.018293
def union(self, b): """ Returns bounds that encompass the union of the two. """ mx, my = min(self.x, b.x), min(self.y, b.y) return Bounds(mx, my, max(self.x+self.width, b.x+b.width) - mx, max(self.y+self.height, b.y+b.height) - my)
[ "def", "union", "(", "self", ",", "b", ")", ":", "mx", ",", "my", "=", "min", "(", "self", ".", "x", ",", "b", ".", "x", ")", ",", "min", "(", "self", ".", "y", ",", "b", ".", "y", ")", "return", "Bounds", "(", "mx", ",", "my", ",", "ma...
41
0.010239
def construct_parser(magic_func): """ Construct an argument parser using the function decorations. """ kwds = getattr(magic_func, 'argcmd_kwds', {}) if 'description' not in kwds: kwds['description'] = getattr(magic_func, '__doc__', None) arg_name = real_name(magic_func) parser = MagicArg...
[ "def", "construct_parser", "(", "magic_func", ")", ":", "kwds", "=", "getattr", "(", "magic_func", ",", "'argcmd_kwds'", ",", "{", "}", ")", "if", "'description'", "not", "in", "kwds", ":", "kwds", "[", "'description'", "]", "=", "getattr", "(", "magic_fun...
35.925926
0.001004
def fetch_columns(self, table_name, silent=False): """ Return the column information for :code:`table_name` by executing a :code:`select top 1 * from table_name` query. :param str table_name: The fully-qualified name of the table to retrieve schema for :param bool silent: Silence consol...
[ "def", "fetch_columns", "(", "self", ",", "table_name", ",", "silent", "=", "False", ")", ":", "return", "self", ".", "execute", "(", "\"select top 1 * from {}\"", ".", "format", "(", "table_name", ")", ",", "silent", "=", "silent", ",", "prepare_only", "=",...
56.6
0.008696
def get_volume(self, volume_id): """ Returns a Volume object by its ID. """ return Volume.get_object(api_token=self.token, volume_id=volume_id)
[ "def", "get_volume", "(", "self", ",", "volume_id", ")", ":", "return", "Volume", ".", "get_object", "(", "api_token", "=", "self", ".", "token", ",", "volume_id", "=", "volume_id", ")" ]
35
0.011173
def move(self, new_location): """Move resource to `new_location`""" self._perform_change(change.MoveResource(self, new_location), 'Moving <%s> to <%s>' % (self.path, new_location))
[ "def", "move", "(", "self", ",", "new_location", ")", ":", "self", ".", "_perform_change", "(", "change", ".", "MoveResource", "(", "self", ",", "new_location", ")", ",", "'Moving <%s> to <%s>'", "%", "(", "self", ".", "path", ",", "new_location", ")", ")"...
55.5
0.008889
def _calculate_fnr_fdr(group): """Calculate the false negative rate (1 - sensitivity) and false discovery rate (1 - precision). """ data = {k: d["value"] for k, d in group.set_index("metric").T.to_dict().items()} return pd.DataFrame([{"fnr": data["fn"] / float(data["tp"] + data["fn"]) * 100.0 if data["t...
[ "def", "_calculate_fnr_fdr", "(", "group", ")", ":", "data", "=", "{", "k", ":", "d", "[", "\"value\"", "]", "for", "k", ",", "d", "in", "group", ".", "set_index", "(", "\"metric\"", ")", ".", "T", ".", "to_dict", "(", ")", ".", "items", "(", ")"...
72.5
0.008518
def brent_max(func, a, b, args=(), xtol=1e-5, maxiter=500): """ Uses a jitted version of the maximization routine from SciPy's fminbound. The algorithm is identical except that it's been switched to maximization rather than minimization, and the tests for convergence have been stripped out to allow ...
[ "def", "brent_max", "(", "func", ",", "a", ",", "b", ",", "args", "=", "(", ")", ",", "xtol", "=", "1e-5", ",", "maxiter", "=", "500", ")", ":", "if", "not", "np", ".", "isfinite", "(", "a", ")", ":", "raise", "ValueError", "(", "\"a must be fini...
26.195946
0.000249
def margin_logit_loss(model_logits, label, nb_classes=10, num_classes=None): """Computes difference between logit for `label` and next highest logit. The loss is high when `label` is unlikely (targeted by default). This follows the same interface as `loss_fn` for TensorOptimizer and projected_optimization, i.e...
[ "def", "margin_logit_loss", "(", "model_logits", ",", "label", ",", "nb_classes", "=", "10", ",", "num_classes", "=", "None", ")", ":", "if", "num_classes", "is", "not", "None", ":", "warnings", ".", "warn", "(", "\"`num_classes` is depreciated. Switch to `nb_clas...
43.8
0.008935
def write_map(fo, datum, schema): """Maps are encoded as a series of blocks. Each block consists of a long count value, followed by that many key/value pairs. A block with count zero indicates the end of the map. Each item is encoded per the map's value schema. If a block's count is negative, th...
[ "def", "write_map", "(", "fo", ",", "datum", ",", "schema", ")", ":", "if", "len", "(", "datum", ")", ">", "0", ":", "write_long", "(", "fo", ",", "len", "(", "datum", ")", ")", "vtype", "=", "schema", "[", "'values'", "]", "for", "key", ",", "...
42.235294
0.001362
async def update(self): """ Updates this interface's messages with the latest data. """ if self.update_lock.locked(): return async with self.update_lock: if self.update_lock.locked(): # if this engagement has caused the semaphore to exhau...
[ "async", "def", "update", "(", "self", ")", ":", "if", "self", ".", "update_lock", ".", "locked", "(", ")", ":", "return", "async", "with", "self", ".", "update_lock", ":", "if", "self", ".", "update_lock", ".", "locked", "(", ")", ":", "# if this enga...
35.304348
0.002398
def removeIndexOnAttribute(self, attributeName): ''' removeIndexOnAttribute - Remove an attribute from indexing (for getElementsByAttr function) and remove indexed data. @param attributeName <lowercase str> - An attribute name. Will be lowercased. "name" and "id" will have no effect. ...
[ "def", "removeIndexOnAttribute", "(", "self", ",", "attributeName", ")", ":", "attributeName", "=", "attributeName", ".", "lower", "(", ")", "if", "attributeName", "in", "self", ".", "otherAttributeIndexFunctions", ":", "del", "self", ".", "otherAttributeIndexFuncti...
55.727273
0.009631
def multibox_layer(from_layers, num_classes, sizes=[.2, .95], ratios=[1], normalization=-1, num_channels=[], clip=False, interm_layer=0, steps=[]): """ the basic aggregation module for SSD detection. Takes in multiple layers, generate multiple object detection targets...
[ "def", "multibox_layer", "(", "from_layers", ",", "num_classes", ",", "sizes", "=", "[", ".2", ",", ".95", "]", ",", "ratios", "=", "[", "1", "]", ",", "normalization", "=", "-", "1", ",", "num_channels", "=", "[", "]", ",", "clip", "=", "False", "...
46.605263
0.009122
def point_mid(pt1, pt2): """ Computes the midpoint of the input points. :param pt1: point 1 :type pt1: list, tuple :param pt2: point 2 :type pt2: list, tuple :return: midpoint :rtype: list """ if len(pt1) != len(pt2): raise ValueError("The input points should have the same d...
[ "def", "point_mid", "(", "pt1", ",", "pt2", ")", ":", "if", "len", "(", "pt1", ")", "!=", "len", "(", "pt2", ")", ":", "raise", "ValueError", "(", "\"The input points should have the same dimension\"", ")", "dist_vector", "=", "vector_generate", "(", "pt1", ...
30.25
0.002004
def isExpandKeyEvent(self, keyEvent): """Check if key event should expand rectangular selection""" return keyEvent.modifiers() & Qt.ShiftModifier and \ keyEvent.modifiers() & Qt.AltModifier and \ keyEvent.key() in (Qt.Key_Left, Qt.Key_Right, Qt.Key_Down, Qt.Key_Up, ...
[ "def", "isExpandKeyEvent", "(", "self", ",", "keyEvent", ")", ":", "return", "keyEvent", ".", "modifiers", "(", ")", "&", "Qt", ".", "ShiftModifier", "and", "keyEvent", ".", "modifiers", "(", ")", "&", "Qt", ".", "AltModifier", "and", "keyEvent", ".", "k...
66.166667
0.014925
def otsu (img, bins=64): r""" Otsu's method to find the optimal threshold separating an image into fore- and background. This rather expensive method iterates over a number of thresholds to separate the images histogram into two parts with a minimal intra-class variance. An increase in the...
[ "def", "otsu", "(", "img", ",", "bins", "=", "64", ")", ":", "# cast bins parameter to int", "bins", "=", "int", "(", "bins", ")", "# cast img parameter to scipy arrax", "img", "=", "numpy", ".", "asarray", "(", "img", ")", "# check supplied parameters", "if", ...
30.566667
0.011622
def dump_view(cls, request): """Dumps sitetrees with items using django-smuggler. :param request: :return: """ from smuggler.views import dump_to_response return dump_to_response(request, [MODEL_TREE, MODEL_TREE_ITEM], filename_prefix='sitetrees')
[ "def", "dump_view", "(", "cls", ",", "request", ")", ":", "from", "smuggler", ".", "views", "import", "dump_to_response", "return", "dump_to_response", "(", "request", ",", "[", "MODEL_TREE", ",", "MODEL_TREE_ITEM", "]", ",", "filename_prefix", "=", "'sitetrees'...
36.125
0.010135
def init_xena(api, logger, owner, ip=None, port=57911): """ Create XenaManager object. :param api: cli/rest :param logger: python logger :param owner: owner of the scripting session :param ip: rest server IP :param port: rest server TCP port :return: Xena object :rtype: XenaApp """ ...
[ "def", "init_xena", "(", "api", ",", "logger", ",", "owner", ",", "ip", "=", "None", ",", "port", "=", "57911", ")", ":", "if", "api", "==", "ApiType", ".", "socket", ":", "api_wrapper", "=", "XenaCliWrapper", "(", "logger", ")", "elif", "api", "==",...
30.117647
0.001894
def _update_char_check(self, element, target, docdelta): """Checks whether the specified element should have its character indices updated as part of real-time updating.""" if docdelta != 0: if (element.docstart <= target and element.docend >= target - docdelta): ...
[ "def", "_update_char_check", "(", "self", ",", "element", ",", "target", ",", "docdelta", ")", ":", "if", "docdelta", "!=", "0", ":", "if", "(", "element", ".", "docstart", "<=", "target", "and", "element", ".", "docend", ">=", "target", "-", "docdelta",...
41.818182
0.010638
def sub_links(string,project): ''' Replace links to different parts of the program, formatted as [[name]] or [[name(object-type)]] with the appropriate URL. Can also link to an item's entry in another's page with the syntax [[parent-name:name]]. The object type can be placed in parentheses for e...
[ "def", "sub_links", "(", "string", ",", "project", ")", ":", "LINK_TYPES", "=", "{", "'module'", ":", "'modules'", ",", "'type'", ":", "'types'", ",", "'procedure'", ":", "'procedures'", ",", "'subroutine'", ":", "'procedures'", ",", "'function'", ":", "'pro...
40.971963
0.008686
def reduce_coordination(network, z): r""" """ # Find minimum spanning tree using random weights am = network.create_adjacency_matrix(weights=sp.rand(network.Nt), triu=False) mst = csgraph.minimum_spanning_tree(am, overwrite=True) mst = mst.tocoo() # ...
[ "def", "reduce_coordination", "(", "network", ",", "z", ")", ":", "# Find minimum spanning tree using random weights", "am", "=", "network", ".", "create_adjacency_matrix", "(", "weights", "=", "sp", ".", "rand", "(", "network", ".", "Nt", ")", ",", "triu", "=",...
38.842105
0.001323
def _start_reader(self): """ Read messages from the Win32 pipe server and handle them. """ while True: message = yield From(self.pipe.read_message()) self._process(message)
[ "def", "_start_reader", "(", "self", ")", ":", "while", "True", ":", "message", "=", "yield", "From", "(", "self", ".", "pipe", ".", "read_message", "(", ")", ")", "self", ".", "_process", "(", "message", ")" ]
31.714286
0.008772
def setLineEdit(self, edit): """ Sets the line edit for this widget. :warning If the inputed edit is NOT an instance of XLineEdit, \ this method will destroy the edit and create a new \ XLineEdit instance. :param edit | <X...
[ "def", "setLineEdit", "(", "self", ",", "edit", ")", ":", "if", "edit", "and", "not", "isinstance", "(", "edit", ",", "XLineEdit", ")", ":", "edit", ".", "setParent", "(", "None", ")", "edit", ".", "deleteLater", "(", ")", "edit", "=", "XLineEdit", "...
31.173913
0.009472
def start_image_acquisition(self): """ Starts image acquisition. :return: None. """ if not self._create_ds_at_connection: self._setup_data_streams() # num_required_buffers = self._num_buffers for data_stream in self._data_streams: ...
[ "def", "start_image_acquisition", "(", "self", ")", ":", "if", "not", "self", ".", "_create_ds_at_connection", ":", "self", ".", "_setup_data_streams", "(", ")", "#", "num_required_buffers", "=", "self", ".", "_num_buffers", "for", "data_stream", "in", "self", "...
32.258427
0.001014
def mcc(self): r"""Return Matthews correlation coefficient (MCC). The Matthews correlation coefficient is defined in :cite:`Matthews:1975` as: :math:`\frac{(tp \cdot tn) - (fp \cdot fn)} {\sqrt{(tp + fp)(tp + fn)(tn + fp)(tn + fn)}}` This is equivalent to the geometric ...
[ "def", "mcc", "(", "self", ")", ":", "if", "(", "(", "(", "self", ".", "_tp", "+", "self", ".", "_fp", ")", "*", "(", "self", ".", "_tp", "+", "self", ".", "_fn", ")", "*", "(", "self", ".", "_tn", "+", "self", ".", "_fp", ")", "*", "(", ...
28.825
0.001678
def median(timeseries, segmentlength, noverlap=None, window=None, plan=None): """Calculate a PSD of this `TimeSeries` using a median average method The median average is similar to Welch's method, using a median average rather than mean. Parameters ---------- timeseries : `~gwpy.timeseries.Tim...
[ "def", "median", "(", "timeseries", ",", "segmentlength", ",", "noverlap", "=", "None", ",", "window", "=", "None", ",", "plan", "=", "None", ")", ":", "return", "_lal_spectrum", "(", "timeseries", ",", "segmentlength", ",", "noverlap", "=", "noverlap", ",...
30.058824
0.000948
def adsAddRoute(net_id, ip_address): # type: (SAmsNetId, str) -> None """Establish a new route in the AMS Router. :param pyads.structs.SAmsNetId net_id: net id of routing endpoint :param str ip_address: ip address of the routing endpoint """ add_route = _adsDLL.AdsAddRoute add_route.restyp...
[ "def", "adsAddRoute", "(", "net_id", ",", "ip_address", ")", ":", "# type: (SAmsNetId, str) -> None", "add_route", "=", "_adsDLL", ".", "AdsAddRoute", "add_route", ".", "restype", "=", "ctypes", ".", "c_long", "# Convert ip address to bytes (PY3) and get pointer.", "ip_ad...
30.333333
0.001776
def _flatten_action_profile(action_profile, indptr): """ Flatten the given action profile. Parameters ---------- action_profile : array_like(int or array_like(float, ndim=1)) Profile of actions of the N players, where each player i' action is a pure action (int) or a mixed action (a...
[ "def", "_flatten_action_profile", "(", "action_profile", ",", "indptr", ")", ":", "N", "=", "len", "(", "indptr", ")", "-", "1", "out", "=", "np", ".", "empty", "(", "indptr", "[", "-", "1", "]", ")", "for", "i", "in", "range", "(", "N", ")", ":"...
32.4
0.000856
def run(self): """ Thread loop. """ # construct WebCache object locally thread_id, args, kwargs = self.execute_queue.get_nowait() try: cache_obj = WebCache(*args, **kwargs) except Exception as e: self.exception_queue[thread_id].put_nowait(e) self.loop = False self.execute_queue...
[ "def", "run", "(", "self", ")", ":", "# construct WebCache object locally", "thread_id", ",", "args", ",", "kwargs", "=", "self", ".", "execute_queue", ".", "get_nowait", "(", ")", "try", ":", "cache_obj", "=", "WebCache", "(", "*", "args", ",", "*", "*", ...
29.961538
0.013682
def cli(conf): """ OpenVPN client_disconnect method """ config = init_config(conf) nas_id = config.get('DEFAULT', 'nas_id') secret = config.get('DEFAULT', 'radius_secret') nas_addr = config.get('DEFAULT', 'nas_addr') radius_addr = config.get('DEFAULT', 'radius_addr') radius_acct_port = c...
[ "def", "cli", "(", "conf", ")", ":", "config", "=", "init_config", "(", "conf", ")", "nas_id", "=", "config", ".", "get", "(", "'DEFAULT'", ",", "'nas_id'", ")", "secret", "=", "config", ".", "get", "(", "'DEFAULT'", ",", "'radius_secret'", ")", "nas_a...
35.272727
0.012538
def _to_str(uri: URIRef) -> str: """ Convert a FHIR style URI into a tag name to be used to retrieve data from a JSON representation Example: http://hl7.org/fhir/Provenance.agent.whoReference --> whoReference :param uri: URI to convert :return: tag name """ local_...
[ "def", "_to_str", "(", "uri", ":", "URIRef", ")", "->", "str", ":", "local_name", "=", "str", "(", "uri", ")", ".", "replace", "(", "str", "(", "FHIR", ")", ",", "''", ")", "return", "local_name", ".", "rsplit", "(", "'.'", ",", "1", ")", "[", ...
47.888889
0.01139
def unlock(self, store=True): """Unlocks the achievement. :param bool store: Whether to send data to server immediately (as to get overlay notification). :rtype: bool """ result = self._iface.ach_unlock(self.name) result and store and self._store() return resul...
[ "def", "unlock", "(", "self", ",", "store", "=", "True", ")", ":", "result", "=", "self", ".", "_iface", ".", "ach_unlock", "(", "self", ".", "name", ")", "result", "and", "store", "and", "self", ".", "_store", "(", ")", "return", "result" ]
28.272727
0.009346
def setup(self): """ Setup py3status and spawn i3status/events/modules threads. """ # SIGTSTP will be received from i3bar indicating that all output should # stop and we should consider py3status suspended. It is however # important that any processes using i3 ipc shoul...
[ "def", "setup", "(", "self", ")", ":", "# SIGTSTP will be received from i3bar indicating that all output should", "# stop and we should consider py3status suspended. It is however", "# important that any processes using i3 ipc should continue to receive", "# those events otherwise it can lead to ...
39.639344
0.000605
def queueStream(self, rdds, oneAtATime=True, default=None): """ Create an input stream from a queue of RDDs or list. In each batch, it will process either one or all of the RDDs returned by the queue. .. note:: Changes to the queue after the stream is created will not be recognized. ...
[ "def", "queueStream", "(", "self", ",", "rdds", ",", "oneAtATime", "=", "True", ",", "default", "=", "None", ")", ":", "if", "default", "and", "not", "isinstance", "(", "default", ",", "RDD", ")", ":", "default", "=", "self", ".", "_sc", ".", "parall...
42.714286
0.002453
def add_extension_if_needed(filepath, ext, check_if_exists=False): """Add the extension ext to fpath if it doesn't have it. Parameters ---------- filepath: str File name or path ext: str File extension check_if_exists: bool Returns ------- File name or path with extension...
[ "def", "add_extension_if_needed", "(", "filepath", ",", "ext", ",", "check_if_exists", "=", "False", ")", ":", "if", "not", "filepath", ".", "endswith", "(", "ext", ")", ":", "filepath", "+=", "ext", "if", "check_if_exists", ":", "if", "not", "os", ".", ...
21.185185
0.001672
def get_state(self, channel): """ Ignore channel """ val = None if channel not in self._unit: return val if self._unit[channel] == 'l/h': val = ((1000 * 3600) / (self._delay[channel] * self._pulses[channel])) elif self._unit[channel] == 'm3...
[ "def", "get_state", "(", "self", ",", "channel", ")", ":", "val", "=", "None", "if", "channel", "not", "in", "self", ".", "_unit", ":", "return", "val", "if", "self", ".", "_unit", "[", "channel", "]", "==", "'l/h'", ":", "val", "=", "(", "(", "1...
37.5625
0.008117
def put_motion_detection_xml(self, xml): """ Put request with xml Motion Detection """ _LOGGING.debug('xml:') _LOGGING.debug("%s", xml) headers = DEFAULT_HEADERS headers['Content-Length'] = len(xml) headers['Host'] = self._host response = requests.put(self.motio...
[ "def", "put_motion_detection_xml", "(", "self", ",", "xml", ")", ":", "_LOGGING", ".", "debug", "(", "'xml:'", ")", "_LOGGING", ".", "debug", "(", "\"%s\"", ",", "xml", ")", "headers", "=", "DEFAULT_HEADERS", "headers", "[", "'Content-Length'", "]", "=", "...
37.297297
0.001412
def getTraitCorrCoef(self,term_i=None): """ Return the estimated trait correlation coefficient matrix for term_i (or the total if term_i is None) To retrieve the trait covariance matrix use \see getTraitCovar Args: term_i: index of the random effect term we want to r...
[ "def", "getTraitCorrCoef", "(", "self", ",", "term_i", "=", "None", ")", ":", "cov", "=", "self", ".", "getTraitCovar", "(", "term_i", ")", "stds", "=", "sp", ".", "sqrt", "(", "cov", ".", "diagonal", "(", ")", ")", "[", ":", ",", "sp", ".", "new...
41.142857
0.011885
def _tmgr(self, uid, rmgr, logger, mq_hostname, port, pending_queue, completed_queue): """ **Purpose**: Method to be run by the tmgr process. This method receives a Task from the pending_queue and submits it to the RTS. At all state transititons, they are synced (blocking) with the AppManager ...
[ "def", "_tmgr", "(", "self", ",", "uid", ",", "rmgr", ",", "logger", ",", "mq_hostname", ",", "port", ",", "pending_queue", ",", "completed_queue", ")", ":", "raise", "NotImplementedError", "(", "'_tmgr() method '", "+", "'not implemented in TaskManager for %s'", ...
59.3125
0.011411
async def updateconfig(self): "Reload configurations, remove non-exist servers, add new servers, and leave others unchanged" exists = {} for s in self.connections: exists[(s.protocol.vhost, s.rawurl)] = s self._createServers(self, '', exists = exists) for _,v in exist...
[ "async", "def", "updateconfig", "(", "self", ")", ":", "exists", "=", "{", "}", "for", "s", "in", "self", ".", "connections", ":", "exists", "[", "(", "s", ".", "protocol", ".", "vhost", ",", "s", ".", "rawurl", ")", "]", "=", "s", "self", ".", ...
43.555556
0.015