INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Use an event to build a one - to - many relationship on a class.
def one_to_many(clsname, **kw): """Use an event to build a one-to-many relationship on a class. This makes use of the :meth:`.References._reference_table` method to generate a full foreign key relationship from the remote table. """ @declared_attr def o2m(cls): cls._references((clsname...
Djeffifies string_to_djeff
def djeffify_string(string_to_djeff): """ Djeffifies string_to_djeff """ string_to_djeff = re.sub(r'^(?=[jg])', 'd', string_to_djeff, flags=re.IGNORECASE) # first string_to_djeff = re.sub(r'[ ](?=[jg])', ' d', string_to_djeff, flags=re.IGNORECASE) # spaces string_to_djeff = re.sub(r'[\n](?=[jg...
Djeffify data between tags
def handle_data(self, data): """ Djeffify data between tags """ if data.strip(): data = djeffify_string(data) self.djhtml += data
Create a foreign key reference from the local class to the given remote table.
def _reference_table(cls, ref_table): """Create a foreign key reference from the local class to the given remote table. Adds column references to the declarative class and adds a ForeignKeyConstraint. """ # create pairs of (Foreign key column, primary key column) ...
Try to run __json__ on the given object. Raise TypeError is __json__ is missing
def __try_to_json(self, request, attr): """ Try to run __json__ on the given object. Raise TypeError is __json__ is missing :param request: Pyramid Request object :type request: <Request> :param obj: Object to JSONify :type obj: any object that has __json__ metho...
Path join helper method Join paths if list passed
def prepare_path(path): """ Path join helper method Join paths if list passed :type path: str|unicode|list :rtype: str|unicode """ if type(path) == list: return os.path.join(*path) return path
Read helper method
def read_from_file(file_path, encoding="utf-8"): """ Read helper method :type file_path: str|unicode :type encoding: str|unicode :rtype: str|unicode """ with codecs.open(file_path, "r", encoding) as f: return f.read()
Write helper method
def write_to_file(file_path, contents, encoding="utf-8"): """ Write helper method :type file_path: str|unicode :type contents: str|unicode :type encoding: str|unicode """ with codecs.open(file_path, "w", encoding) as f: f.write(contents)
Copy file helper method
def copy_file(src, dest): """ Copy file helper method :type src: str|unicode :type dest: str|unicode """ dir_path = os.path.dirname(dest) if not os.path.exists(dir_path): os.makedirs(dir_path) shutil.copy2(src, dest)
Split file name and extension
def get_path_extension(path): """ Split file name and extension :type path: str|unicode :rtype: one str|unicode """ file_path, file_ext = os.path.splitext(path) return file_ext.lstrip('.')
Helper method for absolute and relative paths resolution Split passed path and return each directory parts
def split_path(path): """ Helper method for absolute and relative paths resolution Split passed path and return each directory parts example: "/usr/share/dir" return: ["usr", "share", "dir"] @type path: one of (unicode, str) @rtype: list """ resu...
Creates fully qualified endpoint URIs.
def _create_api_uri(self, *parts): """Creates fully qualified endpoint URIs. :param parts: the string parts that form the request URI """ return urljoin(self.API_URI, '/'.join(map(quote, parts)))
Makes sure we have proper ISO 8601 time.
def _format_iso_time(self, time): """Makes sure we have proper ISO 8601 time. :param time: either already ISO 8601 a string or datetime.datetime :returns: ISO 8601 time :rtype: str """ if isinstance(time, str): return time elif isinstance(time, datetime): return time.strftime('...
Returns the given response or raises an APIError for non - 2xx responses.
def _handle_response(self, response): """Returns the given response or raises an APIError for non-2xx responses. :param requests.Response response: HTTP response :returns: requested data :rtype: requests.Response :raises APIError: for non-2xx responses """ if not str(response.status_code)....
Checks if a next message is possible.
def _check_next(self): """Checks if a next message is possible. :returns: True if a next message is possible, otherwise False :rtype: bool """ if self.is_initial: return True if self.before: if self.before_cursor: return True else: return False else: ...
Colors text with code and given format
def _wrap_color(self, code, text, format=None, style=None): """ Colors text with code and given format """ color = None if code[:3] == self.bg.PREFIX: color = self.bg.COLORS.get(code, None) if not color: color = self.fg.COLORS.get(code, None) if not color...
Registers the given message type in the local database.
def RegisterMessage(self, message): """Registers the given message type in the local database. Args: message: a message.Message, to be registered. Returns: The provided message. """ desc = message.DESCRIPTOR self._symbols[desc.full_name] = message if desc.file.name not in self...
Gets all the messages from a specified file.
def GetMessages(self, files): """Gets all the messages from a specified file. This will find and resolve dependencies, failing if they are not registered in the symbol database. Args: files: The file names to extract messages from. Returns: A dictionary mapping proto names to the mes...
Insert object before index.
def insert(self, index, value): """ Insert object before index. :param int index: index to insert in :param string value: path to insert """ self._list.insert(index, value) self._sync()
Parse runtime path representation to list.
def parse(self, string): """ Parse runtime path representation to list. :param string string: runtime path string :return: list of runtime paths :rtype: list of string """ var, eq, values = string.strip().partition('=') assert var == 'runtimepath' ...
Add some bundle to build group
def add_bundle(self, *args): """ Add some bundle to build group :type bundle: static_bundle.bundles.AbstractBundle @rtype: BuildGroup """ for bundle in args: if not self.multitype and self.has_bundles(): first_bundle = self.get_first_bundle() ...
Return collected files links
def collect_files(self): """ Return collected files links :rtype: list[static_bundle.files.StaticFileResult] """ self.files = [] for bundle in self.bundles: bundle.init_build(self, self.builder) bundle_files = bundle.prepare() self.fil...
Asset minifier Uses default minifier in bundle if it s not defined
def get_minifier(self): """ Asset minifier Uses default minifier in bundle if it's not defined :rtype: static_bundle.minifiers.DefaultMinifier|None """ if self.minifier is None: if not self.has_bundles(): raise Exception("Unable to get default...
Create asset
def create_asset(self, name, **kwargs): """ Create asset :type name: unicode|str :rtype: Asset """ asset = Asset(self, name, **kwargs) self.assets[name] = asset return asset
Render all includes in asset by names
def render_asset(self, name): """ Render all includes in asset by names :type name: str|unicode :rtype: str|unicode """ result = "" if self.has_asset(name): asset = self.get_asset(name) if asset.files: for f in asset.files:...
Return links without build files
def collect_links(self, env=None): """ Return links without build files """ for asset in self.assets.values(): if asset.has_bundles(): asset.collect_files() if env is None: env = self.config.env if env == static_bundle.ENV_PRODUCTIO...
Move files/ make static build
def make_build(self): """ Move files / make static build """ for asset in self.assets.values(): if asset.has_bundles(): asset.collect_files() if not os.path.exists(self.config.output_dir): os.makedirs(self.config.output_dir) if self...
Clear build output dir: type exclude: list|None
def clear(self, exclude=None): """ Clear build output dir :type exclude: list|None """ exclude = exclude or [] for root, dirs, files in os.walk(self.config.output_dir): for f in files: if f not in exclude: os.unlink(os.path....
Coerce everything to strings. All objects representing time get output according to default_date_fmt.
def _default_json_default(obj): """ Coerce everything to strings. All objects representing time get output according to default_date_fmt. """ if isinstance(obj, (datetime.datetime, datetime.date, datetime.time)): return obj.strftime(default_date_fmt) else: return str(obj)
Initialize the zlogger.
def init_logs(path=None, target=None, logger_name='root', level=logging.DEBUG, maxBytes=1*1024*1024, backupCount=5, application_name='default', server_hostname=None, fields=None): """Initialize the zlogge...
formats a logging. Record into a standard json log entry
def format(self, record): """formats a logging.Record into a standard json log entry :param record: record to be formatted :type record: logging.Record :return: the formatted json string :rtype: string """ record_fields = record.__dict__.copy() self._set...
Initialize the model for a Pyramid app.
def includeme(config): """ Initialize the model for a Pyramid app. Activate this setup using ``config.include('baka_model')``. """ settings = config.get_settings() should_create = asbool(settings.get('baka_model.should_create_all', False)) should_drop = asbool(settings.get('baka_model.shou...
validate the passed values in kwargs based on the collection store them in the mongodb collection
def store( self, collection, **kwargs ): ''' validate the passed values in kwargs based on the collection, store them in the mongodb collection ''' key = validate( collection, **kwargs ) if self.fetch( collection, **{ key : kwargs[key] } ): raise Proauth2Error...
Return absolute and relative path for file
def get_abs_and_rel_paths(self, root_path, file_name, input_dir): """ Return absolute and relative path for file :type root_path: str|unicode :type file_name: str|unicode :type input_dir: str|unicode :rtype: tuple """ # todo: change relative path resolvi...
: inheritdoc
def get_files(self): """ :inheritdoc """ assert self.bundle, 'Cannot fetch file name with empty bundle' abs_path, rel_path = self.get_abs_and_rel_paths(self.bundle.path, self.file_path, self.bundle.input_dir) file_cls = self.bundle.get_file_cls() return [file_cls(...
: inheritdoc
def get_files(self): """ :inheritdoc """ assert self.bundle, 'Cannot fetch directory name with empty bundle' result_files = [] bundle_ext = self.bundle.get_extension() ext = "." + bundle_ext if bundle_ext else None if self.directory_path == "": ...
Replicate an existing database to another existing database.
def replicate_existing(source_db, target_db): """Replicate an existing database to another existing database.""" # Get the server from which to manage the replication. server = shortcuts.get_server() logger = logging.getLogger('relax.couchdb.replicate') logger.debug('POST ' + urlparse.urljoin(server...
Generic Metropolis MCMC. Advances the chain by nsteps. Called by: func: mcmc: param adapt: enables adaptive stepwidth alteration ( converges ).
def mcmc_advance(start, stdevs, logp, nsteps = 1e300, adapt=True, callback=None): """ Generic Metropolis MCMC. Advances the chain by nsteps. Called by :func:`mcmc` :param adapt: enables adaptive stepwidth alteration (converges). """ import scipy from numpy import log import progressbar prob = logp(start) ...
** Metropolis Hastings MCMC **
def mcmc(transform, loglikelihood, parameter_names, nsteps=40000, nburn=400, stdevs=0.1, start = 0.5, **problem): """ **Metropolis Hastings MCMC** with automatic step width adaption. Burnin period is also used to guess steps. :param nburn: number of burnin steps :param stdevs: step widths to start with "...
** Ensemble MCMC ** via emcee <http:// dan. iel. fm/ emcee/ > _
def ensemble(transform, loglikelihood, parameter_names, nsteps=40000, nburn=400, start=0.5, **problem): """ **Ensemble MCMC** via `emcee <http://dan.iel.fm/emcee/>`_ """ import emcee import progressbar if 'seed' in problem: numpy.random.seed(problem['seed']) n_params = len(parameter_names) nwalkers = 50...
search monits or works classes. Class must have name attribute: param package_name: monits or works: param base_class: Monit or Work: return: tuple of tuples monit/ work - name and class
def _get_classes(package_name, base_class): """ search monits or works classes. Class must have 'name' attribute :param package_name: 'monits' or 'works' :param base_class: Monit or Work :return: tuple of tuples monit/work-name and class """ classes = {} ...
Adds an EnumDescriptor to the pool.
def AddEnumDescriptor(self, enum_desc): """Adds an EnumDescriptor to the pool. This method also registers the FileDescriptor associated with the message. Args: enum_desc: An EnumDescriptor. """ if not isinstance(enum_desc, descriptor.EnumDescriptor): raise TypeError('Expected instance...
Gets the FileDescriptor for the file containing the specified symbol.
def FindFileContainingSymbol(self, symbol): """Gets the FileDescriptor for the file containing the specified symbol. Args: symbol: The name of the symbol to search for. Returns: A FileDescriptor that contains the specified symbol. Raises: KeyError: if the file can not be found in th...
Loads the named descriptor from the pool.
def FindMessageTypeByName(self, full_name): """Loads the named descriptor from the pool. Args: full_name: The full name of the descriptor to load. Returns: The descriptor for the named type. """ full_name = _NormalizeFullyQualifiedName(full_name) if full_name not in self._descript...
Loads the named enum descriptor from the pool.
def FindEnumTypeByName(self, full_name): """Loads the named enum descriptor from the pool. Args: full_name: The full name of the enum descriptor to load. Returns: The enum descriptor for the named type. """ full_name = _NormalizeFullyQualifiedName(full_name) if full_name not in se...
Loads the named extension descriptor from the pool.
def FindExtensionByName(self, full_name): """Loads the named extension descriptor from the pool. Args: full_name: The full name of the extension descriptor to load. Returns: A FieldDescriptor, describing the named extension. """ full_name = _NormalizeFullyQualifiedName(full_name) m...
Make a protobuf EnumDescriptor given an EnumDescriptorProto protobuf.
def _ConvertEnumDescriptor(self, enum_proto, package=None, file_desc=None, containing_type=None, scope=None): """Make a protobuf EnumDescriptor given an EnumDescriptorProto protobuf. Args: enum_proto: The descriptor_pb2.EnumDescriptorProto protobuf message. package: Opt...
Creates a field descriptor from a FieldDescriptorProto.
def _MakeFieldDescriptor(self, field_proto, message_name, index, is_extension=False): """Creates a field descriptor from a FieldDescriptorProto. For message and enum type fields, this method will do a look up in the pool for the appropriate descriptor for that type. If it is ...
theoretically any data store can be implemented to work with this package which means basic data validation must be done in - package so that weird stuff can t be stored in the data store. this function raises an exception if an invalid table name is passed not all of the required fields are in the data kwargs or if a ...
def validate( table, **data ): ''' theoretically, any data store can be implemented to work with this package, which means basic data validation must be done in-package, so that weird stuff can't be stored in the data store. this function raises an exception if an invalid table name is passed, not ...
Record the results of this experiment by updating the tag.: param results: A dictionary containing the results of the experiment.: type results: dict
def record_results(self, results): """ Record the results of this experiment, by updating the tag. :param results: A dictionary containing the results of the experiment. :type results: dict """ repository = Repo(self.__repository_directory, search_parent_directories=True)...
Tag the current repository.: param data: a dictionary containing the data about the experiment: type data: dict
def __tag_repo(self, data, repository): """ Tag the current repository. :param data: a dictionary containing the data about the experiment :type data: dict """ assert self.__tag_name not in [t.name for t in repository.tags] return TagReference.create(repository, s...
: return: the files that have been modified and can be added
def __get_files_to_be_added(self, repository): """ :return: the files that have been modified and can be added """ for root, dirs, files in os.walk(repository.working_dir): for f in files: relative_path = os.path.join(root, f)[len(repository.working_dir) + 1:]...
Start an experiment by capturing the state of the code: param parameters: a dictionary containing the parameters of the experiment: type parameters: dict: return: the tag representing this experiment: rtype: TagReference
def __start_experiment(self, parameters): """ Start an experiment by capturing the state of the code :param parameters: a dictionary containing the parameters of the experiment :type parameters: dict :return: the tag representing this experiment :rtype: TagReference ...
Get a sqlalchemy. orm. Session instance backed by a transaction.
def get_tm_session(session_factory, transaction_manager): """ Get a ``sqlalchemy.orm.Session`` instance backed by a transaction. This function will hook the session to the transaction manager which will take care of committing any changes. - When using pyramid_tm it will automatically be committed...
run your main spider here and get a list/ tuple of url as result then make the instance of branch thread
def run(self): """run your main spider here, and get a list/tuple of url as result then make the instance of branch thread :return: None """ global existed_urls_list config = config_creator() debug = config.debug main_thread_sleep = config.main_thread_sle...
Copied ( and slightly adapted ) from pypi. description_tools
def pypi_render(source): """ Copied (and slightly adapted) from pypi.description_tools """ ALLOWED_SCHEMES = '''file ftp gopher hdl http https imap mailto mms news nntp prospero rsync rtsp rtspu sftp shttp sip sips snews svn svn+ssh telnet wais irc'''.split() settings_overrides = { ...
Generate a random string of the specified length.
def generate(length=DEFAULT_LENGTH): """ Generate a random string of the specified length. The returned string is composed of an alphabet that shouldn't include any characters that are easily mistakeable for one another (I, 1, O, 0), and hopefully won't accidentally contain any English-language cur...
Require that the named field has the right data_type
def require(name, field, data_type): """Require that the named `field` has the right `data_type`""" if not isinstance(field, data_type): msg = '{0} must have {1}, got: {2}'.format(name, data_type, field) raise AssertionError(msg)
Push a new msg onto the queue return ( success msg )
def _enqueue(self, msg): """Push a new `msg` onto the queue, return `(success, msg)`""" self.log.debug('queueing: %s', msg) if self.queue.full(): self.log.warn('librato_bg queue is full') return False, msg self.queue.put(msg) self.log.debug('enqueued %s....
Forces a flush from the internal queue to the server
def flush(self): """Forces a flush from the internal queue to the server""" queue = self.queue size = queue.qsize() queue.join() self.log.debug('successfully flushed %s items.', size)
Use all decompressor possible to make the stream
def open(name=None, fileobj=None, closefd=True): """ Use all decompressor possible to make the stream """ return Guesser().open(name=name, fileobj=fileobj, closefd=closefd)
Manage a Marv site
def marv(ctx, config, loglevel, logfilter, verbosity): """Manage a Marv site""" if config is None: cwd = os.path.abspath(os.path.curdir) while cwd != os.path.sep: config = os.path.join(cwd, 'marv.conf') if os.path.exists(config): break cwd = os...
This function returns a Pyramid WSGI application.
def main(global_config, **settings): """ This function returns a Pyramid WSGI application. """ set_cache_regions_from_settings(settings) config = Configurator(settings=settings) config.include('cms') config.configure_celery(global_config['__file__']) return config.make_wsgi_app()
Like _VarintDecoder () but decodes signed values.
def _SignedVarintDecoder(mask, result_type): """Like _VarintDecoder() but decodes signed values.""" def DecodeVarint(buffer, pos): result = 0 shift = 0 while 1: b = six.indexbytes(buffer, pos) result |= ((b & 0x7f) << shift) pos += 1 if not (b & 0x80): if result > 0x7fff...
Returns a decoder for a MessageSet item.
def MessageSetItemDecoder(extensions_by_number): """Returns a decoder for a MessageSet item. The parameter is the _extensions_by_number map for the message class. The message set message looks like this: message MessageSet { repeated group Item = 1 { required int32 type_id = 2; require...
Flask like implementation of getting the applicaiton name via the filename of the including file
def get_app_name(): """Flask like implementation of getting the applicaiton name via the filename of the including file """ fn = getattr(sys.modules['__main__'], '__file__', None) if fn is None: return '__main__' return os.path.splitext(os.path.basename(fn))[0]
Given a Python function name return the function it refers to.
def get_function(function_name): """ Given a Python function name, return the function it refers to. """ module, basename = str(function_name).rsplit('.', 1) try: return getattr(__import__(module, fromlist=[basename]), basename) except (ImportError, AttributeError): raise Functio...
Add a function to the function list in order.
def handle_add_fun(self, function_name): """Add a function to the function list, in order.""" function_name = function_name.strip() try: function = get_function(function_name) except Exception, exc: self.wfile.write(js_error(exc) + NEWLINE) return ...
Return the mapping of a document according to the function list.
def handle_map_doc(self, document): """Return the mapping of a document according to the function list.""" # This uses the stored set of functions, sorted by order of addition. for function in sorted(self.functions.values(), key=lambda x: x[0]): try: # It has to be ru...
Reduce several mapped documents by several reduction functions.
def handle_reduce(self, reduce_function_names, mapped_docs): """Reduce several mapped documents by several reduction functions.""" reduce_functions = [] # This gets a large list of reduction functions, given their names. for reduce_function_name in reduce_function_names: try:...
Re - reduce a set of values with a list of rereduction functions.
def handle_rereduce(self, reduce_function_names, values): """Re-reduce a set of values, with a list of rereduction functions.""" # This gets a large list of reduction functions, given their names. reduce_functions = [] for reduce_function_name in reduce_function_names: try: ...
Validate... this function is undocumented but still in CouchDB.
def handle_validate(self, function_name, new_doc, old_doc, user_ctx): """Validate...this function is undocumented, but still in CouchDB.""" try: function = get_function(function_name) except Exception, exc: self.log(repr(exc)) return False try: ...
The main function called to handle a request.
def handle(self): """The main function called to handle a request.""" while True: try: line = self.rfile.readline() try: # All input data are lines of JSON like the following: # ["<cmd_name>" "<cmd_arg1>" "<cmd_arg2>" ...
Log an event on the CouchDB server.
def log(self, string): """Log an event on the CouchDB server.""" self.wfile.write(json.dumps({'log': string}) + NEWLINE)
Generates a universally unique ID. Any arguments only create more randomness.
def guid(*args): """ Generates a universally unique ID. Any arguments only create more randomness. """ t = float(time.time() * 1000) r = float(random.random()*10000000000000) a = random.random() * 10000000000000 data = str(t) + ' ' + str(r) + ' ' + str(a) + ' ' + str(args) data = ha...
Return pages the GitModel knows about.: param int limit: The number of pages to return defaults to 5.: param tuple order_by: The attributes to order on defaults to ( position - modified_at )
def get_pages(self, limit=5, order_by=('position', '-modified_at')): """ Return pages the GitModel knows about. :param int limit: The number of pages to return, defaults to 5. :param tuple order_by: The attributes to order on, defaults to ('position', ...
Return featured pages the GitModel knows about.: param str locale: The locale string like eng_UK.: param int limit: The number of pages to return defaults to 5.: param tuple order_by: The attributes to order on defaults to ( position - modified_at ).
def get_featured_pages( self, limit=5, order_by=('position', '-modified_at')): """ Return featured pages the GitModel knows about. :param str locale: The locale string, like `eng_UK`. :param int limit: The number of pages to return, defaults to 5. ...
register_app takes an application name and redirect_uri It generates client_id ( client_key ) and client_secret then stores all of the above in the data_store and returns a dictionary containing the client_id and client_secret.
def register_app(self, name, redirect_uri, callback): ''' register_app takes an application name and redirect_uri It generates client_id (client_key) and client_secret, then stores all of the above in the data_store, and returns a dictionary containing the client_id and client_se...
request_authorization generates a nonce and stores it in the data_store along with the client_id user_id and expiration timestamp. It then returns a dictionary containing the nonce as code and the passed state. --- response_type MUST be code. this is directly from the OAuth2 spec. this probably doesn t need to be check...
def request_authorization(self, client_id, user_id, response_type, redirect_uri=None, scope=None, state=None, expires=600, callback=None): ''' request_authorization generates a nonce, and stores it in the data_store along with the clien...
request_access_token validates the client_id and client_secret using the provided method then generates an access_token stores it with the user_id from the nonce and returns a dictionary containing an access_token and bearer token. --- from the spec it looks like there are different types of tokens but i don t understa...
def request_access_token(self, client_id, key, code, grant_type, redirect_uri=None, method='direct_auth', callback=None): ''' request_access_token validates the client_id and client_secret, using the provided method, then generates an acc...
authenticate_token checks the passed token and returns the user_id it is associated with. it is assumed that this method won t be directly exposed to the oauth client but some kind of framework or wrapper. this allows the framework to have the user_id without doing additional DB calls.
def authenticate_token(self, token, callback): ''' authenticate_token checks the passed token and returns the user_id it is associated with. it is assumed that this method won't be directly exposed to the oauth client, but some kind of framework or wrapper. this allows the framew...
revoke_token removes the access token from the data_store
def revoke_token(self, token, callback): ''' revoke_token removes the access token from the data_store ''' yield Task(self.data_store.remove, 'tokens', token=token) callback()
_auth - internal method to ensure the client_id and client_secret passed with the nonce match
def _auth(self, client_id, key, method, callback): ''' _auth - internal method to ensure the client_id and client_secret passed with the nonce match ''' available = auth_methods.keys() if method not in available: raise Proauth2Error('invalid_request', ...
_validate_request_code - internal method for verifying the the given nonce. also removes the nonce from the data_store as they are intended for one - time use.
def _validate_request_code(self, code, client_id, callback): ''' _validate_request_code - internal method for verifying the the given nonce. also removes the nonce from the data_store, as they are intended for one-time use. ''' nonce = yield Task(self.data_store.fetch, 'n...
_generate_token - internal function for generating randomized alphanumberic strings of a given length
def _generate_token(self, length=32): ''' _generate_token - internal function for generating randomized alphanumberic strings of a given length ''' return ''.join(choice(ascii_letters + digits) for x in range(length))
Merge multiple ordered so that within - ordered order is preserved
def merge_ordered(ordereds: typing.Iterable[typing.Any]) -> typing.Iterable[typing.Any]: """Merge multiple ordered so that within-ordered order is preserved """ seen_set = set() add_seen = seen_set.add return reversed(tuple(map( lambda obj: add_seen(obj) or obj, filterfalse( ...
Helps us validate the parameters for the request
def validate_params(required, optional, params): """ Helps us validate the parameters for the request :param valid_options: a list of strings of valid options for the api request :param params: a dict, the key-value store which we really only care about the ...
authenticate_token checks the passed token and returns the user_id it is associated with. it is assumed that this method won t be directly exposed to the oauth client but some kind of framework or wrapper. this allows the framework to have the user_id without doing additional DB calls.
def authenticate_token( self, token ): ''' authenticate_token checks the passed token and returns the user_id it is associated with. it is assumed that this method won't be directly exposed to the oauth client, but some kind of framework or wrapper. this allows the framework to h...
Register your own mode and handle method here.
def main(): """Register your own mode and handle method here.""" plugin = Register() if plugin.args.option == 'filenumber': plugin.filenumber_handle() elif plugin.args.option == 'fileage': plugin.fileage_handle() elif plugin.args.option == 'sqlserverlocks': plugin.sqlserverlo...
Get the number of file in the folder.
def filenumber_handle(self): """Get the number of file in the folder.""" self.file_list = [] self.count = 0 status = self.ok if self.args.recursion: self.__result, self.__file_list = self.__get_folder(self.args.path) else: self.__result, self.__fi...
Get current datetime for every file.
def __get_current_datetime(self): """Get current datetime for every file.""" self.wql_time = "SELECT LocalDateTime FROM Win32_OperatingSystem" self.current_time = self.query(self.wql_time) # [{'LocalDateTime': '20160824161431.977000+480'}]' self.current_time_string = str( ...
Get the number of file in the folder.
def fileage_handle(self): """Get the number of file in the folder.""" self.file_list = [] self.ok_file = [] self.warn_file = [] self.crit_file = [] status = self.ok if self.args.recursion: self.__file_list = self.__get_folder(self.args.path) e...
run your main spider here as for branch spider result data you can return everything or do whatever with it in your own code
def run(self): """run your main spider here as for branch spider result data, you can return everything or do whatever with it in your own code :return: None """ config = config_creator() debug = config.debug branch_thread_sleep = config.branch_thread_sle...
Read version info from a file without importing it
def get_version(relpath): """Read version info from a file without importing it""" from os.path import dirname, join if '__file__' not in globals(): # Allow to use function interactively root = '.' else: root = dirname(__file__) # The code below reads text file with unknown...
Make a protobuf Descriptor given a DescriptorProto protobuf.
def MakeDescriptor(desc_proto, package='', build_file_if_cpp=True, syntax=None): """Make a protobuf Descriptor given a DescriptorProto protobuf. Handles nested descriptors. Note that this is limited to the scope of defining a message inside of another message. Composite fields can currently on...
Returns the root if this is a nested type or itself if its the root.
def GetTopLevelContainingType(self): """Returns the root if this is a nested type, or itself if its the root.""" desc = self while desc.containing_type is not None: desc = desc.containing_type return desc
Searches for the specified method and returns its descriptor.
def FindMethodByName(self, name): """Searches for the specified method, and returns its descriptor.""" for method in self.methods: if name == method.name: return method return None
Register your own mode and handle method here.
def main(): """Register your own mode and handle method here.""" plugin = Register() if plugin.args.option == 'sqlserverlocks': plugin.sqlserverlocks_handle() else: plugin.unknown("Unknown actions.")
Converts protobuf message to JSON format.
def MessageToJson(message, including_default_value_fields=False): """Converts protobuf message to JSON format. Args: message: The protocol buffers message instance to serialize. including_default_value_fields: If True, singular primitive fields, repeated fields, and map fields will always be serial...
Converts message to an object according to Proto3 JSON Specification.
def _MessageToJsonObject(message, including_default_value_fields): """Converts message to an object according to Proto3 JSON Specification.""" message_descriptor = message.DESCRIPTOR full_name = message_descriptor.full_name if _IsWrapperMessage(message_descriptor): return _WrapperMessageToJsonObject(message...