text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def _parse_posterior(self): """Read csv paths to list of dataframes.""" paths = self.posterior_ if isinstance(paths, str): paths = [paths] chain_data = [] for path in paths: parsed_output = _read_output(path) for sample, sample_stats, config, a...
[ "def", "_parse_posterior", "(", "self", ")", ":", "paths", "=", "self", ".", "posterior_", "if", "isinstance", "(", "paths", ",", "str", ")", ":", "paths", "=", "[", "paths", "]", "chain_data", "=", "[", "]", "for", "path", "in", "paths", ":", "parse...
41.2
14.55
def constructFilename(signature): """Construct an output filename for the given signature:: signature=[instr+detector,(nx,ny),detnum] The signature is in the image object. """ suffix = buildSignatureKey(signature) filename = os.path.join('.', suffix) return filename
[ "def", "constructFilename", "(", "signature", ")", ":", "suffix", "=", "buildSignatureKey", "(", "signature", ")", "filename", "=", "os", ".", "path", ".", "join", "(", "'.'", ",", "suffix", ")", "return", "filename" ]
29.2
12
def translate( nucleotide_sequence, first_codon_is_start=True, to_stop=True, truncate=False): """Translates cDNA coding sequence into amino acid protein sequence. Should typically start with a start codon but allowing non-methionine first residues since the CDS we're transla...
[ "def", "translate", "(", "nucleotide_sequence", ",", "first_codon_is_start", "=", "True", ",", "to_stop", "=", "True", ",", "truncate", "=", "False", ")", ":", "if", "not", "isinstance", "(", "nucleotide_sequence", ",", "Seq", ")", ":", "nucleotide_sequence", ...
35.90625
20.578125
def rs_find_errata_locator(e_pos, generator=2): '''Compute the erasures/errors/errata locator polynomial from the erasures/errors/errata positions (the positions must be relative to the x coefficient, eg: "hello worldxxxxxxxxx" is tampered to "h_ll_ worldxxxxxxxxx" with xxxxxxxxx being the ecc of length n-k=9, here...
[ "def", "rs_find_errata_locator", "(", "e_pos", ",", "generator", "=", "2", ")", ":", "# See: http://ocw.usu.edu/Electrical_and_Computer_Engineering/Error_Control_Coding/lecture7.pdf and Blahut, Richard E. \"Transform techniques for error control codes.\" IBM Journal of Research and development 2...
209.5
180.75
def connect_sqs(aws_access_key_id=None, aws_secret_access_key=None, **kwargs): """ :type aws_access_key_id: string :param aws_access_key_id: Your AWS Access Key ID :type aws_secret_access_key: string :param aws_secret_access_key: Your AWS Secret Access Key :rtype: :class:`boto.sqs.connection.S...
[ "def", "connect_sqs", "(", "aws_access_key_id", "=", "None", ",", "aws_secret_access_key", "=", "None", ",", "*", "*", "kwargs", ")", ":", "from", "boto", ".", "sqs", ".", "connection", "import", "SQSConnection", "return", "SQSConnection", "(", "aws_access_key_i...
38.307692
16.615385
def two_way(cells): """ Two-way chi-square test of independence. Takes a 3D array as input: N(voxels) x 2 x 2, where the last two dimensions are the contingency table for each of N voxels. Returns an array of p-values. """ # Mute divide-by-zero warning for bad voxels since we account for that ...
[ "def", "two_way", "(", "cells", ")", ":", "# Mute divide-by-zero warning for bad voxels since we account for that", "# later", "warnings", ".", "simplefilter", "(", "\"ignore\"", ",", "RuntimeWarning", ")", "cells", "=", "cells", ".", "astype", "(", "'float64'", ")", ...
45.181818
20.227273
def add_resource(self, path, resource): """ Helper function to add resources to the resource directory during server initialization. :param path: the path for the new created resource :type resource: Resource :param resource: the resource to be added """ assert ...
[ "def", "add_resource", "(", "self", ",", "path", ",", "resource", ")", ":", "assert", "isinstance", "(", "resource", ",", "Resource", ")", "path", "=", "path", ".", "strip", "(", "\"/\"", ")", "paths", "=", "path", ".", "split", "(", "\"/\"", ")", "a...
30.64
15.36
def sortino_ratio(rets, rfr_ann=0, mar=0, full=0, expanding=0): """Compute the sortino ratio as (Ann Rets - Risk Free Rate) / Downside Deviation Ann :param rets: period return series :param rfr_ann: annualized risk free rate :param mar: minimum acceptable rate of return (MAR) :param full: If True, ...
[ "def", "sortino_ratio", "(", "rets", ",", "rfr_ann", "=", "0", ",", "mar", "=", "0", ",", "full", "=", "0", ",", "expanding", "=", "0", ")", ":", "annrets", "=", "returns_annualized", "(", "rets", ",", "expanding", "=", "expanding", ")", "-", "rfr_an...
48.5
22.25
def calling_convention(self): """function calling convention. See :class:CALLING_CONVENTION_TYPES class for possible values""" if self._calling_convention is None: self._calling_convention = \ calldef_types.CALLING_CONVENTION_TYPES.extract(self.attributes) ...
[ "def", "calling_convention", "(", "self", ")", ":", "if", "self", ".", "_calling_convention", "is", "None", ":", "self", ".", "_calling_convention", "=", "calldef_types", ".", "CALLING_CONVENTION_TYPES", ".", "extract", "(", "self", ".", "attributes", ")", "if",...
51.555556
10.333333
def find_program_status(data, zone): """ Find on the HTML document if zoneX has the configuration of the auto-schedule/program (auto_watering) enabled. # expected result if enabled #<input checked="checked" class="switch" id="id_zone2_program_toggle" \ name="zone2_program_toggle" onchange="...
[ "def", "find_program_status", "(", "data", ",", "zone", ")", ":", "if", "not", "isinstance", "(", "data", ",", "BeautifulSoup", ")", ":", "raise", "TypeError", "(", "\"Function requires BeautilSoup HTML element.\"", ")", "try", ":", "child", "=", "data", ".", ...
39.588235
17.352941
def load(self, filename, subset=None): """Load data into the registered fields Argument: | ``filename`` -- the filename to read from Optional argument: | ``subset`` -- a list of field names that are read from the file. If not give...
[ "def", "load", "(", "self", ",", "filename", ",", "subset", "=", "None", ")", ":", "with", "open", "(", "filename", ",", "\"r\"", ")", "as", "f", ":", "name", "=", "None", "num_names", "=", "0", "while", "True", ":", "# read a header line", "line", "...
44.106061
22.045455
def _init_metadata(self): """stub""" SimpleDifficultyItemFormRecord._init_metadata(self) SourceItemFormRecord._init_metadata(self) PDFPreviewFormRecord._init_metadata(self) PublishedFormRecord._init_metadata(self) ProvenanceFormRecord._init_metadata(self) super(Me...
[ "def", "_init_metadata", "(", "self", ")", ":", "SimpleDifficultyItemFormRecord", ".", "_init_metadata", "(", "self", ")", "SourceItemFormRecord", ".", "_init_metadata", "(", "self", ")", "PDFPreviewFormRecord", ".", "_init_metadata", "(", "self", ")", "PublishedFormR...
44
10.5
def autoLayout( self, padX = None, padY = None, direction = Qt.Horizontal, layout = 'Layered', animate = 0, centerOn = None, center = None, debug=False ): ...
[ "def", "autoLayout", "(", "self", ",", "padX", "=", "None", ",", "padY", "=", "None", ",", "direction", "=", "Qt", ".", "Horizontal", ",", "layout", "=", "'Layered'", ",", "animate", "=", "0", ",", "centerOn", "=", "None", ",", "center", "=", "None",...
41.333333
12
def get_argument( # noqa: F811 self, name: str, default: Union[None, str, _ArgDefaultMarker] = _ARG_DEFAULT, strip: bool = True, ) -> Optional[str]: """Returns the value of the argument with the given name. If default is not provided, the argument is considered to b...
[ "def", "get_argument", "(", "# noqa: F811", "self", ",", "name", ":", "str", ",", "default", ":", "Union", "[", "None", ",", "str", ",", "_ArgDefaultMarker", "]", "=", "_ARG_DEFAULT", ",", "strip", ":", "bool", "=", "True", ",", ")", "->", "Optional", ...
37.294118
24.470588
def hashes(self): """Return set of hashes uses in this resource_list.""" hashes = set() if (self.resources is not None): for resource in self: if (resource.md5 is not None): hashes.add('md5') if (resource.sha1 is not None): ...
[ "def", "hashes", "(", "self", ")", ":", "hashes", "=", "set", "(", ")", "if", "(", "self", ".", "resources", "is", "not", "None", ")", ":", "for", "resource", "in", "self", ":", "if", "(", "resource", ".", "md5", "is", "not", "None", ")", ":", ...
37.916667
7.75
def dead_letter(self, description=None): """Move the message to the Dead Letter queue. The Dead Letter queue is a sub-queue that can be used to store messages that failed to process correctly, or otherwise require further inspection or processing. The queue can also be configured to sen...
[ "def", "dead_letter", "(", "self", ",", "description", "=", "None", ")", ":", "self", ".", "_is_live", "(", "'reject'", ")", "try", ":", "self", ".", "message", ".", "reject", "(", "condition", "=", "DEADLETTERNAME", ",", "description", "=", "description",...
58.714286
32.52381
def valueWritePreprocessor(valueString, replaceParamsFile=None): """ Look up variable name in replace param file for the negative id given and return it. Args: valueString (str): String representing the value to be preprocessed. replaceParamsFile (gsshapy.orm.ReplaceParamFile, optional): In...
[ "def", "valueWritePreprocessor", "(", "valueString", ",", "replaceParamsFile", "=", "None", ")", ":", "if", "type", "(", "valueString", ")", "is", "bool", ":", "log", ".", "warning", "(", "\"Only numerical variable types can be handled by the valueReadPreprocessor functio...
35.076923
22.615385
def fmt_part(part, node_labels=None): """Format a |Part|. The returned string looks like:: 0,1 ─── ∅ """ def nodes(x): # pylint: disable=missing-docstring return ','.join(labels(x, node_labels)) if x else EMPTY_SET numer = nodes(part.mechanism) denom = nodes(...
[ "def", "fmt_part", "(", "part", ",", "node_labels", "=", "None", ")", ":", "def", "nodes", "(", "x", ")", ":", "# pylint: disable=missing-docstring", "return", "','", ".", "join", "(", "labels", "(", "x", ",", "node_labels", ")", ")", "if", "x", "else", ...
24.043478
19.956522
def named_field(key, regex, vim=False): """ Creates a named regex group that can be referend via a backref. If key is None the backref is referenced by number. References: https://docs.python.org/2/library/re.html#regular-expression-syntax """ if key is None: #return regex ...
[ "def", "named_field", "(", "key", ",", "regex", ",", "vim", "=", "False", ")", ":", "if", "key", "is", "None", ":", "#return regex", "return", "r'(%s)'", "%", "(", "regex", ",", ")", "if", "vim", ":", "return", "r'\\(%s\\)'", "%", "(", "regex", ")", ...
29
17.266667
def insert(self, table_name, record, attr_names=None): """ Send an INSERT query to the database. :param str table_name: Table name of executing the query. :param record: Record to be inserted. :type record: |dict|/|namedtuple|/|list|/|tuple| :raises IOError: |raises_writ...
[ "def", "insert", "(", "self", ",", "table_name", ",", "record", ",", "attr_names", "=", "None", ")", ":", "self", ".", "insert_many", "(", "table_name", ",", "records", "=", "[", "record", "]", ",", "attr_names", "=", "attr_names", ")" ]
37.588235
18.176471
def emit(self, record): """ Emit a record. Output the record to the file, ensuring that the currently- opened file has the correct date. """ now = time.time() current_name = self.get_filename(now) try: if not self.stream.name == current_name: self._use_file(current_name) except Att...
[ "def", "emit", "(", "self", ",", "record", ")", ":", "now", "=", "time", ".", "time", "(", ")", "current_name", "=", "self", ".", "get_filename", "(", "now", ")", "try", ":", "if", "not", "self", ".", "stream", ".", "name", "==", "current_name", ":...
27.875
12.75
def _lint(self): """Run linter in a subprocess.""" command = self._get_command() process = subprocess.run(command, stdout=subprocess.PIPE, # nosec stderr=subprocess.PIPE) LOG.info('Finished %s', ' '.join(command)) stdout, stderr = self._get_outpu...
[ "def", "_lint", "(", "self", ")", ":", "command", "=", "self", ".", "_get_command", "(", ")", "process", "=", "subprocess", ".", "run", "(", "command", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "# nosec", "stderr", "=", "subprocess", ".", "PI...
49.875
16.5
def backwards(self, orm): "Write your backwards methods here." orm['avocado.DataField'].objects.filter(Q(model_name='thousandg', field_name='af') | Q(model_name='evs', field_name='all_maf'), app_name='variants').update(translator=None)
[ "def", "backwards", "(", "self", ",", "orm", ")", ":", "orm", "[", "'avocado.DataField'", "]", ".", "objects", ".", "filter", "(", "Q", "(", "model_name", "=", "'thousandg'", ",", "field_name", "=", "'af'", ")", "|", "Q", "(", "model_name", "=", "'evs'...
54.2
20.2
def mv_videos(path): """ move videos in sub-directory of path to path. """ count = 0 for f in os.listdir(path): f = os.path.join(path, f) if os.path.isdir(f): for sf in os.listdir(f): sf = os.path.join(f, sf) if os.path.isfile(sf): ...
[ "def", "mv_videos", "(", "path", ")", ":", "count", "=", "0", "for", "f", "in", "os", ".", "listdir", "(", "path", ")", ":", "f", "=", "os", ".", "path", ".", "join", "(", "path", ",", "f", ")", "if", "os", ".", "path", ".", "isdir", "(", "...
37.157895
13.263158
def process_row(self, row): """ Processes a row of AP election data to determine what model objects need to be created. """ division = self.get_division(row) if not division: return None race = self.get_race(row, division) election = self.get_...
[ "def", "process_row", "(", "self", ",", "row", ")", ":", "division", "=", "self", ".", "get_division", "(", "row", ")", "if", "not", "division", ":", "return", "None", "race", "=", "self", ".", "get_race", "(", "row", ",", "division", ")", "election", ...
33.227273
17.954545
def init_stats(output_dir, config): """Init all required ressources for stats handling :param str output_dir: the output directory for the results :param dict config: the project configuration """ try: os.makedirs(output_dir, 0o755) except OSError as e: print("ERROR: Can not cre...
[ "def", "init_stats", "(", "output_dir", ",", "config", ")", ":", "try", ":", "os", ".", "makedirs", "(", "output_dir", ",", "0o755", ")", "except", "OSError", "as", "e", ":", "print", "(", "\"ERROR: Can not create output directory: %s\\n\"", "%", "e", ")", "...
28.3
20.35
def getOr(subject, predicate, *args, **kwargs): """ Retrieve a metadata node or generate a new one :param subject: Subject to which the metadata node should be connected :param predicate: Predicate by which the metadata node should be connected :return: Metadata for given node :...
[ "def", "getOr", "(", "subject", ",", "predicate", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "(", "subject", ",", "predicate", ",", "None", ")", "in", "get_graph", "(", ")", ":", "return", "Metadata", "(", "node", "=", "get_graph", ...
43.083333
20
def run_thermal_displacements(self, t_min=0, t_max=1000, t_step=10, temperatures=None, direction=None, freq_min=None...
[ "def", "run_thermal_displacements", "(", "self", ",", "t_min", "=", "0", ",", "t_max", "=", "1000", ",", "t_step", "=", "10", ",", "temperatures", "=", "None", ",", "direction", "=", "None", ",", "freq_min", "=", "None", ",", "freq_max", "=", "None", "...
40.698413
15.31746
def command_str(self): """get command to execute as string properly escaped :return: string """ if isinstance(self.command, six.string_types): return self.command return ' '.join(map(six.moves.shlex_quote, self.command))
[ "def", "command_str", "(", "self", ")", ":", "if", "isinstance", "(", "self", ".", "command", ",", "six", ".", "string_types", ")", ":", "return", "self", ".", "command", "return", "' '", ".", "join", "(", "map", "(", "six", ".", "moves", ".", "shlex...
33.25
15.375
def _thread_init(cls): """Ensure thread local is initialized.""" if not hasattr(cls._local, '_in_order_futures'): cls._local._in_order_futures = set() cls._local._activated = False
[ "def", "_thread_init", "(", "cls", ")", ":", "if", "not", "hasattr", "(", "cls", ".", "_local", ",", "'_in_order_futures'", ")", ":", "cls", ".", "_local", ".", "_in_order_futures", "=", "set", "(", ")", "cls", ".", "_local", ".", "_activated", "=", "F...
39.2
7.4
def read_i2c_block_data(self, i2c_addr, register, length, force=None): """ Read a block of byte data from a given register. :param i2c_addr: i2c address :type i2c_addr: int :param register: Start register :type register: int :param length: Desired block length ...
[ "def", "read_i2c_block_data", "(", "self", ",", "i2c_addr", ",", "register", ",", "length", ",", "force", "=", "None", ")", ":", "if", "length", ">", "I2C_SMBUS_BLOCK_MAX", ":", "raise", "ValueError", "(", "\"Desired block length over %d bytes\"", "%", "I2C_SMBUS_...
36.916667
14.416667
def omit(dct, *keys): """ Returns a copy of the dictionary filtered to omit the blacklisted keys (or list of keys) >>> omit({"name": "moe", "age": 50, "userid": "moe1"}, "userid", "age") {'name': 'moe'} """ copy = dict() for key in dct: if key not in keys: co...
[ "def", "omit", "(", "dct", ",", "*", "keys", ")", ":", "copy", "=", "dict", "(", ")", "for", "key", "in", "dct", ":", "if", "key", "not", "in", "keys", ":", "copy", "[", "key", "]", "=", "dct", "[", "key", "]", "return", "copy" ]
28.583333
18.333333
def get_messages_since(self, cursor): """Returns a list of messages newer than the given cursor. ``cursor`` should be the ``id`` of the last message received. """ results = [] for msg in reversed(self.cache): if msg["id"] == cursor: break ...
[ "def", "get_messages_since", "(", "self", ",", "cursor", ")", ":", "results", "=", "[", "]", "for", "msg", "in", "reversed", "(", "self", ".", "cache", ")", ":", "if", "msg", "[", "\"id\"", "]", "==", "cursor", ":", "break", "results", ".", "append",...
31.416667
13.166667
def execute_command(self, cmnd, *args, **options): "Execute a command and return a parsed response" args, options = self.preprocess_command(cmnd, *args, **options) return self.client.execute_command(cmnd, *args, **options)
[ "def", "execute_command", "(", "self", ",", "cmnd", ",", "*", "args", ",", "*", "*", "options", ")", ":", "args", ",", "options", "=", "self", ".", "preprocess_command", "(", "cmnd", ",", "*", "args", ",", "*", "*", "options", ")", "return", "self", ...
60.75
20.75
def get_repo_keys(): ''' .. versionadded:: 2017.7.0 List known repo key details. :return: A dictionary containing the repo keys. :rtype: dict CLI Examples: .. code-block:: bash salt '*' pkg.get_repo_keys ''' ret = dict() repo_keys = list() # The double usage of ...
[ "def", "get_repo_keys", "(", ")", ":", "ret", "=", "dict", "(", ")", "repo_keys", "=", "list", "(", ")", "# The double usage of '--with-fingerprint' is necessary in order to", "# retrieve the fingerprint of the subkey.", "cmd", "=", "[", "'apt-key'", ",", "'adv'", ",", ...
29.571429
20.542857
def session(self) -> BaseFileWriterSession: '''Return the File Writer Session.''' return self.session_class( self._path_namer, self._file_continuing, self._headers_included, self._local_timestamping, self._adjust_extension, self._co...
[ "def", "session", "(", "self", ")", "->", "BaseFileWriterSession", ":", "return", "self", ".", "session_class", "(", "self", ".", "_path_namer", ",", "self", ".", "_file_continuing", ",", "self", ".", "_headers_included", ",", "self", ".", "_local_timestamping",...
34.181818
7.272727
def _prepare_src_array(source_array, dtype): """Prepare `source_array` so that it can be used to construct NDArray. `source_array` is converted to a `np.ndarray` if it's neither an `NDArray` \ nor an `np.ndarray`. """ if not isinstance(source_array, NDArray) and not isinstance(source_array, np.ndarr...
[ "def", "_prepare_src_array", "(", "source_array", ",", "dtype", ")", ":", "if", "not", "isinstance", "(", "source_array", ",", "NDArray", ")", "and", "not", "isinstance", "(", "source_array", ",", "np", ".", "ndarray", ")", ":", "try", ":", "source_array", ...
44.909091
20.454545
def accept_script(self, script): """ True when the term is a subset of this term tables. If the parent of this term is already a TableSet,return always false (only one main tableset) :param term: :return: """ if isinstance(self.parent, TableSet): retur...
[ "def", "accept_script", "(", "self", ",", "script", ")", ":", "if", "isinstance", "(", "self", ".", "parent", ",", "TableSet", ")", ":", "return", "False", ",", "False", "tables", "=", "[", "table", "for", "table", "in", "self", ".", "script", ".", "...
36.4375
25.5625
def get_float(self, input_string): """ Return float type user input """ if input_string == '--training_fraction': # was the flag set? try: index = self.args.index(input_string) + 1 except ValueError: # it wasn't, it's optional, so...
[ "def", "get_float", "(", "self", ",", "input_string", ")", ":", "if", "input_string", "==", "'--training_fraction'", ":", "# was the flag set?", "try", ":", "index", "=", "self", ".", "args", ".", "index", "(", "input_string", ")", "+", "1", "except", "Value...
38.410256
21.794872
def parse_file_args(file_obj, file_type, resolver=None, **kwargs): """ Given a file_obj and a file_type try to turn them into a file-like object and a lowercase string of file type. Parameters ----------- file_obj: str: if string repr...
[ "def", "parse_file_args", "(", "file_obj", ",", "file_type", ",", "resolver", "=", "None", ",", "*", "*", "kwargs", ")", ":", "metadata", "=", "{", "}", "opened", "=", "False", "if", "(", "'metadata'", "in", "kwargs", "and", "isinstance", "(", "kwargs", ...
42.033333
20.133333
def merge_pr( pr_num: int, base_ref: str, target_ref: str, commit_title: str, body: str, pr_repo_desc: str, original_head: str, remote: str, merge_method: str, github_user: str, password: str, ) -> None: """Merge a pull request.""" git_log = git[ "log", ...
[ "def", "merge_pr", "(", "pr_num", ":", "int", ",", "base_ref", ":", "str", ",", "target_ref", ":", "str", ",", "commit_title", ":", "str", ",", "body", ":", "str", ",", "pr_repo_desc", ":", "str", ",", "original_head", ":", "str", ",", "remote", ":", ...
30.765625
20.96875
def min_mean_cycle(graph, weight, start=0): """Minimum mean cycle by Karp :param graph: directed graph in listlist or listdict format :param weight: in matrix format or same listdict graph :param int start: vertex that should be contained in cycle :returns: cycle as vertex list, average arc weights...
[ "def", "min_mean_cycle", "(", "graph", ",", "weight", ",", "start", "=", "0", ")", ":", "INF", "=", "float", "(", "'inf'", ")", "n", "=", "len", "(", "graph", ")", "# compute distances", "dist", "=", "[", "[", "INF", "]", "*", "n", "]", "prec", "...
36
15.333333
def arrangeByType(service_list, preferred_types): """Rearrange service_list in a new list so services are ordered by types listed in preferred_types. Return the new list.""" def enumerate(elts): """Return an iterable that pairs the index of an element with that element. For Python...
[ "def", "arrangeByType", "(", "service_list", ",", "preferred_types", ")", ":", "def", "enumerate", "(", "elts", ")", ":", "\"\"\"Return an iterable that pairs the index of an element with\n that element.\n\n For Python 2.2 compatibility\"\"\"", "return", "zip", "(", ...
37.710526
18.447368
def _unlock(self): """ Unlock this keyring by getting the password for the keyring from the user. """ self.keyring_key = getpass.getpass( 'Please enter password for encrypted keyring: ') try: ref_pw = self.get_password('keyring-setting', 'password ...
[ "def", "_unlock", "(", "self", ")", ":", "self", ".", "keyring_key", "=", "getpass", ".", "getpass", "(", "'Please enter password for encrypted keyring: '", ")", "try", ":", "ref_pw", "=", "self", ".", "get_password", "(", "'keyring-setting'", ",", "'password refe...
37.076923
17.384615
def GetFormatStringAttributeNames(self): """Retrieves the attribute names in the format string. Returns: set(str): attribute names. """ if self._format_string_attribute_names is None: self._format_string_attribute_names = ( self._FORMAT_STRING_ATTRIBUTE_NAME_RE.findall( ...
[ "def", "GetFormatStringAttributeNames", "(", "self", ")", ":", "if", "self", ".", "_format_string_attribute_names", "is", "None", ":", "self", ".", "_format_string_attribute_names", "=", "(", "self", ".", "_FORMAT_STRING_ATTRIBUTE_NAME_RE", ".", "findall", "(", "self"...
32.166667
13.75
def _build_implicit_queryset(self, model, requirements): """Build a queryset based on implicit requirements.""" queryset = self._make_model_queryset(model) prefetches = {} self._build_implicit_prefetches( model, prefetches, requirements ) ...
[ "def", "_build_implicit_queryset", "(", "self", ",", "model", ",", "requirements", ")", ":", "queryset", "=", "self", ".", "_make_model_queryset", "(", "model", ")", "prefetches", "=", "{", "}", "self", ".", "_build_implicit_prefetches", "(", "model", ",", "pr...
33.733333
16.266667
def validate(self): """Check self.data. Raise InvalidConfig on error :return: None """ if (self.data.get('content-type') or self.data.get('body')) and \ self.data.get('method', '').lower() not in CONTENT_TYPE_METHODS: raise InvalidConfig( extr...
[ "def", "validate", "(", "self", ")", ":", "if", "(", "self", ".", "data", ".", "get", "(", "'content-type'", ")", "or", "self", ".", "data", ".", "get", "(", "'body'", ")", ")", "and", "self", ".", "data", ".", "get", "(", "'method'", ",", "''", ...
52.571429
29.47619
def _time_shift(self, periods, freq=None): """ Shift each value by `periods`. Note this is different from ExtensionArray.shift, which shifts the *position* of each element, padding the end with missing values. Parameters ---------- periods : int ...
[ "def", "_time_shift", "(", "self", ",", "periods", ",", "freq", "=", "None", ")", ":", "if", "freq", "is", "not", "None", "and", "freq", "!=", "self", ".", "freq", ":", "if", "isinstance", "(", "freq", ",", "str", ")", ":", "freq", "=", "frequencie...
34
17.405405
def _get_package_status(package): """Get the status for a package.""" status = package["status_str"] or "Unknown" stage = package["stage_str"] or "Unknown" if stage == "Fully Synchronised": return status return "%(status)s / %(stage)s" % {"status": status, "stage": stage}
[ "def", "_get_package_status", "(", "package", ")", ":", "status", "=", "package", "[", "\"status_str\"", "]", "or", "\"Unknown\"", "stage", "=", "package", "[", "\"stage_str\"", "]", "or", "\"Unknown\"", "if", "stage", "==", "\"Fully Synchronised\"", ":", "retur...
42
10.428571
def exception(self): '''Return an instance of the corresponding exception''' code, _, message = self.data.partition(' ') return self.find(code)(message)
[ "def", "exception", "(", "self", ")", ":", "code", ",", "_", ",", "message", "=", "self", ".", "data", ".", "partition", "(", "' '", ")", "return", "self", ".", "find", "(", "code", ")", "(", "message", ")" ]
43.25
13.75
def get_vulnerability_chains( current_node, sink, def_use, chain=[] ): """Traverses the def-use graph to find all paths from source to sink that cause a vulnerability. Args: current_node() sink() def_use(dict): chain(list(Node)): A path of nodes between source an...
[ "def", "get_vulnerability_chains", "(", "current_node", ",", "sink", ",", "def_use", ",", "chain", "=", "[", "]", ")", ":", "for", "use", "in", "def_use", "[", "current_node", "]", ":", "if", "use", "==", "sink", ":", "yield", "chain", "else", ":", "vu...
24.615385
19.115385
def parse(self, sentence, params=None, headers=None): """ Request a parse of *sentence* and return the response. Args: sentence (str): sentence to be parsed params (dict): a dictionary of request parameters headers (dict): a dictionary of additional request h...
[ "def", "parse", "(", "self", ",", "sentence", ",", "params", "=", "None", ",", "headers", "=", "None", ")", ":", "if", "params", "is", "None", ":", "params", "=", "{", "}", "params", "[", "'input'", "]", "=", "sentence", "hdrs", "=", "{", "'Accept'...
33.107143
17.321429
def download_object(self, instance, bucket_name, object_name): """ Download an object. :param str instance: A Yamcs instance name. :param str bucket_name: The name of the bucket. :param str object_name: The object to fetch. """ url = '/buckets/{}/{}/{}'.format(in...
[ "def", "download_object", "(", "self", ",", "instance", ",", "bucket_name", ",", "object_name", ")", ":", "url", "=", "'/buckets/{}/{}/{}'", ".", "format", "(", "instance", ",", "bucket_name", ",", "object_name", ")", "response", "=", "self", ".", "_client", ...
38.818182
15.363636
def barf(msg, exit=None, f=sys.stderr): '''Exit with a log message (usually a fatal error)''' exit = const('FSQ_FAIL_TMP') if exit is None else exit shout(msg, f) sys.exit(exit)
[ "def", "barf", "(", "msg", ",", "exit", "=", "None", ",", "f", "=", "sys", ".", "stderr", ")", ":", "exit", "=", "const", "(", "'FSQ_FAIL_TMP'", ")", "if", "exit", "is", "None", "else", "exit", "shout", "(", "msg", ",", "f", ")", "sys", ".", "e...
37.8
16.2
def user_line(self, frame, breakpoint_hits=None): """This function is called when we stop or break at this line.""" if not breakpoint_hits: self.interaction(frame, None) else: commands_result = self.bp_commands(frame, breakpoint_hits) if not commands_result: ...
[ "def", "user_line", "(", "self", ",", "frame", ",", "breakpoint_hits", "=", "None", ")", ":", "if", "not", "breakpoint_hits", ":", "self", ".", "interaction", "(", "frame", ",", "None", ")", "else", ":", "commands_result", "=", "self", ".", "bp_commands", ...
41
12.4
def rebin(a, newshape): """Rebin an array to a new shape.""" slices = [slice(0, old, float(old)/new) for old, new in zip(a.shape, newshape)] coordinates = numpy.mgrid[slices] # choose the biggest smaller integer index indices = coordinates.astype('i') return a[tuple(indices)]
[ "def", "rebin", "(", "a", ",", "newshape", ")", ":", "slices", "=", "[", "slice", "(", "0", ",", "old", ",", "float", "(", "old", ")", "/", "new", ")", "for", "old", ",", "new", "in", "zip", "(", "a", ".", "shape", ",", "newshape", ")", "]", ...
34.111111
10.777778
def loader(pattern, dimensions=None, distributed_dim='time', read_only=False): """ It provide a root descriptor to be used inside a with statement. It automatically close the root when the with statement finish. Keyword arguments: root -- the root descriptor returned by the 'open' function """ ...
[ "def", "loader", "(", "pattern", ",", "dimensions", "=", "None", ",", "distributed_dim", "=", "'time'", ",", "read_only", "=", "False", ")", ":", "if", "dimensions", ":", "root", "=", "tailor", "(", "pattern", ",", "dimensions", ",", "distributed_dim", ","...
35.785714
23.5
def from_transform(cls, matrix): r""" :param matrix: 4x4 3d affine transform matrix :type matrix: :class:`FreeCAD.Matrix` :return: a unit, zero offset coordinate system transformed by the given matrix :rtype: :class:`CoordSystem` Individual rotation & translation matrici...
[ "def", "from_transform", "(", "cls", ",", "matrix", ")", ":", "# Create reference points at origin", "offset", "=", "FreeCAD", ".", "Vector", "(", "0", ",", "0", ",", "0", ")", "x_vertex", "=", "FreeCAD", ".", "Vector", "(", "1", ",", "0", ",", "0", ")...
35.209877
16.777778
def find_exec_in_path(exec_name): """ :param str exec_name: :return: yields full paths :rtype: list[str] """ if "PATH" not in os.environ: return for p in os.environ["PATH"].split(":"): pp = "%s/%s" % (p, exec_name) if os.path.exists(pp): yield pp
[ "def", "find_exec_in_path", "(", "exec_name", ")", ":", "if", "\"PATH\"", "not", "in", "os", ".", "environ", ":", "return", "for", "p", "in", "os", ".", "environ", "[", "\"PATH\"", "]", ".", "split", "(", "\":\"", ")", ":", "pp", "=", "\"%s/%s\"", "%...
24.916667
10.083333
def set_default_init_cli_cmds(self): """ Default init commands are set --retcode true, echo off, set --vt100 off, set dut <dut name> and set testcase <tc name> :return: List of default cli initialization commands. """ init_cli_cmds = [] init_cli_cmds.append("set ...
[ "def", "set_default_init_cli_cmds", "(", "self", ")", ":", "init_cli_cmds", "=", "[", "]", "init_cli_cmds", ".", "append", "(", "\"set --retcode true\"", ")", "init_cli_cmds", ".", "append", "(", "\"echo off\"", ")", "init_cli_cmds", ".", "append", "(", "\"set --v...
37.9375
16.9375
def _jit_give_bond_array(pos, bond_radii, self_bonding_allowed=False): """Calculate a boolean array where ``A[i,j] is True`` indicates a bond between the i-th and j-th atom. """ n = pos.shape[0] bond_array = np.empty((n, n), dtype=nb.boolean) for i in range(n): ...
[ "def", "_jit_give_bond_array", "(", "pos", ",", "bond_radii", ",", "self_bonding_allowed", "=", "False", ")", ":", "n", "=", "pos", ".", "shape", "[", "0", "]", "bond_array", "=", "np", ".", "empty", "(", "(", "n", ",", "n", ")", ",", "dtype", "=", ...
38.157895
11.736842
def get_module_environment(env=None, function=None): ''' Get module optional environment. To setup an environment option for a particular module, add either pillar or config at the minion as follows: system-environment: modules: pkg: _: LC_ALL: en_GB.UTF-8 ...
[ "def", "get_module_environment", "(", "env", "=", "None", ",", "function", "=", "None", ")", ":", "result", "=", "{", "}", "if", "not", "env", ":", "env", "=", "{", "}", "for", "env_src", "in", "[", "env", ".", "get", "(", "'__opts__'", ",", "{", ...
34.54386
23.105263
def add_to_parser(self, parser, group): """ Add this object's information to the parser. """ return parser.add_argument_group(*self.args, **self.kwds)
[ "def", "add_to_parser", "(", "self", ",", "parser", ",", "group", ")", ":", "return", "parser", ".", "add_argument_group", "(", "*", "self", ".", "args", ",", "*", "*", "self", ".", "kwds", ")" ]
42.75
6.5
def similarity(self, other): """Get similarity as a ratio of the two numbers.""" numerator, denominator = sorted((self.value, other.value)) try: ratio = float(numerator) / denominator except ZeroDivisionError: ratio = 0.0 if numerator else 1.0 similarity =...
[ "def", "similarity", "(", "self", ",", "other", ")", ":", "numerator", ",", "denominator", "=", "sorted", "(", "(", "self", ".", "value", ",", "other", ".", "value", ")", ")", "try", ":", "ratio", "=", "float", "(", "numerator", ")", "/", "denominato...
40.111111
11.777778
def bios_image(self, bios_image): """ Sets the bios image for this QEMU VM. :param bios_image: QEMU bios image path """ self._bios_image = self.manager.get_abs_image_path(bios_image) log.info('QEMU VM "{name}" [{id}] has set the QEMU bios image path to {bios_image}'.form...
[ "def", "bios_image", "(", "self", ",", "bios_image", ")", ":", "self", ".", "_bios_image", "=", "self", ".", "manager", ".", "get_abs_image_path", "(", "bios_image", ")", "log", ".", "info", "(", "'QEMU VM \"{name}\" [{id}] has set the QEMU bios image path to {bios_im...
57.1
32.3
def from_xuid(cls, xuid): ''' Instantiates an instance of ``GamerProfile`` from an xuid :param xuid: Xuid to look up :raises: :class:`~xbox.exceptions.GamertagNotFound` :returns: :class:`~xbox.GamerProfile` instance ''' url = 'https://profile.xboxlive....
[ "def", "from_xuid", "(", "cls", ",", "xuid", ")", ":", "url", "=", "'https://profile.xboxlive.com/users/xuid(%s)/profile/settings'", "%", "xuid", "try", ":", "return", "cls", ".", "_fetch", "(", "url", ")", "except", "(", "GamertagNotFound", ",", "InvalidRequest",...
31.631579
24.052632
def create_defaults_for(session, user, only_for=None, detail_values=None): """ Create a sizable amount of defaults for a new user. """ detail_values = detail_values or {} if not user.openid.endswith('.fedoraproject.org'): log.warn("New user not from fedoraproject.org. No defaults set.") r...
[ "def", "create_defaults_for", "(", "session", ",", "user", ",", "only_for", "=", "None", ",", "detail_values", "=", "None", ")", ":", "detail_values", "=", "detail_values", "or", "{", "}", "if", "not", "user", ".", "openid", ".", "endswith", "(", "'.fedora...
39.606061
18.848485
def minimizePowell(objectiveFunction, parameter_guess, verbose=False): ''' Minimizes the objective function using a derivative-free Powell algorithm, starting from an initial parameter guess. Parameters ---------- objectiveFunction : function The function to be minimized. It should tak...
[ "def", "minimizePowell", "(", "objectiveFunction", ",", "parameter_guess", ",", "verbose", "=", "False", ")", ":", "# Execute the minimization, starting from the given parameter guess", "t0", "=", "time", "(", ")", "# Time the process", "OUTPUT", "=", "fmin_powell", "(", ...
42.477273
28.022727
def deprecated_method(to_be_removed_in_version, new_method=None): """This is a decorator which can be used to mark methods as deprecated. It will result in a warning being emitted when the function is used. :param to_be_removed_in_version: Version of this module the decorated method will be removed in. ...
[ "def", "deprecated_method", "(", "to_be_removed_in_version", ",", "new_method", "=", "None", ")", ":", "def", "decorator", "(", "method", ")", ":", "deprecation_message", "=", "generate_method_deprecation_message", "(", "to_be_removed_in_version", "=", "to_be_removed_in_v...
41.8
20.333333
def register_callback_deleted(self, func, serialised=True): """Register a callback function to receive QAPI Unsolicited (resource) DELETED. The callback receives a single argument - the inner message. If `serialised` is not set, the callbacks might arrive out-of-order. """ self._...
[ "def", "register_callback_deleted", "(", "self", ",", "func", ",", "serialised", "=", "True", ")", ":", "self", ".", "__add_callback", "(", "_CB_DELETED", ",", "func", ",", "serialised_if_crud", "=", "serialised", ")" ]
63
19.333333
def create_outbound_email(self, subject, description, email, email_config_id, **kwargs): """Creates an outbound email""" url = 'tickets/outbound_email' priority = kwargs.get('priority', 1) data = { 'subject': subject, 'description': description, 'prior...
[ "def", "create_outbound_email", "(", "self", ",", "subject", ",", "description", ",", "email", ",", "email_config_id", ",", "*", "*", "kwargs", ")", ":", "url", "=", "'tickets/outbound_email'", "priority", "=", "kwargs", ".", "get", "(", "'priority'", ",", "...
37.785714
13.428571
def index(): """ This is not served anywhere in the web application. It is used explicitly in the context of generating static files since flask-frozen requires url_for's to crawl content. url_for's are not used with file.show_file directly and are instead dynamically generated through javascrip...
[ "def", "index", "(", ")", ":", "if", "current_app", ".", "config", "[", "'ARA_PLAYBOOK_OVERRIDE'", "]", "is", "not", "None", ":", "override", "=", "current_app", ".", "config", "[", "'ARA_PLAYBOOK_OVERRIDE'", "]", "files", "=", "(", "models", ".", "File", ...
42.3125
19.6875
def throw_to(self, target, *a): self.ready.append((getcurrent(), ())) """ if len(a) == 1 and isinstance(a[0], preserve_exception): return target.throw(a[0].typ, a[0].val, a[0].tb) """ return target.throw(*a)
[ "def", "throw_to", "(", "self", ",", "target", ",", "*", "a", ")", ":", "self", ".", "ready", ".", "append", "(", "(", "getcurrent", "(", ")", ",", "(", ")", ")", ")", "return", "target", ".", "throw", "(", "*", "a", ")" ]
36.142857
9.571429
def lookup_track(self, track): """ Looks up Django Track object for provided raw importing track object. """ tracks = Track.objects.filter(title__iexact=track.title) for track_obj in tracks: for contributor in track_obj.get_primary_contributors(permitted=False): ...
[ "def", "lookup_track", "(", "self", ",", "track", ")", ":", "tracks", "=", "Track", ".", "objects", ".", "filter", "(", "title__iexact", "=", "track", ".", "title", ")", "for", "track_obj", "in", "tracks", ":", "for", "contributor", "in", "track_obj", "....
41.6
16
def plotConvergenceByObject(results, objectRange, featureRange, numTrials, linestyle='-'): """ Plots the convergence graph: iterations vs number of objects. Each curve shows the convergence for a given number of unique features. """ #################################################...
[ "def", "plotConvergenceByObject", "(", "results", ",", "objectRange", ",", "featureRange", ",", "numTrials", ",", "linestyle", "=", "'-'", ")", ":", "########################################################################", "#", "# Accumulate all the results per column in a conv...
36.860465
22.44186
def notify_exception_handler(*args): """ Provides a notifier exception handler. :param \*args: Arguments. :type \*args: \* :return: Definition success. :rtype: bool """ callback = RuntimeGlobals.components_manager["factory.script_editor"].restore_development_layout foundations.exce...
[ "def", "notify_exception_handler", "(", "*", "args", ")", ":", "callback", "=", "RuntimeGlobals", ".", "components_manager", "[", "\"factory.script_editor\"", "]", ".", "restore_development_layout", "foundations", ".", "exceptions", ".", "base_exception_handler", "(", "...
36.6
23.933333
async def send_file( filename: FilePath, mimetype: Optional[str]=None, as_attachment: bool=False, attachment_filename: Optional[str]=None, add_etags: bool=True, cache_timeout: Optional[int]=None, conditional: bool=False, last_modified: Optional[datetime]=N...
[ "async", "def", "send_file", "(", "filename", ":", "FilePath", ",", "mimetype", ":", "Optional", "[", "str", "]", "=", "None", ",", "as_attachment", ":", "bool", "=", "False", ",", "attachment_filename", ":", "Optional", "[", "str", "]", "=", "None", ","...
38.050847
20.254237
def pattern2re(pattern): """Makes a unicode regular expression from a pattern. Returns ``(start, full_re, int_re)`` where: * `start` is either empty or the subdirectory in which to start searching, * `full_re` is a regular expression object that matches the requested files, i.e. a translation...
[ "def", "pattern2re", "(", "pattern", ")", ":", "pattern_segs", "=", "filter", "(", "None", ",", "pattern", ".", "split", "(", "'/'", ")", ")", "# This anchors the first component either at the start of the string or at", "# the start of a path component", "if", "not", "...
37.538462
18.025641
def add_resource_object(self, path: str, resource, methods: tuple=tuple(), names: Mapping=None): """Add routes by an resource instance's methods. :param path: route path. Should be started with slash (``'/'``). :param resource: A "resource" instance. May be an instance of a plain object. ...
[ "def", "add_resource_object", "(", "self", ",", "path", ":", "str", ",", "resource", ",", "methods", ":", "tuple", "=", "tuple", "(", ")", ",", "names", ":", "Mapping", "=", "None", ")", ":", "names", "=", "names", "or", "{", "}", "if", "methods", ...
48.222222
22.722222
def get_blueprint(service_brokers: Union[List[ServiceBroker], ServiceBroker], broker_credentials: Union[None, List[BrokerCredentials], BrokerCredentials], logger: logging.Logger) -> Blueprint: """ Returns the blueprint with service broker api. :param service_brokers: Ser...
[ "def", "get_blueprint", "(", "service_brokers", ":", "Union", "[", "List", "[", "ServiceBroker", "]", ",", "ServiceBroker", "]", ",", "broker_credentials", ":", "Union", "[", "None", ",", "List", "[", "BrokerCredentials", "]", ",", "BrokerCredentials", "]", ",...
47.379182
26.39777
def getPosArgs(self): """ Return a list, in order, of any parameters marked with "pos=N" in the .cfgspc file. """ if len(self._posArgs) < 1: return [] # The first item in the tuple is the index, so we now sort by it self._posArgs.sort() # Build a return list r...
[ "def", "getPosArgs", "(", "self", ")", ":", "if", "len", "(", "self", ".", "_posArgs", ")", "<", "1", ":", "return", "[", "]", "# The first item in the tuple is the index, so we now sort by it", "self", ".", "_posArgs", ".", "sort", "(", ")", "# Build a return l...
39.916667
12.75
def _and_join(self, terms): """ Joins terms using AND operator. Args: terms (list): terms to join Examples: self._and_join(['term1']) -> 'term1' self._and_join(['term1', 'term2']) -> 'term1 AND term2' self._and_join(['term1', 'term2', 'term3']) -...
[ "def", "_and_join", "(", "self", ",", "terms", ")", ":", "if", "len", "(", "terms", ")", ">", "1", ":", "return", "' AND '", ".", "join", "(", "[", "self", ".", "_or_join", "(", "t", ")", "for", "t", "in", "terms", "]", ")", "else", ":", "retur...
29.388889
21.277778
def transition(self, index, event_time): """Finds the population in each state and moves them to the next state. Parameters ---------- index : iterable of ints An iterable of integer labels for the simulants. event_time : pandas.Timestamp The time at whic...
[ "def", "transition", "(", "self", ",", "index", ",", "event_time", ")", ":", "for", "state", ",", "affected", "in", "self", ".", "_get_state_pops", "(", "index", ")", ":", "if", "not", "affected", ".", "empty", ":", "state", ".", "next_state", "(", "af...
42.461538
17.230769
def regon(self): """ Returns 9 character Polish National Business Registry Number, Polish: Rejestr Gospodarki Narodowej - REGON. https://pl.wikipedia.org/wiki/REGON """ voivodeship_number = self.random_int(0, 49) * 2 + 1 regon_digits = [int(voivodeship_number / 1...
[ "def", "regon", "(", "self", ")", ":", "voivodeship_number", "=", "self", ".", "random_int", "(", "0", ",", "49", ")", "*", "2", "+", "1", "regon_digits", "=", "[", "int", "(", "voivodeship_number", "/", "10", ")", ",", "voivodeship_number", "%", "10",...
33.4375
21.8125
def terminal_cfg_line_sessionid(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") terminal_cfg = ET.SubElement(config, "terminal-cfg", xmlns="urn:brocade.com:mgmt:brocade-terminal") line = ET.SubElement(terminal_cfg, "line") sessionid = ET.SubEleme...
[ "def", "terminal_cfg_line_sessionid", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "terminal_cfg", "=", "ET", ".", "SubElement", "(", "config", ",", "\"terminal-cfg\"", ",", "xmlns", "=", "\"u...
42.818182
15.818182
def _normalize_percent_rgb(value): """ Normalize ``value`` for use in a percentage ``rgb()`` triplet, as follows: * If ``value`` is less than 0%, convert to 0%. * If ``value`` is greater than 100%, convert to 100%. Examples: >>> _normalize_percent_rgb('0%') '0%' >>> _normalize_pe...
[ "def", "_normalize_percent_rgb", "(", "value", ")", ":", "percent", "=", "value", ".", "split", "(", "'%'", ")", "[", "0", "]", "percent", "=", "float", "(", "percent", ")", "if", "'.'", "in", "percent", "else", "int", "(", "percent", ")", "if", "0",...
22.558824
20.205882
def linewidth(self, linewidth=None): """Returns or sets (if a value is provided) the width of the series' line. :param Number linewidth: If given, the series' linewidth will be set to\ this. :rtype: ``Number``""" if linewidth is None: return self._linewidth ...
[ "def", "linewidth", "(", "self", ",", "linewidth", "=", "None", ")", ":", "if", "linewidth", "is", "None", ":", "return", "self", ".", "_linewidth", "else", ":", "if", "not", "is_numeric", "(", "linewidth", ")", ":", "raise", "TypeError", "(", "\"linewid...
32.625
17.8125
def python_dependencies(context: Context, common_path=None): """ Updates python dependencies """ context.pip_command('install', '-r', context.requirements_file) if common_path: context.pip_command('uninstall', '--yes', 'money-to-prisoners-common') context.pip_command('install', '--fo...
[ "def", "python_dependencies", "(", "context", ":", "Context", ",", "common_path", "=", "None", ")", ":", "context", ".", "pip_command", "(", "'install'", ",", "'-r'", ",", "context", ".", "requirements_file", ")", "if", "common_path", ":", "context", ".", "p...
44.666667
18.666667
def find(self, name): """ Returns the Tag that matches the name. :param name: the string representation of the tag :type name: str :return: the tag, None if not found :rtype: Tag """ result = None for t in self.array: if str(t) == name...
[ "def", "find", "(", "self", ",", "name", ")", ":", "result", "=", "None", "for", "t", "in", "self", ".", "array", ":", "if", "str", "(", "t", ")", "==", "name", ":", "result", "=", "Tag", "(", "t", ".", "jobject", ")", "break", "return", "resul...
26.066667
13.533333
def get_relative_to_remote(self): """Return the number of commits we are relative to the remote. Negative is behind, positive in front, zero means we are matched to remote. """ s = self.git("status", "--short", "-b")[0] r = re.compile("\[([^\]]+)\]") toks = r.findall(s) ...
[ "def", "get_relative_to_remote", "(", "self", ")", ":", "s", "=", "self", ".", "git", "(", "\"status\"", ",", "\"--short\"", ",", "\"-b\"", ")", "[", "0", "]", "r", "=", "re", ".", "compile", "(", "\"\\[([^\\]]+)\\]\"", ")", "toks", "=", "r", ".", "f...
38.75
13.75
def make_bezier(n): """ Bezier curves: http://en.wikipedia.org/wiki/B%C3%A9zier_curve#Generalization """ try: return beziers[n] except KeyError: combinations = pascal_row(n - 1) result = [] for t in tsequence: tpowers = (t ** i for i in range(n)) ...
[ "def", "make_bezier", "(", "n", ")", ":", "try", ":", "return", "beziers", "[", "n", "]", "except", "KeyError", ":", "combinations", "=", "pascal_row", "(", "n", "-", "1", ")", "result", "=", "[", "]", "for", "t", "in", "tsequence", ":", "tpowers", ...
34.176471
16.235294
def _validate_translation(self, aligned_prot, aligned_nucl): """ Given a seq for protein and nucleotide, ensure that the translation holds """ codons = [''.join(i) for i in batch(str(aligned_nucl), 3)] for codon, aa in zip(codons, str(aligned_prot)): # Check gaps ...
[ "def", "_validate_translation", "(", "self", ",", "aligned_prot", ",", "aligned_nucl", ")", ":", "codons", "=", "[", "''", ".", "join", "(", "i", ")", "for", "i", "in", "batch", "(", "str", "(", "aligned_nucl", ")", ",", "3", ")", "]", "for", "codon"...
45.541667
19.125
def _make_local_block(x, depth, batch, heads, num_blocks, block_length): """Helper function to create a local version of the keys or values for 1d.""" prev_block = tf.slice(x, [0, 0, 0, 0, 0], [-1, -1, num_blocks - 1, -1, -1]) cur_block = tf.slice(x, [0, 0, 1, 0, 0], [-1, -1, -1, -1, -1]) ...
[ "def", "_make_local_block", "(", "x", ",", "depth", ",", "batch", ",", "heads", ",", "num_blocks", ",", "block_length", ")", ":", "prev_block", "=", "tf", ".", "slice", "(", "x", ",", "[", "0", ",", "0", ",", "0", ",", "0", ",", "0", "]", ",", ...
59.5
16.625
def format(self, record): """Formats a log record and serializes to json""" message_dict = {} if isinstance(record.msg, dict): message_dict = record.msg record.message = None else: record.message = record.getMessage() # only format time if need...
[ "def", "format", "(", "self", ",", "record", ")", ":", "message_dict", "=", "{", "}", "if", "isinstance", "(", "record", ".", "msg", ",", "dict", ")", ":", "message_dict", "=", "record", ".", "msg", "record", ".", "message", "=", "None", "else", ":",...
40.527778
20.166667
def validate(self, value): "Check if value consists only of valid emails." # Use the parent's handling of required fields, etc. super(MultiEmailField, self).validate(value) try: for email in value: validate_email(email) except ValidationError: ...
[ "def", "validate", "(", "self", ",", "value", ")", ":", "# Use the parent's handling of required fields, etc.", "super", "(", "MultiEmailField", ",", "self", ")", ".", "validate", "(", "value", ")", "try", ":", "for", "email", "in", "value", ":", "validate_email...
36.7
17.3
def scalogram(M, circ=False): """Computes so-called 'scalograms' used to easily visualize contacts at different distance scales. Edge cases have been painstakingly taken care of. """ # Sanity checks if not type(M) is np.ndarray: M = np.array(M) if M.shape[0] != M.shape[1]: ...
[ "def", "scalogram", "(", "M", ",", "circ", "=", "False", ")", ":", "# Sanity checks", "if", "not", "type", "(", "M", ")", "is", "np", ".", "ndarray", ":", "M", "=", "np", ".", "array", "(", "M", ")", "if", "M", ".", "shape", "[", "0", "]", "!...
30.264706
17.617647
def _save_uploaded_file_list(samples, file_list_work, out_dir): """ Fixes all absolute work-rooted paths to relative final-rooted paths For CWL, prepare paths relative to output directory. """ if not utils.file_exists(file_list_work): return None if any([cwlutils.is_cwl_run(d) for d in sam...
[ "def", "_save_uploaded_file_list", "(", "samples", ",", "file_list_work", ",", "out_dir", ")", ":", "if", "not", "utils", ".", "file_exists", "(", "file_list_work", ")", ":", "return", "None", "if", "any", "(", "[", "cwlutils", ".", "is_cwl_run", "(", "d", ...
38.257143
18.942857
def destination(self) : "the bus name that the message is to be sent to." result = dbus.dbus_message_get_destination(self._dbobj) if result != None : result = result.decode() #end if return \ result
[ "def", "destination", "(", "self", ")", ":", "result", "=", "dbus", ".", "dbus_message_get_destination", "(", "self", ".", "_dbobj", ")", "if", "result", "!=", "None", ":", "result", "=", "result", ".", "decode", "(", ")", "#end if", "return", "result" ]
31.875
18.125
def removeStepListener(listener): """removeStepListener(traci.StepListener) -> bool Remove the step listener from traci's step listener container. Returns True if the listener was removed successfully, False if it wasn't registered. """ if listener in _stepListeners: _stepListeners.remove(l...
[ "def", "removeStepListener", "(", "listener", ")", ":", "if", "listener", "in", "_stepListeners", ":", "_stepListeners", ".", "remove", "(", "listener", ")", "return", "True", "warnings", ".", "warn", "(", "\"removeStepListener(listener): listener %s not registered as s...
39.5
21.333333
def to_bytes(self, exclude=tuple(), disable=None, **kwargs): """Serialize the current state to a binary string. exclude (list): Names of components or serialization fields to exclude. RETURNS (bytes): The serialized form of the `Language` object. DOCS: https://spacy.io/api/language#to_...
[ "def", "to_bytes", "(", "self", ",", "exclude", "=", "tuple", "(", ")", ",", "disable", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "disable", "is", "not", "None", ":", "deprecation_warning", "(", "Warnings", ".", "W014", ")", "exclude", "=...
46.086957
19.26087