query stringlengths 9 9.05k | document stringlengths 10 222k | negatives listlengths 19 20 | metadata dict |
|---|---|---|---|
GetHandle(XCAFDoc_ShapeTool self) > Handle_XCAFDoc_ShapeTool | def GetHandle(self):
return _XCAFDoc.XCAFDoc_ShapeTool_GetHandle(self) | [
"def GetHandle(self):\n return _XCAFDoc.XCAFDoc_ShapeMapTool_GetHandle(self)",
"def GetHandle(self):\n return _XCAFDoc.XCAFDoc_LayerTool_GetHandle(self)",
"def GetHandle(self):\n return _XCAFDoc.XCAFDoc_DocumentTool_GetHandle(self)",
"def GetHandle(self):\n return _XCAFDoc.XCAFDoc_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns True if the label represents a shape (simple shape, assembly or reference) | def XCAFDoc_ShapeTool_IsShape(*args):
return _XCAFDoc.XCAFDoc_ShapeTool_IsShape(*args) | [
"def IsShape(*args):\n return _XCAFDoc.XCAFDoc_ShapeTool_IsShape(*args)",
"def is_shape(sym,shape):\n return get_shape(sym)==shape",
"def has_shape(self):\n if self.shape is None: return False\n else:\n return True",
"def has_shape(a):\n try:\n a.shape\n ret... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Searchs the SHUO by labels of components from upper_usage componet to next_usage Returns null attribute if no SHUO found | def XCAFDoc_ShapeTool_FindSHUO(*args):
return _XCAFDoc.XCAFDoc_ShapeTool_FindSHUO(*args) | [
"def FindSHUO(*args):\n return _XCAFDoc.XCAFDoc_ShapeTool_FindSHUO(*args)",
"def find_huc(source, shape, in_crs, hint, shrink_factor=1.e-5):\n def _in_huc(shply, huc_shply):\n \"\"\"Checks whether shp is in HUC\"\"\"\n if huc_shply.contains(shply):\n return 2\n elif huc_s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
GetHandle(XCAFDoc_Volume self) > Handle_XCAFDoc_Volume | def GetHandle(self):
return _XCAFDoc.XCAFDoc_Volume_GetHandle(self) | [
"def get_volume(self, volume):\n return self._get(_volume.Volume, volume)",
"def usb_handle(self):\n return self.usb",
"def GetHandle(self):\n return _XCAFDoc.XCAFDoc_DocumentTool_GetHandle(self)",
"def handle(self):\n return self._usb",
"def _get_volume_ref(connection_info_data):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Change ont port admin state to down. | def down(self):
self.update(admin_state='0') | [
"def admin_down(self):\n self.update(admin_state='0')",
"def set_all_ports_admin_disabled(self):\n pass",
"def set_all_ports_admin_disabled(self):\n ports_table = self.get_table_ports()\n ports = [x['portId'] for x in ports_table if x[\"portId\"] not in self.switch.mgmt_ports]\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return cumulative minimum over a DataFrame or Series axis. Returns a DataFrame or Series of the same size containing the cumulative minimum. | def cummin(self: FrameLike, skipna: bool = True) -> FrameLike:
return self._apply_series_op(lambda psser: psser._cum(F.min, skipna), should_resolve=True) | [
"def cummin(self, axis=0):\n return H2OFrame._expr(expr=ExprNode(\"cummin\", self, axis), cache=self._ex._cache)",
"def cummin(self):\n return self._lift(lambda c: c.cummin)",
"def argmin(self, axis: str = 'rows') -> 'DataFrame':\n return self._stat_funcs('argmin', axis)",
"def ts_min(x: ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return cumulative maximum over a DataFrame or Series axis. Returns a DataFrame or Series of the same size containing the cumulative maximum. | def cummax(self: FrameLike, skipna: bool = True) -> FrameLike:
return self._apply_series_op(lambda psser: psser._cum(F.max, skipna), should_resolve=True) | [
"def cummax(self, axis=0):\n return H2OFrame._expr(expr=ExprNode(\"cummax\", self, axis), cache=self._ex._cache)",
"def cummax(self):\n return self._lift(lambda c: c.cummax)",
"def cumargmax(a, return_cummax=False):\n m = np.maximum.accumulate(a)\n x = np.repeat(\n np.arange(a.shape[0... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return counts of unique dtypes in this object. | def get_dtype_counts(self) -> pd.Series:
warnings.warn(
"`get_dtype_counts` has been deprecated and will be "
"removed in a future version. For DataFrames use "
"`.dtypes.value_counts()",
FutureWarning,
)
if not isinstance(self.dtypes, Iterable):
... | [
"def valuecounts_(self): \n unique, counts = np.unique(self, return_counts=True)\n return np.asarray((unique, counts)).T",
"def sum_obj_cols (df):\n df_obj = obj_df(df)\n obj_cols = pd.DataFrame(df_obj.dtypes, columns=['dtypes'])\n obj_cols['unique_values'] = df_obj.nunique()\n return obj_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a Series/DataFrame with absolute numeric value of each element. Returns | def abs(self: FrameLike) -> FrameLike:
def abs(psser: "Series") -> Union["Series", Column]:
if isinstance(psser.spark.data_type, BooleanType):
return psser
elif isinstance(psser.spark.data_type, NumericType):
return psser._with_new_scol(
... | [
"def abs(self):\n return _spark_col_apply(self, F.abs)",
"def get_negatives(self):\n negative_values = (self.df[self.col_name]<0).sum()\n return negative_values",
"def absolute_values( values ):\n absVal = []\n for val in values:\n absVal.append( abs(val))\n\n return absVal",
"def... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Retrieves the index of the first valid value. Returns scalar, tuple, or None Examples Support for DataFrame | def first_valid_index(self) -> Optional[Union[Scalar, Tuple[Scalar, ...]]]:
data_spark_columns = self._internal.data_spark_columns
if len(data_spark_columns) == 0:
return None
cond = reduce(lambda x, y: x & y, map(lambda x: x.isNotNull(), data_spark_columns))
with sql_conf... | [
"def last_valid_index(self) -> Optional[Union[Scalar, Tuple[Scalar, ...]]]:\n data_spark_columns = self._internal.data_spark_columns\n\n if len(data_spark_columns) == 0:\n return None\n\n cond = reduce(lambda x, y: x & y, map(lambda x: x.isNotNull(), data_spark_columns))\n\n l... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return index for last nonNA/null value. Returns scalar, tuple, or None Notes This API only works with PySpark >= 3.0. Examples Support for DataFrame | def last_valid_index(self) -> Optional[Union[Scalar, Tuple[Scalar, ...]]]:
data_spark_columns = self._internal.data_spark_columns
if len(data_spark_columns) == 0:
return None
cond = reduce(lambda x, y: x & y, map(lambda x: x.isNotNull(), data_spark_columns))
last_valid_row... | [
"def first_valid_index(self) -> Optional[Union[Scalar, Tuple[Scalar, ...]]]:\n data_spark_columns = self._internal.data_spark_columns\n\n if len(data_spark_columns) == 0:\n return None\n\n cond = reduce(lambda x, y: x & y, map(lambda x: x.isNotNull(), data_spark_columns))\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Squeeze 1 dimensional axis objects into scalars. Series or DataFrames with a single element are squeezed to a scalar. DataFrames with a single column or a single row are squeezed to a Series. Otherwise the object is unchanged. This method is most useful when you don't know if your object is a Series or DataFrame, but y... | def squeeze(self, axis: Optional[Axis] = None) -> Union[Scalar, "DataFrame", "Series"]:
if axis is not None:
axis = "index" if axis == "rows" else axis
axis = validate_axis(axis)
if isinstance(self, ps.DataFrame):
from pyspark.pandas.series import first_series
... | [
"def squeeze(self, axis=None):\n # print 'input axis:', axis\n sh = self.data.shape\n if axis is None:\n axis = [a for i, a in enumerate(self.axes_names) if sh[i] == 1]\n else:\n assert self.has_axes(axis)\n ssh = np.array([sh[self.get_axis_id(a)] for a i... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Truncate a Series or DataFrame before and after some index value. This is a useful shorthand for boolean indexing based on index values above or below certain thresholds. | def truncate(
self,
before: Optional[Any] = None,
after: Optional[Any] = None,
axis: Optional[Axis] = None,
copy: bool_type = True,
) -> DataFrameOrSeries:
from pyspark.pandas.series import first_series
axis = validate_axis(axis)
indexes = self.index
... | [
"def trim (df, threshold):\n x = df.copy()\n x[np.abs(x)<threshold] = 0\n return x",
"def filter_after(df, date_):\n try:\n return df[df.index <= date_]\n except (AttributeError, TypeError):\n return df",
"def control_beyond_limits(data: ( pd.Series, np.array),\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
FlaskLogin token_loader callback. The token_loader function asks this function to take the token that was stored on the users computer process it to check if its valid and then return a User Object if its valid or None if its not valid. | def load_token(token):
#The Token itself was generated by User.get_auth_token. So it is up to
#us to known the format of the token data itself.
#The Token was encrypted using itsdangerous.URLSafeTimedSerializer which
#allows us to have a max_age on the token itself. When the cookie is stored
... | [
"def load_token(token):\n \n #The Token itself was generated by User.get_auth_token. So it is up to \n #us to known the format of the token data itself. \n \n #The Token was encrypted using itsdangerous.URLSafeTimedSerializer which \n #allows us to have a max_age on the token itself. When the cookie ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the path to the subvolume hdf5 file Similar to gcPath() from illustris_python, modified to load specific subvolumes. | def file_path(base_path, subvolume, file_name):
return '{}/{}_{}_{}/{}.hdf5'.format(base_path, *subvolume, file_name) | [
"def path_in_hdf5(self):\n raise NotImplementedError",
"def path_in_hdf5(self):\n return '/'",
"def _get_h5_path(self, name):\n return posixpath.join(self.h5_path, name)",
"def subsamples(self):\n return path.join(self.root, \"subsamples.dat\")",
"def volume_path(self) -> str:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a specific subvolume's haloprop for all snapshots. | def load_haloprop(base_path, subvolume, fields=None, matches=False):
return load_subvolume(base_path, subvolume, 'Haloprop', fields, matches, True) | [
"def load_snapshot_halos(base_path, snap_num, subvolumes, fields=None, matches=False):\n return load_snapshot(base_path, snap_num, subvolumes, \"Haloprop\", fields, matches)",
"def load_snapshot_subhalos(base_path, snap_num, subvolumes, fields=None, matches=False):\n return load_snapshot(base_path, snap_num... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a specific subvolume's galprop for all snapshots. | def load_galprop(base_path, subvolume, fields=None, matches=False):
return load_subvolume(base_path, subvolume, 'Galprop', fields, matches, True) | [
"def load_snapshot_subhalos(base_path, snap_num, subvolumes, fields=None, matches=False):\n return load_snapshot(base_path, snap_num, subvolumes, \"Galprop\", fields, matches)",
"def get_volume(self):\n return sum(s.volume for s in self.superitems)",
"def get_cg_volumes(self, group_id):\r\n for... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns all halos from queried subvolumes at a specific snapshot. | def load_snapshot_halos(base_path, snap_num, subvolumes, fields=None, matches=False):
return load_snapshot(base_path, snap_num, subvolumes, "Haloprop", fields, matches) | [
"def load_snapshot_subhalos(base_path, snap_num, subvolumes, fields=None, matches=False):\n return load_snapshot(base_path, snap_num, subvolumes, \"Galprop\", fields, matches)",
"def get_volume_snapshots(self, volume):\n LOG.debug('get_volume_snapshot starts')\n pool_name = self.configuration.rbd... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns all subhalos from queried subvolumes at a specific snapshot. | def load_snapshot_subhalos(base_path, snap_num, subvolumes, fields=None, matches=False):
return load_snapshot(base_path, snap_num, subvolumes, "Galprop", fields, matches) | [
"def get_volume_snapshots(self, volume):\n LOG.debug('get_volume_snapshot starts')\n pool_name = self.configuration.rbd_pool\n volume_name = 'volume-%s' % encodeutils.safe_encode(volume[\"id\"])\n snaps_on_vol = self._get_volume_snapshots(pool_name, volume_name)\n snapshots = list... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the header from a queried subvolume. | def load_header(base_path, subvolume):
with h5py.File(file_path(base_path, subvolume, 'subvolume'), 'r') as f:
header = dict(f['Header'].attrs.items())
header.update({key: f['Header'][key][:] for key in f['Header'].keys()})
return header | [
"def getHeader() :\n return header",
"def get_header(self):\n return self.__header",
"def getHeader(self):\r\n\r\n self.sendRequest(GET_HDR)\r\n (status, bufsize, payload) = self.receiveResponse()\r\n\r\n if status == GET_ERR:\r\n return None\r\n\r\n if status !=... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Describe cost management exports. | def describe_cost_management_exports(self):
return [{"name": self.export_name, "container": self.container, "directory": self.directory}] | [
"def test_describe_cost_management_exports(self):\n resource_id = (\n f\"/subscriptions/{self.subscription_id}/resourceGroups/\"\n f\"{self.resource_group_name}/providers/Microsoft.Storage/\"\n f\"storageAccounts/{self.storage_account_name}\"\n )\n\n mock_export... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test to verify Azure downloader is initialized. | def test_get_azure_client(self, _):
client = self.downloader._get_azure_client(self.azure_credentials, self.azure_data_source)
self.assertIsNotNone(client) | [
"def test_initializer(self):\n svc = self.get_mock_client()\n self.assertIsInstance(svc, AzureService)",
"def test_download_host(self):\n pass",
"def test_empty_azure_config_dir():\n pass",
"def test_download(self):\n pass",
"def test_setup(self):\n assert self.http_han... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test that report path is built correctly. | def test_get_report_path(self):
self.assertEqual(self.downloader.directory, self.mock_data.directory)
self.assertEqual(self.downloader.export_name, self.mock_data.export_name)
self.assertEqual(self.downloader._get_report_path(self.mock_data.test_date), self.mock_data.report_path) | [
"def __set_report_path(self):\n self.report_path = os.path.join(self.get_report_path(), \"cyclomatic_report\")\n Path(self.report_path).mkdir(parents=True, exist_ok=True)",
"def report_path(self):\r\n return os.path.join(self._html_dir, 'build.html')",
"def test_path(self):\n self.assert... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test to get the local file path for a report. | def test_get_local_file_for_report(self):
expected_local_file = self.mock_data.export_file
local_file = self.downloader.get_local_file_for_report(self.mock_data.export_key)
self.assertEqual(expected_local_file, local_file) | [
"def get_local_file_for_report(self, report):\n return utils.get_local_file_name(report)",
"def get_report_path(self):\n report_path = os.path.join(logPath, \"report.html\")\n return report_path",
"def test_get_report_path(self):\n self.assertEqual(self.downloader.directory, self.moc... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test that error is thrown when getting manifest with an unexpected report name. | def test_get_manifest_unexpected_report_name(self):
with self.assertRaises(AzureReportDownloaderError):
self.downloader._get_manifest(self.mock_data.bad_test_date) | [
"def test_invalid_manifest_filepath(self):\n load_manifest(\"./ehiiehaiehnatheita\")",
"def testGetBadManifest(self):\n dl = downloader.DockerImageDownloader('non/existing:image')\n with tempfile.TemporaryDirectory() as tmp_dir:\n dl._output_directory = tmp_dir\n with self.assertRaises(erro... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test that Azure report is not downloaded for incorrect key. | def test_download_missing_file(self):
key = "badkey"
with self.assertRaises(AzureReportDownloaderError):
self.downloader.download_file(key) | [
"def test_get_manifest_unexpected_report_name(self):\n with self.assertRaises(AzureReportDownloaderError):\n self.downloader._get_manifest(self.mock_data.bad_test_date)",
"def test_download_url_not_found(self):\n self.skipTest('This test needs to be created.')",
"def no_test_submit_repo... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given a character, predict the next character and hidden state. | def predict(net, char, h=None, top_k=None):
x = np.array([[net.char2int[char]]])
x = one_hot_encode(x, len(net.chars))
inputs = torch.from_numpy(x)
h = tuple([each.data for each in h])
out, h = net(inputs, h)
p = F.softmax(out, dim=1).data
if top_k is None:
... | [
"def _predict_from_seq(self, seq, temp=1.0):\n # encode\n state = self.infenc.predict(seq)\n # start of sequence input\n target_seq = np.array([self.output_dictionary[\"startseq\"]])\n # collect predictions\n output = list()\n for _ in range(self.decoder_seq_length):... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
replaces ' ' with '', that's it | def just_replace_strings_with_nothing(self, artist: str) -> str:
data = re.sub(' ', '', artist)
return data | [
"def replace_empty(s):\n if s == \"\":\n return \" \"\n else:\n return s",
"def remove_space(user_inputs):\r\n return user_inputs.replace(\" \", \"\")",
"def _clean(self, string):\n return re.sub('\\s+', ' ', string).strip()",
"def removeMultipleSpaces(self) -> None:\n sel... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
gets page of lyrics from genius | def get_genius_page(self, artist: str, song: str) -> str:
artist = self.just_replace_strings_with_dashes(artist)
song = self.just_replace_strings_with_dashes(song)
url = self.gen_url + artist + '-' + song + '-lyrics'
resp = requests.get(url)
if resp.status_code == 200:
... | [
"def getLyrics(query):\n\n if ('hakun' in query.lower()):\n return 'Hakuna Matata! What a wonderful phrase \\n Hakuna Matata! Ain\\'t no passing craze'\n\n json = GENIUS.search_genius(query)\n url = (json.get('hits')[0].get('result').get('url'))\n lyrics = GENIUS._scrape_song_lyrics_from_url(url)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets all songs lyrics for a given artist artist input should look like "queens of the stone age" | def get_all_artists_lyrics(self, artist: str) -> List[Dict]:
artist = artist.lower()
song_list = self.get_song_list(artist)
lyric_dict = {}
for i in song_list:
lyrics = self.get_genius_page(artist, i)
lyric_dict[i] = lyrics
return lyric_dict | [
"def get_all_lyrics(self, artist: Artist) -> list:\n return [song.lyrics for song in artist.songs]",
"def lyric_collector(track_lst,artist_lst):\n lyric_lst = []\n\n # Iterate through tracks and store lyrics\n for t, a in tqdm(zip(track_lst, artist_lst)):\n song = genius.search_song(title = t,\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Count the number of word appearence in the tokenized sentences | def count_words(tokenized_sentences):
word_counts = {}
# Loop through each sentence
for sentence in tokenized_sentences: # complete this line
for token in sentence: # complete this line
# If the token is not in the dictionary yet, set the count to 1
... | [
"def _num_tokens(sentences):\n num_tokens = 0\n for sent in sentences:\n if not FLAGS.word_models:\n num_tokens += len(sent) # Characters.\n else:\n num_tokens += len(list(filter(None, sent.split()))) # Words.\n return num_tokens",
"def sentence_count(self, **kwargs):\n token = self.to... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Replace words not in the given vocabulary with '' token. | def replace_oov_words_by_unk(tokenized_sentences, vocabulary, unknown_token="<unk>"):
# Place vocabulary into a set for faster search
vocabulary = set(vocabulary)
# Initialize a list that will hold the sentences
# after less frequent words are replaced by the unknown token
replaced_... | [
"def _replace_oov(original_vocab, line):\n return u\" \".join([\n word if word in original_vocab else u\"<UNK>\" for word in line.split()\n ])",
"def __replace_unused_vocab(vocab_list, new_vocab):\n if new_vocab not in vocab_list:\n pattern = re.compile('\\[UNUSED_.*\\]\\n')\n patter_lowercase... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Preprocess data, i.e., Find tokens that appear at least N times in the training data. Replace tokens that appear less than N times by "" both for training and test data. | def preprocess_data(train_data, test_data, count_threshold):
vocabulary = get_words_with_nplus_frequency(train_data, count_threshold)
train_data_replaced = replace_oov_words_by_unk(train_data, vocabulary, unknown_token="<unk>")
test_data_replaced = replace_oov_words_by_unk(test_data, vocabu... | [
"def _preprocess(self):\n self.data['sentences'] = self.data['text'].apply(self._tokenize_sent)\n self.data['nouns'] = self.data['sentences'].apply(self._get_nouns)\n # self._get_frequent_features()\n # self._compactness_pruning()\n # self._redundancy_pruning()\n # self._ge... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Estimate the probabilities of a next word using the ngram counts with ksmoothing | def estimate_probability(word, previous_n_gram,
n_gram_counts, n_plus1_gram_counts, vocabulary_size, k=1.0):
# Note : 1 . Here we are actually not considering the end token or start token as a part of a vocabulary.
# 2 . Although the literature says we need to prepend the n-... | [
"def smooth(self, ngram):\n ngram_count = self.ngrams_dictionaries[self.n][ngram]\n \n if(ngram_count == 0):\n del self.ngrams_dictionaries[self.n][ngram]\n \n total_ngram_count = len(self.ngrams_dictionaries[self.n].keys()) \n vocabulary_count = len(set(s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Estimate the probabilities of next words using the ngram counts with ksmoothing | def estimate_probabilities(previous_n_gram, n_gram_counts, n_plus1_gram_counts, vocabulary, k=1.0):
previous_n_gram = tuple(previous_n_gram)
# add <e> <unk> to the vocabulary
# <s> is not needed since it should not appear as the next word
vocabulary = vocabulary + ["<e>", "<unk>"]
v... | [
"def estimate_probability(word, previous_n_gram, \r\n n_gram_counts, n_plus1_gram_counts, vocabulary_size, k=1.0):\r\n # Note : 1 . Here we are actually not considering the end token or start token as a part of a vocabulary.\r\n # 2 . Although the literature says we need to pre... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tests if synchronization of BatchNorm running variables is done correctly. If not, the test sometimes fails depending on the timing. | def test_batchnorm_backward_synchronization(variable):
ctx = mx.test_utils.default_context()
for _ in range(20):
layer = nn.BatchNorm()
layer.initialize(ctx=ctx)
for _ in range(3):
data = mx.nd.random.normal(loc=10, scale=2, shape=(1, 3, 10, 10), ctx=ctx)
with mx... | [
"def test_sync_batchnorm_set(tmpdir):\n model = BoringModel()\n plugin = CustomParallelPlugin()\n assert plugin.sync_batchnorm is None\n trainer = Trainer(\n max_epochs=1,\n plugins=[plugin],\n default_root_dir=tmpdir,\n sync_batchnorm=True,\n )\n trainer.fit(model)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This test will test gluon Conv2d computation with ndarray reshape and slice | def test_reshape_conv_slice_conv():
class Net(gluon.HybridBlock):
def __init__(self, **kwargs):
super(Net, self).__init__(**kwargs)
self.conv0 = nn.Conv2D(16, (3, 3))
self.conv1 = nn.Conv2D(32, (3, 3))
def hybrid_forward(self, F, x):
x_reshape = x.res... | [
"def ggml_reshape_2d(ctx: ffi.CData, a: ffi.CData, ne0: int, ne1: int) -> ffi.CData:\n ...",
"def test_on_conv_transpose_2d_stride(self):\n\n # Channels/Colors, #filters, filter_size (square)\n conv_filter = objax.nn.ConvTranspose2D(1, 1, 2, strides=2, padding=objax.ConvPadding.VALID)\n we... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
test of the deformable convolution layer with possible combinations of arguments, currently this layer only supports gpu | def test_DeformableConvolution():
try:
ctx = mx.gpu()
_ = mx.nd.array([0], ctx=ctx)
except mx.base.MXNetError:
pytest.skip("deformable_convolution only supports GPU")
net = nn.HybridSequential()
net.add(
nn.DeformableConvolution(10, kernel_size=(3, 3), strides=1, padding=... | [
"def test_convolution():\n # Default test\n inputs_shape = [3,3,4,5,3]\n filters_shape = [3,1,4,4,3]\n test_convolution_for_parameters(inputs_shape, filters_shape,\n \"Default test\")\n # All dimensions 1\n inputs_shape = [1,1,1,1,1]\n filters_shape = [1,1,1,1,1]\n test_convolution_fo... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Decode data using Base58 with checksum + validate binary prefix against known kinds and cut in the end. | def base58_decode(v: bytes) -> bytes:
try:
prefix_len = next(
len(encoding[2])
for encoding in base58_encodings
if len(v) == encoding[1] and v.startswith(encoding[0])
)
except StopIteration:
raise ValueError('Invalid encoding, prefix or length mismatch... | [
"def multibase_b58decode(data):\n if data.startswith('z'):\n return base58.b58decode((data[1:]).encode())\n raise ValueError('{} cannot be decoded by multibase'\n ' base58.'.format(str(data)))",
"def decode_base58(smartAddress, length):\n n = 0\n for char in smartAddress:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Encode data using Base58 with checksum and add an according binary prefix in the end. | def base58_encode(v: bytes, prefix: bytes) -> bytes:
try:
encoding = next(
encoding
for encoding in base58_encodings
if len(v) == encoding[3] and prefix == encoding[0]
)
except StopIteration:
raise ValueError('Invalid encoding, prefix or length mismatc... | [
"def multibase_b58encode(data):\n raw = base58.b58encode(data)\n return 'z' + raw.decode()",
"def encode_base58(b):\n # Convert big-endian bytes to integer\n n = int('0x0' + binascii.hexlify(b).decode('utf8'), 16)\n # Divide that integer into bas58\n res = []\n while n > 0:\n n, r = di... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Ensure parameter is a signature (starts with b'edsig', b'spsig', b'p2sig', b'sig') | def validate_sig(v):
return _validate(v, prefixes=[b'edsig', b'spsig', b'p2sig', b'sig']) | [
"def handle_signature(self, sig, signode):\n raise NotImplementedError",
"def verify_signature(self, inputs, signature):\n pass",
"def _verify_signature(self):\n #FIXME\n return True",
"def testSigOnly(self):\r\n\r\n r = Reader(bytes=_signature)\r\n self.assertRaises(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check if value is a public key hash. | def is_pkh(v) -> bool:
try:
validate_pkh(v)
except (ValueError, TypeError):
return False
return True | [
"def is_hashable(v):\n try:\n hash(v)\n except TypeError:\n return False\n return True",
"def _hashable(v):\r\n try:\r\n hash(v)\r\n except TypeError:\r\n return False\r\n return True",
"def hashable(v):\n try:\n has... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check if value is a signature. | def is_sig(v) -> bool:
try:
validate_sig(v)
except (ValueError, TypeError):
return False
return True | [
"def _verify_signature(self):\n #FIXME\n return True",
"def validate_signature(self, value):\n provider_id = self.provider.provider_id\n secret_key = get_shared_secret_key(provider_id)\n\n self._check_keys_exist_for_provider(secret_key, provider_id)\n self._compare_signat... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check if value is a public key. | def is_key(v) -> bool:
try:
_validate(v, prefixes=[b"edsk", b"edpk", b"spsk", b"p2sk", b"sppk", b"p2pk"])
except (ValueError, TypeError):
return False
return True | [
"def _has_public_key(self):\n return 'pk' in self.keys or 'pp' in self.keys",
"def is_valid_public_key(public_key: str):\n # Public key length if we using coordinates (04 prefix) is 130\n # symbols.\n if len(public_key) != 130:\n return False\n\n # Check whether public key contains hex c... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check if value is a chain id. | def is_chain_id(v) -> bool:
try:
_validate(v, prefixes=[b'Net'])
except (ValueError, TypeError):
return False
return True | [
"def is_valid_node_id(val):\n if not val:\n return False\n if not isinstance(val, bytes) and not isinstance(val, bytearray):\n return False\n\n length = len(val)\n if length != SHA1_BIN_LEN and length != SHA2_BIN_LEN and \\\n length != SHA3_BIN_LEN:\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Decode chain id from byte form. | def parse_chain_id(data: bytes):
return base58_encode(data, b'Net').decode() | [
"def _decode_object_identifier(self, bytes):\n result = []\n value = 0\n for i in range(len(bytes)):\n byte = bytes[i]\n if isinstance(byte, str):\n byte = ord(byte)\n if value == 0 and byte == 0x80:\n raise Error('ASN1 syntax error... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Decode signature from byte form. | def parse_signature(data: bytes):
return base58_encode(data, b'sig').decode() | [
"def decode_signature(signature: HexString) -> Signature:\n sig_regex = re.compile(f\"^{Protocol.address}{Protocol.address}{Protocol.address}$\")\n x, y, s = sig_regex.search(signature).groups()\n return (int(x, 16), int(y, 16)), int(s, 16)",
"def decode_sig(sig):\n table = maketrans(\"-._... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Decode contract (address + optional entrypoint) from bytes | def parse_contract(data: bytes):
res = parse_address(data[:22])
if len(data) > 22:
res += f'%{data[22:].decode()}'
return res | [
"def disassemble(contract_bytes):\n contract = []\n c = 0\n i = 0\n while c < len(contract_bytes):\n op = contract_bytes[c]\n extra = opcodes[op][\"extra_in\"]\n params = contract_bytes[c+1:c+1+extra]\n contract += [[op, params, None]]\n c += extra+1\n i += 1+le... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Encode boolean value into bytes. | def forge_bool(value: bool) -> bytes:
return b'\xff' if value else b'\x00' | [
"def erd_encode_bool(value: Optional[bool]) -> str:\n if value is None:\n return \"FF\"\n return \"01\" if value else \"00\"",
"def writeBoolean(self, value: bool):\n self.writeByte(1 if value else 0)",
"def _bool_encode(self, d):\n for k, v in d.items():\n if isinstance(v,... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Encode base58 string into bytes. | def forge_base58(value: str) -> bytes:
return base58_decode(value.encode()) | [
"def multibase_b58encode(data):\n raw = base58.b58encode(data)\n return 'z' + raw.decode()",
"def encode_base58(bytestring):\n # Count zero's\n zeros = 0\n for i in range(len(bytestring)):\n if bytestring[i] == 0:\n zeros += 1\n else:\n break\n\n n = int.from_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Encode a value of contract type (address + optional entrypoint) into bytes. | def forge_contract(value) -> bytes:
parts = value.split('%')
address, entrypoint = (parts[0], parts[1]) if len(parts) == 2 else (parts[0], 'default')
res = forge_address(address)
if entrypoint != 'default':
res += entrypoint.encode()
return res | [
"def _encode_value(self, value) -> bytes:\n pass",
"def encode(value: CLValue) -> bytes:\n encoder = ENCODERS[value.cl_type.typeof]\n if value.cl_type.typeof in {CLTypeKey.LIST, CLTypeKey.OPTION}:\n return encoder(\n value.parsed,\n ENCODERS[value.cl_type.inner_type.typeo... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Write a novel at `filepath`. | def write(self, filepath):
with open(filepath, 'w') as f:
written = 0
while written < self.size:
paragraph, length = self.get_paragraph()
f.write(paragraph)
written += length | [
"def write_to(self, filepath):\n output = self._generate_output()\n with open(filepath, 'wb') as out:\n out.write(output.encode('utf-8'))\n out.write(b'<!-- handrolled for excellence -->\\n')",
"def write(self, filename):\n pass",
"def write_to_file(self, filename: str... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a paragraph of text and its wordcount. | def get_paragraph(self):
size = self.paragraph_sizes.get()
size += int(random.randrange(int(size * 0.8), int(size * 1.2)))
lines = []
paragraph_length = 0
while paragraph_length < size:
sentence, length = self.get_sentence()
line... | [
"def ParagraphCount(text):\r\n text = text.split(\"\\n\")\r\n new_paragraphs = 1 + sum(1 for i in range(len(text)-1) if not text[i] and text[i+1])\r\n print(\"\\nThis is the number of paragraphs (blocks of lines separated by multiple new lines) in your text file\\n\")\r\n print(new_parag... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a newly generated string word. | def create_word(self):
template = self.word_constructions.get()
word = ""
for c in template:
if c == "v":
letter = self.get_letter(100)
else:
letter = self.get_letter(0)
word += letter
while not any(letter i... | [
"def random_string():\n\treturn WORD_GENERATOR.generate_word()",
"def generate_word(self, word):\n if word == \"Noun\":\n return self.random_noun()\n elif word == \"Adjective\":\n return self.random_adjective()\n elif word == \"Adverb\":\n return self.random_a... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates empty probability sets for object. | def initiatilise_empty_probability_sets(self):
self.letters = probabilities.ProbabilitySet(adjust=True, redo_repeats=True)
self.punctuation_endline = probabilities.ProbabilitySet()
self.punctuation_midline = probabilities.ProbabilitySet()
self.punctuation_matched = probabilitie... | [
"def generateInitialObjects(self):\n raise NotImplementedError()",
"def create_population(self):\n for i in xrange(0, Problem.NB_POPULATION):\n shuffle(self.keys) # Use Fisher-Yates shuffle, O(n). Better than copying and removing\n self.population.append(Solution(self.keys[:])... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a filtered string of vowels with unlikely ones removed. Vowels are filtered based on if they appear without other vowels. If a word contains just one vowel, that vowel's usage is incremented. A vowel is kept if uses > iteration Where iteration is the number of the current iteration (from 0 to `iterations`). This... | def filter_vowels(self, vowels, word_set, iterations=10):
true_vowels = vowels
for i in range(iterations):
vowels = true_vowels
# Go backwards as the last ones are least likely.
for vowel in vowels[::-1]:
uses = 0
for w... | [
"def remove_vowels(self, word):\n vowel_sample = random.sample(self.vowels,\n random.randrange(len(self.vowels)))\n remove_vowel_rule = str.maketrans(dict.fromkeys(vowel_sample,\n None))\n if len(word) ==... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a string showing the consonant and vowel construction of word. Returns a string with the characters c and v in place of consonants and vowels respectively. | def calculate_construction(self, word):
construction = ""
for c in word.lower():
if c in self.vowels:
construction += "v"
elif c in letters:
construction += "c"
return construction | [
"def generate_syllables(consonants, vowels):\n result = []\n for c in consonants:\n for v in vowels:\n result.append(c + v + \"\\n\")\n return ''.join(result)",
"def translate(x):\n string=\"\"#set up a new string\n x=x.replace(\" \",\"\")#take care of spaces\n for i in range(0... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a playlist with a given name. | def create_playlist(self, playlist_name):
print("create_playlist needs implementation") | [
"def create_playlist(self, playlist_name):\n \n # lower case the playlist name\n pl = playlist_name.lower()\n # create a whole new playlist\n if pl:\n print(\"Successfully created new playlist:\", playlist_name)\n # if the playlist is already existing\n el... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Handles authentication, and persists the XAPPLEWEBKB cookie so that subsequent logins will not cause additional emails from Apple. | def authenticate(self):
LOGGER.info(f"Authenticating as {self.user['apple_id']}")
data = dict(self.user)
# We authenticate every time, so "remember me" is not needed
#data.update({"extended_login": False})
data.update({"extended_login": True})
try:
req = s... | [
"def persist_apple_session(request, response):\n patch_vary_headers(response, ('Cookie',))\n request.apple_login_session.save()\n response.set_cookie(\n APPLE_SESSION_COOKIE_NAME,\n request.apple_login_session.session_key,\n max_age=None,\n expires=None,\n domain=settings... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get path for cookiejar file. | def _get_cookiejar_path(self):
return path.join(
self._cookie_directory,
"".join([c for c in self.user.get("apple_id") if match(r"\w", c)]),
) | [
"def get_default_cookiejar_path():\n cache_dir = xdg.BaseDirectory.save_cache_path('AUR')\n return os.path.join(cache_dir, 'cookiejar.txt')",
"def get_auth_cookie_path(self):\r\n \r\n # fetches authentication type and cookie path if still unloaded\r\n if self._authType == None: self.get_auth_type()\r\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns devices trusted for twostep authentication. | def trusted_devices(self):
request = self.session.get(
f"{self.SETUP_ENDPOINT}/listDevices", params=self.params
)
return request.json().get("devices") | [
"def trust_devices(self, user_id: str, device_list: Optional[str] = None) -> None:\n\n print(f\"{user_id}'s device store: {self.device_store[user_id]}\")\n\n # The device store contains a dictionary of device IDs and known\n # OlmDevices for all users that share a room with us, including us.\n\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Requests that a verification code is sent to the given device. | def send_verification_code(self, device):
data = json.dumps(device)
request = self.session.post(
f"{self.SETUP_ENDPOINT}/sendVerificationCode",
params=self.params,
data=data,
)
LOGGER.info(f"Send Trusted Device ID result-{request.json()}")
retu... | [
"def send_verification_code(request) -> HttpResponse:\n request_data = get_request_data(request.body)\n if request_data is None:\n return error_response()\n\n phone_number = get_e164_phone_number(request_data.phone_number, request_data.region)\n if phone_number is None:\n return error_resp... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get webservice URL, raise an exception if not exists. | def _get_webservice_url(self, ws_key):
if self._webservices.get(ws_key) is None:
raise PyiCloudServiceNotActivatedException(
"Webservice not available", ws_key
)
return self._webservices[ws_key]["url"] | [
"def get_url(endpoint_or_url):\n try:\n return url_for(endpoint_or_url)\n except:\n return endpoint_or_url",
"def test_get_url():\n js = None\n try:\n cfg = config()\n js = rs.job.Service(cfg.job_service_url, cfg.session)\n assert(str(js.get_url()) == str(cfg.job_ser... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets the 'Friends' service. | def friends(self):
service_root = self._get_webservice_url("fmf")
return FindFriendsService(service_root, self.session, self.params) | [
"def get_friends():\r\n friends = datastore.get_friends(g.datastore)\r\n return jsonify({\"friends\": friends})",
"def getFriendsList(self):\n\t\treturn self.friends",
"def get_friends(self):\n\n # return a QuerySet\n person = Profile.objects.filter(id=self.pk)[0]\n friends = person.f... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets the 'Contacts' service. | def contacts(self):
service_root = self._get_webservice_url("contacts")
return ContactsService(service_root, self.session, self.params) | [
"def contacts(self):\n from hubspot3.contacts import ContactsClient\n\n return ContactsClient(**self.auth, **self.options)",
"def get_contacts(self):\n\n\t\treturn self.__contacts",
"def contacts(self):\n return ContactCollection(self.request)",
"def get_contacts():\n # Parse command lin... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns status information for device. This returns only a subset of possible properties. | def status(self, additional=[]): # pylint: disable=dangerous-default-value
self.manager.refresh_client()
fields = ["batteryLevel", "deviceDisplayName", "deviceStatus", "name"]
fields += additional
properties = {}
for field in fields:
properties[field] = self.content.... | [
"async def get_device_status(self, device_id: str) -> dict:\r\n return await self.get(API_DEVICE_STATUS.format(device_id=device_id))",
"def device_status_overview(self):\n if \"deviceStatusOverview\" in self._prop_dict:\n if isinstance(self._prop_dict[\"deviceStatusOverview\"], OneDriveOb... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Send a request to the device to play a sound. It's possible to pass a custom message by changing the `subject`. | def play_sound(self, subject="Find My iPhone Alert"):
data = json.dumps(
{
"device": self.content["id"],
"subject": subject,
"clientContext": {"fmly": True},
}
)
self.session.post(self.sound_url, params=self.params, data=dat... | [
"def playSound(self,sound):\n sound.play()",
"def play(snd):\n\n snd.play()",
"async def sound(self, ctx, name='default', start=0):\n voice = discord.utils.get(self.bot.voice_clients, guild=ctx.guild)\n \n if not (ctx.author.voice or voice):\n await ctx.message.add_reac... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Send a request to the device to trigger 'lost mode'. The device will show the message in `text`, and if a number has been passed, then the person holding the device can call the number without entering the passcode. | def lost_device(
self, number, text="This iPhone has been lost. Please call me.", newpasscode=""
):
data = json.dumps(
{
"text": text,
"userText": True,
"ownerNbr": number,
"lostModeEnabled": True,
"trackingE... | [
"def mark_lost(self, request):\n self.check_xsrf_token(self.request_state)\n device = _get_device(request)\n user_email = user_lib.get_user_email()\n try:\n device.mark_lost(user_email=user_email)\n except device_model.UnauthorizedError as err:\n raise endpoints.UnauthorizedException(str(er... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Customizable logic to determine whether the data should be refreshed. By default, this returns False. Consumers can set `refresh_always` to True or assign their own function that takes a singleargument (the last reponse) and returns a boolean. | def should_refresh_client(self):
return self.refresh_always or FindFriendsService.should_refresh_client_fnc(
self.response
) | [
"def incremental_dataset_refresh_enabled(self) -> Optional[pulumi.Input[bool]]:\n return pulumi.get(self, \"incremental_dataset_refresh_enabled\")",
"def enable_incremental_dataset_refresh(self) -> Optional[pulumi.Input[bool]]:\n return pulumi.get(self, \"enable_incremental_dataset_refresh\")",
"d... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the location of your friend with a given contact_id | def location_of(self, contact_id, default=None):
candidates = [
item.get("location", default)
for item in self.locations
if item.get("id") == contact_id
]
if not candidates:
return default
return candidates[0] | [
"def get_location_by_id(self, location_id):",
"def contact_point(self) -> object:\n return self._contact_point",
"def getContactById(self, id):\n for contact in self.contacts:\n if contact.id == id:\n return contact\n if self.profile:\n if self.profile.i... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return true if the password of a username exists in the keyring. | def password_exists_in_keyring(username):
try:
get_password_from_keyring(username)
except PyiCloudNoStoredPasswordAvailableException:
return False
return True | [
"def is_registered(username):\n with open(PASSFILE, \"r\") as passfile:\n for record in passfile:\n try:\n r_username, r_salt_hash = record.split()\n # The below is just for the linter\n r_salt_hash = r_salt_hash + \"nothing\"\n if use... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Store the password of a username. | def store_password_in_keyring(username, password):
return keyring.set_password(KEYRING_SYSTEM, username, password,) | [
"def set_password(self, username, password, hashfunc=crypt_passwd):\n self[username] = hashfunc(password)",
"def _put_username_password(self) -> None:\n\n username, password = self._locate_userpass_fields()\n username.send_keys(self.yourname)\n password.send_keys(self.yourpass)",
"de... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Delete the password of a username. | def delete_password_in_keyring(username):
return keyring.delete_password(KEYRING_SYSTEM, username,) | [
"def delete_password(self, service, username):\n raise NotImplementedError('handled at a higher level')",
"def remove(ctx, all):\n # retrieving from parameter because host_info is already overwritten\n # with old password from credential file\n credentials.remove_credentials(ctx.obj['username'], a... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Wheels created from sdists are not reproducible by default. We can however workaround this by patching in some configuration with environment variables. | def configure_reproducible_wheels():
# wheel, by default, enables debug symbols in GCC. This incidentally
# captures the build path in the .so file We can override this
# behavior by disabling debug symbols entirely.
# https://github.com/pypa/pip/issues/6505
if os.environ.get("CFLAGS") is not None:... | [
"def __init__(self, wheels):\n super().__init__()\n self.wheels = wheels",
"def sdist():\n pass",
"def monkeypatch_distros(monkeysession):\n\n monkeysession.setattr(DistroMapping, 'distros_for', mock_distros_for)",
"def make_repeatable():\n random.seed(1234)\n np.random.seed(1234)",
... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generate cc_library rule for numpy headers. | def _get_numpy_headers(directory):
sys.path.insert(0, directory)
import numpy
include_dir = os.path.relpath(numpy.get_include(), directory)
sys.path.pop(0)
return """
cc_library(
name = "headers",
hdrs = glob(["{include_dir}/**/*.h"]),
includes = ["{include_dir}"],
)
""".format(
... | [
"def cblas_header_text():\r\n\r\n return \"\"\"\r\n //#include <stddef.h>\r\n\r\n #undef __BEGIN_DECLS\r\n #undef __END_DECLS\r\n #ifdef __cplusplus\r\n #define __BEGIN_DECLS extern \"C\" {\r\n #define __END_DECLS }\r\n #else\r\n #define __BEGIN_DECLS /* empty */\r\n #define ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
node id for dot output | def dot_id(self):
return u"{0}_{1}".format(
Concept.d_clean(self.dot_printname()), str(id(self))[-4:]) | [
"def node_identifier(node: onnx.NodeProto) -> str:\n return node.output[0]",
"def node_id(self) -> str:\n return pulumi.get(self, \"node_id\")",
"def node_id(self):\n return self._node_id",
"def _auto_name(self):\n return \"node_\"+str(self._id)",
"def identifier(cls):\r\n\r\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
printname for dot output | def dot_printname(self):
return self.printname.split('/')[0].replace('-', '_') | [
"def dot():\n print_message(\".\")",
"def printDot(self, filename=\"namespace.dot\"):\n file=open(filename, 'w+')\n\n file.write(\"digraph ns {\\n\")\n for n in self.nodes:\n file.write(n.printDot())\n file.write(\"}\\n\")\n file.close()",
"def dot_format(out, graph, name=\"digraph\")... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Helper functions that creates a titlestyled label | def create_title(text, y=PADDING, screen=None):
if screen is None:
screen = lv.scr_act()
lbl = lv.label(screen)
lbl.set_style(0, styles["title"])
lbl.set_text(text)
lbl.set_long_mode(lv.label.LONG.BREAK)
lbl.set_width(HOR_RES-2*PADDING)
lbl.set_x(PADDING)
lbl.set_align(lv.label.A... | [
"def __create_title(self):\n self.title_label=tk.Label(self, text=\"Welcome to Alexander Gorkun's number converter\\n\"\n \"Click \\\"Convert\\\" to convert \"\n \"a number from one numeration to another\")\n self.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Helper function that creates a button with a text label | def create_button(text, callback=None, screen=None, y=700):
if screen is None:
screen = lv.scr_act()
btn = lv.btn(screen)
btn.set_width(HOR_RES-2*PADDING);
btn.set_height(BTN_HEIGHT);
lbl = lv.label(btn)
lbl.set_text(text)
lbl.set_align(lv.label.ALIGN.CENTER)
btn.align(scre... | [
"def make_button(self, maker):\n maker.make_text_button(self)",
"def CreateButton(self, labelExpr, returnExpr, insPos=None):\n callResult = self._Call(\"CreateButton\", labelExpr, returnExpr, insPos)",
"def create_label(self, on, text: str):\n return tk.Label(on, font=self.FONT, bg=self.BG_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
A sample screen that has a counter and two buttons | def show_counter_screen():
# Get and clear active screen
clear()
create_title("Here is the counter:")
obj = {"counter": 0}
counter_lbl = create_title("%d" % obj["counter"])
counter_lbl.set_y(150-counter_lbl.get_height()//2)
def plus_one(btn, e):
if e == lv.EVENT.RELEASED:
... | [
"def update_count(self):\n self.bttn_clicks += 1\n self.bttn1[\"text\"] = \"positive clicker \" + str(self.bttn_clicks) \n self.label = Label(self, text=\"Total clicks: \" + str(self.bttn_clicks))\n self.label.grid()",
"def test_button(self):\n callback = CallbackCounter()... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the loss function according to the loss config name and parameters. | def get_loss(loss_config):
if hasattr(torch_losses, str(loss_config.name)):
function = getattr(torch_losses, loss_config.name)
return function(**loss_config.params.dict())
if loss_config.name == 'FocalLoss':
return FocalLoss(**loss_config.params.dict())
else:
raise ValueError... | [
"def get_loss_func(loss_func_name):\n\n if loss_func_name == \"cross_entropy\":\n loss_func = nn.CrossEntropyLoss(reduction='mean')\n elif loss_func_name == \"binary_cross_entropy\":\n loss_func = nn.BCELoss(reduction='mean')\n elif loss_func_name == \"mse\":\n loss_func = nn.MSELoss(r... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Remove build directory of gem5 | def clean_gem5(c):
_delete_file(f'{ROOT_DIR}/gem5/build/') | [
"def remove_build():\n yield\n path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'build')\n shutil.rmtree(path)",
"def _remove_build_dir(self):\n\n self._temp_build_dir = None",
"def _clean_native_build():\n rmtree(BUILD_DIR)",
"def clean_build_path(self):\n if os.path... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Clean condor files (log, err, out, ...) | def clean_condor(c):
for fname in glob.glob(os.path.join(ROOT_DIR, '*.dag')):
_delete_pattern(fname + '.*')
for fname in glob.glob(os.path.join(ROOT_DIR, '*.sub')):
temps = []
with open(fname, 'r') as f:
for line in f.readlines():
for w in ('log', 'error', 'ou... | [
"def _clean_files(self):\n if self.delfiles & 1:\n ProcUtils.remove(self.okm)\n if self.delfiles & 2:\n ProcUtils.remove(self.hkm)\n if self.delfiles & 4:\n ProcUtils.remove(self.qkm)\n if self.delfiles & 8:\n ProcUtils.remove(self.obc)\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Build all of gem5 GCN3 | def build_gem5(c, archive=False):
_run(c, f'cd {ROOT_DIR}/gem5/ && scons -j$(nproc) ./build/GCN3_X86/gem5.opt')
if archive:
_run(c, f'tar -czf gem5-build.tar gem5/build/') | [
"def build_examples():\n build_models([\n \"VGG_16\",\n \"VGG_19\",\n \"RESNET_50\",\n \"MOBILENET\",\n #\"INCEPTION_V3\",\n #\"INCEPTION_RESNET\",\n #\"DENSENET_121\",\n #\"DENSENET_169\",\n #\"DENSENET_201\"])\n ])",
"def mk_rg3(self):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Mehod to set documents_names | def set_documents_names(cls, input_list_names: List[str]) -> None:
cls.documents_names = input_list_names | [
"def set_document_name_for_search(self, document_name):\n self.set_value_into_input_field(self.document_name_locator, document_name)",
"def document_name(self, document_name):\n\n self._document_name = document_name",
"def __init__(self, description, corpus_documents):\n self.description = ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
得到过滤后的值, 过滤规则: number小于等于20 address不等于长沙一号机、长沙办公室测试机 python循环删除list,必须把它赋新值才能生效 | def get_filter_value(self):
res = self.get_warning()
value = res[:]
for re in res:
if re['address'] == '长沙一号机' or re['address'] == '长沙办公室测试机':
value.remove(re)
elif int(re['number']) > 20:
value.remove(re)
return value | [
"def filter_list(input_list, th_val=None):\n if not th_val:\n print(\"Inserta el umbral a partir de cual se filtraran los valores de la lista anterior\")\n while True:\n input_val = input()\n try:\n th_val = float(input_val)\n break\n e... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Draw every object with a `.draw()` method, in order of increasing `.z` value | def draw(self, **kwargs):
for o in sorted(self._drawables, key=default_itemgetter("z", default=0)):
o.draw(**kwargs) | [
"def draw():\n window.clear()\n for obj in objects:\n obj.draw()\n draw_circle(obj.x, obj.y, obj.radius)",
"def draw_objects_on_screen(self):\n self.draw_ship()\n self.draw_asteroid()\n self.draw_torpedo()\n self.draw_special_torpedo()",
"def draw_objects(self):\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculates your slide value for Clover based on an input address (in hex). | async def slide(self, ctx, input_hex = None):
try:
# We're accepting strings here - convert
start_addr = int(input_hex, 16)
except:
await ctx.send("Malformed input hex - try again.")
return
# Setup our temp vars
first_str = "0x100000"
... | [
"async def slide(self, ctx, input_hex = None):\n\t\ttry:\n\t\t\t# We're accepting strings here - convert\n\t\t\tstart_addr = int(input_hex, 16)\n\t\texcept:\n\t\t\tawait ctx.send(\"Malformed input hex - try again.\")\n\t\t\treturn\n\t\t# Setup our temp vars\n\t\tfirst_str = \"0x100000\"\n\t\tfirst = int(first_str, ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Converts the input binary to its string representation. | async def binstr(self, ctx, *, input_binary = None):
if input_binary == None:
await ctx.send("Usage: `{}binstr [input_binary]`".format(ctx.prefix))
return
# Clean the string
new_bin = ""
for char in input_binary:
if char is "0" or char is "1":
... | [
"async def binstr(self, ctx, *, input_binary = None):\r\n\t\tif input_binary is None:\r\n\t\t\treturn await ctx.send(\"Usage: `{}binstr [input_binary]`\".format(ctx.prefix))\r\n\t\t# Clean the string\r\n\t\tnew_bin = \"\"\r\n\t\tfor char in input_binary:\r\n\t\t\tif char == \"0\" or char == \"1\":\r\n\t\t\t\tnew_bi... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Converts the input binary to its integer representation. | async def binint(self, ctx, *, input_binary = None):
if input_binary == None:
await ctx.send("Usage: `{}binint [input_binary]`".format(ctx.prefix))
return
try:
msg = int(input_binary, 2)
except Exception:
msg = "I couldn't make that conversion!"
... | [
"async def binint(self, ctx, *, input_binary = None):\n\t\tif input_binary == None:\n\t\t\tawait ctx.send(\"Usage: `{}binint [input_binary]`\".format(ctx.prefix))\n\t\t\treturn\n\t\ttry:\n\t\t\tmsg = int(input_binary, 2)\n\t\texcept Exception:\n\t\t\tmsg = \"I couldn't make that conversion!\"\n\t\tawait ctx.send(ms... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
In the case of assertFailure failing, check that we get lots of information about the exception that was raised. | def test_assertFailure_moreInfo(self):
try:
1 / 0
except ZeroDivisionError:
f = failure.Failure()
d = defer.fail(f)
d = self.assertFailure(d, RuntimeError)
d.addErrback(self._checkInfo, f)
return d | [
"def assertion_failed(self, func, exception):",
"def test_xfail_expected_failure(self):\n assert False",
"def assertion_errored(self, func, exception):",
"def assert_expectations():\n if _failed_expectations:\n assert False, _report_failures()",
"def test_tracebacksCauseTestFailure(self):\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generate a random image given commandline arguments. | def genrandimg(args) -> None:
size = (int(args.x), int(args.y))
fp = Image.new("RGB", size)
data = []
if not args.c: # If color
for i in range(size[0]*size[1]):
r = random.choice([0x00, 0xff])
data.append((r, r, r)) # Each RGB value is the same random value
else: ... | [
"def generateRandomImage(size, lims=[0,255]):\n a,b = lims\n image_array = (b-a)*np.random.random(size) + a\n image = sitk.GetImageFromArray(image_array.astype(int))\n return image",
"def generate_line(args, num_samples, img_pos, path_info):\n line = \" \".join([\"opencv_createsamples -img\", img_p... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Convert image file to RGB. | def convtoRGB(filename: str):
fp = Image.open(filename)
if fp.mode == "RGB":
return 0
fp = fp.convert("RGB")
fp.save(filename)
fp.close()
return 1 | [
"def convert_image_to_rgb(self):\n self.image = self.image.convert('RGB')",
"def convert_to_rgb(image):\n if image.mode != \"RGB\":\n image = image.convert(\"RGB\")\n return image",
"def _read_rgb(rgb_filename, img_h=480, img_w=640): # 0.01s\n # rgb = misc.imread(rgb_file... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Perform one of 3 operations on a tuple of ints. For pixel bitwise operations. | def tuple_operation(a: list, b: list, op: str) -> list:
o = []
for i in range(0, 3):
if op == "xor":
o.append(a[i] ^ b[i])
elif op == "and":
o.append(a[i] & b[i])
elif op == "or":
o.append(a[i] | b[i])
else:
raise RuntimeError('Unkn... | [
"def tuple_int(arg):\n return int(arg[0]), int(arg[1])",
"def Shp(*values):\n return tuple(np.uint64(value) for value in values)",
"def bitmask(*args: Union[int, Sequence[int], Tuple[int, int]]) -> int:\n mask = 0\n\n for a in args:\n if isinstance(a, tuple):\n hi, lo = a\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Attempts to parse Season from filename. If no season is found, returns S01. | def parse_season(filename):
print_info('Attempting to parse {0}'.format(filename))
print_info('Extracting season from {0}'.format(filename))
for regex in SEASON_REGEX:
m = re.search(regex, filename)
if m is None:
continue
extracted_season = m.group('Season').lower()
... | [
"def extract_season(file_name):\n logging.debug(\"Extracting season from {0}\".format(file_name))\n\n season_part = file_name.split(\".\")[0].split(\"_\")[-1]\n season_out = season_part[:2] + \"/\" + season_part[-2:]\n\n return season_out",
"def get_season_number(file):\n\tmedia_info = MediaInfo.parse... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Attempts to parse episode title from filename. Will strip out separators at start of string. If no title is found, returns empty string | def parse_episode_title(filename):
print_info('Attempting to parse episode title from {0}'.format(filename))
for regex in EPISODE_TITLE_REGEX:
m = re.search(regex, filename)
if m is None:
continue
extracted_title = m.group('EpisodeTitle')
return clean_episode_title(... | [
"def parse_anime_episode_title(filename):\n print_info('Attempting to parse episode title from {0}'.format(filename))\n for regex in ANIME_EPISODE_TITLE_REGEXS:\n m = re.search(regex, filename)\n\n if m is None:\n continue\n\n extracted_title = m.group('EpisodeTitle')\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given a filename, attempts to match a part num (a = 1, b = 2) from the title. Returns 0 if no matches. | def parse_episode_part(filename):
print_info('Extracting part num from {0}'.format(filename))
baseline = ord('a')
for regex in EPISODE_PART_REGEXS:
m = re.search(regex, filename)
if m is None:
continue
extracted_part = m.group('Part').lower()
print_info('Extrac... | [
"def test_sequence_simple(self):\n test_str = \"_1.txt\"\n matches = REGEX_FILE_COUNTER.search(test_str)\n self.assertTrue(matches)\n self.assertEqual(matches.group('i'), '1')",
"def parse_file_name(filename):\n import re\n rgx = r'bin_thresh_([0-9]+).*n_bins_([0-9]+)'\n m = r... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given a filename, matches episode and returns episode in E01 format. This will ignore episode parts. Returns None if no matches. | def parse_episode(filename):
print_info('Extracting episode from {0}'.format(filename))
for regex in EPISODE_NUM_REGEXS:
m = re.search(regex, filename)
if m is None:
continue
extracted_ep = m.group('Episode').lower()
print_info('Extracted episode: {0}'.format(extrac... | [
"def parse_anime_episode(filename):\n print_info('Extracting episode from {0}'.format(filename))\n for regex in ANIME_EPISODE_NUM_REGEXS:\n m = re.search(regex, filename)\n\n if m is None:\n continue\n\n extracted_ep = m.group('Episode')\n print_info('Extracted episode: ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given a filename, match anime sub group and return group without brackets. Returns None if no matches. | def parse_anime_group(filename):
print_info('Extracting hash from {0}'.format(filename))
for regex in ANIME_GROUP_REGEXS:
m = re.search(regex, filename)
if m is None:
continue
ep_group = m.group('Group')
print_info('Extracted Group: {0}'.format(ep_group))
re... | [
"def visit_from_file_name(filename):\n expr = re.compile(r\"\\d{4}(?:\\d+)\")\n res = expr.search(filename)\n if res is None:\n return None\n return res.group()",
"def getMatch(reMatch,group=0):\n if reMatch: return reMatch.group(group)\n else: return ''",
"def _grou... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given a filename, matches episode and returns episode in E01 format. This will ignore episode parts. Returns None if no matches. | def parse_anime_episode(filename):
print_info('Extracting episode from {0}'.format(filename))
for regex in ANIME_EPISODE_NUM_REGEXS:
m = re.search(regex, filename)
if m is None:
continue
extracted_ep = m.group('Episode')
print_info('Extracted episode: {0}'.format(ex... | [
"def parse_episode(filename):\n print_info('Extracting episode from {0}'.format(filename))\n for regex in EPISODE_NUM_REGEXS:\n m = re.search(regex, filename)\n\n if m is None:\n continue\n\n extracted_ep = m.group('Episode').lower()\n print_info('Extracted episode: {0}'... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |