query
stringlengths
9
9.05k
document
stringlengths
10
222k
negatives
listlengths
19
20
metadata
dict
Download the list of files, given that the csv list of files have been parsed
def download_file_list(self, limit=None, test_page='https://www.google.com'): # test csv file parsing if self.file_list is None: raise NoFileListProvided() # test Internet connection try: urllib.request.urlopen(test_page, timeout=2) except urllib.request....
[ "def download_files(\n urls: str,\n save_dir: str\n )-> None:\n for url in urls:\n url = 'http://www.ispdados.rj.gov.br/' + url\n \n print(f'Downloading file from {url}')\n # Extract the filename from the URL\n filename = os.path.basename(url)\n\n # Create the f...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
LNPay module initialization function required for interacting with the LNPay API.
def initialize(public_api_key, default_wak=None, params=None): if params is None: params = {} print('initializing lnpay..') global __VERSION__ global __PUBLIC_API_KEY__ global __ENDPOINT_URL__ global __DEFAULT_WAK__ __VERSION__ = 'py' + __version__ __PUBLIC_API_KEY__ = public...
[ "def init_package():\n global PlatformConfiguration\n if not PlatformConfiguration.LoadedAny:\n # May switch over to \"silent\" loading, but not knowing which config files were loaded can\n # cause a lot of errors...\n PlatformConfiguration = econ_platform_core.configuration.load_platform...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Implements fast multifile find and replace. Given an |original| string and a |replacement| string, find matching files by running git grep on |original| in files matching any pattern in |file_globs|. Once files are found, |re.sub| is run to replace |original| with |replacement|. |replacement| may use capture group back...
def MultiFileFindReplace(original, replacement, file_globs): # Posix extended regular expressions do not reliably support the "\s" # shorthand. posix_ere_original = re.sub(r"\\s", "[[:space:]]", original) if sys.platform == 'win32': posix_ere_original = posix_ere_original.replace('"', '""') out, err = sub...
[ "def _scitools_subst(patterns, replacements, filenames,\n pattern_matching_modifiers=0):\n # if some arguments are strings, convert them to lists:\n if isinstance(patterns, basestring):\n patterns = [patterns]\n if isinstance(replacements, basestring):\n replacements = [rep...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
returns number of common characters between two strings
def commonCharacterCount(s1, s2): return sum(min(s1.count(x),s2.count(x)) for x in set(s1))
[ "def common_chars(string1, string2):\n \n common = Counter(string1.casefold()) & Counter(string2.casefold())\n return sum(common.values())", "def string_match(a, b):\n count = 0\n\n shorter = min(len(a), len(b))\n\n for i in range(shorter-1):\n if a[i:i+2] == b[i:i+2]:\n count ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Fit the model using the given censored and noncensored inputs, and return predictions and probabilities.
def naive_fit(censored_inputs, noncensored_inputs, initialize): censored_inputs = censored_inputs[ :, 1: ] # To feed into scikit learn, we omit the unnecessary leading 1's. noncensored_inputs = noncensored_inputs[:, 1:] n_noncens = len(noncensored_inputs) n_cens = len(censored_inputs) ...
[ "def fit_predict(x_train: np.ndarray, y_train: np.ndarray, x_test: np.ndarray) -> np.ndarray:\n logger.log('Creating KNN model with params:')\n model = neighbors.KNeighborsClassifier()\n logger.log(model.get_params())\n\n logger.log('Fitting model...')\n start_time = time.perf_counter()\n model.fi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Bundling the flow conversion functions into a class to track a wider range of normalisation and transformation options. Note that conversions combining norm_factor+cmax, or lower_bound+cmin, may have unintended edge cases. Please combine with caution.
def __init__(self, norm_factor=None, lower_bound=None, rmax=None, rmin=None): #TODO: Enforce typing on arguments self.norm = norm_factor self.eps = lower_bound self.rmax = rmax self.rmin = rmin items = [rmax, rmin] self.inv_rad = any([False if i is None else True ...
[ "def _transform_vmin_vmax(self):\n vmin, vmax = self.vmin, self.vmax\n arr = np.array([vmax, vmin]).astype(float)\n self._upper, self._lower = self._transform(arr)", "def apply_channelTransforms(self):\n try: \n if not (self.chanObj.Calibration[0].PCDATA == '' or self.chanOb...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function plots decision tree.
def plot_decision_tree(classifier, feature_names=None, class_names=None): fig, axes = plt.subplots(nrows=1, ncols=1, figsize=(4, 4)) tree.plot_tree( classifier, feature_names=feature_names, class_names=class_names, rounded=True, filled=True, ) fig.show()
[ "def decision_tree(df):\n features = df[['Temperature(F)', 'Humidity(%)', 'Visibility(mi)', 'Wind_Speed(mph)',\n 'Precipitation(in)', 'Amenity', 'Bump', 'Crossing', 'Give_Way',\n 'Junction', 'No_Exit', 'Railway', 'Roundabout', 'Station', 'Stop',\n 'Traffic_Calming', 'Traffic_Signal', 'Civil_Twi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function takes a pandas dataframe, a list of numerical columns and create a list of columns that needs to be converted to categorical column if it is less than or equal to n_unique_val.
def num_to_cat_list(df, num_col_list, n_unique_val): # columns that needs to converted cols_to_convert = [] for col in num_col_list: unique_val = df[col].nunique() print(col, unique_val) if unique_val <= n_unique_val: cols_to_convert.append(col) return cols_to_conver...
[ "def create_categorical_dummies(df, cols=None, max_uniques=5):\n columns_to_check = df.columns if not cols else cols\n\n #categorical_cols = filter_df_dtypes(df[columns_to_check], include=[object])\n categorical_cols = columns_to_check\n #print(\"TEST create_categorical_dummies: '\\n\\t columns_to_check...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function calculates the confidence interval for the population mean when standard deviation is known.
def ci_mean_std_known(array, std, conf_level=95): # calculate significance level alpha = np.round((1 - conf_level / 100), 2) mean = np.mean(array) n = len(array) # calculate standard error std_error = std / np.sqrt(n) # find z critical value z_star = np.round(stats.norm.ppf(1 - alpha / 2...
[ "def ci_mean_std_unknown(array, conf_level=95):\n # calculate significance level\n alpha = np.round((1 - conf_level / 100), 2)\n # mean of the sample\n mean = np.mean(array)\n # standard deviation\n std = np.std(array)\n # size of the sample\n n = len(array)\n # degrees of freedom\n df...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function calculates the confidence interval for a population mean when the standard deviation is unknown.
def ci_mean_std_unknown(array, conf_level=95): # calculate significance level alpha = np.round((1 - conf_level / 100), 2) # mean of the sample mean = np.mean(array) # standard deviation std = np.std(array) # size of the sample n = len(array) # degrees of freedom df = n - 1 # ...
[ "def ci_mean_std_known(array, std, conf_level=95):\n # calculate significance level\n alpha = np.round((1 - conf_level / 100), 2)\n mean = np.mean(array)\n n = len(array)\n # calculate standard error\n std_error = std / np.sqrt(n)\n # find z critical value\n z_star = np.round(stats.norm.ppf(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function calculates the Confidence Interval for the difference between two means.
def ci_diff_mean_std_known(array1, array2, std1, std2, conf_level=95): # calculate significance level alpha = np.round((1 - conf_level / 100), 2) # means of samples mean1 = np.mean(array1) mean2 = np.mean(array2) # size of the samples n1 = len(array1) n2 = len(array2) # difference...
[ "def calculateConfidenceInterval(accuracies):\n # calculate the sample mean of the accuracies\n sampleMean = np.mean(accuracies)\n\n # calculate the sample standard deviation of the accuracies\n sumOfDiffs = np.sum((accuracies-sampleMean)**2)\n\n # get the bounds of the confidence interval (ci)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function calculates the confidence interval for a population proportion.
def ci_prop(p, n, conf_level=95): # calculate significance level alpha = np.round((1 - conf_level / 100), 2) # standard error std_error = np.sqrt(p * (1 - p) / n) # find the z critical value z_star = np.round(stats.norm.ppf(1 - alpha / 2), 3) # margin of error margin_of_error = np.round(...
[ "def _lower_confidence_bound(self, n_class_samples: int, n_total_samples: int) -> float:\n from statsmodels.stats.proportion import proportion_confint\n\n return proportion_confint(n_class_samples, n_total_samples, alpha=2 * self.alpha, method=\"beta\")[0]", "def compute_confidence_interval(data):\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function calculates Confidence Interval for the difference in two population proportions.
def ci_diff_prop(p1, p2, n1, n2, conf_level=95): # calculate significance level alpha = np.round((1 - conf_level / 100), 2) prop_diff = p1 - p2 # find the z critical value z_star = np.round(stats.norm.ppf(1 - alpha / 2), 3) margin_of_error = z_star * (np.sqrt((p1 * (1 - p1) / n1) + (p2 * (1 - p2...
[ "def ci_prop(p, n, conf_level=95):\n # calculate significance level\n alpha = np.round((1 - conf_level / 100), 2)\n # standard error\n std_error = np.sqrt(p * (1 - p) / n)\n # find the z critical value\n z_star = np.round(stats.norm.ppf(1 - alpha / 2), 3)\n # margin of error\n margin_of_erro...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function takes a pandas date column and give some summary information between two dates.
def describe_date(date): min_date = date.min() max_date = date.max() total_months = ( pd.to_datetime(date.max()).year - pd.to_datetime(date.min()).year ) * 12 + (pd.to_datetime(date.max()).month - pd.to_datetime(date.min()).month) total_days = str(pd.to_datetime(date.max()) - pd.to_datetime(...
[ "def get_basic_stats_by_date(log_path, log_sheet, log_type, start_date, end_date):\n start_date = pd.to_datetime(start_date)\n end_date = pd.to_datetime(end_date)\n log_date = '{}Date'.format(log_type)\n df = create_dataframe_from_log(log_path, log_sheet, log_type)\n df[log_date] = df[log_date].apply...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given a list of words, return list with duplicates removed.
def without_duplicates(words): # initialize empty list where non duplicate words will be stored non_duplicate_words = [] # iterate over list for item in words: # if an item in list is not already in list containing duplicate words.. if item != non_duplicate_words: # append i...
[ "def without_duplicates(words):\n\n # the long way: add each item to a set through iteration\n #\n # duplicate_remover = set([])\n # for word in words:\n # duplicate_remover.add(word)\n # words = list(duplicate_remover)\n # return words\n\n # the quick version: convert to set removes dup...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Translate phrase to pirate talk. Given a phrase, translate each word to the Piratespeak equivalent. Words that cannot be translated into Piratespeak should pass through unchanged. Return the resulting sentence.
def translate_to_pirate_talk(phrase): english_to_pirate = {"sir": "matey", "hotel": "fleabag inn", "student": "swabbie", "boy": "matey", "professor": "foul blaggart", "restaurant": "galley", "your": "yer", "excuse": "arr", "students": "swabbies", "are": "be", "restroom": "head", "my": "me", "is": "be", "man": "mate...
[ "def translate_to_pirate_talk(phrase):\n\n ## creates source dictionary for pirate translations\n pirate_dict = {\"sir\": \"matey\", \"hotel\": \"fleabag inn\", \"student\": \"swabbie\",\n \"man\": \"matey\", \"professor\": \"foul blaggart\",\n \"restaurant\": \"galley\", \...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given list of numbers, return list of pair summing to 0. Given a list of numbers, add up each individual pair of numbers. Return a list of each pair of numbers that adds up to 0.
def get_sum_zero_pairs(numbers): # use set to remove duplicates from list, and listize the set numbers = list(set(numbers)) # list where pairs that sum to zero will go sum_zero_pairs = [] # use enumerate to get item indexes for index, item in enumerate(numbers): # start second iterati...
[ "def get_sum_zero_pairs(numbers):\n numbers = set(numbers)\n numbers = list(numbers)\n pairs_that_add_to_zero = []\n\n for i, item in enumerate(numbers):\n if numbers[i] == len(numbers):\n break\n\n if numbers[i] == 0:\n pairs_that_add_to_zero.append([0, 0]) \n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Displays the explained variance score
def explained_variance_score(self): print('Explained variance score: ' + str(explained_variance_score(self.model.dataset.get_y_test(), self.model.get_predicted())))
[ "def explained_variance(returns, values):\n exp_var = 1 - torch.var(returns - values) / torch.var(returns)\n return exp_var.item()", "def variance_explained(data, k=1):\n _, _, eigenvalues = pca(data, '', k, False)\n return (sum(eigenvalues[:k]) / float(sum(eigenvalues)))", "def explained_va...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Displays the maximum residual error
def max_error(self): print('Maximum residual error: ' + str(max_error(self.model.dataset.get_y_test(), self.model.get_predicted())))
[ "def graph_residual_error(self) -> go.Figure:\n\n if len(self.corrections) == 0:\n raise RuntimeError(\"Please call compute_corrections or compute_from_files to calculate corrections first\")\n\n abs_errors = [abs(i) for i in self.diffs - np.dot(self.coeff_mat, self.corrections)]\n l...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Displays the mean absolute error regression loss
def mean_absolute_error(self): print('Mean absolute error regression loss: ' + str(mean_absolute_error(self.model.dataset.get_y_test(), self.model.get_predicted())))
[ "def mean_squared_error(self):\n print('Mean squared error regression loss: ' + str(mean_squared_error(self.model.dataset.get_y_test(),\n self.model.get_predicted())))", "def print_mean_loss(self):\n print(f'Moyenne {self.l...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Displays the mean squared error regression loss
def mean_squared_error(self): print('Mean squared error regression loss: ' + str(mean_squared_error(self.model.dataset.get_y_test(), self.model.get_predicted())))
[ "def mean_absolute_error(self):\n print('Mean absolute error regression loss: ' + str(mean_absolute_error(self.model.dataset.get_y_test(),\n self.model.get_predicted())))", "def print_mean_loss(self):\n print(f'Moyenne {s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Displays the median absolute error regression loss
def median_absolute_error(self): print('Median absolute error regression loss: ' + str(median_absolute_error(self.model.dataset.get_y_test(), self.model.get_predicted())))
[ "def median_absolute_error(y_true, y_pred, *, multioutput=..., sample_weight=...):\n ...", "def stderr(predicted, actual):\n return np.sqrt(mse(predicted, actual))", "def median_absolute_percentage_error(y_true, y_pred):\n return np.median(np.abs((y_true - y_pred) / y_true))", "def mean_absolute_erro...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Displays the R^2 (coefficient of determination) regression score function
def r2_score(self): print('R^2 (coefficient of determination) regression score function: ' + str(r2_score(self.model.dataset.get_y_test(), self.model.get_predicted())))
[ "def R2_ScoreFunction(y_data, y_model):\n\tcounter = np.sum((y_data-y_model)**2)\n\tdenominator = np.sum((y_data-np.mean(y_data))**2)\n\tR_2 = 1 - (counter/denominator)\n\n\treturn R_2", "def get_regressor_r2_score(self):\n return self.regressor_r2_score", "def get_regressor_r_score(self):\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Displays the mean Poisson deviance regression loss
def mean_poisson_deviance(self): print('Mean Poisson deviance regression loss: ' + str(mean_poisson_deviance(self.model.dataset.get_y_test(), self.model.get_predicted())))
[ "def mean_poisson_deviance(y_true, y_pred, *, sample_weight=...):\n ...", "def mean_gamma_deviance(self):\n print('Mean Gamma deviance regression loss: ' + str(mean_gamma_deviance(self.model.dataset.get_y_test(),\n self.model...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Displays the mean Gamma deviance regression loss
def mean_gamma_deviance(self): print('Mean Gamma deviance regression loss: ' + str(mean_gamma_deviance(self.model.dataset.get_y_test(), self.model.get_predicted())))
[ "def mean_gamma_deviance(y_true, y_pred, *, sample_weight=...):\n ...", "def mean_poisson_deviance(self):\n print('Mean Poisson deviance regression loss: ' + str(mean_poisson_deviance(self.model.dataset.get_y_test(),\n se...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function responsible for displaying the feature importance
def feature_importance(self): if self.model.algorithm == 'DecisionTree' or self.model.algorithm == 'RandomForest': print("Feature importance\n") print(pd.DataFrame(self.model.clf.feature_importances_, index=self.model.dataset.feature_names, columns=['Import...
[ "def feature_importance(self):\n raise NotImplementedError(\n \"Feature importance is not implemented for the Vowpal Wabbit classifiers.\"\n )", "def feature_importance(model, feature_names):\n features_list = []\n imp_list = []\n feat_imps = model.feature_importances_\n for j...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Exports the decision tree graph
def export(self): if self.model.algorithm == 'DecisionTree': dot_data = tree.export_graphviz(self.model.clf, out_file=None) graph = graphviz.Source(dot_data) graph.render("exports/DecisionTreeRegressor")
[ "def export_graphviz(decision_tree, out_file=SENTINEL, max_depth=None,\n feature_names=None, class_names=None, label='all',\n filled=False, leaves_parallel=False, \n node_ids=False, proportion=False, rotate=False,\n rounded=False, special_c...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Converts an array of IDs to a sentence, optionally cutting the result off at the endofsequence token.
def array_to_sentence(self, array: np.array, cut_at_eos=True) -> List[str]: sentence = [] for i in array: s = self.itos[i] if cut_at_eos and s == EOS_TOKEN: break sentence.append(s) return sentence
[ "def id_to_sentence(self, id):\n idxs = self._id_to_idxs(id)\n sentence = []\n for i in range(len(self.__sentence__)):\n part = self.__sentence__[i]\n values = self.__sentence_words__[part]\n sentence.append(str(values[idxs[i]]))\n return ' '.join(sentenc...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert multiple arrays containing sequences of token IDs to their sentences, optionally cutting them off at the endofsequence token.
def arrays_to_sentences(self, arrays: np.array, cut_at_eos=True) \ -> List[List[str]]: sentences = [] for array in arrays: sentences.append( self.array_to_sentence(array=array, cut_at_eos=cut_at_eos)) return sentences
[ "def array_to_sentence(self, array: np.array, cut_at_eos=True) -> List[str]:\n sentence = []\n for i in array:\n s = self.itos[i]\n if cut_at_eos and s == EOS_TOKEN:\n break\n sentence.append(s)\n return sentence", "def _ticks_to_sentences(ticks...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Filter counter by min frequency
def filter_min(counter: Counter, min_freq: int): return Counter({t: c for t, c in counter.items() if c >= min_freq})
[ "def min_filter(counts, filter_size):\n return minimum_filter(counts, size=(filter_size, 1),\n mode='reflect', origin=(filter_size - 1)//2)", "def filter_terms_by_cnt(self, min_count):\n filtered_terms = [term for term in self.term2id if self.term_frequent[term] >= min_c...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Cut counter to most frequent, sorted numerically and alphabetically
def sort_and_cut(counter: Counter, limit: int): # ignoring the alphabetical part, it's fine to do # [word_type for (word_type, count) in counter.most_common(limit)] tokens_and_frequencies = sorted(counter.items(), key=lambda tup: tup[0]) tokens_and_frequencies.sort(key=lambda tup: tup[1], reverse=True) ...
[ "def clip_word_frequence(num, counter):\r\n cut_index = None\r\n sorted_counter = counter.most_common()\r\n for idx, item in enumerate(sorted_counter):\r\n if item[1] < num:\r\n cut_index = idx\r\n break\r\n sorted_counter = counter.most_common(cut_index)\r\n return sorte...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Load the sample set and traces.
def load_sample(self): self.load_images(self.folder + "/sampleSet.txt") self.load_traces(self.folder + "/sampleLabel.txt")
[ "def load_samples(self, samples: List[Sample]): \n self._samples.update({s.id : s for s in samples})\n \n for s in tqdm(samples, total=len(samples)):\n self._sample_atoms.update({s.id: s.atoms})\n for i, c in enumerate(s.compounds):\n # get unique...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Prints the image at index idx.
def print_img_at_idx(self, idx): img = self.images[idx] print_img(img)
[ "def printImage(imageObject):\n # TODO\n pass", "def print_image(indiv,name):\n routine = gp.compile(indiv,pset)\n output = gen_beat_output(routine)\n bits = np.array(map(bitlist,output)[0:24000]).transpose()\n plt.style.use('classic')\n plt.imshow(bits,interpolation='nearest',aspect='auto',c...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create the chain of explode_images and explode_traces formed by counting across two timesteps.
def explode(self): words = ["one", "two", "three", "four", "five", "six", "seven", "eight", "nine"] for i, image in enumerate(self.images): for j, chain in enumerate(list(self.traces[i])): for k, link in enumerate(chain): if k is 0: ...
[ "def explode_chained(self):\n\n words = [\"one\", \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\", \"nine\"]\n\n for i, image in enumerate(self.images):\n for j, chain in enumerate(list(self.traces[i])):\n\n # initialize new lists to keep track of anothe...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create the chain of explode_images and explode_traces formed by counting across all timesteps.
def explode_chained(self): words = ["one", "two", "three", "four", "five", "six", "seven", "eight", "nine"] for i, image in enumerate(self.images): for j, chain in enumerate(list(self.traces[i])): # initialize new lists to keep track of another chain explod...
[ "def explode(self):\n\n words = [\"one\", \"two\", \"three\", \"four\", \"five\", \"six\", \"seven\", \"eight\", \"nine\"]\n\n for i, image in enumerate(self.images):\n for j, chain in enumerate(list(self.traces[i])):\n for k, link in enumerate(chain):\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the queryset of pages to be filtered by this page. By default this includes only live pages and pages that live in the same Wagtail Site as this page. If this page cannot be mapped to a Wagtail site (for example, if it does not live under a site root), then it will not return any filterable results. The filter_c...
def get_filterable_queryset(self): site = self.get_site() if not site: return self.get_model_class().objects.none() queryset = self.get_model_class().objects.in_site(site).live() filterable_list_block = self.get_filterable_list_wagtail_block() if filterable_list_bl...
[ "def filter_children(self, queryset, filter_dict):\n return queryset.filter(**filter_dict)", "def get_filtered_queryset(self):\n filter_fields_dict = self.get_filter_fields()\n\n if not filter_fields_dict:\n return self.get_queryset()\n\n return self.get_queryset().filter(**...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Do not index queries unless they consist of a single topic field.
def set_do_not_index(self, field, value): if field != 'topics' or len(value) > 1: self.do_not_index = True
[ "def search_first_topic(self, topic: str):\n all = self.r.subreddit(\"all\")\n for i in all.search(topic, limit=5):\n return i.over_18, i.url", "def test_token_fetch_empty_topic(self):\n self.client.credentials(HTTP_AUTHORIZATION='Token ' + self.free_token.key)\n response = ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the queryset of pages to be filtered by this page. The class property filterable_categories can be set to a list of page categories from the set in v1.util.ref.categories. If set, this page will only filter pages that are tagged with a tag in those categories. By default this is an empty list and all page tags a...
def get_filterable_queryset(self): queryset = super().get_filterable_queryset() category_names = get_category_children(self.filterable_categories) return queryset.filter(categories__name__in=category_names)
[ "def get_filterable_queryset(self):\n site = self.get_site()\n\n if not site:\n return self.get_model_class().objects.none()\n\n queryset = self.get_model_class().objects.in_site(site).live()\n\n filterable_list_block = self.get_filterable_list_wagtail_block()\n if filt...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
If the specified modules have never been imported, and import prevention is requested, L{ensureNotImported} makes sure they will not be imported in the future.
def test_ensureWhenNotImported(self): modules = {} self.patch(sys, "modules", modules) ensureNotImported(["m1", "m2"], "A message.", preventImports=["m1", "m2", "m3"]) self.assertEqual(modules, {"m1": None, "m2": None, "m3": None})
[ "def test_ensureWhenNotImportedDontPrevent(self):\n modules = {}\n self.patch(sys, \"modules\", modules)\n ensureNotImported([\"m1\", \"m2\"], \"A message.\")\n self.assertEqual(modules, {})", "def _CheckForRequiredImports(self, module):\n try:\n reqMods = module.requ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
If the specified modules have never been imported, and import prevention is not requested, L{ensureNotImported} has no effect.
def test_ensureWhenNotImportedDontPrevent(self): modules = {} self.patch(sys, "modules", modules) ensureNotImported(["m1", "m2"], "A message.") self.assertEqual(modules, {})
[ "def test_ensureWhenNotImported(self):\n modules = {}\n self.patch(sys, \"modules\", modules)\n ensureNotImported([\"m1\", \"m2\"], \"A message.\", preventImports=[\"m1\", \"m2\", \"m3\"])\n self.assertEqual(modules, {\"m1\": None, \"m2\": None, \"m3\": None})", "def test_modules(self)...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
C{simulate} can be called without raising any errors when there are no delayed calls for the reactor and hence there is no defined sleep period.
def test_simulate(self): sut = gireactor.PortableGIReactor(useGtk=False) # Double check that reactor has no sleep period. self.assertIs(None, sut.timeout()) sut.simulate()
[ "async def twisted_sleep(delay, twisted_reactor):\n deferred: Deferred[None] = Deferred()\n twisted_reactor.callLater(delay, deferred.callback, None)\n await deferred", "def _simulate(self, action=None):\n for k in range(int(self.SIMULATION_FREQUENCY // self.config[\"policy_frequency\"])):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Compute the multipie pose report, ploting the FNMR for each view point
def multipie_pose_report( scores_dev, scores_eval, output_filename, titles, figsize=(16, 8), fmr_threshold=1e-3, colors=plt.cm.tab10.colors, optimal_threshold=False, threshold_eval=False, ): cameras = [ "11_0", "12_0", "09_0", "08_0", "13_...
[ "def getFaceProj(self):\n\n var_dim = self.var_dim\n\n elements = self.elements \n Np = self.Np \n\n num_faces = self.num_faces\n\n l_R = self.l_L \n l_L = self.l_R \n\n f2e = self.f2e\n \n P_L = np.zeros( (var_d...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Welcomes the user with a message and randomly picks a question to ask the user about their number
def welcome(): on_session_start() return question(PRIME_QUESTION, intro=WELCOME_SPEECH)
[ "def random_question():\n min_number = 0\n max_number = 20\n return random.randint(min_number, max_number)", "async def ready_message(self, message):\n mention = message.author.mention\n options = [\n f\"¡Perfecto, {mention}!\",\n f\"No esperaba menos, {mention}.\",\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the unexpected response speech.
def unexpected_response(): return say(UNEXPECTED_ANSWER_SPEECH)
[ "def get_speech(self, json_response):\n return str(json_response['result']['fulfillment']['speech'])", "def incorrect_response(self):\n \n self.play_sound('wrong', self.standard_sfx, wait=True)\n self.update_points(False)\n #self.vibrate_buttons() # this is a little confusing wh...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the middle item in the number list (by position not value) picks lower middle index if number is even
def get_middle(): num_list = session_attributes[NUMBER_LIST_KEY] return num_list[round(len(num_list) / 2) - 1] # Subtract 1 since arrays start at 0
[ "def middle(L):\n\n n = len(L)\n new_list =(L[1:n-1])\n return new_list", "def find_index_or_nearest(iterable, item):\n beg = 0\n end = len(iterable) - 1\n while beg <= end:\n mid = beg + (end - beg) // 2\n if iterable[mid] == item:\n return mid\n elif iterable[mi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Rounds a number up if the decimal portion of the number is >= 0.5
def round(x): return int(x + copysign(0.5, x))
[ "def round_half_up(number):\n return number.quantize(decimal.Decimal(\"0.01\"), rounding=decimal.ROUND_HALF_UP)", "def int_round(number):\n if number > 0:\n return int(number + 0.5)\n else:\n return int(number - 0.5)", "def round_up(self, number):\n return math.ceil(number)", "de...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Keeps or remove each number in the number list that returns a true value for a given predicate function. Defaults to keeping the number
def keep_in_numbers(predicate): session_attributes[NUMBER_LIST_KEY] = [n for n in session_attributes[NUMBER_LIST_KEY] if predicate(n)]
[ "def remove(items: Iterable, predicate: Callable) -> List:\n return [x for x in items if not predicate(x)]", "def filter(pred, lst):\n \"*** YOUR CODE HERE ***\"\n i = len(lst)-1\n while i >= 0:\n if not pred(lst[i]):\n lst.pop(i)\n i -= 1", "def remove(predicate, coll):\r\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set model weights and bias value as candidates value
def set_weights_to_layers(self, candidate): last_idx = 0 # Iterate over every layer for layer_idx in range(0, self.num_layers, 1): if layer_idx %2 == 0 : # Get layer dimensions w_shape = self.layers[layer_idx].weight.shape w_n...
[ "def _set_weights(self, weights):\n i = iter(weights)\n\n for param in self.params:\n param.set_value(i.next())", "def set_best_parameters(self):\n self.b1 = self.best_parameters[0]\n self.b2 = self.best_parameters[1]\n self.w1 = self.best_parameters[2]\n self....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Parse out Package name from a repo git url
def package_name_from_url(url): url_repo_part = url.split('/')[-1] if url_repo_part.endswith('.git'): return url_repo_part[:-4] return url_repo_part
[ "def get_repository_name(url):\n li_temp_1 = url.rsplit('/', 1)\n return li_temp_1[1][:-4] if \\\n li_temp_1[1].endswith(\".git\") else li_temp_1[1]", "def get_reponame_from_git_url(url: str) -> Optional[str]:\n repo_url = parse_git_repo(url)\n if repo_url:\n return repo_url.repo\n re...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Extract coordinates of first path from the KMZ file.
def parse_kmz(filename: str) -> List[Tuple[float, float]]: kmz = ZipFile(filename, "r") kml = kmz.open("doc.kml", "r").read() tree = etree.parse(BytesIO(kml)) coordinates = tree.xpath( "/a:kml/a:Document/a:Placemark/a:LineString/a:coordinates", namespaces={"a": "http://www.opengis.net/...
[ "def get_kml_coordinates(kml_obj: fastkml.kml.KML) -> Path:\n\t\n\tgeometry_obj = next(get_kml_document(kml_obj).features()).geometry\n\tcoords_path = [\n\t\tCoordinates(*co_tuple)\n\t\tfor co_tuple in geometry_obj.coords\n\t]\n\t\n\treturn coords_path", "def get_coordinates_kml_file(file_path):\n root = get_k...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Parse a list of coordinates into a dictionary structure with distances.
def calculate_distances(coords: List[Tuple[float, float]]) -> List[Dict]: miles = 0 od = [] for idx in range(len(coords)): if idx == 0: continue dist = distance(coords[idx], coords[idx - 1]).miles miles = miles + dist od.append( { "star...
[ "def coords_to_dict(self, coords_list, translate=True):\n contact_points_list = []\n contact_points_dict = {\n 'urdf_file': self.urdf_file,\n 'contact_points': []}\n for coords in coords_list:\n if translate:\n coords = coords.copy_worldcoords().t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Output a list of dictionaries as JSON lines. This is intended as a simple helper function that takes any list of dictionaries and outputs it one record per line to a jsonl file. This file can be incrementally parsed by a web page, which is handy if you need to operate on records earlier in the file, don't think you'll ...
def output_jsonl(filename: str, data: List): with open(filename, "w") as outfile: for x in data: print(json.dumps(x)) json.dump(x, outfile) outfile.write("\n")
[ "def write_nljson(data, filename):\n with open(filename, 'w') as f:\n [f.write(json.dumps(d, default=json_serialize)+'\\n') for d in data]", "def write_jsonline(dest_filename, items, encoding=__ENCODING_UTF8):\n if isinstance(items, str):\n raise TypeError('json object list can\\'t be str')\n\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Mmain routine to convert KMZ to JSON lines output. This is a convenience function to run the entire script and convert the inputfile from a KMZ file to a JSON lines output file.
def main(infile: str, outfile: str): coords = parse_kmz(infile) distances = calculate_distances(coords) output_jsonl(outfile, distances)
[ "def json_to_kml():", "def OutputNmf(nmf_map, output_path):\n with open(output_path, 'w') as output:\n json.dump(nmf_map, output, indent=2)", "def keyholemarkup2x(file,output='df'):\n r = re.compile(r'(?<=\\.)km+[lz]?',re.I)\n try:\n extension = r.search(file).group(0) #(re.findall(r'(?<=\\.)[\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
An error should be raised when attempting to decorate a nonclass object.
def test_non_class_decorate_error(): with pytest.raises( TypeError, match="Only classes can be decorated with @component." ): @component def fn(): pass
[ "def test_usedAsClassDecorator(self):\r\n self.flakes('''\r\n from interior import decorate\r\n @decorate\r\n class foo:\r\n pass\r\n ''')\r\n\r\n self.flakes('''\r\n from interior import decorate\r\n @decorate(\"foo\")\r\n class bar:\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
An error should be raised when attempting to decorate an abstract class.
def test_abstract_class_decorate_error(): with pytest.raises( TypeError, match="Abstract classes cannot be decorated with @component." ): @component class A(abc.ABC): @abc.abstractmethod def foo(self): pass
[ "def abstract_class_guard(self) -> None:\n pass", "def abstract(f):\r\n\tdef raiser(*args,**kargs):\r\n\t\traise Exception('Abstract function must be overridden by a child class before being called')\r\n\treturn raiser", "def test_component_is_abstract():\n\n class AbstractComponent(Component):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
An error should be raised when attempting to decorate a class with an `__init__` method.
def test_init_decorate_error(): with pytest.raises( TypeError, match="Component classes must not define a custom `__init__` method.", ): @component class A: def __init__(self, a, b=5): self.a = a self.b = b
[ "def raise_init(cls):\r\n def init(self):\r\n raise TypeError(\"Instance creation is not allowed for %s\" % cls)\r\n cls.__init__ = init\r\n return cls", "def froze_init(cls):\n\n def __setattr__(self, key, value):\n if key[0] != \"_\":\n if self.__frozen:\n if ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
When not configuring interactively, an error should be raised if a field has neither a default nor a configured value.
def test_configure_non_interactive_missing_field_value(ExampleComponentClass): with pytest.raises( ValueError, match=r"^No configuration value found for annotated field 'FAKE_NAME.a' of type 'int'.", ): configure(ExampleComponentClass(), {"b": "bar"}, name="FAKE_NAME")
[ "def _field_sanity(self, field):\r\n if isinstance(field, models.BooleanField) and field.has_default():\r\n field.default = int(field.to_python(field.get_default()))\r\n return field", "def test_defaultvalue_value(dummy_form):\n field = DummyField(20)\n assert validators.DefaultValu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
When configuring interactively, subcomponent fields without default or configured values should prompt for a choice of subcomponents to instantiate through the CLI.
def test_configure_interactive_prompt_for_subcomponent_choice(): class AbstractChild: pass @component class Child1(AbstractChild): pass @component class Child2(AbstractChild): pass class Child3_Abstract(AbstractChild): pass @component class Child3A(Ch...
[ "def __init__(self):\n Commande.__init__(self, \"prompt\", \"prompt\")\n self.schema = \"\"\n self.aide_courte = \"affiche ou configure votre prompt\"\n self.aide_longue = AIDE", "def test__ApplicationCommandOptionMetadataSubCommand__new__1():\n options = [\n ApplicationComma...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Bytes received over wired connection.
def wired_rx_bytes(self): return self.raw.get('wired-rx_bytes', 0)
[ "def receive_bytes(self):\n pass", "def bytes_received_on_connection(self):\r\n return self._connection.bytes_received", "def recv_bytes(self):\r\n try:\r\n received = self.socket.recv(4096)\r\n # printf(\"Bytes received: %d\" % (len(received)))\r\n self.rec...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Bytes transferred over wired connection.
def wired_tx_bytes(self): return self.raw.get('wired-tx_bytes', 0)
[ "def BytesTransferred(self) -> int:", "def bytes_transferred(self):\n return self._bytes_transferred", "def bytes_copied(self) -> float:\n return pulumi.get(self, \"bytes_copied\")", "def wired_rx_bytes(self):\n return self.raw.get('wired-rx_bytes', 0)", "def print_transferred_data(self...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Find squared contours with min area
def find_squares(img,minArea=1000): squares = [] contours, hierarchy = cv2.findContours(img, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE) for cnt in contours: cnt_len = cv2.arcLength(cnt, True) cnt = cv2.approxPolyDP(cnt, 0.02*cnt_len, True) if len(cnt) == 4 and cv2.contourArea(cnt) > 1000 and cv2.isCon...
[ "def find_contour(ctx: Context):\n cv2.copyTo(ctx.filter_image, np.ones_like(ctx.temp_image1), ctx.temp_image1)\n contours, _ = cv2.findContours(ctx.temp_image1, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\n\n # take the 5 biggest areas\n contours = sorted(contours, key=lambda c: math.fabs(cv2.contourAr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a mask with the label on the center
def mask_center_label ( gray ) : assert gray is not None # s = ndimage.generate_binary_structure(2,2) # iterate structure label_im, nb_labels = label(gray) # get center label h = label_im.shape[0] w = label_im.shape[1] l = label_im [h//2,w//2] gray [ label_im == l ] = 255 gray [ label_im != l ] ...
[ "def test(shape=(1000,2000)):\n mask = Mask()\n mask.addCircle(400,300,250)\n mask.subtractCircle(400,300,150)\n mask.addRectangle(350,250,1500,700)\n plt.imshow( mask.getMask(shape) )\n return mask", "def create_full_mask(org_w, org_h, annotations):\n label = np.zeros([org_h, org_w, C], dtype=np.uint8)\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Find keypoints return keypoints,oob,oob_corners
def find_keypoints ( gray , quality , ksize , blocksize , max_area = None ) : gray32 = np.float32(gray) points = cv2.goodFeaturesToTrack(gray32,maxCorners = 100, qualityLevel = quality ,minDistance = ksize , blockSize = blocksize ) if points is None : return None , None , None if len(points) < 4 : ret...
[ "def detect_keypoints(self):\n\n # Create an ORB detector to extract the keypoints\n orb = ORB_create(nfeatures=self.nfeatures)\n\n # Find the keypoints and descriptors using ORB\n keypoints1, descriptors1 = orb.detectAndCompute(self.images[0], None)\n keypoints2, descriptors2 = o...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Report a game user (publicReportUser) This API is used to report a game user.
def public_report_user( user_id: str, body: Optional[UserReportRequest] = None, namespace: Optional[str] = None, x_additional_headers: Optional[Dict[str, str]] = None, **kwargs ): if namespace is None: namespace, error = get_services_namespace() if error: return None,...
[ "def report_public(self, reportid):\r\n return reports.ReportsPublic(self, reportid)", "def user_report(self, args):\n user_email = args.user_email\n show_events = args.show_events\n user = self.find_user_by_email(user_email)\n user.display(show_events)", "def profile_report(s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Unban user (unBanUsers) Unban user.
def un_ban_users( body: Optional[ADTOForUnbanUserAPICall] = None, namespace: Optional[str] = None, x_additional_headers: Optional[Dict[str, str]] = None, **kwargs ): if namespace is None: namespace, error = get_services_namespace() if error: return None, error request...
[ "def unBanUsers(self, enforcer):\n enforcer.getService('writeFlexOptFile').execute()\n for user in self.bannedUsers:\n enforcer.getService('resetUserUsage').execute(user, self.when)\n enforcer.getService('notifyEvent').execute(copy.copy(self.bannedUsers), UserEvent.UNBAN)\n se...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Allow items to be randomly assigned to a specific door
def door_assignment(): doors = ['door-money.png', 'door-goat.png', 'door-trash.png'] GameScreen.door1_reveal = random.choice(doors) doors.remove(GameScreen.door1_reveal) GameScreen.door2_reveal = random.choice(doors) doors.remove(GameScreen.door2_reveal) GameScreen.door3...
[ "def pick_random_door():\n\n return random.randint(0, door_count - 1)", "def put_item_random(self, x, y):\n r = int(random() * 10)\n if 3 < r and r <= 6:\n self.put_fireitem(x, y)\n elif 6 < r and r <= 9:\n self.put_bombitem(x, y)", "def randomitem(self):\n r...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Exit game to main menu, reset doors and its counter, reenable buttons, and set score back to 0 (frontend and backend)
def exit_game(self): for i in range(1, 4, 1): self.ids['door' + str(i)].source = \ 'door_closed.jpg' self.ids['button' + str(i)].disabled = False setattr(self, 'door'+str(i)+'_counter', 0) self.manager.current = 'MainMenu' self.ids['score'].tex...
[ "def restart_game(self):\n for i in range(1, 4, 1):\n self.ids['door' + str(i)].source = \\\n 'door_closed.jpg'\n self.ids['button' + str(i)].disabled = False\n setattr(self, 'door'+str(i)+'_counter', 0)\n self.ids['score'].text = 'SCORE: 0'\n sel...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Have game continue to next round, reset doors and its counter, reenable buttons, return to gamescreen, and initate random door selection for new game round
def next_round(self): for i in range(1, 4, 1): self.ids['door' + str(i)].source = \ 'door_closed.jpg' self.ids['button' + str(i)].disabled = False setattr(self, 'door'+str(i)+'_counter', 0) self.win() self.manager.current = 'GameScreen' ...
[ "def restart_game(self):\n for i in range(1, 4, 1):\n self.ids['door' + str(i)].source = \\\n 'door_closed.jpg'\n self.ids['button' + str(i)].disabled = False\n setattr(self, 'door'+str(i)+'_counter', 0)\n self.ids['score'].text = 'SCORE: 0'\n sel...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Have user restart game, reset doors and its counter, reenable buttons, return to gamescreen, and initate random door selection for new game
def restart_game(self): for i in range(1, 4, 1): self.ids['door' + str(i)].source = \ 'door_closed.jpg' self.ids['button' + str(i)].disabled = False setattr(self, 'door'+str(i)+'_counter', 0) self.ids['score'].text = 'SCORE: 0' self.score = 0 ...
[ "def exit_game(self):\n for i in range(1, 4, 1):\n self.ids['door' + str(i)].source = \\\n 'door_closed.jpg'\n self.ids['button' + str(i)].disabled = False\n setattr(self, 'door'+str(i)+'_counter', 0)\n self.manager.current = 'MainMenu'\n self.ids...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function called on to initiate a winner popup when user wins round and contain two buttons that allows user to continue to next round or exit game to main menu
def win_popup(self): content = BoxLayout(orientation='vertical') message_label = Label(text=self.win_message) button_layer = BoxLayout(orientation='horizontal') dismiss_button = Button(text='QUIT', size_hint=(1, 1)) next_button = Button(id='next', text='NEXT ROUND', size_hint=(1,...
[ "def winner():\n winning_lbl_zero.grid(row=0, column=LEFT_COL, rowspan=80, columnspan=2, sticky=N) # Placing the winning image\n messagebox.showinfo(title=\"**** WINNER! ****\", message=\"CONGRATS!!\\n\"\n \"You figured out the word/phrase\\n\"\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function called on to initiate a loss popup when user loses round and contain two buttons that allows user to continue to try again or to exit game to main menu
def lose_popup(self): content = BoxLayout(orientation='vertical') message_label = Label(text=self.loss_message) button_layer = BoxLayout(orientation='horizontal') dismiss_button = Button(text='QUIT', size_hint=(1, 1)) next_button = Button(id='try_again', text='TRY AGAIN', size_hi...
[ "def leave(self):\n p = GameOverPopup(self)\n p.open()", "def game_lose(self):\n self.lose = True\n self.player.reset_animations()\n self.player.reset_actions()\n self.msg.set_text(u'YOU LOSE <Press Space>')\n self.msg.show(True)", "def game_is_lost(self):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Checks the memcheck suppressions files for bad data.
def CheckChange(input_api, output_api): # Add the path to the Chrome valgrind dir to the import path: tools_vg_path = os.path.join(input_api.PresubmitLocalPath(), '..', '..', 'valgrind') sys.path.append(tools_vg_path) import suppressions sup_regex = re.compile('suppressions.*\...
[ "def flush_suppression_list():\n consolidated_data.flush_suppress_list()", "def checkBadInstrumentationMsg(self,file_obj):\n\t\tprint file_obj\n\t\terr=[]\n\t\tfor elem in self.grep('BadInstrumentation', file_obj,True):\n\t\t\terr.append(repr(elem))\n\t\t\tprint elem\n\t\tif ( len(err) > 0 ):\n\t\t\tce=CalErro...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Update aircraft's info with new_attrs from a message
def update(self, new_attrs): self.last_update = round(time()) self.attrs.update(new_attrs)
[ "def update_anime_info(name, new):\n db = opendb()\n anime = tinydb.Query()\n info = db.get(anime.name == name)\n try:\n print('\\nUpdating {}:'.format(name))\n except UnicodeEncodeError:\n print('\\nUpdating {}:'.format(name.encode('gbk', 'ignore')))\n print('Unicode Encode Erro...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test locking the vehicle.
async def test_locking(hass: HomeAssistant) -> None: client_mock = await init_integration(hass) await hass.services.async_call( LOCK_DOMAIN, SERVICE_LOCK, {ATTR_ENTITY_ID: "lock.my_mazda3_lock"}, blocking=True, ) await hass.async_block_till_done() client_mock.lock_d...
[ "def test_locking(self):\r\n def verify_asset_locked_state(locked):\r\n \"\"\" Helper method to verify lock state in the contentstore \"\"\"\r\n asset_location = StaticContent.get_location_from_path('/c4x/edX/toy/asset/sample_static.txt')\r\n content = contentstore().find(ass...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test unlocking the vehicle.
async def test_unlocking(hass: HomeAssistant) -> None: client_mock = await init_integration(hass) await hass.services.async_call( LOCK_DOMAIN, SERVICE_UNLOCK, {ATTR_ENTITY_ID: "lock.my_mazda3_lock"}, blocking=True, ) await hass.async_block_till_done() client_mock.un...
[ "def test_server_lock_unlock(self):\n self.wait_for_status(\"ACTIVE\")\n # lock\n raw_output = self.openstack('server lock ' + self.NAME)\n self.assertEqual(\"\", raw_output)\n # unlock\n raw_output = self.openstack('server unlock ' + self.NAME)\n self.assertEqual(\"...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Transforms a list of documents into a bag of words matrix suitable for the LDA model.
def docs2matrix(docs): # [token for doc in docs for token in doc] term_dictionary = corpora.Dictionary(docs) doc_matrix = [term_dictionary.doc2bow(doc) for doc in docs] logging.info("Len of raw corpus: %d | Len of matrix: %d" % (len(docs), len(doc_matrix))) return doc_matrix, term_dictionary
[ "def bag_of_words_category(docs_x):\n train_x = [] # Initialize input list\n train_y = [] # Initialize output list\n \n # Create output list\n for i, doc in enumerate(docs_x):\n train_x.extend(doc) # Extend main x list with all queries on a category\n train_y.extend([i] * len(doc)) ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Cleans document of stopwords and punctuation. Stopwords are specified at initialization of Processing. Lemmatizes for all languages except Chinese.
def cleaning(self, document): remove_punct = ''.join(i for i in document.lower() if i not in self.punctuation) tokenized = [i for i in remove_punct.split() if i not in self.stopwords] if self.lang is not 'chinese': # Lemmatizes if not chinese tokenized = [self.lemmatize.l...
[ "def clean_text(text):\n\n lemmizer = WordNetLemmatizer()\n stemmer = porter.PorterStemmer()\n\n stop = stopwords.words('english')\n stop += ['.', ',', ':', '...', '!\"', '?\"', \"'\", '\"', ' - ', ' — ', ',\"', '.\"', '!', ';', '♫♫', '♫', \\\n '.\\'\"', '[', ']', '—', \".\\'\", 'ok', 'okay'...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Cleans all documents in a list
def clean_docs(self, docs): cleaned = [self.cleaning(doc) for doc in docs] print(cleaned[0]) return cleaned
[ "def clean_docs(self, length):\n for doc in self.docs:\n doc.token_clean(length)\n doc.stopword_remove(self.stopwords)\n doc.stem()", "def clean(self):\n terms = list(self)\n\n for t in terms:\n self.doc.remove_term(t)", "def clean(corpus):\n #...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return all tokens retrieved from raw sql text.
def get_tokens(self, sql_text): parsed = sqlparse.parse(sql_text)[0] return parsed.tokens
[ "def _find_tokens(self) -> ty.List[str]:\n return self.chunk.tokenize()", "def sql_tokenizer(sql, standard_quoting = False, ignore_whitespace = False,\r\n fqident = False, show_location = False):\r\n global _std_sql_rc, _ext_sql_rc, _std_sql_fq_rc, _ext_sql_fq_rc\r\n if not _std_sql_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get an existing ResolverRule resource's state with the given name, id, and optional extra properties used to qualify the lookup.
def get(resource_name: str, id: pulumi.Input[str], opts: Optional[pulumi.ResourceOptions] = None) -> 'ResolverRule': opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id)) __props__ = ResolverRuleArgs.__new__(ResolverRuleArgs) __props__.__dict__["arn"]...
[ "def get(resource_name: str,\n id: pulumi.Input[str],\n opts: Optional[pulumi.ResourceOptions] = None) -> 'Rule':\n opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id))\n\n __props__ = RuleInitArgs.__new__(RuleInitArgs)\n\n __props__.__dict__[\"applicat...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a hashable object that represents the identity of the item. By default this returns the position of the item in the tree. You may want to override this to return the item label (if you know that labels are unique and don't change), or return something that represents the underlying domain object, e.g. a database...
def GetItemIdentity(self, item): return self.GetIndexOfItem(item)
[ "def item_hash(self):\n return self._item_hash", "def get_key(self, item):\r\n return item[0]", "def item_to_index(self, item_id):\n if item_id in self.item_dict:\n return self.item_dict[item_id]\n else:\n return -1", "def item_id(self):\n return self._...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the expansion state of a tree item.
def GetExpansionStateOfItem(self, item): listOfExpandedItems = [] if self._window.IsExpanded(item): listOfExpandedItems.append(self.GetItemIdentity(item)) listOfExpandedItems.extend(self.GetExpansionStateOfChildren(item)) return listOfExpandedItems
[ "def GetExpansionStateOfChildren(self, item):\n \n listOfExpandedItems = []\n for child in self.GetItemChildren(item):\n listOfExpandedItems.extend(self.GetExpansionStateOfItem(child))\n\n return listOfExpandedItems", "def IsExpanded(self, item):\r\n\r\n return item.I...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the expansion state of the children of a tree item.
def GetExpansionStateOfChildren(self, item): listOfExpandedItems = [] for child in self.GetItemChildren(item): listOfExpandedItems.extend(self.GetExpansionStateOfItem(child)) return listOfExpandedItems
[ "def GetExpansionStateOfItem(self, item):\n \n listOfExpandedItems = []\n if self._window.IsExpanded(item):\n listOfExpandedItems.append(self.GetItemIdentity(item))\n listOfExpandedItems.extend(self.GetExpansionStateOfChildren(item))\n \n return listOfExp...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the checked/unchecked state of a tree item.
def GetCheckedStateOfItem(self, item): listOfCheckedItems = [] if self._window.IsItemChecked(item): listOfCheckedItems.append(self.GetItemIdentity(item)) listOfCheckedItems.extend(self.GetCheckedStateOfChildren(item)) return listOfCheckedIte...
[ "def getCheckedState(self):\r\n if self.isChecked():\r\n return Qt.Checked\r\n else:\r\n return Qt.Unchecked", "def checkitem_states(self):\r\n return CheckItemStates(self)", "def IsItemChecked(self, item):\r\n\r\n return item.IsChecked()", "def GetCheckedStat...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the checked/unchecked state of the children of a tree item.
def GetCheckedStateOfChildren(self, item): listOfCheckedItems = [] for child in self.GetItemChildren(item): listOfCheckedItems.extend(self.GetCheckedStateOfItem(child)) return listOfCheckedItems
[ "def GetCheckedStateOfItem(self, item):\n \n listOfCheckedItems = []\n if self._window.IsItemChecked(item):\n listOfCheckedItems.append(self.GetItemIdentity(item))\n \n listOfCheckedItems.extend(self.GetCheckedStateOfChildren(item))\n \n return lis...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the selection state of a tree item.
def GetSelectionStateOfItem(self, item): listOfSelectedItems = [] if self._window.IsSelected(item): listOfSelectedItems.append(self.GetItemIdentity(item)) listOfSelectedItems.extend(self.GetSelectionStateOfChildren(item)) return listOfSelectedItems
[ "def select_item(self):\n return self.tk.call(self._w, 'select', 'item') or None", "def GetSelectionStateOfChildren(self, item):\n \n listOfSelectedItems = []\n for child in self.GetItemChildren(item):\n listOfSelectedItems.extend(self.GetSelectionStateOfItem(child))\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the selection state of the children of a tree item.
def GetSelectionStateOfChildren(self, item): listOfSelectedItems = [] for child in self.GetItemChildren(item): listOfSelectedItems.extend(self.GetSelectionStateOfItem(child)) return listOfSelectedItems
[ "def GetSelectionStateOfItem(self, item):\n \n listOfSelectedItems = []\n if self._window.IsSelected(item):\n listOfSelectedItems.append(self.GetItemIdentity(item))\n \n listOfSelectedItems.extend(self.GetSelectionStateOfChildren(item))\n return listOfSelecte...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the expansion state of a tree item (expanded or collapsed).
def SetExpansionStateOfItem(self, listOfExpandedItems, item): if self.GetItemIdentity(item) in listOfExpandedItems: self._window.Expand(item) self.SetExpansionStateOfChildren(listOfExpandedItems, item) else: self._window.Collapse(item)
[ "def set_expanded(self, state=None):\n if self.mainUi.graphZone.currentGraphMode == 'tree':\n if state is None:\n state = not self.isExpanded\n else:\n self.pbExpand.setChecked(state)\n self.log.detail(\">>> Set expand state: %s ---> %s\" % (self...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the expansion state of the children of a tree item (expanded or collapsed).
def SetExpansionStateOfChildren(self, listOfExpandedItems, item): for child in self.GetItemChildren(item): self.SetExpansionStateOfItem(listOfExpandedItems, child)
[ "def set_expanded(self, state=None):\n if self.mainUi.graphZone.currentGraphMode == 'tree':\n if state is None:\n state = not self.isExpanded\n else:\n self.pbExpand.setChecked(state)\n self.log.detail(\">>> Set expand state: %s ---> %s\" % (self...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the checked/unchecked state of a tree item.
def SetCheckedStateOfItem(self, listOfCheckedItems, item): if self.GetItemIdentity(item) in listOfCheckedItems: self._window.CheckItem2(item, True) else: self._window.CheckItem2(item, False) self.SetCheckedStateOfChildren(listOfCheckedItems, item)
[ "def set_items_status(self, checked):\n for i in range(self.tree.topLevelItemCount()):\n item = self.tree.topLevelItem(i)\n if checked:\n item.setCheckState(0, QtCore.Qt.Checked)\n else:\n item.setCheckState(0, QtCore.Qt.Unchecked)", "def SetCh...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the checked/unchecked state of the children of a tree item.
def SetCheckedStateOfChildren(self, listOfCheckedItems, item): for child in self.GetItemChildren(item): self.SetCheckedStateOfItem(listOfCheckedItems, child)
[ "def _check_children(item, checked):\n\n for child in _children([item]):\n _set_checked(child, checked)", "def set_items_status(self, checked):\n for i in range(self.tree.topLevelItemCount()):\n item = self.tree.topLevelItem(i)\n if checked:\n item.setCheckSta...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the selection state of a tree item.
def SetSelectedStateOfItem(self, listOfSelectedItems, item): if self.GetItemIdentity(item) in listOfSelectedItems: if self._isTreeList: self._window.SelectItem(item, unselect_others=False) else: self._window.SelectItem(item) self.SetSelectedState...
[ "def setSelectedFromItem(self, item):\n row = self.model.indexFromItem(item).row()\n self.selectRow(row)", "def SetSelected( self, node ):\n self.selected_node = node\n index = self.NodeToIndex( node )\n if index != -1:\n self.Focus( index )\n self.Select( ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the selection state of the children of a tree item.
def SetSelectedStateOfChildren(self, listOfSelectedItems, item): for child in self.GetItemChildren(item): self.SetSelectedStateOfItem(listOfSelectedItems, child)
[ "def set_children(self, item, *newchildren):\n self._visual_drag.set_children(item, *newchildren)\n ttk.Treeview.set_children(self, item, *newchildren)", "def SelectAllChildren(self, item):\r\n\r\n if not self.HasAGWFlag(TR_MULTIPLE) and not self.HasAGWFlag(TR_EXTENDED):\r\n raise ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Finds a suitable handler for the input `Persistent Object` depending on the widget kind.
def FindHandler(pObject): window = pObject.GetWindow() klass = window.__class__ if hasattr(window, "_persistentHandler"): # if control has a handler, just return it return window._persistentHandler for handler, subclasses in STANDALONE_HANDLERS: for subclass in subclasses:...
[ "def match(self, obj):\n for possible_handlers in self._handlers.values():\n for h in possible_handlers:\n if isinstance(obj, h.handles):\n return h\n return None", "def RichTextBuffer_FindHandlerByType(*args, **kwargs):\n return _richtext.RichTextBuffer...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Find an MBean using the provided template. Returns the first matching MBean, or 'None' if no matches are found.
def getFirstMatchingMBean(domain='WebSphere', **attributes): template = '%s:*' % domain for (k, v) in attributes.items(): template += ',%s=%s' % (k, v) result = AdminControl.completeObjectName(template) if result: return MBean(result) else: return None
[ "def getMBean(domain='WebSphere', **attributes):\n queryString = '%s:*' % domain\n for (k, v) in attributes.items():\n queryString += ',%s=%s' % (k, v)\n result = AdminControl.queryNames(queryString).splitlines()\n if len(result) == 1:\n return MBean(result[0])\n elif len(result) == 0:\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Queries given the query criteria, retrieves an array of matching MBeans.
def queryMBeans(domain='WebSphere', **attributes): queryString = '%s:*' % domain for (k, v) in attributes.items(): queryString += ',%s=%s' % (k, v) result = [] for name in AdminControl.queryNames(queryString).splitlines(): if name.strip() != '': result.append(MBean(name)) ...
[ "def query(self, collection, query = {}):\n Database.replaceObjectID(query) # Update all _id keys for use with Mongo\n try:\n return list(self.db[collection].find(query)) # Find using Mongo and convert to list\n except TypeError: # Ensure successful find\n raise Query...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Queries given the query criteria, retrieves single instance of MBean
def getMBean(domain='WebSphere', **attributes): queryString = '%s:*' % domain for (k, v) in attributes.items(): queryString += ',%s=%s' % (k, v) result = AdminControl.queryNames(queryString).splitlines() if len(result) == 1: return MBean(result[0]) elif len(result) == 0: retu...
[ "def getMBean1(domain='WebSphere', **attributes):\n queryString = '%s:*' % domain\n for (k, v) in attributes.items():\n queryString += ',%s=%s' % (k, v)\n result = AdminControl.queryNames(queryString).splitlines()\n if len(result) == 1:\n return MBean(result[0])\n elif len(result) == 0:...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Queries given the query criteria, retrieves single instance of MBean
def getMBean1(domain='WebSphere', **attributes): queryString = '%s:*' % domain for (k, v) in attributes.items(): queryString += ',%s=%s' % (k, v) result = AdminControl.queryNames(queryString).splitlines() if len(result) == 1: return MBean(result[0]) elif len(result) == 0: rai...
[ "def getMBean(domain='WebSphere', **attributes):\n queryString = '%s:*' % domain\n for (k, v) in attributes.items():\n queryString += ',%s=%s' % (k, v)\n result = AdminControl.queryNames(queryString).splitlines()\n if len(result) == 1:\n return MBean(result[0])\n elif len(result) == 0:\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Queries given the query criteria, retrieves an array of matching JMXMBeans.
def queryJMXMBeans(domain='WebSphere', **attributes): queryString = '%s:*' % domain for (k, v) in attributes.items(): queryString += ',%s=%s' % (k, v) result = [] for name in AdminControl.queryNames(queryString).splitlines(): if name.strip() != '': result.append(JMXMBean(name...
[ "def queryMBeans(domain='WebSphere', **attributes):\n queryString = '%s:*' % domain\n for (k, v) in attributes.items():\n queryString += ',%s=%s' % (k, v)\n result = []\n for name in AdminControl.queryNames(queryString).splitlines():\n if name.strip() != '':\n result.append(MBea...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Queries given the query criteria, retrieves single instance of JMXMBean
def getJMXMBean(domain='WebSphere', **attributes): queryString = '%s:*' % domain for (k, v) in attributes.items(): queryString += ',%s=%s' % (k, v) result = AdminControl.queryNames(queryString).splitlines() if len(result) == 1: return JMXMBean(result[0]) elif len(result) == 0: ...
[ "def getJMXMBean1(domain='WebSphere', **attributes):\n queryString = '%s:*' % domain\n for (k, v) in attributes.items():\n queryString += ',%s=%s' % (k, v)\n result = AdminControl.queryNames(queryString).splitlines()\n if len(result) == 1:\n return JMXMBean(result[0])\n elif len(result)...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }