_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
31
13.1k
language
stringclasses
1 value
meta_information
dict
q273900
cli_encrypt
test
def cli_encrypt(context, key): """ Encrypts context.io_manager's stdin and sends that to context.io_manager's stdout. This can be useful to encrypt to disk before attempting to upload, allowing uploads retries and segmented encrypted objects.
python
{ "resource": "" }
q273901
get_status
test
def get_status(app, repo_config, repo_name, sha): """Gets the status of a commit. .. note:: ``repo_name`` might not ever be anything other than ``repo_config['github_repo']``. :param app: Flask app for leeroy :param repo_config: configuration for the repo :param repo_name: The name of the owner/repo :param sha: SHA for the status we are looking for :return: returns json response of status """ url =
python
{ "resource": "" }
q273902
get_pull_request
test
def get_pull_request(app, repo_config, pull_request): """Data for a given pull request. :param app: Flask app :param repo_config: dict with ``github_repo`` key :param pull_request: the pull request
python
{ "resource": "" }
q273903
get_pull_requests
test
def get_pull_requests(app, repo_config): """Last 30 pull requests from a repository. :param app: Flask app :param repo_config: dict with ``github_repo`` key :returns: id for
python
{ "resource": "" }
q273904
Migration.forwards
test
def forwards(self, orm): "Write your forwards methods here." # Note: Remember to use orm['appname.ModelName'] rather
python
{ "resource": "" }
q273905
get_slider_items
test
def get_slider_items(context, amount=None): """Returns the published slider items.""" req
python
{ "resource": "" }
q273906
render_hero_slider
test
def render_hero_slider(context): """ Renders the hero slider. """ req =
python
{ "resource": "" }
q273907
RWLock.reader_acquire
test
def reader_acquire(self): """Acquire the lock to read""" self._order_mutex.acquire() self._readers_mutex.acquire()
python
{ "resource": "" }
q273908
RWLock.reader_release
test
def reader_release(self): """Release the lock after reading""" self._readers_mutex.acquire() self._readers -= 1
python
{ "resource": "" }
q273909
RWLock.writer_acquire
test
def writer_acquire(self): """Acquire the lock to write""" self._order_mutex.acquire()
python
{ "resource": "" }
q273910
TaskRegistry.add
test
def add(self, task_id, backend, category, backend_args, archiving_cfg=None, scheduling_cfg=None): """Add a task to the registry. This method adds task using `task_id` as identifier. If a task with the same identifier already exists on the registry, a `AlreadyExistsError` exception will be raised. :param task_id: identifier of the task to add :param backend: backend used to fetch data from the repository :param category: category of the items to fetch :param backend_args: dictionary of arguments required to run the backend :param archiving_cfg: archiving config for the task, if needed :param scheduling_cfg: scheduling config for the task, if needed :returns: the new task added to the registry :raises AlreadyExistsError: raised when the given task identifier
python
{ "resource": "" }
q273911
TaskRegistry.remove
test
def remove(self, task_id): """Remove a task from the registry. To remove it, pass its identifier with `taks_id` parameter. When the identifier is not found, a `NotFoundError` exception is raised. :param task_id: identifier of the task to remove :raises NotFoundError: raised when the given task identifier is not found on the registry """ try: self._rwlock.writer_acquire()
python
{ "resource": "" }
q273912
TaskRegistry.get
test
def get(self, task_id): """Get a task from the registry. Retrieve a task from the registry using its task identifier. When the task does not exist, a `NotFoundError` exception will be raised. :param task_id: task identifier :returns: a task object :raises NotFoundError: raised when the requested task is not found on the registry """ try:
python
{ "resource": "" }
q273913
TaskRegistry.tasks
test
def tasks(self): """Get the list of tasks""" self._rwlock.reader_acquire() tl = [v for v in self._tasks.values()]
python
{ "resource": "" }
q273914
_TaskConfig.to_dict
test
def to_dict(self): """Returns a dict with the representation of this task configuration object.""" properties = find_class_properties(self.__class__) config = {
python
{ "resource": "" }
q273915
_TaskConfig.from_dict
test
def from_dict(cls, config): """Create an configuration object from a dictionary. Key,value pairs will be used to initialize a task configuration object. If 'config' contains invalid configuration parameters a `ValueError` exception will be raised. :param config: dictionary used to create an instance of this object :returns: a task config instance :raises ValueError: when an invalid configuration parameter is found """ try: obj = cls(**config)
python
{ "resource": "" }
q273916
execute_perceval_job
test
def execute_perceval_job(backend, backend_args, qitems, task_id, category, archive_args=None, max_retries=MAX_JOB_RETRIES): """Execute a Perceval job on RQ. The items fetched during the process will be stored in a Redis queue named `queue`. Setting the parameter `archive_path`, raw data will be stored with the archive manager. The contents from the archive can be retrieved setting the pameter `fetch_from_archive` to `True`, too. Take into account this behaviour will be only available when the backend supports the use of the archive. If archiving is not supported, an `AttributeError` exception will be raised. :param backend: backend to execute :param bakend_args: dict of arguments for running the backend :param qitems: name of the RQ queue used to store the items :param task_id: identifier of the task linked to this job :param category: category of the items to retrieve :param archive_args: archive arguments :param max_retries: maximum number of attempts this job can execute before failing :returns: a `JobResult` instance :raises NotFoundError: raised when the backend is not found :raises AttributeError: raised when archiving is not supported but any of the archive parameters were set """ rq_job = rq.get_current_job() job = PercevalJob(rq_job.id, task_id, backend, category, rq_job.connection, qitems) logger.debug("Running job #%s (task: %s) (%s) (cat:%s)", job.job_id, task_id, backend, category) if not job.has_archiving() and archive_args: raise AttributeError("archive attributes set but archive
python
{ "resource": "" }
q273917
PercevalJob.initialize_archive_manager
test
def initialize_archive_manager(self, archive_path): """Initialize the archive manager. :param archive_path: path where the archive manager is located """ if archive_path == "": raise
python
{ "resource": "" }
q273918
PercevalJob.run
test
def run(self, backend_args, archive_args=None, resume=False): """Run the backend with the given parameters. The method will run the backend assigned to this job, storing the fetched items in a Redis queue. The ongoing status of the job, can be accessed through the property `result`. When `resume` is set, the job will start from the last execution, overwriting 'from_date' and 'offset' parameters, if needed. Setting to `True` the parameter `fetch_from_archive`, items can be fetched from the archive assigned to this job. Any exception during the execution of the process will be raised. :param backend_args: parameters used to un the backend :param archive_args: archive arguments :param resume: fetch items starting where the last execution stopped """ args = backend_args.copy() if archive_args: self.initialize_archive_manager(archive_args['archive_path']) if not resume: max_date = backend_args.get('from_date', None) offset = backend_args.get('offset', None) if max_date: max_date = datetime_to_utc(max_date).timestamp() self._result = JobResult(self.job_id, self.task_id, self.backend, self.category,
python
{ "resource": "" }
q273919
PercevalJob._execute
test
def _execute(self, backend_args, archive_args): """Execute a backend of Perceval. Run the backend of Perceval assigned to this job using the given arguments. It will raise an `AttributeError` when any of the required parameters to run the backend are not found. Other exceptions related to the execution of the backend will be raised too. This method will return an iterator of the items fetched by the backend. These items will include some metadata related to this job. It will also be possible to retrieve the items from the archive setting to `True` the parameter `fetch_from_archive`. :param backend_args: arguments to execute the backend :param archive_args: archive arguments :returns: iterator of items fetched by the backend
python
{ "resource": "" }
q273920
ElasticItemsWriter.create_index
test
def create_index(idx_url, clean=False): """Configure the index to work with""" try: r = requests.get(idx_url) except requests.exceptions.ConnectionError: cause = "Error connecting to Elastic Search (index: %s)" % idx_url raise ElasticSearchError(cause=cause) if r.status_code != 200: # The index does not exist r = requests.put(idx_url) if r.status_code != 200: logger.info("Can't create index %s (%s)", idx_url, r.status_code) cause = "Error creating Elastic Search index
python
{ "resource": "" }
q273921
ElasticItemsWriter.create_mapping
test
def create_mapping(idx_url, mapping): """Create a mapping""" mapping_url = idx_url + '/items/_mapping' mapping = json.dumps(mapping) try: r = requests.put(mapping_url, data=mapping, headers={'Content-Type': 'application/json'}) except requests.exceptions.ConnectionError: cause = "Error connecting to Elastic Search (index: %s, url: %s)" \ % (idx_url, mapping_url) raise ElasticSearchError(cause=cause) if r.status_code != 200: reason = r.json()['error']
python
{ "resource": "" }
q273922
json_encoder
test
def json_encoder(*args, **kwargs): """Custom JSON encoder handler""" obj = cherrypy.serving.request._json_inner_handler(*args,
python
{ "resource": "" }
q273923
ArthurServer.write_items
test
def write_items(cls, writer, items_generator): """Write items to the queue :param writer: the writer object
python
{ "resource": "" }
q273924
Arthur.add_task
test
def add_task(self, task_id, backend, category, backend_args, archive_args=None, sched_args=None): """Add and schedule a task. :param task_id: id of the task :param backend: name of the backend :param category: category of the items to fecth :param backend_args: args needed to initialize the backend :param archive_args: args needed to initialize the archive :param sched_args: scheduling args for this task :returns: the task created """ try: archiving_cfg = self.__parse_archive_args(archive_args) scheduling_cfg = self.__parse_schedule_args(sched_args)
python
{ "resource": "" }
q273925
Arthur.remove_task
test
def remove_task(self, task_id): """Remove and cancel a task. :param task_id: id of the task to be removed """ try: self._scheduler.cancel_task(task_id) except NotFoundError as e:
python
{ "resource": "" }
q273926
Arthur.items
test
def items(self): """Get the items fetched by the jobs.""" # Get and remove queued items in an atomic transaction pipe = self.conn.pipeline() pipe.lrange(Q_STORAGE_ITEMS, 0, -1)
python
{ "resource": "" }
q273927
Arthur.__validate_args
test
def __validate_args(task_id, backend, category, backend_args): """Check that the task arguments received are valid""" if not task_id or task_id.strip() == "": msg = "Missing task_id for task" raise ValueError(msg) if not backend or backend.strip() == "":
python
{ "resource": "" }
q273928
Arthur.__parse_archive_args
test
def __parse_archive_args(self, archive_args): """Parse the archive arguments of a task""" if not archive_args: return None archiving_args = copy.deepcopy(archive_args) if self.archive_path: archiving_args['archive_path'] = self.archive_path else:
python
{ "resource": "" }
q273929
ArthurWorker.perform_job
test
def perform_job(self, job, queue): """Custom method to execute a job and notify of its result :param job: Job object :param queue: the queue containing the object """ result = super().perform_job(job, queue)
python
{ "resource": "" }
q273930
_JobScheduler.schedule_job_task
test
def schedule_job_task(self, queue_id, task_id, job_args, delay=0): """Schedule a job in the given queue.""" self._rwlock.writer_acquire() job_id = self._generate_job_id(task_id) event = self._scheduler.enter(delay, 1, self._enqueue_job,
python
{ "resource": "" }
q273931
_JobScheduler.cancel_job_task
test
def cancel_job_task(self, task_id): """Cancel the job related to the given task.""" try: self._rwlock.writer_acquire() job_id = self._tasks.get(task_id, None) if job_id: self._cancel_job(job_id)
python
{ "resource": "" }
q273932
_JobListener.run
test
def run(self): """Run thread to listen for jobs and reschedule successful ones.""" try: self.listen() except Exception as e:
python
{ "resource": "" }
q273933
_JobListener.listen
test
def listen(self): """Listen for completed jobs and reschedule successful ones.""" pubsub = self.conn.pubsub() pubsub.subscribe(self.pubsub_channel) logger.debug("Listening on channel %s", self.pubsub_channel) for msg in pubsub.listen(): logger.debug("New message received of type %s", str(msg['type'])) if msg['type'] != 'message': logger.debug("Ignoring job message") continue data = pickle.loads(msg['data']) job_id = data['job_id'] job = rq.job.Job.fetch(job_id, connection=self.conn)
python
{ "resource": "" }
q273934
Scheduler.schedule
test
def schedule(self): """Start scheduling jobs.""" if self.async_mode: self._scheduler.start()
python
{ "resource": "" }
q273935
Scheduler.schedule_task
test
def schedule_task(self, task_id): """Schedule a task. :param task_id: identifier of the task to schedule :raises NotFoundError: raised when the requested task is not found in the registry """ task = self.registry.get(task_id) job_args = self._build_job_arguments(task) archiving_cfg = task.archiving_cfg fetch_from_archive = False if not archiving_cfg else archiving_cfg.fetch_from_archive # Schedule the job as soon as possible
python
{ "resource": "" }
q273936
Scheduler.cancel_task
test
def cancel_task(self, task_id): """Cancel or 'un-schedule' a task. :param task_id: identifier of the task to cancel :raises NotFoundError: raised when the requested task is not found in the registry """
python
{ "resource": "" }
q273937
Scheduler._handle_successful_job
test
def _handle_successful_job(self, job): """Handle successufl jobs""" result = job.result task_id = job.kwargs['task_id'] try: task = self.registry.get(task_id) except NotFoundError: logger.warning("Task %s not found; related job #%s will not be rescheduled", task_id, job.id) return if task.archiving_cfg and task.archiving_cfg.fetch_from_archive: logger.info("Job #%s (task: %s) successfully finished", job.id, task_id) return if result.nitems > 0: task.backend_args['next_from_date'] = unixtime_to_datetime(result.max_date) if result.offset:
python
{ "resource": "" }
q273938
Scheduler._handle_failed_job
test
def _handle_failed_job(self, job): """Handle failed jobs""" task_id = job.kwargs['task_id']
python
{ "resource": "" }
q273939
Scheduler._build_job_arguments
test
def _build_job_arguments(task): """Build the set of arguments required for running a job""" job_args = {} job_args['qitems'] = Q_STORAGE_ITEMS job_args['task_id'] = task.task_id # Backend parameters job_args['backend'] = task.backend backend_args = copy.deepcopy(task.backend_args) if 'next_from_date' in backend_args: backend_args['from_date'] = backend_args.pop('next_from_date') if 'next_offset' in backend_args: backend_args['offset'] = backend_args.pop('next_offset') job_args['backend_args'] = backend_args # Category job_args['category'] = task.category
python
{ "resource": "" }
q273940
get_secret
test
def get_secret(secret_name, default=None): """ Gets contents of secret file :param secret_name: The name of the secret present in BANANAS_SECRETS_DIR :param default: Default value to return if no secret
python
{ "resource": "" }
q273941
register
test
def register(view): # Type[BananasAPI] """ Register the API view class in the bananas router. :param BananasAPI view: """ meta = view.get_admin_meta()
python
{ "resource": "" }
q273942
register
test
def register(view=None, *, admin_site=None, admin_class=ModelAdminView): """ Register a generic class based view wrapped with ModelAdmin and fake model :param view: The AdminView to register. :param admin_site: The AdminSite to register the view on. Defaults to bananas.admin.ExtendedAdminSite. :param admin_class: The ModelAdmin class to use for eg. permissions. Defaults to bananas.admin.ModelAdminView. Example: @register # Or with args @register(admin_class=MyModelAdminSubclass) class MyAdminView(bananas.admin.AdminView): def get(self, request): return self.render('template.html', {}) # Also possible: register(MyAdminView, admin_class=MyModelAdminSublass) """ if not admin_site: admin_site = site def wrapped(inner_view): module = inner_view.__module__ app_label = re.search(r"\.?(\w+)\.admin", module).group(1) app_config = apps.get_app_config(app_label) label = getattr(inner_view, "label", None) if not label: label = re.sub("(Admin)|(View)", "", inner_view.__name__).lower() inner_view.label = label model_name = label.capitalize() verbose_name = getattr(inner_view, "verbose_name", model_name) inner_view.verbose_name = verbose_name access_perm_codename = "can_access_" + model_name.lower() access_perm_name = _("Can access {verbose_name}").format( verbose_name=verbose_name ) # The first permission here is expected to be # the general access permission.
python
{ "resource": "" }
q273943
BananasAPI.reverse_action
test
def reverse_action(self, url_name, *args, **kwargs): """ Extended DRF with fallback to requested namespace if request.version is missing """ if self.request and not self.request.version: return
python
{ "resource": "" }
q273944
BananasAPI.get_view_name
test
def get_view_name(self, respect_name=True): """ Get or generate human readable view name. Extended version from DRF to support usage from both class and instance. """ if isinstance(self, type): view = self else: view = self.__class__ # Name may be set by some Views, such as a ViewSet. if respect_name: name = getattr(view, "name", None) if name is not None: return name name
python
{ "resource": "" }
q273945
get_version
test
def get_version(version=None): """Derives a PEP386-compliant version number from VERSION.""" if version is None: version = VERSION assert len(version) == 5 assert version[3] in ("alpha", "beta", "rc", "final") # Now build the two parts of the version number: # main = X.Y[.Z] # sub = .devN - for pre-alpha releases # | {a|b|c}N - for alpha,
python
{ "resource": "" }
q273946
resolve
test
def resolve(cursor, key): """ Get engine or raise exception, resolves Alias-instances to a sibling target. :param cursor: The object so search in :param key: The key to get :return: The object found """ try: result = cursor[key]
python
{ "resource": "" }
q273947
get_engine
test
def get_engine(scheme): """ Perform a lookup in _ENGINE_MAPPING using engine_string. :param scheme: '+'-separated string Maximum of 2 parts, i.e "postgres+psycopg" is OK, "postgres+psycopg2+postgis" is NOT OK. :return: Engine string """ path = scheme.split("+") first, rest = path[0], path[1:] second = rest[0] if rest else None engine = resolve(ENGINE_MAPPING, first) # If the selected engine does not have a second level. if not isinstance(engine, list):
python
{ "resource": "" }
q273948
parse_path
test
def parse_path(path): """ Get database name and database schema from path. :param path: "/"-delimited path, parsed as "/<database name>/<database schema>" :return: tuple with (database or None, schema or None) """ if path is None: raise ValueError("path must be a string")
python
{ "resource": "" }
q273949
database_conf_from_url
test
def database_conf_from_url(url): """ Return a django-style database configuration based on ``url``. :param url: Database URL :return: Django-style database configuration dict Example: >>> conf = database_conf_from_url( ... 'pgsql://joar:hunter2@5monkeys.se:4242/tweets/tweetschema' ... '?hello=world') >>> sorted(conf.items()) # doctest: +NORMALIZE_WHITESPACE [('ENGINE', 'django.db.backends.postgresql_psycopg2'), ('HOST', '5monkeys.se'),
python
{ "resource": "" }
q273950
parse_database_url
test
def parse_database_url(url): """ Parse a database URL and return a DatabaseInfo named tuple. :param url: Database URL :return: DatabaseInfo instance Example: >>> conf = parse_database_url( ... 'pgsql://joar:hunter2@5monkeys.se:4242/tweets/tweetschema' ... '?hello=world') >>> conf # doctest: +NORMALIZE_WHITESPACE DatabaseInfo(engine='django.db.backends.postgresql_psycopg2', name='tweets', schema='tweetschema', user='joar', password='hunter2', host='5monkeys.se',
python
{ "resource": "" }
q273951
LoginAPI.create
test
def create(self, request): """ Log in django staff user """ # TODO: Decorate api with sensitive post parameters as Django admin do? # from django.utils.decorators import method_decorator # from django.views.decorators.debug import sensitive_post_parameters # sensitive_post_parameters_m = method_decorator(sensitive_post_parameters()) login_form = AuthenticationForm(request, data=request.data) if not
python
{ "resource": "" }
q273952
MeAPI.list
test
def list(self, request): """ Retrieve logged in user info """
python
{ "resource": "" }
q273953
ChangePasswordAPI.create
test
def create(self, request): """ Change password for logged in django staff user """ # TODO: Decorate api with sensitive post parameters as Django admin do? password_form = PasswordChangeForm(request.user, data=request.data) if not password_form.is_valid():
python
{ "resource": "" }
q273954
UserDetailsSerializer.build_url_field
test
def build_url_field(self, field_name, model_class): """ This is needed due to DRF's model serializer uses the queryset to build url name # TODO: Move this to own serializer mixin or fix problem elsewhere? """
python
{ "resource": "" }
q273955
parse_bool
test
def parse_bool(value): """ Parse string to bool. :param str value: String value to parse as bool :return bool: """ boolean = parse_str(value).capitalize()
python
{ "resource": "" }
q273956
parse_int
test
def parse_int(value): """ Parse numeric string to int. Supports oct formatted string. :param str value: String value to parse as int :return int: """
python
{ "resource": "" }
q273957
get_parser
test
def get_parser(typ): """ Return appropriate parser for given type. :param typ: Type to get parser for. :return function: Parser """ try: return {
python
{ "resource": "" }
q273958
get_settings
test
def get_settings(): """ Get and parse prefixed django settings from env. TODO: Implement support for complex settings DATABASES = {} CACHES = {} INSTALLED_APPS -> EXCLUDE_APPS ? :return dict: """ settings = {} prefix = environ.get("DJANGO_SETTINGS_PREFIX", "DJANGO_") for key, value in environ.items(): _, _, key = key.partition(prefix) if key: if key in UNSUPPORTED_ENV_SETTINGS: raise ValueError(
python
{ "resource": "" }
q273959
ModelDict.from_model
test
def from_model(cls, model, *fields, **named_fields): """ Work-in-progress constructor, consuming fields and values from django model instance. """ d = ModelDict() if not (fields or named_fields): # Default to all fields fields = [f.attname for f in model._meta.concrete_fields] not_found = object() for name, field in chain(zip(fields, fields), named_fields.items()): _fields = field.split("__") value = model for i, _field in enumerate(_fields, start=1): # NOTE: we don't want to rely on hasattr here previous_value = value value = getattr(previous_value, _field, not_found) if value is not_found: if _field in dir(previous_value): raise ValueError( "{!r}.{} had
python
{ "resource": "" }
q273960
URLSecretField.y64_encode
test
def y64_encode(s): """ Implementation of Y64 non-standard URL-safe base64 variant. See http://en.wikipedia.org/wiki/Base64#Variants_summary_table :return: base64-encoded result with substituted ``{"+", "/", "="} => {".", "_", "-"}``.
python
{ "resource": "" }
q273961
create_field
test
def create_field(field_info): """ Create a field by field info dict. """ field_type = field_info.get('type') if field_type not in FIELDS_NAME_MAP: raise ValueError(_('not support this field: {}').format(field_type))
python
{ "resource": "" }
q273962
create_validator
test
def create_validator(data_struct_dict, name=None): """ create a Validator instance from data_struct_dict :param data_struct_dict: a dict describe validator's fields, like the dict `to_dict()` method returned. :param name: name of Validator class :return: Validator instance """ if name is None: name = 'FromDictValidator' attrs = {} for field_name, field_info in six.iteritems(data_struct_dict):
python
{ "resource": "" }
q273963
cartesian_product
test
def cartesian_product(parameter_dict, combined_parameters=()): """ Generates a Cartesian product of the input parameter dictionary. For example: >>> print cartesian_product({'param1':[1,2,3], 'param2':[42.0, 52.5]}) {'param1':[1,1,2,2,3,3],'param2': [42.0,52.5,42.0,52.5,42.0,52.5]} :param parameter_dict: Dictionary containing parameter names as keys and iterables of data to explore. :param combined_parameters: Tuple of tuples. Defines the order of the parameters and parameters that are linked together. If an inner tuple contains only a single item, you can spare the inner tuple brackets. For example: >>> print cartesian_product( {'param1': [42.0, 52.5], 'param2':['a', 'b'], 'param3' : [1,2,3]}, ('param3',('param1', 'param2'))) {param3':[1,1,2,2,3,3],'param1' : [42.0,52.5,42.0,52.5,42.0,52.5], 'param2':['a','b','a','b','a','b']} :returns: Dictionary with cartesian product lists. """ if not combined_parameters: combined_parameters = list(parameter_dict) else: combined_parameters = list(combined_parameters)
python
{ "resource": "" }
q273964
find_unique_points
test
def find_unique_points(explored_parameters): """Takes a list of explored parameters and finds unique parameter combinations. If parameter ranges are hashable operates in O(N), otherwise O(N**2). :param explored_parameters: List of **explored** parameters :return: List of tuples, first entry being the parameter values, second entry a list containing the run position of the unique combination. """ ranges = [param.f_get_range(copy=False) for param in explored_parameters] zipped_tuples = list(zip(*ranges)) try: unique_elements = OrderedDict() for idx, val_tuple in enumerate(zipped_tuples): if val_tuple not in unique_elements: unique_elements[val_tuple] = [] unique_elements[val_tuple].append(idx) return list(unique_elements.items()) except TypeError: logger = logging.getLogger('pypet.find_unique') logger.error('Your parameter entries could not be hashed, ' 'now I am sorting slowly in O(N**2).') unique_elements = [] for idx, val_tuple in enumerate(zipped_tuples):
python
{ "resource": "" }
q273965
_change_logging_kwargs
test
def _change_logging_kwargs(kwargs): """ Helper function to turn the simple logging kwargs into a `log_config`.""" log_levels = kwargs.pop('log_level', None) log_folder = kwargs.pop('log_folder', 'logs') logger_names = kwargs.pop('logger_names', '') if log_levels is None: log_levels = kwargs.pop('log_levels', logging.INFO) log_multiproc = kwargs.pop('log_multiproc', True) if not isinstance(logger_names, (tuple, list)): logger_names = [logger_names] if not isinstance(log_levels, (tuple, list)): log_levels = [log_levels] if len(log_levels) == 1: log_levels = [log_levels[0] for _ in logger_names] # We don't want to manipulate the original dictionary dictionary = copy.deepcopy(LOGGING_DICT) prefixes = [''] if not log_multiproc: for key in list(dictionary.keys()): if key.startswith('multiproc_'): del dictionary[key] else: prefixes.append('multiproc_') # Add all handlers to all loggers for prefix in prefixes: for handler_dict in dictionary[prefix + 'handlers'].values(): if 'filename' in handler_dict:
python
{ "resource": "" }
q273966
simple_logging_config
test
def simple_logging_config(func): """Decorator to allow a simple logging configuration. This encompasses giving a `log_folder`, `logger_names` as well as `log_levels`. """ @functools.wraps(func) def new_func(self, *args, **kwargs): if use_simple_logging(kwargs): if 'log_config' in kwargs: raise ValueError('Please do not specify `log_config` ' 'if you want to use the simple '
python
{ "resource": "" }
q273967
try_make_dirs
test
def try_make_dirs(filename): """ Tries to make directories for a given `filename`. Ignores any error but notifies via stderr. """ try: dirname = os.path.dirname(os.path.normpath(filename)) racedirs(dirname) except Exception as exc:
python
{ "resource": "" }
q273968
get_strings
test
def get_strings(args): """Returns all valid python strings inside a given argument string.""" string_list = [] for elem in ast.walk(ast.parse(args)):
python
{ "resource": "" }
q273969
rename_log_file
test
def rename_log_file(filename, trajectory=None, env_name=None, traj_name=None, set_name=None, run_name=None, process_name=None, host_name=None): """ Renames a given `filename` with valid wildcard placements. :const:`~pypet.pypetconstants.LOG_ENV` ($env) is replaces by the name of the trajectory`s environment. :const:`~pypet.pypetconstants.LOG_TRAJ` ($traj) is replaced by the name of the trajectory. :const:`~pypet.pypetconstants.LOG_RUN` ($run) is replaced by the name of the current run. If the trajectory is not set to a run 'run_ALL' is used. :const:`~pypet.pypetconstants.LOG_SET` ($set) is replaced by the name of the current run set. If the trajectory is not set to a run 'run_set_ALL' is used. :const:`~pypet.pypetconstants.LOG_PROC` ($proc) is replaced by the name fo the current process. :const:`~pypet.pypetconstant.LOG_HOST` ($host) is replaced by the name of the current host. :param filename: A filename string :param traj: A trajectory container, leave `None` if you provide all the parameters below :param env_name: Name of environemnt, leave `None` to get it from `traj` :param traj_name: Name of trajectory, leave `None` to get it from `traj` :param set_name: Name of run set, leave `None` to get it from `traj` :param run_name: Name of run, leave `None` to get it from `traj` :param process_name: The name of the desired process. If `None` the name of the current process is taken determined by the multiprocessing module. :param host_name: Name of host, leave `None` to determine it automatically with the platform module. :return: The new filename
python
{ "resource": "" }
q273970
HasLogger._set_logger
test
def _set_logger(self, name=None): """Adds a logger with a given `name`. If no name is given, name is constructed as `type(self).__name__`. """ if name is None:
python
{ "resource": "" }
q273971
LoggingManager.extract_replacements
test
def extract_replacements(self, trajectory): """Extracts the wildcards and file replacements from the `trajectory`""" self.env_name = trajectory.v_environment_name self.traj_name = trajectory.v_name
python
{ "resource": "" }
q273972
LoggingManager.show_progress
test
def show_progress(self, n, total_runs): """Displays a progressbar""" if self.report_progress: percentage, logger_name, log_level = self.report_progress if logger_name == 'print': logger = 'print' else: logger = logging.getLogger(logger_name) if n == -1: # Compute the number of digits and avoid log10(0) digits = int(math.log10(total_runs + 0.1)) + 1 self._format_string = 'PROGRESS: Finished %' + '%d' % digits
python
{ "resource": "" }
q273973
LoggingManager._check_and_replace_parser_args
test
def _check_and_replace_parser_args(parser, section, option, rename_func, make_dirs=True): """ Searches for parser settings that define filenames. If such settings are found, they are renamed according to the wildcard rules. Moreover, it is also tried to create the corresponding folders. :param parser: A config parser :param section: A config section :param option: The section option :param rename_func: A function to rename found files :param make_dirs: If the directories of the file should be created. """ args = parser.get(section, option, raw=True) strings = get_strings(args) replace = False for string in strings: isfilename = any(x in string for x in FILENAME_INDICATORS) if isfilename: newstring = rename_func(string) if make_dirs:
python
{ "resource": "" }
q273974
LoggingManager._parser_to_string_io
test
def _parser_to_string_io(parser): """Turns a ConfigParser into a StringIO stream.""" memory_file = StringIO() parser.write(memory_file)
python
{ "resource": "" }
q273975
LoggingManager._find_multiproc_options
test
def _find_multiproc_options(parser): """ Searches for multiprocessing options within a ConfigParser. If such options are found, they are copied (without the `'multiproc_'` prefix) into a new parser. """ sections = parser.sections() if not any(section.startswith('multiproc_') for section in sections): return None mp_parser = NoInterpolationParser() for section in sections: if section.startswith('multiproc_'): new_section = section.replace('multiproc_', '')
python
{ "resource": "" }
q273976
LoggingManager._find_multiproc_dict
test
def _find_multiproc_dict(dictionary): """ Searches for multiprocessing options in a given `dictionary`. If found they are copied (without the `'multiproc_'` prefix) into a new dictionary """ if not any(key.startswith('multiproc_') for key in dictionary.keys()): return None mp_dictionary = {} for key in dictionary.keys(): if key.startswith('multiproc_'): new_key = key.replace('multiproc_', '')
python
{ "resource": "" }
q273977
LoggingManager.check_log_config
test
def check_log_config(self): """ Checks and converts all settings if necessary passed to the Manager. Searches for multiprocessing options as well. """ if self.report_progress: if self.report_progress is True: self.report_progress = (5, 'pypet', logging.INFO) elif isinstance(self.report_progress, (int, float)): self.report_progress = (self.report_progress, 'pypet', logging.INFO) elif isinstance(self.report_progress, str): self.report_progress = (5, self.report_progress, logging.INFO) elif len(self.report_progress) == 2: self.report_progress = (self.report_progress[0], self.report_progress[1], logging.INFO) if self.log_config: if self.log_config == pypetconstants.DEFAULT_LOGGING: pypet_path = os.path.abspath(os.path.dirname(__file__)) init_path = os.path.join(pypet_path, 'logging')
python
{ "resource": "" }
q273978
LoggingManager._handle_config_parsing
test
def _handle_config_parsing(self, log_config): """ Checks for filenames within a config file and translates them. Moreover, directories for the files are created as well. :param log_config: Config file as a stream (like StringIO) """ parser = NoInterpolationParser() parser.readfp(log_config) rename_func = lambda string: rename_log_file(string, env_name=self.env_name, traj_name=self.traj_name, set_name=self.set_name,
python
{ "resource": "" }
q273979
LoggingManager._handle_dict_config
test
def _handle_dict_config(self, log_config): """Recursively walks and copies the `log_config` dict and searches for filenames. Translates filenames and creates directories if necessary. """ new_dict = dict() for key in log_config.keys(): if key == 'filename': filename = log_config[key] filename = rename_log_file(filename, env_name=self.env_name, traj_name=self.traj_name, set_name=self.set_name,
python
{ "resource": "" }
q273980
LoggingManager.make_logging_handlers_and_tools
test
def make_logging_handlers_and_tools(self, multiproc=False): """Creates logging handlers and redirects stdout.""" log_stdout = self.log_stdout if sys.stdout is self._stdout_to_logger: # If we already redirected stdout we don't neet to redo it again log_stdout = False if self.log_config: if multiproc: proc_log_config = self._mp_config else: proc_log_config = self._sp_config
python
{ "resource": "" }
q273981
LoggingManager.finalize
test
def finalize(self, remove_all_handlers=True): """Finalizes the manager, closes and removes all handlers if desired.""" for tool in self._tools: tool.finalize() self._tools = [] self._stdout_to_logger = None for config in (self._sp_config, self._mp_config):
python
{ "resource": "" }
q273982
StdoutToLogger.start
test
def start(self): """Starts redirection of `stdout`""" if sys.stdout is not self: self._original_steam = sys.stdout
python
{ "resource": "" }
q273983
StdoutToLogger.write
test
def write(self, buf): """Writes data from buffer to logger""" if not self._recursion: self._recursion = True try: for line in buf.rstrip().splitlines():
python
{ "resource": "" }
q273984
results_equal
test
def results_equal(a, b): """Compares two result instances Checks full name and all data. Does not consider the comment. :return: True or False :raises: ValueError if both inputs are no result instances """ if a.v_is_parameter and b.v_is_parameter: raise ValueError('Both inputs are not results.') if a.v_is_parameter or b.v_is_parameter: return False if a.v_full_name != b.v_full_name: return False if hasattr(a, '_data') and not hasattr(b, '_data'): return False if hasattr(a, '_data'): akeyset = set(a._data.keys())
python
{ "resource": "" }
q273985
parameters_equal
test
def parameters_equal(a, b): """Compares two parameter instances Checks full name, data, and ranges. Does not consider the comment. :return: True or False :raises: ValueError if both inputs are no parameter instances """ if (not b.v_is_parameter and not a.v_is_parameter): raise ValueError('Both inputs are not parameters') if (not b.v_is_parameter or not a.v_is_parameter): return False if a.v_full_name != b.v_full_name: return False if a.f_is_empty() and b.f_is_empty(): return True if a.f_is_empty() != b.f_is_empty(): return False if not a._values_of_same_type(a.f_get(), b.f_get()): return False if
python
{ "resource": "" }
q273986
manual_run
test
def manual_run(turn_into_run=True, store_meta_data=True, clean_up=True): """Can be used to decorate a function as a manual run function. This can be helpful if you want the run functionality without using an environment. :param turn_into_run: If the trajectory should become a `single run` with more specialized functionality during a single run. :param store_meta_data: If meta-data like runtime should be automatically stored :param clean_up: If all data added during the single run should be removed, only works if ``turn_into_run=True``. """ def wrapper(func): @functools.wraps(func) def new_func(traj,
python
{ "resource": "" }
q273987
deprecated
test
def deprecated(msg=''): """This is a decorator which can be used to mark functions as deprecated. It will result in a warning being emitted when the function is used. :param msg: Additional message added to the warning. """ def wrapper(func): @functools.wraps(func) def new_func(*args, **kwargs): warning_string = "Call to deprecated function
python
{ "resource": "" }
q273988
kwargs_mutual_exclusive
test
def kwargs_mutual_exclusive(param1_name, param2_name, map2to1=None): """ If there exist mutually exclusive parameters checks for them and maps param2 to 1.""" def wrapper(func): @functools.wraps(func) def new_func(*args, **kwargs): if param2_name in kwargs: if param1_name in kwargs: raise ValueError('You cannot specify `%s` and `%s` at the same time, ' 'they are mutually exclusive.' % (param1_name, param2_name))
python
{ "resource": "" }
q273989
kwargs_api_change
test
def kwargs_api_change(old_name, new_name=None): """This is a decorator which can be used if a kwarg has changed its name over versions to also support the old argument name. Issues a warning if the old keyword argument is detected and converts call to new API. :param old_name: Old name of the keyword argument :param new_name: New name of keyword argument """ def wrapper(func): @functools.wraps(func) def new_func(*args, **kwargs): if old_name in kwargs: if new_name is None: warning_string = 'Using deprecated keyword argument `%s` in function `%s`. ' \ 'This keyword is no longer supported, please don`t use it ' \ 'anymore.' % (old_name, func.__name__) else:
python
{ "resource": "" }
q273990
retry
test
def retry(n, errors, wait=0.0, logger_name=None): """This is a decorator that retries a function. Tries `n` times and catches a given tuple of `errors`. If the `n` retries are not enough, the error is reraised. If desired `waits` some seconds. Optionally takes a 'logger_name' of a given logger to print the caught error. """ def wrapper(func): @functools.wraps(func) def new_func(*args, **kwargs): retries = 0 while True: try: result = func(*args, **kwargs) if retries and logger_name: logger = logging.getLogger(logger_name) logger.debug('Retry of `%s` successful' % func.__name__) return result except errors: if retries >= n: if logger_name: logger = logging.getLogger(logger_name) logger.exception('I could not execute `%s` with args %s and kwargs %s, ' 'starting next try. ' % (func.__name__, str(args),
python
{ "resource": "" }
q273991
prefix_naming
test
def prefix_naming(cls): """Decorate that adds the prefix naming scheme""" if hasattr(cls, '__getattr__'):
python
{ "resource": "" }
q273992
add_params
test
def add_params(traj): """Adds all necessary parameters to `traj`.""" # We set the BrianParameter to be the standard parameter traj.v_standard_parameter=Brian2Parameter traj.v_fast_access=True # Add parameters we need for our network traj.f_add_parameter('Net.C',281*pF) traj.f_add_parameter('Net.gL',30*nS) traj.f_add_parameter('Net.EL',-70.6*mV) traj.f_add_parameter('Net.VT',-50.4*mV)
python
{ "resource": "" }
q273993
run_net
test
def run_net(traj): """Creates and runs BRIAN network based on the parameters in `traj`.""" eqs=traj.eqs # Create a namespace dictionairy namespace = traj.Net.f_to_dict(short_names=True, fast_access=True) # Create the Neuron Group neuron=NeuronGroup(traj.N, model=eqs, threshold=traj.Vcut, reset=traj.reset, namespace=namespace) neuron.vm=traj.EL neuron.w=traj.a*(neuron.vm-traj.EL) neuron.Vr=linspace(-48.3*mV,-47.7*mV,traj.N) # bifurcation parameter # Run the network initially for 100 milliseconds print('Initial Run') net = Network(neuron) net.run(100*ms, report='text') # we discard the first spikes # Create a Spike Monitor MSpike=SpikeMonitor(neuron) net.add(MSpike) # Create a State Monitor for the membrane
python
{ "resource": "" }
q273994
euler_scheme
test
def euler_scheme(traj, diff_func): """Simulation function for Euler integration. :param traj: Container for parameters and results :param diff_func: The differential equation we want to integrate """ steps = traj.steps initial_conditions = traj.initial_conditions dimension = len(initial_conditions) # This array will collect the results result_array = np.zeros((steps,dimension)) # Get the function parameters stored into `traj` as a dictionary # with the (short) names as keys : func_params_dict = traj.func_params.f_to_dict(short_names=True, fast_access=True) # Take initial conditions as first result result_array[0] = initial_conditions # Now we compute the Euler Scheme steps-1 times for idx in range(1,steps):
python
{ "resource": "" }
q273995
add_parameters
test
def add_parameters(traj): """Adds all necessary parameters to the `traj` container""" traj.f_add_parameter('steps', 10000, comment='Number of time steps to simulate') traj.f_add_parameter('dt', 0.01, comment='Step size') # Here we want to add the initial conditions as an array parameter. We will simulate # a 3-D differential equation, the Lorenz attractor. traj.f_add_parameter(ArrayParameter,'initial_conditions', np.array([0.0,0.0,0.0]), comment = 'Our initial conditions, as default we will start from' ' origin!') # We will group all parameters
python
{ "resource": "" }
q273996
diff_lorenz
test
def diff_lorenz(value_array, sigma, beta, rho): """The Lorenz attractor differential equation :param value_array: 3d array containing the x,y, and z component values. :param sigma: Constant attractor parameter :param beta: FConstant attractor parameter :param rho: Constant attractor parameter :return: 3d array of the Lorenz system evaluated at `value_array` """ diff_array =
python
{ "resource": "" }
q273997
_create_storage
test
def _create_storage(storage_service, trajectory=None, **kwargs): """Creates a service from a constructor and checks which kwargs are not used""" kwargs_copy = kwargs.copy() kwargs_copy['trajectory'] =
python
{ "resource": "" }
q273998
storage_factory
test
def storage_factory(storage_service, trajectory=None, **kwargs): """Creates a storage service, to be extended if new storage services are added :param storage_service: Storage Service instance of constructor or a string pointing to a file :param trajectory: A trajectory instance :param kwargs: Arguments passed to the storage service :return: A storage service and a set of not used keyword arguments from kwargs """ if 'filename' in kwargs and storage_service is None: filename = kwargs['filename'] _, ext = os.path.splitext(filename) if ext in ('.hdf', '.h4', '.hdf4', '.he2', '.h5', '.hdf5', '.he5'): storage_service = HDF5StorageService else:
python
{ "resource": "" }
q273999
add_parameters
test
def add_parameters(traj): """Adds all necessary parameters to the `traj` container. You can choose between two parameter sets. One for the Lorenz attractor and one for the Roessler attractor. The former is chosen for `traj.diff_name=='diff_lorenz'`, the latter for `traj.diff_name=='diff_roessler'`. You can use parameter presetting to switch between the two cases. :raises: A ValueError if `traj.diff_name` is none of the above """ traj.f_add_parameter('steps', 10000, comment='Number of time steps to simulate') traj.f_add_parameter('dt', 0.01, comment='Step size') # Here we want to add the initial conditions as an array parameter, since we will simulate # a 3-D differential equation, that is the Roessler attractor # (https://en.wikipedia.org/wiki/R%C3%B6ssler_attractor)
python
{ "resource": "" }