code stringlengths 281 23.7M |
|---|
def _get_response(text: str, labels, spans: List[Tuple[(str, int, int)]]) -> str:
tokens = text.split()
(start_chars, end_chars) = _get_token_char_maps(tokens, [True for _ in tokens])
spans_by_label = defaultdict(list)
for (label, start, end) in spans:
spans_by_label[label].append(text[start_cha... |
def load_python_plugin(plugin_module_path: str, plugin: str, _type: str) -> types.ModuleType:
_plugin = None
module_name = 'fledge.plugins.{}.{}.{}'.format(_type, plugin, plugin)
try:
spec = importlib.util.spec_from_file_location(module_name, '{}/{}.py'.format(plugin_module_path, plugin))
_p... |
def test_can_run_combined_transitions():
class CampaignMachine(StateMachine):
draft = State(initial=True)
producing = State()
closed = State()
abort = ((draft.to(closed) | producing.to(closed)) | closed.to(closed))
produce = draft.to(producing)
machine = CampaignMachine()... |
def extractWwwWangmamareadCom(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
tagmap = [('Returning from the Immortal World', 'Returning from the Immortal World', 'translated'), ('Master o... |
class OptionNavigationAnnotationsoptionsEvents(Options):
def add(self):
return self._config_get(None)
def add(self, value: Any):
self._config(value, js_type=False)
def afterUpdate(self):
return self._config_get(None)
def afterUpdate(self, value: Any):
self._config(value, ... |
class BuildingMenu():
keys_go_back = ['']
sep_keys = '.'
joker_key = '*'
min_shortcut = 1
def __init__(self, caller=None, obj=None, title='Building menu: {obj}', keys=None, parents=None, persistent=False):
self.caller = caller
self.obj = obj
self.title = title
self.ke... |
def test_pr_378(tmpdir):
wd = tmpdir.strpath
config_path = os.path.join(wd, 'config.ini')
with open(config_path, 'w+') as config_file:
config_file.write((((make_config_snippet('cloud', 'google') + '\n[login/google]\nimage_user=my_username\nimage_user_sudo=root\nimage_sudo=True\nuser_key_name=elastic... |
class VmDefineSerializer(VmBaseSerializer):
uuid = s.CharField(read_only=True)
hostname = s.RegexField('^[A-Za-z0-9][A-Za-z0-9\\.-]+[A-Za-z0-9]$', max_length=128, min_length=4)
alias = s.RegexField('^[A-Za-z0-9][A-Za-z0-9\\.-]+[A-Za-z0-9]$', max_length=24, min_length=4, required=False)
ostype = s.Intege... |
def setup_to_pass():
print(shellexec('yum install -q -y ntp'))
shutil.copy('/etc/ntp.conf', '/etc/ntp.conf.bak')
shellexec("sed -i 's/restrict default.*/restrict default kod nomodify notrap nopeer noquery/' /etc/ntp.conf")
print(shellexec('systemctl enable ntpd'))
print(shellexec('systemctl start nt... |
def main():
arguments = docopt(__doc__)
debug = arguments['--debug']
verbose = arguments['--verbose']
ch = logging.StreamHandler()
ch.setLevel(logging.WARNING)
if verbose:
ch.setLevel(logging.INFO)
if debug:
ch.setLevel(logging.DEBUG)
logger.addHandler(ch)
logger.info... |
def merge_args_and_kwargs(function_abi: ABIFunction, args: Sequence[Any], kwargs: Dict[(str, Any)]) -> Tuple[(Any, ...)]:
if ((len(args) + len(kwargs)) != len(function_abi.get('inputs', []))):
raise TypeError(f"Incorrect argument count. Expected '{len(function_abi['inputs'])}'. Got '{(len(args) + len(kwargs... |
class OptionPlotoptionsPackedbubbleSonificationContexttracksMappingPan(Options):
def mapFunction(self):
return self._config_get(None)
def mapFunction(self, value: Any):
self._config(value, js_type=False)
def mapTo(self):
return self._config_get(None)
def mapTo(self, text: str):
... |
.asyncio
.workspace_host
class TestCreateUserRole():
async def test_unauthorized(self, unauthorized_api_assertions: HTTPXResponseAssertion, test_client_api: test_data: TestData):
user = test_data['users']['regular']
role = test_data['roles']['castles_manager']
response = (await test_client_... |
class InputMediaAudio(InputMedia):
def __init__(self, media, thumbnail=None, caption=None, parse_mode=None, caption_entities=None, duration=None, performer=None, title=None):
super(InputMediaAudio, self).__init__(type='audio', media=media, caption=caption, parse_mode=parse_mode, caption_entities=caption_ent... |
(autouse=True, scope='function')
def create_test_database():
for url in DATABASE_URLS:
database_url = DatabaseURL(url)
if (database_url.scheme in ['mysql', 'mysql+aiomysql', 'mysql+asyncmy']):
url = str(database_url.replace(driver='pymysql'))
elif (database_url.scheme in ['postgr... |
class OptionPlotoptionsAreasplineSonificationDefaultinstrumentoptionsMappingTremolo(Options):
def depth(self) -> 'OptionPlotoptionsAreasplineSonificationDefaultinstrumentoptionsMappingTremoloDepth':
return self._config_sub_data('depth', OptionPlotoptionsAreasplineSonificationDefaultinstrumentoptionsMappingT... |
def wb_command_version():
wb_path = find_workbench()
if (wb_path is None):
raise OSError('wb_command not found. Please check that it is installed.')
wb_help = util.check_output('wb_command')
wb_version = wb_help.split(os.linesep)[0:3]
sep = '{} '.format(os.linesep)
wb_v = sep.join(wb_... |
def is_valid_ip_address(address):
if (address.lower() in ['127.0.0.1', 'localhost', '::1', '::ffff:127.0.0.1']):
return True
elif (address.lower() in ('unknown', '')):
return False
elif (address.count('.') == 3):
if address.startswith('::ffff:'):
address = address[7:]
... |
.skipif(('pandas' not in sys.modules), reason='Pandas is not installed.')
def test_assert_dict_type():
import pandas as pd
class AnotherDataClass(DataClassJsonMixin):
z: int
class Args(DataClassJsonMixin):
x: int
y: typing.Optional[str]
file: FlyteFile
dataset: Struct... |
def get_valid_types(data: dict) -> typing.Tuple[(typing.Set[str], bool)]:
type_strings = data.get('type', [])
if isinstance(type_strings, str):
type_strings = {type_strings}
else:
type_strings = set(type_strings)
if (not type_strings):
type_strings = {'null', 'boolean', 'object',... |
class PyGameFRL():
def get_pos(self, gazepos):
return ((gazepos[0] - self.frlcor[0]), (gazepos[1] - self.frlcor[1]))
def update(self, display, stimscreen, gazepos):
frlpos = self.get_pos(gazepos)
display.fill()
r = (self.size / 2)
h = 1
for y in range(0, r):
... |
class Migration(migrations.Migration):
initial = True
dependencies = [migrations.swappable_dependency(settings.AUTH_USER_MODEL)]
operations = [migrations.CreateModel(name='ActivityLog', fields=[('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('type', models... |
def test_wf_resolving():
x = my_wf(a=3, b='hello')
assert (x == (5, 'helloworld'))
assert (my_wf.location == 'tests.flytekit.unit.core.test_resolver.my_wf')
workflows_tasks = my_wf.get_all_tasks()
assert (len(workflows_tasks) == 2)
srz_t0_spec = get_serializable(OrderedDict(), serialization_sett... |
def bad_hashid_error(email_or_string):
g.log.info('Submission rejected. No form found for this target.')
if request_wants_json():
return jsonerror(400, {'error': 'Invalid email address'})
return (render_template('error.html', title='Check email address', text=('Email address %s is not formatted corr... |
def test_inforec_dense_table():
path = 'data/lis/records/inforec_01.lis'
(f,) = lis.load(path)
wellsite = f.wellsite_data()[0]
assert wellsite.isstructured()
table = wellsite.table(simple=True)
mnem = np.array(['WN ', 'CN ', 'SRVC'], dtype='O')
np.testing.assert_array_equal(table['MNEM'], ... |
class Block(metaclass=ABCMeta):
NAME = ''
ARGUMENT = False
OPTIONS = {}
def __init__(self, length, tracker, block_mgr, config):
self.arg_spec = self.ARGUMENT
self.option_spec = copy.deepcopy(self.OPTIONS)
if ('attrs' in self.option_spec):
raise ValueError("'attrs' is ... |
def test_fetcher_client_set_cache():
fetcher_client = _initial_fetcher_client()
fetcher_client.set_run_cache(key='test_field_name', value='cached data')
assert (fetcher_client.run_cache['test_field_name'] == 'cached data')
assert (fetcher_client.run_cache['not_existing_key'] is None) |
def extractWwwAmazonCom(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
tagmap = [('PRC', 'PRC', 'translated'), ('Loiterous', 'Loiterous', 'oel')]
for (tagname, name, tl_type) in tagma... |
class TestComparePluginFileHeader(ComparePluginTest):
PLUGIN_NAME = 'File_Header'
PLUGIN_CLASS = ComparePlugin
def test_compare(self):
result = self.c_plugin.compare_function([self.fw_one, self.fw_two, self.fw_three])
assert all(((key in result) for key in ['hexdiff', 'ascii', 'offsets'])), ... |
def run_tests(c=None):
logger = logging.getLogger()
hdlr = logging.StreamHandler()
formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
hdlr.setFormatter(formatter)
logger.addHandler(hdlr)
logger.setLevel(logging.DEBUG)
if (not c):
return True
runner = RyuTestRu... |
def _remove_user_from_monitoring_server(dc_name, user_name):
dc = Dc.objects.get_by_name(dc_name)
mon = get_monitoring(dc)
if (not mon.enabled):
logger.info('Monitoring is disabled in DC %s', dc)
return
logger.info('Going to delete user with name %s in zabbix %s for dc %s.', user_name, m... |
class _FeedHandler(logging.Handler):
def __init__(self, capacity):
logging.Handler.__init__(self)
self._records = collections.deque(maxlen=capacity)
def emit(self, record):
global _last_update
_last_update = int(record.created)
self.acquire()
try:
self... |
def return_terms(summary):
list_of_terms = ['variational', 'adversarial', 'GAN', 'entangle', 'information', 'bottleneck', 'representation', 'understanding', 'graph']
terms = []
for term in list_of_terms:
if (term in summary):
terms += [term]
return ','.join((k for k in terms)) |
def get_argnames(func: Callable) -> List[str]:
sig = inspect.signature(func)
args = [param.name for param in sig.parameters.values() if (param.kind not in (inspect.Parameter.VAR_POSITIONAL, inspect.Parameter.VAR_KEYWORD))]
if (args and (args[0] == 'self')):
args = args[1:]
return args |
class Video(JsonDeserializable):
def de_json(cls, json_string):
if (json_string is None):
return None
obj = cls.check_json(json_string)
if (('thumbnail' in obj) and ('file_id' in obj['thumbnail'])):
obj['thumbnail'] = PhotoSize.de_json(obj['thumbnail'])
return... |
class FaucetDscpMatchTest(FaucetUntaggedTest):
IP_DSCP_MATCH = 46
ETH_TYPE = 2048
SRC_MAC = '0e:00:00:00:00:ff'
DST_MAC = '0e:00:00:00:00:02'
REWRITE_MAC = '0f:00:12:23:48:03'
CONFIG_GLOBAL = ('\nvlans:\n 100:\n description: "untagged"\n\nacls:\n 1:\n - rule:\n ip_... |
class TestAPNSConfigEncoder():
.parametrize('data', NON_OBJECT_ARGS)
def test_invalid_apns(self, data):
with pytest.raises(ValueError) as excinfo:
check_encoding(messaging.Message(topic='topic', apns=data))
expected = 'Message.apns must be an instance of APNSConfig class.'
as... |
def test_mysql_connector_build_uri(connection_config_mysql, db: Session):
connector = MySQLConnector(configuration=connection_config_mysql)
s = connection_config_mysql.secrets
port = ((s['port'] and f":{s['port']}") or '')
uri = f"mysql+pymysql://{s['username']}:{s['password']}{s['host']}{port}/{s['dbna... |
.skipif((not has_tensorflow), reason='needs TensorFlow')
def test_tensorflow_wrapper_construction_requires_keras_model():
import tensorflow as tf
keras_model = tf.keras.Sequential([tf.keras.layers.Dense(12, input_shape=(12,))])
assert isinstance(TensorFlowWrapper(keras_model), Model)
with pytest.raises(... |
def test_train_bad_data_too_few_columns():
with tempfile.TemporaryDirectory() as tmpdir:
testdata = os.path.join(tmpdir, 'test_data')
shutil.copytree('./tests/test_data', testdata)
input_file = os.path.join(testdata, 'bad_data_too_few_columns.csv')
operation = 'train'
sys.arg... |
class OptionPlotoptionsTreegraphSonificationDefaultinstrumentoptionsMappingLowpass(Options):
def frequency(self) -> 'OptionPlotoptionsTreegraphSonificationDefaultinstrumentoptionsMappingLowpassFrequency':
return self._config_sub_data('frequency', OptionPlotoptionsTreegraphSonificationDefaultinstrumentoption... |
class CustomPrefetchSkuSerializer(SkuTestSerializer):
class Meta(SkuTestSerializer):
model = test_models.Sku
fields = ('id', 'variant')
expandable_fields = dict(owners=dict(serializer=serializers.SerializerMethodField, id_source=False, prefetch_related=['owners']))
def get_owners(self, o... |
def get_typed_value(type_name, value):
if isinstance(value, AnyValue):
return value
if isinstance(value, RegexValue):
return value
if (isinstance(value, six.text_type) and VARIABLE_SUBSTITUTION_RE.search(value)):
return ENSURE_ACTION_SUBSTITUTION_DEFAULT_INDEX_RE.sub('[[\\1.0.\\2]]',... |
def get_smtp_config():
smtp_encryption = get_settings()['smtp_encryption']
if (smtp_encryption == 'tls'):
smtp_encryption = 'required'
elif (smtp_encryption == 'ssl'):
smtp_encryption = 'ssl'
elif (smtp_encryption == 'tls_optional'):
smtp_encryption = 'optional'
else:
... |
class TestPrivateComputationGameRepository(unittest.TestCase):
('fbpcs.private_computation.repository.private_computation_game.PRIVATE_COMPUTATION_GAME_CONFIG', {'attribution_compute_dev': {'onedocker_package_name': 'private_attribution/compute-dev', 'arguments': [OneDockerArgument(name='aggregators', required=True... |
class Solution():
def maximumBags(self, capacity: List[int], rocks: List[int], additionalRocks: int) -> int:
ret = 0
tt = list(sorted([(c - r) for (c, r) in zip(capacity, rocks)]))
for a in tt:
if (a == 0):
ret += 1
continue
if (additio... |
class OptionPlotoptionsGaugeSonificationTracksMappingNoteduration(Options):
def mapFunction(self):
return self._config_get(None)
def mapFunction(self, value: Any):
self._config(value, js_type=False)
def mapTo(self):
return self._config_get(None)
def mapTo(self, text: str):
... |
class _ItemDelegate(QtGui.QStyledItemDelegate):
def __init__(self, table_view):
QtGui.QStyledItemDelegate.__init__(self, table_view)
self._horizontal_lines = table_view._editor.factory.horizontal_lines
self._vertical_lines = table_view._editor.factory.vertical_lines
def paint(self, paint... |
def get_clamped_value_counts(value_counts: pd.Series, max_categories_incl_other: int) -> pd.Series:
if (len(value_counts) <= max_categories_incl_other):
categories_shown_as_is = len(value_counts)
else:
categories_shown_as_is = (max_categories_incl_other - 1)
clamped_series = pd.Series(value_... |
.parametrize('middleware_attr', ['MIDDLEWARE', 'MIDDLEWARE_CLASSES'])
def test_tracing_middleware_autoinsertion_list(middleware_attr):
settings = mock.Mock(spec=[middleware_attr], **{middleware_attr: ['a', 'b', 'c']})
ElasticAPMConfig.insert_middleware(settings)
middleware_list = getattr(settings, middlewar... |
def response_for_status(form, host, referrer, status):
if (status['code'] == Form.STATUS_EMAIL_SENT):
return email_sent_success(status)
if (status['code'] == Form.STATUS_NO_EMAIL):
return no_email_sent_success(status)
if (status['code'] == Form.STATUS_EMAIL_EMPTY):
return errors.empt... |
class OptMedia(Options):
def controls(self):
return self.get(True)
def controls(self, flag: bool):
self.set(flag)
def loop(self):
return self.get(False)
def loop(self, flag: bool):
self.set(flag)
def preload(self):
return self.get('none')
def preload(self,... |
class OptionPlotoptionsBellcurveSonificationTracksActivewhen(Options):
def crossingDown(self):
return self._config_get(None)
def crossingDown(self, num: float):
self._config(num, js_type=False)
def crossingUp(self):
return self._config_get(None)
def crossingUp(self, num: float):
... |
def extractMiyorftranslatesWordpressCom(item):
(vol, chp, frag, postfix) = extractVolChapterFragmentPostfix(item['title'])
if ((not (chp or vol)) or ('preview' in item['title'].lower())):
return None
tagmap = [('PRC', 'PRC', 'translated'), ('Loiterous', 'Loiterous', 'oel')]
for (tagname, name, t... |
def add_speaker_marker(img: Arr, border_h: int, face_loc: tuple[(int, int, int, int)], speaker: int, alpha: float=0.0):
color = COLORS_RGB[speaker]
(x0, y0, x1, y1) = face_loc
(y0, y1) = ((y0 + border_h), (y1 + border_h))
shapes = np.zeros_like(img, np.uint8)
cv2.rectangle(shapes, (x0, y0), (x1, y1)... |
class ApiTools(commands.Cog):
__version__ = '0.0.3'
__author__ = 'flare'
def format_help_for_context(self, ctx):
pre_processed = super().format_help_for_context(ctx)
return f'''{pre_processed}
Cog Version: {self.__version__}
Author: {self.__author__}'''
def __init__(self, bot):
s... |
class TestReadIdentityValues(EsptoolTestCase):
.quick_test
def test_read_mac(self):
output = self.run_esptool('read_mac')
mac = re.search('[0-9a-f:]{17}', output)
assert (mac is not None)
mac = mac.group(0)
assert (mac != '00:00:00:00:00:00')
assert (mac != 'ff:ff... |
def test_buildPaintVarScaleUniformAroundCenter():
assert _is_var(ot.PaintFormat.PaintVarScaleUniformAroundCenter)
assert _is_uniform_scale(ot.PaintFormat.PaintVarScaleUniformAroundCenter)
assert _is_around_center(ot.PaintFormat.PaintVarScaleUniformAroundCenter)
checkBuildPaintScale(ot.PaintFormat.PaintV... |
def test_operations_with_combinations():
v = [(- 256), (- 64), (- 16), (- 4.75), (- 3.75), (- 3.25), (- 1), (- 0.75), (- 0.125), 0.0, 0.125, 0.75, 1, 1.5, 3.75, 4.0, 8.0, 32, 128]
for i in range(len(v)):
for j in range(len(v)):
(vx, vy) = (v[i], v[j])
x = Fxp(vx)
y = ... |
def load_evm_tools_test(test_case: Dict[(str, str)], fork_name: str) -> None:
test_file = test_case['test_file']
test_key = test_case['test_key']
index = test_case['index']
with open(test_file) as f:
tests = json.load(f)
env = tests[test_key]['env']
env['blockHashes'] = {'0': env['previo... |
def test_combining_qualifiers(alice, bob, my_logic):
def _is_alice(connection, logic):
assert isinstance(connection, ConnectionAPI)
return (connection is alice)
def _is_my_logic(connection, logic):
assert isinstance(logic, LogicAPI)
return (logic is my_logic)
is_alice_and_my_... |
def extract_error_field(exc: Union[(eql.EqlParseError, kql.KqlParseError)]) -> Optional[str]:
lines = exc.source.splitlines()
mod = ((- 1) if (exc.line == len(lines)) else 0)
line = lines[(exc.line + mod)]
start = exc.column
stop = (start + len(exc.caret.strip()))
return line[start:stop] |
def test_replace_database_url_components():
u = DatabaseURL('postgresql://localhost/mydatabase')
assert (u.database == 'mydatabase')
new = u.replace(database=('test_' + u.database))
assert (new.database == 'test_mydatabase')
assert (str(new) == 'postgresql://localhost/test_mydatabase')
assert (u... |
class CheckDockerImageCLIParserTestSuite(unittest.TestCase):
def test_empty_args(self):
empty_args = generate_args(None, None)
status = CheckCLIParser.verify_args(empty_args)
self.assertEqual(status, 1)
def test_both_arguments(self):
args = generate_args('jboss/wildfly', '43a6ca9... |
def extract_stable_baselines_data(env, filename):
(x, y) = ([], [])
with open(filename, 'r') as f:
for l in f:
l = [e.strip() for e in l.split('|')]
if ('ep_reward_mean' in l):
y.append(float(l[2]))
if ('total_timesteps' in l):
x.append... |
_register_make
_set_nxm_headers([ofproto_v1_0.NXM_OF_ARP_SPA, ofproto_v1_0.NXM_OF_ARP_SPA_W])
class MFArpSpa(MFField):
def make(cls, header):
return cls(header, MF_PACK_STRING_BE32)
def put(self, buf, offset, rule):
return self.putm(buf, offset, rule.flow.arp_spa, rule.wc.arp_spa_mask) |
class Wrapper(browser_model.T):
def __init__(self):
self.type_changelist = []
self.file_changelist = []
self.formula_changelist = []
browser_model.T.__init__(self, Test.g_comp)
self.type_changed += self._type_changed
self.file_changed += self._file_changed
sel... |
class MLX90614(I2CSlave):
_ADDRESS = 90
_OBJADDR = 7
_AMBADDR = 6
NUMPLOTS = 1
PLOTNAMES = ['Temp']
name = 'PIR temperature'
def __init__(self):
super().__init__(self._ADDRESS)
self.source = self._OBJADDR
self.name = 'Passive IR temperature sensor'
self.params... |
class HalMountpoint():
def __init__(self, hal, udi):
self.hal = hal
self.udi = udi
def __str__(self):
udis = self.hal.hal.FindDeviceStringMatch('info.parent', self.udi)
for u in udis:
obj = self.hal.bus.get_object('org.freedesktop.Hal', u)
dev = dbus.Inter... |
def register_instrumentation(client) -> None:
def begin_transaction(*args, **kwargs) -> None:
task = kwargs['task']
trace_parent = get_trace_parent(task)
client.begin_transaction('celery', trace_parent=trace_parent)
def end_transaction(task_id, task, *args, **kwargs) -> None:
nam... |
def _update_stride_info(mm_info, a_shapes, b_shapes, bias_shapes=None):
if ((len(a_shapes) == 2) or (a_shapes[0] == 1)):
mm_info.a_batch_stride = '0'
if ((len(b_shapes) == 2) or (b_shapes[0] == 1)):
mm_info.b_batch_stride = '0'
if (bias_shapes is None):
return
if ((len(bias_shape... |
def test_beacon_domains_punycode(punycode_beacon_file):
bconfig = beacon.BeaconConfig.from_file(punycode_beacon_file)
assert (bconfig.domains == ['kci.com'])
assert (bconfig.domains[0].encode('idna') == b'xn--ki-4ia.com')
assert (b'k\xe7i.com' in bconfig.raw_settings['SETTING_DOMAINS']) |
class _FileOpener(object):
def __init__(self, arg, kwargs, stdio, keep_stdio_open):
self.arg = arg
self.kwargs = kwargs
self.stdio = stdio
self.keep_stdio_open = keep_stdio_open
self.validate_permissions()
def validate_permissions(self):
mode = self.kwargs.get('mo... |
class GroupForm(FlaskForm):
name = StringField(_('Group name'), validators=[DataRequired(message=_('Please enter a name for the group.'))])
description = TextAreaField(_('Description'), validators=[Optional()])
admin = BooleanField(_("Is 'Admin' group?"), description=_('With this option the group has access... |
class Sunburst(DC):
chartFnc = 'SunburstChart'
def innerRadius(self, value):
return self.fnc(('innerRadius(%s)' % JsUtils.jsConvertData(value, None)))
def ringSizes(self, js_func):
return self.fnc(('ringSizes(%s)' % js_func))
def equalRingSizes(self):
return self.fnc(('ringSizes(... |
def test_hicConvertFormat_h5_to_homer():
outfile = NamedTemporaryFile(suffix='.homer', delete=False)
outfile.close()
args = '--matrices {} --outFileName {} --inputFormat cool --outputFormat homer '.format(original_matrix_cool_chr4, outfile.name).split()
compute(hicConvertFormat.main, args, 5)
test =... |
class _DropEventFilter(QtCore.QObject):
def eventFilter(self, source, event):
typ = event.type()
if (typ == QtCore.QEvent.Type.Drop):
self.dropEvent(event)
elif (typ == QtCore.QEvent.Type.DragEnter):
self.dragEnterEvent(event)
return super().eventFilter(source... |
class ShutterLockLever():
def __init__(self, exposure_control_system=None):
self.exposure_control_system = exposure_control_system
self.blocks = False
def activate(self):
if (not self.exposure_control_system):
return
self.blocks = True
def deactivate(self):
... |
def get_company_contributors_repository_commits(df: DataFrame, author_name_field: str, author_email_field: str, repo_name_field: str, language_field: str, license_field: str, company_field: str, commits_id_field: str, datetime_field: str, day: date, result_field: str='Commits') -> DataFrame:
return df.select(f.col(... |
def coordinates2position(coordinates, surface_size=None):
if (surface_size is None):
surface_size = _internals.active_exp.screen.surface.get_size()
rtn = [(coordinates[0] - (surface_size[0] // 2)), ((- coordinates[1]) + (surface_size[1] // 2))]
if ((surface_size[0] % 2) == 0):
rtn[0] += 1
... |
class TrieNodeRequestTracker():
def __init__(self) -> None:
self._trie_fog = fog.HexaryTrieFog()
self._active_prefixes: Set[Nibbles] = set()
self._node_frontier_cache = fog.TrieFrontierCache()
def mark_for_review(self, prefix: Nibbles) -> None:
self._active_prefixes.remove(prefix... |
class SchemaItem(BaseModel):
kw: str
argc_min: NonNegativeInt = 1
argc_max: Optional[NonNegativeInt] = 1
type_map: List[Union[(SchemaItemType, EnumType, None)]] = []
required_children: List[str] = []
deprecation_info: Optional[DeprecationInfo] = None
join_after: Optional[PositiveInt] = None
... |
class OptionPlotoptionsTreegraphSonificationTracksMappingVolume(Options):
def mapFunction(self):
return self._config_get(None)
def mapFunction(self, value: Any):
self._config(value, js_type=False)
def mapTo(self):
return self._config_get(None)
def mapTo(self, text: str):
... |
def hdates_from_date(date, start_year, end_year):
if (not str(start_year).isdigit()):
raise ValueError(f'start_year must be an int: {start_year}')
if (not str(end_year).isdigit()):
raise ValueError(f'end_year must be an int: {end_year}')
start_year = int(start_year)
end_year = int(end_ye... |
class TestOFPGroupStats(unittest.TestCase):
length = (ofproto.OFP_GROUP_STATS_SIZE + ofproto.OFP_BUCKET_COUNTER_SIZE)
group_id = 6606
ref_count = 2102
packet_count =
byte_count =
buck_packet_count =
buck_byte_count =
bucket_counters = [OFPBucketCounter(buck_packet_count, buck_byte_co... |
class PythonBackedTokenizer():
def __init__(self, model_identifier):
self.bos_token_id = 50256
self.eos_token_id = 50256
self._vocab = None
self.model_identifier = model_identifier
def is_available(model_identifier):
try:
import gpt3_tokenizer
open... |
class TestPerformanceMetrics():
def test_performance_metrics(self, ts_short, backend):
m = Prophet(stan_backend=backend)
m.fit(ts_short)
df_cv = diagnostics.cross_validation(m, horizon='4 days', period='10 days', initial='90 days')
df_none = diagnostics.performance_metrics(df_cv, rol... |
class ClipboardHandlerBase(abc.ABC):
def __init__(self) -> None:
self.is_compatible = self._is_compatible()
def copy(self, text: str) -> bool:
if (not self.is_compatible):
logger.error('%s.copy() called on incompatible system!', getattr(self, '__name__', ''))
return False... |
def create_auto_crop_writer():
import os
import nuke
nodes = nuke.selectedNodes()
[node.setSelected(False) for node in nodes]
write_nodes = []
for node in nodes:
write_node = nuke.createNode('Write')
file_path = node['file'].value()
(filename_with_number_seq, ext) = os.pa... |
def get_context_string(context, id_width, ctx, ascii_=False):
hash_str = cstr('#', clr('id'))
if isinstance(hash_str, ColoredStr):
ansi_offset = hash_str.lenesc
else:
ansi_offset = 0
path = utils.get_relative_path(context, ctx['path'])
string = '{hash:>{width}} | {path} ({nbr})'.form... |
class WithdrawalAPI(ABC):
def index(self) -> int:
...
def validator_index(self) -> int:
...
def address(self) -> Address:
...
def amount(self) -> int:
...
def hash(self) -> Hash32:
...
def validate(self) -> None:
...
def encode(self) -> bytes:
... |
def test_loop_broad_peak():
outfile = NamedTemporaryFile(suffix='out', delete=True)
outfile.close()
args = '--data {} --validationData {} --validationType {} --method {} --outFileName {} -r {} --chrPrefixProtein {} '.format((ROOT + 'loops_1.bedgraph'), (ROOT + 'GSM733752_hg19_ctcf_GM12878.broadPeak'), 'bed'... |
def _create_taxed_tickets(db, tax_included=True, discount_code=None):
tax = TaxSubFactory(name='GST', rate=18.0, is_tax_included_in_price=tax_included)
tickets = _create_tickets([123.5, 456.3], event=tax.event)
tickets += [TicketSubFactory(type='donation', event=tax.event, min_price=500.0, max_price=1000.0)... |
('sys.argv', ['flakehell'])
def test_exclude_file(capsys, tmp_path: Path):
(tmp_path / 'checked.py').write_text('import sys\n')
(tmp_path / 'ignored').mkdir()
((tmp_path / 'ignored') / 'first.py').write_text('import sys\n')
((tmp_path / 'ignored') / 'second.py').write_text('invalid syntax!')
with ch... |
class Solution(object):
def middleNode(self, head):
length = 0
curr = head
while (curr is not None):
curr = curr.next
length += 1
mid = (length / 2)
curr = head
while (mid > 0):
curr = curr.next
mid -= 1
return c... |
def get_linked_deployments(deployments: Dict[(str, Any)]) -> Dict[(str, Any)]:
linked_deployments = {dep: data for (dep, data) in deployments.items() if get_in(('runtimeBytecode', 'linkDependencies'), data)}
for (deployment, data) in linked_deployments.items():
if any(((link_dep['value'] == deployment) ... |
def test_correct_number_of_rows_are_generated():
df = gen.generate(props={'region': gen.choice(data=['EMEA', 'LATAM', 'NAM', 'APAC'], weights=[0.1, 0.1, 0.3, 0.5]), 'sic_range': gen.sic_range(), 'sic': gen.sic_industry(sic_range_field='sic_range'), 'country': gen.country_codes(region_field='region'), 'client_name':... |
def test_unicode_addresses(mailer):
msg = mailer.mail(subject='subject', sender=u'AUO <>', recipients=[u'A <>', u'U <>'], cc=[u'O <>'])
msg_as_string = str(msg)
a1 = sanitize_address(u'A <>')
a2 = sanitize_address(u'U <>')
h1_a = Header(('To: %s, %s' % (a1, a2)))
h1_b = Header(('To: %s, %s' % ... |
.asyncio
class TestTasksCleanup():
async def test_cleanup(self, main_session_manager, workspace_session_manager, send_task_mock: MagicMock):
cleanup = CleanupTask(main_session_manager, workspace_session_manager, send_task=send_task_mock)
(await cleanup.run())
send_task_mock.assert_called() |
def test_from_yaml_schema(container: containers.DynamicContainer, tmp_path: pathlib.Path):
schema_path = (tmp_path / 'schema.yml')
with open(schema_path, 'w') as file:
file.write('\n version: "1"\n container:\n provider1:\n provider: Factory\n provides: list\... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.