query
stringlengths
9
9.05k
document
stringlengths
10
222k
negatives
listlengths
19
20
metadata
dict
Tests that the barracks helper cannot be built without api_key argument
def test_init_barracks_helper_fail_when_no_api_key_given(): try: BarracksHelper(None, _base_url) assert False except ValueError: assert True
[ "def test_api_key_error(api):\n\twith pytest.raises(top_stories.APIKeyError):\n\t\tmissingAPI = top_stories.TopStoriesAPI()", "def test_init_barracks_helper_succeed_when_api_key_and_base_url_given():\n base_url = 'http://some.url'\n\n helper = BarracksHelper(_api_key, base_url)\n assert helper.get_api_ke...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tests that the barracks helper is correctly built with an api_key and no base_url
def test_init_barracks_helper_succeed_when_api_key_and_base_url_given(): base_url = 'http://some.url' helper = BarracksHelper(_api_key, base_url) assert helper.get_api_key() == _api_key assert helper.get_base_url() == base_url assert helper.update_checker_helper assert helper.update_checker_he...
[ "def test_init_barracks_helper_fail_when_no_api_key_given():\n try:\n BarracksHelper(None, _base_url)\n assert False\n except ValueError:\n assert True", "def test_api_base(self):\n # load api base\n r = requests.get('{server}/api/0.1/'.format(\n server=self.get...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tests that the client ''check'' callback is called with UpdateDetail when status code is available
def test_check_update_calls_callback_when_update_available(): with requests_mock.mock() as mocked_server: mocked_server.post(_base_url + _check_update_endpoint, text=_json_update_response, status_code=200) request = UpdateDetailRequest('v1', 'MyDevice', '{"AnyCustomData":"any_value"}') upda...
[ "def updates_check():\n data = wait_for_callback(client, cb_updates_name)\n self.assertTrue(isinstance(data, dict))", "def test_update_response_status(self):\n pass", "def test_status_code(self):\n assert self.detail_response.status_code == 200", "def test_modify_client_sta...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tests that the download request is built with appropriate parameters and headers
def test_download_package_helper_properly_build_request_when_valid_url_given(): download_helper = PackageDownloadHelper(_api_key) built_request = download_helper.build_download_request(_update_response_url) headers = built_request.headers assert headers['Authorization'] == _api_key assert headers['...
[ "def test_api_v1_defenders_download_get(self):\n pass", "def test_download(self):\n pass", "def download_created(req, download):", "def test_download1(self):\n pass", "def test_download_manual(self):\n response = self.client.get('/support/download_manual/')\n self.assertEq...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tests that downloaded the file is removed when the md5 not match
def test_file_integrity_remove_file_in_case_of_fail(): test_file = open('./testfile.tmp', 'a') test_file.close() test_file_path = os.path.realpath('./testfile.tmp') test_file_md5 = hashlib.md5(open(test_file_path, 'rb').read()).hexdigest() bad_md5 = 'some_noise_%s' % test_file_md5 PackageDownl...
[ "def _check_final_md5(self, key, file_name):\r\n fp = open(file_name, 'r')\r\n if key.bucket.connection.debug >= 1:\r\n print 'Checking md5 against etag.'\r\n hex_md5 = key.compute_md5(fp)[0]\r\n if hex_md5 != key.etag.strip('\"\\''):\r\n file_name = fp.name\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The getter method for the forecast date. If the forecast date is not supplied, it will be set to the current date.
def forecast_date(self): return self._forecast_date
[ "def forecast_date(self, forecast_date):\n self._forecast_date = forecast_date.strftime(\"%a %b %d\")", "def _get_forecast(self, date):\n # Forecast takes a dt.datetime\n # conversion from dt.date to dt.datetime, there must be a better way, right?\n time = dt.datetime(year=date.year, m...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The setter method for the forecast date. Every time we need to set the date in an instance of Forecast every, we need to make sure that it will be formatted accordingly.
def forecast_date(self, forecast_date): self._forecast_date = forecast_date.strftime("%a %b %d")
[ "def date(self, date):\n self.value = date.strftime(\"%Y-%m-%d\") if date else \"\"", "def setdate(self, strf):\n self.date = strftime(strf)", "def set_date(self, date):\n self.date = date\n return", "def set_datetime(self, date):\n self.date = date", "def forecast_date(se...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The getter method for the day's current wind levels.
def wind(self): return self._wind
[ "def get_wind_values(self):\n return (\n int(self.data[2]), # dir\n float(self.data[3]) / 10, # gust\n float(self.data[4]) / 10, # avg\n float(self.data[5]) / 10, # chill\n )", "def get_current_water_level(self):\n \n url = f'http://water...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
implement the calculation W_battery = TOW W_payload W_empty
def compute(self, inputs, outputs): outputs['TOW'] = inputs['W_battery'] + inputs['W_payload'] + inputs['W_empty']
[ "def _battery_cb(self, msg):\n # self.battery_voltages[msg.header.seq %\n # len(self.battery_voltages)] = msg.voltage\n self.battery_voltages[msg.header.seq % len(\n self.battery_voltages)] = msg.percentage * 100.\n # delta = self.INIT_VOLTAGE - self.MINI...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Evaluate if two hypercubes cross each other.
def hypercubes_overlap(hypercube1, hypercube2): if not isinstance(hypercube1, Volume) or \ not isinstance(hypercube2, Volume): raise TypeError() lowercorner1, uppercorner1 = hypercube1.get_corners() lowercorner2, uppercorner2 = hypercube2.get_corners() nb_dims = len(uppercorner1) ...
[ "def cross(self, other):\n return self.scalar(other) == 0", "def test_cross(self, a, b, expected):\n result = pyCGM.cross(a, b)\n np.testing.assert_almost_equal(result, expected, rounding_precision)", "def cross(series1: Sequence, series2: Sequence) -> bool:\n return crossover(series1, s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the number of small arrays in big array in all dimensions as a shape.
def get_blocks_shape(big_array, small_array): return tuple([int(b/s) for b, s in zip(big_array, small_array)])
[ "def example_count(a):\n try:\n return jnp.shape(a)[0]\n except:\n return 1", "def find_largest_shape(arrays):\r\n out = np.array([0])\r\n for array in arrays:\r\n out = out * np.zeros_like(array)\r\n return out.shape", "def count_dims(da):\n return len(da.dims)", "def s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns list of output files that are crossing buffer at buffer_index.
def get_crossed_outfiles(buffer_index, buffers, outfiles): crossing = list() buffer_of_interest = buffers[buffer_index] for outfile in outfiles.values(): if hypercubes_overlap(buffer_of_interest, outfile): crossing.append(outfile) return crossing
[ "def list_buffer_files(buffer_folder_path, buffer_name): \r\n \r\n #Find all the x and y files in the buffer folder\r\n x_paths = [os.path.join(buffer_folder_path,file_name) for file_name in os.listdir(buffer_folder_path) if file_name.endswith(buffer_name + \"_x.hdf5\")] \r\n y_paths = [os.pat...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Merge two volumes into one.
def merge_volumes(volume1, volume2): if not isinstance(volume1, Volume) or \ not isinstance(volume2, Volume): raise TypeError() lowercorner1, uppercorner1 = volume1.get_corners() lowercorner2, uppercorner2 = volume2.get_corners() lowercorner = (min(lowercorner1[0], lowercorner2[0]), ...
[ "def mergeVolumes(volumes, volName):\n # Extract list of volumes as list of np arrays in int32 format\n npVolumes = [slicer.util.arrayFromVolume(volume).astype(\"int32\") for volume in volumes]\n\n # Merge all volumes in one\n mergedVol = npVolumes[0]\n for i in range(1, len(npVolumes)):\n mergedVol |= npVo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Alias of hypercubes_overlap. We do not verify that it is included but by definition of the problem if volume crosses outfile then volume in outfile.
def included_in(volume, outfile): return hypercubes_overlap(volume, outfile)
[ "def hypercubes_overlap(hypercube1, hypercube2):\n if not isinstance(hypercube1, Volume) or \\\n not isinstance(hypercube2, Volume):\n raise TypeError()\n\n lowercorner1, uppercorner1 = hypercube1.get_corners()\n lowercorner2, uppercorner2 = hypercube2.get_corners()\n nb_dims = len(upperco...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add volume information to dictionary associating output file index to
def add_to_array_dict(array_dict, outfile, volume): if (not isinstance(outfile.index, int) or not isinstance(volume, Volume) or not isinstance(outfile, Volume)): raise TypeError() if not outfile.index in array_dict.keys(): array_dict[outfile.index] = list() array_dict[outf...
[ "def add_volume_info(self, vi):\n vol_num = vi.volume_number\n self.volume_info_dict[vol_num] = vi\n if self.fh:\n self.fh.write(vi.to_string() + \"\\n\")", "def generate_volume_info(self, NAME, path):\n info = {'tags': [], 'name': NAME, 'path': path, 'AttachedToVm': [],\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
From a dictionary of Volumes, creates a dictionary of list of slices. The new arrays_dict associates each output file to each volume that must be written at a time.
def clean_arrays_dict(arrays_dict): for k in arrays_dict.keys(): volumes_list = arrays_dict[k] arrays_dict[k] = [convert_Volume_to_slices(v) for v in volumes_list]
[ "def add_to_array_dict(array_dict, outfile, volume):\n if (not isinstance(outfile.index, int) \n or not isinstance(volume, Volume) \n or not isinstance(outfile, Volume)):\n raise TypeError()\n\n if not outfile.index in array_dict.keys():\n array_dict[outfile.index] = list()\n ar...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Merge volume with other volumes from volumes list in the merge directions.
def apply_merge(volume, volumes, merge_directions): def get_new_volume(volume, lowcorner): v2 = get_volume(lowcorner) if v2 != None: return merge_volumes(volume, v2) else: return volume def get_volume(lowcorner): if not isinstance(lowcorner, tuple): ...
[ "def mergeVolumes(volumes, volName):\n # Extract list of volumes as list of np arrays in int32 format\n npVolumes = [slicer.util.arrayFromVolume(volume).astype(\"int32\") for volume in volumes]\n\n # Merge all volumes in one\n mergedVol = npVolumes[0]\n for i in range(1, len(npVolumes)):\n mergedVol |= npVo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Subscribes the decorated function to all messages from the messagequeue.
def subscribe(): def func_wrapper(func): queue.observe_on(scheduler).subscribe(func) return func return func_wrapper
[ "def _listen_to_queues(cls):\n queues = cls.get_service_queues()\n for queue in queues:\n queue.consume(cls.process_messages)", "def subscribe(func):\n func._zgres_subscriber = True\n return func", "def consume_messages(process_func: Callable[[str], None]):\n consumer = get_con...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Subscribes the decorated function to messages of the given type. The function will be observed on its own thread.
def subscribe_to(type_to_subscribe_to=None): def func_wrapper(func): queue.filter(lambda x:isinstance(x, type_to_subscribe_to) or type_to_subscribe_to == None).observe_on(scheduler).subscribe(func) return func return func_wrapper
[ "def on_event(self, event_type):\n\n def decorator(func):\n\n def wrapper(event):\n if event.type == event_type:\n return func(event)\n\n self.subscribe(wrapper)\n\n return wrapper\n\n return decorator", "def subscribe():\n def fu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Clause server; Statement edns_udp_size; passing mode
def test_isc_server_stmt_edns_udp_size_passing(self): test_string = [ 'edns-udp-size 0;', 'edns-udp-size 1;', 'edns-udp-size 102;', 'edns-udp-size 255;', ] result = optviewserver_stmt_edns_udp_size.runTests(test_string, failureTests=False) ...
[ "def test_isc_server_stmt_edns_udp_size_failing(self):\n test_string = [\n 'edns-udp-size yes;',\n 'edns-udp-size -3;',\n ]\n result = optviewserver_stmt_edns_udp_size.runTests(test_string, failureTests=True)\n self.assertTrue(result[0])", "def SendPacketsSendSize...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Clause server; Statement edns_udp_size; failing mode
def test_isc_server_stmt_edns_udp_size_failing(self): test_string = [ 'edns-udp-size yes;', 'edns-udp-size -3;', ] result = optviewserver_stmt_edns_udp_size.runTests(test_string, failureTests=True) self.assertTrue(result[0])
[ "def test_isc_server_stmt_edns_udp_size_passing(self):\n test_string = [\n 'edns-udp-size 0;',\n 'edns-udp-size 1;',\n 'edns-udp-size 102;',\n 'edns-udp-size 255;',\n ]\n result = optviewserver_stmt_edns_udp_size.runTests(test_string, failureTests=Fal...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Clause Options/View/Server; Statement provideixfr; passing mode
def test_isc_optviewserver_stmt_provide_ixfr_passing(self): test_string = [ 'provide-ixfr yes;', 'provide-ixfr 1;', 'provide-ixfr 0;', 'provide-ixfr no;', 'provide-ixfr True;', 'provide-ixfr False;', ] result = optviewserver...
[ "def test_isc_optviewzone_stmt_provide_ixfr_passing(self):\n test_string = [\n 'provide-ixfr yes;'\n ]\n result = optviewzone_stmt_provide_ixfr.runTests(test_string, failureTests=False)\n self.assertTrue(result[0])\n assertParserResultDictTrue(\n optviewzone_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Clause Options/View/Server; Statement provideixfr; failing mode
def test_isc_optviewserver_stmt_provide_ixfr_failing(self): test_string = [ 'provide-ixfr Y' ] result = optviewserver_stmt_provide_ixfr.runTests(test_string, failureTests=True) self.assertTrue(result[0])
[ "def test_isc_server_stmt_request_ixfr_failing(self):\n test_string = [\n 'request-ixfr Y;'\n ]\n result = optviewserver_stmt_request_ixfr.runTests(test_string, failureTests=True)\n self.assertTrue(result[0])", "def test_isc_optviewserver_stmt_provide_ixfr_passing(self):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Clause server; Statement requestixfr; failing mode
def test_isc_server_stmt_request_ixfr_failing(self): test_string = [ 'request-ixfr Y;' ] result = optviewserver_stmt_request_ixfr.runTests(test_string, failureTests=True) self.assertTrue(result[0])
[ "def test_malformed_query_AdventureWorks2014(self):\r\n with open(self.get_baseline(\\\r\n u'test_malformed_query.txt'),\r\n u'r+b',\r\n buffering=0) as response_file:\r\n request_stream = io.BytesIO()\r\n rpc_client = json_rpc_client.J...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Clause Options/View/Server; Statement transferformat; passing mode
def test_isc_optviewserver_stmt_transfer_format_passing(self): test_string = [ 'transfer-format one-answer;', 'transfer-format many-answers;', ] result = optviewserver_stmt_transfer_format.runTests(test_string, failureTests=False) self.assertTrue(result[0]) ...
[ "def test_isc_optviewzone_stmt_transfer_format_passing(self):\n test_string = [\n 'transfer-format one-answer;',\n 'transfer-format many-answers;',\n ]\n result = optviewzone_stmt_transfer_format.runTests(test_string, failureTests=False)\n self.assertTrue(result[0])...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Clause Options/View/Server; Statement transferformat; failing mode
def test_isc_optviewserver_stmt_transfer_format_failing(self): test_string = [ 'transfer-format no-answer;', 'transfer-format !one-answer;', 'transfer-format many-answer;', ] result = optviewserver_stmt_transfer_format.runTests(test_string, failureTests=True) ...
[ "def test_isc_optviewserver_stmt_transfer_format_passing(self):\n test_string = [\n 'transfer-format one-answer;',\n 'transfer-format many-answers;',\n ]\n result = optviewserver_stmt_transfer_format.runTests(test_string, failureTests=False)\n self.assertTrue(result...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Clause optviewserver; Statement optviewserver_statements_series; passing
def test_isc_optviewserver_statements_series_passing(self): assertParserResultDictTrue( optviewserver_statements_series, 'provide-ixfr yes;' + 'request-ixfr yes;' + 'transfer-format one-answer;', {'provide_ixfr': 'yes', 'request_ixfr': 'ye...
[ "def test_isc_optviewzone_statements_series_passing(self):\n assertParserResultDictTrue(\n optviewzone_statements_series,\n 'use-alt-transfer-source yes;' +\n 'transfer-format many-answers;' +\n 'zone-statistics yes;' +\n 'transfer-source 4.4.4.4 port 53...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Clause optviewserver; Statement statements_series; failing
def test_isc_optviewserver_stmt_statements_series_failing(self): test_string = [ 'statements_series "YYYY";', ] result = optviewserver_statements_series.runTests(test_string, failureTests=True) self.assertTrue(result[0])
[ "def test_isc_optviewserver_statements_series_passing(self):\n assertParserResultDictTrue(\n optviewserver_statements_series,\n 'provide-ixfr yes;' +\n 'request-ixfr yes;' +\n 'transfer-format one-answer;',\n {'provide_ixfr': 'yes',\n 'reques...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a threadspecific storage dictionary.
def _dic(self, thread_id=None): # def _dic(_get_ident=thread.get_ident) make thread.get_ident a local var if thread_id is None: thread_id = thread.get_ident() # Identify the calling thread. try: return _ThDict._tss[thread_id] except KeyError: tss = _ThDict._ts...
[ "def create_dict(self):\n localdict = {}\n key = self.key\n thread = current_thread()\n idt = id(thread)\n def local_deleted(_, key=key):\n # When the localimpl is deleted, remove the thread attribute.\n thread = wrthread()\n if thread is not None:...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Clear the named lazyprop from this object
def clear_lazyprop(object, property_name): assert isinstance(property_name, str) if _LAZY_PROP_VALUES in object.__dict__: if property_name in object.__dict__[_LAZY_PROP_VALUES]: del object.__dict__[_LAZY_PROP_VALUES][property_name] if _LAZY_PROP_SUBSCRIBERS in object.__dict__: ...
[ "def clearProperty(*args):", "def clearProperty(self, prop):\n if hasattr(self.resultObject, prop):\n delattr(self.resultObject, prop)", "def _reset_derived_prop_(self):\n self._derived_properties[\"photosamplers\"] = None", "def reset(self):\r\n instdict = self.__dict__\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Clears all lazy prop from an object. This means they will be reevaluated next time they are run
def clear_all_lazyprops(object): if _LAZY_PROP_VALUES in object.__dict__: del object.__dict__[_LAZY_PROP_VALUES] if _LAZY_PROP_SUBSCRIBERS in object.__dict__: for subscribers in object.__dict__[_LAZY_PROP_SUBSCRIBERS].values(): for fn in subscribers: fn(object)
[ "def clear_lazyprop(object, property_name):\n assert isinstance(property_name, str)\n\n if _LAZY_PROP_VALUES in object.__dict__:\n if property_name in object.__dict__[_LAZY_PROP_VALUES]:\n del object.__dict__[_LAZY_PROP_VALUES][property_name]\n\n if _LAZY_PROP_SUBSCRIBERS in object.__dict...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Clear the lazyprop on the subscriber_object if the listen_to_object property is cleared
def clear_lazyprop_on_lazyprop_cleared(subscriber_object, subscriber_lazyprop, listen_to_object, listen_to_lazyprop=None): if listen_to_lazyprop is None: listen_to_lazyprop = subscriber_lazyprop assert isinstance(listen_to_lazyprop, str) assert isinstance(subs...
[ "def clear_all_lazyprops(object):\n if _LAZY_PROP_VALUES in object.__dict__:\n del object.__dict__[_LAZY_PROP_VALUES]\n\n if _LAZY_PROP_SUBSCRIBERS in object.__dict__:\n for subscribers in object.__dict__[_LAZY_PROP_SUBSCRIBERS].values():\n for fn in subscribers:\n fn(o...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Converts a sentence (string) into a list of words (strings). Extracts the GloVe representation of each word and averages its value into a single vector encoding the meaning of the sentence.
def sentence_to_avg(sentence, word_to_vec_map): # Get a valid word contained in the word_to_vec_map. any_word = list(word_to_vec_map.keys())[0] ### START CODE HERE ### # Step 1: Split sentence into list of lower case words (≈ 1 line) words = sentence.lower().split() # Initialize the avera...
[ "def sentence_to_avg(sentence, word_to_vec_map):\n\n ### START CODE HERE ###\n # Step 1: Split sentence into list of lower case words (鈮?1 line)\n words = sentence.lower().split()\n\n # Initialize the average word vector, should have the same shape as your word vectors.\n avg = np.zeros((50,))\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Converts an array of sentences (strings) into an array of indices corresponding to words in the sentences. The output shape should be such that it can be given to `Embedding()` (described in Figure 4).
def sentences_to_indices(X, word_to_index, max_len): m = X.shape[0] # number of training examples ### START CODE HERE ### # Initialize X_indices as a numpy matrix of zeros and the correct shape (≈ 1 line) X_indices = np.zeros((m, max_len)) for i in ra...
[ "def sentences_to_indices(X, word_to_index, max_len):\n m = X.shape[0]\n X_indices = np.zeros((m, max_len))\n for i in range(m):\n sentence_words = X[i].lower().split()\n j = 0\n for w in sentence_words:\n X_indices[i, j] = word_to_index[w]\n j = j + 1\n return...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates a Keras Embedding() layer and loads in pretrained GloVe 50dimensional vectors.
def pretrained_embedding_layer(word_to_vec_map, word_to_index): vocab_size = len(word_to_index) + 1 # adding 1 to fit Keras embedding (requirement) any_word = list(word_to_vec_map.keys())[0] emb_dim = word_to_vec_map[any_word].shape[0] # define dimensionality of your GloVe word vectors ...
[ "def pretrained_embedding_layer(word_to_vec_map, word_to_index):\n\n vocab_len = len(word_to_index) + 1 # adding 1 to fit Keras embedding (requirement)\n emb_dim = word_to_vec_map[\"cucumber\"].shape[0] # define dimensionality of your GloVe word vectors (= 50)\n\n ### START CODE HERE ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function creating the Emojifyv2 model's graph.
def Emojify_V2(input_shape, word_to_vec_map, word_to_index): ### START CODE HERE ### # Define sentence_indices as the input of the graph. # It should be of shape input_shape and dtype 'int32' (as it contains indices, which are integers). sentence_indices = Input(shape = input_shape, dtype = 'int32'...
[ "def _generate_er(qubo, seed):\n # Compute parameters needed for model\n n = qubo.order()\n p = qubo.size() / scipy.special.binom(n, 2)\n # Generate graph\n graph = nx.erdos_renyi_graph(n=n, p=p, seed=seed)\n # Name the graph\n graph.graph['name'] = '{}-{}-{}'.format(qubo.graph['name'], 'er', s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Attempt to import a module, with a fallback. Attempt to import ``name``. If it fails, return ``alternative``. When supporting multiple versions of Python or optional dependencies, it is useful to be able to try to import a module.
def try_import(name, alternative=None, error_callback=None): module_segments = name.split('.') last_error = None remainder = [] # module_name will be what successfully imports. We cannot walk from the # __import__ result because in import loops (A imports A.B, which imports # C, which calls try...
[ "def maybe_import(name: str) -> Union[ModuleType, None]:\n return importlib.import_module(name) if is_installed(name) else None", "def try_import(module: str, name: str) -> Optional[object]:\n try:\n return getattr(__import__(module, fromlist=[name]), name)\n except ImportError:\n return None...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Map ``function`` across the values of ``dictionary``.
def map_values(function, dictionary): return {k: function(dictionary[k]) for k in dictionary}
[ "def dict_map(function, dictionary):\n\treturn dict((key, function(value)) for key, value in dictionary.items())", "def map_values(fun, a_dict):\n return dict((k, fun(v)) for (k, v) in a_dict.items())", "def dict_apply_listfun(dict, function):\n\tkeys = dict.keys()\n\tvals = [dict[key] for key in keys]\n\tre...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Filter ``dictionary`` by its values using ``function``.
def filter_values(function, dictionary): return {k: v for k, v in dictionary.items() if function(v)}
[ "def filter_dict(dictionary, pred):\n return dict((k, v) for k, v in dictionary.items() if pred(k, v))", "def filter_keys(func, a_dict):\n return dict((k, v) for (k, v) in a_dict.items() if func(k))", "def filter_dict(dict, filter=[]):\n return {key: dict[key] for key in filter}", "def filter(self, f...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a list ``a`` without the elements of ``b``. If a particular value is in ``a`` twice and ``b`` once then the returned list then that value will appear once in the returned list.
def list_subtract(a, b): a_only = list(a) for x in b: if x in a_only: a_only.remove(x) return a_only
[ "def uncommon(a, b):\n temp = list()\n for i in a:\n if i not in b:\n temp.append(i)\n return temp", "def diff_list(a, b):\n b = set(b)\n return [aa for aa in a if aa not in b]", "def difference (b, a):\n a = set(a)\n result = []\n for item in b:\n if item not in...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Reading a environment variable as text.
def env_var_line(key: str) -> str: return str(os.environ.get(key) or "").strip()
[ "async def get_file_environment(environment_name: str) -> str:\n try:\n async with aiofiles.open(os.getenv(environment_name)) as file:\n return await file.read()\n except TypeError:\n raise ValueError(f\"'{environment_name}' environment variable name was not found.\")\n except OSEr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Reading a environment variable as int.
def env_var_int(key: str) -> int: try: return int(env_var_line(key)) except (ValueError, TypeError): return 0
[ "def getEnvInt(key, default):\n value = os.environ.get(key, default)\n try:\n return int(value)\n except ValueError:\n return default", "def get_int(name, default):\n value = os.environ.get(name)\n if value is None:\n return default\n\n try:\n parsed_value = int(value...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Reading a environment variable as float.
def env_var_float(key: str) -> float: try: return float(env_var_line(key)) except (ValueError, TypeError): return 0
[ "def test_env_as_float__float(self) -> None:\n self.assertEqual(\n 123.4,\n parse_env.env_as_float({'koi': '123.4'}, 'koi', 5),\n )", "def test_env_as_float__not_float(self) -> None:\n self.assertEqual(\n 100.9,\n parse_env.env_as_float({'tuna': 'fi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Reading a environment variable as list, source line should be divided by commas.
def env_var_list(key: str) -> list: return list( filter( None, map(str.strip, env_var_line(key).split(",")) ) )
[ "def list_from_env(env_value):\n if isinstance(env_value, str):\n env_value = [u for u in env_value.split(',') if u]\n return env_value", "def doenvlist(filename, folderlist, envvariable, searchsubfolders, searchpt):\n \n for item in envvariable:\n try:\n envlist = [v.strip() ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
returns the Planck function for radiation from a blackbody at temperature T (K) at wavelength(s) wave, given in Angstrom Returns radiance in cgs units.
def blackbody( wave, T, waveunit='Angstrom' ): if waveunit=='Angstrom': # convert wavelength from angstroms to cm wave = wave / 1e10 * 100. elif waveunit=='nm': # convert wavelength from angstroms to cm wave = wave / 1e9 * 100. return( ((2 * h * c* c)/wave**5 ) / (exp(h*...
[ "def Planck(T, wav):\n\twav_cm=wav*1.e-7 #convert wavelengths from nm to cm.\n\tc=2.99792e10 #speed of light, in cm/s\n\th=6.62607e-27#Planck constant, in erg*s\n\tkb=1.38065e-16#Boltzmann constant, in erg/K\n\t\n\timport numpy as np\n\tresult_cm=(2.*h*c**2./wav_cm**5.)*1./(np.exp(h*c/(wav_cm*kb*T))-1) #ergs/cm^3/s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Testing that consecutive slices are forbidden.
def test_forbidden_consecutive_slices( assert_errors, parse_ast_tree, expression, default_options, ): tree = parse_ast_tree(usage_template.format(expression)) visitor = SubscriptVisitor(default_options, tree=tree) visitor.run() assert_errors(visitor, [ConsecutiveSlicesViolation])
[ "def test_slice_negative(self):\n slices = ( (-10,-5), (-20, 20), (3, -10) )\n\n for (start, stop) in slices:\n self.assertEqual(self.normal_list[start:stop],\n self.paginated_list[start:stop])", "def test_forbidden_multiple_consecutive_slices(\n assert_errors,\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Testing that consecutive slices are forbidden.
def test_forbidden_multiple_consecutive_slices( assert_errors, parse_ast_tree, expression, default_options, ): tree = parse_ast_tree(usage_template.format(expression)) visitor = SubscriptVisitor(default_options, tree=tree) visitor.run() assert_errors(visitor, [ ConsecutiveSlice...
[ "def test_slice_negative(self):\n slices = ( (-10,-5), (-20, 20), (3, -10) )\n\n for (start, stop) in slices:\n self.assertEqual(self.normal_list[start:stop],\n self.paginated_list[start:stop])", "def test_forbidden_consecutive_slices(\n assert_errors,\n parse_ast...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
finds the maximum product of four adjacent numbers in a matrix in the same direction
def find_max_product(mtx): max_prod = 0 for row_num in range(20): vert = 0 diag = 0 anti_diag = 0 horiz = horiz_max(mtx[row_num]) if row_num < len(mtx) - 3: vert = vert_max(mtx[row_num], mtx[row_num + 1], mtx[row_num + 2], mtx[row_n...
[ "def compute_largest_column_product(grid):\n max_product = 0\n for column in range(len(grid)):\n for row in range(len(grid) - 3):\n current_product = 1\n for j in range(4):\n current_product *= grid[row + j][column]\n if current_product > max_product:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
List out slot names based on the names of parameters of func
def _slots_from_params(func): funcsig = signature(func) slots = list(funcsig.parameters) slots.remove('self') return slots
[ "def get_slot_names(self, *args, **kwargs):\n return self._opt.get_slot_names(*args, **kwargs)", "def parameterNames(self, p_int): # real signature unknown; restored from __doc__\n return []", "def param_names(self) -> List[str]:", "def _func_list(name, size):\n return [hl.Func(\"%s_%d\" % (name,...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Open or create a wheel file. In write and exclusivewrite modes, if `file_or_path` is not specified, or the specified path is a directory, the wheelfile will be created in the current working directory, with filename generated using the values given via `distname`, `version`, `build_tag`, `language_tag`, `abi_tag`, and ...
def __init__( self, file_or_path: Union[str, Path, BinaryIO] = './', mode: str = 'r', *, distname: Optional[str] = None, version: Optional[Union[str, Version]] = None, build_tag: Optional[Union[int, str]] = None, language_tag: Optional[str] = None, ...
[ "def create_file(path: str, contents: Optional[str] = None) -> None:\n from pip._internal.utils.misc import ensure_dir\n\n ensure_dir(os.path.dirname(path))\n with open(path, \"w\") as f:\n if contents is not None:\n f.write(contents)\n else:\n f.write(\"\\n\")", "def ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a filename from file obj or a path. If given file, the asumption is that the filename is within the value of its `name` attribute. If given a `Path`, assumes it is a path to an actual file, not a directory. If given an unnamed object, this returns None.
def _get_filename( cls, file_or_path: Union[BinaryIO, Path] ) -> Optional[str]: if cls._is_unnamed_or_directory(file_or_path): return None # TODO: test this # If a file object given, ensure its a filename, not a path if isinstance(file_or_path, Path): ...
[ "def guess_filename(obj):\n name = getattr(obj, 'name', None)\n if name and name[0] != '<' and name[-1] != '>':\n return os.path.basename(name)", "def get_file(self, obj):\n try:\n file = inspect.getfile(obj)\n except TypeError:\n return None\n else:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Write a file to the .data directory under a specified section. This method is a handy shortcut for writing into `.data/`, such that you dont have to generate the path yourself. Updates the wheel record, if the record is being kept.
def write_data(self, filename: Union[str, Path], section: str, arcname: Optional[str] = None, *, recursive: bool = True, resolve: bool = True) -> None: self._check_section(section) if isinstance(filename, str): filename = Path(filename) if arcna...
[ "def writeEntryToSection(context, section, key, value, callback=None):\n projectDir = context.projectDir\n if section not in GenericMetadata.SECTIONS:\n raise Exception( \"%s is an unknown section\" % (section,) )\n lockFilepath = os.path.join(projectDir, GenericMetadata.METADATA_LOC...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Write given data to the .data directory under a specified section. This method is a handy shortcut for writing into `.data/`, such that you dont have to generate the path yourself. Updates the wheel record, if the record is being kept.
def writestr_data(self, section: str, zinfo_or_arcname: Union[ZipInfo, str], data: Union[bytes, str]) -> None: self._check_section(section) arcname = ( zinfo_or_arcname.filename if isinstance(zinfo_or_arcname, ZipInfo) else...
[ "def write_data(self, filename: Union[str, Path],\n section: str, arcname: Optional[str] = None,\n *, recursive: bool = True, resolve: bool = True) -> None:\n self._check_section(section)\n\n if isinstance(filename, str):\n filename = Path(filename)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Write a file to `.distinfo` directory in the wheel. This is a shorthand for `write(...)` with `arcname` prefixed with the `.distinfo` path. It also ensures that the metadata files critical to the wheel correctnes (i.e. the ones written into archive on `close()`) aren't being prewritten.
def write_distinfo(self, filename: Union[str, Path], arcname: Optional[str] = None, *, recursive: bool = True, resolve: bool = True) -> None: if resolve and arcname is None: arcname = resolved(filename) elif arcname is None: arcname =...
[ "def _patch_distribution_metadata_write_pkg_file():\r\n distutils.dist.DistributionMetadata.write_pkg_file = (\r\n setuptools.dist.write_pkg_file\r\n )", "def write_dist(version, model, dist_type, output, extra=None, header=None):\n import fitsio\n\n fname=get_dist_path(version, model, dist_typ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get an absolute path relative depth
def __getLibAbsPath(currentPath, depth): libPath = currentPath while depth: libPath = os.path.split(libPath)[0] depth -= 1 return libPath
[ "def path_depth(path):\n parts = os.path.dirname(path).split('/')\n parts = [part for part in parts if part != '']\n length = len(parts)\n return length", "def __getImmediateRoot(depth=1):\n callingFileName = os.path.realpath(getCallingFileName(depth+1))\n return os.path.abspath(os.path.join(cal...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
init Lib Path. append lib path into python path.
def initLibPath(): libHash = { 'Framework': 1, 'UserControlleLib': 1, 'CaseLib': 1 } binPath = os.path.split(os.path.realpath(__file__))[0] for key in libHash: sys.path.append(os.path.join(__getLibAbsPath(binPath, libHash[key]), key))
[ "def manipulate_paths_like_upstream(_executable, sys_path):\n bin_dir = os.path.dirname(os.path.abspath(_executable))\n root_dir = os.path.dirname(bin_dir)\n lib_dir = os.path.join(root_dir, \"lib\")\n sys_path.insert(0, lib_dir)", "def register_pylib_path(self, devkit_path):\n path = os.path.j...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Splitting multipart copy upload. Splits copy upload parts into several ones to fit maximum upload part size limit. Also takes into the account minimum upload part size.
def __init__(self, mpu, min_part_size=5 * MB, max_part_size=5 * GB): super(SplittingMultipartCopyUpload, self).__init__(mpu) self._mpu = mpu self._min_part_size = min_part_size self._max_part_size = max_part_size
[ "def upload_all_parts(self):\n if not self.upload_id:\n raise RuntimeError(\"Attempting to use a multipart upload that has not been initiated.\")\n\n if self.file.name != \"<stdin>\":\n size_left = file_size = os.stat(self.file.name)[ST_SIZE]\n nr_parts = file_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Out of bounds splitting multipart copy upload. Splits out of bounds copy upload parts into several ones to fit memorysafe part size limit. Also takes into the account minimum upload part size.
def __init__(self, mpu, original_size, min_part_size, max_part_size): super(OutOfBoundsSplittingMultipartCopyUpload, self).__init__(mpu, min_part_size, max_part_size) self._original_size = original_size
[ "def upload_all_parts(self):\n if not self.upload_id:\n raise RuntimeError(\"Attempting to use a multipart upload that has not been initiated.\")\n\n if self.file.name != \"<stdin>\":\n size_left = file_size = os.stat(self.file.name)[ST_SIZE]\n nr_parts = file_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Append optimized composite multipart copy upload. Uses original object as a pre uploaded composite part in case of append writes. In order to do so it adjusts the first of the already uploaded chunks. Uploads copy parts as regular parts using content of the original file.
def __init__(self, mpu, original_size, chunk_size, download): super(AppendOptimizedCompositeMultipartCopyUpload, self).__init__(mpu) self._mpu = mpu self._original_size = original_size self._chunk_size = chunk_size self._download = download self._copy_parts = [] s...
[ "def upload_multipart_chunk(self, mp_info):\n\n mp_info[\"stream_buffer\"].seek(0)\n try:\n result = self.conns[mp_info[\"dst_info\"][\"s3_loc\"]].upload_part(\n Body=mp_info[\"stream_buffer\"],\n Bucket=mp_info[\"dst_info\"][\"bucket_name\"],\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert an input text file to an output Morse code file. Notes This function assumes the existence of a MORSE_CODE dictionary, containing a mapping between English letters and their corresponding Morse code.
def english_to_morse( input_file: str = "lorem.txt", output_file: str = "lorem_morse.txt" ):
[ "def write_code(message, file_name):\n\n\t\n\t# Initialize variable current_sentence to be an empty string\n\tcurrent_sentence = \"\"\n\t# Initialize variable current_character to be an empty string\n\tcurrent_character = \"\"\n\t# Loop through each character given in english message\n\tfor character in message:\n\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Determine the appropriate format string for the pie chart percentage label
def pie_pct_format(value): return '' if value < 7 else '{}'.format(value)
[ "def percentage_text(value):\n return \"{}%\".format(value)", "def _to_percent(value, position):\n if plt.rcParams['text.usetex'] is True:\n return '{:1.0%}'.format(value).replace('%', r'$\\%$')\n else:\n return '{:1.0%}'.format(value)", "def format(self, value):\r\n metric = {...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a valid authentication header either from username/password or a token if any were provided; return an empty dict otherwise
def create_auth_header(username=None, password=None, token=None, tenant=None): headers = {} if username and password: credentials = b64encode( '{0}:{1}'.format(username, password).encode('utf-8') ).decode('ascii') headers = { 'Authorization': 'Basic ' ...
[ "def auth_header(token):\n return {'Authorization': f'Bearer {token}'}", "def get_auth_data(self, headers):\n if self.token is None:\n auth = {'password': self.password}\n if self.user_id:\n auth['userId'] = self.user_id\n elif self.user_name:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the setting of this Software.
def setting(self, setting): self._setting = setting
[ "def set_setting(self, name, value):\n w = self.choices['which']\n if w == 'global_default':\n return self.settings.set_global_default(name, value)\n elif w == 'project_default':\n return self.settings.set_project_default(name, value)\n elif w == 'global_variant':\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
y_hat is the output tensor from the network y is the label tensor (no embedding) returns the mask to use for negating the padding
def label_mask(y, y_hat): mask = torch.ones(len(y), np.shape(y)[1]) for i in range(len(y[0])): try: y_hat_index = np.where(y_hat[:,i]==1)[0][0] y_index = np.where(y[:,i]==1)[0][0] index = max(y_hat_index, y_index) mask[index:, i] = 0 except: ...
[ "def same_label_mask(y, y2):\n return tf.cast(tf.squeeze(tf.equal(y, tf.expand_dims(y2, 1))), tf.float32)", "def _masked_labels_and_weights(y_true):\n # Ignore the classes of tokens with negative values.\n mask = tf.greater_equal(y_true, 0)\n # Replace negative labels, which are out of bounds for some l...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
x is the training data tensor (no embedding) returns the mask to use for negating the padding effect on the attention add this mask before taking the softmax!
def attention_mask(x): mask = torch.zeros(len(x), len(x[0])) for i in range(len(x)): try: index = np.where(x[i]==1)[0][0] mask[i][index:] = -np.inf except: pass return mask
[ "def attention_mask(model, x):\n config = model.config\n input_mask = model.inputs[\"input_mask\"]\n final_mask = model.builder.customOp(opName=\"AttentionMask\",\n opVersion=1,\n domain=\"ai.graphcore\",\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Remove securityzone if exist and is not in use
def sec_zone_absent(module, session, endpoint, my_sz): if not my_sz: return True, False, {'label': '', 'id': '', 'msg': 'security-zone does not exist'} if not module.check_mode: aos_delete(session, endpoint, my_sz['id']) return ...
[ "def delete_zone(self, context, zone, zone_params):", "def SecurityZone(self) -> _n_6_t_7:", "def delete_zone(self, context, zone):\n self.client.deleteZone(zoneName=zone['name'])", "def _clear_zone_identifier(filename):\n if os.path.exists(filename + \":Zone.Identifier\"):\n try:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create new securityzone or modify existing pool
def sec_zone_present(module, session, endpoint, my_sz, vni_id, vlan_id): margs = module.params if not my_sz: if 'name' not in margs.keys(): return False, False, {"msg": "name required to create a new " "security-zone"} new_sz = {"sz_type": ...
[ "def test_create_subnetpool(self):\n with self.rbac_utils.override_role(self):\n self._create_subnetpool()", "def sec_zone(module):\n margs = module.params\n\n endpoint = 'blueprints/{}/security-zones'.format(margs['blueprint_id'])\n\n name = margs.get('name', None)\n uuid = margs.ge...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Main function to create, change or delete security zones within an AOS blueprint
def sec_zone(module): margs = module.params endpoint = 'blueprints/{}/security-zones'.format(margs['blueprint_id']) name = margs.get('name', None) uuid = margs.get('id', None) vni_id = margs.get('vni_id', None) vlan_id = margs.get('vlan_id', None) if vni_id: try: vni_i...
[ "def destination_zone(self, action, name=\"\"):\n logging.debug(\"In destination_zone() for AccessRules class.\")\n if action == \"add\":\n sz = SecurityZones(fmc=self.fmc)\n sz.get(name=name)\n if \"id\" in sz.__dict__:\n if \"destinationZones\" in self...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
calculate the loop number on each core
def _cal_core(tik_instance, total_core_loop_num, num_core, core_number): core_loop = tik_instance.Scalar("uint64") sum_core = tik_instance.Scalar("uint64") with tik_instance.if_scope(num_core < total_core_loop_num % MAX_CORE_NUM): core_loop.set_as((total_core_loop_num + core_number - 1) // ...
[ "def get_n_cpu_cycles_per_neuron(self):", "def _cal_core_loop_python(num_data_one_loop, core_loop, ub_ori):\n align_loop = ub_ori // num_data_one_loop\n remainder = core_loop % align_loop\n\n if align_loop > core_loop:\n align_loop = core_loop\n remainder = 0\n\n return align_loop, remai...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
calculate the number of loops and remainder on each core and return python variable
def _cal_core_loop_python(num_data_one_loop, core_loop, ub_ori): align_loop = ub_ori // num_data_one_loop remainder = core_loop % align_loop if align_loop > core_loop: align_loop = core_loop remainder = 0 return align_loop, remainder
[ "def _cal_core(tik_instance, total_core_loop_num, num_core, core_number):\n core_loop = tik_instance.Scalar(\"uint64\")\n sum_core = tik_instance.Scalar(\"uint64\")\n\n with tik_instance.if_scope(num_core < total_core_loop_num % MAX_CORE_NUM):\n core_loop.set_as((total_core_loop_num + core_number - ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
vector_dup zeros when dup_number is python variable
def vector_dup_zero(self, tik_instance, ub_trans, dup_number, offset): scalar_zero = tik_instance.Scalar(dtype="float16", init_value=0.0) repeat_number = dup_number // MAX_MASK tail = dup_number % MAX_MASK with tik_instance.for_range(0, repeat_number // MAX_REPEATS) as \ ...
[ "def _op_generic_Dup(self, args):\n arg_num = len(args)\n if arg_num != 1:\n raise SimOperationError(\"expect exactly one vector to be duplicated, got %d\" % arg_num)\n # Duplicate the vector for this many times\n vector_count = self._vector_count\n # Keep a copy of the...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert a dataframe of indicators into an inverse covariance matrix index
def invcov_index(indicators): df = indicators.copy() df = (df-df.mean())/df.std() I = np.ones(df.shape[1]) E = inv(df.cov()) s1 = I.dot(E).dot(I.T) s2 = I.dot(E).dot(df.T) try: int(s1) S = s2/s1 except TypeError: S = inv(s1).dot(s2) S = pd.Series(S...
[ "def invert(self):\r\n return pd.DataFrame(\r\n np.linalg.pinv(self.data, hermitian=True),\r\n index=self.data.index,\r\n columns=self.data.columns,\r\n ) # do not return CategoryCov because variance can be negative\r", "def build_inverse_covariance(self):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Count the number of pairs with a given sum
def sum_pairs(arr: list, sum: int): pair_count = 0 count_map = {} for i in arr: if i in count_map: count_map[i] += 1 else: count_map[i] = 1 for key, value in count_map.items(): if (sum - key) in count_map: count1 = value ...
[ "def countPairs(self, nums, dist):\n count = 0\n for i in xrange(len(nums)):\n j = i + 1\n while j < len(nums) and nums[j] - nums[i] <= dist:\n count += 1\n j += 1\n return count", "def sum_amicable_pairs(n):\n candidates = list(range(1, ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Archive the provided URL using archive.org's Wayback Machine. Returns the archive.org URL where the capture is stored. Raises a CachedPage exception if archive.org declines to conduct a new capture and returns a previous snapshot instead. To silence that exception, pass into True to the `accept_cache` keyword argument....
def capture( target_url: str, user_agent: str = DEFAULT_USER_AGENT, accept_cache: bool = False, authenticate: bool = False, ): # Put together the URL that will save our request domain = "https://web.archive.org" save_url = urljoin(domain, "/save/") request_url = save_url + target_url ...
[ "def archive(url, wget_options, out_warc_file, directory_prefix):\n site_path = url.split('/bin/view/')[-1]\n directory_prefix = directory_prefix or '/'.join(('./cache', site_path))\n if wget_options != '':\n wget_options = wget_options + ' '\n if not os.path.exists(directory_prefix):\n os...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test readout error on qubit 0 for bell state
def test_readout_error_qubit0(self): # Test circuit: ideal bell state qr = QuantumRegister(2, 'qr') cr = ClassicalRegister(2, 'cr') circuit = QuantumCircuit(qr, cr) circuit.h(qr[0]) circuit.cx(qr[0], qr[1]) # Ensure qubit 0 is measured before qubit 1 circ...
[ "def test_readout_error_qubit1(self):\n\n # Test circuit: ideal bell state\n qr = QuantumRegister(2, 'qr')\n cr = ClassicalRegister(2, 'cr')\n circuit = QuantumCircuit(qr, cr)\n circuit.h(qr[0])\n circuit.cx(qr[0], qr[1])\n # Ensure qubit 0 is measured before qubit 1...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test readout error on qubit 1 for bell state
def test_readout_error_qubit1(self): # Test circuit: ideal bell state qr = QuantumRegister(2, 'qr') cr = ClassicalRegister(2, 'cr') circuit = QuantumCircuit(qr, cr) circuit.h(qr[0]) circuit.cx(qr[0], qr[1]) # Ensure qubit 0 is measured before qubit 1 circ...
[ "def test_readout_error_qubit0(self):\n\n # Test circuit: ideal bell state\n qr = QuantumRegister(2, 'qr')\n cr = ClassicalRegister(2, 'cr')\n circuit = QuantumCircuit(qr, cr)\n circuit.h(qr[0])\n circuit.cx(qr[0], qr[1])\n # Ensure qubit 0 is measured before qubit 1...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test 100% readout error on all qubits
def test_readout_error_all_qubit(self): # Test circuit: ideal bell state qr = QuantumRegister(2, 'qr') cr = ClassicalRegister(2, 'cr') circuit = QuantumCircuit(qr, cr) circuit.h(qr[0]) circuit.cx(qr[0], qr[1]) # Ensure qubit 0 is measured before qubit 1 c...
[ "def test_readout_error_qubit1(self):\n\n # Test circuit: ideal bell state\n qr = QuantumRegister(2, 'qr')\n cr = ClassicalRegister(2, 'cr')\n circuit = QuantumCircuit(qr, cr)\n circuit.h(qr[0])\n circuit.cx(qr[0], qr[1])\n # Ensure qubit 0 is measured before qubit 1...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test a correlated twoqubit readout error
def test_readout_error_correlated_2qubit(self): # Test circuit: prepare all plus state qr = QuantumRegister(2, 'qr') cr = ClassicalRegister(2, 'cr') circuit = QuantumCircuit(qr, cr) circuit.h(qr) circuit.barrier(qr) # We will manually add a correlated measure oper...
[ "def test_readout_error_qubit1(self):\n\n # Test circuit: ideal bell state\n qr = QuantumRegister(2, 'qr')\n cr = ClassicalRegister(2, 'cr')\n circuit = QuantumCircuit(qr, cr)\n circuit.h(qr[0])\n circuit.cx(qr[0], qr[1])\n # Ensure qubit 0 is measured before qubit 1...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test 50% perecent reset error on qubit0
def test_reset_error_specific_qubit_50percent(self): # Test circuit: ideal outcome "11" qr = QuantumRegister(2, 'qr') cr = ClassicalRegister(2, 'cr') circuit = QuantumCircuit(qr, cr) circuit.x(qr) circuit.measure(qr, cr) backend = QasmSimulator() noise_ci...
[ "def test_specific_qubit_pauli_error_reset_25percent(self):\n qr = QuantumRegister(2, 'qr')\n cr = ClassicalRegister(2, 'cr')\n circuit = QuantumCircuit(qr, cr)\n circuit.barrier(qr)\n circuit.reset(qr)\n circuit.barrier(qr)\n circuit.measure(qr, cr)\n backend...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test 25% percent reset error on qubit1
def test_reset_error_specific_qubit_25percent(self): # Test circuit: ideal outcome "11" qr = QuantumRegister(2, 'qr') cr = ClassicalRegister(2, 'cr') circuit = QuantumCircuit(qr, cr) circuit.x(qr) circuit.measure(qr, cr) backend = QasmSimulator() noise_ci...
[ "def test_specific_qubit_pauli_error_reset_25percent(self):\n qr = QuantumRegister(2, 'qr')\n cr = ClassicalRegister(2, 'cr')\n circuit = QuantumCircuit(qr, cr)\n circuit.barrier(qr)\n circuit.reset(qr)\n circuit.barrier(qr)\n circuit.measure(qr, cr)\n backend...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test 100% precent reset error on all qubits
def test_reset_error_all_qubit_100percent(self): # Test circuit: ideal outcome "11" qr = QuantumRegister(2, 'qr') cr = ClassicalRegister(2, 'cr') circuit = QuantumCircuit(qr, cr) circuit.x(qr) circuit.measure(qr, cr) backend = QasmSimulator() noise_circs ...
[ "def test_specific_qubit_pauli_error_reset_25percent(self):\n qr = QuantumRegister(2, 'qr')\n cr = ClassicalRegister(2, 'cr')\n circuit = QuantumCircuit(qr, cr)\n circuit.barrier(qr)\n circuit.reset(qr)\n circuit.barrier(qr)\n circuit.measure(qr, cr)\n backend...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test 100% Pauli error on id gates
def test_all_qubit_pauli_error_gate_100percent(self): qr = QuantumRegister(2, 'qr') cr = ClassicalRegister(2, 'cr') circuit = QuantumCircuit(qr, cr) circuit.iden(qr) circuit.barrier(qr) circuit.measure(qr, cr) backend = QasmSimulator() shots = 100 ...
[ "def test_specific_qubit_pauli_error_gate_100percent(self):\n qr = QuantumRegister(2, 'qr')\n cr = ClassicalRegister(2, 'cr')\n circuit = QuantumCircuit(qr, cr)\n circuit.iden(qr)\n circuit.barrier(qr)\n circuit.measure(qr, cr)\n backend = QasmSimulator()\n sh...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test 100% Pauli error on id gates on qubit1
def test_specific_qubit_pauli_error_gate_100percent(self): qr = QuantumRegister(2, 'qr') cr = ClassicalRegister(2, 'cr') circuit = QuantumCircuit(qr, cr) circuit.iden(qr) circuit.barrier(qr) circuit.measure(qr, cr) backend = QasmSimulator() shots = 100 ...
[ "def test_all_qubit_pauli_error_gate_100percent(self):\n qr = QuantumRegister(2, 'qr')\n cr = ClassicalRegister(2, 'cr')\n circuit = QuantumCircuit(qr, cr)\n circuit.iden(qr)\n circuit.barrier(qr)\n circuit.measure(qr, cr)\n backend = QasmSimulator()\n shots =...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test 100% Pauli error on id gates qubit0
def test_specific_qubit_pauli_error_gate_25percent(self): qr = QuantumRegister(2, 'qr') cr = ClassicalRegister(2, 'cr') circuit = QuantumCircuit(qr, cr) circuit.iden(qr) circuit.barrier(qr) circuit.measure(qr, cr) backend = QasmSimulator() shots = 2000 ...
[ "def test_specific_qubit_pauli_error_gate_100percent(self):\n qr = QuantumRegister(2, 'qr')\n cr = ClassicalRegister(2, 'cr')\n circuit = QuantumCircuit(qr, cr)\n circuit.iden(qr)\n circuit.barrier(qr)\n circuit.measure(qr, cr)\n backend = QasmSimulator()\n sh...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test 100% nonlocal Pauli error on cx(0, 1) gate
def test_nonlocal_pauli_error_gate_25percent(self): qr = QuantumRegister(3, 'qr') cr = ClassicalRegister(3, 'cr') circuit = QuantumCircuit(qr, cr) circuit.cx(qr[0], qr[1]) circuit.barrier(qr) circuit.cx(qr[1], qr[0]) circuit.barrier(qr) circuit.measure(qr,...
[ "def test_unfoldable_gate_error_cirq():\n qbit = LineQubit(0)\n circ = Circuit(ops.measure(qbit))\n with pytest.raises(UnfoldableGateError):\n _fold_gate_at_index_in_moment(circ, moment_index=0, gate_index=0)", "def test_controlled_by_error():\n c = Circuit(3)\n c.add(gates.H(0))\n c.add(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test 25% PauliX error on measure of qubit1
def test_specific_qubit_pauli_error_measure_25percent(self): qr = QuantumRegister(2, 'qr') cr = ClassicalRegister(2, 'cr') circuit = QuantumCircuit(qr, cr) circuit.measure(qr, cr) backend = QasmSimulator() shots = 2000 # test noise model error = pauli_erro...
[ "def test_specific_qubit_pauli_error_gate_25percent(self):\n qr = QuantumRegister(2, 'qr')\n cr = ClassicalRegister(2, 'cr')\n circuit = QuantumCircuit(qr, cr)\n circuit.iden(qr)\n circuit.barrier(qr)\n circuit.measure(qr, cr)\n backend = QasmSimulator()\n sho...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test 25% PauliX error on reset of qubit1
def test_specific_qubit_pauli_error_reset_25percent(self): qr = QuantumRegister(2, 'qr') cr = ClassicalRegister(2, 'cr') circuit = QuantumCircuit(qr, cr) circuit.barrier(qr) circuit.reset(qr) circuit.barrier(qr) circuit.measure(qr, cr) backend = QasmSimula...
[ "def test_reset_error_specific_qubit_25percent(self):\n\n # Test circuit: ideal outcome \"11\"\n qr = QuantumRegister(2, 'qr')\n cr = ClassicalRegister(2, 'cr')\n circuit = QuantumCircuit(qr, cr)\n circuit.x(qr)\n circuit.measure(qr, cr)\n backend = QasmSimulator()\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test amplitude damping error damps to correct state
def test_amplitude_damping_error(self): qr = QuantumRegister(1, 'qr') cr = ClassicalRegister(1, 'cr') circuit = QuantumCircuit(qr, cr) circuit.x(qr) # prepare + state for _ in range(30): # Add noisy identities circuit.barrier(qr) circuit.iden(...
[ "def test_amplitude_damping_error(self):\n qr = QuantumRegister(1, \"qr\")\n cr = ClassicalRegister(1, \"cr\")\n circuit = QuantumCircuit(qr, cr)\n circuit.x(qr) # prepare + state\n for _ in range(30):\n # Add noisy identities\n circuit.barrier(qr)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test noise model basis_gates
def test_noise_model_basis_gates(self): basis_gates = ['u1', 'u2', 'u3', 'cx'] model = NoiseModel(basis_gates) target = sorted(basis_gates) self.assertEqual(model.basis_gates, target) # Check adding readout errors doesn't add to basis gates model = NoiseModel(basis_gates...
[ "def test_noise_model_basis_gates(self):\n basis_gates = [\"u1\", \"u2\", \"u3\", \"cx\"]\n model = NoiseModel(basis_gates)\n target = sorted(basis_gates)\n self.assertEqual(model.basis_gates, target)\n\n # Check adding readout errors doesn't add to basis gates\n model = No...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test two noise models are Equal
def test_noise_models_equal(self): roerror = [[0.9, 0.1], [0.5, 0.5]] error1 = pauli_error([['X', 1]], standard_gates=False) error2 = pauli_error([['X', 1]], standard_gates=True) model1 = NoiseModel() model1.add_all_qubit_quantum_error(error1, ['u3'], False) model1.add_q...
[ "def test_noise_models_equal(self):\n roerror = [[0.9, 0.1], [0.5, 0.5]]\n error1 = kraus_error([np.diag([1, 0]), np.diag([0, 1])])\n error2 = pauli_error([(\"I\", 0.5), (\"Z\", 0.5)])\n\n model1 = NoiseModel()\n model1.add_all_qubit_quantum_error(error1, [\"u3\"], False)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test two noise models are not equal
def test_noise_models_not_equal(self): error = pauli_error([['X', 1]]) model1 = NoiseModel() model1.add_all_qubit_quantum_error(error, ['u3'], False) model2 = NoiseModel(basis_gates=['u3', 'cx']) model2.add_all_qubit_quantum_error(error, ['u3'], False)
[ "def test_noise_models_equal(self):\n roerror = [[0.9, 0.1], [0.5, 0.5]]\n error1 = pauli_error([['X', 1]], standard_gates=False)\n error2 = pauli_error([['X', 1]], standard_gates=True)\n\n model1 = NoiseModel()\n model1.add_all_qubit_quantum_error(error1, ['u3'], False)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates one hot vector of n classes with "index" class
def oneHot(index, n): x = np.zeros(n) x[index] = 1 return x
[ "def onehot(index):\n classNum=2#1\n onehot = np.zeros(classNum)#这代表种类类型\n onehot[index] = 1.0\n return onehot", "def indices_to_one_hot(data, nb_classes):\n targets = np.array(data).reshape(-1)\n return np.eye(nb_classes)[targets]", "def one_hot(length, index):\n result = np.zeros(length)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check if mode contains "check"
def isMode(mode, check): if mode=="default" or mode=="all": return True if mode.__contains__(check): return True if check.__contains__("_"): check_modes = check.split("_") for check_mode in check_modes: if not isMode(mode, check_mode): return...
[ "def is_check(self) -> bool:\n return self.state == \"check\"", "def ModeCheck():\n return GLOBAL.MBCmode.get()", "def is_valid_mode(mode: str) -> bool:\n return mode in (TEST, EASY, HARD)", "def check_mode(self):\n if self.proximity.check_press():\n self.cycle_mode()\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Coordinate embeddings of bounding boxes
def coordinate_embeddings(boxes, dim): batch_size, num_boxes, num_loc = boxes.shape # transform to (x_c, y_c, w, h) format pos = boxes.new_zeros((batch_size, num_boxes, 4)) pos[:, :, 0] = (boxes[:, :, 0] + boxes[:, :, 2]) / 2 * 100 pos[:, :, 1] = (boxes[:, :, 1] + boxes[:, :, 3]) / 2 * 100 pos...
[ "def bounding_box(self):\n latlon00 = self.ij_to_latlon(-1,-1)\n latlon01 = self.ij_to_latlon(-1,self.domain_size[1]+1)\n latlon11 = self.ij_to_latlon(self.domain_size[0]+1,self.domain_size[1]+1)\n latlon10 = self.ij_to_latlon(self.domain_size[0]+1,-1)\n return (latlon00,latlon01,...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set default image feature to an existing model.
def set_default_image_feature(self, image_feature): target = self.dummy_input_imgs # None means batch axis x = image_feature.features.clone()[None] assert x.shape == target.data.shape target.data = x target = self.dummy_image_loc # None means bat...
[ "def set_default_image(self, image):\n raise NotImplementedError", "def set_model( self, model_img ):\n\n\t\tself.model_img = model_img\n\t\tself.mag_initial = -2.5*np.log10( self.model_img.sum() ) + self.zeropoint\n\t\tself.modeled = True", "def set_default(self):\n\n album = self.album\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
function that checks to see if Fermat's theorem holds.
def check_fermat(a, b, c, n): if n > 2 and a**n + b**n == c**n: print("Holy smokes, Fermat was wrong!") else: print("No, that doesn’t work.")
[ "def fermat_test(self, p: int, k: int = 100) -> bool:\n for _ in range(k):\n a = random.randint(2, p-2)\n if gcd(a, p) != 1:\n return False\n if pow(a, p-1, p) != 1:\n return False\n return True # Probably prime.", "def is_equivalence(s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
initialize a bdb hash
def bdb_init_hash(db_file, cache_size=None): db_dir = dirname(db_file) if not isdir(db_dir): makedirs(db_dir) db = DB() if cache_size is None: cache_size = _cache_size db.set_cachesize ( cache_size / (1024*1024*1024), cache_size % (1024*1024*1024) ) db.open(db_file, dbtype=DB_HASH, flags=DB_CREATE) retu...
[ "def hfreq_bdb_init(db_file, cache_size=None):\n\treturn bdb_init_hash(db_file, cache_size)", "def __init__(self):\n _snap.TStrHashF_DJB_swiginit(self, _snap.new_TStrHashF_DJB())", "def __init__(self, ht_size = 100):\n self.ht_size = int(ht_size * 1.0)\n if self.ht_size < 10:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
initialize (open) a bdb frequency hash
def hfreq_bdb_init(db_file, cache_size=None): return bdb_init_hash(db_file, cache_size)
[ "def bdb_init_hash(db_file, cache_size=None):\n\tdb_dir = dirname(db_file)\n\tif not isdir(db_dir):\n\t\tmakedirs(db_dir)\n\tdb = DB()\n\tif cache_size is None:\n\t\tcache_size = _cache_size\n\tdb.set_cachesize (\n\t\tcache_size / (1024*1024*1024),\n\t\tcache_size % (1024*1024*1024)\n\t)\n\tdb.open(db_file, dbtype=...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Compute Mean Volume Backscattering Strength (MVBS) based on intervals of range (``echo_range``) and ``ping_time`` specified in physical units. Output of this function differs from that of ``compute_MVBS_index_binning``, which computes binaveraged Sv according to intervals of ``echo_range`` and ``ping_time`` specified a...
def compute_MVBS(ds_Sv, range_meter_bin=20, ping_time_bin="20S"): # create bin information for echo_range range_interval = np.arange(0, ds_Sv["echo_range"].max() + range_meter_bin, range_meter_bin) # create bin information needed for ping_time ping_interval = ( ds_Sv.ping_time.resample(ping_ti...
[ "def compute_MVBS_index_binning(ds_Sv, range_sample_num=100, ping_num=100):\n da_sv = 10 ** (ds_Sv[\"Sv\"] / 10) # average should be done in linear domain\n da = 10 * np.log10(\n da_sv.coarsen(ping_time=ping_num, range_sample=range_sample_num, boundary=\"pad\").mean(\n skipna=True\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Compute Mean Volume Backscattering Strength (MVBS) based on intervals of ``range_sample`` and ping number (``ping_num``) specified in index number. Output of this function differs from that of ``compute_MVBS``, which computes binaveraged Sv according to intervals of range (``echo_range``) and ``ping_time`` specified in...
def compute_MVBS_index_binning(ds_Sv, range_sample_num=100, ping_num=100): da_sv = 10 ** (ds_Sv["Sv"] / 10) # average should be done in linear domain da = 10 * np.log10( da_sv.coarsen(ping_time=ping_num, range_sample=range_sample_num, boundary="pad").mean( skipna=True ) ) #...
[ "def compute_MVBS(ds_Sv, range_meter_bin=20, ping_time_bin=\"20S\"):\n\n # create bin information for echo_range\n range_interval = np.arange(0, ds_Sv[\"echo_range\"].max() + range_meter_bin, range_meter_bin)\n\n # create bin information needed for ping_time\n ping_interval = (\n ds_Sv.ping_time....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }