_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q57800
StringMagic.body
train
def body(self, environ, file_like): """Pass environ and self.variables in to template. self.variables overrides environ so that suprises in environ don't cause unexpected output if you are passing a value in explicitly. """ variables = environ.copy() variables.update(sel...
python
{ "resource": "" }
q57801
Converter.get_rate_for
train
def get_rate_for(self, currency: str, to: str, reverse: bool=False) -> Number: """Get current market rate for currency""" # Return 1 when currencies match if currency.upper() == to.upper(): return self._format_number('1.0') # Set base and quote currencies base, quot...
python
{ "resource": "" }
q57802
Converter.convert
train
def convert(self, amount: Number, currency: str, to: str, reverse: bool=False) -> Number: """Convert amount to another currency""" rate = self.get_rate_for(currency, to, reverse) if self.return_decimal: amount = Decimal(amount) return amount * rate
python
{ "resource": "" }
q57803
Converter.convert_money
train
def convert_money(self, money: Money, to: str, reverse: bool=False) -> Money: """Convert money to another currency""" converted = self.convert(money.amount, money.currency, to, reverse) return Money(converted, to)
python
{ "resource": "" }
q57804
Screen.add_icon_widget
train
def add_icon_widget(self, ref, x=1, y=1, name="heart"): """ Add Icon Widget """ if ref not in self.widgets: widget = IconWidget(screen=self, ref=ref, x=x, y=y, name=name) self.widgets[ref] = widget return self.widgets[ref]
python
{ "resource": "" }
q57805
Screen.add_scroller_widget
train
def add_scroller_widget(self, ref, left=1, top=1, right=20, bottom=1, direction="h", speed=1, text="Message"): """ Add Scroller Widget """ if ref not in self.widgets: widget = ScrollerWidget(screen=self, ref=ref, left=left, top=top, right=right, bottom=bottom, direc...
python
{ "resource": "" }
q57806
Application.install_dir
train
def install_dir(self): """Returns application installation path. .. note:: If fails this falls back to a restricted interface, which can only be used by approved apps. :rtype: str """ max_len = 500 directory = self._get_str(self._iface.get_install_dir, [se...
python
{ "resource": "" }
q57807
Application.purchase_time
train
def purchase_time(self): """Date and time of app purchase. :rtype: datetime """ ts = self._iface.get_purchase_time(self.app_id) return datetime.utcfromtimestamp(ts)
python
{ "resource": "" }
q57808
PipelineWrapperBuilder.get_args
train
def get_args(self): """ Use this context manager to add arguments to an argparse object with the add_argument method. Arguments must be defined before the command is defined. Note that no-clean and resume are added upon exit and should not be added in the context manager. For mor...
python
{ "resource": "" }
q57809
wrap_rankboost
train
def wrap_rankboost(job, rsem_files, merged_mhc_calls, transgene_out, univ_options, rankboost_options): """ A wrapper for boost_ranks. :param dict rsem_files: Dict of results from rsem :param dict merged_mhc_calls: Dict of results from merging mhc peptide binding predictions :para...
python
{ "resource": "" }
q57810
BotRegistry._path_from_module
train
def _path_from_module(module): """Attempt to determine bot's filesystem path from its module.""" # Convert paths to list because Python's _NamespacePath doesn't support # indexing. paths = list(getattr(module, '__path__', [])) if len(paths) != 1: filename = getattr(mo...
python
{ "resource": "" }
q57811
BotRegistry.create
train
def create(cls, entry): """ Factory that creates an bot config from an entry in INSTALLED_APPS. """ # trading_bots.example.bot.ExampleBot try: # If import_module succeeds, entry is a path to a bot module, # which may specify a bot class with a default_bot ...
python
{ "resource": "" }
q57812
BotRegistry.get_config
train
def get_config(self, config_name, require_ready=True): """ Return the config with the given case-insensitive config_name. Raise LookupError if no config exists with this name. """ if require_ready: self.bots.check_configs_ready() else: self.bots.ch...
python
{ "resource": "" }
q57813
BotRegistry.get_configs
train
def get_configs(self): """ Return an iterable of models. """ self.bots.check_models_ready() for config in self.configs.values(): yield config
python
{ "resource": "" }
q57814
Bots.populate
train
def populate(self, installed_bots=None): """ Load bots. Import each bot module. It is thread-safe and idempotent, but not re-entrant. """ if self.ready: return # populate() might be called by two threads in parallel on servers # that create th...
python
{ "resource": "" }
q57815
Bots.get_bot
train
def get_bot(self, bot_label): """ Import all bots and returns a bot class for the given label. Raise LookupError if no bot exists with this label. """ self.check_bots_ready() try: return self.bots[bot_label] except KeyError: message = "No i...
python
{ "resource": "" }
q57816
Bots.get_configs
train
def get_configs(self): """ Return a list of all installed configs. """ self.check_configs_ready() result = [] for bot in self.bots.values(): result.extend(list(bot.get_models())) return result
python
{ "resource": "" }
q57817
Bots.get_config
train
def get_config(self, bot_label, config_name=None, require_ready=True): """ Return the config matching the given bot_label and config_name. config_name is case-insensitive. Raise LookupError if no bot exists with this label, or no config exists with this name in the bot. Raise Val...
python
{ "resource": "" }
q57818
__to_float
train
def __to_float(val, digits): """Convert val into float with digits decimal.""" try: return round(float(val), digits) except (ValueError, TypeError): return float(0)
python
{ "resource": "" }
q57819
get_json_data
train
def get_json_data(latitude=52.091579, longitude=5.119734): """Get buienradar json data and return results.""" final_result = {SUCCESS: False, MESSAGE: None, CONTENT: None, RAINCONTENT: None} log.info("Getting buienradar json data for latitude=%s, ...
python
{ "resource": "" }
q57820
__get_precipfc_data
train
def __get_precipfc_data(latitude, longitude): """Get buienradar forecasted precipitation.""" url = 'https://gpsgadget.buienradar.nl/data/raintext?lat={}&lon={}' # rounding coordinates prevents unnecessary redirects/calls url = url.format( round(latitude, 2), round(longitude, 2) ) ...
python
{ "resource": "" }
q57821
__get_url
train
def __get_url(url): """Load json data from url and return result.""" log.info("Retrieving weather data (%s)...", url) result = {SUCCESS: False, MESSAGE: None} try: r = requests.get(url) result[STATUS_CODE] = r.status_code result[HEADERS] = r.headers result[CONTENT] = r.t...
python
{ "resource": "" }
q57822
__parse_ws_data
train
def __parse_ws_data(jsondata, latitude=52.091579, longitude=5.119734): """Parse the buienradar json and rain data.""" log.info("Parse ws data: latitude: %s, longitude: %s", latitude, longitude) result = {SUCCESS: False, MESSAGE: None, DATA: None} # select the nearest weather station loc_data = __se...
python
{ "resource": "" }
q57823
__parse_loc_data
train
def __parse_loc_data(loc_data, result): """Parse the json data from selected weatherstation.""" result[DATA] = {ATTRIBUTION: ATTRIBUTION_INFO, FORECAST: [], PRECIPITATION_FORECAST: None} for key, [value, func] in SENSOR_TYPES.items(): result[DATA][key] = None...
python
{ "resource": "" }
q57824
__parse_fc_data
train
def __parse_fc_data(fc_data): """Parse the forecast data from the json section.""" fc = [] for day in fc_data: fcdata = { CONDITION: __cond_from_desc( __get_str( day, __WEATHERDESCRIPTION) ), TEMPERATURE: __g...
python
{ "resource": "" }
q57825
__get_float
train
def __get_float(section, name): """Get the forecasted float from json section.""" try: return float(section[name]) except (ValueError, TypeError, KeyError): return float(0)
python
{ "resource": "" }
q57826
__parse_precipfc_data
train
def __parse_precipfc_data(data, timeframe): """Parse the forecasted precipitation data.""" result = {AVERAGE: None, TOTAL: None, TIMEFRAME: None} log.debug("Precipitation data: %s", data) lines = data.splitlines() index = 1 totalrain = 0 numberoflines = 0 nrlines = min(len(lines), round...
python
{ "resource": "" }
q57827
__cond_from_desc
train
def __cond_from_desc(desc): """Get the condition name from the condition description.""" # '{ 'code': 'conditon', 'detailed', 'exact', 'exact_nl'} for code, [condition, detailed, exact, exact_nl] in __BRCONDITIONS.items(): if exact_nl == desc: return {CONDCODE: code, ...
python
{ "resource": "" }
q57828
__get_ws_distance
train
def __get_ws_distance(wstation, latitude, longitude): """Get the distance to the weatherstation from wstation section of json. wstation: weerstation section of buienradar json (dict) latitude: our latitude longitude: our longitude """ if wstation: try: wslat = float(wstation...
python
{ "resource": "" }
q57829
__getStationName
train
def __getStationName(name, id): """Construct a staiion name.""" name = name.replace("Meetstation", "") name = name.strip() name += " (%s)" % id return name
python
{ "resource": "" }
q57830
WizardView.as_view
train
def as_view(cls, *args, **kwargs): """ This method is used within urls.py to create unique formwizard instances for every request. We need to override this method because we add some kwargs which are needed to make the formwizard usable. """ initkwargs = cls.get_initkwarg...
python
{ "resource": "" }
q57831
WizardView.get_initkwargs
train
def get_initkwargs(cls, form_list, initial_dict=None, instance_dict=None, condition_dict=None, *args, **kwargs): """ Creates a dict with all needed parameters for the form wizard instances. * `form_list` - is a list of forms. The list entries can be single form classes or tupl...
python
{ "resource": "" }
q57832
WizardView.dispatch
train
def dispatch(self, request, *args, **kwargs): """ This method gets called by the routing engine. The first argument is `request` which contains a `HttpRequest` instance. The request is stored in `self.request` for later use. The storage instance is stored in `self.storage`. ...
python
{ "resource": "" }
q57833
WizardView.get
train
def get(self, request, *args, **kwargs): """ This method handles GET requests. If a GET request reaches this point, the wizard assumes that the user just starts at the first step or wants to restart the process. The data of the wizard will be resetted before rendering the first ...
python
{ "resource": "" }
q57834
WizardView.post
train
def post(self, *args, **kwargs): """ This method handles POST requests. The wizard will render either the current step (if form validation wasn't successful), the next step (if the current step was stored successful) or the done view (if no more steps are available) """ ...
python
{ "resource": "" }
q57835
WizardView.render_done
train
def render_done(self, form, **kwargs): """ This method gets called when all forms passed. The method should also re-validate all steps to prevent manipulation. If any form don't validate, `render_revalidation_failure` should get called. If everything is fine call `done`. ...
python
{ "resource": "" }
q57836
WizardView.get_form_prefix
train
def get_form_prefix(self, step=None, form=None): """ Returns the prefix which will be used when calling the actual form for the given step. `step` contains the step-name, `form` the form which will be called with the returned prefix. If no step is given, the form_prefix will det...
python
{ "resource": "" }
q57837
WizardView.get_form
train
def get_form(self, step=None, data=None, files=None): """ Constructs the form for a given `step`. If no `step` is defined, the current step will be determined automatically. The form will be initialized using the `data` argument to prefill the new form. If needed, instance or qu...
python
{ "resource": "" }
q57838
WizardView.render_revalidation_failure
train
def render_revalidation_failure(self, step, form, **kwargs): """ Gets called when a form doesn't validate when rendering the done view. By default, it changed the current step to failing forms step and renders the form. """ self.storage.current_step = step return ...
python
{ "resource": "" }
q57839
WizardView.get_all_cleaned_data
train
def get_all_cleaned_data(self): """ Returns a merged dictionary of all step cleaned_data dictionaries. If a step contains a `FormSet`, the key will be prefixed with formset and contain a list of the formset' cleaned_data dictionaries. """ cleaned_data = {} for for...
python
{ "resource": "" }
q57840
WizardView.get_cleaned_data_for_step
train
def get_cleaned_data_for_step(self, step): """ Returns the cleaned data for a given `step`. Before returning the cleaned data, the stored values are being revalidated through the form. If the data doesn't validate, None will be returned. """ if step in self.form_list: ...
python
{ "resource": "" }
q57841
WizardView.get_step_index
train
def get_step_index(self, step=None): """ Returns the index for the given `step` name. If no step is given, the current step will be used to get the index. """ if step is None: step = self.steps.current return self.get_form_list().keyOrder.index(step)
python
{ "resource": "" }
q57842
WizardView.render
train
def render(self, form=None, **kwargs): """ Returns a ``HttpResponse`` containing a all needed context data. """ form = form or self.get_form() context = self.get_context_data(form, **kwargs) return self.render_to_response(context)
python
{ "resource": "" }
q57843
NamedUrlWizardView.get_initkwargs
train
def get_initkwargs(cls, *args, **kwargs): """ We require a url_name to reverse URLs later. Additionally users can pass a done_step_name to change the URL name of the "done" view. """ assert 'url_name' in kwargs, 'URL name is needed to resolve correct wizard URLs' extra_kw...
python
{ "resource": "" }
q57844
NamedUrlWizardView.get
train
def get(self, *args, **kwargs): """ This renders the form or, if needed, does the http redirects. """ step_url = kwargs.get('step', None) if step_url is None: if 'reset' in self.request.GET: self.storage.reset() self.storage.current_ste...
python
{ "resource": "" }
q57845
NamedUrlWizardView.post
train
def post(self, *args, **kwargs): """ Do a redirect if user presses the prev. step button. The rest of this is super'd from FormWizard. """ prev_step = self.request.POST.get('wizard_prev_step', None) if prev_step and prev_step in self.get_form_list(): self.stor...
python
{ "resource": "" }
q57846
NamedUrlWizardView.render_next_step
train
def render_next_step(self, form, **kwargs): """ When using the NamedUrlFormWizard, we have to redirect to update the browser's URL to match the shown step. """ next_step = self.get_next_step() self.storage.current_step = next_step return redirect(self.url_name, st...
python
{ "resource": "" }
q57847
NamedUrlWizardView.render_revalidation_failure
train
def render_revalidation_failure(self, failed_step, form, **kwargs): """ When a step fails, we have to redirect the user to the first failing step. """ self.storage.current_step = failed_step return redirect(self.url_name, step=failed_step)
python
{ "resource": "" }
q57848
get_store
train
def get_store(logger: Logger=None) -> 'Store': """Get and configure the storage backend""" from trading_bots.conf import settings store_settings = settings.storage store = store_settings.get('name', 'json') if store == 'json': store = 'trading_bots.core.storage.JSONStore' elif store == '...
python
{ "resource": "" }
q57849
parse_request_headers
train
def parse_request_headers(headers): """ convert headers in human readable format :param headers: :return: """ request_header_keys = set(headers.keys(lower=True)) request_meta_keys = set(XHEADERS_TO_ARGS_DICT.keys()) data_header_keys = request_header_keys.intersection(request_meta_keys) ...
python
{ "resource": "" }
q57850
split_docstring
train
def split_docstring(docstring): """ Separates the method's description and paramter's :return: Return description string and list of fields strings """ docstring_list = [line.strip() for line in docstring.splitlines()] description_list = list( takewhile(lambda line: not (line.startswith...
python
{ "resource": "" }
q57851
get_method_docstring
train
def get_method_docstring(cls, method_name): """ return method docstring if method docstring is empty we get docstring from parent :param method: :type method: :return: :rtype: """ method = getattr(cls, method_name, None) if method is None: return docstrign = inspect...
python
{ "resource": "" }
q57852
condition_from_code
train
def condition_from_code(condcode): """Get the condition name from the condition code.""" if condcode in __BRCONDITIONS: cond_data = __BRCONDITIONS[condcode] return {CONDCODE: condcode, CONDITION: cond_data[0], DETAILED: cond_data[1], EXACT: cond_d...
python
{ "resource": "" }
q57853
SubmissionFileValidator.validate
train
def validate(self, **kwargs): """ Validates a submission file :param file_path: path to file to be loaded. :param data: pre loaded YAML object (optional). :return: Bool to indicate the validity of the file. """ try: submission_file_schema = json.load(...
python
{ "resource": "" }
q57854
load_class_by_name
train
def load_class_by_name(name: str): """Given a dotted path, returns the class""" mod_path, _, cls_name = name.rpartition('.') mod = importlib.import_module(mod_path) cls = getattr(mod, cls_name) return cls
python
{ "resource": "" }
q57855
load_yaml_file
train
def load_yaml_file(file_path: str): """Load a YAML file from path""" with codecs.open(file_path, 'r') as f: return yaml.safe_load(f)
python
{ "resource": "" }
q57856
run_itx_resistance_assessment
train
def run_itx_resistance_assessment(job, rsem_files, univ_options, reports_options): """ A wrapper for assess_itx_resistance. :param dict rsem_files: Results from running rsem :param dict univ_options: Dict of universal options used by almost all tools :param dict reports_options: Options specific to...
python
{ "resource": "" }
q57857
CeleryMixin.CELERY_RESULT_BACKEND
train
def CELERY_RESULT_BACKEND(self): """Redis result backend config""" # allow specify directly configured = get('CELERY_RESULT_BACKEND', None) if configured: return configured if not self._redis_available(): return None host, port = self.REDIS_HOST...
python
{ "resource": "" }
q57858
CeleryMixin.BROKER_TYPE
train
def BROKER_TYPE(self): """Custom setting allowing switch between rabbitmq, redis""" broker_type = get('BROKER_TYPE', DEFAULT_BROKER_TYPE) if broker_type not in SUPPORTED_BROKER_TYPES: log.warn("Specified BROKER_TYPE {} not supported. Backing to default {}".format( br...
python
{ "resource": "" }
q57859
CeleryMixin.BROKER_URL
train
def BROKER_URL(self): """Sets BROKER_URL depending on redis or rabbitmq settings""" # also allow specify broker_url broker_url = get('BROKER_URL', None) if broker_url: log.info("Using BROKER_URL setting: {}".format(broker_url)) return broker_url redis_av...
python
{ "resource": "" }
q57860
User.traverse_inventory
train
def traverse_inventory(self, item_filter=None): """Generates market Item objects for each inventory item. :param str item_filter: See `TAG_ITEM_CLASS_` contants from .market module. """ not self._intentory_raw and self._get_inventory_raw() for item in self._intentory_raw['rgDe...
python
{ "resource": "" }
q57861
DataFileValidator.validate
train
def validate(self, **kwargs): """ Validates a data file :param file_path: path to file to be loaded. :param data: pre loaded YAML object (optional). :return: Bool to indicate the validity of the file. """ default_data_schema = json.load(open(self.default_schema_...
python
{ "resource": "" }
q57862
b
train
def b(s): """Conversion to bytes""" if sys.version < '3': if isinstance(s, unicode): #pylint: disable=undefined-variable return s.encode('utf-8') else: return s
python
{ "resource": "" }
q57863
TimblClassifier.validatefeatures
train
def validatefeatures(self,features): """Returns features in validated form, or raises an Exception. Mostly for internal use""" validatedfeatures = [] for feature in features: if isinstance(feature, int) or isinstance(feature, float): validatedfeatures.append( str(feat...
python
{ "resource": "" }
q57864
TimblClassifier.addinstance
train
def addinstance(self, testfile, features, classlabel="?"): """Adds an instance to a specific file. Especially suitable for generating test files""" features = self.validatefeatures(features) if self.delimiter in classlabel: raise ValueError("Class label contains delimiter: " + self...
python
{ "resource": "" }
q57865
TimblClassifier.crossvalidate
train
def crossvalidate(self, foldsfile): """Train & Test using cross validation, testfile is a file that contains the filenames of all the folds!""" options = "-F " + self.format + " " + self.timbloptions + " -t cross_validate" print("Instantiating Timbl API : " + options,file=stderr) if sys...
python
{ "resource": "" }
q57866
TimblClassifier.leaveoneout
train
def leaveoneout(self): """Train & Test using leave one out""" traintestfile = self.fileprefix + '.train' options = "-F " + self.format + " " + self.timbloptions + " -t leave_one_out" if sys.version < '3': self.api = timblapi.TimblAPI(b(options), b"") else: ...
python
{ "resource": "" }
q57867
_AccessState.set_action_cache
train
def set_action_cache(self, action_key, data): """Store action needs and excludes. .. note:: The action is saved only if a cache system is defined. :param action_key: The unique action name. :param data: The action to be saved. """ if self.cache: self.cache.s...
python
{ "resource": "" }
q57868
_AccessState.get_action_cache
train
def get_action_cache(self, action_key): """Get action needs and excludes from cache. .. note:: It returns the action if a cache system is defined. :param action_key: The unique action name. :returns: The action stored in cache or ``None``. """ data = None if sel...
python
{ "resource": "" }
q57869
_AccessState.delete_action_cache
train
def delete_action_cache(self, action_key): """Delete action needs and excludes from cache. .. note:: It returns the action if a cache system is defined. :param action_key: The unique action name. """ if self.cache: self.cache.delete( self.app.config[...
python
{ "resource": "" }
q57870
_AccessState.register_action
train
def register_action(self, action): """Register an action to be showed in the actions list. .. note:: A action can't be registered two times. If it happens, then an assert exception will be raised. :param action: The action to be registered. """ assert action.value not i...
python
{ "resource": "" }
q57871
_AccessState.register_system_role
train
def register_system_role(self, system_role): """Register a system role. .. note:: A system role can't be registered two times. If it happens, then an assert exception will be raised. :param system_role: The system role to be registered. """ assert system_role.value not ...
python
{ "resource": "" }
q57872
_AccessState.load_entry_point_system_roles
train
def load_entry_point_system_roles(self, entry_point_group): """Load system roles from an entry point group. :param entry_point_group: The entrypoint for extensions. """ for ep in pkg_resources.iter_entry_points(group=entry_point_group): self.register_system_role(ep.load())
python
{ "resource": "" }
q57873
main
train
def main(argv=sys.argv[1:]): """Parse argument and start main program.""" args = docopt(__doc__, argv=argv, version=pkg_resources.require('buienradar')[0].version) level = logging.ERROR if args['-v']: level = logging.INFO if args['-v'] == 2: level = logging.DEBUG ...
python
{ "resource": "" }
q57874
Achievement.global_unlock_percent
train
def global_unlock_percent(self): """Global achievement unlock percent. :rtype: float """ percent = CRef.cfloat() result = self._iface.get_ach_progress(self.name, percent) if not result: return 0.0 return float(percent)
python
{ "resource": "" }
q57875
Achievement.unlocked
train
def unlocked(self): """``True`` if achievement is unlocked. :rtype: bool """ achieved = CRef.cbool() result = self._iface.get_ach(self.name, achieved) if not result: return False return bool(achieved)
python
{ "resource": "" }
q57876
Achievement.unlock
train
def unlock(self, store=True): """Unlocks the achievement. :param bool store: Whether to send data to server immediately (as to get overlay notification). :rtype: bool """ result = self._iface.ach_unlock(self.name) result and store and self._store() return resul...
python
{ "resource": "" }
q57877
__parse_ws_data
train
def __parse_ws_data(content, latitude=52.091579, longitude=5.119734): """Parse the buienradar xml and rain data.""" log.info("Parse ws data: latitude: %s, longitude: %s", latitude, longitude) result = {SUCCESS: False, MESSAGE: None, DATA: None} # convert the xml data into a dictionary: try: ...
python
{ "resource": "" }
q57878
__parse_loc_data
train
def __parse_loc_data(loc_data, result): """Parse the xml data from selected weatherstation.""" result[DATA] = {ATTRIBUTION: ATTRIBUTION_INFO, FORECAST: [], PRECIPITATION_FORECAST: None} for key, [value, func] in SENSOR_TYPES.items(): result[DATA][key] = None ...
python
{ "resource": "" }
q57879
__parse_fc_data
train
def __parse_fc_data(fc_data): """Parse the forecast data from the xml section.""" from buienradar.buienradar import condition_from_code fc = [] for daycnt in range(1, 6): daysection = __BRDAYFC % daycnt if daysection in fc_data: tmpsect = fc_data[daysection] fcdat...
python
{ "resource": "" }
q57880
__get_ws_distance
train
def __get_ws_distance(wstation, latitude, longitude): """Get the distance to the weatherstation from wstation section of xml. wstation: weerstation section of buienradar xml (dict) latitude: our latitude longitude: our longitude """ if wstation: try: wslat = float(wstation[_...
python
{ "resource": "" }
q57881
predict_mhcii_binding
train
def predict_mhcii_binding(job, peptfile, allele, univ_options, mhcii_options): """ Predict binding for each peptide in `peptfile` to `allele` using the IEDB mhcii binding prediction tool. :param toil.fileStore.FileID peptfile: The input peptide fasta :param str allele: Allele to predict binding aga...
python
{ "resource": "" }
q57882
predict_netmhcii_binding
train
def predict_netmhcii_binding(job, peptfile, allele, univ_options, netmhciipan_options): """ Predict binding for each peptide in `peptfile` to `allele` using netMHCIIpan. :param toil.fileStore.FileID peptfile: The input peptide fasta :param str allele: Allele to predict binding against :param dict u...
python
{ "resource": "" }
q57883
_P.update
train
def update(self, permission): """In-place update of permissions.""" self.needs.update(permission.needs) self.excludes.update(permission.excludes)
python
{ "resource": "" }
q57884
Permission._load_permissions
train
def _load_permissions(self): """Load permissions associated to actions.""" result = _P(needs=set(), excludes=set()) if not self.allow_by_default: result.needs.update(self.explicit_needs) for explicit_need in self.explicit_needs: if explicit_need.method == 'action...
python
{ "resource": "" }
q57885
lazy_result
train
def lazy_result(f): """Decorate function to return LazyProxy.""" @wraps(f) def decorated(ctx, param, value): return LocalProxy(lambda: f(ctx, param, value)) return decorated
python
{ "resource": "" }
q57886
process_action
train
def process_action(ctx, param, value): """Return an action if exists.""" actions = current_app.extensions['invenio-access'].actions if value not in actions: raise click.BadParameter('Action "%s" is not registered.', value) return actions[value]
python
{ "resource": "" }
q57887
process_email
train
def process_email(ctx, param, value): """Return an user if it exists.""" user = User.query.filter(User.email == value).first() if not user: raise click.BadParameter('User with email \'%s\' not found.', value) return user
python
{ "resource": "" }
q57888
process_role
train
def process_role(ctx, param, value): """Return a role if it exists.""" role = Role.query.filter(Role.name == value).first() if not role: raise click.BadParameter('Role with name \'%s\' not found.', value) return role
python
{ "resource": "" }
q57889
allow_user
train
def allow_user(user): """Allow a user identified by an email address.""" def processor(action, argument): db.session.add( ActionUsers.allow(action, argument=argument, user_id=user.id) ) return processor
python
{ "resource": "" }
q57890
allow_role
train
def allow_role(role): """Allow a role identified by an email address.""" def processor(action, argument): db.session.add( ActionRoles.allow(action, argument=argument, role_id=role.id) ) return processor
python
{ "resource": "" }
q57891
process_allow_action
train
def process_allow_action(processors, action, argument): """Process allow action.""" for processor in processors: processor(action, argument) db.session.commit()
python
{ "resource": "" }
q57892
deny_user
train
def deny_user(user): """Deny a user identified by an email address.""" def processor(action, argument): db.session.add( ActionUsers.deny(action, argument=argument, user_id=user.id) ) return processor
python
{ "resource": "" }
q57893
deny_role
train
def deny_role(role): """Deny a role identified by an email address.""" def processor(action, argument): db.session.add( ActionRoles.deny(action, argument=argument, role_id=role.id) ) return processor
python
{ "resource": "" }
q57894
process_deny_action
train
def process_deny_action(processors, action, argument): """Process deny action.""" for processor in processors: processor(action, argument) db.session.commit()
python
{ "resource": "" }
q57895
remove_global
train
def remove_global(): """Remove global action rule.""" def processor(action, argument): ActionUsers.query_by_action(action, argument=argument).filter( ActionUsers.user_id.is_(None) ).delete(synchronize_session=False) return processor
python
{ "resource": "" }
q57896
remove_user
train
def remove_user(user): """Remove a action for a user.""" def processor(action, argument): ActionUsers.query_by_action(action, argument=argument).filter( ActionUsers.user_id == user.id ).delete(synchronize_session=False) return processor
python
{ "resource": "" }
q57897
remove_role
train
def remove_role(role): """Remove a action for a role.""" def processor(action, argument): ActionRoles.query_by_action(action, argument=argument).filter( ActionRoles.role_id == role.id ).delete(synchronize_session=False) return processor
python
{ "resource": "" }
q57898
process_remove_action
train
def process_remove_action(processors, action, argument): """Process action removals.""" for processor in processors: processor(action, argument) db.session.commit()
python
{ "resource": "" }
q57899
list_actions
train
def list_actions(): """List all registered actions.""" for name, action in _current_actions.items(): click.echo('{0}:{1}'.format( name, '*' if hasattr(action, 'argument') else '' ))
python
{ "resource": "" }