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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
906f93734beb0747a45f65b8 | train | class | class Discriminator(nn.Module):
def __init__(self, num_conv_block=4):
super(Discriminator, self).__init__()
block = []
in_channels = 3
out_channels = 64
for _ in range(num_conv_block):
block += [nn.ReflectionPad2d(1),
nn.Conv2d(in_channels... | class Discriminator(nn.Module):
| def __init__(self, num_conv_block=4):
super(Discriminator, self).__init__()
block = []
in_channels = 3
out_channels = 64
for _ in range(num_conv_block):
block += [nn.ReflectionPad2d(1),
nn.Conv2d(in_channels, out_channels, 3),
... | import torch.nn as nn
import torch
class Discriminator(nn.Module):
| 15 | 91 | 304 | 6 | 8 | jtiger958/super-resolution-ESRGAN-pytorch | model/Discriminator.py | Python | Discriminator | Discriminator | 5 | 46 | 5 | 5 | b10b0f3636c6d75d3bd8af54e141b048473e6b76 | bigcode/the-stack | train |
6cff6cef65c4a815d0841cfe | train | class | class UnitTest(unittest.TestCase):
"""Class: UnitTest
Description: Class which is a representation of a unit testing.
Methods:
setUp
test_deletedmp_cmdline
test_deletedmp_arg
tearDown
"""
def setUp(self):
"""Function: setUp
Description: Init... | class UnitTest(unittest.TestCase):
| """Class: UnitTest
Description: Class which is a representation of a unit testing.
Methods:
setUp
test_deletedmp_cmdline
test_deletedmp_arg
tearDown
"""
def setUp(self):
"""Function: setUp
Description: Initialization for unit testing.
... | #!/usr/bin/python
# Classification (U)
"""Program: delete_dump.py
Description: Integration testing of delete_dump in elastic_db_repo.py.
Usage:
test/integration/elastic_db_repo/delete_dump.py
Arguments:
"""
# Libraries and Global Variables
# Standard
import sys
import os
import shutil
if s... | 149 | 209 | 699 | 7 | 142 | mjpernot/elastic-repo | test/integration/elastic_db_repo/delete_dump.py | Python | UnitTest | UnitTest | 39 | 144 | 39 | 40 | 891cb546c9eedbc3c566ae189006a382da2c7a64 | bigcode/the-stack | train |
c9a6164589232efa37245176 | train | function | def get_error_details(res: Dict[str, Any]) -> str:
""" Parses the error details retrieved from the application and outputs the resulted string.
:type res: ``Dict[str, Any]``
:param res: The error data retrieved from the application.
:return: The parsed error details.
:rtype: ``str``
"""
me... | def get_error_details(res: Dict[str, Any]) -> str:
| """ Parses the error details retrieved from the application and outputs the resulted string.
:type res: ``Dict[str, Any]``
:param res: The error data retrieved from the application.
:return: The parsed error details.
:rtype: ``str``
"""
message, details = "Couldn't find details for the err... | ''
error_message = str(e)
user_profile.set_result(action=action,
success=False,
error_code=error_code,
error_message=error_message)
demisto.error(traceback.format_exc())
'''HELPER FUNCTIONS''... | 63 | 64 | 151 | 14 | 49 | diCagri/content | Packs/SalesforceFusion/Integrations/SalesforceFusionIAM/SalesforceFusionIAM.py | Python | get_error_details | get_error_details | 262 | 277 | 262 | 262 | 98b5220b0cda16801ac7f03f333ad2fa5643beff | bigcode/the-stack | train |
5dc9a6e2e068b91b09ae4aa5 | train | class | class Client(BaseClient):
""" A client class that implements logic to authenticate with the application. """
def __init__(self, base_url, verify=True, proxy=False, ok_codes=(), headers=None, auth=None, client_id=None,
username=None, password=None, client_secret=None):
super().__init__(... | class Client(BaseClient):
| """ A client class that implements logic to authenticate with the application. """
def __init__(self, base_url, verify=True, proxy=False, ok_codes=(), headers=None, auth=None, client_id=None,
username=None, password=None, client_secret=None):
super().__init__(base_url, verify, proxy, o... | from CommonServerPython import *
import traceback
import urllib3
# Disable insecure warnings
urllib3.disable_warnings()
ERROR_CODES_TO_SKIP = [
404
]
''' GLOBAL VARIABLES '''
URI_PREFIX = '/services/data/v51.0/'
'''CLIENT CLASS'''
class Client(BaseClient):
| 60 | 256 | 2,054 | 5 | 55 | diCagri/content | Packs/SalesforceFusion/Integrations/SalesforceFusionIAM/SalesforceFusionIAM.py | Python | Client | Client | 18 | 256 | 18 | 18 | 194c89e779c9dcae4a56213be746f8e6a553beb9 | bigcode/the-stack | train |
1165f10cb3502114b67aff87 | train | function | def main():
user_profile = None
params = demisto.params()
base_url = urljoin(params['url'].strip('/'))
client_id = params.get('client_id')
client_secret = params.get('client_secret')
username = params.get('credentials', {}).get('identifier')
password = params.get('credentials', {}).get('pass... | def main():
| user_profile = None
params = demisto.params()
base_url = urljoin(params['url'].strip('/'))
client_id = params.get('client_id')
client_secret = params.get('client_secret')
username = params.get('credentials', {}).get('identifier')
password = params.get('credentials', {}).get('password')
s... | COMMAND FUNCTIONS'''
def test_module(client: Client):
""" Tests connectivity with the client. """
client.test()
return_results('ok')
def get_mapping_fields(client: Client) -> GetMappingFieldsResponse:
""" Creates and returns a GetMappingFieldsResponse object of the user schema in the application
... | 166 | 166 | 556 | 3 | 163 | diCagri/content | Packs/SalesforceFusion/Integrations/SalesforceFusionIAM/SalesforceFusionIAM.py | Python | main | main | 305 | 379 | 305 | 305 | a9820ad13f73a9f1a67227cff70a9e99ce2448fe | bigcode/the-stack | train |
84c19d261a8897b01be597f8 | train | function | def test_module(client: Client):
""" Tests connectivity with the client. """
client.test()
return_results('ok')
| def test_module(client: Client):
| """ Tests connectivity with the client. """
client.test()
return_results('ok')
| [0]
if isinstance(res, dict):
message = res.get('message', 'No error message was supplied')
details = res.get('detail', 'No details regarding the error were supplied')
return f'{message}: {details}'
'''COMMAND FUNCTIONS'''
def test_module(client: Client):
| 63 | 64 | 26 | 7 | 56 | diCagri/content | Packs/SalesforceFusion/Integrations/SalesforceFusionIAM/SalesforceFusionIAM.py | Python | test_module | test_module | 283 | 287 | 283 | 283 | b650834a76b349986bf52939f70a8cf2a90cf420 | bigcode/the-stack | train |
8f10e568c24affedcd60e574 | train | function | def get_mapping_fields(client: Client) -> GetMappingFieldsResponse:
""" Creates and returns a GetMappingFieldsResponse object of the user schema in the application
:param client: (Client) The integration Client object that implements a get_app_fields() method
:return: (GetMappingFieldsResponse) An object t... | def get_mapping_fields(client: Client) -> GetMappingFieldsResponse:
| """ Creates and returns a GetMappingFieldsResponse object of the user schema in the application
:param client: (Client) The integration Client object that implements a get_app_fields() method
:return: (GetMappingFieldsResponse) An object that represents the user schema
"""
app_fields = client.get_a... | 'No details regarding the error were supplied')
return f'{message}: {details}'
'''COMMAND FUNCTIONS'''
def test_module(client: Client):
""" Tests connectivity with the client. """
client.test()
return_results('ok')
def get_mapping_fields(client: Client) -> GetMappingFieldsResponse:
| 64 | 64 | 133 | 14 | 50 | diCagri/content | Packs/SalesforceFusion/Integrations/SalesforceFusionIAM/SalesforceFusionIAM.py | Python | get_mapping_fields | get_mapping_fields | 290 | 302 | 290 | 290 | 635f3ade1d15b8c07129cba4b7093dc0cf1bc2c2 | bigcode/the-stack | train |
3c61665e03137bba292edd9a | train | function | def get_node_ranks(nodes, beta, r_start):
N = len(nodes)
r1 = [(1-beta)/N for _ in range(N)]
for i, node in enumerate(nodes):
for j, dest in enumerate(node):
r1[int(dest)] += beta * r_start[i] / len(node)
return r1
| def get_node_ranks(nodes, beta, r_start):
| N = len(nodes)
r1 = [(1-beta)/N for _ in range(N)]
for i, node in enumerate(nodes):
for j, dest in enumerate(node):
r1[int(dest)] += beta * r_start[i] / len(node)
return r1
| from decimal import Decimal, ROUND_HALF_UP
# import time
def get_node_ranks(nodes, beta, r_start):
| 25 | 64 | 73 | 12 | 12 | frankopandzic/Node_Rank-Lab_assignment | NodeRank.py | Python | get_node_ranks | get_node_ranks | 5 | 11 | 5 | 5 | c400bb907004d480de61afe520ce92313db5ecab | bigcode/the-stack | train |
f1d041f1a02e251e7c747b90 | train | function | def hints(env: PysmtEnv) -> FrozenSet[Hint]:
assert isinstance(env, PysmtEnv)
mgr = env.formula_manager
i = mgr.Symbol("i", types.REAL)
r = mgr.Symbol("r", types.REAL)
l = mgr.Symbol("l", types.REAL)
inc_i = mgr.Symbol("inc_i", types.BOOL)
symbs = frozenset([i, r, l, inc_i])
x_i = symb_... | def hints(env: PysmtEnv) -> FrozenSet[Hint]:
| assert isinstance(env, PysmtEnv)
mgr = env.formula_manager
i = mgr.Symbol("i", types.REAL)
r = mgr.Symbol("r", types.REAL)
l = mgr.Symbol("l", types.REAL)
inc_i = mgr.Symbol("inc_i", types.BOOL)
symbs = frozenset([i, r, l, inc_i])
x_i = symb_to_next(mgr, i)
x_r = symb_to_next(mgr, r... | msat_make_impl(menv, i_geq_l,
x_i_eq_0_and_x_l_eq_l_p_1))
# (G F inc_i) -> ! G F r > i
G_F_x_i_gt_i = enc.make_G(enc.make_F(inc_i))
r_gt_i = msat_make_gt(menv, r, i)
n_G_F_r_gt_i = msat_make_not(menv, enc.make_G(enc.make_F(r_gt_i)))
ltl = msat_make_impl(men... | 157 | 157 | 524 | 15 | 141 | EnricoMagnago/F3 | benchmarks/f3_wrong_hints/scaling_ltl_infinite_state/4-extending_bound_0.py | Python | hints | hints | 115 | 166 | 115 | 115 | 20f6dd81b4c544186d3cac5e21734aae7567211c | bigcode/the-stack | train |
1bcc7bd3779c04b3645df0b9 | train | function | def msat_make_impl(menv: msat_env, arg0: msat_term, arg1: msat_term):
n_arg0 = msat_make_not(menv, arg0)
return msat_make_or(menv, n_arg0, arg1)
| def msat_make_impl(menv: msat_env, arg0: msat_term, arg1: msat_term):
| n_arg0 = msat_make_not(menv, arg0)
return msat_make_or(menv, n_arg0, arg1)
| , arg1: msat_term):
leq = msat_make_leq(menv, arg0, arg1)
return msat_make_not(menv, leq)
def msat_make_impl(menv: msat_env, arg0: msat_term, arg1: msat_term):
| 64 | 64 | 57 | 26 | 38 | EnricoMagnago/F3 | benchmarks/f3_wrong_hints/scaling_ltl_infinite_state/4-extending_bound_0.py | Python | msat_make_impl | msat_make_impl | 33 | 35 | 33 | 33 | 6517b33753958b928ace2c9a49a92b8749eb6875 | bigcode/the-stack | train |
ac9da58af938bb0015b61d9f | train | function | def msat_make_lt(menv: msat_env, arg0: msat_term, arg1: msat_term):
geq = msat_make_geq(menv, arg0, arg1)
return msat_make_not(menv, geq)
| def msat_make_lt(menv: msat_env, arg0: msat_term, arg1: msat_term):
| geq = msat_make_geq(menv, arg0, arg1)
return msat_make_not(menv, geq)
| import pysmt.typing as types
from ltl.ltl import TermMap, LTLEncoder
from utils import name_next, symb_to_next
from hint import Hint, Location
def msat_make_lt(menv: msat_env, arg0: msat_term, arg1: msat_term):
| 64 | 64 | 56 | 26 | 37 | EnricoMagnago/F3 | benchmarks/f3_wrong_hints/scaling_ltl_infinite_state/4-extending_bound_0.py | Python | msat_make_lt | msat_make_lt | 19 | 21 | 19 | 19 | f682ff02b643620fb47f1bac9d203fab49c9977a | bigcode/the-stack | train |
3e64891684b99a49a6da0773 | train | function | def msat_make_gt(menv: msat_env, arg0: msat_term, arg1: msat_term):
leq = msat_make_leq(menv, arg0, arg1)
return msat_make_not(menv, leq)
| def msat_make_gt(menv: msat_env, arg0: msat_term, arg1: msat_term):
| leq = msat_make_leq(menv, arg0, arg1)
return msat_make_not(menv, leq)
| q(menv: msat_env, arg0: msat_term, arg1: msat_term):
return msat_make_leq(menv, arg1, arg0)
def msat_make_gt(menv: msat_env, arg0: msat_term, arg1: msat_term):
| 64 | 64 | 56 | 26 | 38 | EnricoMagnago/F3 | benchmarks/f3_wrong_hints/scaling_ltl_infinite_state/4-extending_bound_0.py | Python | msat_make_gt | msat_make_gt | 28 | 30 | 28 | 28 | 6ebfbc8ba8c3ffb3ba712af6009f476ff9bc91f6 | bigcode/the-stack | train |
aa37c0503502d78c869bd0b1 | train | function | def msat_make_geq(menv: msat_env, arg0: msat_term, arg1: msat_term):
return msat_make_leq(menv, arg1, arg0)
| def msat_make_geq(menv: msat_env, arg0: msat_term, arg1: msat_term):
| return msat_make_leq(menv, arg1, arg0)
| arg1: msat_term):
geq = msat_make_geq(menv, arg0, arg1)
return msat_make_not(menv, geq)
def msat_make_geq(menv: msat_env, arg0: msat_term, arg1: msat_term):
| 64 | 64 | 43 | 27 | 37 | EnricoMagnago/F3 | benchmarks/f3_wrong_hints/scaling_ltl_infinite_state/4-extending_bound_0.py | Python | msat_make_geq | msat_make_geq | 24 | 25 | 24 | 24 | b508b807d803a8843eb678982d7c937a8b671e86 | bigcode/the-stack | train |
a3fc04727099c31235778d03 | train | function | def check_ltl(menv: msat_env, enc: LTLEncoder) -> Tuple[Iterable, msat_term,
msat_term, msat_term]:
assert menv
assert isinstance(menv, msat_env)
assert enc
assert isinstance(enc, LTLEncoder)
bool_type = msat_get_bool_type(menv)
real_type =... | def check_ltl(menv: msat_env, enc: LTLEncoder) -> Tuple[Iterable, msat_term,
msat_term, msat_term]:
| assert menv
assert isinstance(menv, msat_env)
assert enc
assert isinstance(enc, LTLEncoder)
bool_type = msat_get_bool_type(menv)
real_type = msat_get_rational_type(menv)
i = msat_declare_function(menv, "i", real_type)
i = msat_make_constant(menv, i)
r = msat_declare_function(menv, "r... | _to_next
from hint import Hint, Location
def msat_make_lt(menv: msat_env, arg0: msat_term, arg1: msat_term):
geq = msat_make_geq(menv, arg0, arg1)
return msat_make_not(menv, geq)
def msat_make_geq(menv: msat_env, arg0: msat_term, arg1: msat_term):
return msat_make_leq(menv, arg1, arg0)
def msat_make_g... | 256 | 256 | 1,116 | 34 | 222 | EnricoMagnago/F3 | benchmarks/f3_wrong_hints/scaling_ltl_infinite_state/4-extending_bound_0.py | Python | check_ltl | check_ltl | 38 | 112 | 38 | 39 | 56fc8b2caf96c9be96727a1aebaaed721ebc6250 | bigcode/the-stack | train |
21e21be018487c11db4fd601 | train | class | @heat_base.HeatObjectRegistry.register
class RawTemplate(
heat_base.HeatObject,
base.VersionedObjectDictCompat,
base.ComparableVersionedObject,
):
# Version 1.0: Initial version
# Version 1.1: Added files_id
VERSION = '1.1'
fields = {
'id': fields.IntegerField(),
# TODO(cwol... | @heat_base.HeatObjectRegistry.register
class RawTemplate(
heat_base.HeatObject,
base.VersionedObjectDictCompat,
base.ComparableVersionedObject,
):
# Version 1.0: Initial version
# Version 1.1: Added files_id
| VERSION = '1.1'
fields = {
'id': fields.IntegerField(),
# TODO(cwolfe): remove deprecated files in future release
'files': heat_fields.JsonField(nullable=True),
'files_id': fields.IntegerField(nullable=True),
'template': heat_fields.JsonField(),
'environment': he... | the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
"""RawTemplate object."""
import copy
from oslo_config import cfg
from oslo_log import lo... | 205 | 205 | 685 | 60 | 145 | larsks/heat | heat/objects/raw_template.py | Python | RawTemplate | RawTemplate | 35 | 118 | 35 | 42 | af0209291e8d7a96fa064aa9e4ffb70557587074 | bigcode/the-stack | train |
6967ccf41cf828b6fff95392 | train | function | def test_determine_config_type(tmpdir):
# Ensure the default created config is of simple type
workspace = tmpdir.strpath
temp_config_path = workspace + '/config.yaml'
make_default_config_if_needed(temp_config_path)
got_output = backend.determine_config_type(config_path=temp_config_path)
expected... | def test_determine_config_type(tmpdir):
# Ensure the default created config is of simple type
| workspace = tmpdir.strpath
temp_config_path = workspace + '/config.yaml'
make_default_config_if_needed(temp_config_path)
got_output = backend.determine_config_type(config_path=temp_config_path)
expected_output = {
'message': '',
'type': 'minimal',
}
assert got_output == expec... | ,
'bootstrap_url': 'file:///opt/dcos_install_tmp'
}
make_default_config_if_needed(temp_config_path)
config = Config(temp_config_path)
assert expected_data == config.config
def test_determine_config_type(tmpdir):
# Ensure the default created config is of simple type
| 64 | 64 | 92 | 21 | 42 | Chewie/dcos | dcos_installer/test_backend.py | Python | test_determine_config_type | test_determine_config_type | 209 | 219 | 209 | 210 | e310d7d1359cdb456ad4dd5299525cec175c4dbf | bigcode/the-stack | train |
9d0a881a465e6d6ae1e9f0fb | train | function | @pytest.fixture(scope='module')
def config_aws(config_testing):
if 'aws' not in config_testing:
pytest.skip("Skipped because there is no `testing.aws` configuration in dcos-release.config.yaml")
return config_testing['aws']
| @pytest.fixture(scope='module')
def config_aws(config_testing):
| if 'aws' not in config_testing:
pytest.skip("Skipped because there is no `testing.aws` configuration in dcos-release.config.yaml")
return config_testing['aws']
| cos-release.config.yaml')
@pytest.fixture(scope='module')
def config_testing(config):
if 'testing' not in config:
pytest.skip("Skipped because there is no `testing` configuration in dcos-release.config.yaml")
return config['testing']
@pytest.fixture(scope='module')
def config_aws(config_testing):
| 64 | 64 | 51 | 13 | 51 | Chewie/dcos | dcos_installer/test_backend.py | Python | config_aws | config_aws | 32 | 36 | 32 | 33 | f5d9f2243330bb7e35aee462aae3ecafebc7b231 | bigcode/the-stack | train |
a75dc269a2d2e6bbddc8cfe0 | train | function | def aws_cf_configure(s3_bucket_name, config, config_aws, tmpdir, monkeypatch):
monkeypatch.setenv('BOOTSTRAP_VARIANT', 'test_variant')
session = gen.build_deploy.aws.get_test_session(config_aws)
s3 = session.resource('s3')
s3_bucket = s3.Bucket(s3_bucket_name)
s3_bucket.create(CreateBucketConfigurat... | def aws_cf_configure(s3_bucket_name, config, config_aws, tmpdir, monkeypatch):
| monkeypatch.setenv('BOOTSTRAP_VARIANT', 'test_variant')
session = gen.build_deploy.aws.get_test_session(config_aws)
s3 = session.resource('s3')
s3_bucket = s3.Bucket(s3_bucket_name)
s3_bucket.create(CreateBucketConfiguration={'LocationConstraint': config_aws['region_name']})
create_config(confi... | '\naws_template_storage_region_name: {}'.format(config_aws['region_name'])
assert aws_cf_configure(bucket, config_str, config_aws, tmpdir, monkeypatch) == 0
def aws_cf_configure(s3_bucket_name, config, config_aws, tmpdir, monkeypatch):
| 64 | 64 | 174 | 22 | 41 | Chewie/dcos | dcos_installer/test_backend.py | Python | aws_cf_configure | aws_cf_configure | 330 | 345 | 330 | 330 | 164d135de33b60afa51eccefe9c74fd7ef1b1c6e | bigcode/the-stack | train |
6366316adac1ec730ae40dfe | train | function | def test_do_configure(tmpdir, monkeypatch):
monkeypatch.setenv('BOOTSTRAP_VARIANT', 'test_variant')
create_config(simple_full_config, tmpdir)
create_fake_build_artifacts(tmpdir)
with tmpdir.as_cwd():
assert backend.do_configure(config_path='genconf/config.yaml') == 0
| def test_do_configure(tmpdir, monkeypatch):
| monkeypatch.setenv('BOOTSTRAP_VARIANT', 'test_variant')
create_config(simple_full_config, tmpdir)
create_fake_build_artifacts(tmpdir)
with tmpdir.as_cwd():
assert backend.do_configure(config_path='genconf/config.yaml') == 0
| param[1]
simple_full_config = """---
cluster_name: DC/OS
master_discovery: static
exhibitor_storage_backend: static
master_list:
- 127.0.0.1
bootstrap_url: http://example.com
"""
def test_do_configure(tmpdir, monkeypatch):
| 64 | 64 | 72 | 11 | 53 | Chewie/dcos | dcos_installer/test_backend.py | Python | test_do_configure | test_do_configure | 271 | 276 | 271 | 271 | e3b2411b1d8cb14e19ba20e6ffdbe936aea544fc | bigcode/the-stack | train |
158f547a48cd71a9327b72cf | train | function | def test_good_create_config_from_post(tmpdir):
"""
Test that it creates the config
"""
# Create a temp config
workspace = tmpdir.strpath
temp_config_path = workspace + '/config.yaml'
make_default_config_if_needed(temp_config_path)
temp_ip_detect_path = workspace + '/ip-detect'
f = o... | def test_good_create_config_from_post(tmpdir):
| """
Test that it creates the config
"""
# Create a temp config
workspace = tmpdir.strpath
temp_config_path = workspace + '/config.yaml'
make_default_config_if_needed(temp_config_path)
temp_ip_detect_path = workspace + '/ip-detect'
f = open(temp_ip_detect_path, "w")
f.write("#/bi... | some-variant')
version_data = subprocess.check_output(['dcos_installer', '--version']).decode()
assert json.loads(version_data) == {
'version': '1.10.0-beta2',
'variant': 'some-variant'
}
def test_good_create_config_from_post(tmpdir):
| 65 | 65 | 217 | 10 | 55 | Chewie/dcos | dcos_installer/test_backend.py | Python | test_good_create_config_from_post | test_good_create_config_from_post | 112 | 140 | 112 | 112 | 47fdfb47581912ed391095cf6e6c866b4521a409 | bigcode/the-stack | train |
3f1e1965009ff2c8186e8c14 | train | function | def test_success():
mock_config = to_config({
'master_list': ['10.0.0.1', '10.0.0.2', '10.0.0.5'],
'agent_list': ['10.0.0.3', '10.0.0.4']
})
expected_output = {
"success": "http://10.0.0.1",
"master_count": 3,
"agent_count": 2
}
expected_output_bad = {
... | def test_success():
| mock_config = to_config({
'master_list': ['10.0.0.1', '10.0.0.2', '10.0.0.5'],
'agent_list': ['10.0.0.3', '10.0.0.4']
})
expected_output = {
"success": "http://10.0.0.1",
"master_count": 3,
"agent_count": 2
}
expected_output_bad = {
"success": "",
... | _path = workspace + '/config.yaml'
make_default_config_if_needed(temp_config_path)
got_output = backend.determine_config_type(config_path=temp_config_path)
expected_output = {
'message': '',
'type': 'minimal',
}
assert got_output == expected_output
def test_success():
| 64 | 64 | 205 | 4 | 59 | Chewie/dcos | dcos_installer/test_backend.py | Python | test_success | test_success | 222 | 244 | 222 | 222 | a7957ce410495a152fbf5c989060636af7bb483b | bigcode/the-stack | train |
818760ce830e01c9ad36ff39 | train | function | @pytest.fixture(scope='module')
def config():
if not os.path.exists('dcos-release.config.yaml'):
pytest.skip("Skipping because there is no configuration in dcos-release.config.yaml")
return release.load_config('dcos-release.config.yaml')
| @pytest.fixture(scope='module')
def config():
| if not os.path.exists('dcos-release.config.yaml'):
pytest.skip("Skipping because there is no configuration in dcos-release.config.yaml")
return release.load_config('dcos-release.config.yaml')
| import pytest
import gen
import gen.build_deploy.aws
import release
from dcos_installer import backend
from dcos_installer.config import Config, make_default_config_if_needed, to_config
os.environ["BOOTSTRAP_ID"] = "12345"
@pytest.fixture(scope='module')
def config():
| 64 | 64 | 51 | 9 | 55 | Chewie/dcos | dcos_installer/test_backend.py | Python | config | config | 18 | 22 | 18 | 19 | fdca79dbc6e41a8a16af997f102aad2e52c8c6fd | bigcode/the-stack | train |
77c11ceb977a6a9c8f1d8db1 | train | function | def test_do_aws_cf_configure_valid_storage_config(config_aws, tmpdir, monkeypatch):
bucket = str(uuid.uuid4())
config_str = valid_storage_config.format(
key_id=config_aws["access_key_id"],
bucket=bucket,
access_key=config_aws["secret_access_key"])
assert aws_cf_configure(bucket, conf... | def test_do_aws_cf_configure_valid_storage_config(config_aws, tmpdir, monkeypatch):
| bucket = str(uuid.uuid4())
config_str = valid_storage_config.format(
key_id=config_aws["access_key_id"],
bucket=bucket,
access_key=config_aws["secret_access_key"])
assert aws_cf_configure(bucket, config_str, config_aws, tmpdir, monkeypatch) == 0
| {key_id}
aws_template_storage_bucket: {bucket}
aws_template_storage_bucket_path: mofo-the-gorilla
aws_template_storage_secret_access_key: {access_key}
aws_template_upload: true
"""
def test_do_aws_cf_configure_valid_storage_config(config_aws, tmpdir, monkeypatch):
| 64 | 64 | 90 | 21 | 43 | Chewie/dcos | dcos_installer/test_backend.py | Python | test_do_aws_cf_configure_valid_storage_config | test_do_aws_cf_configure_valid_storage_config | 309 | 315 | 309 | 309 | 7047f8dbe3a939dc91ac195509c7c4eef9ee1c28 | bigcode/the-stack | train |
9a7550d27f33af723ebb0288 | train | function | def test_version(monkeypatch):
monkeypatch.setenv('BOOTSTRAP_VARIANT', 'some-variant')
version_data = subprocess.check_output(['dcos_installer', '--version']).decode()
assert json.loads(version_data) == {
'version': '1.10.0-beta2',
'variant': 'some-variant'
}
| def test_version(monkeypatch):
| monkeypatch.setenv('BOOTSTRAP_VARIANT', 'some-variant')
version_data = subprocess.check_output(['dcos_installer', '--version']).decode()
assert json.loads(version_data) == {
'version': '1.10.0-beta2',
'variant': 'some-variant'
}
| ))
except subprocess.CalledProcessError as e:
print(e.output)
assert e.output.decode('ascii') == "Must provide the version of the cluster upgrading from\n"
else:
raise Exception("Test passed, this should not pass without specifying a version number")
def test_version(monkeypatch):
| 64 | 64 | 75 | 7 | 57 | Chewie/dcos | dcos_installer/test_backend.py | Python | test_version | test_version | 103 | 109 | 103 | 103 | dd9d134e576dabe98afa3f3d3f852d53fe40c047 | bigcode/the-stack | train |
307eb63979160e43d4deaa12 | train | function | def create_config(config_str, tmpdir):
genconf_dir = tmpdir.join('genconf')
genconf_dir.ensure(dir=True)
config_path = genconf_dir.join('config.yaml')
config_path.write(config_str)
genconf_dir.join('ip-detect').write('#!/bin/bash\necho 127.0.0.1')
| def create_config(config_str, tmpdir):
| genconf_dir = tmpdir.join('genconf')
genconf_dir.ensure(dir=True)
config_path = genconf_dir.join('config.yaml')
config_path.write(config_str)
genconf_dir.join('ip-detect').write('#!/bin/bash\necho 127.0.0.1')
| tmpdir.as_cwd():
return backend.do_aws_cf_configure()
finally:
objects = [{'Key': o.key} for o in s3_bucket.objects.all()]
s3_bucket.delete_objects(Delete={'Objects': objects})
s3_bucket.delete()
def create_config(config_str, tmpdir):
| 64 | 64 | 75 | 9 | 55 | Chewie/dcos | dcos_installer/test_backend.py | Python | create_config | create_config | 348 | 353 | 348 | 348 | 4a13ff3af1d297821a2b37fdf9b389eed8d854ef | bigcode/the-stack | train |
f091234f1cc24197c7a62f6b | train | function | def create_fake_build_artifacts(tmpdir):
artifact_dir = tmpdir.join('artifacts/bootstrap')
artifact_dir.ensure(dir=True)
artifact_dir.join('12345.bootstrap.tar.xz').write('contents_of_bootstrap', ensure=True)
artifact_dir.join('12345.active.json').write('["package--version"]', ensure=True)
artifact_... | def create_fake_build_artifacts(tmpdir):
| artifact_dir = tmpdir.join('artifacts/bootstrap')
artifact_dir.ensure(dir=True)
artifact_dir.join('12345.bootstrap.tar.xz').write('contents_of_bootstrap', ensure=True)
artifact_dir.join('12345.active.json').write('["package--version"]', ensure=True)
artifact_dir.join('test_variant.bootstrap.latest')... | ')
genconf_dir.ensure(dir=True)
config_path = genconf_dir.join('config.yaml')
config_path.write(config_str)
genconf_dir.join('ip-detect').write('#!/bin/bash\necho 127.0.0.1')
def create_fake_build_artifacts(tmpdir):
| 64 | 64 | 190 | 9 | 55 | Chewie/dcos | dcos_installer/test_backend.py | Python | create_fake_build_artifacts | create_fake_build_artifacts | 356 | 370 | 356 | 356 | ce6c386e7d80cf853629909072b7be5b10d4ec44 | bigcode/the-stack | train |
31bd731dab5d4397f5a99442 | train | function | def test_password_hash():
"""Tests that the password hashing method creates de-cryptable hash
"""
password = 'DcosTestingPassword!@#'
# only reads from STDOUT
hash_pw = subprocess.check_output(['dcos_installer', '--hash-password', password])
print(hash_pw)
hash_pw = hash_pw.decode('ascii').s... | def test_password_hash():
| """Tests that the password hashing method creates de-cryptable hash
"""
password = 'DcosTestingPassword!@#'
# only reads from STDOUT
hash_pw = subprocess.check_output(['dcos_installer', '--hash-password', password])
print(hash_pw)
hash_pw = hash_pw.decode('ascii').strip('\n')
assert pass... | .yaml")
return config['testing']
@pytest.fixture(scope='module')
def config_aws(config_testing):
if 'aws' not in config_testing:
pytest.skip("Skipped because there is no `testing.aws` configuration in dcos-release.config.yaml")
return config_testing['aws']
def test_password_hash():
| 64 | 64 | 102 | 5 | 59 | Chewie/dcos | dcos_installer/test_backend.py | Python | test_password_hash | test_password_hash | 39 | 47 | 39 | 39 | f968f9620431c1f05bba6c0862b2747dc7b5c38d | bigcode/the-stack | train |
cddf541e6212f4f2cc53f26e | train | function | def test_get_config(tmpdir):
workspace = tmpdir.strpath
temp_config_path = workspace + '/config.yaml'
expected_data = {
'cluster_name': 'DC/OS',
'master_discovery': 'static',
'exhibitor_storage_backend': 'static',
'resolvers': ['8.8.8.8', '8.8.4.4'],
'ssh_port': 22,
... | def test_get_config(tmpdir):
| workspace = tmpdir.strpath
temp_config_path = workspace + '/config.yaml'
expected_data = {
'cluster_name': 'DC/OS',
'master_discovery': 'static',
'exhibitor_storage_backend': 'static',
'resolvers': ['8.8.8.8', '8.8.4.4'],
'ssh_port': 22,
'process_timeout': 10... | way to calculate value.',
'ssh_key_path': 'could not find ssh private key: genconf/ssh_key'
}
with tmpdir.as_cwd():
assert Config(config_path='genconf/config.yaml').do_validate(include_ssh=True) == expected_output
def test_get_config(tmpdir):
| 64 | 64 | 143 | 7 | 56 | Chewie/dcos | dcos_installer/test_backend.py | Python | test_get_config | test_get_config | 190 | 206 | 190 | 190 | 7d139d8805baf666ff9f8e4a9f4f33f9209b15aa | bigcode/the-stack | train |
163ed710fe331b27f11bf68e | train | function | def test_do_aws_configure(tmpdir, monkeypatch):
monkeypatch.setenv('BOOTSTRAP_VARIANT', 'test_variant')
create_config(aws_base_config, tmpdir)
create_fake_build_artifacts(tmpdir)
with tmpdir.as_cwd():
assert backend.do_aws_cf_configure() == 0
| def test_do_aws_configure(tmpdir, monkeypatch):
| monkeypatch.setenv('BOOTSTRAP_VARIANT', 'test_variant')
create_config(aws_base_config, tmpdir)
create_fake_build_artifacts(tmpdir)
with tmpdir.as_cwd():
assert backend.do_aws_cf_configure() == 0
| don't need valid AWS /
# s3 credentials in this configuration.
aws_template_storage_bucket: psychic
aws_template_storage_bucket_path: mofo-the-gorilla
aws_template_storage_region_name: us-west-2
aws_template_upload: false
"""
def test_do_aws_configure(tmpdir, monkeypatch):
| 64 | 64 | 71 | 13 | 51 | Chewie/dcos | dcos_installer/test_backend.py | Python | test_do_aws_configure | test_do_aws_configure | 289 | 295 | 289 | 289 | 369ad93bf5b5140cf245d7469f37736a2ba0540e | bigcode/the-stack | train |
863a62daf765f8a1cf1f9590 | train | function | def test_bad_create_config_from_post(tmpdir):
# Create a temp config
workspace = tmpdir.strpath
temp_config_path = workspace + '/config.yaml'
make_default_config_if_needed(temp_config_path)
bad_post_data = {
"agent_list": "foo",
"master_list": ["foo"],
}
expected_bad_message... | def test_bad_create_config_from_post(tmpdir):
# Create a temp config
| workspace = tmpdir.strpath
temp_config_path = workspace + '/config.yaml'
make_default_config_if_needed(temp_config_path)
bad_post_data = {
"agent_list": "foo",
"master_list": ["foo"],
}
expected_bad_messages = {
"agent_list": "Must be a JSON formatted list, but couldn't ... | _fake_build_artifacts(tmpdir)
with tmpdir.as_cwd():
messages = backend.create_config_from_post(
post_data=good_post_data,
config_path=temp_config_path)
assert messages == expected_good_messages
def test_bad_create_config_from_post(tmpdir):
# Create a temp config
| 64 | 64 | 188 | 17 | 46 | Chewie/dcos | dcos_installer/test_backend.py | Python | test_bad_create_config_from_post | test_bad_create_config_from_post | 143 | 165 | 143 | 144 | c720db59a4485e86755046e53b1e0a489e07fa80 | bigcode/the-stack | train |
1c02a96a7f8212278d6cf276 | train | function | def test_set_superuser_password(tmpdir):
"""Test that --set-superuser-hash works"""
with tmpdir.as_cwd():
tmpdir.join('genconf').ensure(dir=True)
# TODO(cmaloney): Add tests for the behavior around a non-existent config.yaml
# Setting in a non-empty config.yaml which has no password s... | def test_set_superuser_password(tmpdir):
| """Test that --set-superuser-hash works"""
with tmpdir.as_cwd():
tmpdir.join('genconf').ensure(dir=True)
# TODO(cmaloney): Add tests for the behavior around a non-existent config.yaml
# Setting in a non-empty config.yaml which has no password set
make_default_config_if_needed(... | .check_output(['dcos_installer', '--hash-password', password])
print(hash_pw)
hash_pw = hash_pw.decode('ascii').strip('\n')
assert passlib.hash.sha512_crypt.verify(password, hash_pw), 'Hash does not match password'
def test_set_superuser_password(tmpdir):
| 64 | 64 | 186 | 9 | 55 | Chewie/dcos | dcos_installer/test_backend.py | Python | test_set_superuser_password | test_set_superuser_password | 50 | 68 | 50 | 50 | 2440cd9d2460609a3b923dcbab1e1e677e340876 | bigcode/the-stack | train |
8e6387e3bfd9ea5e71c235e9 | train | function | @pytest.fixture(scope='module')
def config_testing(config):
if 'testing' not in config:
pytest.skip("Skipped because there is no `testing` configuration in dcos-release.config.yaml")
return config['testing']
| @pytest.fixture(scope='module')
def config_testing(config):
| if 'testing' not in config:
pytest.skip("Skipped because there is no `testing` configuration in dcos-release.config.yaml")
return config['testing']
| 45"
@pytest.fixture(scope='module')
def config():
if not os.path.exists('dcos-release.config.yaml'):
pytest.skip("Skipping because there is no configuration in dcos-release.config.yaml")
return release.load_config('dcos-release.config.yaml')
@pytest.fixture(scope='module')
def config_testing(config):
| 64 | 64 | 46 | 11 | 53 | Chewie/dcos | dcos_installer/test_backend.py | Python | config_testing | config_testing | 25 | 29 | 25 | 26 | 043b5dcf64a1499819ff28d7a6b3b8536b2a6153 | bigcode/the-stack | train |
091a318af87f59a195dc448a | train | function | def test_accept_overrides_for_undefined_config_params(tmpdir):
temp_config_path = tmpdir.strpath + '/config.yaml'
param = ('fake_test_param_name', 'fake_test_param_value')
make_default_config_if_needed(temp_config_path)
create_fake_build_artifacts(tmpdir)
with tmpdir.as_cwd():
messages = bac... | def test_accept_overrides_for_undefined_config_params(tmpdir):
| temp_config_path = tmpdir.strpath + '/config.yaml'
param = ('fake_test_param_name', 'fake_test_param_value')
make_default_config_if_needed(temp_config_path)
create_fake_build_artifacts(tmpdir)
with tmpdir.as_cwd():
messages = backend.create_config_from_post(
post_data=dict([param... | '', 'agent_list': ''})
bad_out, bad_code = backend.success(mock_config)
assert got_output == expected_output
assert code == 200
assert bad_out == expected_output_bad
assert bad_code == 400
def test_accept_overrides_for_undefined_config_params(tmpdir):
| 64 | 64 | 124 | 13 | 50 | Chewie/dcos | dcos_installer/test_backend.py | Python | test_accept_overrides_for_undefined_config_params | test_accept_overrides_for_undefined_config_params | 247 | 258 | 247 | 247 | c94246b8b69b56357f43e9e596c2ea944027d42e | bigcode/the-stack | train |
d9e7b2f40ae5cfc9193159b4 | train | function | def test_do_validate_config(tmpdir, monkeypatch):
monkeypatch.setenv('BOOTSTRAP_VARIANT', 'test_variant')
# Create a temp config
genconf_dir = tmpdir.join('genconf')
genconf_dir.ensure(dir=True)
temp_config_path = str(genconf_dir.join('config.yaml'))
# Initialize with defautls
make_default... | def test_do_validate_config(tmpdir, monkeypatch):
| monkeypatch.setenv('BOOTSTRAP_VARIANT', 'test_variant')
# Create a temp config
genconf_dir = tmpdir.join('genconf')
genconf_dir.ensure(dir=True)
temp_config_path = str(genconf_dir.join('config.yaml'))
# Initialize with defautls
make_default_config_if_needed(temp_config_path)
create_fa... | foo',
}
create_fake_build_artifacts(tmpdir)
with tmpdir.as_cwd():
messages = backend.create_config_from_post(
post_data=bad_post_data,
config_path=temp_config_path)
assert messages == expected_bad_messages
def test_do_validate_config(tmpdir, monkeypatch):
| 64 | 64 | 207 | 11 | 52 | Chewie/dcos | dcos_installer/test_backend.py | Python | test_do_validate_config | test_do_validate_config | 168 | 187 | 168 | 168 | 37709ad96c070cb9342d862307ed38c12f58c408 | bigcode/the-stack | train |
4773164bad632c4ef8e446bc | train | function | def test_generate_node_upgrade_script(tmpdir, monkeypatch):
upgrade_config = """
---
# The name of your DC/OS cluster. Visable in the DC/OS user interface.
cluster_name: 'DC/OS'
master_discovery: static
exhibitor_storage_backend: 'static'
resolvers:
- 8.8.8.8
- 8.8.4.4
ssh_port: 22
process_timeout: 10000
bootstrap_... | def test_generate_node_upgrade_script(tmpdir, monkeypatch):
| upgrade_config = """
---
# The name of your DC/OS cluster. Visable in the DC/OS user interface.
cluster_name: 'DC/OS'
master_discovery: static
exhibitor_storage_backend: 'static'
resolvers:
- 8.8.8.8
- 8.8.4.4
ssh_port: 22
process_timeout: 10000
bootstrap_url: file:///opt/dcos_install_tmp
master_list: ['10.0.0.1', ... | config
# Set the password
create_fake_build_artifacts(tmpdir)
subprocess.check_call(['dcos_installer', '--set-superuser-password', 'foo'], cwd=str(tmpdir))
# Check that config.yaml has the password set
config = Config('genconf/config.yaml')
assert passlib.hash.sha512_cr... | 94 | 95 | 319 | 12 | 82 | Chewie/dcos | dcos_installer/test_backend.py | Python | test_generate_node_upgrade_script | test_generate_node_upgrade_script | 71 | 100 | 71 | 71 | f0650869c5cde989b9b0087ea368559ccc266144 | bigcode/the-stack | train |
3429b89177ff3fec3fd803b6 | train | function | def test_override_aws_template_storage_region_name(config_aws, tmpdir, monkeypatch):
bucket = str(uuid.uuid4())
config_str = valid_storage_config.format(
key_id=config_aws["access_key_id"],
bucket=bucket,
access_key=config_aws["secret_access_key"])
config_str += '\naws_template_stora... | def test_override_aws_template_storage_region_name(config_aws, tmpdir, monkeypatch):
| bucket = str(uuid.uuid4())
config_str = valid_storage_config.format(
key_id=config_aws["access_key_id"],
bucket=bucket,
access_key=config_aws["secret_access_key"])
config_str += '\naws_template_storage_region_name: {}'.format(config_aws['region_name'])
assert aws_cf_configure(buc... | , monkeypatch) == 0
# TODO: add an assertion that the config that was resolved inside do_aws_cf_configure
# ended up with the correct region where the above testing bucket was created.
def test_override_aws_template_storage_region_name(config_aws, tmpdir, monkeypatch):
| 64 | 64 | 109 | 19 | 45 | Chewie/dcos | dcos_installer/test_backend.py | Python | test_override_aws_template_storage_region_name | test_override_aws_template_storage_region_name | 320 | 327 | 320 | 320 | 6f4a135adb10b002576f9f93b1b9fa4320028df0 | bigcode/the-stack | train |
5415b1e70de59b0ba60a3a35 | train | function | def test_nonlocal1d():
# NonLocal1d with 'embedded_gaussian' mode
imgs = torch.randn(2, 3, 20)
nonlocal_1d = NonLocal1d(3)
if torch.__version__ == 'parrots':
if torch.cuda.is_available():
imgs = imgs.cuda()
nonlocal_1d.cuda()
out = nonlocal_1d(imgs)
assert out.sha... | def test_nonlocal1d():
# NonLocal1d with 'embedded_gaussian' mode
| imgs = torch.randn(2, 3, 20)
nonlocal_1d = NonLocal1d(3)
if torch.__version__ == 'parrots':
if torch.cuda.is_available():
imgs = imgs.cuda()
nonlocal_1d.cuda()
out = nonlocal_1d(imgs)
assert out.shape == imgs.shape
# NonLocal1d with 'dot_product' mode
imgs = ... | if torch.__version__ == 'parrots':
if torch.cuda.is_available():
nonlocal_2d.cuda()
out = nonlocal_2d(imgs)
assert out.shape == imgs.shape
# NonLocal2d with 'dot_product' mode and sub_sample
nonlocal_2d = NonLocal2d(3, mode='dot_product', sub_sample=True)
for m in [nonlocal_2d.... | 213 | 213 | 713 | 21 | 191 | jinliwei1997/mmcv | tests/test_cnn/test_non_local.py | Python | test_nonlocal1d | test_nonlocal1d | 155 | 219 | 155 | 156 | ff400dbefb02e1c9f7df05a8cb2d92e369fa473f | bigcode/the-stack | train |
bd6932c04e412785fe799c16 | train | function | def test_nonlocal():
with pytest.raises(ValueError):
# mode should be in ['embedded_gaussian', 'dot_product']
_NonLocalNd(3, mode='unsupport_mode')
# _NonLocalNd with zero initialization
_NonLocalNd(3)
_NonLocalNd(3, norm_cfg=dict(type='BN'))
# _NonLocalNd without zero initializati... | def test_nonlocal():
| with pytest.raises(ValueError):
# mode should be in ['embedded_gaussian', 'dot_product']
_NonLocalNd(3, mode='unsupport_mode')
# _NonLocalNd with zero initialization
_NonLocalNd(3)
_NonLocalNd(3, norm_cfg=dict(type='BN'))
# _NonLocalNd without zero initialization
_NonLocalNd(3,... | import pytest
import torch
import torch.nn as nn
from mmcv.cnn import NonLocal1d, NonLocal2d, NonLocal3d
from mmcv.cnn.bricks.non_local import _NonLocalNd
def test_nonlocal():
| 53 | 64 | 115 | 5 | 47 | jinliwei1997/mmcv | tests/test_cnn/test_non_local.py | Python | test_nonlocal | test_nonlocal | 9 | 20 | 9 | 9 | 8ab99c1c9d5fde12fc273fce70a9d24a74963ba5 | bigcode/the-stack | train |
3f5716448eb6423f9b95bc3e | train | function | def test_nonlocal2d():
# NonLocal2d with 'embedded_gaussian' mode
imgs = torch.randn(2, 3, 20, 20)
nonlocal_2d = NonLocal2d(3)
if torch.__version__ == 'parrots':
if torch.cuda.is_available():
imgs = imgs.cuda()
nonlocal_2d.cuda()
out = nonlocal_2d(imgs)
assert out... | def test_nonlocal2d():
# NonLocal2d with 'embedded_gaussian' mode
| imgs = torch.randn(2, 3, 20, 20)
nonlocal_2d = NonLocal2d(3)
if torch.__version__ == 'parrots':
if torch.cuda.is_available():
imgs = imgs.cuda()
nonlocal_2d.cuda()
out = nonlocal_2d(imgs)
assert out.shape == imgs.shape
# NonLocal2d with 'dot_product' mode
img... | d)
if torch.__version__ == 'parrots':
if torch.cuda.is_available():
nonlocal_3d.cuda()
out = nonlocal_3d(imgs)
assert out.shape == imgs.shape
# NonLocal3d with 'dot_product' mode and sub_sample
nonlocal_3d = NonLocal3d(3, mode='dot_product', sub_sample=True)
for m in [nonloc... | 219 | 219 | 731 | 21 | 197 | jinliwei1997/mmcv | tests/test_cnn/test_non_local.py | Python | test_nonlocal2d | test_nonlocal2d | 88 | 152 | 88 | 89 | cb2b928f4163a121e1a6cb316bd52274abd8c800 | bigcode/the-stack | train |
30147a59c76ce1df3e6a4df1 | train | function | def test_nonlocal3d():
# NonLocal3d with 'embedded_gaussian' mode
imgs = torch.randn(2, 3, 10, 20, 20)
nonlocal_3d = NonLocal3d(3)
if torch.__version__ == 'parrots':
if torch.cuda.is_available():
# NonLocal is only implemented on gpu in parrots
imgs = imgs.cuda()
... | def test_nonlocal3d():
# NonLocal3d with 'embedded_gaussian' mode
| imgs = torch.randn(2, 3, 10, 20, 20)
nonlocal_3d = NonLocal3d(3)
if torch.__version__ == 'parrots':
if torch.cuda.is_available():
# NonLocal is only implemented on gpu in parrots
imgs = imgs.cuda()
nonlocal_3d.cuda()
out = nonlocal_3d(imgs)
assert out.shap... | import pytest
import torch
import torch.nn as nn
from mmcv.cnn import NonLocal1d, NonLocal2d, NonLocal3d
from mmcv.cnn.bricks.non_local import _NonLocalNd
def test_nonlocal():
with pytest.raises(ValueError):
# mode should be in ['embedded_gaussian', 'dot_product']
_NonLocalNd(3, mode='unsupport_m... | 184 | 217 | 724 | 21 | 163 | jinliwei1997/mmcv | tests/test_cnn/test_non_local.py | Python | test_nonlocal3d | test_nonlocal3d | 23 | 85 | 23 | 24 | 673ca33b264f517c0fe9a10a1e8b64103e12c5b1 | bigcode/the-stack | train |
74d61cdc3be1cad6698f2528 | train | function | def b2x(b):
return b2a_hex(b).decode('ascii')
| def b2x(b):
| return b2a_hex(b).decode('ascii')
| binascii import b2a_hex
from decimal import Decimal
from test_framework.blocktools import create_coinbase
from test_framework.mininode import CBlock
from test_framework.test_framework import FujicoinTestFramework
from test_framework.util import assert_equal, assert_raises_rpc_error
def b2x(b):
| 64 | 64 | 18 | 6 | 57 | fujicoin/fujicoin-3.0-v0.15.3 | test/functional/mining.py | Python | b2x | b2x | 20 | 21 | 20 | 20 | dd983796ba46c6c7e69c394b87a802cb745261b3 | bigcode/the-stack | train |
916efc0dca6950e7fdd8b4a9 | train | class | class MiningTest(FujicoinTestFramework):
def set_test_params(self):
self.num_nodes = 2
self.setup_clean_chain = False
def run_test(self):
node = self.nodes[0]
self.log.info('getmininginfo')
mining_info = node.getmininginfo()
assert_equal(mining_info['blocks'], 2... | class MiningTest(FujicoinTestFramework):
| def set_test_params(self):
self.num_nodes = 2
self.setup_clean_chain = False
def run_test(self):
node = self.nodes[0]
self.log.info('getmininginfo')
mining_info = node.getmininginfo()
assert_equal(mining_info['blocks'], 200)
assert_equal(mining_info['cha... | #!/usr/bin/env python3
# Copyright (c) 2014-2016 The Fujicoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test mining RPCs
- getmininginfo
- getblocktemplate proposal mode
- submitblock"""
import copy
from ... | 226 | 256 | 1,148 | 10 | 216 | fujicoin/fujicoin-3.0-v0.15.3 | test/functional/mining.py | Python | MiningTest | MiningTest | 29 | 132 | 29 | 29 | b896b048b7eb8a7c1085800d51b22bd7831b2dd4 | bigcode/the-stack | train |
27593f5d12cf507285bca4a4 | train | function | def assert_template(node, block, expect, rehash=True):
if rehash:
block.hashMerkleRoot = block.calc_merkle_root()
rsp = node.getblocktemplate({'data': b2x(block.serialize()), 'mode': 'proposal'})
assert_equal(rsp, expect)
| def assert_template(node, block, expect, rehash=True):
| if rehash:
block.hashMerkleRoot = block.calc_merkle_root()
rsp = node.getblocktemplate({'data': b2x(block.serialize()), 'mode': 'proposal'})
assert_equal(rsp, expect)
| _framework.mininode import CBlock
from test_framework.test_framework import FujicoinTestFramework
from test_framework.util import assert_equal, assert_raises_rpc_error
def b2x(b):
return b2a_hex(b).decode('ascii')
def assert_template(node, block, expect, rehash=True):
| 64 | 64 | 61 | 13 | 51 | fujicoin/fujicoin-3.0-v0.15.3 | test/functional/mining.py | Python | assert_template | assert_template | 23 | 27 | 23 | 23 | db60d4fb5ce1f5191a26b7036ba6d8fc1e91ecf5 | bigcode/the-stack | train |
bf4bec2df8ba73f73f993cda | train | class | class WXAPI(object):
def __init__(self, host):
self.wx_host = host
self.wx_filehost = ''
self.wx_conf = {}
# jsLogin时这个appid只能使用: wx782c26e4c19acffb
self.appid = Constant.API_APPID
self.uuid = ''
self.redirect_uri = ''
self.skey = ''
self.sid ... | class WXAPI(object):
| def __init__(self, host):
self.wx_host = host
self.wx_filehost = ''
self.wx_conf = {}
# jsLogin时这个appid只能使用: wx782c26e4c19acffb
self.appid = Constant.API_APPID
self.uuid = ''
self.redirect_uri = ''
self.skey = ''
self.sid = ''
self.uin ... | #!/usr/bin/env python
# coding: utf-8
#===================================================
from utils import *
from config import Constant
from config import Log
#---------------------------------------------------
import sys
import os
import cookielib
import random
import requests
import time
import xml.dom.minidom
#... | 88 | 256 | 9,084 | 5 | 83 | scmsqhn/WeixinBot | wxbot_project_py2.7/wechat/wechat_apis.py | Python | WXAPI | WXAPI | 22 | 1,003 | 22 | 23 | a493321cb960f6174fe9484edea2a4a9470c4448 | bigcode/the-stack | train |
acf77471d050939bdaa111ea | train | function | def main():
# error checking
try:
checkEnv()
except Exception as err:
raise Exception(f"500 Internal Server Error: {err}")
# setup gcloud
try:
gcloud_cmd = f"gcloud auth activate-service-account {SA_NAME}@{GCP_PROJECT_ID}.iam.gserviceaccount.com --key-file=./creds.json"
... | def main():
# error checking
| try:
checkEnv()
except Exception as err:
raise Exception(f"500 Internal Server Error: {err}")
# setup gcloud
try:
gcloud_cmd = f"gcloud auth activate-service-account {SA_NAME}@{GCP_PROJECT_ID}.iam.gserviceaccount.com --key-file=./creds.json"
print(f"CMD: {gcloud_cmd}")
... | env constants
load_dotenv()
GCP_PROJECT_ID = os.getenv("GCP_PROJECT_ID", "")
GCP_LOCATION = os.getenv("GCP_LOCATION", "")
GCP_DATASET = os.getenv("GCP_DATASET", "")
GCP_DATASTORE = os.getenv("GCP_DATASTORE", "")
GCP_JSON_BUCKET = os.getenv("GCP_JSON_BUCKET", "")
SA_NAME = os.getenv("SA_NAME", "")
def main():
# err... | 93 | 94 | 314 | 8 | 85 | anvilproject/client-apis | gcp/data_transfer.py | Python | main | main | 20 | 51 | 20 | 21 | b93161004eea2a0b8a131c5b7ac826a3ee24792c | bigcode/the-stack | train |
8a50144e5bb620016808f907 | train | function | def checkEnv():
if not GCP_PROJECT_ID:
err = "no GCP_PROJECT_ID in .env"
raise Exception(f"500 Internal Server Error: {err}")
if not GCP_LOCATION:
err = "no GCP_LOCATION in .env"
raise Exception(f"500 Internal Server Error: {err}")
if not GCP_DATASET:
err = "no GCP_DA... | def checkEnv():
| if not GCP_PROJECT_ID:
err = "no GCP_PROJECT_ID in .env"
raise Exception(f"500 Internal Server Error: {err}")
if not GCP_LOCATION:
err = "no GCP_LOCATION in .env"
raise Exception(f"500 Internal Server Error: {err}")
if not GCP_DATASET:
err = "no GCP_DATASET in .env"
... | (), stdout=subprocess.PIPE)
output, error = process.communicate()
print(f"OUTPUT: {output}")
if error:
raise Exception(f"500 Internal Server Error: {error}")
except Exception as err:
raise Exception(f"500 Internal Server Error: {err}")
def checkEnv():
| 63 | 64 | 205 | 4 | 59 | anvilproject/client-apis | gcp/data_transfer.py | Python | checkEnv | checkEnv | 54 | 73 | 54 | 54 | 9329c79a828db1c888a8cd03f18aa568ceb6c588 | bigcode/the-stack | train |
2ce6a1c6251270705119f772 | train | class | class Order(ndb.Model):
order_link = ndb.StringProperty()
order_number = ndb.IntegerProperty(required=True)
order_status = ndb.StringProperty()
order_delivery_date = ndb.DateProperty()
job_number = ndb.IntegerProperty()
status = ndb.StringProperty()
stages = ndb.JsonProperty()
records_... | class Order(ndb.Model):
| order_link = ndb.StringProperty()
order_number = ndb.IntegerProperty(required=True)
order_status = ndb.StringProperty()
order_delivery_date = ndb.DateProperty()
job_number = ndb.IntegerProperty()
status = ndb.StringProperty()
stages = ndb.JsonProperty()
records_link = ndb.StringPropert... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from google.appengine.ext import ndb
class Order(ndb.Model):
| 30 | 64 | 108 | 6 | 23 | clashboom/pt | app/model.py | Python | Order | Order | 8 | 26 | 8 | 8 | 3df27f2d8311eb66c85e433e92417a21aa6fa2a8 | bigcode/the-stack | train |
ad5d74a468b392603fdae0f6 | train | class | class Elite(Order):
color = ndb.StringProperty(required=True)
streamer = ndb.StringProperty()
accessories = ndb.JsonProperty()
notes = ndb.TextProperty()
| class Elite(Order):
| color = ndb.StringProperty(required=True)
streamer = ndb.StringProperty()
accessories = ndb.JsonProperty()
notes = ndb.TextProperty()
| = ndb.IntegerProperty()
status = ndb.StringProperty()
stages = ndb.JsonProperty()
records_link = ndb.StringProperty()
@classmethod
def get_all(cls):
return cls.query()
@classmethod
def get_or_create(cls):
pass
class Elite(Order):
| 64 | 64 | 38 | 4 | 59 | clashboom/pt | app/model.py | Python | Elite | Elite | 29 | 33 | 29 | 29 | e23f80178b9efebce4b34e2f019130a78c346a8c | bigcode/the-stack | train |
75c31c78ac6655772914c896 | train | function | def get_clean_data(species, trait):
markers, pheno = get_markers_and_pheno(species, trait)
# Remove missing phenotypic values from both datasets.
has_trait_data = pheno.notnull()
clean_pheno = pheno[has_trait_data].copy(deep=True)
clean_markers = markers.drop(markers.columns[~has_trait_data], axis=... | def get_clean_data(species, trait):
| markers, pheno = get_markers_and_pheno(species, trait)
# Remove missing phenotypic values from both datasets.
has_trait_data = pheno.notnull()
clean_pheno = pheno[has_trait_data].copy(deep=True)
clean_markers = markers.drop(markers.columns[~has_trait_data], axis=1)
# Remove samples with many m... | from __future__ import print_function
import numpy as np
from genomic_neuralnet.config import REQUIRED_MARKER_CALL_PROPORTION, \
REQUIRED_MARKERS_PER_SAMPLE_PROP
from genomic_neuralnet.util import get_markers_and_pheno
def get_clean_data(species, trait):
| 60 | 121 | 404 | 9 | 50 | lambdaman/genomic-neuralnet | genomic_neuralnet/common/read_clean_data.py | Python | get_clean_data | get_clean_data | 9 | 44 | 9 | 9 | 94badd199282754c9d53ba8e61a49437952385ed | bigcode/the-stack | train |
724e55aa42baad01c90a35da | train | class | class PolyCollection(Collection):
@docstring.dedent_interpd
def __init__(self, verts, sizes = None, closed = True, **kwargs):
"""
*verts* is a sequence of ( *verts0*, *verts1*, ...) where
*verts_i* is a sequence of *xy* tuples of vertices, or an
equivalent :mod:`numpy` array of s... | class PolyCollection(Collection):
@docstring.dedent_interpd
| def __init__(self, verts, sizes = None, closed = True, **kwargs):
"""
*verts* is a sequence of ( *verts0*, *verts1*, ...) where
*verts_i* is a sequence of *xy* tuples of vertices, or an
equivalent :mod:`numpy` array of shape (*nv*, 2).
*sizes* is *None* (default) or a sequen... | * is a sequence of :class:`matplotlib.path.Path`
instances.
%(Collection)s
"""
Collection.__init__(self, **kwargs)
self.set_paths(paths)
self._sizes = sizes
def set_paths(self, paths):
self._paths = paths
def get_paths(self):
return self._paths... | 172 | 172 | 574 | 14 | 158 | tkf/matplotlib | lib/matplotlib/collections.py | Python | PolyCollection | PolyCollection | 690 | 748 | 690 | 691 | 23ddac93ef502a86f4c4a364a484e575aa0b96c3 | bigcode/the-stack | train |
f0bb974fbd5e4ebc2ab69e18 | train | class | class PatchCollection(Collection):
"""
A generic collection of patches.
This makes it easier to assign a color map to a heterogeneous
collection of patches.
This also may improve plotting speed, since PatchCollection will
draw faster than a large number of patches.
"""
def __init__(se... | class PatchCollection(Collection):
| """
A generic collection of patches.
This makes it easier to assign a color map to a heterogeneous
collection of patches.
This also may improve plotting speed, since PatchCollection will
draw faster than a large number of patches.
"""
def __init__(self, patches, match_original=False, ... | unrecognized units: %s' % self._units)
_affine = transforms.Affine2D
for x, y, a in zip(self._widths, self._heights, self._angles):
trans = _affine().scale(x * sc, y * sc).rotate(a)
self._transforms.append(trans)
if self._units == 'xy':
m = ax.transData.get_... | 152 | 152 | 507 | 5 | 147 | tkf/matplotlib | lib/matplotlib/collections.py | Python | PatchCollection | PatchCollection | 1,144 | 1,204 | 1,144 | 1,144 | 2411430cdf21ef80895f6f7438260e1deb138491 | bigcode/the-stack | train |
f2995b9742bdfc96a112eff2 | train | class | class QuadMesh(Collection):
"""
Class for the efficient drawing of a quadrilateral mesh.
A quadrilateral mesh consists of a grid of vertices. The
dimensions of this array are (*meshWidth* + 1, *meshHeight* +
1). Each vertex in the mesh has a different set of "mesh
coordinates" representing its ... | class QuadMesh(Collection):
| """
Class for the efficient drawing of a quadrilateral mesh.
A quadrilateral mesh consists of a grid of vertices. The
dimensions of this array are (*meshWidth* + 1, *meshHeight* +
1). Each vertex in the mesh has a different set of "mesh
coordinates" representing its position in the topology of ... | to backend implementers.
"""
Path = mpath.Path
triangles = tri.get_masked_triangles()
verts = np.concatenate((tri.x[triangles][...,np.newaxis],
tri.y[triangles][...,np.newaxis]), axis=2)
return [Path(x) for x in verts]
@allow_rasterization
... | 256 | 256 | 1,724 | 5 | 251 | tkf/matplotlib | lib/matplotlib/collections.py | Python | QuadMesh | QuadMesh | 1,275 | 1,453 | 1,275 | 1,275 | 5f9513aebc7dc9e8ad7b13f63acbc5282d809051 | bigcode/the-stack | train |
d4692033fa267a9b9b110fc6 | train | class | class BrokenBarHCollection(PolyCollection):
"""
A collection of horizontal bars spanning *yrange* with a sequence of
*xranges*.
"""
@docstring.dedent_interpd
def __init__(self, xranges, yrange, **kwargs):
"""
*xranges*
sequence of (*xmin*, *xwidth*)
*yrange*
... | class BrokenBarHCollection(PolyCollection):
| """
A collection of horizontal bars spanning *yrange* with a sequence of
*xranges*.
"""
@docstring.dedent_interpd
def __init__(self, xranges, yrange, **kwargs):
"""
*xranges*
sequence of (*xmin*, *xwidth*)
*yrange*
*ymin*, *ywidth*
%(Coll... | ._paths = [mpath.Path(xy) for xy in verts]
set_paths = set_verts
@allow_rasterization
def draw(self, renderer):
if self._sizes is not None:
self._transforms = [
transforms.Affine2D().scale(
(np.sqrt(x) * self.figure.dpi / 72.0))
for x... | 105 | 105 | 353 | 9 | 96 | tkf/matplotlib | lib/matplotlib/collections.py | Python | BrokenBarHCollection | BrokenBarHCollection | 751 | 791 | 751 | 751 | b01fa49c754a52c64d4c28a853625cf656eecf71 | bigcode/the-stack | train |
ac557677819067f515a54447 | train | class | class StarPolygonCollection(RegularPolyCollection):
"""
Draw a collection of regular stars with *numsides* points."""
_path_generator = mpath.Path.unit_regular_star
| class StarPolygonCollection(RegularPolyCollection):
| """
Draw a collection of regular stars with *numsides* points."""
_path_generator = mpath.Path.unit_regular_star
| ))
for x in self._sizes]
return Collection.draw(self, renderer)
def get_numsides(self):
return self._numsides
def get_rotation(self):
return self._rotation
def get_sizes(self):
return self._sizes
class StarPolygonCollection(RegularPolyCollection):
| 64 | 64 | 37 | 9 | 54 | tkf/matplotlib | lib/matplotlib/collections.py | Python | StarPolygonCollection | StarPolygonCollection | 858 | 862 | 858 | 858 | 1b2e22923aebfa71137b8e05e55709ae2d607f10 | bigcode/the-stack | train |
514d402a24a1e75980ac5fa9 | train | class | class CircleCollection(Collection):
"""
A collection of circles, drawn using splines.
"""
@docstring.dedent_interpd
def __init__(self, sizes, **kwargs):
"""
*sizes*
Gives the area of the circle in points^2
%(Collection)s
"""
Collection.__init__(se... | class CircleCollection(Collection):
| """
A collection of circles, drawn using splines.
"""
@docstring.dedent_interpd
def __init__(self, sizes, **kwargs):
"""
*sizes*
Gives the area of the circle in points^2
%(Collection)s
"""
Collection.__init__(self,**kwargs)
self._sizes = s... | matplotlib color arg or sequence of rgba tuples
"""
warnings.warn('LineCollection.color deprecated; use set_color instead')
return self.set_color(c)
def get_color(self):
return self._edgecolors
get_colors = get_color # for compatibility with old versions
class CircleCollection... | 64 | 64 | 216 | 5 | 58 | tkf/matplotlib | lib/matplotlib/collections.py | Python | CircleCollection | CircleCollection | 1,029 | 1,058 | 1,029 | 1,029 | 3467c79f63106b8aa7464df35878226870adfde6 | bigcode/the-stack | train |
032050f7f0718cc1cdd25882 | train | class | class EllipseCollection(Collection):
"""
A collection of ellipses, drawn using splines.
"""
@docstring.dedent_interpd
def __init__(self, widths, heights, angles, units='points', **kwargs):
"""
*widths*: sequence
lengths of first axes (e.g., major axis lengths)
*h... | class EllipseCollection(Collection):
| """
A collection of ellipses, drawn using splines.
"""
@docstring.dedent_interpd
def __init__(self, widths, heights, angles, units='points', **kwargs):
"""
*widths*: sequence
lengths of first axes (e.g., major axis lengths)
*heights*: sequence
lengths... | ):
"""
A collection of circles, drawn using splines.
"""
@docstring.dedent_interpd
def __init__(self, sizes, **kwargs):
"""
*sizes*
Gives the area of the circle in points^2
%(Collection)s
"""
Collection.__init__(self,**kwargs)
self._sizes ... | 218 | 218 | 727 | 6 | 212 | tkf/matplotlib | lib/matplotlib/collections.py | Python | EllipseCollection | EllipseCollection | 1,061 | 1,142 | 1,061 | 1,061 | 31ee09b3ebea5266d30033415577f35b3f0aa4cb | bigcode/the-stack | train |
0b4828772e667886bc7acf9c | train | class | class LineCollection(Collection):
"""
All parameters must be sequences or scalars; if scalars, they will
be converted to sequences. The property of the ith line
segment is::
prop[i % len(props)]
i.e., the properties cycle if the ``len`` of props is less than the
number of segments.
... | class LineCollection(Collection):
| """
All parameters must be sequences or scalars; if scalars, they will
be converted to sequences. The property of the ith line
segment is::
prop[i % len(props)]
i.e., the properties cycle if the ``len`` of props is less than the
number of segments.
"""
zorder = 2
def __init... | """
Collection.__init__(self,**kwargs)
self._sizes = sizes
self._numsides = numsides
self._paths = [self._path_generator(numsides)]
self._rotation = rotation
self.set_transform(transforms.IdentityTransform())
@allow_rasterization
def draw(self, renderer):... | 256 | 256 | 1,271 | 5 | 250 | tkf/matplotlib | lib/matplotlib/collections.py | Python | LineCollection | LineCollection | 872 | 1,027 | 872 | 872 | 0988a98ebcaa622a50aae469c3a43cbfcc82bb84 | bigcode/the-stack | train |
f498573c7b62cf8b52468b79 | train | class | class Collection(artist.Artist, cm.ScalarMappable):
"""
Base class for Collections. Must be subclassed to be usable.
All properties in a collection must be sequences or scalars;
if scalars, they will be converted to sequences. The
property of the ith element of the collection is::
prop[i %... | class Collection(artist.Artist, cm.ScalarMappable):
| """
Base class for Collections. Must be subclassed to be usable.
All properties in a collection must be sequences or scalars;
if scalars, they will be converted to sequences. The
property of the ith element of the collection is::
prop[i % len(props)]
Keyword arguments and default valu... | """
Classes for the efficient drawing of large collections of objects that
share most properties, e.g. a large number of line segments or
polygons.
The classes are not meant to be as flexible as their single element
counterparts (e.g. you may not be able to select all line styles) but
they are meant to be fast for com... | 203 | 256 | 4,541 | 13 | 189 | tkf/matplotlib | lib/matplotlib/collections.py | Python | Collection | Collection | 27 | 627 | 27 | 27 | a5bcf34f89261ecb4eab791863340fcb21e8e54c | bigcode/the-stack | train |
31a2fc4a4a04a5fa3a4c0327 | train | class | class TriMesh(Collection):
"""
Class for the efficient drawing of a triangular mesh using
Gouraud shading.
A triangular mesh is a :class:`~matplotlib.tri.Triangulation`
object.
"""
def __init__(self, triangulation, **kwargs):
Collection.__init__(self, **kwargs)
self._triangu... | class TriMesh(Collection):
| """
Class for the efficient drawing of a triangular mesh using
Gouraud shading.
A triangular mesh is a :class:`~matplotlib.tri.Triangulation`
object.
"""
def __init__(self, triangulation, **kwargs):
Collection.__init__(self, **kwargs)
self._triangulation = triangulation;
... | = [p.get_linewidth() for p in patches]
linestyles = [p.get_linestyle() for p in patches]
antialiaseds = [p.get_antialiased() for p in patches]
Collection.__init__(
self,
edgecolors=edgecolors,
facecolors=facecolors,
... | 156 | 156 | 522 | 5 | 150 | tkf/matplotlib | lib/matplotlib/collections.py | Python | TriMesh | TriMesh | 1,206 | 1,272 | 1,206 | 1,206 | 949cd720d1aee349b7e75984dc07d92dc668eeb7 | bigcode/the-stack | train |
ac96bff54109bfdc4e67a869 | train | class | class PathCollection(Collection):
"""
This is the most basic :class:`Collection` subclass.
"""
@docstring.dedent_interpd
def __init__(self, paths, sizes=None, **kwargs):
"""
*paths* is a sequence of :class:`matplotlib.path.Path`
instances.
%(Collection)s
"""
... | class PathCollection(Collection):
| """
This is the most basic :class:`Collection` subclass.
"""
@docstring.dedent_interpd
def __init__(self, paths, sizes=None, **kwargs):
"""
*paths* is a sequence of :class:`matplotlib.path.Path`
instances.
%(Collection)s
"""
Collection.__init__(self,... | patch after
rendering (default no offsets)
If any of *edgecolors*, *facecolors*, *linewidths*, *antialiaseds*
are None, they default to their :data:`matplotlib.rcParams` patch
setting, in sequence form.
""")
class PathCollection(Collection):
| 64 | 64 | 209 | 5 | 59 | tkf/matplotlib | lib/matplotlib/collections.py | Python | PathCollection | PathCollection | 655 | 688 | 655 | 655 | c02db42475a6e0c74a7ba7323cd20f1f14eddc63 | bigcode/the-stack | train |
98b3bce5b973e3423a764a1e | train | class | class RegularPolyCollection(Collection):
"""Draw a collection of regular polygons with *numsides*."""
_path_generator = mpath.Path.unit_regular_polygon
@docstring.dedent_interpd
def __init__(self,
numsides,
rotation = 0 ,
sizes = (1,),
... | class RegularPolyCollection(Collection):
| """Draw a collection of regular polygons with *numsides*."""
_path_generator = mpath.Path.unit_regular_polygon
@docstring.dedent_interpd
def __init__(self,
numsides,
rotation = 0 ,
sizes = (1,),
**kwargs):
"""
*numsides... | * to *ymax*
A :class:`BrokenBarHCollection` is returned. *kwargs* are
passed on to the collection.
"""
xranges = []
for ind0, ind1 in mlab.contiguous_regions(where):
xslice = x[ind0:ind1]
if not len(xslice):
continue
xranges.a... | 126 | 126 | 420 | 6 | 119 | tkf/matplotlib | lib/matplotlib/collections.py | Python | RegularPolyCollection | RegularPolyCollection | 793 | 855 | 793 | 793 | cf09625d5dad7eaba35820c0bf302ea41bf39685 | bigcode/the-stack | train |
eecd02b34eb0fe006d21e6a2 | train | class | class AsteriskPolygonCollection(RegularPolyCollection):
"""
Draw a collection of regular asterisks with *numsides* points."""
_path_generator = mpath.Path.unit_regular_asterisk
| class AsteriskPolygonCollection(RegularPolyCollection):
| """
Draw a collection of regular asterisks with *numsides* points."""
_path_generator = mpath.Path.unit_regular_asterisk
| return self._rotation
def get_sizes(self):
return self._sizes
class StarPolygonCollection(RegularPolyCollection):
"""
Draw a collection of regular stars with *numsides* points."""
_path_generator = mpath.Path.unit_regular_star
class AsteriskPolygonCollection(RegularPolyCollection):
| 64 | 64 | 43 | 10 | 53 | tkf/matplotlib | lib/matplotlib/collections.py | Python | AsteriskPolygonCollection | AsteriskPolygonCollection | 865 | 869 | 865 | 865 | cf99117f9406378522c8bee866bca4cddb495579 | bigcode/the-stack | train |
0cb5926835fdbc5570f730fb | train | class | class NLLLoss(Module):
""" The negative log likelihood loss. It is useful to train a classification
problem with `C` classes.
The `input` given through a forward call is expected to contain
log-probabilities of each class. `input` has to be a Tensor of size either
:math:`(minibatch, C)` or :math:`(... | class NLLLoss(Module):
| """ The negative log likelihood loss. It is useful to train a classification
problem with `C` classes.
The `input` given through a forward call is expected to contain
log-probabilities of each class. `input` has to be a Tensor of size either
:math:`(minibatch, C)` or :math:`(minibatch, C, d_1, d_2,... | )
"""
def __init__(self, weight: Tensor = None, reduction: str = "mean") -> None:
super().__init__()
assert reduction in [
"none",
"sum",
"mean",
None,
], "only 'sum', 'mean' and 'none' supported by now"
self.weight = weight
... | 256 | 256 | 1,544 | 6 | 249 | EsdeathYZH/oneflow | python/oneflow/nn/modules/loss.py | Python | NLLLoss | NLLLoss | 320 | 461 | 320 | 320 | 00188ccdf2f443ec71dab8d0a6fda10c4c1b1ceb | bigcode/the-stack | train |
ad3260283e0014e32a72d5ce | train | class | class MSELoss(Module):
"""The interface is consistent with PyTorch.
The documentation is referenced from:
https://pytorch.org/docs/stable/generated/torch.nn.MSELoss.html?highlight=mseloss#torch.nn.MSELoss
Creates a criterion that measures the mean squared error (squared L2 norm) between
each elemen... | class MSELoss(Module):
| """The interface is consistent with PyTorch.
The documentation is referenced from:
https://pytorch.org/docs/stable/generated/torch.nn.MSELoss.html?highlight=mseloss#torch.nn.MSELoss
Creates a criterion that measures the mean squared error (squared L2 norm) between
each element in the input :math:`x... | __(self, reduction: str = "mean", log_target: bool = False) -> None:
super().__init__()
assert reduction in [
"sum",
"none",
"mean",
None,
], "Argument reduction only support 'sum'/'mean'/'none'/None for now!"
self.reduction = reduction
... | 256 | 256 | 948 | 6 | 249 | EsdeathYZH/oneflow | python/oneflow/nn/modules/loss.py | Python | MSELoss | MSELoss | 582 | 669 | 582 | 582 | 76d1fd011ccacba06235c2225f6a1d1d37e58ced | bigcode/the-stack | train |
06925625e787ccce8a59dea8 | train | class | class CTCLoss(Module):
"""The Connectionist Temporal Classification loss.
The interface is consistent with PyTorch.
The documentation is referenced from:
https://pytorch.org/docs/stable/generated/torch.nn.CTCLoss.html#torch.nn.CTCLoss
Calculates loss between a continuous (unsegmented) time series a... | class CTCLoss(Module):
| """The Connectionist Temporal Classification loss.
The interface is consistent with PyTorch.
The documentation is referenced from:
https://pytorch.org/docs/stable/generated/torch.nn.CTCLoss.html#torch.nn.CTCLoss
Calculates loss between a continuous (unsegmented) time series and a target sequence. C... | >>> out = m(x1, x2, target)
>>> out
tensor(8.2, dtype=oneflow.float32)
>>> m = flow.nn.MarginRankingLoss(margin = 10, reduction="mean")
>>> out = m(x1, x2, target)
>>> out
tensor(8.3333, dtype=oneflow.float32)
"""
def __init__(self, margin=0.0, reduction: str... | 256 | 256 | 1,734 | 6 | 250 | EsdeathYZH/oneflow | python/oneflow/nn/modules/loss.py | Python | CTCLoss | CTCLoss | 753 | 905 | 753 | 753 | 1949af6dfb0a3af5bc951ba5499f8f80b525400b | bigcode/the-stack | train |
40f6e650021c7e4d37c90107 | train | class | class SmoothL1Loss(Module):
"""Creates a criterion that uses a squared term if the absolute
element-wise error falls below beta and an L1 term otherwise.
The interface is consistent with PyTorch.
The documentation is referenced from:
https://pytorch.org/docs/stable/generated/torch.nn.SmoothL1Loss.ht... | class SmoothL1Loss(Module):
| """Creates a criterion that uses a squared term if the absolute
element-wise error falls below beta and an L1 term otherwise.
The interface is consistent with PyTorch.
The documentation is referenced from:
https://pytorch.org/docs/stable/generated/torch.nn.SmoothL1Loss.html
It is less sensitive... | _neg_input = flow.negative(input)
_max_val = flow.clip(_neg_input, 0)
_neg_max_val = flow.negative(_max_val)
if self.pos_weight:
_log_weight = (self.pos_weight - 1) * target + 1
_loss = (1 - target) * input + _log_weight * (
flow.log(flow.exp(_neg_... | 256 | 256 | 1,593 | 7 | 248 | EsdeathYZH/oneflow | python/oneflow/nn/modules/loss.py | Python | SmoothL1Loss | SmoothL1Loss | 1,032 | 1,162 | 1,032 | 1,032 | 77627637fe77447d09536b0f89d14f8d872348ce | bigcode/the-stack | train |
e9fa815ec47cc0edd93eeb15 | train | class | class MarginRankingLoss(Module):
"""Creates a criterion that measures the loss given
inputs :math:`x1`, :math:`x2`, two 1D mini-batch `Tensors`,
and a label 1D mini-batch tensor :math:`y` (containing 1 or -1).
If :math:`y = 1` then it assumed the first input should be ranked higher
(have a larger v... | class MarginRankingLoss(Module):
| """Creates a criterion that measures the loss given
inputs :math:`x1`, :math:`x2`, two 1D mini-batch `Tensors`,
and a label 1D mini-batch tensor :math:`y` (containing 1 or -1).
If :math:`y = 1` then it assumed the first input should be ranked higher
(have a larger value) than the second input, and ... | .5589, 4.0823, 0.1173]], dtype=oneflow.float32)
>>> m = flow.nn.MSELoss(reduction="mean")
>>> out = m(input, target)
>>> out
tensor(1.3573, dtype=oneflow.float32)
>>> m = flow.nn.MSELoss(reduction="sum")
>>> out = m(input, target)
>>> out
tensor(8.1436, dt... | 256 | 256 | 893 | 6 | 249 | EsdeathYZH/oneflow | python/oneflow/nn/modules/loss.py | Python | MarginRankingLoss | MarginRankingLoss | 672 | 750 | 672 | 672 | e5e157aeedd1a2138098246942421b1daae80e49 | bigcode/the-stack | train |
fb92718f905bd84d2b1b8aeb | train | class | class KLDivLoss(Module):
"""The interface is consistent with PyTorch.
The documentation is referenced from:
https://pytorch.org/docs/stable/generated/torch.nn.KLDivLoss.html?highlight=kldivloss#torch.nn.KLDivLoss
The Kullback-Leibler divergence loss measure
`Kullback-Leibler divergence`_ is a usef... | class KLDivLoss(Module):
| """The interface is consistent with PyTorch.
The documentation is referenced from:
https://pytorch.org/docs/stable/generated/torch.nn.KLDivLoss.html?highlight=kldivloss#torch.nn.KLDivLoss
The Kullback-Leibler divergence loss measure
`Kullback-Leibler divergence`_ is a useful distance measure for c... | 1],
input.shape[2],
input.shape[3],
)
input = flow.F.transpose(input, perm=(0, 2, 3, 1))
input = input.reshape(shape=[-1, input.shape[3]])
target = target.flatten()
res = self.nllloss_1d(input, target)
res = res.resh... | 256 | 256 | 1,356 | 6 | 250 | EsdeathYZH/oneflow | python/oneflow/nn/modules/loss.py | Python | KLDivLoss | KLDivLoss | 464 | 579 | 464 | 464 | c3f18d45a4777ed1c13bfab361d5ed09e385a56e | bigcode/the-stack | train |
6556267711fc0383503ce4f1 | train | class | class BCEWithLogitsLoss(Module):
"""This operator combines the `Sigmoid` and `BCELoss` together. For numerical stability,
we apply some math tricks instead of using `Sigmoid` layer with `BCELoss`.
The equation is:
if :attr:`reduction` = ``"none"``:
.. math::
out = -weight*[Pos\\_weight*y... | class BCEWithLogitsLoss(Module):
| """This operator combines the `Sigmoid` and `BCELoss` together. For numerical stability,
we apply some math tricks instead of using `Sigmoid` layer with `BCELoss`.
The equation is:
if :attr:`reduction` = ``"none"``:
.. math::
out = -weight*[Pos\\_weight*y*log\\sigma({x}) + (1-y)*log(1-\\... | self._xdivy_op = (
flow.builtin_op("xdivy").Input("x").Input("y").Output("z").Build()
)
self.constant = _ConstantBase
def forward(
self,
log_probs: Tensor,
targets: Tensor,
input_lengths: Tensor,
target_lengths: Tensor,
) -> Tensor:
(... | 256 | 256 | 1,310 | 8 | 247 | EsdeathYZH/oneflow | python/oneflow/nn/modules/loss.py | Python | BCEWithLogitsLoss | BCEWithLogitsLoss | 908 | 1,029 | 908 | 908 | 15aced718805c96339967d2509a29edb001f73be | bigcode/the-stack | train |
2db38d8db5c811c77608d60a | train | class | class CrossEntropyLoss(Module):
"""This criterion combines :class:`~flow.nn.LogSoftmax` and :class:`~flow.nn.NLLLoss` in one single class.
It is useful when training a classification problem with `C` classes.
The `input` is expected to contain raw, unnormalized scores for each class.
`input` has to b... | class CrossEntropyLoss(Module):
| """This criterion combines :class:`~flow.nn.LogSoftmax` and :class:`~flow.nn.NLLLoss` in one single class.
It is useful when training a classification problem with `C` classes.
The `input` is expected to contain raw, unnormalized scores for each class.
`input` has to be a Tensor of size either :math:... | m_mean(input, target)
>>> out
tensor(2.6667, dtype=oneflow.float32)
>>> m_mean = flow.nn.L1Loss(reduction="sum")
>>> out = m_mean(input, target)
>>> out
tensor(24., dtype=oneflow.float32)
"""
def __init__(self, reduction: str = "mean", reduce=True) -> None:
... | 256 | 256 | 1,236 | 6 | 249 | EsdeathYZH/oneflow | python/oneflow/nn/modules/loss.py | Python | CrossEntropyLoss | CrossEntropyLoss | 104 | 220 | 104 | 104 | 38bfe65cae72c7ab971fa6d1dc6e0df70400f059 | bigcode/the-stack | train |
1caed1bd2f87688e439a7304 | train | class | class L1Loss(Module):
"""This operator computes the L1 Loss between each element in `input` and `target`.
The equation is:
if reduction = "none":
.. math::
output = |Target - Input|
if reduction = "mean":
.. math::
output = \\frac{1}{n}\\sum_{i=1}^n|Target_i - Input_i|
... | class L1Loss(Module):
| """This operator computes the L1 Loss between each element in `input` and `target`.
The equation is:
if reduction = "none":
.. math::
output = |Target - Input|
if reduction = "mean":
.. math::
output = \\frac{1}{n}\\sum_{i=1}^n|Target_i - Input_i|
if reduction = "sum"... | """
Copyright 2020 The OneFlow Authors. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agr... | 167 | 186 | 622 | 6 | 160 | EsdeathYZH/oneflow | python/oneflow/nn/modules/loss.py | Python | L1Loss | L1Loss | 24 | 101 | 24 | 24 | 7ff7730dc95889626ec717449715943dbaf062d4 | bigcode/the-stack | train |
0a1aa65a536dfaf06662ec7d | train | class | class BCELoss(Module):
"""This operator computes the binary cross entropy loss.
The equation is:
if reduction = "none":
.. math::
out = -(Target_i*log(Input_i) + (1-Target_i)*log(1-Input_i))
if reduction = "mean":
.. math::
out = -\\frac{1}{n}\\sum_{i=1}^n(Target_i*log(Inp... | class BCELoss(Module):
| """This operator computes the binary cross entropy loss.
The equation is:
if reduction = "none":
.. math::
out = -(Target_i*log(Input_i) + (1-Target_i)*log(1-Input_i))
if reduction = "mean":
.. math::
out = -\\frac{1}{n}\\sum_{i=1}^n(Target_i*log(Input_i) + (1-Target_i)*lo... | ))
input = input.reshape(shape=[-1, input.shape[3]])
target = target.flatten()
elif input_shape_len >= 5:
raise NotImplemented
out = flow.F.sparse_softmax_cross_entropy(
input, target, depth=input.shape[len(input.shape) - 1]
)
if self.ignor... | 256 | 256 | 869 | 6 | 249 | EsdeathYZH/oneflow | python/oneflow/nn/modules/loss.py | Python | BCELoss | BCELoss | 223 | 317 | 223 | 223 | eff128aa3420be9b9b20757d59ed4907bab9fdb8 | bigcode/the-stack | train |
3f713bab09eda95cdb4dc7eb | train | class | class LxPerCpuCounterSum(sdb.SingleInputCommand):
"""
Return the sum of a per-CPU counter.
EXAMPLES
Get the global memory commitment made in a system (this is almost the
same as calling vm_memory_committed() on the kernel C code):
sdb> addr vm_committed_as | cpu_counter_sum
... | class LxPerCpuCounterSum(sdb.SingleInputCommand):
| """
Return the sum of a per-CPU counter.
EXAMPLES
Get the global memory commitment made in a system (this is almost the
same as calling vm_memory_committed() on the kernel C code):
sdb> addr vm_committed_as | cpu_counter_sum
(s64)1067887
Get the number of o... | for cpu in cpus:
if cpu >= self.ncpus:
raise sdb.CommandError(
self.name,
f"available CPUs [0-{self.ncpus -1}] - requested CPU {cpu}")
yield drgn_percpu.per_cpu_ptr(obj, cpu)
class LxPerCpuCounterSum(sdb.SingleInputCommand):
| 73 | 73 | 245 | 13 | 60 | sravyamks/sdb | sdb/commands/linux/per_cpu.py | Python | LxPerCpuCounterSum | LxPerCpuCounterSum | 73 | 103 | 73 | 73 | 145818e15112cccd6021bfc50ee57c30a21b3294 | bigcode/the-stack | train |
878cc49d68245a1708ed6b44 | train | class | class LxPerCpuPtr(sdb.SingleInputCommand):
"""
Return the per-CPU pointer for the given CPU (or all if none is specified).
EXAMPLES
Get the per-CPU data of the "kmalloc-8" kmem cache for CPUs 0 and 1:
sdb> slabs | filter obj.name == "kmalloc-8" | member cpu_slab
(struct kme... | class LxPerCpuPtr(sdb.SingleInputCommand):
| """
Return the per-CPU pointer for the given CPU (or all if none is specified).
EXAMPLES
Get the per-CPU data of the "kmalloc-8" kmem cache for CPUs 0 and 1:
sdb> slabs | filter obj.name == "kmalloc-8" | member cpu_slab
(struct kmem_cache_cpu *)0x2f040
sdb> slab... | .org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitat... | 142 | 142 | 474 | 12 | 129 | sravyamks/sdb | sdb/commands/linux/per_cpu.py | Python | LxPerCpuPtr | LxPerCpuPtr | 28 | 70 | 28 | 28 | 4b40352344dbf39c7cc812a0bde8baaaf867e04d | bigcode/the-stack | train |
3f245de700e4c35ef45612e0 | train | class | class SequencialExecutionStrategy(ExecutionStrategy):
def __init__(self, configuration, results, execution, benchmarks):
super().__init__(configuration, results, execution, benchmarks)
self.__running = False
self.__current = None
self.__timeout = None
@property
def is_stop... | class SequencialExecutionStrategy(ExecutionStrategy):
| def __init__(self, configuration, results, execution, benchmarks):
super().__init__(configuration, results, execution, benchmarks)
self.__running = False
self.__current = None
self.__timeout = None
@property
def is_stopped(self):
return not self.__running
def s... | # -*- coding: utf-8 -*-
import threading
from ..config.ConfigurationManager import ConfigurationManager
from ..results.ResultsManager import ResultsManager
from .ExecutionState import ExecutionState
from ..benchmarks.BenchmarkInstance import BenchmarkInstance
from ..benchmarks.BenchmarkSuiteInstance import BenchmarkS... | 110 | 116 | 387 | 9 | 100 | pip-benchmark/pip-benchmark-python | pip_benchmark_python/runner/execution/SequencialExecutionStrategy.py | Python | SequencialExecutionStrategy | SequencialExecutionStrategy | 17 | 86 | 17 | 18 | 9233f850bd60032e749a3d23d95b3ccc70bcaa36 | bigcode/the-stack | train |
59d95af70da3e48670df62a2 | train | class | class EditAvatar(AbstractCommand):
"""Изменение аватара."""
name = settings.AVA_INFO
@login_required
def execute(self, serv, msg, *args, **kwargs):
username = getattr(msg, settings.SENDER, None)
user = db.User.by_name(username)
ava = getattr(msg, settings.DATA, None)
if... | class EditAvatar(AbstractCommand):
| """Изменение аватара."""
name = settings.AVA_INFO
@login_required
def execute(self, serv, msg, *args, **kwargs):
username = getattr(msg, settings.SENDER, None)
user = db.User.by_name(username)
ava = getattr(msg, settings.DATA, None)
if user and ava:
user.ava... | : user.pub_key, settings.ACCOUNT_NAME: dest_user})
else:
mes = Msg.error_resp('Ошибка определения ключа')
serv.write_client_data(conn, mes)
logger.info(f'User {src_user} get pub_key {dest_user}')
return True
class EditAvatar(AbstractCommand):
| 64 | 64 | 103 | 6 | 57 | mom1/messager | talkative_server/talkative_server/contacts/commands.py | Python | EditAvatar | EditAvatar | 99 | 112 | 99 | 99 | f23ab40f0728e6e3b7ee540f16bb860c16441c5c | bigcode/the-stack | train |
c8c430328d16629627f9efd6 | train | class | class DelContactCommand(AbstractCommand):
"""Обрабатывает запросы на удаление контакта."""
name = settings.DEL_CONTACT
@login_required
def execute(self, serv, msg, *args, **kwargs):
"""Выполнение."""
src_user = getattr(msg, settings.USER, None)
contact = getattr(msg, settings.A... | class DelContactCommand(AbstractCommand):
| """Обрабатывает запросы на удаление контакта."""
name = settings.DEL_CONTACT
@login_required
def execute(self, serv, msg, *args, **kwargs):
"""Выполнение."""
src_user = getattr(msg, settings.USER, None)
contact = getattr(msg, settings.ACCOUNT_NAME, None)
user = db.User.... | _data(serv.names.get(src_user), Msg.success())
serv.notify(self.name)
else:
serv.write_client_data(serv.names.get(src_user), Msg.error_resp('Не найден контакт'))
logger.info(f'User {src_user} add contact {contact}')
return True
class DelContactCommand(AbstractCommand):
| 64 | 64 | 144 | 7 | 56 | mom1/messager | talkative_server/talkative_server/contacts/commands.py | Python | DelContactCommand | DelContactCommand | 42 | 59 | 42 | 42 | bc2e9023dec1a4b59da7429afa5273bc0ce4c69f | bigcode/the-stack | train |
241b59a632d5260e20201916 | train | class | class RequestKeyCommand(AbstractCommand):
"""Обрабатывает запросы на получение списка контактов пользователя."""
name = settings.PUBLIC_KEY_REQUEST
@login_required
def execute(self, serv, msg, *args, **kwargs):
"""Выполнение."""
dest_user = getattr(msg, settings.DESTINATION, None)
... | class RequestKeyCommand(AbstractCommand):
| """Обрабатывает запросы на получение списка контактов пользователя."""
name = settings.PUBLIC_KEY_REQUEST
@login_required
def execute(self, serv, msg, *args, **kwargs):
"""Выполнение."""
dest_user = getattr(msg, settings.DESTINATION, None)
src_user = getattr(msg, settings.SENDE... | )
contacts = [c.contact.username for c in user.contacts]
serv.write_client_data(serv.names.get(src_user), Msg.success(202, **{settings.LIST_INFO: contacts}))
logger.info(f'User {src_user} get list contacts')
return True
class RequestKeyCommand(AbstractCommand):
| 64 | 64 | 179 | 7 | 56 | mom1/messager | talkative_server/talkative_server/contacts/commands.py | Python | RequestKeyCommand | RequestKeyCommand | 78 | 96 | 78 | 78 | 8f055fb05875cd0ffe3c5768ca34b79bc05da6d6 | bigcode/the-stack | train |
76930a06b6d2fbc83e02f13d | train | class | class AddContactCommand(AbstractCommand):
"""Обрабатывает запросы на добавление контакта."""
name = settings.ADD_CONTACT
@login_required
def execute(self, serv, msg, *args, **kwargs):
"""Выполнение."""
src_user = getattr(msg, settings.USER, None)
contact = getattr(msg, settings... | class AddContactCommand(AbstractCommand):
| """Обрабатывает запросы на добавление контакта."""
name = settings.ADD_CONTACT
@login_required
def execute(self, serv, msg, *args, **kwargs):
"""Выполнение."""
src_user = getattr(msg, settings.USER, None)
contact = getattr(msg, settings.ACCOUNT_NAME, None)
user = db.Use... | from talkative_server.commands import AbstractCommand, main_commands
from talkative_server.db import DBManager
from talkative_server.decorators import login_required
from talkative_server.jim_mes import Message as Msg
logger = logging.getLogger('server__contacts')
db = DBManager()
class AddContactCommand(AbstractComma... | 64 | 64 | 165 | 7 | 57 | mom1/messager | talkative_server/talkative_server/contacts/commands.py | Python | AddContactCommand | AddContactCommand | 20 | 39 | 20 | 20 | c825bde7e2c0de2ab01a9ab7cf40c066210e4d7a | bigcode/the-stack | train |
a3ba03d2a577b38aa832f90d | train | class | class ListContactsCommand(AbstractCommand):
"""Обрабатывает запросы на получение списка контактов пользователя."""
name = settings.GET_CONTACTS
@login_required
def execute(self, serv, msg, *args, **kwargs):
"""Выполнение."""
src_user = getattr(msg, settings.USER, None)
user = d... | class ListContactsCommand(AbstractCommand):
| """Обрабатывает запросы на получение списка контактов пользователя."""
name = settings.GET_CONTACTS
@login_required
def execute(self, serv, msg, *args, **kwargs):
"""Выполнение."""
src_user = getattr(msg, settings.USER, None)
user = db.User.by_name(src_user)
contacts = ... | _user)
if contact:
with serv.db_lock:
user.del_contact(contact)
serv.write_client_data(serv.names.get(src_user), Msg.success())
serv.notify(self.name)
logger.info(f'User {src_user} del contact {contact}')
return True
class ListContactsCommand(A... | 64 | 64 | 133 | 7 | 56 | mom1/messager | talkative_server/talkative_server/contacts/commands.py | Python | ListContactsCommand | ListContactsCommand | 62 | 75 | 62 | 62 | 6a7b3a1f07fdba9fdae272194be6c0809c14e3e7 | bigcode/the-stack | train |
6d956e74e8c264046720ff92 | train | function | @secret.command(name="list")
@click.option(
"-e", "--env", default=None, help="The env to use when loading the config file"
)
@click.option(
"-c", "--config", default="opta.yml", help="Opta config file", show_default=True
)
def list_command(env: Optional[str], config: str) -> None:
"""List the secrets setup... | @secret.command(name="list")
@click.option(
"-e", "--env", default=None, help="The env to use when loading the config file"
)
@click.option(
"-c", "--config", default="opta.yml", help="Opta config file", show_default=True
)
def list_command(env: Optional[str], config: str) -> None:
| """List the secrets setup for the given k8s service module"""
layer = Layer.load_from_yaml(config, env)
amplitude_client.send_event(amplitude_client.LIST_SECRETS_EVENT)
gen_all(layer)
configure_kubectl(layer)
create_namespace_if_not_exists(layer.name)
secrets = get_secrets(layer.name)
f... | @secret.command(name="list")
@click.option(
"-e", "--env", default=None, help="The env to use when loading the config file"
)
@click.option(
"-c", "--config", default="opta.yml", help="Opta config file", show_default=True
)
def list_command(env: Optional[str], config: str) -> None:
| 76 | 64 | 157 | 76 | 0 | wpride/opta | opta/commands/secret.py | Python | list_command | list_command | 54 | 71 | 54 | 61 | f359a1fef10311f09a9f2876522da7359f1a13fc | bigcode/the-stack | train |
43ddb6e6397ae475b43d9b46 | train | function | @click.group(cls=DYMGroup)
def secret() -> None:
"""Commands for manipulating secrets for a k8s service"""
pass
| @click.group(cls=DYMGroup)
def secret() -> None:
| """Commands for manipulating secrets for a k8s service"""
pass
| configure_kubectl,
create_namespace_if_not_exists,
get_secrets,
update_manual_secrets,
)
from opta.exceptions import UserErrors
from opta.layer import Layer
from opta.utils import check_opta_file_exists
@click.group(cls=DYMGroup)
def secret() -> None:
| 64 | 64 | 29 | 13 | 50 | wpride/opta | opta/commands/secret.py | Python | secret | secret | 19 | 22 | 19 | 20 | c9fd026171c8915ade24b2162d97de27acf78f12 | bigcode/the-stack | train |
1176eda14fab83d88fdfb7d1 | train | function | @secret.command()
@click.argument("secret")
@click.argument("value")
@click.option(
"-e", "--env", default=None, help="The env to use when loading the config file"
)
@click.option(
"-c", "--config", default="opta.yml", help="Opta config file", show_default=True
)
def update(secret: str, value: str, env: Optiona... | @secret.command()
@click.argument("secret")
@click.argument("value")
@click.option(
"-e", "--env", default=None, help="The env to use when loading the config file"
)
@click.option(
"-c", "--config", default="opta.yml", help="Opta config file", show_default=True
)
def update(secret: str, value: str, env: Optiona... | """Update a given secret of a k8s service with a new value"""
check_opta_file_exists(config)
layer = Layer.load_from_yaml(config, env)
gen_all(layer)
configure_kubectl(layer)
create_namespace_if_not_exists(layer.name)
amplitude_client.send_event(amplitude_client.UPDATE_SECRET_EVENT)
up... | @secret.command()
@click.argument("secret")
@click.argument("value")
@click.option(
"-e", "--env", default=None, help="The env to use when loading the config file"
)
@click.option(
"-c", "--config", default="opta.yml", help="Opta config file", show_default=True
)
def update(secret: str, value: str, env: Optiona... | 90 | 64 | 179 | 90 | 0 | wpride/opta | opta/commands/secret.py | Python | update | update | 74 | 95 | 74 | 83 | 445a51c004f854e14fa9e4615f0aad8672d63bef | bigcode/the-stack | train |
682944f607bf23cdbfaa2c40 | train | function | @secret.command()
@click.argument("secret")
@click.option(
"-e", "--env", default=None, help="The env to use when loading the config file"
)
@click.option(
"-c", "--config", default="opta.yml", help="Opta config file", show_default=True
)
def view(secret: str, env: Optional[str], config: str) -> None:
"""Vi... | @secret.command()
@click.argument("secret")
@click.option(
"-e", "--env", default=None, help="The env to use when loading the config file"
)
@click.option(
"-c", "--config", default="opta.yml", help="Opta config file", show_default=True
)
def view(secret: str, env: Optional[str], config: str) -> None:
| """View a given secret of a k8s service"""
check_opta_file_exists(config)
layer = Layer.load_from_yaml(config, env)
layer.verify_cloud_credentials()
amplitude_client.send_event(amplitude_client.VIEW_SECRET_EVENT)
gen_all(layer)
configure_kubectl(layer)
create_namespace_if_not_exists(la... | @secret.command()
@click.argument("secret")
@click.option(
"-e", "--env", default=None, help="The env to use when loading the config file"
)
@click.option(
"-c", "--config", default="opta.yml", help="Opta config file", show_default=True
)
def view(secret: str, env: Optional[str], config: str) -> None:
| 81 | 66 | 222 | 81 | 0 | wpride/opta | opta/commands/secret.py | Python | view | view | 25 | 51 | 25 | 33 | a52cb940fe62ec097706737d1a4e623b34ccaedb | bigcode/the-stack | train |
b6c980879bb0da5d56601db2 | train | class | class CueSheetCues(Document):
pass
| class CueSheetCues(Document):
| pass
| , software
#distributed under the License is distributed on an "AS IS" BASIS,
#WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#See the License for the specific language governing permissions and
#limitations under the License.
from frappe.model.document import Document
class CueSheetCues(Docum... | 64 | 64 | 9 | 7 | 56 | haynieresearch/filmcomposer | filmcomposer/rights_management/doctype/cue_sheet_cues/cue_sheet_cues.py | Python | CueSheetCues | CueSheetCues | 20 | 21 | 20 | 20 | ed3f1877a96d5c62c95758ac312192af51e4ad6d | bigcode/the-stack | train |
e22d4ed2334aba6f5c748ef8 | train | class | class UnitTest(unittest.TestCase):
"""Class: UnitTest
Description: Class which is a representation of a unit testing.
Methods:
setUp
test_update_marker
tearDown
"""
def setUp(self):
"""Function: setUp
Description: Initialization for unit testing.
... | class UnitTest(unittest.TestCase):
| """Class: UnitTest
Description: Class which is a representation of a unit testing.
Methods:
setUp
test_update_marker
tearDown
"""
def setUp(self):
"""Function: setUp
Description: Initialization for unit testing.
Arguments:
"""
... | .py.
Usage:
test/integration/check_log/update_marker.py
Arguments:
"""
# Libraries and Global Variables
# Standard
import sys
import os
if sys.version_info < (2, 7):
import unittest2 as unittest
else:
import unittest
# Third-party
# Local
sys.path.append(os.getcwd())
import check_log
imp... | 101 | 102 | 342 | 7 | 94 | mjpernot/check-log | test/integration/check_log/update_marker.py | Python | UnitTest | UnitTest | 37 | 98 | 37 | 38 | 953f663860051244e378c48151dfbc3a0c3c5cf0 | bigcode/the-stack | train |
61e247f2f0894a9222f8836e | train | function | def test_foo(capsys):
with pytest.raises(ZeroDivisionError):
tm.foo(1)
tm.main(1)
cap_out, _ = capsys.readouterr()
assert cap_out == 'ZeroDivisionError\n'
with pytest.raises(ArithmeticError):
tm.foo(2)
tm.main(2)
cap_out, _ = capsys.readouterr()
assert cap_out == 'Arithm... | def test_foo(capsys):
| with pytest.raises(ZeroDivisionError):
tm.foo(1)
tm.main(1)
cap_out, _ = capsys.readouterr()
assert cap_out == 'ZeroDivisionError\n'
with pytest.raises(ArithmeticError):
tm.foo(2)
tm.main(2)
cap_out, _ = capsys.readouterr()
assert cap_out == 'ArithmeticError\n'
with... | import pytest
import module2_11 as tm
def test_foo(capsys):
| 19 | 64 | 136 | 8 | 10 | ivaninkv/python_basics | week2/module1/module2_11_test.py | Python | test_foo | test_foo | 5 | 22 | 5 | 5 | 7ade60c556c46955ad31ab36baa8168324cb28b6 | bigcode/the-stack | train |
2d84640b0a51f92db9ad97b5 | train | function | def bouquet_from_designs(
designs: Iterable[Design], pool: FlowerCounter, demand: FlowerCounter
) -> Optional[Bouquet]:
"""Attempts to create a bouquet from each available design in turn."""
for design in designs:
if all(pool[flower] >= qty for flower, qty in design.required.items()):
un... | def bouquet_from_designs(
designs: Iterable[Design], pool: FlowerCounter, demand: FlowerCounter
) -> Optional[Bouquet]:
| """Attempts to create a bouquet from each available design in turn."""
for design in designs:
if all(pool[flower] >= qty for flower, qty in design.required.items()):
unused = (pool - design.required).elements()
remainder = [flower for flower in unused if flower.size == design.siz... | Counter
from .utils import bouquet_to_string, design_complexity, flower_demand, read_lines
__version__ = "0" # Forever at nil
def bouquet_from_designs(
designs: Iterable[Design], pool: FlowerCounter, demand: FlowerCounter
) -> Optional[Bouquet]:
| 64 | 64 | 154 | 30 | 33 | edelooff/balderdash | balderdash/__init__.py | Python | bouquet_from_designs | bouquet_from_designs | 15 | 28 | 15 | 17 | 8d8a603b83957841b6f78beedc146d34af5254e8 | bigcode/the-stack | train |
e3a8cb4ebb2afea177b43e30 | train | function | def generate_bouquets(
flowers: Iterator[Flower], designs: Iterable[Design], buffer: int = 250
) -> Iterator[Bouquet]:
demand = flower_demand(designs)
pool: FlowerCounter = Counter(islice(flowers, buffer))
try:
while True:
if bouquet := bouquet_from_designs(designs, pool, demand):
... | def generate_bouquets(
flowers: Iterator[Flower], designs: Iterable[Design], buffer: int = 250
) -> Iterator[Bouquet]:
| demand = flower_demand(designs)
pool: FlowerCounter = Counter(islice(flowers, buffer))
try:
while True:
if bouquet := bouquet_from_designs(designs, pool, demand):
under_buffer = max(0, buffer - sum(pool.values()))
pool.update(islice(flowers, under_buffer))... | + Counter(islice(filler, design.additional))
pool -= flowers
return Bouquet(design.name, design.size, flowers)
return None
def generate_bouquets(
flowers: Iterator[Flower], designs: Iterable[Design], buffer: int = 250
) -> Iterator[Bouquet]:
| 64 | 64 | 128 | 33 | 30 | edelooff/balderdash | balderdash/__init__.py | Python | generate_bouquets | generate_bouquets | 31 | 45 | 31 | 33 | f66572e76c5891cb21069ba09d37ae02a2db5d52 | bigcode/the-stack | train |
2463459a225bfaf17a7e5086 | train | function | def select_filler(pool: FlowerCounter, demand: FlowerCounter) -> Iterator[Flower]:
"""Yields Flower least in demand relative to its availability."""
scarcity = {flower: demand[flower] / pool[flower] for flower in pool}
while True:
yield (flower := min(scarcity, key=scarcity.get))
pool[flower... | def select_filler(pool: FlowerCounter, demand: FlowerCounter) -> Iterator[Flower]:
| """Yields Flower least in demand relative to its availability."""
scarcity = {flower: demand[flower] / pool[flower] for flower in pool}
while True:
yield (flower := min(scarcity, key=scarcity.get))
pool[flower] -= 1
try:
scarcity[flower] = demand[flower] / pool[flower]
... | (0, buffer - sum(pool.values()))
pool.update(islice(flowers, under_buffer))
yield bouquet
else:
pool[next(flowers)] += 1
except StopIteration:
return
def select_filler(pool: FlowerCounter, demand: FlowerCounter) -> Iterator[Flower]:
| 64 | 64 | 115 | 19 | 44 | edelooff/balderdash | balderdash/__init__.py | Python | select_filler | select_filler | 48 | 57 | 48 | 48 | 6926db7fe54b54a889ab29bc89c4f5d0eda81278 | bigcode/the-stack | train |
6a943882263e1dd8747438d9 | train | function | def main() -> None:
parser = ArgumentParser()
parser.add_argument(
"infile",
nargs="?",
default="-",
type=FileType("r"),
help="File with design and flower inputs, to use instead of stdin",
)
parser.add_argument(
"--buffer",
default=250,
typ... | def main() -> None:
| parser = ArgumentParser()
parser.add_argument(
"infile",
nargs="?",
default="-",
type=FileType("r"),
help="File with design and flower inputs, to use instead of stdin",
)
parser.add_argument(
"--buffer",
default=250,
type=int,
help=... | yield (flower := min(scarcity, key=scarcity.get))
pool[flower] -= 1
try:
scarcity[flower] = demand[flower] / pool[flower]
except ZeroDivisionError:
del pool[flower], scarcity[flower]
def main() -> None:
| 64 | 64 | 164 | 6 | 58 | edelooff/balderdash | balderdash/__init__.py | Python | main | main | 60 | 81 | 60 | 60 | 0498018dd9d81107f72c496189276a66762d149d | bigcode/the-stack | train |
eab43178d1c9a992ed9fd603 | train | class | @ddt.ddt
class TestSecondaryContactsDocumentPropagation(base.TestACLPropagation):
"""Test Secondary Contacts role permissions propagation
This tests are different from other ACR test in acr_propagation package
because we map document to parent directly (one rank)
e.g Standard -> with document.Reference URL and... | @ddt.ddt
class TestSecondaryContactsDocumentPropagation(base.TestACLPropagation):
| """Test Secondary Contacts role permissions propagation
This tests are different from other ACR test in acr_propagation package
because we map document to parent directly (one rank)
e.g Standard -> with document.Reference URL and check that
Standard's Secondary Contacts can read/create etc document and its c... | # Copyright (C) 2019 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
"""Test Access Control roles Secondary Contacts propagation"""
import ddt
from ggrc.models import all_models
from integration.ggrc.access_control import rbac_factories
from integration.ggrc.access_control.... | 106 | 231 | 773 | 17 | 88 | sfarbotka/ggrc-core | test/integration/ggrc/access_control/acl_propagation/test_one_rank_secondary_contacts_document.py | Python | TestSecondaryContactsDocumentPropagation | TestSecondaryContactsDocumentPropagation | 14 | 126 | 14 | 15 | 242cfb9a3e9f986b00a54c2cef232c272e4896f7 | bigcode/the-stack | train |
8f08b5fad67a21d09e56f8ff | train | function | def create_manual_events(manual_events):
"""Create regex patterns to match manual events against templates."""
result = []
for name, pattern in manual_events:
if not pattern:
# Allow hierarchical events; concat all patterns from events
# starting with 'name'
patte... | def create_manual_events(manual_events):
| """Create regex patterns to match manual events against templates."""
result = []
for name, pattern in manual_events:
if not pattern:
# Allow hierarchical events; concat all patterns from events
# starting with 'name'
pattern = r'|'.join(
p for n, ... | ('ssh.sesion.cmd', r'type=(USER_CMD)'),
('ssh.session.end', r'type=(USER_END)'),
('ssh.logout', r'type=(USER_LOGOUT)'),
('ssh.session', None),
('ssh', None),
]
def create_manual_events(manual_events):
| 64 | 64 | 122 | 8 | 56 | Lab41/magichour | magichour/validate/datagen/eventgen/auditd.py | Python | create_manual_events | create_manual_events | 35 | 50 | 35 | 35 | 0455f50f8110c659a37977194b9c76b98e07fc55 | bigcode/the-stack | train |
4bda1be88c0a517a63bb6d5d | train | function | def event_gen(templates, manual_list=simple_ssh_events):
"""Generate events manually against the automatically discovered templates."""
result = []
manual_events = create_manual_events(manual_list)
for mevent in manual_events:
template_ids = [
t.id for t in templates if mevent.templa... | def event_gen(templates, manual_list=simple_ssh_events):
| """Generate events manually against the automatically discovered templates."""
result = []
manual_events = create_manual_events(manual_list)
for mevent in manual_events:
template_ids = [
t.id for t in templates if mevent.template_regex.search(
t.raw_str)]
if t... | in manual_events if p and n.startswith(name))
mevent = ManualEvent(
id=name,
template_ids=None,
template_regex_pattern=pattern,
template_regex=re.compile(pattern))
result.append(mevent)
return result
def event_gen(templates, manual_list=simple_ssh_eve... | 64 | 64 | 102 | 14 | 49 | Lab41/magichour | magichour/validate/datagen/eventgen/auditd.py | Python | event_gen | event_gen | 53 | 64 | 53 | 53 | 4e80b94eef6bc9279f15b7179501385d3837a7fb | bigcode/the-stack | train |
5ecaac1296cf955c4d19ae40 | train | function | def map_label(label, classes):
mapped_label = np.zeros(label.shape)
for i in range(classes.shape[0]):
mapped_label[label == classes[i]] = i
return mapped_label
| def map_label(label, classes):
| mapped_label = np.zeros(label.shape)
for i in range(classes.shape[0]):
mapped_label[label == classes[i]] = i
return mapped_label
| data['fsl_test_unseen_index'] = list(unseenlabels)
data['fsl_train_unseen_index'] = fsl_train_unseen_index
data['fsl_train_seen_index'] = data['train_seen_index']
# ==============================构造数据集==============================
def map_label(label, classes):
| 63 | 64 | 42 | 7 | 56 | LiangjunFeng/Generative-Any-Shot-Learning | VisualEmbedding/finetune_sem.py | Python | map_label | map_label | 88 | 92 | 88 | 88 | d426f6ddb6b64f36002e387d4215723aba1985af | bigcode/the-stack | train |
7490b4c954a51bc45fecba5e | train | function | def train_model(model, criterion, nclasses, mse, optimizer, scheduler, num_epochs):
for epoch in range(num_epochs):
if epoch in [0, 5, 10, 15, 20, 25, 30, 40, 50, 60, 70, 80, 90, 100]:
data['features'] = extract_feature(model_ft, exact_list=['avgpool'])
savemat(savepath + benchmark +... | def train_model(model, criterion, nclasses, mse, optimizer, scheduler, num_epochs):
| for epoch in range(num_epochs):
if epoch in [0, 5, 10, 15, 20, 25, 30, 40, 50, 60, 70, 80, 90, 100]:
data['features'] = extract_feature(model_ft, exact_list=['avgpool'])
savemat(savepath + benchmark + "/res101_finetune_sem_" + str(epoch) + "epo.mat",
{'features': ... | outputs = []
for name, module in self.submodule._modules.items():
if name == "fc": x = x.view(x.size(0), -1)
x = module(x)
if name in self.extracted_layers:
outputs.append(x)
return outputs
def extract_feature(model, exact_list=['avgpool']):
mod... | 193 | 193 | 646 | 19 | 173 | LiangjunFeng/Generative-Any-Shot-Learning | VisualEmbedding/finetune_sem.py | Python | train_model | train_model | 189 | 248 | 189 | 189 | f39173192d6a62158e92baa931a1dfe30f3c96ad | bigcode/the-stack | train |
6049de6bd78a305e331f0591 | train | class | class FeatureExtractor(nn.Module):
def __init__(self, submodule, extracted_layers):
super(FeatureExtractor, self).__init__()
self.submodule = submodule
self.extracted_layers = extracted_layers
def forward(self, x):
outputs = []
for name, module in self.submodule._modules... | class FeatureExtractor(nn.Module):
| def __init__(self, submodule, extracted_layers):
super(FeatureExtractor, self).__init__()
self.submodule = submodule
self.extracted_layers = extracted_layers
def forward(self, x):
outputs = []
for name, module in self.submodule._modules.items():
if name == "f... | )
all_dataset = dataset(alldata_files, alllabel, alldataatt, data_transforms['val'])
all_loader = DataLoader(all_dataset, batch_size=16, shuffle=False, num_workers=4)
# #==============================ResNet101特征提取==============================
class FeatureExtractor(nn.Module):
| 63 | 64 | 113 | 6 | 57 | LiangjunFeng/Generative-Any-Shot-Learning | VisualEmbedding/finetune_sem.py | Python | FeatureExtractor | FeatureExtractor | 154 | 167 | 154 | 154 | 2d95bee7d66c986b2a141e625f73fdf65657f3af | bigcode/the-stack | train |
c63de9a2286c5af0c5cfffa7 | train | class | class dataset(Dataset):
def __init__(self, data_files, label, att, transform):
super().__init__()
self.data_files = data_files
self.label = label
self.att = att
self.transform = transform
def __getitem__(self, index):
data = Image.open(self.data_files[index])
... | class dataset(Dataset):
| def __init__(self, data_files, label, att, transform):
super().__init__()
self.data_files = data_files
self.label = label
self.att = att
self.transform = transform
def __getitem__(self, index):
data = Image.open(self.data_files[index])
data = self.transfo... | ']]
trainlabel = data['labels'][data['train_seen_index']]
trainatt = att[data['train_seen_index']]
trainlabel = map_label(trainlabel, np.unique(trainlabel))
alldata_files = data['image_files']
alldataatt = att
alllabel = data['labels']
class dataset(Dataset):
| 64 | 64 | 172 | 5 | 59 | LiangjunFeng/Generative-Any-Shot-Learning | VisualEmbedding/finetune_sem.py | Python | dataset | dataset | 105 | 126 | 105 | 105 | abf419f84737105603e7924d36d717f003ad0777 | bigcode/the-stack | train |
9a59c0ad6ed2ec17547bdde8 | train | function | def extract_feature(model, exact_list=['avgpool']):
model.eval()
myexactor = FeatureExtractor(model, exact_list)
feature_list = []
for data in tqdm(all_loader):
inputs, _, _ = data
if torch.cuda.is_available():
inputs = inputs.cuda()
feature = myexactor(inputs)[0]
... | def extract_feature(model, exact_list=['avgpool']):
| model.eval()
myexactor = FeatureExtractor(model, exact_list)
feature_list = []
for data in tqdm(all_loader):
inputs, _, _ = data
if torch.cuda.is_available():
inputs = inputs.cuda()
feature = myexactor(inputs)[0]
feature = feature.view(feature.shape[0], feat... | , module in self.submodule._modules.items():
if name == "fc": x = x.view(x.size(0), -1)
x = module(x)
if name in self.extracted_layers:
outputs.append(x)
return outputs
def extract_feature(model, exact_list=['avgpool']):
| 64 | 64 | 115 | 11 | 52 | LiangjunFeng/Generative-Any-Shot-Learning | VisualEmbedding/finetune_sem.py | Python | extract_feature | extract_feature | 170 | 186 | 170 | 170 | 564837631217b6fa1aee7992c21cbbff6cc80f08 | bigcode/the-stack | train |
b1bc7b04654b0cc22b01e52a | train | function | def get_env_for_runner(build_path, repo_path, result_path, work_path):
binary_path = os.path.join(build_path, 'clickhouse')
odbc_bridge_path = os.path.join(build_path, 'clickhouse-odbc-bridge')
library_bridge_path = os.path.join(build_path, 'clickhouse-library-bridge')
my_env = os.environ.copy()
my... | def get_env_for_runner(build_path, repo_path, result_path, work_path):
| binary_path = os.path.join(build_path, 'clickhouse')
odbc_bridge_path = os.path.join(build_path, 'clickhouse-odbc-bridge')
library_bridge_path = os.path.join(build_path, 'clickhouse-library-bridge')
my_env = os.environ.copy()
my_env["CLICKHOUSE_TESTS_BUILD_PATH"] = build_path
my_env["CLICKHOUSE... | ,
'pull_request': pr_info.number,
'pr_info': {'changed_files' : list(pr_info.changed_files)},
'docker_images_with_versions': docker_images,
'shuffle_test_groups': False,
'use_tmpfs': False,
'disable_net_host': True,
}
def get_env_for_runner(build_path, repo_path, resu... | 79 | 79 | 266 | 17 | 62 | zhangjmruc/ClickHouse | tests/ci/integration_test_check.py | Python | get_env_for_runner | get_env_for_runner | 49 | 66 | 49 | 49 | b42bd2e139226337d558eb5c72faa2984fa98c39 | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.