query
stringlengths
9
9.05k
document
stringlengths
10
222k
negatives
listlengths
19
20
metadata
dict
Parse any object other than a HyExpression beginning with a HySymbol equal to one of the disallowed_heads.
def notpexpr(*disallowed_heads): return some(lambda x: not ( isinstance(x, HyExpression) and x and isinstance(x[0], HySymbol) and x[0] in disallowed_heads))
[ "def visit_TheoryUnparsedTerm(self, x):\n return self.visit(parse_raw_formula(x))", "def test_missing_single_token(self):\n self.helper_test_evaluate_raises(\n 'A or (B and (C and not D))',\n expected_exc_type=MissingSymbolError,\n A=0,\n B=1,\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Parse `parser` several times (`lo` to `hi`) in a row. `hi` can be float('inf'). The result is a list no matter the number of instances.
def times(lo, hi, parser): @Parser def f(tokens, s): result = [] for _ in range(lo): (v, s) = parser.run(tokens, s) result.append(v) end = s.max try: for _ in (repeat(1) if isinf(hi) else range(hi - lo)): (v, s) = parser.run(tok...
[ "def rep(parser: Parser, times: int) -> Parser:\n return Sequence(*([parser] * times))", "def list_of(\n parser: Callable[[str, Mapping[str, str]], _T],\n *,\n sep: Optional[str] = None,\n terminal: bool = False,\n) -> Callable[[str, Mapping[str, str]], List[_T]]:\n\n def _parser(string: str, at...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Matches the given parser and produces a named tuple `(Tag tag value)` with `tag` set to the given tag name and `value` set to the parser's value.
def tag(tag_name, parser): return parser >> (lambda x: Tag(tag_name, x))
[ "def tag_value(tag_name: Any, elem: Widget) -> Widget:\n t, v = yield from elem\n return t, (tag_name, v)", "def value_by_tag(self, tag = \"\"):\n if tag == \"\":\n return None\n ante = ('<' , tag, '>')\n post = ('</', tag, '>')\n anteStr = ''.join(ante)\n postStr = ''.join(post)\n in...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Read last build timestamp from the log file
def last_build_processed_timestamp(log_file): # Get last build processed timestamp last_timestamp = 0 with open(log_file, "r") as process_file: if os.path.getsize(process_file.name) > 0: last_timestamp = process_file.readline().strip() return last_timestamp
[ "def GetBuildDate(build_filename):\n try:\n with open(build_filename) as f:\n return float(f.readline())\n except (IOError, ValueError):\n return 0.0", "def read_last_line_in_data_log():\n timestamp = datetime.datetime.utcnow().strftime(\"%Y%m%d\")\n log_file_path = r'C:/Users/kimdu/Documents/p...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generates plots for all videos in a directory
def generate_plots(path): videos = glob(path + '/*.mkv') print(path, len(videos), videos) if len(videos) == 0: return else: videos = videos[0] metadata_list = glob(path + '/metadata.txt') #print(path, len(metadata_list), metadata_list) if len(metadata_list) == 0: r...
[ "def main():\n\tfor f in os.listdir():\n\t\tif f.endswith(\".mp4\"):\n\t\t\tmake_images(f)\n\t\t\t#plot_changes(f) # Uncomment if you want to create plots of changes in-between frames", "def plot_all(motion,name_dir,save_fig,show,scatter,norm,extension):\n stg = motion + '.' + extension\n list_dir = os.list...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create `nb_existing` + `nb_new` lines in the transmittal.
def create_lines(self, nb_existing=1, nb_new=1, **kwargs): doc = DocumentFactory( metadata_factory_class=ContractorDeliverableFactory, revision_factory_class=ContractorDeliverableRevisionFactory, category=self.category) rev = doc.get_latest_revision() metadata...
[ "def addline(self, newline):\r\n self.Nline = self.Nline + 1\r\n self.PROG = self.PROG + ('N%02i ' % self.Nline) + newline + '\\n'", "def add_lines_to_buffer(self, n):\n for x in range(n):\n self.add_line_to_buffer()", "def nitems_written(self, *args, **kwargs):\n return _...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Non contractor cannot ack receipt of transmittals.
def test_non_contractor_acks_receipt(self): res = self.client.post(self.url) self.assertEqual(res.status_code, 403)
[ "def _send_ack(self):\n ack_packet = packet.Packet.from_data(\n 0,\n self.dest_addr,\n self.own_addr,\n ack=self._next_expected_seqnum\n )\n self._schedule_send_out_of_order(ack_packet)", "def ack_required(self):\n v = self[22]\n v = v...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Make a prediction with the given input. The prediction process consists of the input tensor transferring to the model device, forward pass of the nn_module in eval mode and application of the prediction_transform to the raw prediction output.
def predict(self, input): self._check_predict_ready() with torch.no_grad(): self.eval() input = deep_to(input, self.device) prediction = self.nn_module(input) prediction = self.prediction_transform(prediction) return prediction
[ "def predict(self, input_seq, pred_y, adapt):\n inputs = input_seq[:][:]\n cur_predict = []\n \n seq = torch.FloatTensor(inputs[-self.sequence_length:]).view(1, self.sequence_length, self.input_size).to(self.device)\n if(adapt and not isinstance(self.pre_x, int)):\n err...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set the nn_module into train mode.
def train(self, mode: bool = True): if self.nn_module.training != mode: self.nn_module.train(mode)
[ "def _set_train_mode(self):\n pass", "def train(self, mode: bool = True) -> Module:\n self.training = mode\n return self", "def set_train_mode(training, mnet, hnet, hhnet, dis):\n for net in [mnet, hnet, hhnet, dis]:\n if net is not None:\n if training:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generate an empty configuration file with only a single empty Site policy
def create_empty_config_file(): config = { "config": [ { "site": { "username": "", "name": "", "ip_address": "", "password": "", "local": "", ...
[ "def generate_all_default_but_one():\n CONFIG_SETS = {\n 'no_AEC': {'-aec': 0,},\n 'no_AGC': {'-agc': 0,},\n 'no_HP_filter': {'-hpf': 0,},\n 'no_level_estimator': {'-le': 0,},\n 'no_noise_suppressor': {'-ns': 0,},\n 'no_transient_suppressor': {'-ts': 0,},\n 'no_vad': {'-vad': 0,}...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set up the remote site. Meant to be overridden by inheriting classes
def setup_remote_site(self): raise NotImplementedError
[ "def setup_local_site(self):\n raise NotImplementedError", "def setUp(self):\n self.setup_remote_site()\n self.setup_local_site()", "def setUp(self):\n super().setUp()\n self.site = self.get_site()\n self.mainpage = self.get_mainpage()", "async def setup(self):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set up the local site. Meant to be overridden by inheriting classes
def setup_local_site(self): raise NotImplementedError
[ "def setUp(self):\n super().setUp()\n self.site = self.get_site()\n self.mainpage = self.get_mainpage()", "def setUp(self):\n self.setup_remote_site()\n self.setup_local_site()", "def setup_remote_site(self):\n raise NotImplementedError", "def setup(self):\n se...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set up the test case. Setup the remote and local site.
def setUp(self): self.setup_remote_site() self.setup_local_site()
[ "def setUp(self):\n self.weblab_instance_runner = TestWeblabInstanceRunner()\n self.weblab_instance_runner.start()\n self.weblab_instance_runner.wait_until_ready(10)\n self.core_server_url = self.weblab_instance_runner.core_server_url", "def setup_remote_site(self):\n raise NotI...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tear down the test case. Tear down the remote and local site.
def tearDown(self): self.teardown_local_site() self.teardown_remote_site() time.sleep(2)
[ "def teardown_test(self):\n self.log.info('Tearing down the test case')\n self.iperf_server.stop()\n self.access_point.bridge.teardown(self.brconfigs)\n self.access_point.close()\n wputils.reset_host_interface(self.pkt_sender.interface)\n self.mon.usb('on')", "def teardow...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generate a basic configuration containing the local and remote site policies. Actual site credentials are set in global variables imported from multisite_test_credentials
def create_site_config(): config = { "config": [ { "site": { "username": "%s" % SITE1_LOGIN, "name": "Site1", "ip_address": "%s" % SITE1_IPADDR, "password": "%s" % SITE...
[ "def create_conf():\n print 'Creating %s' % silverlining_conf\n username = raw_input('Your service-provider username: ')\n api_key = raw_input('Your service-provider API key: ')\n for path in ['id_rsa.pub', 'id_dsa.pub']:\n pubkey_path = os.path.join(os.environ['HOME'], '.ssh', path)\n if ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Verify that the remote site has the entry
def verify_remote_site_has_entry(self, mac, ip, tenant_name, l3out_name, remote_epg_name): site2 = Session(SITE2_URL, SITE2_LOGIN, SITE2_PASSWORD) resp = site2.login() self.assertTrue(resp.ok) query = ('/api/mo/uni/tn-%s/out-%s/instP-%s.json?query-target=children' % (tenant_name, ...
[ "def hash_exists_remotely(self):\n try:\n self.lookup_by_hash()\n except requests.exceptions.HTTPError:\n return False\n return True", "def check(url):\n r = requests.get(url)\n return r.status_code == requests.codes.ok", "def test_source_host_is_availabl...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Verify that the remote site has the entry and provides the specfied contract
def verify_remote_site_has_entry_with_provided_contract(self, mac, ip, tenant_name, l3out_name, remote_epg_name, contract_name): site2 = Session(SITE2_URL, SITE2_LOGIN, SITE2_PASSWORD) resp = site2.login() self.assertTrue(resp.ok) query = '/api/mo/uni/tn-%s/out-%s.json?query-target=subt...
[ "def check_contract(self, context, value, silent): # @UnusedVariable", "def verify_remote_site_has_entry(self, mac, ip, tenant_name, l3out_name, remote_epg_name):\n site2 = Session(SITE2_URL, SITE2_LOGIN, SITE2_PASSWORD)\n resp = site2.login()\n self.assertTrue(resp.ok)\n\n query = ('...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Verify that the remote site has the policy
def verify_remote_site_has_policy(self, tenant_name, l3out_name, instp_name): site2 = Session(SITE2_URL, SITE2_LOGIN, SITE2_PASSWORD) resp = site2.login() self.assertTrue(resp.ok) query = ('/api/mo/uni/tn-%s/out-%s/instP-%s.json' % (tenant_name, l3out_name, instp_name)) resp = s...
[ "def test_metapolicy_none_empty_domains(self):\n policy = policies.Policy('media.example.com', 'api.example.com')\n policy.metapolicy(policies.SITE_CONTROL_NONE)\n self.assertEqual(len(\n policy.xml_dom.getElementsByTagName('allow-access-from')), 0)", "def test_metapolicy(self):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get a mock of the command line arguments
def get_args(): args = mock.Mock() args.debug = None args.generateconfig = None args.config = 'doesntmatter' return args
[ "def mock_get_args():\n\n return MagicMock()", "def GetCommandLineArgs():\n pass", "def testCommandLineArguments(self):\n manager.ArgumentHelperManager.RegisterHelpers(\n [TestHelper, AnotherTestHelper])\n\n arg_parser = argparse.ArgumentParser(conflict_handler=u'resolve')\n manager.Argument...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test add multiple endpoints
def test_basic_add_multiple_endpoint(self): mac1, ip1 = self.setup_with_endpoint() mac2 = '00:11:22:33:33:35' ip2 = '3.4.3.6' self.add_endpoint(mac2, ip2, 'intersite-testsuite', 'app', 'epg') time.sleep(2) self.assertTrue(self.verify_remote_site_has_entry(mac1, ip1, 'int...
[ "def test_basic_add_endpoint(self):\n args = self.get_args()\n config = self.create_config_file()\n self.write_config_file(config, args)\n collector = execute_tool(args, test_mode=True)\n time.sleep(2)\n\n config['config'].append(self.create_export_policy())\n self.w...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test basic MAC move
def test_basic_mac_move(self): args = self.get_args() self.write_config_file(self.create_config_file(), args) execute_tool(args, test_mode=True) ip = '3.4.3.4' mac = '00:11:22:33:33:33' self.assertFalse(self.verify_remote_site_has_entry(mac, ip, 'intersite-testsuite', ...
[ "def test_mac_randomization_wep(self):\n self.connect_to_network_and_verify_mac_randomization(self.wep_2g)", "def test_acl_mac(self):\n\n # Basic iACL testing with source MAC\n pkts = self.create_stream(self.pg0, self.pg2, self.pg_if_packet_sizes)\n self.pg0.add_stream(pkts)\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test remove one of multiple endpoints
def test_basic_remove_one_of_multiple_endpoint(self): args = self.get_args() config = self.create_config_file() self.write_config_file(config, args) execute_tool(args, test_mode=True) time.sleep(2) mac1 = '00:11:22:33:33:34' ip1 = '3.4.3.5' self.add_endpo...
[ "def test_basic_remove_one_of_multiple_endpoint(self):\n args = self.get_args()\n config = self.create_config_file()\n self.write_config_file(config, args)\n execute_tool(args, test_mode=True)\n\n time.sleep(2)\n mac1 = '00:11:22:33:33:34'\n ip1 = '3.4.3.5'\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test add the endpoint
def test_basic_add_endpoint(self): args = self.get_args() config = self.create_config_file() self.write_config_file(config, args) execute_tool(args, test_mode=True) time.sleep(2) mac = '00:11:22:33:33:33' ip = '3.4.3.4' self.assertTrue(self.verify_remote_...
[ "def test_basic_add_endpoint(self):\n args = self.get_args()\n config = self.create_config_file()\n self.write_config_file(config, args)\n collector = execute_tool(args, test_mode=True)\n time.sleep(2)\n\n config['config'].append(self.create_export_policy())\n self.w...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test remove the endpoint
def test_basic_remove_endpoint(self): args = self.get_args() config = self.create_config_file() self.write_config_file(config, args) execute_tool(args, test_mode=True) time.sleep(2) mac = '00:11:22:33:33:33' ip = '3.4.3.4' self.assertTrue(self.verify_rem...
[ "def test_basic_remove_endpoint(self):\n mac, ip = self.setup_with_endpoint()\n time.sleep(2)\n\n self.assertTrue(self.verify_remote_site_has_entry(mac, ip, 'intersite-testsuite', 'l3out',\n 'intersite-testsuite-app-epg1'))\n self....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create the export policy
def create_export_policy(): config = { "export": { "tenant": "intersite-testsuite", "app": "app", "epg": "epg", "remote_epg": "intersite-testsuite-app-epg", "remote_sites": [ { ...
[ "def create_export_policy(l3out_name):\n export_policy = {\n \"export\": {\n \"tenant\": \"intersite-testsuite\",\n \"app\": \"app\",\n \"epg\": \"epg\",\n \"remote_epg\": \"intersite-testsuite-app-epg\",\n \"remote_sites\"...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test adding the endpoint
def test_basic_add_endpoint(self): args = self.get_args() config = self.create_config_file() self.write_config_file(config, args) collector = execute_tool(args, test_mode=True) time.sleep(2) config['config'].append(self.create_export_policy()) self.write_config_f...
[ "def test_basic_add_endpoint(self):\n args = self.get_args()\n config = self.create_config_file()\n self.write_config_file(config, args)\n execute_tool(args, test_mode=True)\n time.sleep(2)\n\n mac = '00:11:22:33:33:33'\n ip = '3.4.3.4'\n self.assertTrue(self....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a configuration with different EPGs
def create_diff_epg_config_file(self): config = self.create_site_config() export_policy = { "export": { "tenant": "intersite-testsuite", "app": "app", "epg": "epg", "remote_epg": "intersite-testsuite-app-epg2", "...
[ "def create_configuration(EngineType=None, EngineVersion=None, Name=None, Tags=None):\n pass", "def create_configuration(self, **kwargs):", "def create_config(self) -> None:\n pass", "def _gen_config():\n cfg = {\"frontends\": {}, \"backends\": {}}\n for machine in Machine.objects(\n mo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test changing the policy name
def test_basic_change_policy_name(self): args = self.get_args() config = self.create_config_file() mac = '00:11:22:33:33:33' ip = '3.4.3.4' self.write_config_file(config, args) collector = execute_tool(args, test_mode=True) time.sleep(4) self.assertTrue(se...
[ "def test_get_policy_by_name(self):\n pass", "def policy_name(self, policy_name):\n self._policy_name = policy_name", "def test_replace_namespaced_policy(self):\n pass", "def test_add_policy(self):\n pass", "def policy_name(self, policy_name):\n\n self._policy_name = polic...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test removing one of multiple endpoints
def test_basic_remove_one_of_multiple_endpoint(self): args = self.get_args() config = self.create_config_file() self.write_config_file(config, args) execute_tool(args, test_mode=True) time.sleep(2) mac1 = '00:11:22:33:33:34' ip1 = '3.4.3.5' self.add_endpo...
[ "def test_basic_remove_one_of_multiple_endpoint(self):\n args = self.get_args()\n config = self.create_config_file()\n self.write_config_file(config, args)\n execute_tool(args, test_mode=True)\n\n time.sleep(2)\n mac1 = '00:11:22:33:33:34'\n ip1 = '3.4.3.5'\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test removing the endpoint
def test_basic_remove_endpoint(self): mac, ip = self.setup_with_endpoint() time.sleep(2) self.assertTrue(self.verify_remote_site_has_entry(mac, ip, 'intersite-testsuite', 'l3out', 'intersite-testsuite-app-epg1')) self.remove_endp...
[ "def test_basic_remove_endpoint(self):\n args = self.get_args()\n config = self.create_config_file()\n self.write_config_file(config, args)\n execute_tool(args, test_mode=True)\n\n time.sleep(2)\n mac = '00:11:22:33:33:33'\n ip = '3.4.3.4'\n\n self.assertTrue(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create the export policy
def create_export_policy(l3out_name): export_policy = { "export": { "tenant": "intersite-testsuite", "app": "app", "epg": "epg", "remote_epg": "intersite-testsuite-app-epg", "remote_sites": [ { ...
[ "def create_export_policy():\n config = {\n \"export\": {\n \"tenant\": \"intersite-testsuite\",\n \"app\": \"app\",\n \"epg\": \"epg\",\n \"remote_epg\": \"intersite-testsuite-app-epg\",\n \"remote_sites\": [\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test adding endpoint with multiple OutsideL3 interfaces
def test_basic_add_endpoint_multiple_l3out(self): args = self.get_args() config = self.create_config_file('l3out1') for policy in config['config']: if 'export' in policy: for site_policy in policy['export']['remote_sites']: interface_policy = {"l3o...
[ "def test_basic_add_multiple_endpoint(self):\n mac1, ip1 = self.setup_with_endpoint()\n mac2 = '00:11:22:33:33:35'\n ip2 = '3.4.3.6'\n self.add_endpoint(mac2, ip2, 'intersite-testsuite', 'app', 'epg')\n time.sleep(2)\n\n self.assertTrue(self.verify_remote_site_has_entry(mac...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add a remote entry
def add_remote_duplicate_entry(self, ip): site2 = Session(SITE2_URL, SITE2_LOGIN, SITE2_PASSWORD) resp = site2.login() self.assertTrue(resp.ok) tenant = Tenant('intersite-testsuite-remote') l3out = OutsideL3('l3out', tenant) other_epg = OutsideEPG('other', l3out) ...
[ "def add(self, name: str, address: str) -> RemoteInfo:\n self.__verify_repo_initialized()\n succ = heads.add_remote(self._env.branchenv, name=name, address=address)\n if succ is False:\n raise ValueError(f'No-Op: Remote named: {name} already exists.')\n return RemoteInfo(name=...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test a basic duplicate entry scenario. An existing entry exists on the remote site but on a different OutsideEPG on the same OutsideL3.
def test_basic_duplicate(self): args = self.get_args() config = self.create_config_file() self.write_config_file(config, args) execute_tool(args, test_mode=True) mac = '00:11:22:33:33:33' ip = '3.4.3.4' self.assertFalse(self.verify_remote_site_has_entry(mac, ip, ...
[ "def test_to_create__duplicate_entry(self):\n tester = self.app.test_client(self)\n res = tester.post('/API/v1/entries', data=TestBase.duplicate_entry,\n headers=self.access_header,\n content_type='application/json')\n self.assertEqual(res.statu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test a basic multiple duplicate entry scenario.
def test_basic_multiple_duplicate(self): args = self.get_args() config = self.create_config_file() self.write_config_file(config, args) execute_tool(args, test_mode=True) for i in range(0, 5): mac = '00:11:22:33:33:3' + str(i) ip = '3.4.3.' + str(i) ...
[ "def test_duplicate_entries(self):", "def test_to_create__duplicate_entry(self):\n tester = self.app.test_client(self)\n res = tester.post('/API/v1/entries', data=TestBase.duplicate_entry,\n headers=self.access_header,\n content_type='application/jso...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test a basic duplicate entry scenario. An existing entry exists on the remote site but on a different OutsideEPG on the same OutsideL3.
def test_basic_duplicate(self): args = self.get_args() config = self.create_config_file() self.write_config_file(config, args) execute_tool(args, test_mode=True) mac = '00:11:22:33:33:33' ip = '3.4.3.4' self.assertFalse(self.verify_remote_site_has_entry(mac, ip, ...
[ "def test_to_create__duplicate_entry(self):\n tester = self.app.test_client(self)\n res = tester.post('/API/v1/entries', data=TestBase.duplicate_entry,\n headers=self.access_header,\n content_type='application/json')\n self.assertEqual(res.statu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test basic deletion of a stale entry on tool startup
def test_basic_deletion(self): args = self.get_args() config_filename = 'testsuite_cfg.json' args.config = config_filename config = self.create_config_file() config_file = open(config_filename, 'w') config_file.write(str(json.dumps(config))) config_file.close() ...
[ "def test_delete_run(self):\n pass", "async def test_unload_entry(hass: HomeAssistant, loaded_entry: MockConfigEntry) -> None:\n\n assert loaded_entry.state == config_entries.ConfigEntryState.LOADED\n assert await hass.config_entries.async_unload(loaded_entry.entry_id)\n await hass.async_block_til...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generates start and end points for a transect
def get_start_end_points(path, transect): transect_array = np.genfromtxt(path + 'tran_sim_pts.csv', delimiter=",") start_point = transect_array[2 * transect, :] end_point = transect_array[2 * transect + 1, :] # force start points to be west of end points if start_point[0] > end_point[0]...
[ "def get_transect(self, transect):\n obj = self.get_vertical_cross_section(lon0=transect.lon0,\n lat0=transect.lat0,\n lon1=transect.lon1,\n lat1=transect.lat1,\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Hack for overwriting the TLD on all user and expr records to server_name THIS WILL BREAK things when we support multiple domains
def update_domain(): for e in Expr.search() + User.search(): e.set_tld(config.server_name)
[ "def user_domain(tbac):\n if tbac:\n return 'tbacdomain'\n return 'system'", "def add_domain(user):\n if \"@\" not in user:\n user = user + \"@linaro.org\"\n return user", "def update_domain_nameservers(DomainName=None, FIAuthKey=None, Nameservers=None):\n pass", "def user_domain_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test adding refpix around an array
def test_add_refpix(): data = np.ones((10, 10)) refpix = (2, 3, 4, 5) new_array = bpd.add_refpix(data, refpix) yd, xd = new_array.shape print, xd, yd assert yd == 19 assert xd == 15 assert np.all(new_array[0:5, 5] == np.array([0, 0, 0, 0, 1])) assert np.all(new_array[13:, 5] == np....
[ "def perturb_image(img: np.ndarray) -> np.ndarray:\r\n img = img.copy()\r\n for bit_fault in np.nditer(bit_faults, flags=[\"refs_ok\"]):\r\n item = bit_fault.item()\r\n\r\n img[item.x, item.y, item.rgb] = item.bit_action.call(\r\n img[item.x, item.y, item.rgb], ite...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test the translation of a bad pixel list into flags
def test_apply_flags(): true_value = dqflags.pixel['HOT'] + dqflags.pixel['DO_NOT_USE'] print(true_value) badmap = np.zeros((10, 10), dtype=np.int) true_map = np.zeros((10, 10), dtype=np.uint32) for i in range(10): badmap[i, i] = 1 true_map[i, i] = true_value print(true_map)...
[ "def test_bad_pixels(self) :\n\n # check channel 7\n bt = self.get_ch(7)\n bad = bt.quality.get_pixels_from_condition('NO_VALUE')\n self._mask_out_pixels(bad, 'MISSING_CH7')\n bad = bt.quality.get_pixels_from_condition('OUT_OF_RANGE')\n self._mask_out_pixels(bad, 'SAT_CH7')...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test the combination of bad pixel maps. Simply bitwise_or combination of input maps
def test_combine_bad_pixel_types(): satval = dqflags.pixel['SATURATED'] sat_map = np.zeros((5, 5), dtype=np.uint32) sat_map[0, 0] = satval rcval = dqflags.pixel['RC'] rc_map = np.zeros((5, 5), dtype=np.uint32) rc_map[0, 0] = rcval rc_map[1, 1] = rcval lowqeval = dqflags.pixel['LOW_QE']...
[ "def goodpix(map1,map2):\n\n from numpy import where,logical_and\n from healpy import UNSEEN\n\n return where(logical_and(map1!=UNSEEN,map2!=UNSEEN))", "def test_apply_flags():\n true_value = dqflags.pixel['HOT'] + dqflags.pixel['DO_NOT_USE']\n\n print(true_value)\n\n badmap = np.zeros((10, 10),...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Prompts user to select output file
def select_output(self): filename, _filter = QFileDialog.getSaveFileName( self, filter="OpenSCENARIO (*.xosc)") # Update text field only if user press 'OK' if filename: if filename[-4:] != "xosc": filename += ".xosc" self.select_pat...
[ "def prompt_for_output_file(original_file_name):\n print 'Original file: {}'.format(original_file_name)\n choice = io.binary_choice('Output file (s)ame/(n)ew file? ', 's', 'n')\n if choice == 'n':\n new_file_name = io.prompt_valid_file_name('New file name: ')\n return new_file_name\n retur...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Enables/Disables text field for user defined maps
def user_defined_map(self): if self.map_selection.currentText() == "User Defined": self.map_selection_user_defined.setEnabled(True) else: self.map_selection_user_defined.setDisabled(True)
[ "def enable(self, value):\n \n self.obj.set_sensitive(value)\n self.obj.set_editable(value)", "def __enableControls(self):\n for key in self._keyMap.keys():\n self.__acceptKeyDown(key)\n self.__acceptKeyUp(key)", "def dummy():\n\t\t\tself.edit = True", "def _e...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Auto populates road network if available
def load_road_network(self): if QgsProject.instance().mapLayersByName("Metadata"): metadata_layer = QgsProject.instance().mapLayersByName("Metadata")[0] road_network = "" for feature in metadata_layer.getFeatures(): road_network = feature["Road Network"] ...
[ "def init_network(roads):\n #roads=(\n #(\"LB\", \"leuven\", \"brussel\", 27.0, 120),\n #(\"BL\", \"brussel\", \"leuven\", 30.0, 120),\n #(\"LA\", \"leuven\", \"antwerpen\", 61.0, 120),\n #(\"AL\", \"antwerpen\", \"leuven\", 63.0, 120),\n #(\"BO\", \"brussel\", \"oostende\", 110.0, 120)...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Checks value if it can be converted to float.
def is_float(self, value): try: float(value) return True except ValueError: return False
[ "def isFloat(value): \n try:\n float(value)\n return True\n except ValueError:\n return False", "def isfloat(value):\n try:\n float(value)\n return True\n except ValueError:\n return False", "def isfloat(value): \n try:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Main function for generating OpenSCENARIO files.
def main(self): root = etree.Element("OpenSCENARIO") self.get_header(root) self.get_parameter_declarations(root) etree.SubElement(root, "CatalogLocations") self.get_road_network(root) self.get_entities(root) storyboard = etree.SubElement(root, "Storyboard") ...
[ "def main():\n\n scenario = 2\n verbose = 3\n\n ### Generic for all scenario - Data Pre processing -\n ### Removal of ['neutrophil', 'serumLevelsOfWhiteBloodCell', 'lymphocytes'] due to the significant lack of information.\n data = PreProcess(\"./data.csv\", ['neutrophil', 'serumLevelsOfWhiteBloodCel...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets entity list from layers and export into OpenSCENARIO file.
def get_entities(self, root): entity = etree.SubElement(root, "Entities") # Ego Vehicles if QgsProject.instance().mapLayersByName("Vehicles - Ego"): vehicle_ego_layer = QgsProject.instance().mapLayersByName("Vehicles - Ego")[0] for feature in vehicle_ego_layer.getFeatures...
[ "def addEntitiesToScenario(entityList,entities):\n for entity in entityList:\n entity_bounding_box = xosc.BoundingBox(2,5,1.6,2,0,0.9)\n if len(entity.has_bounding_box) != 0:\n entity_bounding_box = checkBoundingBox(entity.has_bounding_box[0])\n entity_name = getNameFromIRI(entity...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generate vehicle properties. Properties are ignored by CARLA simulator, hence generic numbers are used. (as of CARLA 0.9.10)
def get_generic_vehicle_properties(self, vehicle, is_ego=False): etree.SubElement(vehicle, "ParameterDeclarations") performance = etree.SubElement(vehicle, "Performance") performance.set("maxSpeed", "69.444") performance.set("maxAcceleration", "200") performance.set("maxDecelerat...
[ "def def_main_properties(self): \n prop = {}\n\n prop['sample_run'] = [37524,37525]\n prop['sum_runs'] = True \n prop['wb_run'] = 37520\n \n # if energy is specified as a list (even with single value e.g. ei=[81])\n # The numbers are treated as a...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Writes OpenSCENARIO tags for entity teleport action
def entity_teleport_action(self, entity, orientation, pos_x, pos_y, pos_z): private_act = etree.SubElement(entity, "PrivateAction") teleport_action = etree.SubElement(private_act, "TeleportAction") teleport_pos = etree.SubElement(teleport_action, "Position") teleport_worldpos = etree.Sub...
[ "def main(self):\n root = etree.Element(\"OpenSCENARIO\")\n self.get_header(root)\n self.get_parameter_declarations(root)\n etree.SubElement(root, \"CatalogLocations\")\n self.get_road_network(root)\n self.get_entities(root)\n storyboard = etree.SubElement(root, \"St...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Writes ControllerAction OpenSCENARIO tags for vehicles
def vehicle_controller(self, entity, veh_id, agent, agent_camera, is_ego): if is_ego: controller_id = f"HeroAgent_{veh_id}" else: controller_id = f"VehicleAgent_{veh_id}" private_act = etree.SubElement(entity, "PrivateAction") controller_act = etree.SubElement(pr...
[ "def main(self):\n root = etree.Element(\"OpenSCENARIO\")\n self.get_header(root)\n self.get_parameter_declarations(root)\n etree.SubElement(root, \"CatalogLocations\")\n self.get_road_network(root)\n self.get_entities(root)\n storyboard = etree.SubElement(root, \"St...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets maneuvers from QGIS layer. If no maneuvers are detected, create a minimal XML structure.
def get_maneuvers(self, act): if QgsProject.instance().mapLayersByName("Maneuvers"): layer = QgsProject.instance().mapLayersByName("Maneuvers")[0] if layer.featureCount() == 0: self.generate_minimal_maneuver(act) error_message = "No maneuvers set... Genera...
[ "def generate_minimal_maneuver(self, act):\n entity = \"\"\n pos_x = 0\n pos_y = 0\n if QgsProject.instance().mapLayersByName(\"Vehicles - Ego\"):\n layer = QgsProject.instance().mapLayersByName(\"Vehicles - Ego\")[0]\n if layer.featureCount() != 0:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates a minimal XML structure to meet OpenSCENARIO specifications when no maneuvers are set. Entity reference will take any one vehicle spawned (prioritizing ego). Creates a speed action at position +100 meters, to prevent scenario from exiting immediately after being run.
def generate_minimal_maneuver(self, act): entity = "" pos_x = 0 pos_y = 0 if QgsProject.instance().mapLayersByName("Vehicles - Ego"): layer = QgsProject.instance().mapLayersByName("Vehicles - Ego")[0] if layer.featureCount() != 0: for feature in la...
[ "def main(self):\n root = etree.Element(\"OpenSCENARIO\")\n self.get_header(root)\n self.get_parameter_declarations(root)\n etree.SubElement(root, \"CatalogLocations\")\n self.get_road_network(root)\n self.get_entities(root)\n storyboard = etree.SubElement(root, \"St...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Writes stop triggers for maneuvers if enabled.
def get_maneuver_stop_trigger(self, feature, event): stop_trigger = etree.SubElement(event, "StopTrigger") cond_group = etree.SubElement(stop_trigger, "ConditionGroup") cond = etree.SubElement(cond_group, "Condition") cond_name = f'Condition for Maneuver ID {str(feature["id"])}' ...
[ "def stop(self) -> None:\n for func in self.triggers:\n func.trigger_stop()\n self.triggers = set()\n self.triggers_delay_start = set()\n self.set_auto_start(False)", "def reset_all_stop_trigger_vars(self):\n self.StopTrigButtonName.set('No stop trigger is set: analys...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Writes story start triggers.
def get_story_start_trigger(self, act): act_start = etree.SubElement(act, "StartTrigger") cond_group = etree.SubElement(act_start, "ConditionGroup") time_cond = etree.SubElement(cond_group, "Condition") time_cond.set("name", "StartTime") time_cond.set("delay", "0") time_c...
[ "def create_triggers(self):\n triggers = self.get_source_triggers()\n if not triggers:\n self.create_insert_trigger()\n self.create_update_trigger()\n self.create_delete_trigger()\n self.commit()", "def triggers(self, triggers):\n\n self._triggers =...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Writes story stop triggers.
def get_story_stop_trigger(self, act): stop = etree.SubElement(act, "StopTrigger") cond_group = etree.SubElement(stop, "ConditionGroup") cond = etree.SubElement(cond_group, "Condition") cond.set("name", "EndCondition") cond.set("delay", "0") cond.set("conditionEdge", "ris...
[ "def stop(self) -> None:\n for func in self.triggers:\n func.trigger_stop()\n self.triggers = set()\n self.triggers_delay_start = set()\n self.set_auto_start(False)", "def sw_trig_stop(self):\n self.send_command(\"SW_TRIG_STOP\")", "def reset_all_stop_trigger_vars(s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Save and export pretty printed XOSC file.
def write_xosc(self, generated_xml): reparsed_xml = minidom.parseString(generated_xml).toprettyxml(indent=" ") xosc_file = open(self._filepath, "w") xosc_file.write(reparsed_xml) xosc_file.close() msg = QMessageBox() if self._warning_message: msg.setIcon(Q...
[ "def prettyprint(self, _file):\n xstr = \"reg \" + self.name + \" \" + self.type.desc()\n _file.write(xstr + \"\\n\")", "def save(self):\n Preferences.setPrinter(\n \"PrinterName\",\n self.printerNameEdit.text())\n if self.printerColorButton.isChecked():\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Retrieve news articles containing keywords.
def get_news(keywords, news='all'): if news is 'all': return news_client.get_everything(q=keywords) elif news is 'top': return news_client.get_top_headlines(q=keywords) else: raise AttributeError("Optional argument news expected 'top' or 'all'")
[ "def searchnews(self,\n keywords=None,\n dateStart=None,\n dateEnd=None,\n sortBy=None,\n domains=None,\n page=20,\n sources='abc-news',\n language=None,\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Displays text, search volume, average cpc and categories for idea.
def DisplayIdea(keyword): logger.info('Found Keyword with text [%s]' % keyword['KEYWORD_TEXT']) logger.info(' Keyword Idea search volume: %s' % keyword['SEARCH_VOLUME']) logger.info(' Keyword Idea average CPC: %s' % keyword['AVERAGE_CPC']) logger.info(' Keyword Idea categories: %s' % keyword['CATEGORY_PRODUC...
[ "def main():\n\n\tst.title(\"Sentiment Analysis Emoji App\")\n\n\tactivities = [\"Sentiment\",\"Text Analysis on URL\",\"About\"]\n\tchoice = st.sidebar.selectbox(\"Choice\",activities)\n\n\tif choice == 'Sentiment':\n\t\tst.subheader(\"Sentiment Analysis\")\n\t\tst.write(emoji.emojize('Everyone :red_heart: Streaml...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
parse datetime range str to pair of datetime objects.
def parse_datetime_range(date_time_range, exception_class=Exception): try: start, end = date_time_range.split(',') except Exception as error: logging.exception(error) raise exception_class( 'there is no `,` in date time range %s' % date_time_range ) if start: ...
[ "def date_range(s):\n dates = s.split(':')\n if len(dates) != 2:\n raise ValueError(\"Date range not in format '<date1>:<date2>'\")\n result = []\n for date in dates:\n try:\n epoch_sec = time.mktime(time.strptime(date, '%Y-%m-%d'))\n except ValueError:\n raise...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check instance type is in one of expected types.
def is_instance(instance, expected_types): for expected_type in expected_types: if isinstance(instance, expected_type): return True return False
[ "def check_type(instance, type):\n\tif not isinstance(instance, type):\n\t\traise TypeError('Instance expected type {0}, but got: {1}', type(type), type(instance))", "def __is_type_instance( self, instance_type ):\n for index, instance in enumerate(INSTANCE_TYPES):\n if instance == instance_typ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
get switch machines from file.
def get_switch_machines_from_file(filename): switches = [] switch_machines = {} with open(filename) as switch_file: for line in switch_file: line = line.strip() if not line: # ignore empty line continue if line.startswith('#'): ...
[ "def get_machines():\r\n return listMachinesFomFile", "def get_switches(file):\n try:\n switches = file.project().get_attribute_as_list(\n attribute='Switches', package='QGen',\n index=os.path.basename(file.path))\n if not switches:\n sw...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Loads all slurm data in a folder and builds a json file which it stores.
def load_slurm_folder(p): filter_function = lambda f: True if ".out" in f else False slurm_dict = {"runs": []} for f in filter(filter_function, os.listdir(p)): slurm_dict["runs"].append(load_slurm_data(os.path.join(p, f))) exit("Success!")
[ "def build_json():\n data = []\n files_list = os.listdir(DATA_DIR)\n for filename in files_list: \n filepath = DATA_DIR + \"/\" + filename\n with open(filepath, 'r', errors='replace') as f: \n content = f.read()\n dentry = {\"file_name\": filename, \"content\": content}\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Parses the XML post data and stores all the information required to fuzz the XML data as attributes.
def parse_xml_data(self, xml_post_data): try: read_handler = parse_xmlrpc(xml_post_data) except: raise ValueError(ERR_MSG % xml_post_data[:50]) else: # Tried to do this with self.update but it was failing :S for k, v in read_handler.get_data_contai...
[ "def do_post_parse_xml(self, *args, **kwargs): # real signature unknown\n pass", "def parse_data(self):\n\n msg = self.xml['dom'].childNodes[0]\n self.data = xml_to_dicts(msg, False)\n\n # Get some metadata together\n self.id = \"%s:%s\" % (self.data['src']['name']['#cdata'], se...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a .h file by surrounding the contents of a yaccgenerated .hpp with a ifndefdefineendif guard.
def create_h_wrapper(target, source, env): t = str(target[1]) fp = open(t, 'w') define = os.path.splitext(os.path.split(t)[1])[0] fp.write('#ifndef %s_h\n' % define) fp.write('#define %s_h\n' % define) fp.write(open(t + 'pp', 'r').read()) fp.write('#endif // %s_h\n' % define)
[ "def write_header(dot_H_code_filename):\n\n filename = dot_H_code_filename.replace(\".\", \"_\")\n filename = filename.upper()\n filename = \"__\" + filename + \"_\"\n\n first_str = \"\"\"\n#pragma once\n\n\n#ifndef \"\"\"\n\n second_str = \"#define \"\n\n third_str = \"\"\"\n \n#include <strin...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
returns a list of random bdays of length n
def gen_birthdays(n): list = [] for date in range(n): list.append(random.randint(1, 365)) return list
[ "def getRandomList(n):\n lyst = list()\n for count in range (n):\n lyst.append(random.randint(1, n))\n return lyst", "def generatoze(b):\r\n l = []\r\n for i in range(b):\r\n k = random.randint(0, 100)\r\n l.append(k)\r\n return l", "def rand_list(n, limit):\n g = []\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
generates sample bdays for number of students and returns count of how many had matches
def num_matches(students, samples): count = 0 for i in range(samples): bday_list = gen_birthdays(students) if has_duplicates(bday_list): count += 1 return count
[ "def test(self,n_tests,day):\n sample = random.sample(list(self.statuses),k = n_tests)\n self.testInf[day] = len(np.where(np.array(sample) == INF)[0])\n self.testHealthy[day] = n_tests - self.testInf[day]\n self.nTests[day] = n_tests", "def num_students(self,dd=\"\"):\n\t\tif dd==\"\":...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
rospy.Subscriber('YOUR_STRING_HERE', ..., self.navToPose, queue_size=1) handle nav goal events This is a callback function. It should exract data from goal, drive in a striaght line to reach the goal and then spin to match the goal orientation.
def navToPose(self,goal): goalX=(goal.pose.position.x - self._current.position.x) goalY=(goal.pose.position.y - self._current.position.y) goalDistance=((goalX**2)+(goalY**2))**(.5) goalAngle=math.radians(math.atan2(goalY,goalX)) self.rotate(goalAngle) time.sleep(2) ...
[ "def navigate(self, pose):\n self.client.wait_for_server()\n goal = MoveBaseGoal()\n goal.target_pose.header.frame_id = \"odom\"\n goal.target_pose.header.stamp = rospy.Time.now()\n goal.target_pose.pose = pose\n\n self.client.send_goal(goal)\n self.client.wait_for_r...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Find rightmost value less than x in list a
def find_lt(a,x): i = bisect_left(a,x) if i: return a[i-1] raise ValueError
[ "def find_lt(a, x):\n i = bisect_left(a, x)\n if i:\n return int(i-1)\n print('in find_lt,{}'.format(a))\n raise ValueError", "def find_min(list):\n return find_value_at(list, -1)", "def find_le(a, x):\n i = bisect_right(a, x)\n if i:\n return a[i - 1]\n rai...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Find leftmost item greater than or equal to x in list a
def find_ge(a,x): i = bisect_left(a,x) if i != len(a): return a[i] raise ValueError
[ "def find_gt(a, x):\n x = bisect_right(a, x)\n if x != len(a):\n return a[x]\n raise ValueError", "def GetIdxFirstLargerThan(el, lst):\n return lst.index(GetFirstLargerThan(el, lst))", "def find_gt_index(a, x):\n i = bisect_right(a, x)\n if i < len(a):\n return i\n raise Value...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Make a list of alternate allele frequencies and number of reads
def get_altL(fn): f = open(fn,'r') linesL = [ x.strip().split('\t') for x in f.readlines() ] f.close() if linesL[0][0][0] == '#': linesL = linesL[1:] for i in range(len(linesL)): if linesL[i][4] == '0': # if the number of reads supporting alternate is 0, we'll switch to 1 so avoid nu...
[ "def allele_freqs(self):\n diploid = self.geno.sum(2) * 0.5\n return np.nanmean(diploid, axis = 0)", "def GenFrequencies(alignment):\n bases = {'A':0,'C':0,'G':0,'T':0,'-':0}\n FreqArray = []\n SeqLen = getLen(alignment)\n for i in range(SeqLen):\n FreqArray.append(bases.copy())\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates dict of expected alternate allele frequencies and consistent genotypes
def freq_to_genotype(pL,sL,er): h = sum(pL) # number of different haplotypes L = [ bin(x)[2:] for x in range(1,2**h-1) ] # range from 1 to 2**h-1 because we don't want 0% or 100% allele freq M = [ '0'*(len(L[-1])-len(x))+x for x in L ] p_freqL = [] for i in range(len(pL)): p_freqL += [sL[i]/...
[ "def build_intrenal_hap_dict(self, alleles):\n\n internal = {}\n for i, haplotype in enumerate(alleles):\n if type(haplotype[0])==tuple: #Checks if X is a tuple/list of alleles.\n n = len(haplotype)\n if n==1:\n internal[1 << i] = self.hap_di...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Reduces a list of genotypes to distinct genotypes given ploidy
def collapse_genotypes(pL,gL): if len(gL) < 2: return gL else: uniqueL = [] # list of unique genotypes relative to ploidy for g in gL: s = '' for i in xrange(len(pL)): s += ''.join(sorted(g[0:pL[i]])) g = g[pL[i]:] if s ...
[ "def all_genotype(ploidy):\n return [\"\".join(comb) for comb in cwr(\"ACGT-\", ploidy)]", "def unique_genres(table):\n genre_str = ''\n genre_col = MyPyTable.get_column(table, 'Genres', False)\n vals, counts = get_frequencies(table, 'Genres')\n for v in vals:\n genre_str = genre_str + v + '...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Maximum likelihood estimator of alt_freq given possibilities in exp_freqL
def estimate_genotype(alt_freq,exp_freqL): try: i = find_lt(exp_freqL,alt_freq) # Find rightmost value less than x except ValueError: i = float("-inf") try: j = find_ge(exp_freqL,alt_freq) # Find leftmost item greater than or equal to x except ValueError: j = float("inf")...
[ "def freq_eff(self):", "def exp(self, log_L: np.ndarray) -> np.ndarray:", "def findMaximal(freqSet):", "def _get_log_freq(sample_rate, max_sweep_rate, offset):\n start, stop = math.log(offset), math.log(offset + max_sweep_rate // 2)\n return torch.exp(torch.linspace(start, stop, sample_rate, dtype=torch...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get account asset information.
async def get_user_account(self): uri = "/v3/spot/assets" success, error = await self.request("GET", uri, auth=True) return success, error
[ "def get_asset_details(self, **params):\n res = self._request_withdraw_api('get', 'assetDetail.html', True, data=params)\n if not res.get('success'):\n raise BinanceWithdrawException(res['msg'])\n return res", "def get_asset_details(self, **params):\n return self._request_ma...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Initialize. fetch all open order information.
async def _initialize(self): result, error = await self._rest_api.get_open_orders(self._raw_symbol) if error: e = Error("get open order nos failed: {}".format(error)) logger.error(e, caller=self) SingleTask.run(self._init_success_callback, False, e) return...
[ "def request_orders(self):\n self.enqueue_http_request(\"private/OpenOrders\", {}, \"orders\")", "def get_all_open_orders(self):\n self.__init_client()\n open_orders = retry(lambda: self.client\n .futures_get_open_orders(symbol=self.pair)) \n if len(op...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get open order id list.
async def get_open_order_nos(self): success, error = await self._rest_api.get_open_orders(self._raw_symbol) if error: return False, error order_nos = [] for order_info in success["data"]: order_nos.append(order_info["order_id"]) return order_nos, None
[ "async def get_open_order_nos(self):\n success, error = await self._rest_api.get_open_orders(self._raw_symbol)\n if error:\n return None, error\n order_nos = []\n for order_info in success:\n order_no = \"{}_{}\".format(order_info[\"orderId\"], order_info[\"clientOr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Populate the facts for firewall
def populate_facts(self, connection, ansible_facts, data=None): fos = self._fos if self._fos else connection vdom = self._module.params['vdom'] ansible_facts['ansible_network_resources'].pop('system', None) facts = {} if self._uri.startswith(tuple(FACT_SYSTEM_SUBSETS)): ...
[ "def _facts(facts):\n return {'swift_facts': facts}", "def CreateRules(context):\n\n Firewall_Rules = []\n \"\"\"\n Loop through many defined firewalls and build a Dict to be append to the list\n \"\"\"\n\n for rule in context.properties['rules']:\n given_name = rule['name']\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check if user is already followed
def is_user_already_followed(followed_user_id, user_id): result = Follow.objects.filter(followed_user=followed_user_id, user=user_id).exists() return result
[ "def check_if_already_following(self, request, user_model):\n followees = Follower.objects.all()\n for follow in followees:\n if str(request.user.username) == str(follow.followers) and str(user_model.username) == str(follow.user):\n return True\n return False", "def ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Notifies the user when they are followed
def was_followed(sender, instance, created, **kwargs): sendr = User.objects.get(id=instance.user_id) followed = User.objects.get(id=instance.followed_user_id) if created: notify.send(sender=sendr, recipient=followed, verb='followed', description="{} followed you.".format(sendr.u...
[ "def follow_user(cls, user, following):\r\n pass", "def follow_user(cls, user, following):\n pass", "def follow_user(request, user_id):\n user = get_object_or_404(User, id=user_id)\n if request.user in user.profile.followers.all():\n user.profile.followers.remove(request.user)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get all Jenkins jobs associated with pull requests
def get_pr_jobs(): res = requests.get( uri + "/view/Pull%20Requests/api/json", headers={"accept": "application/json"}, auth=requests.auth.HTTPBasicAuth(user, password), verify=verify, ) if res.status_code != 200: raise RuntimeError("Received non 200 status code from j...
[ "def jobs(self):\n template = 'https://ci.appveyor.com/api/projects/{0.username}/{0.project}'\n url = template.format(self)\n headers = {'Authorization': 'Bearer {0.api_token}'.format(self)}\n response = requests.get(url, headers=headers)\n info = self.json_decoder.decode(response...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Determin weather a Jenkins job accepts build parameters
def job_has_params(job_url): name = job_url.rstrip("/").rsplit("/")[-1] if name in ( "pr-docs", "pr-lint", "pr-pre-commit", ): return False else: return True
[ "def jenkins_flag():\n flags = os.environ.get('BODEGA_TEST_FLAGS', '').lower().split(',')\n return 'jenkins' in flags", "def is_build_job(self):\n\n for fspec in self.outdata:\n if '.lib.' in fspec.lfn and '.log.' not in fspec.lfn:\n return True\n\n return False", "...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Filter jobs by a keyword. When the keyword is 'all' every job is returned
def filter_jobs(jobs, keyword): for job in jobs: if keyword == "all": yield job elif job["name"].find(keyword) != -1: yield job
[ "def __filter_jobs(self, job_url: str):\r\n soup = self.__get_html_parser(job_url)\r\n results = soup.find('div', {'data-automation': 'jobAdDetails'}) # {'class': 'FYwKg WaMPc_4'})\r\n listed_items = results.find_all('li')\r\n job_description = PrefixTrie()\r\n\r\n for item in li...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Request jenkins to build a job
def build_job(job_url, pr_number, run_full, has_params): log.debug( "job_url: %s pr_num: %s run_full: %s has_params: %s", job_url, pr_number, run_full, has_params, ) if has_params: pr_url = "{}/job/PR-{}/buildWithParameters?runFull={}".format( job_...
[ "def req_build(job_name):\n ret_crumb = get_crumb()\n req_header = {\n 'Content-Type': 'application/json',\n 'Jenkins-Crumb': ret_crumb,\n }\n req_url = f\"{req_info['url']}/job/{job_name}/build\"\n print(req_url)\n req_auth = (req_info['user'], req_info['user_token'])\n\n respons...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Constructor for the Solver class. name Name of the SMT solver that this object represents.
def __init__(self, name=""): # Name of the SMT solver that this object represents. self.name = name
[ "def __init__(self, name):\n assert type(name) is str, \"Problem name must be a string\"\n\n self.name = name\n self.datadir = \"data/\"\n self.nt = 0\n self.dt = 0.\n self.ttot = 0.\n self.cfl = 0.\n self.ninfo = 10\n self.rkorder = 1\n self.d =...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Checks and updates the satisfiability of the SMT query represented by the Query object provided. If the SMT query is satisfiable, the Query object is updated with a satisfying model; if the query is unsatisfiable, the Query object is updated with an unsatisfiable core. query Query object that represents an SMT query.
def checkSat(self, query): errMsg = "Method has not yet been implemented." raise NotImplementedError(errMsg)
[ "def checkSat(self, query):\n # Write the SMT query to a temporary file.\n smtQueryFileHandler = NamedTemporaryFile()\n with smtQueryFileHandler:\n smtQueryFileHandler.write(query.queryStr)\n smtQueryFileHandler.seek(0)\n\n command = self._generateBoolectorComma...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test validating ingress session.
async def test_validate_session(api_client: TestClient, coresys: CoreSys): with patch("aiohttp.web_request.BaseRequest.__getitem__", return_value=None): resp = await api_client.post( "/ingress/validate_session", json={"session": "non-existing"}, ) assert resp.status =...
[ "def test_read_namespaced_ingress(self):\n pass", "def testGetIngressPort(self):\n self.oxc.get_ingress(file_name = 'get_ingress_port.xml')", "def test_read_namespaced_ingress_status(self):\n pass", "async def test_validate_session_with_user_id(\n api_client: TestClient, coresys: CoreS...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test validating ingress session with user ID passed.
async def test_validate_session_with_user_id( api_client: TestClient, coresys: CoreSys, ha_ws_client: AsyncMock ): with patch("aiohttp.web_request.BaseRequest.__getitem__", return_value=None): resp = await api_client.post( "/ingress/validate_session", json={"session": "non-existi...
[ "async def test_validate_session(api_client: TestClient, coresys: CoreSys):\n with patch(\"aiohttp.web_request.BaseRequest.__getitem__\", return_value=None):\n resp = await api_client.post(\n \"/ingress/validate_session\",\n json={\"session\": \"non-existing\"},\n )\n a...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Records a transaction and returns True if this transaction is recorded successfully. A transaction is recorded successfully when this bank account is not locked, has enough balance, and the budget associated with the transaction is not locked.
def record_transaction(self, transaction: Transaction) -> bool: if self._locked: print('Failed to record transaction! Your account has been locked!' ) return False if transaction.amount > self.bank_balance: print('Failed to record transaction! Not e...
[ "def record_transaction(self) -> None:\n Menu.prompt_record_transaction()\n tx_data = Transaction.prompt_record_tx()\n new_tx = Transaction.generate_new_tx(tx_data)\n\n # Convert the user budget category int input to the enum\n budget_category_int = new_tx.budget_category\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Prints a list of transactions in the given budget for review.
def print_transactions_for_review(self, budget: Budget) -> None: print(f'Please review the following transactions in the {budget.name} ' f'budget:') transactions = self.get_transactions_by_budget(budget.category) for transaction in transactions: print(transaction)
[ "def view_transactions(self) -> None:\n user_choice = Menu.prompt_view_transactions()\n if user_choice == 5:\n print(\"Returning to main menu...\")\n return\n\n budget_category = BudgetManager.category_mapping[user_choice]\n print(f\"\\nTransactions in the {budget_c...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Issues a warning to the user that they are about to exceed this budget.
def _warn_nearing_exceed_budget(self, budget: Budget, exceeded_percent: int) -> None: print(f'[WARNING] You are about to exceed the {budget.name} budget! ' f'You went over {exceeded_percent}% of the total ' f'${budget.total_amount}.')
[ "def _notify_exceeded_budget(self, budget: Budget) -> None:\n print(f'[NOTIFICATION] You have exceeded the {budget.name} budget.')", "def _check_budget(self, required_capital:float):\n available_cash = float(api.get_account().cash)\n if required_capital > available_cash:\n raise Ex...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Notifies the user that they've just exceeded this budget.
def _notify_exceeded_budget(self, budget: Budget) -> None: print(f'[NOTIFICATION] You have exceeded the {budget.name} budget.')
[ "def _warn_nearing_exceed_budget(self, budget: Budget,\n exceeded_percent: int) -> None:\n print(f'[WARNING] You are about to exceed the {budget.name} budget! '\n f'You went over {exceeded_percent}% of the total '\n f'${budget.total_amount}.')", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a list of transactions for the given budget category.
def get_transactions_by_budget(self, category: BudgetCategory) -> list: return [transaction for transaction in self.transactions if transaction.budget_category == category]
[ "def get_transactions_for_budget(self, budget_name=None):\n if len(self.budgets) > 1 and budget_name is None:\n self._logger.error('There are multiple budgets and no budget name was provided')\n raise MultipleBudgets\n if budget_name is None:\n self._logger.debug('No b...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a list of budgets.
def get_budgets(self) -> list: return self.budget_manager.get_budgets()
[ "def get_budgets(self) -> list:\n return list(self.budgets.values())", "def view_budgets(self) -> None:\n Menu.prompt_view_budgets()\n for budget in self.user.budget_manager:\n print(f\"{budget}\\n\")", "def yearly_budgets(self):\n return self._yearly_budgets", "def prin...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Issues a warning or locks budget/bank account when these
def _warn_and_lock_if_needed(self, transaction: Transaction) -> None: budget = self.budget_manager.get_budget(transaction.budget_category) exceeded_ratio = budget.exceeded_ratio if exceeded_ratio > 1: self._notify_exceeded_budget(budget) self._lock_budget(budget) ...
[ "def issue_locked_warning() -> None:\n print(\"\\n[red]Warning:[/red] Your bank account has been completely \"\n \"locked out for exceeding 2 or more categories!\")", "def _notify_exceeded_budget(self, budget: Budget) -> None:\n print(f'[NOTIFICATION] You have exceeded the {budget.name}...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates and returns a test bank account.
def load_test_account() -> BankAccount: budget_manager = BudgetCreator.load_test_budget_manager() return TroublemakerBankAccount('123123', 'HSBC', 1000, budget_manager)
[ "def example_bank_account():\n \n return BankAccount(\"Test User\", 1000.0)", "def create_test_account(self):\n if not hasattr(self, \"headers\"):\n self.headers = {\"Content-Type\": \"application/json\"}\n self.account = {\n \"account_number\": \"11223344\",\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Prompts the user for bank account details, initializes a Bank Account based on the given user type and returns it.
def create_bank_account(cls, user_type: UserType) -> BankAccount: bank_account_no = input('Enter bank account number: ') bank_name = input('Enter bank name: ') bank_balance = -1 while bank_balance < 0: bank_balance = float(input('Enter bank balance: ')) if bank_ba...
[ "def create_account():\n menu_str = \"Which type of account would you like to create? \\n\\\n A - Savings account \\n\\\n B - Checking account \\n\\\n ? \"\n class_choices = {'A': SavingsAccount, 'B': CheckingAccount}\n a = validate_choice(input(menu_str), class_choices)(\n cust...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create authorization code in db
async def create_authorization_code( self, *args, **kwargs ) -> OAuth2AuthorizationCode: authorization_code = await super().create_authorization_code( *args, **kwargs ) data = authorization_code._asdict() # TODO: handle None values for optional property f...
[ "def add_admin_access_code():\n admin_ac = app.config['SECRET_KEY']\n new_access_code_doc = models.AccessCode(\n access_code=admin_ac,\n role='a', # admin role\n expiration=36500, # init expiration to roughly 100 year!\n )\n new_access_code_doc.save()\n app.logger.debug('Added ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Revokes an existing token. The `revoked` Flag of the Token must be set to True
async def revoke_token(self, request: Request, token: str) -> None: token_record = ... token_record.revoked = True token_record.save()
[ "def revoke_token(self, token, request):\n token.revoked = True\n token.save()", "def revoke_token(token):\n token.delete_instance()", "def revoke_token():\n json_request = request.json\n refresh_token = json_request.get('refresh_token')\n if not refresh_token:\n return msg.erro...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Converts fastapi Request instance to OAuth2Request instance
async def _oauth2_request(request: Request): form = await request.form() def get(user, query_params): post = dict(form) method = request.method headers = CaseInsensitiveDict(**request.headers) url = str(request.url) return OAuth2Request( settings=get_aioauth...
[ "def _get_oauth_request(self, request):\n return oauth2.Request.from_request(request.method, request.build_absolute_uri(),\n headers=request.META, query_string=request.raw_post_data)", "def as_request(obj):\n if isinstance(obj, Request):\n return obj\n elif isinstance(obj, list):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }