code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
# TODO needs to be documented properly. d_len = len(definition) if d_len == 0: return None if d_len == 1: return xml_to_json(element, definition[0], required) first = definition[0] if hasattr(first, '__call__'): # TODO I think it could be done without creating the...
def _parse_tuple(element, definition, required)
Parse xml element by a definition given in tuple format. :param element: ElementTree element :param definition: definition schema :type definition: tuple :param required: parsed value should be not None :type required: bool :return: parsed xml
3.613408
3.722678
0.970647
if len(definition) == 0: raise XmlToJsonException('List definition needs some definition') tag = definition[0] tag_def = definition[1] if len(definition) > 1 else None sub_list = [] for el in element.findall(tag): sub_list.append(xml_to_json(el, tag_def)) return sub_list
def _parse_list(element, definition)
Parse xml element by definition given by list. Find all elements matched by the string given as the first value in the list (as XPath or @attribute). If there is a second argument it will be handled as a definitions for the elements matched or the text when not. :param element: ElementTree elemen...
3.521428
3.536451
0.995752
required = False if name[-1] == '*': name = name[0:-1] required = True return name, required
def _parse_name(name)
Parse name in complex dict definition. In complex definition required params can be marked with `*`. :param name: :return: name and required flag :rtype: tuple
4.532699
4.931171
0.919193
"parse 'hostname:22' into a host and port, with the port optional" args = (spec.split(':', 1) + [default_port])[:2] args[1] = int(args[1]) return args[0], args[1]
def get_host_port(spec, default_port)
parse 'hostname:22' into a host and port, with the port optional
5.825496
2.782494
2.093624
''' Returns the lineage name, or None if the name cannot be found. ''' clonify_ids = [p.heavy['clonify']['id'] for p in self.heavies if 'clonify' in p.heavy] if len(clonify_ids) > 0: return clonify_ids[0] return None
def name(self)
Returns the lineage name, or None if the name cannot be found.
6.060001
4.02197
1.506725
''' Returns all lineage Pair objects that contain verified pairings. ''' if not hasattr(self.just_pairs[0], 'verified'): self.verify_light_chains() return [p for p in self.just_pairs if p.verified]
def verified_pairs(self)
Returns all lineage Pair objects that contain verified pairings.
10.036724
4.286393
2.341531
''' Calculate the size of the lineage. Inputs (optional) ----------------- pairs_only: count only paired sequences Returns ------- Lineage size (int) ''' if pairs_only: return len(self.just_pairs) else: ret...
def size(self, pairs_only=False)
Calculate the size of the lineage. Inputs (optional) ----------------- pairs_only: count only paired sequences Returns ------- Lineage size (int)
6.945227
2.865221
2.423976
''' Clusters the light chains to identify potentially spurious (non-lineage) pairings. Following clustering, all pairs in the largest light chain cluster are assumed to be correctly paired. For each of those pairs, the <verified> attribute is set to True. For pairs not in the lar...
def verify_light_chains(self, threshold=0.9)
Clusters the light chains to identify potentially spurious (non-lineage) pairings. Following clustering, all pairs in the largest light chain cluster are assumed to be correctly paired. For each of those pairs, the <verified> attribute is set to True. For pairs not in the largest light c...
6.637198
2.187114
3.034684
''' Returns a multiple sequence alignment of all lineage sequence with the UCA where matches to the UCA are shown as dots and mismatches are shown as the mismatched residue. Inputs (optional) ----------------- seq_field: the sequence field to be used for alignmen...
def dot_alignment(self, seq_field='vdj_nt', name_field='seq_id', uca=None, chain='heavy', uca_name='UCA', as_fasta=False, just_alignment=False)
Returns a multiple sequence alignment of all lineage sequence with the UCA where matches to the UCA are shown as dots and mismatches are shown as the mismatched residue. Inputs (optional) ----------------- seq_field: the sequence field to be used for alignment. Default is 'vdj_n...
2.493858
1.871959
1.332218
bad_pars = set(kwargs) - set(self._child_params) if bad_pars: raise KeyError("Invalid init params for State: %s" % ", ".join(bad_pars)) child = copy(self) for k, v in kwargs.items(): setattr(child, k, v) child.parent = self # append mes...
def to_child(self, append_message="", **kwargs)
Basic implementation of returning a child state
3.563793
3.241375
1.099469
el = ET.SubElement(parent, key) value = data[key] if isinstance(value, dict): if '_attr' in value: for a_name, a_value in viewitems(value['_attr']): el.set(a_name, a_value) if '_text' in value: el.text = value['_text'] else: el.text...
def complex_el_from_dict(parent, data, key)
Create element from a dict definition and add it to ``parent``. :param parent: parent element :type parent: Element :param data: dictionary with elements definitions, it can be a simple \ {element_name: 'element_value'} or complex \ {element_name: {_attr: {name: value, name1: value1}, _text: 'text'...
2.37828
2.417145
0.983921
el = ET.SubElement(parent, element) el.text = data.pop(element) return el
def element_from_dict(parent, data, element)
Create ``element`` to ``parent`` and sets its value to data[element], which will be removed from the ``data``. :param parent: parent element :type parent: Element :param data: dictionary where data[element] is desired value :type data: dict(str, str) :param element: name of the new element ...
5.288609
7.210647
0.733444
channel = channel.copy() # TODO use deepcopy # list will not clone the dictionaries in the list and `elemen_from_dict` # pops items from them articles = list(articles) rss = ET.Element('rss') rss.set('version', '2.0') channel_node = ET.SubElement(rss, 'channel') element_from...
def rss_create(channel, articles)
Create RSS xml feed. :param channel: channel info [title, link, description, language] :type channel: dict(str, str) :param articles: list of articles, an article is a dictionary with some \ required fields [title, description, link] and any optional, which will \ result to `<dict_key>dict_value</d...
2.783516
2.675883
1.040223
secure_token = config[TOKEN_SERVICE_SECURITY_CONFIG] sha1hash = hashlib.sha1() sha1hash.update(random_token + secure_token) return sha1hash.hexdigest().upper()
def compute_token(random_token, config)
Compute a hash of the given token with a preconfigured secret. :param random_token: random token :type random_token: str :return: hashed token :rtype: str
4.765831
5.186791
0.91884
random_token = security[TOKEN_RANDOM] hashed_token = security[TOKEN_HASHED] return str(hashed_token) == str(compute_token(random_token))
def verify_security_data(security)
Verify an untrusted security token. :param security: security token :type security: dict :return: True if valid :rtype: bool
5.65601
5.644665
1.00201
''' Initializes an AbTools pipeline. Initialization includes printing the AbTools splash, setting up logging, creating the project directory, and logging both the project directory and the log location. Args: log_file (str): Path to the log file. Required. project_dir (str): ...
def initialize(log_file, project_dir=None, debug=False)
Initializes an AbTools pipeline. Initialization includes printing the AbTools splash, setting up logging, creating the project directory, and logging both the project directory and the log location. Args: log_file (str): Path to the log file. Required. project_dir (str): Path to the ...
4.217495
1.756125
2.401592
''' Lists files in a given directory. Args: d (str): Path to a directory. extension (str): If supplied, only files that contain the specificied extension will be returned. Default is ``False``, which returns all files in ``d``. Returns: list: A sorted...
def list_files(d, extension=None)
Lists files in a given directory. Args: d (str): Path to a directory. extension (str): If supplied, only files that contain the specificied extension will be returned. Default is ``False``, which returns all files in ``d``. Returns: list: A sorted list of fil...
2.862227
1.832452
1.561966
if not value or ctx.resilient_parsing: return message = 'Zsl %(version)s\nPython %(python_version)s' click.echo(message % { 'version': version, 'python_version': sys.version, }, color=ctx.color) ctx.exit()
def _get_version(ctx, _, value)
Click callback for option to show current ZSL version.
3.971956
2.748131
1.44533
try: resource_description = resource_map[name] if len(resource_description) == 2: module_name, model_name = resource_map[name] resource_class = ModelResource elif len(resource_description) == 3: module_name, model_name, resource_class = resource_map[n...
def create_model_resource(resource_map, name, app=Injected)
Create a model resource from a dict ``resource_map`` {'resource name': ('model package', 'model class')} :param resource_map: dict with resource descriptions :type resource_map: dict(str, tuple(str)) :param name: name of the concrete resource :param app: current application, injected :type app:...
2.141778
2.083397
1.028022
return {key: value for key, value in viewitems(dictionary) if key in allowed_keys}
def dict_pick(dictionary, allowed_keys)
Return a dictionary only with keys found in `allowed_keys`
3.682392
3.251517
1.132515
if 'page' not in params: return page = params['page'] del params['page'] # 'per_page' je len alias za 'limit' if 'per_page' in params: per_page = params.get('per_page') del params['per_page'] else: per_page = params.get('limit', 10) params['offset'] =...
def page_to_offset(params)
Transforms `page`/`per_page` from `params` to `limit`/`offset` suitable for SQL. :param dict params: The dictionary containing `page` and `per_page` values will be added the values `limit` and `offset`.
2.916641
2.947282
0.989604
# type: (str, dict, dict) -> AppModel ctx = self._create_context(params, args, data) model = self._create_one(ctx) self._save_one(model, ctx) return self._return_saved_one(model, ctx)
def create(self, params, args, data)
POST /resource/model_cls/ data Create new resource
5.017239
5.55283
0.903546
# type: (str, dict, dict) -> Union[List[AppModel], AppModel] if params is None: params = [] if args is None: args = {} ctx = self._create_context(params, args, data) row_id = ctx.get_row_id() if row_id: return self._get_one(r...
def read(self, params=None, args=None, data=None)
GET /resource/model_cls/[params:id]?[args:{limit,offset,page,per_page,filter_by,order_by,related,fields}] Get resource/s :param params :type params list :param args :type args dict :param data :type data: dict
3.269197
3.508642
0.931756
# type: (str, dict, dict) -> Union[List[AppModel], AppModel] ctx = self._create_context(params, args, data) row_id = ctx.get_row_id() if row_id is not None: model = self._update_one(ctx) return None if model is None else model.get_app_model() els...
def update(self, params, args, data)
PUT /resource/model_cls/[params:id] data Update resource/s
4.440382
4.892633
0.907565
# type: (str, dict, dict) -> None ctx = self._create_context(params, args, data) row_id = ctx.get_row_id() if row_id is not None: return self._delete_one(row_id, ctx) else: return self._delete_collection(ctx)
def delete(self, params, args, data)
DELETE /resource/model_cls/[params]?[args] delete resource/s
3.564253
3.850309
0.925706
assert isinstance(ctx, ResourceQueryContext) fields = dict_pick(ctx.data, self._model_columns) model = self.model_cls(**fields) return model
def _create_one(self, ctx)
Creates an instance to be saved when a model is created.
11.038747
8.656114
1.275254
assert isinstance(ctx, ResourceQueryContext) self._orm.add(model) self._orm.flush()
def _save_one(self, model, ctx)
Saves the created instance.
11.459397
9.419649
1.216542
assert isinstance(ctx, ResourceQueryContext) fields = ctx.data row_id = ctx.get_row_id() return self._update_one_simple(row_id, fields, ctx)
def _update_one(self, ctx)
Update row
7.117788
6.096663
1.167489
assert isinstance(ctx, ResourceQueryContext) models = [] for row in ctx.data: models.append(self._update_one_simple(row.pop('id'), row, ctx)) return models
def _update_collection(self, ctx)
Bulk update
8.590953
8.134624
1.056097
assert isinstance(ctx, ResourceQueryContext) return self._orm.query(self.model_cls).filter(self._model_pk == row_id)
def _create_delete_one_query(self, row_id, ctx)
Delete row by id query creation. :param int row_id: Identifier of the deleted row. :param ResourceQueryContext ctx: The context of this delete query.
7.570521
5.938902
1.274734
assert isinstance(ctx, ResourceQueryContext) filter_by = ctx.get_filter_by() q = self._orm.query(self.model_cls) if filter_by is not None: q = self.to_filter(q, filter_by) return q.delete()
def _delete_collection(self, ctx)
Delete a collection from DB, optionally filtered by ``filter_by``
4.430662
3.895015
1.137521
smtp_config = config['SMTP'] # Receivers must be an array. if not isinstance(receivers, list) and not isinstance(receivers, tuple): receivers = [receivers] # Create the messages msgs = [] if text is not None: msgs.append(MIMEText(text, 'plain', charset)) if html is no...
def send_email(sender, receivers, subject, text=None, html=None, charset='utf-8', config=Injected)
Sends an email. :param sender: Sender as string or None for default got from config. :param receivers: String or array of recipients. :param subject: Subject. :param text: Plain text message. :param html: Html message. :param charset: Charset. :param config: Current configuration
1.891826
1.939179
0.975581
# type: (List[str])->TaskNamespace assert isinstance(packages, list), "Packages must be list of strings." self._task_packages += packages return self
def add_packages(self, packages)
Adds an automatic resolution of urls into tasks. :param packages: The url will determine package/module and the class. :return: self
9.116429
8.065608
1.130284
# type: (str)->Tuple[Any, Callable] logging.getLogger(__name__).debug("Routing path '%s'.", path) cls = None for strategy in self._strategies: if strategy.can_route(path): cls = strategy.route(path) break if cls is None: ...
def route(self, path)
Returns the task handling the given request path.
4.6324
4.496985
1.030112
# type:(Callable)->Tuple[Any, Callable] task = instantiate(cls) logging.getLogger(__name__).debug("Task object {0} created [{1}].".format(cls.__name__, task)) return task, get_callable(task)
def _create_result(self, cls)
Create the task using the injector initialization. :param cls: :return:
8.702129
9.129478
0.95319
''' Converts ABI or AB1 files to FASTA format. Args: input (str): Path to a file or directory containing abi/ab1 files or zip archives of abi/ab1 files output (str): Path to a directory for the output FASTA files ''' direcs = [input, ] # unzip any zip archives ...
def abi_to_fasta(input, output)
Converts ABI or AB1 files to FASTA format. Args: input (str): Path to a file or directory containing abi/ab1 files or zip archives of abi/ab1 files output (str): Path to a directory for the output FASTA files
3.23381
2.314491
1.397202
instance.__class__ = type( '%s_extended_with_%s' % (instance.__class__.__name__, new_class.__name__), (new_class, instance.__class__,), {} )
def extend(instance, new_class)
Adds new_class to the ancestors of instance. :param instance: Instance that will have a new ancestor. :param new_class: Ancestor.
2.634019
3.742687
0.703777
# type: (str, str, str, str, str, str, str, bool, str) -> Union[str, None] options = { 'model_prefix': model_prefix, 'collection_prefix': collection_prefix, 'model_fn': model_fn, 'collection_fn': collection_fn } generator = ModelGenerator(module, ...
def generate_js_models(module, models, collection_prefix, model_prefix, model_fn, collection_fn, marker, integrate, js_file)
Generate models for Backbone Javascript applications. :param module: module from which models are imported :param models: model name, can be a tuple WineCountry/WineCountries as singular/plural :param model_prefix: namespace prefix for models (app.models.) :param collection_prefix: namespace prefix for...
3.391851
3.666244
0.925157
for model in model_names: if isinstance(model, tuple): model = model[0] try: model_cls = getattr(self.models, model) self.table_to_class[class_mapper(model_cls).tables[0].name] = model except AttributeError: ...
def _map_table_name(self, model_names)
Pre foregin_keys potrbejeme pre z nazvu tabulky zistit class, tak si to namapujme
3.622054
3.50359
1.033812
if type(msg) is not str: msg = urlencode(msg) return self.push(channel_id, msg)
def push_msg(self, channel_id, msg)
Push ``msg`` for given ``channel_id``. If ``msg`` is not string, it will be urlencoded
5.418451
3.884126
1.395025
return self.push(channel_id, json.dumps(obj).replace('"', '\\"'))
def push_object(self, channel_id, obj)
Push ``obj`` for ``channel_id``. ``obj`` will be encoded as JSON in the request.
6.627275
6.451256
1.027284
channel_path = self.channel_path(channel_id) response = requests.post(channel_path, data) return response.json()
def push(self, channel_id, data)
Push message with POST ``data`` for ``channel_id``
4.602527
4.152696
1.108323
req = requests.delete(self.channel_path(channel_id)) return req
def delete_channel(self, channel_id)
Deletes channel
6.429539
6.489946
0.990692
value = str(value) if allow_unicode: value = unicodedata.normalize('NFKC', value) value = re.sub(r'[^\w\s-]', '', value, flags=re.U).strip().lower() return re.sub(r'[-\s]+', '-', value, flags=re.U) else: value = unicodedata.normalize('NFKD', value).encode('ascii', 'igno...
def slugify(value, allow_unicode=False)
Normalizes string, converts to lowercase, removes non-alpha characters, and converts spaces to hyphens. :param value: string :param allow_unicode: allow utf8 characters :type allow_unicode: bool :return: slugified string :rtype: str :Example: >>> slugify('pekná líščička') '...
1.596858
1.797393
0.88843
if hasattr(urllib, 'parse'): return urllib.parse.urlencode(query) else: return urllib.urlencode(query)
def urlencode(query)
Encode string to be used in urls (percent encoding). :param query: string to be encoded :type query: str :return: urlencoded string :rtype: str :Example: >>> urlencode('pekná líščička') 'pekn%C3%A1%20l%C3%AD%C5%A1%C4%8Di%C4%8Dka'
2.46613
3.873326
0.636696
from zsl.interface.web.performers.default import create_not_found_mapping from zsl.interface.web.performers.resource import create_resource_mapping create_not_found_mapping() create_resource_mapping()
def initialize()
Import in this form is necessary so that we avoid the unwanted behavior and immediate initialization of the application objects. This makes the initialization procedure run in the time when it is necessary and has every required resources.
5.735419
5.655097
1.014204
# type: (Zsl, str, int, **Any)->None return flask.run( host=flask.config.get('FLASK_HOST', host), port=flask.config.get('FLASK_PORT', port), debug=flask.config.get('DEBUG', False), **options )
def run_web(self, flask, host='127.0.0.1', port=5000, **options)
Alias for Flask.run
3.336147
3.132187
1.065117
if args is None: args = {} command_fn = self.commands[command] return command_fn(**args)
def execute_command(self, command, args=None)
Execute a command :param command: name of the command :type command: str :param args: optional named arguments for command :type args: dict :return: the result of command :raises KeyError: if command is not found
4.300663
3.961465
1.085624
bounded_dispatcher = CommandDispatcher() bounded_dispatcher.commands = self.commands.copy() for name in self.commands: method = getattr(instance, name, None) if method and inspect.ismethod(method) and method.__self__ == instance: bounded_dispat...
def bound(self, instance)
Return a new dispatcher, which will switch all command functions with bounded methods of given instance matched by name. It will match only regular methods. :param instance: object instance :type instance: object :return: new Dispatcher :rtype: CommandDispatcher
3.551502
2.962602
1.198778
''' Compresses data and uploads to S3. S3 upload uses ``s3cmd``, so you must either: 1) Manually configure ``s3cmd`` prior to use (typically using ``s3cmd --configure``). 2) Configure ``s3cmd`` using ``s3.configure()``. 3) Pass your access key and secret key to ``compress_and_upl...
def compress_and_upload(data, compressed_file, s3_path, multipart_chunk_size_mb=500, method='gz', delete=False, access_key=None, secret_key=None)
Compresses data and uploads to S3. S3 upload uses ``s3cmd``, so you must either: 1) Manually configure ``s3cmd`` prior to use (typically using ``s3cmd --configure``). 2) Configure ``s3cmd`` using ``s3.configure()``. 3) Pass your access key and secret key to ``compress_and_upload``, which...
3.12945
1.268509
2.46703
''' Uploads a single file to S3, using s3cmd. Args: f (str): Path to a single file. s3_path (str): The S3 path, with the filename omitted. The S3 filename will be the basename of the ``f``. For example:: put(f='/path/to/myfile.tar.gz', s3_path='s3://my_bucket/...
def put(f, s3_path, multipart_chunk_size_mb=500, logger=None)
Uploads a single file to S3, using s3cmd. Args: f (str): Path to a single file. s3_path (str): The S3 path, with the filename omitted. The S3 filename will be the basename of the ``f``. For example:: put(f='/path/to/myfile.tar.gz', s3_path='s3://my_bucket/path/to/') ...
2.955948
1.789986
1.65138
''' Creates a compressed/uncompressed tar file. Args: d: Can be one of three things: 1. the path to a single file, as a string 2. the path to a single directory, as a string 3. an iterable of file or directory paths output (str): Output file path. ...
def compress(d, output, fmt='gz', logger=None)
Creates a compressed/uncompressed tar file. Args: d: Can be one of three things: 1. the path to a single file, as a string 2. the path to a single directory, as a string 3. an iterable of file or directory paths output (str): Output file path. fmt: ...
3.166711
2.047912
1.546312
''' Configures s3cmd prior to first use. If no arguments are provided, you will be prompted to enter the access key and secret key interactively. Args: access_key (str): AWS access key secret_key (str): AWS secret key ''' if not logger: logger = log.get_logger('s3...
def configure(access_key=None, secret_key=None, logger=None)
Configures s3cmd prior to first use. If no arguments are provided, you will be prompted to enter the access key and secret key interactively. Args: access_key (str): AWS access key secret_key (str): AWS secret key
3.357791
2.100767
1.598365
if not reduce(lambda still_valid, param: still_valid and param in data, r_params, True): raise RequestException(msg_err_missing_params(*r_params))
def required_params(data, *r_params)
Check if given parameters are in the given dict, if not raise an exception. :param data: data to check :type data: dict :param r_params: required parameters :raises RequestException: if params not in data
7.483214
6.42867
1.164038
fn_args = inspect.getargspec(fn) if fn_args.defaults: required_params(args, fn_args.args[:-len(fn_args.defaults)]) else: required_params(args, fn_args) if not fn_args.keywords: return {key: value for key, value in viewitems(args) if key in fn_args.args} else: r...
def safe_args(fn, args)
Check if ``args`` as a dictionary has the required parameters of ``fn`` function and filter any waste parameters so ``fn`` can be safely called with them. :param fn: function object :type fn: Callable :param args: dictionary of parameters :type args: dict :return: dictionary to be used as n...
2.831407
3.046246
0.929474
''' Returns a pymongo Database object. .. note: Both ``user`` and ``password`` are required when connecting to a MongoDB database that has authentication enabled. Arguments: db (str): Name of the MongoDB database. Required. ip (str): IP address of the MongoDB server....
def get_db(db, ip='localhost', port=27017, user=None, password=None)
Returns a pymongo Database object. .. note: Both ``user`` and ``password`` are required when connecting to a MongoDB database that has authentication enabled. Arguments: db (str): Name of the MongoDB database. Required. ip (str): IP address of the MongoDB server. Default is ...
2.466936
1.554217
1.587254
''' Returns a sorted list of collection names found in ``db``. Arguments: db (Database): A pymongo Database object. Can be obtained with ``get_db``. collection (str): Name of a collection. If the collection is present in the MongoDB database, a single-element list ...
def get_collections(db, collection=None, prefix=None, suffix=None)
Returns a sorted list of collection names found in ``db``. Arguments: db (Database): A pymongo Database object. Can be obtained with ``get_db``. collection (str): Name of a collection. If the collection is present in the MongoDB database, a single-element list will ...
2.922242
1.28489
2.274312
''' Renames a MongoDB collection. Arguments: db (Database): A pymongo Database object. Can be obtained with ``get_db``. collection (str): Name of the collection to be renamed. new_name (str, func): ``new_name`` can be one of two things:: 1. The new collec...
def rename_collection(db, collection, new_name)
Renames a MongoDB collection. Arguments: db (Database): A pymongo Database object. Can be obtained with ``get_db``. collection (str): Name of the collection to be renamed. new_name (str, func): ``new_name`` can be one of two things:: 1. The new collection name, a...
3.323184
1.501642
2.213034
''' Updates MongoDB documents. Sets ``field`` equal to ``value`` for all documents that meet ``match`` criteria. Arguments: field (str): Field to update. value (str): Update value. db (Database): A pymongo Database object. collection (str): Collection name. ...
def update(field, value, db, collection, match=None)
Updates MongoDB documents. Sets ``field`` equal to ``value`` for all documents that meet ``match`` criteria. Arguments: field (str): Field to update. value (str): Update value. db (Database): A pymongo Database object. collection (str): Collection name. match (...
3.47995
1.662878
2.092727
''' Builds a simple (single field) or complex (multiple fields) index on a single collection in a MongoDB database. Args: db (Database): A pymongo Database object. collection (str): Collection name. fields: Can be one of two things: - the name of a single field, ...
def index(db, collection, fields, directions=None, desc=False, background=False)
Builds a simple (single field) or complex (multiple fields) index on a single collection in a MongoDB database. Args: db (Database): A pymongo Database object. collection (str): Collection name. fields: Can be one of two things: - the name of a single field, as a string ...
4.319897
1.424904
3.03171
# type: (str, Any)->str if profile_dir is None: import settings profile_dir = settings if hasattr(profile_dir, '__file__'): profile_dir = os.path.dirname(profile_dir.__file__) return os.path.join(profile_dir, '{0}.cfg'.format(profile))
def get_settings_from_profile(profile, profile_dir=None)
Returns the configuration file path for the given profile. :param profile: Profile name to be used. :param profile_dir: The directory where the profile configuration file should reside. It may be also a module, and then the directory of the module is used. :return: Configuration fi...
3.314725
3.446069
0.961886
# type: (Any) -> None if config_object: self.config.from_mapping(config_object) else: self.config.from_object(self._default_settings_module) zsl_settings = os.environ.get(SETTINGS_ENV_VAR_NAME) if zsl_settings is not None: self.confi...
def _configure(self, config_object=None)
Read the configuration from config files. Loads the default settings and the profile settings if available. Check :func:`.set_profile`. :param config_object: This parameter is the configuration decscription may be a dict or string describing the module from which the con...
3.388193
3.695091
0.916944
# type: () -> Callable def configure(binder): # type: (Binder) -> Callable binder.bind(ServiceApplication, to=self, scope=singleton) binder.bind(Config, to=self.config, scope=singleton) return configure
def _get_app_module(self)
Returns a module which binds the current app and configuration. :return: configuration callback :rtype: Callable
5.199439
5.560625
0.935046
self._register() self._create_injector() self._bind_core() self._bind_modules(modules) self.logger.debug("Injector configuration with modules {0}.".format(modules)) self._dependencies_initialized = True
def _configure_injector(self, modules)
Create the injector and install the modules. There is a necessary order of calls. First we have to bind `Config` and `Zsl`, then we need to register the app into the global stack and then we can install all other modules, which can use `Zsl` and `Config` injection. :param modul...
6.11698
6.015165
1.016926
# type: (Binder) -> None redis_cache_module = RedisCacheModule() binder.bind( RedisCacheModule, to=redis_cache_module, scope=singleton ) binder.bind( CacheModule, to=redis_cache_module, scope=singlet...
def configure(self, binder)
Initializer of the cache - creates the Redis cache module as the default cache infrastructure. The module is bound to `RedisCacheModule` and `CacheModule` keys. The initializer also creates `RedisIdHelper` and bounds it to `RedisIdHelper` and `IdHelper` keys. :param Binder binder: The b...
2.60592
2.159964
1.206465
@wraps(f) def error_handling_function(*args, **kwargs): @inject(error_config=ErrorConfiguration) def get_error_configuration(error_config): # type:(ErrorConfiguration)->ErrorConfiguration return error_config def should_skip_handling(): use_flask...
def error_handler(f)
Default error handler. - On server side error shows a message 'An error occurred!' and returns 500 status code. - Also serves well in the case when the resource/task/method is not found - returns 404 status code.
3.664421
3.545867
1.033434
''' Wraps a property to provide lazy evaluation. Eliminates boilerplate. Also provides for setting and deleting the property. Use as you would use the @property decorator:: # OLD: class MyClass(): def __init__(): self._compute = None @property ...
def lazy_property(func)
Wraps a property to provide lazy evaluation. Eliminates boilerplate. Also provides for setting and deleting the property. Use as you would use the @property decorator:: # OLD: class MyClass(): def __init__(): self._compute = None @property d...
3.406605
1.155933
2.94706
''' Initializes a coroutine -- essentially it just takes a generator function and calls generator.next() to get things going. ''' def start(*args, **kwargs): cr = func(*args, **kwargs) cr.next() return cr return start
def coroutine(func)
Initializes a coroutine -- essentially it just takes a generator function and calls generator.next() to get things going.
6.182648
2.13687
2.89332
''' str: Returns the sequence, as a FASTA-formatted string Note: The FASTA string is built using ``Sequence.id`` and ``Sequence.sequence``. ''' if not self._fasta: self._fasta = '>{}\n{}'.format(self.id, self.sequence) return self._fasta
def fasta(self)
str: Returns the sequence, as a FASTA-formatted string Note: The FASTA string is built using ``Sequence.id`` and ``Sequence.sequence``.
4.914081
2.249647
2.184379
''' str: Returns the sequence, as a FASTQ-formatted string If ``Sequence.qual`` is ``None``, then ``None`` will be returned instead of a FASTQ string ''' if self.qual is None: self._fastq = None else: if self._fastq is None: ...
def fastq(self)
str: Returns the sequence, as a FASTQ-formatted string If ``Sequence.qual`` is ``None``, then ``None`` will be returned instead of a FASTQ string
4.357296
2.251667
1.935142
''' str: Returns the reverse complement of ``Sequence.sequence``. ''' if self._reverse_complement is None: self._reverse_complement = self._get_reverse_complement() return self._reverse_complement
def reverse_complement(self)
str: Returns the reverse complement of ``Sequence.sequence``.
4.228335
2.814703
1.502231
''' Returns a region of ``Sequence.sequence``, in FASTA format. If called without kwargs, the entire sequence will be returned. Args: start (int): Start position of the region to be returned. Default is 0. end (int): End position of the region ...
def region(self, start=0, end=None)
Returns a region of ``Sequence.sequence``, in FASTA format. If called without kwargs, the entire sequence will be returned. Args: start (int): Start position of the region to be returned. Default is 0. end (int): End position of the region to be returned. Nega...
4.463251
1.498384
2.97871
value = str(value) camelized = "".join(x.title() if x else '_' for x in value.split("_")) if not first_upper: camelized = camelized[0].lower() + camelized[1:] return camelized
def underscore_to_camelcase(value, first_upper=True)
Transform string from underscore_string to camelCase. :param value: string with underscores :param first_upper: the result will have its first character in upper case :type value: str :return: string in CamelCase or camelCase according to the first_upper :rtype: str :Example: >>> under...
2.311762
2.884869
0.801341
return str(et_node.text).strip() if et_node is not None and et_node.text else default
def et_node_to_string(et_node, default='')
Simple method to get stripped text from node or ``default`` string if None is given. :param et_node: Element or None :param default: string returned if None is given, default ``''`` :type et_node: xml.etree.ElementTree.Element, None :type default: str :return: text from node or default :rtype: ...
3.777028
3.712063
1.017501
return ''.join(random.choice(chars) for _ in range(size))
def generate_random_string(size=6, chars=string.ascii_uppercase + string.digits)
Generate random string. :param size: Length of the returned string. Default is 6. :param chars: List of the usable characters. Default is string.ascii_uppercase + string.digits. :type size: int :type chars: str :return: The random string. :rtype: str
2.750764
4.972034
0.553247
if escaped_chars is None: escaped_chars = ["\\", "'", ] # l = ["\\", '"', "'", "\0", ] for i in escaped_chars: if i in s: s = s.replace(i, '\\' + i) return s
def addslashes(s, escaped_chars=None)
Add slashes for given characters. Default is for ``\`` and ``'``. :param s: string :param escaped_chars: list of characters to prefix with a slash ``\`` :return: string with slashed characters :rtype: str :Example: >>> addslashes("'") "\\'"
4.101466
4.737424
0.865759
# type: (Union[List[str], str], str)->str if transform is None: transform = _identity if values is not None and not isinstance(values, (str, bytes)): values = delimiter.join(transform(x) for x in values) return values
def join_list(values, delimiter=', ', transform=None)
Concatenates the upper-cased values using the given delimiter if the given values variable is a list. Otherwise it is just returned. :param values: List of strings or string . :param delimiter: The delimiter used to join the values. :return: The concatenation or identity.
3.455711
3.44431
1.00331
(module_name, class_name) = full_class_name.rsplit('.', 1) module = importlib.import_module(module_name) return getattr(module, class_name)
def fetch_class(full_class_name)
Fetches the given class. :param string full_class_name: Name of the class to be fetched.
1.708429
2.431625
0.702587
ctxt = {} exec(state.student_code, globals(), ctxt) sel_indx = ctxt["selected_option"] if sel_indx != correct: state.report(Feedback(msgs[sel_indx - 1])) else: state.reporter.success_msg = msgs[correct - 1] return state
def has_chosen(state, correct, msgs)
Verify exercises of the type MultipleChoiceExercise Args: state: State instance describing student and solution code. Can be omitted if used with Ex(). correct: index of correct option, where 1 is the first option. msgs : list of feedback messages corresponding to each option. ...
7.8634
7.237037
1.08655
for test in iter_tests(tests): # assume test is function needing a state argument # partial state so reporter can test state.do_test(partial(test, state)) # return original state, so can be chained return state
def multi(state, *tests)
Run multiple subtests. Return original state (for chaining). This function could be thought as an AND statement, since all tests it runs must pass Args: state: State instance describing student and solution code, can be omitted if used with Ex() tests: one or more sub-SCTs to run. :Examp...
17.726313
23.094429
0.767558
for test in iter_tests(tests): try: test(state) except TestFail: # it fails, as expected, off to next one continue return state.report(Feedback(msg)) # return original state, so can be chained return state
def check_not(state, *tests, msg)
Run multiple subtests that should fail. If all subtests fail, returns original state (for chaining) - This function is currently only tested in working with ``has_code()`` in the subtests. - This function can be thought as a ``NOT(x OR y OR ...)`` statement, since all tests it runs must fail - This functio...
12.96873
16.401512
0.790703
success = False first_feedback = None for test in iter_tests(tests): try: multi(state, test) success = True except TestFail as e: if not first_feedback: first_feedback = e.feedback if success: return state # todo:...
def check_or(state, *tests)
Test whether at least one SCT passes. If all of the tests fail, the feedback of the first test will be presented to the student. Args: state: State instance describing student and solution code, can be omitted if used with Ex() tests: one or more sub-SCTs to run :Example: The SCT ...
6.689362
6.91029
0.968029
feedback = None try: multi(state, check) except TestFail as e: feedback = e.feedback # todo: let if from except wrap try-except # only once teach uses force_diagnose try: multi(state, diagnose) except TestFail as e: if feedback is not None or state.forc...
def check_correct(state, check, diagnose)
Allows feedback from a diagnostic SCT, only if a check SCT fails. Args: state: State instance describing student and solution code. Can be omitted if used with Ex(). check: An sct chain that must succeed. diagnose: An sct chain to run if the check fails. :Example: The SCT below...
8.738289
9.757313
0.895563
_msg = state.build_message(msg) state.report(Feedback(_msg, state)) return state
def fail(state, msg="fail")
Always fails the SCT, with an optional msg. This function takes a single argument, ``msg``, that is the feedback given to the student. Note that this would be a terrible idea for grading submissions, but may be useful while writing SCTs. For example, failing a test will highlight the code as if the previou...
14.403616
20.192211
0.713325
if not reduce(lambda still_valid, param: still_valid and param in element.attrib, attributes, True): raise NotValidXmlException(msg_err_missing_attributes(element.tag, *attributes))
def required_attributes(element, *attributes)
Check element for required attributes. Raise ``NotValidXmlException`` on error. :param element: ElementTree element :param attributes: list of attributes names to check :raises NotValidXmlException: if some argument is missing
7.268656
6.519131
1.114973
for child in children: if element.find(child) is None: raise NotValidXmlException(msg_err_missing_children(element.tag, *children))
def required_elements(element, *children)
Check element (``xml.etree.ElementTree.Element``) for required children, defined as XPath. Raise ``NotValidXmlException`` on error. :param element: ElementTree element :param children: list of XPaths to check :raises NotValidXmlException: if some child is missing
4.900583
4.405182
1.112459
required_elements(element, *children) required_attributes(element, *attributes)
def required_items(element, children, attributes)
Check an xml element to include given attributes and children. :param element: ElementTree element :param children: list of XPaths to check :param attributes: list of attributes names to check :raises NotValidXmlException: if some argument is missing :raises NotValidXmlException: if some child is m...
5.993406
7.225757
0.82945
if len(args) > 0: return {key: element.get(key) for key in args} if len(kwargs) > 0: return {new_key: element.get(old_key) for new_key, old_key in viewitems(kwargs)} return element.attrib
def attrib_to_dict(element, *args, **kwargs)
For an ElementTree ``element`` extract specified attributes. If an attribute does not exists, its value will be ``None``. attrib_to_dict(element, 'attr_a', 'attr_b') -> {'attr_a': 'value', 'attr_a': 'value'} Mapping between xml attributes and dictionary keys is done with kwargs. attrib_to_dict(element...
2.65042
2.710136
0.977966
r = requests.get(xml_path) root = ET.fromstring(r.content) return root
def get_xml_root(xml_path)
Load and parse an xml by given xml_path and return its root. :param xml_path: URL to a xml file :type xml_path: str :return: xml root
2.647685
3.656499
0.724104
if attribute is not None: return int(element.get(attribute)) else: return int(element.text)
def element_to_int(element, attribute=None)
Convert ``element`` object to int. If attribute is not given, convert ``element.text``. :param element: ElementTree element :param attribute: attribute name :type attribute: str :returns: integer :rtype: int
2.386127
2.628556
0.907771
if attrib is None: attrib = {} el = ET.Element(name, attrib) if text is not None: el.text = text return el
def create_el(name, text=None, attrib=None)
Create element with given attributes and set element.text property to given text value (if text is not None) :param name: element name :type name: str :param text: text node value :type text: str :param attrib: attributes :type attrib: dict :returns: xml element :rtype: Element
2.068698
2.812576
0.735517
members = inspect.getmembers(cls, lambda a: not (inspect.isroutine(a) and a.__name__ == 'modules')) modules = [module for name, module in members if not name.startswith('_')] return modules
def modules(cls)
Collect all the public class attributes. All class attributes should be a DI modules, this method collects them and returns as a list. :return: list of DI modules :rtype: list[Union[Module, Callable]]
3.357882
3.635739
0.923576
''' Gets sequences and assigns them to the appropriate mAb pair, based on the sequence name. Inputs: ::db:: is a pymongo database connection object ::collection:: is the collection name, as a string If ::subject:: is provided, only sequences with a 'subject' field matching ::subject:: will ...
def get_pairs(db, collection, experiment=None, subject=None, group=None, name='seq_id', delim=None, delim_occurance=1, pairs_only=False, h_selection_func=None, l_selection_func=None)
Gets sequences and assigns them to the appropriate mAb pair, based on the sequence name. Inputs: ::db:: is a pymongo database connection object ::collection:: is the collection name, as a string If ::subject:: is provided, only sequences with a 'subject' field matching ::subject:: will be incl...
2.791193
1.218391
2.290885
''' Assigns sequences to the appropriate mAb pair, based on the sequence name. Inputs: ::seqs:: is a list of dicts, of the format returned by querying a MongoDB containing Abstar output. ::name:: is the dict key of the field to be used to group the sequences into pairs. Default is ...
def assign_pairs(seqs, name='seq_id', delim=None, delim_occurance=1, pairs_only=False, h_selection_func=None, l_selection_func=None)
Assigns sequences to the appropriate mAb pair, based on the sequence name. Inputs: ::seqs:: is a list of dicts, of the format returned by querying a MongoDB containing Abstar output. ::name:: is the dict key of the field to be used to group the sequences into pairs. Default is 'seq_id' ...
3.92117
1.312848
2.986767
''' Removes duplicate sequences from a list of Pair objects. If a Pair has heavy and light chains, both chains must identically match heavy and light chains from another Pair to be considered a duplicate. If a Pair has only a single chain, identical matches to that chain will cause the single chain...
def deduplicate(pairs, aa=False, ignore_primer_regions=False)
Removes duplicate sequences from a list of Pair objects. If a Pair has heavy and light chains, both chains must identically match heavy and light chains from another Pair to be considered a duplicate. If a Pair has only a single chain, identical matches to that chain will cause the single chain Pair to be ...
3.305253
1.713462
1.928991
''' Completes the 5' end of a a truncated sequence with germline nucleotides. Input is a MongoDB dict (seq) and the species. ''' vgerm = germlines.get_germline(seq['v_gene']['full'], species) aln = global_alignment(seq['vdj_nt'], vgerm) prepend = '' for s,...
def _refine_v(seq, species)
Completes the 5' end of a a truncated sequence with germline nucleotides. Input is a MongoDB dict (seq) and the species.
6.531277
3.17457
2.057373
''' Completes the 3' end of a a truncated sequence with germline nucleotides. Input is a MongoDB dict (seq) and the species. ''' jgerm = germlines.get_germline(seq['j_gene']['full'], species) aln = global_alignment(seq['vdj_nt'], jgerm) append = '' for s, ...
def _refine_j(seq, species)
Completes the 3' end of a a truncated sequence with germline nucleotides. Input is a MongoDB dict (seq) and the species.
6.507836
3.301504
1.971173
''' Retranslates a nucleotide sequence following refinement. Input is a Pair sequence (basically a dict of MongoDB output). ''' if len(seq['vdj_nt']) % 3 != 0: trunc = len(seq['vdj_nt']) % 3 seq['vdj_nt'] = seq['vdj_nt'][:-trunc] seq['vdj_aa'] = Se...
def _retranslate(seq)
Retranslates a nucleotide sequence following refinement. Input is a Pair sequence (basically a dict of MongoDB output).
5.569981
2.191696
2.541403
''' Returns the sequence pair as a fasta string. If the Pair object contains both heavy and light chain sequences, both will be returned as a single string. By default, the fasta string contains the 'vdj_nt' sequence for each chain. To change, use the <key> option to select an a...
def fasta(self, key='vdj_nt', append_chain=True)
Returns the sequence pair as a fasta string. If the Pair object contains both heavy and light chain sequences, both will be returned as a single string. By default, the fasta string contains the 'vdj_nt' sequence for each chain. To change, use the <key> option to select an alternate sequence. ...
4.905464
1.581998
3.100803
''' Generates a matplotlib colormap from a single color. Colormap will be built, by default, from white to ``color``. Args: color: Can be one of several things: 1. Hex code 2. HTML color name 3. RGB tuple dark (bool): If ``True``, colormap will be...
def cmap_from_color(color, dark=False)
Generates a matplotlib colormap from a single color. Colormap will be built, by default, from white to ``color``. Args: color: Can be one of several things: 1. Hex code 2. HTML color name 3. RGB tuple dark (bool): If ``True``, colormap will be built from ...
3.874916
1.448764
2.674635