Search is not available for this dataset
text
stringlengths
75
104k
def export(self): """ This method deactivates the security context for the calling process and returns an interprocess token which, when passed to :meth:`imprt` in another process, will re-activate the context in the second process. Only a single instantiation of a given context may be ...
def imprt(import_token): """ This is the corresponding method to :meth:`export`, used to import a saved context token from another process into this one and construct a :class:`Context` object from it. :param import_token: a token obtained from the :meth:`export` of another context ...
def lifetime(self): """ The lifetime of the context in seconds (only valid after :meth:`step` has been called). If the context does not have a time limit on its validity, this will be :const:`gssapi.C_INDEFINITE` """ minor_status = ffi.new('OM_uint32[1]') lifetim...
def delete(self): """ Delete a security context. This method will delete the local data structures associated with the specified security context, and may return an output token, which when passed to :meth:`process_context_token` on the peer may instruct it to also delete its context. ...
def step(self, input_token=None): """Performs a step to establish the context as an initiator. This method should be called in a loop and fed input tokens from the acceptor, and its output tokens should be sent to the acceptor, until this context's :attr:`established` attribute is True....
def step(self, input_token): """Performs a step to establish the context as an acceptor. This method should be called in a loop and fed input tokens from the initiator, and its output tokens should be sent to the initiator, until this context's :attr:`established` attribute is True. ...
def mechs(self): """ The set of mechanisms supported by the credential. :type: :class:`~gssapi.oids.OIDSet` """ if not self._mechs: self._mechs = self._inquire(False, False, False, True)[3] return self._mechs
def export(self): """ Serializes this credential into a byte string, which can be passed to :meth:`imprt` in another process in order to deserialize the byte string back into a credential. Exporting a credential does not destroy it. :returns: The serialized token representation ...
def imprt(cls, token): """ Deserializes a byte string token into a :class:`Credential` object. The token must have previously been exported by the same GSSAPI implementation as is being used to import it. :param token: A token previously obtained from the :meth:`export` of another ...
def store(self, usage=None, mech=None, overwrite=False, default=False, cred_store=None): """ Stores this credential into a 'credential store'. It can either store this credential in the default credential store, or into a specific credential store specified by a set of mechanism-specific...
def get_all_mechs(): """ Return an :class:`OIDSet` of all the mechanisms supported by the underlying GSSAPI implementation. """ minor_status = ffi.new('OM_uint32[1]') mech_set = ffi.new('gss_OID_set[1]') try: retval = C.gss_indicate_mechs(minor_status, mech_set) if GSS_ERROR(...
def mech_from_string(input_string): """ Takes a string form of a mechanism OID, in dot-separated: "1.2.840.113554.1.2.2" or numeric ASN.1: "{1 2 840 113554 1 2 2}" notation, and returns an :class:`OID` object representing the mechanism, which can be passed to other GSSAPI methods. ...
def singleton_set(cls, single_oid): """ Factory function to create a new :class:`OIDSet` with a single member. :param single_oid: the OID to use as a member of the new set :type single_oid: :class:`OID` :returns: an OID set with the OID passed in as the only member :rtyp...
def add(self, new_oid): """ Adds another :class:`OID` to this set. :param new_oid: the OID to add. :type new_oid: :class:`OID` """ if self._oid_set[0]: oid_ptr = None if isinstance(new_oid, OID): oid_ptr = ffi.addressof(new_oid._oi...
def main(properties=properties, options=options, **custom_options): """Imports and runs setup function with given properties.""" return init(**dict(options, **custom_options))(**properties)
def init( dist='dist', minver=None, maxver=None, use_markdown_readme=True, use_stdeb=False, use_distribute=False, ): """Imports and returns a setup function. If use_markdown_readme is set, then README.md is added to setuptools READMES list. If use_stdeb is set on a Debian b...
def main(context=None, *args, **kwargs): """ kwargs: 'command_publish_address': in the form of `tcp://*:5555` or any other zeromq address format. IE `ipc://*:5555` 'command_subscribe_address': in the form of `tcp://*:5555` or any other zeromq address format. IE `ipc://*:5555` ...
def _create_file(): """ Returns a file handle which is used to record audio """ f = wave.open('audio.wav', mode='wb') f.setnchannels(2) p = pyaudio.PyAudio() f.setsampwidth(p.get_sample_size(pyaudio.paInt16)) f.setframerate(p.get_default_input_device_info()['defaultSampleRate']) try:...
def get_devices(self, device_type='all'): num_devices = self._pyaudio.get_device_count() self._logger.debug('Found %d PyAudio devices', num_devices) for i in range(num_devices): info = self._pyaudio.get_device_info_by_index(i) name = info['name'] if name in se...
def open_stream(self, bits, channels, rate=None, chunksize=1024, output=True): if rate is None: rate = int(self.info['defaultSampleRate']) # Check if format is supported is_supported_...
def djfrontend_h5bp_css(version=None): """ Returns HTML5 Boilerplate CSS file. Included in HTML5 Boilerplate. """ if version is None: version = getattr(settings, 'DJFRONTEND_H5BP_CSS', DJFRONTEND_H5BP_CSS_DEFAULT) return format_html( '<link rel="stylesheet" href="{0}djfrontend/c...
def djfrontend_normalize(version=None): """ Returns Normalize CSS file. Included in HTML5 Boilerplate. """ if version is None: version = getattr(settings, 'DJFRONTEND_NORMALIZE', DJFRONTEND_NORMALIZE_DEFAULT) return format_html( '<link rel="stylesheet" href="{0}djfrontend/css/no...
def djfrontend_fontawesome(version=None): """ Returns Font Awesome CSS file. TEMPLATE_DEBUG returns full file, otherwise returns minified file. """ if version is None: version = getattr(settings, 'DJFRONTEND_FONTAWESOME', DJFRONTEND_FONTAWESOME_DEFAULT) return format_html( '<lin...
def djfrontend_modernizr(version=None): """ Returns Modernizr JavaScript file according to version number. TEMPLATE_DEBUG returns full file, otherwise returns minified file. Included in HTML5 Boilerplate. """ if version is None: version = getattr(settings, 'DJFRONTEND_MODERNIZR', DJFRONT...
def djfrontend_jquery(version=None): """ Returns jQuery JavaScript file according to version number. TEMPLATE_DEBUG returns full file, otherwise returns minified file from Google CDN with local fallback. Included in HTML5 Boilerplate. """ if version is None: version = getattr(settings, '...
def djfrontend_jqueryui(version=None): """ Returns the jQuery UI plugin file according to version number. TEMPLATE_DEBUG returns full file, otherwise returns minified file from Google CDN with local fallback. """ if version is None: version = getattr(settings, 'DJFRONTEND_JQUERYUI', DJFRONTE...
def djfrontend_jquery_datatables(version=None): """ Returns the jQuery DataTables plugin file according to version number. TEMPLATE_DEBUG returns full file, otherwise returns minified file. """ if version is None: if not getattr(settings, 'DJFRONTEND_JQUERY_DATATABLES', False): v...
def djfrontend_jquery_datatables_css(version=None): """ Returns the jQuery DataTables CSS file according to version number. """ if version is None: if not getattr(settings, 'DJFRONTEND_JQUERY_DATATABLES_CSS', False): version = getattr(settings, 'DJFRONTEND_JQUERY_DATATABLES_VERSION',...
def djfrontend_jquery_datatables_themeroller(version=None): """ Returns the jQuery DataTables ThemeRoller CSS file according to version number. """ if version is None: if not getattr(settings, 'DJFRONTEND_JQUERY_DATATABLES_THEMEROLLER', False): version = getattr(settings, 'DJFRONTEND...
def djfrontend_jquery_formset(version=None): """ Returns the jQuery Dynamic Formset plugin file according to version number. TEMPLATE_DEBUG returns full file, otherwise returns minified file. """ if version is None: version = getattr(settings, 'DJFRONTEND_JQUERY_FORMSET', DJFRONTEND_JQUERY_F...
def djfrontend_jquery_scrollto(version=None): """ Returns the jQuery ScrollTo plugin file according to version number. TEMPLATE_DEBUG returns full file, otherwise returns minified file. """ if version is None: version = getattr(settings, 'DJFRONTEND_JQUERY_SCROLLTO', DJFRONTEND_JQUERY_SCROLL...
def djfrontend_jquery_smoothscroll(version=None): """ Returns the jQuery Smooth Scroll plugin file according to version number. TEMPLATE_DEBUG returns full file, otherwise returns minified file. """ if version is None: version = getattr(settings, 'DJFRONTEND_JQUERY_SMOOTHSCROLL', DJFRONTEND_...
def djfrontend_twbs_css(version=None): """ Returns Twitter Bootstrap CSS file. TEMPLATE_DEBUG returns full file, otherwise returns minified file. """ if version is None: if not getattr(settings, 'DJFRONTEND_TWBS_CSS', False): version = getattr(settings, 'DJFRONTEND_TWBS_VERSION',...
def djfrontend_twbs_js(version=None, files=None): """ Returns Twitter Bootstrap JavaScript file(s). all returns concatenated file; full file for TEMPLATE_DEBUG, minified otherwise. Other choice are: affix, alert, button, carousel, collapse, dropdown, ...
def djfrontend_ga(account=None): """ Returns Google Analytics asynchronous snippet. Use DJFRONTEND_GA_SETDOMAINNAME to set domain for multiple, or cross-domain tracking. Set DJFRONTEND_GA_SETALLOWLINKER to use _setAllowLinker method on target site for cross-domain tracking. Included in HTML5 Boilerp...
def render(self, name, value, attrs=None): u"""Render CodeMirrorTextarea""" if self.js_var_format is not None: js_var_bit = 'var %s = ' % (self.js_var_format % name) else: js_var_bit = '' output = [super(CodeMirrorTextarea, self).render(name, value, attrs), ...
def iter_auth_hashes(user, purpose, minutes_valid): """ Generate auth tokens tied to user and specified purpose. The hash expires at midnight on the minute of now + minutes_valid, such that when minutes_valid=1 you get *at least* 1 minute to use the token. """ now = timezone.now().replace(micro...
def calc_expiry_time(minutes_valid): """Return specific time an auth_hash will expire.""" return ( timezone.now() + datetime.timedelta(minutes=minutes_valid + 1) ).replace(second=0, microsecond=0)
def get_user_token(user, purpose, minutes_valid): """Return login token info for given user.""" token = ''.join( dumps([ user.get_username(), get_auth_hash(user, purpose), ]).encode('base64').split('\n') ) return { 'id': get_meteor_id(user), 'token...
def serialize(self, obj, *args, **kwargs): """Serialize user as per Meteor accounts serialization.""" # use default serialization, then modify to suit our needs. data = super(Users, self).serialize(obj, *args, **kwargs) # everything that isn't handled explicitly ends up in `profile` ...
def deserialize_profile(profile, key_prefix='', pop=False): """De-serialize user profile fields into concrete model fields.""" result = {} if pop: getter = profile.pop else: getter = profile.get def prefixed(name): """Return name prefixed by `...
def update(self, selector, update, options=None): """Update user data.""" # we're ignoring the `options` argument at this time del options user = get_object( self.model, selector['_id'], pk=this.user_id, ) profile_update = self.deserialize_profile(...
def user_factory(self): """Retrieve the current user (or None) from the database.""" if this.user_id is None: return None return self.user_model.objects.get(pk=this.user_id)
def update_subs(new_user_id): """Update subs to send added/removed for collections with user_rel.""" for sub in Subscription.objects.filter(connection=this.ws.connection): params = loads(sub.params_ejson) pub = API.get_pub_by_name(sub.publication) # calculate the que...
def auth_failed(**credentials): """Consistent fail so we don't provide attackers with valuable info.""" if credentials: user_login_failed.send_robust( sender=__name__, credentials=auth._clean_credentials(credentials), ) raise MeteorError(40...
def validated_user(cls, token, purpose, minutes_valid): """Resolve and validate auth token, returns user object.""" try: username, auth_hash = loads(token.decode('base64')) except (ValueError, Error): cls.auth_failed(token=token) try: user = cls.user_m...
def check_secure(): """Check request, return False if using SSL or local connection.""" if this.request.is_secure(): return True # using SSL elif this.request.META['REMOTE_ADDR'] in [ 'localhost', '127.0.0.1', ]: return True # loc...
def get_username(self, user): """Retrieve username from user selector.""" if isinstance(user, basestring): return user elif isinstance(user, dict) and len(user) == 1: [(key, val)] = user.items() if key == 'username' or (key == self.user_model.USERNAME_FIELD): ...
def create_user(self, params): """Register a new user account.""" receivers = create_user.send( sender=__name__, request=this.request, params=params, ) if len(receivers) == 0: raise NotImplementedError( 'Handler for `create_...
def do_login(self, user): """Login a user.""" this.user_id = user.pk this.user_ddp_id = get_meteor_id(user) # silent subscription (sans sub/nosub msg) to LoggedInUser pub this.user_sub_id = meteor_random_id() API.do_sub(this.user_sub_id, 'LoggedInUser', silent=True) ...
def do_logout(self): """Logout a user.""" # silent unsubscription (sans sub/nosub msg) from LoggedInUser pub API.do_unsub(this.user_sub_id, silent=True) del this.user_sub_id self.update_subs(None) user_logged_out.send( sender=self.user_model, request=this.requ...
def login(self, params): """Login either with resume token or password.""" if 'password' in params: return self.login_with_password(params) elif 'resume' in params: return self.login_with_resume_token(params) else: self.auth_failed(**params)
def login_with_password(self, params): """Authenticate using credentials supplied in params.""" # never allow insecure login self.check_secure() username = self.get_username(params['user']) password = self.get_password(params['password']) user = auth.authenticate(userna...
def login_with_resume_token(self, params): """ Login with existing resume token. Either the token is valid and the user is logged in, or the token is invalid and a non-specific ValueError("Login failed.") exception is raised - don't be tempted to give clues to attackers as to wh...
def change_password(self, old_password, new_password): """Change password.""" try: user = this.user except self.user_model.DoesNotExist: self.auth_failed() user = auth.authenticate( username=user.get_username(), password=self.get_password(o...
def forgot_password(self, params): """Request password reset email.""" username = self.get_username(params) try: user = self.user_model.objects.get(**{ self.user_model.USERNAME_FIELD: username, }) except self.user_model.DoesNotExist: se...
def reset_password(self, token, new_password): """Reset password using a token received in email then logs user in.""" user = self.validated_user( token, purpose=HashPurpose.PASSWORD_RESET, minutes_valid=HASH_MINUTES_VALID[HashPurpose.PASSWORD_RESET], ) user.set_p...
def dict_merge(lft, rgt): """ Recursive dict merge. Recursively merges dict's. not just simple lft['key'] = rgt['key'], if both lft and rgt have a key who's value is a dict then dict_merge is called on both values and the result stored in the returned dictionary. """ if not isinstance(rgt, ...
def read(path, default=None, encoding='utf8'): """Read encoded contents from specified path or return default.""" if not path: return default try: with io.open(path, mode='r', encoding=encoding) as contents: return contents.read() except IOError: if default is not Non...
def get(self, request, path): """Return HTML (or other related content) for Meteor.""" if path == 'meteor_runtime_config.js': config = { 'DDP_DEFAULT_CONNECTION_URL': request.build_absolute_uri('/'), 'PUBLIC_SETTINGS': self.meteor_settings.get('public', {}), ...
def get_meteor_id(obj_or_model, obj_pk=None): """Return an Alea ID for the given object.""" if obj_or_model is None: return None # Django model._meta is now public API -> pylint: disable=W0212 meta = obj_or_model._meta model = meta.model if model is ObjectMapping: # this doesn't ...
def get_meteor_ids(model, object_ids): """Return Alea ID mapping for all given ids of specified model.""" # Django model._meta is now public API -> pylint: disable=W0212 meta = model._meta result = collections.OrderedDict( (str(obj_pk), None) for obj_pk in object_ids ) if...
def get_object_id(model, meteor_id): """Return an object ID for the given meteor_id.""" if meteor_id is None: return None # Django model._meta is now public API -> pylint: disable=W0212 meta = model._meta if model is ObjectMapping: # this doesn't make sense - raise TypeError ...
def get_object_ids(model, meteor_ids): """Return all object IDs for the given meteor_ids.""" if model is ObjectMapping: # this doesn't make sense - raise TypeError raise TypeError("Can't map ObjectMapping instances through self.") # Django model._meta is now public API -> pylint: disable=W02...
def get_object(model, meteor_id, *args, **kwargs): """Return an object for the given meteor_id.""" # Django model._meta is now public API -> pylint: disable=W0212 meta = model._meta if isinstance(meta.pk, AleaIdField): # meteor_id is the primary key return model.objects.filter(*args, **k...
def get_pk_value_on_save(self, instance): """Generate ID if required.""" value = super(AleaIdField, self).get_pk_value_on_save(instance) if not value: value = self.get_seeded_value(instance) return value
def pre_save(self, model_instance, add): """Generate ID if required.""" value = super(AleaIdField, self).pre_save(model_instance, add) if (not value) and self.default in (meteor_random_id, NOT_PROVIDED): value = self.get_seeded_value(model_instance) setattr(model_instance...
def set_default_forwards(app_name, operation, apps, schema_editor): """Set default value for AleaIdField.""" model = apps.get_model(app_name, operation.model_name) for obj_pk in model.objects.values_list('pk', flat=True): model.objects.filter(pk=obj_pk).update(**{ operation.name: get_met...
def set_default_reverse(app_name, operation, apps, schema_editor): """Unset default value for AleaIdField.""" model = apps.get_model(app_name, operation.model_name) for obj_pk in model.objects.values_list('pk', flat=True): get_meteor_id(model, obj_pk)
def truncate(self, app_label, schema_editor, models): """Truncate tables.""" for model_name in models: model = '%s_%s' % (app_label, model_name) schema_editor.execute( 'TRUNCATE TABLE %s RESTART IDENTITY CASCADE' % ( model.lower(), ...
def database_forwards(self, app_label, schema_editor, from_state, to_state): """Use schema_editor to apply any forward changes.""" self.truncate(app_label, schema_editor, self.truncate_forwards)
def database_backwards(self, app_label, schema_editor, from_state, to_state): """Use schema_editor to apply any reverse changes.""" self.truncate(app_label, schema_editor, self.truncate_backwards)
def initialize_options(self): """Set command option defaults.""" setuptools.command.build_py.build_py.initialize_options(self) self.meteor = 'meteor' self.meteor_debug = False self.build_lib = None self.package_dir = None self.meteor_builds = [] self.no_pr...
def finalize_options(self): """Update command options.""" # Get all the information we need to install pure Python modules # from the umbrella 'install' command -- build (source) directory, # install (target) directory, and whether to compile .py files. self.set_undefined_options...
def run(self): """Peform build.""" for (package, source, target, extra_args) in self.meteor_builds: src_dir = self.get_package_dir(package) # convert UNIX-style paths to directory names project_dir = self.path_to_dir(src_dir, source) target_dir = self.path...
def path_to_dir(*path_args): """Convert a UNIX-style path into platform specific directory spec.""" return os.path.join( *list(path_args[:-1]) + path_args[-1].split(posixpath.sep) )
def seed(self, values): """Seed internal state from supplied values.""" if not values: # Meteor uses epoch seconds as the seed if no args supplied, we use # a much more secure seed by default to avoid hash collisions. seed_ids = [int, str, random, self, values, self._...
def state(self): """Return internal state, useful for testing.""" return {'c': self.c, 's0': self.s0, 's1': self.s1, 's2': self.s2}
def random_string(self, length, alphabet): """Return string of `length` elements chosen from `alphabet`.""" return ''.join( self.choice(alphabet) for n in range(length) )
def api_endpoint(path_or_func=None, decorate=True): """ Decorator to mark a method as an API endpoint for later registration. Args: path_or_func: either the function to be decorated or its API path. decorate (bool): Apply API_ENDPOINT_DECORATORS if True (default). Returns: Call...
def api_endpoints(obj): """Iterator over all API endpoint names and callbacks.""" for name in dir(obj): attr = getattr(obj, name) api_path = getattr(attr, 'api_path', None) if api_path: yield ( '%s%s' % (obj.api_path_prefix, api_path), attr, ...
def api_path_map(self): """Cached dict of api_path: func.""" if self._api_path_cache is None: self._api_path_cache = { api_path: func for api_path, func in api_endpoints(self) } return self._api_path_cache
def clear_api_path_map_cache(self): """Clear out cache for api_path_map.""" self._api_path_cache = None for api_provider in self.api_providers: if six.get_method_self( api_provider.clear_api_path_map_cache, ) is not None: api_provider.clear...
def safe_call(func, *args, **kwargs): """ Call `func(*args, **kwargs)` but NEVER raise an exception. Useful in situations such as inside exception handlers where calls to `logging.error` try to send email, but the SMTP server isn't always availalbe and you don't want your exception handler blowing ...
def dprint(name, val): """Debug print name and val.""" from pprint import pformat print( '% 5s: %s' % ( name, '\n '.join( pformat( val, indent=4, width=75, ).split('\n') ), ), )
def validate_kwargs(func, kwargs): """Validate arguments to be supplied to func.""" func_name = func.__name__ argspec = inspect.getargspec(func) all_args = argspec.args[:] defaults = list(argspec.defaults or []) # ignore implicit 'self' argument if inspect.ismethod(func) and all_args[:1] ==...
def on_open(self): """Handle new websocket connection.""" this.request = WSGIRequest(self.ws.environ) this.ws = self this.send = self.send this.reply = self.reply self.logger = self.ws.logger self.remote_ids = collections.defaultdict(set) # `_tx_buffer` ...
def on_close(self, *args, **kwargs): """Handle closing of websocket connection.""" if self.connection is not None: del self.pgworker.connections[self.connection.pk] self.connection.delete() self.connection = None signals.request_finished.send(sender=self.__cla...
def on_message(self, message): """Process a message received from remote.""" if self.ws.closed: return None try: safe_call(self.logger.debug, '< %s %r', self, message) # process individual messages for data in self.ddp_frames_from_message(message)...
def ddp_frames_from_message(self, message): """Yield DDP messages from a raw WebSocket message.""" # parse message set try: msgs = ejson.loads(message) except ValueError: self.reply( 'error', error=400, reason='Data is not valid EJSON', ...
def process_ddp(self, data): """Process a single DDP message.""" msg_id = data.get('id', None) try: msg = data.pop('msg') except KeyError: self.reply( 'error', reason='Bad request', offendingMessage=data, ) r...
def dispatch(self, msg, kwargs): """Dispatch msg to appropriate recv_foo handler.""" # enforce calling 'connect' first if self.connection is None and msg != 'connect': self.reply('error', reason='Must connect first') return if msg == 'method': if ( ...
def send(self, data, tx_id=None): """Send `data` (raw string or EJSON payload) to WebSocket client.""" # buffer data until we get pre-requisite data if tx_id is None: tx_id = self.get_tx_id() self._tx_buffer[tx_id] = data # de-queue messages from buffer while...
def recv_connect(self, version=None, support=None, session=None): """DDP connect handler.""" del session # Meteor doesn't even use this! if self.connection is not None: raise MeteorError( 400, 'Session already established.', self.connection.connection...
def recv_ping(self, id_=None): """DDP ping handler.""" if id_ is None: self.reply('pong') else: self.reply('pong', id=id_)
def recv_sub(self, id_, name, params): """DDP sub handler.""" self.api.sub(id_, name, *params)
def recv_unsub(self, id_=None): """DDP unsub handler.""" if id_: self.api.unsub(id_) else: self.reply('nosub')
def recv_method(self, method, params, id_, randomSeed=None): """DDP method handler.""" if randomSeed is not None: this.random_streams.random_seed = randomSeed this.alea_random = alea.Alea(randomSeed) self.api.method(method, params, id_) self.reply('updated', metho...
def ddpp_sockjs_info(environ, start_response): """Inform client that WebSocket service is available.""" import random import ejson start_response( '200 OK', [ ('Content-Type', 'application/json; charset=UTF-8'), ] + common_headers(environ), ) yield ejson.dump...
def addr(val, default_port=8000, defualt_host='localhost'): """ Convert a string of format host[:port] into Addr(host, port). >>> addr('0:80') Addr(host='0', port=80) >>> addr('127.0.0.1:80') Addr(host='127.0.0.1', port=80) >>> addr('0.0.0.0', default_port=8000) Addr(host='0.0.0.0', p...