code
stringlengths
66
870k
docstring
stringlengths
19
26.7k
func_name
stringlengths
1
138
language
stringclasses
1 value
repo
stringlengths
7
68
path
stringlengths
5
324
url
stringlengths
46
389
license
stringclasses
7 values
def rpc_events_subscribe(handler, event_id, event_types=None, attributes=None): """ Subscribe the client to the specified event published by the server. When the event is published the specified *attributes* of it and it's corresponding id and type information will be sent to the client. :param str event_id: The ...
Subscribe the client to the specified event published by the server. When the event is published the specified *attributes* of it and it's corresponding id and type information will be sent to the client. :param str event_id: The identifier of the event to subscribe to. :param list event_types: A list of sub-typ...
rpc_events_subscribe
python
rsmusllp/king-phisher
king_phisher/server/server_rpc.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/server/server_rpc.py
BSD-3-Clause
def rpc_events_unsubscribe(handler, event_id, event_types=None, attributes=None): """ Unsubscribe from an event published by the server that the client previously subscribed to. :param str event_id: The identifier of the event to subscribe to. :param list event_types: A list of sub-types for the corresponding eve...
Unsubscribe from an event published by the server that the client previously subscribed to. :param str event_id: The identifier of the event to subscribe to. :param list event_types: A list of sub-types for the corresponding event. :param list attributes: A list of attributes of the event object to be sent to th...
rpc_events_unsubscribe
python
rsmusllp/king-phisher
king_phisher/server/server_rpc.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/server/server_rpc.py
BSD-3-Clause
def rpc_geoip_lookup(handler, ip, lang=None): """ Look up an IP address in the servers GeoIP database. If the IP address can not be found in the database, None will be returned. :param str ip: The IP address to look up. :param str lang: The language to prefer for regional names. :return: The geographic informati...
Look up an IP address in the servers GeoIP database. If the IP address can not be found in the database, None will be returned. :param str ip: The IP address to look up. :param str lang: The language to prefer for regional names. :return: The geographic information for the specified IP address. :rtype: dict
rpc_geoip_lookup
python
rsmusllp/king-phisher
king_phisher/server/server_rpc.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/server/server_rpc.py
BSD-3-Clause
def rpc_geoip_lookup_multi(handler, ips, lang=None): """ Look up multiple IP addresses in the servers GeoIP database. Each IP address that can not be found in the database will have its result set to None. :param list ips: The list of IP addresses to look up. :param str lang: The language to prefer for regional ...
Look up multiple IP addresses in the servers GeoIP database. Each IP address that can not be found in the database will have its result set to None. :param list ips: The list of IP addresses to look up. :param str lang: The language to prefer for regional names. :return: A dictionary containing the results keye...
rpc_geoip_lookup_multi
python
rsmusllp/king-phisher
king_phisher/server/server_rpc.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/server/server_rpc.py
BSD-3-Clause
def rpc_hostnames_add(handler, hostname): """ Add a hostname to the list of values that are configured for use with this server. At this time, these changes (like other config changes) are not persisted in the server so they will be lost when the server reboots. .. versionadded:: 1.13.0 :param str hostname: The...
Add a hostname to the list of values that are configured for use with this server. At this time, these changes (like other config changes) are not persisted in the server so they will be lost when the server reboots. .. versionadded:: 1.13.0 :param str hostname: The hostname to add.
rpc_hostnames_add
python
rsmusllp/king-phisher
king_phisher/server/server_rpc.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/server/server_rpc.py
BSD-3-Clause
def rpc_plugins_list(handler): """ Return information regarding enabled plugins in the server. :return: A dictionary representing enabled plugins and their meta-data. :rtype: dict """ plugin_manager = handler.server.plugin_manager plugins = {} for _, plugin in plugin_manager: plugins[plugin.name] = { 'aut...
Return information regarding enabled plugins in the server. :return: A dictionary representing enabled plugins and their meta-data. :rtype: dict
rpc_plugins_list
python
rsmusllp/king-phisher
king_phisher/server/server_rpc.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/server/server_rpc.py
BSD-3-Clause
def rpc_graphql(handler, session, query, query_vars=None): """ Execute a GraphQL query and return the results. If the query fails to execute the errors returned are populated in the **errors** key of the results dictionary. If the query executes successfully the returned data is available in the **data** key of th...
Execute a GraphQL query and return the results. If the query fails to execute the errors returned are populated in the **errors** key of the results dictionary. If the query executes successfully the returned data is available in the **data** key of the results dictionary. :param str query: The GraphQL query to ...
rpc_graphql
python
rsmusllp/king-phisher
king_phisher/server/server_rpc.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/server/server_rpc.py
BSD-3-Clause
def rpc_ssl_letsencrypt_certbot_version(handler): """ Find the certbot binary and retrieve it's version information. If the certbot binary could not be found, ``None`` is returned. .. versionadded:: 1.14.0 :return: The version of certbot. :rtype: str """ bin_path = letsencrypt.get_certbot_bin_path(handler.con...
Find the certbot binary and retrieve it's version information. If the certbot binary could not be found, ``None`` is returned. .. versionadded:: 1.14.0 :return: The version of certbot. :rtype: str
rpc_ssl_letsencrypt_certbot_version
python
rsmusllp/king-phisher
king_phisher/server/server_rpc.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/server/server_rpc.py
BSD-3-Clause
def rpc_ssl_letsencrypt_issue(handler, hostname, load=True): """ Issue a certificate with Let's Encrypt. This operation can fail for a wide variety of reasons, check the ``message`` key of the returned dictionary for a string description of what occurred. Successful operation requires that the certbot utility be i...
Issue a certificate with Let's Encrypt. This operation can fail for a wide variety of reasons, check the ``message`` key of the returned dictionary for a string description of what occurred. Successful operation requires that the certbot utility be installed, and the server's Let's Encrypt data path is configured...
rpc_ssl_letsencrypt_issue
python
rsmusllp/king-phisher
king_phisher/server/server_rpc.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/server/server_rpc.py
BSD-3-Clause
def rpc_ssl_sni_hostnames_get(handler): """ Get the hostnames that have available Server Name Indicator (SNI) configurations for use with SSL. .. versionadded:: 1.14.0 :return: A dictionary keyed by hostnames with values of dictionaries containing additional metadata. :rtype: dict """ if not advancedhttpserve...
Get the hostnames that have available Server Name Indicator (SNI) configurations for use with SSL. .. versionadded:: 1.14.0 :return: A dictionary keyed by hostnames with values of dictionaries containing additional metadata. :rtype: dict
rpc_ssl_sni_hostnames_get
python
rsmusllp/king-phisher
king_phisher/server/server_rpc.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/server/server_rpc.py
BSD-3-Clause
def rpc_ssl_sni_hostnames_load(handler, hostname): """ Load the SNI configuration for the specified *hostname*, effectively enabling it. If SSL is not enabled, SNI is not available, or the necessary data files are not available, this function returns ``False``. .. versionadded:: 1.14.0 :param str hostname: The ...
Load the SNI configuration for the specified *hostname*, effectively enabling it. If SSL is not enabled, SNI is not available, or the necessary data files are not available, this function returns ``False``. .. versionadded:: 1.14.0 :param str hostname: The hostname to configure SSL for. :return: Returns ``True...
rpc_ssl_sni_hostnames_load
python
rsmusllp/king-phisher
king_phisher/server/server_rpc.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/server/server_rpc.py
BSD-3-Clause
def rpc_ssl_sni_hostnames_unload(handler, hostname): """ Unload the SNI configuration for the specified *hostname*, effectively disabling it. If SNI is not available, or the specified configuration was not already loaded, this function returns ``False``. .. versionadded:: 1.14.0 :param str hostname: The hostnam...
Unload the SNI configuration for the specified *hostname*, effectively disabling it. If SNI is not available, or the specified configuration was not already loaded, this function returns ``False``. .. versionadded:: 1.14.0 :param str hostname: The hostname to configure SSL for. :return: Returns ``True`` only i...
rpc_ssl_sni_hostnames_unload
python
rsmusllp/king-phisher
king_phisher/server/server_rpc.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/server/server_rpc.py
BSD-3-Clause
def rpc_ssl_status(handler): """ Get information regarding the status of SSL on the server. This method returns a dictionary with keys describing whether or not SSL is enabled on one or more interfaces, and whether or not the server possess the SNI support. For details regarding which addresses are using SSL, see ...
Get information regarding the status of SSL on the server. This method returns a dictionary with keys describing whether or not SSL is enabled on one or more interfaces, and whether or not the server possess the SNI support. For details regarding which addresses are using SSL, see the :py:func:`~rpc_config_get` m...
rpc_ssl_status
python
rsmusllp/king-phisher
king_phisher/server/server_rpc.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/server/server_rpc.py
BSD-3-Clause
def embed_youtube_video(video_id, autoplay=True, enable_js=False, start=0, end=None): """ A Jinja function to embed a video into a web page using YouTube's `iframe API <https://developers.google.com/youtube/iframe_api_reference>`_. In order to enable a training button after the video has ended the youtube.js file ...
A Jinja function to embed a video into a web page using YouTube's `iframe API <https://developers.google.com/youtube/iframe_api_reference>`_. In order to enable a training button after the video has ended the youtube.js file needs to be included and *enable_js* just be set to True. If *start* or *end* are specifi...
embed_youtube_video
python
rsmusllp/king-phisher
king_phisher/server/template_extras.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/server/template_extras.py
BSD-3-Clause
def make_redirect_page(url, title='Automatic Redirect'): """ A Jinja function which will create an HTML page that will automatically redirect the viewer to a different url. :param str url: The URL to redirect the user to. :param str title: The title to use in the resulting HTML page. """ title = html.escape(tit...
A Jinja function which will create an HTML page that will automatically redirect the viewer to a different url. :param str url: The URL to redirect the user to. :param str title: The title to use in the resulting HTML page.
make_redirect_page
python
rsmusllp/king-phisher
king_phisher/server/template_extras.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/server/template_extras.py
BSD-3-Clause
def __init__(self, handler, manager): """ :param handler: The request handler that should be used by this socket. :type handler: :py:class:`advancedhttpserver.RequestHandler` :param manager: The manager that this event socket should register with. :type manager: :py:class:`.WebSocketsManager` """ handler....
:param handler: The request handler that should be used by this socket. :type handler: :py:class:`advancedhttpserver.RequestHandler` :param manager: The manager that this event socket should register with. :type manager: :py:class:`.WebSocketsManager`
__init__
python
rsmusllp/king-phisher
king_phisher/server/web_sockets.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/server/web_sockets.py
BSD-3-Clause
def is_subscribed(self, event_id, event_type): """ Check if the client is currently subscribed to the specified server event. :param str event_id: The identifier of the event to subscribe to. :param str event_type: A sub-type for the corresponding event. :return: Whether or not the client is subscribed to th...
Check if the client is currently subscribed to the specified server event. :param str event_id: The identifier of the event to subscribe to. :param str event_type: A sub-type for the corresponding event. :return: Whether or not the client is subscribed to the event. :rtype: bool
is_subscribed
python
rsmusllp/king-phisher
king_phisher/server/web_sockets.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/server/web_sockets.py
BSD-3-Clause
def publish(self, event): """ Publish the event by sending the relevant information to the client. If the client has not requested to receive the information through a subscription, then no data will be sent. :param event: The object representing the data to be published. :type event: :py:class:`.Event` ...
Publish the event by sending the relevant information to the client. If the client has not requested to receive the information through a subscription, then no data will be sent. :param event: The object representing the data to be published. :type event: :py:class:`.Event`
publish
python
rsmusllp/king-phisher
king_phisher/server/web_sockets.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/server/web_sockets.py
BSD-3-Clause
def __init__(self, config, job_manager): """ :param config: Configuration to retrieve settings from. :type config: :py:class:`smoke_zephyr.configuration.Configuration` :param job_manager: A job manager instance that can be used to schedule tasks. :type job_manager: :py:class:`smoke_zephyr.job.JobManager` ""...
:param config: Configuration to retrieve settings from. :type config: :py:class:`smoke_zephyr.configuration.Configuration` :param job_manager: A job manager instance that can be used to schedule tasks. :type job_manager: :py:class:`smoke_zephyr.job.JobManager`
__init__
python
rsmusllp/king-phisher
king_phisher/server/web_sockets.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/server/web_sockets.py
BSD-3-Clause
def dispatch(self, handler): """ A method that is suitable for use as a :py:attr:`~advancedhttpserver.RequestHandler.web_socket_handler`. :param handler: The current request handler instance. :type handler: :py:class:`~king_phisher.server.server.KingPhisherRequestHandler` """ if not ipaddress.ip_address(...
A method that is suitable for use as a :py:attr:`~advancedhttpserver.RequestHandler.web_socket_handler`. :param handler: The current request handler instance. :type handler: :py:class:`~king_phisher.server.server.KingPhisherRequestHandler`
dispatch
python
rsmusllp/king-phisher
king_phisher/server/web_sockets.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/server/web_sockets.py
BSD-3-Clause
def ping_all(self): """ Ping all of the connected web sockets to ensure they stay alive. This method is automatically executed periodically through a job added when the manager is initialized. """ disconnected = collections.deque() for web_socket in self.web_sockets: if web_socket.connected: try: ...
Ping all of the connected web sockets to ensure they stay alive. This method is automatically executed periodically through a job added when the manager is initialized.
ping_all
python
rsmusllp/king-phisher
king_phisher/server/web_sockets.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/server/web_sockets.py
BSD-3-Clause
def stop(self): """ Shutdown the manager and clean up the resources it has allocated. """ self.job_manager.job_delete(self._ping_job) for web_socket in self.web_sockets: if web_socket.connected: web_socket.close() self.web_sockets = [] self._work_queue.put(None) self._worker_thread.join()
Shutdown the manager and clean up the resources it has allocated.
stop
python
rsmusllp/king-phisher
king_phisher/server/web_sockets.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/server/web_sockets.py
BSD-3-Clause
def get_hostnames(config): """ List the hostnames that are configured for this server instance. This list is generated by first checking the server's configuration for the ``hostnames`` option. Then if ``vhost_directories`` is enabled, the webroot is checked for additional values. .. note:: This function makes...
List the hostnames that are configured for this server instance. This list is generated by first checking the server's configuration for the ``hostnames`` option. Then if ``vhost_directories`` is enabled, the webroot is checked for additional values. .. note:: This function makes no attempt to validate these v...
get_hostnames
python
rsmusllp/king-phisher
king_phisher/server/web_tools.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/server/web_tools.py
BSD-3-Clause
def get_vhost_directories(config): """ List the hostnames that are configured through the Virtual Host directories. If the server option ``vhost_directories`` is disabled, this function returns ``None``. .. versionadded:: 1.13.0 :param config: Configuration to retrieve settings from. :type config: :py:class:`s...
List the hostnames that are configured through the Virtual Host directories. If the server option ``vhost_directories`` is disabled, this function returns ``None``. .. versionadded:: 1.13.0 :param config: Configuration to retrieve settings from. :type config: :py:class:`smoke_zephyr.configuration.Configuration...
get_vhost_directories
python
rsmusllp/king-phisher
king_phisher/server/web_tools.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/server/web_tools.py
BSD-3-Clause
def _ex_config_logging(arguments, config, console_handler): """ If a setting is configured improperly, this will terminate execution via :py:func:`sys.exit`. :return: The path to a log file if one is in use. :rtype: str """ default_log_level = min( getattr(logging, (arguments.loglvl or constants.DEFAULT_LOG_L...
If a setting is configured improperly, this will terminate execution via :py:func:`sys.exit`. :return: The path to a log file if one is in use. :rtype: str
_ex_config_logging
python
rsmusllp/king-phisher
king_phisher/server/__main__.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/server/__main__.py
BSD-3-Clause
def clear_database(): """ Delete all data from all tables in the connected database. The database schema will remain unaffected. .. warning:: This action can not be reversed and there is no confirmation before it takes place. """ engine = Session.connection().engine with contextlib.closing(engine.connect())...
Delete all data from all tables in the connected database. The database schema will remain unaffected. .. warning:: This action can not be reversed and there is no confirmation before it takes place.
clear_database
python
rsmusllp/king-phisher
king_phisher/server/database/manager.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/server/database/manager.py
BSD-3-Clause
def export_database(target_file): """ Export the contents of the database using SQLAlchemy's serialization. This creates an archive file containing all of the tables and their data. The resulting export can be imported into another supported database so long as the :py:data:`~king_phisher.server.database.models.SC...
Export the contents of the database using SQLAlchemy's serialization. This creates an archive file containing all of the tables and their data. The resulting export can be imported into another supported database so long as the :py:data:`~king_phisher.server.database.models.SCHEMA_VERSION` is the same. :param s...
export_database
python
rsmusllp/king-phisher
king_phisher/server/database/manager.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/server/database/manager.py
BSD-3-Clause
def import_database(target_file, clear=True): """ Import the contents of a serialized database from an archive previously created with the :py:func:`.export_database` function. The current :py:data:`~king_phisher.server.database.models.SCHEMA_VERSION` must be the same as the exported archive. .. warning:: This...
Import the contents of a serialized database from an archive previously created with the :py:func:`.export_database` function. The current :py:data:`~king_phisher.server.database.models.SCHEMA_VERSION` must be the same as the exported archive. .. warning:: This will by default delete the contents of the curren...
import_database
python
rsmusllp/king-phisher
king_phisher/server/database/manager.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/server/database/manager.py
BSD-3-Clause
def get_metadata(key, session=None): """ Store a piece of metadata regarding the King Phisher database. :param str key: The name of the data. :param value: The value to store. :type value: int, str :param session: The session to use to store the value. """ if not isinstance(key, str): raise TypeError('key mu...
Store a piece of metadata regarding the King Phisher database. :param str key: The name of the data. :param value: The value to store. :type value: int, str :param session: The session to use to store the value.
get_metadata
python
rsmusllp/king-phisher
king_phisher/server/database/manager.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/server/database/manager.py
BSD-3-Clause
def get_row_by_id(session, table, row_id): """ Retrieve a database row from the specified table by it's unique id. :param session: The database session to use for the query. :type session: `.Session` :param table: The table object or the name of the database table where the row resides. :param row_id: The id of ...
Retrieve a database row from the specified table by it's unique id. :param session: The database session to use for the query. :type session: `.Session` :param table: The table object or the name of the database table where the row resides. :param row_id: The id of the row to retrieve. :return: The object repre...
get_row_by_id
python
rsmusllp/king-phisher
king_phisher/server/database/manager.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/server/database/manager.py
BSD-3-Clause
def normalize_connection_url(connection_url): """ Normalize a connection url by performing any conversions necessary for it to be used with the database API. :param str connection_url: The connection url to normalize. :return: The normalized connection url. :rtype: str """ if connection_url == ':memory:': co...
Normalize a connection url by performing any conversions necessary for it to be used with the database API. :param str connection_url: The connection url to normalize. :return: The normalized connection url. :rtype: str
normalize_connection_url
python
rsmusllp/king-phisher
king_phisher/server/database/manager.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/server/database/manager.py
BSD-3-Clause
def init_alembic(engine, schema_version): """ Creates the alembic_version table and sets the value of the table according to the specified schema version. :param engine: The engine used to connect to the database. :type engine: :py:class:`sqlalchemy.engine.Engine` :param int schema_version: The MetaData schema_v...
Creates the alembic_version table and sets the value of the table according to the specified schema version. :param engine: The engine used to connect to the database. :type engine: :py:class:`sqlalchemy.engine.Engine` :param int schema_version: The MetaData schema_version to set the alembic version to.
init_alembic
python
rsmusllp/king-phisher
king_phisher/server/database/manager.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/server/database/manager.py
BSD-3-Clause
def init_database(connection_url, extra_init=False): """ Create and initialize the database engine. This must be done before the session object can be used. This will also attempt to perform any updates to the database schema if the backend supports such operations. :param str connection_url: The url for the data...
Create and initialize the database engine. This must be done before the session object can be used. This will also attempt to perform any updates to the database schema if the backend supports such operations. :param str connection_url: The url for the database connection. :param bool extra_init: Run optional ex...
init_database
python
rsmusllp/king-phisher
king_phisher/server/database/manager.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/server/database/manager.py
BSD-3-Clause
def init_database_postgresql(connection_url): """ Perform additional initialization checks and operations for a PostgreSQL database. If the database is hosted locally this will ensure that the service is currently running and start it if it is not. Additionally if the specified database or user do not exist, they ...
Perform additional initialization checks and operations for a PostgreSQL database. If the database is hosted locally this will ensure that the service is currently running and start it if it is not. Additionally if the specified database or user do not exist, they will be created. :param connection_url: The url ...
init_database_postgresql
python
rsmusllp/king-phisher
king_phisher/server/database/manager.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/server/database/manager.py
BSD-3-Clause
def register_table(table): """ Register a database table. This will populate the information provided in DATABASE_TABLES dictionary. This also forwards signals to the appropriate listeners within the :py:mod:`server.signal` module. :param cls table: The table to register. """ metatable = table.metatable() data...
Register a database table. This will populate the information provided in DATABASE_TABLES dictionary. This also forwards signals to the appropriate listeners within the :py:mod:`server.signal` module. :param cls table: The table to register.
register_table
python
rsmusllp/king-phisher
king_phisher/server/database/models.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/server/database/models.py
BSD-3-Clause
def assert_session_has_permissions(self, *args, **kwargs): """ A convenience function which wraps :py:meth:`~.session_has_permissions` and raises a :py:exc:`~king_phisher.errors.KingPhisherPermissionError` if the session does not have the specified permissions. """ if self.session_has_permissions(*args, **k...
A convenience function which wraps :py:meth:`~.session_has_permissions` and raises a :py:exc:`~king_phisher.errors.KingPhisherPermissionError` if the session does not have the specified permissions.
assert_session_has_permissions
python
rsmusllp/king-phisher
king_phisher/server/database/models.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/server/database/models.py
BSD-3-Clause
def session_has_permissions(self, access, session): """ Check that the authenticated session has the permissions specified in *access*. The permissions in *access* are abbreviated with the first letter of create, read, update, and delete. For example, to check for read and update permissions, *access* would b...
Check that the authenticated session has the permissions specified in *access*. The permissions in *access* are abbreviated with the first letter of create, read, update, and delete. For example, to check for read and update permissions, *access* would be ``'ru'``. .. note:: This will always return ``Tru...
session_has_permissions
python
rsmusllp/king-phisher
king_phisher/server/database/models.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/server/database/models.py
BSD-3-Clause
def session_has_create_access(cls, session, instance=None): """ Check that the authenticated *session* has access to create the specified model *instance*. :param session: The authenticated session to check access for. :param instance: The optional model instance to inspect. :return: Whether the session ha...
Check that the authenticated *session* has access to create the specified model *instance*. :param session: The authenticated session to check access for. :param instance: The optional model instance to inspect. :return: Whether the session has the desired permissions. :rtype: bool
session_has_create_access
python
rsmusllp/king-phisher
king_phisher/server/database/models.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/server/database/models.py
BSD-3-Clause
def session_has_delete_access(cls, session, instance=None): """ Check that the authenticated *session* has access to delete the specified model *instance*. :param session: The authenticated session to check access for. :param instance: The optional model instance to inspect. :return: Whether the session ha...
Check that the authenticated *session* has access to delete the specified model *instance*. :param session: The authenticated session to check access for. :param instance: The optional model instance to inspect. :return: Whether the session has the desired permissions. :rtype: bool
session_has_delete_access
python
rsmusllp/king-phisher
king_phisher/server/database/models.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/server/database/models.py
BSD-3-Clause
def session_has_read_access(cls, session, instance=None): """ Check that the authenticated *session* has access to read the specified model *instance*. :param session: The authenticated session to check access for. :param instance: The optional model instance to inspect. :return: Whether the session has th...
Check that the authenticated *session* has access to read the specified model *instance*. :param session: The authenticated session to check access for. :param instance: The optional model instance to inspect. :return: Whether the session has the desired permissions. :rtype: bool
session_has_read_access
python
rsmusllp/king-phisher
king_phisher/server/database/models.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/server/database/models.py
BSD-3-Clause
def session_has_read_prop_access(cls, session, prop, instance=None): """ Check that the authenticated *session* has access to read the property of the specified model *instance*. This allows models to only explicitly control which of their attributes can be read by a particular *session*. :param session: The...
Check that the authenticated *session* has access to read the property of the specified model *instance*. This allows models to only explicitly control which of their attributes can be read by a particular *session*. :param session: The authenticated session to check access for. :param instance: The optiona...
session_has_read_prop_access
python
rsmusllp/king-phisher
king_phisher/server/database/models.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/server/database/models.py
BSD-3-Clause
def session_has_update_access(cls, session, instance=None): """ Check that the authenticated *session* has access to update the specified model *instance*. :param session: The authenticated session to check access for. :param instance: The optional model instance to inspect. :return: Whether the session ha...
Check that the authenticated *session* has access to update the specified model *instance*. :param session: The authenticated session to check access for. :param instance: The optional model instance to inspect. :return: Whether the session has the desired permissions. :rtype: bool
session_has_update_access
python
rsmusllp/king-phisher
king_phisher/server/database/models.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/server/database/models.py
BSD-3-Clause
def metatable(cls): """ Generate a :py:class:`.MetaTable` instance for this model class. :return: The appropriate metadata for the table represented by this model. :rtype: :py:class:`.MetaTable` """ columns = tuple(col.name for col in cls.__table__.columns) return MetaTable(column_names=columns, model=cl...
Generate a :py:class:`.MetaTable` instance for this model class. :return: The appropriate metadata for the table represented by this model. :rtype: :py:class:`.MetaTable`
metatable
python
rsmusllp/king-phisher
king_phisher/server/database/models.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/server/database/models.py
BSD-3-Clause
def __init__(self, namespace=None, order_by='created'): """ .. versionchanged:: 1.14.0 Added the *order_by* parameter. :param str namespace: The unique identifier of this namespace. :param str order_by: The attribute to order stored items by. This must be one of "created", "id", "key", or "modified". """ ...
.. versionchanged:: 1.14.0 Added the *order_by* parameter. :param str namespace: The unique identifier of this namespace. :param str order_by: The attribute to order stored items by. This must be one of "created", "id", "key", or "modified".
__init__
python
rsmusllp/king-phisher
king_phisher/server/database/storage.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/server/database/storage.py
BSD-3-Clause
def validate_credential(credential, campaign): """ Validate a *credential* object with regards to the configuration provided in *campaign*. This uses :py:func:`~.validate_credential_fields` to validate each field individually and then return either ``None``, ``True`` or ``False``. If no validation took place on an...
Validate a *credential* object with regards to the configuration provided in *campaign*. This uses :py:func:`~.validate_credential_fields` to validate each field individually and then return either ``None``, ``True`` or ``False``. If no validation took place on any field, ``None`` is returned, otherwise if any fi...
validate_credential
python
rsmusllp/king-phisher
king_phisher/server/database/validation.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/server/database/validation.py
BSD-3-Clause
def validate_credential_fields(credential, campaign): """ Validate a *credential* object with regards to the configuration provided in *campaign*. Each field in the *credential* object is validated and a new :py:class:`~.CredentialCollection` is returned with it's fields set to the results of the validation. A fie...
Validate a *credential* object with regards to the configuration provided in *campaign*. Each field in the *credential* object is validated and a new :py:class:`~.CredentialCollection` is returned with it's fields set to the results of the validation. A fields validation results are either ``None``, ``True`` or `...
validate_credential_fields
python
rsmusllp/king-phisher
king_phisher/server/database/validation.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/server/database/validation.py
BSD-3-Clause
def info_has_read_prop_access(cls, info, model, field_name=None, instance=None): """ Check that the context provided by *info* has access to read the specified property of the model. This can be used to ensure that sessions which can not read a protected field can also not obtain indirect access such as filte...
Check that the context provided by *info* has access to read the specified property of the model. This can be used to ensure that sessions which can not read a protected field can also not obtain indirect access such as filtering or sorting by it. :param info: The resolve information for this execution. :...
info_has_read_prop_access
python
rsmusllp/king-phisher
king_phisher/server/graphql/middleware.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/server/graphql/middleware.py
BSD-3-Clause
def sa_get_relationship(session, model, name): """ Resolve the relationship on a SQLAlchemy model to either an object (in the case of one-to-one relationships) or a query to all of the objects (in the case of one-to-many relationships). :param session: The SQLAlchemy session to associate the query with. :param m...
Resolve the relationship on a SQLAlchemy model to either an object (in the case of one-to-one relationships) or a query to all of the objects (in the case of one-to-many relationships). :param session: The SQLAlchemy session to associate the query with. :param model: The SQLAlchemy model of the object associated...
sa_get_relationship
python
rsmusllp/king-phisher
king_phisher/server/graphql/types/database.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/server/graphql/types/database.py
BSD-3-Clause
def sa_object_resolver(attname, default_value, model, info, **kwargs): """ Resolve the attribute for the given SQLAlchemy model object. If the attribute is a relationship, use :py:func:`.sa_get_relationship` to resolve it. :param str attname: The name of the attribute to resolve on the object. :param default_val...
Resolve the attribute for the given SQLAlchemy model object. If the attribute is a relationship, use :py:func:`.sa_get_relationship` to resolve it. :param str attname: The name of the attribute to resolve on the object. :param default_value: The default value to return if the attribute is unavailable. :param mo...
sa_object_resolver
python
rsmusllp/king-phisher
king_phisher/server/graphql/types/database.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/server/graphql/types/database.py
BSD-3-Clause
def forward( self, sample: torch.FloatTensor, timestep: Union[torch.Tensor, float, int], encoder_hidden_states: torch.Tensor, audio_embedding: Optional[torch.Tensor] = None, class_labels: Optional[torch.Tensor] = None, mask_cond_fea: Optional[torch.Tensor] = None,...
Args: sample (`torch.FloatTensor`): (batch, channel, height, width) noisy inputs tensor timestep (`torch.FloatTensor` or `float` or `int`): (batch) timesteps encoder_hidden_states (`torch.FloatTensor`): (batch, sequence_length, feature_dim) encoder hidden states ...
forward
python
fudan-generative-vision/hallo
hallo/models/unet_3d.py
https://github.com/fudan-generative-vision/hallo/blob/master/hallo/models/unet_3d.py
MIT
def forward(self,): """ empty function to override abstract function of nn Module """
empty function to override abstract function of nn Module
forward
python
fudan-generative-vision/hallo
scripts/inference.py
https://github.com/fudan-generative-vision/hallo/blob/master/scripts/inference.py
MIT
def get_modules(self): """ Simple method to avoid too-few-public-methods pylint error """ return { "reference_unet": self.reference_unet, "denoising_unet": self.denoising_unet, "face_locator": self.face_locator, "imageproj": self.imageproj,...
Simple method to avoid too-few-public-methods pylint error
get_modules
python
fudan-generative-vision/hallo
scripts/inference.py
https://github.com/fudan-generative-vision/hallo/blob/master/scripts/inference.py
MIT
def inference_process(args: argparse.Namespace): """ Perform inference processing. Args: args (argparse.Namespace): Command-line arguments. This function initializes the configuration for the inference process. It sets up the necessary modules and variables to prepare for the upcoming infe...
Perform inference processing. Args: args (argparse.Namespace): Command-line arguments. This function initializes the configuration for the inference process. It sets up the necessary modules and variables to prepare for the upcoming inference steps.
inference_process
python
fudan-generative-vision/hallo
scripts/inference.py
https://github.com/fudan-generative-vision/hallo/blob/master/scripts/inference.py
MIT
def make_tfrecord_loaders(args): """Load train/val/test dataset from shuffled TFRecords""" import data_utils.tf_dl data_set_args = {'batch_size': args.batch_size, 'max_seq_len': args.seq_length, 'max_preds_per_seq': args.max_preds_per_seq, 'tra...
Load train/val/test dataset from shuffled TFRecords
make_tfrecord_loaders
python
THUDM/GLM
configure_data.py
https://github.com/THUDM/GLM/blob/master/configure_data.py
MIT
def get_split(args): """ Get dataset splits from comma separated string list """ splits = [] if args.split.find(',') != -1: splits = [float(s) for s in args.split.split(',')] elif args.split.find('/') != -1: splits = [float(s) for s in args.split.split('/')] else: spl...
Get dataset splits from comma separated string list
get_split
python
THUDM/GLM
configure_data.py
https://github.com/THUDM/GLM/blob/master/configure_data.py
MIT
def configure_data(): """add cmdline flags for configuring datasets""" # These are options that are used by data_utils, but are either # deprecated or not meant to be exposed to the command line user. # These options are intneded to be set in code by specific scripts. defaults = { 'world_siz...
add cmdline flags for configuring datasets
configure_data
python
THUDM/GLM
configure_data.py
https://github.com/THUDM/GLM/blob/master/configure_data.py
MIT
def process_batch(batch, args): """Process batch and produce inputs for the model.""" keys = ["text", "label"] if args.pretrained_bert: keys += ["padding_mask", "types"] else: keys += ["mask", "position"] if args.cloze_eval: if args.fast_decode: keys +...
Process batch and produce inputs for the model.
process_batch
python
THUDM/GLM
finetune_glm.py
https://github.com/THUDM/GLM/blob/master/finetune_glm.py
MIT
def finetune_forward_step(batch, model, args, timers, mems): """Simple forward step with cross-entropy loss.""" # Get the batch. timers('batch generator').start() try: batch_ = next(batch) except BaseException: batch_ = batch data = process_batch(batch_, args) timers('batch ...
Simple forward step with cross-entropy loss.
finetune_forward_step
python
THUDM/GLM
finetune_glm.py
https://github.com/THUDM/GLM/blob/master/finetune_glm.py
MIT
def _build_infinite_size_dataloader(dataloader): """Build a looped dataloader with infinite size.""" iterator = dataloader.__iter__() while True: try: yield iterator.__next__() except StopIteration: iterator = dataloader.__iter__()
Build a looped dataloader with infinite size.
_build_infinite_size_dataloader
python
THUDM/GLM
finetune_glm.py
https://github.com/THUDM/GLM/blob/master/finetune_glm.py
MIT
def finetune(args, train_valid_datasets_provider, model_kwargs, forward_step=finetune_forward_step, end_of_epoch_callback_provider=None): """Main finetune function used across all tasks.""" global tokenizer timers = Timers() tokenizer = prepare_tokenizer(args) pretrain_glm.tokenizer = t...
Main finetune function used across all tasks.
finetune
python
THUDM/GLM
finetune_glm.py
https://github.com/THUDM/GLM/blob/master/finetune_glm.py
MIT
def add(self, hyp: torch.LongTensor, sum_logprobs: float, mems=None): """ Add a new hypothesis to the list. """ score = sum_logprobs / (max(hyp.shape[-1], 1) ** self.length_penalty) if len(self) < self.num_beams or score > self.worst_score: self.beams.append((score, h...
Add a new hypothesis to the list.
add
python
THUDM/GLM
generation_utils.py
https://github.com/THUDM/GLM/blob/master/generation_utils.py
MIT
def is_done(self, best_sum_logprobs: float, cur_len: int) -> bool: """ If there are enough hypotheses and that none of the hypotheses being generated can become better than the worst one in the heap, then we are done with this sentence. """ if len(self) < self.num_beams: ...
If there are enough hypotheses and that none of the hypotheses being generated can become better than the worst one in the heap, then we are done with this sentence.
is_done
python
THUDM/GLM
generation_utils.py
https://github.com/THUDM/GLM/blob/master/generation_utils.py
MIT
def evaluate_and_print_results(prefix, data_iterator, model, args, timers, forward_step_func, verbose=False, step=None, summary_writer=None): """Helper function to evaluate and dump results on screen.""" lm_loss, gpt_loss, bert_loss, sent_loss, multi_loss = evaluate(data_iterator,...
Helper function to evaluate and dump results on screen.
evaluate_and_print_results
python
THUDM/GLM
pretrain_glm.py
https://github.com/THUDM/GLM/blob/master/pretrain_glm.py
MIT
def get_train_val_test_data(args, tokenizer): """Load the data on rank zero and boradcast number of tokens to all GPUS.""" (train_data, val_data, test_data) = (None, None, None) # Data loader only on rank 0 of each model parallel group. if mpu.get_model_parallel_rank() == 0: data_config = confi...
Load the data on rank zero and boradcast number of tokens to all GPUS.
get_train_val_test_data
python
THUDM/GLM
pretrain_glm.py
https://github.com/THUDM/GLM/blob/master/pretrain_glm.py
MIT
def print_params_min_max_norm(optimizer, iteration): """Print min, max, and norm of all parameters.""" index = 0 rank = torch.distributed.get_rank() string = 'iteration, rank, index, model-parallel,min, max, norm\n' optimizer_ = optimizer if isinstance(optimizer, FP16_Optimizer): optimiz...
Print min, max, and norm of all parameters.
print_params_min_max_norm
python
THUDM/GLM
utils.py
https://github.com/THUDM/GLM/blob/master/utils.py
MIT
def load_weights(src, dst, dst2src=False): """ Loads weights from src to dst via in place copy. src is a huggingface gpt2model, while dst is one of our models. dst2src=True loads parameters from our models into huggingface's. ^dst2src is still untested """ conv_layer = 'Conv1D' in str(type(s...
Loads weights from src to dst via in place copy. src is a huggingface gpt2model, while dst is one of our models. dst2src=True loads parameters from our models into huggingface's. ^dst2src is still untested
load_weights
python
THUDM/GLM
utils.py
https://github.com/THUDM/GLM/blob/master/utils.py
MIT
def move_weights(our, oai, dst2src=False): """ Loads weights from `oai` to `our` via in place copy. `oai` is a huggingface gpt2model, while `our` is one of our models. dst2src=True loads parameters from our models into huggingface's. ^dst2src=True is still untested """ # while isinstance(...
Loads weights from `oai` to `our` via in place copy. `oai` is a huggingface gpt2model, while `our` is one of our models. dst2src=True loads parameters from our models into huggingface's. ^dst2src=True is still untested
move_weights
python
THUDM/GLM
utils.py
https://github.com/THUDM/GLM/blob/master/utils.py
MIT
def split_ds(ds, split=None, shuffle=True, save_splits=None, load_splits=None): """ Split a dataset into subsets given proportions of how much to allocate per split. If a split is 0% returns None for that split. Purpose: Useful for creating train/val/test splits Arguments: ds (Dataset or arr...
Split a dataset into subsets given proportions of how much to allocate per split. If a split is 0% returns None for that split. Purpose: Useful for creating train/val/test splits Arguments: ds (Dataset or array-like): Data to be split. split (1D array-like): proportions to split `ds`. `...
split_ds
python
THUDM/GLM
data_utils/datasets.py
https://github.com/THUDM/GLM/blob/master/data_utils/datasets.py
MIT
def __getitem__(self, index): """process+tokenize string and return string,label,and stringlen""" x = self.X[index] if self.tokenizer is not None: x = self.tokenizer.EncodeAsIds(x, self.preprocess_fn) elif self.preprocess_fn is not None: x = self.preprocess_fn(x) ...
process+tokenize string and return string,label,and stringlen
__getitem__
python
THUDM/GLM
data_utils/datasets.py
https://github.com/THUDM/GLM/blob/master/data_utils/datasets.py
MIT
def write(self, writer_gen=None, path=None, skip_header=False): """ given a generator of metrics for each of the data points X_i, write the metrics, text, and labels to a csv file """ if path is None: path = self.path + '.results' print('generating csv at ...
given a generator of metrics for each of the data points X_i, write the metrics, text, and labels to a csv file
write
python
THUDM/GLM
data_utils/datasets.py
https://github.com/THUDM/GLM/blob/master/data_utils/datasets.py
MIT
def __getitem__(self, index): """gets the index'th string from the dataset""" x = self.X[index] if self.tokenizer is not None: x = self.tokenizer.EncodeAsIds(x, self.preprocess_fn) elif self.preprocess_fn is not None: x = self.preprocess_fn(x) y = self.Y[i...
gets the index'th string from the dataset
__getitem__
python
THUDM/GLM
data_utils/datasets.py
https://github.com/THUDM/GLM/blob/master/data_utils/datasets.py
MIT
def write(self, writer_gen=None, path=None, skip_header=False): """ given a generator of metrics for each of the data points X_i, write the metrics, text, and labels to a json file """ if path is None: path = self.path + '.results' jsons = [] if ...
given a generator of metrics for each of the data points X_i, write the metrics, text, and labels to a json file
write
python
THUDM/GLM
data_utils/datasets.py
https://github.com/THUDM/GLM/blob/master/data_utils/datasets.py
MIT
def __init__(self, ds, tokenizer, max_seq_len=1024, sample_across_doc=True, non_sentence_start=0.0, filter_english=False, **kwargs): """ sentence_start: the stripped article must start with a complete sentence """ self.ds = ds se...
sentence_start: the stripped article must start with a complete sentence
__init__
python
THUDM/GLM
data_utils/datasets.py
https://github.com/THUDM/GLM/blob/master/data_utils/datasets.py
MIT
def sentence_tokenize(self, sent, sentence_num=0, beginning=False, ending=False): """tokenize sentence and get token types""" tokens = self.tokenizer.EncodeAsIds(sent).tokenization str_type = 'str' + str(sentence_num) token_types = [self.tokenizer.get_type(str_type).Id] * len(tokens) ...
tokenize sentence and get token types
sentence_tokenize
python
THUDM/GLM
data_utils/datasets.py
https://github.com/THUDM/GLM/blob/master/data_utils/datasets.py
MIT
def get_doc(self, idx): """gets text of document corresponding to idx""" rtn = self.ds[idx] if isinstance(rtn, dict): rtn = rtn['text'] return rtn
gets text of document corresponding to idx
get_doc
python
THUDM/GLM
data_utils/datasets.py
https://github.com/THUDM/GLM/blob/master/data_utils/datasets.py
MIT
def create_random_sentencepair(self, target_seq_length, rng, np_rng): """ fetches a random sentencepair corresponding to rng state similar to https://github.com/google-research/bert/blob/master/create_pretraining_data.py#L248-L294 """ is_random_next = None curr_strs = []...
fetches a random sentencepair corresponding to rng state similar to https://github.com/google-research/bert/blob/master/create_pretraining_data.py#L248-L294
create_random_sentencepair
python
THUDM/GLM
data_utils/datasets.py
https://github.com/THUDM/GLM/blob/master/data_utils/datasets.py
MIT
def truncate_seq_pair(self, a, b, max_seq_len, rng): """ Truncate sequence pair according to original BERT implementation: https://github.com/google-research/bert/blob/master/create_pretraining_data.py#L391 """ tokens_a, token_types_a = a tokens_b, token_types_b = b ...
Truncate sequence pair according to original BERT implementation: https://github.com/google-research/bert/blob/master/create_pretraining_data.py#L391
truncate_seq_pair
python
THUDM/GLM
data_utils/datasets.py
https://github.com/THUDM/GLM/blob/master/data_utils/datasets.py
MIT
def mask_token(self, idx, tokens, types, vocab_words, rng): """ helper function to mask `idx` token from `tokens` according to section 3.3.1 of https://arxiv.org/pdf/1810.04805.pdf """ label = tokens[idx] if rng.random() < 0.8: new_label = self.tokenizer.get_c...
helper function to mask `idx` token from `tokens` according to section 3.3.1 of https://arxiv.org/pdf/1810.04805.pdf
mask_token
python
THUDM/GLM
data_utils/datasets.py
https://github.com/THUDM/GLM/blob/master/data_utils/datasets.py
MIT
def pad_seq(self, seq): """helper function to pad sequence pair""" num_pad = max(0, self.max_seq_len - len(seq)) pad_mask = [0] * len(seq) + [1] * num_pad seq += [self.tokenizer.get_command('pad').Id] * num_pad return seq, pad_mask
helper function to pad sequence pair
pad_seq
python
THUDM/GLM
data_utils/datasets.py
https://github.com/THUDM/GLM/blob/master/data_utils/datasets.py
MIT
def create_masked_lm_predictions(self, a, b, mask_lm_prob, max_preds_per_seq, vocab_words, rng): """ Mask sequence pair for BERT training according to: https://github.com/google-research/bert/blob/master/create_pretraining_data.py#L338 """ tokens_a, token_types_a = a toke...
Mask sequence pair for BERT training according to: https://github.com/google-research/bert/blob/master/create_pretraining_data.py#L338
create_masked_lm_predictions
python
THUDM/GLM
data_utils/datasets.py
https://github.com/THUDM/GLM/blob/master/data_utils/datasets.py
MIT
def filename_to_url(filename, cache_dir=None): """ Return the url and etag (which may be ``None``) stored for `filename`. Raise ``EnvironmentError`` if `filename` or its stored metadata do not exist. """ if cache_dir is None: cache_dir = PYTORCH_PRETRAINED_BERT_CACHE if sys.version_info[...
Return the url and etag (which may be ``None``) stored for `filename`. Raise ``EnvironmentError`` if `filename` or its stored metadata do not exist.
filename_to_url
python
THUDM/GLM
data_utils/file_utils.py
https://github.com/THUDM/GLM/blob/master/data_utils/file_utils.py
MIT
def cached_path(url_or_filename, cache_dir=None): """ Given something that might be a URL (or might be a local path), determine which. If it's a URL, download the file and cache it, and return the path to the cached file. If it's already a local path, make sure the file exists and then return the pa...
Given something that might be a URL (or might be a local path), determine which. If it's a URL, download the file and cache it, and return the path to the cached file. If it's already a local path, make sure the file exists and then return the path.
cached_path
python
THUDM/GLM
data_utils/file_utils.py
https://github.com/THUDM/GLM/blob/master/data_utils/file_utils.py
MIT
def split_s3_path(url): """Split a full s3 path into the bucket name and path.""" parsed = urlparse(url) if not parsed.netloc or not parsed.path: raise ValueError("bad s3 path {}".format(url)) bucket_name = parsed.netloc s3_path = parsed.path # Remove '/' at beginning of path. if s3_...
Split a full s3 path into the bucket name and path.
split_s3_path
python
THUDM/GLM
data_utils/file_utils.py
https://github.com/THUDM/GLM/blob/master/data_utils/file_utils.py
MIT
def s3_request(func): """ Wrapper function for s3 requests in order to create more helpful error messages. """ @wraps(func) def wrapper(url, *args, **kwargs): try: return func(url, *args, **kwargs) except ClientError as exc: if int(exc.response["Error"]["...
Wrapper function for s3 requests in order to create more helpful error messages.
s3_request
python
THUDM/GLM
data_utils/file_utils.py
https://github.com/THUDM/GLM/blob/master/data_utils/file_utils.py
MIT
def get_from_cache(url, cache_dir=None): """ Given a URL, look for the corresponding dataset in the local cache. If it's not there, download it. Then return the path to the cached file. """ if cache_dir is None: cache_dir = PYTORCH_PRETRAINED_BERT_CACHE if sys.version_info[0] == 3 and is...
Given a URL, look for the corresponding dataset in the local cache. If it's not there, download it. Then return the path to the cached file.
get_from_cache
python
THUDM/GLM
data_utils/file_utils.py
https://github.com/THUDM/GLM/blob/master/data_utils/file_utils.py
MIT
def read_set_from_file(filename): ''' Extract a de-duped collection (set) of text from a file. Expected file format is one item per line. ''' collection = set() with open(filename, 'r', encoding='utf-8') as file_: for line in file_: collection.add(line.rstrip()) return co...
Extract a de-duped collection (set) of text from a file. Expected file format is one item per line.
read_set_from_file
python
THUDM/GLM
data_utils/file_utils.py
https://github.com/THUDM/GLM/blob/master/data_utils/file_utils.py
MIT
def exists_lazy(path, data_type='data'): """ Check if we've already made a lazy version of this file for the `data_type` field. """ if not os.path.exists(get_lazy_path(path)): return False contents = os.listdir(get_lazy_path(path)) if data_type not in contents: return False i...
Check if we've already made a lazy version of this file for the `data_type` field.
exists_lazy
python
THUDM/GLM
data_utils/lazy_loader.py
https://github.com/THUDM/GLM/blob/master/data_utils/lazy_loader.py
MIT
def SetTokenizer(self, tokenizer): """ logic to set and remove (set to None) tokenizer. combines preprocessing/tokenization into one callable. """ if tokenizer is None: if not hasattr(self, '_tokenizer'): self._tokenizer = tokenizer else: ...
logic to set and remove (set to None) tokenizer. combines preprocessing/tokenization into one callable.
SetTokenizer
python
THUDM/GLM
data_utils/lazy_loader.py
https://github.com/THUDM/GLM/blob/master/data_utils/lazy_loader.py
MIT
def __getitem__(self, index): """ read file and splice strings based on string ending array `self.ends` """ if not isinstance(index, slice): if index == 0: start = 0 else: start = self.ends[index - 1] end = self.ends[ind...
read file and splice strings based on string ending array `self.ends`
__getitem__
python
THUDM/GLM
data_utils/lazy_loader.py
https://github.com/THUDM/GLM/blob/master/data_utils/lazy_loader.py
MIT
def _batch(self, batch): """extracts samples only pertaining to this worker's batch""" start = self.rank*self.batch_size//self.world_size end = (self.rank+1)*self.batch_size//self.world_size return batch[start:end]
extracts samples only pertaining to this worker's batch
_batch
python
THUDM/GLM
data_utils/samplers.py
https://github.com/THUDM/GLM/blob/master/data_utils/samplers.py
MIT
def data_iterator(self, _iter, wrap_around=False): """iterates through data and handles wrap around""" for i, idx in enumerate(_iter): if i < self.wrap_around%self.batch_size: continue if wrap_around: self.wrap_around += 1 self.wrap...
iterates through data and handles wrap around
data_iterator
python
THUDM/GLM
data_utils/samplers.py
https://github.com/THUDM/GLM/blob/master/data_utils/samplers.py
MIT
def make_tokenizer(tokenizer_type, corpus, model_path=None, vocab_size=None, model_type=None, pad_token=0, character_coverage=1.0, command_tokens=None, type_tokens=None, fix_command_token=False, **kwargs): """ Helper function to instantiate a tokenizer given common combinations of options. ...
Helper function to instantiate a tokenizer given common combinations of options.
make_tokenizer
python
THUDM/GLM
data_utils/tokenization.py
https://github.com/THUDM/GLM/blob/master/data_utils/tokenization.py
MIT
def EncodeAsIds(self, text, process_fn=None): """ encode text using text tokenizer and shift Id values for command tokens """ processed_text = text if process_fn is not None: processed_text = process_fn(processed_text) def split_on_token(tok_extended: Command...
encode text using text tokenizer and shift Id values for command tokens
EncodeAsIds
python
THUDM/GLM
data_utils/tokenization.py
https://github.com/THUDM/GLM/blob/master/data_utils/tokenization.py
MIT
def EncodeAsTokens(self, text, process_fn=None): """ encode text as tokens using text tokenizer """ tokenization = self.text_tokenizer.EncodeAsTokens(text, process_fn=process_fn) tokenization.set_command_tokens(self._command_tokens) return tokenization
encode text as tokens using text tokenizer
EncodeAsTokens
python
THUDM/GLM
data_utils/tokenization.py
https://github.com/THUDM/GLM/blob/master/data_utils/tokenization.py
MIT
def IdToToken(self, Id, type_token=False): """convert Id to token accounting for command and type tokens""" if isinstance(Id, (TypeToken, CommandToken)): return Id.token if type_token: return self.type_id_map[Id].token if Id < self.num_command_tokens: ...
convert Id to token accounting for command and type tokens
IdToToken
python
THUDM/GLM
data_utils/tokenization.py
https://github.com/THUDM/GLM/blob/master/data_utils/tokenization.py
MIT
def TokenToId(self, token, type_token=False): """convert token to Id accounting for command and type tokens""" if isinstance(token, (TypeToken, CommandToken)): return token.Id if type_token: return self.type_token_map[token].Id if token in self.command_token_map: ...
convert token to Id accounting for command and type tokens
TokenToId
python
THUDM/GLM
data_utils/tokenization.py
https://github.com/THUDM/GLM/blob/master/data_utils/tokenization.py
MIT
def DecodeIds(self, Ids, type_token=False): """ convert Ids to tokens accounting for command and type tokens, tokens are joined and returned as a string. """ if type_token: return ' '.join(Id.token if isinstance(Id, TypeToken) else self.type_id_map[Id].token for Id in...
convert Ids to tokens accounting for command and type tokens, tokens are joined and returned as a string.
DecodeIds
python
THUDM/GLM
data_utils/tokenization.py
https://github.com/THUDM/GLM/blob/master/data_utils/tokenization.py
MIT
def DecodeTokens(self, Tokens, type_token=False): """ convert tokens to a string accounting for command and type tokens. """ if type_token: return ' '.join(t.token if isinstance(t, TypeToken) else t for t in Tokens) rtn_strs = [] current_str = [] if is...
convert tokens to a string accounting for command and type tokens.
DecodeTokens
python
THUDM/GLM
data_utils/tokenization.py
https://github.com/THUDM/GLM/blob/master/data_utils/tokenization.py
MIT
def DecodeIds(self, Ids): """converts ascii ids to tokens before joining them into text""" if isinstance(Ids, Tokenization): Ids = Ids.tokenization return ''.join([self.IdToToken(tok) for tok in Ids])
converts ascii ids to tokens before joining them into text
DecodeIds
python
THUDM/GLM
data_utils/tokenization.py
https://github.com/THUDM/GLM/blob/master/data_utils/tokenization.py
MIT
def DecodeTokens(self, Tokens): """just concatenates ascii tokens into text""" if isinstance(Tokens, Tokenization): Tokens = Tokens.tokenization return ''.join(Tokens)
just concatenates ascii tokens into text
DecodeTokens
python
THUDM/GLM
data_utils/tokenization.py
https://github.com/THUDM/GLM/blob/master/data_utils/tokenization.py
MIT