query
stringlengths
9
9.05k
document
stringlengths
10
222k
negatives
listlengths
19
20
metadata
dict
Tests that 'admin' cannot add a product with empty fields
def test_admin_cannot_create_product_with_empty_fields(self): resp = self.admin_register() reply = self.admin_login() token = reply['token'] product = dict( prod_name='', category='', stock=20, price=150 ) resp = self.client.post( '/api/v1/products', content_type='application/json', data=json.dumps(product), headers={'Authorization': 'Bearer {}'.format(token)} ) reply = json.loads(resp.data.decode()) self.assertEqual(reply['message'], 'Please enter all fields!') self.assertEqual(resp.status_code, 400)
[ "def test_product_cannot_create_with_invalid_details(self):\n res = self.client().post('/api/v1/products', data=json.dumps(self.empty_product), headers = {\"content-type\": \"application/json\"})\n self.assertEqual(res.status_code, 201)", "def test_update_product_with_empty_fields(self):\n re...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tests that product_name field cannot contain a number
def test_Product_name_cannot_contain_a_number(self): resp = self.admin_register() reply = self.admin_login() token = reply['token'] product = dict( prod_name='NY_3', category='denims', stock=20, price=150 ) resp = self.client.post( '/api/v1/products', content_type='application/json', data=json.dumps(product), headers={'Authorization': 'Bearer {}'.format(token)} ) reply = json.loads(resp.data.decode()) self.assertEqual(reply['message'], 'Please enter strings in name and category!') self.assertEqual(resp.status_code, 400)
[ "def test_category_cannot_contain_a_number(self):\n resp = self.admin_register()\n reply = self.admin_login()\n token = reply['token']\n product = dict(\n prod_name='NY_denims',\n category='4dens',\n stock=20,\n price=150\n )\n re...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tests that category field cannot contain a number
def test_category_cannot_contain_a_number(self): resp = self.admin_register() reply = self.admin_login() token = reply['token'] product = dict( prod_name='NY_denims', category='4dens', stock=20, price=150 ) resp = self.client.post( '/api/v1/products', content_type='application/json', data=json.dumps(product), headers={'Authorization': 'Bearer {}'.format(token)} ) reply = json.loads(resp.data.decode()) self.assertEqual(reply['message'], 'Please enter strings in name and category!') self.assertEqual(resp.status_code, 400)
[ "def test_isNumericCategory(self):\n obs = self.overview_map.isNumericCategory('Treatment')\n self.assertEqual(obs, False)\n\n obs = self.overview_map.isNumericCategory('DOB')\n self.assertEqual(obs, True)", "def test_non_numberic_validation(self):", "def test_validate_input_value_ca...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tests that stock and price fields must be numbers
def test_stock_and_price_must_be_numbers(self): resp = self.admin_register() reply = self.admin_login() token = reply['token'] product = dict( prod_name='NY_denims', category='denims', stock='stock', price='money' ) resp = self.client.post( '/api/v1/products', content_type='application/json', data=json.dumps(product), headers={'Authorization': 'Bearer {}'.format(token)} ) reply = json.loads(resp.data.decode()) self.assertEqual(reply['message'], 'The Stock and Price must be numbers!') self.assertEqual(resp.status_code, 400)
[ "def test_add_sale_with_price_not_digit_format(self):\n self.register_admin_test_account()\n token = self.login_admin_test()\n\n response = self.app_test_client.post('{}/saleorder'.format(\n self.base_url), json={'name': \"Hand Bag\", 'price': \"1500\", 'quantity': 3, 'totalamt': \"\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tests that product already exists in the Inventory
def test_product_exists_in_inventory(self): resp = self.admin_register() reply = self.admin_login() token = reply['token'] product = dict( prod_name='NY_denims', category='denims', stock=20, price=150 ) resp = self.client.post( '/api/v1/products', content_type='application/json', data=json.dumps(product), headers={'Authorization': 'Bearer {}'.format(token)} ) product = dict( prod_name='NY_denims', category='denims', stock=20, price=150 ) resp = self.client.post( '/api/v1/products', content_type='application/json', data=json.dumps(product), headers={'Authorization': 'Bearer {}'.format(token)} ) reply = json.loads(resp.data.decode()) self.assertEqual(reply['message'], 'This product exists in the Inventory!') self.assertEqual(resp.status_code, 400)
[ "def test_already_existing_product_name(self):\n self.query_with_token(\n self.access_token,\n create_product.format(\n supplier_id=self.supplier_id, backup_id=self.backup_id))\n response = self.query_with_token(\n self.access_token,\n create_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tests that a user can view a product in the Inventory
def test_view_a_product(self): resp = self.admin_register() reply = self.admin_login() token = reply['token'] product = dict( prod_name='NY_denims', category='denims', stock=20, price=150 ) resp = self.client.post( '/api/v1/products', content_type='application/json', data=json.dumps(product), headers={'Authorization': 'Bearer {}'.format(token)} ) reply = json.loads(resp.data.decode()) self.assertEqual(reply['message'], 'Product successfully added to Inventory!') self.assertEqual(resp.status_code, 201) resp = self.client.get( '/api/v1/products/1', headers={'Authorization': 'Bearer {}'.format(token)} ) reply = json.loads(resp.data.decode()) self.assertIn('NY_denims', str(reply['product'])) self.assertEqual(resp.status_code, 200)
[ "def test_permission_detail(self):\n\n self.client.logout()\n\n error_message = \"Authentication credentials were not provided.\"\n\n data = {\n \"user\": self.user_1,\n \"item\": self.item_1,\n \"quantity\": 90,\n }\n inventory = Inventory.objects...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tests that a user cannot view a product in the Inventory with blacklisted token
def test_cannot_view_a_product_with_blacklisted_token(self): resp = self.admin_register() reply = self.admin_login() token = reply['token'] product = dict( prod_name='NY_denims', category='denims', stock=20, price=150 ) resp = self.client.post( '/api/v1/products', content_type='application/json', data=json.dumps(product), headers={'Authorization': 'Bearer {}'.format(token)} ) reply = json.loads(resp.data.decode()) self.assertEqual(reply['message'], 'Product successfully added to Inventory!') self.assertEqual(resp.status_code, 201) resp = self.client.delete( '/api/v1/logout', headers={'Authorization': 'Bearer {}'.format(token)} ) reply = json.loads(resp.data.decode()) self.assertEqual(reply['message'], 'You are successfully logged out!') self.assertEqual(resp.status_code, 200) resp = self.client.get( '/api/v1/products/1', headers={'Authorization': 'Bearer {}'.format(token)} ) reply = json.loads(resp.data.decode()) self.assertEqual(reply['message'], 'Invalid Authentication, Please Login!') self.assertEqual(resp.status_code, 401)
[ "def test_cannot_view_all_products_with_blacklisted_token(self):\n resp = self.admin_register()\n reply = self.admin_login()\n token = reply['token']\n product = dict(\n prod_name='NY_denims',\n category='denims',\n stock=20,\n price=150\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tests that a user can view all products in the Inventory
def test_view_all_products(self): resp = self.admin_register() reply = self.admin_login() token = reply['token'] product = dict( prod_name='NY_denims', category='denims', stock=20, price=150 ) resp = self.client.post( '/api/v1/products', content_type='application/json', data=json.dumps(product), headers={'Authorization': 'Bearer {}'.format(token)} ) reply = json.loads(resp.data.decode()) self.assertEqual(reply['message'], 'Product successfully added to Inventory!') self.assertEqual(resp.status_code, 201) resp = self.client.get( '/api/v1/products', headers={'Authorization': 'Bearer {}'.format(token)} ) reply = json.loads(resp.data.decode()) self.assertIn('NY_denims', str(reply['products'])) self.assertEqual(resp.status_code, 200)
[ "def test_list_products_logged_in(self):\n\n # Log in seller\n self.client.login(username=\"test_seller\", password=\"secret\")\n\n # Issue a GET request\n response = self.client.get(reverse('website:products'))\n\n # Check that the response is 200\n self.assertEqual(respon...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tests that a user cannot view all products in the Inventory with blacklisted token
def test_cannot_view_all_products_with_blacklisted_token(self): resp = self.admin_register() reply = self.admin_login() token = reply['token'] product = dict( prod_name='NY_denims', category='denims', stock=20, price=150 ) resp = self.client.post( '/api/v1/products', content_type='application/json', data=json.dumps(product), headers={'Authorization': 'Bearer {}'.format(token)} ) reply = json.loads(resp.data.decode()) self.assertEqual(reply['message'], 'Product successfully added to Inventory!') self.assertEqual(resp.status_code, 201) resp = self.client.delete( '/api/v1/logout', headers={'Authorization': 'Bearer {}'.format(token)} ) reply = json.loads(resp.data.decode()) self.assertEqual(reply['message'], 'You are successfully logged out!') self.assertEqual(resp.status_code, 200) resp = self.client.get( '/api/v1/products', headers={'Authorization': 'Bearer {}'.format(token)} ) reply = json.loads(resp.data.decode()) self.assertEqual(reply['message'], 'Invalid Authentication, Please Login!') self.assertEqual(resp.status_code, 401)
[ "def test_cannot_view_a_product_with_blacklisted_token(self):\n resp = self.admin_register()\n reply = self.admin_login()\n token = reply['token']\n product = dict(\n prod_name='NY_denims',\n category='denims',\n stock=20,\n price=150\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tests that a user cannot view a product that doesnot exist in the Inventory
def test_view_product_that_doesnot_exist_in_inventory(self): resp = self.admin_register() reply = self.admin_login() token = reply['token'] product = dict( prod_name='NY_denims', category='denims', stock=20, price=150 ) resp = self.client.post( '/api/v1/products', content_type='application/json', data=json.dumps(product), headers={'Authorization': 'Bearer {}'.format(token)} ) reply = json.loads(resp.data.decode()) self.assertEqual(reply['message'], 'Product successfully added to Inventory!') self.assertEqual(resp.status_code, 201) resp = self.client.get( '/api/v1/products/2', headers={'Authorization': 'Bearer {}'.format(token)} ) reply = json.loads(resp.data.decode()) self.assertEqual(reply['message'], 'This product does not exist!') self.assertEqual(resp.status_code, 404)
[ "def test_cannot_sale_nonexistant_product(self):\n reply = self.admin_add_product()\n\n resp = self.admin_create_user()\n reply = self.attendant_login()\n token = reply['token']\n sale = dict(products = [\n {\n \"prod_name\":\"Paris_heels\", \n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tests that a user cannot view products from empty Inventory
def test_view_products_from_empty_inventory(self): resp = self.admin_register() reply = self.admin_login() token = reply['token'] resp = self.client.get( '/api/v1/products', headers={'Authorization': 'Bearer {}'.format(token)} ) reply = json.loads(resp.data.decode()) self.assertEqual(reply['message'], 'There are no products yet!') self.assertEqual(resp.status_code, 404)
[ "def test_admin_cannot_delete_product_from_empty_Inventory(self):\n resp = self.admin_register()\n reply = self.admin_login()\n token = reply['token']\n \n resp = self.client.delete(\n '/api/v1/products/1',\n content_type='application/json',\n head...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tests that a user cannot view a product with invalid id
def test_view_product_with_invalid_id(self): resp = self.admin_register() reply = self.admin_login() token = reply['token'] product = dict( prod_name='NY_denims', category='denims', stock=20, price=150 ) resp = self.client.post( '/api/v1/products', content_type='application/json', data=json.dumps(product), headers={'Authorization': 'Bearer {}'.format(token)} ) reply = json.loads(resp.data.decode()) self.assertEqual(reply['message'], 'Product successfully added to Inventory!') self.assertEqual(resp.status_code, 201) resp = self.client.get( '/api/v1/products/2kk', headers={'Authorization': 'Bearer {}'.format(token)} ) reply = json.loads(resp.data.decode()) self.assertEqual(reply['message'], 'Try an interger for product id') self.assertEqual(resp.status_code, 400)
[ "def test_wrong_products_id(self):\n\t\tresponse = self.client.get('/api/V1/products/a', content_type=\"application/json\")\n\t\tself.assertEqual(response.status_code,404)", "def test_detail_odd_product_id_permission(self):\n self.assertEqual(self.product_2.id, 2)\n\n token = Token.objects.create(us...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test that product cannot be updated successfully with blacklisted token
def test_cannot_update_product_with_blacklisted_token(self): resp = self.admin_register() reply = self.admin_login() token = reply['token'] product = dict( prod_name='NY_denims', category='denims', stock=20, price=150 ) resp = self.client.post( '/api/v1/products', content_type='application/json', data=json.dumps(product), headers={'Authorization': 'Bearer {}'.format(token)} ) reply = json.loads(resp.data.decode()) self.assertEqual(reply['message'], 'Product successfully added to Inventory!') self.assertEqual(resp.status_code, 201) resp = self.client.delete( '/api/v1/logout', headers={'Authorization': 'Bearer {}'.format(token)} ) reply = json.loads(resp.data.decode()) self.assertEqual(reply['message'], 'You are successfully logged out!') self.assertEqual(resp.status_code, 200) product_update = dict( prod_name='NY_jeans', category='denims', stock=50, price=180 ) resp = self.client.put( '/api/v1/products/1', content_type='application/json', data=json.dumps(product_update), headers={'Authorization': 'Bearer {}'.format(token)} ) reply = json.loads(resp.data.decode()) self.assertEqual(reply['message'], 'Invalid Authentication, Please Login!') self.assertEqual(resp.status_code, 401)
[ "def test_cannot_create_product_with_blacklisted_token(self):\n resp = self.admin_register()\n reply = self.admin_login()\n token = reply['token']\n\n resp = self.client.delete(\n '/api/v1/logout',\n headers={'Authorization': 'Bearer {}'.format(token)}\n )\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test that you cant updated a nonexistant product
def test_update_nonexistant_product(self): resp = self.admin_register() reply = self.admin_login() token = reply['token'] product_update = dict( prod_name='NY_jeans', category='denims', stock=50, price=180 ) resp = self.client.put( '/api/v1/products/1', content_type='application/json', data=json.dumps(product_update), headers={'Authorization': 'Bearer {}'.format(token)} ) reply = json.loads(resp.data.decode()) self.assertEqual(reply['message'], "This product doesn't exists in the Inventory!") self.assertEqual(resp.status_code, 400)
[ "def test_update_product_not_found(self):\n test_product = ProductFactory()\n resp = self.app.put(\n \"/products/0\",\n json=test_product.serialize(),\n content_type=\"application/json\")\n self.assertEqual(resp.status_code, status.HTTP_404_NOT_FOUND)", "def t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test that product cannot be updated with unauthorised user
def test_unauthorized_product_update(self): resp = self.admin_create_user() reply = self.attendant_login() token = reply['token'] product_update = dict( prod_name='NY_jeans', category='denims', stock=50, price=180 ) resp = self.client.put( '/api/v1/products/1', content_type='application/json', data=json.dumps(product_update), headers={'Authorization': 'Bearer {}'.format(token)} ) reply = json.loads(resp.data.decode()) self.assertEqual(reply['message'], 'Unauthorized Access!') self.assertEqual(resp.status_code, 401)
[ "def test_check_permission_update_not_owner(self):\n\n error_message = \"Authentication credentials were not provided.\"\n\n data = {\n \"item\": self.item_2.id,\n \"status\": \"SELL\",\n \"entry_quantity\": 700,\n \"price\": Decimal(\"3222.23\"),\n }...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test that product cannot be updated with empty fields
def test_update_product_with_empty_fields(self): resp = self.admin_register() reply = self.admin_login() token = reply['token'] product = dict( prod_name='NY_denims', category='denims', stock=20, price=150 ) resp = self.client.post( '/api/v1/products', content_type='application/json', data=json.dumps(product), headers={'Authorization': 'Bearer {}'.format(token)} ) reply = json.loads(resp.data.decode()) self.assertEqual(reply['message'], 'Product successfully added to Inventory!') self.assertEqual(resp.status_code, 201) product_update = dict( prod_name='', category='', stock=50, price=180 ) resp = self.client.put( '/api/v1/products/1', content_type='application/json', data=json.dumps(product_update), headers={'Authorization': 'Bearer {}'.format(token)} ) reply = json.loads(resp.data.decode()) self.assertEqual(reply['message'], 'prod_name and category cannot be empty!') self.assertEqual(resp.status_code, 400)
[ "def test_update_product_required_fields(self):\n data = {\n 'pk': 1,\n 'name': None,\n 'description': '''\n Yogurt also spelled yoghurt, yogourt or yoghourt,\n is a food produced by bacterial fermentation of milk.\n '''\n }\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test that admin can delete a product
def test_admin_delete_product(self): resp = self.admin_register() reply = self.admin_login() token = reply['token'] product = dict( prod_name='NY_denims', category='denims', stock=20, price=150 ) resp = self.client.post( '/api/v1/products', content_type='application/json', data=json.dumps(product), headers={'Authorization': 'Bearer {}'.format(token)} ) reply = json.loads(resp.data.decode()) self.assertEqual(reply['message'], 'Product successfully added to Inventory!') self.assertEqual(resp.status_code, 201) resp = self.client.delete( '/api/v1/products/1', content_type='application/json', headers={'Authorization': 'Bearer {}'.format(token)} ) reply = json.loads(resp.data.decode()) self.assertEqual(reply['message'], 'Product deleted!') self.assertEqual(resp.status_code, 200)
[ "def test_non_admin_cannot_delete_product(self):\n resp = self.admin_register()\n reply = self.admin_login()\n token = reply['token']\n product = dict(\n prod_name='NY_denims',\n category='denims',\n stock=20,\n price=150\n )\n re...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test that a non admin cannot delete a product
def test_non_admin_cannot_delete_product(self): resp = self.admin_register() reply = self.admin_login() token = reply['token'] product = dict( prod_name='NY_denims', category='denims', stock=20, price=150 ) resp = self.client.post( '/api/v1/products', content_type='application/json', data=json.dumps(product), headers={'Authorization': 'Bearer {}'.format(token)} ) reply = json.loads(resp.data.decode()) self.assertEqual(reply['message'], 'Product successfully added to Inventory!') self.assertEqual(resp.status_code, 201) resp = self.admin_create_user() reply = self.attendant_login() token = reply['token'] resp = self.client.delete( '/api/v1/products/1', content_type='application/json', headers={'Authorization': 'Bearer {}'.format(token)} ) reply = json.loads(resp.data.decode()) self.assertEqual(reply['message'], 'Unauthorized Access!') self.assertEqual(resp.status_code, 401)
[ "def test_admin_cannot_delete_nonexistant_product(self):\n resp = self.admin_register()\n reply = self.admin_login()\n token = reply['token']\n product = dict(\n prod_name='NY_denims',\n category='denims',\n stock=20,\n price=150\n )\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test that admin cannnot delete a product from empty Inventory
def test_admin_cannot_delete_product_from_empty_Inventory(self): resp = self.admin_register() reply = self.admin_login() token = reply['token'] resp = self.client.delete( '/api/v1/products/1', content_type='application/json', headers={'Authorization': 'Bearer {}'.format(token)} ) reply = json.loads(resp.data.decode()) self.assertEqual(reply['message'], 'There are no products in Inventory!') self.assertEqual(resp.status_code, 404)
[ "def test_admin_cannot_delete_nonexistant_product(self):\n resp = self.admin_register()\n reply = self.admin_login()\n token = reply['token']\n product = dict(\n prod_name='NY_denims',\n category='denims',\n stock=20,\n price=150\n )\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test that admin cannnot delete a nonexistant product
def test_admin_cannot_delete_nonexistant_product(self): resp = self.admin_register() reply = self.admin_login() token = reply['token'] product = dict( prod_name='NY_denims', category='denims', stock=20, price=150 ) resp = self.client.post( '/api/v1/products', content_type='application/json', data=json.dumps(product), headers={'Authorization': 'Bearer {}'.format(token)} ) reply = json.loads(resp.data.decode()) self.assertEqual(reply['message'], 'Product successfully added to Inventory!') self.assertEqual(resp.status_code, 201) resp = self.client.delete( '/api/v1/products/2', content_type='application/json', headers={'Authorization': 'Bearer {}'.format(token)} ) reply = json.loads(resp.data.decode()) self.assertEqual(reply['message'], 'This product does not exist in Inventory!') self.assertEqual(resp.status_code, 404)
[ "def test_non_admin_cannot_delete_product(self):\n resp = self.admin_register()\n reply = self.admin_login()\n token = reply['token']\n product = dict(\n prod_name='NY_denims',\n category='denims',\n stock=20,\n price=150\n )\n re...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test ComBat feature harmonization.
def test_combat(): # Check if example data directory exists example_data_dir = th.find_exampledatadir() # Check if example data required exists features = glob.glob(os.path.join(example_data_dir, 'examplefeatures_Patient*.hdf5')) if len(features) < 7: message = 'Too few example features for ComBat testing not found! ' +\ 'Run the create_example_data script from the WORC exampledata ' +\ 'directory!' raise WORCValueError(message) elif len(features) > 7: message = 'Too many example features for ComBat testing not found! ' +\ 'Run the create_example_data script from the WORC exampledata ' +\ 'directory!' raise WORCValueError(message) objectlabels = os.path.join(example_data_dir, 'objectlabels.csv') # Python config = os.path.join(example_data_dir, 'ComBatConfig_python.ini') features_train_out = [f.replace('examplefeatures_', 'examplefeatures_ComBat_python_') for f in features] # First run synthetic test # Synthetictest() # # Run the Combat function: only for training # ComBat(features_train_in=features, # labels_train=objectlabels, # config=config, # features_train_out=features_train_out) # # Run the Combat function: now for train + testing ComBat(features_train_in=features[0:4], labels_train=objectlabels, config=config, features_train_out=features_train_out[0:4], features_test_in=features[4:], labels_test=objectlabels, features_test_out=features_train_out[4:]) # # Matlab # config = os.path.join(example_data_dir, 'ComBatConfig_matlab.ini') # features_train_out = [f.replace('examplefeatures_', 'examplefeatures_ComBat_matlab_') for f in features] # # # # Run the Combat function: only for training # ComBat(features_train_in=features, # labels_train=objectlabels, # config=config, # features_train_out=features_train_out) # # # Run the Combat function: now for train + testing # ComBat(features_train_in=features[0:4], # labels_train=objectlabels, # config=config, # features_train_out=features_train_out[0:4], # features_test_in=features[4:], # labels_test=objectlabels, # features_test_out=features_train_out[4:]) # Remove the feature files # for i in glob.glob(os.path.join(example_data_dir, '*features_ComBat*.hdf5')): # os.remove(i)
[ "def test_single_feature_label():\n pass", "def test_workbench_scenarios(self):\n result_title = 'Adaptive Numeric Input XBlock'\n basic_scenario = \"<adaptivenumericinput />\"\n test_result = self.xblock.workbench_scenarios()\n self.assertEquals(result_title, test_result[0][0])\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns true for all hostclasses which aren't tagged as nonZDD hostclasses
def is_deployable(self, hostclass): return ((hostclass in self._hostclasses and is_truthy(self._hostclasses[hostclass].get("deployable"))) or hostclass not in self._hostclasses)
[ "def IsNoHost(self):\n if self.no_host:\n return True\n return any([node.no_host for node in self.GetAncestorGroups()])", "def is_opaque(self, classobj):\n try:\n return self.instance_vars[classobj] == []\n except KeyError:\n return False", "def has_ghosts(self):\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the integration test for this hostclass, or None if none exists
def get_integration_test(self, hostclass): return (hostclass in self._hostclasses and self._hostclasses[hostclass].get("integration_test")) or None
[ "def current_test(self) -> IUTest:\n if self._running_test is not None and self._running_test < len(self._tests):\n return self._tests[self._running_test]\n return None", "def get_test(self,test_id):\n for test in self.suite.get_tests():\n if test.id == test_id:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Promote AMI to specified stage. And, conditionally, make executable by production account if ami is staged as tested.
def _promote_ami(self, ami, stage): prod_baker = self._disco_bake.option("prod_baker") promote_conditions = [ stage == "tested", prod_baker, ami.tags.get("baker") == prod_baker, ] try: self._disco_bake.promote_ami(ami, stage) if all(promote_conditions): self._disco_bake.promote_ami_to_production(ami) except: logging.exception("promotion failed")
[ "def _execute_stage(self, stage):\n new_retcode = {\n 'init': self.__preconfigure,\n 'lock': self.__get_lock,\n 'configure': self.core.plugins_configure,\n 'prepare': self.core.plugins_prepare_test,\n 'start': self.core.plugins_start_test,\n '...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Line is correctlt split and missing/corrupetd fields are checked.
def test_read_line(self): expected_data = ['\"lu, jr\"','ming-yuan','\"DRUG,1\"',135.999,True,3] input_string = '001,\"LU, JR\",MING-YUAN,\"DRUG,1\",135.999\n' data = read_line(input_string) self.assertEqual(expected_data[0],data[0]) self.assertEqual(expected_data[1],data[1]) self.assertEqual(expected_data[2],data[2]) self.assertAlmostEqual(expected_data[3],data[3]) self.assertEqual(expected_data[4],data[4]) self.assertAlmostEqual(expected_data[5],data[5]) #Check for odd numers of quotation marks input_string = '001,\"LU\",\"MING-YUAN,DRUG1,135\n' data = read_line(input_string) self.assertFalse(data[4]) #Check for missing fields input_string = '001,,MING-YUAN,DRUG1,135\n' data = read_line(input_string) self.assertFalse(data[4]) input_string = '001,LU,MING-YUAN,DRUG1,\n' data = read_line(input_string) self.assertFalse(data[4]) #Check for corrupted fields input_string = '001x,LU,MING-YUAN,DRUG1,135\n' data = read_line(input_string) self.assertFalse(data[4]) input_string = '001,LU,MING-YUAN,DRUG1,1ag5\n' data = read_line(input_string) self.assertFalse(data[4])
[ "def check_record(idline,nclline,sepline,qualiline):\n return check_idline(idline) and check_sepline(sepline)", "def check_separation(self, line):\n # Raising an error, in case the passed object is not a string or not the separation string\n if not isinstance(line, str):\n raise TypeEr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Unique drug list dict is correctly returned.
def test_get_unique_drug_list(self): dict1 = self.test_dict dict2 = get_unique_drug_list(self.test_sorted_tuple) self.assertEqual(dict1, dict2)
[ "def _make_data_unique(collected_data: List[Dict]) -> List[Dict]:\n return list(dict(x) for x in set(tuple(x.items()) for x in collected_data))", "def unique_drugs(self):\n if self.results is not None:\n return tuple(self.results['drug'].unique())", "def get_drugs(drug_ind_lst, ind2drug...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Total cost of each drug is correct.
def test_get_total_cost_each_drug(self): list1 = self.test_total_cost_each_drug list2 = get_total_cost_each_drug(self.test_sorted_tuple, self.test_dict) self.assertEqual(list1, list2)
[ "def cost(self) -> float:", "def total_cost(self):\n return sum(partial_solution.cost for partial_solution in self)", "def totalpartcost(self):\n cost = 0.0\n for (element, myvendor, qty, price) in self.data:\n cost += qty * price\n return cost", "def totalordercost(self...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Checks if a string is a permutation of a palindrome by populating a map and counting the occurrences of letters. O(N)
def is_palindrome_permutation(string): letter_to_count = dict() for letter in string: letter_to_count[letter] = letter_to_count.get(letter, 0) + 1 residual = 0 for count in letter_to_count.values(): residual += count % 2 # there are can be a single letter with an odd character count when the palindrome is of odd length return residual <= 1
[ "def check_palindrome_permutation(string: str) -> bool:\n\n string = string.lower()\n\n char_counter = defaultdict(int)\n for char in string:\n count = char_counter[char]\n if count:\n char_counter[char] -= 1\n else:\n char_counter[char] += 1\n\n return sum(cha...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Compute the cycle consistenty loss. L_cyc = lamA [Expectation of L1_norm(F(G(A)) A)] + lamb [Expectation of L1_norm(G(F(B)) B)]
def __cycle_consistency_loss(self, reconstructedA, reconstructedB): loss = self.opt.lamA * tf.reduce_mean(tf.abs(reconstructedA - self.realA)) + \ self.opt.lamB * tf.reduce_mean(tf.abs(reconstructedB - self.realB)) return loss
[ "def directed_cycle_score(A):\n\n # Implement your cycle score given Problem 4 Part 2\n temp_matrix = np.zeros(A.shape)\n alpha = 0.05\n k = 0\n summation_term = 999999\n num_terms = A.shape[0]\n # while change < 0.05:\n for i in range(num_terms):\n summation_term = (1 / np.math.facto...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Compute the identity loss. L_idt = lamda_idt [lamA [Expectation of L1_norm(F(A) A)] + lamB [Expectation of L1_norm(G(B) B)]]
def __identity_loss(self, identA, identB): loss = self.opt.lambda_ident * (self.opt.lamA * tf.reduce_mean(tf.abs(identB - self.realA)) + \ self.opt.lamB * tf.reduce_mean(tf.abs(identA - self.realB))) return loss
[ "def l1_loss(D, G, real_data, generated_data, losses, options):\n return torch.nn.L1Loss()(generated_data, real_data)", "def one_step(i_t, h_tm1):\n h_t = self.activation(T.dot(i_t, self.W) + T.dot(h_tm1, self.W_rec) + self.b)\n return h_t", "def l1_loss(obs, actual):\n # (tf.Tenso...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Parses a tensorflow.SequenceExample into an image and caption.
def parse_sequence_example(serialized, image_id, image_feature, caption_feature): context, sequence = tf.parse_single_sequence_example( serialized, context_features={ image_id : tf.FixedLenFeature([], dtype=tf.int64), image_feature: tf.FixedLenFeature([], dtype=tf.string) }, sequence_features={ caption_feature: tf.FixedLenSequenceFeature([], dtype=tf.int64), }) encoded_image_id = context[image_id] encoded_image = context[image_feature] caption = sequence[caption_feature] return encoded_image_id, encoded_image, caption
[ "def parse_sequence_example(serialized, image_feature, caption_feature):\n context, sequence = tf.parse_single_sequence_example(\n serialized,\n context_features={\n image_feature: tf.FixedLenFeature([], dtype=tf.string)\n },\n sequence_features={\n caption_featu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Run demo, testing whether input words are beer related.
def run_demo(): while True: embeddings = beer_emb.embed_doc(input("Test if words are beer-related: "), word_filter=False) for word_vec in embeddings: print(is_beer_related(word_vec))
[ "def test_run():\r\n print(count_words(\"cat bat mat cat bat cat\", 3))\r\n print(count_words(\"betty bought a bit of butter but the butter was bitter\", 3))", "def test_demo_runs(self):\n self.star.run_demo()", "def test_run():\n print count_words(\"cat bat mat cat bat cat\", 3)\n print coun...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Load parsed beautifulsoup object holding the full html
def load_parsed(self): with open(self.fname) as f: self.parsed = BeautifulSoup(f.read(), features="html.parser")
[ "def load_website(self):\n# r = urllib.request.urlopen(self.url).read()\n r = requests.get(self.url).content \n self.soup = bs(r, \"lxml\")", "def parse(html):\n\n return BeautifulSoup(html, 'html.parser')", "def update_html(self):\n self.html = self.driver.page_source\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Iterator over maintext paragraph elements; this includes footnotes.
def _paragraphs_raw(self): for par in self.parsed.find_all("p")[self.PAR_START:]: yield par
[ "def linked_text_paragraphs(self):\n for par in self._main_paragraphs_raw():\n par_links = par.find_all('a')\n if len(par_links) == 0:\n self.main_count += len(par.text)\n yield par.text\n else:\n for el in par.contents:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Checks whether an element contains footnote text.
def is_footnote_text(self, par): return (par is not None) and ("foot" in par.attrs.get("class", []))
[ "def is_footnote(self, par):\n if par.find_next_sibling('p') is None:\n return False\n return self.is_footnote_text(par) or self.is_footnote_link(par)", "def is_footnote_link(self, par):\n return self.is_footnote_text(par.find_next_sibling('p'))", "def is_footnote(self):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Checks whether an element is a link adjacent to footnote text.
def is_footnote_link(self, par): return self.is_footnote_text(par.find_next_sibling('p'))
[ "def is_footnote(self, par):\n if par.find_next_sibling('p') is None:\n return False\n return self.is_footnote_text(par) or self.is_footnote_link(par)", "def is_link(fragment):\n return (isinstance(fragment, scrapely.htmlpage.HtmlTag) and\n fragment.tag == 'a' and\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Checks whether a paragraph element is part of a footnote.
def is_footnote(self, par): if par.find_next_sibling('p') is None: return False return self.is_footnote_text(par) or self.is_footnote_link(par)
[ "def is_footnote_text(self, par):\n return (par is not None) and (\"foot\" in par.attrs.get(\"class\", []))", "def is_footnote_link(self, par):\n return self.is_footnote_text(par.find_next_sibling('p'))", "def is_footnote(self):\n return self.style['float'] == 'footnote'", "def is_footnot...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Walk over pararaphs in the main text. If a footnote link is found, jump to that paragraph, then back to the main text.
def linked_text_paragraphs(self): for par in self._main_paragraphs_raw(): par_links = par.find_all('a') if len(par_links) == 0: self.main_count += len(par.text) yield par.text else: for el in par.contents: if el.name is None: #this is plain text self.main_count += len(str(el)) yield str(el) elif el.name == "a" and "href" in el.attrs: id = el["href"].lstrip('#') try: foot_par = self._get_footnote_par(id) except NoFootnoteError: self.log(f"Could not find footnote for {id}, skipping.") self.footnote_count += len(foot_par.text) yield foot_par.text
[ "def is_footnote_link(self, par):\n return self.is_footnote_text(par.find_next_sibling('p'))", "def test_forward_paragraph(self):\n before_b = \"\"\"\\\n Americans live in the most severe weather-prone country on Earth. Each year,\n Americans cope with an average of 10,000 thunderstorms, 2,500...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Material saver. Saves material and their properties the JSON file for type building elements. If the Project parent is set, it automatically saves it to the file given in Project.data. Alternatively you can specify a path to a file with Materials. If this file does not exist, a new file is created.
def save_material(material, data_class): data_class.material_bind["version"] = "0.7" add_to_json = True warning_text = ("Material with same name and same properties already " "exists in JSON, consider this material or revising your " "properties") for id, check in data_class.material_bind.items(): if id != "version": if check["name"] == material.name and \ check["density"] == material.density and \ check["thermal_conduc"] == material.thermal_conduc and \ check["heat_capac"] == material.heat_capac and \ check[ "thickness_default"] == material.thickness_default and \ check["thickness_list"] == material.thickness_list: warnings.warn(warning_text) print(material.name) add_to_json = False break if add_to_json is True: data_class.material_bind[ material.material_id] = collections.OrderedDict() data_class.material_bind[ material.material_id]["name"] = material.name data_class.material_bind[ material.material_id]["density"] = material.density data_class.material_bind[ material.material_id]["thermal_conduc"] = material.thermal_conduc data_class.material_bind[ material.material_id]["heat_capac"] = material.heat_capac data_class.material_bind[ material.material_id][ "thickness_default"] = material.thickness_default data_class.material_bind[ material.material_id]["thickness_list"] = material.thickness_list data_class.material_bind[ material.material_id]["solar_absorp"] = material.solar_absorp with open(utilities.get_full_path(data_class.path_mat), 'w') as file: file.write(json.dumps( data_class.material_bind, indent=4, separators=(',', ': ')))
[ "def save_materials_properties(read_dir, saving_name='Materials_info'):\n info_df = get_materials_properties(read_dir)\n save_this(\n info_df,\n read_dir,\n saving_name,\n authorized=True,\n save_type='csv',\n save_index=False)\n # print('**SAVED**')\n # print(f...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a new Settings, reading from a default location for the given domain (~/Library/Preferences/%s.plist).
def __init__(self, domain='com.markfickett.gors'): settingsDir = os.path.expanduser(self.__SETTINGS_DIR) if not os.path.isdir(settingsDir): os.makedirs(settingsDir) self.__settingsFileName = os.path.join(settingsDir, domain + '.plist') if os.path.isfile(self.__settingsFileName): self.__settings = plistlib.readPlist( self.__settingsFileName) else: self.clear() self.__currentGroupNames = []
[ "def create(domain: str) -> None:\n explain_step(f\"Creating default configuration file for website {domain}\")\n run_command(\n f\"webserver genconf -q {domain} | sudo tee /etc/webserver/conf.d/{domain}.conf > /dev/null\"\n )", "def load_settings(runcard: dict) -> Settings:\n return Settings(*...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the full name of the given keyName under the current group. If extant is True, only return extant keys; otherwise return None.
def __getKey(self, keyNameRaw, extant=True): fullKeyName = self.__DELIMITER.join( self.__currentGroupNames + [str(keyNameRaw)]) if extant and (fullKeyName not in self.__settings): return None return fullKeyName
[ "def extract_key_name(self):\n # quick and dirty regex parsing..\n # consider using gnupg.\n _, out, _ = self.as_user('/usr/bin/gpg --list-keys')\n patterns = [\n 'pub\\s+.*?uid\\s+debrepo.*?sub\\s+\\w+/(\\w+)\\s+[\\w-]+$',\n '^pub.*?\\n\\s+(.*?)\\nuid',\n ]\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function gets the total occurrences of words and syllables in the original Unicode Garshana corpus. To do this, it opens a .csv file with utf16 encoding, and splits on commans, expecting the line of sumerian text to be in the 8th column. Filters annotations from each line, and tracks the occurrence of each word and syllable. All combinations of unigrams, bigrams, and trigrams are treated as individual syllables.
def get_counts(data): word_count = {} syll_count = {} infile = data.corpus try: open_file = codecs.open(infile, 'r', encoding='utf-16') for line in open_file: line = line.lower() # Remove tablet indexing info and line numbers. Grab only text data line = line.split(',') text = clean_line(line[7]) # Update the occurrences of the words in the line for word in text.split(): count = word_count.setdefault(word, 0) word_count[word] = count + 1 # Track occurrences of syllables update_syllable_count(word, syll_count) open_file.close() except IOError: print("Cannot open: " + infile) return (word_count, syll_count)
[ "def total_syllables(target_text):\n\n splited_text = target_text.split()\n count = 0\n for word in splited_text:\n count = count + word_syllables(word)\n return count", "def get_analyze_per_file(self):\n \"\"\"Exclude tags, exclude binary (img), count words without non literal character...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the accounting period that is currently valid. Valid is an accounting_period when the current date lies between begin and end of the accounting_period
def get_current_valid_accounting_period(): current_valid_accounting_period = None for accounting_period in AccountingPeriod.objects.all(): if accounting_period.begin < date.today() and accounting_period.end > date.today(): return accounting_period if not current_valid_accounting_period: raise AccountingPeriodNotFound()
[ "def getCurrentValidAccountingPeriod():\n currentValidAccountingPeriod = None\n for accountingPeriod in AccountingPeriod.objects.all():\n if accountingPeriod.begin < date.today() and accountingPeriod.end > date.today():\n return accountingPeriod\n if currentValidAccoun...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Transform mp3 file into wav format calling bash and using mpg123 or ffmpeg.
def mp3_to_wav(mp3_file, wav_file, encoder='mpg123'): if encoder == 'mpg123': bash_command = ['mpg123', '-w', wav_file, '--mono', mp3_file] else: bash_command = ['ffmpeg', '-i', mp3_file, wav_file] subprocess.run(bash_command)
[ "def mp3_to_wav(input):\n sound = AudioSegment.from_file(input, format='mp3')\n sound.export(name_wav(input), format='wav')\n print(name_wav(input))", "def wav_to_mp3(input):\n sound = AudioSegment.from_file(input, format='wav')\n sound.export(name_mp3(input), format='mp3')", "def ogg2wav(oggfile...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Limit arrays of frequency and features by maximum frequency and bottom frequency.
def limit_by_freq(freq, features, upper_limit, lower_limit=None): # Copy into arrays, in order to apply mask freq = np.array(freq, dtype=np.float) features = np.array(features, dtype=np.float) # Mask for bottom limit if lower_limit is not None: bottom_mask = freq >= lower_limit features = features[bottom_mask] freq = freq[bottom_mask] # Mask for upper limit upper_mask = freq <= upper_limit features = features[upper_mask] freq = freq[upper_mask] return freq, features
[ "def findMaximal(freqSet):", "def max_filter(counts, filter_size):\n return maximum_filter(counts, size=(filter_size, 1),\n mode='reflect', origin=(filter_size - 1)//2)", "def truncate(data,mask,freq,minfreq,maxfreq):\n new_data = []\n new_freq = []\n new_mask = []\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check if song is already transformed into temp.
def check_wav(song, source_folder, temp_folder, encoder='mpg123'): # Name of files song_name, extension = os.path.splitext(song) mp3_file = os.path.join(source_folder, song) if '.wav' != extension: wav_file = os.path.join(temp_folder, song_name + '.wav') try: if not os.path.isfile(wav_file): mp3_to_wav( mp3_file=mp3_file, wav_file=wav_file, encoder=encoder) else: pass except MemoryError: logger.error('MemoryError: %s MP3 couldn\'t be transformed into WAV', song_name) else: # Already a wav file copyfile(mp3_file, os.path.join(temp_folder, song_name))
[ "def check_exists(music_file, raw_song, meta_tags):\n log.debug('Cleaning any temp files and checking '\n 'if \"{}\" already exists'.format(music_file))\n songs = os.listdir(const.args.folder)\n for song in songs:\n if song.endswith('.temp'):\n os.remove(os.path.join(const.ar...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the free space in Gigabits.
def get_free_gb(): mem_info = get_mem_info() free_gb = float(mem_info['MemAvailable'].value) / 10**6 return free_gb
[ "def free_space(self):\n if not self.partitions:\n free = self.size - self.partition_start\n else:\n free = self.size - self.current_usage\n\n if self.type == GPT:\n free -= Size(GPT_BACKUP_SIZE)\n else:\n free -= Size(1)\n\n log.debug('...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
True if it can't run, else otherwise. Condition is Gb of RAM memory available.
def ram_condition(min_gb=3): return get_free_gb() < min_gb
[ "def check_if_sufficient_memory():\n percent_memory = psutil.virtual_memory().percent\n if percent_memory > 75:\n raise ValueError('Please use a device with more CPU ram or a smaller dataset')", "def memory_check(self) -> bool:\n available_bytes = psutil.virtual_memory().available\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The camera that took the image
def camera(self): return self.__camera
[ "def camera(self):\r\n return self.__camera", "def camera(self):\n return self._camera", "def get_camera(self):\n return self._camera", "def query_camera(self):\n ok, orig_pic = self.vs.read() # Read video stream\n if ok: # If no errors\n orig_pic = imutils.rota...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
r""" Property for the exterior orientation parameters
def exteriorOrientationParameters(self): return self.__exteriorOrientationParameters
[ "def exteriorOrientationParameters(self):\r\n return self.__exteriorOrientationParameters", "def orient(self):\n return self.__ph.get('orient', PH_ORIENT_HORZ)", "def orientation(self, v=None):\n if v is None:\n v = self._DEFAULT_ORIENTATION\n if isinstance(v, ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The rotation matrix of the image Relates to the exterior orientation
def rotationMatrix(self): R = Compute3DRotationMatrix(self.exteriorOrientationParameters[3], self.exteriorOrientationParameters[4], self.exteriorOrientationParameters[5]) return R
[ "def rotation_matrix(self):\n return self.affine_matrix[0:3][:, 0:3]", "def rotation(self):\n\t\treturn self.piv.a.rotate.v", "def matrix(self):\n return self._rotation", "def get_rotation_as_rotation_mat(self):\n return self._rotation_mat", "def rotation(self):\n return self.tra...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
r""" Compute inner orientation parameters
def ComputeInnerOrientation(self, imagePoints): # implementing observation vectors imagePoints = imagePoints.reshape(np.size(imagePoints), 1) fMarks = self.camera.fiducialMarks.reshape(np.size(self.camera.fiducialMarks), 1) n = int(len(imagePoints)) # number of observations u = 6 # 6 orientation parameters A = np.zeros((n, u)) # A matrix (n,u) j = 0 for i in range(len(imagePoints)): if i % 2 == 0: A[i, 0] = 1; A[i, 1] = 0; A[i, 2] = fMarks[j]; A[i, 3] = fMarks[j + 1]; A[i, 4] = 0 A[i, 5] = 0 else: A[i, 0] = 0; A[i, 1] = 1; A[i, 2] = 0; A[i, 3] = 0; A[i, 4] = fMarks[j]; A[i, 5] = fMarks[j + 1] j += 2 X = np.dot(la.inv(np.dot(np.transpose(A), A)), np.dot(np.transpose(A), imagePoints)) v = np.dot(A, X) - imagePoints adjustment_results = {"params": X, "residuals": v, "N": np.dot(np.transpose(A), A)} self.__innerOrientationParameters = X # updating the inner orientation params return adjustment_results
[ "def ComputeInverseInnerOrientation(self):\r\n inner = self.__innerOrientationParameters\r\n matrix = np.array([[inner['a1'], inner['a2']], [inner['b1'], inner['b2']]])\r\n # inverse matrix\r\n inv_matrix = np.linalg.inv(matrix)\r\n return {'a0*': -inner['a0'], 'a1*': inv_matrix[0...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Computes the geometric inner orientation parameters
def ComputeGeometricParameters(self): # extracting inner orientation params a0 = self.innerOrientationParameters[0] b0 = self.innerOrientationParameters[1] a1 = self.innerOrientationParameters[2] a2 = self.innerOrientationParameters[3] b1 = self.innerOrientationParameters[4] b2 = self.innerOrientationParameters[5] # computing algebric params tx = a0; ty = b0 theta = np.arctan(b1 / b2) gamma = np.arctan((a1 * np.sin(theta) + a2 * np.cos(theta)) / (b1 * np.sin(theta) + b2 * np.cos(theta))) sx = a1 * np.cos(theta) - a2 * np.sin(theta) sy = (a1 * np.sin(theta) + a2 * np.cos(theta)) / np.sin(gamma) return {"translationX": tx, "translationY": ty, "rotationAngle": np.rad2deg(theta), "scaleFactorX": sx, "scaleFactorY": sy, "shearAngle": np.rad2deg(gamma)}
[ "def ComputeGeometricParameters(self):\r\n # algebraic inner orinetation paramters\r\n x = self.__innerOrientationParameters\r\n tx = x['a0']\r\n ty = x['b0']\r\n tetha = np.arctan((x['b1'] / x['b2']))\r\n gamma = np.arctan((x['a1'] * np.sin(tetha) + x['a2'] * np.cos(tetha)...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Computes the parameters of the inverse inner orientation transformation
def ComputeInverseInnerOrientation(self): a0 = self.innerOrientationParameters[0] b0 = self.innerOrientationParameters[1] a1 = self.innerOrientationParameters[2] a2 = self.innerOrientationParameters[3] b1 = self.innerOrientationParameters[4] b2 = self.innerOrientationParameters[5] mat = np.array([[a1[0], a2[0]], [b1[0], b2[0]]]) mat = la.inv(mat) return np.array([a0[0], b0[0], mat[0, 0], mat[0, 1], mat[1, 0], mat[1, 1]]).T
[ "def ComputeInverseInnerOrientation(self):\r\n inner = self.__innerOrientationParameters\r\n matrix = np.array([[inner['a1'], inner['a2']], [inner['b1'], inner['b2']]])\r\n # inverse matrix\r\n inv_matrix = np.linalg.inv(matrix)\r\n return {'a0*': -inner['a0'], 'a1*': inv_matrix[0...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Transforms camera points to image points
def CameraToImage(self, cameraPoints): # setting up the required matrices a0 = self.innerOrientationParameters[0] b0 = self.innerOrientationParameters[1] a1 = self.innerOrientationParameters[2] a2 = self.innerOrientationParameters[3] b1 = self.innerOrientationParameters[4] b2 = self.innerOrientationParameters[5] if np.isscalar(a0): R = np.array([[a1, a2], [b1, b2]]) T = np.array([[a0], [b0]]) else: R = np.array([[a1[0], a2[0]], [b1[0], b2[0]]]) T = np.array([[a0[0]], [b0[0]]]) cameraPoints = cameraPoints.T # computing the transformation to the image system return (T + np.dot(R, cameraPoints)).T
[ "def CameraToImage(self, cameraPoints):\r\n # get algebric parameters\r\n inner = self.__innerOrientationParameters\r\n\r\n imgPoints = np.zeros((len(cameraPoints[:, 0]), 2))\r\n for i in range(len(cameraPoints[:, 0])):\r\n imgPoints[i, 0] = inner['a0'] + inner['a1'] * cameraP...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Compute exterior orientation parameters. This function can be used in conjecture with ``self.__ComputeDesignMatrix(groundPoints)`` and ``self__ComputeObservationVector(imagePoints)``
def ComputeExteriorOrientation(self, imagePoints, groundPoints, epsilon): # cameraPoints = self.ImageToCamera(imagePoints) cameraPoints = imagePoints self.__ComputeApproximateVals(cameraPoints, groundPoints) l0 = self.__ComputeObservationVector(groundPoints.T) l0 = np.reshape(l0, (-1, 1)) l = cameraPoints.reshape(np.size(cameraPoints), 1) - l0 A = self.__ComputeDesignMatrix(groundPoints.T) N = np.dot(A.T, A) u = np.dot(A.T, l) deltaX = np.dot(la.inv(N), u) # update orientation pars self.__exteriorOrientationParameters = np.add(self.__exteriorOrientationParameters, np.reshape(deltaX, 6)) while la.norm(deltaX) > epsilon: l0 = self.__ComputeObservationVector(groundPoints.T) l0 = np.reshape(l0, (-1, 1)) l = cameraPoints.reshape(np.size(cameraPoints), 1) - l0 A = self.__ComputeDesignMatrix(groundPoints.T) N = np.dot(A.T, A) u = np.dot(A.T, l) deltaX = np.dot(la.inv(N), u) # update orientation pars self.__exteriorOrientationParameters = np.add(self.__exteriorOrientationParameters, np.reshape(deltaX, 6)) # compute residuals l_a = np.reshape(self.__ComputeObservationVector(groundPoints.T), (-1, 1)) v = l_a - cameraPoints.reshape(np.size(cameraPoints), 1) if (np.size(A, 0) - np.size(deltaX)) != 0: sig = np.dot(v.T, v) / (np.size(A, 0) - np.size(deltaX)) sigmaX = sig[0] * la.inv(N) else: sigmaX = None return [self.exteriorOrientationParameters, sigmaX, v]
[ "def ComputeExteriorOrientation(self, imagePoints, groundPoints, epsilon):\r\n # compute control points in camera system using the inner orientation\r\n camera_points = self.ImageToCamera(imagePoints)\r\n\r\n # compute approximate values for exteriror orientation using conformic transformation\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Transforming ground points to image points
def GroundToImage(self, groundPoints): X0 = float(self.exteriorOrientationParameters[0]) Y0 = float(self.exteriorOrientationParameters[1]) Z0 = float(self.exteriorOrientationParameters[2]) xp = float(self.camera.principalPoint[0]) yp = float(self.camera.principalPoint[1]) R = self.rotationMatrix r11 = float(R[0, 0]) r12 = float(R[0, 1]) r13 = float(R[0, 2]) r21 = float(R[1, 0]) r22 = float(R[1, 1]) r23 = float(R[1, 2]) r31 = float(R[2, 0]) r32 = float(R[2, 1]) r33 = float(R[2, 2]) f = self.camera.focalLength camPoints = [] for i in range(groundPoints.shape[0]): x = xp - (f) * (((r11 * (groundPoints[i, 0] - X0) + r21 * (groundPoints[i, 1] - Y0) + r31 * ( groundPoints[i, 2] - Z0)) / (r13 * (groundPoints[i, 0] - X0) + r23 * ( groundPoints[i, 1] - Y0) + r33 * (groundPoints[i, 2] - Z0)))) y = yp - (f) * (((r12 * (groundPoints[i, 0] - X0) + r22 * (groundPoints[i, 1] - Y0) + r32 * ( groundPoints[i, 2] - Z0)) / (r13 * (groundPoints[i, 0] - X0) + r23 * ( groundPoints[i, 1] - Y0) + r33 * (groundPoints[i, 2] - Z0)))) camPoints.append([x, y]) # return self.CameraToImage(np.array(camPoints)) return (np.array(camPoints))
[ "def GroundToImage(self, groundPoints):\r\n X0_1 = self.exteriorOrientationParameters[0]\r\n Y0_1 = self.exteriorOrientationParameters[1]\r\n Z0_1 = self.exteriorOrientationParameters[2]\r\n O1 = np.array([X0_1, Y0_1, Z0_1]).T\r\n R1 = self.RotationMatrix\r\n x1 = np.zeros(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Transforming ground points to image points
def GroundToImage_RzRyRz(self, groundPoints): X0 = float(self.exteriorOrientationParameters[0]) Y0 = float(self.exteriorOrientationParameters[1]) Z0 = float(self.exteriorOrientationParameters[2]) xp = float(self.camera.principalPoint[0]) yp = float(self.camera.principalPoint[1]) R = self.rotationMatrix_RzRyRz r11 = float(R[0, 0]) r12 = float(R[0, 1]) r13 = float(R[0, 2]) r21 = float(R[1, 0]) r22 = float(R[1, 1]) r23 = float(R[1, 2]) r31 = float(R[2, 0]) r32 = float(R[2, 1]) r33 = float(R[2, 2]) f = self.camera.focalLength camPoints = [] for i in range(groundPoints.shape[0]): x = xp - (f) * (((r11 * (groundPoints[i, 0] - X0) + r21 * (groundPoints[i, 1] - Y0) + r31 * ( groundPoints[i, 2] - Z0)) / (r13 * (groundPoints[i, 0] - X0) + r23 * ( groundPoints[i, 1] - Y0) + r33 * (groundPoints[i, 2] - Z0)))) y = yp - (f) * (((r12 * (groundPoints[i, 0] - X0) + r22 * (groundPoints[i, 1] - Y0) + r32 * ( groundPoints[i, 2] - Z0)) / (r13 * (groundPoints[i, 0] - X0) + r23 * ( groundPoints[i, 1] - Y0) + r33 * (groundPoints[i, 2] - Z0)))) camPoints.append([x, y]) # return self.CameraToImage(np.array(camPoints)) return (np.array(camPoints))
[ "def GroundToImage(self, groundPoints):\r\n X0_1 = self.exteriorOrientationParameters[0]\r\n Y0_1 = self.exteriorOrientationParameters[1]\r\n Z0_1 = self.exteriorOrientationParameters[2]\r\n O1 = np.array([X0_1, Y0_1, Z0_1]).T\r\n R1 = self.RotationMatrix\r\n x1 = np.zeros(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Transforms Image point to a Ray in world system
def ImageToRay(self, imagePoints): pass # delete after implementations
[ "def _cast_ray(self, point):\n\n ray_direction_cam_frame = self.K_inv @ np.hstack([point[0], point[1], 1])\n point_on_image_plane_world_frame = self.C2W @ np.hstack([ray_direction_cam_frame, 1])\n point_on_image_plane_world_frame = point_on_image_plane_world_frame / point_on_image_plane_world_f...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generating grid of points biased by ppa (principal point delta)
def GeneratePointsImg(self, n, ppa): x = np.linspace(0,self.camera.sensorSize,n)+ppa[0] y = np.linspace(0,self.camera.sensorSize,n)+ppa[1] return np.meshgrid(x, y)
[ "def sample_pareto_from_isometric_normal(\n n_points, dimension, center, random_state\n ):\n X = random_state.randn(n_points, dimension)\n Y = pareto_front(X)\n return X + center, Y", "def _generate_p(self):\n self._values, weights = zip(*self._weights.ite...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Description When is given a directory name that exist Expected Result Shows log that directory was found
def test_has_directory_log(self, check_fn_true, caplog): #setup records = caplog.records has_directory = extractor.make_has_directory(os.path.isdir) directory_path = "./data/observed" #when test1 = has_directory(directory_path) #result assert len(records) == 1 assert records[0].message == f"It was found directory {directory_path}"
[ "def test_doesnt_have_directory_log(self, check_fn_false, caplog):\n\n #setup\n records = caplog.records\n has_directory = extractor.make_has_directory(os.path.isdir)\n directory_path = \"./data/tests\"\n \n #when\n test2 = has_directory(directory_path)\n\n #r...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Description When is given a directory name that doesnt exist Expected Result returns False
def test_doesnt_have_directory(self, check_fn_false): # setup has_directory = extractor.make_has_directory(os.path.isdir) # when test2 = has_directory("./data/tests") # result assert test2 is False
[ "def __is_directory_name(filename):\n return filename[-1] == '/'", "def is_valid_directory(parser, arg):", "def test_doesnt_have_directory_log(self, check_fn_false, caplog):\n\n #setup\n records = caplog.records\n has_directory = extractor.make_has_directory(os.path.isdir)\n d...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Description When is given a directory name that doesnt exist Expected Result Shows log that directory wasn't found
def test_doesnt_have_directory_log(self, check_fn_false, caplog): #setup records = caplog.records has_directory = extractor.make_has_directory(os.path.isdir) directory_path = "./data/tests" #when test2 = has_directory(directory_path) #result assert len(records) == 1 assert records[0].message == f"It wasn't found directory {directory_path}"
[ "def test_log_to_file_when_dir_does_not_exist(self):\n XKNX(log_directory=\"/xknx/is/fun\")\n\n assert not os.path.isfile(\"/xknx/is/fun/xknx.log\")", "def testNoSuchDirectory(self):\n\n self.assertRaises(OSError,\n parse_package,\n \"no_such_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Description When is given a directory path that has forecast as parent folder and csv file with desired name Expected Result returns dictionary with right data
def test_forecast_folder_path(self): #setup filepath = ".data/forecast/Kano-KN_-9.09_7.39.json" expected_result = { "type": "forecast", "city": "Kano", "state": "KN", "coordinates": ['-9.09', '7.39'], "forecast": {} } #result assert extractor.get_metadata_from_filepath(filepath) == expected_result
[ "def get_data():\n\n root_dir = os.getcwd()\n csv_path = os.path.join(root_dir, \"data\", \"csv\")\n\n file_names = [f for f in os.listdir(csv_path) if f.endswith(\".csv\")]\n key_names = [\n name.replace(\"olist_\", \"\")\n .replace(\".csv\", \"\")\n .replace(\"_dataset\", \"\")\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Description When is given a csv_filepath and output_filepath and its the first time reading it Expected Result creates a json file with right values
def test_first_time_reading_csv_file(self): # Create a temporary directory for test files temp_dir = "test_files/observed" os.makedirs(temp_dir, exist_ok=True) # Create a test CSV file csv_filepath = os.path.join(temp_dir, "Abadia-BA_-11.56_-37.52.csv") with open(csv_filepath, "w", newline="") as csv_file: writer = csv.writer(csv_file, delimiter=";") writer.writerow(["periods", "precipitation", "temperature", "max_temperature"]) writer.writerow(["2023-01-01", "5", "25", "30"]) writer.writerow(["2023-01-02", "10", "23", "28"]) # Define the expected output JSON file path expected_output_filepath = os.path.join(temp_dir, "BA_Abadia.json") # Call the function under test extractor.csv_to_json(csv_filepath, temp_dir) # Verify that the output JSON file exists assert os.path.exists(expected_output_filepath) # Load the output JSON file with open(expected_output_filepath, "r") as json_file: json_data = json.load(json_file) # Verify the contents of the JSON file expected_data = { "city": "Abadia", "state": "BA", "coordinates": ["-11.56", "-37.52"], "observed": { "periods": ["2023-01-01", "2023-01-02"], "precipitation": ["5", "10"], "temperature": ["25", "23"], "max_temperature": ["30", "28"] } } assert json_data == expected_data # Clean up the temporary directory and files os.remove(csv_filepath) os.remove(expected_output_filepath) os.rmdir(temp_dir)
[ "def create_json_from_csv(csv_file, delimiter, cols_delimiter, keep, dic_types, infer_types, max_docs, json_file, per_line):\n\n # Get header of csv\n header_csv = get_header_csv(csv_file, cols_delimiter)\n\n # Create structure of json\n print(' [INFO] Creating json\\'s structure')\n jstruct = creat...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Description When is given a csv_filepath and output_filepath and already exists the file Expected Result concatenate the old json file with the values found in 2nd reading.
def test_when_file_already_exist(self): # Create a temporary directory for test files temp_dir = ["test_files/observed", "test_files/forecast", "test_files/output"] for dir in temp_dir: os.makedirs(dir, exist_ok=True) # Create the 1st csv file first_csv_filepath = os.path.join(temp_dir[0], "Abadia-BA_-11.56_-37.52.csv") with open(first_csv_filepath, "w", newline="") as csv_file: writer = csv.writer(csv_file, delimiter=";") writer.writerow(["periods", "precipitation", "temperature", "max_temperature"]) writer.writerow(["2023-01-01", "5", "25", "30"]) writer.writerow(["2023-01-02", "10", "23", "28"]) # Creating the 2nd csv file in different directory second_csv_filepath = os.path.join(temp_dir[1], "Abadia-BA_-11.56_-37.52.csv") with open(second_csv_filepath, "w", newline="") as csv_file: writer = csv.writer(csv_file, delimiter=";") writer.writerow(["periods", "precipitation", "temperature", "max_temperature"]) writer.writerow(["2023-01-01", "5", "25", "30"]) writer.writerow(["2023-01-02", "10", "23", "28"]) # Define the expected output JSON file path expected_output_filepath = os.path.join(temp_dir[2], "BA_Abadia.json") # Call the function under test extractor.csv_to_json(first_csv_filepath, temp_dir[2]) extractor.csv_to_json(second_csv_filepath, temp_dir[2]) # Verify that the output JSON file exists assert os.path.exists(expected_output_filepath) # Load the output JSON file with open(expected_output_filepath, "r") as json_file: json_data = json.load(json_file) # Verify the contents of the JSON file expected_data = { "city": "Abadia", "state": "BA", "coordinates": ["-11.56", "-37.52"], "observed": { "periods": ["2023-01-01", "2023-01-02"], "precipitation": ["5", "10"], "temperature": ["25", "23"], "max_temperature": ["30", "28"] }, "forecast": { "periods": ["2023-01-01", "2023-01-02"], "precipitation": ["5", "10"], "temperature": ["25", "23"], "max_temperature": ["30", "28"] }, } # Assertion assert json_data == expected_data # Clean up the temporary directory and files os.remove(first_csv_filepath) os.remove(second_csv_filepath) os.remove(expected_output_filepath) for dir in temp_dir: os.rmdir(dir)
[ "def prepare_temp_source_csv_file(self, csv_file_path):\n updated_rows = []\n with open(temp_file_dir, \"w\") as ftempout:\n column_processed = False\n for line in open(csv_file_path):\n if not column_processed:\n updated_column_name = self.get_u...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Description When is given a csv_filepath and output_filepath and one of the columns has blank character Expected Result creates a json file ignoring blank column
def test_blank_column(self): # Create a temporary directory for test files temp_dir = "test_files/observed" os.makedirs(temp_dir, exist_ok=True) # Create a test CSV file csv_filepath = os.path.join(temp_dir, "Abadia-BA_-11.56_-37.52.csv") with open(csv_filepath, "w", newline="") as csv_file: writer = csv.writer(csv_file, delimiter=";") writer.writerow(["periods", "precipitation", "temperature", ""]) writer.writerow(["2023-01-01", "5", "25", ""]) writer.writerow(["2023-01-02", "10", "23", ""]) # Define the expected output JSON file path expected_output_filepath = os.path.join(temp_dir, "BA_Abadia.json") # Call the function under test extractor.csv_to_json(csv_filepath, temp_dir) # Verify that the output JSON file exists assert os.path.exists(expected_output_filepath) # Load the output JSON file with open(expected_output_filepath, "r") as json_file: json_data = json.load(json_file) # Verify the contents of the JSON file expected_data = { "city": "Abadia", "state": "BA", "coordinates": ["-11.56", "-37.52"], "observed": { "periods": ["2023-01-01", "2023-01-02"], "precipitation": ["5", "10"], "temperature": ["25", "23"] } } assert json_data == expected_data # Clean up the temporary directory and files os.remove(csv_filepath) os.remove(expected_output_filepath) os.rmdir(temp_dir)
[ "def parse_csv_data_to_json(input_file, output_file):\n with open(input_file) as f:\n # open the output file for writing\n with open(output_file, 'w') as myfile:\n\n # read in the csv\n input_content = csv.reader(f, delimiter=',')\n\n # skip the header and store it ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Delete a log file.
def delete_log(file_path): if os.path.exists(file_path): print('Deleting log %s...' % file_path) os.remove(file_path) else: raise ValueError("File %r doesn't exists - cannot delete." % file_path)
[ "def remove_log():\n os.remove(_log_filename)", "def delete_log():\n log_path = Path.cwd() / \"premise.log\"\n if log_path.exists():\n log_path.unlink()", "def delete_file(fileName):\n os.remove(fileName)\n print (\"Deleteing file: \" + str(fileName))\n write_log()\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
retorna o valor de graus Farenheit convertido para Celsius
def toCelsius(farenheit): return (farenheit - 32)*5 / 9
[ "def convert_f_to_c(temp_in_farenheit): ## ##\n celsiustemp = round((temp_in_farenheit - 32) * 5/9, 1) ##\n return celsiustemp ##", "def fahr_to_celsius(temp_fah...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return github API URL as string
def get_api_url(self): url = 'https://api.{}/repos/{}/{}/git/'.format(HOST_GITHUB, \ self.repo, self.product) return url
[ "def get_GitHubAPIURL(self) -> str:\r\n return self.githubAPIURL", "def github_url(self):\n return self.github.replace('.git', '')", "def github_url(self) -> str:\n remote_url = self._repo.remotes[REMOTE].url\n # if we have an ssh remote, convert it to a URL\n for ssh_login in...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get a specific tag's data from Github API.
def get_tag(self, sha): return self.get_url_data(self.api_url + 'tags/' + sha)
[ "def remote_tag(tag):\n url = \"%s/git/refs/tags\" % get_github_api_url()\n for result in requests.get(url).json():\n try:\n if result[\"ref\"] == \"refs/tags/%s\" % tag:\n return result\n except TypeError:\n return", "def get_tag(self, tag):\n resp ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Github API can only return all tags, but we only want the latest.
def get_latest_tags(self): start = len(self.tags) - self.num_comparisons tags = self.tags latest = [] for i in xrange(len(tags)): if i >= start: parts = tags[i]['ref'].split('/') release_num = parts[2] sha = tags[i]['object']['sha'] tag = [release_num, sha] latest.append(tag) return latest
[ "def latest_github_tag():\n release_tags_github_url = \"https://api.github.com/repos/rackerlabs/openstack-guest-agents-unix/tags\"\n release_tags_json = urllib2.urlopen(release_tags_github_url)\n release_tags_data = json.load(release_tags_json)\n return str(release_tags_data[0]['name'])[1:]", "def rem...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return github tag release URL as string
def get_url_tag_release(self, release_num): url = 'https://{}/{}/{}/releases/tag/{}'.format( HOST_GITHUB, self.repo, self.product, release_num ) return url
[ "def get_url_tag_commit(self, git_sha):\n\n url = 'https://{}/{}/{}/commit/{}'.format(\n HOST_GITHUB,\n self.repo,\n self.product,\n git_sha\n )\n return url", "def latest_repo_release(url: str) -> str:\n\n resp = requests.get(url)\n t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return github tag commit SHA URL as string
def get_url_tag_commit(self, git_sha): url = 'https://{}/{}/{}/commit/{}'.format( HOST_GITHUB, self.repo, self.product, git_sha ) return url
[ "def github_url(self):\n return self.github.replace('.git', '')", "def get_github_hash(owner: str, repo: str, path: str) -> str:\n url = FILE_API_URL.format(owner=owner, repo=repo, path=path.lstrip('/'))\n res = requests.get(url)\n res_json = res.json()\n most_recent_commit = res_json[0]\n r...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Parse CHANGELOG for latest tag.
def get_changelog(self, commit_sha): url = 'https://{}/{}/{}/' + commit_sha + '/CHANGELOG' url = url.format(HOST_GITHUB_RAW, self.repo, self.product) req = requests.get(url) lines = req.text first = self.latest_tags[self.num_comparisons - 1][VERS] last = self.latest_tags[self.num_comparisons - 2][VERS] flag = False log = '' for line in lines.splitlines(): if first in line: flag = True if last in line: flag = False if flag: log += line + '\n' return log
[ "def parse_log():\n\thistory = {}\n\ttemp_commit = ''\n\tlogs = open('gda_git_logs_temp.txt', 'r')\n\n\tfor line in logs:\n\t\twords = line.split(' ')\n\t\tif words[0] == 'commit':\n\t\t\ttemp_commit = words[1].rstrip()\n\t\telif words[0] == 'Date:':\n\t\t\tyear = words[7]\n\t\t\tmonth = month_to_num(words[4])\n\t\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Constructs release notes for Bugzilla service deployment ticket.
def get_release_notes(self): notes = self.output.get_header('RELEASE NOTES') notes += 'https://{}/{}/{}/releases'.format(HOST_GITHUB, \ self.repo, self.product) + '\n' notes += self.output.get_sub_header('COMPARISONS') notes += self.get_comparison(self.latest_tags[0][VERS], self.latest_tags[1][VERS]) if len(self.latest_tags) >= (MAX_COMPARISONS_TO_SHOW - 1): notes += self.get_comparison(self.latest_tags[1][VERS], self.latest_tags[2][VERS]) if len(self.latest_tags) >= MAX_COMPARISONS_TO_SHOW: notes += self.get_comparison(self.latest_tags[2][VERS], self.latest_tags[3][VERS]) tag_data = self.get_tag(self.latest_tags[3][SHA]) notes += self.output.get_sub_header('TAGS') notes += self.get_url_tag_release(self.latest_tags[3][VERS]) + '\n' notes += self.get_url_tag_commit(tag_data["object"]["sha"]) + '\n' changelog = self.get_changelog(tag_data["object"]["sha"]) if changelog: notes += self.output.get_sub_header('CHANGELOG') notes += changelog return notes
[ "def release_notes(version, author, git_ref_target, git_ref_source, build_type):\n print('generating release notes')\n if git_ref_source:\n if git_ref_source != 'HEAD':\n git_ref_source = 'origin/{}'.format(git_ref_source)\n changelog = run('git log origin/{}..{}'.format(git_ref_targe...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets the sampling_time of this PcrTestRecordResult. 核酸检测采样时间
def sampling_time(self): return self._sampling_time
[ "def samplingTime(self):\n return self._AWG.samplingTime_ns()", "def _get_sampling_time(self):\n return 1/self.sampling_frequency*TIME_CONVERSION['s'][self.time_unit]", "def sampling_rate(self):\n return self.track.sampling_rate", "def sampling_rate(self):\n return self.librarycall...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the sampling_time of this PcrTestRecordResult. 核酸检测采样时间
def sampling_time(self, sampling_time): self._sampling_time = sampling_time
[ "def setSamplingTime(self, time):\n return self._AWG.setSamplingTime_ns(time)", "def sampling_time(self):\n return self._sampling_time", "def set_sample_interval(self, secs):\n self._sample_interval_secs = secs", "def _reset_sampling_time(self):\n member = self.get_member(str('samp...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets the test_time of this PcrTestRecordResult. 核酸检测结果更新时间
def test_time(self): return self._test_time
[ "def test_time(self) -> float:\n return self._test_time", "def update_time(self):\n return self._update_time", "def get_update_time(self):\n return self._utime", "def updated_time(self):\n return self._updated_time", "def GetTimeRecorded(self):\n return self.time", "def ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the test_time of this PcrTestRecordResult. 核酸检测结果更新时间
def test_time(self, test_time): self._test_time = test_time
[ "def setTestTime(self, testTime):\r\n return self._domInstance.setAttribute('time', testTime)", "def latest_test_usage_record_time(self, latest_test_usage_record_time):\n\n self._latest_test_usage_record_time = latest_test_usage_record_time", "def test_time(self) -> float:\n return self._te...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets the test_result of this PcrTestRecordResult. 核酸检测结果,可选值包括: \"positive\",即阳性 \"negative\",即阴性 \"unknown\",未知
def test_result(self): return self._test_result
[ "def get_test_result(self):\n failure_info_list = self._outcome.errors[1][1]\n if not failure_info_list:\n return 'OK'\n elif failure_info_list[0].__name__ == 'AssertionError':\n return 'FAIL'\n else: # 'NameError'\n return 'ERROR'", "...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the test_result of this PcrTestRecordResult. 核酸检测结果,可选值包括: \"positive\",即阳性 \"negative\",即阴性 \"unknown\",未知
def test_result(self, test_result): self._test_result = test_result
[ "def SetTestResult(test_info: paranoid_pb2.TestInfo,\n test_result: paranoid_pb2.TestResultsEntry):\n if not test_info.paranoid_lib_version:\n # Stores version value in test_info. As checks can be updated and become\n # stronger, this attribute can be useful to know when it makes sense to\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets the confidence of this PcrTestRecordResult.
def confidence(self): return self._confidence
[ "def confidence(self):\n return self.__confidence", "def confidence(self) -> float:\n return self._confidence", "def confidence(self) -> float:\n return float(self.class_scores[self.class_num])", "def confidence(self):\n score_uncertanity = 1-self.score\n clarity_uncertainty...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets the words_block_count of this PcrTestRecordResult. 代表检测识别出来的文字块数目。
def words_block_count(self): return self._words_block_count
[ "def getblockcount(self):\n return self.call('getblockcount')", "def word_count(self):\n return self._word_count", "def word_count(self):\n return self.index.word_count()", "def words_block_count(self, words_block_count):\n self._words_block_count = words_block_count", "def size_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the words_block_count of this PcrTestRecordResult. 代表检测识别出来的文字块数目。
def words_block_count(self, words_block_count): self._words_block_count = words_block_count
[ "def words_block_count(self):\n return self._words_block_count", "def block_count(self, block_count):\n\n self._block_count = block_count", "def words_count(self, words_count):\n\n self._words_count = words_count", "def words_block_list(self, words_block_list):\n self._words_block_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets the words_block_list of this PcrTestRecordResult. 识别文字块列表,输出顺序从左到右,从上到下。
def words_block_list(self): return self._words_block_list
[ "def getBlockedWords(self):\n return self.blocklist[\"words\"]", "def getBlocklist(self):\n return self.blocklist", "def words_block_list(self, words_block_list):\n self._words_block_list = words_block_list", "def get_blocks(self):\n return self.blocks", "def get_blocks(self):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the words_block_list of this PcrTestRecordResult. 识别文字块列表,输出顺序从左到右,从上到下。
def words_block_list(self, words_block_list): self._words_block_list = words_block_list
[ "def words_block_list(self):\n return self._words_block_list", "def kv_block_list(self, kv_block_list):\n self._kv_block_list = kv_block_list", "def words_block_count(self, words_block_count):\n self._words_block_count = words_block_count", "def add_blocks(self, block_list):\n bloc...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Prompt user for input and continue to do so until input is valid. This function takes two required inputs, the message to display, and the limit of characters required. If the user enters something too long, they are prompted again until the input is correct. If the optional isNumber parameter is True, then it will also continue to prompt the user until a valid number is input.
def LimitedInput(message, limit, isNumber=False): keepAsking = True while keepAsking: answer = input(message) if len(answer) > limit: print("The input must be", limit, "characters or less.") else: keepAsking = False if isNumber is True and CheckNumber(answer) is False: print("The input must be a number.") keepAsking = True return answer
[ "def ask_num(message, min, max):\n while True:\n try:\n number = int(input(message))\n except:\n print(\"that was not a number\")\n continue\n if max >= number >= min:\n break\n return number", "def ask_user():\r\n password_lenght = 0\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function returns True if userInput can be converted to a number and returns False if it cannot.
def CheckNumber(userInput): try: float(userInput) return True except(ValueError): return False
[ "def validate_num_input(self, user_input, max_num) -> bool:\n\n try:\n num = int(user_input)\n if num < 1 or num > max_num:\n raise ValueError(\n f'This should be a number between 1 and {max_num}!')\n except ValueError as e:\n print(f'...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function prompts the user for a date using the message variable. User will continue to be prompted until the format is correct. The date format is very specific in the format DD/MM/YYYYY This function will confirm there are the right number of characters, the / are in the right place, the input are numbers, the days are between 1 and 31, the months are between 1 and 12, and the year is between 2000 and 3000 (roll on year 3k bug!)
def DateInput(message): askAgainMessage = "The date must be in the format DD/MM/YYYY" keepAsking = True while keepAsking: answer = input(message) # First we check if there are two / by splitting using / and looking # for 3 items in the returned list. dateCheck = answer.split(sep="/") if len(dateCheck) is not 3: print(askAgainMessage) else: # If all is order, we can assign the 3 items to day, month, year day = dateCheck[0] month = dateCheck[1] year = dateCheck[2] # Next we check each item has the right amount of characters # and they can all be converted into numbers. if (len(day) == 2 and len(month) == 2 and len(year) == 4 and CheckNumber(day) and CheckNumber(month) and CheckNumber(year)): day = int(day) month = int(month) year = int(year) if (day > 0 and day < 32 and month > 0 and month < 13 and year > 2000 and year < 3000): keepAsking = False else: print(askAgainMessage) else: print(askAgainMessage) return answer
[ "def check_date(message, param):\n while True:\n try:\n day, month, year = input(message).split(param)\n return str(datetime.datetime(int(year), int(month), int(day)).strftime(\"%d/%m/%Y\"))\n except ValueError:\n continue", "def read_date(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
takes first row of tworow belief np array and converts it to dict indexed by label of positive beliefs
def np_to_belief(np_array,labels): return dict((l,np_array[0,i]) for i,l in enumerate(labels))
[ "def faces_to_dict(faces):\n label_list = np.unique(faces)\n adj_dict = dict()\n for label in label_list:\n adj_list = list(np.unique(faces[np.where(faces == label)[0]]))\n adj_list.remove(label)\n adj_dict[label] = adj_list\n return adj_dict", "def label_counts(self):\n d=...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
takes a list of votes and predicts based on threshold returns true iff fraction of true votes >= f
def thresh_vote(lst, f): if len(lst) == 0: # guess 0 by default (appropriate for our dataset) q = 0 else: q = float(sum(lst)) / len(lst) return q >= f
[ "def _fit_threshold(self):\n self.threshold = 0\n current_best = 0\n for i in range(1000):\n old = self.threshold\n self.threshold = i/1000\n f = f1_score(self.y, self.predict(self.pred, self.X_text))\n if f <= current_best:\n self.thre...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Takes dictionaries of predicted and ground truth and returns confusion matrix
def confusion_matrix(predicted, gt): tp = [k for k in predicted if predicted[k] and gt[k]] tn = [k for k in predicted if not predicted[k] and not gt[k]] fp = [k for k in predicted if predicted[k] and not gt[k]] fn = [k for k in predicted if not predicted [k] and gt[k]] return tp, tn, fp, fn
[ "def confusion_matrix(actual, predictions):\n\n if predictions.shape[0] != actual.shape[0]:\n raise ValueError(\"predictions and actual must be the same length!\")\n\n confuse_matrix = np.random.uniform(0, 10, size=(2, 2))\n # True Positive (TP): we predict a label of 1 (positive), and the true labe...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns argmax, max of dictionary
def argmax(d): return max(d.iteritems(), key=operator.itemgetter(1))
[ "def keywithmaxval(d):\n\treturn max(d, key=lambda k: d[k])", "def max(self):\n try:\n res = {\n 'target': self.target.max(),\n 'params': dict(\n zip(self.keys, self.params[self.target.argmax()])\n )\n }\n except V...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Produce nboot bootstrap samples from applying func to data
def bootstrap(data,func,nboot): n = len(data) resamples = np.array([[random.choice(data) for i in range(n)] for j in range(nboot)]) return np.apply_along_axis(func, 1, resamples)
[ "def bootstrap_replicate_1d(data, func):\r\n bs_sample = np.random.choice(data, len(data))\r\n return func(bs_sample)", "def bootstrap_replicate_1d(data, func):\n bs_sample = np.random.choice(data, len(data))\n return func(bs_sample)", "def bootstrap_replicate_1d(data, func):\n bs_sam...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
trace finds the line, the filename and error message and returns it to the user
def trace(): import traceback tb = sys.exc_info()[2] tbinfo = traceback.format_tb(tb)[0] # script name + line number line = tbinfo.split(", ")[1] # Get Python syntax error # synerror = traceback.format_exc().splitlines()[-1] return line, __file__, synerror
[ "def trace():\n import traceback, inspect,sys\n tb = sys.exc_info()[2]\n tbinfo = traceback.format_tb(tb)[0]\n filename = inspect.getfile(inspect.currentframe())\n # script name + line number\n line = tbinfo.split(\", \")[1]\n # Get Python syntax error\n #\n synerror = traceback.format_ex...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
In this function, you will instantiate several times, given the data provided. Then, you will open "sh_additional_info.csv" and for each line in that file, perform an operation using one of the methods of one of your classes. Follow the commented instructions in this main() function. Refer to Problem Set 07 README.md for instructions and tips.
def main(): # Refer to Problem Set 07 README.md for instructions and tips. # 6.1: Read in < sh_basic_info.csv > basic_info = read_csv_file('sh_basic_info.csv') # 6.2: Create instances of < SuperHeroine > heroines = {} for hero in basic_info: heroines[hero['name']] = SuperHeroine(hero['name'], hero['full_name'], hero['team'], hero['eye_color'], hero['hair_color'], hero['base']) print(heroines) # 6.3: Read in < sh_additional_info.csv > additional_info = read_csv_file('sh_additional_info.csv') # 6.4: Add powers and nemesis for row in additional_info: name = row["Heroine Name"] instance_affected = heroines[name] how_affected = row["Category"] value = row['Value'] if how_affected == 'power': instance_affected.add_power(value) else: instance_affected.add_nemesis(value) # 6.5: Write to file write_to_file('storm.txt',heroines['Storm']) write_to_file('scarlet_witch.txt',heroines['Scarlet Witch']) write_to_file('jessica_jones.txt',heroines['Jessica Jones'])
[ "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" ] ] } }
Updates x, y (memoryshared) coordinates with actual mouse position with a given frequency.
def stream(bus, address, frequency, x, y, stop_trigger): mouse = Mouse.list_connected(bus=bus, address=address)[0] delay = 1./frequency while not stop_trigger: x1, y1 = mouse.get_position_change() x.value += x1 y.value += y1 time.sleep(delay)
[ "def update_coordinates(self):\n self.x, self.y = pygame.mouse.get_pos()", "def refresh_pos(self):\r\n\r\n self.mouse_pos = pygame.mouse.get_pos()", "def update(self, event):\n self.xy = [event.x, event.y]", "def update_pointer(self):\n pointer_length = -self.pointer_frac * sel...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the focal length of the telescope.
def focal_length(self): return self.f * self.diameter
[ "def get_focal_length(self):\n return self.focal_length", "def get_focal_length(self):\n return self._calibration_mat[0][0]", "def focal_length(self):\n if not hasattr(self, \"_focal_length\"):\n if (self.spacecraft_name == \"VIKING ORBITER 1\"):\n if (self.sensor_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the plate scale as an `~astropy.units.Quantity`.
def plate_scale(self): return 206265 * uu.arcsec / (self.diameter.to('mm') * self.f)
[ "def platescale(self):\n return None if self['fratio'] is None or self['diameter'] is None \\\n else 206265/self['fratio']/self['diameter']/1e3", "def getScale(self):\n return _libsbml.Unit_getScale(self)", "def plate_scale(platescale):\n if platescale.unit.is_equivalent(si.arcse...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }