text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def warn(self,message): """write a warning to the log file. Parameters ---------- message : str the warning text """ s = str(datetime.now()) + " WARNING: " + message + '\n' if self.echo: print(s,end='') if self.filename: ...
[ "def", "warn", "(", "self", ",", "message", ")", ":", "s", "=", "str", "(", "datetime", ".", "now", "(", ")", ")", "+", "\" WARNING: \"", "+", "message", "+", "'\\n'", "if", "self", ".", "echo", ":", "print", "(", "s", ",", "end", "=", "''", ")...
25.733333
15.6
def dec2bin(s): """ dec2bin 十进制 to 二进制: bin() :param s: :return: """ if not isinstance(s, int): num = int(s) else: num = s mid = [] while True: if num == 0: break num, rem = divmod(num, 2) mid.append(base[rem]) return ''.jo...
[ "def", "dec2bin", "(", "s", ")", ":", "if", "not", "isinstance", "(", "s", ",", "int", ")", ":", "num", "=", "int", "(", "s", ")", "else", ":", "num", "=", "s", "mid", "=", "[", "]", "while", "True", ":", "if", "num", "==", "0", ":", "break...
17.526316
19.736842
def delete_audit_sink(self, name, **kwargs): """ delete an AuditSink This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.delete_audit_sink(name, async_req=True) >>> result = thread.get(...
[ "def", "delete_audit_sink", "(", "self", ",", "name", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async_req'", ")", ":", "return", "self", ".", "delete_audit_sink_with_htt...
91.153846
64.076923
def route(method, pattern, handler=None): """register a routing rule Example: route('GET', '/path/<param>', handler) """ if handler is None: return partial(route, method, pattern) return routes.append(method, pattern, handler)
[ "def", "route", "(", "method", ",", "pattern", ",", "handler", "=", "None", ")", ":", "if", "handler", "is", "None", ":", "return", "partial", "(", "route", ",", "method", ",", "pattern", ")", "return", "routes", ".", "append", "(", "method", ",", "p...
23.272727
17.181818
def picard_mark_duplicates(job, bam, bai, validation_stringency='LENIENT'): """ Runs Picard MarkDuplicates on a BAM file. Requires that the BAM file be coordinate sorted. :param JobFunctionWrappingJob job: passed automatically by Toil :param str bam: FileStoreID for BAM file :param str bai: FileSto...
[ "def", "picard_mark_duplicates", "(", "job", ",", "bam", ",", "bai", ",", "validation_stringency", "=", "'LENIENT'", ")", ":", "work_dir", "=", "job", ".", "fileStore", ".", "getLocalTempDir", "(", ")", "# Retrieve file path", "job", ".", "fileStore", ".", "re...
43.363636
22.363636
def pairwise_corr(data, columns=None, covar=None, tail='two-sided', method='pearson', padjust='none', export_filename=None): '''Pairwise (partial) correlations between columns of a pandas dataframe. Parameters ---------- data : pandas DataFrame DataFrame. Note that this functi...
[ "def", "pairwise_corr", "(", "data", ",", "columns", "=", "None", ",", "covar", "=", "None", ",", "tail", "=", "'two-sided'", ",", "method", "=", "'pearson'", ",", "padjust", "=", "'none'", ",", "export_filename", "=", "None", ")", ":", "from", "pingouin...
42.730519
22.068182
def verbosityToLogLevel(verbosity): """ Returns the specfied verbosity level interpreted as a logging level. """ ret = 0 if verbosity == 1: ret = logging.INFO elif verbosity >= 2: ret = logging.DEBUG return ret
[ "def", "verbosityToLogLevel", "(", "verbosity", ")", ":", "ret", "=", "0", "if", "verbosity", "==", "1", ":", "ret", "=", "logging", ".", "INFO", "elif", "verbosity", ">=", "2", ":", "ret", "=", "logging", ".", "DEBUG", "return", "ret" ]
24.5
15.3
def create(self, stage, scp_config, config=None): '''Create a pipeline stage. Instantiates `stage` with `config`. This essentially translates to ``stage(config)``, except that two keys from `scp_config` are injected into the configuration: ``tmp_dir_path`` is an execution-speci...
[ "def", "create", "(", "self", ",", "stage", ",", "scp_config", ",", "config", "=", "None", ")", ":", "# Figure out what we have for a stage and its name", "if", "isinstance", "(", "stage", ",", "basestring", ")", ":", "stage_name", "=", "stage", "stage_obj", "="...
39.656716
23.029851
def select_atoms(indices): '''Select atoms by their indices. You can select the first 3 atoms as follows:: select_atoms([0, 1, 2]) Return the current selection dictionary. ''' rep = current_representation() rep.select({'atoms': Selection(indices, current_system().n_atoms)}) ret...
[ "def", "select_atoms", "(", "indices", ")", ":", "rep", "=", "current_representation", "(", ")", "rep", ".", "select", "(", "{", "'atoms'", ":", "Selection", "(", "indices", ",", "current_system", "(", ")", ".", "n_atoms", ")", "}", ")", "return", "rep",...
25.461538
21.307692
def ApprovalUrnBuilder(subject, user, approval_id): """Encode an approval URN.""" return aff4.ROOT_URN.Add("ACL").Add(subject).Add(user).Add(approval_id)
[ "def", "ApprovalUrnBuilder", "(", "subject", ",", "user", ",", "approval_id", ")", ":", "return", "aff4", ".", "ROOT_URN", ".", "Add", "(", "\"ACL\"", ")", ".", "Add", "(", "subject", ")", ".", "Add", "(", "user", ")", ".", "Add", "(", "approval_id", ...
53
15.333333
def run_workers(no_subprocess, watch_paths=None, is_background=False): """ subprocess handler """ import atexit, os, subprocess, signal if watch_paths: from watchdog.observers import Observer # from watchdog.observers.fsevents import FSEventsObserver as Observer # from watchd...
[ "def", "run_workers", "(", "no_subprocess", ",", "watch_paths", "=", "None", ",", "is_background", "=", "False", ")", ":", "import", "atexit", ",", "os", ",", "subprocess", ",", "signal", "if", "watch_paths", ":", "from", "watchdog", ".", "observers", "impor...
32.636364
16.787879
def get_full_permission_string(self, perm): """ Return full permission string (app_label.perm_model) """ if not getattr(self, 'model', None): raise AttributeError("You need to use `add_permission_logic` to " "register the instance to the model...
[ "def", "get_full_permission_string", "(", "self", ",", "perm", ")", ":", "if", "not", "getattr", "(", "self", ",", "'model'", ",", "None", ")", ":", "raise", "AttributeError", "(", "\"You need to use `add_permission_logic` to \"", "\"register the instance to the model c...
49.545455
14.818182
def add_enrollment(db, uuid, organization, from_date=None, to_date=None): """Enroll a unique identity to an organization. The function adds a new relationship between the unique identity identified by 'uuid' and the given 'organization'. The given identity and organization must exist prior to add this ...
[ "def", "add_enrollment", "(", "db", ",", "uuid", ",", "organization", ",", "from_date", "=", "None", ",", "to_date", "=", "None", ")", ":", "if", "uuid", "is", "None", ":", "raise", "InvalidValueError", "(", "'uuid cannot be None'", ")", "if", "uuid", "=="...
38.542373
22.067797
def _to_dict(self): """ Converts object into a dictionary. """ for i, tag in enumerate(self.tags): if tag in ("", None): self.tags.pop(i) data = { 'name': self.name, 'referenceId': self.reference_id, 'shortDescripti...
[ "def", "_to_dict", "(", "self", ")", ":", "for", "i", ",", "tag", "in", "enumerate", "(", "self", ".", "tags", ")", ":", "if", "tag", "in", "(", "\"\"", ",", "None", ")", ":", "self", ".", "tags", ".", "pop", "(", "i", ")", "data", "=", "{", ...
36.548387
10.16129
def get_resource_metadata(self, resource=None): """ Get resource metadata :param resource: The name of the resource to get metadata for :return: list """ result = self._make_metadata_request(meta_id=0, metadata_type='METADATA-RESOURCE') if resource: re...
[ "def", "get_resource_metadata", "(", "self", ",", "resource", "=", "None", ")", ":", "result", "=", "self", ".", "_make_metadata_request", "(", "meta_id", "=", "0", ",", "metadata_type", "=", "'METADATA-RESOURCE'", ")", "if", "resource", ":", "result", "=", ...
41.1
20.7
def array_to_csv(array_like): # type: (np.array or Iterable or int or float) -> str """Convert an array like object to CSV. To understand better what an array like object is see: https://docs.scipy.org/doc/numpy/user/basics.creation.html#converting-python-array-like-objects-to-numpy-arrays Args: ...
[ "def", "array_to_csv", "(", "array_like", ")", ":", "# type: (np.array or Iterable or int or float) -> str", "stream", "=", "StringIO", "(", ")", "np", ".", "savetxt", "(", "stream", ",", "array_like", ",", "delimiter", "=", "','", ",", "fmt", "=", "'%s'", ")", ...
38.466667
28.333333
def light_general_attention(key, context, hidden_size, projected_align=False): """ It is a implementation of the Luong et al. attention mechanism with general score. Based on the paper: https://arxiv.org/abs/1508.04025 "Effective Approaches to Attention-based Neural Machine Translation" Args: ke...
[ "def", "light_general_attention", "(", "key", ",", "context", ",", "hidden_size", ",", "projected_align", "=", "False", ")", ":", "batch_size", "=", "tf", ".", "shape", "(", "context", ")", "[", "0", "]", "max_num_tokens", ",", "token_size", "=", "context", ...
52.605263
27.842105
def registerToDataTypes( cls ): """ Registers this class as a valid datatype for saving and loading via the datatype system. """ from projexui.xdatatype import registerDataType registerDataType(cls.__name__, lambda pyvalue: pyvalue.toString(), lam...
[ "def", "registerToDataTypes", "(", "cls", ")", ":", "from", "projexui", ".", "xdatatype", "import", "registerDataType", "registerDataType", "(", "cls", ".", "__name__", ",", "lambda", "pyvalue", ":", "pyvalue", ".", "toString", "(", ")", ",", "lambda", "qvaria...
40.666667
12.222222
def list_parse(name_list): """Parse a comma-separated list of values, or a filename (starting with @) containing a list value on each line. """ if name_list and name_list[0] == '@': value = name_list[1:] if not os.path.exists(value): log.warning('The file %s does not exist' ...
[ "def", "list_parse", "(", "name_list", ")", ":", "if", "name_list", "and", "name_list", "[", "0", "]", "==", "'@'", ":", "value", "=", "name_list", "[", "1", ":", "]", "if", "not", "os", ".", "path", ".", "exists", "(", "value", ")", ":", "log", ...
36.176471
15.411765
def export_transcripts(adapter, build='37'): """Export all transcripts from the database Args: adapter(scout.adapter.MongoAdapter) build(str) Yields: transcript(scout.models.Transcript) """ LOG.info("Exporting all transcripts") for tx_obj in adapter.transcripts...
[ "def", "export_transcripts", "(", "adapter", ",", "build", "=", "'37'", ")", ":", "LOG", ".", "info", "(", "\"Exporting all transcripts\"", ")", "for", "tx_obj", "in", "adapter", ".", "transcripts", "(", "build", "=", "build", ")", ":", "yield", "tx_obj" ]
24.428571
16.857143
def p(self, value, event): """Return the conditional probability P(X=value | parents=parent_values), where parent_values are the values of parents in event. (event must assign each parent a value.) >>> bn = BayesNode('X', 'Burglary', {T: 0.2, F: 0.625}) >>> bn.p(False, {'...
[ "def", "p", "(", "self", ",", "value", ",", "event", ")", ":", "assert", "isinstance", "(", "value", ",", "bool", ")", "ptrue", "=", "self", ".", "cpt", "[", "event_values", "(", "event", ",", "self", ".", "parents", ")", "]", "return", "if_", "(",...
46.181818
13.727273
def _StatusUpdateThreadMain(self): """Main function of the status update thread.""" while self._status_update_active: # Make a local copy of the PIDs in case the dict is changed by # the main thread. for pid in list(self._process_information_per_pid.keys()): self._CheckStatusAnalysisPr...
[ "def", "_StatusUpdateThreadMain", "(", "self", ")", ":", "while", "self", ".", "_status_update_active", ":", "# Make a local copy of the PIDs in case the dict is changed by", "# the main thread.", "for", "pid", "in", "list", "(", "self", ".", "_process_information_per_pid", ...
36.357143
16.5
def clear_data(self): """ Clear menu data from previous menu generation. """ self.__header.title = None self.__header.subtitle = None self.__prologue.text = None self.__epilogue.text = None self.__items_section.items = None
[ "def", "clear_data", "(", "self", ")", ":", "self", ".", "__header", ".", "title", "=", "None", "self", ".", "__header", ".", "subtitle", "=", "None", "self", ".", "__prologue", ".", "text", "=", "None", "self", ".", "__epilogue", ".", "text", "=", "...
31
5.888889
def write(self, data, mode='w'): """ Write data to the file. `data` is the data to write `mode` is the mode argument to pass to `open()` """ with open(self.path, mode) as f: f.write(data)
[ "def", "write", "(", "self", ",", "data", ",", "mode", "=", "'w'", ")", ":", "with", "open", "(", "self", ".", "path", ",", "mode", ")", "as", "f", ":", "f", ".", "write", "(", "data", ")" ]
26.666667
10.222222
def handle_get_vts_command(self, vt_et): """ Handles <get_vts> command. @return: Response string for <get_vts> command. """ vt_id = vt_et.attrib.get('vt_id') vt_filter = vt_et.attrib.get('filter') if vt_id and vt_id not in self.vts: text = "Failed to find v...
[ "def", "handle_get_vts_command", "(", "self", ",", "vt_et", ")", ":", "vt_id", "=", "vt_et", ".", "attrib", ".", "get", "(", "'vt_id'", ")", "vt_filter", "=", "vt_et", ".", "attrib", ".", "get", "(", "'filter'", ")", "if", "vt_id", "and", "vt_id", "not...
29.36
21.08
def fillNoneValues(column): """Fill all NaN/NaT values of a column with an empty string Args: column (pandas.Series): A Series object with all rows. Returns: column: Series with filled NaN values. """ if column.dtype == object: column.fillna('', inplace=True) return col...
[ "def", "fillNoneValues", "(", "column", ")", ":", "if", "column", ".", "dtype", "==", "object", ":", "column", ".", "fillna", "(", "''", ",", "inplace", "=", "True", ")", "return", "column" ]
26
17.833333
def get_element_masses(self): """ Get the masses of elements in the package. :returns: [kg] An array of element masses. The sequence of the elements in the result corresponds with the sequence of elements in the element list of the material. """ result = [0]...
[ "def", "get_element_masses", "(", "self", ")", ":", "result", "=", "[", "0", "]", "*", "len", "(", "self", ".", "material", ".", "elements", ")", "for", "compound", "in", "self", ".", "material", ".", "compounds", ":", "c", "=", "self", ".", "get_com...
36.8125
19.3125
def cookie_signature(seed, *parts): """Generates a cookie signature.""" sha1 = hmac.new(seed, digestmod=hashlib.sha1) for part in parts: if part: sha1.update(part) return sha1.hexdigest()
[ "def", "cookie_signature", "(", "seed", ",", "*", "parts", ")", ":", "sha1", "=", "hmac", ".", "new", "(", "seed", ",", "digestmod", "=", "hashlib", ".", "sha1", ")", "for", "part", "in", "parts", ":", "if", "part", ":", "sha1", ".", "update", "(",...
31
11.428571
def step_I_create_logrecords_with_table(context): """ Step definition that creates one more log records by using a table. .. code-block: gherkin When I create log records with: | category | level | message | | foo | ERROR | Hello Foo | | foo.bar | WARN ...
[ "def", "step_I_create_logrecords_with_table", "(", "context", ")", ":", "assert", "context", ".", "table", ",", "\"REQUIRE: context.table\"", "context", ".", "table", ".", "require_columns", "(", "[", "\"category\"", ",", "\"level\"", ",", "\"message\"", "]", ")", ...
34.216216
16.216216
def get_obj_class(self, obj_type): """ Returns the object class based on parent and object types. In most cases the object class can be derived from object type alone but sometimes the same object type name is used for different object types so the parent (or even grandparent) type is r...
[ "def", "get_obj_class", "(", "self", ",", "obj_type", ")", ":", "if", "obj_type", "in", "IxnObject", ".", "str_2_class", ":", "if", "type", "(", "IxnObject", ".", "str_2_class", "[", "obj_type", "]", ")", "is", "dict", ":", "if", "self", ".", "obj_type",...
54.045455
29
def batch(self, table_name, timeout=None): ''' Creates a batch object which can be used as a context manager. Commits the batch on exit. :param str table_name: The name of the table to commit the batch to. :param int timeout: The server timeout, expressed in seco...
[ "def", "batch", "(", "self", ",", "table_name", ",", "timeout", "=", "None", ")", ":", "batch", "=", "TableBatch", "(", ")", "yield", "batch", "self", ".", "commit_batch", "(", "table_name", ",", "batch", ",", "timeout", "=", "timeout", ")" ]
36.333333
22
def run_filter_radia(job, bams, radia_file, univ_options, radia_options, chrom): """ This module will run filterradia on the RNA and DNA bams. ARGUMENTS 1. bams: REFER ARGUMENTS of run_radia() 2. univ_options: REFER ARGUMENTS of run_radia() 3. radia_file: <JSid of vcf generated by run_radia()> ...
[ "def", "run_filter_radia", "(", "job", ",", "bams", ",", "radia_file", ",", "univ_options", ",", "radia_options", ",", "chrom", ")", ":", "job", ".", "fileStore", ".", "logToMaster", "(", "'Running filter-radia on %s:%s'", "%", "(", "univ_options", "[", "'patien...
46.854839
16.33871
def _reflect_table(self): """Load the tables definition from the database.""" with self.db.lock: try: self._table = SQLATable(self.name, self.db.metadata, schema=self.db.schema, ...
[ "def", "_reflect_table", "(", "self", ")", ":", "with", "self", ".", "db", ".", "lock", ":", "try", ":", "self", ".", "_table", "=", "SQLATable", "(", "self", ".", "name", ",", "self", ".", "db", ".", "metadata", ",", "schema", "=", "self", ".", ...
40.5
14
def _process_cell(i, state, finite=False): """Process 3 cells and return a value from 0 to 7. """ op_1 = state[i - 1] op_2 = state[i] if i == len(state) - 1: if finite: op_3 = state[0] else: op_3 = 0 else: op_3 = state[i + 1] result = 0 for i, ...
[ "def", "_process_cell", "(", "i", ",", "state", ",", "finite", "=", "False", ")", ":", "op_1", "=", "state", "[", "i", "-", "1", "]", "op_2", "=", "state", "[", "i", "]", "if", "i", "==", "len", "(", "state", ")", "-", "1", ":", "if", "finite...
25.1875
17.1875
def scale_0to1(image_in, exclude_outliers_below=False, exclude_outliers_above=False): """Scale the two images to [0, 1] based on min/max from both. Parameters ----------- image_in : ndarray Input image exclude_outliers_{below,above} : float Lower/upper...
[ "def", "scale_0to1", "(", "image_in", ",", "exclude_outliers_below", "=", "False", ",", "exclude_outliers_above", "=", "False", ")", ":", "min_value", "=", "image_in", ".", "min", "(", ")", "max_value", "=", "image_in", ".", "max", "(", ")", "# making a copy t...
25.666667
20.333333
def fetchImageUrl(self, image_id): """Fetches the url to the original image from an image attachment ID :param image_id: The image you want to fethc :type image_id: str :return: An url where you can download the original image :rtype: str :raises: FBchatException if requ...
[ "def", "fetchImageUrl", "(", "self", ",", "image_id", ")", ":", "image_id", "=", "str", "(", "image_id", ")", "data", "=", "{", "\"photo_id\"", ":", "str", "(", "image_id", ")", "}", "j", "=", "self", ".", "_get", "(", "ReqUrl", ".", "ATTACHMENT_PHOTO"...
35.684211
18.263158
def build_url_field(self, field_name, model_class): """ Create a field representing the object's own URL. """ field_class = self.serializer_url_field field_kwargs = get_url_kwargs(model_class) return field_class, field_kwargs
[ "def", "build_url_field", "(", "self", ",", "field_name", ",", "model_class", ")", ":", "field_class", "=", "self", ".", "serializer_url_field", "field_kwargs", "=", "get_url_kwargs", "(", "model_class", ")", "return", "field_class", ",", "field_kwargs" ]
33.375
10.625
def write(self, document, obj, *args, **kwargs): """ Returns a Deferred that fire the factory result that should be the document. """ try: document = IWritableDocument(document) mime_type = document.mime_type writer = self.lookup_writer(mime_ty...
[ "def", "write", "(", "self", ",", "document", ",", "obj", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "document", "=", "IWritableDocument", "(", "document", ")", "mime_type", "=", "document", ".", "mime_type", "writer", "=", "self"...
40.3125
12.8125
def splitFASTA(params): """ Read the FASTA file named params['fastaFile'] and print out its sequences into files named 0.fasta, 1.fasta, etc. with params['seqsPerJob'] sequences per file. """ assert params['fastaFile'][-1] == 'a', ('You must specify a file in ' ...
[ "def", "splitFASTA", "(", "params", ")", ":", "assert", "params", "[", "'fastaFile'", "]", "[", "-", "1", "]", "==", "'a'", ",", "(", "'You must specify a file in '", "'fasta-format that ends in '", "'.fasta'", ")", "fileCount", "=", "count", "=", "seqCount", ...
36.84
15.56
def delete_patch(self, patch_name=None, remove=False, backup=False): """ Delete specified patch from the series If remove is True the patch file will also be removed. If remove and backup are True a copy of the deleted patch file will be made. """ if patch_name: patch...
[ "def", "delete_patch", "(", "self", ",", "patch_name", "=", "None", ",", "remove", "=", "False", ",", "backup", "=", "False", ")", ":", "if", "patch_name", ":", "patch", "=", "Patch", "(", "patch_name", ")", "else", ":", "patch", "=", "self", ".", "d...
39.923077
17.384615
def serialize_dict(self, value): """ Ensure that all values of a dictionary are properly serialized :param value: :return: """ # Check if this is a dict if not isinstance(value, dict): return value # Loop over all the values and serialize the...
[ "def", "serialize_dict", "(", "self", ",", "value", ")", ":", "# Check if this is a dict", "if", "not", "isinstance", "(", "value", ",", "dict", ")", ":", "return", "value", "# Loop over all the values and serialize them", "return", "{", "dict_key", ":", "self", "...
27.625
17.5
def first_return(): """Generate a random walk and return its length upto the moment that the walker first returns to the origin. It is mathematically provable that the walker will eventually return, meaning that the function call will halt, although it may take a *very* long time and your computer may run out of ...
[ "def", "first_return", "(", ")", ":", "walk", "=", "randwalk", "(", ")", ">>", "drop", "(", "1", ")", ">>", "takewhile", "(", "lambda", "v", ":", "v", "!=", "Origin", ")", ">>", "list", "return", "len", "(", "walk", ")" ]
40.909091
18.181818
def _send_string_clipboard(self, string: str, paste_command: model.SendMode): """ Use the clipboard to send a string. """ backup = self.clipboard.text # Keep a backup of current content, to restore the original afterwards. if backup is None: logger.warning("Tried to ...
[ "def", "_send_string_clipboard", "(", "self", ",", "string", ":", "str", ",", "paste_command", ":", "model", ".", "SendMode", ")", ":", "backup", "=", "self", ".", "clipboard", ".", "text", "# Keep a backup of current content, to restore the original afterwards.", "if...
50.642857
25.642857
def disconnect(self): """Disconnect from the socket.""" if self.pipeline: self._send(*self.pipeline) self.pipeline = None
[ "def", "disconnect", "(", "self", ")", ":", "if", "self", ".", "pipeline", ":", "self", ".", "_send", "(", "*", "self", ".", "pipeline", ")", "self", ".", "pipeline", "=", "None" ]
30.6
9.6
def get_as_datetime_with_default(self, index, default_value): """ Converts array element into a Date or returns default value if conversion is not possible. :param index: an index of element to get. :param default_value: the default value :return: Date value ot the element or ...
[ "def", "get_as_datetime_with_default", "(", "self", ",", "index", ",", "default_value", ")", ":", "value", "=", "self", "[", "index", "]", "return", "DateTimeConverter", ".", "to_datetime_with_default", "(", "value", ",", "default_value", ")" ]
39.5
26.5
def health_check(self): """Gets a single item to determine if Dynamo is functioning.""" logger.debug('Health Check on Table: {namespace}'.format( namespace=self.namespace )) try: self.get_all() return True except ClientError as e: ...
[ "def", "health_check", "(", "self", ")", ":", "logger", ".", "debug", "(", "'Health Check on Table: {namespace}'", ".", "format", "(", "namespace", "=", "self", ".", "namespace", ")", ")", "try", ":", "self", ".", "get_all", "(", ")", "return", "True", "ex...
30.714286
20.357143
def walk_paths(self, base: Optional[pathlib.PurePath] = pathlib.PurePath()) \ -> Iterator[pathlib.PurePath]: """ Recursively traverse all paths inside this entity, including the entity itself. :param base: The base path to prepend to the entity name. ...
[ "def", "walk_paths", "(", "self", ",", "base", ":", "Optional", "[", "pathlib", ".", "PurePath", "]", "=", "pathlib", ".", "PurePath", "(", ")", ")", "->", "Iterator", "[", "pathlib", ".", "PurePath", "]", ":", "raise", "NotImplementedError", "(", ")" ]
35.545455
17.545455
def move_layer_down(self): """Move the layer down.""" layer = self.list_layers_in_map_report.selectedItems()[0] index = self.list_layers_in_map_report.indexFromItem(layer).row() item = self.list_layers_in_map_report.takeItem(index) self.list_layers_in_map_report.insertItem(index ...
[ "def", "move_layer_down", "(", "self", ")", ":", "layer", "=", "self", ".", "list_layers_in_map_report", ".", "selectedItems", "(", ")", "[", "0", "]", "index", "=", "self", ".", "list_layers_in_map_report", ".", "indexFromItem", "(", "layer", ")", ".", "row...
56.714286
21.571429
def mkdtemp(suffix="", prefix=template, dir=None): """User-callable function to create and return a unique temporary directory. The return value is the pathname of the directory. Arguments are as for mkstemp, except that the 'text' argument is not accepted. The directory is readable, writable, an...
[ "def", "mkdtemp", "(", "suffix", "=", "\"\"", ",", "prefix", "=", "template", ",", "dir", "=", "None", ")", ":", "if", "dir", "is", "None", ":", "dir", "=", "gettempdir", "(", ")", "names", "=", "_get_candidate_names", "(", ")", "for", "seq", "in", ...
29.965517
21.482759
def _check_type(self): """Check that point value types match the descriptor type.""" check_type = metric_descriptor.MetricDescriptorType.to_type_class( self.descriptor.type) for ts in self.time_series: if not ts.check_points_type(check_type): raise ValueEr...
[ "def", "_check_type", "(", "self", ")", ":", "check_type", "=", "metric_descriptor", ".", "MetricDescriptorType", ".", "to_type_class", "(", "self", ".", "descriptor", ".", "type", ")", "for", "ts", "in", "self", ".", "time_series", ":", "if", "not", "ts", ...
49.285714
13.714286
def choices(self): """Menu options for new configuration files """ print("| {0}K{1}{2}eep the old and .new files, no changes".format( self.red, self.endc, self.br)) print("| {0}O{1}{2}verwrite all old configuration files with new " "ones".format(self.red, self.e...
[ "def", "choices", "(", "self", ")", ":", "print", "(", "\"| {0}K{1}{2}eep the old and .new files, no changes\"", ".", "format", "(", "self", ".", "red", ",", "self", ".", "endc", ",", "self", ".", "br", ")", ")", "print", "(", "\"| {0}O{1}{2}verwrite all old con...
41.035714
16.392857
def param_value_encode(self, param_id, param_value, param_type, param_count, param_index): ''' Emit the value of a onboard parameter. The inclusion of param_count and param_index in the message allows the recipient to keep track of received parameters and ...
[ "def", "param_value_encode", "(", "self", ",", "param_id", ",", "param_value", ",", "param_type", ",", "param_count", ",", "param_index", ")", ":", "return", "MAVLink_param_value_message", "(", "param_id", ",", "param_value", ",", "param_type", ",", "param_count", ...
80.466667
56.733333
def convert(qlr, images, label, **kwargs): r"""Converts one or more images to a raster instruction file. :param qlr: An instance of the BrotherQLRaster class :type qlr: :py:class:`brother_ql.raster.BrotherQLRaster` :param images: The images to be converted. They can be filenames or ins...
[ "def", "convert", "(", "qlr", ",", "images", ",", "label", ",", "*", "*", "kwargs", ")", ":", "label_specs", "=", "label_type_specs", "[", "label", "]", "dots_printable", "=", "label_specs", "[", "'dots_printable'", "]", "right_margin_dots", "=", "label_specs"...
38.045714
19.371429
def remove_first(self): """Removes first :return: True iff head has been removed """ if self.head is None: return False self.head = self.head.next_node return True
[ "def", "remove_first", "(", "self", ")", ":", "if", "self", ".", "head", "is", "None", ":", "return", "False", "self", ".", "head", "=", "self", ".", "head", ".", "next_node", "return", "True" ]
19.636364
17.545455
def text(self): """ Return the String assosicated with the current text """ if self.m_name == -1 or self.m_event != const.TEXT: return u'' return self.sb[self.m_name]
[ "def", "text", "(", "self", ")", ":", "if", "self", ".", "m_name", "==", "-", "1", "or", "self", ".", "m_event", "!=", "const", ".", "TEXT", ":", "return", "u''", "return", "self", ".", "sb", "[", "self", ".", "m_name", "]" ]
26.5
15.75
def fit_quantile(self, X, y, quantile, max_iter=20, tol=0.01, weights=None): """fit ExpectileGAM to a desired quantile via binary search Parameters ---------- X : array-like, shape (n_samples, m_features) Training vectors, where n_samples is the number of samples ...
[ "def", "fit_quantile", "(", "self", ",", "X", ",", "y", ",", "quantile", ",", "max_iter", "=", "20", ",", "tol", "=", "0.01", ",", "weights", "=", "None", ")", ":", "def", "_within_tol", "(", "a", ",", "b", ",", "tol", ")", ":", "return", "np", ...
33.028986
19.608696
def p_if_else(p): """ statement : if_then_part NEWLINE program_co else_part """ cond_ = p[1] then_ = p[3] else_ = p[4][0] endif = p[4][1] p[0] = make_sentence('IF', cond_, then_, make_block(else_, endif), lineno=p.lineno(2))
[ "def", "p_if_else", "(", "p", ")", ":", "cond_", "=", "p", "[", "1", "]", "then_", "=", "p", "[", "3", "]", "else_", "=", "p", "[", "4", "]", "[", "0", "]", "endif", "=", "p", "[", "4", "]", "[", "1", "]", "p", "[", "0", "]", "=", "ma...
30.625
20.375
def lastgenome(args): """ %prog genome_A.fasta genome_B.fasta Run LAST by calling LASTDB, LASTAL and LAST-SPLIT. The recipe is based on tutorial here: <https://github.com/mcfrith/last-genome-alignments> The script runs the following steps: $ lastdb -P0 -uNEAR -R01 Chr10A-NEAR Chr10A.fa ...
[ "def", "lastgenome", "(", "args", ")", ":", "from", "jcvi", ".", "apps", ".", "grid", "import", "MakeManager", "p", "=", "OptionParser", "(", "lastgenome", ".", "__doc__", ")", "opts", ",", "args", "=", "p", ".", "parse_args", "(", "args", ")", "if", ...
31.428571
20.734694
def init(self): """ Init or reset the virtual device. :rtype: str :return: The initial response of the virtual device. """ self.logged_in = False if self.login_type == self.LOGIN_TYPE_PASSWORDONLY: self.prompt_stage = self.PROMPT_STAGE_PASSWORD ...
[ "def", "init", "(", "self", ")", ":", "self", ".", "logged_in", "=", "False", "if", "self", ".", "login_type", "==", "self", ".", "LOGIN_TYPE_PASSWORDONLY", ":", "self", ".", "prompt_stage", "=", "self", ".", "PROMPT_STAGE_PASSWORD", "elif", "self", ".", "...
31.294118
18.470588
def main(arguments=None): '''Converts a given url with the specified arguments.''' parsed_options, arguments = get_options(arguments) image_url = arguments[0] image_url = quote(image_url) try: config = Config.load(None) except Exception: config = None if not parsed_option...
[ "def", "main", "(", "arguments", "=", "None", ")", ":", "parsed_options", ",", "arguments", "=", "get_options", "(", "arguments", ")", "image_url", "=", "arguments", "[", "0", "]", "image_url", "=", "quote", "(", "image_url", ")", "try", ":", "config", "...
28.28
25
def call_task_fn(self): """Call the function attached to the task.""" if not self.fn: return self.log_finished() future = asyncio.Future() future.add_done_callback(lambda x: self.log_finished()) if inspect.iscoroutinefunction(self.fn): f = asyncio.ensure_future(self.fn()) f.add_done_callback(lambda...
[ "def", "call_task_fn", "(", "self", ")", ":", "if", "not", "self", ".", "fn", ":", "return", "self", ".", "log_finished", "(", ")", "future", "=", "asyncio", ".", "Future", "(", ")", "future", ".", "add_done_callback", "(", "lambda", "x", ":", "self", ...
27
19.6
def _update_state(self, value: str) -> None: """Update state temporary during open or close.""" attribute = next(attr for attr in self._device['device_info'].get( 'Attributes', []) if attr.get( 'AttributeDisplayName') == 'doorstate') if attribute is not None: ...
[ "def", "_update_state", "(", "self", ",", "value", ":", "str", ")", "->", "None", ":", "attribute", "=", "next", "(", "attr", "for", "attr", "in", "self", ".", "_device", "[", "'device_info'", "]", ".", "get", "(", "'Attributes'", ",", "[", "]", ")",...
49.142857
9.142857
def send(self, stack: Layers): """ Intercept any potential "AnswerCallbackQuery" before adding the stack to the output buffer. """ if not isinstance(stack, Stack): stack = Stack(stack) if 'callback_query' in self._update and stack.has_layer(Update): ...
[ "def", "send", "(", "self", ",", "stack", ":", "Layers", ")", ":", "if", "not", "isinstance", "(", "stack", ",", "Stack", ")", ":", "stack", "=", "Stack", "(", "stack", ")", "if", "'callback_query'", "in", "self", ".", "_update", "and", "stack", ".",...
35.418605
18.627907
def textslice(self, start, end): """ Return a chunk referencing a slice of a scalar text value. """ return self._select(self._pointer.textslice(start, end))
[ "def", "textslice", "(", "self", ",", "start", ",", "end", ")", ":", "return", "self", ".", "_select", "(", "self", ".", "_pointer", ".", "textslice", "(", "start", ",", "end", ")", ")" ]
36.8
11.6
def print_critical_paths(critical_paths): """ Prints the results of the critical path length analysis. Done by default by the `timing_critical_path()` function. """ line_indent = " " * 2 # print the critical path for cp_with_num in enumerate(critical_paths): ...
[ "def", "print_critical_paths", "(", "critical_paths", ")", ":", "line_indent", "=", "\" \"", "*", "2", "# print the critical path", "for", "cp_with_num", "in", "enumerate", "(", "critical_paths", ")", ":", "print", "(", "\"Critical path\"", ",", "cp_with_num", "[",...
44.333333
10.75
def search(self, filter, attributes=None): """Search LDAP for records.""" if attributes is None: attributes = ['*'] if filter is None: filter = ["(objectclass=*)"] # Convert filter list into an LDAP-consumable format filterstr = "(&{})".format(''.join(fi...
[ "def", "search", "(", "self", ",", "filter", ",", "attributes", "=", "None", ")", ":", "if", "attributes", "is", "None", ":", "attributes", "=", "[", "'*'", "]", "if", "filter", "is", "None", ":", "filter", "=", "[", "\"(objectclass=*)\"", "]", "# Conv...
32.4375
11.5625
def handle_response(response): """ Given a requests.Response object, throw the appropriate exception, if applicable. """ # ignore valid responses if response.status_code < 400: return cls = _status_to_exception_type.get(response.status_code, HttpError) kwargs = { 'code': r...
[ "def", "handle_response", "(", "response", ")", ":", "# ignore valid responses", "if", "response", ".", "status_code", "<", "400", ":", "return", "cls", "=", "_status_to_exception_type", ".", "get", "(", "response", ".", "status_code", ",", "HttpError", ")", "kw...
27.090909
21.545455
def com_adobe_fonts_check_family_max_4_fonts_per_family_name(ttFonts): """Verify that each group of fonts with the same nameID 1 has maximum of 4 fonts""" from collections import Counter from fontbakery.utils import get_name_entry_strings failed = False family_names = list() for ttFont in ttFonts: na...
[ "def", "com_adobe_fonts_check_family_max_4_fonts_per_family_name", "(", "ttFonts", ")", ":", "from", "collections", "import", "Counter", "from", "fontbakery", ".", "utils", "import", "get_name_entry_strings", "failed", "=", "False", "family_names", "=", "list", "(", ")"...
42.76
19.08
def extract_to_disk(self): """Extract all files and write them to disk.""" archive_name, extension = os.path.splitext(os.path.basename(self.file.name)) if not os.path.isdir(os.path.join(os.getcwd(), archive_name)): os.mkdir(archive_name) os.chdir(archive_name) for fil...
[ "def", "extract_to_disk", "(", "self", ")", ":", "archive_name", ",", "extension", "=", "os", ".", "path", ".", "splitext", "(", "os", ".", "path", ".", "basename", "(", "self", ".", "file", ".", "name", ")", ")", "if", "not", "os", ".", "path", "....
44.1
14.8
def getlist(self, key, delimiter=',', **kwargs): """ Gets the setting value as a :class:`list`; it splits the string using ``delimiter``. :param str delimiter: split the value using this delimiter :rtype: list """ value = self.get(key, **kwargs) if value is None...
[ "def", "getlist", "(", "self", ",", "key", ",", "delimiter", "=", "','", ",", "*", "*", "kwargs", ")", ":", "value", "=", "self", ".", "get", "(", "key", ",", "*", "*", "kwargs", ")", "if", "value", "is", "None", ":", "return", "value", "if", "...
31.842105
19.631579
def create_or_update( self, resource_group_name, vm_scale_set_name, parameters, custom_headers=None, raw=False, polling=True, **operation_config): """Create or update a VM scale set. :param resource_group_name: The name of the resource group. :type resource_group_name: str :...
[ "def", "create_or_update", "(", "self", ",", "resource_group_name", ",", "vm_scale_set_name", ",", "parameters", ",", "custom_headers", "=", "None", ",", "raw", "=", "False", ",", "polling", "=", "True", ",", "*", "*", "operation_config", ")", ":", "raw_result...
48.88
26.04
def delete_archives(self, *archives): ''' Delete archives :return: ''' # Remove paths _archives = [] for archive in archives: _archives.append(os.path.basename(archive)) archives = _archives[:] ret = {'files': {}, 'errors': {}} ...
[ "def", "delete_archives", "(", "self", ",", "*", "archives", ")", ":", "# Remove paths", "_archives", "=", "[", "]", "for", "archive", "in", "archives", ":", "_archives", ".", "append", "(", "os", ".", "path", ".", "basename", "(", "archive", ")", ")", ...
33
15.4
def _change_iscsi_target_settings(self, iscsi_info): """Change iSCSI target settings. :param iscsi_info: A dictionary that contains information of iSCSI target like target_name, lun, ip_address, port etc. :raises: IloError, on an error from iLO. """ su...
[ "def", "_change_iscsi_target_settings", "(", "self", ",", "iscsi_info", ")", ":", "sushy_system", "=", "self", ".", "_get_sushy_system", "(", "PROLIANT_SYSTEM_ID", ")", "try", ":", "pci_settings_map", "=", "(", "sushy_system", ".", "bios_settings", ".", "bios_mappin...
41.425532
16.468085
def get_weichert_factor(beta, cmag, cyear, end_year): ''' Gets the Weichert adjustment factor for each the magnitude bins :param float beta: Beta value of Gutenberg & Richter parameter (b * log(10.)) :param np.ndarray cmag: Magnitude values of the completeness table :param np.ndar...
[ "def", "get_weichert_factor", "(", "beta", ",", "cmag", ",", "cyear", ",", "end_year", ")", ":", "if", "len", "(", "cmag", ")", ">", "1", ":", "# cval corresponds to the mid-point of the completeness bins", "# In the original code it requires that the magnitude bins be", ...
34.6875
23.4375
def find_all_matching_parsers(self, strict: bool, desired_type: Type[Any] = JOKER, required_ext: str = JOKER) \ -> Tuple[Tuple[List[Parser], List[Parser], List[Parser]], List[Parser], List[Parser], List[Parser]]: """ Implementation of the parent method by lookin into the...
[ "def", "find_all_matching_parsers", "(", "self", ",", "strict", ":", "bool", ",", "desired_type", ":", "Type", "[", "Any", "]", "=", "JOKER", ",", "required_ext", ":", "str", "=", "JOKER", ")", "->", "Tuple", "[", "Tuple", "[", "List", "[", "Parser", "...
50.142857
29.659341
def head(self, n=6): """ Returns first n values of your column as a DataFrame. This is executing: SELECT <name_of_the_column> FROM <name_of_the_table> LIMIT <n> Parameters ---------- n: int number of...
[ "def", "head", "(", "self", ",", "n", "=", "6", ")", ":", "q", "=", "self", ".", "_query_templates", "[", "'column'", "]", "[", "'head'", "]", ".", "format", "(", "column", "=", "self", ".", "name", ",", "schema", "=", "self", ".", "schema", ",",...
31.147059
16.147059
def filters(self): """List of filters available for the dataset.""" if self._filters is None: self._filters, self._attributes = self._fetch_configuration() return self._filters
[ "def", "filters", "(", "self", ")", ":", "if", "self", ".", "_filters", "is", "None", ":", "self", ".", "_filters", ",", "self", ".", "_attributes", "=", "self", ".", "_fetch_configuration", "(", ")", "return", "self", ".", "_filters" ]
41.6
14.8
def cci(series, window=14): """ compute commodity channel index """ price = typical_price(series) typical_mean = rolling_mean(price, window) res = (price - typical_mean) / (.015 * np.std(typical_mean)) return pd.Series(index=series.index, data=res)
[ "def", "cci", "(", "series", ",", "window", "=", "14", ")", ":", "price", "=", "typical_price", "(", "series", ")", "typical_mean", "=", "rolling_mean", "(", "price", ",", "window", ")", "res", "=", "(", "price", "-", "typical_mean", ")", "/", "(", "...
33.625
8.125
def format_valid_streams(plugin, streams): """Formats a dict of streams. Filters out synonyms and displays them next to the stream they point to. Streams are sorted according to their quality (based on plugin.stream_weight). """ delimiter = ", " validstreams = [] for name, strea...
[ "def", "format_valid_streams", "(", "plugin", ",", "streams", ")", ":", "delimiter", "=", "\", \"", "validstreams", "=", "[", "]", "for", "name", ",", "stream", "in", "sorted", "(", "streams", ".", "items", "(", ")", ",", "key", "=", "lambda", "stream", ...
26.354839
20.483871
def inROI(self, Y): '''which points are inside ROI''' if Y.ndim > 1: area = np.zeros((Y.shape[0],4)) else: area = np.zeros((1,4)) pts = np.zeros((0,), int) pdist = np.zeros((0,), int) dist0 = 0 for k in range(len(self.prect)): s...
[ "def", "inROI", "(", "self", ",", "Y", ")", ":", "if", "Y", ".", "ndim", ">", "1", ":", "area", "=", "np", ".", "zeros", "(", "(", "Y", ".", "shape", "[", "0", "]", ",", "4", ")", ")", "else", ":", "area", "=", "np", ".", "zeros", "(", ...
47.382353
19.676471
def despeckle_simple(B, th2=2): """Single-chromosome despeckling Simple speckle removing function on a single chromomsome. It also works for multiple chromosomes but trends may be disrupted. Parameters ---------- B : array_like The input matrix to despeckle th2 : float The ...
[ "def", "despeckle_simple", "(", "B", ",", "th2", "=", "2", ")", ":", "A", "=", "np", ".", "copy", "(", "B", ")", "n1", "=", "A", ".", "shape", "[", "0", "]", "dist", "=", "{", "u", ":", "np", ".", "diag", "(", "A", ",", "u", ")", "for", ...
25.871795
20.153846
def pom_contains_modules(): """ Reads pom.xml in current working directory and checks, if there is non-empty modules tag. """ pom_file = None try: pom_file = open("pom.xml") pom = pom_file.read() finally: if pom_file: pom_file.close() artifact = MavenArti...
[ "def", "pom_contains_modules", "(", ")", ":", "pom_file", "=", "None", "try", ":", "pom_file", "=", "open", "(", "\"pom.xml\"", ")", "pom", "=", "pom_file", ".", "read", "(", ")", "finally", ":", "if", "pom_file", ":", "pom_file", ".", "close", "(", ")...
23.117647
19.235294
def send_message(self, recipient_list, subject, body): """发送站内消息 :param recipient_list: 收件人列表 :param subject: 标题 :param body: 内容(不能超过 1024 个字符) """ url = 'http://www.shanbay.com/api/v1/message/' recipient = ','.join(recipient_list) data = { 'r...
[ "def", "send_message", "(", "self", ",", "recipient_list", ",", "subject", ",", "body", ")", ":", "url", "=", "'http://www.shanbay.com/api/v1/message/'", "recipient", "=", "','", ".", "join", "(", "recipient_list", ")", "data", "=", "{", "'recipient'", ":", "r...
32.352941
14
def set_bulk_size(size): """Set size limit on bulk execution. Bulk execution bundles many operators to run together. This can improve performance when running a lot of small operators sequentially. Parameters ---------- size : int Maximum number of operators that can be bundled in ...
[ "def", "set_bulk_size", "(", "size", ")", ":", "prev", "=", "ctypes", ".", "c_int", "(", ")", "check_call", "(", "_LIB", ".", "MXEngineSetBulkSize", "(", "ctypes", ".", "c_int", "(", "size", ")", ",", "ctypes", ".", "byref", "(", "prev", ")", ")", ")...
24.47619
20.809524
def on_select_fit(self, event): """ Picks out the fit selected in the fit combobox and sets it to the current fit of the GUI then calls the select function of the fit to set the GUI's bounds boxes and alter other such parameters Parameters ---------- event : the ...
[ "def", "on_select_fit", "(", "self", ",", "event", ")", ":", "fit_val", "=", "self", ".", "fit_box", ".", "GetValue", "(", ")", "if", "self", ".", "s", "not", "in", "self", ".", "pmag_results_data", "[", "'specimens'", "]", "or", "not", "self", ".", ...
39.870968
22.451613
def _get_info(self, formula_def): ''' Get package info ''' fields = ( 'name', 'os', 'os_family', 'release', 'version', 'dependencies', 'os_dependencies', 'os_family_dependencies', ...
[ "def", "_get_info", "(", "self", ",", "formula_def", ")", ":", "fields", "=", "(", "'name'", ",", "'os'", ",", "'os_family'", ",", "'release'", ",", "'version'", ",", "'dependencies'", ",", "'os_dependencies'", ",", "'os_family_dependencies'", ",", "'summary'", ...
31.342857
14.428571
def import_account(self, label: str, encrypted_pri_key: str, pwd: str, b58_address: str, b64_salt: str, n: int = 16384) -> AccountData: """ This interface is used to import account by providing account data. :param label: str, wallet label :param encrypted_pri_key...
[ "def", "import_account", "(", "self", ",", "label", ":", "str", ",", "encrypted_pri_key", ":", "str", ",", "pwd", ":", "str", ",", "b58_address", ":", "str", ",", "b64_salt", ":", "str", ",", "n", ":", "int", "=", "16384", ")", "->", "AccountData", "...
63.333333
32.25
def format_date(value, format='%b %d, %Y', convert_tz=None): """ Format an Excel date or date string, returning a formatted date. To return a Python :py:class:`datetime.datetime` object, pass ``None`` as a ``format`` argument. >>> format_date(42419.82163) 'Feb. 19, 2016' .. code-block:: ht...
[ "def", "format_date", "(", "value", ",", "format", "=", "'%b %d, %Y'", ",", "convert_tz", "=", "None", ")", ":", "if", "isinstance", "(", "value", ",", "float", ")", "or", "isinstance", "(", "value", ",", "int", ")", ":", "seconds", "=", "(", "value", ...
30.230769
19
def from_web_element(self, web_element): """ Store reference to a WebElement instance representing the element on the DOM. Use it when an instance of WebElement has already been created (e.g. as the result of find_element) and you want to create a UIComponent out of it withou...
[ "def", "from_web_element", "(", "self", ",", "web_element", ")", ":", "if", "isinstance", "(", "web_element", ",", "WebElement", ")", "is", "not", "True", ":", "raise", "TypeError", "(", "\"web_element parameter is not of type WebElement.\"", ")", "self", ".", "_w...
55.181818
24.454545
def _split_string_to_tokens(text): """Splits text to a list of string tokens.""" if not text: return [] ret = [] token_start = 0 # Classify each character in the input string is_alnum = [c in _ALPHANUMERIC_CHAR_SET for c in text] for pos in xrange(1, len(text)): if is_alnum[pos] != is_alnum[pos - ...
[ "def", "_split_string_to_tokens", "(", "text", ")", ":", "if", "not", "text", ":", "return", "[", "]", "ret", "=", "[", "]", "token_start", "=", "0", "# Classify each character in the input string", "is_alnum", "=", "[", "c", "in", "_ALPHANUMERIC_CHAR_SET", "for...
30.058824
13.647059
def plot_isobar(self, P, Tmin=None, Tmax=None, methods_P=[], pts=50, only_valid=True): # pragma: no cover r'''Method to create a plot of the property vs temperature at a specific pressure according to either a specified list of methods, or user methods (if set), or all ...
[ "def", "plot_isobar", "(", "self", ",", "P", ",", "Tmin", "=", "None", ",", "Tmax", "=", "None", ",", "methods_P", "=", "[", "]", ",", "pts", "=", "50", ",", "only_valid", "=", "True", ")", ":", "# pragma: no cover", "if", "not", "has_matplotlib", ":...
45.361111
20
def _threshold_to_row(thresholds_keyword): """Helper to make a message row from a threshold We are expecting something like this: { 'thresholds': { 'structure': { 'ina_structure_flood_hazard_classification': { 'classes': {...
[ "def", "_threshold_to_row", "(", "thresholds_keyword", ")", ":", "if", "isinstance", "(", "thresholds_keyword", ",", "str", ")", ":", "thresholds_keyword", "=", "literal_eval", "(", "thresholds_keyword", ")", "for", "k", ",", "v", "in", "list", "(", "thresholds_...
38.492537
16.708955
def _classify_arithmetic(self, regs_init, regs_fini, mem_fini, written_regs, read_regs): """Classify binary-operation gadgets. """ matches = [] # TODO: Review these restrictions. op_restrictions = { "+": lambda x, y: False, "-": lambda x, y: x == y, ...
[ "def", "_classify_arithmetic", "(", "self", ",", "regs_init", ",", "regs_fini", ",", "mem_fini", ",", "written_regs", ",", "read_regs", ")", ":", "matches", "=", "[", "]", "# TODO: Review these restrictions.", "op_restrictions", "=", "{", "\"+\"", ":", "lambda", ...
40.372881
22.237288
def sampleLocation(self): """ Simple method to sample uniformly from a cylinder. """ areaRatio = self.radius / (self.radius + self.height) if random.random() < areaRatio: return self._sampleLocationOnDisc() else: return self._sampleLocationOnSide()
[ "def", "sampleLocation", "(", "self", ")", ":", "areaRatio", "=", "self", ".", "radius", "/", "(", "self", ".", "radius", "+", "self", ".", "height", ")", "if", "random", ".", "random", "(", ")", "<", "areaRatio", ":", "return", "self", ".", "_sample...
30.666667
9.333333
def aes_encrypt(base64_encryption_key, data): """Encrypt data with AES-CBC and sign it with HMAC-SHA256 Arguments: base64_encryption_key (str): a base64-encoded string containing an AES encryption key and HMAC signing key as generated by generate_encryption_key() data (str): a byte ...
[ "def", "aes_encrypt", "(", "base64_encryption_key", ",", "data", ")", ":", "if", "isinstance", "(", "data", ",", "text_type", ")", ":", "data", "=", "data", ".", "encode", "(", "\"UTF-8\"", ")", "aes_key_bytes", ",", "hmac_key_bytes", "=", "_extract_keys", "...
43.904762
23.809524
def _ignore_interrupts(self): """ Ignore interrupt and termination signals. Used as a pre-execution function (preexec_fn) for subprocess.Popen calls that pypiper will control over (i.e., manually clean up). """ signal.signal(signal.SIGINT, signal.SIG_IGN) signal.s...
[ "def", "_ignore_interrupts", "(", "self", ")", ":", "signal", ".", "signal", "(", "signal", ".", "SIGINT", ",", "signal", ".", "SIG_IGN", ")", "signal", ".", "signal", "(", "signal", ".", "SIGTERM", ",", "signal", ".", "SIG_IGN", ")" ]
43.75
13.75
def _find_family_class(dev): """! @brief Search the families list for matching entry.""" for familyInfo in FAMILIES: # Skip if wrong vendor. if dev.vendor != familyInfo.vendor: continue # Scan each level of families for familyName in dev.f...
[ "def", "_find_family_class", "(", "dev", ")", ":", "for", "familyInfo", "in", "FAMILIES", ":", "# Skip if wrong vendor.", "if", "dev", ".", "vendor", "!=", "familyInfo", ".", "vendor", ":", "continue", "# Scan each level of families", "for", "familyName", "in", "d...
40.882353
12.352941
def urljoin(domain, path=None, scheme=None): """ Joins a domain, path and scheme part together, returning a full URL. :param domain: the domain, e.g. ``example.com`` :param path: the path part of the URL, e.g. ``/example/`` :param scheme: the scheme part of the URL, e.g. ``http``, defaulting to the...
[ "def", "urljoin", "(", "domain", ",", "path", "=", "None", ",", "scheme", "=", "None", ")", ":", "if", "scheme", "is", "None", ":", "scheme", "=", "getattr", "(", "settings", ",", "'DEFAULT_URL_SCHEME'", ",", "'http'", ")", "return", "urlunparse", "(", ...
39.142857
20.142857
def like_cosi(cosi,vsini_dist,veq_dist,vgrid=None): """likelihood of Data (vsini_dist, veq_dist) given cosi """ sini = np.sqrt(1-cosi**2) def integrand(v): #return vsini_dist(v)*veq_dist(v/sini) return vsini_dist(v*sini)*veq_dist(v) if vgrid is None: return quad(integrand,0,n...
[ "def", "like_cosi", "(", "cosi", ",", "vsini_dist", ",", "veq_dist", ",", "vgrid", "=", "None", ")", ":", "sini", "=", "np", ".", "sqrt", "(", "1", "-", "cosi", "**", "2", ")", "def", "integrand", "(", "v", ")", ":", "#return vsini_dist(v)*veq_dist(v/s...
34.272727
10.090909
def is_unknown(input, model_file=None, model_proto=None, name=None): """Returns true if input id is unknown piece. Args: input: An arbitrary tensor of int32. model_file: The sentencepiece model file path. model_proto: The sentencepiece model serialized proto. Either `model_file` or `mo...
[ "def", "is_unknown", "(", "input", ",", "model_file", "=", "None", ",", "model_proto", "=", "None", ",", "name", "=", "None", ")", ":", "return", "_gen_sentencepiece_processor_op", ".", "sentencepiece_get_piece_type", "(", "input", ",", "model_file", "=", "model...
38.9375
21.1875