query
stringlengths
9
9.05k
document
stringlengths
10
222k
negatives
listlengths
19
20
metadata
dict
This method starts the crawling process which is scraping urls from the next available link in frontier and adding the scraped links to the frontier
def start_crawling(self): global domain global subdomain_dict global valid_set global max_outlinks_url global max_outlinks_num global previous_num while self.frontier.has_next_url(): url = self.frontier.get_next_url() logger.info("...
[ "def start_crawling(self):\r\n print_start = time.time()\r\n start = time.time()\r\n\r\n while self.frontier.has_next_url():\r\n url = self.frontier.get_next_url()\r\n # limit output to every 30 seconds or so\r\n if time.time() - start > 15:\r\n #...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This method, using the given url, should find the corresponding file in the corpus and return a dictionary containing the url, content of the file in binary format and the content size in bytes
def fetch_url(self, url): url_data = { "url": url, "content": None, "size": 0 } corp_file_name = self.corpus.get_file_name(url) #Using Corpus method to get file_name associated with URL content = b'' #To initialize binary content for data in op...
[ "def retrieve_file(url):\n doc = urlopen(url)\n lines = doc.read().decode()\n doc.close()\n return lines", "def _read(url):\n if os.path.exists(url): \n file_obj = open(url, 'r') \n file_body = file_obj.read() \n file_obj.close() \n #start_response('200 OK', [('Content-T...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The url_data coming from the fetch_url method will be given as a parameter to this method. url_data contains the fetched url, the url content in binary format, and the size of the content in bytes. This method should return a list of urls in their absolute form (some links in the content are relative and needs to be co...
def extract_next_links(self, url_data): try: outputLinks = [] etree_parser = etree.parse(StringIO(url_data['content'].decode('utf-8')), etree.HTMLParser()) #Parsing through the content of the file and then decoded for data in etree_parser.xpath("//@href"): #Getting data with...
[ "def extract_next_links(self, url_data):\r\n\r\n\r\n # Ban non-text/HTML type documents\r\n try:\r\n if not re.search(r\"text\", url_data[\"content_type\"]):\r\n return []\r\n except TypeError as e:\r\n return []\r\n\r\n # use relevant url depending o...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
this function show a car's information
def car_info(manufacturer, model, **options): cardict = { 'manufacturer': manufacturer.title(), 'model': model.title(), } for option, value in options.items(): cardict['option'] = value return cardict
[ "def show_inventory(self):\n for i in self.inventory:\n self.show_car(i)", "def extract_car_details(car):\n title_selector = {'class': 'card__body-title'}\n link_selector = {'class': 'card__link'}\n key_info_selector = {'class': 'card__body-keyinfo'}\n\n year_index = 0\n engine_in...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Detect round objects in a image and extract as new images Takes a image file, find all round objects and extract them as new images. Uses opencv function HoughCircles to detect circles. Then make a new image file using center position and radius info about it, save in a folder called "extracted", which is in the folder...
def extract_coins(file_, folder): image = cv2.imread(folder + file_) output = image.copy() gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) #Add border border_size = 10 BLACK = [0, 0, 0] image = cv2.copyMakeBorder(image,border_size,border_size,border_size,border_size,cv2.BORDER_CONSTANT,value=BLACK) # detect ci...
[ "def getCircle(img):\n output = img.copy()\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n circles = cv2.HoughCircles(gray, cv2.HOUGH_GRADIENT, 0.7, 40,\n param1=80, param2=15, minRadius=7,\n maxRadius=0)\n bloons = []\n sizes = []\n if ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function to merge the gaudilog files of the different subprocesses.
def merge_log(pcfgs, cfg): log_files = [ os.path.join(pcfg.output.path, pcfg.output.name + ".gaudi-log") for pcfg in pcfgs ] gaudi_log = os.path.join(cfg.output.path, cfg.output.name + ".gaudi-log") with open(gaudi_log, "w") as log: log.write("Merged log files\n################\...
[ "def merge_multiproc_files(command, filename, barcode, err_log, stat_log):\n exit_str = Popen(\"cat \" + err_log + \"_multiproc_* | grep EXIT_CODE\",\n stdout=PIPE, shell=True).communicate()[0]\n exit_code = 0\n for i in exit_str.split('\\n'):\n m = re.match(\"EXIT_CODE: (.*)\\n\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Since subscription IDs were not previously stored, a direct migration will leave us
def resync_subscriptions(apps, schema_editor): # This is okay, since we're only doing a forward migration. from djstripe.models import Subscription from djstripe.context_managers import stripe_temporary_api_version with stripe_temporary_api_version("2016-03-07"): if Subscription.objects.count...
[ "def success(self, migration):", "def _after_migration(self):\n pass", "def removeSubscription(subscriber):", "def downgrade_to_free():\n if not current_user.subscription.active:\n subscription = Subscription.query.get(current_user.subscription.id)\n free_plan = Plan.query.filter_by(na...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Since invoiceitem IDs were not previously stored (the ``stripe_id`` field held the id of the linked subsription), a direct migration will leave us with a bunch of orphaned objects. It was decided
def resync_invoiceitems(apps, schema_editor): # This is okay, since we're only doing a forward migration. from djstripe.models import InvoiceItem from djstripe.context_managers import stripe_temporary_api_version with stripe_temporary_api_version("2016-03-07"): if InvoiceItem.objects.count():...
[ "def test_invoice_has_not_been_paid(self):\n invoice = Invoice.objects.create(total=100.00)\n invoice.save()\n\n Transaction.objects.bulk_create([\n Transaction(invoice=invoice, amount=10.00),\n Transaction(invoice=invoice, amount=20.00),\n ])\n\n self.assert...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Ensure that all customers attached to subscriber are purged on deletion.
def on_subscriber_delete_purge_customers(collector, field, sub_objs, using): for obj in sub_objs: obj.purge() SET_NULL(collector, field, sub_objs, using)
[ "def delete_all_subscribers(self):\n with self._lock:\n self._cache_clear()\n self._persistent_store.delete_all_subscribers()", "def removeSubscription(subscriber):", "def remove_existing_customers(self):\n \n customers = self.add_new_customers()\n for customer ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Examples of when Notification.Builder should not be flagged.
def testFalsePositives(self): mock_input = MockInputApi() mock_input.files = [ MockFile( 'chrome/android/java/src/org/chromium/chrome/browser/notifications/' 'ChromeNotificationWrapperBuilder.java', ['new Notification.Builder()']), MockFile( 'chrom...
[ "def _init_notification(self):\n self.notification = notify.Notification(\n 'remind_bedtime bug!', icon='appointment')\n self.notification.set_timeout(notify.EXPIRES_NEVER)\n self.notification.set_urgency(notify.URGENCY_CRITICAL)\n self.notification.set_hint('transient', False...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Examples of when AlertDialog.Builder should not be flagged.
def testFalsePositives(self): mock_input = MockInputApi() mock_input.files = [ MockFile('path/One.java', ['AlertDialog.Builder']), MockFile('path/Two.java', ['// do not: new AlertDialog.Builder()']), MockFile('path/Three.java', ['/** ChromeAlertDialogBuilder', ...
[ "def testFailure_WrongBuilderCheck(self):\n mock_input = MockInputApi()\n mock_input.files = [\n MockFile('path/One.java',\n ['import android.support.v7.app.AlertDialog;',\n 'new AlertDialog.Builder()']),\n MockFile('path/Two.java',\n ['import and...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Use of AppCompat AlertDialog.Builder is correctly flagged.
def testFailure_WrongBuilderCheck(self): mock_input = MockInputApi() mock_input.files = [ MockFile('path/One.java', ['import android.support.v7.app.AlertDialog;', 'new AlertDialog.Builder()']), MockFile('path/Two.java', ['import android.app.Ale...
[ "def testFalsePositives(self):\n mock_input = MockInputApi()\n mock_input.files = [\n MockFile('path/One.java', ['AlertDialog.Builder']),\n MockFile('path/Two.java', ['// do not: new AlertDialog.Builder()']),\n MockFile('path/Three.java',\n ['/** ChromeAlertDialogBuilder',...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tests that main handles exceptions appropriately.
def test_main_exceptions(_get_argparser): class TestError(Exception): pass def raise_error(opt, verbose=True): # pylint: disable=unused-argument if opt == 1: raise errors.FunkyError(returncode=5) elif opt == 2: raise TestError("Test Exception") _get_argpar...
[ "def test_main_if_check_args(self):\n\n sys.argv[1:] = [1, 2, 3, 4]\n with self.assertRaises(SystemExit) as ctx:\n main()\n self.assertEqual(1, ctx.exception.code)", "def test_main__no_action(self) -> None:\n config_file = self._setup_config({})\n try:\n ma...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns some fuzzy string comparison of the two strings.
def fuzzy(str1, str2): return seqmatcher(None, str1, str2).ratio()
[ "def string_compare_with_processing(s1, s2, **kwargs):\n\n # Before we do anything, see if we have a match.\n if s1 == s2:\n return True\n\n if kwargs.get('lowercase', True):\n s1 = s1.lower()\n s2 = s2.lower()\n\n # Keep checking...\n if s1 == s2:\n return True\n\n\n #...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
function generating the listing of the .h5 files in the selected directory, returning the abs path
def listing(mypath): files = [join(mypath, f) for f in listdir(mypath) if f.endswith(".h5")] return(files)
[ "def view_path(self, collection_id: int) -> pathlib.Path:\n\n return self._path / f\"{collection_id}.hdf5\"", "def list_files(path_to_dir):\n # group based encoding?\n is_single_file = os.path.isfile(path_to_dir)\n\n if is_single_file:\n all_files = [path_to_dir]\n else:\n # Find ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
concatenate .h5 files created from binner in different and smaller files
def concatenate_batch(particle,num_files): outpath=path_generator(particle)[1] infiles=listing(outpath) lists = np.array_split(np.array(infiles),num_files) counter=1 for infile in lists: print(infile) counter+=1 ci=FileConcatenator(infile) name='concatenated_'+str(cou...
[ "def example_bed_l2_h5():\n yield h5py.File(\"tests/test_data/example_test_2label.h5\", \"r\")", "def split_train_hdf(size_SB=4000):\n hdf5_file_train = h5py.File(HDF5_PATH_TRAIN, \"r\")\n data_num_train = hdf5_file_train[\"train_img\"].shape[0]\n data_num_train = range(0, data_num_train)\n random....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns API url for getting movie details
def movie_details_url(movie_id): return '%s/movie/%s?api_key=%s&append_to_response=videos' % ( BASE_URL, movie_id, API_KEY )
[ "def get_video_url():\n return f'{API_URL}{quote(VIDEO_NAME)}'", "def get_poster_url(name, api_key=api_key):\n URL = \"https://api.themoviedb.org/3/search/movie?api_key=%s&language=en-US&query=%s&page=1&include_adult=false\"\\\n % (api_key, name)\n # Sanitize the URL\n URL = quote(URL, \":=&/?\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get upcoming movie ids from the API
def upcoming_movie_ids(): response = requests.get(UPCOMING_URL).json() movies = response['results'] ids = [movie_obj['id'] for movie_obj in movies] return ids
[ "def upcoming_movies():\n movie_ids = upcoming_movie_ids()\n urls = [movie_details_url(movie_id) for movie_id in movie_ids]\n\n return [get_movie_model(api_url) for api_url in urls]", "def list_upcoming_movies(self):\n self.endpoint = 'list_upcoming.json'\n return self.__make_request()", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Make movie model from url
def get_movie_model(api_url): res = requests.get(api_url).json() title = res['title'].encode('ascii', 'ignore') storyline = res['overview'].encode('ascii', 'ignore') yt_code = res['videos']['results'][0]['key'].encode('ascii', 'ignore') poster = 'https://image.tmdb.org/t/p/w500/' + res['poster_path'...
[ "def loadModelURL(url, fmt):\n # Select load function\n load_functions = {'sbml': cobra.io.read_sbml_model,\n 'json': cobra.io.load_json_model,\n 'mat': cobra.io.load_matlab_model}\n if fmt not in load_functions:\n raise KeyError(f'{fmt} is not a valid forma...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get array of upcoming movies
def upcoming_movies(): movie_ids = upcoming_movie_ids() urls = [movie_details_url(movie_id) for movie_id in movie_ids] return [get_movie_model(api_url) for api_url in urls]
[ "def list_upcoming_movies(self):\n self.endpoint = 'list_upcoming.json'\n return self.__make_request()", "def upcoming_movie_ids():\n response = requests.get(UPCOMING_URL).json()\n movies = response['results']\n ids = [movie_obj['id'] for movie_obj in movies]\n return ids", "def get_mo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the package type. Available package types are defined in PackageType. Only ASR9K supports Service Packs concept
def get_package_type(name): if name.find(SMU_INDICATOR) != -1: return PackageType.SMU elif name.find(SP_INDICATOR) != -1: return PackageType.SERVICE_PACK elif name.find(TAR_INDICATOR) != -1: return PackageType.SOFTWARE else: return PackageType.PACKAGE
[ "def package_type(self):\n ret = self._get_attr(\"packageType\")\n return ret", "def get_pkg_type():\n plt = get_os_name()\n if plt in PACK_TYPES:\n return PACK_TYPES[plt]\n raise UnsupportedOsError(f'No supported Package type for platform \"{plt}\"')", "def predefined_package_type...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given a package name, try to derive a name which can be used to lookup a SMU or SP in the SMU meta file. However, there is no guarantee that the correct name can be derived. That depends on the given name if it is within the parsing criteria.
def get_smu_lookup_name(name): name = name.strip() package_type = get_package_type(name) if package_type != PackageType.SMU and package_type != PackageType.SERVICE_PACK: return name # The worst case scenario of the name could be "disk0:asr9k-px-4.2.1.CSCud90009-1.0.0.pie" # .smu ...
[ "def resolvemoname(self, moname):\n for c in self.APICPACKAGES:\n if moname.startswith(c):\n package = c\n name = moname[len(c):len(moname)]\n break\n else:\n raise LookupError(\n 'Unable to find class %s in package list...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The smu_info_dict has the following format smu name > set()
def union_set_from_dict(smu_info_dict): result_set = set() for smu_set in smu_info_dict.values(): result_set = result_set.union(smu_set) return result_set
[ "def get_smu_info_dict(db_session, smu_loader, package_list):\r\n smu_info_dict = dict()\r\n\r\n for package_name in package_list:\r\n smu_name = SMUInfoLoader.get_smu_name_from_package_name(db_session, package_name=package_name)\r\n smu_info_dict[package_name] = smu_loader.get_smu_info(smu_name...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given a package list, return a dictionary. If a package name cannot be resolved to a SMU name, its value will be None.
def get_smu_info_dict(db_session, smu_loader, package_list): smu_info_dict = dict() for package_name in package_list: smu_name = SMUInfoLoader.get_smu_name_from_package_name(db_session, package_name=package_name) smu_info_dict[package_name] = smu_loader.get_smu_info(smu_name) return...
[ "def get_package(self, package_name):\n return package_key(package_name).get()", "def parse_package(string_package):\n res = {'dsc': string_package}\n current_field = None\n for line in string_package.splitlines():\n if not line.startswith(' '):\n field, contents = line.split(\":\", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the validated list given the SMU/SP list. A smu_list may contain packages, SMUs, SPs, or junk texts.
def get_optimized_list(package_to_optimize_list): unrecognized_list = [] package_list = [] result_list = [] db_session = DBSession() missing_peer_packages_dict = dict() smu_loader = SMUInfoLoader.get_loader_from_package(package_to_optimize_list) if smu_loader.is_valid: smu_...
[ "def parse_swupdate_list(sulist):\n for record in RECORD_RE.findall(sulist):\n yield dict(ITEM_RE.findall(record))", "def parse_spw_argument(self, spw):\n if type(spw) == list:\n return spw\n elif type(spw) == int:\n return [spw]\n sublists = spw.split(',')\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
loads the welcome message and channel from conf_filename can be easily expanded to load other config data
def load_welcome_config(): with open(conf_filename, 'r') as conf_file: config = tomlkit.loads(conf_file.read()) return config["welcome"]
[ "def load_config(self):\n\n self.bot_token = None\n self.load_music = None\n try:\n log.info(\"Loading config...\")\n self.config = BotConfig()\n self.config_data = self.config.data\n self.bot_data = self.config_data[\"bot\"]\n self.bot_tok...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
keptrim trim pixels from Target Pixel Files keptrim will extract a squareshaped series of subimages from a Target Pixel File. The simple purpose of this task is to reduce the size of large data sets such as the superstamps or twowheel engineering data for the sake of processing efficiency. Performing a keptrim step spe...
def keptrim(infile, column, row, imsize, outfile=None, kepid=None, overwrite=False, verbose=False, logfile='keptrim.log'): if outfile is None: outfile = infile.split('.')[0] + "-{}.fits".format(__all__[0]) # log the call hashline = '------------------------------------------------------...
[ "def make_sketches(path_in, path_sketch):\r\n \r\n os.chdir(path_in)\r\n file_list = glob.glob(\"*\")\r\n file_list.sort()\r\n# os.chdir(path_sketch)\r\n\r\n for file in file_list:\r\n a = Image.open(file)\r\n a = a.filter(ImageFilter.GaussianBlur(radius = 2))\r\n a = a.filter(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Notifies a client that its config has changed. This function is executed when we save a Client model, and it makes a POST request on the WAMPHTTP bridge, allowing us to make a WAMP publication from Django.
def notify_server_config_changed(sender, instance, **kwargs): requests.post("http://127.0.0.1:8080/notify", json={ 'topic': 'clientconfig.' + instance.ip, 'args': [model_to_dict(instance)] })
[ "def configuration_changed(self, config_changes):\n # TODO: implement", "def post(self):\n\n client_id = self.request.get('from')\n logging.info(\"Connecting client update channel \"+client_id)\n add_update_client(client_id)", "def _on_config_changes(self, **kwargs) -> None:\n sel...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
get the status code from systemctl status
def _get_status_code_from_systemctl(self, assigner_id, command): output = self._smtclient.execute_cmd_direct(assigner_id, command) exit_code = 0 for line in output['response']: if 'Main PID' in line: # the status code start with = and before /FAILURE p...
[ "def getStatus(self):\n exitcode, output = q.system.process.execute(self._status_cmd, dieOnNonZeroExitCode=False, outputToStdout=False)\n if exitcode == os.EX_OK:\n return AppStatusType.RUNNING\n else:\n return AppStatusType.HALTED\n\n return AppStatusType.UNKNOWN",...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tranfer this object to a tuple type, format is like (fcp_id, wwpn_npiv, wwpn_phy, chpid, state, owner)
def to_tuple(self): return (self.get_dev_no(), self.get_npiv_port(), self.get_physical_port(), self.get_chpid(), self.get_dev_status(), self.get_owner())
[ "def to_tuple(self) -> Tuple:\n return self.symbol, tuple(self.dofs), self.factor, tuple(tuple(t) for t in self.qn_list)", "def items(self) -> tuple:\n return tuple((field[0], getattr(self, field[0])) for field in self._c_struct._fields_)", "def as_tuple(self):\n return tuple(self._v)", "...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Increase connections of the given FCP devices
def increase_fcp_connections(self, fcp_list, assigner_id=None): with database.get_fcp_conn(): fcp_connections = {} for fcp in fcp_list: # increase connections by 1 fcp_connections[fcp] = self.db.increase_connections_by_assigner(fcp, assigner_id) ...
[ "def decrease_fcp_connections(self, fcp_list):\n with database.get_fcp_conn():\n fcp_connections = {}\n for fcp in fcp_list:\n try:\n LOG.info('Decreasing the connections of FCP device {}'.format(fcp))\n # Decrease connections of FCP ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Decrease connections of FCP devices by 1
def decrease_fcp_connections(self, fcp_list): with database.get_fcp_conn(): fcp_connections = {} for fcp in fcp_list: try: LOG.info('Decreasing the connections of FCP device {}'.format(fcp)) # Decrease connections of FCP device by 1...
[ "def disconnect(self, device):", "def maxconn(self):\n return 1", "def test_dp_disconnect_cleanup(self):\n valve = self.valves_manager.valves[self.DP_ID]\n port_num = list(valve.dp.ports.keys())[0]\n self.port_expected_status(port_num, 1)\n self.disconnect_dp()...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This method is to check if the FCP wwpn_npiv or wwpn_phy is empty string, if yes, raise error
def _valid_fcp_devcie_wwpn(self, fcp_list, assigner_id): for fcp in fcp_list: fcp_id, wwpn_npiv, wwpn_phy, *_ = fcp if not wwpn_npiv: # wwpn_npiv not found in FCP DB errmsg = ("NPIV WWPN of FCP device %s not found in " "database."...
[ "def _are_fields_empty(self):\n if not self._gmail_addr:\n raise Exception('The gmail email address cannot be empty.')\n if not self._receiptant_addr:\n raise Exception(\"The receiptant address cannot be empty.\")\n if not self._subject:\n self.subject = ''\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Reserve FCP devices in the FCP database and set fcp multipath template id.
def reserve_fcp_devices(self, fcp_list, assigner_id, fcp_template_id): self.db.reserve_fcps(fcp_list, assigner_id, fcp_template_id)
[ "def release_fcp_devices(self, assigner_id, fcp_template_id):\n with database.get_fcp_conn():\n try:\n if fcp_template_id is None:\n errmsg = (\"fcp_template_id is not specified \"\n \"while releasing FCP devices.\")\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Unreserve FCP devices in the FCP database and unset fcp multipath template id.
def unreserve_fcp_devices(self, fcp_list): self.db.unreserve_fcps(fcp_list)
[ "def release_fcp_devices(self, assigner_id, fcp_template_id):\n with database.get_fcp_conn():\n try:\n if fcp_template_id is None:\n errmsg = (\"fcp_template_id is not specified \"\n \"while releasing FCP devices.\")\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Release FCP devices that belongs to the assigner_id and fcp_template_id.
def release_fcp_devices(self, assigner_id, fcp_template_id): with database.get_fcp_conn(): try: if fcp_template_id is None: errmsg = ("fcp_template_id is not specified " "while releasing FCP devices.") LOG.error(er...
[ "def reserve_fcp_devices(self, fcp_list, assigner_id, fcp_template_id):\n self.db.reserve_fcps(fcp_list, assigner_id, fcp_template_id)", "def unreserve_fcp_devices(self, fcp_list):\n self.db.unreserve_fcps(fcp_list)", "def do_release_device(self, inp):\n self.agfs.releasedev()", "def rele...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a dict of all FCPs in FCP_DB
def get_fcp_dict_in_db(self): try: # Get all FCPs found in DB. fcp_in_db = self.db.get_all_fcps_of_assigner() except exception.SDKObjectNotExistError: fcp_in_db = list() # this method is called by _sync_db_with_zvm, # change this msg to warnin...
[ "def pb_instances(fb_dir, fbr, f2p):\n fb_file = '%s/%s.tsv'%(fb_dir,fbr)\n pb = []\n with open(fb_file,'r') as f:\n for row in csv.DictReader(f,delimiter='\\t'):\n pb.append({f2p[fbr][key]:value for (key,value) in row.iteritems() if key in f2p[fbr]})\n\n return pb", "def get_all_fac...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a dict of all FCPs in ZVM
def get_fcp_dict_in_zvm(self): # Get the userid of smt server smt_userid = zvmutils.get_smt_userid() # Return a dict of all FCPs in ZVM fcp_dict_in_zvm = self.get_all_fcp_pool(smt_userid) fcp_id_to_object = {fcp.lower(): fcp_dict_in_zvm[fcp] for fcp in...
[ "def zfs( self ):\n zpool_list = zfs.pool.list( self.name )\n return zpool_list[self.name]", "def get_all_instances():\n resources = query_openvz(False, \"ctid,hostname,status\")\n candidates = {}\n for r in resources:\n candidates[r[0]] = {\"vm_id\": r[0],\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Update FCP records queried from zVM into FCP table.
def sync_fcp_table_with_zvm(self, fcp_dict_in_zvm): with database.get_fcp_conn(): # Get a dict of all FCPs already existed in FCP table fcp_dict_in_db = self.get_fcp_dict_in_db() # Divide FCPs into three sets inter_set = set(fcp_dict_in_zvm) & set(fcp_dict_in_db) ...
[ "def _sync_db_with_zvm(self):\n\n LOG.info(\"Enter: Sync FCP DB with FCP info queried from z/VM.\")\n LOG.info(\"Querying FCP status on z/VM.\")\n # Get a dict of all FCPs in ZVM\n fcp_dict_in_zvm = self.get_fcp_dict_in_zvm()\n # Update the dict of all FCPs into FCP table in datab...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sync FCP DB with the FCP info queried from zVM
def _sync_db_with_zvm(self): LOG.info("Enter: Sync FCP DB with FCP info queried from z/VM.") LOG.info("Querying FCP status on z/VM.") # Get a dict of all FCPs in ZVM fcp_dict_in_zvm = self.get_fcp_dict_in_zvm() # Update the dict of all FCPs into FCP table in database sel...
[ "def sync_fcp_table_with_zvm(self, fcp_dict_in_zvm):\n with database.get_fcp_conn():\n # Get a dict of all FCPs already existed in FCP table\n fcp_dict_in_db = self.get_fcp_dict_in_db()\n # Divide FCPs into three sets\n inter_set = set(fcp_dict_in_zvm) & set(fcp_di...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a FCP Multipath Template and return the basic information of
def create_fcp_template(self, name, description: str = '', fcp_devices: str = '', host_default: bool = False, default_sp_list: list = None, min_fcp_paths_count: int = None): LOG.info("Try to create a"...
[ "def create(self, template):\n raise NotImplementedError('Create Template not implemented')", "def make_template(self):\n\n missing = TEMPLATE_REQUIRED.difference(self.data)\n if missing:\n return (\"<h3>Template must have %s filled in.</h3>\" %\n ', '.join(missing))...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Edit a FCP Multipath Template
def edit_fcp_template(self, fcp_template_id, name=None, description=None, fcp_devices=None, host_default=None, default_sp_list=None, min_fcp_paths_count=None): LOG.info("Enter: edit_fcp_template with args {}".format( (fcp_...
[ "def edit_template(self, data: dict) -> None:\n self.add_operation({\n 'op': 'editTemplate',\n 'data': data,\n })", "def set_templatefile(self):\n\n self.par_template = filedialog.askopenfilename()\n self.entry_template.delete(0, END)\n self.entry_template....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
group raw_item with template_id and path
def _update_template_fcp_raw_usage(self, raw_usage, raw_item): (fcp_id, template_id, path_id, assigner_id, connections, reserved, wwpn_npiv, wwpn_phy, chpid, state, owner, tmpl_id) = raw_item if not raw_usage.get(template_id, None): raw_usage[template_id] = {} if no...
[ "def _group_templates(templates):\n grouped = groupby(templates, itemgetter(2))\n\n for key, sub_iter in grouped:\n yield key, list(sub_iter)", "def _iter_paths(self, fields):\n for template in self._template_list:\n try:\n yield template.format(**fields)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
shrink fcp list in statistics sections to range fcp
def _shrink_fcp_list_in_statistics_usage(self, statistics_usage): for template_statistics in statistics_usage.values(): for path in template_statistics: # count total and available fcp before shrink if template_statistics[path]["total"]: template_s...
[ "def segment_filter_by_size(cn_amp, binsize = 10000, fold = 5):\n # old version\n # return cn_amp[cn_amp['End'] - cn_amp['Start'] >= fold * binsize]\n\n cn_amp_merged = misc.merge_bed(cn_amp, gap = 100000)\n cn_amp_drop = pd.DataFrame([\n row for row in cn_amp_merged if (row[2] - row[1] < fold * ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get FCP Multipath Templates detail info.
def get_fcp_templates_details(self, template_id_list=None, raw=False, statistics=True, sync_with_zvm=False): not_exist = [] if template_id_list: for template_id in template_id_list: if not self.db.fcp_template_exist_in_db(template_id): ...
[ "def get_template_info(self):\n rospack = rospkg.RosPack()\n path_template = rospack.get_path('package_generator_templates')\n path_template += \"/templates/\"\n template_names = os.listdir(path_template)\n\n return [path_template, template_names]", "def get_device_templates(sel...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Delete FCP Multipath Template by id.
def delete_fcp_template(self, template_id): return self.db.delete_fcp_template(template_id)
[ "def delete_service_template(self, id):\n return self._request('delete', path='/templates/{}'.format(id), value_only=True)", "def delete_template(request):\n if request.method == 'POST':\n tid = int(request.POST.get('tid'))\n t_kpi.objects.filter(id=tid).delete()\n \n return ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set up the Bluetooth LE Scanner.
def setup_scanner(hass, config, see, discovery_info=None): # noqa: C901 new_devices = {} hass.data.setdefault(DATA_BLE, {DATA_BLE_ADAPTER: None}) def handle_stop(event): """Try to shut down the bluetooth child process nicely.""" # These should never be unset at the point this runs, but ju...
[ "def _make_ble_connection(self):\n if self.device == None:\n adapter = pygatt.backends.GATTToolBackend()\n nuki_ble_connection_ready = False\n\n while nuki_ble_connection_ready == False:\n print(\"Starting BLE adapter...\")\n adapter.start()\n print(\"Init Nuki BLE connection....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Discover Bluetooth LE devices.
def discover_ble_devices(): _LOGGER.debug("Discovering Bluetooth LE devices") try: adapter = pygatt.GATTToolBackend() hass.data[DATA_BLE][DATA_BLE_ADAPTER] = adapter devs = adapter.scan() devices = {x["address"]: x["name"] for x in devs} _LOGG...
[ "def search(self,num):\n while True:\n if num ==1:\n device_address = None\n time.sleep(3) # Sleep three seconds\n nearby_devices = bluetooth.discover_devices()\n\n for mac_address in nearby_devices:\n device_address =...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Lookup Bluetooth LE devices and update status.
def update_ble(now): devs = discover_ble_devices() if devs_track_battery: adapter = hass.data[DATA_BLE][DATA_BLE_ADAPTER] for mac in devs_to_track: if mac not in devs: continue if devs[mac] is None: devs[mac] = mac ...
[ "def search(self,num):\n while True:\n if num ==1:\n device_address = None\n time.sleep(3) # Sleep three seconds\n nearby_devices = bluetooth.discover_devices()\n\n for mac_address in nearby_devices:\n device_address =...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set sys.defaultencoding to `sys_enc` and update stdout/stderr writers to corresponding encoding
def setup_console(sys_enc=default_unicode): global ansi reload(sys) try: if sys.platform.startswith("win"): import ctypes enc = "cp%d" % ctypes.windll.kernel32.GetOEMCP() else: enc = (sys.stdout.encoding if sys.stdout.isatty() else ...
[ "def setdefaultencoding(name):\n\tpass", "def SetDefaultEncoding(*args, **kwargs):\n pass", "def uenc_set_encoding(encoding=None):\n global uenc_encoding\n\n if encoding is None:\n import locale\n LC_CTYPE = locale.LC_CTYPE\n language, encoding = locale.getlocale(LC_CTYPE)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates align_info.json file containing warp_matrices and .geojson data. If that file exists, add warp_matrices with None value for new products (if found) and doesn't touch existing data
def create_init_align_json(data_path): data_path = os.path.normpath(data_path) json_file_name = os.path.join(data_path, "align_info.json") if os.path.exists(json_file_name): with open(json_file_name, "r") as f: align_info = json.load(f) else: geojson_file_name = "{}.geojson"...
[ "def align_data(data_path, aligned_data_path=None,\n align_info_file=None):\n if aligned_data_path is None:\n aligned_data_path = os.path.join(data_path, 'aligned')\n if align_info_file is None:\n align_info_file = os.path.join(data_path, 'align_info.json')\n # create directory ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Warp tiff file with warp matrix and areate new tiff file.
def warp_image(image, warp_matrix, output_image, size=None): dataset = gdal.Open(image) array = dataset.ReadAsArray() if size is None: size = array.shape[-2:] band_list = [] for i in range(dataset.RasterCount): band = dataset.GetRasterBand(i + 1) # 1-based index warped_band...
[ "def reproject(self, file):\n fname = os.path.basename(file)\n dst = os.path.join(self.tif_folder, \"proj_\" + fname)\n out = gdal.Warp(dst, file, dstSRS=PROJ)\n del out", "def reprojectTiff(self,inFname,outFname):\n if not os.path.exists(inFname):\n print \"reproject...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Align image to base image and return warp matrix.
def _get_warp_matrix(base_image, image): # Allready unused # Define the motion model warp_mode = cv2.MOTION_TRANSLATION warp_matrix = np.eye(2, 3, dtype=np.float64) # Specify the number of iterations. number_of_iterations = 5000 # Specify the threshold of the increment # in the correlatio...
[ "def test_03_02_align_separately(self):\n np.random.seed(0)\n shape = (47, 53)\n i, j = np.mgrid[0 : shape[0], 0 : shape[1]]\n for offset in ((3, 5), (-3, 5), (3, -5), (-3, -5)):\n image1 = np.random.uniform(size=shape).astype(np.float32)\n image2 = image1[\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Aligns all products in data directory by given base product. e.g. align_data("Ijevan", "Ijevan_aligned")
def align_data(data_path, aligned_data_path=None, align_info_file=None): if aligned_data_path is None: aligned_data_path = os.path.join(data_path, 'aligned') if align_info_file is None: align_info_file = os.path.join(data_path, 'align_info.json') # create directory for aligned...
[ "def align():\n sh.clustalo('-i', amplified, '-o', aligned)", "def align_index(standard, raw_data, *, axis='both'):\n if axis is 'both':\n aligned_data = raw_data.reindex(major_axis=standard.index, minor_axis=standard.columns)\n elif axis is 'major':\n aligned_data = raw_dat...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test Email class is built successfully into a string
def test_email_build(email): def _check_string(build, prefix, string): expected = f'{prefix}: {string}' if string not in ['', ' '] else f'{prefix}:' assert expected in build, f'{expected} is not in built string:\n{build}' build = email.build() assert isinstance(build, str), f'Expected str ...
[ "def test_obj_creation_email(self):\n eq_(self.obj.email, \"ignucius@example.org\")", "def test_reformat_email_2(self):\n email = 'test@example.com'\n self.assertEqual(self.cmd.reformat_email(email), 'test@example.com')", "def test_prepare_email():\n subject = \"Send this subject value\"...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test client is active property method
def test_is_active(self): code, msg = self.client.server.noop() assert code == 250, f'Client is not active. Code - {code}. Message - {msg}' assert self.client.is_active, 'Client is not active'
[ "def test_properties(mqtt_client: MockedMQTT):\n device = DysonPureHotCoolLink(SERIAL, CREDENTIAL, DEVICE_TYPE)\n device.connect(HOST)\n\n # Status\n assert device.focus_mode is True\n\n new_status = {\"product-state\": {\"ffoc\": [\"ON\", \"OFF\"]}}\n mqtt_client.state_change(new_status)\n ass...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test the client close function (quitting SMTP server) & reconnecting post close
def test_close_and_reconnect(self): assert self.client.is_active, 'Client must be active to test quit' self.client.close() assert not self.client.is_active, 'Client must be inactive following close call' self.client.reconnect() assert self.client.is_active, 'Client must be ac...
[ "def close_client(session):\n # taken from https://github.com/giampaolo/pyftpdlib/ \\\n # blob/master/pyftpdlib/test/__init__.py\n try:\n if session.sock is not None:\n try:\n resp = session.quit()\n except Exception:\n pass\n el...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Takes a repo name like "gocodeup/codeupsetupscript" and returns a dictionary with the language of the repo and the readme contents.
def process_repo(repo: str) -> Dict[str, str]: contents = get_repo_contents(repo) readme_download_url = get_readme_download_url(contents) if readme_download_url == "": readme_contents = None else: readme_contents = requests.get(readme_download_url).text return { "repo": repo,...
[ "def readme_text():\n return P.README.read_text(encoding=\"utf-8\")", "def readme():\n with open('README.rst') as readme_file:\n return readme_file.read()", "def pkg_info():\n try:\n doc = __doc__.decode(\"UTF-8\")\n except (AttributeError, UnicodeError):\n doc = __doc__ # Pytho...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Loop through all of the repos and process them. Returns the processed data.
def scrape_github_data() -> List[Dict[str, str]]: REPOS = get_all_urls() return [process_repo(repo) for repo in REPOS]
[ "def update_existing_repos(repos, auth):\n for repo in repos:\n github_api = repo.get('github_api')\n if github_api:\n print('* Repo checking for update: [ %s ]' % repo['name'])\n git_repo = process_request(url=github_api, auth=auth)\n process_tags(git_repo=git_repo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the tuple for the present toplevel group
def getCurrentTop(self): topLevelItems = sorted(self.conaryClient.getUpdateItemList()) for name, version, flavor in topLevelItems: if name.startswith('group-') and name.endswith('-appliance'): break else: logger.warn('Unable to find top-level group') ...
[ "def get_group():\n root = QgsProject.instance().layerTreeRoot()\n return root", "def get_group(self): # real signature unknown; restored from __doc__\n return \"\"", "def toplevel(self):\n return self.simplified().deatomized()", "def getGroupPrevChild(self) -> \"SoBase const *\":\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the tuple for the new toplevel group after applying an update job.
def getUpdatedTop(self, topTuple, updateJob): added = set() topErased = False for jobList in updateJob.getJobs(): for (name, (oldVersion, oldFlavor), (newVersion, newFlavor), isAbsolute) in jobList: if name == topTuple.name: if ...
[ "def getCurrentTop(self):\n topLevelItems = sorted(self.conaryClient.getUpdateItemList())\n for name, version, flavor in topLevelItems:\n if name.startswith('group-') and name.endswith('-appliance'):\n break\n else:\n logger.warn('Unable to find top-level gr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return to the previous address
def backAddress(wallet): wallet.backAddress()
[ "def moveToPrevious(self):\n pass", "def history_back(state):\n\n state.nav.undo_step()", "def back(self):\n self._command(\"goBack\")", "def backstep(self):\n\n self.timestep -= 1\n self.historyLayer.backstep()", "def previous_field(self):\n self.stack[-1].previous()",...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Spawn a bash shell
def pexpect_spawn_bash(self, line): self.spawn("/usr/bin/env bash", "\r\nbash> ", "\r\n> ", "PS1='bash> '")
[ "def spawn_bash(mycommand,env={},debug=False,opt_name=None,**keywords):\r\n\targs=[BASH_BINARY]\r\n\tif not opt_name:\r\n\t opt_name=mycommand.split()[0]\r\n\tif debug:\r\n\t args.append(\"-x\")\r\n\targs.append(\"-c\")\r\n\targs.append(mycommand)\r\n\treturn spawn(args,env=env,opt_name=opt_name,**keywords)",...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Spawn a Root session
def pexpect_spawn_root(self, line): self.spawn("root", "\r\nroot \[\d+\] ", "\r\n> ")
[ "def start_session(self):\n if self._in_session:\n return\n\n enter = getattr(self._underlying_runner, '__enter__', None)\n if enter is not None:\n logging.info('Starting session.')\n self._in_session = True\n enter()\n else:\n logging.error('Keep alive not supported.')", "def...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the pexpect child object (for debugging)
def pexpect_get_child(self, line): return self._child
[ "def child ( p , *a ) :\n return LoKi.MCChild.child ( p , *a )", "def expect(self, obj):\r\n return Expect(obj, self._messageHandler, context=self._currently_running)", "def test_stdout(self):\n data = []\n proto = MagicMock()\n p = Channel3Protocol('joe', data.append, proto)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Run SCWRL4 to reconstruct sidechains.
def run(self, data, config=None, pipeline=None): model = self.get_vals(data) outfile = Path(model).with_suffix(".scwrl4.pdb") if not outfile.exists() or self.overwrite: command_line = self.SCWRL4( (self.bin_dir, "Scwrl4"), options={"input": model, "ou...
[ "def stage_second_four_edges_555(self):\n\n # return if they are already staged\n if self.y_plane_edges_are_l4e() and self.z_plane_edges_are_l4e():\n return\n\n first_four_wing_strs = list(self.get_x_plane_wing_strs())\n wing_strs_for_second_four = []\n\n log.info(\"fir...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Uses the WsRemoteService framework to parse connectionrelated args and establish a connection to a remote projectServer. Instantiates a local version of SubjectInterface to handle client requests coming from the projectServer connection.
def __init__(self, args, webSocketChannelName='wsSubject'): self.subjectInterface = SubjectInterface(subjectRemote=False) self.wsRemoteService = WsRemoteService(args, webSocketChannelName) self.wsRemoteService.addHandlerClass(SubjectInterface, self.subjectInterface)
[ "def connect_to_server():\n\n if verbose:\n Logger().info(\"Setting up IPC client\")\n\n global ipc_client\n ipc_client = IPC()\n ipc_client.connect()\n\n # Wait for connection\n time.sleep(1)\n\n if verbose:\n Logger().info(\"Client successfully connected\")\n\n server_proxy =...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
create string representation of args and kwargs
def args_to_str(*args, **kwargs): rv = "" for arg in args: rv += "{0}, ".format(str(arg)) for key, val in kwargs: rv += "{0} = {1}, ".format(key,str(val)) return rv.rstrip(', ')
[ "def kwargs_to_string(kwargs):\n outstr = ''\n for arg in kwargs:\n outstr += ' --{} {}'.format(arg, kwargs[arg])\n return outstr", "def _serialize_params(cls, *args, **kwargs):\n args_list = list(map(str, args))\n args_list.extend([str(kwargs), cls.__name__])\n key = \"\".joi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets `feature` to `feature_value` in this feature set. `feature_value` may be HAS_FEATURE, NOT_HAS_FEATURE, a homorganic variable, or None (which clears the feature from the feature set).
def set (self, feature, feature_value): if feature not in self._features: # QAZ: error message. raise MismatchedTypesError() if feature_value is None: # It is of no consequence if the feature has no existing # value when it is being removed anyway. ...
[ "def set_feature(self, feature):\n self.feature = feature # pragma: no cover", "def set_features_hypo(self, feature_name = '', feature_value = ''):\n self.features_hypo[feature_name] = feature_value", "def remove_feature(self, feature):\n if not isinstance(feature, Feature):\n r...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates a Person Object and adds it to the repository
def add_person(self, id, name, phone, address): p = Person(id, name, phone, address) self.__validator.validate(p) self.__repo + p
[ "def add_new_person_to_family(self):\n print('ADD NEW PERSON TO FAMILY')\n family_db = JsonDatabase(self.DATABASE_NAME, self.DATABASE_DIR)\n new_person = Person()\n new_person.set_firstname(input('Type firstname: '))\n new_person.set_lastname(input('Type lastname: '))\n new...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Removes a person from the repository
def remove_person(self, id, name, phone, address): p = Person(id, name, phone, address) self.__repo - p
[ "def remove_person(self, handle, transaction):\n\n if self.readonly or not handle:\n return\n person = self.get_person_from_handle(handle)\n #self.genderStats.uncount_person (person)\n #self.remove_from_surname_list(person)\n if isinstance(handle, UNITYPE):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a list of all persons that match the given phone number
def search_by_phone(self, item): l = self.get_all() list = [] for i in l: if item.lower() in i.phone_number.lower(): list.append(i) return list
[ "def Search_Contact_PhoneNumber(self, phoneNumber):\n exists = False\n result_list = []\n\n for i in range(self.Get_ContactList_Length()):\n if self.__contactList[i].Get_PhoneNumber() == phoneNumber:\n result_list.append(self.Get_Contact_Details(i))\n return res...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Folds the given data over a given period.
def fold(time, period, origo=0.0, shift=0.0, normalize=True, clip_range=None): tf = ((time - origo)/period + shift) % 1. if not normalize: tf *= period if clip_range is not None: mask = np.logical_and(clip_range[0]<tf, tf<clip_range[1]) tf = tf[mask], mask return tf
[ "def fold(self, period=None, midpoint_epoch=None):\n\n folded = self.copy()\n folded.remove_column('time')\n\n if midpoint_epoch is None:\n midpoint_epoch = self.time[0]\n else:\n midpoint_epoch = Time(midpoint_epoch)\n\n period_sec = period.to_value(u.s)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Contamination from a third object radiating as a blackbody given a contamination estimate in a reference wavelength.
def contamination_bb(c1, T, wl1, wl2): B1 = planck(T, wl1) B2 = planck(T, wl2) return c1*(B2/B1)
[ "def canopy_boundary_layer_conductance(self, wind, canht):\n # z0m roughness length governing momentum transfer [m]\n z0m = self.dz0v_dh * canht\n \n # z0h roughness length governing transfer of heat and vapour [m]\n # *Heat tranfer typically less efficent than momentum transfer. Ther...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert label name to DataEntryId
def label_to_data_id(self): return {"Altitude": DataEntryIds.CALCULATED_ALTITUDE, "MaxAltitude": None, "State": DataEntryIds.STATE, "Pressure": DataEntryIds.PRESSURE, "Acceleration": [DataEntryIds.ACCELERATION_X, DataEntryIds.ACCELERATION_Y, ...
[ "def id_for_label(value):\n return f\"labels->{value}\"", "def label_from_id(id_string):\n temp = id_string.replace('_', ' ').strip()\n label = temp[0].upper() + temp[1:] \n return label", "def label2ParamId(cls, label):\n param = ''\n label = label.lower().replace('&amp;', '')\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a FetchedAvailability corresponding to a given room.
def get_fa_for_room(building_name, room_name): #TODO: move to models.py? building = Building.objects.get(name=building_name) rooms = (Room.objects.filter(kind__building=building) .filter(name=room_name)) if len(rooms) != 1: errmsg = ("%d rooms with name %s in building %s (expected 1)"...
[ "def details(self, room, **kwargs):\n if isinstance(room, Room):\n roomId = room.id\n elif isinstance(room, basestring):\n roomId = room\n else:\n raise ValueError(\"missing room Id\")\n apiparm = []\n return Room(self.api.session.get(self._uri_app...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Queries django for the current list of time_ranges of when that room is free on that date (string in YYYYMMDD format or datetime.date)
def get_db_avails(building_name, room_name, date): # 1. find room. 2. find avail object. 3. get avails filtered by date. fa = get_fa_for_room(building_name, room_name) freetimeranges = fa.freetimerange_set.filter(date=date) return [(ftr.time.start, ftr.time.end) for ftr in freetimeranges]
[ "def getFreeRoomsForTimespan(self, dateOfArrival, dateOfDepature):\n returnValue = list()\n\n for curRoom in self.__rooms:\n if(curRoom.isFree(dateOfArrival, dateOfDepature)):\n returnValue.append(curRoom)\n\n return returnValue", "def get_table_time_slots_available(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return style for scrollbars.
def scrollbar(): return """QScrollBar{ border: none; background: white; width:7px; margin: 0px 0px 0px 0px; } QScrollBar::handle{ background: #333333; min-height: 0px; } QS...
[ "def getStyle(self, index):\n result = { 'width' : 1, 'top' : 0, 'write' : True }\n if index == BLACK_BAR:\n result['height'] = self.height\n if index == TALL_BAR:\n result['height'] = self.height + 5\n if index == WHITE_BAR:\n result['write'] = False\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Method to instantiate stateful fetchers once
def instantiateStatefulFetcher( self, statefulFetcher: "Type[StatefulFetcher]", setup_block: "Optional[Mapping[str, Any]]" = None, ) -> "StatefulFetcher": instStatefulFetcher = self._sngltn.get(statefulFetcher) if instStatefulFetcher is None: # Let's augment the l...
[ "def __init_manager(self):\n try:\n self._db_info_cache = pd.read_hdf(\n self._hdf5_filepath, DATABASE_HDF5_STRUCT[\"metadata-db-info\"]\n )\n self._init_state = 1\n if not self.initiate_memory_cache():\n raise RuntimeError(\"Cannot in...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This method adds scheme handlers (aka "fetchers") from a given stateful fetcher, also adding the needed programs
def addStatefulSchemeHandlers( self, statefulSchemeHandler: "Type[AbstractStatefulFetcher]", fetchers_setup_block: "Optional[Mapping[str, Mapping[str, Any]]]" = None, ) -> None: # Get the scheme handlers from this fetcher schemeHandlers = statefulSchemeHandler.GetSchemeHandl...
[ "def addSchemeHandlers(\n self,\n schemeHandlers: \"Mapping[str, Union[ProtocolFetcher, Type[AbstractStatefulFetcher]]]\",\n fetchers_setup_block: \"Optional[Mapping[str, Mapping[str, Any]]]\" = None,\n ) -> None:\n if isinstance(schemeHandlers, dict):\n instSchemeHandlers ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This method adds scheme handlers (aka "fetchers") or instantiates stateful scheme handlers (aka "stateful fetchers")
def addSchemeHandlers( self, schemeHandlers: "Mapping[str, Union[ProtocolFetcher, Type[AbstractStatefulFetcher]]]", fetchers_setup_block: "Optional[Mapping[str, Mapping[str, Any]]]" = None, ) -> None: if isinstance(schemeHandlers, dict): instSchemeHandlers = dict() ...
[ "def addStatefulSchemeHandlers(\n self,\n statefulSchemeHandler: \"Type[AbstractStatefulFetcher]\",\n fetchers_setup_block: \"Optional[Mapping[str, Mapping[str, Any]]]\" = None,\n ) -> None:\n\n # Get the scheme handlers from this fetcher\n schemeHandlers = statefulSchemeHandle...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This method generates a random passphrase, which is stored in a crypt4gh encrypted file (along with the FUSE filesystem used) using either the default WfExSbackend public key, or the public keys stored in the files provided as a parameter. It returns the FUSE filesystem, the command to be used to mount, the generated p...
def generateSecuredWorkdirPassphrase( self, workdir_passphrase_file: "AbsPath", private_key_filename: "Optional[AnyPath]" = None, private_key_passphrase: "Optional[str]" = None, public_key_filenames: "Sequence[AnyPath]" = [], ) -> "Tuple[EncryptedFSType, AnyPath, str, Sequenc...
[ "def generate_keys():\n aeskey = get_random_bytes(16)\n rsakey = RSA.generate(2048)\n\n \"\"\" Old, bad(?) implementation. We're not using this anymore. To be fair, we never really got an explanation of why it was bad to directly write into bootloader.c, then make, then remove the key, but it was phased ou...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets the mediated_device_types of this V1NodeMediatedDeviceTypesConfig.
def mediated_device_types(self): return self._mediated_device_types
[ "def mediated_devices_types(self):\n return self._mediated_devices_types", "def mediated_device_types(self, mediated_device_types):\n\n self._mediated_device_types = mediated_device_types", "def mediated_devices_types(self, mediated_devices_types):\n\n self._mediated_devices_types = mediate...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the mediated_device_types of this V1NodeMediatedDeviceTypesConfig.
def mediated_device_types(self, mediated_device_types): self._mediated_device_types = mediated_device_types
[ "def mediated_devices_types(self, mediated_devices_types):\n\n self._mediated_devices_types = mediated_devices_types", "def mediated_devices_types(self):\n return self._mediated_devices_types", "def mediated_device_types(self):\n return self._mediated_device_types", "def device_type(self,...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets the mediated_devices_types of this V1NodeMediatedDeviceTypesConfig. Deprecated. Use mediatedDeviceTypes instead.
def mediated_devices_types(self): return self._mediated_devices_types
[ "def mediated_device_types(self):\n return self._mediated_device_types", "def mediated_devices_types(self, mediated_devices_types):\n\n self._mediated_devices_types = mediated_devices_types", "def mediated_device_types(self, mediated_device_types):\n\n self._mediated_device_types = mediated...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the mediated_devices_types of this V1NodeMediatedDeviceTypesConfig. Deprecated. Use mediatedDeviceTypes instead.
def mediated_devices_types(self, mediated_devices_types): self._mediated_devices_types = mediated_devices_types
[ "def mediated_device_types(self, mediated_device_types):\n\n self._mediated_device_types = mediated_device_types", "def mediated_devices_types(self):\n return self._mediated_devices_types", "def mediated_device_types(self):\n return self._mediated_device_types", "def device_type(self, dev...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the node_selector of this V1NodeMediatedDeviceTypesConfig.
def node_selector(self, node_selector): if node_selector is None: raise ValueError("Invalid value for `node_selector`, must not be `None`") self._node_selector = node_selector
[ "def node_selector(self, node_selector):\n self._node_selector = node_selector", "def setNodeSourceType(self, nodeID, sourceType):\n index = self.getNodeIndexbyID(nodeID)\n en.setnodevalue(ph=self.epanet_proj, index=index, property=en.SOURCETYPE, value=sourceType)", "def setSelector(self, s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tests that a page object field contains a definition with the expected values.
def test_models_xapi_fields_object_page_object_field(field): assert field.definition.type == "http://activitystrea.ms/schema/1.0/page" assert field.definition.name == {"en": "page"}
[ "def test_definition(self):\n name_field = StringField()\n age_field = IntField()\n\n class DummyPerson(Document):\n name = name_field\n age = age_field\n non_field = True\n \n self.assertEqual(DummyPerson._fields['name'], name_field)\n self...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Overrides twisted.conch.recvline.RecvLine.initializeScreen() to not to show prompt
def initializeScreen(self): self.terminal.reset() self.setInsertMode()
[ "def _init(self):\n self._stdscr = curses.initscr()\n self._stdscr.keypad(1)\n self._stdscr.nodelay(1)\n self._stdscr.clear()\n curses.cbreak()\n curses.noecho()\n\n event.event(sys.stdin).connect(self._userinput)", "def prompt(self):\n\t\t_globals._console.write(f...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Overrides twisted.conch.recvline.RecvLine.drawInputLine() to reset prompt
def drawInputLine(self): self.terminal.write(self.prompt + ''.join(self.lineBuffer))
[ "def promptFromScratch(self):\n\n # Draw prompt message\n self.stdscr.addstr(self.height - 1, 0, self.prompt)\n self.stdscr.addstr(self.height - 1, len(self.prompt) + 1,\n self.string[self.view:self.view + self.width -\n len(self.prompt) - 2])\n\n # Fill with spaces...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set attribute inside vectorized environments.
def set_attr(self, attr_name, value, indices=None): raise RuntimeError('This method is not implemented')
[ "def setMVector(*args, **kwargs):\n \n pass", "def setParticleAttr(randomVector=float, object=\"string\", relative=bool, floatValue=float, randomFloat=float, attribute=\"string\", vectorValue=float):\n pass", "def _set_vectors(self):\r\n \r\n pass", "def set_attribute(self,att,val):...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Call instance methods of vectorized environments.
def env_method(self, method_name, *method_args, indices=None, **method_kwargs): raise RuntimeError('This method is not implemented')
[ "def Vector(*args, **kwargs): # real signature unknown\r\n pass", "def _execute_vector(self):\r\n \r\n self._result = self.current_vector.execute(self.formatted_args)", "def _init_vectors(cls) :\n if len(cls._vectorkeys) == 0 :\n def pred(c) :\n return inspect.i...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Adds a multilayer LSTM to the model parameters.
def create_multilayer_lstm_params(num_layers, in_size, state_size): lstm_layers = [] for i in range(num_layers): lstm_layer = torch.nn.LSTMCell(input_size=int(in_size), hidden_size=int(state_size), bias=True) lstm_layers.append(lstm_layer) in_size = state_size return torch.nn.ModuleL...
[ "def three_layer_lstm(self, num_neurons_layer_1, num_neurons_layer_2,\n num_neurons_layer_3, num_epochs, dropout,\n X_train, Y_train, X_val, Y_val):\n model = Sequential()\n # layer: 1\n model.add(LSTM(num_neurons_layer_1, activation='tanh', return_se...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Update a single column in a vector field.
def test_update_column(fake_vector: Path) -> None: # change the value of the file vector_field = sw.VectorField() vector_field._update_file({"new": str(fake_vector)}) # read a column vector_field.w_column.v_model = "GID_0" # first one to select assert vector_field.v_model["column"] == "GID_0"...
[ "def set_col(self, i, vec):\n self.data[i+0] = vec[0]\n self.data[i+3] = vec[1]\n self.data[i+6] = vec[2]", "def update_cell(self, row_id, field, value):\n\n pass", "def update(self, *args):\n return _vnl_vectorPython.vnl_vectorF_update(self, *args)", "def update(self, *args):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the number of mines that are within one row and column of a given cell, not including the cell itself.
def nearby_mines(self, cell): # Keep count of nearby mines count = 0 # Loop over all cells within one row and column for i in range(cell[0] - 1, cell[0] + 2): for j in range(cell[1] - 1, cell[1] + 2): # Ignore the cell itself if (i, j) == ce...
[ "def num_mines(self) -> int:\n count = 0\n for row in self:\n for cell in row:\n if cell.mine:\n count += 1\n return count", "def count_adjacent_mines(self, *, column, row):\r\n num_adjacent_mines = 0\r\n for i in range(-1, 2):\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Checks if all mines have been flagged.
def won(self): return self.mines_found == self.mines
[ "def check_if_all_tiles_cleared(self):\r\n all_cleared = True\r\n for tile in self.tiles.values():\r\n if not tile.is_mine:\r\n if tile.is_hidden:\r\n all_cleared = False\r\n break\r\n return all_cleared", "def _new_ships_are_all...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the set of all cells in self.cells known to be mines.
def known_mines(self): return {cell for cell in self.cells if len(self.cells)==self.count}
[ "def MinesKnown(self):\n if len(self.cells) == self.count:\n return set(self.cells)\n else:\n return set()", "def SafesKnown(self):\n if self.count == 0:\n return set(self.cells)\n else:\n return set()", "def unset_cells(self):\n ret...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Updates internal knowledge representation given the fact that a cell is known to be a mine.
def mark_mine(self, cell): if cell in self.cells and self.count>0: self.cells-={cell} self.count-=1 #flags this sentence as having been changed - to try again to subtract if subset of others self.changed=True
[ "def update_cell(self, adj, cell):\n adj.g = cell.g + 1\n adj.h = self.get_cost(adj)\n adj.parent = cell\n adj.f = adj.h + adj.g", "def updateCell(self, grid, cell, state):\r\n grid[cell] = state\r\n if self.playerInfo.isP1:\r\n self.view.iconsToDraw.append(cel...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Updates internal knowledge representation given the fact that a cell is known to be safe.
def mark_safe(self, cell): if cell in self.cells: self.cells-={cell} self.changed=True
[ "def update(self, row, col, change):\n cell = self.grid[row][col]\n\n if isinstance(cell, dict):\n if len(cell.keys()) == 0:\n cell = change\n else:\n (cell).update(change)\n\n self.grid[row][col] = cell", "def updateCell(self, grid, cell, s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Marks a cell as a mine, and updates all knowledge to mark that cell as a mine as well.
def mark_mine(self, cell): self.mines.add(cell) for sentence in self.knowledge: sentence.mark_mine(cell)
[ "def mark_mine(self, cell):\n if cell in self.cells and self.count>0:\n self.cells-={cell}\n self.count-=1\n #flags this sentence as having been changed - to try again to subtract if subset of others\n self.changed=True", "def __addMine(self, c: int, r: int) -> N...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }