uid stringlengths 24 24 | split stringclasses 1
value | category stringclasses 2
values | content stringlengths 5 482k | signature stringlengths 1 14k | suffix stringlengths 1 482k | prefix stringlengths 9 14k | prefix_token_count int64 3 5.01k | prefix_token_budget int64 64 256 | element_token_count int64 1 292k | signature_token_count int64 1 5.01k | prefix_context_token_count int64 0 255 | repo stringlengths 7 112 | path stringlengths 4 208 | language stringclasses 1
value | name stringlengths 1 218 | qualname stringlengths 1 218 | start_line int64 1 26.7k | end_line int64 1 26.7k | signature_start_line int64 1 26.7k | signature_end_line int64 1 26.7k | source_hash stringlengths 40 40 | source_dataset stringclasses 1
value | source_split stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
bed7e1f041189c058f434f8e | train | function | def hSAGetAccountInformation(dce, handle, pwszJobName, ccBufferSize = MAX_BUFFER_SIZE):
request = SAGetAccountInformation()
request['Handle'] = handle
request['pwszJobName'] = checkNullString(pwszJobName)
request['ccBufferSize'] = ccBufferSize
for _ in range(ccBufferSize):
request['wszBuffer... | def hSAGetAccountInformation(dce, handle, pwszJobName, ccBufferSize = MAX_BUFFER_SIZE):
| request = SAGetAccountInformation()
request['Handle'] = handle
request['pwszJobName'] = checkNullString(pwszJobName)
request['ccBufferSize'] = ccBufferSize
for _ in range(ccBufferSize):
request['wszBuffer'].append(0)
return dce.request(request)
| handle
request['ccBufferSize'] = ccBufferSize
for _ in range(ccBufferSize):
request['wszBuffer'].append(0)
return dce.request(request)
def hSAGetAccountInformation(dce, handle, pwszJobName, ccBufferSize = MAX_BUFFER_SIZE):
| 64 | 64 | 95 | 24 | 40 | addenial/impacket | impacket/dcerpc/v5/sasec.py | Python | hSAGetAccountInformation | hSAGetAccountInformation | 168 | 175 | 168 | 168 | 23e88b77bdfea383b7c76beb279a67bf3ede66f5 | bigcode/the-stack | train |
b4c05bdee5ee2bc216e13d75 | train | class | class SASetAccountInformationResponse(NDRCALL):
structure = (
('ErrorCode',ULONG),
)
| class SASetAccountInformationResponse(NDRCALL):
| structure = (
('ErrorCode',ULONG),
)
| 0
structure = (
('Handle', PSASEC_HANDLE),
('pwszJobName', WSTR),
('pwszAccount', WSTR),
('pwszPassword', LPWSTR),
('dwJobFlags', DWORD),
)
class SASetAccountInformationResponse(NDRCALL):
| 64 | 64 | 23 | 10 | 54 | addenial/impacket | impacket/dcerpc/v5/sasec.py | Python | SASetAccountInformationResponse | SASetAccountInformationResponse | 73 | 76 | 73 | 73 | b6f68f23c8528b0b8fdad5e5001d131f690b779b | bigcode/the-stack | train |
8457fc01ea86c21724c05fb6 | train | class | class SASetNSAccountInformationResponse(NDRCALL):
structure = (
('ErrorCode',ULONG),
)
| class SASetNSAccountInformationResponse(NDRCALL):
| structure = (
('ErrorCode',ULONG),
)
| 1)
class SASetNSAccountInformation(NDRCALL):
opnum = 1
structure = (
('Handle', PSASEC_HANDLE),
('pwszAccount', LPWSTR),
('pwszPassword', LPWSTR),
)
class SASetNSAccountInformationResponse(NDRCALL):
| 64 | 64 | 24 | 11 | 53 | addenial/impacket | impacket/dcerpc/v5/sasec.py | Python | SASetNSAccountInformationResponse | SASetNSAccountInformationResponse | 87 | 90 | 87 | 87 | 73208fc491338255c4471295580cf8d4aa763d97 | bigcode/the-stack | train |
7d84bf95c92cb72219d3c4e6 | train | class | class SASetNSAccountInformation(NDRCALL):
opnum = 1
structure = (
('Handle', PSASEC_HANDLE),
('pwszAccount', LPWSTR),
('pwszPassword', LPWSTR),
)
| class SASetNSAccountInformation(NDRCALL):
| opnum = 1
structure = (
('Handle', PSASEC_HANDLE),
('pwszAccount', LPWSTR),
('pwszPassword', LPWSTR),
)
| ('dwJobFlags', DWORD),
)
class SASetAccountInformationResponse(NDRCALL):
structure = (
('ErrorCode',ULONG),
)
# 3.2.5.3.5 SASetNSAccountInformation (Opnum 1)
class SASetNSAccountInformation(NDRCALL):
| 64 | 64 | 50 | 10 | 54 | addenial/impacket | impacket/dcerpc/v5/sasec.py | Python | SASetNSAccountInformation | SASetNSAccountInformation | 79 | 85 | 79 | 79 | b1fe150cdcaa8e47a1e8baea226c746cc1155f5d | bigcode/the-stack | train |
951557ab42f41b98cfba25be | train | class | class SASetAccountInformation(NDRCALL):
opnum = 0
structure = (
('Handle', PSASEC_HANDLE),
('pwszJobName', WSTR),
('pwszAccount', WSTR),
('pwszPassword', LPWSTR),
('dwJobFlags', DWORD),
)
| class SASetAccountInformation(NDRCALL):
| opnum = 0
structure = (
('Handle', PSASEC_HANDLE),
('pwszJobName', WSTR),
('pwszAccount', WSTR),
('pwszPassword', LPWSTR),
('dwJobFlags', DWORD),
)
| ################################################################################
# STRUCTURES
################################################################################
class WORD_ARRAY(NDRUniConformantArray):
item = '<H'
################################################################################
# RPC ... | 64 | 64 | 67 | 9 | 55 | addenial/impacket | impacket/dcerpc/v5/sasec.py | Python | SASetAccountInformation | SASetAccountInformation | 63 | 71 | 63 | 63 | 68ed814c7df739ab27b682d9bd2ea8abda3c0e1b | bigcode/the-stack | train |
a38035c0ae706167c954eb42 | train | function | def hSASetAccountInformation(dce, handle, pwszJobName, pwszAccount, pwszPassword, dwJobFlags=0):
request = SASetAccountInformation()
request['Handle'] = handle
request['pwszJobName'] = checkNullString(pwszJobName)
request['pwszAccount'] = checkNullString(pwszAccount)
request['pwszPassword'] = checkN... | def hSASetAccountInformation(dce, handle, pwszJobName, pwszAccount, pwszPassword, dwJobFlags=0):
| request = SASetAccountInformation()
request['Handle'] = handle
request['pwszJobName'] = checkNullString(pwszJobName)
request['pwszAccount'] = checkNullString(pwszAccount)
request['pwszPassword'] = checkNullString(pwszPassword)
request['dwJobFlags'] = dwJobFlags
return dce.request(request)
| string == NULL:
return string
if string[-1:] != '\x00':
return string + '\x00'
else:
return string
def hSASetAccountInformation(dce, handle, pwszJobName, pwszAccount, pwszPassword, dwJobFlags=0):
| 64 | 64 | 112 | 30 | 33 | addenial/impacket | impacket/dcerpc/v5/sasec.py | Python | hSASetAccountInformation | hSASetAccountInformation | 144 | 151 | 144 | 144 | 674b27141c5eadfb3071c3e6e5f7bc8ef8b5bfc7 | bigcode/the-stack | train |
fe8e4abdb7663d8869ce9ce2 | train | function | def hSAGetNSAccountInformation(dce, handle, ccBufferSize = MAX_BUFFER_SIZE):
request = SAGetNSAccountInformation()
request['Handle'] = handle
request['ccBufferSize'] = ccBufferSize
for _ in range(ccBufferSize):
request['wszBuffer'].append(0)
return dce.request(request)
| def hSAGetNSAccountInformation(dce, handle, ccBufferSize = MAX_BUFFER_SIZE):
| request = SAGetNSAccountInformation()
request['Handle'] = handle
request['ccBufferSize'] = ccBufferSize
for _ in range(ccBufferSize):
request['wszBuffer'].append(0)
return dce.request(request)
| request['Handle'] = handle
request['pwszAccount'] = checkNullString(pwszAccount)
request['pwszPassword'] = checkNullString(pwszPassword)
return dce.request(request)
def hSAGetNSAccountInformation(dce, handle, ccBufferSize = MAX_BUFFER_SIZE):
| 64 | 64 | 75 | 20 | 44 | addenial/impacket | impacket/dcerpc/v5/sasec.py | Python | hSAGetNSAccountInformation | hSAGetNSAccountInformation | 160 | 166 | 160 | 160 | 35d4700553711fafadbab2087c6ec2b1125e359f | bigcode/the-stack | train |
906ddfe7f46594f7bb3b33aa | train | class | class SAGetNSAccountInformationResponse(NDRCALL):
structure = (
('wszBuffer',WORD_ARRAY),
('ErrorCode',ULONG),
)
| class SAGetNSAccountInformationResponse(NDRCALL):
| structure = (
('wszBuffer',WORD_ARRAY),
('ErrorCode',ULONG),
)
| Opnum 2)
class SAGetNSAccountInformation(NDRCALL):
opnum = 2
structure = (
('Handle', PSASEC_HANDLE),
('ccBufferSize', DWORD),
('wszBuffer', WORD_ARRAY),
)
class SAGetNSAccountInformationResponse(NDRCALL):
| 64 | 64 | 32 | 11 | 53 | addenial/impacket | impacket/dcerpc/v5/sasec.py | Python | SAGetNSAccountInformationResponse | SAGetNSAccountInformationResponse | 101 | 105 | 101 | 101 | ef11d1e4aba65be6329adf5c9c5f4c58b4b9c603 | bigcode/the-stack | train |
3e289dd878750033481093dc | train | function | def _mix_settings_with_env(settings):
"""Reads CONAN_ENV_XXXX variables from environment
and if it's defined uses these value instead of the default
from conf file. If you specify a compiler with ENV variable you
need to specify all the subsettings, the file defaulted will be
ignored"""
def get... | def _mix_settings_with_env(settings):
| """Reads CONAN_ENV_XXXX variables from environment
and if it's defined uses these value instead of the default
from conf file. If you specify a compiler with ENV variable you
need to specify all the subsettings, the file defaulted will be
ignored"""
def get_env_value(name_):
env_name = ... | if os.path.exists(self.default_profile_path):
remove(self.default_profile_path)
self.initialize_default_profile()
def initialize_settings(self):
if not os.path.exists(self.settings_path):
save(self.settings_path, normalize(get_default_settings_yml()))
def reset_setting... | 85 | 85 | 284 | 8 | 77 | matthiasng/conan | conans/client/cache/cache.py | Python | _mix_settings_with_env | _mix_settings_with_env | 283 | 311 | 283 | 283 | ef29c308d16a025a2d8ee78d43acdce54a02776f | bigcode/the-stack | train |
1e796eee655b3ab7c69f6513 | train | class | class ClientCache(object):
""" Class to represent/store/compute all the paths involved in the execution
of conans commands. Accesses to real disk and reads/write things. (OLD client ConanPaths)
"""
def __init__(self, cache_folder, output):
self.cache_folder = cache_folder
self._output =... | class ClientCache(object):
| """ Class to represent/store/compute all the paths involved in the execution
of conans commands. Accesses to real disk and reads/write things. (OLD client ConanPaths)
"""
def __init__(self, cache_folder, output):
self.cache_folder = cache_folder
self._output = output
# Caching
... | ocks import Lock
CONAN_CONF = 'conan.conf'
CONAN_SETTINGS = "settings.yml"
LOCALDB = ".conan.db"
REMOTES = "remotes.json"
PROFILES_FOLDER = "profiles"
HOOKS_FOLDER = "hooks"
TEMPLATES_FOLDER = "templates"
def is_case_insensitive_os():
system = platform.system()
return system != "Linux" and system != "FreeBSD... | 256 | 256 | 1,676 | 5 | 250 | matthiasng/conan | conans/client/cache/cache.py | Python | ClientCache | ClientCache | 64 | 280 | 64 | 64 | adc216d2805292f1737cf3fad70cb21fa0557b6b | bigcode/the-stack | train |
d5d278dc5a92db008618a7b0 | train | function | def is_case_insensitive_os():
system = platform.system()
return system != "Linux" and system != "FreeBSD" and system != "SunOS"
| def is_case_insensitive_os():
| system = platform.system()
return system != "Linux" and system != "FreeBSD" and system != "SunOS"
| Lock
CONAN_CONF = 'conan.conf'
CONAN_SETTINGS = "settings.yml"
LOCALDB = ".conan.db"
REMOTES = "remotes.json"
PROFILES_FOLDER = "profiles"
HOOKS_FOLDER = "hooks"
TEMPLATES_FOLDER = "templates"
def is_case_insensitive_os():
| 64 | 64 | 34 | 7 | 57 | matthiasng/conan | conans/client/cache/cache.py | Python | is_case_insensitive_os | is_case_insensitive_os | 37 | 39 | 37 | 37 | 04863dc143e86ce604c59f868958c917bf0b8ec9 | bigcode/the-stack | train |
d28bff7e1768023e45241bba | train | function | def process_gpu(cntr):
# GPUs may not have been assigned to a pod
gpu = 0
gpuvendor = 'nvidia'
try:
gpu = cntr["resources"]["limits"]["nvidia.com/gpu"]
except KeyError:
try:
gpu = cntr["resources"]["limits"]["amd.com/gpu"]
gpuvendor = 'amd'
excep... | def process_gpu(cntr):
# GPUs may not have been assigned to a pod
| gpu = 0
gpuvendor = 'nvidia'
try:
gpu = cntr["resources"]["limits"]["nvidia.com/gpu"]
except KeyError:
try:
gpu = cntr["resources"]["limits"]["amd.com/gpu"]
gpuvendor = 'amd'
except KeyError:
gpu = 0
gpuvendor = ''
return gpu, ... | .metadata.namespace,
"size": rsrc.spec.resources.requests["storage"],
"mode": rsrc.spec.access_modes[0],
"class": rsrc.spec.storage_class_name,
}
return res
def process_gpu(cntr):
# GPUs may not have been assigned to a pod
| 64 | 64 | 106 | 20 | 43 | StefanoFioravanzo/kubeflow | components/jupyter-web-app/backend/kubeflow_jupyter/common/utils.py | Python | process_gpu | process_gpu | 262 | 277 | 262 | 264 | 872cd3b93993d56c1b91a1a83147e54259cd9635 | bigcode/the-stack | train |
114527e905d813b688f503c3 | train | function | def get_data_vols(body, defaults):
"""
Checks the config and the form values and returns a list of Volume
Dictionaries for the Notebook's Data Volumes. If the Data Volumes are
readOnly, then the value from the config will be used instead. The Volume
Dict has the same format as the Volume interface o... | def get_data_vols(body, defaults):
| """
Checks the config and the form values and returns a list of Volume
Dictionaries for the Notebook's Data Volumes. If the Data Volumes are
readOnly, then the value from the config will be used instead. The Volume
Dict has the same format as the Volume interface of the frontend.
"""
default... | (ws))
elif form_ws is not None:
ws = form_ws
logger.info("Using form's Workspace Volume: {}".format(ws))
else:
ws = default_ws
logger.info("Using the default Workspace Volume: {}".format(ws))
return ws
def get_data_vols(body, defaults):
| 66 | 66 | 220 | 9 | 56 | StefanoFioravanzo/kubeflow | components/jupyter-web-app/backend/kubeflow_jupyter/common/utils.py | Python | get_data_vols | get_data_vols | 223 | 246 | 223 | 223 | a67384e6b97fe7d0c2e10b5659627e6e5ec9c986 | bigcode/the-stack | train |
7e1bd64daf9636603761ed17 | train | function | def process_resource(rsrc, rsrc_events):
# VAR: change this function according to the main resource
cntr = rsrc["spec"]["template"]["spec"]["containers"][0]
status, reason = process_status(rsrc, rsrc_events)
gpu, gpuvendor = process_gpu(cntr)
res = {
"name": rsrc["metadata"]["name"],
... | def process_resource(rsrc, rsrc_events):
# VAR: change this function according to the main resource
| cntr = rsrc["spec"]["template"]["spec"]["containers"][0]
status, reason = process_status(rsrc, rsrc_events)
gpu, gpuvendor = process_gpu(cntr)
res = {
"name": rsrc["metadata"]["name"],
"namespace": rsrc["metadata"]["namespace"],
"age": get_uptime(rsrc["metadata"]["creationTim... | tr["resources"]["limits"]["amd.com/gpu"]
gpuvendor = 'amd'
except KeyError:
gpu = 0
gpuvendor = ''
return gpu, gpuvendor
def process_resource(rsrc, rsrc_events):
# VAR: change this function according to the main resource
| 64 | 64 | 210 | 23 | 40 | StefanoFioravanzo/kubeflow | components/jupyter-web-app/backend/kubeflow_jupyter/common/utils.py | Python | process_resource | process_resource | 280 | 300 | 280 | 281 | 339c0f8cea7d332c23e1b522329b72f20f400e7a | bigcode/the-stack | train |
7fbe126e86403e2f59366104 | train | function | def set_notebook_shm(notebook, body, defaults):
if defaults["shm"].get("readOnly", False):
if not defaults["shm"]["value"]:
return
elif "shm" in body:
if not body["shm"]:
return
else:
if not defaults["shm"]["value"]:
return
notebook_spec = not... | def set_notebook_shm(notebook, body, defaults):
| if defaults["shm"].get("readOnly", False):
if not defaults["shm"]["value"]:
return
elif "shm" in body:
if not body["shm"]:
return
else:
if not defaults["shm"]["value"]:
return
notebook_spec = notebook["spec"]["template"]["spec"]
notebook_c... | extra = json.loads(resources_str)
except Exception as e:
r["success"] = False
r["log"] = api.parse_error(e)
return r
container["resources"]["limits"] = extra
return r
def set_notebook_shm(notebook, body, defaults):
| 64 | 64 | 175 | 13 | 50 | StefanoFioravanzo/kubeflow | components/jupyter-web-app/backend/kubeflow_jupyter/common/utils.py | Python | set_notebook_shm | set_notebook_shm | 514 | 531 | 514 | 514 | 7c73d6f60af03d47533f8d546b0befb8c81c4fc5 | bigcode/the-stack | train |
9407208d29d53b78026d4f33 | train | function | def spawner_ui_config():
for config in CONFIGS:
c = None
try:
with open(config, "r") as f:
c = f.read()
except IOError:
logger.warning("Config file '{}' is not found".format(config))
continue
try:
if yaml.safe_load(c) i... | def spawner_ui_config():
| for config in CONFIGS:
c = None
try:
with open(config, "r") as f:
c = f.read()
except IOError:
logger.warning("Config file '{}' is not found".format(config))
continue
try:
if yaml.safe_load(c) is None:
#... | is None:
# YAML exists but is empty
return {}
else:
# YAML exists and is not empty
return yaml.safe_load(c)
except yaml.YAMLError as e:
logger.warning("Couldn't load yaml: {}".format(e))
return None
def spawner_ui_config():
| 64 | 64 | 182 | 6 | 57 | StefanoFioravanzo/kubeflow | components/jupyter-web-app/backend/kubeflow_jupyter/common/utils.py | Python | spawner_ui_config | spawner_ui_config | 88 | 115 | 88 | 88 | 6ce6870c9c319ec582b4ba9f1d14fee891d910d6 | bigcode/the-stack | train |
1ad2a153c2f66ef551a10181 | train | function | def create_logger(name):
handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(
logging.Formatter(
"%(asctime)s | %(name)s | %(levelname)s | %(message)s"
)
)
logger = logging.getLogger(name)
logger.setLevel(logging.INFO)
logger.addHandler(handler)
retur... | def create_logger(name):
| handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(
logging.Formatter(
"%(asctime)s | %(name)s | %(levelname)s | %(message)s"
)
)
logger = logging.getLogger(name)
logger.setLevel(logging.INFO)
logger.addHandler(handler)
return logger
| ")
USER_PREFIX = os.getenv("USERID_PREFIX", "accounts.google.com:")
EVENT_TYPE_NORMAL = "Normal"
EVENT_TYPE_WARNING = "Warning"
STATUS_ERROR = "error"
STATUS_WARNING = "warning"
STATUS_RUNNING = "running"
STATUS_WAITING = "waiting"
# Logging
def create_logger(name):
| 64 | 64 | 73 | 5 | 58 | StefanoFioravanzo/kubeflow | components/jupyter-web-app/backend/kubeflow_jupyter/common/utils.py | Python | create_logger | create_logger | 34 | 44 | 34 | 34 | 314972b5a96bcbf7e5228e1c01ea8708a446687f | bigcode/the-stack | train |
65c66a802ac3e77d7e31596a | train | function | def set_notebook_image(notebook, body, defaults):
"""
If the image is set to readOnly, use only the value from the config
"""
if defaults["image"].get("readOnly", False):
image = defaults["image"]["value"]
logger.info("Using default Image: " + image)
elif body.get("customImageCheck",... | def set_notebook_image(notebook, body, defaults):
| """
If the image is set to readOnly, use only the value from the config
"""
if defaults["image"].get("readOnly", False):
image = defaults["image"]["value"]
logger.info("Using default Image: " + image)
elif body.get("customImageCheck", False):
image = body["customImage"]
... | event_timestamp, reverse=True):
if e.type == EVENT_TYPE_WARNING:
return STATUS_WAITING, e.message
return None, None
def event_timestamp(event):
return event.metadata.creation_timestamp.replace(tzinfo=None)
# Notebook YAML processing
def set_notebook_image(notebook, body, defaults):
| 64 | 64 | 171 | 12 | 51 | StefanoFioravanzo/kubeflow | components/jupyter-web-app/backend/kubeflow_jupyter/common/utils.py | Python | set_notebook_image | set_notebook_image | 359 | 376 | 359 | 359 | ec8dc16b4bc532336e875372c5a76a591314028f | bigcode/the-stack | train |
47774b91417bdbfeff131972 | train | function | def volume_from_config(config_vol, notebook):
"""
Create a Volume Dict from the config.yaml. This dict has the same fields as
a Volume returned from the frontend
"""
vol_name = config_vol["name"]["value"].replace(
"{notebook-name}", notebook["name"]
)
vol_class = handle_storage_class... | def volume_from_config(config_vol, notebook):
| """
Create a Volume Dict from the config.yaml. This dict has the same fields as
a Volume returned from the frontend
"""
vol_name = config_vol["name"]["value"].replace(
"{notebook-name}", notebook["name"]
)
vol_class = handle_storage_class(config_vol["class"]["value"])
return {
... | "class" not in vol:
return None
if vol["class"] == "{empty}":
return ""
if vol["class"] == "{none}":
return None
else:
return vol["class"]
# Volume handling functions
def volume_from_config(config_vol, notebook):
| 64 | 64 | 155 | 9 | 54 | StefanoFioravanzo/kubeflow | components/jupyter-web-app/backend/kubeflow_jupyter/common/utils.py | Python | volume_from_config | volume_from_config | 163 | 181 | 163 | 163 | 5d5102d53309db249acec71b20b84f4a1aec9619 | bigcode/the-stack | train |
d87fa911d12a6711ac7df635 | train | function | def set_notebook_gpus(notebook, body, defaults):
gpus = None
gpuDefaults = defaults.get("gpus", {})
if gpuDefaults.get("readOnly", False):
# The server should not allow the user to set the GPUs
# if the config's value is readOnly. Use the config's value
gpus = gpuDefaults["value"]
... | def set_notebook_gpus(notebook, body, defaults):
| gpus = None
gpuDefaults = defaults.get("gpus", {})
if gpuDefaults.get("readOnly", False):
# The server should not allow the user to set the GPUs
# if the config's value is readOnly. Use the config's value
gpus = gpuDefaults["value"]
logger.info(f"Using default GPU config: {gp... | body, defaults):
container = notebook["spec"]["template"]["spec"]["containers"][0]
if defaults["memory"].get("readOnly", False):
memory = defaults["memory"]["value"]
logger.info("Using default Memory: " + memory)
elif body.get("memory", ""):
memory = body["memory"]
logger.i... | 131 | 131 | 438 | 13 | 117 | StefanoFioravanzo/kubeflow | components/jupyter-web-app/backend/kubeflow_jupyter/common/utils.py | Python | set_notebook_gpus | set_notebook_gpus | 411 | 463 | 411 | 411 | da5d3e57788364ab5f2529c485e2f2ac709bf617 | bigcode/the-stack | train |
d949d6f87caa6a5f4e993ad8 | train | function | def set_notebook_configurations(notebook, body, defaults):
notebook_labels = notebook["metadata"]["labels"]
if defaults["configurations"].get("readOnly", False):
labels = defaults["configurations"]["value"]
logger.info("Using default Configurations: {}".format(labels))
elif body.get("config... | def set_notebook_configurations(notebook, body, defaults):
| notebook_labels = notebook["metadata"]["labels"]
if defaults["configurations"].get("readOnly", False):
labels = defaults["configurations"]["value"]
logger.info("Using default Configurations: {}".format(labels))
elif body.get("configurations", None) is not None:
labels = body["config... | containers"][0]
vendor = gpus["vendor"]
num = int(gpus["num"])
limits = container["resources"].get("limits", {})
limits[vendor] = num
container["resources"]["limits"] = limits
def set_notebook_configurations(notebook, body, defaults):
| 64 | 64 | 168 | 13 | 50 | StefanoFioravanzo/kubeflow | components/jupyter-web-app/backend/kubeflow_jupyter/common/utils.py | Python | set_notebook_configurations | set_notebook_configurations | 466 | 486 | 466 | 466 | 046efad9e43f8008a0c05ae815fe443d70a0e79c | bigcode/the-stack | train |
e160f3e05c580451001dc1d7 | train | function | def set_notebook_memory(notebook, body, defaults):
container = notebook["spec"]["template"]["spec"]["containers"][0]
if defaults["memory"].get("readOnly", False):
memory = defaults["memory"]["value"]
logger.info("Using default Memory: " + memory)
elif body.get("memory", ""):
memory ... | def set_notebook_memory(notebook, body, defaults):
| container = notebook["spec"]["template"]["spec"]["containers"][0]
if defaults["memory"].get("readOnly", False):
memory = defaults["memory"]["value"]
logger.info("Using default Memory: " + memory)
elif body.get("memory", ""):
memory = body["memory"]
logger.info("Using form's ... | ["cpu"]
logger.info("Using form's CPU: " + cpu)
else:
cpu = defaults["cpu"]["value"]
logger.info("Using default CPU: " + cpu)
container["resources"]["requests"]["cpu"] = cpu
def set_notebook_memory(notebook, body, defaults):
| 64 | 64 | 126 | 12 | 51 | StefanoFioravanzo/kubeflow | components/jupyter-web-app/backend/kubeflow_jupyter/common/utils.py | Python | set_notebook_memory | set_notebook_memory | 395 | 408 | 395 | 395 | a94b992f2619c5181f866ba51773fd22c8c503e1 | bigcode/the-stack | train |
fa6c72f5f54e633de7342f2d | train | function | def event_timestamp(event):
return event.metadata.creation_timestamp.replace(tzinfo=None)
| def event_timestamp(event):
| return event.metadata.creation_timestamp.replace(tzinfo=None)
| 1 nodes are available: 1 Insufficient cpu (originated in pod)
'''
for e in sorted(rsrc_events, key=event_timestamp, reverse=True):
if e.type == EVENT_TYPE_WARNING:
return STATUS_WAITING, e.message
return None, None
def event_timestamp(event):
| 64 | 64 | 17 | 5 | 58 | StefanoFioravanzo/kubeflow | components/jupyter-web-app/backend/kubeflow_jupyter/common/utils.py | Python | event_timestamp | event_timestamp | 354 | 355 | 354 | 354 | b0acf31ebd2b218daee90660c9a12501680e10a6 | bigcode/the-stack | train |
b5b71905b8d58f3fd66546e8 | train | function | def add_notebook_volume_secret(nb, secret, secret_name, mnt_path, mode):
# Create the volume in the Pod
spec = nb["spec"]["template"]["spec"]
container = nb["spec"]["template"]["spec"]["containers"][0]
volume = {
"name": secret,
"secret": {"defaultMode": mode, "secretName": secret_name,... | def add_notebook_volume_secret(nb, secret, secret_name, mnt_path, mode):
# Create the volume in the Pod
| spec = nb["spec"]["template"]["spec"]
container = nb["spec"]["template"]["spec"]["containers"][0]
volume = {
"name": secret,
"secret": {"defaultMode": mode, "secretName": secret_name, },
}
spec["volumes"].append(volume)
# Container volumeMounts
mnt = {
"mountPath": ... | )
# Container Mounts
mnt = {"mountPath": mnt_path, "name": vol_name}
container["volumeMounts"].append(mnt)
def add_notebook_volume_secret(nb, secret, secret_name, mnt_path, mode):
# Create the volume in the Pod
| 64 | 64 | 133 | 28 | 36 | StefanoFioravanzo/kubeflow | components/jupyter-web-app/backend/kubeflow_jupyter/common/utils.py | Python | add_notebook_volume_secret | add_notebook_volume_secret | 546 | 562 | 546 | 547 | d687693d55ddac7b4138276431396a8b0c1d10a1 | bigcode/the-stack | train |
099961842d54f4d90010683d | train | function | def get_username_from_request():
if USER_HEADER not in request.headers:
logger.debug("User header not present!")
username = None
else:
user = request.headers[USER_HEADER]
username = user.replace(USER_PREFIX, "")
logger.debug(
"User: '{}' | Headers: '{}' '{}'".... | def get_username_from_request():
| if USER_HEADER not in request.headers:
logger.debug("User header not present!")
username = None
else:
user = request.headers[USER_HEADER]
username = user.replace(USER_PREFIX, "")
logger.debug(
"User: '{}' | Headers: '{}' '{}'".format(
username,... | "%(asctime)s | %(name)s | %(levelname)s | %(message)s"
)
)
logger = logging.getLogger(name)
logger.setLevel(logging.INFO)
logger.addHandler(handler)
return logger
logger = create_logger(__name__)
# Utils
def get_username_from_request():
| 64 | 64 | 84 | 6 | 57 | StefanoFioravanzo/kubeflow | components/jupyter-web-app/backend/kubeflow_jupyter/common/utils.py | Python | get_username_from_request | get_username_from_request | 51 | 64 | 51 | 51 | 9b383ecccb45445dfdd87b3c9e9b34e7e7240c00 | bigcode/the-stack | train |
12b820e36e5599d849ca8c72 | train | function | def get_workspace_vol(body, defaults):
"""
Checks the config and the form values and returns a Volume Dict for the
workspace. If the workspace is readOnly, then the value from the config
will be used instead. The Volume Dict has the same format as the Volume
interface of the frontend.
"""
de... | def get_workspace_vol(body, defaults):
| """
Checks the config and the form values and returns a Volume Dict for the
workspace. If the workspace is readOnly, then the value from the config
will be used instead. The Volume Dict has the same format as the Volume
interface of the frontend.
"""
default_ws = volume_from_config(defaults[... | =namespace,),
spec=client.V1PersistentVolumeClaimSpec(
access_modes=[vol["mode"]],
storage_class_name=handle_storage_class(vol),
resources=client.V1ResourceRequirements(
requests={"storage": vol["size"]}
),
),
)
def get_workspace_vol(bo... | 64 | 64 | 185 | 8 | 56 | StefanoFioravanzo/kubeflow | components/jupyter-web-app/backend/kubeflow_jupyter/common/utils.py | Python | get_workspace_vol | get_workspace_vol | 200 | 220 | 200 | 200 | 28a03659a43c30b749bcfa7a6f62cd2057ce7157 | bigcode/the-stack | train |
67d4d5d588d036b5f392a181 | train | function | def handle_storage_class(vol):
# handle the StorageClass
if "class" not in vol:
return None
if vol["class"] == "{empty}":
return ""
if vol["class"] == "{none}":
return None
else:
return vol["class"]
| def handle_storage_class(vol):
# handle the StorageClass
| if "class" not in vol:
return None
if vol["class"] == "{empty}":
return ""
if vol["class"] == "{none}":
return None
else:
return vol["class"]
| if mins == 0:
return "just now"
if mins == 1:
age = str(mins) + " min"
else:
age = str(mins) + " mins"
return age + " ago"
def handle_storage_class(vol):
# handle the StorageClass
| 64 | 64 | 64 | 13 | 51 | StefanoFioravanzo/kubeflow | components/jupyter-web-app/backend/kubeflow_jupyter/common/utils.py | Python | handle_storage_class | handle_storage_class | 150 | 159 | 150 | 151 | 202a87298a837b9555f9f612f64820f64ce1355e | bigcode/the-stack | train |
9c19dfd84946a6dad5d5e886 | train | function | def get_uptime(then):
now = dt.datetime.now()
then = dt.datetime.strptime(then, "%Y-%m-%dT%H:%M:%SZ")
diff = now - then.replace(tzinfo=None)
days = diff.days
hours = int(diff.seconds / 3600)
mins = int((diff.seconds % 3600) / 60)
age = ""
if days > 0:
if days == 1:
... | def get_uptime(then):
| now = dt.datetime.now()
then = dt.datetime.strptime(then, "%Y-%m-%dT%H:%M:%SZ")
diff = now - then.replace(tzinfo=None)
days = diff.days
hours = int(diff.seconds / 3600)
mins = int((diff.seconds % 3600) / 60)
age = ""
if days > 0:
if days == 1:
age = str(days) + " da... | :
logger.error("Notebook config is not a valid yaml")
return {}
except AttributeError as e:
logger.error(
"Can't load the config at {}: {}".format(config, str(e))
)
logger.warning("Couldn't load any config")
return {}
def get_uptime(then):... | 64 | 65 | 218 | 7 | 57 | StefanoFioravanzo/kubeflow | components/jupyter-web-app/backend/kubeflow_jupyter/common/utils.py | Python | get_uptime | get_uptime | 118 | 147 | 118 | 118 | 525652d41cb44c823d207fca8828566e7a9d2874 | bigcode/the-stack | train |
8ad82f7b60ac71ed2ab0c9bd | train | function | def set_notebook_cpu(notebook, body, defaults):
container = notebook["spec"]["template"]["spec"]["containers"][0]
if defaults["cpu"].get("readOnly", False):
cpu = defaults["cpu"]["value"]
logger.info("Using default CPU: " + cpu)
elif body.get("cpu", ""):
cpu = body["cpu"]
lo... | def set_notebook_cpu(notebook, body, defaults):
| container = notebook["spec"]["template"]["spec"]["containers"][0]
if defaults["cpu"].get("readOnly", False):
cpu = defaults["cpu"]["value"]
logger.info("Using default CPU: " + cpu)
elif body.get("cpu", ""):
cpu = body["cpu"]
logger.info("Using form's CPU: " + cpu)
else:
... | ("Using form's Image: " + image)
else:
image = defaults["image"]["value"]
logger.info("Using default Image: " + image)
notebook["spec"]["template"]["spec"]["containers"][0]["image"] = image
def set_notebook_cpu(notebook, body, defaults):
| 64 | 64 | 126 | 12 | 51 | StefanoFioravanzo/kubeflow | components/jupyter-web-app/backend/kubeflow_jupyter/common/utils.py | Python | set_notebook_cpu | set_notebook_cpu | 379 | 392 | 379 | 379 | 26d34b065acb1bffdb8792d3627ae40222e54755 | bigcode/the-stack | train |
b4fa3bc197f63b7e1844b774 | train | function | def add_notebook_volume(notebook, vol_name, claim, mnt_path):
spec = notebook["spec"]["template"]["spec"]
container = notebook["spec"]["template"]["spec"]["containers"][0]
volume = {"name": vol_name, "persistentVolumeClaim": {"claimName": claim}}
spec["volumes"].append(volume)
# Container Mounts
... | def add_notebook_volume(notebook, vol_name, claim, mnt_path):
| spec = notebook["spec"]["template"]["spec"]
container = notebook["spec"]["template"]["spec"]["containers"][0]
volume = {"name": vol_name, "persistentVolumeClaim": {"claimName": claim}}
spec["volumes"].append(volume)
# Container Mounts
mnt = {"mountPath": mnt_path, "name": vol_name}
contain... | notebook_spec["volumes"].append(shm_volume)
shm_mnt = {"mountPath": "/dev/shm", "name": "dshm"}
notebook_cont["volumeMounts"].append(shm_mnt)
def add_notebook_volume(notebook, vol_name, claim, mnt_path):
| 64 | 64 | 107 | 17 | 47 | StefanoFioravanzo/kubeflow | components/jupyter-web-app/backend/kubeflow_jupyter/common/utils.py | Python | add_notebook_volume | add_notebook_volume | 534 | 543 | 534 | 534 | 910b8f5538ef46593d6fc36532ec6a02c2ac1cbd | bigcode/the-stack | train |
f1a16a48941c37a74b0b14d3 | train | function | def process_pvc(rsrc):
# VAR: change this function according to the main resource
res = {
"name": rsrc.metadata.name,
"namespace": rsrc.metadata.namespace,
"size": rsrc.spec.resources.requests["storage"],
"mode": rsrc.spec.access_modes[0],
"class": rsrc.spec.storage_class... | def process_pvc(rsrc):
# VAR: change this function according to the main resource
| res = {
"name": rsrc.metadata.name,
"namespace": rsrc.metadata.namespace,
"size": rsrc.spec.resources.requests["storage"],
"mode": rsrc.spec.access_modes[0],
"class": rsrc.spec.storage_class_name,
}
return res
| s))
else:
vols = default_vols
logger.info("Using the default Data Volumes: {}".format(vols))
return vols
# Functions for transforming the data from k8s api
def process_pvc(rsrc):
# VAR: change this function according to the main resource
| 64 | 64 | 83 | 20 | 43 | StefanoFioravanzo/kubeflow | components/jupyter-web-app/backend/kubeflow_jupyter/common/utils.py | Python | process_pvc | process_pvc | 250 | 259 | 250 | 251 | 8821054f5d0d277a4063eee71895a3b557b14339 | bigcode/the-stack | train |
1fb75c7f7e6ad057fcf579d1 | train | function | def pvc_from_dict(vol, namespace):
if vol is None:
return None
return client.V1PersistentVolumeClaim(
metadata=client.V1ObjectMeta(name=vol["name"], namespace=namespace,),
spec=client.V1PersistentVolumeClaimSpec(
access_modes=[vol["mode"]],
storage_class_name=han... | def pvc_from_dict(vol, namespace):
| if vol is None:
return None
return client.V1PersistentVolumeClaim(
metadata=client.V1ObjectMeta(name=vol["name"], namespace=namespace,),
spec=client.V1PersistentVolumeClaimSpec(
access_modes=[vol["mode"]],
storage_class_name=handle_storage_class(vol),
... | "size": config_vol["size"]["value"],
"mode": config_vol["accessModes"]["value"],
"path": config_vol["mountPath"]["value"],
"class": vol_class,
"extraFields": config_vol.get("extra", {}),
}
def pvc_from_dict(vol, namespace):
| 64 | 64 | 98 | 8 | 56 | StefanoFioravanzo/kubeflow | components/jupyter-web-app/backend/kubeflow_jupyter/common/utils.py | Python | pvc_from_dict | pvc_from_dict | 184 | 197 | 184 | 184 | 43bc5ca672a9c08644ec9f9938e516610907c0c7 | bigcode/the-stack | train |
4d3d063be0c6a8e6276211da | train | function | def set_notebook_extra_resources(notebook, body, defaults):
r = {"success": True, "log": ""}
container = notebook["spec"]["template"]["spec"]["containers"][0]
if defaults["extraResources"].get("readOnly", False):
resources_str = defaults["extraResources"]["value"]
logger.info("Using the def... | def set_notebook_extra_resources(notebook, body, defaults):
| r = {"success": True, "log": ""}
container = notebook["spec"]["template"]["spec"]["containers"][0]
if defaults["extraResources"].get("readOnly", False):
resources_str = defaults["extraResources"]["value"]
logger.info("Using the default Extra Resources: " + resources_str)
elif body.get("... | : {}".format(labels))
if not isinstance(labels, list):
logger.warning(
"Labels for PodDefaults are not list: {}".format(labels)
)
return
for l in labels:
notebook_labels[l] = "true"
def set_notebook_extra_resources(notebook, body, defaults):
| 64 | 64 | 196 | 13 | 51 | StefanoFioravanzo/kubeflow | components/jupyter-web-app/backend/kubeflow_jupyter/common/utils.py | Python | set_notebook_extra_resources | set_notebook_extra_resources | 489 | 511 | 489 | 489 | 2b3917ed242a4896c20fbd6cfe1cc71d075920c1 | bigcode/the-stack | train |
8b7d00b3add34655720b6a6e | train | function | def load_param_yaml(f, **kwargs):
c = None
try:
with open(f, "r") as f:
c = f.read().format(**kwargs)
except IOError:
logger.info("Error opening: {}".format(f))
return None
try:
if yaml.safe_load(c) is None:
# YAML exists but is empty
... | def load_param_yaml(f, **kwargs):
| c = None
try:
with open(f, "r") as f:
c = f.read().format(**kwargs)
except IOError:
logger.info("Error opening: {}".format(f))
return None
try:
if yaml.safe_load(c) is None:
# YAML exists but is empty
return {}
else:
... | else:
user = request.headers[USER_HEADER]
username = user.replace(USER_PREFIX, "")
logger.debug(
"User: '{}' | Headers: '{}' '{}'".format(
username, USER_HEADER, USER_PREFIX
)
)
return username
def load_param_yaml(f, **kwargs):
| 64 | 64 | 125 | 9 | 54 | StefanoFioravanzo/kubeflow | components/jupyter-web-app/backend/kubeflow_jupyter/common/utils.py | Python | load_param_yaml | load_param_yaml | 67 | 85 | 67 | 67 | c32cad169df827b1748a980c12f441c1ad2f49e4 | bigcode/the-stack | train |
62a71a3db2a9543962f2fd55 | train | function | def find_error_event(rsrc_events):
'''
Returns status and reason from the latest event that surfaces the cause
of why the resource could not be created. For a Notebook, it can be due to:
EVENT_TYPE EVENT_REASON DESCRIPTION
Warning FailedCreate pods "x" is forbi... | def find_error_event(rsrc_events):
| '''
Returns status and reason from the latest event that surfaces the cause
of why the resource could not be created. For a Notebook, it can be due to:
EVENT_TYPE EVENT_REASON DESCRIPTION
Warning FailedCreate pods "x" is forbidden: error looking up service acco... | # Provide the user with detailed information (if any) about why the notebook is not starting
status_event, reason_event = find_error_event(rsrc_events)
if status_event:
status, reason = status_event, reason_event
return status, reason
def find_error_event(rsrc_events):
| 64 | 64 | 148 | 8 | 55 | StefanoFioravanzo/kubeflow | components/jupyter-web-app/backend/kubeflow_jupyter/common/utils.py | Python | find_error_event | find_error_event | 338 | 351 | 338 | 338 | e431aa8c6739ed8683e28e8ddf1d7d528dec8347 | bigcode/the-stack | train |
f971ffc3207f8ed63b63fcd9 | train | function | def process_status(rsrc, rsrc_events):
"""
Return status and reason. Status may be [running|waiting|warning|error]
"""
# If the Notebook is being deleted, the status will be waiting
if "deletionTimestamp" in rsrc["metadata"]:
return STATUS_WAITING, "Deleting Notebook Server"
# Check the... | def process_status(rsrc, rsrc_events):
| """
Return status and reason. Status may be [running|waiting|warning|error]
"""
# If the Notebook is being deleted, the status will be waiting
if "deletionTimestamp" in rsrc["metadata"]:
return STATUS_WAITING, "Deleting Notebook Server"
# Check the status
try:
s = rsrc["stat... | ("/")[-1],
"cpu": cntr["resources"]["requests"]["cpu"],
"gpu": gpu,
"gpuvendor": gpuvendor,
"memory": cntr["resources"]["requests"]["memory"],
"volumes": [v["name"] for v in cntr["volumeMounts"]],
"status": status,
"reason": reason,
}
return res
def proces... | 92 | 92 | 309 | 10 | 81 | StefanoFioravanzo/kubeflow | components/jupyter-web-app/backend/kubeflow_jupyter/common/utils.py | Python | process_status | process_status | 303 | 335 | 303 | 303 | cb5bd042135cdf4185cd6289c55a6d9444d7934f | bigcode/the-stack | train |
ad7ce6cc479a77f5691123ea | train | function | def update_config(config_file):
exp_config = None
with open(config_file) as f:
exp_config = edict(yaml.load(f))
for k, v in exp_config.items():
if k in config:
if isinstance(v, dict):
if k == 'TRAIN':
if 'BBOX_WEIGHTS' in v:... | def update_config(config_file):
| exp_config = None
with open(config_file) as f:
exp_config = edict(yaml.load(f))
for k, v in exp_config.items():
if k in config:
if isinstance(v, dict):
if k == 'TRAIN':
if 'BBOX_WEIGHTS' in v:
v['... |
# RCNN nms
config.TEST.NMS = 0.3
config.TEST.max_per_image = 300
#
config.TEST.KEY_FRAME_INTERVAL = 9
config.TEST.SEQ_NMS = False
# Test Model Epoch
config.TEST.test_epoch = 0
def update_config(config_file):
| 64 | 64 | 193 | 6 | 57 | sdroh1027/track_to_learn | fgfa_rfcn/config/config.py | Python | update_config | update_config | 160 | 181 | 160 | 160 | 68cfcc526328d53b03b06f87b4d662730dcd6186 | bigcode/the-stack | train |
6ca4919d3730c30b94ac5aa0 | train | class | class TestDynamicsBindings(TestCase):
def setUp(self):
self.model = pin.buildSampleModelHumanoidRandom()
self.data = self.model.createData()
qmax = np.matrix(np.full((self.model.nq,1),np.pi))
self.q = pin.randomConfiguration(self.model,-qmax,qmax)
self.v = rand(self.model.n... | class TestDynamicsBindings(TestCase):
| def setUp(self):
self.model = pin.buildSampleModelHumanoidRandom()
self.data = self.model.createData()
qmax = np.matrix(np.full((self.model.nq,1),np.pi))
self.q = pin.randomConfiguration(self.model,-qmax,qmax)
self.v = rand(self.model.nv)
self.tau = rand(self.model.n... | import unittest
from test_case import TestCase
import pinocchio as pin
from pinocchio.utils import rand, zero
import numpy as np
# common quantities for all tests.
# They correspond to the default values of the arguments, and they need to stay this way
r_coeff = 0.0
inv_damping = 0.0
update_kinematics = True
class Tes... | 90 | 241 | 805 | 7 | 82 | mkatliar/pinocchio | unittest/python/bindings_dynamics.py | Python | TestDynamicsBindings | TestDynamicsBindings | 14 | 80 | 14 | 15 | d566aff01f8eeb697e0f6b928a6b86f8170b73f1 | bigcode/the-stack | train |
08cd1af0f79acebcee7fc305 | train | class | class PythonSH(BaseSH):
"""Python Syntax Highlighter"""
# Syntax highlighting rules:
add_kw = ['async', 'await']
PROG = re.compile(make_python_patterns(additional_keywords=add_kw), re.S)
IDPROG = re.compile(r"\s+(\w+)", re.S)
ASPROG = re.compile(r"\b(as)\b")
# Syntax highlighting stat... | class PythonSH(BaseSH):
| """Python Syntax Highlighter"""
# Syntax highlighting rules:
add_kw = ['async', 'await']
PROG = re.compile(make_python_patterns(additional_keywords=add_kw), re.S)
IDPROG = re.compile(r"\s+(\w+)", re.S)
ASPROG = re.compile(r"\b(as)\b")
# Syntax highlighting states (from one text block t... | string1 = any("uf_sqstring", [uf_sqstring])
ufstring2 = any("uf_dqstring", [uf_dqstring])
ufstring3 = any("uf_sq3string", [uf_sq3string])
ufstring4 = any("uf_dq3string", [uf_dq3string])
ufstring5 = any("ufe_sqstring", [ufe_sqstring])
ufstring6 = any("ufe_dqstring", [ufe_dqstring])
return "... | 256 | 256 | 1,871 | 6 | 249 | TediaN97/spyder | spyder/utils/syntaxhighlighters.py | Python | PythonSH | PythonSH | 486 | 684 | 486 | 486 | f72b81664a907106eaa52eff0c6e40e2eb309c9b | bigcode/the-stack | train |
54f8b5eeeaabfb646a7d84cc | train | class | class BaseWebSH(BaseSH):
"""Base class for CSS and HTML syntax highlighters"""
NORMAL = 0
COMMENT = 1
def __init__(self, parent, font=None, color_scheme=None):
BaseSH.__init__(self, parent, font, color_scheme)
def highlight_block(self, text):
"""Implement highlight specif... | class BaseWebSH(BaseSH):
| """Base class for CSS and HTML syntax highlighters"""
NORMAL = 0
COMMENT = 1
def __init__(self, parent, font=None, color_scheme=None):
BaseSH.__init__(self, parent, font, color_scheme)
def highlight_block(self, text):
"""Implement highlight specific for CSS and HTML."""
... | [rRuU])?'[^'\\\n]*(\\.[^'\\\n]*)*'?"
dqstring = r'(\b[rRuU])?"[^"\\\n]*(\\.[^"\\\n]*)*"?'
string = any("string", [sqstring, dqstring])
return "|".join([kw, string, number, links, comment,
any("SYNC", [r"\n"])])
class YamlSH(GenericSH):
"""yaml Syntax Highlighter"""
# Sy... | 144 | 144 | 482 | 7 | 136 | TediaN97/spyder | spyder/utils/syntaxhighlighters.py | Python | BaseWebSH | BaseWebSH | 1,015 | 1,072 | 1,015 | 1,015 | f4cf602a45840a5fb91709d4a60d78270b5c2405 | bigcode/the-stack | train |
6886a152e6833775ed1c21c0 | train | class | class YamlSH(GenericSH):
"""yaml Syntax Highlighter"""
# Syntax highlighting rules:
PROG = re.compile(make_yaml_patterns(), re.S)
| class YamlSH(GenericSH):
| """yaml Syntax Highlighter"""
# Syntax highlighting rules:
PROG = re.compile(make_yaml_patterns(), re.S)
| "\\\n]*(\\.[^"\\\n]*)*"?'
string = any("string", [sqstring, dqstring])
return "|".join([kw, string, number, links, comment,
any("SYNC", [r"\n"])])
class YamlSH(GenericSH):
| 64 | 64 | 33 | 7 | 57 | TediaN97/spyder | spyder/utils/syntaxhighlighters.py | Python | YamlSH | YamlSH | 1,006 | 1,009 | 1,006 | 1,006 | 4fb008920039619762d684a4b27282a6a2a0c716 | bigcode/the-stack | train |
82a0c45b752d17aa88de936c | train | class | class DiffSH(BaseSH):
"""Simple Diff/Patch Syntax Highlighter Class"""
def highlight_block(self, text):
"""Implement highlight specific Diff/Patch files."""
text = to_text_string(text)
if text.startswith("+++"):
self.setFormat(0, qstring_length(text), self.formats["keyw... | class DiffSH(BaseSH):
| """Simple Diff/Patch Syntax Highlighter Class"""
def highlight_block(self, text):
"""Implement highlight specific Diff/Patch files."""
text = to_text_string(text)
if text.startswith("+++"):
self.setFormat(0, qstring_length(text), self.formats["keyword"])
elif te... | , builtin,
any("SYNC", [r"\n"])])
class IdlSH(GenericSH):
"""IDL Syntax Highlighter"""
PROG = re.compile(make_idl_patterns(), re.S|re.I)
#==============================================================================
# Diff/Patch highlighter
#===================================... | 64 | 64 | 178 | 6 | 57 | TediaN97/spyder | spyder/utils/syntaxhighlighters.py | Python | DiffSH | DiffSH | 923 | 939 | 923 | 923 | f0c9d6d4db63a69f503f672ca54340400e8a7723 | bigcode/the-stack | train |
0a26bdd9a0187278b99252e1 | train | function | def get_code_cell_name(text):
"""Returns a code cell name from a code cell comment."""
name = text.strip().lstrip("#% ")
if name.startswith("<codecell>"):
name = name[10:].lstrip()
elif name.startswith("In["):
name = name[2:]
if name.endswith("]:"):
name = nam... | def get_code_cell_name(text):
| """Returns a code cell name from a code cell comment."""
name = text.strip().lstrip("#% ")
if name.startswith("<codecell>"):
name = name[10:].lstrip()
elif name.startswith("In["):
name = name[2:]
if name.endswith("]:"):
name = name[:-1]
name = name.str... | string])
return "|".join([instance, kw, builtin, comment,
ufstring1, ufstring2, ufstring3, ufstring4, ufstring5,
ufstring6, string, number, any("SYNC", [r"\n"])])
def get_code_cell_name(text):
| 63 | 64 | 91 | 7 | 56 | TediaN97/spyder | spyder/utils/syntaxhighlighters.py | Python | get_code_cell_name | get_code_cell_name | 473 | 483 | 473 | 473 | 15b81eeddf7a54dc59357ca5a0604398c33d517e | bigcode/the-stack | train |
1d9aab97523f0b7ebf55ca61 | train | class | class CppSH(BaseSH):
"""C/C++ Syntax Highlighter"""
# Syntax highlighting rules:
PROG = re.compile(make_cpp_patterns(), re.S)
# Syntax highlighting states (from one text block to another):
NORMAL = 0
INSIDE_COMMENT = 1
def __init__(self, parent, font=None, color_scheme=None):
... | class CppSH(BaseSH):
| """C/C++ Syntax Highlighter"""
# Syntax highlighting rules:
PROG = re.compile(make_cpp_patterns(), re.S)
# Syntax highlighting states (from one text block to another):
NORMAL = 0
INSIDE_COMMENT = 1
def __init__(self, parent, font=None, color_scheme=None):
BaseSH.__init__(self,... | \\.[^"\\\n]*)*"?'
string = any("string", [sqstring, dqstring])
if define is None:
define = any("define", [r"#[^\n]*"])
return "|".join([instance, kw, comment, string, number,
comment_start, comment_end, builtin,
define, any("SYNC", [r"\n"])])
def ma... | 119 | 119 | 399 | 7 | 112 | TediaN97/spyder | spyder/utils/syntaxhighlighters.py | Python | CppSH | CppSH | 753 | 799 | 753 | 753 | 8075126f3ecaf05d8dc610c7379373ab04b8d8f4 | bigcode/the-stack | train |
f0b5da096378c89cb919cfbb | train | class | class FortranSH(BaseSH):
"""Fortran Syntax Highlighter"""
# Syntax highlighting rules:
PROG = re.compile(make_fortran_patterns(), re.S|re.I)
IDPROG = re.compile(r"\s+(\w+)", re.S)
# Syntax highlighting states (from one text block to another):
NORMAL = 0
def __init__(self, parent, font... | class FortranSH(BaseSH):
| """Fortran Syntax Highlighter"""
# Syntax highlighting rules:
PROG = re.compile(make_fortran_patterns(), re.S|re.I)
IDPROG = re.compile(r"\s+(\w+)", re.S)
# Syntax highlighting states (from one text block to another):
NORMAL = 0
def __init__(self, parent, font=None, color_scheme=None):... | \n]*(\\.[^'\\\n]*)*'?"
dqstring = r'(\b[rRuU])?"[^"\\\n]*(\\.[^"\\\n]*)*"?'
string = any("string", [sqstring, dqstring])
return "|".join([kw, comment, string, number, builtin,
any("SYNC", [r"\n"])])
class FortranSH(BaseSH):
| 91 | 92 | 308 | 7 | 84 | TediaN97/spyder | spyder/utils/syntaxhighlighters.py | Python | FortranSH | FortranSH | 841 | 873 | 841 | 841 | 90571861d80099d7f155bf2384c52471e44605c7 | bigcode/the-stack | train |
b8b1bf150f8e5cb9977e9040 | train | class | class NsisSH(CppSH):
"""NSIS Syntax Highlighter"""
# Syntax highlighting rules:
PROG = re.compile(make_nsis_patterns(), re.S)
| class NsisSH(CppSH):
| """NSIS Syntax Highlighter"""
# Syntax highlighting rules:
PROG = re.compile(make_nsis_patterns(), re.S)
| r"\#[^\n]*", r"\/\*(.*?)\*\/"])
return make_generic_c_patterns(kwstr1+' '+kwstr2+' '+kwstr3, bistr,
instance=instance, define=define,
comment=comment)
class NsisSH(CppSH):
| 64 | 64 | 36 | 8 | 56 | TediaN97/spyder | spyder/utils/syntaxhighlighters.py | Python | NsisSH | NsisSH | 957 | 960 | 957 | 957 | 5ae452351f8d27605194282c1addb8f3f41e6d15 | bigcode/the-stack | train |
4614fad58c7e4ed050a07976 | train | class | class PygmentsSH(BaseSH):
"""Generic Pygments syntax highlighter."""
# Store the language name and a ref to the lexer
_lang_name = None
_lexer = None
# Syntax highlighting states (from one text block to another):
NORMAL = 0
def __init__(self, parent, font=None, color_scheme=None):
... | class PygmentsSH(BaseSH):
| """Generic Pygments syntax highlighter."""
# Store the language name and a ref to the lexer
_lang_name = None
_lexer = None
# Syntax highlighting states (from one text block to another):
NORMAL = 0
def __init__(self, parent, font=None, color_scheme=None):
# Map Pygments toke... | QTextCharFormat(self.formats['normal'])
font.setFontStrikeOut(True)
self.formats['strikethrough'] = font
font = QTextCharFormat(self.formats['string'])
font.setUnderlineStyle(True)
self.formats['link'] = font
self.formats['code'] = self.formats['string']
... | 249 | 249 | 832 | 8 | 241 | TediaN97/spyder | spyder/utils/syntaxhighlighters.py | Python | PygmentsSH | PygmentsSH | 1,230 | 1,336 | 1,230 | 1,230 | 3523e53ea042948058e5440d2d46ccbb7b95475a | bigcode/the-stack | train |
92d073928a0941a5dde127b9 | train | function | def make_generic_c_patterns(keywords, builtins,
instance=None, define=None, comment=None):
"Strongly inspired from idlelib.ColorDelegator.make_pat"
kw = r"\b" + any("keyword", keywords.split()) + r"\b"
builtin = r"\b" + any("builtin", builtins.split()+C_TYPES.split()) + r"\b"... | def make_generic_c_patterns(keywords, builtins,
instance=None, define=None, comment=None):
| "Strongly inspired from idlelib.ColorDelegator.make_pat"
kw = r"\b" + any("keyword", keywords.split()) + r"\b"
builtin = r"\b" + any("builtin", builtins.split()+C_TYPES.split()) + r"\b"
if comment is None:
comment = any("comment", [r"//[^\n]*", r"\/\*(.*?)\*\/"])
comment_start = any("co... | latexonly endlink endverbatim enum example exception f$ file fn hideinitializer htmlinclude htmlonly if image include ingroup internal invariant interface latexonly li line link mainpage name namespace nosubgrouping note overload p page par param post pre ref relates remarks return retval sa section see showinitializer... | 117 | 117 | 392 | 21 | 96 | TediaN97/spyder | spyder/utils/syntaxhighlighters.py | Python | make_generic_c_patterns | make_generic_c_patterns | 726 | 748 | 726 | 727 | 959e78c17537b219c01a06849b7c6ad97946c697 | bigcode/the-stack | train |
52d84c5b5314a530065eb646 | train | function | def make_md_patterns():
h1 = '^#[^#]+'
h2 = '^##[^#]+'
h3 = '^###[^#]+'
h4 = '^####[^#]+'
h5 = '^#####[^#]+'
h6 = '^######[^#]+'
titles = any('title', [h1, h2, h3, h4, h5, h6])
html_tags = any("builtin", [r"<", r"[\?/]?>", r"(?<=<).*?(?=[ >])"])
html_symbols = '&[^; ].+;... | def make_md_patterns():
| h1 = '^#[^#]+'
h2 = '^##[^#]+'
h3 = '^###[^#]+'
h4 = '^####[^#]+'
h5 = '^#####[^#]+'
h6 = '^######[^#]+'
titles = any('title', [h1, h2, h3, h4, h5, h6])
html_tags = any("builtin", [r"<", r"[\?/]?>", r"(?<=<).*?(?=[ >])"])
html_symbols = '&[^; ].+;'
html_comment = '<!... | keywords = any("keyword", [r" [\w:-]*?(?==)"])
string = any("string", [r'".*?"'])
comment = any("comment", [r"<!--.*?-->"])
multiline_comment_start = any("multiline_comment_start", [r"<!--"])
multiline_comment_end = any("multiline_comment_end", [r"-->"])
return "|".join([comment, multiline_com... | 152 | 152 | 508 | 5 | 146 | TediaN97/spyder | spyder/utils/syntaxhighlighters.py | Python | make_md_patterns | make_md_patterns | 1,093 | 1,137 | 1,093 | 1,093 | 7b1786d11f8750fc9f71ef6ee7f08cfed8ad440c | bigcode/the-stack | train |
21b594b6a27ebbac21f8464d | train | function | def any(name, alternates):
"Return a named group pattern matching list of alternates."
return "(?P<%s>" % name + "|".join(alternates) + ")"
| def any(name, alternates):
| "Return a named group pattern matching list of alternates."
return "(?P<%s>" % name + "|".join(alternates) + ")"
| = name.lower()
scheme = {}
for key in COLOR_SCHEME_KEYS:
try:
scheme[key] = CONF.get('appearance', name+'/'+key)
except:
scheme[key] = CONF.get('appearance', 'spyder/'+key)
return scheme
def any(name, alternates):
| 64 | 64 | 42 | 7 | 56 | TediaN97/spyder | spyder/utils/syntaxhighlighters.py | Python | any | any | 127 | 129 | 127 | 127 | a4cada7d554ddd82b74c1077387c0e6dfc1dfdaf | bigcode/the-stack | train |
7950d0cf313a094a0e2d1e69 | train | class | class HtmlSH(BaseWebSH):
"""HTML Syntax Highlighter"""
PROG = re.compile(make_html_patterns(), re.S)
| class HtmlSH(BaseWebSH):
| """HTML Syntax Highlighter"""
PROG = re.compile(make_html_patterns(), re.S)
| _comment_start = any("multiline_comment_start", [r"<!--"])
multiline_comment_end = any("multiline_comment_end", [r"-->"])
return "|".join([comment, multiline_comment_start,
multiline_comment_end, tags, keywords, string])
class HtmlSH(BaseWebSH):
| 64 | 64 | 27 | 7 | 57 | TediaN97/spyder | spyder/utils/syntaxhighlighters.py | Python | HtmlSH | HtmlSH | 1,085 | 1,087 | 1,085 | 1,085 | a40da1ab919de03ea5c1024296f79c64f5d8af22 | bigcode/the-stack | train |
2f761f3d2edb5e63bdeed873 | train | function | def make_opencl_patterns():
# Keywords:
kwstr1 = 'cl_char cl_uchar cl_short cl_ushort cl_int cl_uint cl_long cl_ulong cl_half cl_float cl_double cl_platform_id cl_device_id cl_context cl_command_queue cl_mem cl_program cl_kernel cl_event cl_sampler cl_bool cl_bitfield cl_device_type cl_platform_info cl_device... | def make_opencl_patterns():
# Keywords:
| kwstr1 = 'cl_char cl_uchar cl_short cl_ushort cl_int cl_uint cl_long cl_ulong cl_half cl_float cl_double cl_platform_id cl_device_id cl_context cl_command_queue cl_mem cl_program cl_kernel cl_event cl_sampler cl_bool cl_bitfield cl_device_type cl_platform_info cl_device_info cl_device_address_info cl_device_fp_conf... | self.formats["comment" if inside_comment else "normal"])
match = self.PROG.search(text)
index = 0
while match:
for key, value in list(match.groupdict().items()):
if value:
start, end = get_span(match, key)
... | 256 | 256 | 2,154 | 10 | 246 | TediaN97/spyder | spyder/utils/syntaxhighlighters.py | Python | make_opencl_patterns | make_opencl_patterns | 802 | 813 | 802 | 803 | 79a104b4125ee45bd296a656f424577c9c146c83 | bigcode/the-stack | train |
ea5303812d1fec0f1f17a982 | train | class | class Fortran77SH(FortranSH):
"""Fortran 77 Syntax Highlighter"""
def highlight_block(self, text):
"""Implement highlight specific for Fortran77."""
text = to_text_string(text)
if text.startswith(("c", "C")):
self.setFormat(0, qstring_length(text), self.formats["comment... | class Fortran77SH(FortranSH):
| """Fortran 77 Syntax Highlighter"""
def highlight_block(self, text):
"""Implement highlight specific for Fortran77."""
text = to_text_string(text)
if text.startswith(("c", "C")):
self.setFormat(0, qstring_length(text), self.formats["comment"])
self.highlight... | start1, end1 = get_span(match1, 1)
self.setFormat(start1, end1-start1,
self.formats["definition"])
match = self.PROG.search(text, match.end())
self.highlight_extras(text)
class Fortran77SH(FortranSH):
| 64 | 64 | 139 | 10 | 54 | TediaN97/spyder | spyder/utils/syntaxhighlighters.py | Python | Fortran77SH | Fortran77SH | 875 | 887 | 875 | 875 | 5ec9ceb74335a5477f88ecb0a9d66eee35aacd7b | bigcode/the-stack | train |
d6fb2328db07c696ab883270 | train | class | class CythonSH(PythonSH):
"""Cython Syntax Highlighter"""
ADDITIONAL_KEYWORDS = [
"cdef", "ctypedef", "cpdef", "inline", "cimport", "extern",
"include", "begin", "end", "by", "gil", "nogil", "const", "public",
"readonly", "fused", "static", "api", "DEF", "IF", "ELIF", "ELSE"]
... | class CythonSH(PythonSH):
| """Cython Syntax Highlighter"""
ADDITIONAL_KEYWORDS = [
"cdef", "ctypedef", "cpdef", "inline", "cimport", "extern",
"include", "begin", "end", "by", "gil", "nogil", "const", "public",
"readonly", "fused", "static", "api", "DEF", "IF", "ELIF", "ELSE"]
ADDITIONAL_BUILTINS = C_TY... | block = block.next()
return statments
def rehighlight(self):
BaseSH.rehighlight(self)
#==============================================================================
# Cython syntax highlighter
#==============================================================================
C... | 64 | 64 | 189 | 8 | 56 | TediaN97/spyder | spyder/utils/syntaxhighlighters.py | Python | CythonSH | CythonSH | 692 | 703 | 692 | 692 | 334d9149bcffd1905227b1bb6e3c85946c65de75 | bigcode/the-stack | train |
60e53d9656c2ab9e756990ab | train | function | def get_color_scheme(name):
"""Get a color scheme from config using its name"""
name = name.lower()
scheme = {}
for key in COLOR_SCHEME_KEYS:
try:
scheme[key] = CONF.get('appearance', name+'/'+key)
except:
scheme[key] = CONF.get('appearance', 'spyder/'+key... | def get_color_scheme(name):
| """Get a color scheme from config using its name"""
name = name.lower()
scheme = {}
for key in COLOR_SCHEME_KEYS:
try:
scheme[key] = CONF.get('appearance', name+'/'+key)
except:
scheme[key] = CONF.get('appearance', 'spyder/'+key)
return scheme
| key=None):
if key is not None:
start, end = match.span(key)
else:
start, end = match.span()
start = qstring_length(match.string[:start])
end = qstring_length(match.string[:end])
return start, end
def get_color_scheme(name):
| 64 | 64 | 77 | 6 | 57 | TediaN97/spyder | spyder/utils/syntaxhighlighters.py | Python | get_color_scheme | get_color_scheme | 115 | 124 | 115 | 115 | aa35812aaea3131279889a7f070860f5b941f92c | bigcode/the-stack | train |
8da66116fa25cda17de6fdd1 | train | class | class IdlSH(GenericSH):
"""IDL Syntax Highlighter"""
PROG = re.compile(make_idl_patterns(), re.S|re.I)
| class IdlSH(GenericSH):
| """IDL Syntax Highlighter"""
PROG = re.compile(make_idl_patterns(), re.S|re.I)
| "\\\n]*(\\.[^"\\\n]*)*"?'
string = any("string", [sqstring, dqstring])
return "|".join([kw, comment, string, number, builtin,
any("SYNC", [r"\n"])])
class IdlSH(GenericSH):
| 64 | 64 | 31 | 7 | 57 | TediaN97/spyder | spyder/utils/syntaxhighlighters.py | Python | IdlSH | IdlSH | 915 | 917 | 915 | 915 | 00e3654fc518e8eb0369700d7eb2d3182023cca7 | bigcode/the-stack | train |
4c563bca1ca50681c1d4d776 | train | function | def get_span(match, key=None):
if key is not None:
start, end = match.span(key)
else:
start, end = match.span()
start = qstring_length(match.string[:start])
end = qstring_length(match.string[:end])
return start, end
| def get_span(match, key=None):
| if key is not None:
start, end = match.span(key)
else:
start, end = match.span()
start = qstring_length(match.string[:start])
end = qstring_length(match.string[:end])
return start, end
| custom_extension_lexer_mapping[key] = value
# Tuple of keys is iterated over and each is mapped to value.
else:
for k in key:
custom_extension_lexer_mapping[k] = value
#==============================================================================
# Auxiliary functions
#=========... | 64 | 64 | 63 | 8 | 55 | TediaN97/spyder | spyder/utils/syntaxhighlighters.py | Python | get_span | get_span | 105 | 112 | 105 | 105 | fca06891b09e63714e9679fed3547ee76738139e | bigcode/the-stack | train |
67ea9883b639aa99ca87c5f3 | train | function | def make_fortran_patterns():
"Strongly inspired from idlelib.ColorDelegator.make_pat"
kwstr = 'access action advance allocatable allocate apostrophe assign assignment associate asynchronous backspace bind blank blockdata call case character class close common complex contains continue cycle data deallocate de... | def make_fortran_patterns():
| "Strongly inspired from idlelib.ColorDelegator.make_pat"
kwstr = 'access action advance allocatable allocate apostrophe assign assignment associate asynchronous backspace bind blank blockdata call case character class close common complex contains continue cycle data deallocate decimal delim default dimension ... | clGetEventInfo, clRetainEvent, clReleaseEvent, clGetEventProfilingInfo, clFlush, clFinish, clEnqueueReadBuffer, clEnqueueWriteBuffer, clEnqueueCopyBuffer, clEnqueueReadImage, clEnqueueWriteImage, clEnqueueCopyImage, clEnqueueCopyImageToBuffer, clEnqueueCopyBufferToImage, clEnqueueMapBuffer, clEnqueueMapImage, clEnqueu... | 256 | 256 | 1,306 | 6 | 249 | TediaN97/spyder | spyder/utils/syntaxhighlighters.py | Python | make_fortran_patterns | make_fortran_patterns | 823 | 839 | 823 | 823 | 7ab534112812704d4a1592aafebbb56919cf1d44 | bigcode/the-stack | train |
9bad8df02793626b416bef4b | train | function | def make_nsis_patterns():
"Strongly inspired from idlelib.ColorDelegator.make_pat"
kwstr1 = 'Abort AddBrandingImage AddSize AllowRootDirInstall AllowSkipFiles AutoCloseWindow BGFont BGGradient BrandingText BringToFront Call CallInstDLL Caption ClearErrors CompletedText ComponentText CopyFiles CRCCheck CreateD... | def make_nsis_patterns():
| "Strongly inspired from idlelib.ColorDelegator.make_pat"
kwstr1 = 'Abort AddBrandingImage AddSize AllowRootDirInstall AllowSkipFiles AutoCloseWindow BGFont BGGradient BrandingText BringToFront Call CallInstDLL Caption ClearErrors CompletedText ComponentText CopyFiles CRCCheck CreateDirectory CreateFont CreateS... | , number, builtin,
any("SYNC", [r"\n"])])
class IdlSH(GenericSH):
"""IDL Syntax Highlighter"""
PROG = re.compile(make_idl_patterns(), re.S|re.I)
#==============================================================================
# Diff/Patch highlighter
#===========================... | 256 | 256 | 2,068 | 6 | 249 | TediaN97/spyder | spyder/utils/syntaxhighlighters.py | Python | make_nsis_patterns | make_nsis_patterns | 944 | 955 | 944 | 944 | d84981154891637dd8906ecebeda7a388d5be0bf | bigcode/the-stack | train |
1c1c197fdf49f9ea56b2e98a | train | class | class TextSH(BaseSH):
"""Simple Text Syntax Highlighter Class (only highlight spaces)."""
def highlight_block(self, text):
"""Implement highlight, only highlight spaces."""
text = to_text_string(text)
self.setFormat(0, qstring_length(text), self.formats["normal"])
self.hi... | class TextSH(BaseSH):
| """Simple Text Syntax Highlighter Class (only highlight spaces)."""
def highlight_block(self, text):
"""Implement highlight, only highlight spaces."""
text = to_text_string(text)
self.setFormat(0, qstring_length(text), self.formats["normal"])
self.highlight_extras(text)
| highlight_block().
"""
self.highlight_spaces(text, offset=offset)
self.highlight_patterns(text, offset=offset)
def rehighlight(self):
QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
QSyntaxHighlighter.rehighlight(self)
QApplication.restoreOverrideCurs... | 64 | 64 | 72 | 6 | 58 | TediaN97/spyder | spyder/utils/syntaxhighlighters.py | Python | TextSH | TextSH | 369 | 376 | 369 | 369 | 8a5fef7fb0d9530d0e9000cfb3ff44c7e495fe3a | bigcode/the-stack | train |
20637203f3f219a1a50308ff | train | class | class MarkdownSH(BaseSH):
"""Markdown Syntax Highlighter"""
# Syntax highlighting rules:
PROG = re.compile(make_md_patterns(), re.S)
NORMAL = 0
CODE = 1
def highlightBlock(self, text):
text = to_text_string(text)
previous_state = self.previousBlockState()
if ... | class MarkdownSH(BaseSH):
| """Markdown Syntax Highlighter"""
# Syntax highlighting rules:
PROG = re.compile(make_md_patterns(), re.S)
NORMAL = 0
CODE = 1
def highlightBlock(self, text):
text = to_text_string(text)
previous_state = self.previousBlockState()
if previous_state == self.CODE... | r'|(^(?: |\t)*[0-9]+\. )'
r'|(^(?: |\t)*- )'
r'|(^(?: |\t)*\* )')
# code
code = any('code', ['^`{3,}.*$'])
inline_code = any('inline_code', ['`[^`]*`'])
# math - $$
math = any('number', [r'^(?:\${2}).*$', html_symbols])
comment = any('c... | 161 | 162 | 543 | 6 | 155 | TediaN97/spyder | spyder/utils/syntaxhighlighters.py | Python | MarkdownSH | MarkdownSH | 1,140 | 1,215 | 1,140 | 1,140 | 8a5dde16ab3c5d2bebde49ff1bbb18232658bd17 | bigcode/the-stack | train |
3ec64f7a784d4ba0083cdcfc | train | function | def guess_pygments_highlighter(filename):
"""
Factory to generate syntax highlighter for the given filename.
If a syntax highlighter is not available for a particular file, this
function will attempt to generate one based on the lexers in Pygments. If
Pygments is not available or does not hav... | def guess_pygments_highlighter(filename):
| """
Factory to generate syntax highlighter for the given filename.
If a syntax highlighter is not available for a particular file, this
function will attempt to generate one based on the lexers in Pygments. If
Pygments is not available or does not have an appropriate lexer, TextSH
will be... | .+)',
bygroups(Generic.Error, Name.Constant), '#pop'),
(r'(\sTRACE)(\s.+)',
bygroups(Generic.Error, Name.Constant), '#pop'),
(r'(\s\w+)(\s.+)',
bygroups(Comment, Generic.Output), '#pop'),
],
}
def guess_pygments_highlighter(filename):
| 80 | 80 | 268 | 9 | 71 | TediaN97/spyder | spyder/utils/syntaxhighlighters.py | Python | guess_pygments_highlighter | guess_pygments_highlighter | 1,378 | 1,413 | 1,378 | 1,378 | 5318eb5d0db8a7090e79399d99e4dc045f263104 | bigcode/the-stack | train |
4346344af7da85d451fa18c6 | train | function | def make_python_patterns(additional_keywords=[], additional_builtins=[]):
"Strongly inspired from idlelib.ColorDelegator.make_pat"
kwlist = keyword.kwlist + additional_keywords
builtinlist = [str(name) for name in dir(builtins)
if not name.startswith('_')] + additional_builtins
r... | def make_python_patterns(additional_keywords=[], additional_builtins=[]):
| "Strongly inspired from idlelib.ColorDelegator.make_pat"
kwlist = keyword.kwlist + additional_keywords
builtinlist = [str(name) for name in dir(builtins)
if not name.startswith('_')] + additional_builtins
repeated = set(kwlist) & set(builtinlist)
for repeated_element in repea... | Highlighter Class (only highlight spaces)."""
def highlight_block(self, text):
"""Implement highlight, only highlight spaces."""
text = to_text_string(text)
self.setFormat(0, qstring_length(text), self.formats["normal"])
self.highlight_extras(text)
class GenericSH(BaseSH... | 256 | 256 | 1,402 | 14 | 241 | TediaN97/spyder | spyder/utils/syntaxhighlighters.py | Python | make_python_patterns | make_python_patterns | 406 | 470 | 406 | 406 | b2ea059ea45a0174df117f010712afaca63a1f08 | bigcode/the-stack | train |
c2cc8ee12b71da9f2093dc68 | train | class | class EnamlSH(PythonSH):
"""Enaml Syntax Highlighter"""
ADDITIONAL_KEYWORDS = ["enamldef", "template", "attr", "event", "const", "alias",
"func"]
ADDITIONAL_BUILTINS = []
PROG = re.compile(make_python_patterns(ADDITIONAL_KEYWORDS,
... | class EnamlSH(PythonSH):
| """Enaml Syntax Highlighter"""
ADDITIONAL_KEYWORDS = ["enamldef", "template", "attr", "event", "const", "alias",
"func"]
ADDITIONAL_BUILTINS = []
PROG = re.compile(make_python_patterns(ADDITIONAL_KEYWORDS,
ADDITIONAL_BUILTINS), r... | = re.compile(make_python_patterns(ADDITIONAL_KEYWORDS,
ADDITIONAL_BUILTINS), re.S)
IDPROG = re.compile(r"\s+([\w\.]+)", re.S)
#==============================================================================
# Enaml syntax highlighter
#=============================... | 64 | 64 | 103 | 8 | 55 | TediaN97/spyder | spyder/utils/syntaxhighlighters.py | Python | EnamlSH | EnamlSH | 709 | 716 | 709 | 709 | bf394f1543d702124d78b3370d34395128777c64 | bigcode/the-stack | train |
841f170cbb5bb7f1454f65af | train | function | def make_cpp_patterns():
return make_generic_c_patterns(C_KEYWORDS1+' '+C_KEYWORDS2, C_KEYWORDS3)
| def make_cpp_patterns():
| return make_generic_c_patterns(C_KEYWORDS1+' '+C_KEYWORDS2, C_KEYWORDS3)
| if define is None:
define = any("define", [r"#[^\n]*"])
return "|".join([instance, kw, comment, string, number,
comment_start, comment_end, builtin,
define, any("SYNC", [r"\n"])])
def make_cpp_patterns():
| 64 | 64 | 27 | 5 | 59 | TediaN97/spyder | spyder/utils/syntaxhighlighters.py | Python | make_cpp_patterns | make_cpp_patterns | 750 | 751 | 750 | 750 | fd0135a60a4a4873bdc6522e35fc02cca8b78c15 | bigcode/the-stack | train |
8b2a13825f7489dbace66b05 | train | class | class OpenCLSH(CppSH):
"""OpenCL Syntax Highlighter"""
PROG = re.compile(make_opencl_patterns(), re.S)
| class OpenCLSH(CppSH):
| """OpenCL Syntax Highlighter"""
PROG = re.compile(make_opencl_patterns(), re.S)
| kernel'
keyword_list = C_KEYWORDS1+' '+C_KEYWORDS2+' '+kwstr1+' '+kwstr2
builtin_list = C_KEYWORDS3+' '+builtins+' '+qualifiers
return make_generic_c_patterns(keyword_list, builtin_list)
class OpenCLSH(CppSH):
| 64 | 64 | 30 | 8 | 56 | TediaN97/spyder | spyder/utils/syntaxhighlighters.py | Python | OpenCLSH | OpenCLSH | 815 | 817 | 815 | 815 | 144649bde3a206d732267eb9566b9b72f248641a | bigcode/the-stack | train |
63743306335ac33496f0db05 | train | class | class GenericSH(BaseSH):
"""Generic Syntax Highlighter"""
# Syntax highlighting rules:
PROG = None # to be redefined in child classes
def highlight_block(self, text):
"""Implement highlight using regex defined in children classes."""
text = to_text_string(text)
self.set... | class GenericSH(BaseSH):
| """Generic Syntax Highlighter"""
# Syntax highlighting rules:
PROG = None # to be redefined in child classes
def highlight_block(self, text):
"""Implement highlight using regex defined in children classes."""
text = to_text_string(text)
self.setFormat(0, qstring_length(t... | (only highlight spaces)."""
def highlight_block(self, text):
"""Implement highlight, only highlight spaces."""
text = to_text_string(text)
self.setFormat(0, qstring_length(text), self.formats["normal"])
self.highlight_extras(text)
class GenericSH(BaseSH):
| 64 | 64 | 169 | 6 | 58 | TediaN97/spyder | spyder/utils/syntaxhighlighters.py | Python | GenericSH | GenericSH | 379 | 400 | 379 | 379 | 284140110fa5bdc6bb2a9caa44a0c79519ad4600 | bigcode/the-stack | train |
c68105a841ec577f46bbaa24 | train | function | def make_html_patterns():
"""Strongly inspired from idlelib.ColorDelegator.make_pat """
tags = any("builtin", [r"<", r"[\?/]?>", r"(?<=<).*?(?=[ >])"])
keywords = any("keyword", [r" [\w:-]*?(?==)"])
string = any("string", [r'".*?"'])
comment = any("comment", [r"<!--.*?-->"])
multiline_comm... | def make_html_patterns():
| """Strongly inspired from idlelib.ColorDelegator.make_pat """
tags = any("builtin", [r"<", r"[\?/]?>", r"(?<=<).*?(?=[ >])"])
keywords = any("keyword", [r" [\w:-]*?(?==)"])
string = any("string", [r'".*?"'])
comment = any("comment", [r"<!--.*?-->"])
multiline_comment_start = any("multiline_... | [key])
except KeyError:
# Happens with unmatched end-of-comment.
# See spyder-ide/spyder#1462.
pass
match = self.PROG.search(text, match.end())
match_count += 1
... | 64 | 64 | 160 | 5 | 59 | TediaN97/spyder | spyder/utils/syntaxhighlighters.py | Python | make_html_patterns | make_html_patterns | 1,074 | 1,083 | 1,074 | 1,074 | a851d5ba021f91e6bd9feae383269ed5e1a7d037 | bigcode/the-stack | train |
be3f779da768f7e3c9f39001 | train | class | class BaseSH(QSyntaxHighlighter):
"""Base Syntax Highlighter Class"""
# Syntax highlighting rules:
PROG = None
BLANKPROG = re.compile(r"\s+")
# Syntax highlighting states (from one text block to another):
NORMAL = 0
# Syntax highlighting parameters.
BLANK_ALPHA_FACTOR = 0.31
... | class BaseSH(QSyntaxHighlighter):
| """Base Syntax Highlighter Class"""
# Syntax highlighting rules:
PROG = None
BLANKPROG = re.compile(r"\s+")
# Syntax highlighting states (from one text block to another):
NORMAL = 0
# Syntax highlighting parameters.
BLANK_ALPHA_FACTOR = 0.31
sig_outline_explorer_data_change... | color scheme from config using its name"""
name = name.lower()
scheme = {}
for key in COLOR_SCHEME_KEYS:
try:
scheme[key] = CONF.get('appearance', name+'/'+key)
except:
scheme[key] = CONF.get('appearance', 'spyder/'+key)
return scheme
def any(name, a... | 256 | 256 | 1,600 | 8 | 247 | TediaN97/spyder | spyder/utils/syntaxhighlighters.py | Python | BaseSH | BaseSH | 159 | 366 | 159 | 159 | 44ceffe1b642a38650008c5b92fd02c05e9e3659 | bigcode/the-stack | train |
24f9ccf9509792c2502b365a | train | class | class PythonLoggingLexer(RegexLexer):
"""
A lexer for logs generated by the Python builtin 'logging' library.
Taken from
https://bitbucket.org/birkenfeld/pygments-main/pull-requests/451/add-python-logging-lexer
"""
name = 'Python Logging'
aliases = ['pylog', 'pythonlogging']
... | class PythonLoggingLexer(RegexLexer):
| """
A lexer for logs generated by the Python builtin 'logging' library.
Taken from
https://bitbucket.org/birkenfeld/pygments-main/pull-requests/451/add-python-logging-lexer
"""
name = 'Python Logging'
aliases = ['pylog', 'pythonlogging']
filenames = ['*.log']
tokens = {
... | (self, text):
""" Actually highlight the block"""
# Note that an undefined blockstate is equal to -1, so the first block
# will have the correct behaviour of starting at 0.
if self._allow_highlight:
start = self.previousBlockState() + 1
end = start + qstring... | 126 | 126 | 423 | 8 | 118 | TediaN97/spyder | spyder/utils/syntaxhighlighters.py | Python | PythonLoggingLexer | PythonLoggingLexer | 1,339 | 1,375 | 1,339 | 1,339 | f5b03ffe9f71ae00891fac6c1816677ae229ad49 | bigcode/the-stack | train |
23ae14bf2dac64f02385c549 | train | class | class GetTextSH(GenericSH):
"""gettext Syntax Highlighter"""
# Syntax highlighting rules:
PROG = re.compile(make_gettext_patterns(), re.S)
| class GetTextSH(GenericSH):
| """gettext Syntax Highlighter"""
# Syntax highlighting rules:
PROG = re.compile(make_gettext_patterns(), re.S)
| \n]*(\\.[^"\\\n]*)*"?'
string = any("string", [sqstring, dqstring])
return "|".join([kw, string, number, fuzzy, links, comment,
any("SYNC", [r"\n"])])
class GetTextSH(GenericSH):
| 63 | 64 | 34 | 7 | 56 | TediaN97/spyder | spyder/utils/syntaxhighlighters.py | Python | GetTextSH | GetTextSH | 983 | 986 | 983 | 983 | f457d7455c83c6a30912b7158ea09fcf3698891b | bigcode/the-stack | train |
5b502cb2d0d4b95637aabccd | train | function | def make_idl_patterns():
"""Strongly inspired by idlelib.ColorDelegator.make_pat."""
kwstr = 'begin of pro function endfor endif endwhile endrep endcase endswitch end if then else for do while repeat until break case switch common continue exit return goto help message print read retall stop'
bistr1 = 'a... | def make_idl_patterns():
| """Strongly inspired by idlelib.ColorDelegator.make_pat."""
kwstr = 'begin of pro function endfor endif endwhile endrep endcase endswitch end if then else for do while repeat until break case switch common continue exit return goto help message print read retall stop'
bistr1 = 'a_correlate abs acos adapt_... | G.match(text, end)
if match1:
start1, end1 = get_span(match1, 1)
self.setFormat(start1, end1-start1,
self.formats["definition"])
match = self.PROG.search(text, match.end())
... | 256 | 256 | 2,004 | 6 | 249 | TediaN97/spyder | spyder/utils/syntaxhighlighters.py | Python | make_idl_patterns | make_idl_patterns | 896 | 913 | 896 | 896 | 21b3f5948d78af14f29b37df319df4ea6579f59a | bigcode/the-stack | train |
bcaab8e9aad6c74f15e4443b | train | function | def create_patterns(patterns, compile=False):
"""
Create patterns from pattern dictionary.
The key correspond to the group name and the values a list of
possible pattern alternatives.
"""
all_patterns = []
for key, value in patterns.items():
all_patterns.append(any(key, [va... | def create_patterns(patterns, compile=False):
| """
Create patterns from pattern dictionary.
The key correspond to the group name and the values a list of
possible pattern alternatives.
"""
all_patterns = []
for key, value in patterns.items():
all_patterns.append(any(key, [value]))
regex = '|'.join(all_patterns)
... | ('appearance', 'spyder/'+key)
return scheme
def any(name, alternates):
"Return a named group pattern matching list of alternates."
return "(?P<%s>" % name + "|".join(alternates) + ")"
def create_patterns(patterns, compile=False):
| 64 | 64 | 89 | 9 | 54 | TediaN97/spyder | spyder/utils/syntaxhighlighters.py | Python | create_patterns | create_patterns | 132 | 148 | 132 | 132 | 0b94c0d0e6439a4492ddff3aee7f642ac2c6cdf2 | bigcode/the-stack | train |
41fec9caf9a8983c9e30378d | train | function | def make_gettext_patterns():
"Strongly inspired from idlelib.ColorDelegator.make_pat"
kwstr = 'msgid msgstr'
kw = r"\b" + any("keyword", kwstr.split()) + r"\b"
fuzzy = any("builtin", [r"#,[^\n]*"])
links = any("normal", [r"#:[^\n]*"])
comment = any("comment", [r"#[^\n]*"])
number = an... | def make_gettext_patterns():
| "Strongly inspired from idlelib.ColorDelegator.make_pat"
kwstr = 'msgid msgstr'
kw = r"\b" + any("keyword", kwstr.split()) + r"\b"
fuzzy = any("builtin", [r"#,[^\n]*"])
links = any("normal", [r"#:[^\n]*"])
comment = any("comment", [r"#[^\n]*"])
number = any("number",
... | _c_patterns(kwstr1+' '+kwstr2+' '+kwstr3, bistr,
instance=instance, define=define,
comment=comment)
class NsisSH(CppSH):
"""NSIS Syntax Highlighter"""
# Syntax highlighting rules:
PROG = re.compile(make_nsis_patterns(), re.S)
... | 87 | 87 | 293 | 6 | 80 | TediaN97/spyder | spyder/utils/syntaxhighlighters.py | Python | make_gettext_patterns | make_gettext_patterns | 966 | 981 | 966 | 966 | aa4176de0ff0f96136511adc7e9b4b4046b51850 | bigcode/the-stack | train |
f65b5717d6dcdaf6369c59ee | train | function | def make_yaml_patterns():
"Strongly inspired from sublime highlighter "
kw = any("keyword", [r":|>|-|\||\[|\]|[A-Za-z][\w\s\-\_ ]+(?=:)"])
links = any("normal", [r"#:[^\n]*"])
comment = any("comment", [r"#[^\n]*"])
number = any("number",
[r"\b[+-]?[0-9]+[lL]?\b",
... | def make_yaml_patterns():
| "Strongly inspired from sublime highlighter "
kw = any("keyword", [r":|>|-|\||\[|\]|[A-Za-z][\w\s\-\_ ]+(?=:)"])
links = any("normal", [r"#:[^\n]*"])
comment = any("comment", [r"#[^\n]*"])
number = any("number",
[r"\b[+-]?[0-9]+[lL]?\b",
r"\b[+-]?0[xX][0-9A-F... | dqstring])
return "|".join([kw, string, number, fuzzy, links, comment,
any("SYNC", [r"\n"])])
class GetTextSH(GenericSH):
"""gettext Syntax Highlighter"""
# Syntax highlighting rules:
PROG = re.compile(make_gettext_patterns(), re.S)
#=====================================... | 82 | 82 | 275 | 5 | 76 | TediaN97/spyder | spyder/utils/syntaxhighlighters.py | Python | make_yaml_patterns | make_yaml_patterns | 991 | 1,004 | 991 | 991 | 48c2585374cd11ae48662ef888809e0d96110532 | bigcode/the-stack | train |
7a32edc85b22d7742b0fb049 | train | function | def image_data_augmentation(x_train):
print('Using real-time data augmentation.')
# This will do preprocessing and realtime data augmentation:
datagen = ImageDataGenerator(
featurewise_center=False, # set input mean to 0 over the dataset
samplewise_center=False, # set each sample mean to ... | def image_data_augmentation(x_train):
| print('Using real-time data augmentation.')
# This will do preprocessing and realtime data augmentation:
datagen = ImageDataGenerator(
featurewise_center=False, # set input mean to 0 over the dataset
samplewise_center=False, # set each sample mean to 0
featurewise_std_normalizatio... | = y_train[indexTrain[0:noTrainingSamples], :]
x_test = x_test[indexTest[0:noTestingSamples], :]
y_test = y_test[indexTest[0:noTestingSamples], :]
# normalize data
xTrainMean = np.mean(x_train, axis=0)
xTtrainStd = np.std(x_train, axis=0)
x_train = (x_train - xTrainMean) / xTtrainStd
x_test... | 135 | 135 | 450 | 8 | 126 | emielsteerneman/sparse-evolutionary-artificial-neural-networks | Tutorial-ECMLPKDD-2019-Scalable-Deep-Learning/set_mlp.py | Python | image_data_augmentation | image_data_augmentation | 619 | 658 | 619 | 619 | 22dea84f384c3214151e7ad0d1f6a40bb1b59ced | bigcode/the-stack | train |
e8f23e163e9b1c8d20a40e39 | train | class | class NoActivation:
"""
This is a plugin function for no activation.
f(x) = x * 1
"""
@staticmethod
def activation(z):
"""
:param z: (array) w(x) + b
:return: z (array)
"""
return z
@staticmethod
def prime(z):
"""
The prime of z ... | class NoActivation:
| """
This is a plugin function for no activation.
f(x) = x * 1
"""
@staticmethod
def activation(z):
"""
:param z: (array) w(x) + b
:return: z (array)
"""
return z
@staticmethod
def prime(z):
"""
The prime of z * 1 = 1
:par... | , y_pred):
return y_pred - y_true
def delta(self, y_true, y_pred):
"""
Back propagation error delta
:return: (array)
"""
return self.prime(y_true, y_pred) * self.activation_fn.prime(y_pred)
class NoActivation:
| 64 | 64 | 116 | 4 | 60 | emielsteerneman/sparse-evolutionary-artificial-neural-networks | Tutorial-ECMLPKDD-2019-Scalable-Deep-Learning/set_mlp.py | Python | NoActivation | NoActivation | 145 | 167 | 145 | 145 | 789d8adee74c5bc1db335876c67372e07bdbfee8 | bigcode/the-stack | train |
ea7e56022edb5923a3db4c94 | train | class | class Sigmoid:
@staticmethod
def activation(z):
return 1 / (1 + np.exp(-z))
@staticmethod
def prime(z):
return Sigmoid.activation(z) * (1 - Sigmoid.activation(z))
| class Sigmoid:
@staticmethod
| def activation(z):
return 1 / (1 + np.exp(-z))
@staticmethod
def prime(z):
return Sigmoid.activation(z) * (1 - Sigmoid.activation(z))
|
def activation(z):
z[z < 0] = 0
return z
@staticmethod
def prime(z):
z[z < 0] = 0
z[z > 0] = 1
return z
class Sigmoid:
@staticmethod
| 64 | 64 | 51 | 8 | 55 | emielsteerneman/sparse-evolutionary-artificial-neural-networks | Tutorial-ECMLPKDD-2019-Scalable-Deep-Learning/set_mlp.py | Python | Sigmoid | Sigmoid | 101 | 108 | 101 | 102 | 0f5612bbac63fb7acf3e524acdee72e465e07910 | bigcode/the-stack | train |
805d069d9ac3d60d39c63769 | train | function | def createSparseWeights(epsilon, noRows, noCols):
# generate an Erdos Renyi sparse weights mask
weights = lil_matrix((noRows, noCols))
for i in range(epsilon * (noRows + noCols)):
weights[np.random.randint(0, noRows), np.random.randint(0, noCols)] = np.float64(np.random.randn() * np.sqrt(2 / (noRows... | def createSparseWeights(epsilon, noRows, noCols):
# generate an Erdos Renyi sparse weights mask
| weights = lil_matrix((noRows, noCols))
for i in range(epsilon * (noRows + noCols)):
weights[np.random.randint(0, noRows), np.random.randint(0, noCols)] = np.float64(np.random.randn() * np.sqrt(2 / (noRows + noCols)))
print("Create sparse matrix with ", weights.getnnz(), " connections and ",
... | ()
return idx
def find_last_pos(array, value):
idx = (np.abs(array - value))[::-1].argmin()
return array.shape[0] - idx
def createSparseWeights(epsilon, noRows, noCols):
# generate an Erdos Renyi sparse weights mask
| 64 | 64 | 145 | 25 | 38 | emielsteerneman/sparse-evolutionary-artificial-neural-networks | Tutorial-ECMLPKDD-2019-Scalable-Deep-Learning/set_mlp.py | Python | createSparseWeights | createSparseWeights | 70 | 78 | 70 | 71 | 00bf13094c36dbf8f907e65c94150748e94acfea | bigcode/the-stack | train |
ae430f6bb65f9f91a7423aef | train | class | class SET_MLP:
def __init__(self, dimensions, activations, epsilon=20):
"""
:param dimensions: (tpl/ list) Dimensions of the neural net. (input, hidden layer, output)
:param activations: (tpl/ list) Activations functions.
Example of three hidden layer with
- 3312 input featu... | class SET_MLP:
| def __init__(self, dimensions, activations, epsilon=20):
"""
:param dimensions: (tpl/ list) Dimensions of the neural net. (input, hidden layer, output)
:param activations: (tpl/ list) Activations functions.
Example of three hidden layer with
- 3312 input features
- 3... | @staticmethod
def loss(y_true, y_pred):
"""
:param y_true: (array) One hot encoded truth vector.
:param y_pred: (array) Prediction vector
:return: (flt)
"""
return np.mean((y_pred - y_true) ** 2)
@staticmethod
def prime(y_true, y_pred):
return y_p... | 256 | 256 | 4,511 | 5 | 251 | emielsteerneman/sparse-evolutionary-artificial-neural-networks | Tutorial-ECMLPKDD-2019-Scalable-Deep-Learning/set_mlp.py | Python | SET_MLP | SET_MLP | 170 | 564 | 170 | 170 | d9b7c1d4f6b8fb503fb93345653f6b22f536ef05 | bigcode/the-stack | train |
40b751ef342b0993b0d20585 | train | function | def find_first_pos(array, value):
idx = (np.abs(array - value)).argmin()
return idx
| def find_first_pos(array, value):
| idx = (np.abs(array - value)).argmin()
return idx
| out):
for i in range(out.shape[0]):
s = 0
for j in range(a.shape[0]):
s += a[j, rows[i]] * delta[j, cols[i]]
out[i] = s / a.shape[0]
def find_first_pos(array, value):
| 64 | 64 | 25 | 8 | 56 | emielsteerneman/sparse-evolutionary-artificial-neural-networks | Tutorial-ECMLPKDD-2019-Scalable-Deep-Learning/set_mlp.py | Python | find_first_pos | find_first_pos | 60 | 62 | 60 | 60 | cc096e36090d6cc78597ece20e256700aceaeddc | bigcode/the-stack | train |
d4c15cabcb722bb5e4886402 | train | function | def find_last_pos(array, value):
idx = (np.abs(array - value))[::-1].argmin()
return array.shape[0] - idx
| def find_last_pos(array, value):
| idx = (np.abs(array - value))[::-1].argmin()
return array.shape[0] - idx
| [0]):
s += a[j, rows[i]] * delta[j, cols[i]]
out[i] = s / a.shape[0]
def find_first_pos(array, value):
idx = (np.abs(array - value)).argmin()
return idx
def find_last_pos(array, value):
| 64 | 64 | 34 | 8 | 55 | emielsteerneman/sparse-evolutionary-artificial-neural-networks | Tutorial-ECMLPKDD-2019-Scalable-Deep-Learning/set_mlp.py | Python | find_last_pos | find_last_pos | 65 | 67 | 65 | 65 | 8498d10341c72b51e2462ee6225ab2416558c8fe | bigcode/the-stack | train |
df303120f42e1c1ff2f3018c | train | function | def load_fashion_mnist_data(noTrainingSamples,noTestingSamples):
np.random.seed(0)
data=np.load("../Tutorial-IJCAI-2019-Scalable-Deep-Learning/data/fashion_mnist.npz")
indexTrain=np.arange(data["X_train"].shape[0])
np.random.shuffle(indexTrain)
indexTest=np.arange(data["X_test"].shape[0])
np.... | def load_fashion_mnist_data(noTrainingSamples,noTestingSamples):
| np.random.seed(0)
data=np.load("../Tutorial-IJCAI-2019-Scalable-Deep-Learning/data/fashion_mnist.npz")
indexTrain=np.arange(data["X_train"].shape[0])
np.random.shuffle(indexTrain)
indexTest=np.arange(data["X_test"].shape[0])
np.random.shuffle(indexTest)
X_train=data["X_train"][indexTrain... | range(y_test.shape[0]):
if (np.argmax(activations[j]) == np.argmax(y_test[j])):
correctClassification += 1
accuracy = correctClassification / y_test.shape[0]
return accuracy, activations
def load_fashion_mnist_data(noTrainingSamples,noTestingSamples):
| 64 | 64 | 212 | 14 | 49 | emielsteerneman/sparse-evolutionary-artificial-neural-networks | Tutorial-ECMLPKDD-2019-Scalable-Deep-Learning/set_mlp.py | Python | load_fashion_mnist_data | load_fashion_mnist_data | 566 | 586 | 566 | 566 | da13660542654fa0dc9f7192d9b0840005823e75 | bigcode/the-stack | train |
55e08e5d3da9a49d5d9b3119 | train | class | class ReLU:
@staticmethod
def activation(z):
z[z < 0] = 0
return z
@staticmethod
def prime(z):
z[z < 0] = 0
z[z > 0] = 1
return z
| class ReLU:
@staticmethod
| def activation(z):
z[z < 0] = 0
return z
@staticmethod
def prime(z):
z[z < 0] = 0
z[z > 0] = 1
return z
| rows, ncols = A.shape
dtype = {'names': ['f{}'.format(i) for i in range(ncols)], 'formats': ncols * [A.dtype]}
return np.in1d(A.view(dtype), B.view(dtype)) # boolean return
class ReLU:
@staticmethod
| 64 | 64 | 63 | 8 | 55 | emielsteerneman/sparse-evolutionary-artificial-neural-networks | Tutorial-ECMLPKDD-2019-Scalable-Deep-Learning/set_mlp.py | Python | ReLU | ReLU | 88 | 98 | 88 | 89 | ae3ba771b574f6f5d5d0c27aa743cac27edad32d | bigcode/the-stack | train |
578e3f7931f19c613e5ed3f1 | train | function | def backpropagation_updates_Numpy(a, delta, rows, cols, out):
for i in range(out.shape[0]):
s = 0
for j in range(a.shape[0]):
s += a[j, rows[i]] * delta[j, cols[i]]
out[i] = s / a.shape[0]
| def backpropagation_updates_Numpy(a, delta, rows, cols, out):
| for i in range(out.shape[0]):
s = 0
for j in range(a.shape[0]):
s += a[j, rows[i]] * delta[j, cols[i]]
out[i] = s / a.shape[0]
| may encounter some "solvable" issues if you compile it in Windows.
import sparseoperations
import datetime
from keras.datasets import cifar10
from keras.utils import np_utils
from keras.preprocessing.image import ImageDataGenerator
def backpropagation_updates_Numpy(a, delta, rows, cols, out):
| 64 | 64 | 71 | 17 | 46 | emielsteerneman/sparse-evolutionary-artificial-neural-networks | Tutorial-ECMLPKDD-2019-Scalable-Deep-Learning/set_mlp.py | Python | backpropagation_updates_Numpy | backpropagation_updates_Numpy | 52 | 57 | 52 | 52 | e78296b1abf5dffebf92ca2d733c8400600ef4c6 | bigcode/the-stack | train |
e11646ccd64294f365c457bc | train | function | def array_intersect(A, B):
# this are for array intersection
nrows, ncols = A.shape
dtype = {'names': ['f{}'.format(i) for i in range(ncols)], 'formats': ncols * [A.dtype]}
return np.in1d(A.view(dtype), B.view(dtype)) # boolean return
| def array_intersect(A, B):
# this are for array intersection
| nrows, ncols = A.shape
dtype = {'names': ['f{}'.format(i) for i in range(ncols)], 'formats': ncols * [A.dtype]}
return np.in1d(A.view(dtype), B.view(dtype)) # boolean return
| sparse matrix with ", weights.getnnz(), " connections and ",
(weights.getnnz() / (noRows * noCols)) * 100, "% density level")
weights = weights.tocsr()
return weights
def array_intersect(A, B):
# this are for array intersection
| 64 | 64 | 74 | 16 | 47 | emielsteerneman/sparse-evolutionary-artificial-neural-networks | Tutorial-ECMLPKDD-2019-Scalable-Deep-Learning/set_mlp.py | Python | array_intersect | array_intersect | 81 | 85 | 81 | 82 | 56f33caec5d9646effb2d797eb16c438a6edc38e | bigcode/the-stack | train |
6c13a066f2f71db77ab3bdbf | train | function | def load_cifar10_data(noTrainingSamples,noTestingSamples):
np.random.seed(0)
# read CIFAR10 data
(x_train, y_train), (x_test, y_test) = cifar10.load_data()
y_train = np_utils.to_categorical(y_train, 10)
y_test = np_utils.to_categorical(y_test, 10)
x_train = x_train.astype('float32')
x_test... | def load_cifar10_data(noTrainingSamples,noTestingSamples):
| np.random.seed(0)
# read CIFAR10 data
(x_train, y_train), (x_test, y_test) = cifar10.load_data()
y_train = np_utils.to_categorical(y_train, 10)
y_test = np_utils.to_categorical(y_test, 10)
x_train = x_train.astype('float32')
x_test = x_test.astype('float32')
indexTrain = np.arange(x_t... | ],:]
Y_test=data["Y_test"][indexTest[0:noTestingSamples],:]
#normalize in 0..1
X_train = X_train.astype('float64') / 255.
X_test = X_test.astype('float64') / 255.
return X_train, Y_train, X_test, Y_test
def load_cifar10_data(noTrainingSamples,noTestingSamples):
| 85 | 85 | 285 | 13 | 71 | emielsteerneman/sparse-evolutionary-artificial-neural-networks | Tutorial-ECMLPKDD-2019-Scalable-Deep-Learning/set_mlp.py | Python | load_cifar10_data | load_cifar10_data | 588 | 616 | 588 | 588 | 7be4c17ad70d6b5e5cc89bf4f19357d06702b8b4 | bigcode/the-stack | train |
d8eb753d4a1056a520522abf | train | class | class MSE:
def __init__(self, activation_fn=None):
"""
:param activation_fn: Class object of the activation function.
"""
if activation_fn:
self.activation_fn = activation_fn
else:
self.activation_fn = NoActivation
def activation(self, z):
... | class MSE:
| def __init__(self, activation_fn=None):
"""
:param activation_fn: Class object of the activation function.
"""
if activation_fn:
self.activation_fn = activation_fn
else:
self.activation_fn = NoActivation
def activation(self, z):
return sel... | ] = 1
return z
class Sigmoid:
@staticmethod
def activation(z):
return 1 / (1 + np.exp(-z))
@staticmethod
def prime(z):
return Sigmoid.activation(z) * (1 - Sigmoid.activation(z))
class MSE:
| 64 | 64 | 206 | 4 | 60 | emielsteerneman/sparse-evolutionary-artificial-neural-networks | Tutorial-ECMLPKDD-2019-Scalable-Deep-Learning/set_mlp.py | Python | MSE | MSE | 111 | 142 | 111 | 111 | f146441bb9455efc7ea4f950d4ff21cd866c2af9 | bigcode/the-stack | train |
3703448ba6a755e7d18c0f2a | train | function | def downgrade():
"""Downgrade database schema and/or data back to the previous revision."""
# recreate Request table (query generated with SHOW CREATE TABLE)
op.execute("""
CREATE TABLE `requests` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`request_type` enum('documentation','interview','popula... | def downgrade():
| """Downgrade database schema and/or data back to the previous revision."""
# recreate Request table (query generated with SHOW CREATE TABLE)
op.execute("""
CREATE TABLE `requests` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`request_type` enum('documentation','interview','population sample')
... | ", "auditable_type"),
("custom_attribute_definitions", "definition_type"),
("fulltext_record_properties", "type"),
("notifications", "object_type"),
("object_documents", "documentable_type"),
("object_owners", "ownable_type"),
("object_people", "personable_type"),
("relationshi... | 136 | 136 | 454 | 3 | 133 | Killswitchz/ggrc-core | src/ggrc/migrations/versions/20170719165433_1e3f798a4cc6_remove_request_model.py | Python | downgrade | downgrade | 45 | 87 | 45 | 45 | 17dd4aa67c49a4cf83a79a7cb9573b970c580e72 | bigcode/the-stack | train |
3e8fd81239526824ac2fa4e6 | train | function | def upgrade():
"""Upgrade database schema and/or data, creating a new revision."""
op.execute("DROP TABLE `requests`")
replace(op, "audits", "object_type",
old_value="Request", new_value="Assessment")
deletions_required = (
("audit_objects", "auditable_type"),
("custom_attribute_definiti... | def upgrade():
| """Upgrade database schema and/or data, creating a new revision."""
op.execute("DROP TABLE `requests`")
replace(op, "audits", "object_type",
old_value="Request", new_value="Assessment")
deletions_required = (
("audit_objects", "auditable_type"),
("custom_attribute_definitions", "definiti... | ic import op
from ggrc.migrations.utils.cleanup import replace
from ggrc.migrations.utils.cleanup import delete
# revision identifiers, used by Alembic.
revision = '1e3f798a4cc6'
down_revision = '47d3cb39bad7'
def upgrade():
| 64 | 64 | 193 | 3 | 61 | Killswitchz/ggrc-core | src/ggrc/migrations/versions/20170719165433_1e3f798a4cc6_remove_request_model.py | Python | upgrade | upgrade | 19 | 42 | 19 | 19 | d77a06bb88828cf7496b723636136e6f94b98b26 | bigcode/the-stack | train |
dc7367ce63fd00341e2c9c52 | train | function | def format_convert_test():
# mass format [2, 3, 6]
masses = [2, 3, 6]
# position format (1, 1, 2, 2, 2, 3, 3, 3, 3, 3, 3)
positions = convert_masses_to_positions(masses)
# boundary_string ({0},{1},{0},{0},{1},{0},{0},{0},{0},{0},)
boundary_string = boundary_string_from_masses(masses)
print(p... | def format_convert_test():
# mass format [2, 3, 6]
| masses = [2, 3, 6]
# position format (1, 1, 2, 2, 2, 3, 3, 3, 3, 3, 3)
positions = convert_masses_to_positions(masses)
# boundary_string ({0},{1},{0},{0},{1},{0},{0},{0},{0},{0},)
boundary_string = boundary_string_from_masses(masses)
print(positions)
print(boundary_string)
| 3f, S=%.3f" % (pk(h, gold, one_minus=True),
WD(h, gold, one_minus=True, window_size=2), B(h, gold), S(h, gold)))
def format_convert_test():
# mass format [2, 3, 6]
| 63 | 64 | 127 | 18 | 45 | liuxuan320/text_segmentation_evaluation | single_test.py | Python | format_convert_test | format_convert_test | 22 | 30 | 22 | 23 | 1502c481b3856a8c8108f1db367d53ba6012e224 | bigcode/the-stack | train |
50c20d69ba5babeefa8a8031 | train | function | def example_in_paper_test():
gold = [2, 3, 6]
h_list = [[5, 6], [2, 2, 7], [2, 3, 3, 3], [1, 1, 3, 1, 5]]
for n, h in enumerate(h_list):
cm = boundary_confusion_matrix(h, gold)
print("第%d次实验" % int(n + 1))
# The P, R and F values are different from those in the normal method because ... | def example_in_paper_test():
| gold = [2, 3, 6]
h_list = [[5, 6], [2, 2, 7], [2, 3, 3, 3], [1, 1, 3, 1, 5]]
for n, h in enumerate(h_list):
cm = boundary_confusion_matrix(h, gold)
print("第%d次实验" % int(n + 1))
# The P, R and F values are different from those in the normal method because it will correct the near miss... |
from segeval.similarity.boundary import boundary_similarity as B
from segeval.similarity.segmentation import segmentation_similarity as S
from segeval.format import *
from segeval.similarity import boundary_confusion_matrix
from segeval.ml import precision, recall, fmeasure
def example_in_paper_test():
| 68 | 68 | 227 | 7 | 60 | liuxuan320/text_segmentation_evaluation | single_test.py | Python | example_in_paper_test | example_in_paper_test | 10 | 19 | 10 | 10 | 6867023b9fa7fc0893165d7d60f49ce3f9ee0fd1 | bigcode/the-stack | train |
ec60bc32612963c1284d20e9 | train | function | def resnet44():
return ResNet(BasicBlock, [7, 7, 7])
| def resnet44():
| return ResNet(BasicBlock, [7, 7, 7])
| (hist1+hist2+hist3)
return out#,hist
def resnet20():
return ResNet(BasicBlock, [3, 3, 3])
def resnet32():
return ResNet(BasicBlock, [5, 5, 5])
def resnet44():
| 64 | 64 | 22 | 5 | 59 | hecate64/CSQ | modelscifar/resnet20hist.py | Python | resnet44 | resnet44 | 167 | 168 | 167 | 167 | d0d9baf7864ee905c2603d5b33f0120d97c8e33b | bigcode/the-stack | train |
7a8afb156400818756cc6239 | train | class | class BasicBlock(nn.Module):
expansion = 1
def __init__(self, in_planes, planes, stride=1, option='A'):
super(BasicBlock, self).__init__()
self.conv1 = conv(in_planes, planes, kernel_size=3, stride=stride, padding=1, bias=False)
self.bn1 = nn.BatchNorm2d(planes)
self.conv2 = con... | class BasicBlock(nn.Module):
| expansion = 1
def __init__(self, in_planes, planes, stride=1, option='A'):
super(BasicBlock, self).__init__()
self.conv1 = conv(in_planes, planes, kernel_size=3, stride=stride, padding=1, bias=False)
self.bn1 = nn.BatchNorm2d(planes)
self.conv2 = conv(planes, planes, kernel_size... | =padding, bias=bias, nbits=nbits)
def _weights_init(m):
classname = m.__class__.__name__
#print(classname)
if isinstance(m, nn.Linear) or isinstance(m, nn.Conv2d):
init.kaiming_normal_(m.weight)
class LambdaLayer(nn.Module):
def __init__(self, lambd):
super(LambdaLayer, self).__init... | 117 | 117 | 390 | 6 | 111 | hecate64/CSQ | modelscifar/resnet20hist.py | Python | BasicBlock | BasicBlock | 61 | 94 | 61 | 61 | f8868dd47d5d74f85de56d082a24c7e96ade2df9 | bigcode/the-stack | train |
36a01b11d74a026ec9f0499f | train | function | def resnet110():
return ResNet(BasicBlock, [18, 18, 18])
| def resnet110():
| return ResNet(BasicBlock, [18, 18, 18])
| ResNet(BasicBlock, [5, 5, 5])
def resnet44():
return ResNet(BasicBlock, [7, 7, 7])
def resnet56():
return ResNet(BasicBlock, [9, 9, 9])
def resnet110():
| 64 | 64 | 22 | 5 | 59 | hecate64/CSQ | modelscifar/resnet20hist.py | Python | resnet110 | resnet110 | 175 | 176 | 175 | 175 | a7320ea2c109103e27272ebffb697d9a079a69a9 | bigcode/the-stack | train |
e74c5ef5feccaaa7d3abfbda | train | class | class LambdaLayer(nn.Module):
def __init__(self, lambd):
super(LambdaLayer, self).__init__()
self.lambd = lambd
def forward(self, x):
return self.lambd(x)
| class LambdaLayer(nn.Module):
| def __init__(self, lambd):
super(LambdaLayer, self).__init__()
self.lambd = lambd
def forward(self, x):
return self.lambd(x)
| bias=bias, nbits=nbits)
def _weights_init(m):
classname = m.__class__.__name__
#print(classname)
if isinstance(m, nn.Linear) or isinstance(m, nn.Conv2d):
init.kaiming_normal_(m.weight)
class LambdaLayer(nn.Module):
| 64 | 64 | 50 | 6 | 58 | hecate64/CSQ | modelscifar/resnet20hist.py | Python | LambdaLayer | LambdaLayer | 52 | 58 | 52 | 52 | 31c41e5723b911369ee9f539c39c78102219f37b | bigcode/the-stack | train |
b4d1a78211f1206bb2e6a694 | train | function | def resnet20():
return ResNet(BasicBlock, [3, 3, 3])
| def resnet20():
| return ResNet(BasicBlock, [3, 3, 3])
| ), -1)
out = self.linear(out)
hist = hist1+hist2+hist3+hist4+hist5+hist6+hist7+hist8+hist9
#print(hist1+hist2+hist3)
return out#,hist
def resnet20():
| 64 | 64 | 22 | 5 | 58 | hecate64/CSQ | modelscifar/resnet20hist.py | Python | resnet20 | resnet20 | 159 | 160 | 159 | 159 | ff2adbdcff30b5dc260e9b376ffdce0dfec38f07 | bigcode/the-stack | train |
c92aa08adb26336dabbaac1a | train | function | def resnet56():
return ResNet(BasicBlock, [9, 9, 9])
| def resnet56():
| return ResNet(BasicBlock, [9, 9, 9])
| ResNet(BasicBlock, [3, 3, 3])
def resnet32():
return ResNet(BasicBlock, [5, 5, 5])
def resnet44():
return ResNet(BasicBlock, [7, 7, 7])
def resnet56():
| 64 | 64 | 22 | 5 | 59 | hecate64/CSQ | modelscifar/resnet20hist.py | Python | resnet56 | resnet56 | 171 | 172 | 171 | 171 | e1f3f95929cada8e53b96d5cdeea78f5e9260237 | bigcode/the-stack | train |
17ece859435f830a798d1061 | train | function | def resnet32():
return ResNet(BasicBlock, [5, 5, 5])
| def resnet32():
| return ResNet(BasicBlock, [5, 5, 5])
| +hist4+hist5+hist6+hist7+hist8+hist9
#print(hist1+hist2+hist3)
return out#,hist
def resnet20():
return ResNet(BasicBlock, [3, 3, 3])
def resnet32():
| 64 | 64 | 22 | 5 | 59 | hecate64/CSQ | modelscifar/resnet20hist.py | Python | resnet32 | resnet32 | 163 | 164 | 163 | 163 | e7f420e57bf814a7caa1dfaafd7f62973a02a84c | bigcode/the-stack | train |
58752fdc58944ed2887fe1a3 | train | function | def conv(input, output, kernel_size=3, stride=1, padding=1, bias=False,nbits=2):
return Q.Conv2dLSQ_sym(input, output, kernel_size=kernel_size, stride=stride, padding=padding, bias=bias, nbits=nbits)
| def conv(input, output, kernel_size=3, stride=1, padding=1, bias=False,nbits=2):
| return Q.Conv2dLSQ_sym(input, output, kernel_size=kernel_size, stride=stride, padding=padding, bias=bias, nbits=nbits)
| __ = ['ResNet', 'resnet20', 'resnet32', 'resnet44', 'resnet56', 'resnet110', 'resnet1202']
def conv(input, output, kernel_size=3, stride=1, padding=1, bias=False,nbits=2):
| 64 | 64 | 64 | 27 | 37 | hecate64/CSQ | modelscifar/resnet20hist.py | Python | conv | conv | 40 | 41 | 40 | 40 | 9976fe4bb9452e7b3b7c6898a69e4e73ec4a3776 | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.