text
stringlengths
78
104k
score
float64
0
0.18
def clean(ctx, docs=False, bytecode=False, extra=''): '''Cleanup all build artifacts''' patterns = ['build', 'dist', 'cover', 'docs/_build', '**/*.pyc', '*.egg-info', '.tox'] for pattern in patterns: print('Removing {0}'.format(pattern)) with ctx.cd(ROOT): ctx.run('rm -rf {0}'.fo...
0.005988
def create_filter(self): """Get an instance of filter services facade.""" return Filter( self.networkapi_url, self.user, self.password, self.user_ldap)
0.009302
def connection_made(self, transport): """Create connection, use to send message and close. Args: transport (asyncio.DatagramTransport): Transport used for sending. """ self.transport = transport self.transport.sendto(self.message) self.transport.close()
0.006369
def _on_timeout(self, info: str = None) -> None: """Timeout callback of _HTTPConnection instance. Raise a `HTTPTimeoutError` when a timeout occurs. :info string key: More detailed timeout information. """ self._timeout = None error_message = "Timeout {0}".format(info) i...
0.003945
def from_header(cls, header, beam=None, lat=None): """ Create a new WCSHelper class from the given header. Parameters ---------- header : `astropy.fits.HDUHeader` or string The header to be used to create the WCS helper beam : :class:`AegeanTools.fits_image....
0.003493
def step(self): """Perform a single step of the morphological snake evolution.""" # Assign attributes to local variables for convenience. u = self._u gI = self._data dgI = self._ddata theta = self._theta v = self._v if u is None: raise...
0.008824
def incident_path(cls, project, incident): """Return a fully-qualified incident string.""" return google.api_core.path_template.expand( "projects/{project}/incidents/{incident}", project=project, incident=incident, )
0.007246
def generate_checkpoints(engine, crypto_factory, min_dt=None, max_dt=None, logger=None): """ Create a generator of decrypted remote checkpoints. Checkpoints are yielded in ascending order of their timestamp. This function selects all notebook checkpoints (optionally, falling w...
0.000755
def resizeEvent(self, event): """ Recalculates the chart information when the widget resizes. :param event | <QResizeEvent> """ super(XChart, self).resizeEvent(event) if self.isVisible(): self.recalculate()
0.013423
def post(self, endpoint, data, files=None, headers=None): # pylint: disable=unused-argument """ Create a new item :param endpoint: endpoint (API URL) :type endpoint: str :param data: properties of item to create :type data: dict :param files: Not used. To...
0.005405
def predict(self, X, break_ties="random", return_probs=False, **kwargs): """Predicts int labels for an input X on all tasks Args: X: The input for the predict_proba method break_ties: A tie-breaking policy return_probs: Return the predicted probabilities as well ...
0.003344
def get_mesos_task(task_name): """ Get a mesos task with a specific task name """ tasks = get_mesos_tasks() if tasks is not None: for task in tasks: if task['name'] == task_name: return task return None
0.003861
def dump(self, filename, encoding="utf8"): """ Dumps the ascii art in the file. Args: filename (str): File to dump the ascii art. encoding (str): Optional. Default "utf-8". """ with open(filename, mode='w', encoding=encoding) as text_file: text...
0.005666
def setIV(self, IV): """Will set the Initial Value, used in conjunction with CBC mode""" _baseDes.setIV(self, IV) for key in (self.__key1, self.__key2, self.__key3): key.setIV(IV)
0.031915
def RelaxNGValidate(self, rng): """Use RelaxNG schema to validate the document as it is processed. Activation is only possible before the first Read(). If @rng is None, then RelaxNG schema validation is deactivated. """ ret = libxml2mod.xmlTextReaderRelaxNGValidate(self._o...
0.005797
def linspace_bins(self,dim,*args,**kwargs): """ Like linspace, but shifts the space to create edges for histograms. """ return self.spike_times.get_label(dim).linspace_bins(*args,**kwargs)
0.026786
def go_stdlib(self): """Return the set of all Go standard library import paths. :rtype: frozenset of string """ out = self._go_dist.create_go_cmd('list', args=['std']).check_output() return frozenset(out.decode('utf-8').strip().split())
0.003891
def get_xml(html, content_tag='ekb', fail_if_empty=False): """Extract the content XML from the HTML output of the TRIPS web service. Parameters ---------- html : str The HTML output from the TRIPS web service. content_tag : str The xml tag used to label the content. Default is 'ekb'...
0.002217
def unauthorized_callback(self): """ Redirect to login url with next param set as request.url """ return redirect(self.login_url(params=dict(next=request.url)))
0.010417
def filter(self, f): """ Return a new DStream containing only the elements that satisfy predicate. """ def func(iterator): return filter(f, iterator) return self.mapPartitions(func, True)
0.012552
def SIMPLE(val): ''' This is a basic case-sensitive "sorted order" index keygen function for strings. This will return a value that is suitable to be used for ordering by a 7-byte prefix of a string (that is 7 characters from a byte-string, and 1.75-7 characters from a unicode string, depending on c...
0.004489
def execute(self, input_args=None, monitor=False): """Executes the workflow. :param input_args: External input arguments to the workflow. They have to be in a form of a dictionary where each key is an EOTask used in the workflow and each value is a dictionary or a tuple of arguments. ...
0.00558
def score(*args): """Get score of core-periphery pairs. Parameters ---------- G : Graph object. c : Dict object, the keys and values of which are the name of node and its ID of belonging core-periphery pair. Returns ------- q : List. q[i] is the quality of core-periphery pair i. """...
0.069414
def _set_port_control(self, v, load=False): """ Setter method for port_control, mapped from YANG variable /interface/fortygigabitethernet/dot1x/port_control (enumeration) If this variable is read-only (config: false) in the source YANG file, then _set_port_control is considered as a private method. ...
0.005518
def collect_transitive_dependencies( collected: Set[str], dep_graph: DepGraph, from_name: str ) -> None: """Collect transitive dependencies. From a dependency graph, collects a list of transitive dependencies by recursing through a dependency graph. """ immediate_deps = dep_graph[from_name] ...
0.004016
def _create_scale_operator(self, identity_multiplier, diag, tril, perturb_diag, perturb_factor, shift, validate_args, dtype): """Construct `scale` from various components. Args: identity_multiplier: floating point rank 0 `Tensor` representing a sc...
0.003902
def getRootDirectory(cls): """ Get the root directory that contains files added through C{SparkContext.addFile()}. """ if cls._is_running_on_worker: return cls._root_directory else: # This will have to change if we support multiple SparkContexts: ...
0.005038
def kindpath(self, kind): """Returns a path to the resources for a given input kind. :param `kind`: The kind of input: - "ad": Active Directory - "monitor": Files and directories - "registry": Windows Registry - "script": Scripts - "splun...
0.001901
def _project_is_apache(): """Determine if a project is Apache. Look for a key string in a set of possible license files to figure out if a project looks to be Apache. This is used as a precondition for enforcing license headers. """ global _is_apache_cache if _is_apache_cache is not None: ...
0.001351
def init(self, fle=None): """ Executes the preprocessing steps at the instantiation stage to read in the tables from hdf5 and hold them in memory. """ if fle is None: fname = self.kwargs.get('gmpe_table', self.GMPE_TABLE) if fname is None: ...
0.001181
def stop_consuming(self): """ Tell RabbitMQ that you would like to stop consuming by sending the Basic.Cancel RPC command. """ if self._channel: self._logger.info('Sending a Basic.Cancel RPC command to RabbitMQ') self._channel.basic_cancel(self.on_cancelok...
0.005865
def convert(input): """Input GEIS files "input" will be read and a HDUList object will be returned that matches the waiver-FITS format written out by 'stwfits' in IRAF. The user can use the writeto method to write the HDUList object to a FITS file. """ global dat cardLen = fits.C...
0.00355
def template(tem, queue=False, **kwargs): ''' Execute the information stored in a template file on the minion. This function does not ask a master for a SLS file to render but instead directly processes the file at the provided path on the minion. CLI Example: .. code-block:: bash sa...
0.001072
def clearPrefs(self): """clear the left panel and preferences""" self.preferences.clear() tradebox_num = len(self.css('div.tradebox')) for i in range(tradebox_num): self.xpath(path['trade-box'])[0].right_click() self.css1('div.item-trade-contextmenu-list-remove')....
0.005405
def embed(**kwargs): """Call this to embed IPython at the current point in your program. The first invocation of this will create an :class:`InteractiveShellEmbed` instance and then call it. Consecutive calls just call the already created instance. Here is a simple example:: from IPython...
0.001057
def frexp10(x): """ Finds the mantissa and exponent of a number :math:`x` such that :math:`x = m 10^e`. Parameters ---------- x : float Number :math:`x` such that :math:`x = m 10^e`. Returns ------- mantissa : float Number :math:`m` such that :math:`x = m 10^e`. e...
0.003914
def route_filter_rules_list(route_filter, resource_group, **kwargs): ''' .. versionadded:: 2019.2.0 List all routes within a route filter. :param route_filter: The route filter to query. :param resource_group: The resource group name assigned to the route filter. CLI Example: .....
0.002006
def __setupMenus(self): """ Sets up the main menu. """ if True: # Don't use self.menuBar(), on OS-X this is not shared across windows. # See: http://qt-project.org/doc/qt-4.8/qmenubar.html#details # And:http://qt-project.org/doc/qt-4.8/qmainwindow.html#menuBar...
0.009504
def main(): """ This is a Toil pipeline for the UNC best practice RNA-Seq analysis. RNA-seq fastqs are combined, aligned, sorted, filtered, and quantified. Please read the README.md located in the same directory. """ # Define Parser object and add to toil parser = build_parser() Job.Run...
0.000766
def add_colons(s): """Add colons after every second digit. This function is used in functions to prettify serials. >>> add_colons('teststring') 'te:st:st:ri:ng' """ return ':'.join([s[i:i + 2] for i in range(0, len(s), 2)])
0.004016
def searchForThreads(self, name, limit=10): """ Find and get a thread by its name :param name: Name of the thread :param limit: The max. amount of groups to fetch :return: :class:`models.User`, :class:`models.Group` and :class:`models.Page` objects, ordered by relevance ...
0.004023
def write_summary_cnts(self, go_ids): """Write summary of level and depth counts for specific GO ids.""" obo = self.obo cnts = self.get_cnts_levels_depths_recs([obo.get(GO) for GO in go_ids]) self._write_summary_cnts(cnts)
0.007874
def convert_cifar100(directory, output_directory, output_filename='cifar100.hdf5'): """Converts the CIFAR-100 dataset to HDF5. Converts the CIFAR-100 dataset to an HDF5 dataset compatible with :class:`fuel.datasets.CIFAR100`. The converted dataset is saved as 'cifar100.hdf5'. ...
0.000327
def to_binary_string(obj, encoding=None): """Convert `obj` to binary string (bytes in Python 3, str in Python 2)""" if PY2: # Python 2 if encoding is None: return str(obj) else: return obj.encode(encoding) else: # Python 3 return byte...
0.00271
def check_directory(self): """Check if migrations directory exists.""" exists = os.path.exists(self.directory) if not exists: logger.error("No migrations directory found. Check your path or create a migration first.") logger.error("Directory: %s" % self.directory) ...
0.008982
def data_advanced(request): """Return server side data.""" columns = [ ColumnDT(User.id, search_method="numeric"), ColumnDT(User.name), ColumnDT(Address.description), ColumnDT(User.birthday, search_method="date"), ColumnDT(User.age, search_method="numeric") ] que...
0.002004
def combine_validations(items, vkey="validate"): """Combine multiple batch validations into validation outputs. """ csvs = set([]) pngs = set([]) for v in [x.get(vkey) for x in items]: if v and v.get("grading_summary"): csvs.add(v.get("grading_summary")) if v and v.get("g...
0.003717
def from_array(array): """ Deserialize a new EncryptedCredentials from a given dictionary. :return: new EncryptedCredentials instance. :rtype: EncryptedCredentials """ if array is None or not array: return None # end if assert_type_or_raise(ar...
0.003436
def compile_with_value(self, func, args=None, owner=None): '''Compile the function with array-like objects''' # format args if args is None: args = [] # cast numpy.ndarray into theano.tensor theano_args = [self.cast2theano_var(a, 'extheano.jit.Compiler-arg-%d' % i) ...
0.006173
def validate_binary_sign(signed_query, signature, cert=None, algorithm=OneLogin_Saml2_Constants.RSA_SHA1, debug=False): """ Validates signed binary data (Used to validate GET Signature). :param signed_query: The element we should validate :type: string :param signature: The si...
0.003933
def exec_stmt(self, exec_loc, body, in_opt): """(2.6, 2.7) exec_stmt: 'exec' expr ['in' test [',' test]]""" in_loc, globals, locals = None, None, None loc = exec_loc.join(body.loc) if in_opt: in_loc, globals, locals = in_opt if locals: loc = loc.jo...
0.003752
def compute_fdm(fixmat, fwhm=2, scale_factor=1): """ Computes a fixation density map for the calling fixmat. Creates a map the size of the image fixations were recorded on. Every pixel contains the frequency of fixations for this image. The fixation map is smoothed by convolution with a ...
0.004423
def plot(self): """ Draws energy chart using matplotlib. """ import matplotlib.pyplot as plt plt.plot(self.E) plt.show()
0.060606
def is_period_arraylike(arr): """ Check whether an array-like is a periodical array-like or PeriodIndex. Parameters ---------- arr : array-like The array-like to check. Returns ------- boolean Whether or not the array-like is a periodical array-like or PeriodInd...
0.001274
def _request(self, data): # type: (str) -> None """Override parent by buffering the metric instead of sending now""" data = bytearray("{}\n".format(data).encode()) self._prepare_batches_for_storage(len(data)) self._batches[-1].extend(data)
0.010714
def get_parameterized_program(self): """ Return a function that accepts parameters and returns a new Quil program. :returns: a function """ cost_para_programs = [] driver_para_programs = [] for idx in range(self.steps): cost_list = [] dri...
0.002505
def major_complex(network, state): """Return the major complex of the network. Args: network (Network): The |Network| of interest. state (tuple[int]): The state of the network (a binary tuple). Returns: SystemIrreducibilityAnalysis: The |SIA| for the |Subsystem| with maxima...
0.001536
def addFixedEffect(self,F=None,A=None): """ add fixed effect to the model Args: F: fixed effect matrix [N,1] A: design matrix [K,P] (e.g. SP.ones((1,P)) common effect; SP.eye(P) any effect) """ if A==None: A = SP.eye(self.P) if F==None...
0.023976
def decode_transformer(encoder_output, encoder_decoder_attention_bias, targets, hparams, name, task=None, causal=True): """Original Transformer decoder.""" orig_hparams = hparams...
0.010163
def get_minimum_span(low, high, span): """ If lower and high values are equal ensures they are separated by the defined span. """ if is_number(low) and low == high: if isinstance(low, np.datetime64): span = span * np.timedelta64(1, 's') low, high = low-span, high+span ...
0.002967
def recentProgress(self): """Returns an array of the most recent [[StreamingQueryProgress]] updates for this query. The number of progress updates retained for each stream is configured by Spark session configuration `spark.sql.streaming.numRecentProgressUpdates`. """ return [jso...
0.010695
def get_registration(self, path): """ Returns registration item for specified path. If an email template is not registered, this will raise NotRegistered. """ if not self.is_registered(path): raise NotRegistered("Email template not registered") return self._r...
0.006006
def _calc_delta(self,ensemble,scaling_matrix=None): ''' calc the scaled ensemble differences from the mean ''' mean = np.array(ensemble.mean(axis=0)) delta = ensemble.as_pyemu_matrix() for i in range(ensemble.shape[0]): delta.x[i,:] -= mean if scaling...
0.010616
def list(self,table, **kparams): """ get a collection of records by table name. returns a collection of SnowRecord obj. """ records = self.api.list(table, **kparams) return records
0.013158
def s_to_ev(offset_us, source_to_detector_m, array): """convert time (s) to energy (eV) Parameters: =========== numpy array of time in s offset_us: float. Delay of detector in us source_to_detector_m: float. Distance source to detector in m Returns: ======== numpy array of energy in...
0.002217
def trending( self, accept_language=None, user_agent=None, client_id=None, client_ip=None, location=None, country_code=None, market=None, safe_search=None, set_lang=None, custom_headers=None, raw=False, **operation_config): """The Image Trending Search API lets you search on Bing and get back a ...
0.000791
def _digest_auth_stage2(self, _unused): """Do the second stage (<iq type='set'/>) of legacy "digest" authentication. [client only]""" iq=Iq(stanza_type="set") q=iq.new_query("jabber:iq:auth") q.newTextChild(None,"username",to_utf8(self.my_jid.node)) q.newTextChil...
0.02107
def benchmarkOneQuery(request, repeatLimit=3, pageLimit=3): """ Repeat the query several times; perhaps don't go through *all* the pages. Returns minimum time to run backend.searchVariants() to execute the query (as far as pageLimit allows), *not* including JSON processing to prepare queries or par...
0.000712
def convert_sequence(seq, to_material): '''Translate a DNA sequence into peptide sequence. The following conversions are supported: Transcription (seq is DNA, to_material is 'rna') Reverse transcription (seq is RNA, to_material is 'dna') Translation (seq is RNA, to_material is 'peptide'...
0.00039
def _check_queue(queue, kwargs): ''' Utility function to queue the state run if requested and to check for conflicts in currently running states ''' if queue: _wait(kwargs.get('__pub_jid')) else: conflict = running(concurrent=kwargs.get('concurrent', False)) if conflict: ...
0.00463
def poll_for_exceptionless_callable(callable, attempts, interval): '''Poll with a given callable for a specified number of times. :param callable: callable to invoke in loop -- if no exception is raised the call is considered succeeded :param attempts: number of iterations to attempt ...
0.001333
def _ParseUSNChangeJournal(self, parser_mediator, usn_change_journal): """Parses an USN change journal. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. usn_change_journal (pyfsntsfs.usn_change_journal): USN cha...
0.008932
def print_results(args): """Print comics.""" min_comics, filename = args with codecs.open(filename, 'a', 'utf-8') as fp: for name, url in sorted(load_result(json_file).items()): if name in exclude_comics: continue if has_gocomics_comic(name): p...
0.001931
def stream_realtime(self, stream, value): """Stream a realtime value as an IndividualReadingReport. If the streaming interface of the VirtualInterface this VirtualDevice is attached to is not opened, the realtime reading may be dropped. Args: stream (int): The strea...
0.004886
def _finalize(self, all_msg_errors=None): """Access all the instance descriptors This wil trigger an exception if a required parameter is not set """ if all_msg_errors is None: all_msg_errors = [] for key in self.stored(): try: ge...
0.003559
def cmd_link_add(self, args): '''add new link''' descriptor = args[0] print("Adding link %s" % descriptor) self.link_add(descriptor)
0.012195
def register_run_plugins(self, plugin_name, plugin_class): """ Loads a plugin as a dictionary and attaches needed parts to correct Icetea run global parts. :param plugin_name: Name of the plugins :param plugin_class: PluginBase :return: Nothing """ if plu...
0.003851
def send( self): """*send the mobi book generated to kindle email address(es)* **Return:** - ``success`` -- True or False depending on the success/failure of sending the email to the kindle email address(es). """ self.log.debug('starting the ``send`` method') ...
0.003774
def _optimize_image_external(filename, func, image_format, new_ext): """Optimize the file with the external function.""" new_filename = filename + TMP_SUFFIX + new_ext new_filename = os.path.normpath(new_filename) shutil.copy2(filename, new_filename) ext_args = ExtArgs(filename, new_filename) n...
0.001279
def create(self, auth, type, desc, defer=False): """ Create something in Exosite. Args: auth: <cik> type: What thing to create. desc: Information about thing. """ return self._call('create', auth, [type, desc], defer)
0.006993
def register(self, other, **kwargs): """ Align a mesh with another mesh or a PointCloud using the principal axes of inertia as a starting point which is refined by iterative closest point. Parameters ------------ mesh : trimesh.Trimesh object Mesh to al...
0.001741
def find_all(self, table, limit=10): ''' 从数据库里查询所有记录 Args: table: 表名字 str limit: 限制数量 return: 成功: [dict] 保存的记录 失败: -1 并打印返回报错信息 ''' sql = "select * from {} limit 0,{}".format(table, limit) res = self.query(sql) ...
0.006006
def api_version(self, v): """Set the api_version and associated configurations.""" self._api_version = v if (self._api_version >= '2.0'): self.default_quality = 'default' self.allowed_qualities = ['default', 'color', 'bitonal', 'gray'] else: # versions 1.0 and 1....
0.004535
def _init_map(self, record_types=None, **kwargs): """Initialize form map""" osid_objects.OsidObjectForm._init_map(self, record_types=record_types) self._my_map['outputScore'] = self._output_score_default self._my_map['gradeSystemId'] = str(kwargs['grade_system_id']) self._my_map[...
0.007394
def render_to_string(template_name, context=None, request=None, using=None): """ Loads a template and renders it with a context. Returns a string. template_name may be a string or a list of strings. """ if isinstance(template_name, (list, tuple)): template = select_template(template_name, us...
0.002247
def addBiosample(self, biosample): """ Adds the specified biosample to this dataset. """ id_ = biosample.getId() self._biosampleIdMap[id_] = biosample self._biosampleIds.append(id_) self._biosampleNameMap[biosample.getName()] = biosample
0.006826
def set_poll_func(self, func, func_err_handler=None): '''Can be used to integrate pulse client into existing eventloop. Function will be passed a list of pollfd structs and timeout value (seconds, float), which it is responsible to use and modify (set poll flags) accordingly, returning int value >= 0 with ...
0.019876
def validate_document(self, definition): """ Validate given pipeline document. The method is trying to load, parse and validate the spline document. The validator verifies the Python structure B{not} the file format. Args: definition (str): path and filename of a ya...
0.003673
def CB(self): ''' Vertices C and B, list. ''' try: return self._CB except AttributeError: pass self._CB = [self.C, self.B] return self._CB
0.009132
def operator_is(u): """operator_is operator.""" global _aux if np.ndim(u) == 2: P = _P2 elif np.ndim(u) == 3: P = _P3 else: raise ValueError("u has an invalid number of dimensions " "(should be 2 or 3)") if u.shape != _aux.shape[1:]: ...
0.008511
def start(self): """Run FIO job in thread""" self.__thread = Threads(target=self.run, args=(True, True, False)) self.__thread.setDaemon(True) self.__thread.start()
0.010204
def create(self, module_name, class_name, args=None, kwargs=None, factory_method=None, factory_args=None, factory_kwargs=None, static=False, calls=None): """ Initializes an instance of the service """ if args is None: args = [] if kwargs i...
0.003757
def as_list_with_options(self): """ Similar to list(self) except elements which have an option associated with them are returned as a ``TListItemWithOption`` """ it = ROOT.TIter(self) elem = it.Next() result = [] while elem: if it.GetOption(): ...
0.004024
def _check_lambda_alias(self): """Check if lambda alias exists. Returns: True if alias exists False if alias does not exist """ aliases = self.lambda_client.list_aliases(FunctionName=self.app_name) matched_alias = False for alias in aliases['Alia...
0.006279
def fontChar(self, font, char): """ Checks if characters occurs in the given font. """ font_files = self._getCharFont(self._getFont(font), char) print('The character is {0}present in this font.'.format('' if font_files else 'not '))
0.011029
def _status_apf(): ''' Return True if apf is running otherwise return False ''' status = 0 table = iptc.Table(iptc.Table.FILTER) for chain in table.chains: if 'sanity' in chain.name.lower(): status = 1 return True if status else False
0.003546
def read(self, filenames): '''' Read a list of files. Their configuration values are merged, with preference to values from files earlier in the list. ''' for fn in filenames: try: self.configs[fn] = ordered_json.load(fn) except IOError: ...
0.004854
def filter_label(label, replace_by_similar=True): """Some labels currently don't work together because of LaTeX naming clashes. Those will be replaced by simple strings. """ bad_names = ['celsius', 'degree', 'ohm', 'venus', 'mars', 'astrosun', 'fullmoon', 'leftmoon', 'female', 'male', 'c...
0.001292
def combine(self, other): """An instance of lunr.MatchData will be created for every term that matches a document. However only one instance is required in a lunr.Index~Result. This method combines metadata from another instance of MatchData with this object's metadata. ...
0.002695
def preferred(self): """ Get the preferred subtag. :return: preferred :class:`language_tags.Subtag.Subtag` if exists, otherwise None. """ if 'Preferred-Value' in self.data['record']: preferred = self.data['record']['Preferred-Value'] type = self.data['typ...
0.006608