text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def untrain(self, category, text): """ Untrains a category with a sample of text :param category: the name of the category we want to train :type category: str :param text: the text we want to untrain the category with :type text: str """ try: ...
[ "def", "untrain", "(", "self", ",", "category", ",", "text", ")", ":", "try", ":", "bayes_category", "=", "self", ".", "categories", ".", "get_category", "(", "category", ")", "except", "KeyError", ":", "return", "tokens", "=", "self", ".", "tokenizer", ...
32.727273
19.181818
def channel_open( self, registry_address: PaymentNetworkID, token_address: TokenAddress, partner_address: Address, settle_timeout: BlockTimeout = None, retry_timeout: NetworkTimeout = DEFAULT_RETRY_TIMEOUT, ) -> ChannelID: """ Open a ch...
[ "def", "channel_open", "(", "self", ",", "registry_address", ":", "PaymentNetworkID", ",", "token_address", ":", "TokenAddress", ",", "partner_address", ":", "Address", ",", "settle_timeout", ":", "BlockTimeout", "=", "None", ",", "retry_timeout", ":", "NetworkTimeo...
38.967033
21.274725
def representation_function_compiler(self, func_name): """Generic function can be used to compile __repr__ or __unicode__ or __str__""" def get_col_accessor(col): return ALCHEMY_TEMPLATES.col_accessor.safe_substitute(col=col) def get_col_evaluator(col): return ALCHEMY_T...
[ "def", "representation_function_compiler", "(", "self", ",", "func_name", ")", ":", "def", "get_col_accessor", "(", "col", ")", ":", "return", "ALCHEMY_TEMPLATES", ".", "col_accessor", ".", "safe_substitute", "(", "col", "=", "col", ")", "def", "get_col_evaluator"...
57.0625
35.4375
def trac_tickets(self): ''' Looks for any of the following trac ticket formats in the description field: t12345, t 12345, T12345, T 12345, #12345, # 12345, ticket 12345, TICKET 12345 ''' # ticket_numbers = re.findall(re.compile("([t#]\s?[0-9]{2,})|([t#][0-9]{2,})", re.IGNORE...
[ "def", "trac_tickets", "(", "self", ")", ":", "# ticket_numbers = re.findall(re.compile(\"([t#]\\s?[0-9]{2,})|([t#][0-9]{2,})\", re.IGNORECASE), self.description)", "ticket_numbers", "=", "re", ".", "findall", "(", "r\"^[tT#]\\s?[0-9]+\"", ",", "self", ".", "description", ")", ...
51.5
35.5
def interpret_stats(results): """Generates the string to be shown as updates after the execution of a Cypher query :param results: ``ResultSet`` with the raw results of the execution of the Cypher query """ stats = results.stats contains_updates = stats.pop("contains_updates...
[ "def", "interpret_stats", "(", "results", ")", ":", "stats", "=", "results", ".", "stats", "contains_updates", "=", "stats", ".", "pop", "(", "\"contains_updates\"", ",", "False", ")", "if", "stats", "else", "False", "if", "not", "contains_updates", ":", "re...
37.111111
18.333333
def pop_state(self, idx=None): """ Pops off the most recent state. :param idx: If provided, specifies the index at which the next string begins. """ self.state.pop() if idx is not None: self.str_begin = idx
[ "def", "pop_state", "(", "self", ",", "idx", "=", "None", ")", ":", "self", ".", "state", ".", "pop", "(", ")", "if", "idx", "is", "not", "None", ":", "self", ".", "str_begin", "=", "idx" ]
23.166667
17
def _get_client(): ''' Return cloud client ''' client = salt.cloud.CloudClient( os.path.join(os.path.dirname(__opts__['conf_file']), 'cloud') ) return client
[ "def", "_get_client", "(", ")", ":", "client", "=", "salt", ".", "cloud", ".", "CloudClient", "(", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "__opts__", "[", "'conf_file'", "]", ")", ",", "'cloud'", ")", ")", "ret...
24.25
24
def create_from_data_channel(cls, data_channel): """Scan the data tree on the given data_channel to create a corresponding InputSetGenerator tree. """ gather_depth = cls._get_gather_depth(data_channel) generator = InputSetGeneratorNode() for (data_path, data_node) in dat...
[ "def", "create_from_data_channel", "(", "cls", ",", "data_channel", ")", ":", "gather_depth", "=", "cls", ".", "_get_gather_depth", "(", "data_channel", ")", "generator", "=", "InputSetGeneratorNode", "(", ")", "for", "(", "data_path", ",", "data_node", ")", "in...
45.333333
14.666667
def get_set(self, project, articleset, **filters): """List the articlesets in a project""" url = URL.articleset.format(**locals()) return self.request(url, **filters)
[ "def", "get_set", "(", "self", ",", "project", ",", "articleset", ",", "*", "*", "filters", ")", ":", "url", "=", "URL", ".", "articleset", ".", "format", "(", "*", "*", "locals", "(", ")", ")", "return", "self", ".", "request", "(", "url", ",", ...
46.75
5
def create_vs(lb, name, ip, port, protocol, profile, pool_name): ''' Create a virtual server CLI Examples: .. code-block:: bash salt-run f5.create_vs lbalancer vs_name 10.0.0.1 80 tcp http poolname ''' if __opts__['load_balancers'].get(lb, None): (username, password) = list(__...
[ "def", "create_vs", "(", "lb", ",", "name", ",", "ip", ",", "port", ",", "protocol", ",", "profile", ",", "pool_name", ")", ":", "if", "__opts__", "[", "'load_balancers'", "]", ".", "get", "(", "lb", ",", "None", ")", ":", "(", "username", ",", "pa...
30.222222
27.444444
def load_params_from_file(self, fname: str): """ Loads and sets model parameters from file. :param fname: Path to load parameters from. """ utils.check_condition(os.path.exists(fname), "No model parameter file found under %s. " ...
[ "def", "load_params_from_file", "(", "self", ",", "fname", ":", "str", ")", ":", "utils", ".", "check_condition", "(", "os", ".", "path", ".", "exists", "(", "fname", ")", ",", "\"No model parameter file found under %s. \"", "\"This is either not a model directory or ...
66
35.2
def get_route_templates(self): """ Generate Openshift route templates or playbook tasks. Each port on a service definition found in container.yml represents an externally exposed port. """ def _get_published_ports(service_config): result = [] for port in s...
[ "def", "get_route_templates", "(", "self", ")", ":", "def", "_get_published_ports", "(", "service_config", ")", ":", "result", "=", "[", "]", "for", "port", "in", "service_config", ".", "get", "(", "'ports'", ",", "[", "]", ")", ":", "protocol", "=", "'T...
42.290323
19.16129
def _create_directory(cls, directory, loop=False): """ Creates the given directory if it does not exists. :param directory: The directory to create. :type directory: str :param loop: Tell us if we are in the creation loop or not. :type loop: bool """ if...
[ "def", "_create_directory", "(", "cls", ",", "directory", ",", "loop", "=", "False", ")", ":", "if", "not", "loop", "and", "PyFunceble", ".", "directory_separator", "in", "directory", ":", "# * We are not in the loop.", "# and", "# * The directory separator in the giv...
35.25
21.159091
def save(self, commit=True): """ Saves the instance. """ if self.instance.pk: # First handle updates post = super().save(commit=False) post.updated_by = self.user post.updates_count = F('updates_count') + 1 else: post = Post( ...
[ "def", "save", "(", "self", ",", "commit", "=", "True", ")", ":", "if", "self", ".", "instance", ".", "pk", ":", "# First handle updates", "post", "=", "super", "(", ")", ".", "save", "(", "commit", "=", "False", ")", "post", ".", "updated_by", "=", ...
36.766667
17.866667
def fit_interval_censoring( self, lower_bound, upper_bound, event_observed=None, timeline=None, label=None, alpha=None, ci_labels=None, show_progress=False, entry=None, weights=None, ): # pylint: disable=too-many-arguments ...
[ "def", "fit_interval_censoring", "(", "self", ",", "lower_bound", ",", "upper_bound", ",", "event_observed", "=", "None", ",", "timeline", "=", "None", ",", "label", "=", "None", ",", "alpha", "=", "None", ",", "ci_labels", "=", "None", ",", "show_progress",...
45.363636
28.636364
def grep(source, regex, stop_on_first=False): """Grep the constant pool of all classes in source.""" loader = ClassLoader(source, max_cache=-1) r = re.compile(regex) def _matches(constant): return r.match(constant.value) for klass in loader.classes: it = loader.search_constant_pool...
[ "def", "grep", "(", "source", ",", "regex", ",", "stop_on_first", "=", "False", ")", ":", "loader", "=", "ClassLoader", "(", "source", ",", "max_cache", "=", "-", "1", ")", "r", "=", "re", ".", "compile", "(", "regex", ")", "def", "_matches", "(", ...
31.928571
16.071429
def split_evenly(n, chunks): """Split an integer into evenly distributed list >>> split_evenly(7, 3) [3, 2, 2] >>> split_evenly(12, 3) [4, 4, 4] >>> split_evenly(35, 10) [4, 4, 4, 4, 4, 3, 3, 3, 3, 3] >>> split_evenly(1, 2) Traceback (most recent call last): ... Chunk...
[ "def", "split_evenly", "(", "n", ",", "chunks", ")", ":", "if", "n", "<", "chunks", ":", "raise", "ChunkingError", "(", "\"Number of chunks is greater than number\"", ")", "if", "n", "%", "chunks", "==", "0", ":", "# Either we can evenly split or only 1 chunk left",...
27.384615
19.730769
def spielman_wr(self, norm=True): """Returns a list of site-specific omega values calculated from the `ExpCM`. Args: `norm` (bool) If `True`, normalize the `omega_r` values by the ExpCM gene-wide `omega`. Returns: ...
[ "def", "spielman_wr", "(", "self", ",", "norm", "=", "True", ")", ":", "wr", "=", "[", "]", "for", "r", "in", "range", "(", "self", ".", "nsites", ")", ":", "num", "=", "0", "den", "=", "0", "for", "i", "in", "range", "(", "N_CODON", ")", ":"...
40.244444
21.511111
def get_configuration(dev): r"""Get the current active configuration of the device. dev is the Device object to which the request will be sent to. This function differs from the Device.get_active_configuration method because the later may use cached data, while this function always does a devi...
[ "def", "get_configuration", "(", "dev", ")", ":", "bmRequestType", "=", "util", ".", "build_request_type", "(", "util", ".", "CTRL_IN", ",", "util", ".", "CTRL_TYPE_STANDARD", ",", "util", ".", "CTRL_RECIPIENT_DEVICE", ")", "return", "dev", ".", "ctrl_transfer",...
34.315789
15.157895
def clamp_within_range(self, x, y): """ Clamp x and y so that they fall within range of the tilemap. """ x = int(x) y = int(y) if x < 0: x = 0 if y < 0: y = 0 if x > self.size_in_tiles.X: x = self.size_in_tiles.X ...
[ "def", "clamp_within_range", "(", "self", ",", "x", ",", "y", ")", ":", "x", "=", "int", "(", "x", ")", "y", "=", "int", "(", "y", ")", "if", "x", "<", "0", ":", "x", "=", "0", "if", "y", "<", "0", ":", "y", "=", "0", "if", "x", ">", ...
23.058824
16.823529
def get_rudder_scores_vs_background(self): ''' Returns ------- pd.DataFrame of rudder scores vs background ''' df = self.get_term_and_background_counts() corpus_percentiles = self._get_percentiles_from_freqs(df['corpus']) background_percentiles = self._get...
[ "def", "get_rudder_scores_vs_background", "(", "self", ")", ":", "df", "=", "self", ".", "get_term_and_background_counts", "(", ")", "corpus_percentiles", "=", "self", ".", "_get_percentiles_from_freqs", "(", "df", "[", "'corpus'", "]", ")", "background_percentiles", ...
46.538462
26.692308
def _get_seqprop_to_seqprop_alignment(self, seqprop1, seqprop2): """Return the alignment stored in self.sequence_alignments given a seqprop + another seqprop""" if isinstance(seqprop1, str): seqprop1_id = seqprop1 else: seqprop1_id = seqprop1.id if isinstance(seqp...
[ "def", "_get_seqprop_to_seqprop_alignment", "(", "self", ",", "seqprop1", ",", "seqprop2", ")", ":", "if", "isinstance", "(", "seqprop1", ",", "str", ")", ":", "seqprop1_id", "=", "seqprop1", "else", ":", "seqprop1_id", "=", "seqprop1", ".", "id", "if", "isi...
40.833333
19.222222
def handle_basic_executor_options(options, parser): """Handle the options specified by add_basic_executor_options().""" # setup logging logLevel = logging.INFO if options.debug: logLevel = logging.DEBUG elif options.quiet: logLevel = logging.WARNING util.setup_logging(level=logLe...
[ "def", "handle_basic_executor_options", "(", "options", ",", "parser", ")", ":", "# setup logging", "logLevel", "=", "logging", ".", "INFO", "if", "options", ".", "debug", ":", "logLevel", "=", "logging", ".", "DEBUG", "elif", "options", ".", "quiet", ":", "...
35.111111
10.777778
def format(self, record): """ Format the record using the corresponding formatter. """ if record.levelno == DEBUG: return self.debug_formatter.format(record) if record.levelno == INFO: return self.info_formatter.format(record) if record.levelno == ...
[ "def", "format", "(", "self", ",", "record", ")", ":", "if", "record", ".", "levelno", "==", "DEBUG", ":", "return", "self", ".", "debug_formatter", ".", "format", "(", "record", ")", "if", "record", ".", "levelno", "==", "INFO", ":", "return", "self",...
40
9.285714
def _client_send(self, msg): """Sends an Rpc message through the connection. Args: msg: string, the message to send. Raises: Error: a socket error occurred during the send. """ try: self._client.write(msg.encode("utf8") + b'\n') s...
[ "def", "_client_send", "(", "self", ",", "msg", ")", ":", "try", ":", "self", ".", "_client", ".", "write", "(", "msg", ".", "encode", "(", "\"utf8\"", ")", "+", "b'\\n'", ")", "self", ".", "_client", ".", "flush", "(", ")", "self", ".", "log", "...
31.111111
17.777778
def GetPixelColor(x: int, y: int, handle: int = 0) -> int: """ Get pixel color of a native window. x: int. y: int. handle: int, the handle of a native window. Return int, the bgr value of point (x,y). r = bgr & 0x0000FF g = (bgr & 0x00FF00) >> 8 b = (bgr & 0xFF0000) >> 16 If hand...
[ "def", "GetPixelColor", "(", "x", ":", "int", ",", "y", ":", "int", ",", "handle", ":", "int", "=", "0", ")", "->", "int", ":", "hdc", "=", "ctypes", ".", "windll", ".", "user32", ".", "GetWindowDC", "(", "ctypes", ".", "c_void_p", "(", "handle", ...
38.3
17.4
def _unlock(self, name, client_id, request_id): """Handles unlocking Complains if a non-existent lock should be released or if a lock should be released that was acquired by another client before. """ if name in self._locks: other_client_id, other_request_id...
[ "def", "_unlock", "(", "self", ",", "name", ",", "client_id", ",", "request_id", ")", ":", "if", "name", "in", "self", ".", "_locks", ":", "other_client_id", ",", "other_request_id", "=", "self", ".", "_locks", "[", "name", "]", "if", "other_client_id", ...
46.068966
19.758621
def _assign_method(self, resource_class, method_type): """ Using reflection, assigns a new method to this class. Args: resource_class: A resource class method_type: The HTTP method type """ """ If we assigned the same method to each method, it's ...
[ "def", "_assign_method", "(", "self", ",", "resource_class", ",", "method_type", ")", ":", "\"\"\"\n If we assigned the same method to each method, it's the same\n method in memory, so we need one for each acceptable HTTP method.\n \"\"\"", "method_name", "=", "resourc...
38.213333
17.386667
def normalize_dates(): """Experiment to make sense of TLG dates. TODO: start here, parse everything with pass """ _dict = get_date_author() for tlg_date in _dict: date = {} if tlg_date == 'Varia': #give a homer-to-byz date for 'varia' pass elif tlg_dat...
[ "def", "normalize_dates", "(", ")", ":", "_dict", "=", "get_date_author", "(", ")", "for", "tlg_date", "in", "_dict", ":", "date", "=", "{", "}", "if", "tlg_date", "==", "'Varia'", ":", "#give a homer-to-byz date for 'varia'", "pass", "elif", "tlg_date", "==",...
26
15.111111
def help_center_category_translations_missing(self, category_id, **kwargs): "https://developer.zendesk.com/rest_api/docs/help_center/translations#list-missing-translations" api_path = "/api/v2/help_center/categories/{category_id}/translations/missing.json" api_path = api_path.format(category_id=...
[ "def", "help_center_category_translations_missing", "(", "self", ",", "category_id", ",", "*", "*", "kwargs", ")", ":", "api_path", "=", "\"/api/v2/help_center/categories/{category_id}/translations/missing.json\"", "api_path", "=", "api_path", ".", "format", "(", "category_...
74.6
34.6
def tokenize_number(val, line): """Parse val correctly into int or float.""" try: num = int(val) typ = TokenType.int except ValueError: num = float(val) typ = TokenType.float return {'type': typ, 'value': num, 'line': line}
[ "def", "tokenize_number", "(", "val", ",", "line", ")", ":", "try", ":", "num", "=", "int", "(", "val", ")", "typ", "=", "TokenType", ".", "int", "except", "ValueError", ":", "num", "=", "float", "(", "val", ")", "typ", "=", "TokenType", ".", "floa...
26.3
16.9
def number_of_nodes(self, t=None): """Return the number of nodes in the t snpashot of a dynamic graph. Parameters ---------- t : snapshot id (default=None) If None return the number of nodes in the flattened graph. Returns ------- nnodes : int ...
[ "def", "number_of_nodes", "(", "self", ",", "t", "=", "None", ")", ":", "if", "t", "is", "None", ":", "return", "len", "(", "self", ".", "_node", ")", "else", ":", "nds", "=", "sum", "(", "[", "1", "for", "n", "in", "self", ".", "degree", "(", ...
25.7
21.366667
def get_name(self): """Get name based on 4 class attributes Each attribute is substituted by '' if attribute does not exist :return: dependent_host_name/dependent_service_description..host_name/service_description :rtype: str TODO: Clean this function (use format for string) ...
[ "def", "get_name", "(", "self", ")", ":", "return", "getattr", "(", "self", ",", "'dependent_host_name'", ",", "''", ")", "+", "'/'", "+", "getattr", "(", "self", ",", "'dependent_service_description'", ",", "''", ")", "+", "'..'", "+", "getattr", "(", "...
46.833333
22.333333
def get_fastq_files(data): """Retrieve fastq files for the given lane, ready to process. """ assert "files" in data, "Did not find `files` in input; nothing to process" ready_files = [] should_gzip = True # Bowtie does not accept gzipped fastq if 'bowtie' in data['reference'].keys(): ...
[ "def", "get_fastq_files", "(", "data", ")", ":", "assert", "\"files\"", "in", "data", ",", "\"Did not find `files` in input; nothing to process\"", "ready_files", "=", "[", "]", "should_gzip", "=", "True", "# Bowtie does not accept gzipped fastq", "if", "'bowtie'", "in", ...
47
21
def merge_from(self, other): """Merge information from another PhoneNumber object into this one.""" if other.country_code is not None: self.country_code = other.country_code if other.national_number is not None: self.national_number = other.national_number if othe...
[ "def", "merge_from", "(", "self", ",", "other", ")", ":", "if", "other", ".", "country_code", "is", "not", "None", ":", "self", ".", "country_code", "=", "other", ".", "country_code", "if", "other", ".", "national_number", "is", "not", "None", ":", "self...
55.166667
14.611111
def detect_stream_mode(stream): ''' detect_stream_mode - Detect the mode on a given stream @param stream <object> - A stream object If "mode" is present, that will be used. @return <type> - "Bytes" type or "str" type ''' # If "Mode" is present, pull from that i...
[ "def", "detect_stream_mode", "(", "stream", ")", ":", "# If \"Mode\" is present, pull from that", "if", "hasattr", "(", "stream", ",", "'mode'", ")", ":", "if", "'b'", "in", "stream", ".", "mode", ":", "return", "bytes", "elif", "'t'", "in", "stream", ".", "...
26.548387
17.774194
def create_git_commit(self, message, tree, parents, author=github.GithubObject.NotSet, committer=github.GithubObject.NotSet): """ :calls: `POST /repos/:owner/:repo/git/commits <http://developer.github.com/v3/git/commits>`_ :param message: string :param tree: :class:`github.GitTree.GitTre...
[ "def", "create_git_commit", "(", "self", ",", "message", ",", "tree", ",", "parents", ",", "author", "=", "github", ".", "GithubObject", ".", "NotSet", ",", "committer", "=", "github", ".", "GithubObject", ".", "NotSet", ")", ":", "assert", "isinstance", "...
55.433333
25.966667
def to_match(self): """Return a unicode object with the MATCH representation of this BetweenClause.""" template = u'({field_name} BETWEEN {lower_bound} AND {upper_bound})' return template.format( field_name=self.field.to_match(), lower_bound=self.lower_bound.to_match(), ...
[ "def", "to_match", "(", "self", ")", ":", "template", "=", "u'({field_name} BETWEEN {lower_bound} AND {upper_bound})'", "return", "template", ".", "format", "(", "field_name", "=", "self", ".", "field", ".", "to_match", "(", ")", ",", "lower_bound", "=", "self", ...
52.142857
13.571429
def readInfoElement(self, infoElement, instanceObject): """ Read the info element. :: <info/> <info"> <location/> </info> """ infoLocation = self.locationFromElement(infoElement) instanceObject.addInfo(in...
[ "def", "readInfoElement", "(", "self", ",", "infoElement", ",", "instanceObject", ")", ":", "infoLocation", "=", "self", ".", "locationFromElement", "(", "infoElement", ")", "instanceObject", ".", "addInfo", "(", "infoLocation", ",", "copySourceName", "=", "self",...
25
22.928571
def add_cert(self, cert): """ Explicitely adds certificate to set of trusted in the store @param cert - X509 object to add """ if not isinstance(cert, X509): raise TypeError("cert should be X509") libcrypto.X509_STORE_add_cert(self.store, cert.cert)
[ "def", "add_cert", "(", "self", ",", "cert", ")", ":", "if", "not", "isinstance", "(", "cert", ",", "X509", ")", ":", "raise", "TypeError", "(", "\"cert should be X509\"", ")", "libcrypto", ".", "X509_STORE_add_cert", "(", "self", ".", "store", ",", "cert"...
37.75
9.25
def gene_by_protein_id(self, protein_id): """ Get the gene ID associated with the given protein ID, return its Gene object """ gene_id = self.gene_id_of_protein_id(protein_id) return self.gene_by_id(gene_id)
[ "def", "gene_by_protein_id", "(", "self", ",", "protein_id", ")", ":", "gene_id", "=", "self", ".", "gene_id_of_protein_id", "(", "protein_id", ")", "return", "self", ".", "gene_by_id", "(", "gene_id", ")" ]
35.571429
7
def _config_parser_constrained(self, read_only): """:return: Config Parser constrained to our submodule in read or write mode""" try: pc = self.parent_commit except ValueError: pc = None # end handle empty parent repository parser = self._config_parser(sel...
[ "def", "_config_parser_constrained", "(", "self", ",", "read_only", ")", ":", "try", ":", "pc", "=", "self", ".", "parent_commit", "except", "ValueError", ":", "pc", "=", "None", "# end handle empty parent repository", "parser", "=", "self", ".", "_config_parser",...
43.2
12.9
def add_vts(self, task_name, targets, cache_key, valid, phase): """ Add a single VersionedTargetSet entry to the report. :param InvalidationCacheManager cache_manager: :param CacheKey cache_key: :param bool valid: :param string phase: """ if task_name not in self._task_reports: self.ad...
[ "def", "add_vts", "(", "self", ",", "task_name", ",", "targets", ",", "cache_key", ",", "valid", ",", "phase", ")", ":", "if", "task_name", "not", "in", "self", ".", "_task_reports", ":", "self", ".", "add_task", "(", "task_name", ")", "self", ".", "_t...
40
12.1
def _onNavigate(self, index): '''Handle selection of path segment.''' if index > 0: self.setLocation( self._locationWidget.itemData(index), interactive=True )
[ "def", "_onNavigate", "(", "self", ",", "index", ")", ":", "if", "index", ">", "0", ":", "self", ".", "setLocation", "(", "self", ".", "_locationWidget", ".", "itemData", "(", "index", ")", ",", "interactive", "=", "True", ")" ]
34.833333
17.5
def _get_from_cache(self, sector, scale, eft, basis): """Try to load a set of Wilson coefficients from the cache, else return None.""" try: return self._cache[eft][scale][basis][sector] except KeyError: return None
[ "def", "_get_from_cache", "(", "self", ",", "sector", ",", "scale", ",", "eft", ",", "basis", ")", ":", "try", ":", "return", "self", ".", "_cache", "[", "eft", "]", "[", "scale", "]", "[", "basis", "]", "[", "sector", "]", "except", "KeyError", ":...
37.714286
13
def betweenness_centrality(self, normalized=True): """ Calculates betweenness centrality and returns an node id -> weight dictionary. Node betweenness weights are updated in the process. """ bc = proximity.brandes_betweenness_centrality(self, normalized) for id, w in bc.iteritems...
[ "def", "betweenness_centrality", "(", "self", ",", "normalized", "=", "True", ")", ":", "bc", "=", "proximity", ".", "brandes_betweenness_centrality", "(", "self", ",", "normalized", ")", "for", "id", ",", "w", "in", "bc", ".", "iteritems", "(", ")", ":", ...
51.571429
15.142857
def print_entitlements(opts, data, page_info=None, show_list_info=True): """Print entitlements as a table or output in another format.""" if utils.maybe_print_as_json(opts, data, page_info): return headers = ["Name", "Token", "Created / Updated", "Identifier"] rows = [] for entitlement in ...
[ "def", "print_entitlements", "(", "opts", ",", "data", ",", "page_info", "=", "None", ",", "show_list_info", "=", "True", ")", ":", "if", "utils", ".", "maybe_print_as_json", "(", "opts", ",", "data", ",", "page_info", ")", ":", "return", "headers", "=", ...
33.027778
25.194444
def _create_co_virtual_idp(self, context): """ Create a virtual IdP to represent the CO. :type context: The current context :rtype: saml.server.Server :param context: :return: An idp server """ co_name = self._get_co_name(context) context.decorat...
[ "def", "_create_co_virtual_idp", "(", "self", ",", "context", ")", ":", "co_name", "=", "self", ".", "_get_co_name", "(", "context", ")", "context", ".", "decorate", "(", "self", ".", "KEY_CO_NAME", ",", "co_name", ")", "# Verify that we are configured for this CO...
43
20.813953
def parse_list_header(value): """Parse lists as described by RFC 2068 Section 2. In particular, parse comma-separated lists where the elements of the list may include quoted-strings. A quoted-string could contain a comma. A non-quoted string could have quotes in the middle. Quotes are removed au...
[ "def", "parse_list_header", "(", "value", ")", ":", "result", "=", "[", "]", "for", "item", "in", "_parse_list_header", "(", "value", ")", ":", "if", "item", "[", ":", "1", "]", "==", "item", "[", "-", "1", ":", "]", "==", "'\"'", ":", "item", "=...
33.793103
19.827586
def echo_error(root_resource, message): """Generate an error, but we get to set the error message.""" params = dict(message=message) return root_resource.get(ECHO_ERROR_PATH, params)
[ "def", "echo_error", "(", "root_resource", ",", "message", ")", ":", "params", "=", "dict", "(", "message", "=", "message", ")", "return", "root_resource", ".", "get", "(", "ECHO_ERROR_PATH", ",", "params", ")" ]
46.25
5
def compare_vm_configs(new_config, current_config): ''' Compares virtual machine current and new configuration, the current is the one which is deployed now, and the new is the target config. Returns the differences between the objects in a dictionary, the keys are the configuration parameter keys a...
[ "def", "compare_vm_configs", "(", "new_config", ",", "current_config", ")", ":", "diffs", "=", "{", "}", "keys", "=", "set", "(", "new_config", ".", "keys", "(", ")", ")", "# These values identify the virtual machine, comparison is unnecessary", "keys", ".", "discar...
40.06383
18.191489
def merge_upwards_if_smaller_than(self, small_size, a_or_u): """After prune_if_smaller_than is run, we may still have excess nodes. For example, with a small_size of 609710690: 7 /* 28815419 /data/* 32 /data/srv/* 925746...
[ "def", "merge_upwards_if_smaller_than", "(", "self", ",", "small_size", ",", "a_or_u", ")", ":", "# Assert that we're not messing things up.", "prev_app_size", "=", "self", ".", "app_size", "(", ")", "prev_use_size", "=", "self", ".", "use_size", "(", ")", "small_no...
37.47619
17.428571
def expire(self, current_time=None): """Expire any old entries `current_time` Optional time to be used to clean up queue (can be used in unit tests) """ if not self._queue: return if current_time is None: current_time = time() while ...
[ "def", "expire", "(", "self", ",", "current_time", "=", "None", ")", ":", "if", "not", "self", ".", "_queue", ":", "return", "if", "current_time", "is", "None", ":", "current_time", "=", "time", "(", ")", "while", "self", ".", "_queue", ":", "# Get top...
31.837209
18.395349
def enforce_filetype_file(form, field): '''Only allowed domains in resource.url when filetype is file''' if form._fields.get('filetype').data != RESOURCE_FILETYPE_FILE: return domain = urlparse(field.data).netloc allowed_domains = current_app.config['RESOURCES_FILE_ALLOWED_DOMAINS'] allowed_...
[ "def", "enforce_filetype_file", "(", "form", ",", "field", ")", ":", "if", "form", ".", "_fields", ".", "get", "(", "'filetype'", ")", ".", "data", "!=", "RESOURCE_FILETYPE_FILE", ":", "return", "domain", "=", "urlparse", "(", "field", ".", "data", ")", ...
47.875
19.5
def clean(file_, imports): """Remove modules that aren't imported in project from file.""" modules_not_imported = compare_modules(file_, imports) re_remove = re.compile("|".join(modules_not_imported)) to_write = [] try: f = open_func(file_, "r+") except OSError: logging.error("F...
[ "def", "clean", "(", "file_", ",", "imports", ")", ":", "modules_not_imported", "=", "compare_modules", "(", "file_", ",", "imports", ")", "re_remove", "=", "re", ".", "compile", "(", "\"|\"", ".", "join", "(", "modules_not_imported", ")", ")", "to_write", ...
27.291667
20.75
def find_by_localpath(self, path): """ Returns the repo with the specified local <path> """ # note that the paths in self.jsondata were already _homepath2real()'d # in the class' __init__() resolved = _homepath2real(path) for row in self.jsondata: if r...
[ "def", "find_by_localpath", "(", "self", ",", "path", ")", ":", "# note that the paths in self.jsondata were already _homepath2real()'d", "# in the class' __init__()", "resolved", "=", "_homepath2real", "(", "path", ")", "for", "row", "in", "self", ".", "jsondata", ":", ...
40.4
10.2
def get_new_working_set(self): """ Get a new list of IPs to work with from the queue. This returns None if there is no update. Read all the messages from the queue on which we get the IP addresses that we have to monitor. We will ignore all of them, except the last one,...
[ "def", "get_new_working_set", "(", "self", ")", ":", "new_list_of_ips", "=", "None", "while", "True", ":", "try", ":", "new_list_of_ips", "=", "self", ".", "q_monitor_ips", ".", "get_nowait", "(", ")", "self", ".", "q_monitor_ips", ".", "task_done", "(", ")"...
38.857143
19.785714
def qualified_name(self): '''return the fully qualified name (`<module>.<struct>#<field>`)''' return '{0}.{1}#{2}'.format(self.module.name, self.struct.name, self.name)
[ "def", "qualified_name", "(", "self", ")", ":", "return", "'{0}.{1}#{2}'", ".", "format", "(", "self", ".", "module", ".", "name", ",", "self", ".", "struct", ".", "name", ",", "self", ".", "name", ")" ]
60.666667
30.666667
def _relay_message(self, message): """ Relay messages from the forum on the server to the client represented by this actor. """ info("relaying message: {message}") if not message.was_sent_by(self._id_factory): self.pipe.send(message) self.pipe.de...
[ "def", "_relay_message", "(", "self", ",", "message", ")", ":", "info", "(", "\"relaying message: {message}\"", ")", "if", "not", "message", ".", "was_sent_by", "(", "self", ".", "_id_factory", ")", ":", "self", ".", "pipe", ".", "send", "(", "message", ")...
31.8
13.2
def resp_set_wififirmware(self, resp): """Default callback for get_wififirmware """ if resp: self.wifi_firmware_version = float(str(str(resp.version >> 16) + "." + str(resp.version & 0xff))) self.wifi_firmware_build_timestamp = resp.build
[ "def", "resp_set_wififirmware", "(", "self", ",", "resp", ")", ":", "if", "resp", ":", "self", ".", "wifi_firmware_version", "=", "float", "(", "str", "(", "str", "(", "resp", ".", "version", ">>", "16", ")", "+", "\".\"", "+", "str", "(", "resp", "....
46.833333
19
def calculate_sync_order(oscillator_phases): """! @brief Calculates level of global synchronization (order parameter) for input phases. @details This parameter is tend 1.0 when the oscillatory network close to global synchronization and it tend to 0.0 when desynchronizatio...
[ "def", "calculate_sync_order", "(", "oscillator_phases", ")", ":", "exp_amount", "=", "0.0", "average_phase", "=", "0.0", "for", "phase", "in", "oscillator_phases", ":", "exp_amount", "+=", "math", ".", "expm1", "(", "abs", "(", "1j", "*", "phase", ")", ")",...
41.48
26.48
def cast(cls, value_type, value, visitor=None, **kwargs): """Cast is for visitors where you are visiting some random data structure (perhaps returned by a previous ``VisitorPattern.visit()`` operation), and you want to convert back to the value type. This function also takes positional ...
[ "def", "cast", "(", "cls", ",", "value_type", ",", "value", ",", "visitor", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "visitor", "is", "None", ":", "visitor", "=", "cls", ".", "Visitor", "(", "cls", ".", "grok", ",", "cls", ".", "reve...
36.045455
19.227273
def secure_required(view_func): """ Decorator to switch an url from http to https. If a view is accessed through http and this decorator is applied to that view, than it will return a permanent redirect to the secure (https) version of the same view. The decorator also must check that ``USEREN...
[ "def", "secure_required", "(", "view_func", ")", ":", "def", "_wrapped_view", "(", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "not", "request", ".", "is_secure", "(", ")", ":", "if", "getattr", "(", "settings", ",", "'USERENA...
45.761905
25.095238
def fetch(self): """ Fetch a ExecutionInstance :returns: Fetched ExecutionInstance :rtype: twilio.rest.studio.v1.flow.execution.ExecutionInstance """ params = values.of({}) payload = self._version.fetch( 'GET', self._uri, para...
[ "def", "fetch", "(", "self", ")", ":", "params", "=", "values", ".", "of", "(", "{", "}", ")", "payload", "=", "self", ".", "_version", ".", "fetch", "(", "'GET'", ",", "self", ".", "_uri", ",", "params", "=", "params", ",", ")", "return", "Execu...
23.857143
17.285714
def _path_factory(check): """Create a function that checks paths.""" @functools.wraps(check) def validator(paths): if isinstance(paths, str): check(paths) elif isinstance(paths, collections.Sequence): for path in paths: check(path) else: ...
[ "def", "_path_factory", "(", "check", ")", ":", "@", "functools", ".", "wraps", "(", "check", ")", "def", "validator", "(", "paths", ")", ":", "if", "isinstance", "(", "paths", ",", "str", ")", ":", "check", "(", "paths", ")", "elif", "isinstance", "...
28.5
18.785714
def get_meta(self, name, meta_key=None): '''Get the ``content`` attribute of a meta tag ``name``. For example:: head.get_meta('decription') returns the ``content`` attribute of the meta tag with attribute ``name`` equal to ``description`` or ``None``. If a differen...
[ "def", "get_meta", "(", "self", ",", "name", ",", "meta_key", "=", "None", ")", ":", "meta_key", "=", "meta_key", "or", "'name'", "for", "child", "in", "self", ".", "meta", ".", "_children", ":", "if", "isinstance", "(", "child", ",", "Html", ")", "a...
36.944444
20.944444
def _update(self, rect, delta_y, force_update_margins=False): """ Updates panels """ helper = TextHelper(self.editor) if not self: return for zones_id, zone in self._panels.items(): if zones_id == Panel.Position.TOP or \ zones_id == Panel.Position.B...
[ "def", "_update", "(", "self", ",", "rect", ",", "delta_y", ",", "force_update_margins", "=", "False", ")", ":", "helper", "=", "TextHelper", "(", "self", ".", "editor", ")", "if", "not", "self", ":", "return", "for", "zones_id", ",", "zone", "in", "se...
45.761905
12.714286
def marshal_with(schema, code='default', description='', inherit=None, apply=None): """Marshal the return value of the decorated view function using the specified schema. Usage: .. code-block:: python class PetSchema(Schema): class Meta: fields = ('name', 'category...
[ "def", "marshal_with", "(", "schema", ",", "code", "=", "'default'", ",", "description", "=", "''", ",", "inherit", "=", "None", ",", "apply", "=", "None", ")", ":", "def", "wrapper", "(", "func", ")", ":", "options", "=", "{", "code", ":", "{", "'...
31.75
20.46875
def isInstrumentAllowed(self, instrument): """Checks if the specified instrument can be set for this analysis, either if the instrument was assigned directly (by using "Allows instrument entry of results") or indirectly via Method ("Allows manual entry of results") in Analysis Service Ed...
[ "def", "isInstrumentAllowed", "(", "self", ",", "instrument", ")", ":", "if", "isinstance", "(", "instrument", ",", "str", ")", ":", "uid", "=", "instrument", "else", ":", "uid", "=", "instrument", ".", "UID", "(", ")", "return", "uid", "in", "self", "...
43.875
16.75
def safe_execute_script(self, script): """ When executing a script that contains a jQuery command, it's important that the jQuery library has been loaded first. This method will load jQuery if it wasn't already loaded. """ try: self.execute_script(script) exce...
[ "def", "safe_execute_script", "(", "self", ",", "script", ")", ":", "try", ":", "self", ".", "execute_script", "(", "script", ")", "except", "Exception", ":", "# The likely reason this fails is because: \"jQuery is not defined\"", "self", ".", "activate_jquery", "(", ...
52.1
15.5
def remove_router_interface(self, context, router_info): """Removes previously configured interface from router on Arista HW. This deals with both IPv6 and IPv4 configurations. """ if router_info: router_name = self._arista_router_name(router_info['id'], ...
[ "def", "remove_router_interface", "(", "self", ",", "context", ",", "router_info", ")", ":", "if", "router_info", ":", "router_name", "=", "self", ".", "_arista_router_name", "(", "router_info", "[", "'id'", "]", ",", "router_info", "[", "'name'", "]", ")", ...
48.521739
17.608696
def search_edges_with_bel(self, bel: str) -> List[Edge]: """Search edges with given BEL. :param bel: A BEL string to use as a search """ return self.session.query(Edge).filter(Edge.bel.like(bel))
[ "def", "search_edges_with_bel", "(", "self", ",", "bel", ":", "str", ")", "->", "List", "[", "Edge", "]", ":", "return", "self", ".", "session", ".", "query", "(", "Edge", ")", ".", "filter", "(", "Edge", ".", "bel", ".", "like", "(", "bel", ")", ...
37.166667
15.5
def has_false(self, e, extra_constraints=(), solver=None, model_callback=None): #pylint:disable=unused-argument """ Should return False if `e` can possibly be False. :param e: The AST. :param extra_constraints: Extra constraints (as ASTs) to add to the solver for thi...
[ "def", "has_false", "(", "self", ",", "e", ",", "extra_constraints", "=", "(", ")", ",", "solver", "=", "None", ",", "model_callback", "=", "None", ")", ":", "#pylint:disable=unused-argument", "#if self._solver_required and solver is None:", "# raise BackendError(\"%s...
55.4
35.266667
def _config_params(base_config, assoc_files, region, out_file, items): """Add parameters based on configuration variables, associated files and genomic regions. """ params = [] dbsnp = assoc_files.get("dbsnp") if dbsnp: params += ["--dbsnp", dbsnp] cosmic = assoc_files.get("cosmic") ...
[ "def", "_config_params", "(", "base_config", ",", "assoc_files", ",", "region", ",", "out_file", ",", "items", ")", ":", "params", "=", "[", "]", "dbsnp", "=", "assoc_files", ".", "get", "(", "\"dbsnp\"", ")", "if", "dbsnp", ":", "params", "+=", "[", "...
47.833333
19.433333
def render(pass_info, saltenv='base', sls='', argline='', **kwargs): ''' Fetch secret from pass based on pass_path ''' try: _get_pass_exec() except SaltRenderError: raise # Make sure environment variable HOME is set, since Pass looks for the # password-store under ~/.passwor...
[ "def", "render", "(", "pass_info", ",", "saltenv", "=", "'base'", ",", "sls", "=", "''", ",", "argline", "=", "''", ",", "*", "*", "kwargs", ")", ":", "try", ":", "_get_pass_exec", "(", ")", "except", "SaltRenderError", ":", "raise", "# Make sure environ...
30.384615
20.692308
def signature_unsafe(m: bytes, sk: bytes, pk: bytes) -> bytes: """ Not safe to use with secret keys or secret data. See module docstring. This function should be used for testing only. """ h = H(sk) a = decodecoord(h) r = Hint(h[b // 8 : b // 4] + m) R = scalarmult_B(r) S = (r + Hi...
[ "def", "signature_unsafe", "(", "m", ":", "bytes", ",", "sk", ":", "bytes", ",", "pk", ":", "bytes", ")", "->", "bytes", ":", "h", "=", "H", "(", "sk", ")", "a", "=", "decodecoord", "(", "h", ")", "r", "=", "Hint", "(", "h", "[", "b", "//", ...
32.166667
15.333333
def list(): """ List blink(1) devices connected, by serial number :return: List of blink(1) device serial numbers """ try: devs = hid.enumerate(VENDOR_ID,PRODUCT_ID) serials = list(map(lambda d:d.get('serial_number'), devs)) return serials ...
[ "def", "list", "(", ")", ":", "try", ":", "devs", "=", "hid", ".", "enumerate", "(", "VENDOR_ID", ",", "PRODUCT_ID", ")", "serials", "=", "list", "(", "map", "(", "lambda", "d", ":", "d", ".", "get", "(", "'serial_number'", ")", ",", "devs", ")", ...
32.363636
16.181818
def ordered_async_call(func_list): """ Runs the list of function asynchronously, returns the response maintaining the order :param func_list: Expects list of lists to be of format [[func1, args1, kwargs1], [func2, args2, kwargs2], ...] :return: List of output of the functions [output1, ...
[ "def", "ordered_async_call", "(", "func_list", ")", ":", "def", "worker", "(", "function", ",", "f_args", ",", "f_kwargs", ",", "queue", ",", "index", ")", ":", "\"\"\"\n Runs the function and appends the output to list, and the Exception in the case of error\n ...
34.857143
22.653061
def MakePmfFromItems(t, name=''): """Makes a PMF from a sequence of value-probability pairs Args: t: sequence of value-probability pairs name: string name for this PMF Returns: Pmf object """ pmf = Pmf(dict(t), name) pmf.Normalize() return pmf
[ "def", "MakePmfFromItems", "(", "t", ",", "name", "=", "''", ")", ":", "pmf", "=", "Pmf", "(", "dict", "(", "t", ")", ",", "name", ")", "pmf", ".", "Normalize", "(", ")", "return", "pmf" ]
21.923077
18.076923
def is_node_highlighted(graph: BELGraph, node: BaseEntity) -> bool: """Returns if the given node is highlighted. :param graph: A BEL graph :param node: A BEL node :type node: tuple :return: Does the node contain highlight information? :rtype: bool """ return NODE_HIGHLIGHT in graph.node...
[ "def", "is_node_highlighted", "(", "graph", ":", "BELGraph", ",", "node", ":", "BaseEntity", ")", "->", "bool", ":", "return", "NODE_HIGHLIGHT", "in", "graph", ".", "node", "[", "node", "]" ]
31.7
15.6
def persist_block(self, block: 'BaseBlock' ) -> Tuple[Tuple[Hash32, ...], Tuple[Hash32, ...]]: """ Persist the given block's header and uncles. Assumes all block transactions have been persisted already. """ with self.db.atomic_batch()...
[ "def", "persist_block", "(", "self", ",", "block", ":", "'BaseBlock'", ")", "->", "Tuple", "[", "Tuple", "[", "Hash32", ",", "...", "]", ",", "Tuple", "[", "Hash32", ",", "...", "]", "]", ":", "with", "self", ".", "db", ".", "atomic_batch", "(", ")...
36.8
14
def exists(self, task_name): """ Determines if task directory exists. `task_name` Task name. Returns ``True`` if task exists. """ try: return os.path.exists(self._get_task_dir(task_name)) except OSError: return False
[ "def", "exists", "(", "self", ",", "task_name", ")", ":", "try", ":", "return", "os", ".", "path", ".", "exists", "(", "self", ".", "_get_task_dir", "(", "task_name", ")", ")", "except", "OSError", ":", "return", "False" ]
21.928571
20.857143
def _gather_group_members(group, groups, users): ''' Gather group members ''' _group = __salt__['group.info'](group) if not _group: log.warning('Group %s does not exist, ignoring.', group) return for member in _group['members']: if member not in users: users...
[ "def", "_gather_group_members", "(", "group", ",", "groups", ",", "users", ")", ":", "_group", "=", "__salt__", "[", "'group.info'", "]", "(", "group", ")", "if", "not", "_group", ":", "log", ".", "warning", "(", "'Group %s does not exist, ignoring.'", ",", ...
25.538462
19.846154
def add_metadata_sectors(self, vtoc, sector_list, header): """Add track/sector list """ tslist = BaseSectorList(header) for start in range(0, len(sector_list), header.ts_pairs): end = min(start + header.ts_pairs, len(sector_list)) if _xd: log.debug("ts: %d-%d" % (...
[ "def", "add_metadata_sectors", "(", "self", ",", "vtoc", ",", "sector_list", ",", "header", ")", ":", "tslist", "=", "BaseSectorList", "(", "header", ")", "for", "start", "in", "range", "(", "0", ",", "len", "(", "sector_list", ")", ",", "header", ".", ...
48.466667
13.733333
def load_hashes(filename): """Load the hashes dict from the hashfile""" # { filename : (sha1 of header if available or 'NA', # sha1 of input, # sha1 of output) } hashes = {} try: with open(filename, 'r') as cython_hash_file: for hash_record in cyt...
[ "def", "load_hashes", "(", "filename", ")", ":", "# { filename : (sha1 of header if available or 'NA',", "# sha1 of input,", "# sha1 of output) }", "hashes", "=", "{", "}", "try", ":", "with", "open", "(", "filename", ",", "'r'", ")", "as", "...
37.5625
17.6875
def detached_signature_for(plaintext_str, keys): """ Signs the given plaintext string and returns the detached signature. A detached signature in GPG speak is a separate blob of data containing a signature for the specified plaintext. :param bytes plaintext_str: bytestring to sign :param keys:...
[ "def", "detached_signature_for", "(", "plaintext_str", ",", "keys", ")", ":", "ctx", "=", "gpg", ".", "core", ".", "Context", "(", "armor", "=", "True", ")", "ctx", ".", "signers", "=", "keys", "(", "sigblob", ",", "sign_result", ")", "=", "ctx", ".", ...
41.166667
15.944444
def subscribe(self, peer_jid): """ Request presence subscription with the given `peer_jid`. This is deliberately not a coroutine; we don’t know whether the peer is online (usually) and they may defer the confirmation very long, if they confirm at all. Use :meth:`on_subscribed` t...
[ "def", "subscribe", "(", "self", ",", "peer_jid", ")", ":", "self", ".", "client", ".", "enqueue", "(", "stanza", ".", "Presence", "(", "type_", "=", "structs", ".", "PresenceType", ".", "SUBSCRIBE", ",", "to", "=", "peer_jid", ")", ")" ]
41
19.769231
def rectify_pi(self): """ rectify the prior information equation with the current state of the parameter_data dataframe. Equations that list fixed, tied or missing parameters are removed. This method is called during Pst.write() """ if self.prior_information.shape[0] == 0: ...
[ "def", "rectify_pi", "(", "self", ")", ":", "if", "self", ".", "prior_information", ".", "shape", "[", "0", "]", "==", "0", ":", "return", "self", ".", "_parse_pi_par_names", "(", ")", "adj_names", "=", "self", ".", "adj_par_names", "def", "is_good", "("...
39.166667
14.444444
def repp(file, config=None, module=None, active=None, format=None, trace_level=0): """ Tokenize with a Regular Expression PreProcessor (REPP). Results are printed directly to stdout. If more programmatic access is desired, the :mod:`delphin.repp` module provides a similar interface. A...
[ "def", "repp", "(", "file", ",", "config", "=", "None", ",", "module", "=", "None", ",", "active", "=", "None", ",", "format", "=", "None", ",", "trace_level", "=", "0", ")", ":", "from", "delphin", ".", "repp", "import", "REPP", "if", "config", "i...
38.795455
19.295455
def make_env_key(app_name, key): """Creates an environment key-equivalent for the given key""" key = key.replace('-', '_').replace(' ', '_') return str("_".join((x.upper() for x in (app_name, key))))
[ "def", "make_env_key", "(", "app_name", ",", "key", ")", ":", "key", "=", "key", ".", "replace", "(", "'-'", ",", "'_'", ")", ".", "replace", "(", "' '", ",", "'_'", ")", "return", "str", "(", "\"_\"", ".", "join", "(", "(", "x", ".", "upper", ...
52
9.75
def mergesort(list_of_lists, key=None): """ Perform an N-way merge operation on sorted lists. @param list_of_lists: (really iterable of iterable) of sorted elements (either by naturally or by C{key}) @param key: specify sort key function (like C{sort()}, C{sorted()}) Yields tuples of the form C{(i...
[ "def", "mergesort", "(", "list_of_lists", ",", "key", "=", "None", ")", ":", "heap", "=", "[", "]", "for", "i", ",", "itr", "in", "enumerate", "(", "iter", "(", "pl", ")", "for", "pl", "in", "list_of_lists", ")", ":", "try", ":", "item", "=", "it...
31.893939
19.80303
def create_custom_resource_definition(self, body, **kwargs): """ create a CustomResourceDefinition This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.create_custom_resource_definition(body, as...
[ "def", "create_custom_resource_definition", "(", "self", ",", "body", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async_req'", ")", ":", "return", "self", ".", "create_cus...
66.26087
38.086957
def compare_graph_searchers(): """Prints a table of results like this: >>> compare_graph_searchers() Searcher Romania(A, B) Romania(O, N) Australia breadth_first_tree_search < 21/ 22/ 59/B> <1158/1159/3288/N> < 7/ 8/ 22/WA> breadth_first...
[ "def", "compare_graph_searchers", "(", ")", ":", "compare_searchers", "(", "problems", "=", "[", "GraphProblem", "(", "'A'", ",", "'B'", ",", "romania", ")", ",", "GraphProblem", "(", "'O'", ",", "'N'", ",", "romania", ")", ",", "GraphProblem", "(", "'Q'",...
75.428571
33.428571
def _get_configured_module(option_name, known_modules=None): """Get the module specified by the value of option_name. The value of the configuration option will be used to load the module by name from the known module list or treated as a path if not found in known_modules. Args: option_name: na...
[ "def", "_get_configured_module", "(", "option_name", ",", "known_modules", "=", "None", ")", ":", "from", "furious", ".", "job_utils", "import", "path_to_reference", "config", "=", "get_config", "(", ")", "option_value", "=", "config", "[", "option_name", "]", "...
40.409091
20.681818
def get_no_record_response(self, request): """ Get an HTTPResponse that can be used when there's no related EnterpriseCustomer. """ username, course_id, program_uuid, enterprise_customer_uuid = self.get_required_query_params(request) data = { self.REQUIRED_PARAM_USERN...
[ "def", "get_no_record_response", "(", "self", ",", "request", ")", ":", "username", ",", "course_id", ",", "program_uuid", ",", "enterprise_customer_uuid", "=", "self", ".", "get_required_query_params", "(", "request", ")", "data", "=", "{", "self", ".", "REQUIR...
39.631579
20.684211
def readFromProto(cls, proto): """ Overrides :meth:`~nupic.bindings.regions.PyRegion.PyRegion.readFromProto`. Read state from proto object. :param proto: SPRegionProto capnproto object """ instance = cls(proto.columnCount, proto.inputWidth) instance.spatialImp = proto.spatialImp i...
[ "def", "readFromProto", "(", "cls", ",", "proto", ")", ":", "instance", "=", "cls", "(", "proto", ".", "columnCount", ",", "proto", ".", "inputWidth", ")", "instance", ".", "spatialImp", "=", "proto", ".", "spatialImp", "instance", ".", "learningMode", "="...
30.35
17.75
def _activation_summary(x): """Helper to create summaries for activations. Creates a summary that provides a histogram of activations. Creates a summary that measure the sparsity of activations. Args: x: Tensor Returns: nothing """ # Remove 'tower_[0-9]/' from the name in case this is a multi-GPU ...
[ "def", "_activation_summary", "(", "x", ")", ":", "# Remove 'tower_[0-9]/' from the name in case this is a multi-GPU training", "# session. This helps the clarity of presentation on tensorboard.", "tf", ".", "histogram_summary", "(", "x", ".", "name", "+", "'/activations'", ",", ...
38.538462
20.923077
def seek_to_position(position): """Seek to an absolute position in stream.""" message = command(protobuf.CommandInfo_pb2.SeekToPlaybackPosition) send_command = message.inner() send_command.options.playbackPosition = position return message
[ "def", "seek_to_position", "(", "position", ")", ":", "message", "=", "command", "(", "protobuf", ".", "CommandInfo_pb2", ".", "SeekToPlaybackPosition", ")", "send_command", "=", "message", ".", "inner", "(", ")", "send_command", ".", "options", ".", "playbackPo...
42.333333
13.166667
def with_spark_context(application_name, conf=None): """Context manager for a spark context Parameters ---------- application_name : string conf : string, optional Returns ------- sc : SparkContext Examples -------- Used within a context manager >>> with with_spark_con...
[ "def", "with_spark_context", "(", "application_name", ",", "conf", "=", "None", ")", ":", "if", "conf", "is", "None", ":", "conf", "=", "default_configuration", "assert", "isinstance", "(", "conf", ",", "SparkConfiguration", ")", "sc", "=", "conf", ".", "spa...
20.172414
21.448276
def remove_elements(target, indices): """Remove multiple elements from a list and return result. This implementation is faster than the alternative below. Also note the creation of a new list to avoid altering the original. We don't have any current use for the original intact list, but may in the f...
[ "def", "remove_elements", "(", "target", ",", "indices", ")", ":", "copied", "=", "list", "(", "target", ")", "for", "index", "in", "reversed", "(", "indices", ")", ":", "del", "copied", "[", "index", "]", "return", "copied" ]
35.666667
17