index int64 0 50.7k | project_path stringclasses 279
values | completion_path stringlengths 57 199 | signature_postion stringlengths 3 11 | class_position stringlengths 3 11 | function_name stringlengths 1 62 | class_name stringlengths 0 55 | body_position stringlengths 3 11 | body_position_with_comments stringlengths 3 11 | masked_class stringlengths 14 8.32k | masked_class_with_comment stringlengths 14 8.32k | func_body stringlengths 9 6.72k | func_body_with_comment stringlengths 9 6.72k | len_func_body int64 1 643 | len_input int64 10 2.02k | len_output int64 4 1.9k | total int64 20 2.05k | file_code stringlengths 14 442k | file_code_with_comment stringlengths 14 442k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
18,394 | /home/hieuvd/dung_repo/raw/stars_01/jupyterhub_jupyterhub/jupyterhub | /home/hieuvd/dung_repo/raw/stars_01/jupyterhub_jupyterhub/jupyterhub/examples/service-whoami/whoami-oauth.py | 28,29 | 1,53 | main | 29,51 | 29,51 | """An example service authenticating with the Hub.
This example service serves `/services/whoami-oauth/`,
authenticated with the Hub,
showing the user their own info.
"""
import json
import os
from urllib.parse import urlparse
from tornado.httpserver import HTTPServer
from tornado.ioloop import IOLoop
from tornado.w... | """An example service authenticating with the Hub.
This example service serves `/services/whoami-oauth/`,
authenticated with the Hub,
showing the user their own info.
"""
import json
import os
from urllib.parse import urlparse
from tornado.httpserver import HTTPServer
from tornado.ioloop import IOLoop
from tornado.w... | app = Application(
[
(os.environ['JUPYTERHUB_SERVICE_PREFIX'], WhoAmIHandler),
(
url_path_join(
os.environ['JUPYTERHUB_SERVICE_PREFIX'], 'oauth_callback'
),
HubOAuthCallbackHandler,
),
(r'.*',... | app = Application(
[
(os.environ['JUPYTERHUB_SERVICE_PREFIX'], WhoAmIHandler),
(
url_path_join(
os.environ['JUPYTERHUB_SERVICE_PREFIX'], 'oauth_callback'
),
HubOAuthCallbackHandler,
),
(r'.*',... | 27 | 265 | 210 | 475 | """An example service authenticating with the Hub.
This example service serves `/services/whoami-oauth/`,
authenticated with the Hub,
showing the user their own info.
"""
import json
import os
from urllib.parse import urlparse
from tornado.httpserver import HTTPServer
from tornado.ioloop import IOLoop
from tornado.w... | """An example service authenticating with the Hub.
This example service serves `/services/whoami-oauth/`,
authenticated with the Hub,
showing the user their own info.
"""
import json
import os
from urllib.parse import urlparse
from tornado.httpserver import HTTPServer
from tornado.ioloop import IOLoop
from tornado.w... | |
18,395 | /home/hieuvd/dung_repo/raw/stars_01/jupyterhub_jupyterhub/jupyterhub | /home/hieuvd/dung_repo/raw/stars_01/jupyterhub_jupyterhub/jupyterhub/examples/service-whoami/whoami-oauth.py | 21,23 | 20,28 | get | WhoAmIHandler | 23,28 | 23,28 | class WhoAmIHandler(HubOAuthenticated, RequestHandler):
@authenticated
def get(self):
FILL_FUNC_BODY | class WhoAmIHandler(HubOAuthenticated, RequestHandler):
@authenticated
def get(self):
FILL_FUNC_BODY | user_model = self.get_current_user()
self.set_header('content-type', 'application/json')
self.write(json.dumps(user_model, indent=1, sort_keys=True))
| user_model = self.get_current_user()
self.set_header('content-type', 'application/json')
self.write(json.dumps(user_model, indent=1, sort_keys=True))
| 8 | 39 | 64 | 103 | """An example service authenticating with the Hub.
This example service serves `/services/whoami-oauth/`,
authenticated with the Hub,
showing the user their own info.
"""
import json
import os
from urllib.parse import urlparse
from tornado.httpserver import HTTPServer
from tornado.ioloop import IOLoop
from tornado.w... | """An example service authenticating with the Hub.
This example service serves `/services/whoami-oauth/`,
authenticated with the Hub,
showing the user their own info.
"""
import json
import os
from urllib.parse import urlparse
from tornado.httpserver import HTTPServer
from tornado.ioloop import IOLoop
from tornado.w... |
18,396 | /home/hieuvd/dung_repo/raw/stars_01/jupyterhub_jupyterhub/jupyterhub | /home/hieuvd/dung_repo/raw/stars_01/jupyterhub_jupyterhub/jupyterhub/examples/service-whoami/whoami.py | 27,28 | 1,45 | main | 28,43 | 28,43 | """An example service authenticating with the Hub.
This serves `/services/whoami-api/`, authenticated with the Hub, showing the user their own info.
HubAuthenticated only supports token-based access.
"""
import json
import os
from urllib.parse import urlparse
from tornado.httpserver import HTTPServer
from tornado.i... | """An example service authenticating with the Hub.
This serves `/services/whoami-api/`, authenticated with the Hub, showing the user their own info.
HubAuthenticated only supports token-based access.
"""
import json
import os
from urllib.parse import urlparse
from tornado.httpserver import HTTPServer
from tornado.i... | app = Application(
[
(os.environ['JUPYTERHUB_SERVICE_PREFIX'] + '/?', WhoAmIHandler),
(r'.*', WhoAmIHandler),
]
)
http_server = HTTPServer(app)
url = urlparse(os.environ['JUPYTERHUB_SERVICE_URL'])
http_server.listen(url.port, url.hostname)
IOLoop.curren... | app = Application(
[
(os.environ['JUPYTERHUB_SERVICE_PREFIX'] + '/?', WhoAmIHandler),
(r'.*', WhoAmIHandler),
]
)
http_server = HTTPServer(app)
url = urlparse(os.environ['JUPYTERHUB_SERVICE_URL'])
http_server.listen(url.port, url.hostname)
IOLoop.curren... | 21 | 247 | 142 | 389 | """An example service authenticating with the Hub.
This serves `/services/whoami-api/`, authenticated with the Hub, showing the user their own info.
HubAuthenticated only supports token-based access.
"""
import json
import os
from urllib.parse import urlparse
from tornado.httpserver import HTTPServer
from tornado.i... | """An example service authenticating with the Hub.
This serves `/services/whoami-api/`, authenticated with the Hub, showing the user their own info.
HubAuthenticated only supports token-based access.
"""
import json
import os
from urllib.parse import urlparse
from tornado.httpserver import HTTPServer
from tornado.i... | |
18,397 | /home/hieuvd/dung_repo/raw/stars_01/jupyterhub_jupyterhub/jupyterhub | /home/hieuvd/dung_repo/raw/stars_01/jupyterhub_jupyterhub/jupyterhub/examples/service-whoami/whoami.py | 20,22 | 19,27 | get | WhoAmIHandler | 22,27 | 22,27 | class WhoAmIHandler(HubAuthenticated, RequestHandler):
@authenticated
def get(self):
FILL_FUNC_BODY | class WhoAmIHandler(HubAuthenticated, RequestHandler):
@authenticated
def get(self):
FILL_FUNC_BODY | user_model = self.get_current_user()
self.set_header('content-type', 'application/json')
self.write(json.dumps(user_model, indent=1, sort_keys=True))
| user_model = self.get_current_user()
self.set_header('content-type', 'application/json')
self.write(json.dumps(user_model, indent=1, sort_keys=True))
| 8 | 38 | 64 | 102 | """An example service authenticating with the Hub.
This serves `/services/whoami-api/`, authenticated with the Hub, showing the user their own info.
HubAuthenticated only supports token-based access.
"""
import json
import os
from urllib.parse import urlparse
from tornado.httpserver import HTTPServer
from tornado.i... | """An example service authenticating with the Hub.
This serves `/services/whoami-api/`, authenticated with the Hub, showing the user their own info.
HubAuthenticated only supports token-based access.
"""
import json
import os
from urllib.parse import urlparse
from tornado.httpserver import HTTPServer
from tornado.i... |
18,398 | /home/hieuvd/dung_repo/raw/stars_01/jupyterhub_jupyterhub/jupyterhub | /home/hieuvd/dung_repo/raw/stars_01/jupyterhub_jupyterhub/jupyterhub/jupyterhub/_data.py | 4,5 | 1,27 | get_data_files | 6,26 | 5,26 | """Get the data files for this package."""
def get_data_files():
FILL_FUNC_BODYDATA_FILES_PATH = get_data_files()
| """Get the data files for this package."""
def get_data_files():
"""Walk up until we find share/jupyterhub"""
FILL_FUNC_BODYDATA_FILES_PATH = get_data_files()
| import sys
from os.path import abspath, dirname, exists, join, split
path = abspath(dirname(__file__))
starting_points = [path]
if not path.startswith(sys.prefix):
starting_points.append(sys.prefix)
for path in starting_points:
# walk up, looking for prefix/share/jupyter
... | """Walk up until we find share/jupyterhub"""
import sys
from os.path import abspath, dirname, exists, join, split
path = abspath(dirname(__file__))
starting_points = [path]
if not path.startswith(sys.prefix):
starting_points.append(sys.prefix)
for path in starting_points:
# ... | 76 | 61 | 243 | 304 | """Get the data files for this package."""
def get_data_files():
FILL_FUNC_BODYDATA_FILES_PATH = get_data_files()
| """Get the data files for this package."""
def get_data_files():
"""Walk up until we find share/jupyterhub"""
FILL_FUNC_BODYDATA_FILES_PATH = get_data_files()
| |
18,400 | /home/hieuvd/dung_repo/raw/stars_01/jupyterhub_jupyterhub/jupyterhub | /home/hieuvd/dung_repo/raw/stars_01/jupyterhub_jupyterhub/jupyterhub/jupyterhub/alembic/env.py | 55,56 | 1,114 | run_migrations_offline | 67,82 | 56,82 | import logging
import sys
from logging.config import fileConfig
from alembic import context
from sqlalchemy import engine_from_config, pool
# this is the Alembic Config object, which provides
# access to the values within the .ini file in use.
config = context.config
# Interpret the config file for Python logging.
# ... | import logging
import sys
from logging.config import fileConfig
from alembic import context
from sqlalchemy import engine_from_config, pool
# this is the Alembic Config object, which provides
# access to the values within the .ini file in use.
config = context.config
# Interpret the config file for Python logging.
# ... | connectable = config.attributes.get('connection', None)
config_opts = {}
config_opts.update(common_config_opts)
config_opts["literal_binds"] = True
if connectable is None:
config_opts["url"] = config.get_main_option("sqlalchemy.url")
else:
config_opts["connection"] = connectable... | """Run migrations in 'offline' mode.
This configures the context with just a URL
and not an Engine, though an Engine is acceptable
here as well. By skipping the Engine creation
we don't even need a DBAPI to be available.
Calls to context.execute() here emit the given string to the
script ... | 26 | 822 | 146 | 968 | import logging
import sys
from logging.config import fileConfig
from alembic import context
from sqlalchemy import engine_from_config, pool
# this is the Alembic Config object, which provides
# access to the values within the .ini file in use.
config = context.config
# Interpret the config file for Python logging.
# ... | import logging
import sys
from logging.config import fileConfig
from alembic import context
from sqlalchemy import engine_from_config, pool
# this is the Alembic Config object, which provides
# access to the values within the .ini file in use.
config = context.config
# Interpret the config file for Python logging.
# ... | |
18,401 | /home/hieuvd/dung_repo/raw/stars_01/jupyterhub_jupyterhub/jupyterhub | /home/hieuvd/dung_repo/raw/stars_01/jupyterhub_jupyterhub/jupyterhub/jupyterhub/alembic/versions/0eee8c825d24_added_properties_column.py | 21,22 | 1,30 | upgrade | 22,28 | 22,28 | """added properties column
Revision ID: 0eee8c825d24
Revises: 833da8570507
Create Date: 2021-09-15 14:04:09.067024
"""
# revision identifiers, used by Alembic.
revision = '0eee8c825d24'
down_revision = '651f5419b74d'
branch_labels = None
depends_on = None
import sqlalchemy as sa
from alembic import op
from jupyter... | """added properties column
Revision ID: 0eee8c825d24
Revises: 833da8570507
Create Date: 2021-09-15 14:04:09.067024
"""
# revision identifiers, used by Alembic.
revision = '0eee8c825d24'
down_revision = '651f5419b74d'
branch_labels = None
depends_on = None
import sqlalchemy as sa
from alembic import op
from jupyter... | engine = op.get_bind().engine
tables = sa.inspect(engine).get_table_names()
if 'groups' in tables:
op.add_column('groups', sa.Column('properties', JSONDict))
| engine = op.get_bind().engine
tables = sa.inspect(engine).get_table_names()
if 'groups' in tables:
op.add_column('groups', sa.Column('properties', JSONDict))
| 13 | 205 | 65 | 270 | """added properties column
Revision ID: 0eee8c825d24
Revises: 833da8570507
Create Date: 2021-09-15 14:04:09.067024
"""
# revision identifiers, used by Alembic.
revision = '0eee8c825d24'
down_revision = '651f5419b74d'
branch_labels = None
depends_on = None
import sqlalchemy as sa
from alembic import op
from jupyter... | """added properties column
Revision ID: 0eee8c825d24
Revises: 833da8570507
Create Date: 2021-09-15 14:04:09.067024
"""
# revision identifiers, used by Alembic.
revision = '0eee8c825d24'
down_revision = '651f5419b74d'
branch_labels = None
depends_on = None
import sqlalchemy as sa
from alembic import op
from jupyter... | |
18,403 | /home/hieuvd/dung_repo/raw/stars_01/jupyterhub_jupyterhub/jupyterhub | /home/hieuvd/dung_repo/raw/stars_01/jupyterhub_jupyterhub/jupyterhub/jupyterhub/alembic/versions/1cebaf56856c_session_id.py | 25,26 | 1,44 | add_column_if_table_exists | 26,35 | 26,35 | """Add session_id to auth tokens
Revision ID: 1cebaf56856c
Revises: 3ec6993fe20c
Create Date: 2017-12-07 14:43:51.500740
"""
# revision identifiers, used by Alembic.
revision = '1cebaf56856c'
down_revision = '3ec6993fe20c'
branch_labels = None
depends_on = None
import logging
logger = logging.getLogger('alembic')
... | """Add session_id to auth tokens
Revision ID: 1cebaf56856c
Revises: 3ec6993fe20c
Create Date: 2017-12-07 14:43:51.500740
"""
# revision identifiers, used by Alembic.
revision = '1cebaf56856c'
down_revision = '3ec6993fe20c'
branch_labels = None
depends_on = None
import logging
logger = logging.getLogger('alembic')
... | engine = op.get_bind().engine
if table not in sa.inspect(engine).get_table_names():
# table doesn't exist, no need to upgrade
# because jupyterhub will create it on launch
logger.warning("Skipping upgrade of absent table: %s", table)
return
op.add_column(table, column)
| engine = op.get_bind().engine
if table not in sa.inspect(engine).get_table_names():
# table doesn't exist, no need to upgrade
# because jupyterhub will create it on launch
logger.warning("Skipping upgrade of absent table: %s", table)
return
op.add_column(table, column)
| 34 | 311 | 102 | 413 | """Add session_id to auth tokens
Revision ID: 1cebaf56856c
Revises: 3ec6993fe20c
Create Date: 2017-12-07 14:43:51.500740
"""
# revision identifiers, used by Alembic.
revision = '1cebaf56856c'
down_revision = '3ec6993fe20c'
branch_labels = None
depends_on = None
import logging
logger = logging.getLogger('alembic')
... | """Add session_id to auth tokens
Revision ID: 1cebaf56856c
Revises: 3ec6993fe20c
Create Date: 2017-12-07 14:43:51.500740
"""
# revision identifiers, used by Alembic.
revision = '1cebaf56856c'
down_revision = '3ec6993fe20c'
branch_labels = None
depends_on = None
import logging
logger = logging.getLogger('alembic')
... | |
18,404 | /home/hieuvd/dung_repo/raw/stars_01/jupyterhub_jupyterhub/jupyterhub | /home/hieuvd/dung_repo/raw/stars_01/jupyterhub_jupyterhub/jupyterhub/jupyterhub/alembic/versions/3c2384c5aae1_add_from_config_column_to_the_services_.py | 32,33 | 1,52 | upgrade | 33,48 | 33,48 | """Add from_config column to the services table
Revision ID: 3c2384c5aae1
Revises: 0eee8c825d24
Create Date: 2023-02-27 16:22:26.196231
"""
# revision identifiers, used by Alembic.
revision = '3c2384c5aae1'
down_revision = '0eee8c825d24'
branch_labels = None
depends_on = None
import sqlalchemy as sa
from alembic imp... | """Add from_config column to the services table
Revision ID: 3c2384c5aae1
Revises: 0eee8c825d24
Create Date: 2023-02-27 16:22:26.196231
"""
# revision identifiers, used by Alembic.
revision = '3c2384c5aae1'
down_revision = '0eee8c825d24'
branch_labels = None
depends_on = None
import sqlalchemy as sa
from alembic imp... | engine = op.get_bind().engine
tables = sa.inspect(engine).get_table_names()
if 'services' in tables:
op.add_column(
'services',
sa.Column('from_config', sa.Boolean, default=True),
)
op.execute('UPDATE services SET from_config = true')
for item in COL_D... | engine = op.get_bind().engine
tables = sa.inspect(engine).get_table_names()
if 'services' in tables:
op.add_column(
'services',
sa.Column('from_config', sa.Boolean, default=True),
)
op.execute('UPDATE services SET from_config = true')
for item in COL_D... | 32 | 425 | 147 | 572 | """Add from_config column to the services table
Revision ID: 3c2384c5aae1
Revises: 0eee8c825d24
Create Date: 2023-02-27 16:22:26.196231
"""
# revision identifiers, used by Alembic.
revision = '3c2384c5aae1'
down_revision = '0eee8c825d24'
branch_labels = None
depends_on = None
import sqlalchemy as sa
from alembic imp... | """Add from_config column to the services table
Revision ID: 3c2384c5aae1
Revises: 0eee8c825d24
Create Date: 2023-02-27 16:22:26.196231
"""
# revision identifiers, used by Alembic.
revision = '3c2384c5aae1'
down_revision = '0eee8c825d24'
branch_labels = None
depends_on = None
import sqlalchemy as sa
from alembic imp... | |
18,405 | /home/hieuvd/dung_repo/raw/stars_01/jupyterhub_jupyterhub/jupyterhub | /home/hieuvd/dung_repo/raw/stars_01/jupyterhub_jupyterhub/jupyterhub/jupyterhub/alembic/versions/3ec6993fe20c_encrypted_auth_state.py | 57,58 | 1,70 | downgrade | 58,70 | 58,70 | """0.8 changes
- encrypted auth_state
- remove proxy/hub data from db
OAuth data was also added in this revision,
but no migration to do because they are entirely new tables,
which will be created on launch.
Revision ID: 3ec6993fe20c
Revises: af4cbdb2d13c
Create Date: 2017-07-28 16:44:40.413648
"""
# revision iden... | """0.8 changes
- encrypted auth_state
- remove proxy/hub data from db
OAuth data was also added in this revision,
but no migration to do because they are entirely new tables,
which will be created on launch.
Revision ID: 3ec6993fe20c
Revises: af4cbdb2d13c
Create Date: 2017-07-28 16:44:40.413648
"""
# revision iden... | # drop all the new tables
engine = op.get_bind().engine
for table in ('oauth_clients', 'oauth_codes', 'oauth_access_tokens', 'spawners'):
if engine.has_table(table):
op.drop_table(table)
op.drop_column('users', 'encrypted_auth_state')
op.add_column('users', sa.Column('auth_stat... | # drop all the new tables
engine = op.get_bind().engine
for table in ('oauth_clients', 'oauth_codes', 'oauth_access_tokens', 'spawners'):
if engine.has_table(table):
op.drop_table(table)
op.drop_column('users', 'encrypted_auth_state')
op.add_column('users', sa.Column('auth_stat... | 30 | 508 | 167 | 675 | """0.8 changes
- encrypted auth_state
- remove proxy/hub data from db
OAuth data was also added in this revision,
but no migration to do because they are entirely new tables,
which will be created on launch.
Revision ID: 3ec6993fe20c
Revises: af4cbdb2d13c
Create Date: 2017-07-28 16:44:40.413648
"""
# revision iden... | """0.8 changes
- encrypted auth_state
- remove proxy/hub data from db
OAuth data was also added in this revision,
but no migration to do because they are entirely new tables,
which will be created on launch.
Revision ID: 3ec6993fe20c
Revises: af4cbdb2d13c
Create Date: 2017-07-28 16:44:40.413648
"""
# revision iden... | |
18,406 | /home/hieuvd/dung_repo/raw/stars_01/jupyterhub_jupyterhub/jupyterhub | /home/hieuvd/dung_repo/raw/stars_01/jupyterhub_jupyterhub/jupyterhub/jupyterhub/alembic/versions/4621fec11365_manage_roles.py | 38,39 | 1,45 | downgrade | 39,45 | 39,45 | """manage roles
Revision ID: 4621fec11365
Revises: 3c2384c5aae1
Create Date: 2024-04-09 09:28:13.576059
"""
# revision identifiers, used by Alembic.
revision = '4621fec11365'
down_revision = '3c2384c5aae1'
branch_labels = None
depends_on = None
import sqlalchemy as sa
from alembic import op
def upgrade():
eng... | """manage roles
Revision ID: 4621fec11365
Revises: 3c2384c5aae1
Create Date: 2024-04-09 09:28:13.576059
"""
# revision identifiers, used by Alembic.
revision = '4621fec11365'
down_revision = '3c2384c5aae1'
branch_labels = None
depends_on = None
import sqlalchemy as sa
from alembic import op
def upgrade():
eng... | engine = op.get_bind().engine
tables = sa.inspect(engine).get_table_names()
for table in ['group_role_map', 'roles', 'service_role_map', 'user_role_map']:
if table not in tables:
continue
op.drop_column(table, 'managed_by_auth')
| engine = op.get_bind().engine
tables = sa.inspect(engine).get_table_names()
for table in ['group_role_map', 'roles', 'service_role_map', 'user_role_map']:
if table not in tables:
continue
op.drop_column(table, 'managed_by_auth')
| 21 | 324 | 94 | 418 | """manage roles
Revision ID: 4621fec11365
Revises: 3c2384c5aae1
Create Date: 2024-04-09 09:28:13.576059
"""
# revision identifiers, used by Alembic.
revision = '4621fec11365'
down_revision = '3c2384c5aae1'
branch_labels = None
depends_on = None
import sqlalchemy as sa
from alembic import op
def upgrade():
eng... | """manage roles
Revision ID: 4621fec11365
Revises: 3c2384c5aae1
Create Date: 2024-04-09 09:28:13.576059
"""
# revision identifiers, used by Alembic.
revision = '4621fec11365'
down_revision = '3c2384c5aae1'
branch_labels = None
depends_on = None
import sqlalchemy as sa
from alembic import op
def upgrade():
eng... | |
18,407 | /home/hieuvd/dung_repo/raw/stars_01/jupyterhub_jupyterhub/jupyterhub | /home/hieuvd/dung_repo/raw/stars_01/jupyterhub_jupyterhub/jupyterhub/jupyterhub/alembic/versions/4dc2d5a8c53c_user_options.py | 21,22 | 1,30 | upgrade | 22,28 | 22,28 | """persist user_options
Revision ID: 4dc2d5a8c53c
Revises: 896818069c98
Create Date: 2019-02-28 14:14:27.423927
"""
# revision identifiers, used by Alembic.
revision = '4dc2d5a8c53c'
down_revision = '896818069c98'
branch_labels = None
depends_on = None
import sqlalchemy as sa
from alembic import op
from jupyterhub... | """persist user_options
Revision ID: 4dc2d5a8c53c
Revises: 896818069c98
Create Date: 2019-02-28 14:14:27.423927
"""
# revision identifiers, used by Alembic.
revision = '4dc2d5a8c53c'
down_revision = '896818069c98'
branch_labels = None
depends_on = None
import sqlalchemy as sa
from alembic import op
from jupyterhub... | engine = op.get_bind().engine
tables = sa.inspect(engine).get_table_names()
if 'spawners' in tables:
op.add_column('spawners', sa.Column('user_options', JSONDict()))
| engine = op.get_bind().engine
tables = sa.inspect(engine).get_table_names()
if 'spawners' in tables:
op.add_column('spawners', sa.Column('user_options', JSONDict()))
| 13 | 212 | 71 | 283 | """persist user_options
Revision ID: 4dc2d5a8c53c
Revises: 896818069c98
Create Date: 2019-02-28 14:14:27.423927
"""
# revision identifiers, used by Alembic.
revision = '4dc2d5a8c53c'
down_revision = '896818069c98'
branch_labels = None
depends_on = None
import sqlalchemy as sa
from alembic import op
from jupyterhub... | """persist user_options
Revision ID: 4dc2d5a8c53c
Revises: 896818069c98
Create Date: 2019-02-28 14:14:27.423927
"""
# revision identifiers, used by Alembic.
revision = '4dc2d5a8c53c'
down_revision = '896818069c98'
branch_labels = None
depends_on = None
import sqlalchemy as sa
from alembic import op
from jupyterhub... | |
18,408 | /home/hieuvd/dung_repo/raw/stars_01/jupyterhub_jupyterhub/jupyterhub | /home/hieuvd/dung_repo/raw/stars_01/jupyterhub_jupyterhub/jupyterhub/jupyterhub/alembic/versions/56cc5a70207e_token_tracking.py | 64,65 | 1,72 | downgrade | 65,72 | 65,72 | """token tracking
Revision ID: 56cc5a70207e
Revises: 1cebaf56856c
Create Date: 2017-12-19 15:21:09.300513
"""
# revision identifiers, used by Alembic.
revision = '56cc5a70207e'
down_revision = '1cebaf56856c'
branch_labels = None
depends_on = None
import logging
import sqlalchemy as sa
from alembic import op
logge... | """token tracking
Revision ID: 56cc5a70207e
Revises: 1cebaf56856c
Create Date: 2017-12-19 15:21:09.300513
"""
# revision identifiers, used by Alembic.
revision = '56cc5a70207e'
down_revision = '1cebaf56856c'
branch_labels = None
depends_on = None
import logging
import sqlalchemy as sa
from alembic import op
logge... | op.drop_constraint(None, 'oauth_codes', type_='foreignkey')
op.drop_constraint(None, 'oauth_access_tokens', type_='foreignkey')
op.drop_column('oauth_access_tokens', 'last_activity')
op.drop_column('oauth_access_tokens', 'created')
op.drop_column('api_tokens', 'note')
op.drop_column('api_tokens'... | op.drop_constraint(None, 'oauth_codes', type_='foreignkey')
op.drop_constraint(None, 'oauth_access_tokens', type_='foreignkey')
op.drop_column('oauth_access_tokens', 'last_activity')
op.drop_column('oauth_access_tokens', 'created')
op.drop_column('api_tokens', 'note')
op.drop_column('api_tokens'... | 16 | 589 | 149 | 738 | """token tracking
Revision ID: 56cc5a70207e
Revises: 1cebaf56856c
Create Date: 2017-12-19 15:21:09.300513
"""
# revision identifiers, used by Alembic.
revision = '56cc5a70207e'
down_revision = '1cebaf56856c'
branch_labels = None
depends_on = None
import logging
import sqlalchemy as sa
from alembic import op
logge... | """token tracking
Revision ID: 56cc5a70207e
Revises: 1cebaf56856c
Create Date: 2017-12-19 15:21:09.300513
"""
# revision identifiers, used by Alembic.
revision = '56cc5a70207e'
down_revision = '1cebaf56856c'
branch_labels = None
depends_on = None
import logging
import sqlalchemy as sa
from alembic import op
logge... | |
18,409 | /home/hieuvd/dung_repo/raw/stars_01/jupyterhub_jupyterhub/jupyterhub | /home/hieuvd/dung_repo/raw/stars_01/jupyterhub_jupyterhub/jupyterhub/jupyterhub/alembic/versions/651f5419b74d_api_token_scopes.py | 46,47 | 1,146 | upgrade | 47,140 | 47,140 | """api_token_scopes
Revision ID: 651f5419b74d
Revises: 833da8570507
Create Date: 2022-02-28 12:42:55.149046
"""
# revision identifiers, used by Alembic.
revision = '651f5419b74d'
down_revision = '833da8570507'
branch_labels = None
depends_on = None
import sqlalchemy as sa
from alembic import op
from sqlalchemy impo... | """api_token_scopes
Revision ID: 651f5419b74d
Revises: 833da8570507
Create Date: 2022-02-28 12:42:55.149046
"""
# revision identifiers, used by Alembic.
revision = '651f5419b74d'
down_revision = '833da8570507'
branch_labels = None
depends_on = None
import sqlalchemy as sa
from alembic import op
from sqlalchemy impo... | c = op.get_bind()
tables = sa.inspect(c.engine).get_table_names()
# oauth codes are short lived, no need to upgrade them
if 'oauth_code_role_map' in tables:
op.drop_table('oauth_code_role_map')
if 'oauth_codes' in tables:
op.add_column('oauth_codes', sa.Column('scopes', orm.JSONLis... | c = op.get_bind()
tables = sa.inspect(c.engine).get_table_names()
# oauth codes are short lived, no need to upgrade them
if 'oauth_code_role_map' in tables:
op.drop_table('oauth_code_role_map')
if 'oauth_codes' in tables:
op.add_column('oauth_codes', sa.Column('scopes', orm.JSONLis... | 236 | 563 | 1,123 | 1,686 | """api_token_scopes
Revision ID: 651f5419b74d
Revises: 833da8570507
Create Date: 2022-02-28 12:42:55.149046
"""
# revision identifiers, used by Alembic.
revision = '651f5419b74d'
down_revision = '833da8570507'
branch_labels = None
depends_on = None
import sqlalchemy as sa
from alembic import op
from sqlalchemy impo... | """api_token_scopes
Revision ID: 651f5419b74d
Revises: 833da8570507
Create Date: 2022-02-28 12:42:55.149046
"""
# revision identifiers, used by Alembic.
revision = '651f5419b74d'
down_revision = '833da8570507'
branch_labels = None
depends_on = None
import sqlalchemy as sa
from alembic import op
from sqlalchemy impo... | |
18,410 | /home/hieuvd/dung_repo/raw/stars_01/jupyterhub_jupyterhub/jupyterhub | /home/hieuvd/dung_repo/raw/stars_01/jupyterhub_jupyterhub/jupyterhub/jupyterhub/alembic/versions/833da8570507_rbac.py | 69,70 | 1,105 | downgrade | 70,105 | 70,105 | """
rbac changes for jupyterhub 2.0
Revision ID: 833da8570507
Revises: 4dc2d5a8c53c
Create Date: 2021-02-17 15:03:04.360368
"""
# revision identifiers, used by Alembic.
revision = '833da8570507'
down_revision = '4dc2d5a8c53c'
branch_labels = None
depends_on = None
import sqlalchemy as sa
from alembic import op
fro... | """
rbac changes for jupyterhub 2.0
Revision ID: 833da8570507
Revises: 4dc2d5a8c53c
Create Date: 2021-02-17 15:03:04.360368
"""
# revision identifiers, used by Alembic.
revision = '833da8570507'
down_revision = '4dc2d5a8c53c'
branch_labels = None
depends_on = None
import sqlalchemy as sa
from alembic import op
fro... | for table_name in ('services', 'spawners'):
column_name = "oauth_client_id"
target_table = "oauth_clients"
target_column = "identifier"
with op.batch_alter_table(
table_name,
schema=None,
naming_convention=orm.meta.naming_convention,
) as ... | for table_name in ('services', 'spawners'):
column_name = "oauth_client_id"
target_table = "oauth_clients"
target_column = "identifier"
with op.batch_alter_table(
table_name,
schema=None,
naming_convention=orm.meta.naming_convention,
) as ... | 79 | 704 | 419 | 1,123 | """
rbac changes for jupyterhub 2.0
Revision ID: 833da8570507
Revises: 4dc2d5a8c53c
Create Date: 2021-02-17 15:03:04.360368
"""
# revision identifiers, used by Alembic.
revision = '833da8570507'
down_revision = '4dc2d5a8c53c'
branch_labels = None
depends_on = None
import sqlalchemy as sa
from alembic import op
fro... | """
rbac changes for jupyterhub 2.0
Revision ID: 833da8570507
Revises: 4dc2d5a8c53c
Create Date: 2021-02-17 15:03:04.360368
"""
# revision identifiers, used by Alembic.
revision = '833da8570507'
down_revision = '4dc2d5a8c53c'
branch_labels = None
depends_on = None
import sqlalchemy as sa
from alembic import op
fro... | |
18,411 | /home/hieuvd/dung_repo/raw/stars_01/jupyterhub_jupyterhub/jupyterhub | /home/hieuvd/dung_repo/raw/stars_01/jupyterhub_jupyterhub/jupyterhub/jupyterhub/alembic/versions/896818069c98_token_expires.py | 19,20 | 1,25 | upgrade | 20,23 | 20,23 | """Add APIToken.expires_at
Revision ID: 896818069c98
Revises: d68c98b66cd4
Create Date: 2018-05-07 11:35:58.050542
"""
# revision identifiers, used by Alembic.
revision = '896818069c98'
down_revision = 'd68c98b66cd4'
branch_labels = None
depends_on = None
import sqlalchemy as sa
from alembic import op
def upgrade... | """Add APIToken.expires_at
Revision ID: 896818069c98
Revises: d68c98b66cd4
Create Date: 2018-05-07 11:35:58.050542
"""
# revision identifiers, used by Alembic.
revision = '896818069c98'
down_revision = 'd68c98b66cd4'
branch_labels = None
depends_on = None
import sqlalchemy as sa
from alembic import op
def upgrade... | op.add_column('api_tokens', sa.Column('expires_at', sa.DateTime(), nullable=True))
| op.add_column('api_tokens', sa.Column('expires_at', sa.DateTime(), nullable=True))
| 4 | 199 | 36 | 235 | """Add APIToken.expires_at
Revision ID: 896818069c98
Revises: d68c98b66cd4
Create Date: 2018-05-07 11:35:58.050542
"""
# revision identifiers, used by Alembic.
revision = '896818069c98'
down_revision = 'd68c98b66cd4'
branch_labels = None
depends_on = None
import sqlalchemy as sa
from alembic import op
def upgrade... | """Add APIToken.expires_at
Revision ID: 896818069c98
Revises: d68c98b66cd4
Create Date: 2018-05-07 11:35:58.050542
"""
# revision identifiers, used by Alembic.
revision = '896818069c98'
down_revision = 'd68c98b66cd4'
branch_labels = None
depends_on = None
import sqlalchemy as sa
from alembic import op
def upgrade... | |
18,412 | /home/hieuvd/dung_repo/raw/stars_01/jupyterhub_jupyterhub/jupyterhub | /home/hieuvd/dung_repo/raw/stars_01/jupyterhub_jupyterhub/jupyterhub/jupyterhub/alembic/versions/99a28a4418e1_user_created.py | 26,27 | 1,55 | upgrade | 27,52 | 27,52 | """user.created and spawner.started
Revision ID: 99a28a4418e1
Revises: 56cc5a70207e
Create Date: 2018-03-21 14:27:17.466841
"""
# revision identifiers, used by Alembic.
revision = '99a28a4418e1'
down_revision = '56cc5a70207e'
branch_labels = None
depends_on = None
from datetime import datetime, timezone
import sq... | """user.created and spawner.started
Revision ID: 99a28a4418e1
Revises: 56cc5a70207e
Create Date: 2018-03-21 14:27:17.466841
"""
# revision identifiers, used by Alembic.
revision = '99a28a4418e1'
down_revision = '56cc5a70207e'
branch_labels = None
depends_on = None
from datetime import datetime, timezone
import sq... | op.add_column('users', sa.Column('created', sa.DateTime, nullable=True))
c = op.get_bind()
# fill created date with current time
now = utcnow()
c.execute(
f"""
UPDATE users
SET created='{now}'
"""
)
tables = sa.inspect(c.engine).get_table_names()
if 'spa... | op.add_column('users', sa.Column('created', sa.DateTime, nullable=True))
c = op.get_bind()
# fill created date with current time
now = utcnow()
c.execute(
f"""
UPDATE users
SET created='{now}'
"""
)
tables = sa.inspect(c.engine).get_table_names()
if 'spa... | 58 | 249 | 218 | 467 | """user.created and spawner.started
Revision ID: 99a28a4418e1
Revises: 56cc5a70207e
Create Date: 2018-03-21 14:27:17.466841
"""
# revision identifiers, used by Alembic.
revision = '99a28a4418e1'
down_revision = '56cc5a70207e'
branch_labels = None
depends_on = None
from datetime import datetime, timezone
import sq... | """user.created and spawner.started
Revision ID: 99a28a4418e1
Revises: 56cc5a70207e
Create Date: 2018-03-21 14:27:17.466841
"""
# revision identifiers, used by Alembic.
revision = '99a28a4418e1'
down_revision = '56cc5a70207e'
branch_labels = None
depends_on = None
from datetime import datetime, timezone
import sq... | |
18,413 | /home/hieuvd/dung_repo/raw/stars_01/jupyterhub_jupyterhub/jupyterhub | /home/hieuvd/dung_repo/raw/stars_01/jupyterhub_jupyterhub/jupyterhub/jupyterhub/alembic/versions/af4cbdb2d13c_services.py | 19,20 | 1,26 | upgrade | 20,23 | 20,23 | """services
Revision ID: af4cbdb2d13c
Revises: eeb276e51423
Create Date: 2016-07-28 16:16:38.245348
"""
# revision identifiers, used by Alembic.
revision = 'af4cbdb2d13c'
down_revision = 'eeb276e51423'
branch_labels = None
depends_on = None
import sqlalchemy as sa
from alembic import op
def upgrade():
FILL_FUNC_B... | """services
Revision ID: af4cbdb2d13c
Revises: eeb276e51423
Create Date: 2016-07-28 16:16:38.245348
"""
# revision identifiers, used by Alembic.
revision = 'af4cbdb2d13c'
down_revision = 'eeb276e51423'
branch_labels = None
depends_on = None
import sqlalchemy as sa
from alembic import op
def upgrade():
FILL_FUNC_B... | op.add_column('api_tokens', sa.Column('service_id', sa.Integer))
| op.add_column('api_tokens', sa.Column('service_id', sa.Integer))
| 3 | 206 | 30 | 236 | """services
Revision ID: af4cbdb2d13c
Revises: eeb276e51423
Create Date: 2016-07-28 16:16:38.245348
"""
# revision identifiers, used by Alembic.
revision = 'af4cbdb2d13c'
down_revision = 'eeb276e51423'
branch_labels = None
depends_on = None
import sqlalchemy as sa
from alembic import op
def upgrade():
FILL_FUNC_B... | """services
Revision ID: af4cbdb2d13c
Revises: eeb276e51423
Create Date: 2016-07-28 16:16:38.245348
"""
# revision identifiers, used by Alembic.
revision = 'af4cbdb2d13c'
down_revision = 'eeb276e51423'
branch_labels = None
depends_on = None
import sqlalchemy as sa
from alembic import op
def upgrade():
FILL_FUNC_B... | |
18,414 | /home/hieuvd/dung_repo/raw/stars_01/jupyterhub_jupyterhub/jupyterhub | /home/hieuvd/dung_repo/raw/stars_01/jupyterhub_jupyterhub/jupyterhub/jupyterhub/alembic/versions/d68c98b66cd4_client_description.py | 19,20 | 1,30 | upgrade | 20,28 | 20,28 | """client-description
Revision ID: d68c98b66cd4
Revises: 99a28a4418e1
Create Date: 2018-04-13 10:50:17.968636
"""
# revision identifiers, used by Alembic.
revision = 'd68c98b66cd4'
down_revision = '99a28a4418e1'
branch_labels = None
depends_on = None
import sqlalchemy as sa
from alembic import op
def upgrade():
F... | """client-description
Revision ID: d68c98b66cd4
Revises: 99a28a4418e1
Create Date: 2018-04-13 10:50:17.968636
"""
# revision identifiers, used by Alembic.
revision = 'd68c98b66cd4'
down_revision = '99a28a4418e1'
branch_labels = None
depends_on = None
import sqlalchemy as sa
from alembic import op
def upgrade():
F... | engine = op.get_bind().engine
tables = sa.inspect(engine).get_table_names()
if 'oauth_clients' in tables:
op.add_column(
'oauth_clients', sa.Column('description', sa.Unicode(length=1023))
)
| engine = op.get_bind().engine
tables = sa.inspect(engine).get_table_names()
if 'oauth_clients' in tables:
op.add_column(
'oauth_clients', sa.Column('description', sa.Unicode(length=1023))
)
| 15 | 191 | 89 | 280 | """client-description
Revision ID: d68c98b66cd4
Revises: 99a28a4418e1
Create Date: 2018-04-13 10:50:17.968636
"""
# revision identifiers, used by Alembic.
revision = 'd68c98b66cd4'
down_revision = '99a28a4418e1'
branch_labels = None
depends_on = None
import sqlalchemy as sa
from alembic import op
def upgrade():
F... | """client-description
Revision ID: d68c98b66cd4
Revises: 99a28a4418e1
Create Date: 2018-04-13 10:50:17.968636
"""
# revision identifiers, used by Alembic.
revision = 'd68c98b66cd4'
down_revision = '99a28a4418e1'
branch_labels = None
depends_on = None
import sqlalchemy as sa
from alembic import op
def upgrade():
F... | |
18,415 | /home/hieuvd/dung_repo/raw/stars_01/jupyterhub_jupyterhub/jupyterhub | /home/hieuvd/dung_repo/raw/stars_01/jupyterhub_jupyterhub/jupyterhub/jupyterhub/alembic/versions/eeb276e51423_auth_state.py | 22,23 | 1,29 | upgrade | 23,26 | 23,26 | """auth_state
Adds auth_state column to Users table.
Revision ID: eeb276e51423
Revises: 19c0846f6344
Create Date: 2016-04-11 16:06:49.239831
"""
# revision identifiers, used by Alembic.
revision = 'eeb276e51423'
down_revision = '19c0846f6344'
branch_labels = None
depends_on = None
import sqlalchemy as sa
from alemb... | """auth_state
Adds auth_state column to Users table.
Revision ID: eeb276e51423
Revises: 19c0846f6344
Create Date: 2016-04-11 16:06:49.239831
"""
# revision identifiers, used by Alembic.
revision = 'eeb276e51423'
down_revision = '19c0846f6344'
branch_labels = None
depends_on = None
import sqlalchemy as sa
from alemb... | op.add_column('users', sa.Column('auth_state', JSONDict))
| op.add_column('users', sa.Column('auth_state', JSONDict))
| 3 | 238 | 27 | 265 | """auth_state
Adds auth_state column to Users table.
Revision ID: eeb276e51423
Revises: 19c0846f6344
Create Date: 2016-04-11 16:06:49.239831
"""
# revision identifiers, used by Alembic.
revision = 'eeb276e51423'
down_revision = '19c0846f6344'
branch_labels = None
depends_on = None
import sqlalchemy as sa
from alemb... | """auth_state
Adds auth_state column to Users table.
Revision ID: eeb276e51423
Revises: 19c0846f6344
Create Date: 2016-04-11 16:06:49.239831
"""
# revision identifiers, used by Alembic.
revision = 'eeb276e51423'
down_revision = '19c0846f6344'
branch_labels = None
depends_on = None
import sqlalchemy as sa
from alemb... | |
18,416 | /home/hieuvd/dung_repo/raw/stars_01/jupyterhub_jupyterhub/jupyterhub | /home/hieuvd/dung_repo/raw/stars_01/jupyterhub_jupyterhub/jupyterhub/jupyterhub/apihandlers/groups.py | 115,117 | 107,154 | post | GroupAPIHandler | 118,143 | 117,143 | class GroupAPIHandler(_GroupAPIHandler):
"""View and modify groups by name"""
@needs_scope('read:groups', 'read:groups:name', 'read:roles:groups')
def get(self, group_name):
group = self.find_group(group_name)
self.write(json.dumps(self.group_model(group)))
@needs_scope('admin:groups')... | class GroupAPIHandler(_GroupAPIHandler):
"""View and modify groups by name"""
@needs_scope('read:groups', 'read:groups:name', 'read:roles:groups')
def get(self, group_name):
group = self.find_group(group_name)
self.write(json.dumps(self.group_model(group)))
@needs_scope('admin:groups')... | self.check_authenticator_managed_groups()
model = self.get_json_body()
if model is None:
model = {}
else:
self._check_group_model(model)
existing = orm.Group.find(self.db, name=group_name)
if existing is not None:
raise web.HTTPError(4... | """POST creates a group by name"""
self.check_authenticator_managed_groups()
model = self.get_json_body()
if model is None:
model = {}
else:
self._check_group_model(model)
existing = orm.Group.find(self.db, name=group_name)
if existing is ... | 66 | 249 | 296 | 545 | """Group handlers"""
# Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.
import json
from tornado import web
from .. import orm
from ..scopes import Scope, needs_scope
from .base import APIHandler
class _GroupAPIHandler(APIHandler):
def _usernames_to_users(self,... | """Group handlers"""
# Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.
import json
from tornado import web
from .. import orm
from ..scopes import Scope, needs_scope
from .base import APIHandler
class _GroupAPIHandler(APIHandler):
def _usernames_to_users(self,... |
18,417 | /home/hieuvd/dung_repo/raw/stars_01/jupyterhub_jupyterhub/jupyterhub | /home/hieuvd/dung_repo/raw/stars_01/jupyterhub_jupyterhub/jupyterhub/jupyterhub/apihandlers/groups.py | 43,45 | 42,107 | get | GroupListAPIHandler | 46,73 | 45,73 | class GroupListAPIHandler(_GroupAPIHandler):
@needs_scope('list:groups')
def get(self):
FILL_FUNC_BODY @needs_scope('admin:groups')
async def post(self):
"""POST creates Multiple groups"""
self.check_authenticator_managed_groups()
model = self.get_json_body()
if not mode... | class GroupListAPIHandler(_GroupAPIHandler):
@needs_scope('list:groups')
def get(self):
"""List groups"""
FILL_FUNC_BODY @needs_scope('admin:groups')
async def post(self):
"""POST creates Multiple groups"""
self.check_authenticator_managed_groups()
model = self.get_json_... | query = full_query = self.db.query(orm.Group)
sub_scope = self.parsed_scopes['list:groups']
if sub_scope != Scope.ALL:
if not set(sub_scope).issubset({'group'}):
# the only valid filter is group=...
# don't expand invalid !server=x to all groups!
... | """List groups"""
query = full_query = self.db.query(orm.Group)
sub_scope = self.parsed_scopes['list:groups']
if sub_scope != Scope.ALL:
if not set(sub_scope).issubset({'group'}):
# the only valid filter is group=...
# don't expand invalid !ser... | 104 | 409 | 395 | 804 | """Group handlers"""
# Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.
import json
from tornado import web
from .. import orm
from ..scopes import Scope, needs_scope
from .base import APIHandler
class _GroupAPIHandler(APIHandler):
def _usernames_to_users(self,... | """Group handlers"""
# Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.
import json
from tornado import web
from .. import orm
from ..scopes import Scope, needs_scope
from .base import APIHandler
class _GroupAPIHandler(APIHandler):
def _usernames_to_users(self,... |
18,418 | /home/hieuvd/dung_repo/raw/stars_01/jupyterhub_jupyterhub/jupyterhub | /home/hieuvd/dung_repo/raw/stars_01/jupyterhub_jupyterhub/jupyterhub/jupyterhub/apihandlers/groups.py | 201,203 | 198,214 | put | GroupPropertiesAPIHandler | 203,214 | 203,214 | class GroupPropertiesAPIHandler(_GroupAPIHandler):
"""Modify a group's properties"""
@needs_scope('groups')
def put(self, group_name):
FILL_FUNC_BODY | class GroupPropertiesAPIHandler(_GroupAPIHandler):
"""Modify a group's properties"""
@needs_scope('groups')
def put(self, group_name):
FILL_FUNC_BODY | group = self.find_group(group_name)
data = self.get_json_body()
# self._check_group_model(data)
if not isinstance(data, dict):
raise web.HTTPError(400, "Must specify properties")
self.log.info("Updating properties of group %s", group_name)
group.properties = d... | group = self.find_group(group_name)
data = self.get_json_body()
# self._check_group_model(data)
if not isinstance(data, dict):
raise web.HTTPError(400, "Must specify properties")
self.log.info("Updating properties of group %s", group_name)
group.properties = d... | 28 | 54 | 135 | 189 | """Group handlers"""
# Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.
import json
from tornado import web
from .. import orm
from ..scopes import Scope, needs_scope
from .base import APIHandler
class _GroupAPIHandler(APIHandler):
def _usernames_to_users(self,... | """Group handlers"""
# Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.
import json
from tornado import web
from .. import orm
from ..scopes import Scope, needs_scope
from .base import APIHandler
class _GroupAPIHandler(APIHandler):
def _usernames_to_users(self,... |
18,419 | /home/hieuvd/dung_repo/raw/stars_01/jupyterhub_jupyterhub/jupyterhub | /home/hieuvd/dung_repo/raw/stars_01/jupyterhub_jupyterhub/jupyterhub/jupyterhub/apihandlers/groups.py | 157,159 | 154,198 | post | GroupUsersAPIHandler | 160,176 | 159,176 | class GroupUsersAPIHandler(_GroupAPIHandler):
"""Modify a group's user list"""
@needs_scope('groups')
def post(self, group_name):
FILL_FUNC_BODY @needs_scope('groups')
async def delete(self, group_name):
"""DELETE removes users from a group"""
self.check_authenticator_managed_groups(... | class GroupUsersAPIHandler(_GroupAPIHandler):
"""Modify a group's user list"""
@needs_scope('groups')
def post(self, group_name):
"""POST adds users to a group"""
FILL_FUNC_BODY @needs_scope('groups')
async def delete(self, group_name):
"""DELETE removes users from a group"""
... | self.check_authenticator_managed_groups()
group = self.find_group(group_name)
data = self.get_json_body()
self._check_group_model(data)
if 'users' not in data:
raise web.HTTPError(400, "Must specify users to add")
self.log.info("Adding %i users to group %s", l... | """POST adds users to a group"""
self.check_authenticator_managed_groups()
group = self.find_group(group_name)
data = self.get_json_body()
self._check_group_model(data)
if 'users' not in data:
raise web.HTTPError(400, "Must specify users to add")
self.... | 52 | 330 | 242 | 572 | """Group handlers"""
# Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.
import json
from tornado import web
from .. import orm
from ..scopes import Scope, needs_scope
from .base import APIHandler
class _GroupAPIHandler(APIHandler):
def _usernames_to_users(self,... | """Group handlers"""
# Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.
import json
from tornado import web
from .. import orm
from ..scopes import Scope, needs_scope
from .base import APIHandler
class _GroupAPIHandler(APIHandler):
def _usernames_to_users(self,... |
18,420 | /home/hieuvd/dung_repo/raw/stars_01/jupyterhub_jupyterhub/jupyterhub | /home/hieuvd/dung_repo/raw/stars_01/jupyterhub_jupyterhub/jupyterhub/jupyterhub/apihandlers/groups.py | 36,37 | 14,42 | check_authenticator_managed_groups | _GroupAPIHandler | 38,42 | 37,42 | class _GroupAPIHandler(APIHandler):
def _usernames_to_users(self, usernames):
"""Turn a list of usernames into user objects"""
users = []
for username in usernames:
username = self.authenticator.normalize_username(username)
user = self.find_user(username)
... | class _GroupAPIHandler(APIHandler):
def _usernames_to_users(self, usernames):
"""Turn a list of usernames into user objects"""
users = []
for username in usernames:
username = self.authenticator.normalize_username(username)
user = self.find_user(username)
... | if self.authenticator.manage_groups:
raise web.HTTPError(400, "Group management via API is disabled")
| """Raise error on group-management APIs if Authenticator is managing groups"""
if self.authenticator.manage_groups:
raise web.HTTPError(400, "Group management via API is disabled")
| 10 | 274 | 40 | 314 | """Group handlers"""
# Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.
import json
from tornado import web
from .. import orm
from ..scopes import Scope, needs_scope
from .base import APIHandler
class _GroupAPIHandler(APIHandler):
def _usernames_to_users(self,... | """Group handlers"""
# Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.
import json
from tornado import web
from .. import orm
from ..scopes import Scope, needs_scope
from .base import APIHandler
class _GroupAPIHandler(APIHandler):
def _usernames_to_users(self,... |
18,421 | /home/hieuvd/dung_repo/raw/stars_01/jupyterhub_jupyterhub/jupyterhub | /home/hieuvd/dung_repo/raw/stars_01/jupyterhub_jupyterhub/jupyterhub/jupyterhub/apihandlers/hub.py | 69,71 | 68,98 | get | InfoAPIHandler | 76,98 | 71,98 | class InfoAPIHandler(APIHandler):
@needs_scope('read:hub')
def get(self):
FILL_FUNC_BODY | class InfoAPIHandler(APIHandler):
@needs_scope('read:hub')
def get(self):
"""GET /api/info returns detailed info about the Hub and its API.
Currently, it returns information on the python version, spawner and authenticator.
Since this information might be sensitive, it is an authenticat... |
def _class_info(typ):
"""info about a class (Spawner or Authenticator)"""
info = {'class': f'{typ.__module__}.{typ.__name__}'}
pkg = typ.__module__.split('.')[0]
try:
version = sys.modules[pkg].__version__
except (KeyError, AttributeEr... | """GET /api/info returns detailed info about the Hub and its API.
Currently, it returns information on the python version, spawner and authenticator.
Since this information might be sensitive, it is an authenticated endpoint
"""
def _class_info(typ):
"""info about a... | 46 | 94 | 236 | 330 | """API handlers for administering the Hub itself"""
# Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.
import json
import sys
from tornado import web
from .._version import __version__
from ..scopes import needs_scope
from .base import APIHandler
class ShutdownAPIH... | """API handlers for administering the Hub itself"""
# Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.
import json
import sys
from tornado import web
from .._version import __version__
from ..scopes import needs_scope
from .base import APIHandler
class ShutdownAPIH... |
18,422 | /home/hieuvd/dung_repo/raw/stars_01/jupyterhub_jupyterhub/jupyterhub | /home/hieuvd/dung_repo/raw/stars_01/jupyterhub_jupyterhub/jupyterhub/jupyterhub/apihandlers/hub.py | 58,59 | 54,68 | get | RootAPIHandler | 64,68 | 59,68 | class RootAPIHandler(APIHandler):
def check_xsrf_cookie(self):
return
def get(self):
FILL_FUNC_BODY | class RootAPIHandler(APIHandler):
def check_xsrf_cookie(self):
return
def get(self):
"""GET /api/ returns info about the Hub and its API.
It is not an authenticated endpoint
For now, it just returns the version of JupyterHub itself.
"""
FILL_FUNC_BODY | data = {'version': __version__}
self.finish(json.dumps(data))
| """GET /api/ returns info about the Hub and its API.
It is not an authenticated endpoint
For now, it just returns the version of JupyterHub itself.
"""
data = {'version': __version__}
self.finish(json.dumps(data))
| 5 | 90 | 31 | 121 | """API handlers for administering the Hub itself"""
# Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.
import json
import sys
from tornado import web
from .._version import __version__
from ..scopes import needs_scope
from .base import APIHandler
class ShutdownAPIH... | """API handlers for administering the Hub itself"""
# Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.
import json
import sys
from tornado import web
from .._version import __version__
from ..scopes import needs_scope
from .base import APIHandler
class ShutdownAPIH... |
18,423 | /home/hieuvd/dung_repo/raw/stars_01/jupyterhub_jupyterhub/jupyterhub | /home/hieuvd/dung_repo/raw/stars_01/jupyterhub_jupyterhub/jupyterhub/jupyterhub/apihandlers/hub.py | 16,18 | 15,54 | post | ShutdownAPIHandler | 25,54 | 18,54 | class ShutdownAPIHandler(APIHandler):
@needs_scope('shutdown')
def post(self):
FILL_FUNC_BODY | class ShutdownAPIHandler(APIHandler):
@needs_scope('shutdown')
def post(self):
"""POST /api/shutdown triggers a clean shutdown
POST (JSON) parameters:
- servers: specify whether single-user servers should be terminated
- proxy: specify whether the proxy should be terminated
... | from ..app import JupyterHub
app = JupyterHub.instance()
data = self.get_json_body()
if data:
if 'proxy' in data:
proxy = data['proxy']
if proxy not in {True, False}:
raise web.HTTPError(
400, f"pro... | """POST /api/shutdown triggers a clean shutdown
POST (JSON) parameters:
- servers: specify whether single-user servers should be terminated
- proxy: specify whether the proxy should be terminated
"""
from ..app import JupyterHub
app = JupyterHub.instance()
... | 88 | 92 | 276 | 368 | """API handlers for administering the Hub itself"""
# Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.
import json
import sys
from tornado import web
from .._version import __version__
from ..scopes import needs_scope
from .base import APIHandler
class ShutdownAPIH... | """API handlers for administering the Hub itself"""
# Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.
import json
import sys
from tornado import web
from .._version import __version__
from ..scopes import needs_scope
from .base import APIHandler
class ShutdownAPIH... |
18,424 | /home/hieuvd/dung_repo/raw/stars_01/jupyterhub_jupyterhub/jupyterhub | /home/hieuvd/dung_repo/raw/stars_01/jupyterhub_jupyterhub/jupyterhub/jupyterhub/apihandlers/proxy.py | 53,55 | 13,77 | patch | ProxyAPIHandler | 59,77 | 55,77 | class ProxyAPIHandler(APIHandler):
@needs_scope('proxy')
async def get(self):
"""GET /api/proxy fetches the routing table
This is the same as fetching the routing table directly from the proxy,
but without clients needing to maintain separate
"""
offset, limit = self.get... | class ProxyAPIHandler(APIHandler):
@needs_scope('proxy')
async def get(self):
"""GET /api/proxy fetches the routing table
This is the same as fetching the routing table directly from the proxy,
but without clients needing to maintain separate
"""
offset, limit = self.get... | if not self.request.body:
raise web.HTTPError(400, "need JSON body")
try:
model = json.loads(self.request.body.decode('utf8', 'replace'))
except ValueError:
raise web.HTTPError(400, "Request body must be JSON dict")
if not isinstance(model, dict):
... | """PATCH updates the location of the proxy
Can be used to notify the Hub that a new proxy is in charge
"""
if not self.request.body:
raise web.HTTPError(400, "need JSON body")
try:
model = json.loads(self.request.body.decode('utf8', 'replace'))
e... | 57 | 407 | 225 | 632 | """Proxy handlers"""
# Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.
import json
from tornado import web
from ..scopes import needs_scope
from .base import APIHandler
class ProxyAPIHandler(APIHandler):
@needs_scope('proxy')
async def get(self):
"... | """Proxy handlers"""
# Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.
import json
from tornado import web
from ..scopes import needs_scope
from .base import APIHandler
class ProxyAPIHandler(APIHandler):
@needs_scope('proxy')
async def get(self):
"... |
18,425 | /home/hieuvd/dung_repo/raw/stars_01/jupyterhub_jupyterhub/jupyterhub | /home/hieuvd/dung_repo/raw/stars_01/jupyterhub_jupyterhub/jupyterhub/jupyterhub/apihandlers/services.py | 59,60 | 32,201 | add_service | ServiceAPIHandler | 72,115 | 60,115 | class ServiceAPIHandler(APIHandler):
@needs_scope('read:services', 'read:services:name', 'read:roles:services')
def get(self, service_name):
if service_name not in self.services:
raise web.HTTPError(404, f"No such service: {service_name}")
service = self.services[service_name]
... | class ServiceAPIHandler(APIHandler):
@needs_scope('read:services', 'read:services:name', 'read:roles:services')
def get(self, service_name):
if service_name not in self.services:
raise web.HTTPError(404, f"No such service: {service_name}")
service = self.services[service_name]
... |
self._check_service_model(spec)
self._check_service_scopes(spec)
service_name = spec["name"]
managed = bool(spec.get('command'))
if managed:
msg = f"Can not create managed service {service_name} at runtime"
self.log.error(msg, exc_info=True)
... | """Add a new service and related objects to the database
Args:
spec (dict): The service specification
Raises:
web.HTTPError: Raise if the service is not created
Returns:
Service: Returns the service instance.
"""
self._check_servic... | 117 | 1,310 | 507 | 1,817 | """Service handlers
Currently GET-only, no actions can be taken to modify services.
"""
# Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.
import json
from typing import Optional, Tuple
from tornado import web
from .. import orm
from ..roles import get_default_roles... | """Service handlers
Currently GET-only, no actions can be taken to modify services.
"""
# Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.
import json
from typing import Optional, Tuple
from tornado import web
from .. import orm
from ..roles import get_default_roles... |
18,426 | /home/hieuvd/dung_repo/raw/stars_01/jupyterhub_jupyterhub/jupyterhub | /home/hieuvd/dung_repo/raw/stars_01/jupyterhub_jupyterhub/jupyterhub/jupyterhub/apihandlers/services.py | 21,23 | 20,32 | get | ServiceListAPIHandler | 23,32 | 23,32 | class ServiceListAPIHandler(APIHandler):
@needs_scope('list:services')
def get(self):
FILL_FUNC_BODY | class ServiceListAPIHandler(APIHandler):
@needs_scope('list:services')
def get(self):
FILL_FUNC_BODY | data = {}
service_scope = self.parsed_scopes['list:services']
for name, service in self.services.items():
if service_scope == Scope.ALL or name in service_scope.get("service", {}):
model = self.service_model(service)
data[name] = model
self.wri... | data = {}
service_scope = self.parsed_scopes['list:services']
for name, service in self.services.items():
if service_scope == Scope.ALL or name in service_scope.get("service", {}):
model = self.service_model(service)
data[name] = model
self.wri... | 27 | 39 | 105 | 144 | """Service handlers
Currently GET-only, no actions can be taken to modify services.
"""
# Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.
import json
from typing import Optional, Tuple
from tornado import web
from .. import orm
from ..roles import get_default_roles... | """Service handlers
Currently GET-only, no actions can be taken to modify services.
"""
# Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.
import json
from typing import Optional, Tuple
from tornado import web
from .. import orm
from ..roles import get_default_roles... |
18,427 | /home/hieuvd/dung_repo/raw/stars_01/jupyterhub_jupyterhub/jupyterhub | /home/hieuvd/dung_repo/raw/stars_01/jupyterhub_jupyterhub/jupyterhub/jupyterhub/emptyclass.py | 11,12 | 10,16 | empty_function | EmptyClass | 12,14 | 12,14 | class EmptyClass:
def empty_function(self, *args, **kwargs):
FILL_FUNC_BODY def __getattr__(self, attr):
return self.empty_function
| class EmptyClass:
def empty_function(self, *args, **kwargs):
FILL_FUNC_BODY def __getattr__(self, attr):
return self.empty_function
| return self
| return self
| 2 | 50 | 7 | 57 | """
Simple empty class that returns itself for all functions called on it.
This allows us to call any method of any name on this, and it'll return another
instance of itself that'll allow any method to be called on it.
Primarily used to mock out the statsd client when statsd is not being used
"""
class EmptyClass:
... | """
Simple empty class that returns itself for all functions called on it.
This allows us to call any method of any name on this, and it'll return another
instance of itself that'll allow any method to be called on it.
Primarily used to mock out the statsd client when statsd is not being used
"""
class EmptyClass:
... |
18,428 | /home/hieuvd/dung_repo/raw/stars_01/jupyterhub_jupyterhub/jupyterhub | /home/hieuvd/dung_repo/raw/stars_01/jupyterhub_jupyterhub/jupyterhub/jupyterhub/handlers/metrics.py | 16,18 | 9,22 | get | MetricsHandler | 18,22 | 18,22 | class MetricsHandler(BaseHandler):
"""
Handler to serve Prometheus metrics
"""
_accept_token_auth = True
@metrics_authentication
async def get(self):
FILL_FUNC_BODY | class MetricsHandler(BaseHandler):
"""
Handler to serve Prometheus metrics
"""
_accept_token_auth = True
@metrics_authentication
async def get(self):
FILL_FUNC_BODY | self.set_header('Content-Type', CONTENT_TYPE_LATEST)
self.write(generate_latest(REGISTRY))
| self.set_header('Content-Type', CONTENT_TYPE_LATEST)
self.write(generate_latest(REGISTRY))
| 3 | 63 | 42 | 105 | """Handlers for serving prometheus metrics"""
from prometheus_client import CONTENT_TYPE_LATEST, REGISTRY, generate_latest
from ..utils import metrics_authentication
from .base import BaseHandler
class MetricsHandler(BaseHandler):
"""
Handler to serve Prometheus metrics
"""
_accept_token_auth = Tru... | """Handlers for serving prometheus metrics"""
from prometheus_client import CONTENT_TYPE_LATEST, REGISTRY, generate_latest
from ..utils import metrics_authentication
from .base import BaseHandler
class MetricsHandler(BaseHandler):
"""
Handler to serve Prometheus metrics
"""
_accept_token_auth = Tru... |
18,429 | /home/hieuvd/dung_repo/raw/stars_01/jupyterhub_jupyterhub/jupyterhub | /home/hieuvd/dung_repo/raw/stars_01/jupyterhub_jupyterhub/jupyterhub/jupyterhub/handlers/static.py | 17,18 | 8,24 | set_extra_headers | CacheControlStaticFilesHandler | 18,24 | 18,24 | class CacheControlStaticFilesHandler(StaticFileHandler):
"""StaticFileHandler subclass that sets Cache-Control: no-cache without `?v=`
rather than relying on default browser cache behavior.
"""
def compute_etag(self):
return None
def set_extra_headers(self, path):
FILL_FUNC_BODY | class CacheControlStaticFilesHandler(StaticFileHandler):
"""StaticFileHandler subclass that sets Cache-Control: no-cache without `?v=`
rather than relying on default browser cache behavior.
"""
def compute_etag(self):
return None
def set_extra_headers(self, path):
FILL_FUNC_BODY | if "v" not in self.request.arguments or self.settings.get(
"no_cache_static", False
):
self.add_header("Cache-Control", "no-cache")
| if "v" not in self.request.arguments or self.settings.get(
"no_cache_static", False
):
self.add_header("Cache-Control", "no-cache")
| 12 | 89 | 59 | 148 | # Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.
import os
from tornado.web import StaticFileHandler
class CacheControlStaticFilesHandler(StaticFileHandler):
"""StaticFileHandler subclass that sets Cache-Control: no-cache without `?v=`
rather than relying ... | # Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.
import os
from tornado.web import StaticFileHandler
class CacheControlStaticFilesHandler(StaticFileHandler):
"""StaticFileHandler subclass that sets Cache-Control: no-cache without `?v=`
rather than relying ... |
18,430 | /home/hieuvd/dung_repo/raw/stars_01/jupyterhub_jupyterhub/jupyterhub | /home/hieuvd/dung_repo/raw/stars_01/jupyterhub_jupyterhub/jupyterhub/jupyterhub/handlers/static.py | 30,32 | 24,34 | get_absolute_path | LogoHandler | 33,34 | 32,34 | class LogoHandler(StaticFileHandler):
"""A singular handler for serving the logo."""
def get(self):
return super().get('')
@classmethod
def get_absolute_path(cls, root, path):
FILL_FUNC_BODY | class LogoHandler(StaticFileHandler):
"""A singular handler for serving the logo."""
def get(self):
return super().get('')
@classmethod
def get_absolute_path(cls, root, path):
"""We only serve one file, ignore relative path"""
FILL_FUNC_BODY | return os.path.abspath(root)
| """We only serve one file, ignore relative path"""
return os.path.abspath(root)
| 2 | 82 | 14 | 96 | # Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.
import os
from tornado.web import StaticFileHandler
class CacheControlStaticFilesHandler(StaticFileHandler):
"""StaticFileHandler subclass that sets Cache-Control: no-cache without `?v=`
rather than relying ... | # Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.
import os
from tornado.web import StaticFileHandler
class CacheControlStaticFilesHandler(StaticFileHandler):
"""StaticFileHandler subclass that sets Cache-Control: no-cache without `?v=`
rather than relying ... |
18,431 | /home/hieuvd/dung_repo/raw/stars_01/jupyterhub_jupyterhub/jupyterhub | /home/hieuvd/dung_repo/raw/stars_01/jupyterhub_jupyterhub/jupyterhub/jupyterhub/log.py | 97,98 | 1,194 | _scrub_headers | 99,125 | 98,125 | """logging utilities"""
# Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.
import json
import logging
import traceback
from functools import partial
from http.cookies import SimpleCookie
from urllib.parse import urlparse, urlunparse
from tornado.log import LogFormatte... | """logging utilities"""
# Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.
import json
import logging
import traceback
from functools import partial
from http.cookies import SimpleCookie
from urllib.parse import urlparse, urlunparse
from tornado.log import LogFormatte... | headers = dict(headers)
if 'Authorization' in headers:
auth = headers['Authorization']
if ' ' in auth:
auth_type = auth.split(' ', 1)[0]
else:
# no space, hide the whole thing in case there was a mistake
auth_type = ''
headers['Authorization'] ... | """scrub auth info from headers"""
headers = dict(headers)
if 'Authorization' in headers:
auth = headers['Authorization']
if ' ' in auth:
auth_type = auth.split(' ', 1)[0]
else:
# no space, hide the whole thing in case there was a mistake
auth_type... | 88 | 1,623 | 260 | 1,883 | """logging utilities"""
# Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.
import json
import logging
import traceback
from functools import partial
from http.cookies import SimpleCookie
from urllib.parse import urlparse, urlunparse
from tornado.log import LogFormatte... | """logging utilities"""
# Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.
import json
import logging
import traceback
from functools import partial
from http.cookies import SimpleCookie
from urllib.parse import urlparse, urlunparse
from tornado.log import LogFormatte... | |
18,432 | /home/hieuvd/dung_repo/raw/stars_01/jupyterhub_jupyterhub/jupyterhub | /home/hieuvd/dung_repo/raw/stars_01/jupyterhub_jupyterhub/jupyterhub/jupyterhub/log.py | 63,64 | 60,70 | formatException | CoroutineLogFormatter | 64,70 | 64,70 | class CoroutineLogFormatter(LogFormatter):
"""Log formatter that scrubs coroutine frames"""
def formatException(self, exc_info):
FILL_FUNC_BODY | class CoroutineLogFormatter(LogFormatter):
"""Log formatter that scrubs coroutine frames"""
def formatException(self, exc_info):
FILL_FUNC_BODY | return ''.join(coroutine_traceback(*exc_info))
# url params to be scrubbed if seen
# any url param that *contains* one of these
# will be scrubbed from logs
| return ''.join(coroutine_traceback(*exc_info))
# url params to be scrubbed if seen
# any url param that *contains* one of these
# will be scrubbed from logs
| 25 | 50 | 58 | 108 | """logging utilities"""
# Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.
import json
import logging
import traceback
from functools import partial
from http.cookies import SimpleCookie
from urllib.parse import urlparse, urlunparse
from tornado.log import LogFormatte... | """logging utilities"""
# Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.
import json
import logging
import traceback
from functools import partial
from http.cookies import SimpleCookie
from urllib.parse import urlparse, urlunparse
from tornado.log import LogFormatte... |
18,434 | /home/hieuvd/dung_repo/raw/stars_01/jupyterhub_jupyterhub/jupyterhub | /home/hieuvd/dung_repo/raw/stars_01/jupyterhub_jupyterhub/jupyterhub/jupyterhub/metrics.py | 387,388 | 289,421 | start | PeriodicMetricsCollector | 391,415 | 388,415 | class PeriodicMetricsCollector(LoggingConfigurable):
"""
Collect metrics to be calculated periodically
"""
active_users_enabled = Bool(
True,
help="""
Enable active_users prometheus metric.
Populates a `active_users` prometheus metric, with a label `period` that counts ... | class PeriodicMetricsCollector(LoggingConfigurable):
"""
Collect metrics to be calculated periodically
"""
active_users_enabled = Bool(
True,
help="""
Enable active_users prometheus metric.
Populates a `active_users` prometheus metric, with a label `period` that counts ... | if self.active_users_enabled:
# Setup periodic refresh of the metric
self._periodic_callbacks["active_users"] = PeriodicCallback(
self.update_active_users,
self.active_users_update_interval * 1000,
jitter=0.01,
)
# ... | """
Start the periodic update process
"""
if self.active_users_enabled:
# Setup periodic refresh of the metric
self._periodic_callbacks["active_users"] = PeriodicCallback(
self.update_active_users,
self.active_users_update_interval ... | 56 | 1,067 | 265 | 1,332 | """
Prometheus metrics exported by JupyterHub
Read https://prometheus.io/docs/practices/naming/ for naming
conventions for metrics & labels. We generally prefer naming them
`<noun>_<verb>_<type_suffix>`. So a histogram that's tracking
the duration (in seconds) of servers spawning would be called
server_spawn_duration_... | """
Prometheus metrics exported by JupyterHub
Read https://prometheus.io/docs/practices/naming/ for naming
conventions for metrics & labels. We generally prefer naming them
`<noun>_<verb>_<type_suffix>`. So a histogram that's tracking
the duration (in seconds) of servers spawning would be called
server_spawn_duration_... |
18,435 | /home/hieuvd/dung_repo/raw/stars_01/jupyterhub_jupyterhub/jupyterhub | /home/hieuvd/dung_repo/raw/stars_01/jupyterhub_jupyterhub/jupyterhub/jupyterhub/metrics.py | 161,163 | 153,169 | from_status | ServerPollStatus | 164,169 | 163,169 | class ServerPollStatus(Enum):
"""
Possible values for 'status' label of SERVER_POLL_DURATION_SECONDS
"""
running = 'running'
stopped = 'stopped'
@classmethod
def from_status(cls, status):
FILL_FUNC_BODY | class ServerPollStatus(Enum):
"""
Possible values for 'status' label of SERVER_POLL_DURATION_SECONDS
"""
running = 'running'
stopped = 'stopped'
@classmethod
def from_status(cls, status):
"""Return enum string for a given poll status"""
FILL_FUNC_BODY | if status is None:
return cls.running
return cls.stopped
| """Return enum string for a given poll status"""
if status is None:
return cls.running
return cls.stopped
| 8 | 94 | 29 | 123 | """
Prometheus metrics exported by JupyterHub
Read https://prometheus.io/docs/practices/naming/ for naming
conventions for metrics & labels. We generally prefer naming them
`<noun>_<verb>_<type_suffix>`. So a histogram that's tracking
the duration (in seconds) of servers spawning would be called
server_spawn_duration_... | """
Prometheus metrics exported by JupyterHub
Read https://prometheus.io/docs/practices/naming/ for naming
conventions for metrics & labels. We generally prefer naming them
`<noun>_<verb>_<type_suffix>`. So a histogram that's tracking
the duration (in seconds) of servers spawning would be called
server_spawn_duration_... |
18,436 | /home/hieuvd/dung_repo/raw/stars_01/jupyterhub_jupyterhub/jupyterhub | /home/hieuvd/dung_repo/raw/stars_01/jupyterhub_jupyterhub/jupyterhub/jupyterhub/objects.py | 201,203 | 190,220 | server | Hub | 203,210 | 203,210 | class Hub(Server):
"""Bring it all together at the hub.
The Hub is a server, plus its API path suffix
the api_url is the full URL plus the api_path suffix on the end
of the server base_url.
"""
cookie_name = 'jupyterhub-hub-login'
@property
def server(self):
FILL_FUNC_BODY public_... | class Hub(Server):
"""Bring it all together at the hub.
The Hub is a server, plus its API path suffix
the api_url is the full URL plus the api_path suffix on the end
of the server base_url.
"""
cookie_name = 'jupyterhub-hub-login'
@property
def server(self):
FILL_FUNC_BODY public_... | warnings.warn(
"Hub.server is deprecated in JupyterHub 0.8. Access attributes on the Hub directly.",
DeprecationWarning,
stacklevel=2,
)
return self
| warnings.warn(
"Hub.server is deprecated in JupyterHub 0.8. Access attributes on the Hub directly.",
DeprecationWarning,
stacklevel=2,
)
return self
| 18 | 205 | 62 | 267 | """Some general objects for use in JupyterHub"""
# Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.
import socket
import warnings
from urllib.parse import urlparse, urlunparse
from traitlets import HasTraits, Instance, Integer, Unicode, default, observe, validate
fro... | """Some general objects for use in JupyterHub"""
# Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.
import socket
import warnings
from urllib.parse import urlparse, urlunparse
from traitlets import HasTraits, Instance, Integer, Unicode, default, observe, validate
fro... |
18,437 | /home/hieuvd/dung_repo/raw/stars_01/jupyterhub_jupyterhub/jupyterhub | /home/hieuvd/dung_repo/raw/stars_01/jupyterhub_jupyterhub/jupyterhub/jupyterhub/objects.py | 123,125 | 23,190 | _orm_server_changed | Server | 126,134 | 125,134 | class Server(HasTraits):
"""An object representing an HTTP endpoint.
*Some* of these reside in the database (user servers),
but others (Hub, proxy) are in-memory only.
"""
orm_server = Instance(orm.Server, allow_none=True)
ip = Unicode()
connect_ip = Unicode()
connect_port = Integer()... | class Server(HasTraits):
"""An object representing an HTTP endpoint.
*Some* of these reside in the database (user servers),
but others (Hub, proxy) are in-memory only.
"""
orm_server = Instance(orm.Server, allow_none=True)
ip = Unicode()
connect_ip = Unicode()
connect_port = Integer()... | obj = change.new
self.proto = obj.proto
self.ip = obj.ip
self.port = obj.port
self.base_url = obj.base_url
self.cookie_name = obj.cookie_name
# setter to pass through to the database
| """When we get an orm_server, get attributes from there."""
obj = change.new
self.proto = obj.proto
self.ip = obj.ip
self.port = obj.port
self.base_url = obj.base_url
self.cookie_name = obj.cookie_name
# setter to pass through to the database
| 26 | 1,557 | 82 | 1,639 | """Some general objects for use in JupyterHub"""
# Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.
import socket
import warnings
from urllib.parse import urlparse, urlunparse
from traitlets import HasTraits, Instance, Integer, Unicode, default, observe, validate
fro... | """Some general objects for use in JupyterHub"""
# Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.
import socket
import warnings
from urllib.parse import urlparse, urlunparse
from traitlets import HasTraits, Instance, Integer, Unicode, default, observe, validate
fro... |
18,440 | /home/hieuvd/dung_repo/raw/stars_01/jupyterhub_jupyterhub/jupyterhub | /home/hieuvd/dung_repo/raw/stars_01/jupyterhub_jupyterhub/jupyterhub/jupyterhub/services/service.py | 87,89 | 71,98 | base_url | _MockUser | 89,98 | 89,98 | class _MockUser(HasTraits):
name = Unicode()
server = Instance(orm.Server, allow_none=True)
state = Dict()
service = Instance(__name__ + '.Service')
host = Unicode()
@property
def url(self):
if not self.server:
return ''
if self.host:
return self.host... | class _MockUser(HasTraits):
name = Unicode()
server = Instance(orm.Server, allow_none=True)
state = Dict()
service = Instance(__name__ + '.Service')
host = Unicode()
@property
def url(self):
if not self.server:
return ''
if self.host:
return self.host... | if not self.server:
return ''
return self.server.base_url
# We probably shouldn't use a Spawner here,
# but there are too many concepts to share.
| if not self.server:
return ''
return self.server.base_url
# We probably shouldn't use a Spawner here,
# but there are too many concepts to share.
| 24 | 144 | 60 | 204 | """A service is a process that talks to JupyterHub.
Types of services:
Managed:
- managed by JupyterHub (always subprocess, no custom Spawners)
- always a long-running process
- managed services are restarted automatically if they exit unexpectedly
Unmanaged:
- managed by external serv... | """A service is a process that talks to JupyterHub.
Types of services:
Managed:
- managed by JupyterHub (always subprocess, no custom Spawners)
- always a long-running process
- managed services are restarted automatically if they exit unexpectedly
Unmanaged:
- managed by external serv... |
18,441 | /home/hieuvd/dung_repo/raw/stars_01/jupyterhub_jupyterhub/jupyterhub | /home/hieuvd/dung_repo/raw/stars_01/jupyterhub_jupyterhub/jupyterhub/jupyterhub/services/service.py | 127,128 | 98,158 | start | _ServiceSpawner | 129,158 | 128,158 | class _ServiceSpawner(LocalProcessSpawner):
"""Subclass of LocalProcessSpawner
Removes notebook-specific-ness from LocalProcessSpawner.
"""
cwd = Unicode()
cmd = Command(minlen=0)
_service_name = Unicode()
@default("oauth_access_scopes")
def _default_oauth_access_scopes(self):
... | class _ServiceSpawner(LocalProcessSpawner):
"""Subclass of LocalProcessSpawner
Removes notebook-specific-ness from LocalProcessSpawner.
"""
cwd = Unicode()
cmd = Command(minlen=0)
_service_name = Unicode()
@default("oauth_access_scopes")
def _default_oauth_access_scopes(self):
... | env = self.get_env()
# no activity url for services
env.pop('JUPYTERHUB_ACTIVITY_URL', None)
if os.name == 'nt':
env['SYSTEMROOT'] = os.environ['SYSTEMROOT']
cmd = self.cmd
self.log.info("Spawning %s", ' '.join(shlex.quote(s) for s in cmd))
try:
... | """Start the process"""
env = self.get_env()
# no activity url for services
env.pop('JUPYTERHUB_ACTIVITY_URL', None)
if os.name == 'nt':
env['SYSTEMROOT'] = os.environ['SYSTEMROOT']
cmd = self.cmd
self.log.info("Spawning %s", ' '.join(shlex.quote(s) f... | 79 | 260 | 315 | 575 | """A service is a process that talks to JupyterHub.
Types of services:
Managed:
- managed by JupyterHub (always subprocess, no custom Spawners)
- always a long-running process
- managed services are restarted automatically if they exit unexpectedly
Unmanaged:
- managed by external serv... | """A service is a process that talks to JupyterHub.
Types of services:
Managed:
- managed by JupyterHub (always subprocess, no custom Spawners)
- always a long-running process
- managed services are restarted automatically if they exit unexpectedly
Unmanaged:
- managed by external serv... |
18,442 | /home/hieuvd/dung_repo/raw/stars_01/jupyterhub_jupyterhub/jupyterhub | /home/hieuvd/dung_repo/raw/stars_01/jupyterhub_jupyterhub/jupyterhub/jupyterhub/traitlets.py | 70,71 | 49,96 | validate | ByteSpecification | 78,96 | 71,96 | class ByteSpecification(Integer):
"""
Allow easily specifying bytes in units of 1024 with suffixes
Suffixes allowed are:
- K -> Kilobyte
- M -> Megabyte
- G -> Gigabyte
- T -> Terabyte
"""
UNIT_SUFFIXES = {
'K': 1024,
'M': 1024 * 1024,
'G': 1024 * 10... | class ByteSpecification(Integer):
"""
Allow easily specifying bytes in units of 1024 with suffixes
Suffixes allowed are:
- K -> Kilobyte
- M -> Megabyte
- G -> Gigabyte
- T -> Terabyte
"""
UNIT_SUFFIXES = {
'K': 1024,
'M': 1024 * 1024,
'G': 1024 * 10... | if isinstance(value, (int, float)):
return int(value)
try:
num = float(value[:-1])
except ValueError:
raise TraitError(
f'{value} is not a valid memory specification. Must be an int or a string with suffix K, M, G, T'
)
suf... | """
Validate that the passed in value is a valid memory specification
It could either be a pure int, when it is taken as a byte value.
If it has one of the suffixes, it is converted into the appropriate
pure byte value.
"""
if isinstance(value, (int, float)):
... | 71 | 279 | 196 | 475 | """
Traitlets that are used in JupyterHub
"""
# Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.
import sys
# See compatibility note on `group` keyword in https://docs.python.org/3/library/importlib.metadata.html#entry-points
if sys.version_info < (3, 10):
from im... | """
Traitlets that are used in JupyterHub
"""
# Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.
import sys
# See compatibility note on `group` keyword in https://docs.python.org/3/library/importlib.metadata.html#entry-points
if sys.version_info < (3, 10):
from im... |
18,443 | /home/hieuvd/dung_repo/raw/stars_01/jupyterhub_jupyterhub/jupyterhub | /home/hieuvd/dung_repo/raw/stars_01/jupyterhub_jupyterhub/jupyterhub/jupyterhub/traitlets.py | 106,107 | 96,113 | validate | Callable | 107,113 | 107,113 | class Callable(TraitType):
"""
A trait which is callable.
Classes are callable, as are instances
with a __call__() method.
"""
info_text = 'a callable'
def validate(self, obj, value):
FILL_FUNC_BODY | class Callable(TraitType):
"""
A trait which is callable.
Classes are callable, as are instances
with a __call__() method.
"""
info_text = 'a callable'
def validate(self, obj, value):
FILL_FUNC_BODY | if callable(value):
return value
else:
self.error(obj, value)
| if callable(value):
return value
else:
self.error(obj, value)
| 7 | 80 | 34 | 114 | """
Traitlets that are used in JupyterHub
"""
# Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.
import sys
# See compatibility note on `group` keyword in https://docs.python.org/3/library/importlib.metadata.html#entry-points
if sys.version_info < (3, 10):
from im... | """
Traitlets that are used in JupyterHub
"""
# Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.
import sys
# See compatibility note on `group` keyword in https://docs.python.org/3/library/importlib.metadata.html#entry-points
if sys.version_info < (3, 10):
from im... |
18,444 | /home/hieuvd/dung_repo/raw/stars_01/jupyterhub_jupyterhub/jupyterhub | /home/hieuvd/dung_repo/raw/stars_01/jupyterhub_jupyterhub/jupyterhub/jupyterhub/traitlets.py | 43,44 | 28,49 | validate | Command | 44,49 | 44,49 | class Command(List):
"""Traitlet for a command that should be a list of strings,
but allows it to be specified as a single string.
"""
def __init__(self, default_value=Undefined, **kwargs):
kwargs.setdefault('minlen', 1)
if isinstance(default_value, str):
default_value = [de... | class Command(List):
"""Traitlet for a command that should be a list of strings,
but allows it to be specified as a single string.
"""
def __init__(self, default_value=Undefined, **kwargs):
kwargs.setdefault('minlen', 1)
if isinstance(default_value, str):
default_value = [de... | if isinstance(value, str):
value = [value]
return super().validate(obj, value)
| if isinstance(value, str):
value = [value]
return super().validate(obj, value)
| 9 | 186 | 35 | 221 | """
Traitlets that are used in JupyterHub
"""
# Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.
import sys
# See compatibility note on `group` keyword in https://docs.python.org/3/library/importlib.metadata.html#entry-points
if sys.version_info < (3, 10):
from im... | """
Traitlets that are used in JupyterHub
"""
# Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.
import sys
# See compatibility note on `group` keyword in https://docs.python.org/3/library/importlib.metadata.html#entry-points
if sys.version_info < (3, 10):
from im... |
18,445 | /home/hieuvd/dung_repo/raw/stars_01/jupyterhub_jupyterhub/jupyterhub | /home/hieuvd/dung_repo/raw/stars_01/jupyterhub_jupyterhub/jupyterhub/jupyterhub/traitlets.py | 139,140 | 113,157 | load_entry_points | EntryPointType | 144,149 | 140,149 | class EntryPointType(Type):
"""Entry point-extended Type
classes can be registered via entry points
in addition to standard 'mypackage.MyClass' strings
"""
_original_help = ''
def __init__(self, *args, entry_point_group, **kwargs):
self.entry_point_group = entry_point_group
su... | class EntryPointType(Type):
"""Entry point-extended Type
classes can be registered via entry points
in addition to standard 'mypackage.MyClass' strings
"""
_original_help = ''
def __init__(self, *args, entry_point_group, **kwargs):
self.entry_point_group = entry_point_group
su... | return {
entry_point.name.lower(): entry_point
for entry_point in entry_points(group=self.entry_point_group)
}
| """Load my entry point group
Returns a dict whose keys are lowercase entrypoint names
"""
return {
entry_point.name.lower(): entry_point
for entry_point in entry_points(group=self.entry_point_group)
}
| 9 | 364 | 47 | 411 | """
Traitlets that are used in JupyterHub
"""
# Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.
import sys
# See compatibility note on `group` keyword in https://docs.python.org/3/library/importlib.metadata.html#entry-points
if sys.version_info < (3, 10):
from im... | """
Traitlets that are used in JupyterHub
"""
# Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.
import sys
# See compatibility note on `group` keyword in https://docs.python.org/3/library/importlib.metadata.html#entry-points
if sys.version_info < (3, 10):
from im... |
18,446 | /home/hieuvd/dung_repo/raw/stars_01/jupyterhub_jupyterhub/jupyterhub | /home/hieuvd/dung_repo/raw/stars_01/jupyterhub_jupyterhub/jupyterhub/jupyterhub/traitlets.py | 19,20 | 18,28 | validate | URLPrefix | 20,28 | 20,28 | class URLPrefix(Unicode):
def validate(self, obj, value):
FILL_FUNC_BODY | class URLPrefix(Unicode):
def validate(self, obj, value):
FILL_FUNC_BODY | u = super().validate(obj, value)
if not u.startswith('/'):
u = '/' + u
if not u.endswith('/'):
u = u + '/'
return u
| u = super().validate(obj, value)
if not u.startswith('/'):
u = '/' + u
if not u.endswith('/'):
u = u + '/'
return u
| 22 | 29 | 66 | 95 | """
Traitlets that are used in JupyterHub
"""
# Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.
import sys
# See compatibility note on `group` keyword in https://docs.python.org/3/library/importlib.metadata.html#entry-points
if sys.version_info < (3, 10):
from im... | """
Traitlets that are used in JupyterHub
"""
# Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.
import sys
# See compatibility note on `group` keyword in https://docs.python.org/3/library/importlib.metadata.html#entry-points
if sys.version_info < (3, 10):
from im... |
18,449 | /home/hieuvd/dung_repo/raw/stars_01/jupyterhub_jupyterhub/jupyterhub | /home/hieuvd/dung_repo/raw/stars_01/jupyterhub_jupyterhub/jupyterhub/setup.py | 73,74 | 62,80 | get_inputs | BaseCommand | 74,76 | 74,76 | class BaseCommand(Command):
"""Dumb empty command because Command needs subclasses to override too much"""
user_options = []
def initialize_options(self):
pass
def finalize_options(self):
pass
def get_inputs(self):
FILL_FUNC_BODY def get_outputs(self):
return []
| class BaseCommand(Command):
"""Dumb empty command because Command needs subclasses to override too much"""
user_options = []
def initialize_options(self):
pass
def finalize_options(self):
pass
def get_inputs(self):
FILL_FUNC_BODY def get_outputs(self):
return []
| return []
| return []
| 2 | 96 | 7 | 103 | #!/usr/bin/env python3
# Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.
import os
import shutil
import sys
from subprocess import check_call
from setuptools import Command, setup
from setuptools.command.bdist_egg import bdist_egg
from setuptools.command.build_py imp... | #!/usr/bin/env python3
# Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.
import os
import shutil
import sys
from subprocess import check_call
from setuptools import Command, setup
from setuptools.command.bdist_egg import bdist_egg
from setuptools.command.build_py imp... |
18,450 | /home/hieuvd/dung_repo/raw/stars_01/jupyterhub_jupyterhub/jupyterhub | /home/hieuvd/dung_repo/raw/stars_01/jupyterhub_jupyterhub/jupyterhub/setup.py | 118,119 | 115,168 | should_run | CSS | 120,148 | 119,148 | class CSS(BaseCommand):
description = "compile CSS"
def should_run(self):
FILL_FUNC_BODY def run(self):
if not self.should_run():
print("CSS up-to-date")
return
self.run_command('js')
print("Building css")
args = ['npm', 'run', 'css']
try:
... | class CSS(BaseCommand):
description = "compile CSS"
def should_run(self):
"""Does CSS need to run?"""
FILL_FUNC_BODY def run(self):
if not self.should_run():
print("CSS up-to-date")
return
self.run_command('js')
print("Building css")
args = [... | css_targets = [pjoin(static, 'css', 'style.min.css')]
css_maps = [t + '.map' for t in css_targets]
targets = css_targets + css_maps
earliest_target_mtime = float('inf')
earliest_target_name = ''
for t in targets:
if not os.path.exists(t):
print... | """Does CSS need to run?"""
css_targets = [pjoin(static, 'css', 'style.min.css')]
css_maps = [t + '.map' for t in css_targets]
targets = css_targets + css_maps
earliest_target_mtime = float('inf')
earliest_target_name = ''
for t in targets:
if not os.p... | 102 | 242 | 326 | 568 | #!/usr/bin/env python3
# Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.
import os
import shutil
import sys
from subprocess import check_call
from setuptools import Command, setup
from setuptools.command.bdist_egg import bdist_egg
from setuptools.command.build_py imp... | #!/usr/bin/env python3
# Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.
import os
import shutil
import sys
from subprocess import check_call
from setuptools import Command, setup
from setuptools.command.bdist_egg import bdist_egg
from setuptools.command.build_py imp... |
18,451 | /home/hieuvd/dung_repo/raw/stars_01/jupyterhub_jupyterhub/jupyterhub | /home/hieuvd/dung_repo/raw/stars_01/jupyterhub_jupyterhub/jupyterhub/setup.py | 217,218 | 216,229 | run | Command | 218,229 | 218,229 | class Command(cls):
def run(self):
FILL_FUNC_BODY | class Command(cls):
def run(self):
FILL_FUNC_BODY | try:
self.run_command('js')
self.run_command('css')
self.run_command('jsx')
except Exception:
if strict:
raise
else:
pass
return super().run()
| try:
self.run_command('js')
self.run_command('css')
self.run_command('jsx')
except Exception:
if strict:
raise
else:
pass
return super().run()
| 13 | 24 | 74 | 98 | #!/usr/bin/env python3
# Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.
import os
import shutil
import sys
from subprocess import check_call
from setuptools import Command, setup
from setuptools.command.bdist_egg import bdist_egg
from setuptools.command.build_py imp... | #!/usr/bin/env python3
# Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.
import os
import shutil
import sys
from subprocess import check_call
from setuptools import Command, setup
from setuptools.command.bdist_egg import bdist_egg
from setuptools.command.build_py imp... |
18,452 | /home/hieuvd/dung_repo/raw/stars_01/jupyterhub_jupyterhub/jupyterhub | /home/hieuvd/dung_repo/raw/stars_01/jupyterhub_jupyterhub/jupyterhub/setup.py | 174,175 | 168,215 | should_run | JSX | 175,188 | 175,188 | class JSX(BaseCommand):
description = "build admin app"
jsx_dir = pjoin(here, 'jsx')
js_target = pjoin(static, 'js', 'admin-react.js')
def should_run(self):
FILL_FUNC_BODY def run(self):
if not self.should_run():
print("JSX admin app is up to date")
return
i... | class JSX(BaseCommand):
description = "build admin app"
jsx_dir = pjoin(here, 'jsx')
js_target = pjoin(static, 'js', 'admin-react.js')
def should_run(self):
FILL_FUNC_BODY def run(self):
if not self.should_run():
print("JSX admin app is up to date")
return
i... | if os.getenv('READTHEDOCS'):
# yarn not available on RTD
return False
if not os.path.exists(self.js_target):
return True
js_target_mtime = mtime(self.js_target)
jsx_mtime = recursive_mtime(self.jsx_dir)
if js_target_mtime < jsx_mtime:
... | if os.getenv('READTHEDOCS'):
# yarn not available on RTD
return False
if not os.path.exists(self.js_target):
return True
js_target_mtime = mtime(self.js_target)
jsx_mtime = recursive_mtime(self.jsx_dir)
if js_target_mtime < jsx_mtime:
... | 29 | 299 | 127 | 426 | #!/usr/bin/env python3
# Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.
import os
import shutil
import sys
from subprocess import check_call
from setuptools import Command, setup
from setuptools.command.bdist_egg import bdist_egg
from setuptools.command.build_py imp... | #!/usr/bin/env python3
# Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.
import os
import shutil
import sys
from subprocess import check_call
from setuptools import Command, setup
from setuptools.command.bdist_egg import bdist_egg
from setuptools.command.build_py imp... |
18,453 | /home/hieuvd/dung_repo/raw/stars_01/jupyterhub_jupyterhub/jupyterhub | /home/hieuvd/dung_repo/raw/stars_01/jupyterhub_jupyterhub/jupyterhub/setup.py | 96,97 | 80,115 | run | NPM | 97,115 | 97,115 | class NPM(BaseCommand):
description = "fetch static client-side components with bower"
user_options = []
node_modules = pjoin(here, 'node_modules')
bower_dir = pjoin(static, 'components')
def should_run(self):
if not os.path.exists(self.bower_dir):
return True
if not os... | class NPM(BaseCommand):
description = "fetch static client-side components with bower"
user_options = []
node_modules = pjoin(here, 'node_modules')
bower_dir = pjoin(static, 'components')
def should_run(self):
if not os.path.exists(self.bower_dir):
return True
if not os... | if not self.should_run():
print("npm dependencies up to date")
return
print("installing js dependencies with npm")
check_call(
['npm', 'install', '--progress=false', '--unsafe-perm'],
cwd=here,
shell=shell,
)
os.utime(s... | if not self.should_run():
print("npm dependencies up to date")
return
print("installing js dependencies with npm")
check_call(
['npm', 'install', '--progress=false', '--unsafe-perm'],
cwd=here,
shell=shell,
)
os.utime(s... | 41 | 184 | 174 | 358 | #!/usr/bin/env python3
# Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.
import os
import shutil
import sys
from subprocess import check_call
from setuptools import Command, setup
from setuptools.command.bdist_egg import bdist_egg
from setuptools.command.build_py imp... | #!/usr/bin/env python3
# Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.
import os
import shutil
import sys
from subprocess import check_call
from setuptools import Command, setup
from setuptools.command.bdist_egg import bdist_egg
from setuptools.command.build_py imp... |
18,454 | /home/hieuvd/dung_repo/raw/stars_01/jupyterhub_jupyterhub/jupyterhub | /home/hieuvd/dung_repo/raw/stars_01/jupyterhub_jupyterhub/jupyterhub/setup.py | 239,240 | 232,245 | run | bdist_egg_disabled | 240,245 | 240,245 | class bdist_egg_disabled(bdist_egg):
"""Disabled version of bdist_egg
Prevents setup.py install from performing setuptools' default easy_install,
which it should never ever do.
"""
def run(self):
FILL_FUNC_BODY | class bdist_egg_disabled(bdist_egg):
"""Disabled version of bdist_egg
Prevents setup.py install from performing setuptools' default easy_install,
which it should never ever do.
"""
def run(self):
FILL_FUNC_BODY | sys.exit(
"Aborting implicit building of eggs. Use `pip install .` to install from source."
)
| sys.exit(
"Aborting implicit building of eggs. Use `pip install .` to install from source."
)
| 15 | 78 | 38 | 116 | #!/usr/bin/env python3
# Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.
import os
import shutil
import sys
from subprocess import check_call
from setuptools import Command, setup
from setuptools.command.bdist_egg import bdist_egg
from setuptools.command.build_py imp... | #!/usr/bin/env python3
# Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.
import os
import shutil
import sys
from subprocess import check_call
from setuptools import Command, setup
from setuptools.command.bdist_egg import bdist_egg
from setuptools.command.build_py imp... |
18,455 | /home/hieuvd/dung_repo/raw/stars_01/jupyterhub_jupyterhub/jupyterhub | /home/hieuvd/dung_repo/raw/stars_01/jupyterhub_jupyterhub/jupyterhub/setup.py | 246,247 | 245,253 | run | develop_js_css | 247,253 | 247,253 | class develop_js_css(develop):
def run(self):
FILL_FUNC_BODY | class develop_js_css(develop):
def run(self):
FILL_FUNC_BODY | if not self.uninstall:
self.distribution.run_command('js')
self.distribution.run_command('css')
super().run()
| if not self.uninstall:
self.distribution.run_command('js')
self.distribution.run_command('css')
super().run()
| 6 | 27 | 47 | 74 | #!/usr/bin/env python3
# Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.
import os
import shutil
import sys
from subprocess import check_call
from setuptools import Command, setup
from setuptools.command.bdist_egg import bdist_egg
from setuptools.command.build_py imp... | #!/usr/bin/env python3
# Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.
import os
import shutil
import sys
from subprocess import check_call
from setuptools import Command, setup
from setuptools.command.bdist_egg import bdist_egg
from setuptools.command.build_py imp... |
18,462 | /home/hieuvd/dung_repo/raw/stars_01/jzhang38_TinyLlama/TinyLlama | /home/hieuvd/dung_repo/raw/stars_01/jzhang38_TinyLlama/TinyLlama/lit_gpt/config.py | 80,82 | 11,101 | mlp_class | Config | 82,85 | 82,85 | @dataclass
class Config:
org: str = "Lightning-AI"
name: str = "lit-GPT"
block_size: int = 4096
vocab_size: int = 50254
padding_multiple: int = 512
padded_vocab_size: Optional[int] = None
n_layer: int = 16
n_head: int = 32
n_embd: int = 4096
rotary_percentage: float = 0.25
pa... | @dataclass
class Config:
org: str = "Lightning-AI"
name: str = "lit-GPT"
block_size: int = 4096
vocab_size: int = 50254
padding_multiple: int = 512
padded_vocab_size: Optional[int] = None
n_layer: int = 16
n_head: int = 32
n_embd: int = 4096
rotary_percentage: float = 0.25
pa... | # `self._mlp_class` cannot be the type to keep the config json serializable
return getattr(lit_gpt.model, self._mlp_class)
| # `self._mlp_class` cannot be the type to keep the config json serializable
return getattr(lit_gpt.model, self._mlp_class)
| 15 | 1,503 | 46 | 1,549 | from dataclasses import dataclass
from typing import Any, Literal, Optional, Type
import torch
from typing_extensions import Self
import lit_gpt.model
from lit_gpt.utils import find_multiple
@dataclass
class Config:
org: str = "Lightning-AI"
name: str = "lit-GPT"
block_size: int = 4096
vocab_size: i... | from dataclasses import dataclass
from typing import Any, Literal, Optional, Type
import torch
from typing_extensions import Self
import lit_gpt.model
from lit_gpt.utils import find_multiple
@dataclass
class Config:
org: str = "Lightning-AI"
name: str = "lit-GPT"
block_size: int = 4096
vocab_size: i... |
18,464 | /home/hieuvd/dung_repo/raw/stars_01/jzhang38_TinyLlama/TinyLlama | /home/hieuvd/dung_repo/raw/stars_01/jzhang38_TinyLlama/TinyLlama/lit_gpt/packed_dataset.py | 106,107 | 60,121 | add_array | PackedDatasetBuilder | 107,117 | 107,117 | class PackedDatasetBuilder(object):
def __init__(self, outdir, prefix, chunk_size, sep_token, dtype="auto", vocab_size=None):
if dtype == "auto":
if vocab_size is None:
raise ValueError("vocab_size cannot be None when dtype='auto'")
if vocab_size is not None and vocab... | class PackedDatasetBuilder(object):
def __init__(self, outdir, prefix, chunk_size, sep_token, dtype="auto", vocab_size=None):
if dtype == "auto":
if vocab_size is None:
raise ValueError("vocab_size cannot be None when dtype='auto'")
if vocab_size is not None and vocab... | while self._idx + arr.shape[0] > self._chunk_size:
part_len = self._chunk_size - self._idx
self._arr[self._idx : self._idx + part_len] = arr[:part_len]
self._write_chunk()
arr = arr[part_len:]
arr_len = arr.shape[0]
self._arr[self._idx : self._idx... | while self._idx + arr.shape[0] > self._chunk_size:
part_len = self._chunk_size - self._idx
self._arr[self._idx : self._idx + part_len] = arr[:part_len]
self._write_chunk()
arr = arr[part_len:]
arr_len = arr.shape[0]
self._arr[self._idx : self._idx... | 35 | 540 | 134 | 674 | # Very loosely inspired by indexed_dataset in Fairseq, Megatron
# https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/data/indexed_dataset.py
import os
import random
import struct
import numpy as np
import torch
from torch.utils.data import IterableDataset, get_worker_info
dtypes = {1: np.uint8, 2: np.int8, 3:... | # Very loosely inspired by indexed_dataset in Fairseq, Megatron
# https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/data/indexed_dataset.py
import os
import random
import struct
import numpy as np
import torch
from torch.utils.data import IterableDataset, get_worker_info
dtypes = {1: np.uint8, 2: np.int8, 3:... |
18,465 | /home/hieuvd/dung_repo/raw/stars_01/jzhang38_TinyLlama/TinyLlama | /home/hieuvd/dung_repo/raw/stars_01/jzhang38_TinyLlama/TinyLlama/lit_gpt/packed_dataset.py | 150,151 | 121,214 | _read_header | PackedDatasetIterator | 151,161 | 151,161 | class PackedDatasetIterator:
def __init__(self, filenames, n_chunks, block_size, seed, shuffle, wrap):
self._seed = seed
self._shuffle = shuffle
self._rng = np.random.default_rng(seed) if shuffle else None
self._block_idxs = None
self._wrap = wrap
# TODO: instead of... | class PackedDatasetIterator:
def __init__(self, filenames, n_chunks, block_size, seed, shuffle, wrap):
self._seed = seed
self._shuffle = shuffle
self._rng = np.random.default_rng(seed) if shuffle else None
self._block_idxs = None
self._wrap = wrap
# TODO: instead of... | with open(path, "rb") as f:
magic = f.read(len(HDR_MAGIC))
assert magic == HDR_MAGIC, "File doesn't match expected format."
version = struct.unpack("<Q", f.read(8))
assert version == (1,)
(dtype_code,) = struct.unpack("<B", f.read(1))
dtype... | with open(path, "rb") as f:
magic = f.read(len(HDR_MAGIC))
assert magic == HDR_MAGIC, "File doesn't match expected format."
version = struct.unpack("<Q", f.read(8))
assert version == (1,)
(dtype_code,) = struct.unpack("<B", f.read(1))
dtype... | 39 | 893 | 156 | 1,049 | # Very loosely inspired by indexed_dataset in Fairseq, Megatron
# https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/data/indexed_dataset.py
import os
import random
import struct
import numpy as np
import torch
from torch.utils.data import IterableDataset, get_worker_info
dtypes = {1: np.uint8, 2: np.int8, 3:... | # Very loosely inspired by indexed_dataset in Fairseq, Megatron
# https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/data/indexed_dataset.py
import os
import random
import struct
import numpy as np
import torch
from torch.utils.data import IterableDataset, get_worker_info
dtypes = {1: np.uint8, 2: np.int8, 3:... |
18,469 | /home/hieuvd/dung_repo/raw/stars_01/kaixindelele_ChatPaper/ChatPaper | /home/hieuvd/dung_repo/raw/stars_01/kaixindelele_ChatPaper/ChatPaper/ChatReviewerAndResponse/chat_response.py | 141,142 | 1,157 | chat_response_main | 142,146 | 142,146 | import argparse
import configparser
import datetime
import json
import os
import re
import time
from collections import namedtuple
import numpy as np
import openai
import tenacity
import tiktoken
from get_paper import Paper
# ChatResponse
ResponseParams = namedtuple(
"Params", ["comment_path", "file_format", "l... | import argparse
import configparser
import datetime
import json
import os
import re
import time
from collections import namedtuple
import numpy as np
import openai
import tenacity
import tiktoken
from get_paper import Paper
# ChatResponse
ResponseParams = namedtuple(
"Params", ["comment_path", "file_format", "l... | Response1 = Response(args=args)
Response1.response_by_chatgpt(comment_path=args.comment_path)
| Response1 = Response(args=args)
Response1.response_by_chatgpt(comment_path=args.comment_path)
| 4 | 1,683 | 40 | 1,723 | import argparse
import configparser
import datetime
import json
import os
import re
import time
from collections import namedtuple
import numpy as np
import openai
import tenacity
import tiktoken
from get_paper import Paper
# ChatResponse
ResponseParams = namedtuple(
"Params", ["comment_path", "file_format", "l... | import argparse
import configparser
import datetime
import json
import os
import re
import time
from collections import namedtuple
import numpy as np
import openai
import tenacity
import tiktoken
from get_paper import Paper
# ChatResponse
ResponseParams = namedtuple(
"Params", ["comment_path", "file_format", "l... | |
18,470 | /home/hieuvd/dung_repo/raw/stars_01/kaixindelele_ChatPaper/ChatPaper | /home/hieuvd/dung_repo/raw/stars_01/kaixindelele_ChatPaper/ChatPaper/ChatReviewerAndResponse/chat_response.py | 69,73 | 25,141 | chat_response | Response | 73,132 | 73,132 | class Response:
# 初始化方法,设置属性
def __init__(self, args=None):
if args.language == 'en':
self.language = 'English'
elif args.language == 'zh':
self.language = 'Chinese'
else:
self.language = 'Chinese'
# 创建一个ConfigParser对象
self.config =... | class Response:
# 初始化方法,设置属性
def __init__(self, args=None):
if args.language == 'en':
self.language = 'English'
elif args.language == 'zh':
self.language = 'Chinese'
else:
self.language = 'Chinese'
# 创建一个ConfigParser对象
self.config =... | openai.api_key = self.chat_api_list[self.cur_api]
self.cur_api += 1
self.cur_api = 0 if self.cur_api >= len(self.chat_api_list) - 1 else self.cur_api
response_prompt_token = 1000
text_token = len(self.encoding.encode(text))
input_text_index = int(len(text) * (self.max_tok... | openai.api_key = self.chat_api_list[self.cur_api]
self.cur_api += 1
self.cur_api = 0 if self.cur_api >= len(self.chat_api_list) - 1 else self.cur_api
response_prompt_token = 1000
text_token = len(self.encoding.encode(text))
input_text_index = int(len(text) * (self.max_tok... | 197 | 776 | 668 | 1,444 | import argparse
import configparser
import datetime
import json
import os
import re
import time
from collections import namedtuple
import numpy as np
import openai
import tenacity
import tiktoken
from get_paper import Paper
# ChatResponse
ResponseParams = namedtuple(
"Params", ["comment_path", "file_format", "l... | import argparse
import configparser
import datetime
import json
import os
import re
import time
from collections import namedtuple
import numpy as np
import openai
import tenacity
import tiktoken
from get_paper import Paper
# ChatResponse
ResponseParams = namedtuple(
"Params", ["comment_path", "file_format", "l... |
18,475 | /home/hieuvd/dung_repo/raw/stars_01/kaixindelele_ChatPaper/ChatPaper | /home/hieuvd/dung_repo/raw/stars_01/kaixindelele_ChatPaper/ChatPaper/auto_survey/utils/figures.py | 12,13 | 1,48 | generate_line_plots | 13,22 | 13,22 | import numpy as np
import matplotlib.pyplot as plt
def generate_points(initial_value, final_value, smoothness=0.1, max_num = 200):
x = np.array([_ for _ in range(max_num)])
y = initial_value + ( final_value-initial_value) * (x/200)**smoothness
noise = np.random.normal(0, 0.01, max_num)
y += noise
r... | import numpy as np
import matplotlib.pyplot as plt
def generate_points(initial_value, final_value, smoothness=0.1, max_num = 200):
x = np.array([_ for _ in range(max_num)])
y = initial_value + ( final_value-initial_value) * (x/200)**smoothness
noise = np.random.normal(0, 0.01, max_num)
y += noise
r... | plt.figure()
for i in range(num_curves):
x, y = data[i]
plt.plot(x , y, label=legends[i])
plt.xlabel(x_label)
plt.ylabel(y_label)
plt.legend()
plt.savefig(save_to)
| plt.figure()
for i in range(num_curves):
x, y = data[i]
plt.plot(x , y, label=legends[i])
plt.xlabel(x_label)
plt.ylabel(y_label)
plt.legend()
plt.savefig(save_to)
| 17 | 539 | 101 | 640 | import numpy as np
import matplotlib.pyplot as plt
def generate_points(initial_value, final_value, smoothness=0.1, max_num = 200):
x = np.array([_ for _ in range(max_num)])
y = initial_value + ( final_value-initial_value) * (x/200)**smoothness
noise = np.random.normal(0, 0.01, max_num)
y += noise
r... | import numpy as np
import matplotlib.pyplot as plt
def generate_points(initial_value, final_value, smoothness=0.1, max_num = 200):
x = np.array([_ for _ in range(max_num)])
y = initial_value + ( final_value-initial_value) * (x/200)**smoothness
noise = np.random.normal(0, 0.01, max_num)
y += noise
r... | |
18,476 | /home/hieuvd/dung_repo/raw/stars_01/kaixindelele_ChatPaper/ChatPaper | /home/hieuvd/dung_repo/raw/stars_01/kaixindelele_ChatPaper/ChatPaper/auto_survey/utils/file_operations.py | 39,40 | 1,59 | copy_templates | 40,54 | 40,54 | import hashlib
import os, shutil
import datetime
from utils.tex_processing import replace_title
import re
def urlify(s):
# Remove all non-word characters (everything except numbers and letters)
s = re.sub(r"[^\w\s]", '', s)
# Replace all runs of whitespace with a single dash
s = re.sub(r"\s+", '_', s)
... | import hashlib
import os, shutil
import datetime
from utils.tex_processing import replace_title
import re
def urlify(s):
# Remove all non-word characters (everything except numbers and letters)
s = re.sub(r"[^\w\s]", '', s)
# Replace all runs of whitespace with a single dash
s = re.sub(r"\s+", '_', s)
... | # Create a copy in the outputs folder.
# 1. create a folder "outputs_%Y%m%d_%H%M%S" (destination_folder)
# 2. copy all contents in "latex_templates/{template}" to that folder
# 3. return (bibtex_path, destination_folder)
now = datetime.datetime.now()
target_name = now.strftime("outputs_%Y%... | # Create a copy in the outputs folder.
# 1. create a folder "outputs_%Y%m%d_%H%M%S" (destination_folder)
# 2. copy all contents in "latex_templates/{template}" to that folder
# 3. return (bibtex_path, destination_folder)
now = datetime.datetime.now()
target_name = now.strftime("outputs_%Y%... | 59 | 430 | 253 | 683 | import hashlib
import os, shutil
import datetime
from utils.tex_processing import replace_title
import re
def urlify(s):
# Remove all non-word characters (everything except numbers and letters)
s = re.sub(r"[^\w\s]", '', s)
# Replace all runs of whitespace with a single dash
s = re.sub(r"\s+", '_', s)
... | import hashlib
import os, shutil
import datetime
from utils.tex_processing import replace_title
import re
def urlify(s):
# Remove all non-word characters (everything except numbers and letters)
s = re.sub(r"[^\w\s]", '', s)
# Replace all runs of whitespace with a single dash
s = re.sub(r"\s+", '_', s)
... | |
18,477 | /home/hieuvd/dung_repo/raw/stars_01/kaixindelele_ChatPaper/ChatPaper | /home/hieuvd/dung_repo/raw/stars_01/kaixindelele_ChatPaper/ChatPaper/auto_survey/utils/gpt_interaction.py | 11,12 | 1,124 | get_gpt_responses | 12,28 | 12,28 | import os
import time
import openai
import logging
import requests
import json
log = logging.getLogger(__name__)
def get_gpt_responses(systems, prompts, model="gpt-4", temperature=0.4):
FILL_FUNC_BODYclass GPTModel_API2D_SUPPORT:
def __init__(self, model="gpt-4", temperature=0, presence_penalty=0,
... | import os
import time
import openai
import logging
import requests
import json
log = logging.getLogger(__name__)
def get_gpt_responses(systems, prompts, model="gpt-4", temperature=0.4):
FILL_FUNC_BODYclass GPTModel_API2D_SUPPORT:
def __init__(self, model="gpt-4", temperature=0, presence_penalty=0,
... | conversation_history = [
{"role": "system", "content": systems},
{"role": "user", "content": prompts}
]
response = openai.ChatCompletion.create(
model=model,
messages=conversation_history,
n=1, # Number of responses you want to generate
temperature=temperatur... | conversation_history = [
{"role": "system", "content": systems},
{"role": "user", "content": prompts}
]
response = openai.ChatCompletion.create(
model=model,
messages=conversation_history,
n=1, # Number of responses you want to generate
temperature=temperatur... | 46 | 1,169 | 164 | 1,333 | import os
import time
import openai
import logging
import requests
import json
log = logging.getLogger(__name__)
def get_gpt_responses(systems, prompts, model="gpt-4", temperature=0.4):
FILL_FUNC_BODYclass GPTModel_API2D_SUPPORT:
def __init__(self, model="gpt-4", temperature=0, presence_penalty=0,
... | import os
import time
import openai
import logging
import requests
import json
log = logging.getLogger(__name__)
def get_gpt_responses(systems, prompts, model="gpt-4", temperature=0.4):
FILL_FUNC_BODYclass GPTModel_API2D_SUPPORT:
def __init__(self, model="gpt-4", temperature=0, presence_penalty=0,
... | |
18,478 | /home/hieuvd/dung_repo/raw/stars_01/kaixindelele_ChatPaper/ChatPaper | /home/hieuvd/dung_repo/raw/stars_01/kaixindelele_ChatPaper/ChatPaper/auto_survey/utils/knowledge.py | 8,9 | 1,62 | tiktoken_len | 9,14 | 9,14 | import tiktoken
from random import shuffle
# `tokenizer`: used to count how many tokens
tokenizer_name = tiktoken.encoding_for_model('gpt-4')
tokenizer = tiktoken.get_encoding(tokenizer_name.name)
def tiktoken_len(text):
FILL_FUNC_BODYclass Knowledge:
def __init__(self, db):
self.db = db
self.cont... | import tiktoken
from random import shuffle
# `tokenizer`: used to count how many tokens
tokenizer_name = tiktoken.encoding_for_model('gpt-4')
tokenizer = tiktoken.get_encoding(tokenizer_name.name)
def tiktoken_len(text):
FILL_FUNC_BODYclass Knowledge:
def __init__(self, db):
self.db = db
self.cont... | # evaluate how many tokens for the given text
tokens = tokenizer.encode(text, disallowed_special=())
return len(tokens)
| # evaluate how many tokens for the given text
tokens = tokenizer.encode(text, disallowed_special=())
return len(tokens)
| 15 | 530 | 43 | 573 | import tiktoken
from random import shuffle
# `tokenizer`: used to count how many tokens
tokenizer_name = tiktoken.encoding_for_model('gpt-4')
tokenizer = tiktoken.get_encoding(tokenizer_name.name)
def tiktoken_len(text):
FILL_FUNC_BODYclass Knowledge:
def __init__(self, db):
self.db = db
self.cont... | import tiktoken
from random import shuffle
# `tokenizer`: used to count how many tokens
tokenizer_name = tiktoken.encoding_for_model('gpt-4')
tokenizer = tiktoken.get_encoding(tokenizer_name.name)
def tiktoken_len(text):
FILL_FUNC_BODYclass Knowledge:
def __init__(self, db):
self.db = db
self.cont... | |
18,479 | /home/hieuvd/dung_repo/raw/stars_01/kaixindelele_ChatPaper/ChatPaper | /home/hieuvd/dung_repo/raw/stars_01/kaixindelele_ChatPaper/ChatPaper/auto_survey/utils/knowledge.py | 35,36 | 14,62 | to_prompts | Knowledge | 36,49 | 36,49 | class Knowledge:
def __init__(self, db):
self.db = db
self.contents = []
def collect_knowledge(self, keywords_dict, max_query):
"""
keywords_dict:
{"machine learning": 5, "language model": 2};
"""
db = self.db
if max_query > 0:
for... | class Knowledge:
def __init__(self, db):
self.db = db
self.contents = []
def collect_knowledge(self, keywords_dict, max_query):
"""
keywords_dict:
{"machine learning": 5, "language model": 2};
"""
db = self.db
if max_query > 0:
for... | if len(self.contents) == 0:
return ""
prompts = []
tokens = 0
for idx, content in enumerate(self.contents):
prompt = "Reference {}: {}\n".format(idx, content["content"])
tokens += tiktoken_len(prompt)
if tokens >= max_tokens:
... | if len(self.contents) == 0:
return ""
prompts = []
tokens = 0
for idx, content in enumerate(self.contents):
prompt = "Reference {}: {}\n".format(idx, content["content"])
tokens += tiktoken_len(prompt)
if tokens >= max_tokens:
... | 35 | 340 | 127 | 467 | import tiktoken
from random import shuffle
# `tokenizer`: used to count how many tokens
tokenizer_name = tiktoken.encoding_for_model('gpt-4')
tokenizer = tiktoken.get_encoding(tokenizer_name.name)
def tiktoken_len(text):
# evaluate how many tokens for the given text
tokens = tokenizer.encode(text, disallowed_... | import tiktoken
from random import shuffle
# `tokenizer`: used to count how many tokens
tokenizer_name = tiktoken.encoding_for_model('gpt-4')
tokenizer = tiktoken.get_encoding(tokenizer_name.name)
def tiktoken_len(text):
# evaluate how many tokens for the given text
tokens = tokenizer.encode(text, disallowed_... |
18,480 | /home/hieuvd/dung_repo/raw/stars_01/kaixindelele_ChatPaper/ChatPaper | /home/hieuvd/dung_repo/raw/stars_01/kaixindelele_ChatPaper/ChatPaper/auto_survey/utils/tex_processing.py | 49,50 | 1,69 | create_copies | 50,64 | 50,64 | import os
import re
import shutil
def replace_title(save_to_path, title):
# Define input and output file names
input_file_name = os.path.join(save_to_path, "template.tex")
output_file_name = os.path.join(save_to_path , "main.tex")
# Open the input file and read its content
with open(input_file_nam... | import os
import re
import shutil
def replace_title(save_to_path, title):
# Define input and output file names
input_file_name = os.path.join(save_to_path, "template.tex")
output_file_name = os.path.join(save_to_path , "main.tex")
# Open the input file and read its content
with open(input_file_nam... | tex_files = find_tex_files(output_dir)
for tex_file in tex_files:
path = os.path.join(output_dir, tex_file)
all_figs = find_figure_names(path)
for fig in all_figs:
original_fig = os.path.join(output_dir, "fig.png")
target_fig = os.path.join(output_dir, fig)
... | tex_files = find_tex_files(output_dir)
for tex_file in tex_files:
path = os.path.join(output_dir, tex_file)
all_figs = find_figure_names(path)
for fig in all_figs:
original_fig = os.path.join(output_dir, "fig.png")
target_fig = os.path.join(output_dir, fig)
... | 37 | 480 | 162 | 642 | import os
import re
import shutil
def replace_title(save_to_path, title):
# Define input and output file names
input_file_name = os.path.join(save_to_path, "template.tex")
output_file_name = os.path.join(save_to_path , "main.tex")
# Open the input file and read its content
with open(input_file_nam... | import os
import re
import shutil
def replace_title(save_to_path, title):
# Define input and output file names
input_file_name = os.path.join(save_to_path, "template.tex")
output_file_name = os.path.join(save_to_path , "main.tex")
# Open the input file and read its content
with open(input_file_nam... | |
18,757 | /home/hieuvd/dung_repo/raw/stars_01/kennethreitz_records/records | /home/hieuvd/dung_repo/raw/stars_01/kennethreitz_records/records/setup.py | 58,59 | 1,107 | read | 59,62 | 59,62 | #!/usr/bin/env python
import io
import os
import sys
from codecs import open
from shutil import rmtree
from setuptools import setup, Command
here = os.path.abspath(os.path.dirname(__file__))
with io.open(os.path.join(here, "README.rst"), encoding="utf-8") as f:
long_description = "\n" + f.read()
class PublishC... | #!/usr/bin/env python
import io
import os
import sys
from codecs import open
from shutil import rmtree
from setuptools import setup, Command
here = os.path.abspath(os.path.dirname(__file__))
with io.open(os.path.join(here, "README.rst"), encoding="utf-8") as f:
long_description = "\n" + f.read()
class PublishC... | return open(f, encoding="utf-8").read()
| return open(f, encoding="utf-8").read()
| 3 | 980 | 21 | 1,001 | #!/usr/bin/env python
import io
import os
import sys
from codecs import open
from shutil import rmtree
from setuptools import setup, Command
here = os.path.abspath(os.path.dirname(__file__))
with io.open(os.path.join(here, "README.rst"), encoding="utf-8") as f:
long_description = "\n" + f.read()
class PublishC... | #!/usr/bin/env python
import io
import os
import sys
from codecs import open
from shutil import rmtree
from setuptools import setup, Command
here = os.path.abspath(os.path.dirname(__file__))
with io.open(os.path.join(here, "README.rst"), encoding="utf-8") as f:
long_description = "\n" + f.read()
class PublishC... | |
18,758 | /home/hieuvd/dung_repo/raw/stars_01/kennethreitz_records/records | /home/hieuvd/dung_repo/raw/stars_01/kennethreitz_records/records/setup.py | 33,34 | 16,49 | run | PublishCommand | 34,49 | 34,49 | class PublishCommand(Command):
"""Support setup.py publish."""
description = "Build and publish the package."
user_options = []
@staticmethod
def status(s):
"""Prints things in bold."""
print("\033[1m{}\033[0m".format(s))
def initialize_options(self):
pass
def fin... | class PublishCommand(Command):
"""Support setup.py publish."""
description = "Build and publish the package."
user_options = []
@staticmethod
def status(s):
"""Prints things in bold."""
print("\033[1m{}\033[0m".format(s))
def initialize_options(self):
pass
def fin... | try:
self.status("Removing previous builds...")
rmtree(os.path.join(here, "dist"))
except FileNotFoundError:
pass
self.status("Building Source and Wheel (universal) distribution...")
os.system("{} setup.py sdist bdist_wheel --universal".format(sys.exe... | try:
self.status("Removing previous builds...")
rmtree(os.path.join(here, "dist"))
except FileNotFoundError:
pass
self.status("Building Source and Wheel (universal) distribution...")
os.system("{} setup.py sdist bdist_wheel --universal".format(sys.exe... | 31 | 126 | 144 | 270 | #!/usr/bin/env python
import io
import os
import sys
from codecs import open
from shutil import rmtree
from setuptools import setup, Command
here = os.path.abspath(os.path.dirname(__file__))
with io.open(os.path.join(here, "README.rst"), encoding="utf-8") as f:
long_description = "\n" + f.read()
class PublishC... | #!/usr/bin/env python
import io
import os
import sys
from codecs import open
from shutil import rmtree
from setuptools import setup, Command
here = os.path.abspath(os.path.dirname(__file__))
with io.open(os.path.join(here, "README.rst"), encoding="utf-8") as f:
long_description = "\n" + f.read()
class PublishC... |
19,743 | /home/hieuvd/dung_repo/raw/stars_01/kkroening_ffmpeg-python/ffmpeg-python | /home/hieuvd/dung_repo/raw/stars_01/kkroening_ffmpeg-python/ffmpeg-python/examples/get_video_thumbnail.py | 18,19 | 1,36 | generate_thumbnail | 19,33 | 19,33 | #!/usr/bin/env python
from __future__ import unicode_literals, print_function
import argparse
import ffmpeg
import sys
parser = argparse.ArgumentParser(description='Generate video thumbnail')
parser.add_argument('in_filename', help='Input filename')
parser.add_argument('out_filename', help='Output filename')
parser.a... | #!/usr/bin/env python
from __future__ import unicode_literals, print_function
import argparse
import ffmpeg
import sys
parser = argparse.ArgumentParser(description='Generate video thumbnail')
parser.add_argument('in_filename', help='Input filename')
parser.add_argument('out_filename', help='Output filename')
parser.a... | try:
(
ffmpeg
.input(in_filename, ss=time)
.filter('scale', width, -1)
.output(out_filename, vframes=1)
.overwrite_output()
.run(capture_stdout=True, capture_stderr=True)
)
except ffmpeg.Error as e:
print(e.stderr.de... | try:
(
ffmpeg
.input(in_filename, ss=time)
.filter('scale', width, -1)
.output(out_filename, vframes=1)
.overwrite_output()
.run(capture_stdout=True, capture_stderr=True)
)
except ffmpeg.Error as e:
print(e.stderr.de... | 21 | 239 | 135 | 374 | #!/usr/bin/env python
from __future__ import unicode_literals, print_function
import argparse
import ffmpeg
import sys
parser = argparse.ArgumentParser(description='Generate video thumbnail')
parser.add_argument('in_filename', help='Input filename')
parser.add_argument('out_filename', help='Output filename')
parser.a... | #!/usr/bin/env python
from __future__ import unicode_literals, print_function
import argparse
import ffmpeg
import sys
parser = argparse.ArgumentParser(description='Generate video thumbnail')
parser.add_argument('in_filename', help='Input filename')
parser.add_argument('out_filename', help='Output filename')
parser.a... | |
19,744 | /home/hieuvd/dung_repo/raw/stars_01/kkroening_ffmpeg-python/ffmpeg-python | /home/hieuvd/dung_repo/raw/stars_01/kkroening_ffmpeg-python/ffmpeg-python/examples/read_frame_as_jpeg.py | 14,15 | 1,29 | read_frame_as_jpeg | 15,25 | 15,25 | #!/usr/bin/env python
from __future__ import unicode_literals
import argparse
import ffmpeg
import sys
parser = argparse.ArgumentParser(
description='Read individual video frame into memory as jpeg and write to stdout')
parser.add_argument('in_filename', help='Input filename')
parser.add_argument('frame_num', hel... | #!/usr/bin/env python
from __future__ import unicode_literals
import argparse
import ffmpeg
import sys
parser = argparse.ArgumentParser(
description='Read individual video frame into memory as jpeg and write to stdout')
parser.add_argument('in_filename', help='Input filename')
parser.add_argument('frame_num', hel... | out, err = (
ffmpeg
.input(in_filename)
.filter('select', 'gte(n,{})'.format(frame_num))
.output('pipe:', vframes=1, format='image2', vcodec='mjpeg')
.run(capture_stdout=True)
)
return out
| out, err = (
ffmpeg
.input(in_filename)
.filter('select', 'gte(n,{})'.format(frame_num))
.output('pipe:', vframes=1, format='image2', vcodec='mjpeg')
.run(capture_stdout=True)
)
return out
| 16 | 186 | 102 | 288 | #!/usr/bin/env python
from __future__ import unicode_literals
import argparse
import ffmpeg
import sys
parser = argparse.ArgumentParser(
description='Read individual video frame into memory as jpeg and write to stdout')
parser.add_argument('in_filename', help='Input filename')
parser.add_argument('frame_num', hel... | #!/usr/bin/env python
from __future__ import unicode_literals
import argparse
import ffmpeg
import sys
parser = argparse.ArgumentParser(
description='Read individual video frame into memory as jpeg and write to stdout')
parser.add_argument('in_filename', help='Input filename')
parser.add_argument('frame_num', hel... | |
19,745 | /home/hieuvd/dung_repo/raw/stars_01/kkroening_ffmpeg-python/ffmpeg-python | /home/hieuvd/dung_repo/raw/stars_01/kkroening_ffmpeg-python/ffmpeg-python/examples/split_silence.py | 41,42 | 1,142 | get_chunk_times | 42,97 | 42,97 | #!/usr/bin/env python
from __future__ import unicode_literals
import argparse
import errno
import ffmpeg
import logging
import os
import re
import subprocess
import sys
logging.basicConfig(level=logging.INFO, format='%(message)s')
logger = logging.getLogger(__file__)
logger.setLevel(logging.INFO)
DEFAULT_DURATION =... | #!/usr/bin/env python
from __future__ import unicode_literals
import argparse
import errno
import ffmpeg
import logging
import os
import re
import subprocess
import sys
logging.basicConfig(level=logging.INFO, format='%(message)s')
logger = logging.getLogger(__file__)
logger.setLevel(logging.INFO)
DEFAULT_DURATION =... | input_kwargs = {}
if start_time is not None:
input_kwargs['ss'] = start_time
else:
start_time = 0.
if end_time is not None:
input_kwargs['t'] = end_time - start_time
p = _logged_popen(
(ffmpeg
.input(in_filename, **input_kwargs)
.filter('silen... | input_kwargs = {}
if start_time is not None:
input_kwargs['ss'] = start_time
else:
start_time = 0.
if end_time is not None:
input_kwargs['t'] = end_time - start_time
p = _logged_popen(
(ffmpeg
.input(in_filename, **input_kwargs)
.filter('silen... | 157 | 1,113 | 700 | 1,813 | #!/usr/bin/env python
from __future__ import unicode_literals
import argparse
import errno
import ffmpeg
import logging
import os
import re
import subprocess
import sys
logging.basicConfig(level=logging.INFO, format='%(message)s')
logger = logging.getLogger(__file__)
logger.setLevel(logging.INFO)
DEFAULT_DURATION =... | #!/usr/bin/env python
from __future__ import unicode_literals
import argparse
import errno
import ffmpeg
import logging
import os
import re
import subprocess
import sys
logging.basicConfig(level=logging.INFO, format='%(message)s')
logger = logging.getLogger(__file__)
logger.setLevel(logging.INFO)
DEFAULT_DURATION =... | |
19,747 | /home/hieuvd/dung_repo/raw/stars_01/kkroening_ffmpeg-python/ffmpeg-python | /home/hieuvd/dung_repo/raw/stars_01/kkroening_ffmpeg-python/ffmpeg-python/ffmpeg/_probe.py | 7,8 | 1,31 | probe | 16,30 | 8,30 | import json
import subprocess
from ._run import Error
from ._utils import convert_kwargs_to_cmd_line_args
def probe(filename, cmd='ffprobe', timeout=None, **kwargs):
FILL_FUNC_BODY__all__ = ['probe']
| import json
import subprocess
from ._run import Error
from ._utils import convert_kwargs_to_cmd_line_args
def probe(filename, cmd='ffprobe', timeout=None, **kwargs):
"""Run ffprobe on the specified file and return a JSON representation of the output.
Raises:
:class:`ffmpeg.Error`: if ffprobe returns ... | args = [cmd, '-show_format', '-show_streams', '-of', 'json']
args += convert_kwargs_to_cmd_line_args(kwargs)
args += [filename]
p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
communicate_kwargs = {}
if timeout is not None:
communicate_kwargs['timeout'] = time... | """Run ffprobe on the specified file and return a JSON representation of the output.
Raises:
:class:`ffmpeg.Error`: if ffprobe returns a non-zero exit code,
an :class:`Error` is returned with a generic error message.
The stderr output can be retrieved by accessing the
... | 43 | 163 | 177 | 340 | import json
import subprocess
from ._run import Error
from ._utils import convert_kwargs_to_cmd_line_args
def probe(filename, cmd='ffprobe', timeout=None, **kwargs):
FILL_FUNC_BODY__all__ = ['probe']
| import json
import subprocess
from ._run import Error
from ._utils import convert_kwargs_to_cmd_line_args
def probe(filename, cmd='ffprobe', timeout=None, **kwargs):
"""Run ffprobe on the specified file and return a JSON representation of the output.
Raises:
:class:`ffmpeg.Error`: if ffprobe returns ... | |
19,749 | /home/hieuvd/dung_repo/raw/stars_01/kkroening_ffmpeg-python/ffmpeg-python | /home/hieuvd/dung_repo/raw/stars_01/kkroening_ffmpeg-python/ffmpeg-python/ffmpeg/_view.py | 32,34 | 1,109 | view | 34,108 | 34,108 | from __future__ import unicode_literals
from builtins import str
from .dag import get_outgoing_edges
from ._run import topo_sort
import tempfile
from ffmpeg.nodes import (
FilterNode,
get_stream_spec_nodes,
InputNode,
OutputNode,
stream_operator,
)
_RIGHT_ARROW = '\u2192'
def _get_node_color(n... | from __future__ import unicode_literals
from builtins import str
from .dag import get_outgoing_edges
from ._run import topo_sort
import tempfile
from ffmpeg.nodes import (
FilterNode,
get_stream_spec_nodes,
InputNode,
OutputNode,
stream_operator,
)
_RIGHT_ARROW = '\u2192'
def _get_node_color(n... | try:
import graphviz
except ImportError:
raise ImportError(
'failed to import graphviz; please make sure graphviz is installed (e.g. '
'`pip install graphviz`)'
)
show_labels = kwargs.pop('show_labels', True)
if pipe and filename is not None:
rais... | try:
import graphviz
except ImportError:
raise ImportError(
'failed to import graphviz; please make sure graphviz is installed (e.g. '
'`pip install graphviz`)'
)
show_labels = kwargs.pop('show_labels', True)
if pipe and filename is not None:
rais... | 223 | 243 | 832 | 1,075 | from __future__ import unicode_literals
from builtins import str
from .dag import get_outgoing_edges
from ._run import topo_sort
import tempfile
from ffmpeg.nodes import (
FilterNode,
get_stream_spec_nodes,
InputNode,
OutputNode,
stream_operator,
)
_RIGHT_ARROW = '\u2192'
def _get_node_color(n... | from __future__ import unicode_literals
from builtins import str
from .dag import get_outgoing_edges
from ._run import topo_sort
import tempfile
from ffmpeg.nodes import (
FilterNode,
get_stream_spec_nodes,
InputNode,
OutputNode,
stream_operator,
)
_RIGHT_ARROW = '\u2192'
def _get_node_color(n... | |
19,750 | /home/hieuvd/dung_repo/raw/stars_01/laramies_theHarvester/theHarvester | /home/hieuvd/dung_repo/raw/stars_01/laramies_theHarvester/theHarvester/theHarvester/discovery/anubis.py | 10,11 | 4,21 | do_search | SearchAnubis | 11,15 | 11,15 | class SearchAnubis:
def __init__(self, word) -> None:
self.word = word
self.totalhosts: list = []
self.proxy = False
async def do_search(self) -> None:
FILL_FUNC_BODY async def get_hostnames(self) -> list:
return self.totalhosts
async def process(self, proxy: bool = Fals... | class SearchAnubis:
def __init__(self, word) -> None:
self.word = word
self.totalhosts: list = []
self.proxy = False
async def do_search(self) -> None:
FILL_FUNC_BODY async def get_hostnames(self) -> list:
return self.totalhosts
async def process(self, proxy: bool = Fals... | url = f'https://jldc.me/anubis/subdomains/{self.word}'
response = await AsyncFetcher.fetch_all([url], json=True, proxy=self.proxy)
self.totalhosts = response[0]
| url = f'https://jldc.me/anubis/subdomains/{self.word}'
response = await AsyncFetcher.fetch_all([url], json=True, proxy=self.proxy)
self.totalhosts = response[0]
| 12 | 129 | 70 | 199 | from theHarvester.lib.core import AsyncFetcher
class SearchAnubis:
def __init__(self, word) -> None:
self.word = word
self.totalhosts: list = []
self.proxy = False
async def do_search(self) -> None:
FILL_FUNC_BODY async def get_hostnames(self) -> list:
return self.totalhost... | from theHarvester.lib.core import AsyncFetcher
class SearchAnubis:
def __init__(self, word) -> None:
self.word = word
self.totalhosts: list = []
self.proxy = False
async def do_search(self) -> None:
FILL_FUNC_BODY async def get_hostnames(self) -> list:
return self.totalhost... |
19,751 | /home/hieuvd/dung_repo/raw/stars_01/laramies_theHarvester/theHarvester | /home/hieuvd/dung_repo/raw/stars_01/laramies_theHarvester/theHarvester/theHarvester/discovery/baidusearch.py | 14,15 | 5,33 | do_search | SearchBaidu | 15,22 | 15,22 | class SearchBaidu:
def __init__(self, word, limit) -> None:
self.word = word
self.total_results = ''
self.server = 'www.baidu.com'
self.hostname = 'www.baidu.com'
self.limit = limit
self.proxy = False
async def do_search(self) -> None:
FILL_FUNC_BODY async def... | class SearchBaidu:
def __init__(self, word, limit) -> None:
self.word = word
self.total_results = ''
self.server = 'www.baidu.com'
self.hostname = 'www.baidu.com'
self.limit = limit
self.proxy = False
async def do_search(self) -> None:
FILL_FUNC_BODY async def... | headers = {'Host': self.hostname, 'User-agent': Core.get_user_agent()}
base_url = f'https://{self.server}/s?wd=%40{self.word}&pn=xx&oq={self.word}'
urls = [base_url.replace('xx', str(num)) for num in range(0, self.limit, 10) if num <= self.limit]
responses = await AsyncFetcher.fetch_all(... | headers = {'Host': self.hostname, 'User-agent': Core.get_user_agent()}
base_url = f'https://{self.server}/s?wd=%40{self.word}&pn=xx&oq={self.word}'
urls = [base_url.replace('xx', str(num)) for num in range(0, self.limit, 10) if num <= self.limit]
responses = await AsyncFetcher.fetch_all(... | 36 | 227 | 157 | 384 | from theHarvester.lib.core import AsyncFetcher, Core
from theHarvester.parsers import myparser
class SearchBaidu:
def __init__(self, word, limit) -> None:
self.word = word
self.total_results = ''
self.server = 'www.baidu.com'
self.hostname = 'www.baidu.com'
self.limit = lim... | from theHarvester.lib.core import AsyncFetcher, Core
from theHarvester.parsers import myparser
class SearchBaidu:
def __init__(self, word, limit) -> None:
self.word = word
self.total_results = ''
self.server = 'www.baidu.com'
self.hostname = 'www.baidu.com'
self.limit = lim... |
19,752 | /home/hieuvd/dung_repo/raw/stars_01/laramies_theHarvester/theHarvester | /home/hieuvd/dung_repo/raw/stars_01/laramies_theHarvester/theHarvester/theHarvester/discovery/bevigil.py | 16,17 | 5,40 | do_search | SearchBeVigil | 17,31 | 17,31 | class SearchBeVigil:
def __init__(self, word) -> None:
self.word = word
self.totalhosts: set = set()
self.interestingurls: set = set()
self.key = Core.bevigil_key()
if self.key is None:
self.key = ''
raise MissingKey('bevigil')
self.proxy = Fal... | class SearchBeVigil:
def __init__(self, word) -> None:
self.word = word
self.totalhosts: set = set()
self.interestingurls: set = set()
self.key = Core.bevigil_key()
if self.key is None:
self.key = ''
raise MissingKey('bevigil')
self.proxy = Fal... | subdomain_endpoint = f'https://osint.bevigil.com/api/{self.word}/subdomains/'
url_endpoint = f'https://osint.bevigil.com/api/{self.word}/urls/'
headers = {'X-Access-Token': self.key}
responses = await AsyncFetcher.fetch_all([subdomain_endpoint], json=True, proxy=self.proxy, headers=head... | subdomain_endpoint = f'https://osint.bevigil.com/api/{self.word}/subdomains/'
url_endpoint = f'https://osint.bevigil.com/api/{self.word}/urls/'
headers = {'X-Access-Token': self.key}
responses = await AsyncFetcher.fetch_all([subdomain_endpoint], json=True, proxy=self.proxy, headers=head... | 40 | 214 | 231 | 445 | from theHarvester.discovery.constants import MissingKey
from theHarvester.lib.core import AsyncFetcher, Core
class SearchBeVigil:
def __init__(self, word) -> None:
self.word = word
self.totalhosts: set = set()
self.interestingurls: set = set()
self.key = Core.bevigil_key()
... | from theHarvester.discovery.constants import MissingKey
from theHarvester.lib.core import AsyncFetcher, Core
class SearchBeVigil:
def __init__(self, word) -> None:
self.word = word
self.totalhosts: set = set()
self.interestingurls: set = set()
self.key = Core.bevigil_key()
... |
19,753 | /home/hieuvd/dung_repo/raw/stars_01/laramies_theHarvester/theHarvester | /home/hieuvd/dung_repo/raw/stars_01/laramies_theHarvester/theHarvester/theHarvester/discovery/binaryedgesearch.py | 18,19 | 7,43 | do_search | SearchBinaryEdge | 19,37 | 19,37 | class SearchBinaryEdge:
def __init__(self, word, limit) -> None:
self.word = word
self.totalhosts: set = set()
self.proxy = False
self.key = Core.binaryedge_key()
self.limit = 501 if limit >= 501 else limit
self.limit = 2 if self.limit == 1 else self.limit
if ... | class SearchBinaryEdge:
def __init__(self, word, limit) -> None:
self.word = word
self.totalhosts: set = set()
self.proxy = False
self.key = Core.binaryedge_key()
self.limit = 501 if limit >= 501 else limit
self.limit = 2 if self.limit == 1 else self.limit
if ... | base_url = f'https://api.binaryedge.io/v2/query/domains/subdomain/{self.word}'
headers = {'X-KEY': self.key, 'User-Agent': Core.get_user_agent()}
for page in range(1, self.limit):
params = {'page': page}
response = await AsyncFetcher.fetch_all([base_url], json=True, proxy... | base_url = f'https://api.binaryedge.io/v2/query/domains/subdomain/{self.word}'
headers = {'X-KEY': self.key, 'User-Agent': Core.get_user_agent()}
for page in range(1, self.limit):
params = {'page': page}
response = await AsyncFetcher.fetch_all([base_url], json=True, proxy... | 80 | 197 | 288 | 485 | import asyncio
from theHarvester.discovery.constants import MissingKey, get_delay
from theHarvester.lib.core import AsyncFetcher, Core
class SearchBinaryEdge:
def __init__(self, word, limit) -> None:
self.word = word
self.totalhosts: set = set()
self.proxy = False
self.key = Core.... | import asyncio
from theHarvester.discovery.constants import MissingKey, get_delay
from theHarvester.lib.core import AsyncFetcher, Core
class SearchBinaryEdge:
def __init__(self, word, limit) -> None:
self.word = word
self.totalhosts: set = set()
self.proxy = False
self.key = Core.... |
19,754 | /home/hieuvd/dung_repo/raw/stars_01/laramies_theHarvester/theHarvester | /home/hieuvd/dung_repo/raw/stars_01/laramies_theHarvester/theHarvester/theHarvester/discovery/bingsearch.py | 51,52 | 8,88 | do_search_vhost | SearchBing | 52,64 | 52,64 | class SearchBing:
def __init__(self, word, limit, start) -> None:
self.word = word.replace(' ', '%20')
self.results: list[Any] = []
self.total_results = ''
self.server = 'www.bing.com'
self.apiserver = 'api.search.live.net'
self.hostname = 'www.bing.com'
self.... | class SearchBing:
def __init__(self, word, limit, start) -> None:
self.word = word.replace(' ', '%20')
self.results: list[Any] = []
self.total_results = ''
self.server = 'www.bing.com'
self.apiserver = 'api.search.live.net'
self.hostname = 'www.bing.com'
self.... | headers = {
'Host': self.hostname,
'Cookie': 'mkt=en-US;ui=en-US;SRCHHPGUSR=NEWWND=0&ADLT=DEMOTE&NRSLT=50',
'Accept-Language': 'en-us,en',
'User-agent': Core.get_user_agent(),
}
base_url = f'http://{self.server}/search?q=ip:{self.word}&go=&count=50... | headers = {
'Host': self.hostname,
'Cookie': 'mkt=en-US;ui=en-US;SRCHHPGUSR=NEWWND=0&ADLT=DEMOTE&NRSLT=50',
'Accept-Language': 'en-us,en',
'User-agent': Core.get_user_agent(),
}
base_url = f'http://{self.server}/search?q=ip:{self.word}&go=&count=50... | 42 | 826 | 241 | 1,067 | from typing import Any
from theHarvester.discovery.constants import MissingKey
from theHarvester.lib.core import AsyncFetcher, Core
from theHarvester.parsers import myparser
class SearchBing:
def __init__(self, word, limit, start) -> None:
self.word = word.replace(' ', '%20')
self.results: list[A... | from typing import Any
from theHarvester.discovery.constants import MissingKey
from theHarvester.lib.core import AsyncFetcher, Core
from theHarvester.parsers import myparser
class SearchBing:
def __init__(self, word, limit, start) -> None:
self.word = word.replace(' ', '%20')
self.results: list[A... |
19,755 | /home/hieuvd/dung_repo/raw/stars_01/laramies_theHarvester/theHarvester | /home/hieuvd/dung_repo/raw/stars_01/laramies_theHarvester/theHarvester/theHarvester/discovery/bravesearch.py | 42,43 | 8,53 | get_emails | SearchBrave | 43,46 | 43,46 | class SearchBrave:
def __init__(self, word, limit):
self.word = word
self.results = ''
self.totalresults = ''
self.server = 'https://search.brave.com/search?q='
self.limit = limit
self.proxy = False
async def do_search(self):
headers = {'User-Agent': Core... | class SearchBrave:
def __init__(self, word, limit):
self.word = word
self.results = ''
self.totalresults = ''
self.server = 'https://search.brave.com/search?q='
self.limit = limit
self.proxy = False
async def do_search(self):
headers = {'User-Agent': Core... | rawres = myparser.Parser(self.totalresults, self.word)
return await rawres.emails()
| rawres = myparser.Parser(self.totalresults, self.word)
return await rawres.emails()
| 7 | 516 | 33 | 549 | import asyncio
from theHarvester.discovery.constants import get_delay
from theHarvester.lib.core import AsyncFetcher, Core
from theHarvester.parsers import myparser
class SearchBrave:
def __init__(self, word, limit):
self.word = word
self.results = ''
self.totalresults = ''
self.s... | import asyncio
from theHarvester.discovery.constants import get_delay
from theHarvester.lib.core import AsyncFetcher, Core
from theHarvester.parsers import myparser
class SearchBrave:
def __init__(self, word, limit):
self.word = word
self.results = ''
self.totalresults = ''
self.s... |
19,756 | /home/hieuvd/dung_repo/raw/stars_01/laramies_theHarvester/theHarvester | /home/hieuvd/dung_repo/raw/stars_01/laramies_theHarvester/theHarvester/theHarvester/discovery/bufferoverun.py | 17,18 | 7,47 | do_search | SearchBufferover | 18,38 | 18,38 | class SearchBufferover:
def __init__(self, word) -> None:
self.word = word
self.totalhosts: set = set()
self.totalips: set = set()
self.key = Core.bufferoverun_key()
if self.key is None:
raise MissingKey('bufferoverun')
self.proxy = False
async def do... | class SearchBufferover:
def __init__(self, word) -> None:
self.word = word
self.totalhosts: set = set()
self.totalips: set = set()
self.key = Core.bufferoverun_key()
if self.key is None:
raise MissingKey('bufferoverun')
self.proxy = False
async def do... | url = f'https://tls.bufferover.run/dns?q={self.word}'
response = await AsyncFetcher.fetch_all(
[url],
json=True,
headers={'User-Agent': Core.get_user_agent(), 'x-api-key': f'{self.key}'},
proxy=self.proxy,
)
dct = response[0]
if dct... | url = f'https://tls.bufferover.run/dns?q={self.word}'
response = await AsyncFetcher.fetch_all(
[url],
json=True,
headers={'User-Agent': Core.get_user_agent(), 'x-api-key': f'{self.key}'},
proxy=self.proxy,
)
dct = response[0]
if dct... | 54 | 196 | 285 | 481 | import re
from theHarvester.discovery.constants import MissingKey
from theHarvester.lib.core import AsyncFetcher, Core
class SearchBufferover:
def __init__(self, word) -> None:
self.word = word
self.totalhosts: set = set()
self.totalips: set = set()
self.key = Core.bufferoverun_ke... | import re
from theHarvester.discovery.constants import MissingKey
from theHarvester.lib.core import AsyncFetcher, Core
class SearchBufferover:
def __init__(self, word) -> None:
self.word = word
self.totalhosts: set = set()
self.totalips: set = set()
self.key = Core.bufferoverun_ke... |
19,757 | /home/hieuvd/dung_repo/raw/stars_01/laramies_theHarvester/theHarvester | /home/hieuvd/dung_repo/raw/stars_01/laramies_theHarvester/theHarvester/theHarvester/discovery/censysearch.py | 48,49 | 13,57 | get_hostnames | SearchCensys | 49,51 | 49,51 | class SearchCensys:
def __init__(self, domain, limit: int = 500) -> None:
self.word = domain
self.key = Core.censys_key()
if self.key[0] is None or self.key[1] is None:
raise MissingKey('Censys ID and/or Secret')
self.totalhosts: set = set()
self.emails: set = set... | class SearchCensys:
def __init__(self, domain, limit: int = 500) -> None:
self.word = domain
self.key = Core.censys_key()
if self.key[0] is None or self.key[1] is None:
raise MissingKey('Censys ID and/or Secret')
self.totalhosts: set = set()
self.emails: set = set... | return self.totalhosts
| return self.totalhosts
| 2 | 497 | 11 | 508 | from censys.common import __version__
from censys.common.exceptions import (
CensysRateLimitExceededException,
CensysUnauthorizedException,
)
from censys.search import CensysCerts
from theHarvester.discovery.constants import MissingKey
from theHarvester.lib.core import Core
from theHarvester.lib.version import... | from censys.common import __version__
from censys.common.exceptions import (
CensysRateLimitExceededException,
CensysUnauthorizedException,
)
from censys.search import CensysCerts
from theHarvester.discovery.constants import MissingKey
from theHarvester.lib.core import Core
from theHarvester.lib.version import... |
19,758 | /home/hieuvd/dung_repo/raw/stars_01/laramies_theHarvester/theHarvester | /home/hieuvd/dung_repo/raw/stars_01/laramies_theHarvester/theHarvester/theHarvester/discovery/certspottersearch.py | 10,11 | 4,34 | do_search | SearchCertspoter | 11,27 | 11,27 | class SearchCertspoter:
def __init__(self, word) -> None:
self.word = word
self.totalhosts: set = set()
self.proxy = False
async def do_search(self) -> None:
FILL_FUNC_BODY async def get_hostnames(self) -> set:
return self.totalhosts
async def process(self, proxy: bool =... | class SearchCertspoter:
def __init__(self, word) -> None:
self.word = word
self.totalhosts: set = set()
self.proxy = False
async def do_search(self) -> None:
FILL_FUNC_BODY async def get_hostnames(self) -> set:
return self.totalhosts
async def process(self, proxy: bool =... | base_url = f'https://api.certspotter.com/v1/issuances?domain={self.word}&expand=dns_names'
try:
response = await AsyncFetcher.fetch_all([base_url], json=True, proxy=self.proxy)
response = response[0]
if isinstance(response, list):
for dct in response:
... | base_url = f'https://api.certspotter.com/v1/issuances?domain={self.word}&expand=dns_names'
try:
response = await AsyncFetcher.fetch_all([base_url], json=True, proxy=self.proxy)
response = response[0]
if isinstance(response, list):
for dct in response:
... | 56 | 141 | 232 | 373 | from theHarvester.lib.core import AsyncFetcher
class SearchCertspoter:
def __init__(self, word) -> None:
self.word = word
self.totalhosts: set = set()
self.proxy = False
async def do_search(self) -> None:
FILL_FUNC_BODY async def get_hostnames(self) -> set:
return self.tota... | from theHarvester.lib.core import AsyncFetcher
class SearchCertspoter:
def __init__(self, word) -> None:
self.word = word
self.totalhosts: set = set()
self.proxy = False
async def do_search(self) -> None:
FILL_FUNC_BODY async def get_hostnames(self) -> set:
return self.tota... |
19,759 | /home/hieuvd/dung_repo/raw/stars_01/laramies_theHarvester/theHarvester | /home/hieuvd/dung_repo/raw/stars_01/laramies_theHarvester/theHarvester/theHarvester/discovery/constants.py | 71,72 | 1,124 | google_workaround | 77,111 | 72,111 | import random
from theHarvester.lib.core import AsyncFetcher, Core
async def splitter(links):
"""
Method that tries to remove duplicates
LinkedinLists pulls a lot of profiles with the same name.
This method tries to remove duplicates from the list.
:param links: list of links to remove duplicates... | import random
from theHarvester.lib.core import AsyncFetcher, Core
async def splitter(links):
"""
Method that tries to remove duplicates
LinkedinLists pulls a lot of profiles with the same name.
This method tries to remove duplicates from the list.
:param links: list of links to remove duplicates... | url = 'https://websniffer.cc/'
data = {
'Cookie': '',
'url': visit_url,
'submit': 'Submit',
'type': 'GET&http=1.1',
'uak': str(random.randint(4, 8)), # select random UA to send to Google
}
returned_html = await AsyncFetcher.post_fetch(url, headers={'User-Agent': ... | """
Function that makes a request on our behalf if Google starts to block us
:param visit_url: Url to scrape
:return: Correct html that can be parsed by BS4
"""
url = 'https://websniffer.cc/'
data = {
'Cookie': '',
'url': visit_url,
'submit': 'Submit',
'type':... | 161 | 882 | 485 | 1,367 | import random
from theHarvester.lib.core import AsyncFetcher, Core
async def splitter(links):
"""
Method that tries to remove duplicates
LinkedinLists pulls a lot of profiles with the same name.
This method tries to remove duplicates from the list.
:param links: list of links to remove duplicates... | import random
from theHarvester.lib.core import AsyncFetcher, Core
async def splitter(links):
"""
Method that tries to remove duplicates
LinkedinLists pulls a lot of profiles with the same name.
This method tries to remove duplicates from the list.
:param links: list of links to remove duplicates... | |
19,761 | /home/hieuvd/dung_repo/raw/stars_01/laramies_theHarvester/theHarvester | /home/hieuvd/dung_repo/raw/stars_01/laramies_theHarvester/theHarvester/theHarvester/discovery/crtsh.py | 10,11 | 4,34 | do_search | SearchCrtsh | 11,27 | 11,27 | class SearchCrtsh:
def __init__(self, word) -> None:
self.word = word
self.data: list = []
self.proxy = False
async def do_search(self) -> list:
FILL_FUNC_BODY async def process(self, proxy: bool = False) -> None:
self.proxy = proxy
data = await self.do_search()
... | class SearchCrtsh:
def __init__(self, word) -> None:
self.word = word
self.data: list = []
self.proxy = False
async def do_search(self) -> list:
FILL_FUNC_BODY async def process(self, proxy: bool = False) -> None:
self.proxy = proxy
data = await self.do_search()
... | data: set = set()
try:
url = f'https://crt.sh/?q=%25.{self.word}&output=json'
response = await AsyncFetcher.fetch_all([url], json=True, proxy=self.proxy)
response = response[0]
data = set([dct['name_value'][2:] if '*.' == dct['name_value'][:2] else dct['na... | data: set = set()
try:
url = f'https://crt.sh/?q=%25.{self.word}&output=json'
response = await AsyncFetcher.fetch_all([url], json=True, proxy=self.proxy)
response = response[0]
data = set([dct['name_value'][2:] if '*.' == dct['name_value'][:2] else dct['na... | 68 | 134 | 230 | 364 | from theHarvester.lib.core import AsyncFetcher
class SearchCrtsh:
def __init__(self, word) -> None:
self.word = word
self.data: list = []
self.proxy = False
async def do_search(self) -> list:
FILL_FUNC_BODY async def process(self, proxy: bool = False) -> None:
self.proxy = ... | from theHarvester.lib.core import AsyncFetcher
class SearchCrtsh:
def __init__(self, word) -> None:
self.word = word
self.data: list = []
self.proxy = False
async def do_search(self) -> list:
FILL_FUNC_BODY async def process(self, proxy: bool = False) -> None:
self.proxy = ... |
19,762 | /home/hieuvd/dung_repo/raw/stars_01/laramies_theHarvester/theHarvester | /home/hieuvd/dung_repo/raw/stars_01/laramies_theHarvester/theHarvester/theHarvester/discovery/dnsdumpster.py | 17,18 | 9,63 | do_search | SearchDnsDumpster | 18,56 | 18,56 | class SearchDnsDumpster:
def __init__(self, word) -> None:
self.word = word.replace(' ', '%20')
self.results = ''
self.totalresults = ''
self.server = 'dnsdumpster.com'
self.proxy = False
async def do_search(self) -> None:
FILL_FUNC_BODY async def get_hostnames(self):... | class SearchDnsDumpster:
def __init__(self, word) -> None:
self.word = word.replace(' ', '%20')
self.results = ''
self.totalresults = ''
self.server = 'dnsdumpster.com'
self.proxy = False
async def do_search(self) -> None:
FILL_FUNC_BODY async def get_hostnames(self):... | try:
agent = Core.get_user_agent()
headers = {'User-Agent': agent}
session = aiohttp.ClientSession(headers=headers)
# create a session to properly verify
url = f'https://{self.server}'
csrftoken = ''
if self.proxy is False:
... | try:
agent = Core.get_user_agent()
headers = {'User-Agent': agent}
session = aiohttp.ClientSession(headers=headers)
# create a session to properly verify
url = f'https://{self.server}'
csrftoken = ''
if self.proxy is False:
... | 125 | 183 | 478 | 661 | import asyncio
import aiohttp
from theHarvester.lib.core import Core
from theHarvester.parsers import myparser
class SearchDnsDumpster:
def __init__(self, word) -> None:
self.word = word.replace(' ', '%20')
self.results = ''
self.totalresults = ''
self.server = 'dnsdumpster.com'
... | import asyncio
import aiohttp
from theHarvester.lib.core import Core
from theHarvester.parsers import myparser
class SearchDnsDumpster:
def __init__(self, word) -> None:
self.word = word.replace(' ', '%20')
self.results = ''
self.totalresults = ''
self.server = 'dnsdumpster.com'
... |
19,763 | /home/hieuvd/dung_repo/raw/stars_01/laramies_theHarvester/theHarvester | /home/hieuvd/dung_repo/raw/stars_01/laramies_theHarvester/theHarvester/theHarvester/discovery/dnssearch.py | 199,200 | 1,225 | generate_postprocessing_callback | 217,225 | 200,225 | """
============
DNS Browsing
============
Explore the space around known hosts & ips for extra catches.
"""
import asyncio
import re
import sys
from collections.abc import Callable
from ipaddress import IPv4Network
from aiodns import DNSResolver
from theHarvester.lib import hostchecker
from theHarvester.lib.core i... | """
============
DNS Browsing
============
Explore the space around known hosts & ips for extra catches.
"""
import asyncio
import re
import sys
from collections.abc import Callable
from ipaddress import IPv4Network
from aiodns import DNSResolver
from theHarvester.lib import hostchecker
from theHarvester.lib.core i... |
def append_matching_hosts(host: str) -> None:
if host and target in host:
for __name, __hosts in allhosts.items():
if host not in __hosts:
__hosts.append(host)
return append_matching_hosts
| """
Postprocess the query results asynchronously too, instead of waiting for
the querying stage to be completely finished.
Parameters
----------
target: str.
The domain wanted as TLD.
allhosts: List.
A collection of all the subdomains -of target- found so far.
Returns
... | 24 | 1,891 | 84 | 1,975 | """
============
DNS Browsing
============
Explore the space around known hosts & ips for extra catches.
"""
import asyncio
import re
import sys
from collections.abc import Callable
from ipaddress import IPv4Network
from aiodns import DNSResolver
from theHarvester.lib import hostchecker
from theHarvester.lib.core i... | """
============
DNS Browsing
============
Explore the space around known hosts & ips for extra catches.
"""
import asyncio
import re
import sys
from collections.abc import Callable
from ipaddress import IPv4Network
from aiodns import DNSResolver
from theHarvester.lib import hostchecker
from theHarvester.lib.core i... | |
19,764 | /home/hieuvd/dung_repo/raw/stars_01/laramies_theHarvester/theHarvester | /home/hieuvd/dung_repo/raw/stars_01/laramies_theHarvester/theHarvester/theHarvester/discovery/dnssearch.py | 40,41 | 27,52 | run | DnsForce | 41,52 | 41,52 | class DnsForce:
def __init__(self, domain, dnsserver, verbose: bool = False) -> None:
self.domain = domain
self.subdo = False
self.verbose = verbose
# self.dnsserver = [dnsserver] if isinstance(dnsserver, str) else dnsserver
# self.dnsserver = list(map(str, dnsserver.split(',... | class DnsForce:
def __init__(self, domain, dnsserver, verbose: bool = False) -> None:
self.domain = domain
self.subdo = False
self.verbose = verbose
# self.dnsserver = [dnsserver] if isinstance(dnsserver, str) else dnsserver
# self.dnsserver = list(map(str, dnsserver.split(',... | print(f'Starting DNS brute forcing with {len(self.list)} words')
checker = hostchecker.Checker(self.list, nameserver=self.dnsserver)
resolved_pair, hosts, ips = await checker.check()
return resolved_pair, hosts, ips
#####################################################################
... | print(f'Starting DNS brute forcing with {len(self.list)} words')
checker = hostchecker.Checker(self.list, nameserver=self.dnsserver)
resolved_pair, hosts, ips = await checker.check()
return resolved_pair, hosts, ips
#####################################################################
... | 26 | 223 | 106 | 329 | """
============
DNS Browsing
============
Explore the space around known hosts & ips for extra catches.
"""
import asyncio
import re
import sys
from collections.abc import Callable
from ipaddress import IPv4Network
from aiodns import DNSResolver
from theHarvester.lib import hostchecker
from theHarvester.lib.core i... | """
============
DNS Browsing
============
Explore the space around known hosts & ips for extra catches.
"""
import asyncio
import re
import sys
from collections.abc import Callable
from ipaddress import IPv4Network
from aiodns import DNSResolver
from theHarvester.lib import hostchecker
from theHarvester.lib.core i... |
19,765 | /home/hieuvd/dung_repo/raw/stars_01/laramies_theHarvester/theHarvester | /home/hieuvd/dung_repo/raw/stars_01/laramies_theHarvester/theHarvester/theHarvester/discovery/duckduckgosearch.py | 32,33 | 7,89 | crawl | SearchDuckDuckGo | 38,78 | 33,78 | class SearchDuckDuckGo:
def __init__(self, word, limit) -> None:
self.word = word
self.results = ''
self.totalresults = ''
self.dorks: list = []
self.links: list = []
self.database = 'https://duckduckgo.com/?q='
self.api = 'https://api.duckduckgo.com/?q=x&form... | class SearchDuckDuckGo:
def __init__(self, word, limit) -> None:
self.word = word
self.results = ''
self.totalresults = ''
self.dorks: list = []
self.links: list = []
self.database = 'https://duckduckgo.com/?q='
self.api = 'https://api.duckduckgo.com/?q=x&form... | urls = set()
try:
load = ujson.loads(text)
for keys in load.keys(): # Iterate through keys of dict.
val = load.get(keys)
if isinstance(val, int) or isinstance(val, dict) or val is None:
continue
if isinstance(... | """
Function parses json and returns URLs.
:param text: formatted json
:return: set of URLs
"""
urls = set()
try:
load = ujson.loads(text)
for keys in load.keys(): # Iterate through keys of dict.
val = load.get(keys)
... | 160 | 515 | 442 | 957 | import ujson
from theHarvester.lib.core import AsyncFetcher, Core
from theHarvester.parsers import myparser
class SearchDuckDuckGo:
def __init__(self, word, limit) -> None:
self.word = word
self.results = ''
self.totalresults = ''
self.dorks: list = []
self.links: list = [... | import ujson
from theHarvester.lib.core import AsyncFetcher, Core
from theHarvester.parsers import myparser
class SearchDuckDuckGo:
def __init__(self, word, limit) -> None:
self.word = word
self.results = ''
self.totalresults = ''
self.dorks: list = []
self.links: list = [... |
19,766 | /home/hieuvd/dung_repo/raw/stars_01/laramies_theHarvester/theHarvester | /home/hieuvd/dung_repo/raw/stars_01/laramies_theHarvester/theHarvester/theHarvester/discovery/fullhuntsearch.py | 27,28 | 5,30 | process | SearchFullHunt | 28,30 | 28,30 | class SearchFullHunt:
def __init__(self, word) -> None:
self.word = word
self.key = Core.fullhunt_key()
if self.key is None:
raise MissingKey('fullhunt')
self.total_results = None
self.proxy = False
async def do_search(self) -> None:
url = f'https://f... | class SearchFullHunt:
def __init__(self, word) -> None:
self.word = word
self.key = Core.fullhunt_key()
if self.key is None:
raise MissingKey('fullhunt')
self.total_results = None
self.proxy = False
async def do_search(self) -> None:
url = f'https://f... | self.proxy = proxy
await self.do_search()
| self.proxy = proxy
await self.do_search()
| 5 | 252 | 18 | 270 | from theHarvester.discovery.constants import MissingKey
from theHarvester.lib.core import AsyncFetcher, Core
class SearchFullHunt:
def __init__(self, word) -> None:
self.word = word
self.key = Core.fullhunt_key()
if self.key is None:
raise MissingKey('fullhunt')
self.to... | from theHarvester.discovery.constants import MissingKey
from theHarvester.lib.core import AsyncFetcher, Core
class SearchFullHunt:
def __init__(self, word) -> None:
self.word = word
self.key = Core.fullhunt_key()
if self.key is None:
raise MissingKey('fullhunt')
self.to... |
19,767 | /home/hieuvd/dung_repo/raw/stars_01/laramies_theHarvester/theHarvester | /home/hieuvd/dung_repo/raw/stars_01/laramies_theHarvester/theHarvester/theHarvester/discovery/githubcode.py | 44,46 | 28,140 | fragments_from_response | SearchGithubCode | 46,55 | 46,55 | class SearchGithubCode:
def __init__(self, word, limit) -> None:
self.word = word
self.total_results = ''
self.server = 'api.github.com'
self.limit = limit
self.counter: int = 0
self.page: int | None = 1
self.key = Core.github_key()
# If you don't have... | class SearchGithubCode:
def __init__(self, word, limit) -> None:
self.word = word
self.total_results = ''
self.server = 'api.github.com'
self.limit = limit
self.counter: int = 0
self.page: int | None = 1
self.key = Core.github_key()
# If you don't have... | items: list[dict[str, Any]] = json_data.get('items') or list()
fragments: list[str] = list()
for item in items:
matches = item.get('text_matches') or list()
for match in matches:
fragments.append(match.get('fragment'))
return [fragment for fragmen... | items: list[dict[str, Any]] = json_data.get('items') or list()
fragments: list[str] = list()
for item in items:
matches = item.get('text_matches') or list()
for match in matches:
fragments.append(match.get('fragment'))
return [fragment for fragmen... | 36 | 1,256 | 103 | 1,359 | import asyncio
import random
import urllib.parse as urlparse
from typing import Any, NamedTuple
import aiohttp
from theHarvester.discovery.constants import MissingKey, get_delay
from theHarvester.lib.core import Core
from theHarvester.parsers import myparser
class RetryResult(NamedTuple):
time: float
class Su... | import asyncio
import random
import urllib.parse as urlparse
from typing import Any, NamedTuple
import aiohttp
from theHarvester.discovery.constants import MissingKey, get_delay
from theHarvester.lib.core import Core
from theHarvester.parsers import myparser
class RetryResult(NamedTuple):
time: float
class Su... |
19,768 | /home/hieuvd/dung_repo/raw/stars_01/laramies_theHarvester/theHarvester | /home/hieuvd/dung_repo/raw/stars_01/laramies_theHarvester/theHarvester/theHarvester/discovery/hackertarget.py | 26,27 | 4,32 | process | SearchHackerTarget | 27,30 | 27,30 | class SearchHackerTarget:
"""
Class uses the HackerTarget api to gather subdomains and ips
"""
def __init__(self, word) -> None:
self.word = word
self.total_results = ''
self.hostname = 'https://api.hackertarget.com'
self.proxy = False
self.results = None
as... | class SearchHackerTarget:
"""
Class uses the HackerTarget api to gather subdomains and ips
"""
def __init__(self, word) -> None:
self.word = word
self.total_results = ''
self.hostname = 'https://api.hackertarget.com'
self.proxy = False
self.results = None
as... | self.proxy = proxy
await self.do_search()
| self.proxy = proxy
await self.do_search()
| 5 | 306 | 20 | 326 | from theHarvester.lib.core import AsyncFetcher, Core
class SearchHackerTarget:
"""
Class uses the HackerTarget api to gather subdomains and ips
"""
def __init__(self, word) -> None:
self.word = word
self.total_results = ''
self.hostname = 'https://api.hackertarget.com'
... | from theHarvester.lib.core import AsyncFetcher, Core
class SearchHackerTarget:
"""
Class uses the HackerTarget api to gather subdomains and ips
"""
def __init__(self, word) -> None:
self.word = word
self.total_results = ''
self.hostname = 'https://api.hackertarget.com'
... |
19,769 | /home/hieuvd/dung_repo/raw/stars_01/laramies_theHarvester/theHarvester | /home/hieuvd/dung_repo/raw/stars_01/laramies_theHarvester/theHarvester/theHarvester/discovery/huntersearch.py | 23,24 | 7,90 | do_search | SearchHunter | 24,67 | 24,67 | class SearchHunter:
def __init__(self, word, limit, start) -> None:
self.word = word
self.limit = limit
self.limit = 10 if limit > 10 else limit
self.start = start
self.key = Core.hunter_key()
if self.key is None:
raise MissingKey('Hunter')
self.to... | class SearchHunter:
def __init__(self, word, limit, start) -> None:
self.word = word
self.limit = limit
self.limit = 10 if limit > 10 else limit
self.start = start
self.key = Core.hunter_key()
if self.key is None:
raise MissingKey('Hunter')
self.to... | # First determine if a user account is not a free account, this call is free
is_free = True
headers = {'User-Agent': Core.get_user_agent()}
acc_info_url = f'https://api.hunter.io/v2/account?api_key={self.key}'
response = await AsyncFetcher.fetch_all([acc_info_url], headers=header... | # First determine if a user account is not a free account, this call is free
is_free = True
headers = {'User-Agent': Core.get_user_agent()}
acc_info_url = f'https://api.hunter.io/v2/account?api_key={self.key}'
response = await AsyncFetcher.fetch_all([acc_info_url], headers=header... | 254 | 395 | 843 | 1,238 | import asyncio
from theHarvester.discovery.constants import MissingKey
from theHarvester.lib.core import AsyncFetcher, Core
class SearchHunter:
def __init__(self, word, limit, start) -> None:
self.word = word
self.limit = limit
self.limit = 10 if limit > 10 else limit
self.start =... | import asyncio
from theHarvester.discovery.constants import MissingKey
from theHarvester.lib.core import AsyncFetcher, Core
class SearchHunter:
def __init__(self, word, limit, start) -> None:
self.word = word
self.limit = limit
self.limit = 10 if limit > 10 else limit
self.start =... |
19,770 | /home/hieuvd/dung_repo/raw/stars_01/laramies_theHarvester/theHarvester | /home/hieuvd/dung_repo/raw/stars_01/laramies_theHarvester/theHarvester/theHarvester/discovery/intelxsearch.py | 25,26 | 12,77 | do_search | SearchIntelx | 26,64 | 26,64 | class SearchIntelx:
def __init__(self, word) -> None:
self.word = word
self.key = Core.intelx_key()
if self.key is None:
raise MissingKey('Intelx')
self.database = 'https://2.intelx.io'
self.results: Any = None
self.info: tuple[Any, ...] = ()
self.... | class SearchIntelx:
def __init__(self, word) -> None:
self.word = word
self.key = Core.intelx_key()
if self.key is None:
raise MissingKey('Intelx')
self.database = 'https://2.intelx.io'
self.results: Any = None
self.info: tuple[Any, ...] = ()
self.... | try:
# Based on: https://github.com/IntelligenceX/SDK/blob/master/Python/intelxapi.py
# API requests self identification
# https://intelx.io/integrations
headers = {
'x-key': self.key,
'User-Agent': f'{Core.get_user_agent()}-theHarv... | try:
# Based on: https://github.com/IntelligenceX/SDK/blob/master/Python/intelxapi.py
# API requests self identification
# https://intelx.io/integrations
headers = {
'x-key': self.key,
'User-Agent': f'{Core.get_user_agent()}-theHarv... | 97 | 289 | 438 | 727 | import asyncio
from typing import Any
import requests
import ujson
from theHarvester.discovery.constants import MissingKey
from theHarvester.lib.core import AsyncFetcher, Core
from theHarvester.parsers import intelxparser
class SearchIntelx:
def __init__(self, word) -> None:
self.word = word
sel... | import asyncio
from typing import Any
import requests
import ujson
from theHarvester.discovery.constants import MissingKey
from theHarvester.lib.core import AsyncFetcher, Core
from theHarvester.parsers import intelxparser
class SearchIntelx:
def __init__(self, word) -> None:
self.word = word
sel... |
19,771 | /home/hieuvd/dung_repo/raw/stars_01/laramies_theHarvester/theHarvester | /home/hieuvd/dung_repo/raw/stars_01/laramies_theHarvester/theHarvester/theHarvester/discovery/netlas.py | 15,16 | 5,28 | do_search | SearchNetlas | 16,22 | 16,22 | class SearchNetlas:
def __init__(self, word) -> None:
self.word = word
self.totalhosts: list = []
self.totalips: list = []
self.key = Core.netlas_key()
if self.key is None:
raise MissingKey('netlas')
self.proxy = False
async def do_search(self) -> Non... | class SearchNetlas:
def __init__(self, word) -> None:
self.word = word
self.totalhosts: list = []
self.totalips: list = []
self.key = Core.netlas_key()
if self.key is None:
raise MissingKey('netlas')
self.proxy = False
async def do_search(self) -> Non... | api = f'https://app.netlas.io/api/domains/?q=*.{self.word}&source_type=include&start=0&fields=*'
headers = {'X-API-Key': self.key}
response = await AsyncFetcher.fetch_all([api], json=True, headers=headers, proxy=self.proxy)
for domain in response[0]['items']:
self.totalhosts.... | api = f'https://app.netlas.io/api/domains/?q=*.{self.word}&source_type=include&start=0&fields=*'
headers = {'X-API-Key': self.key}
response = await AsyncFetcher.fetch_all([api], json=True, headers=headers, proxy=self.proxy)
for domain in response[0]['items']:
self.totalhosts.... | 19 | 170 | 125 | 295 | from theHarvester.discovery.constants import MissingKey
from theHarvester.lib.core import AsyncFetcher, Core
class SearchNetlas:
def __init__(self, word) -> None:
self.word = word
self.totalhosts: list = []
self.totalips: list = []
self.key = Core.netlas_key()
if self.key i... | from theHarvester.discovery.constants import MissingKey
from theHarvester.lib.core import AsyncFetcher, Core
class SearchNetlas:
def __init__(self, word) -> None:
self.word = word
self.totalhosts: list = []
self.totalips: list = []
self.key = Core.netlas_key()
if self.key i... |
19,772 | /home/hieuvd/dung_repo/raw/stars_01/laramies_theHarvester/theHarvester | /home/hieuvd/dung_repo/raw/stars_01/laramies_theHarvester/theHarvester/theHarvester/discovery/onyphe.py | 21,22 | 9,98 | do_search | SearchOnyphe | 22,35 | 22,35 | class SearchOnyphe:
def __init__(self, word) -> None:
self.word = word
self.response = ''
self.totalhosts: set = set()
self.totalips: set = set()
self.asns: set = set()
self.key = Core.onyphe_key()
if self.key is None:
raise MissingKey('onyphe')
... | class SearchOnyphe:
def __init__(self, word) -> None:
self.word = word
self.response = ''
self.totalhosts: set = set()
self.totalips: set = set()
self.asns: set = set()
self.key = Core.onyphe_key()
if self.key is None:
raise MissingKey('onyphe')
... | # https://www.onyphe.io/docs/apis/search
# https://www.onyphe.io/search?q=domain%3Acharter.com&captcharesponse=j5cGT
# base_url = f'https://www.onyphe.io/api/v2/search/?q=domain:domain:{self.word}'
base_url = f'https://www.onyphe.io/api/v2/search/?q=domain:{self.word}'
headers = ... | # https://www.onyphe.io/docs/apis/search
# https://www.onyphe.io/search?q=domain%3Acharter.com&captcharesponse=j5cGT
# base_url = f'https://www.onyphe.io/api/v2/search/?q=domain:domain:{self.word}'
base_url = f'https://www.onyphe.io/api/v2/search/?q=domain:{self.word}'
headers = ... | 34 | 877 | 249 | 1,126 | from urllib.parse import urlparse
from theHarvester.discovery.constants import MissingKey
from theHarvester.lib.core import AsyncFetcher, Core
# from theHarvester.parsers import myparser
class SearchOnyphe:
def __init__(self, word) -> None:
self.word = word
self.response = ''
self.totalh... | from urllib.parse import urlparse
from theHarvester.discovery.constants import MissingKey
from theHarvester.lib.core import AsyncFetcher, Core
# from theHarvester.parsers import myparser
class SearchOnyphe:
def __init__(self, word) -> None:
self.word = word
self.response = ''
self.totalh... |
19,773 | /home/hieuvd/dung_repo/raw/stars_01/laramies_theHarvester/theHarvester | /home/hieuvd/dung_repo/raw/stars_01/laramies_theHarvester/theHarvester/theHarvester/discovery/otxsearch.py | 13,14 | 6,33 | do_search | SearchOtx | 14,24 | 14,24 | class SearchOtx:
def __init__(self, word) -> None:
self.word = word
self.totalhosts: set = set()
self.totalips: set = set()
self.proxy = False
async def do_search(self) -> None:
FILL_FUNC_BODY async def get_hostnames(self) -> set:
return self.totalhosts
async def... | class SearchOtx:
def __init__(self, word) -> None:
self.word = word
self.totalhosts: set = set()
self.totalips: set = set()
self.proxy = False
async def do_search(self) -> None:
FILL_FUNC_BODY async def get_hostnames(self) -> set:
return self.totalhosts
async def... | url = f'https://otx.alienvault.com/api/v1/indicators/domain/{self.word}/passive_dns'
response = await AsyncFetcher.fetch_all([url], json=True, proxy=self.proxy)
responses = response[0]
dct = responses
self.totalhosts = {host['hostname'] for host in dct['passive_dns']}
# f... | url = f'https://otx.alienvault.com/api/v1/indicators/domain/{self.word}/passive_dns'
response = await AsyncFetcher.fetch_all([url], json=True, proxy=self.proxy)
responses = response[0]
dct = responses
self.totalhosts = {host['hostname'] for host in dct['passive_dns']}
# f... | 43 | 162 | 203 | 365 | import re
from theHarvester.lib.core import AsyncFetcher
class SearchOtx:
def __init__(self, word) -> None:
self.word = word
self.totalhosts: set = set()
self.totalips: set = set()
self.proxy = False
async def do_search(self) -> None:
FILL_FUNC_BODY async def get_hostnames... | import re
from theHarvester.lib.core import AsyncFetcher
class SearchOtx:
def __init__(self, word) -> None:
self.word = word
self.totalhosts: set = set()
self.totalips: set = set()
self.proxy = False
async def do_search(self) -> None:
FILL_FUNC_BODY async def get_hostnames... |
19,774 | /home/hieuvd/dung_repo/raw/stars_01/laramies_theHarvester/theHarvester | /home/hieuvd/dung_repo/raw/stars_01/laramies_theHarvester/theHarvester/theHarvester/discovery/pentesttools.py | 20,21 | 9,75 | poll | SearchPentestTools | 21,43 | 21,43 | class SearchPentestTools:
def __init__(self, word) -> None:
# Script is largely based off https://pentest-tools.com/public/api_client.py.txt
self.word = word
self.key = Core.pentest_tools_key()
if self.key is None:
raise MissingKey('PentestTools')
self.total_resul... | class SearchPentestTools:
def __init__(self, word) -> None:
# Script is largely based off https://pentest-tools.com/public/api_client.py.txt
self.word = word
self.key = Core.pentest_tools_key()
if self.key is None:
raise MissingKey('PentestTools')
self.total_resul... | while True:
time.sleep(3)
# Get the status of our scan
scan_status_data = {'op': 'get_scan_status', 'scan_id': scan_id}
responses = await AsyncFetcher.post_fetch(url=self.api, data=ujson.dumps(scan_status_data), proxy=self.proxy)
res_json = ujson.loads... | while True:
time.sleep(3)
# Get the status of our scan
scan_status_data = {'op': 'get_scan_status', 'scan_id': scan_id}
responses = await AsyncFetcher.post_fetch(url=self.api, data=ujson.dumps(scan_status_data), proxy=self.proxy)
res_json = ujson.loads... | 69 | 544 | 340 | 884 | import time
import ujson
from theHarvester.discovery.constants import MissingKey
from theHarvester.lib.core import AsyncFetcher, Core
class SearchPentestTools:
def __init__(self, word) -> None:
# Script is largely based off https://pentest-tools.com/public/api_client.py.txt
self.word = word
... | import time
import ujson
from theHarvester.discovery.constants import MissingKey
from theHarvester.lib.core import AsyncFetcher, Core
class SearchPentestTools:
def __init__(self, word) -> None:
# Script is largely based off https://pentest-tools.com/public/api_client.py.txt
self.word = word
... |
19,775 | /home/hieuvd/dung_repo/raw/stars_01/laramies_theHarvester/theHarvester | /home/hieuvd/dung_repo/raw/stars_01/laramies_theHarvester/theHarvester/theHarvester/discovery/projectdiscovery.py | 14,15 | 5,30 | do_search | SearchDiscovery | 15,24 | 15,24 | class SearchDiscovery:
def __init__(self, word) -> None:
self.word = word
self.key = Core.projectdiscovery_key()
if self.key is None:
raise MissingKey('ProjectDiscovery')
self.total_results = None
self.proxy = False
async def do_search(self):
FILL_FUNC_BODY ... | class SearchDiscovery:
def __init__(self, word) -> None:
self.word = word
self.key = Core.projectdiscovery_key()
if self.key is None:
raise MissingKey('ProjectDiscovery')
self.total_results = None
self.proxy = False
async def do_search(self):
FILL_FUNC_BODY ... | url = f'https://dns.projectdiscovery.io/dns/{self.word}/subdomains'
response = await AsyncFetcher.fetch_all(
[url],
json=True,
headers={'User-Agent': Core.get_user_agent(), 'Authorization': self.key},
proxy=self.proxy,
)
self.total_results ... | url = f'https://dns.projectdiscovery.io/dns/{self.word}/subdomains'
response = await AsyncFetcher.fetch_all(
[url],
json=True,
headers={'User-Agent': Core.get_user_agent(), 'Authorization': self.key},
proxy=self.proxy,
)
self.total_results ... | 22 | 152 | 133 | 285 | from theHarvester.discovery.constants import MissingKey
from theHarvester.lib.core import AsyncFetcher, Core
class SearchDiscovery:
def __init__(self, word) -> None:
self.word = word
self.key = Core.projectdiscovery_key()
if self.key is None:
raise MissingKey('ProjectDiscovery'... | from theHarvester.discovery.constants import MissingKey
from theHarvester.lib.core import AsyncFetcher, Core
class SearchDiscovery:
def __init__(self, word) -> None:
self.word = word
self.key = Core.projectdiscovery_key()
if self.key is None:
raise MissingKey('ProjectDiscovery'... |
19,776 | /home/hieuvd/dung_repo/raw/stars_01/laramies_theHarvester/theHarvester | /home/hieuvd/dung_repo/raw/stars_01/laramies_theHarvester/theHarvester/theHarvester/discovery/rapiddns.py | 12,13 | 6,44 | do_search | SearchRapidDns | 13,38 | 13,38 | class SearchRapidDns:
def __init__(self, word) -> None:
self.word = word
self.total_results: list = []
self.proxy = False
async def do_search(self):
FILL_FUNC_BODY async def process(self, proxy: bool = False) -> None:
self.proxy = proxy
await self.do_search()
asy... | class SearchRapidDns:
def __init__(self, word) -> None:
self.word = word
self.total_results: list = []
self.proxy = False
async def do_search(self):
FILL_FUNC_BODY async def process(self, proxy: bool = False) -> None:
self.proxy = proxy
await self.do_search()
asy... | try:
headers = {'User-agent': Core.get_user_agent()}
# TODO see if it's worth adding sameip searches
# f'{self.hostname}/sameip/{self.word}?full=1#result'
urls = [f'https://rapiddns.io/subdomain/{self.word}?full=1#result']
responses = await AsyncFetche... | try:
headers = {'User-agent': Core.get_user_agent()}
# TODO see if it's worth adding sameip searches
# f'{self.hostname}/sameip/{self.word}?full=1#result'
urls = [f'https://rapiddns.io/subdomain/{self.word}?full=1#result']
responses = await AsyncFetche... | 83 | 123 | 381 | 504 | from bs4 import BeautifulSoup
from theHarvester.lib.core import AsyncFetcher, Core
class SearchRapidDns:
def __init__(self, word) -> None:
self.word = word
self.total_results: list = []
self.proxy = False
async def do_search(self):
FILL_FUNC_BODY async def process(self, proxy: boo... | from bs4 import BeautifulSoup
from theHarvester.lib.core import AsyncFetcher, Core
class SearchRapidDns:
def __init__(self, word) -> None:
self.word = word
self.total_results: list = []
self.proxy = False
async def do_search(self):
FILL_FUNC_BODY async def process(self, proxy: boo... |
19,777 | /home/hieuvd/dung_repo/raw/stars_01/laramies_theHarvester/theHarvester | /home/hieuvd/dung_repo/raw/stars_01/laramies_theHarvester/theHarvester/theHarvester/discovery/rocketreach.py | 20,21 | 7,64 | do_search | SearchRocketReach | 21,58 | 21,58 | class SearchRocketReach:
def __init__(self, word, limit) -> None:
self.ips: set = set()
self.word = word
self.key = Core.rocketreach_key()
if self.key is None:
raise MissingKey('RocketReach')
self.hosts: set = set()
self.proxy = False
self.baseurl ... | class SearchRocketReach:
def __init__(self, word, limit) -> None:
self.ips: set = set()
self.word = word
self.key = Core.rocketreach_key()
if self.key is None:
raise MissingKey('RocketReach')
self.hosts: set = set()
self.proxy = False
self.baseurl ... | try:
headers = {
'Api-Key': self.key,
'Content-Type': 'application/json',
'User-Agent': Core.get_user_agent(),
}
next_page = 1 # track pagination
for count in range(1, self.limit):
data = f'{{"query... | try:
headers = {
'Api-Key': self.key,
'Content-Type': 'application/json',
'User-Agent': Core.get_user_agent(),
}
next_page = 1 # track pagination
for count in range(1, self.limit):
data = f'{{"query... | 138 | 212 | 489 | 701 | import asyncio
from theHarvester.discovery.constants import MissingKey, get_delay
from theHarvester.lib.core import AsyncFetcher, Core
class SearchRocketReach:
def __init__(self, word, limit) -> None:
self.ips: set = set()
self.word = word
self.key = Core.rocketreach_key()
if self... | import asyncio
from theHarvester.discovery.constants import MissingKey, get_delay
from theHarvester.lib.core import AsyncFetcher, Core
class SearchRocketReach:
def __init__(self, word, limit) -> None:
self.ips: set = set()
self.word = word
self.key = Core.rocketreach_key()
if self... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.