_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
31
13.1k
language
stringclasses
1 value
meta_information
dict
q9800
StoredInstance.invalidate
train
def invalidate(self, callback=True): # type: (bool) -> bool """ Applies the component invalidation. :param callback: If True, call back the component before the invalidation :return: False if the component wasn't valid """ with self._lock: if self.state != StoredInstance.VALID: # Instance is not running... return False # Change the state self.state = StoredInstance.INVALID # Call the handlers self.__safe_handlers_callback("pre_invalidate") # Call the component if callback: # pylint: disable=W0212 self.__safe_validation_callback( constants.IPOPO_CALLBACK_INVALIDATE )
python
{ "resource": "" }
q9801
StoredInstance.validate
train
def validate(self, safe_callback=True): # type: (bool) -> bool """ Ends the component validation, registering services :param safe_callback: If True, calls the component validation callback :return: True if the component has been validated, else False :raise RuntimeError: You try to awake a dead component """ with self._lock: if self.state in ( StoredInstance.VALID, StoredInstance.VALIDATING, StoredInstance.ERRONEOUS, ): # No work to do (yet) return False if self.state == StoredInstance.KILLED: raise RuntimeError("{0}: Zombies !".format(self.name)) # Clear the error trace self.error_trace = None # Call the handlers self.__safe_handlers_callback("pre_validate")
python
{ "resource": "" }
q9802
StoredInstance.__callback
train
def __callback(self, event, *args, **kwargs): # type: (str, *Any, **Any) -> Any """ Calls the registered method in the component for the given event :param event: An event (IPOPO_CALLBACK_VALIDATE, ...) :return: The callback result, or None :raise Exception: Something went wrong """ comp_callback = self.context.get_callback(event) if not comp_callback: # No registered callback return True
python
{ "resource": "" }
q9803
StoredInstance.__field_callback
train
def __field_callback(self, field, event, *args, **kwargs): # type: (str, str, *Any, **Any) -> Any """ Calls the registered method in the component for the given field event :param field: A field name :param event: An event (IPOPO_CALLBACK_VALIDATE, ...) :return: The callback result, or None :raise Exception: Something went wrong """ # Get the field callback info cb_info = self.context.get_field_callback(field, event) if not cb_info: # No registered callback return True # Extract information
python
{ "resource": "" }
q9804
StoredInstance.safe_callback
train
def safe_callback(self, event, *args, **kwargs): # type: (str, *Any, **Any) -> Any """ Calls the registered method in the component for the given event, ignoring raised exceptions :param event: An event (IPOPO_CALLBACK_VALIDATE, ...) :return: The callback result, or None """ if self.state == StoredInstance.KILLED: # Invalid state return None try: return self.__callback(event, *args, **kwargs) except FrameworkException as ex: # Important error self._logger.exception( "Critical error calling back %s: %s", self.name, ex ) # Kill the component self._ipopo_service.kill(self.name) if ex.needs_stop: # Framework must be stopped...
python
{ "resource": "" }
q9805
StoredInstance.__safe_handler_callback
train
def __safe_handler_callback(self, handler, method_name, *args, **kwargs): # type: (Any, str, *Any, **Any) -> Any """ Calls the given method with the given arguments in the given handler. Logs exceptions, but doesn't propagate them. Special arguments can be given in kwargs: * 'none_as_true': If set to True and the method returned None or doesn't exist, the result is considered as True. If set to False, None result is kept as is. Default is False. * 'only_boolean': If True, the result can only be True or False, else the result is the value returned by the method. Default is False. :param handler: The handler to call :param method_name: The name of the method to call :param args: List of arguments for the method to call :param kwargs: Dictionary of arguments for the method to call and to control the call :return: The method result, or None on error """ if handler is None or method_name is None: return None # Behavior flags only_boolean =
python
{ "resource": "" }
q9806
StoredInstance.__safe_handlers_callback
train
def __safe_handlers_callback(self, method_name, *args, **kwargs): # type: (str, *Any, **Any) -> bool """ Calls the given method with the given arguments in all handlers. Logs exceptions, but doesn't propagate them. Methods called in handlers must return None, True or False. Special parameters can be given in kwargs: * 'exception_as_error': if it is set to True and an exception is raised by a handler, then this method will return False. By default, this flag is set to False and exceptions are ignored. * 'break_on_false': if it set to True, the loop calling the handler will stop after an handler returned False. By default, this flag is set to False, and all handlers are called. :param method_name: Name of the method to call :param args: List of arguments for the method to call :param kwargs: Dictionary of arguments for the method to call and the
python
{ "resource": "" }
q9807
StoredInstance.__set_binding
train
def __set_binding(self, dependency, service, reference): # type: (Any, Any, ServiceReference) -> None """ Injects a service in the component :param dependency: The dependency handler :param service: The injected service :param reference: The reference of the injected service """ # Set the value setattr(self.instance, dependency.get_field(), dependency.get_value())
python
{ "resource": "" }
q9808
StoredInstance.__update_binding
train
def __update_binding( self, dependency, service, reference, old_properties, new_value ): # type: (Any, Any, ServiceReference, dict, bool) -> None """ Calls back component binding and field binding methods when the properties of an injected dependency have been updated. :param dependency: The dependency handler :param service: The injected service :param reference: The reference of the injected service :param old_properties: Previous properties of the dependency :param new_value: If True, inject the new value of the handler """ if new_value: # Set the value
python
{ "resource": "" }
q9809
StoredInstance.__unset_binding
train
def __unset_binding(self, dependency, service, reference): # type: (Any, Any, ServiceReference) -> None """ Removes a service from the component :param dependency: The dependency handler :param service: The injected service :param reference: The reference of the injected service """ # Call the component back self.__safe_field_callback( dependency.get_field(), constants.IPOPO_CALLBACK_UNBIND_FIELD, service,
python
{ "resource": "" }
q9810
_parse_boolean
train
def _parse_boolean(value): """ Returns a boolean value corresponding to the given value. :param value: Any value :return: Its boolean value """ if not value: return False try: # Lower string to check known "false" value
python
{ "resource": "" }
q9811
_VariableFilterMixIn._find_keys
train
def _find_keys(self): """ Looks for the property keys in the filter string :return: A list of property
python
{ "resource": "" }
q9812
_VariableFilterMixIn.update_filter
train
def update_filter(self): """ Update the filter according to the new properties :return: True if the filter changed, else False :raise ValueError: The filter is invalid """ # Consider the filter invalid self.valid_filter = False try: # Format the new filter filter_str = self._original_filter.format( **self._component_context.properties ) except KeyError as ex: # An entry is missing: abandon logging.warning("Missing filter value: %s", ex) raise ValueError("Missing filter value") try: # Parse the new LDAP
python
{ "resource": "" }
q9813
_VariableFilterMixIn.on_property_change
train
def on_property_change(self, name, old_value, new_value): # pylint: disable=W0613 """ A component property has been updated :param name: Name of the property :param old_value: Previous value of the property :param new_value: New value of the property """ if name in self._keys: try: if self.update_filter(): # This is a key for the filter and the filter has changed
python
{ "resource": "" }
q9814
_VariableFilterMixIn._reset
train
def _reset(self): """ Called when the filter has been changed """ with self._lock: # Start listening to services with the new filter self.stop() self.start() for svc_ref in self.get_bindings(): # Check if the current reference matches the filter if not self.requirement.filter.matches( svc_ref.get_properties()
python
{ "resource": "" }
q9815
EventData.set
train
def set(self, data=None): """ Sets the event """ self.__data = data
python
{ "resource": "" }
q9816
EventData.wait
train
def wait(self, timeout=None): """ Waits for the event or for the timeout :param timeout: Wait timeout (in seconds) :return: True if the event as been set, else False """ # The 'or' part is for Python 2.6 result = self.__event.wait(timeout)
python
{ "resource": "" }
q9817
FutureResult.__notify
train
def __notify(self): """ Notify the given callback about the result of the execution """ if self.__callback is not None: try: self.__callback(
python
{ "resource": "" }
q9818
FutureResult.set_callback
train
def set_callback(self, method, extra=None): """ Sets a callback method, called once the result has been computed or in case of exception. The callback method must have the following signature: ``callback(result, exception, extra)``. :param method: The method to call back in the end of the execution :param extra: Extra parameter
python
{ "resource": "" }
q9819
ThreadPool.start
train
def start(self): """ Starts the thread pool. Does nothing if the pool is already started. """ if not self._done_event.is_set(): # Stop event not set: we're running return # Clear the stop event self._done_event.clear() # Compute the number of threads to start to handle pending tasks nb_pending_tasks = self._queue.qsize() if nb_pending_tasks > self._max_threads: nb_threads = self._max_threads nb_pending_tasks = self._max_threads elif nb_pending_tasks < self._min_threads: nb_threads = self._min_threads
python
{ "resource": "" }
q9820
ThreadPool.__start_thread
train
def __start_thread(self): """ Starts a new thread, if possible """ with self.__lock: if self.__nb_threads >= self._max_threads: # Can't create more threads return False if self._done_event.is_set(): # We're stopped: do nothing return False # Prepare thread and start it name = "{0}-{1}".format(self._logger.name, self._thread_id) self._thread_id += 1 thread = threading.Thread(target=self.__run, name=name)
python
{ "resource": "" }
q9821
ThreadPool.stop
train
def stop(self): """ Stops the thread pool. Does nothing if the pool is already stopped. """ if self._done_event.is_set(): # Stop event set: we're stopped return # Set the stop event self._done_event.set() with self.__lock: # Add something in the queue (to unlock the join()) try: for _ in self._threads: self._queue.put(self._done_event, True, self._timeout) except queue.Full: # There is already something in the queue pass # Copy the list of threads to wait for threads = self._threads[:] # Join threads outside the lock for thread in threads: while thread.is_alive():
python
{ "resource": "" }
q9822
ThreadPool.enqueue
train
def enqueue(self, method, *args, **kwargs): """ Queues a task in the pool :param method: Method to call :return: A FutureResult object, to get the result of the task :raise ValueError: Invalid method :raise Full: The task queue is full """ if not hasattr(method, "__call__"): raise ValueError( "{0} has no __call__ member.".format(method.__name__) ) # Prepare the future result object future = FutureResult(self._logger) # Use a lock, as we might be "resetting" the queue with
python
{ "resource": "" }
q9823
ThreadPool.clear
train
def clear(self): """ Empties the current queue content. Returns once the queue have been emptied. """ with self.__lock: # Empty the current queue try: while True: self._queue.get_nowait() self._queue.task_done()
python
{ "resource": "" }
q9824
ThreadPool.join
train
def join(self, timeout=None): """ Waits for all the tasks to be executed :param timeout: Maximum time to wait (in seconds) :return: True if the queue has been emptied, else False """ if self._queue.empty(): # Nothing to wait for... return True elif timeout is None: # Use the original join self._queue.join()
python
{ "resource": "" }
q9825
ThreadPool.__run
train
def __run(self): """ The main loop """ already_cleaned = False try: while not self._done_event.is_set(): try: # Wait for an action (blocking) task = self._queue.get(True, self._timeout) if task is self._done_event: # Stop event in the queue: get out self._queue.task_done() return except queue.Empty: # Nothing to do yet pass else: with self.__lock: self.__nb_active_threads += 1 # Extract elements method, args, kwargs, future = task try: # Call the method future.execute(method, args, kwargs) except Exception as ex: self._logger.exception( "Error executing %s: %s", method.__name__, ex ) finally: # Mark the action as executed self._queue.task_done() # Thread is not active anymore with self.__lock: self.__nb_pending_task -= 1 self.__nb_active_threads -= 1 # Clean up thread if necessary with self.__lock: extra_threads = self.__nb_threads - self.__nb_active_threads
python
{ "resource": "" }
q9826
docid
train
def docid(url, encoding='ascii'): """Get DocID from URL. DocID generation depends on bytes of the URL string. So, if non-ascii charactors in the URL, encoding should be considered properly. Args: url (str or bytes): Pre-encoded bytes or string will be encoded with the 'encoding' argument. encoding (str, optional): Defaults to 'ascii'. Used to encode url argument if it is not pre-encoded into bytes. Returns: DocID: The DocID object. Examples: >>> from os_docid import docid >>> docid('http://www.google.com/') 1d5920f4b44b27a8-ed646a3334ca891f-ff90821feeb2b02a33a6f9fc8e5f3fcd >>> docid('1d5920f4b44b27a8-ed646a3334ca891f-ff90821feeb2b02a33a6f9fc8e5f3fcd')
python
{ "resource": "" }
q9827
sanitize_html
train
def sanitize_html(value, valid_tags=VALID_TAGS, strip=True): """ Strips unwanted markup
python
{ "resource": "" }
q9828
deobfuscate_email
train
def deobfuscate_email(text): """ Deobfuscate email addresses in provided text """ text = unescape(text) # Find the "dot" text = _deobfuscate_dot1_re.sub('.', text) text = _deobfuscate_dot2_re.sub(r'\1.\2', text) text = _deobfuscate_dot3_re.sub(r'\1.\2', text) #
python
{ "resource": "" }
q9829
simplify_text
train
def simplify_text(text): """ Simplify text to allow comparison. >>> simplify_text("Awesome Coder wanted at Awesome Company") 'awesome coder wanted at awesome company' >>> simplify_text("Awesome Coder, wanted at Awesome Company! ") 'awesome coder wanted at awesome company' >>> simplify_text(u"Awesome Coder, wanted at Awesome Company! ") == 'awesome
python
{ "resource": "" }
q9830
dropdb
train
def dropdb(): """Drop database tables""" manager.db.engine.echo = True if prompt_bool("Are you sure you want to lose all your data"): manager.db.drop_all()
python
{ "resource": "" }
q9831
createdb
train
def createdb(): """Create database tables from sqlalchemy models""" manager.db.engine.echo = True
python
{ "resource": "" }
q9832
sync_resources
train
def sync_resources(): """Sync the client's resources with the Lastuser server""" print("Syncing resources with Lastuser...") resources = manager.app.lastuser.sync_resources()['results'] for rname, resource in six.iteritems(resources): if resource['status'] == 'error': print("Error for %s: %s" %
python
{ "resource": "" }
q9833
load_config_from_file
train
def load_config_from_file(app, filepath): """Helper function to load config from a specified file""" try: app.config.from_pyfile(filepath) return True except IOError: # TODO: Can we print to sys.stderr in production? Should this go to #
python
{ "resource": "" }
q9834
IdMixin.id
train
def id(cls): """ Database identity for this model, used for foreign key references from other models """ if cls.__uuid_primary_key__:
python
{ "resource": "" }
q9835
IdMixin.url_id
train
def url_id(cls): """The URL id""" if cls.__uuid_primary_key__: def url_id_func(self): """The URL id, UUID primary key rendered as a hex string""" return self.id.hex def url_id_is(cls): return SqlHexUuidComparator(cls.id) url_id_func.__name__ = 'url_id' url_id_property = hybrid_property(url_id_func) url_id_property = url_id_property.comparator(url_id_is) return url_id_property else: def url_id_func(self): """The URL id, integer primary
python
{ "resource": "" }
q9836
UrlForMixin.register_view_for
train
def register_view_for(cls, app, action, classview, attr): """ Register a classview and viewhandler for a given app and action """ if 'view_for_endpoints' not in cls.__dict__:
python
{ "resource": "" }
q9837
UrlForMixin.view_for
train
def view_for(self, action='view'): """ Return the classview viewhandler that handles the specified action """
python
{ "resource": "" }
q9838
UrlForMixin.classview_for
train
def classview_for(self, action='view'): """ Return the classview that contains the viewhandler for the specified action """
python
{ "resource": "" }
q9839
BaseNameMixin.name
train
def name(cls): """The URL name of this object, unique across all instances of this model""" if cls.__name_length__ is None: column_type = UnicodeText() else: column_type = Unicode(cls.__name_length__) if cls.__name_blank_allowed__:
python
{ "resource": "" }
q9840
BaseNameMixin.title
train
def title(cls): """The title of this object""" if cls.__title_length__ is None:
python
{ "resource": "" }
q9841
BaseNameMixin.upsert
train
def upsert(cls, name, **fields): """Insert or update an instance""" instance = cls.get(name) if instance:
python
{ "resource": "" }
q9842
BaseScopedNameMixin.get
train
def get(cls, parent, name): """Get an instance matching the parent and name"""
python
{ "resource": "" }
q9843
BaseScopedNameMixin.short_title
train
def short_title(self): """ Generates an abbreviated title by subtracting the parent's title from this instance's title. """ if self.title and self.parent is not None and hasattr(self.parent, 'title') and self.parent.title: if self.title.startswith(self.parent.title): short = self.title[len(self.parent.title):].strip()
python
{ "resource": "" }
q9844
BaseScopedNameMixin.permissions
train
def permissions(self, actor, inherited=None): """ Permissions for this model, plus permissions inherited from the parent. """ if inherited is not None: return inherited | super(BaseScopedNameMixin, self).permissions(actor) elif self.parent is not None and isinstance(self.parent, PermissionMixin):
python
{ "resource": "" }
q9845
BaseScopedIdMixin.get
train
def get(cls, parent, url_id): """Get an instance matching the parent and url_id"""
python
{ "resource": "" }
q9846
BaseScopedIdMixin.make_id
train
def make_id(self): """Create a new URL id that is unique to the parent container""" if self.url_id is None: # Set id only if empty
python
{ "resource": "" }
q9847
make_timestamp_columns
train
def make_timestamp_columns(): """Return two columns, created_at and updated_at, with appropriate defaults""" return ( Column('created_at', DateTime, default=func.utcnow(), nullable=False),
python
{ "resource": "" }
q9848
auto_init_default
train
def auto_init_default(column): """ Set the default value for a column when it's first accessed rather than first committed to the database. """ if isinstance(column, ColumnProperty): default = column.columns[0].default else: default = column.default @event.listens_for(column, 'init_scalar', retval=True, propagate=True) def init_scalar(target, value, dict_): # A subclass may override the column and not provide a default. Watch out for that. if default: if default.is_callable:
python
{ "resource": "" }
q9849
load_model
train
def load_model(model, attributes=None, parameter=None, kwargs=False, permission=None, addlperms=None, urlcheck=[]): """ Decorator to load a model given a query parameter. Typical usage:: @app.route('/<profile>') @load_model(Profile, {'name': 'profile'}, 'profileob') def profile_view(profileob): # 'profileob' is now a Profile model instance. The load_model decorator replaced this: # profileob = Profile.query.filter_by(name=profile).first_or_404() return "Hello, %s" % profileob.name Using the same name for request and parameter makes code easier to understand:: @app.route('/<profile>') @load_model(Profile, {'name': 'profile'}, 'profile') def profile_view(profile): return "Hello, %s" % profile.name ``load_model`` aborts with a 404 if no instance is found. :param model: The SQLAlchemy model to query. Must contain a ``query`` object (which is the default with Flask-SQLAlchemy) :param attributes: A dict of attributes (from the URL request) that will be used to query for the object. For each key:value pair, the key is the name of the column on the model and the value is the name of the request parameter that contains the data :param parameter: The name of the parameter to the decorated function via which the result is passed. Usually the same as the attribute. If the parameter name is prefixed with 'g.', the parameter is also made available as g.<parameter> :param kwargs: If True, the original request parameters are passed to the decorated function as a ``kwargs`` parameter :param permission: If present, ``load_model`` calls the
python
{ "resource": "" }
q9850
dict_jsonify
train
def dict_jsonify(param): """Convert the parameter into a dictionary before calling jsonify, if it's not already one"""
python
{ "resource": "" }
q9851
dict_jsonp
train
def dict_jsonp(param): """Convert the parameter into a dictionary before calling jsonp, if it's not already one"""
python
{ "resource": "" }
q9852
cors
train
def cors(origins, methods=['HEAD', 'OPTIONS', 'GET', 'POST', 'PUT', 'PATCH', 'DELETE'], headers=['Accept', 'Accept-Language', 'Content-Language', 'Content-Type', 'X-Requested-With'], max_age=None): """ Adds CORS headers to the decorated view function. :param origins: Allowed origins (see below) :param methods: A list of allowed HTTP methods :param headers: A list of allowed HTTP headers :param max_age: Duration in seconds for which the CORS response may be cached The :obj:`origins` parameter may be one of: 1. A callable that receives the origin as a parameter. 2. A list of origins. 3. ``*``, indicating that this resource is accessible by any origin. Example use:: from flask import Flask, Response from coaster.views import cors app = Flask(__name__) @app.route('/any') @cors('*') def any_origin(): return Response() @app.route('/static', methods=['GET', 'POST']) @cors(['https://hasgeek.com'], methods=['GET'], headers=['Content-Type', 'X-Requested-With'], max_age=3600) def static_list(): return Response() def check_origin(origin): # check if origin should be allowed return True @app.route('/callable') @cors(check_origin) def callable_function(): return Response() """ def inner(f): @wraps(f) def wrapper(*args, **kwargs): origin = request.headers.get('Origin') if request.method not in methods: abort(405) if origins == '*': pass elif is_collection(origins) and origin in origins: pass elif callable(origins) and origins(origin): pass else: abort(403)
python
{ "resource": "" }
q9853
requires_permission
train
def requires_permission(permission): """ View decorator that requires a certain permission to be present in ``current_auth.permissions`` before the view is allowed to proceed. Aborts with ``403 Forbidden`` if the permission is not present. The decorated view will have an ``is_available`` method that can be called to perform the same test. :param permission: Permission that is required. If a collection type is provided, any one permission must be available """ def inner(f): def is_available_here(): if not hasattr(current_auth, 'permissions'): return False elif is_collection(permission): return bool(current_auth.permissions.intersection(permission)) else: return permission in current_auth.permissions def is_available(context=None): result = is_available_here() if result and hasattr(f, 'is_available'): # We passed,
python
{ "resource": "" }
q9854
uuid1mc_from_datetime
train
def uuid1mc_from_datetime(dt): """ Return a UUID1 with a random multicast MAC id and with a timestamp matching the given datetime object or timestamp value. .. warning:: This function does not consider the timezone, and is not guaranteed to return a unique UUID. Use under controlled conditions only. >>> dt = datetime.now() >>> u1 = uuid1mc() >>> u2 = uuid1mc_from_datetime(dt) >>> # Both timestamps should be very close to each other but not an exact match >>> u1.time > u2.time True >>> u1.time - u2.time < 5000 True >>> d2 = datetime.fromtimestamp((u2.time - 0x01b21dd213814000) * 100 / 1e9) >>> d2 == dt True """ fields = list(uuid1mc().fields) if isinstance(dt, datetime): timeval = time.mktime(dt.timetuple()) + dt.microsecond / 1e6 else: # Assume we got
python
{ "resource": "" }
q9855
uuid2buid
train
def uuid2buid(value): """ Convert a UUID object to a 22-char BUID string >>> u = uuid.UUID('33203dd2-f2ef-422f-aeb0-058d6f5f7089') >>> uuid2buid(u) 'MyA90vLvQi-usAWNb19wiQ' """ if six.PY3: #
python
{ "resource": "" }
q9856
newpin
train
def newpin(digits=4): """ Return a random numeric string with the specified number of digits, default 4. >>> len(newpin()) 4 >>> len(newpin(5)) 5 >>> newpin().isdigit() True """ randnum = randint(0, 10 ** digits)
python
{ "resource": "" }
q9857
make_name
train
def make_name(text, delim=u'-', maxlength=50, checkused=None, counter=2): u""" Generate an ASCII name slug. If a checkused filter is provided, it will be called with the candidate. If it returns True, make_name will add counter numbers starting from 2 until a suitable candidate is found. :param string delim: Delimiter between words, default '-' :param int maxlength: Maximum length of name, default 50 :param checkused: Function to check if a generated name is available for use :param int counter: Starting position for name counter >>> make_name('This is a title') 'this-is-a-title' >>> make_name('Invalid URL/slug here') 'invalid-url-slug-here' >>> make_name('this.that') 'this-that' >>> make_name('this:that') 'this-that' >>> make_name("How 'bout this?") 'how-bout-this' >>> make_name(u"How’s that?") 'hows-that' >>> make_name(u'K & D') 'k-d' >>> make_name('billion+ pageviews') 'billion-pageviews' >>> make_name(u'हिन्दी slug!') 'hindii-slug' >>> make_name(u'Your webapps should talk not just in English, but in español, Kiswahili, 廣州話 and অসমীয়া too.', maxlength=250) u'your-webapps-should-talk-not-just-in-english-but-in-espanol-kiswahili-guang-zhou-hua-and-asmiiyaa-too' >>> make_name(u'__name__', delim=u'_') 'name' >>> make_name(u'how_about_this', delim=u'_') 'how_about_this' >>> make_name(u'and-that', delim=u'_') 'and_that' >>> make_name(u'Umlauts in Mötörhead') 'umlauts-in-motorhead' >>> make_name('Candidate', checkused=lambda c: c in ['candidate']) 'candidate2' >>> make_name('Candidate', checkused=lambda c: c in ['candidate'], counter=1) 'candidate1' >>> make_name('Candidate', checkused=lambda c: c in ['candidate', 'candidate1', 'candidate2'], counter=1) 'candidate3' >>> make_name('Long title, but snipped', maxlength=20) 'long-title-but-snipp' >>> len(make_name('Long title, but snipped', maxlength=20)) 20 >>> make_name('Long candidate', maxlength=10, checkused=lambda c: c in ['long-candi', 'long-cand1']) 'long-cand2' >>> make_name(u'Lǝnkǝran') 'lankaran' >>> make_name(u'example@example.com') 'example-example-com'
python
{ "resource": "" }
q9858
check_password
train
def check_password(reference, attempt): """ Compare a reference password with the user attempt. >>> check_password('{PLAIN}foo', 'foo') True >>> check_password(u'{PLAIN}bar', 'bar') True >>> check_password(u'{UNKNOWN}baz', 'baz') False >>> check_password(u'no-encoding', u'no-encoding') False >>> check_password(u'{SSHA}q/uVU8r15k/9QhRi92CWUwMJu2DM6TUSpp25', u're-foo') True >>> check_password(u'{BCRYPT}$2b$12$NfKivgz7njR3/rWZ56EsDe7..PPum.fcmFLbdkbP.chtMTcS1s01C', 'foo') True """ if reference.startswith(u'{PLAIN}'): if reference[7:] == attempt: return True elif reference.startswith(u'{SSHA}'): # In python3 b64decode takes inputtype as bytes as opposed to str in python 2, and returns # binascii.Error as opposed to TypeError if six.PY3: # pragma: no cover try: if isinstance(reference, six.text_type): ref = b64decode(reference[6:].encode('utf-8')) else:
python
{ "resource": "" }
q9859
format_currency
train
def format_currency(value, decimals=2): """ Return a number suitably formatted for display as currency, with thousands separated by commas and up to two decimal points. >>> format_currency(1000) '1,000' >>> format_currency(100) '100' >>> format_currency(999.95) '999.95' >>> format_currency(99.95) '99.95' >>> format_currency(100000) '100,000' >>> format_currency(1000.00)
python
{ "resource": "" }
q9860
md5sum
train
def md5sum(data): """ Return md5sum of data as a 32-character string. >>> md5sum('random text') 'd9b9bec3f4cc5482e7c5ef43143e563a' >>> md5sum(u'random text') 'd9b9bec3f4cc5482e7c5ef43143e563a' >>> len(md5sum('random text')) 32 """ if six.PY3: # pragma: no cover
python
{ "resource": "" }
q9861
midnight_to_utc
train
def midnight_to_utc(dt, timezone=None, naive=False): """ Returns a UTC datetime matching the midnight for the given date or datetime. >>> from datetime import date >>> midnight_to_utc(datetime(2017, 1, 1)) datetime.datetime(2017, 1, 1, 0, 0, tzinfo=<UTC>) >>> midnight_to_utc(pytz.timezone('Asia/Kolkata').localize(datetime(2017, 1, 1))) datetime.datetime(2016, 12, 31, 18, 30, tzinfo=<UTC>) >>> midnight_to_utc(datetime(2017, 1, 1), naive=True) datetime.datetime(2017, 1, 1, 0, 0) >>> midnight_to_utc(pytz.timezone('Asia/Kolkata').localize(datetime(2017, 1, 1)), naive=True) datetime.datetime(2016, 12, 31, 18, 30) >>> midnight_to_utc(date(2017, 1, 1)) datetime.datetime(2017, 1, 1, 0, 0, tzinfo=<UTC>) >>> midnight_to_utc(date(2017, 1, 1), naive=True) datetime.datetime(2017, 1, 1, 0, 0) >>> midnight_to_utc(date(2017, 1, 1), timezone='Asia/Kolkata') datetime.datetime(2016, 12, 31, 18, 30, tzinfo=<UTC>) >>> midnight_to_utc(datetime(2017, 1, 1), timezone='Asia/Kolkata') datetime.datetime(2016, 12, 31, 18, 30, tzinfo=<UTC>) >>>
python
{ "resource": "" }
q9862
getbool
train
def getbool(value): """ Returns a boolean from any of a range of values. Returns None for unrecognized values. Numbers other than 0 and 1 are considered unrecognized. >>> getbool(True) True >>> getbool(1) True >>>
python
{ "resource": "" }
q9863
unicode_http_header
train
def unicode_http_header(value): r""" Convert an ASCII HTTP header string into a unicode string with the appropriate encoding applied. Expects headers to be RFC 2047 compliant. >>> unicode_http_header('=?iso-8859-1?q?p=F6stal?=') == u'p\xf6stal' True >>> unicode_http_header(b'=?iso-8859-1?q?p=F6stal?=') == u'p\xf6stal' True >>> unicode_http_header('p\xf6stal') == u'p\xf6stal'
python
{ "resource": "" }
q9864
get_email_domain
train
def get_email_domain(emailaddr): """ Return the domain component of an email address. Returns None if the provided string cannot be parsed as an email address. >>> get_email_domain('test@example.com') 'example.com' >>> get_email_domain('test+trailing@example.com') 'example.com' >>> get_email_domain('Example Address <test@example.com>') 'example.com' >>> get_email_domain('foobar') >>> get_email_domain('foo@bar@baz') 'bar' >>> get_email_domain('foobar@') >>>
python
{ "resource": "" }
q9865
sorted_timezones
train
def sorted_timezones(): """ Return a list of timezones sorted by offset from UTC. """ def hourmin(delta): if delta.days < 0: hours, remaining = divmod(86400 - delta.seconds, 3600) else: hours, remaining = divmod(delta.seconds, 3600) minutes, remaining = divmod(remaining, 60) return hours, minutes now = datetime.utcnow() # Make a list of country code mappings timezone_country = {} for countrycode in pytz.country_timezones: for timezone in pytz.country_timezones[countrycode]: timezone_country[timezone] = countrycode # Make a list of timezones, discarding the US/* and Canada/* zones since they aren't reliable for # DST, and discarding UTC and GMT since timezones in that zone have their own names timezones = [(pytz.timezone(tzname).utcoffset(now, is_dst=False), tzname) for tzname in pytz.common_timezones if not tzname.startswith('US/') and not tzname.startswith('Canada/') and tzname not in ('GMT', 'UTC')] # Sort timezones by offset from UTC
python
{ "resource": "" }
q9866
namespace_from_url
train
def namespace_from_url(url): """ Construct a dotted namespace string from a URL. """ parsed = urlparse(url) if parsed.hostname is None or parsed.hostname in ['localhost', 'localhost.localdomain'] or ( _ipv4_re.search(parsed.hostname)): return None namespace = parsed.hostname.split('.')
python
{ "resource": "" }
q9867
base_domain_matches
train
def base_domain_matches(d1, d2): """ Check if two domains have the same base domain, using the Public Suffix List. >>> base_domain_matches('https://hasjob.co', 'hasjob.co') True >>> base_domain_matches('hasgeek.hasjob.co', 'hasjob.co') True >>> base_domain_matches('hasgeek.com', 'hasjob.co') False >>> base_domain_matches('static.hasgeek.co.in', 'hasgeek.com') False >>> base_domain_matches('static.hasgeek.co.in', 'hasgeek.co.in') True >>> base_domain_matches('example@example.com', 'example.com')
python
{ "resource": "" }
q9868
MarkdownColumn
train
def MarkdownColumn(name, deferred=False, group=None, **kwargs): """ Create a composite column that autogenerates HTML from Markdown text, storing data in db columns named with ``_html`` and ``_text`` prefixes. """ return composite(MarkdownComposite,
python
{ "resource": "" }
q9869
VersionedAssets.require
train
def require(self, *namespecs): """Return a bundle of the requested assets and their dependencies.""" blacklist = set([n[1:] for n in namespecs if n.startswith('!')]) not_blacklist = [n for n in namespecs if
python
{ "resource": "" }
q9870
StateTransitionWrapper._state_invalid
train
def _state_invalid(self): """ If the state is invalid for the transition, return details on what didn't match :return: Tuple of (state manager, current state, label for current state) """ for statemanager, conditions in self.statetransition.transitions.items(): current_state = getattr(self.obj, statemanager.propname) if conditions['from'] is None: state_valid = True else: mstate = conditions['from'].get(current_state)
python
{ "resource": "" }
q9871
StateManager.add_conditional_state
train
def add_conditional_state(self, name, state, validator, class_validator=None, cache_for=None, label=None): """ Add a conditional state that combines an existing state with a validator that must also pass. The validator receives the object on which the property is present as a parameter. :param str name: Name of the new state :param ManagedState state: Existing state that this is based on :param validator: Function that will be called with the host object as a parameter :param class_validator: Function that will be called when the state is queried on the class instead of the instance. Falls back to ``validator`` if not specified. Receives the class as the parameter :param cache_for: Integer or function that indicates how long ``validator``'s result can be cached (not applicable to ``class_validator``). ``None`` implies no cache, ``0`` implies indefinite cache (until invalidated by a transition) and any other integer is the number of seconds for which to cache the assertion :param label: Label for this state (string or 2-tuple) TODO: `cache_for`'s implementation is currently pending a test case demonstrating how it will be used.
python
{ "resource": "" }
q9872
StateManager.requires
train
def requires(self, from_, if_=None, **data): """ Decorates a method that may be called if the given state is currently active. Registers a transition internally, but does not change the state. :param from_: Required state to allow this call (can be a state group) :param if_: Validator(s) that, given the object, must all return True for the call to proceed
python
{ "resource": "" }
q9873
StateManagerWrapper.current
train
def current(self): """ All states and state groups that are currently active. """ if self.obj is not None: return {name: mstate(self.obj, self.cls) for
python
{ "resource": "" }
q9874
gfm
train
def gfm(text): """ Prepare text for rendering by a regular Markdown processor. """ def indent_code(matchobj): syntax = matchobj.group(1) code = matchobj.group(2) if syntax: result = ' :::' + syntax + '\n' else: result = '' # The last line will be blank since it had the closing "```". Discard it # when indenting the lines. return result + '\n'.join([' ' + line for line in code.split('\n')[:-1]]) use_crlf = text.find('\r') != -1 if use_crlf: text = text.replace('\r\n', '\n') # Render GitHub-style ```code blocks``` into Markdown-style 4-space indented blocks text = CODEPATTERN_RE.sub(indent_code, text) text, code_blocks = remove_pre_blocks(text) text, inline_blocks = remove_inline_code_blocks(text)
python
{ "resource": "" }
q9875
markdown
train
def markdown(text, html=False, valid_tags=GFM_TAGS): """ Return Markdown rendered text using GitHub Flavoured Markdown, with HTML escaped and syntax-highlighting enabled. """ if text is None: return None if html:
python
{ "resource": "" }
q9876
ViewHandlerWrapper.is_available
train
def is_available(self): """Indicates whether this view is available in the current context""" if hasattr(self._viewh.wrapped_func, 'is_available'):
python
{ "resource": "" }
q9877
get_current_url
train
def get_current_url(): """ Return the current URL including the query string as a relative path. If the app uses subdomains, return an absolute path """ if current_app.config.get('SERVER_NAME') and ( # Check current hostname against server name, ignoring port numbers, if any (split on ':') request.environ['HTTP_HOST'].split(':', 1)[0] != current_app.config['SERVER_NAME'].split(':', 1)[0]):
python
{ "resource": "" }
q9878
get_next_url
train
def get_next_url(referrer=False, external=False, session=False, default=__marker): """ Get the next URL to redirect to. Don't return external URLs unless explicitly asked for. This is to protect the site from being an unwitting redirector to external URLs. Subdomains are okay, however. This function looks for a ``next`` parameter in the request or in the session (depending on whether parameter ``session`` is True). If no ``next`` is present, it checks the referrer (if enabled), and finally returns either the provided default (which can be any value including ``None``) or the script root (typically ``/``). """ if session: next_url = request_session.pop('next', None) or request.args.get('next', '') else: next_url = request.args.get('next', '') if
python
{ "resource": "" }
q9879
annotation_wrapper
train
def annotation_wrapper(annotation, doc=None): """ Defines an annotation, which can be applied to attributes in a database model. """ def decorator(attr): __cache__.setdefault(attr, []).append(annotation) # Also mark the annotation on the object itself. This will # fail if the object has a restrictive __slots__, but it's # required for some objects like Column because SQLAlchemy copies # them in subclasses, changing their hash and making them # undiscoverable via the cache. try: if not hasattr(attr,
python
{ "resource": "" }
q9880
SchemaMeta.build_attributes
train
def build_attributes(cls, attributes, namespace): """Return an attributes dictionary with ValueTokens replaced by a property which returns the config value. """ config_path = attributes.get('config_path') tokens = {} def build_config_key(value_def, config_key): key = value_def.config_key or config_key return '%s.%s' % (config_path, key) if config_path else key def build_token(name, value_def): config_key = build_config_key(value_def, name) value_token = ValueToken.from_definition( value_def, namespace, config_key)
python
{ "resource": "" }
q9881
cache_as_field
train
def cache_as_field(cache_name): """Cache a functions return value as the field 'cache_name'.""" def cache_wrapper(func): @functools.wraps(func) def inner_wrapper(self, *args, **kwargs):
python
{ "resource": "" }
q9882
extract_value
train
def extract_value(proxy): """Given a value proxy type, Retrieve a value from a namespace, raising exception if no value is found, or the value does not validate. """ value = proxy.namespace.get(proxy.config_key, proxy.default) if value is UndefToken: raise errors.ConfigurationError("%s is missing value for: %s" %
python
{ "resource": "" }
q9883
build_reader
train
def build_reader(validator, reader_namespace=config.DEFAULT): """A factory method for creating a custom config reader from a validation function. :param validator: a validation function which acceptance one argument (the configuration value), and returns that value casted to the appropriate type. :param reader_namespace: the default namespace to use. Defaults to `DEFAULT`.
python
{ "resource": "" }
q9884
get_namespaces_from_names
train
def get_namespaces_from_names(name, all_names): """Return a generator which yields namespace objects.""" names = configuration_namespaces.keys() if
python
{ "resource": "" }
q9885
validate
train
def validate(name=DEFAULT, all_names=False): """Validate all registered keys after loading configuration. Missing values or values which do not pass validation raise :class:`staticconf.errors.ConfigurationError`. By default only validates the `DEFAULT` namespace. :param name: the namespace to validate :type name: string :param all_names: if True validates all
python
{ "resource": "" }
q9886
has_duplicate_keys
train
def has_duplicate_keys(config_data, base_conf, raise_error): """Compare two dictionaries for duplicate keys. if raise_error is True then raise on exception, otherwise log return True."""
python
{ "resource": "" }
q9887
build_compare_func
train
def build_compare_func(err_logger=None): """Returns a compare_func that can be passed to MTimeComparator. The returned compare_func first tries os.path.getmtime(filename), then calls err_logger(filename) if that fails. If err_logger is None, then it does nothing. err_logger is always called within the context of an OSError raised by os.path.getmtime(filename). Information on this error can be retrieved by calling sys.exc_info inside of err_logger."""
python
{ "resource": "" }
q9888
ConfigNamespace.get_config_dict
train
def get_config_dict(self): """Reconstruct the nested structure of this object's configuration and return it as a dict. """ config_dict = {} for dotted_key, value in self.get_config_values().items(): subkeys = dotted_key.split('.') d =
python
{ "resource": "" }
q9889
ConfigHelp.view_help
train
def view_help(self): """Return a help message describing all the statically configured keys. """ def format_desc(desc): return "%s (Type: %s, Default: %s)\n%s" % ( desc.name, desc.validator.__name__.replace('validate_', ''), desc.default, desc.help or '') def format_namespace(key, desc_list): return "\nNamespace: %s\n%s" % ( key,
python
{ "resource": "" }
q9890
_validate_iterable
train
def _validate_iterable(iterable_type, value): """Convert the iterable to iterable_type, or raise a Configuration exception. """ if isinstance(value, six.string_types):
python
{ "resource": "" }
q9891
build_list_type_validator
train
def build_list_type_validator(item_validator): """Return a function which validates that the value is a list of items which are validated using item_validator. """ def validate_list_of_type(value):
python
{ "resource": "" }
q9892
build_map_type_validator
train
def build_map_type_validator(item_validator): """Return a function which validates that the value is a mapping of items. The function should return pairs of items that will be passed to the `dict` constructor.
python
{ "resource": "" }
q9893
register_value_proxy
train
def register_value_proxy(namespace, value_proxy, help_text): """Register a value proxy with the namespace, and add the help_text.""" namespace.register_proxy(value_proxy) config.config_help.add(
python
{ "resource": "" }
q9894
build_getter
train
def build_getter(validator, getter_namespace=None): """Create a getter function for retrieving values from the config cache. Getters will default to the DEFAULT namespace. """ def proxy_register(key_name, default=UndefToken, help=None,
python
{ "resource": "" }
q9895
ProxyFactory.build
train
def build(self, validator, namespace, config_key, default, help): """Build or retrieve a ValueProxy from the attributes. Proxies are keyed using a repr because default values can be mutable types. """ proxy_attrs = validator, namespace, config_key, default proxy_key = repr(proxy_attrs) if proxy_key in self.proxies:
python
{ "resource": "" }
q9896
minimizeSPSA
train
def minimizeSPSA(func, x0, args=(), bounds=None, niter=100, paired=True, a=1.0, alpha=0.602, c=1.0, gamma=0.101, disp=False, callback=None): """ Minimization of an objective function by a simultaneous perturbation stochastic approximation algorithm. This algorithm approximates the gradient of the function by finite differences along stochastic directions Deltak. The elements of Deltak are drawn from +- 1 with probability one half. The gradient is approximated from the symmetric difference f(xk + ck*Deltak) - f(xk - ck*Deltak), where the evaluation step size ck is scaled according ck = c/(k+1)**gamma. The algorithm takes a step of size ak = a/(0.01*niter+k+1)**alpha along the negative gradient. See Spall, IEEE, 1998, 34, 817-823 for guidelines about how to choose the algorithm's parameters (a, alpha, c, gamma). Parameters ---------- func: callable objective function to be minimized: called as `func(x, *args)`, if `paired=True`, then called with keyword argument `seed` additionally x0: array-like initial guess for parameters args: tuple extra arguments to be supplied to func bounds: array-like bounds on the variables niter: int number of iterations after which to terminate the algorithm paired: boolean calculate gradient for same random seeds a: float scaling parameter for step size alpha: float scaling exponent for step size c: float scaling parameter for evaluation step size gamma: float scaling exponent for evaluation step size disp: boolean whether to output status updates during the optimization callback: callable called after each iteration, as callback(xk), where xk are the current parameters Returns ------- `scipy.optimize.OptimizeResult` object """ A = 0.01 * niter if bounds is not None: bounds = np.asarray(bounds) project = lambda x: np.clip(x, bounds[:, 0], bounds[:, 1]) if args is not None: # freeze function arguments def funcf(x, **kwargs): return func(x, *args, **kwargs) N = len(x0) x = x0 for k
python
{ "resource": "" }
q9897
bisect
train
def bisect(func, a, b, xtol=1e-6, errorcontrol=True, testkwargs=dict(), outside='extrapolate', ascending=None, disp=False): """Find root by bysection search. If the function evaluation is noisy then use `errorcontrol=True` for adaptive sampling of the function during the bisection search. Parameters ---------- func: callable Function of which the root should be found. If `errorcontrol=True` then the function should be derived from `AverageBase`. a, b: float initial interval xtol: float target tolerance for interval size errorcontrol: boolean if true, assume that function is derived from `AverageBase`. testkwargs: only for `errorcontrol=True` see `AverageBase.test0` outside: ['extrapolate', 'raise'] How to handle the case where f(a) and f(b) have same sign, i.e. where the root lies outside of the interval. If 'raise' throws a `BisectException`. ascending: allow passing in directly whether function is ascending or not if ascending=True then it is assumed without check that f(a) < 0 and f(b) > 0 if ascending=False then it is assumed without check that f(a) > 0 and f(b) < 0 Returns ------- float, root of function """ search = True # check whether function is ascending or not if ascending is None: if errorcontrol: testkwargs.update(dict(type_='smaller', force=True)) fa = func.test0(a, **testkwargs) fb = func.test0(b, **testkwargs) else: fa = func(a) < 0 fb = func(b) < 0 if fa and not fb: ascending = True elif fb and not fa: ascending = False else: if disp: print('Warning: func(a) and func(b) do not have opposing signs -> no search done')
python
{ "resource": "" }
q9898
AveragedFunction.diffse
train
def diffse(self, x1, x2): """Standard error of the difference between the function values at x1 and x2""" f1, f1se = self(x1) f2, f2se = self(x2) if self.paired: fx1 = np.array(self.cache[tuple(x1)]) fx2 =
python
{ "resource": "" }
q9899
alphanum_order
train
def alphanum_order(triples): """ Sort a list of triples by relation name. Embedded integers are sorted numerically, but otherwise the sorting is alphabetic. """ return sorted( triples, key=lambda
python
{ "resource": "" }