_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q51600
QueryField.eq_
train
def eq_(self, value): ''' Creates a query expression where ``this field == value`` .. note:: The prefered usage is via an operator: ``User.name == value`` ''' if isinstance(value, QueryField): return self.__cached_id == value.__cached_id return QueryExpression({ ...
python
{ "resource": "" }
q51601
QueryField.ne_
train
def ne_(self, value): ''' Creates a query expression where ``this field != value`` .. note:: The prefered usage is via an operator: ``User.name != value`` ''' if isinstance(value, QueryField): return self.__cached_id != value.__cached_id return self.__comparator(...
python
{ "resource": "" }
q51602
get_resource
train
def get_resource(url): """ Issue a GET request to R25 with the given url and return a response as an etree element. """ response = R25_DAO().getURL(url, {"Accept": "text/xml"}) if response.status != 200: raise DataFailureException(url, response.status, response.data) tree = etree.fr...
python
{ "resource": "" }
q51603
weather
train
def weather(api_key, latitude, longitude, date_time=None): # type:(str, float, float) -> Weather """ This is a shortcut method that can be used to perform a basic weather request with the default settings. :param str api_key: Darksky.net API key :param float latitude: The requested latitude. Maybe ...
python
{ "resource": "" }
q51604
DarkSky.url
train
def url(self): # type:() -> str """ Build and returns a URL used to make a Dark Sky API call. """ url = "https://api.darksky.net/forecast/{key}/{lat},{lon}".format(key=self.api_key, lat=self.latitude, ...
python
{ "resource": "" }
q51605
DarkSky.exclude_invert
train
def exclude_invert(self): # type:() -> None """ Inverts the values in self.exclude .. code-block:: python >>> import pydarksky >>> darksky = pydarksky.DarkSky('0' * 32) >>> darksky.EXCLUDES ('currently', 'minutely', 'hourly', 'daily', 'a...
python
{ "resource": "" }
q51606
AuthMixin.authenticate
train
def authenticate(self, request): """ Attempt to authenticate the request. :param request: django.http.Request instance :return bool: True if success else raises HTTP_401 """ authenticators = self._meta.authenticators if request.method == 'OPTIONS' and ADREST_ALLOW_OPT...
python
{ "resource": "" }
q51607
AuthMixin.check_rights
train
def check_rights(self, resources, request=None): """ Check rights for resources. :return bool: True if operation is success else HTTP_403_FORBIDDEN """ if not self.auth: return True try: if not self.auth.test_rights(resources, request=request): ...
python
{ "resource": "" }
q51608
LexiconCreator.count_n_grams_py_polarity
train
def count_n_grams_py_polarity(self, data_set_reader, n_grams, filters): """ Returns a map of n-gram and the number of times it appeared in positive context and the number of times it appeared in negative context in dataset file. :param data_set_reader: Dataset containing tweets and thei...
python
{ "resource": "" }
q51609
load_config
train
def load_config(paths=DEFAULT_CONFIG_PATHS): """Attempt to load config from paths, in order. Args: paths (List[string]): list of paths to python files Return: Config: loaded config """ config = Config() for path in paths: if os.path.isfile(path): config.load...
python
{ "resource": "" }
q51610
Config.load_pyfile
train
def load_pyfile(self, path): """Load python file as config. Args: path (string): path to the python file """ with open(path) as config_file: contents = config_file.read() try: exec(compile(contents, path, 'exec'), self) exc...
python
{ "resource": "" }
q51611
channel_parameters
train
def channel_parameters(parameter_prefix, channel_names, configuration_entry): """ Return parameters specific to a channel for a model. """ if configuration_entry in (True, False): return ([], [parameter_prefix])[configuration_entry] parameters = [] if isinstance(configuration_entry, di...
python
{ "resource": "" }
q51612
BaseModel.save
train
def save(self, filename, clobber=False, **kwargs): """ Save the model configuration to a YAML-formatted file. :param filename: The filename to save the model configuration to. :type filename: str :param clobber: [optional] Clobber the filena...
python
{ "resource": "" }
q51613
BaseModel._latex_labels
train
def _latex_labels(self, labels): """ LaTeX-ify labels based on information provided in the configuration. """ config = self._configuration.get("latex_labels", {}) return [config.get(label, label) for label in labels]
python
{ "resource": "" }
q51614
BaseModel.parameters
train
def parameters(self): """ Return the model parameters. """ try: return self._parameters except AttributeError: None parameters = [] parameters.extend(self.grid_points.dtype.names) model_configuration = self._configuration.get("model", {}) ...
python
{ "resource": "" }
q51615
BaseModel._overlapping_channels
train
def _overlapping_channels(self, wavelengths): """ Return the channels that match the given wavelength array. """ sizes = self.meta["channel_sizes"] min_a, max_a = wavelengths.min(), wavelengths.max() matched_channel_names = [] for i, (name, size) in enumerate(zi...
python
{ "resource": "" }
q51616
BaseModel._format_data
train
def _format_data(self, data): """ Sort the data in blue wavelengths to red, and ignore any spectra that have entirely non-finite or negative fluxes. """ return [spectrum for spectrum in \ sorted(data if isinstance(data, (list, tuple)) else [data], key=...
python
{ "resource": "" }
q51617
BaseModel._apply_data_mask
train
def _apply_data_mask(self, data): """ Apply pre-defined masks to the data. """ data = self._format_data(data) masked_data, pixels_affected = [], 0 data_mask = self._configuration.get("masks", {}).get("data", []) for spectrum in data: masked_spectrum ...
python
{ "resource": "" }
q51618
BaseModel._model_mask
train
def _model_mask(self, wavelengths=None): """ Apply pre-defined model masks. """ if wavelengths is None: wavelengths = self.wavelengths wavelengths = np.array(wavelengths) mask = np.ones_like(wavelengths, dtype=bool) model_mask = self._configuration.g...
python
{ "resource": "" }
q51619
BaseModel._match_channels_to_data
train
def _match_channels_to_data(self, data): """ Match observed data to a channel, and return possibly superfluous model parameters. """ data = self._format_data(data) matched_channels = [] for spectrum in data: match = self._overlapping_channels(spectru...
python
{ "resource": "" }
q51620
BaseModel._initial_proposal_distribution
train
def _initial_proposal_distribution(self, parameters, theta, size, default_std=1e-4): """ Generate an initial proposal distribution around the point theta. """ missing_parameters = set(parameters).difference(theta) if missing_parameters: raise ValueError("cann...
python
{ "resource": "" }
q51621
file_md5
train
def file_md5(f, size=8192): "Calculates the MD5 of a file." md5 = hashlib.md5() while True: data = f.read(size) if not data: break md5.update(data) return md5.hexdigest()
python
{ "resource": "" }
q51622
GameManager.open_fd
train
def open_fd(cls, name): """Open a file or create it.""" # Try to create it, if can't, try to open. try: return os.open(name, os.O_CREAT | os.O_RDWR | os.O_EXCL) except OSError as e: if e.errno != errno.EEXIST: raise return os.open(name,...
python
{ "resource": "" }
q51623
GameManager.new_game
train
def new_game(self): """Creates a new game of 2048.""" self.game = self.game_class(self, self.screen) self.save()
python
{ "resource": "" }
q51624
GameManager._load_score
train
def _load_score(self): """Load the best score from file.""" score = int(self.score_file.read()) self.score_file.seek(0, os.SEEK_SET) return score
python
{ "resource": "" }
q51625
GameManager.got_score
train
def got_score(self, score): """Update the best score if the new score is higher, returning the change.""" if score > self._score: delta = score - self._score self._score = score self._score_changed = True self.save() return delta return...
python
{ "resource": "" }
q51626
require_backup_exists
train
def require_backup_exists(func): """ Requires that the file referred to by `backup_file` exists in the file system before running the decorated function. """ def new_func(*args, **kwargs): backup_file = kwargs['backup_file'] if not os.path.exists(backup_file): raise Resto...
python
{ "resource": "" }
q51627
get_mysql_args
train
def get_mysql_args(db_config): """ Returns an array of argument values that will be passed to a `mysql` or `mysqldump` process when it is started based on the given database configuration. """ db = db_config['NAME'] mapping = [('--user={0}', db_config.get('USER')), ('--passwo...
python
{ "resource": "" }
q51628
get_postgresql_args
train
def get_postgresql_args(db_config, extra_args=None): """ Returns an array of argument values that will be passed to a `psql` or `pg_dump` process when it is started based on the given database configuration. """ db = db_config['NAME'] mapping = [('--username={0}', db_config.get('USER')), ...
python
{ "resource": "" }
q51629
Projects.project
train
def project(self, term, **kwargs): """Search for a project by id. Args: term (str): Term to search for. kwargs (dict): additional keywords passed into requests.session.get params keyword. """ params = kwargs baseuri = self._BASE_URI + 'projects/' ...
python
{ "resource": "" }
q51630
DictField.wrap
train
def wrap(self, value): ''' Validates ``value`` and then returns a dictionary with each key in ``value`` mapped to its value wrapped with ``DictField.value_type`` ''' self.validate_wrap(value) ret = {} for k, v in value.items(): ret[k] = self.value_type.wra...
python
{ "resource": "" }
q51631
DictField.unwrap
train
def unwrap(self, value, session=None): ''' Validates ``value`` and then returns a dictionary with each key in ``value`` mapped to its value unwrapped using ``DictField.value_type`` ''' self.validate_unwrap(value) ret = {} for k, v in value.items(): ret[k] ...
python
{ "resource": "" }
q51632
KVField.validate_unwrap
train
def validate_unwrap(self, value): ''' Expects a list of dictionaries with ``k`` and ``v`` set to the keys and values that will be unwrapped into the output python dictionary should have ''' if not isinstance(value, list): self._fail_validation_type(value, lis...
python
{ "resource": "" }
q51633
KVField.wrap
train
def wrap(self, value): ''' Expects a dictionary with the keys being instances of ``KVField.key_type`` and the values being instances of ``KVField.value_type``. After validation, the dictionary is transformed into a list of dictionaries with ``k`` and ``v`` fields set to the ...
python
{ "resource": "" }
q51634
KVField.unwrap
train
def unwrap(self, value, session=None): ''' Expects a list of dictionaries with ``k`` and ``v`` set to the keys and values that will be unwrapped into the output python dictionary should have. Validates the input and then constructs the dictionary from the list. ''' ...
python
{ "resource": "" }
q51635
apply_filters
train
def apply_filters(query, args): """ Apply all QueryFilters, validating the querystring in the process. """ pre_joins = [] for querystring_key, filter_value in args.items(multi=True): if querystring_key in filter_registry: cls_inst = filter_registry[querystring_key] qu...
python
{ "resource": "" }
q51636
_ecdsa_sign_recoverable
train
def _ecdsa_sign_recoverable(msg32, seckey): """ Takes a message of 32 bytes and a private key Returns a recoverable signature of length 64 """ assert isinstance(msg32, bytes) assert isinstance(seckey, bytes) assert len(msg32) == len(seckey) == 32 if not _verify_seckey(seckey): ...
python
{ "resource": "" }
q51637
_parse_to_recoverable_signature
train
def _parse_to_recoverable_signature(sig): """ Returns a parsed recoverable signature of length 65 bytes """ # Buffer for getting values of signature object assert isinstance(sig, bytes) assert len(sig) == 65 # Make a recoverable signature of 65 bytes rec_sig = ffi.new("secp256k1_ecd...
python
{ "resource": "" }
q51638
ecdsa_sign_compact
train
def ecdsa_sign_compact(msg32, seckey): """ Takes the same message and seckey as _ecdsa_sign_recoverable Returns an unsigned char array of length 65 containing the signed message """ # Assign 65 bytes to output output64 = ffi.new("unsigned char[65]") # ffi definition of recid reci...
python
{ "resource": "" }
q51639
ecdsa_recover_compact
train
def ecdsa_recover_compact(msg32, sig): """ Takes the a message and a parsed recoverable signature Returns the serialized public key from the private key in the sign function """ assert isinstance(msg32, bytes) assert len(msg32) == 32 _check_signature(sig) # Check that recid is of...
python
{ "resource": "" }
q51640
ecdsa_verify_compact
train
def ecdsa_verify_compact(msg32, sig, pub): """ Takes a message of length 32 and a signed message and a pubkey Returns True if the signature is valid """ assert isinstance(msg32, bytes) assert len(msg32) == 32 # Check if pubkey has been bin_electrum encoded. # If so, append \04 to...
python
{ "resource": "" }
q51641
ecdsa_verify_raw
train
def ecdsa_verify_raw(msg32, vrs, pub): """ Takes a message, the signature being verified and a pubkey Returns 1 if signature is valid with given pubkey """ # assert len(vrs) == 3 if len(vrs) == 3: return ecdsa_verify_compact(msg32, _encode_sig(*vrs), pub) else: return...
python
{ "resource": "" }
q51642
_setup_virtualenv
train
def _setup_virtualenv(): """ Setup and install virtualenv """ print("Downloading virtualenv...") import gzip, tarfile, io, tempfile, shutil tf = tarfile.open(fileobj=io.BytesIO(urlopen(VIRTUALENV_URL).read())) temp_folder = tempfile.mkdtemp() tf.extractall(temp_folder) print("Calling virtual...
python
{ "resource": "" }
q51643
_run_with_different_python
train
def _run_with_different_python(executable): """ Run bootstrap.py with a different python executable """ args = [arg for arg in sys.argv if arg != VIRTUALENV_OPTION] args.insert(0, executable) print("Running bootstrap.py with {0}".format(executable)) exit(subprocess.call(args))
python
{ "resource": "" }
q51644
DynamicMixin.get_collection
train
def get_collection(self, request, **resources): """ Get filters and return filtered result. :return collection: collection of related resources. """ if self._meta.queryset is None: return [] # Filter collection filters = self.get_filters(request, **resource...
python
{ "resource": "" }
q51645
DynamicMixin.get_default_filters
train
def get_default_filters(self, **resources): """ Return default filters by a model fields. :return dict: name, field """ return dict((k, (v, False)) for k, v in resources.items() if k in self._meta.fields)
python
{ "resource": "" }
q51646
DynamicMixin.get_filters
train
def get_filters(self, request, **resources): """ Make filters from GET variables. :return dict: filters """ filters = dict() if not self._meta.fields: return filters for field in request.GET.iterkeys(): tokens = field.split(LOOKUP_SEP) ...
python
{ "resource": "" }
q51647
DynamicMixin.get_sorting
train
def get_sorting(self, request, **resources): """ Get sorting options. :return list: sorting order """ sorting = [] if not request.GET: return sorting prefix = self._meta.dyn_prefix + 'sort' return request.GET.getlist(prefix)
python
{ "resource": "" }
q51648
auto_zip_open
train
def auto_zip_open(filepath, mode): """Convenience function for opening potentially-compressed files.""" if filepath.endswith('.gz'): outfile = gzip.open(filepath, mode) elif filepath.endswith('.bz2'): outfile = bz2.BZ2File(filepath, mode) else: outfile = open(filepath, mode) ...
python
{ "resource": "" }
q51649
process_full_position
train
def process_full_position(data, header, var_only=False): """ Return genetic data when all alleles called on same line. Returns an array containing one item, a tuple of five items: (string) chromosome (string) start position (1-based) (array of strings) matching dbSNP entries ...
python
{ "resource": "" }
q51650
process_allele
train
def process_allele(allele_data, dbsnp_data, header, reference): """Combine data from multiple lines refering to a single allele. Returns three items in this order: (string) concatenated variant sequence (ie allele the genome has) (string) concatenated reference sequence (string) start p...
python
{ "resource": "" }
q51651
get_split_pos_lines
train
def get_split_pos_lines(data, cgi_input, header): """Advance across split alleles and return data from each. CGI var file reports alleles separately for heterozygous sites: all variant or reference information is called for the first allele, then for the second. This function moves forward in the file ...
python
{ "resource": "" }
q51652
process_split_position
train
def process_split_position(data, cgi_input, header, reference, var_only=False): """Process CGI var where alleles are reported separately. Split positions report each allele with one or more lines. To ensure that we've read through all lines, we end up reading one line beyond. This function returns dat...
python
{ "resource": "" }
q51653
process_next_position
train
def process_next_position(data, cgi_input, header, reference, var_only): """ Determine appropriate processing to get data, then convert it to VCF There are two types of lines in the var file: - "full position": single allele (hemizygous) or all-allele line All alleles at this position are repre...
python
{ "resource": "" }
q51654
convert
train
def convert(cgi_input, twobit_ref, twobit_name, var_only=False): """Generator that converts CGI var data to VCF-formated strings""" # Set up CGI input. Default is to assume a str generator. if isinstance(cgi_input, str) or isinstance(cgi_input, unicode): cgi_input = auto_zip_open(cgi_input, 'rb') ...
python
{ "resource": "" }
q51655
convert_to_file
train
def convert_to_file(cgi_input, output_file, twobit_ref, twobit_name, var_only=False): """Convert a CGI var file and output VCF-formatted data to file""" if isinstance(output_file, str): output_file = auto_zip_open(output_file, 'w') conversion = convert(cgi_input=cgi_input, twobit_ref=twobit_ref, t...
python
{ "resource": "" }
q51656
get_reference_genome_file
train
def get_reference_genome_file(refseqdir, build): """ Convenience fxn to get reference genome from target dir, download if needed """ if not os.path.exists(refseqdir) or not os.path.isdir(refseqdir): raise ValueError("No directory at {}".format(refseqdir)) twobit_name = '' if build in ['b...
python
{ "resource": "" }
q51657
from_command_line
train
def from_command_line(): """ Run CGI var to gVCF conversion from the command line. """ # Parse options parser = argparse.ArgumentParser( description='Convert Complete Genomics var files to gVCF format.') parser.add_argument( '-d', '--refseqdir', metavar='REFSEQDIR', required=True...
python
{ "resource": "" }
q51658
job
train
def job(func_or_queue=None, connection=None, *args, **kwargs): """ The same as RQ's job decorator, but it works automatically works out the ``connection`` argument from RQ_QUEUES. And also, it allows simplified ``@job`` syntax to put job into default queue. """ if callable(func_or_queue): ...
python
{ "resource": "" }
q51659
Channel.publish
train
def publish(self, **kwargs): "Publishes to the channel which notifies all connected handlers." log.debug('Publish to {0}'.format(self)) self.signal.send(sender=self.name, **kwargs)
python
{ "resource": "" }
q51660
Channel.subscribe
train
def subscribe(self, receiver): "Subscribes an external handler to this channel." log.debug('{0}.{1} subscribe to {2}' .format(receiver.__module__, receiver.__name__, self)) self.signal.connect(receiver)
python
{ "resource": "" }
q51661
RPCResource.configure_rpc
train
def configure_rpc(cls, scheme=None): """ Get methods from scheme. """ scheme = scheme or cls._meta.scheme if not scheme: return if isinstance(scheme, basestring): scheme = importlib.import_module(scheme) cls.scheme_name = scheme.__name__ method...
python
{ "resource": "" }
q51662
RPCResource.handle_request
train
def handle_request(self, request, **resources): """ Call RPC method. :return object: call's result """ if request.method == 'OPTIONS': return super(RPCResource, self).handle_request( request, **resources) payload = request.data try: ...
python
{ "resource": "" }
q51663
RPCResource.rpc_call
train
def rpc_call(self, request, method=None, params=None, **kwargs): """ Call a RPC method. return object: a result """ args = [] kwargs = dict() if isinstance(params, dict): kwargs.update(params) else: args = list(as_tuple(params)) ...
python
{ "resource": "" }
q51664
AutoJSONRPC.rpc_call
train
def rpc_call(self, request, method=None, **payload): """ Call REST API with RPC force. return object: a result """ if not method or self.separator not in method: raise AssertionError("Wrong method name: {0}".format(method)) resource_name, method = method.split(self...
python
{ "resource": "" }
q51665
browserstacker_command
train
def browserstacker_command(func): """ Shortcut to define command for BrowserStacker. """ pass_decorator = click.make_pass_decorator(APIWrapper) return cli.command()(pass_decorator(func))
python
{ "resource": "" }
q51666
AbstractQualifiedDublinCoreTerm.qdc
train
def qdc(self): '''Return the qdc tag for the term ''' start_tag = ''.join(('<', self.get_term_display().lower(), ' q="', self.qualifier, '">',)) if self.qualifier else ''.join(('<', self.get_term_display().lower(), '>', )) qdc = ''.join((start_tag, saxutils.escape(self.conten...
python
{ "resource": "" }
q51667
QualifiedDublinCoreElement.save
train
def save(self, *args, **kwargs): '''Make sure that the term is valid. If changed, create a QualifiedDublinCoreElementHistory object and save it. ''' if not self.term in self.DCELEMENT_CODE_MAP: raise ValueError('Extended Dublin Core Terms such as '+self.DCTERM_CODE_MAP[self.t...
python
{ "resource": "" }
q51668
Subscene.download
train
def download(self, sub_url): """download and unzip subtitle archive to a temp location""" response = requests.get(sub_url, headers=self.headers).text soup = BS(response, 'lxml') downlink = self.base_url+soup.select('.download a')[0]['href'] data = requests.get(downlink, headers=s...
python
{ "resource": "" }
q51669
excursion
train
def excursion(directory): """Context-manager that temporarily changes to a new working directory.""" old_dir = os.getcwd() try: os.chdir(directory) yield finally: os.chdir(old_dir)
python
{ "resource": "" }
q51670
Query.query
train
def query(self): """ The mongo query object which would be executed if this Query object were used """ if self._rawquery==True: return self.__query return flatten(self.__query)
python
{ "resource": "" }
q51671
Query.clone
train
def clone(self): ''' Creates a clone of the current query and all settings. Further updates to the cloned object or the original object will not affect each other ''' qclone = Query(self.type, self.session) qclone.__query = deepcopy(self.__query) qclone._...
python
{ "resource": "" }
q51672
Query.one
train
def one(self): ''' Execute the query and return one result. If more than one result is returned, raises a ``BadResultException`` ''' count = -1 for count, result in enumerate(self): if count > 0: raise BadResultException('Too many results for .one...
python
{ "resource": "" }
q51673
Query.filter
train
def filter(self, *query_expressions): ''' Apply the given query expressions to this query object **Example**: ``s.query(SomeObj).filter(SomeObj.age > 10, SomeObj.blood_type == 'O')`` :param query_expressions: Instances of :class:`ommongo.query_expression.QueryExpression` ....
python
{ "resource": "" }
q51674
Query.filter_by
train
def filter_by(self, **filters): ''' Filter for the names in ``filters`` being equal to the associated values. Cannot be used for sub-objects since keys must be strings''' for name, value in filters.items(): self.filter(resolve_name(self.type, name) == value) return self
python
{ "resource": "" }
q51675
Query.count
train
def count(self, with_limit_and_skip=False): ''' Execute a count on the number of results this query would return. :param with_limit_and_skip: Include ``.limit()`` and ``.skip()`` arguments in the count? ''' return self.__get_query_result().cursor.count(with_limit_and_skip=with_limit...
python
{ "resource": "" }
q51676
Query._apply_dict
train
def _apply_dict(self, qe_dict): ''' Apply a query expression, updating the query object ''' for k, v in qe_dict.items(): k = resolve_name(self.type, k) if not k in self.__query: self.__query[k] = v continue if not isinstance(self.__quer...
python
{ "resource": "" }
q51677
Query.sort
train
def sort(self, *sort_tuples): ''' pymongo-style sorting. Accepts a list of tuples. :param sort_tuples: varargs of sort tuples. ''' query = self for name, direction in sort_tuples: field = resolve_name(self.type, name) if direction in (ASCENDING, 1): ...
python
{ "resource": "" }
q51678
Query.in_
train
def in_(self, qfield, *values): ''' Check to see that the value of ``qfield`` is one of ``values`` :param qfield: Instances of :class:`ommongo.query_expression.QueryExpression` :param values: Values should be python values which ``qfield`` \ understands ''' ...
python
{ "resource": "" }
q51679
Query.find_and_modify
train
def find_and_modify(self, new=False, remove=False): ''' The mongo "find and modify" command. Behaves like an update expression in that "execute" must be called to do the update and return the results. :param new: Whether to return the new object or old (default: False) ...
python
{ "resource": "" }
q51680
RemoveQuery.or_
train
def or_(self, first_qe, *qes): ''' Works the same as the query expression method ``or_`` ''' self.__query_obj.or_(first_qe, *qes) return self
python
{ "resource": "" }
q51681
RemoveQuery.in_
train
def in_(self, qfield, *values): ''' Works the same as the query expression method ``in_`` ''' self.__query_obj.in_(qfield, *values) return self
python
{ "resource": "" }
q51682
RemoveQuery.nin
train
def nin(self, qfield, *values): ''' Works the same as the query expression method ``nin_`` ''' self.__query_obj.nin(qfield, *values) return self
python
{ "resource": "" }
q51683
action_handler_adapter
train
def action_handler_adapter(handler_cls: type, action_name: str) -> Callable: """ wraps class to wsgi application dispathing action""" if not hasattr(handler_cls(), action_name): message = "{0} does'nt have attr:{1}".format(handler_cls, action_name) raise ValueError(message) def wsgiapp(env...
python
{ "resource": "" }
q51684
MethodDispatcher.on_view_not_found
train
def on_view_not_found( self, _, start_response: Callable[[str, List[Tuple[str, str]]], None], ) -> Iterable[bytes]: """ called when valid view is not found """ start_response( "405 Method Not Allowed", [('Content-type', 'text/plain')]) return ...
python
{ "resource": "" }
q51685
ActionDispatcher.register_actionhandler
train
def register_actionhandler(self, action_handler: type) -> None: """ register class as action handler """ for k in action_handler.__dict__: if k.startswith('_'): continue app = action_handler_adapter(action_handler, k) self.register_app(k, app)
python
{ "resource": "" }
q51686
ActionDispatcher.detect_view_name
train
def detect_view_name(self, environ: Dict[str, Any]) -> str: """ get view name from routing args """ urlvars = environ.get('wsgiorg.routing_args', [(), {}])[1] return urlvars.get(self.action_var_name)
python
{ "resource": "" }
q51687
ActionDispatcher.on_view_not_found
train
def on_view_not_found( self, environ: Dict[str, Any], start_response: Callable[[str, List[Tuple[str, str]]], None], ) -> Iterable[bytes]: """ called when action is not found """ start_response( "404 Not Found", [('Content-type', 'text/plain')]) ...
python
{ "resource": "" }
q51688
Plugin.save
train
async def save(self, request, response): """Save session to response cookies.""" if isinstance(response, Response) and SESSION_KEY in request and not response.prepared: session = request[SESSION_KEY] if session.save(response.set_cookie): self.app.logger.debug('Ses...
python
{ "resource": "" }
q51689
Plugin.load_user
train
async def load_user(self, request): """Load user from request.""" if USER_KEY not in request: session = await self.load(request) if 'id' not in session: return None request[USER_KEY] = request.user = await self._user_loader(session['id']) ret...
python
{ "resource": "" }
q51690
Plugin.check_user
train
async def check_user(self, request, func=None, location=None, **kwargs): """Check for user is logged and pass the given func. :param func: user checker function, defaults to default_user_checker :param location: where to redirect if user is not logged in. May be either string (URL) ...
python
{ "resource": "" }
q51691
Plugin.user_pass
train
def user_pass(self, func=None, location=None, **rkwargs): """Decorator ensures that user pass the given func.""" def wrapper(view): view = to_coroutine(view) @functools.wraps(view) async def handler(request, *args, **kwargs): await self.check_user(req...
python
{ "resource": "" }
q51692
Plugin.login
train
async def login(self, request, id_): """Login an user by ID.""" session = await self.load(request) session['id'] = id_
python
{ "resource": "" }
q51693
Session.save
train
def save(self, set_cookie, **params): """Update cookies if the session has been changed.""" if set(self.store.items()) ^ set(self.items()): value = dict(self.items()) value = json.dumps(value) value = self.encrypt(value) if not isinstance(value, str): ...
python
{ "resource": "" }
q51694
Session.encrypt
train
def encrypt(self, value): """Encrypt session data.""" timestamp = str(int(time.time())) value = base64.b64encode(value.encode(self.encoding)) signature = create_signature(self.secret, value + timestamp.encode(), encoding=self.encoding) return ...
python
{ "resource": "" }
q51695
Session.decrypt
train
def decrypt(self, value): """Decrypt session data.""" try: value, timestamp, signature = value.split("|") except ValueError: return None if check_signature(signature, self.secret, value + timestamp, encoding=self.encoding): return base64.b64decode(valu...
python
{ "resource": "" }
q51696
SimpleExecutionEngine.execute_step
train
def execute_step(self, step): """ Execute the named step. Also control the multiplicity of input and output entities :param step: step to prepare input for :param kwargs: input to be prepared :return: dict of output by entity type """ inputs = self.get_inputs(ste...
python
{ "resource": "" }
q51697
NullBooleanPGPPublicKeyField.get_prep_value
train
def get_prep_value(self, value): """Before encryption, need to prepare values.""" value = super(NullBooleanPGPPublicKeyField, self).get_prep_value(value) if value is None: return None return "%s" % bool(value)
python
{ "resource": "" }
q51698
BaseWrapper.add_threading
train
def add_threading(self, flag): """ Indicates that this wrapper should use threading by appending an argument with the specified `flag` followed by the number of threads specified in the BioLite configuration file. """ threads = min(int(config.get_resource('threads')), self.max_concurrency) if threads > 1:...
python
{ "resource": "" }
q51699
build
train
def build(template_directories): """ Build a template from the source template directories. :param template_directories: source template directories :return: template workflow """ template = load_template(template_directories[0]) for directory in template_directories[1:]: template.u...
python
{ "resource": "" }