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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1fd5b56d3ae5746c3eb6d3d9 | train | function | def setup_module(module):
os.makedirs(tmp_aws_dir)
| def setup_module(module):
| os.makedirs(tmp_aws_dir)
| standard_library
standard_library.install_aliases()
import configparser
import os
import shutil
import tempfile
from unittest.mock import patch, MagicMock
from byu_awslogin.util import data_cache
tmp_aws_dir = "{}/.aws".format(tempfile.gettempdir())
def setup_module(module):
| 64 | 64 | 13 | 5 | 59 | Gi60s/awslogin | test/byu_awslogin/util/test_data_cache.py | Python | setup_module | setup_module | 19 | 20 | 19 | 19 | 58853936958b1cc4799e46ab00d3ec9ed8f5522f | bigcode/the-stack | train |
2478fce2e4b4919bf4cff5e4 | train | function | @patch("byu_awslogin.util.data_cache._aws_file")
@patch("byu_awslogin.util.data_cache.os.path.exists")
def test_cache_adfs_auth(mock_exists, mock_aws_file):
mock_exists.return_value = True
creds_file = "{}/credentials".format(tmp_aws_dir)
mock_aws_file.return_value = creds_file
test_adfs_auth_val = b"t... | @patch("byu_awslogin.util.data_cache._aws_file")
@patch("byu_awslogin.util.data_cache.os.path.exists")
def test_cache_adfs_auth(mock_exists, mock_aws_file):
| mock_exists.return_value = True
creds_file = "{}/credentials".format(tmp_aws_dir)
mock_aws_file.return_value = creds_file
test_adfs_auth_val = b"testing\ntesting"
data_cache.cache_adfs_auth(test_adfs_auth_val)
assert test_adfs_auth_val == data_cache.load_cached_adfs_auth()
| _file(file):
config = configparser.ConfigParser()
config.read(file)
return config
@patch("byu_awslogin.util.data_cache._aws_file")
@patch("byu_awslogin.util.data_cache.os.path.exists")
def test_cache_adfs_auth(mock_exists, mock_aws_file):
| 64 | 64 | 119 | 44 | 19 | Gi60s/awslogin | test/byu_awslogin/util/test_data_cache.py | Python | test_cache_adfs_auth | test_cache_adfs_auth | 33 | 43 | 33 | 35 | 5ca1901ee9738824dbe85a0d8dd9feee093f9de8 | bigcode/the-stack | train |
4815e8e2f8f7c676cf6d5161 | train | function | @patch("byu_awslogin.util.data_cache._open_config_file")
def test_get_status(mock_open_config_file, capsys):
test_config = """
[default]
adfs_role = ReadOnly@fake-account
adfs_expires = 01-02-2017 15:03
[profile foobar]
adfs_role = Admin@fake-account
adfs_expires = 02-05-2018 16:42
"""
configfile = configp... | @patch("byu_awslogin.util.data_cache._open_config_file")
def test_get_status(mock_open_config_file, capsys):
| test_config = """
[default]
adfs_role = ReadOnly@fake-account
adfs_expires = 01-02-2017 15:03
[profile foobar]
adfs_role = Admin@fake-account
adfs_expires = 02-05-2018 16:42
"""
configfile = configparser.ConfigParser()
configfile.read_string(test_config)
mock_open_config_file.return_value = configf... | _config_file.has_section.call_count == 1
assert mock_config_file.has_option.call_count == 1
assert mock_config_file.__getitem__.call_count == 1
@patch("byu_awslogin.util.data_cache._open_config_file")
def test_get_status(mock_open_config_file, capsys):
| 65 | 65 | 217 | 28 | 36 | Gi60s/awslogin | test/byu_awslogin/util/test_data_cache.py | Python | test_get_status | test_get_status | 131 | 158 | 131 | 132 | f5f64f7c681791e604f694f882e6f08951ac78ad | bigcode/the-stack | train |
f579589276f89dbe1e92b934 | train | function | @patch("byu_awslogin.util.data_cache._aws_file")
@patch("byu_awslogin.util.data_cache.os.path.exists")
def test_remove_cached_adfs_auth(mock_exists, mock_aws_file):
mock_exists.return_value = True
creds_file = "{}/credentials".format(tmp_aws_dir)
mock_aws_file.return_value = creds_file
test_adfs_auth_v... | @patch("byu_awslogin.util.data_cache._aws_file")
@patch("byu_awslogin.util.data_cache.os.path.exists")
def test_remove_cached_adfs_auth(mock_exists, mock_aws_file):
| mock_exists.return_value = True
creds_file = "{}/credentials".format(tmp_aws_dir)
mock_aws_file.return_value = creds_file
test_adfs_auth_val = b"testing\ntesting"
data_cache.cache_adfs_auth(test_adfs_auth_val)
data_cache.remove_cached_adfs_auth()
written_config = read_config_file(creds_fil... | _auth_val)
assert test_adfs_auth_val == data_cache.load_cached_adfs_auth()
@patch("byu_awslogin.util.data_cache._aws_file")
@patch("byu_awslogin.util.data_cache.os.path.exists")
def test_remove_cached_adfs_auth(mock_exists, mock_aws_file):
| 64 | 64 | 161 | 45 | 19 | Gi60s/awslogin | test/byu_awslogin/util/test_data_cache.py | Python | test_remove_cached_adfs_auth | test_remove_cached_adfs_auth | 46 | 61 | 46 | 48 | e626dcee457b3e935274eb32dc8dfdd14839278c | bigcode/the-stack | train |
9bd9b53262001fb404dd61c8 | train | function | def read_config_file(file):
config = configparser.ConfigParser()
config.read(file)
return config
| def read_config_file(file):
| config = configparser.ConfigParser()
config.read(file)
return config
| MagicMock
from byu_awslogin.util import data_cache
tmp_aws_dir = "{}/.aws".format(tempfile.gettempdir())
def setup_module(module):
os.makedirs(tmp_aws_dir)
def teardown_module(module):
shutil.rmtree(tmp_aws_dir)
def read_config_file(file):
| 64 | 64 | 23 | 6 | 58 | Gi60s/awslogin | test/byu_awslogin/util/test_data_cache.py | Python | read_config_file | read_config_file | 27 | 30 | 27 | 27 | 68986879afb8440298ef105b446e2fa65b88cc00 | bigcode/the-stack | train |
9752fd8ae9f6d5e7b4f3d215 | train | function | def teardown_module(module):
shutil.rmtree(tmp_aws_dir)
| def teardown_module(module):
| shutil.rmtree(tmp_aws_dir)
| import os
import shutil
import tempfile
from unittest.mock import patch, MagicMock
from byu_awslogin.util import data_cache
tmp_aws_dir = "{}/.aws".format(tempfile.gettempdir())
def setup_module(module):
os.makedirs(tmp_aws_dir)
def teardown_module(module):
| 64 | 64 | 14 | 5 | 59 | Gi60s/awslogin | test/byu_awslogin/util/test_data_cache.py | Python | teardown_module | teardown_module | 23 | 24 | 23 | 23 | 503d5bcb854e5d9dd15172eea6b447288a3865e4 | bigcode/the-stack | train |
bd426698a70907069b91a5dc | train | function | def format_body(signatories, model_payload):
# type: (List[Dict[str, Any]], Dict[str, Any]) -> str
def append_separator(i, len_sig):
# type: (int, int) -> None
if i + 1 == len(signatories):
result.append('.')
elif i + 2 == len(signatories):
result.append(' and')
... | def format_body(signatories, model_payload):
# type: (List[Dict[str, Any]], Dict[str, Any]) -> str
| def append_separator(i, len_sig):
# type: (int, int) -> None
if i + 1 == len(signatories):
result.append('.')
elif i + 2 == len(signatories):
result.append(' and')
elif i + 3 != len(signatories):
result.append(',')
result = ["The {}".format(mo... | UserProfile
from django.http import HttpRequest, HttpResponse
from six import text_type
from six.moves import range
from typing import Any, Dict, List, Optional, Tuple, Union
def format_body(signatories, model_payload):
# type: (List[Dict[str, Any]], Dict[str, Any]) -> str
| 69 | 69 | 230 | 29 | 39 | roberthoenig/zulip | zerver/webhooks/hellosign/view.py | Python | format_body | format_body | 14 | 36 | 14 | 15 | 63892e8fcc8b2a0035be904aa53f533655f94df7 | bigcode/the-stack | train |
2588f28daf98ff70d2199a02 | train | function | def ready_payload(signatories, payload):
# type: (List[Dict[str, Any]], Dict[str, Dict[str, Any]]) -> Dict[str, Any]
model_payload = {'contract_title': payload['signature_request']['title']}
for i, signatory in enumerate(signatories):
model_payload['name_{}'.format(i)] = signatory['signer_name']
... | def ready_payload(signatories, payload):
# type: (List[Dict[str, Any]], Dict[str, Dict[str, Any]]) -> Dict[str, Any]
| model_payload = {'contract_title': payload['signature_request']['title']}
for i, signatory in enumerate(signatories):
model_payload['name_{}'.format(i)] = signatory['signer_name']
model_payload['status_{}'.format(i)] = signatory['status_code']
return model_payload
| was just {} by {}".format(status, name))
append_separator(i, len(signatories))
result = ''.join(result)
return result
def ready_payload(signatories, payload):
# type: (List[Dict[str, Any]], Dict[str, Dict[str, Any]]) -> Dict[str, Any]
| 64 | 64 | 100 | 34 | 29 | roberthoenig/zulip | zerver/webhooks/hellosign/view.py | Python | ready_payload | ready_payload | 38 | 44 | 38 | 39 | add5428e3f22c5cb792ae955fcea84820b827499 | bigcode/the-stack | train |
611cc3b559b7fc768ea07d87 | train | function | @api_key_only_webhook_view('HelloSign')
@has_request_variables
def api_hellosign_webhook(request, user_profile,
payload=REQ(argument_type='body'),
stream=REQ(default='hellosign'),
topic=REQ(default=None)):
# type: (HttpRequest, UserProfil... | @api_key_only_webhook_view('HelloSign')
@has_request_variables
def api_hellosign_webhook(request, user_profile,
payload=REQ(argument_type='body'),
stream=REQ(default='hellosign'),
topic=REQ(default=None)):
# type: (HttpRequest, UserProfil... | try:
model_payload = ready_payload(payload['signature_request']['signatures'],
payload)
except KeyError as e:
return json_error(_("Missing key {} in JSON").format(str(e)))
body = format_body(payload['signature_request']['signatures'], model_payload)
... | @api_key_only_webhook_view('HelloSign')
@has_request_variables
def api_hellosign_webhook(request, user_profile,
payload=REQ(argument_type='body'),
stream=REQ(default='hellosign'),
topic=REQ(default=None)):
# type: (HttpRequest, UserProfil... | 84 | 64 | 177 | 84 | 0 | roberthoenig/zulip | zerver/webhooks/hellosign/view.py | Python | api_hellosign_webhook | api_hellosign_webhook | 46 | 63 | 46 | 52 | e527d572edce7473fea0e08e83955e98ba5510b8 | bigcode/the-stack | train |
afb01bdaa3a8e3476018187d | train | class | class MWUEncoder(Executor):
def __init__(self, greetings: str, *args, **kwargs):
super().__init__(*args, **kwargs)
self._greetings = greetings
@requests
def encode(self, *args, **kwargs) -> Any:
pass
| class MWUEncoder(Executor):
| def __init__(self, greetings: str, *args, **kwargs):
super().__init__(*args, **kwargs)
self._greetings = greetings
@requests
def encode(self, *args, **kwargs) -> Any:
pass
| from typing import Any
from jina import Executor, requests
class MWUEncoder(Executor):
| 19 | 64 | 63 | 7 | 11 | Rohitpandit021/jina | tests/daemon/unit/api/endpoints/mwu_encoder.py | Python | MWUEncoder | MWUEncoder | 6 | 13 | 6 | 6 | 751bec08e021bc83bdb8a109aaa485deaa6a81ba | bigcode/the-stack | train |
ed3f8f542aea5525a16a85b3 | train | function | def get_afu_ids(device_name):
return map(
read_line,
glob.glob(
os.path.join(
PCI_DEVICES_PATH_PATTERN, "fpga",
device_name, "intel-fpga-port.*", "afu_id")
)
)
| def get_afu_ids(device_name):
| return map(
read_line,
glob.glob(
os.path.join(
PCI_DEVICES_PATH_PATTERN, "fpga",
device_name, "intel-fpga-port.*", "afu_id")
)
)
| PCI_DEVICES_PATH, bdf)
if paths:
p0 = paths[0]
path = find_pf_by_vf(p0) if is_vf(p0) else p0
return get_bdf_by_path(path)
return bdf
def get_afu_ids(device_name):
| 64 | 64 | 56 | 8 | 55 | NeCTAR-RC/cyborg | cyborg/accelerator/drivers/fpga/intel/sysinfo.py | Python | get_afu_ids | get_afu_ids | 168 | 176 | 168 | 168 | 96c2880fcf1646df8d86def8af8a99c945b0f3aa | bigcode/the-stack | train |
0d6d84885bf477d147774c64 | train | function | def get_link_targets(links):
return map(
lambda p:
os.path.realpath(
os.path.join(os.path.dirname(p), os.readlink(p))),
links)
| def get_link_targets(links):
| return map(
lambda p:
os.path.realpath(
os.path.join(os.path.dirname(p), os.readlink(p))),
links)
| pgas_by_know_list():
return filter(
lambda p: (
read_line(os.path.join(p, "vendor")),
read_line(os.path.join(p, "device"))
) in KNOWN_FPGAS,
glob.glob(PCI_DEVICES_PATH_PATTERN))
def get_link_targets(links):
| 64 | 64 | 38 | 7 | 57 | NeCTAR-RC/cyborg | cyborg/accelerator/drivers/fpga/intel/sysinfo.py | Python | get_link_targets | get_link_targets | 87 | 92 | 87 | 87 | ba2634de570e6e6af1823ed19ddb8ee3a0421ebc | bigcode/the-stack | train |
2a531b30f8f87769fbc9d24d | train | function | def get_traits(device_name, product_id, vf=True):
"""Generate traits for devices.
: param devices_name: name of PF/VF, for example, "intel-fpga-dev.0".
: param product_id: product id of PF/VF, for example, "0x09c4".
: param vf: True if device_name is a VF, otherwise False.
"""
# "CUSTOM_PROGRAMM... | def get_traits(device_name, product_id, vf=True):
| """Generate traits for devices.
: param devices_name: name of PF/VF, for example, "intel-fpga-dev.0".
: param product_id: product id of PF/VF, for example, "0x09c4".
: param vf: True if device_name is a VF, otherwise False.
"""
# "CUSTOM_PROGRAMMABLE" not support at present
traits = []
i... | )
def get_region_ids(device_name):
return map(
read_line,
glob.glob(
os.path.join(
SYS_FPGA, device_name,
"intel-fpga-fme.*", "pr/interface_id")
)
)
def get_traits(device_name, product_id, vf=True):
| 64 | 64 | 204 | 12 | 52 | NeCTAR-RC/cyborg | cyborg/accelerator/drivers/fpga/intel/sysinfo.py | Python | get_traits | get_traits | 190 | 207 | 190 | 190 | 0ff66fa8bbccbd694ce1ac8db073eca8f7f4e5de | bigcode/the-stack | train |
ad4643cc9fc8bce37bdf12b9 | train | function | def _generate_dep_list(fpga, pf_has_vf):
driver_dep = driver_deployable.DriverDeployable()
driver_dep.attribute_list = _generate_attribute_list(fpga)
driver_dep.attach_handle_list = []
# pf without sriov enabled.
if not pf_has_vf:
driver_dep.num_accelerators = 1
driver_dep.attach_han... | def _generate_dep_list(fpga, pf_has_vf):
| driver_dep = driver_deployable.DriverDeployable()
driver_dep.attribute_list = _generate_attribute_list(fpga)
driver_dep.attach_handle_list = []
# pf without sriov enabled.
if not pf_has_vf:
driver_dep.num_accelerators = 1
driver_dep.attach_handle_list = \
[_generate_attac... | (fpga):
driver_cpid = driver_controlpath_id.DriverControlPathID()
driver_cpid.cpid_type = "PCI"
driver_cpid.cpid_info = utils.pci_str_to_json(fpga["devices"])
return driver_cpid
def _generate_dep_list(fpga, pf_has_vf):
| 66 | 66 | 222 | 13 | 52 | NeCTAR-RC/cyborg | cyborg/accelerator/drivers/fpga/intel/sysinfo.py | Python | _generate_dep_list | _generate_dep_list | 283 | 304 | 283 | 283 | 4f4242a84de20d5e47d43e3061157ec0704fb214 | bigcode/the-stack | train |
269d3ce015658a2f21300f18 | train | function | def is_fpga(p):
infos = (read_line(os.path.join(p, "vendor")),
read_line(os.path.join(p, "device")))
if infos in KNOWN_FPGAS:
return os.path.realpath(p)
| def is_fpga(p):
| infos = (read_line(os.path.join(p, "vendor")),
read_line(os.path.join(p, "device")))
if infos in KNOWN_FPGAS:
return os.path.realpath(p)
| _HANDLER = {}
DEVICE_EXPOSED = ["vendor", "device"]
PRODUCT_MAP = {"0x09c4": "PAC_ARRIA10"}
DRIVER_NAME = "intel"
def read_line(filename):
with open(filename) as f:
return f.readline().strip()
def is_fpga(p):
| 64 | 64 | 49 | 6 | 58 | NeCTAR-RC/cyborg | cyborg/accelerator/drivers/fpga/intel/sysinfo.py | Python | is_fpga | is_fpga | 64 | 68 | 64 | 64 | 21de15547255d32cb78900f6de12283978fa97be | bigcode/the-stack | train |
38583fddfe39228b05edc8e3 | train | function | def get_region_ids(device_name):
return map(
read_line,
glob.glob(
os.path.join(
SYS_FPGA, device_name,
"intel-fpga-fme.*", "pr/interface_id")
)
)
| def get_region_ids(device_name):
| return map(
read_line,
glob.glob(
os.path.join(
SYS_FPGA, device_name,
"intel-fpga-fme.*", "pr/interface_id")
)
)
|
def get_afu_ids(device_name):
return map(
read_line,
glob.glob(
os.path.join(
PCI_DEVICES_PATH_PATTERN, "fpga",
device_name, "intel-fpga-port.*", "afu_id")
)
)
def get_region_ids(device_name):
| 64 | 64 | 51 | 7 | 57 | NeCTAR-RC/cyborg | cyborg/accelerator/drivers/fpga/intel/sysinfo.py | Python | get_region_ids | get_region_ids | 179 | 187 | 179 | 179 | 3a8db3c195c953a1ce33adea48f84855711656e8 | bigcode/the-stack | train |
5b453d9cb541205caf79fa40 | train | function | def split_bdf(bdf):
return ["0x" + v for v in bdf.replace(".", ":").rsplit(":")[1:]]
| def split_bdf(bdf):
| return ["0x" + v for v in bdf.replace(".", ":").rsplit(":")[1:]]
| BDF_PATTERN.match(bdf) else False
def get_bdf_by_path(path):
bdf = os.path.basename(path)
if is_bdf(bdf):
return bdf
return os.path.basename(os.readlink(os.path.join(path, "device")))
def split_bdf(bdf):
| 63 | 64 | 31 | 7 | 56 | NeCTAR-RC/cyborg | cyborg/accelerator/drivers/fpga/intel/sysinfo.py | Python | split_bdf | split_bdf | 155 | 156 | 155 | 155 | 14f2ab39c721f047d660b0f2dfd244289e40a357 | bigcode/the-stack | train |
770aa87b93928319c4d82d75 | train | function | def all_vf_fpgas():
return [dev.rsplit("/", 2)[0] for dev in
glob.glob(os.path.join(SYS_FPGA, "*/device/physfn"))]
| def all_vf_fpgas():
| return [dev.rsplit("/", 2)[0] for dev in
glob.glob(os.path.join(SYS_FPGA, "*/device/physfn"))]
| pga", "*")
return set(get_link_targets(find_fpgas_by_know_list())) | set(
map(lambda p: p.rsplit("/", 2)[0],
get_link_targets(glob.glob(os.path.join(SYS_FPGA, "*")))))
def all_vf_fpgas():
| 63 | 64 | 43 | 8 | 55 | NeCTAR-RC/cyborg | cyborg/accelerator/drivers/fpga/intel/sysinfo.py | Python | all_vf_fpgas | all_vf_fpgas | 102 | 104 | 102 | 102 | 0dafcbaa157fd8fd9ef58225bd3a56f5a6e8e235 | bigcode/the-stack | train |
6157ea4cb70b61fe842b543c | train | function | def _generate_controlpath_id(fpga):
driver_cpid = driver_controlpath_id.DriverControlPathID()
driver_cpid.cpid_type = "PCI"
driver_cpid.cpid_info = utils.pci_str_to_json(fpga["devices"])
return driver_cpid
| def _generate_controlpath_id(fpga):
| driver_cpid = driver_controlpath_id.DriverControlPathID()
driver_cpid.cpid_type = "PCI"
driver_cpid.cpid_info = utils.pci_str_to_json(fpga["devices"])
return driver_cpid
| _info)
driver_device_obj.type = fpga["type"]
driver_device_obj.controlpath_id = _generate_controlpath_id(fpga)
driver_device_obj.deployable_list = _generate_dep_list(fpga, pf_has_vf)
return driver_device_obj
def _generate_controlpath_id(fpga):
| 64 | 64 | 59 | 9 | 54 | NeCTAR-RC/cyborg | cyborg/accelerator/drivers/fpga/intel/sysinfo.py | Python | _generate_controlpath_id | _generate_controlpath_id | 276 | 280 | 276 | 276 | 1e82bcf1893c6e4e5717686683010fc003d6d27b | bigcode/the-stack | train |
ab7c599fcfde6fab760077fe | train | function | def fpga_device(path):
infos = {}
# NOTE "In 3.x, os.path.walk is removed in favor of os.walk."
for (dirpath, dirnames, filenames) in os.walk(path):
for filename in filenames:
if filename in DEVICE_EXPOSED:
key = DEVICE_FILE_MAP.get(filename) or filename
... | def fpga_device(path):
| infos = {}
# NOTE "In 3.x, os.path.walk is removed in favor of os.walk."
for (dirpath, dirnames, filenames) in os.walk(path):
for filename in filenames:
if filename in DEVICE_EXPOSED:
key = DEVICE_FILE_MAP.get(filename) or filename
if key in DEVICE_FILE_H... | = "CUSTOM_FPGA_FUNCTION_ID_INTEL_" + i.upper()
traits.append(trait)
for i in get_region_ids(device_name):
trait = "CUSTOM_FPGA_REGION_INTEL_" + i.upper()
traits.append(trait)
return {"traits": traits}
def fpga_device(path):
| 64 | 64 | 130 | 6 | 58 | NeCTAR-RC/cyborg | cyborg/accelerator/drivers/fpga/intel/sysinfo.py | Python | fpga_device | fpga_device | 210 | 224 | 210 | 210 | 2165d69e4c58d2d15afdff1d5db77c4c24280f01 | bigcode/the-stack | train |
5c23bf37c70ff45ca76271df | train | function | def all_vfs_in_pf_fpgas(pf_path):
return get_link_targets(
glob.glob(os.path.join(pf_path, "virtfn*")))
| def all_vfs_in_pf_fpgas(pf_path):
| return get_link_targets(
glob.glob(os.path.join(pf_path, "virtfn*")))
| "*/device")):
maps[os.path.realpath(f)] = os.path.dirname(f)
return maps
def bdf_path_map():
return dict(map(lambda f: (os.path.basename(f), f), all_fpgas()))
def all_vfs_in_pf_fpgas(pf_path):
| 63 | 64 | 34 | 13 | 50 | NeCTAR-RC/cyborg | cyborg/accelerator/drivers/fpga/intel/sysinfo.py | Python | all_vfs_in_pf_fpgas | all_vfs_in_pf_fpgas | 123 | 125 | 123 | 123 | abcb6ac4f60e9dd78907fa3aee9765ea7e57b364 | bigcode/the-stack | train |
5ab43d8a55e917edbabcabf8 | train | function | def all_fpgas():
# glob.glob1("/sys/class/fpga", "*")
return set(get_link_targets(find_fpgas_by_know_list())) | set(
map(lambda p: p.rsplit("/", 2)[0],
get_link_targets(glob.glob(os.path.join(SYS_FPGA, "*")))))
| def all_fpgas():
# glob.glob1("/sys/class/fpga", "*")
| return set(get_link_targets(find_fpgas_by_know_list())) | set(
map(lambda p: p.rsplit("/", 2)[0],
get_link_targets(glob.glob(os.path.join(SYS_FPGA, "*")))))
| PCI_DEVICES_PATH_PATTERN))
def get_link_targets(links):
return map(
lambda p:
os.path.realpath(
os.path.join(os.path.dirname(p), os.readlink(p))),
links)
def all_fpgas():
# glob.glob1("/sys/class/fpga", "*")
| 64 | 64 | 70 | 20 | 44 | NeCTAR-RC/cyborg | cyborg/accelerator/drivers/fpga/intel/sysinfo.py | Python | all_fpgas | all_fpgas | 95 | 99 | 95 | 96 | 8f78aa157e28e0e47b51f3857331d6882ac34a40 | bigcode/the-stack | train |
1082e3809109142fe30c145e | train | function | def find_fpgas_by_know_list():
return filter(
lambda p: (
read_line(os.path.join(p, "vendor")),
read_line(os.path.join(p, "device"))
) in KNOWN_FPGAS,
glob.glob(PCI_DEVICES_PATH_PATTERN))
| def find_fpgas_by_know_list():
| return filter(
lambda p: (
read_line(os.path.join(p, "vendor")),
read_line(os.path.join(p, "device"))
) in KNOWN_FPGAS,
glob.glob(PCI_DEVICES_PATH_PATTERN))
| ):
return os.path.realpath(
os.path.join(os.path.dirname(p), os.readlink(p)))
# TODO(s_shogo) This function name should be reconsidered in py3
# env( filter() in py3 returns iterator, not list)
def find_fpgas_by_know_list():
| 64 | 64 | 60 | 10 | 54 | NeCTAR-RC/cyborg | cyborg/accelerator/drivers/fpga/intel/sysinfo.py | Python | find_fpgas_by_know_list | find_fpgas_by_know_list | 78 | 84 | 78 | 78 | b022268491e4e3d6b18da4800976d8142196596c | bigcode/the-stack | train |
1ff3635bdcff13a5dc764d39 | train | function | def all_pfs_have_vf():
return list(filter(lambda p: glob.glob(os.path.join(p, "virtfn0")),
all_fpgas()))
| def all_pfs_have_vf():
| return list(filter(lambda p: glob.glob(os.path.join(p, "virtfn0")),
all_fpgas()))
| .glob(os.path.join(SYS_FPGA, "*")))))
def all_vf_fpgas():
return [dev.rsplit("/", 2)[0] for dev in
glob.glob(os.path.join(SYS_FPGA, "*/device/physfn"))]
def all_pfs_have_vf():
| 64 | 64 | 33 | 8 | 56 | NeCTAR-RC/cyborg | cyborg/accelerator/drivers/fpga/intel/sysinfo.py | Python | all_pfs_have_vf | all_pfs_have_vf | 107 | 109 | 107 | 107 | 11f950b11a513a60af8fff1a055569f65648430f | bigcode/the-stack | train |
8181d462a9c9bd1fb2019144 | train | function | def _generate_attach_handle(fpga):
driver_ah = driver_attach_handle.DriverAttachHandle()
driver_ah.attach_type = constants.AH_TYPE_PCI
driver_ah.attach_info = utils.pci_str_to_json(fpga["devices"])
driver_ah.in_use = False
return driver_ah
| def _generate_attach_handle(fpga):
| driver_ah = driver_attach_handle.DriverAttachHandle()
driver_ah.attach_type = constants.AH_TYPE_PCI
driver_ah.attach_info = utils.pci_str_to_json(fpga["devices"])
driver_ah.in_use = False
return driver_ah
| regions"]:
# Only vfs in regions can be attach, no pf.
driver_dep.attach_handle_list.append(
_generate_attach_handle(vf))
driver_dep.name = vf["name"]
driver_dep.driver_name = DRIVER_NAME
return [driver_dep]
def _generate_attach_handle(fpga):
| 64 | 64 | 67 | 8 | 56 | NeCTAR-RC/cyborg | cyborg/accelerator/drivers/fpga/intel/sysinfo.py | Python | _generate_attach_handle | _generate_attach_handle | 307 | 312 | 307 | 307 | 18900c3c8617932e5bfaf75e221b39d203d8a2c6 | bigcode/the-stack | train |
8ab2db2267bfec13ab6554f4 | train | function | def get_pf_bdf(bdf):
paths = glob.glob0(PCI_DEVICES_PATH, bdf)
if paths:
p0 = paths[0]
path = find_pf_by_vf(p0) if is_vf(p0) else p0
return get_bdf_by_path(path)
return bdf
| def get_pf_bdf(bdf):
| paths = glob.glob0(PCI_DEVICES_PATH, bdf)
if paths:
p0 = paths[0]
path = find_pf_by_vf(p0) if is_vf(p0) else p0
return get_bdf_by_path(path)
return bdf
| df):
return bdf
return os.path.basename(os.readlink(os.path.join(path, "device")))
def split_bdf(bdf):
return ["0x" + v for v in bdf.replace(".", ":").rsplit(":")[1:]]
def get_pf_bdf(bdf):
| 63 | 64 | 71 | 8 | 55 | NeCTAR-RC/cyborg | cyborg/accelerator/drivers/fpga/intel/sysinfo.py | Python | get_pf_bdf | get_pf_bdf | 159 | 165 | 159 | 159 | 00b3e6211004a39382047c097a08d3c62537f837 | bigcode/the-stack | train |
0ab01db75011eeeda7655bc5 | train | function | def get_bdf_by_path(path):
bdf = os.path.basename(path)
if is_bdf(bdf):
return bdf
return os.path.basename(os.readlink(os.path.join(path, "device")))
| def get_bdf_by_path(path):
| bdf = os.path.basename(path)
if is_bdf(bdf):
return bdf
return os.path.basename(os.readlink(os.path.join(path, "device")))
| _pf_by_vf(path):
if glob.glob(os.path.join(path, "physfn")):
return link_real_path(os.path.join(path, "physfn"))
def is_bdf(bdf):
return True if BDF_PATTERN.match(bdf) else False
def get_bdf_by_path(path):
| 64 | 64 | 46 | 8 | 55 | NeCTAR-RC/cyborg | cyborg/accelerator/drivers/fpga/intel/sysinfo.py | Python | get_bdf_by_path | get_bdf_by_path | 148 | 152 | 148 | 148 | 14c923f2feb2e2eab73527a8fc4b030aa2c85620 | bigcode/the-stack | train |
dbdbafacd50a8acf13b3fadb | train | function | def is_bdf(bdf):
return True if BDF_PATTERN.match(bdf) else False
| def is_bdf(bdf):
| return True if BDF_PATTERN.match(bdf) else False
| physfn")) or
glob.glob(os.path.join(path, "physfn"))) else False
def find_pf_by_vf(path):
if glob.glob(os.path.join(path, "physfn")):
return link_real_path(os.path.join(path, "physfn"))
def is_bdf(bdf):
| 63 | 64 | 21 | 7 | 56 | NeCTAR-RC/cyborg | cyborg/accelerator/drivers/fpga/intel/sysinfo.py | Python | is_bdf | is_bdf | 144 | 145 | 144 | 144 | 139e4b098035263bd1418fa9919b7374683a7bbe | bigcode/the-stack | train |
8153db1b0dc41b7e30f79491 | train | function | def fpga_tree():
def gen_fpga_infos(path, vf=True):
bdf = get_bdf_by_path(path)
names = glob.glob1(os.path.join(path, "fpga"), "*")
# name = os.path.basename(path)
fpga = {"type": constants.DEVICE_FPGA,
"devices": bdf, "stub": True,
"name": "_".join((s... | def fpga_tree():
| def gen_fpga_infos(path, vf=True):
bdf = get_bdf_by_path(path)
names = glob.glob1(os.path.join(path, "fpga"), "*")
# name = os.path.basename(path)
fpga = {"type": constants.DEVICE_FPGA,
"devices": bdf, "stub": True,
"name": "_".join((socket.gethostname... | ) in os.walk(path):
for filename in filenames:
if filename in DEVICE_EXPOSED:
key = DEVICE_FILE_MAP.get(filename) or filename
if key in DEVICE_FILE_HANDLER and callable(
DEVICE_FILE_HANDLER(key)):
infos[key] = DEVICE_FILE_HANDLE... | 95 | 95 | 319 | 5 | 89 | NeCTAR-RC/cyborg | cyborg/accelerator/drivers/fpga/intel/sysinfo.py | Python | fpga_tree | fpga_tree | 227 | 258 | 227 | 227 | 470b0e58575d0ed134745c5fca4d4934b596df5c | bigcode/the-stack | train |
88574fa3d67a89c7617e46f5 | train | function | def read_line(filename):
with open(filename) as f:
return f.readline().strip()
| def read_line(filename):
| with open(filename) as f:
return f.readline().strip()
| ")
DEVICE_FILE_MAP = {"vendor": "vendor",
"device": "product_id"}
DEVICE_FILE_HANDLER = {}
DEVICE_EXPOSED = ["vendor", "device"]
PRODUCT_MAP = {"0x09c4": "PAC_ARRIA10"}
DRIVER_NAME = "intel"
def read_line(filename):
| 64 | 64 | 20 | 5 | 59 | NeCTAR-RC/cyborg | cyborg/accelerator/drivers/fpga/intel/sysinfo.py | Python | read_line | read_line | 59 | 61 | 59 | 59 | 7721766d700b8a21f0db94a71329cbd97c46e784 | bigcode/the-stack | train |
cd3ed036ca1354dde159550a | train | function | def all_pf_fpgas():
return filter(lambda p: glob.glob(os.path.join(p, "sriov_totalvfs")),
all_fpgas())
| def all_pf_fpgas():
| return filter(lambda p: glob.glob(os.path.join(p, "sriov_totalvfs")),
all_fpgas())
| ():
return dict(map(lambda f: (os.path.basename(f), f), all_fpgas()))
def all_vfs_in_pf_fpgas(pf_path):
return get_link_targets(
glob.glob(os.path.join(pf_path, "virtfn*")))
def all_pf_fpgas():
| 63 | 64 | 34 | 7 | 56 | NeCTAR-RC/cyborg | cyborg/accelerator/drivers/fpga/intel/sysinfo.py | Python | all_pf_fpgas | all_pf_fpgas | 128 | 130 | 128 | 128 | 12a29c084b10fcb164c40064ce4e02e6a74dfb14 | bigcode/the-stack | train |
278835299d4febf8f8fb0ffe | train | function | def find_pf_by_vf(path):
if glob.glob(os.path.join(path, "physfn")):
return link_real_path(os.path.join(path, "physfn"))
| def find_pf_by_vf(path):
| if glob.glob(os.path.join(path, "physfn")):
return link_real_path(os.path.join(path, "physfn"))
| "sriov_totalvfs")),
all_fpgas())
def is_vf(path):
return True if (
glob.glob(os.path.join(path, "device/physfn")) or
glob.glob(os.path.join(path, "physfn"))) else False
def find_pf_by_vf(path):
| 64 | 64 | 36 | 8 | 55 | NeCTAR-RC/cyborg | cyborg/accelerator/drivers/fpga/intel/sysinfo.py | Python | find_pf_by_vf | find_pf_by_vf | 139 | 141 | 139 | 139 | cd31018720d69c2c335f966d56d27d92547cbde2 | bigcode/the-stack | train |
3dd935ab1c9def3d5263f79a | train | function | def is_vf(path):
return True if (
glob.glob(os.path.join(path, "device/physfn")) or
glob.glob(os.path.join(path, "physfn"))) else False
| def is_vf(path):
| return True if (
glob.glob(os.path.join(path, "device/physfn")) or
glob.glob(os.path.join(path, "physfn"))) else False
| _path):
return get_link_targets(
glob.glob(os.path.join(pf_path, "virtfn*")))
def all_pf_fpgas():
return filter(lambda p: glob.glob(os.path.join(p, "sriov_totalvfs")),
all_fpgas())
def is_vf(path):
| 64 | 64 | 42 | 6 | 58 | NeCTAR-RC/cyborg | cyborg/accelerator/drivers/fpga/intel/sysinfo.py | Python | is_vf | is_vf | 133 | 136 | 133 | 133 | 841d2c3a06a87dc79facfde58555ce90cc848eff | bigcode/the-stack | train |
6f92f14e2d012a872d272885 | train | function | def _generate_driver_device(fpga, pf_has_vf):
driver_device_obj = driver_device.DriverDevice()
driver_device_obj.vendor = fpga["vendor"]
driver_device_obj.stub = fpga["stub"]
driver_device_obj.model = fpga.get('model', "miss_model_info")
driver_device_obj.vendor_board_info = fpga.get('vendor_board_i... | def _generate_driver_device(fpga, pf_has_vf):
| driver_device_obj = driver_device.DriverDevice()
driver_device_obj.vendor = fpga["vendor"]
driver_device_obj.stub = fpga["stub"]
driver_device_obj.model = fpga.get('model', "miss_model_info")
driver_device_obj.vendor_board_info = fpga.get('vendor_board_info',
... | fs:
vf_fpga = gen_fpga_infos(vf, True)
fpga["regions"].append(vf_fpga)
devs.append(_generate_driver_device(fpga, pf in pf_has_vf))
return devs
def _generate_driver_device(fpga, pf_has_vf):
| 64 | 64 | 171 | 13 | 50 | NeCTAR-RC/cyborg | cyborg/accelerator/drivers/fpga/intel/sysinfo.py | Python | _generate_driver_device | _generate_driver_device | 261 | 273 | 261 | 261 | cb58b966e0df22745ba4f2979269449858658bb9 | bigcode/the-stack | train |
6e9e0af86b08c53b089f3791 | train | function | def bdf_path_map():
return dict(map(lambda f: (os.path.basename(f), f), all_fpgas()))
| def bdf_path_map():
| return dict(map(lambda f: (os.path.basename(f), f), all_fpgas()))
| fn0")),
all_fpgas()))
def target_symbolic_map():
maps = {}
for f in glob.glob(os.path.join(SYS_FPGA, "*/device")):
maps[os.path.realpath(f)] = os.path.dirname(f)
return maps
def bdf_path_map():
| 64 | 64 | 26 | 6 | 57 | NeCTAR-RC/cyborg | cyborg/accelerator/drivers/fpga/intel/sysinfo.py | Python | bdf_path_map | bdf_path_map | 119 | 120 | 119 | 119 | 0b7f41812d3b788047b94a5420a0d1a524801305 | bigcode/the-stack | train |
729a617f6470c37400c90c7d | train | function | def _generate_attribute_list(fpga):
attr_list = []
for k, v in fpga.items():
if k == "rc":
driver_attr = driver_attribute.DriverAttribute()
driver_attr.key, driver_attr.value = k, v
attr_list.append(driver_attr)
if k == "traits":
values = fpga.get(... | def _generate_attribute_list(fpga):
| attr_list = []
for k, v in fpga.items():
if k == "rc":
driver_attr = driver_attribute.DriverAttribute()
driver_attr.key, driver_attr.value = k, v
attr_list.append(driver_attr)
if k == "traits":
values = fpga.get(k, [])
for index_pf, val... | ah = driver_attach_handle.DriverAttachHandle()
driver_ah.attach_type = constants.AH_TYPE_PCI
driver_ah.attach_info = utils.pci_str_to_json(fpga["devices"])
driver_ah.in_use = False
return driver_ah
def _generate_attribute_list(fpga):
| 64 | 64 | 204 | 8 | 55 | NeCTAR-RC/cyborg | cyborg/accelerator/drivers/fpga/intel/sysinfo.py | Python | _generate_attribute_list | _generate_attribute_list | 315 | 337 | 315 | 315 | 57d169447f2d17c599081a8b55b3af0787962490 | bigcode/the-stack | train |
bca4f1ba0619c1dd7db6d21e | train | function | def target_symbolic_map():
maps = {}
for f in glob.glob(os.path.join(SYS_FPGA, "*/device")):
maps[os.path.realpath(f)] = os.path.dirname(f)
return maps
| def target_symbolic_map():
| maps = {}
for f in glob.glob(os.path.join(SYS_FPGA, "*/device")):
maps[os.path.realpath(f)] = os.path.dirname(f)
return maps
| ] for dev in
glob.glob(os.path.join(SYS_FPGA, "*/device/physfn"))]
def all_pfs_have_vf():
return list(filter(lambda p: glob.glob(os.path.join(p, "virtfn0")),
all_fpgas()))
def target_symbolic_map():
| 63 | 64 | 48 | 6 | 57 | NeCTAR-RC/cyborg | cyborg/accelerator/drivers/fpga/intel/sysinfo.py | Python | target_symbolic_map | target_symbolic_map | 112 | 116 | 112 | 112 | f439be97e36880fbf85264e98b2dd64589163177 | bigcode/the-stack | train |
521b14c70a177cb97cd39a8b | train | function | def link_real_path(p):
return os.path.realpath(
os.path.join(os.path.dirname(p), os.readlink(p)))
| def link_real_path(p):
| return os.path.realpath(
os.path.join(os.path.dirname(p), os.readlink(p)))
| f:
return f.readline().strip()
def is_fpga(p):
infos = (read_line(os.path.join(p, "vendor")),
read_line(os.path.join(p, "device")))
if infos in KNOWN_FPGAS:
return os.path.realpath(p)
def link_real_path(p):
| 64 | 64 | 27 | 6 | 58 | NeCTAR-RC/cyborg | cyborg/accelerator/drivers/fpga/intel/sysinfo.py | Python | link_real_path | link_real_path | 71 | 73 | 71 | 71 | 781e4e86e8bedb8214eae62d314bdf80bd0a06d5 | bigcode/the-stack | train |
26301b497b354d05bc66ee2f | train | function | @pytest.mark.parametrize("available_protocol", registered_workflow_protocols)
def test_default_protocol_schemas(available_protocol):
"""A simple test to ensure that each available protocol
can both create, and be created from a schema."""
protocol_class = registered_workflow_protocols[available_protocol]
... | @pytest.mark.parametrize("available_protocol", registered_workflow_protocols)
def test_default_protocol_schemas(available_protocol):
| """A simple test to ensure that each available protocol
can both create, and be created from a schema."""
protocol_class = registered_workflow_protocols[available_protocol]
if (
protocol_class.__abstractmethods__ is not None
and len(protocol_class.__abstractmethods__) > 0
):
... | import pytest
from openff.evaluator.plugins import register_default_plugins
from openff.evaluator.workflow import registered_workflow_protocols
# Load the default protocols.
register_default_plugins()
@pytest.mark.parametrize("available_protocol", registered_workflow_protocols)
def test_default_protocol_schemas(avail... | 60 | 64 | 151 | 23 | 37 | jaketanderson/openff-evaluator | openff/evaluator/tests/test_protocols/test_defaults.py | Python | test_default_protocol_schemas | test_default_protocol_schemas | 10 | 29 | 10 | 11 | 5a040c63e2595b71ad0ed45fde09daa091e78ee0 | bigcode/the-stack | train |
a24cc2d0aff831b95ace2d4c | train | function | def is_successful_status(status):
return status['status'] == "success" or \
status['http_method'] == "DELETE" and status['http_status'] == 404
| def is_successful_status(status):
| return status['status'] == "success" or \
status['http_method'] == "DELETE" and status['http_status'] == 404
| fos.set('firewall',
'address',
data=filtered_data,
vdom=vdom)
elif state == "absent":
return fos.delete('firewall',
'address',
mkey=filtered_data['name'],
vdom... | 64 | 64 | 39 | 7 | 57 | gvashchenkolineate/gvashchenkolineate_infra_trytravis | ansible/venv/lib/python2.7/site-packages/ansible/modules/network/fortios/fortios_firewall_address.py | Python | is_successful_status | is_successful_status | 455 | 457 | 455 | 455 | a3e73e1b2b5e77311eef5ec7cab06d9275b33f85 | bigcode/the-stack | train |
07c43d4a2a24896ab73a2dfd | train | function | def underscore_to_hyphen(data):
if isinstance(data, list):
for elem in data:
elem = underscore_to_hyphen(elem)
elif isinstance(data, dict):
new_data = {}
for k, v in data.items():
new_data[k.replace('_', '-')] = underscore_to_hyphen(v)
data = new_data
... | def underscore_to_hyphen(data):
| if isinstance(data, list):
for elem in data:
elem = underscore_to_hyphen(elem)
elif isinstance(data, dict):
new_data = {}
for k, v in data.items():
new_data[k.replace('_', '-')] = underscore_to_hyphen(v)
data = new_data
return data
| uuid',
'visibility', 'wildcard', 'wildcard_fqdn']
dictionary = {}
for attribute in option_list:
if attribute in json and json[attribute] is not None:
dictionary[attribute] = json[attribute]
return dictionary
def underscore_to_hyphen(data):
| 64 | 64 | 79 | 8 | 55 | gvashchenkolineate/gvashchenkolineate_infra_trytravis | ansible/venv/lib/python2.7/site-packages/ansible/modules/network/fortios/fortios_firewall_address.py | Python | underscore_to_hyphen | underscore_to_hyphen | 418 | 428 | 418 | 418 | fbdcd75a0a412e97e109411d03aac62c5bdbed76 | bigcode/the-stack | train |
d8e68cb85b63a96e99ca2dc2 | train | function | def login(data, fos):
host = data['host']
username = data['username']
password = data['password']
ssl_verify = data['ssl_verify']
fos.debug('on')
if 'https' in data and not data['https']:
fos.https('off')
else:
fos.https('on')
fos.login(host, username, password, verify=... | def login(data, fos):
| host = data['host']
username = data['username']
password = data['password']
ssl_verify = data['ssl_verify']
fos.debug('on')
if 'https' in data and not data['https']:
fos.https('off')
else:
fos.https('on')
fos.login(host, username, password, verify=ssl_verify)
| .3"
'''
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.connection import Connection
from ansible.module_utils.network.fortios.fortios import FortiOSHandler
from ansible.module_utils.network.fortimanager.common import FAIL_SOCKET_MSG
def login(data, fos):
| 64 | 64 | 86 | 6 | 57 | gvashchenkolineate/gvashchenkolineate_infra_trytravis | ansible/venv/lib/python2.7/site-packages/ansible/modules/network/fortios/fortios_firewall_address.py | Python | login | login | 384 | 396 | 384 | 384 | d2d6c6d6c852c3b07056af4740462b139cdffd4f | bigcode/the-stack | train |
1a792a0aee9222cc3f40914c | train | function | def filter_firewall_address_data(json):
option_list = ['allow_routing', 'associated_interface', 'cache_ttl',
'color', 'comment', 'country',
'end_ip', 'epg_name', 'filter',
'fqdn', 'list', 'name',
'obj_id', 'organization', 'policy_group',
... | def filter_firewall_address_data(json):
| option_list = ['allow_routing', 'associated_interface', 'cache_ttl',
'color', 'comment', 'country',
'end_ip', 'epg_name', 'filter',
'fqdn', 'list', 'name',
'obj_id', 'organization', 'policy_group',
'sdn', 'sdn_tag', 'star... | = data['ssl_verify']
fos.debug('on')
if 'https' in data and not data['https']:
fos.https('off')
else:
fos.https('on')
fos.login(host, username, password, verify=ssl_verify)
def filter_firewall_address_data(json):
| 64 | 64 | 164 | 8 | 56 | gvashchenkolineate/gvashchenkolineate_infra_trytravis | ansible/venv/lib/python2.7/site-packages/ansible/modules/network/fortios/fortios_firewall_address.py | Python | filter_firewall_address_data | filter_firewall_address_data | 399 | 415 | 399 | 399 | ab490beaf94c1b92e5f4840482d1ac0e6dba3e1f | bigcode/the-stack | train |
e2018eca1975e0805a61e3a0 | train | function | def fortios_firewall(data, fos):
if data['firewall_address']:
resp = firewall_address(data, fos)
return not is_successful_status(resp), \
resp['status'] == "success", \
resp
| def fortios_firewall(data, fos):
| if data['firewall_address']:
resp = firewall_address(data, fos)
return not is_successful_status(resp), \
resp['status'] == "success", \
resp
| ',
mkey=filtered_data['name'],
vdom=vdom)
def is_successful_status(status):
return status['status'] == "success" or \
status['http_method'] == "DELETE" and status['http_status'] == 404
def fortios_firewall(data, fos):
| 64 | 64 | 49 | 9 | 54 | gvashchenkolineate/gvashchenkolineate_infra_trytravis | ansible/venv/lib/python2.7/site-packages/ansible/modules/network/fortios/fortios_firewall_address.py | Python | fortios_firewall | fortios_firewall | 460 | 467 | 460 | 461 | a7ff2929f93f2b693a5101bcd9e8b58c5549e923 | bigcode/the-stack | train |
9edc5354779225fac55ad087 | train | function | def firewall_address(data, fos):
vdom = data['vdom']
if 'state' in data and data['state']:
state = data['state']
elif 'state' in data['firewall_address'] and data['firewall_address']:
state = data['firewall_address']['state']
else:
state = True
firewall_address_data = data['f... | def firewall_address(data, fos):
| vdom = data['vdom']
if 'state' in data and data['state']:
state = data['state']
elif 'state' in data['firewall_address'] and data['firewall_address']:
state = data['firewall_address']['state']
else:
state = True
firewall_address_data = data['firewall_address']
filtered_da... | elem = underscore_to_hyphen(elem)
elif isinstance(data, dict):
new_data = {}
for k, v in data.items():
new_data[k.replace('_', '-')] = underscore_to_hyphen(v)
data = new_data
return data
def firewall_address(data, fos):
| 64 | 64 | 170 | 7 | 56 | gvashchenkolineate/gvashchenkolineate_infra_trytravis | ansible/venv/lib/python2.7/site-packages/ansible/modules/network/fortios/fortios_firewall_address.py | Python | firewall_address | firewall_address | 431 | 452 | 431 | 431 | fd5a43cb7c7a8e010e04d5f3ec476090598fce6b | bigcode/the-stack | train |
f383b20fab0c9f6c8a761ddb | train | function | def main():
fields = {
"host": {"required": False, "type": "str"},
"username": {"required": False, "type": "str"},
"password": {"required": False, "type": "str", "default": "", "no_log": True},
"vdom": {"required": False, "type": "str", "default": "root"},
"https": {"required... | def main():
| fields = {
"host": {"required": False, "type": "str"},
"username": {"required": False, "type": "str"},
"password": {"required": False, "type": "str", "default": "", "no_log": True},
"vdom": {"required": False, "type": "str", "default": "root"},
"https": {"required": False, "t... | fos):
vdom = data['vdom']
if 'state' in data and data['state']:
state = data['state']
elif 'state' in data['firewall_address'] and data['firewall_address']:
state = data['firewall_address']['state']
else:
state = True
firewall_address_data = data['firewall_address']
filt... | 256 | 256 | 1,089 | 3 | 252 | gvashchenkolineate/gvashchenkolineate_infra_trytravis | ansible/venv/lib/python2.7/site-packages/ansible/modules/network/fortios/fortios_firewall_address.py | Python | main | main | 470 | 567 | 470 | 470 | 8b07f6997746b8001f3a34aea544c53bf65b0224 | bigcode/the-stack | train |
55e5546cff954256f31247ba | train | class | class _state(param.Parameterized):
"""
Holds global state associated with running apps, allowing running
apps to indicate their state to a user.
"""
busy = param.Boolean(default=False, readonly=True, doc="""
Whether the application is currently busy processing a user
callback.""")
... | class _state(param.Parameterized):
| """
Holds global state associated with running apps, allowing running
apps to indicate their state to a user.
"""
busy = param.Boolean(default=False, readonly=True, doc="""
Whether the application is currently busy processing a user
callback.""")
cache = param.Dict(default={}, do... | """
Various utilities for recording and embedding state in a rendered app.
"""
from __future__ import absolute_import, division, unicode_literals
import threading
from weakref import WeakKeyDictionary, WeakSet
import param
from bokeh.document import Document
from bokeh.io import curdoc as _curdoc
from pyviz_comms i... | 83 | 256 | 910 | 7 | 75 | nritsche/panel | panel/io/state.py | Python | _state | _state | 17 | 149 | 17 | 17 | 5916c4bc79ba227fab0cdaa3073d187b3145ca3f | bigcode/the-stack | train |
1cd78fda7051a1bc1e327992 | train | function | def getToken() :
payload = {"username": username, "password": password}
url = 'https://140.115.52.100:8080/api/internal/login'
headers = { "Accept" : "application/json"}
r = requests.post(url, json = payload, verify = False)
return r.json()['jwt']
| def getToken() :
| payload = {"username": username, "password": password}
url = 'https://140.115.52.100:8080/api/internal/login'
headers = { "Accept" : "application/json"}
r = requests.post(url, json = payload, verify = False)
return r.json()['jwt']
| import requests
requests.packages.urllib3.disable_warnings()
username='student'
password='lora_experiment'
def getToken() :
| 29 | 64 | 72 | 5 | 24 | lovenery/WLSNK | Data-collect/after-zip/api.py | Python | getToken | getToken | 7 | 12 | 7 | 7 | 534ccffd8488a498e97333ea0fa76f92cd45792f | bigcode/the-stack | train |
bb7c0135b05c249d79b7fd6a | train | function | def getFrame(eui, jwt) :
payload = {'limit' : '2', 'offset' : '0'}
header = {'Grpc-Metadata-Authorization' : jwt }
url = 'https://140.115.52.100:8080/api/devices/{}/frames'.format(eui)
r = requests.get(url, params = payload, headers = header, verify = False)
return r.json()['result']
| def getFrame(eui, jwt) :
| payload = {'limit' : '2', 'offset' : '0'}
header = {'Grpc-Metadata-Authorization' : jwt }
url = 'https://140.115.52.100:8080/api/devices/{}/frames'.format(eui)
r = requests.get(url, params = payload, headers = header, verify = False)
return r.json()['result']
| }
url = 'https://140.115.52.100:8080/api/internal/login'
headers = { "Accept" : "application/json"}
r = requests.post(url, json = payload, verify = False)
return r.json()['jwt']
def getFrame(eui, jwt) :
| 64 | 64 | 92 | 9 | 55 | lovenery/WLSNK | Data-collect/after-zip/api.py | Python | getFrame | getFrame | 14 | 19 | 14 | 14 | dbfc649828b33d2e8b103dbd17b9911cdcdaee5a | bigcode/the-stack | train |
f299c99a430e6a7a1adce82c | train | function | def ninja_alias( w, alias, deps ):
if deps:
assert type( deps ) == list, 'Expecting deps to be of type list'
w.build(
outputs = alias,
implicit = deps,
rule = 'phony',
)
w.newline()
return alias
| def ninja_alias( w, alias, deps ):
| if deps:
assert type( deps ) == list, 'Expecting deps to be of type list'
w.build(
outputs = alias,
implicit = deps,
rule = 'phony',
)
w.newline()
return alias
| w.newline()
return f_stamp
# ninja_alias
#
# Create an alias for the given dependencies
#
# - w : instance of ninja_syntax Writer
# - alias : alias name(s)
# - deps : dependencies
#
def ninja_alias( w, alias, deps ):
| 64 | 64 | 67 | 11 | 53 | jbrzozo24/mflowgen | mflowgen/backends/ninja_syntax_extra.py | Python | ninja_alias | ninja_alias | 184 | 197 | 184 | 185 | a34882ae70b6e89edd3a9e9c83c0e77acfcfaeb1 | bigcode/the-stack | train |
e57fdca8348946bfff0fc5a0 | train | function | def ninja_graph( w ):
command = 'dot -Tpdf .mflowgen/graph.dot > graph.pdf'
w.rule(
name = 'graph',
description = 'graph: Generating a PDF of the user-defined graph',
command = command,
)
w.newline()
w.build(
outputs = 'graph',
rule = 'graph',
)
w.newline()
| def ninja_graph( w ):
| command = 'dot -Tpdf .mflowgen/graph.dot > graph.pdf'
w.rule(
name = 'graph',
description = 'graph: Generating a PDF of the user-defined graph',
command = command,
)
w.newline()
w.build(
outputs = 'graph',
rule = 'graph',
)
w.newline()
| w.build(
outputs = 'list',
rule = 'list',
)
w.newline()
# ninja_graph
#
# Write out ninja rule to generate a PDF of the user-defined graph
#
# - w : instance of ninja_syntax Writer
#
def ninja_graph( w ):
| 64 | 64 | 90 | 7 | 57 | jbrzozo24/mflowgen | mflowgen/backends/ninja_syntax_extra.py | Python | ninja_graph | ninja_graph | 447 | 462 | 447 | 448 | 733906f44861426dd101756786be5deba0d2f1f5 | bigcode/the-stack | train |
bc442b7d94b8bbf80893e1ec | train | function | def ninja_symlink( w, dst, src, deps=None, src_is_symlink=False ):
if deps:
assert type( deps ) == list, 'Expecting deps to be of type list'
# Stamp files
dst_dir = os.path.dirname( dst )
dst_base = os.path.basename( dst )
dst_stamp = stamp( dst )
# Relative paths for symlinking after changing di... | def ninja_symlink( w, dst, src, deps=None, src_is_symlink=False ):
| if deps:
assert type( deps ) == list, 'Expecting deps to be of type list'
# Stamp files
dst_dir = os.path.dirname( dst )
dst_base = os.path.basename( dst )
dst_stamp = stamp( dst )
# Relative paths for symlinking after changing directories
src_relative = os.path.relpath( src, dst_dir )
dst_re... | dst : path to linked file/directory
# - src : path to source file/directory
# - deps : additional dependencies for ninja build
# - src_is_symlink : boolean, flag if source is a symlink (and has stamp)
#
def ninja_symlink( w, dst, src, deps=None, src_is_symlink=False ):
| 75 | 75 | 253 | 21 | 54 | jbrzozo24/mflowgen | mflowgen/backends/ninja_syntax_extra.py | Python | ninja_symlink | ninja_symlink | 64 | 103 | 64 | 65 | 6348302715f5bb76276ed16ad1c4db389bb31b84 | bigcode/the-stack | train |
9d655aed4ca613e1d35aeba5 | train | function | def ninja_diff( w, name, src, dst ):
exclude_files = [
'configure.yml',
'.time_end',
'.time_start',
'mflowgen-run*',
'mflowgen-debug',
'.stamp',
'inputs',
'outputs',
]
command = ' '.join( [
# Newline
'echo &&',
# Diff the src and dst
'diff -r -u --minimal',
# ... | def ninja_diff( w, name, src, dst ):
| exclude_files = [
'configure.yml',
'.time_end',
'.time_start',
'mflowgen-run*',
'mflowgen-debug',
'.stamp',
'inputs',
'outputs',
]
command = ' '.join( [
# Newline
'echo &&',
# Diff the src and dst
'diff -r -u --minimal',
# Exclude build-system specific files
... | = name,
description = name + ': Clean build directories',
command = command,
)
w.newline()
w.build(
outputs = name,
rule = name,
)
w.newline()
# ninja_diff
#
# Write out rules for diffs
#
# - w : instance of Writer
#
def ninja_diff( w, name, src, dst ):
| 84 | 84 | 283 | 13 | 71 | jbrzozo24/mflowgen | mflowgen/backends/ninja_syntax_extra.py | Python | ninja_diff | ninja_diff | 298 | 341 | 298 | 299 | 9dd13b7963a1ec13de0586cdb723ba021592f805 | bigcode/the-stack | train |
90e3fc9a592576935f195a7c | train | function | def ninja_execute( w, outputs, rule, command, description='', deps=None, pool='' ):
if deps:
assert type( deps ) == list, 'Expecting deps to be of type list'
rule_params = {
'name' : rule,
'command' : command,
'description' : description,
'pool' : pool,
}
if not pool:
... | def ninja_execute( w, outputs, rule, command, description='', deps=None, pool='' ):
| if deps:
assert type( deps ) == list, 'Expecting deps to be of type list'
rule_params = {
'name' : rule,
'command' : command,
'description' : description,
'pool' : pool,
}
if not pool:
del( rule_params['pool'] )
if not description:
del( rule_params['description... | - outputs : outputs of the execute rule
# - rule : name of the execute rule
# - command : string, command for the rule
# - deps : additional dependencies for ninja build
#
def ninja_execute( w, outputs, rule, command, description='', deps=None, pool='' ):
| 64 | 64 | 155 | 21 | 43 | jbrzozo24/mflowgen | mflowgen/backends/ninja_syntax_extra.py | Python | ninja_execute | ninja_execute | 116 | 146 | 116 | 117 | 6cfaae14726c91e453ca9e04d93285497bf33339 | bigcode/the-stack | train |
24b6b272fdaa88df2ad42569 | train | function | def ninja_status( w, steps ):
steps_comma_separated = ','.join( steps )
w.rule(
name = 'status',
description = 'status: Listing status for each step',
command = get_top_dir() + '/mflowgen/scripts/mflowgen-status' \
' --backend ninja -s ' + steps_comma_separated
)
w.new... | def ninja_status( w, steps ):
| steps_comma_separated = ','.join( steps )
w.rule(
name = 'status',
description = 'status: Listing status for each step',
command = get_top_dir() + '/mflowgen/scripts/mflowgen-status' \
' --backend ninja -s ' + steps_comma_separated
)
w.newline()
w.build(
outputs ... | ',
rule = 'graph',
)
w.newline()
# ninja_status
#
# Write out rules for printing build status
#
# - w : instance of ninja_syntax Writer
# - steps : list of step names to print status for
#
def ninja_status( w, steps ):
| 64 | 64 | 111 | 9 | 55 | jbrzozo24/mflowgen | mflowgen/backends/ninja_syntax_extra.py | Python | ninja_status | ninja_status | 515 | 531 | 515 | 516 | 81cc73216bf2e3bf9373fd6d3258c7189ecbeaf4 | bigcode/the-stack | train |
d454e3899acd59d043e95601 | train | function | def ninja_list( w, build_dirs, debug_targets ):
# Split the build ID and step name from the build_dir
#
# For example, this:
#
# 4-synopsys-dc-synthesis
#
# turns into this:
#
# ( '4', 'synopsys-dc-synthesis' )
#
steps = []
for _ in sorted( build_dirs.values(), \
... | def ninja_list( w, build_dirs, debug_targets ):
# Split the build ID and step name from the build_dir
#
# For example, this:
#
# 4-synopsys-dc-synthesis
#
# turns into this:
#
# ( '4', 'synopsys-dc-synthesis' )
#
| steps = []
for _ in sorted( build_dirs.values(), \
key = lambda x: int(x.split('-')[0]) ):
tokens = _.split('-')
steps.append( ( tokens[0], '-'.join(tokens[1:]) ) )
steps_str = \
[ '"{: >3} : {}"'.format(x,y) for x, y in ( steps ) ]
generic = [
'"list -- List all ste... | untimes',
)
w.newline()
# ninja_list
#
# Write out ninja rule to list all steps
#
# - w : instance of ninja_syntax Writer
# - build_dirs : list of build directories
# - debug_targets : dict of debug targets with key (id) and value (target)
#
def ninja_list( w, build_dirs, debug_targets ):
# Split... | 150 | 150 | 500 | 81 | 69 | jbrzozo24/mflowgen | mflowgen/backends/ninja_syntax_extra.py | Python | ninja_list | ninja_list | 374 | 438 | 374 | 386 | 0d3bff227af631aff61e9a195018d0520bfbd098 | bigcode/the-stack | train |
3586edecce88eff29d487813 | train | function | def ninja_common_rules( w ):
# cpdir
w.rule(
name = 'cpdir',
description = 'cpdir: Copying $src to $dst',
command = 'rm -rf ./$dst && ' +
'cp -aL $src $dst || true && ' +
'chmod -R +w $dst && ' +
'touch $stamp',
)
w.newline()
# cp... | def ninja_common_rules( w ):
# cpdir
| w.rule(
name = 'cpdir',
description = 'cpdir: Copying $src to $dst',
command = 'rm -rf ./$dst && ' +
'cp -aL $src $dst || true && ' +
'chmod -R +w $dst && ' +
'touch $stamp',
)
w.newline()
# cpdir-and-parameterize
#
# Copies a par... | the given dependencies
#
# - w : instance of ninja_syntax Writer
# - alias : alias name(s)
# - deps : dependencies
#
def ninja_alias( w, alias, deps ):
if deps:
assert type( deps ) == list, 'Expecting deps to be of type list'
w.build(
outputs = alias,
implicit = deps,
rule = 'phony',
... | 140 | 140 | 469 | 13 | 127 | jbrzozo24/mflowgen | mflowgen/backends/ninja_syntax_extra.py | Python | ninja_common_rules | ninja_common_rules | 206 | 267 | 206 | 209 | 8747cefe5dc3564ad886229ad815490ac3e9de3e | bigcode/the-stack | train |
6b3cee2aae0ed3c0100b1f38 | train | function | def ninja_runtimes( w ):
w.rule(
name = 'runtimes',
description = 'runtimes: Listing runtimes for each step',
command = get_top_dir() + '/mflowgen/scripts/mflowgen-runtimes',
)
w.newline()
w.build(
outputs = 'runtimes',
rule = 'runtimes',
)
w.newline()
| def ninja_runtimes( w ):
| w.rule(
name = 'runtimes',
description = 'runtimes: Listing runtimes for each step',
command = get_top_dir() + '/mflowgen/scripts/mflowgen-runtimes',
)
w.newline()
w.build(
outputs = 'runtimes',
rule = 'runtimes',
)
w.newline()
| ()
w.build(
outputs = name,
rule = name,
)
w.newline()
# ninja_runtimes
#
# Write out ninja rules for calculating runtimes from timestamps
#
# - w : instance of ninja_syntax Writer
#
def ninja_runtimes( w ):
| 64 | 64 | 93 | 9 | 55 | jbrzozo24/mflowgen | mflowgen/backends/ninja_syntax_extra.py | Python | ninja_runtimes | ninja_runtimes | 350 | 363 | 350 | 351 | 6e201e5a1e3951796e69c631fe6203aae65438c1 | bigcode/the-stack | train |
7be6999d5d9cb5b8a447e18b | train | function | def ninja_stamp( w, f, deps=None ):
if deps:
assert type( deps ) == list, 'Expecting deps to be of type list'
f_stamp = stamp( f )
w.build(
outputs = f_stamp,
implicit = [ f ] + deps,
rule = 'stamp',
variables = { 'stamp' : f_stamp },
)
w.newline()
return f_stamp
| def ninja_stamp( w, f, deps=None ):
| if deps:
assert type( deps ) == list, 'Expecting deps to be of type list'
f_stamp = stamp( f )
w.build(
outputs = f_stamp,
implicit = [ f ] + deps,
rule = 'stamp',
variables = { 'stamp' : f_stamp },
)
w.newline()
return f_stamp
| # ninja_stamp
#
# Stamps the given file with a '.stamp.' prefix
#
# - w : instance of ninja_syntax Writer
# - f : file to stamp
# - deps : additional dependencies for ninja build
#
def ninja_stamp( w, f, deps=None ):
| 64 | 64 | 94 | 12 | 52 | jbrzozo24/mflowgen | mflowgen/backends/ninja_syntax_extra.py | Python | ninja_stamp | ninja_stamp | 157 | 173 | 157 | 158 | f94d4bf858b125b23dbbf9d2b5c105e4808de4fc | bigcode/the-stack | train |
9c322a92810bb7f7e1d2dfec | train | function | def ninja_clean( w, name, command ):
w.rule(
name = name,
description = name + ': Clean build directories',
command = command,
)
w.newline()
w.build(
outputs = name,
rule = name,
)
w.newline()
| def ninja_clean( w, name, command ):
| w.rule(
name = name,
description = name + ': Clean build directories',
command = command,
)
w.newline()
w.build(
outputs = name,
rule = name,
)
w.newline()
| description = 'stamp: Stamping at $stamp',
command = 'touch $stamp',
)
w.newline()
# ninja_clean
#
# Write out ninja rules for cleaning
#
# - w : instance of ninja_syntax Writer
#
def ninja_clean( w, name, command ):
| 64 | 64 | 66 | 11 | 53 | jbrzozo24/mflowgen | mflowgen/backends/ninja_syntax_extra.py | Python | ninja_clean | ninja_clean | 276 | 289 | 276 | 277 | b13cd898b7f3da9d27faba75b8ab04074eefd25a | bigcode/the-stack | train |
2c3e472b2a310c61fe0e9fa4 | train | function | def ninja_cpdir( w, dst, src, deps=None, sandbox=True ):
if deps:
assert type( deps ) == list, 'Expecting deps to be of type list'
if sandbox:
rule = 'cpdir-and-parameterize'
else:
rule = 'mkdir-and-symlink'
target = dst + '/.stamp'
w.build(
outputs = target,
#implicit = [ src ] + d... | def ninja_cpdir( w, dst, src, deps=None, sandbox=True ):
| if deps:
assert type( deps ) == list, 'Expecting deps to be of type list'
if sandbox:
rule = 'cpdir-and-parameterize'
else:
rule = 'mkdir-and-symlink'
target = dst + '/.stamp'
w.build(
outputs = target,
#implicit = [ src ] + deps,
implicit = deps,
rule = rule,
varia... | directory
# - src : path to source directory
# - deps : list, additional dependencies for ninja build
# - sandbox : bool, True (copies src dir), False (symlinks src contents)
#
def ninja_cpdir( w, dst, src, deps=None, sandbox=True ):
| 64 | 64 | 143 | 18 | 46 | jbrzozo24/mflowgen | mflowgen/backends/ninja_syntax_extra.py | Python | ninja_cpdir | ninja_cpdir | 29 | 51 | 29 | 30 | cac57fb494b12803d18ad8e20ae7a4351e941e42 | bigcode/the-stack | train |
c107e965d2cc16807695ea55 | train | function | def ninja_graph_detailed( w, build_dirs ):
build_dirs_commas = ','.join( build_dirs )
python_graph_cmd = ' '.join([
get_top_dir() + '/mflowgen/scripts/mflowgen-graph',
'-t ' + build_dirs_commas,
'-g .graph.dot',
'-o .graph.subgraph.dot',
])
command = ' && '.join([
'ninja -t graph > .graph... | def ninja_graph_detailed( w, build_dirs ):
| build_dirs_commas = ','.join( build_dirs )
python_graph_cmd = ' '.join([
get_top_dir() + '/mflowgen/scripts/mflowgen-graph',
'-t ' + build_dirs_commas,
'-g .graph.dot',
'-o .graph.subgraph.dot',
])
command = ' && '.join([
'ninja -t graph > .graph.dot',
python_graph_cmd,
'dot -Tps2 ... | w : instance of ninja_syntax Writer
# - build_dirs : list of build directories
#
# The build directories are used to create subgraphs in the default ninja
# build graph.. otherwise the graph is too messy to see anything in.
#
def ninja_graph_detailed( w, build_dirs ):
| 64 | 64 | 196 | 12 | 52 | jbrzozo24/mflowgen | mflowgen/backends/ninja_syntax_extra.py | Python | ninja_graph_detailed | ninja_graph_detailed | 476 | 505 | 476 | 477 | 13d99c427acc315fad363a7abd3035077abb649d | bigcode/the-stack | train |
68a0b49cb315f16dbcff390f | train | function | def ninja_info( w, build_dir ):
build_id = build_dir.split('-')[0] # <- first number
step_name = '-'.join( build_dir.split('-')[1:]) # <- remainder
target = 'info-' + build_id
command = get_top_dir() + '/mflowgen/scripts/mflowgen-letters' \
+ ' -c -t ' + step_name
comman... | def ninja_info( w, build_dir ):
| build_id = build_dir.split('-')[0] # <- first number
step_name = '-'.join( build_dir.split('-')[1:]) # <- remainder
target = 'info-' + build_id
command = get_top_dir() + '/mflowgen/scripts/mflowgen-letters' \
+ ' -c -t ' + step_name
command = command + ' && ' + get_top_di... | 'status',
rule = 'status',
)
w.newline()
# ninja_info
#
# Write out rules for printing step info
#
# - w : instance of Writer
# - build_dir : build_dir for this info target
#
def ninja_info( w, build_dir ):
| 64 | 64 | 194 | 10 | 54 | jbrzozo24/mflowgen | mflowgen/backends/ninja_syntax_extra.py | Python | ninja_info | ninja_info | 541 | 565 | 541 | 542 | 487b00d6113f4d5937b98b3b6ed8d931a2e9638b | bigcode/the-stack | train |
f81f12c402dc4b05bd9f588c | train | class | class Worker(object):
def __init__(self, zmq_host, zmq_work_port, zmq_results_port, worker_id,
max_retries, profile_count=0, concurrency=256, batch_size=1):
work_endpoint = 'tcp://%s:%d' % (zmq_host, zmq_work_port)
results_endpoint = 'tcp://%s:%d' % (zmq_host, zmq_results_port)
... | class Worker(object):
| def __init__(self, zmq_host, zmq_work_port, zmq_results_port, worker_id,
max_retries, profile_count=0, concurrency=256, batch_size=1):
work_endpoint = 'tcp://%s:%d' % (zmq_host, zmq_work_port)
results_endpoint = 'tcp://%s:%d' % (zmq_host, zmq_results_port)
ipv6 = is_ipv6(zmq... | self.network_timeout = network_timeout
gevent.queue.Queue.__init__(self, maxsize)
logging.info('Initializing ConnectionPool to %s with %d '
'connections...',
factory_kwargs.get('url', 'UNKNOWN'), maxsize)
for _ in xrange(maxsize):
self.put... | 256 | 256 | 3,044 | 4 | 251 | yujunz/ssbench | ssbench/worker.py | Python | Worker | Worker | 76 | 443 | 76 | 76 | 1c72561ec2d278b1e889e0f8c4f7966d1a1eeb17 | bigcode/the-stack | train |
841da9184a91dd9a933d57fc | train | class | class ConnectionPool(gevent.queue.Queue):
def __init__(self, factory, factory_kwargs, maxsize=1,
network_timeout=client.DEFAULT_NETWORK_TIMEOUT):
self.factory = factory
self.factory_kwargs = factory_kwargs
self.network_timeout = network_timeout
gevent.queue.Queue.__... | class ConnectionPool(gevent.queue.Queue):
| def __init__(self, factory, factory_kwargs, maxsize=1,
network_timeout=client.DEFAULT_NETWORK_TIMEOUT):
self.factory = factory
self.factory_kwargs = factory_kwargs
self.network_timeout = network_timeout
gevent.queue.Queue.__init__(self, maxsize)
logging.inf... |
from httplib import CannotSendRequest
from contextlib import contextmanager
from geventhttpclient.response import HTTPConnectionClosed
from ssbench.importer import random
from ssbench.util import add_dicts, raise_file_descriptor_limit
from ssbench.util import is_ipv6
import ssbench.swift_client as client
DEFAULT_BL... | 90 | 90 | 302 | 9 | 80 | yujunz/ssbench | ssbench/worker.py | Python | ConnectionPool | ConnectionPool | 38 | 73 | 38 | 38 | 25a42b5d59b67a5cebbacd823f42c7d3fd255490 | bigcode/the-stack | train |
d2b3e932c1eb1a9ebe2aa6f5 | train | function | def main():
SDK_URL = ""
if "SDK_URL" in os.environ:
SDK_URL = os.environ["SDK_URL"]
TARGET_LIBS_ZIP = "agora_sdk.zip"
TARGET_INTERNAL_FOLDER = "agora_sdk"
#if need reset
ZIP_STRUCTURE_FOLDER = "Agora_Native_SDK_for_iOS_FULL/libs"
CRY_FRAMEWORK_NAME = "AgoraRtcCryptoLoader.f... | def main():
| SDK_URL = ""
if "SDK_URL" in os.environ:
SDK_URL = os.environ["SDK_URL"]
TARGET_LIBS_ZIP = "agora_sdk.zip"
TARGET_INTERNAL_FOLDER = "agora_sdk"
#if need reset
ZIP_STRUCTURE_FOLDER = "Agora_Native_SDK_for_iOS_FULL/libs"
CRY_FRAMEWORK_NAME = "AgoraRtcCryptoLoader.framework"
... | #!/usr/bin/python
# -*- coding: UTF-8 -*-
import re
import os
def main():
| 22 | 148 | 495 | 3 | 18 | AgoraIO-Community/RTC-Hackthon | UIChallengeProject/1099+iOS/OpenLive-iOS/ci.env.py | Python | main | main | 6 | 61 | 6 | 6 | 6ff8d199fec1008f6616b8b35e03fcaf5d78fba4 | bigcode/the-stack | train |
a1b3cbf382d692b17b81ca0b | train | function | def get_param_binary_baseline():
params = get_base_params()
baseline_params = {
'objective': 'binary:logistic',
'booster': 'gbtree',
'use_label_encoder': False,
}
params.update(baseline_params)
return params
| def get_param_binary_baseline():
| params = get_base_params()
baseline_params = {
'objective': 'binary:logistic',
'booster': 'gbtree',
'use_label_encoder': False,
}
params.update(baseline_params)
return params
| ():
base_params = {
'n_estimators': DEFAULT_NUM_BOOST_ROUND,
'learning_rate': 0.1,
'n_jobs': -1,
'proc.max_category_levels' : MAX_CATEGORY_LEVELS,
}
return base_params
def get_param_binary_baseline():
| 64 | 64 | 60 | 7 | 56 | zhiqiangdon/autogluon | tabular/src/autogluon/tabular/models/xgboost/hyperparameters/parameters.py | Python | get_param_binary_baseline | get_param_binary_baseline | 31 | 39 | 31 | 31 | 86305ca0e87964c4cb6db0f80cdac33423924eee | bigcode/the-stack | train |
03bc14f5156072952b1aca0d | train | function | def get_param_regression_baseline():
params = get_base_params()
baseline_params = {
'objective': 'reg:squarederror',
'booster': 'gbtree',
}
params.update(baseline_params)
return params
| def get_param_regression_baseline():
| params = get_base_params()
baseline_params = {
'objective': 'reg:squarederror',
'booster': 'gbtree',
}
params.update(baseline_params)
return params
| _params()
baseline_params = {
'objective': 'multi:softmax',
'booster': 'gbtree',
'num_class': num_classes,
'use_label_encoder': False,
}
params.update(baseline_params)
return params
def get_param_regression_baseline():
| 64 | 64 | 54 | 8 | 55 | zhiqiangdon/autogluon | tabular/src/autogluon/tabular/models/xgboost/hyperparameters/parameters.py | Python | get_param_regression_baseline | get_param_regression_baseline | 54 | 61 | 54 | 54 | fad6ca74ea601499809dcbfa62b8326c48e50654 | bigcode/the-stack | train |
c2fe332d6d69a90b26920cd1 | train | function | def get_base_params():
base_params = {
'n_estimators': DEFAULT_NUM_BOOST_ROUND,
'learning_rate': 0.1,
'n_jobs': -1,
'proc.max_category_levels' : MAX_CATEGORY_LEVELS,
}
return base_params
| def get_base_params():
| base_params = {
'n_estimators': DEFAULT_NUM_BOOST_ROUND,
'learning_rate': 0.1,
'n_jobs': -1,
'proc.max_category_levels' : MAX_CATEGORY_LEVELS,
}
return base_params
| _baseline(num_classes=num_classes)
elif problem_type == SOFTCLASS:
return get_param_multiclass_baseline(num_classes=num_classes)
elif problem_type == REGRESSION:
return get_param_regression_baseline()
else:
return get_param_binary_baseline()
def get_base_params():
| 64 | 64 | 61 | 5 | 59 | zhiqiangdon/autogluon | tabular/src/autogluon/tabular/models/xgboost/hyperparameters/parameters.py | Python | get_base_params | get_base_params | 21 | 28 | 21 | 21 | 1616df407b36a09625f106cb1d109163179439b8 | bigcode/the-stack | train |
adf330c6f0596fe27d152027 | train | function | def get_param_baseline(problem_type, num_classes=None):
if problem_type == BINARY:
return get_param_binary_baseline()
elif problem_type == MULTICLASS:
return get_param_multiclass_baseline(num_classes=num_classes)
elif problem_type == SOFTCLASS:
return get_param_multiclass_baseline(nu... | def get_param_baseline(problem_type, num_classes=None):
| if problem_type == BINARY:
return get_param_binary_baseline()
elif problem_type == MULTICLASS:
return get_param_multiclass_baseline(num_classes=num_classes)
elif problem_type == SOFTCLASS:
return get_param_multiclass_baseline(num_classes=num_classes)
elif problem_type == REGRESSI... | = 10000
MAX_CATEGORY_LEVELS = 100 # maximum number of allowed levels per categorical feature
# Options: [10, 100, 200, 300, 400, 500, 1000, 10000]
def get_param_baseline(problem_type, num_classes=None):
| 64 | 64 | 104 | 12 | 52 | zhiqiangdon/autogluon | tabular/src/autogluon/tabular/models/xgboost/hyperparameters/parameters.py | Python | get_param_baseline | get_param_baseline | 8 | 18 | 8 | 8 | d59b2851518c0a89961d3d138805901497f20801 | bigcode/the-stack | train |
fc4564fdde3d11012992f3b5 | train | function | def get_param_multiclass_baseline(num_classes):
params = get_base_params()
baseline_params = {
'objective': 'multi:softmax',
'booster': 'gbtree',
'num_class': num_classes,
'use_label_encoder': False,
}
params.update(baseline_params)
return params
| def get_param_multiclass_baseline(num_classes):
| params = get_base_params()
baseline_params = {
'objective': 'multi:softmax',
'booster': 'gbtree',
'num_class': num_classes,
'use_label_encoder': False,
}
params.update(baseline_params)
return params
| params = get_base_params()
baseline_params = {
'objective': 'binary:logistic',
'booster': 'gbtree',
'use_label_encoder': False,
}
params.update(baseline_params)
return params
def get_param_multiclass_baseline(num_classes):
| 64 | 64 | 72 | 11 | 52 | zhiqiangdon/autogluon | tabular/src/autogluon/tabular/models/xgboost/hyperparameters/parameters.py | Python | get_param_multiclass_baseline | get_param_multiclass_baseline | 42 | 51 | 42 | 42 | ecbff3ddd13d5ec61c223644fbab54a8d112a0ac | bigcode/the-stack | train |
ca4c983c9f5e87b62846c708 | train | function | def quote(name):
remove_chars = ['"', "'"]
for i in remove_chars:
name = name.replace(i, '')
return name
| def quote(name):
| remove_chars = ['"', "'"]
for i in remove_chars:
name = name.replace(i, '')
return name
| =api,
base_url=url,
verify=verify # TLS certificate verification
)
def clean_for_spdx(name):
newname = re.sub('[;:!*()/,]', '', name)
newname = re.sub('[ .]', '', newname)
return newname
def quote(name):
| 64 | 64 | 31 | 4 | 59 | matthewb66/bdconsole | addons/export_spdx.py | Python | quote | quote | 149 | 153 | 149 | 149 | 2e6a1b068294eaffa13c6a4cb9a2e8428af880fd | bigcode/the-stack | train |
806ff4b6277d4ba92c189ccf | train | function | def check_projver(pargs):
params = {
'q': "name:" + pargs.project_name,
'sort': 'name',
}
projects = bd.get_resource('projects', params=params, items=False)
if projects['totalCount'] == 0:
print("Project '{}' does not exist".format(pargs.project_name))
print('Available p... | def check_projver(pargs):
| params = {
'q': "name:" + pargs.project_name,
'sort': 'name',
}
projects = bd.get_resource('projects', params=params, items=False)
if projects['totalCount'] == 0:
print("Project '{}' does not exist".format(pargs.project_name))
print('Available projects:')
project... | opyrights = True
args.no_files = True
if args.output == "":
args.output = clean_for_spdx(args.project_name + "-" + args.project_version) + ".json"
if args.output and os.path.exists(args.output):
backup_file(args.output)
def check_projver(pargs):
| 64 | 64 | 196 | 7 | 57 | matthewb66/bdconsole | addons/export_spdx.py | Python | check_projver | check_projver | 744 | 766 | 744 | 744 | 60c29aad28b149ee4c588279cc986269d332c50b | bigcode/the-stack | train |
05b4933b4e756cd795a43837 | train | function | def get_all_projects():
global bd
projs = bd.get_resource('projects', items=True)
projlist = []
for proj in projs:
projlist.append(proj['name'])
return projlist
| def get_all_projects():
| global bd
projs = bd.get_resource('projects', items=True)
projlist = []
for proj in projs:
projlist.append(proj['name'])
return projlist
| ('[;:!*()/,]', '', name)
newname = re.sub('[ .]', '', newname)
return newname
def quote(name):
remove_chars = ['"', "'"]
for i in remove_chars:
name = name.replace(i, '')
return name
def get_all_projects():
| 64 | 64 | 48 | 5 | 58 | matthewb66/bdconsole | addons/export_spdx.py | Python | get_all_projects | get_all_projects | 156 | 163 | 156 | 156 | 19730d0e92a061234cc5508036c751dc5a9032aa | bigcode/the-stack | train |
dc6098d193d91d69be4d58ee | train | function | def process_project(projspdxname, hcomps, bom):
global proj_list
global spdx
global spdx_custom_lics
#
# Process hierarchical BOM elements
for hcomp in hcomps:
if 'componentVersionName' in hcomp:
print("{}/{}".format(hcomp['componentName'], hcomp['componentVersionName']))
... | def process_project(projspdxname, hcomps, bom):
| global proj_list
global spdx
global spdx_custom_lics
#
# Process hierarchical BOM elements
for hcomp in hcomps:
if 'componentVersionName' in hcomp:
print("{}/{}".format(hcomp['componentName'], hcomp['componentVersionName']))
else:
print("{}/? - (no versio... | ,
matchtype_contains_dict[tchecktype])
break
processed_comp_list.append(child)
if len(child['_meta']['links']) > 2:
thisref = [d['href'] for d in child['_meta']['links'] if d['rel'] == 'children']
process_child... | 224 | 224 | 748 | 14 | 209 | matthewb66/bdconsole | addons/export_spdx.py | Python | process_project | process_project | 594 | 676 | 594 | 594 | 3785d277ee02d0d0de3850a7854d16941d11e010 | bigcode/the-stack | train |
5e19befa9260784efef6795f | train | function | def get_files(fcomp):
# Get files
retfile = "NOASSERTION"
hrefs = fcomp['_meta']['links']
link = next((item for item in hrefs if item["rel"] == "matched-files"), None)
if link:
thishref = link['href']
headers = {
'accept': "application/vnd.blackducksoftware.bill-of-mater... | def get_files(fcomp):
# Get files
| retfile = "NOASSERTION"
hrefs = fcomp['_meta']['links']
link = next((item for item in hrefs if item["rel"] == "matched-files"), None)
if link:
thishref = link['href']
headers = {
'accept': "application/vnd.blackducksoftware.bill-of-materials-6+json",
}
resp =... | Y-%m-%dT%H:%M:%S.%fZ")),
"annotationType": "OTHER",
"annotator": quote("Person: " + comment['user']['email']),
"comment": quote(comment['comment']),
}
)
return annotations
def get_files(fcomp):
# Get files
| 69 | 69 | 233 | 11 | 57 | matthewb66/bdconsole | addons/export_spdx.py | Python | get_files | get_files | 442 | 463 | 442 | 443 | ef07a7d2bd02cb3005ef2c20feef610cd53750c8 | bigcode/the-stack | train |
b896809e52ff94e9fa3c918e | train | function | def get_orig_data(dcomp):
# Get copyrights, CPE
copyrights = "NOASSERTION"
cpe = "NOASSERTION"
pkg = "NOASSERTION"
try:
if 'origins' in dcomp.keys() and len(dcomp['origins']) > 0:
orig = dcomp['origins'][0]
if 'externalNamespace' in orig.keys() and 'externalId' in ori... | def get_orig_data(dcomp):
# Get copyrights, CPE
| copyrights = "NOASSERTION"
cpe = "NOASSERTION"
pkg = "NOASSERTION"
try:
if 'origins' in dcomp.keys() and len(dcomp['origins']) > 0:
orig = dcomp['origins'][0]
if 'externalNamespace' in orig.keys() and 'externalId' in orig.keys():
pkg = calculate_purl(orig[... | re.match('^(\d+):', compver) # 10
if epoch_m:
qual['epoch'] = epoch_m[1]
if qual:
purl += '?' + '&'.join('='.join([k, quote(v)]) for k, v in qual.items()) # 8
return purl
return ''
def get_orig_data(dcomp):
# Get copyrights, CPE
| 91 | 92 | 308 | 15 | 76 | matthewb66/bdconsole | addons/export_spdx.py | Python | get_orig_data | get_orig_data | 379 | 413 | 379 | 380 | a77967b51169f946e8bc76ef7f26ec973ac73672 | bigcode/the-stack | train |
12589941733f7cbe975b72ee | train | function | def get_bom_components(ver):
global bom_comp_dict
res = bd.list_resources(ver)
if 'components' not in res:
thishref = res['href'] + "/components?limit=2000"
headers = {
'accept': "application/vnd.blackducksoftware.bill-of-materials-6+json",
}
res = bd.get_json(th... | def get_bom_components(ver):
| global bom_comp_dict
res = bd.list_resources(ver)
if 'components' not in res:
thishref = res['href'] + "/components?limit=2000"
headers = {
'accept': "application/vnd.blackducksoftware.bill-of-materials-6+json",
}
res = bd.get_json(thishref, headers=headers)
... | params=params)
for ver in versions:
if ver['versionName'] == pargs.project_version:
return proj, ver
print("Version '{}' does not exist in project '{}'".format(pargs.project_name, pargs.project_version))
sys.exit(2)
def get_bom_components(ver):
| 64 | 64 | 164 | 7 | 57 | matthewb66/bdconsole | addons/export_spdx.py | Python | get_bom_components | get_bom_components | 769 | 790 | 769 | 769 | b2667fd3a1f7e692f6a90c878f554fda11249ffa | bigcode/the-stack | train |
f7853621ed620ba8b9391b7a | train | function | def clean_for_spdx(name):
newname = re.sub('[;:!*()/,]', '', name)
newname = re.sub('[ .]', '', newname)
return newname
| def clean_for_spdx(name):
| newname = re.sub('[;:!*()/,]', '', name)
newname = re.sub('[ .]', '', newname)
return newname
| '' or api is None:
print('BLACKDUCK_API_TOKEN not set or specified as option --blackduck_api_token')
sys.exit(2)
bd = Client(
token=api,
base_url=url,
verify=verify # TLS certificate verification
)
def clean_for_spdx(name):
| 64 | 64 | 41 | 7 | 57 | matthewb66/bdconsole | addons/export_spdx.py | Python | clean_for_spdx | clean_for_spdx | 143 | 146 | 143 | 143 | afc0419e4958b728956bdc37c1f9b88ac6800417 | bigcode/the-stack | train |
4a2608a636fc2b5d83207b9c | train | function | def process_children(pkgname, compverurl, child_url, indenttext):
global spdx_custom_lics
res = bd.get_json(child_url)
for child in res['items']:
if 'componentName' in child and 'componentVersionName' in child:
print("{}{}/{}".format(indenttext, child['componentName'], child['component... | def process_children(pkgname, compverurl, child_url, indenttext):
| global spdx_custom_lics
res = bd.get_json(child_url)
for child in res['items']:
if 'componentName' in child and 'componentVersionName' in child:
print("{}{}/{}".format(indenttext, child['componentName'], child['componentVersionName']))
else:
# No version - skip
... | is the external ref for Acme,
"copyrightText": quote(copyrights),
"annotations": annotations,
}
if pkg != '':
thisdict["externalRefs"] = [
{
"referenceLocator": pkg,
"referenceCategory": "OTHER",
... | 94 | 94 | 315 | 16 | 77 | matthewb66/bdconsole | addons/export_spdx.py | Python | process_children | process_children | 542 | 575 | 542 | 542 | 18dfa4774f58697c81114408924784aa6d70e725 | bigcode/the-stack | train |
b75255a876b2f646e64d7579 | train | function | def process_comp_relationship(parentname, childname, mtypes):
global matchtype_depends_dict
reln = False
for tchecktype in matchtype_depends_dict.keys():
if tchecktype in mtypes:
add_relationship(parentname, childname, matchtype_depends_dict[tchecktype])
reln = True
... | def process_comp_relationship(parentname, childname, mtypes):
| global matchtype_depends_dict
reln = False
for tchecktype in matchtype_depends_dict.keys():
if tchecktype in mtypes:
add_relationship(parentname, childname, matchtype_depends_dict[tchecktype])
reln = True
break
if not reln:
for tchecktype in matchtype... | = [d['href'] for d in child['_meta']['links'] if d['rel'] == 'children']
process_children(childpkgname, child['componentVersion'], thisref[0], " " + indenttext)
return
def process_comp_relationship(parentname, childname, mtypes):
| 64 | 64 | 123 | 13 | 50 | matthewb66/bdconsole | addons/export_spdx.py | Python | process_comp_relationship | process_comp_relationship | 578 | 591 | 578 | 578 | 3f3753935ad58c7fe18f6b40ef1d2e4be5079651 | bigcode/the-stack | train |
c99939c81edc7d28d52a88d2 | train | function | def get_comments(ccomp):
# Get comments/annotations
annotations = []
hrefs = ccomp['_meta']['links']
link = next((item for item in hrefs if item["rel"] == "comments"), None)
if link:
thishref = link['href']
headers = {
'accept': "application/vnd.blackducksoftware.bill-of... | def get_comments(ccomp):
# Get comments/annotations
| annotations = []
hrefs = ccomp['_meta']['links']
link = next((item for item in hrefs if item["rel"] == "comments"), None)
if link:
thishref = link['href']
headers = {
'accept': "application/vnd.blackducksoftware.bill-of-materials-6+json",
}
resp = bd.get_json... | + thiscr
else:
pass
# print(" INFO: No copyright data available due to no assigned origin")
except Exception as exc:
print("except" + str(exc))
return copyrights, cpe, pkg
def get_comments(ccomp):
# Get comments/annotations
| 64 | 64 | 210 | 13 | 50 | matthewb66/bdconsole | addons/export_spdx.py | Python | get_comments | get_comments | 416 | 439 | 416 | 417 | b325c8ae558081ddf16feb508f44b76959fd7724 | bigcode/the-stack | train |
e7a0b8bed38da7dbb5527764 | train | function | def check_params():
global args
if args.version:
print("Script version: " + script_version)
sys.exit(0)
if args.basic:
args.download_loc = False
args.no_copyrights = True
args.no_files = True
if args.output == "":
args.output = clean_for_spdx(args.projec... | def check_params():
| global args
if args.version:
print("Script version: " + script_version)
sys.exit(0)
if args.basic:
args.download_loc = False
args.no_copyrights = True
args.no_files = True
if args.output == "":
args.output = clean_for_spdx(args.project_name + "-" + args.... | _relationship(parent, child, reln):
global spdx
mydict = {
"spdxElementId": quote(parent),
"relationshipType": quote(reln),
"relatedSpdxElement": quote(child)
}
spdx['relationships'].append(mydict)
def check_params():
| 64 | 64 | 103 | 4 | 60 | matthewb66/bdconsole | addons/export_spdx.py | Python | check_params | check_params | 726 | 741 | 726 | 726 | fb352a7c467fb7c60929a584dcf9c3e95c950272 | bigcode/the-stack | train |
07bd7457061946468e121745 | train | function | def process_comp(tcomp):
# global output_dict
global bom_components
global bom_comp_dict
global spdx_custom_lics
global spdx
global processed_comp_list
cver = tcomp['componentVersion']
if cver in bom_comp_dict.keys():
# ind = compverlist.index(tcomp['componentVersion'])
... | def process_comp(tcomp):
# global output_dict
| global bom_components
global bom_comp_dict
global spdx_custom_lics
global spdx
global processed_comp_list
cver = tcomp['componentVersion']
if cver in bom_comp_dict.keys():
# ind = compverlist.index(tcomp['componentVersion'])
bomentry = bom_comp_dict[cver]
else:
b... | if item["rel"] == "matched-files"), None)
if link:
thishref = link['href']
headers = {
'accept': "application/vnd.blackducksoftware.bill-of-materials-6+json",
}
resp = bd.get_json(thishref, headers=headers)
cfile = resp['items']
if len(cfile) > 0:
... | 203 | 203 | 678 | 12 | 191 | matthewb66/bdconsole | addons/export_spdx.py | Python | process_comp | process_comp | 466 | 539 | 466 | 467 | 55a9a9f91af0dc092a19d881f0f6be38d858f138 | bigcode/the-stack | train |
acf1b0724bb104cdfeeb4051 | train | function | def add_relationship(parent, child, reln):
global spdx
mydict = {
"spdxElementId": quote(parent),
"relationshipType": quote(reln),
"relatedSpdxElement": quote(child)
}
spdx['relationships'].append(mydict)
| def add_relationship(parent, child, reln):
| global spdx
mydict = {
"spdxElementId": quote(parent),
"relationshipType": quote(reln),
"relatedSpdxElement": quote(child)
}
spdx['relationships'].append(mydict)
| ": 310,
# "reference": "SPDXRef-DoapSource"
# }
# }],
# "snippetFromFile": "SPDXRef-DoapSource"
# }],
pass
def add_relationship(parent, child, reln):
| 64 | 64 | 62 | 10 | 53 | matthewb66/bdconsole | addons/export_spdx.py | Python | add_relationship | add_relationship | 715 | 723 | 715 | 715 | 47148b3e5aae34dba334bc7330aaa1cb0450d030 | bigcode/the-stack | train |
4619ee0f45b92bdd57fbbd04 | train | function | def backup_file(filename):
import os
if os.path.isfile(filename):
# Determine root filename so the extension doesn't get longer
n = os.path.splitext(filename)[0]
# Is e an integer?
try:
root = n
except ValueError:
root = filename
# Find ... | def backup_file(filename):
| import os
if os.path.isfile(filename):
# Determine root filename so the extension doesn't get longer
n = os.path.splitext(filename)[0]
# Is e an integer?
try:
root = n
except ValueError:
root = filename
# Find next available file version... | name = name.replace(i, '')
return name
def get_all_projects():
global bd
projs = bd.get_resource('projects', items=True)
projlist = []
for proj in projs:
projlist.append(proj['name'])
return projlist
def backup_file(filename):
| 64 | 64 | 142 | 5 | 58 | matthewb66/bdconsole | addons/export_spdx.py | Python | backup_file | backup_file | 166 | 186 | 166 | 166 | 7867dce740db125fbc55b68efd147dd00e976cce | bigcode/the-stack | train |
e8b3a62aedf5a2e723e1b969 | train | function | def openhub_get_download(oh_url):
try:
page = requests.get(oh_url)
tree = html.fromstring(page.content)
link = ""
enlistments = tree.xpath("//a[text()='Project Links:']//following::a[text()='Code Locations:']//@href")
if len(enlistments) > 0:
enlist_url = "https:... | def openhub_get_download(oh_url):
| try:
page = requests.get(oh_url)
tree = html.fromstring(page.content)
link = ""
enlistments = tree.xpath("//a[text()='Project Links:']//following::a[text()='Code Locations:']//@href")
if len(enlistments) > 0:
enlist_url = "https://openhub.net" + str(enlistments[0... | = "{}.{:03d}".format(root, i)
if not os.path.isfile(new_file):
os.rename(filename, new_file)
print("INFO: Moved old output file '{}' to '{}'\n".format(filename, new_file))
return new_file
return ''
def openhub_get_download(oh_url):
| 68 | 69 | 230 | 9 | 59 | matthewb66/bdconsole | addons/export_spdx.py | Python | openhub_get_download | openhub_get_download | 189 | 214 | 189 | 189 | 51930cc254583a2e1b9446d817bea1253e443d30 | bigcode/the-stack | train |
195e923d9e795d3a68c4b2c5 | train | function | def calculate_purl(namespace, extid):
spdx_origin_map = {
"alpine": {"p_type": "apk", "p_namespace": "alpine", "p_sep": "/"},
"android": {"p_type": "apk", "p_namespace": "android", "p_sep": ":"},
"bitbucket": {"p_type": "bitbucket", "p_namespace": "", "p_sep": ":"},
"bower": {"p_type... | def calculate_purl(namespace, extid):
| spdx_origin_map = {
"alpine": {"p_type": "apk", "p_namespace": "alpine", "p_sep": "/"},
"android": {"p_type": "apk", "p_namespace": "android", "p_sep": ":"},
"bitbucket": {"p_type": "bitbucket", "p_namespace": "", "p_sep": ":"},
"bower": {"p_type": "bower", "p_namespace": "", "p_sep"... | += "/" + 1st part of split(component_id by id_separator)
# 6. if id_separator not in component_id:
# if external_namespace is pypi
# then purl += "/" + regexp_replace(lower(component_id), '[-_.]+', '-', 'g')
# else purl += "/{:component_id}"
# else
# purl += "/" + 2n... | 256 | 256 | 1,293 | 9 | 247 | matthewb66/bdconsole | addons/export_spdx.py | Python | calculate_purl | calculate_purl | 301 | 376 | 301 | 301 | a1b766c4834db808c31aff1400b2dc99342484c1 | bigcode/the-stack | train |
b9da2f217f6ced455d09376d | train | function | def add_snippet():
# "snippets": [{
# "SPDXID": "SPDXRef-Snippet",
# "comment": "This snippet was identified as significant and highlighted in this Apache-2.0 file, when a
# commercial scanner identified it as being derived from file foo.c in package xyz which is licensed under
# GPL-2.0.",
... | def add_snippet():
# "snippets": [{
# "SPDXID": "SPDXRef-Snippet",
# "comment": "This snippet was identified as significant and highlighted in this Apache-2.0 file, when a
# commercial scanner identified it as being derived from file foo.c in package xyz which is licensed under
# GPL-2.0.",
... | pass
| def add_snippet():
# "snippets": [{
# "SPDXID": "SPDXRef-Snippet",
# "comment": "This snippet was identified as significant and highlighted in this Apache-2.0 file, when a
# commercial scanner identified it as being derived from file foo.c in package xyz which is licensed under
# GPL-2.0.",
... | 407 | 123 | 410 | 407 | 0 | matthewb66/bdconsole | addons/export_spdx.py | Python | add_snippet | add_snippet | 679 | 712 | 679 | 711 | 833cf913f9f17196557cb7d7a5279fbfb07b69b8 | bigcode/the-stack | train |
5fb9d3c916c910bc74f8a770 | train | function | def get_licenses(lcomp):
global spdx_custom_lics
# Get licenses
lic_string = "NOASSERTION"
quotes = False
if 'licenses' in lcomp.keys():
proc_item = lcomp['licenses']
if len(proc_item[0]['licenses']) > 1:
proc_item = proc_item[0]['licenses']
for lic in proc_ite... | def get_licenses(lcomp):
| global spdx_custom_lics
# Get licenses
lic_string = "NOASSERTION"
quotes = False
if 'licenses' in lcomp.keys():
proc_item = lcomp['licenses']
if len(proc_item[0]['licenses']) > 1:
proc_item = proc_item[0]['licenses']
for lic in proc_item:
thislic = ... | 1]/text()")
if len(link) > 0:
sp = str(link[0].split(" ")[0]).replace('\n', '')
#
# Check format
protocol = sp.split('://')[0]
if protocol in ['https', 'http', 'git']:
return sp
except Exception as exc:
print('ERROR: Canno... | 109 | 109 | 365 | 7 | 102 | matthewb66/bdconsole | addons/export_spdx.py | Python | get_licenses | get_licenses | 217 | 265 | 217 | 217 | 1fe9a67e2aa9151eba123367a0d632359b8aa62c | bigcode/the-stack | train |
0e0776d04c4982acfdabe9e0 | train | class | class ParameterSet(NamedItem):
"""
Collection of model parameters to run a simulation
A ParameterSet contains a collection of Parameters required to run the simulation.
The parameters contain scale factors used for calibration, so often a project will
contain multiple ParameterSets corresponding to... | class ParameterSet(NamedItem):
| """
Collection of model parameters to run a simulation
A ParameterSet contains a collection of Parameters required to run the simulation.
The parameters contain scale factors used for calibration, so often a project will
contain multiple ParameterSets corresponding to different calibrations.
A... | for generation of smoothed/interpolated values, default uses sciris smoothinterp
:param pop_names: Optionally specify a list of populations to modify
:param kwargs: Optionally pass arguments to the generating function/class constructor
:return:
"""
pop_names = sc.promotetolist... | 256 | 256 | 2,133 | 7 | 249 | atomicateam/atomica | atomica/parameters.py | Python | ParameterSet | ParameterSet | 168 | 393 | 168 | 168 | a20519d351f36dedce062c571e092f8efced098e | bigcode/the-stack | train |
5c209c24634aa71373118544 | train | class | class Parameter(NamedItem):
"""
Class to hold one set of parameter values disaggregated by populations.
:param name: The name of the parameter (should match framework code name)
:param ts: A dict where the key is population name and the value is a TimeSeries instance
"""
def __init__(self, na... | class Parameter(NamedItem):
| """
Class to hold one set of parameter values disaggregated by populations.
:param name: The name of the parameter (should match framework code name)
:param ts: A dict where the key is population name and the value is a TimeSeries instance
"""
def __init__(self, name: str, ts: dict):
... | """
Implements data-based model parameters (:class:`ParameterSet`)
A :class:`ParameterSet` (or 'parset') is an intermediate representation of
model parameters. The main role of the parset is to store the calibration
values that are used to scale model parameters. Therefore, every parameter
in the model appears in the ... | 143 | 256 | 1,325 | 6 | 137 | atomicateam/atomica | atomica/parameters.py | Python | Parameter | Parameter | 23 | 165 | 23 | 23 | bda97ce97c7f85ff1b94bde89ab7153dedbd0acc | bigcode/the-stack | train |
c7a42814c4e71e3885675e8d | train | class | class sizable_button(pg.sprite.Sprite):
def __init__(self,x,y,text,screen,width,height,font_size,text_padding, clr, cngclr):
super().__init__()
self.x = x
self.y = y
self.text = text
self.screen = screen
self.curclr = clr
self.clr = clr
self.c... | class sizable_button(pg.sprite.Sprite):
| def __init__(self,x,y,text,screen,width,height,font_size,text_padding, clr, cngclr):
super().__init__()
self.x = x
self.y = y
self.text = text
self.screen = screen
self.curclr = clr
self.clr = clr
self.cngclr = cngclr
self.size = font_... | #self.x - WIDTH
def mouseover(self,pos):
if pos[0] > self.x - (WIDTH/6) and pos[0] < self.x + (WIDTH/6):
if pos[1] > self.y - (HEIGHT/20) and pos[1] < self.y + (HEIGHT/20):
return True
return False
class sizable_button(pg.sprite.Sprite):
| 87 | 87 | 290 | 7 | 79 | zekebrmn/PyFlappy | buttons.py | Python | sizable_button | sizable_button | 35 | 66 | 35 | 35 | 46caab7fa747ba284131fae6698560c1ed26a1e6 | bigcode/the-stack | train |
70015811bf484653c91fba88 | train | class | class button(pg.sprite.Sprite):
def __init__(self,x,y,text,screen,clr,cngclr):
super().__init__()
self.x = x
self.y = y
self.text = text
self.screen = screen
self.curclr = clr
self.clr = clr
self.cngclr = cngclr
self.surf=pg.Surface((... | class button(pg.sprite.Sprite):
| def __init__(self,x,y,text,screen,clr,cngclr):
super().__init__()
self.x = x
self.y = y
self.text = text
self.screen = screen
self.curclr = clr
self.clr = clr
self.cngclr = cngclr
self.surf=pg.Surface((WIDTH/3,HEIGHT/10))
self... | import pygame as pg
from settings import *
from util import *
class button(pg.sprite.Sprite):
| 19 | 78 | 261 | 6 | 13 | zekebrmn/PyFlappy | buttons.py | Python | button | button | 5 | 32 | 5 | 5 | 3eb92d191148e2c26c5d16ed98e3642b00f3895a | bigcode/the-stack | train |
94afe8c69ac48b097ad9f540 | train | function | def _seed(table_obj, file_path, tx=None):
with open(file_path, 'r') as f:
reader = DictReader(f, delimiter=',')
rows = list(reader)
if tx is not None:
rows = [_tx_row(row, tx) for row in rows]
op.bulk_insert(table_obj, rows)
| def _seed(table_obj, file_path, tx=None):
| with open(file_path, 'r') as f:
reader = DictReader(f, delimiter=',')
rows = list(reader)
if tx is not None:
rows = [_tx_row(row, tx) for row in rows]
op.bulk_insert(table_obj, rows)
| , books_file)
def downgrade():
_downgrade(user_table)
_downgrade(author_table)
_downgrade(book_table, 'isbn')
_downgrade(booking_table)
_downgrade(loan_table)
def _seed(table_obj, file_path, tx=None):
| 64 | 64 | 71 | 12 | 52 | gekorob/liebraryrest | migrations/versions/a16400f30ed4_.py | Python | _seed | _seed | 64 | 72 | 64 | 64 | 84a252350e9f1fb9280b5cfdb3de7164ed15ccf1 | bigcode/the-stack | train |
698ed9927cad054432ee0878 | train | function | def downgrade():
_downgrade(user_table)
_downgrade(author_table)
_downgrade(book_table, 'isbn')
_downgrade(booking_table)
_downgrade(loan_table)
| def downgrade():
| _downgrade(user_table)
_downgrade(author_table)
_downgrade(book_table, 'isbn')
_downgrade(booking_table)
_downgrade(loan_table)
| ')
books_file = os.path.join(csv_path, 'books.csv')
_seed(user_table, users_file)
_seed(author_table, authors_file,
{'birth_date': (lambda d: datetime.strptime(d, '%Y%m%d'))})
_seed(book_table, books_file)
def downgrade():
| 64 | 64 | 48 | 3 | 61 | gekorob/liebraryrest | migrations/versions/a16400f30ed4_.py | Python | downgrade | downgrade | 56 | 61 | 56 | 56 | 7099ff84500fea2851f774d3eccc2316af55bfe8 | bigcode/the-stack | train |
2ee7f1ac7774f6205e856a57 | train | function | def _downgrade(table_obj, primary_key=None):
bind = op.get_bind()
key = 'id'
if primary_key is not None:
key = primary_key
for row in bind.execute(table_obj.select()):
op.execute(table_obj.delete().where(getattr(table_obj.c, key) == getattr(row, key)))
| def _downgrade(table_obj, primary_key=None):
| bind = op.get_bind()
key = 'id'
if primary_key is not None:
key = primary_key
for row in bind.execute(table_obj.select()):
op.execute(table_obj.delete().where(getattr(table_obj.c, key) == getattr(row, key)))
| rows = [_tx_row(row, tx) for row in rows]
op.bulk_insert(table_obj, rows)
def _tx_row(row, tx):
for k in tx:
row[k] = tx[k](row[k])
return row
def _downgrade(table_obj, primary_key=None):
| 64 | 64 | 71 | 12 | 51 | gekorob/liebraryrest | migrations/versions/a16400f30ed4_.py | Python | _downgrade | _downgrade | 81 | 88 | 81 | 81 | 0c039a1d4431e03f06e311f89700d56c49eb6c91 | bigcode/the-stack | train |
7bafb0e34d3fde5bcbd5803a | train | function | def upgrade():
users_file = os.path.join(csv_path, 'users.csv')
authors_file = os.path.join(csv_path, 'authors.csv')
books_file = os.path.join(csv_path, 'books.csv')
_seed(user_table, users_file)
_seed(author_table, authors_file,
{'birth_date': (lambda d: datetime.strptime(d, '%Y%m%d'))})... | def upgrade():
| users_file = os.path.join(csv_path, 'users.csv')
authors_file = os.path.join(csv_path, 'authors.csv')
books_file = os.path.join(csv_path, 'books.csv')
_seed(user_table, users_file)
_seed(author_table, authors_file,
{'birth_date': (lambda d: datetime.strptime(d, '%Y%m%d'))})
_seed(book... | ',
column('id', sa.Integer))
loan_table = table('loan',
column('id', sa.Integer))
migrations_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), os.path.pardir)
csv_path = os.path.join(migrations_dir, 'csv')
def upgrade():
| 64 | 64 | 91 | 3 | 61 | gekorob/liebraryrest | migrations/versions/a16400f30ed4_.py | Python | upgrade | upgrade | 45 | 53 | 45 | 45 | 45306c2bb8ae792dd135e4afd12c892d02ce6996 | bigcode/the-stack | train |
18ad791bd35e40d51c6b74ec | train | function | def _tx_row(row, tx):
for k in tx:
row[k] = tx[k](row[k])
return row
| def _tx_row(row, tx):
| for k in tx:
row[k] = tx[k](row[k])
return row
| (file_path, 'r') as f:
reader = DictReader(f, delimiter=',')
rows = list(reader)
if tx is not None:
rows = [_tx_row(row, tx) for row in rows]
op.bulk_insert(table_obj, rows)
def _tx_row(row, tx):
| 64 | 64 | 29 | 8 | 56 | gekorob/liebraryrest | migrations/versions/a16400f30ed4_.py | Python | _tx_row | _tx_row | 75 | 78 | 75 | 75 | 37c9864cd5fb1e7226b894426a3aaa87f1f8a350 | bigcode/the-stack | train |
832bedf3063b461adece3687 | train | class | class style():
BLACK = '\033[30m'
RED = '\033[31m'
GREEN = '\033[32m'
YELLOW = '\033[33m'
BLUE = '\033[34m'
MAGENTA = '\033[35m'
CYAN = '\033[36m'
WHITE = '\033[37m'
UNDERLINE = '\033[4m'
RESET = '\033[0m'
| class style():
| BLACK = '\033[30m'
RED = '\033[31m'
GREEN = '\033[32m'
YELLOW = '\033[33m'
BLUE = '\033[34m'
MAGENTA = '\033[35m'
CYAN = '\033[36m'
WHITE = '\033[37m'
UNDERLINE = '\033[4m'
RESET = '\033[0m'
| USB Port',
'5. QMI & PPP Setup Information',
'6. OS Release',
'7. Raspberry Pi Model Infomation',
'8. Exit'
]
choice_question = [
'1. Home',
'2. Exit',
]
#os.system("")
class style():
| 64 | 64 | 97 | 3 | 61 | sixfab/setup-and-diagnostic-tool | diagnostic_tool/diagnostic_tool.py | Python | style | style | 35 | 45 | 35 | 35 | 9799eb1c3589c9fdfd71acc2b32dc5e4185ec1fd | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.