query stringlengths 9 9.05k | document stringlengths 10 222k | negatives listlengths 19 20 | metadata dict |
|---|---|---|---|
Checks that the ChemicalSystem's ProteinComponent are suitable for the alchemical protocol. | def validate_protein(state: ChemicalSystem):
nprot = sum(1 for comp in state.values()
if isinstance(comp, ProteinComponent))
if nprot > 1:
errmsg = "Multiple ProteinComponent found, only one is supported"
raise ValueError(errmsg) | [
"def check_proportions(self):\r\n\r\n proportions = [\r\n v['proportion'] for k, v in self.composition.items()\r\n ]\r\n\r\n if sum(proportions) < 1.0:\r\n raise ValueError('Sum of proportions between host and pathogen must be 1.0.')\r\n elif sum(proportions) > 1.0:... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Display the prefix(es) that the bot uses | async def prefix(self, ctx):
prefixes = await self.bot.get_prefix(ctx.message)
formatted = self._format_prefixes(prefixes)
await ctx.send(f"You can mention me or use any of the following "
f"prefixes like so: {formatted}") | [
"async def prefix(self,ctx):\r\n\t\ttry:\r\n\t\t\tprefixes = self.bot.config[f\"{ctx.guild.id}\"][\"prefix\"]\r\n\t\texcept KeyError:\r\n\t\t\tself.bot.config[f\"{ctx.guild.id}\"][\"prefix\"] = ['$','!','`','.','-','?']\r\n\t\t\tawait self._save()\r\n\t\t\tprefixes = self.bot.config[f\"{ctx.guild.id}\"][\"prefix\"]... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Plot a graph between accuracy and support threshold. Plot a line graph between accuracy of the association rule mining based classifier and support threshold. | def accuracy_vs_support(confidence_threshold : float, coverage_threshold : int, top_k_rules : int):
print("\nPlotting accuracy vs support_threshold\n")
print("top_k_rules is {}".format(top_k_rules))
print("Confidence Threshold is {}".format(confidence_threshold))
print("Coverage Threshold is {}\n".forma... | [
"def plot_accuracy(self):\n plot_title, img_title = self.prep_titles(\"\")\n test_legend = ['training data', 'test data']\n\n # Data for plotting x- and y-axis\n x = np.arange(1, CFG.EPOCHS + 1)\n y = [self.tr_accuracy, self.test_accuracy]\n\n # prints x and y-axis values\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Plot a graph between time taken to extract rules and support threshold. Plot a line graph between time taken to extract rules by the association rule mining based classifier and support threshold. | def timetaken_vs_support(confidence_threshold, coverage_threshold, top_k_rules):
print("\nPlotting time taken to extract rules vs support_threshold\n")
print("top_k_rules is {}".format(top_k_rules))
print("Confidence Threshold is {}".format(confidence_threshold))
print("Coverage Threshold is {}\n".forma... | [
"def plot_thresholds(args, axis, x_thr=None, y_thr=None):\n if x_thr is None:\n x_thr = [args.inspect_times[0], args.inspect_times[-1]]\n if y_thr is None:\n y_thr = args.p_threshold * 100\n\n axis.axhline(y_thr, linestyle=\"--\", linewidth=1, color=\"grey\", zorder=-1)\n for _time in x_th... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Plot a graph between accuracy achieved at each iteration of GA optimization. Plot a line graph between accuracy of the association rule mining based classifier and iteration count of GA on the parameters support_threshold and confidence_threshold. | def accuracy_vs_ga_iteration(coverage_threshold, top_k_rules):
print("\nPlotting accuracy vs ga_iteration_count\n")
print("top_k_rules is {}".format(top_k_rules))
print("Coverage Threshold is {}\n".format(coverage_threshold))
gen, avg, mini, maxi = ga_optimize.main()
plt.plot(gen, avg, 'g',label='... | [
"def accuracy_vs_pso_iteration(coverage_threshold, top_k_rules):\n print(\"\\nPlotting accuracy vs pso_iteration_count\\n\")\n print(\"top_k_rules is {}\".format(top_k_rules))\n print(\"Coverage Threshold is {}\\n\".format(coverage_threshold))\n\n gen, avg, mini, maxi = pso_optimize.main()\n\n plt.pl... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Plot a graph between accuracy achieved at each iteration of PSO optimization. Plot a line graph between accuracy of the association rule mining based classifier and iteration count of PSO on the parameters support_threshold and confidence_threshold. | def accuracy_vs_pso_iteration(coverage_threshold, top_k_rules):
print("\nPlotting accuracy vs pso_iteration_count\n")
print("top_k_rules is {}".format(top_k_rules))
print("Coverage Threshold is {}\n".format(coverage_threshold))
gen, avg, mini, maxi = pso_optimize.main()
plt.plot(gen, avg, 'g', lab... | [
"def plot_accuracy(self):\n plot_title, img_title = self.prep_titles(\"\")\n test_legend = ['training data', 'test data']\n\n # Data for plotting x- and y-axis\n x = np.arange(1, CFG.EPOCHS + 1)\n y = [self.tr_accuracy, self.test_accuracy]\n\n # prints x and y-axis values\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Plot a graph between ChiSquare statistics and features. Plot 2 bar graphs side by side of ChiSquare stats of the feature and critical value for comparison. log is used to appropriately scaling for better visualization. | def chi2_stats_vs_feature():
print("\nPlotting chi square statistics vs Features\n")
features, chi2_critical, chi2_stats = chi2_feature_select.get_chi2_stats(verbose = True)
width = 0.8
chi2_critical = list(map(math.log, chi2_critical))
chi2_stats = list(map(math.log, chi2_stats))
x = lis... | [
"def plot_comparisons(gridsearch_model_df):\n perf_df_t = gridsearch_model_df.drop('best_params', axis=1).T\n perf_df_t.columns = perf_df_t.iloc[0]\n perf_df_t = perf_df_t.iloc[1:]\n\n ax = perf_df_t.plot.barh(figsize=(10,6))\n fig = plt.gcf()\n\n ax.set(title='Metrics Comparison', \n yl... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Map a java staging request to the right args. | def _JavaStagingMapper(command_path, descriptor, app_dir, staging_dir):
del descriptor # Unused, app_dir is sufficient
java.CheckIfJavaIsInstalled('local staging for java')
java_bin = files.FindExecutableOnPath('java')
args = ([java_bin, '-classpath', command_path, _JAVA_APPCFG_ENTRY_POINT] +
_JAVA_A... | [
"def _map_arguments(self, args):\n data = args.get('data')\n comp = args.get('comp')\n library = args.get('library')\n dry_run = args.get('dry_run', False)\n\n self._set_link('srcmaps-catalog', SrcmapsCatalog_SG,\n comp=comp, data=data,\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Invokes a staging command with a given .yaml and temp dir. | def Run(self, staging_area, descriptor, app_dir):
staging_dir = tempfile.mkdtemp(dir=staging_area)
args = self.mapper(self.GetPath(), descriptor, app_dir, staging_dir)
log.info('Executing staging command: [{0}]\n\n'.format(' '.join(args)))
out = cStringIO.StringIO()
err = cStringIO.StringIO()
re... | [
"def staging():\n project_name = _get_project_name()\n origin = '%s/%s.tar' % (SETTINGS['releases_dir'], project_name)\n destination = '%s/%s.tar' % (SETTINGS['staging']['path'], project_name)\n put(origin, destination)\n\n with cd(SETTINGS['staging']['path']):\n run('mkdir -p %(rel)s && cd %(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the default stager. | def GetStager(staging_area):
return Stager(_STAGING_REGISTRY, staging_area) | [
"def GetNoopStager(staging_area):\n return Stager({}, staging_area)",
"def default():\n return DefaultSwh.default()",
"def default_wiper(self):\n return self._default_wiper",
"def getDefaultFetcher():\n global _default_fetcher\n\n if _default_fetcher is None:\n setDefaultFetcher(cr... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the beta stager, used for `gcloud beta ` commands. | def GetBetaStager(staging_area):
registry = _STAGING_REGISTRY.copy()
registry.update(_STAGING_REGISTRY_BETA)
return Stager(registry, staging_area) | [
"def GetStager(staging_area):\n return Stager(_STAGING_REGISTRY, staging_area)",
"def getBeta(self):\n\t\treturn self.relativistic_beta",
"def get_stage(self, stg_name):\n if stg_name not in self.__dict__:\n raise AttributeError\n return self.__dict__[stg_name]",
"def GetNoopStager(s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get a stager with an empty registry. | def GetNoopStager(staging_area):
return Stager({}, staging_area) | [
"def GetStager(staging_area):\n return Stager(_STAGING_REGISTRY, staging_area)",
"def empty_animal_shelter():\n return AnimalShelter()",
"def __cleanRegistry():\n registry = CollectorRegistry()\n return registry",
"def empty_fuselage():\n fus = Fuselage(construct_geometry=False)\n retu... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Quantize the RGB image along all 3 channels and assign values of the nearest cluster center to each pixel. Return the quantized image and cluster centers. | def quantizeRGB(origImg: np.ndarray, k: int) -> np.ndarray:
######################################################################################
## TODO: YOUR CODE GOES HERE ##
#########################################################################... | [
"def color_quantization(self):\n Z = self.img.reshape((-1,3))\n\n # convert to np.float32\n Z = np.float32(Z)\n\n # define criteria, number of clusters(K) and apply kmeans()\n # Criteria arguments for termination of algorithm:\n # -type:\n # cv2.TERM_CRITERIA_EPS... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Convert the image to HSV, quantize the Hue channel and assign values of the nearest cluster center to each pixel. Return the quantized image and cluster centers. | def quantizeHSV(origImg: np.ndarray, k: int) -> np.ndarray:
######################################################################################
## TODO: YOUR CODE GOES HERE ##
#####################################################################... | [
"def quantize_image(img_num: np.ndarray, n_clusters: int) -> np.ndarray:\n\n m, l, k = img_num.shape[0], img_num.shape[1], img_num.shape[2]\n\n df = pd.DataFrame(img_num.reshape(m*l, k))\n\n df.columns = [\"R\", \"G\", \"B\"]\n kmeans = KMeans(n_clusters=n_clusters)\n kmeans.fit(df)\n\n df[\"clust... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculate the quantization error by finding the sum of squared differences between the original and quantized images. Implement a vectorized version (using numpy) of this error metric. | def computeQuantizationError(origImg: np.ndarray, quantizedImg: np.ndarray) -> int:
######################################################################################
## TODO: YOUR CODE GOES HERE ##
##################################################... | [
"def quantizeImage(imOrig: np.ndarray, nQuant: int, nIter: int) -> (List[np.ndarray], List[float]):\r\n MSE=[] #A list of the MSE error in each iteration\r\n alllist=[] #A list of the quantized image in each iteration\r\n\r\n if is_rgb(imOrig): #for the RGB images\r\n YIQimage=transformRGB2YIQ(imOri... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Initialises a new QuestionnaireLoader instance to read and process data from files generated by the RED questionnaires. Arguments data_dir String. Path to the directory that contains data files that need to be loaded. Keyword Arguments output_path String. Path to the file in which processed data needs to be stored, or ... | def __init__(self, data_dir, output_path=None, task_name="Q1_Questions"):
# Remember the task name.
self._task_name = task_name
# Load all data.
self.load_from_directory(data_dir, task_name)
self.process_raw_data()
if not (output_path is None):
self.w... | [
"def __init__(self, data_dir, output_path=None, task_name=\"ReadingTest\", \\\n answer_file=None):\n \n # Define the default answer_file.\n if answer_file is None:\n answer_file = os.path.join( \\\n os.path.dirname(os.path.abspath(__file__)), \\\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Loads data from a single file. This function overwrites the parent's load_from_file function to allow for the checking of answers. Arguments file_path String. Path to the file that needs to be loaded. Keyword arguments delimiter String. Delimiter for the data file. Default = "," missing List. List of values that code f... | def load_from_file(self, file_path, delimiter=",", missing=None, \
auto_typing=True, string_vars=None):
# Load the data from a file.
raw = read_behaviour(file_path, delimiter=",", missing=None, \
auto_typing=True, string_vars=["Response"])
# If the file ... | [
"def load_from_file(self, file_path, delimiter=\",\", missing=None, \\\n auto_typing=True, string_vars=None):\n \n # Load the data from a file.\n raw = read_behaviour(file_path, delimiter=\",\", missing=None, \\\n auto_typing=True, string_vars=[\"Sentence\", \"Response\"])... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Computes the variables that need to be computed from this task, and stores them in the self.data dict. This has one key for every variable of interest, and each of these keys points to a NumPy array with shape (N,) where N is the number of participants. The processed data comes from the self.raw dict, so make sure that... | def process_raw_data(self):
# Get all participant names, or return straight away if no data was
# loaded yet.
if hasattr(self, "raw"):
participants = self.raw.keys()
participants.sort()
else:
self.data = None
return
# Coun... | [
"def process_raw_data(self):\n \n # Define some variables of interest.\n vor = [\"n_sentences\", \"n_correct\", \"p_correct\", \"median_RT\", \\\n \"mean_RT\", \"stdev_RT\", \"scaled_stdev_RT\"]\n \n # Get all participant names, or return straight away if no data was\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Method creates top model. This model will be added at the top of keras application model. | def create_model_tail(self, model):
# Creating a sequential model to at as top layers
top_model = keras.Sequential()
top_model.add(keras.layers.Flatten(input_shape=model.output_shape[1:]))
# Add multiple layers
for layer_num, layer_dim in enumerate(self.num_nodes):
t... | [
"def addTopModel(bottom_model, num_classes):\n\n top_model = bottom_model.output\n top_model = GlobalAveragePooling2D()(top_model)\n top_model = Dense(1024,activation='relu')(top_model)\n top_model = Dense(1024,activation='relu')(top_model)\n top_model = Dense(512,activation='relu')(top_model)\n t... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Asserts a dict used for report_options argument for request_report method builds the correct string output. | def test_report_options_dict(self, api_instance: Reports):
report_type = "_GET_MERCHANT_LISTINGS_ALL_DATA_"
report_options = {"custom": True, "somethingelse": "abc"}
params = api_instance.request_report(
report_type=report_type,
report_options=report_options,
)
... | [
"def report(context, sample_config, output_config):\n\n config_json = json.load(open(sample_config))\n\n json_out = dict()\n\n json_out[\"analysis\"] = dict()\n\n if config_json[\"analysis\"][\"BALSAMIC_version\"]:\n bv = config_json[\"analysis\"][\"BALSAMIC_version\"]\n\n json_out[\"analysis\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
GetReportRequestListByNextToken operation, via method decorator. | def test_get_report_request_list_by_next_token(self, api_instance: Reports):
params = api_instance.get_report_request_list(next_token="RXmLZ2bEgE")
self.assert_common_params(params, action="GetReportRequestListByNextToken")
assert params["NextToken"] == "RXmLZ2bEgE" | [
"def test_get_report_request_list_by_next_token_alias(self, api_instance: Reports):\n params = api_instance.get_report_request_list_by_next_token(\"0hytxbkaOb\")\n self.assert_common_params(params, action=\"GetReportRequestListByNextToken\")\n assert params[\"NextToken\"] == \"0hytxbkaOb\"",
... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
GetReportRequestListByNextToken operation, via alias method. | def test_get_report_request_list_by_next_token_alias(self, api_instance: Reports):
params = api_instance.get_report_request_list_by_next_token("0hytxbkaOb")
self.assert_common_params(params, action="GetReportRequestListByNextToken")
assert params["NextToken"] == "0hytxbkaOb" | [
"def test_get_report_request_list_by_next_token(self, api_instance: Reports):\n params = api_instance.get_report_request_list(next_token=\"RXmLZ2bEgE\")\n self.assert_common_params(params, action=\"GetReportRequestListByNextToken\")\n assert params[\"NextToken\"] == \"RXmLZ2bEgE\"",
"def get_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
GetReportListByNextToken operation, via method decorator. | def test_get_report_list_by_next_token(self, api_instance: Reports):
params = api_instance.get_report_list(next_token="5u6Of2fS8B")
self.assert_common_params(params, action="GetReportListByNextToken")
assert params["NextToken"] == "5u6Of2fS8B" | [
"def test_get_report_list_by_next_token_alias(self, api_instance: Reports):\n params = api_instance.get_report_list_by_next_token(\"3TczcliCkb\")\n self.assert_common_params(params, action=\"GetReportListByNextToken\")\n assert params[\"NextToken\"] == \"3TczcliCkb\"",
"def test_get_report_re... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
GetReportListByNextToken operation, via alias method. | def test_get_report_list_by_next_token_alias(self, api_instance: Reports):
params = api_instance.get_report_list_by_next_token("3TczcliCkb")
self.assert_common_params(params, action="GetReportListByNextToken")
assert params["NextToken"] == "3TczcliCkb" | [
"def test_get_report_list_by_next_token(self, api_instance: Reports):\n params = api_instance.get_report_list(next_token=\"5u6Of2fS8B\")\n self.assert_common_params(params, action=\"GetReportListByNextToken\")\n assert params[\"NextToken\"] == \"5u6Of2fS8B\"",
"def test_get_report_request_lis... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
GetReportScheduleListByNextToken operation, via method decorator. | def test_get_report_schedule_list_by_next_token(self, api_instance: Reports):
params = api_instance.get_report_schedule_list(next_token="Yj3hOfPcIE")
self.assert_common_params(params, action="GetReportScheduleListByNextToken")
assert params["NextToken"] == "Yj3hOfPcIE" | [
"def test_get_report_schedule_list_by_next_token_alias(self, api_instance: Reports):\n params = api_instance.get_report_schedule_list_by_next_token(\"SAlt4JwJGv\")\n self.assert_common_params(params, action=\"GetReportScheduleListByNextToken\")\n assert params[\"NextToken\"] == \"SAlt4JwJGv\"",... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
GetReportScheduleListByNextToken operation, via alias method. | def test_get_report_schedule_list_by_next_token_alias(self, api_instance: Reports):
params = api_instance.get_report_schedule_list_by_next_token("SAlt4JwJGv")
self.assert_common_params(params, action="GetReportScheduleListByNextToken")
assert params["NextToken"] == "SAlt4JwJGv" | [
"def test_get_report_schedule_list_by_next_token(self, api_instance: Reports):\n params = api_instance.get_report_schedule_list(next_token=\"Yj3hOfPcIE\")\n self.assert_common_params(params, action=\"GetReportScheduleListByNextToken\")\n assert params[\"NextToken\"] == \"Yj3hOfPcIE\"",
"def l... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Using enums for report_type and schedule should produce the correct string literals when cleaned. | def test_manage_report_schedule_enums(
self, api_instance: Reports, report_type, schedule
):
params = api_instance.manage_report_schedule(
report_type=report_type,
schedule=schedule,
)
self.assert_common_params(params, action="ManageReportSchedule")
as... | [
"def report_type(self):\n if self.type is None:\n text = \"unknown report type\"\n elif self.type in REPORT_TYPE:\n text = REPORT_TYPE[self.type]\n else:\n text = self.type + \" report\"\n if self.cycle:\n text += \", cycle %d\" % self.cycle\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Using enums for processing_status should produce the correct string literal when cleaned. | def test_cancel_report_requests_processing_enums(
self, api_instance: Reports, processing_status
):
params = api_instance.cancel_report_requests(
processing_statuses=processing_status,
)
assert params["ReportProcessingStatusList.Status.1"] == "_DONE_NO_DATA_" | [
"def normalize_status(status):\n return status.replace('_', ' ').title() # We dont override if the data is empty.",
"def map_status(status):\n new_status = \"\"\n if \"new\" in status:\n new_status = \"requested\"\n elif \"translating\" in status:\n new_status = ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
If the testlist is a list, returns an ast.Tuple with a Load context, otherwise returns the orginal node. | def ast_for_testlist(testlist):
if isinstance(testlist, list):
value = ast.Tuple()
value.elts = testlist
value.ctx = Load
else:
value = testlist
return value | [
"def visit_List(self, node):\n self.generic_visit(node)\n if isinstance(node.ctx, ast.Load):\n return to_call(to_attribute(self.operator, '__list__'), node.elts)\n return node",
"def visit_Tuple(self, node):\n self.generic_visit(node)\n if isinstance(node.ctx, ast.Loa... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Write the parser and lexer tables. | def write_tables(self):
parse_dir, parse_mod = self._tables_location()
# Using optimized = 0 force yacc to compare the parser signature to the
# parse_tab signature and will update it if necessary.
yacc.yacc(method='LALR',
module=self,
start='enaml',
... | [
"def _write_tables(cls):\n path = inspect.getfile(cls)\n parent = os.path.split(path)[0]\n # Need to change directories to get the file written at the right\n # location.\n cwd = os.getcwd()\n os.chdir(parent)\n tabname = cls._table_name('lex', relative=True)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Recursively sets the context of the node to the given context which should be Store or Del. If the node is not one of the allowed types for the context, an error is raised with an appropriate message. | def set_context(self, node, ctx, p):
# XXX passing the yacc production object to raise the error
# message is a bit flakey and gets things wrong occasionally
# when there are blank lines around the error. We can do better.
items = None
err_msg = ''
node_type = type(node)
... | [
"def _repair_context(self, context):\n\n if isinstance(context, Graph):\n return self._repair_context(context.identifier)\n elif isinstance(context, URIRef):\n return context\n else:\n return NULL_CONTEXT",
"def set_node_context(tree: ast.AST) -> ast.AST:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create a module object using the provided body and kwargs. | def create_module(self, body: list, **kwargs):
return ast.Module(body=body) | [
"def create_module(cls, *args, **kwargs): # real signature unknown\n pass",
"def create_module(cls, *args, **kwargs): # real signature unknown\r\n pass",
"def create_module(self, mid, paras):\n class_name = self.modules[mid]['class']\n names = class_name.split('.')\n # Module ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set the arguments for an ast.Call node. | def set_call_arguments(self, node, args):
node.args = args.args
node.keywords = args.keywords
node.starargs = args.starargs
node.kwargs = args.kwargs | [
"def visit_Call(self, node):\n assert hasattr(node, 'args')\n if node.args:\n assert isinstance(node.args[0], gast.Starred)\n # modify args\n if isinstance(node.args[0].value, gast.Name):\n node.args[0].value.id += '_new'\n\n assert hasattr(node, ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Validate the correctness of names in an enamldef definition. This function ensures that identifiers do not shadow one another. | def _validate_enamldef(self, node, lexer):
ident_names = set()
def check_id(name, node):
if name in ident_names:
msg = "redeclaration of identifier '%s'"
msg += " (this will be an error in Enaml version 1.0)"
syntax_warning(msg % name, FakeTok... | [
"def verify_naming(self, reserved):\n for w in reserved:\n if w in self.decisions:\n raise ParseError('Duplicate variable/block name \"{}\"'.format(w))",
"def validate_name(name, reserved_names=()):",
"def check_naming_convention(func_defs: List[DahliaFuncDef]):\n\n def is_re... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Validate the correctness of names in a template definitions. This function ensures that parameters, const expressions, and identifiers do not shadow one another. | def _validate_template(self, node, lexer):
param_names = set()
const_names = set()
ident_names = set()
def check_const(name, node):
msg = None
if name in param_names:
msg = "declaration of 'const %s' shadows a parameter"
elif name in c... | [
"def _validate_template_inst(self, node, lexer):\n names = set()\n if node.identifiers:\n names.update(node.identifiers.names)\n for binding in node.body:\n if binding.name not in names:\n msg = \"'%s' is not a valid template id reference\"\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Validate a template instantiation. This function ensures that the bindings on the instantiation refer to declared identifiers on the instantiation. | def _validate_template_inst(self, node, lexer):
names = set()
if node.identifiers:
names.update(node.identifiers.names)
for binding in node.body:
if binding.name not in names:
msg = "'%s' is not a valid template id reference"
syntax_error(m... | [
"def _validate_template(self, node, lexer):\n param_names = set()\n const_names = set()\n ident_names = set()\n\n def check_const(name, node):\n msg = None\n if name in param_names:\n msg = \"declaration of 'const %s' shadows a parameter\"\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Validate arguments and keywords arguments. Assume that the second token is a STAR. | def _validate_arglist_and_kwlist(self, p, items, keywords):
kwnames = set()
args = []
kws = []
self._validate_arglist_list(items, p.lexer.lexer)
for arg in items:
if isinstance(arg, ast.keyword):
kws.append(arg)
kwnames.add(arg.arg)
... | [
"def check_args() -> bool:\n if len(sys.argv) == 2:\n keyword = sys.argv[1]\n for ch in keyword:\n if ch.isdigit():\n print(\"Usage viginere.py keyword\")\n sys.exit(1)\n else:\n print(\"Usage vigenere.py keyword\")\n sys.exit(1)",
"def va... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a tuple containing the number of arrived and departed TCP connections at the given host and port, along with the last update timestamp. | def connection_stats(self, host="localhost", port=9090):
mgr = NetworkConnectionsManager(self.db_uri_)
return mgr.connection_stats(host, port) | [
"def _extractConnectionStatistics(self, ttoutput):\n assert isinstance(ttoutput, str), \"type ttoutput: %s\"%type(ttoutput)\n\n hostRE = r\"host \\w+:\\s*([0-9.]+):([0-9]+)\" # Matches a line containing one of the hosts that are communicating here\n startTimeRE = r'first packet:\\s*([\\w\\s:\\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the number of pending and served TCP connections at the given host and port. | def num_pending_connections(self, host="localhost", port=9090):
mgr = NetworkConnectionsManager(self.db_uri_)
return mgr.num_pending_connections(host, port) | [
"def num_connections_by_status(self, host=\"localhost\", port=9090, status=NetworkConnectionsManager.wait_connection_status):\n\t\tmgr = NetworkConnectionsManager(self.db_uri_)\n\t\treturn mgr.num_connections_by_status(host, port, status)",
"def cached_hosts_count_on_port(self, port):\n hosts_count = 0\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the number of TCP connections to the given host and port and for the given status. | def num_connections_by_status(self, host="localhost", port=9090, status=NetworkConnectionsManager.wait_connection_status):
mgr = NetworkConnectionsManager(self.db_uri_)
return mgr.num_connections_by_status(host, port, status) | [
"def statusCount(conn, status):\n curs = conn.cursor()\n curs.execute(\n '''select count(*) from inventory where status = %s''',[status])\n return curs.fetchone()[0]",
"def connection_exist(self):\r\n p = subprocess.Popen([\"/home/pi/sebastian/sebastian-flask/netstat_helper.sh\", \":5000\"]... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
r"""|coro| Requests previously offline members from the guild to be filled up | async def request_offline_members(self, *guilds):
... | [
"async def request_support_server_members(self):\n try:\n guild: discord.Guild = self.ex.client.get_guild(self.ex.keys.bot_support_server_id) or await self.ex. \\\n client.fetch_guild(self.ex.keys.bot_support_server_id)\n if not guild.chunked:\n await guild... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generate colormap for N lines/points from the given colormap Later used in loop for each line/point by colorVal = scalarMap.to_rgba(i) i from 0 | def LineColorCoding(N,cmap='jet'):
colormap_name = cmap
cm = plt.get_cmap(colormap_name)
cNorm = colors.Normalize(vmin=0, vmax=N-1)
scalarMap = cmx.ScalarMappable(norm=cNorm, cmap=cm)
return scalarMap | [
"def get_color_map(n):\n jet = plt.get_cmap('jet')\n cNorm = colors.Normalize(vmin=0, vmax=n-1)\n scalarMap = cmx.ScalarMappable(norm=cNorm, cmap=jet)\n outmap = []\n for i in range(n):\n outmap.append( scalarMap.to_rgba(i) )\n return outmap",
"def color_generator(N, colormap='gnuplot'):... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Secure the uploaded file is an image | def secure_filetype(file):
ext_list = ['png', 'jpg', 'jpeg']
ext_valid = file.filename.split('.')[-1] in ext_list
mimetype_list = ["image/jpeg", "image/jpg", "image/png"]
mimetype_valid = file.mimetype in mimetype_list
return ext_valid and mimetype_valid | [
"def upload_is_image(data):\n # From django/forms/fields.py\n if hasattr(data, 'temporary_file_path'):\n file = data.temporary_file_path()\n else:\n if hasattr(data, 'read'):\n file = io.BytesIO(data.read())\n else:\n file = io.BytesIO(data['content'])\n\n try:... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Secure the size of the uploaded file is smaller than MAX_FILESIZE | def secure_filesize(filepath):
return os.path.getsize(filepath) <= MAX_FILESIZE | [
"def validate_size(uploaded_file):\n if uploaded_file.size > MAX_UPLOAD_SIZE:\n raise ValidationError(UploadFormErrors.SIZE)",
"def validate_file_size(file):\n limit = 2621440 # 2.5MB\n if file.size > limit:\n raise ValidationError('File too large. Size should not exceed 2.5 MB.')",
"def... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
create pillow image with barcode inside | def save_barcode_to_pillow(self, scale_x=1, scale_y=1):
# creating a black and while 1-BIT image
# note: if you have problems with 1-BIT images
# select image type "L" and set color=255 for a greyscale image
im = Image.new('1',
(int(self.barcode_array['num_cols']... | [
"def _generate_barcode(string_to_encode, module_size):\n #TODO: document\n if isinstance(module_size, int) and module_size > 0:\n encoder = DataMatrixEncoder(string_to_encode)\n buffer = BytesIO()\n buffer.write(encoder.get_imagedata(module_size))\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
str > Boolean Given a str 'myint', return 'True' if each digit is greater than or equal to the previous digit going from lefttoright. Return 'False' otw >>> isTidy('129') True >>> isTidy('7') True >>> isTidy('100') False | def isTidy(mystr):
for char_index in range(len(mystr) - 1):
if mystr[char_index] > mystr[char_index + 1]:
return False
return True | [
"def checkTidy(num):\n\n num = [int(n) for n in list(str(num))]\n\n for i in range(len(num) - 1, 0, -1):\n if num[i]<num[i-1]:\n return False\n\n return True",
"def is_palindrome_integer(num: int) -> bool:\n\tif num < 0:\n\t\treturn False\n\tnum_str = str(num)\n\n\treturn num_str == num... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
str > str Given an integer string 'mystr', return a tidy integer string that is as close as possible to 'mystr'. The algorithm to use | def maxTidy(mystr):
tidyFlag = isTidy(mystr)
while not tidyFlag:
numarray = [int(char) for char in mystr]
for i in range(1, len(numarray)):
if numarray[i] < numarray[i - 1]:
numarray[i - 1] -= 1
for j in range(i, len(numarray)):
n... | [
"def str2int(s):\r\n idx, sgn = (1, -1) if '-' == s[0] else (0, 1)\r\n ans = 0\r\n\r\n for i in range(idx, len(s)):\r\n ans = ans*10 + int(s[i])\r\n\r\n return ans*sgn",
"def numerifyId(string):\n for i in range(0, len(string)):\n if string[i] < \"0\" or string[i] > \"9\":\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
(string, tuple) > Note Initialize a note with memo and optional list of tags. Automatically set the note's creation date and a unique id. | def __init__(self, memo, tags=()):
self.memo = memo
self.tags = tags
self.creation_date = datetime.date.today()
global last_id
last_id += 1
self.id = last_id | [
"def new_note(self, memo, tags=\"\"):\n\t\tself.notes.append(Note(memo, tags))",
"def CreateNote(self):",
"def create_note(self, owner, title, text, note_type, important):\r\n note = self.create(owner=owner, title=title, text=text, note_type=note_type, important=important)\r\n return note",
"def... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
(Notebook) > string Returns a nicely formatted string of all the notes in the Notebook | def __str__(self):
result = "\nNotebook:\n"
for note in self.notes:
result += f"\nNote created on {note.creation_date}.\nTags: " \
f"{', '.join(note.tags)}\nMemo: {note.memo}"
return result | [
"def getnotes():",
"def __repr__(self):\n return str(self.notes)",
"def getNotesString(self, *args):\n return _libsbml.SBase_getNotesString(self, *args)",
"def render_note(note: str) -> str:\n note = emojize(note)\n note = markdown(note, extensions=['nl2br'])\n return note",
"def note... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
(int) > Note Locate the note with the given id. | def _find_note(self, note_id):
for note in self.notes:
if str(note.id) == str(note_id):
return note
return None | [
"def _find_note(self, id):\n for note in self.notes:\n if note.id == id:\n return note\n return None",
"def _find_note(self, note_id):\n for note in self.notes:\n if note.id == note_id:\n return note\n return None",
"def _find_note(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
(int, string) > None Find the note with the given id and change its memo to the given value. | def modify_memo(self, note_id, memo):
try:
self._find_note(note_id).memo = memo
except AttributeError:
print(f"Note with id {note_id} not found") | [
"def modify_memo(self, note_id, memo):\n self._find_note(note_id).memo = memo",
"def updateEntryMemo(self, id, memo):\n query = (\"UPDATE %s \" % self.__tablename__ +\n \"SET memo=? WHERE id=?\",\n (memo, id))\n self.sql_execute(query)",
"def modify(self, not... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
(int, list) > None Find the note with the given id and change its tags to the given value. | def modify_tags(self, note_id, tags):
try:
self._find_note(note_id).tags = tags
except AttributeError:
print(f"Note with id {note_id} not found") | [
"def modify_tags(self, id, new_tag):\n for note in self.notes:\n if note.id == id:\n note.memo = new_tag",
"def modify_tags(self, note_id, tags):\n\t\tself._find_note(note_id).tags = tags",
"def modify_tags(note_id, tags):\n self.find_note(note_id).tags = tags",
"def mo... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Find all notes that match the given filter string. | def search(self, filtr):
return [note for note in self.notes if note.match(filtr)] | [
"def search(self, filter):\n return [note for note in self.notes if note.match(filter)]",
"def search(self, filter):\n\t\treturn [note for note in self.notes if note.match(filter)]",
"def search_notes(self, query_string):\n found_notes = []\n for note in self.__notes:\n found = n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This method is used in order to start the server | def start_server(self):
app.run(host=str(self.__constants.host),
port=int(self.__constants.port),
debug=bool(self.__constants.runindebug)) | [
"def _start(self):\n\n ip = mh.cfg['Extensions']['TestEnv']['server_ip']\n port = mh.cfg['Extensions']['TestEnv']['server_port']\n self._server = application(urls, globals())\n httpserver.runsimple(self._server.wsgifunc(), (str(ip), port))",
"def __start_server(self):\n self._se... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This method returns a list of duplicate files | def find_duplicates():
return AppServer.service.find_duplicated_files() | [
"def detect_file_duplicates( self, role ):\n duplicates = []\n for x,f in enumerate(self.files):\n for y,f2 in enumerate(self.files):\n if (f != f2) and (f['path_rel'] == f2['path_rel']) and (f2 not in duplicates):\n duplicates.append(f)\n return dup... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the operation times in minutes as a dictionary. | def get_operation_times(self):
self.write("TIMERS?")
timers = {}
timers['psu'] = int(re.search(r"\d+", self.read()).group())
timers['laser'] = int(re.search(r"\d+", self.read()).group())
timers['laser_above_1A'] = int(re.search(r"\d+", self.read()).group())
self.read() #... | [
"def _get_time_interval_in_minutes(self):\n return self.visa.get_request_interval_in_minutes()",
"def get_time(self):\n return [self.hours, self.mins, self.secs]",
"def get_time_dict(self):\n return {\n \"activity\" : self.activity_name,\n \"start_time\": self.start_ti... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Disable emission and unlock the button afterwards. You have to press the physical button to enable emission again. | def disable_emission(self):
self.ask("LASER=OFF")
self.ask("LASER=ON") # unlocks emission button, does NOT start emission! | [
"def _disable(self):\n self.enabled = False",
"def disable(self):\r\n self.isEnabled = False",
"def disable(self):\r\n self.enabled = False",
"def on_disable(self) -> None:\n self._cancel_automation()",
"def disable(self):\n self.isEnabled = False",
"def disable(self):\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
gets the dimensions of `filename` | def GetDimensions(filename):
with Image(filename=filename) as img:
dimensions = (img.width, img.height)
return(dimensions) | [
"def image_size_from_file(filename):\n with PIL.Image.open(filename) as img:\n width, height = img.size\n return height, width",
"def getimagesize(filename):\n img = Image.open(filename)\n (w,h) = img.size\n t = \"IMAGETYPE_%S\" % img.format\n a = \"width=\\\"%d\\\" height=\\\"%d\\\"\" % img.size... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
generate random offsets for frames | def GenerateOffsets(frames, cut_pixels):
def GenRandom(max_rand):
return random.randint(-max_rand, max_rand)
max_rand = int(cut_pixels / 2)
if frames == 2:
return([(0, 0), (max_rand, max_rand), (0, 0)])
finished = False
while not finished:
coords = [(0, 0)]
for i in... | [
"def sample_rotating_offset(offsets, t, start_t, frame):\n offsets[:] = (offsets[:] + 1) % STATE.layout.columns",
"def _create_random_offsets(self, block_locations):\n\n min_x, max_x, min_y, _ = self._find_min_and_max_coords(block_locations)\n x_offset = randrange(10 - (max_x - min_x)) - min_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Rounds x to the 1st significant figure of y | def round_to(x, y):
return round(x, -int(floor(log10(abs(y))))) | [
"def round(x):\n return int(x + copysign(0.5, x))",
"def round_to(x, y):\n return int(numpy.ceil(x / float(y))) * y",
"def divide_and_round_up(x, y):\n return ((x - 1) // y) + 1",
"def oddround(x):\n\n return x-mod(x,2)+1",
"def iround(x):\n return int(round(x) - .5) + (x > 0)",
"def ir... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Depending on the attack type parameter, spread the worm or perform a SYNFLOOD attack on specified address. | def attack_command(s, atck_type=None, victim_ip=None):
global BOT_STATES
global PORT
valid_attack = {
'0' : 'spread worm',
'1' : 'syn flood'
}
# Validate user input options
if not atck_type or not victim_ip:
print("Invalid input. Enter 'help for options.")
return... | [
"def apply_attack(self, data):",
"def attack(self):\n pass",
"def allow_attack(self, action):\n return True",
"def _send_attack(self, **attack_dict):\n logger.info('Start attack - %s', attack_dict)\n self.sdn_interface.post('attack', attack_dict)",
"def on_attacked(self, action):... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Send a 'STOP' message to all enrolled bots and reset states to ready. | def stop_command(s):
global BOT_STATES
logger.info("Sending STOP")
print("Sending STOP to all BUSY bots.")
for addr in BOT_STATES.keys():
if BOT_STATES[addr] == 2:
s.sendto('STOP', (addr, PORT))
logger.info("Sent STOP to {}".format(addr))
print("Sent STOP to {... | [
"def _stop_bot(_event):\n pass",
"def stopall():\n \n for ag in agents:\n ag.stop()",
"async def n4rstop(self):\n\n self.is_polling = False\n await self.bot.say(\"Ok, stopped polling!\")",
"def stop_all(self):\n for s in self.sockets[:]:\n self.stop(s)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check in on status of bots. Sends the bots a ROLL message where they respond with their states. | def roll_command(s):
for addr in BOT_STATES.keys():
s.sendto('ROLL', (addr, PORT))
print('ROLL sent to {}'.format(addr))
logger.info('All bot statuses updated.') | [
"async def status_changer():\r\n playing = [discord.Game(name=\"with management\")]\r\n streaming = []\r\n listening = [discord.Activity(type=discord.ActivityType.listening, name=\"for DM's\")]\r\n watching = [discord.Activity(type=discord.ActivityType.watching, name=\"for cries of help\"), discord.Acti... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
List bots characterized by their current state. | def list_bots():
bot_count = len(BOT_STATES)
idle = []
ready = []
busy = []
for addr in BOT_STATES.keys():
if BOT_STATES[addr] == 0:
idle.append(addr)
elif BOT_STATES[addr] == 1:
ready.append(addr)
elif BOT_STATES[addr] == 2:
busy.appe... | [
"def list_bots(self, source, target, *args):\n return \"<br />Currently active bots: <br /><br />\" + (\"<br />\".join(\n [\"{}: <b>{}</b>\".format(x.username, x.channel) for x in\n self.protocol.bots]))",
"async def bot_list(self) -> list:\n return await self._do_request(\"ge... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Listens on specified port for bot responses, adds bots if not enrolled, and updates their states. | def bot_listener():
global BOT_STATES
global PORT
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind(('', PORT))
while True:
bot_resp, client_addr = sock.recvfrom(1024)
if bot_resp == 'HELO':
logger.info("Received 'HELO' from: {}".format(client_addr))
... | [
"async def listening(self,ctx,*,game):\r\n\t\tawait self.bot.change_presence(game=discord.Game(name=game,type=2))\r\n\t\tawait self.ctx.send(f\"Set status to listening to {game}\")",
"def accepting_connections():\r\n for c in all_connections_bot:\r\n c.shutdown(socket.SHUT_RDWR)\r\n c.close()\r\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gray out all buttons | def disable_buttons(self):
self.cancel.set_sensitive(False)
self.logout.set_sensitive(False)
self.suspend.set_sensitive(False)
self.reboot.set_sensitive(False)
self.shutdown.set_sensitive(False) | [
"def deactivate_all(self):\n\t\t\n\t\tfor button in self.buttons:\n\t\t\tif button not in [\"apply\", \"clear\"]:\n\t\t\t\tself.buttons[button].set_sensitive(False)",
"def disableAllButtons(self):\n\n self.browseButton['state'] = DISABLED\n self.saveButton['state'] = DISABLED\n self.clearButt... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Loads bunch of AUCS stored in files files should be tagged as tag_cellline_ligand. and contain a single column with all AUCs. This is convenientn if you ran many simulation that stores AUC in different files | def loaddata(self, directory=None, tag="AUC"):
self.data = {}
for c in self.cellLines:
self.data[c] = {}
for l in self.ligands:
self.data[c][l] = []
for l in self.ligands:
for c in self.cellLines:
if self.verbose:print("Combini... | [
"def load_ineraction_files(file_prefix):\n\tbinintfile=file_prefix+'.binint.log'\n\tcollfile=file_prefix+'.collision.log'\n\tmergefile=file_prefix+'.semergedisrupt.log'\n\tunitsfile=file_prefix+'.conv.sh'\n\n\twith open(binintfile, 'r') as f:\n\t\tnum_int = sum([1 for line in f if '****' in line])\n\t\tf.seek(0) #n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
returns all mean AUCS in a matrix structure | def get_mean(self):
mean = np.array(np.zeros((4,8)))
for i,c in enumerate(self.cellLines):
for j,l in enumerate(self.ligands):
mean[i][j] = self.aucs[c][l]['mean']
return mean | [
"def matrix_mean(matrix):\n return sum(map(mean,matrix))",
"def mean(data_matrix):\n return np.asmatrix(np.mean(data_matrix, axis=0))",
"def my_mean(matrix):\n\n # Check if the matrix is not empty to make sure we do not divide by 0.\n if matrix.shape[0] == 0:\n s = 1\n else:\n s = m... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
returns all mean AUCS in a dictionary structure | def get_mean_dict(self):
mean = {}
for c in self.cellLines:
mean[c] = {}
for l in self.ligands:
mean[c][l] = self.aucs[c][l]['mean']
return mean | [
"def fmean(configuration):\n fmean_dict_all = {\n \"HL\" : {'H1' : 100., 'L1' : 100.},\n \"HLV\" : {'H1' : 100., 'L1' : 100., 'V1': 130.},\n \"HLVK\" : {'H1' : 100., 'L1' : 100., 'V1': 130., 'K1' : 130.},\n \"HLVKI\" : {'H1' : 100., 'L1' : 100., 'V1': 130., 'K1' : 130., 'I1' : 100.},\n \"GW170817\" ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Decrypt a message with a given private key. Takes in a private_key generated by Crypto.PublicKey.RSA, which must be of size exactly 4096 If the ciphertext is invalid, return None | def decrypt(private_key, ciphertext):
if len(ciphertext) < 512 + 16:
return None
msg_header = ciphertext[:512]
msg_iv = ciphertext[512:512+16]
msg_body = ciphertext[512+16:]
try:
symmetric_key = PKCS1_OAEP.new(private_key).decrypt(msg_header)
except ValueError:
return None
if len(symmetric_key... | [
"def decrypt(private_key, msg):\n key_bits = private_key.n.bit_length()\n chunks = rsa_helpers.cp_encode(key_bits, msg)\n decoded_chunks = [pow(c, private_key.d, private_key.n) for c in chunks]\n return rsa_helpers.cp_decode(key_bits, decoded_chunks)",
"def decrypt(private_key, msg):\n return priva... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
starts from an entity and executes the path by doing depth first search. If there are multiple edges with the same label, we consider max_branch number. | def execute_one_program(self, e: str, path: List[str], depth: int, max_branch: int):
if depth == len(path):
# reached end, return node
return [e]
next_rel = path[depth]
next_entities = self.train_map[(e, path[depth])]
# next_entities = list(set(self.train_map[(e, ... | [
"def _walk_full_graph_by_path(start, path):\n o = start\n for p in path:\n for i in o.inputs:\n if i.op.type == p:\n o = i.op\n break\n return o",
"def _follow_branch(e, v0):\n #argument v0 to prevent infinte loops for isolated closed loops\n edges = [e];... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculates precision of each path wrt a query relation, i.e. ratio of how many times, a path was successful when executed to how many times the path was executed. | def calc_precision_map(self, output_filenm=""):
logger.info("Calculating precision map")
success_map, total_map = {}, {} # map from query r to a dict of path and ratio of success
# not sure why I am getting RuntimeError: dictionary changed size during iteration.
train_map = [((e1, r), e... | [
"def precision(df, single=False, query_number=None):\n df = df.sort_values(\"query\")\n query_index = 0\n last_query_index = len(df[\"query\"])\n if single:\n try:\n query_index = df[\"query\"].tolist().index(query_number)\n last_query_index = len(df[\"query\"]) - df[\"query... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Computes a pixel neighbor map for given pixel distances within an TM and between pixels at adjecent TMs. | def compute_pixneighbor_map(
config, pixdist: float = 1.8, intertmdist: float = 2.5
) -> list:
m = config.GetMapping()
xpix = np.array(m.GetXPixVector())
ypix = np.array(m.GetYPixVector())
size = m.GetSize()
dist = pixdist * size
intdist = intertmdist * size
neighbors = [] # [[]]*2048
... | [
"def transport_map(img):\n row, col = img.shape[:2]\n I = [None] * col # To store column number of images\n T = np.zeros((row,col), dtype=float) #Transport map\n C = np.zeros((row,col), dtype=int) #Map with path chosen\n for i in range(row):\n print \"row number Transport map:\",i\n fo... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Fetch the blogroll from a YAML file Return a dictionary generator | def loadblogs(filename):
stream = file(filename, 'r')
data = yaml.load_all(stream)
return data | [
"def yaml_loader(filepath):\n with open(filepath, \"r\") as file_descriptor:\n data = yaml.load(file_descriptor)\n return data",
"def get_dict_from_yml(self, filename):\r\n\r\n fid = open(os.path.join(RESOURCE_PATH, filename), 'r')\r\n result = ya... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Update the Firebase store from blogroll.yaml Add any blogs in the YAML file that aren't already in the Firebase store, along with its owner and the latest ETag or LastModified data from the feed. | def update_firebase():
# Firebase instance and auth param
fb = firebase.FirebaseApplication(FIREBASE_URL, None)
auth = {'auth': FIREBASE_SECRET}
# Current blogroll.yaml and FB store
yamlpath = path.join(path.dirname(__file__), '..', 'blogroll.yaml')
blogroll = loadblogs(yamlpath)
fb_store ... | [
"def update_posts(accounts):\n # print(account.columns)\n for index, post in accounts.iterrows():\n\n # If a post with this URL already exists in database, then continue with next one\n if collection.count_documents({'Posts.URL': post['URL']}, limit=1) != 0:\n print('Post with url ', ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculate the marginals P(y_s|X) and P(y_s, y_s+1|X) using forward and backward messages returns (mx26, m1x26x26) marginal distributions for each letter in the word | def get_marginals(word, model):
# forward and backward message at once
char_count, _ = word.shape
alpha = np.zeros((char_count, model.dimY)) # alphas
lbeta = np.zeros((char_count, model.dimY)) # log version of betas
first_term = np.dot(word, model.getW(model.labels))
second_term_a = model._T
... | [
"def marginals(self, maxsteps=500):\n\n n, _ = self.adjacency.shape\n # message pass\n self.belief_propagation(maxsteps)\n\n marginals = np.empty((n, self.n_clusters))\n i = 0\n # for each var\n for k, v in self.var.items():\n if v.enabled: # only include... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Indicator func [label == k] | def get_ind(labels, k):
return (np.array(labels) == k).astype('float64') | [
"def check_labels (points, labels, fun):\n your_labels = fun (points)\n return (labels == your_labels)",
"def presence(label):\r\n\r\n return lambda x, y: 1.0 * ((label in x) == (label in y))",
"def indicator_func(*args):\n for value_set in args:\n if value_set[0] != value_set[1]:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
calculate the gradient for given word with m chars and corresponding true labels W and T are initial weights TODO matrix implementation | def calculate_gradient_crf(train, model):
word = train[0]
label = train[1]
char_count, _ = word.shape
# get the marginals
marY, marY1 = get_marginals(word, model)
# calculate w_k for all 26 Ws. To do matrix approach
grad_W = []
for k in range(1,model.dimY+1):
ind_k = get_ind(labe... | [
"def gradient(w, x, t):\n return 2 * np.dot(x.T, (nn(x, w) - t))",
"def gradient_phrase(self,interp):\n # Compute the interpolated phrase probs\n interpolated = self.get_interpolated_phrase_probs(interp)\n\n # for each sample, log and sum across phrases, then compute the feature value\n # differen... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Draw the button to the screen depending on soundon flag. | def draw_sound_button(self):
if self.settings.sound_on:
self.screen.blit(self.image_sound_on, self.rect)
else:
self.screen.blit(self.image_sound_off, self.rect) | [
"def button_sound(self):\n sound = pygame.mixer.Sound('assests/sounds/Button_Sound.wav')\n sound.play()",
"def draw_button(self):\n draw.rect(self.screen, self.button_color, self.rect, 3)\n self.screen.blit(self.msg_image, self.msg_image_rect)",
"def draw(self):\r\n if not sel... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
checks if balance is positive | def balance(balance):
if float(balance) >= 0.0:
return True
else:
return False | [
"def balance_check():\n if balance > 0:\n return True\n else:\n return False",
"def positive_balance_check(user):\n return has_positive_balance(user)",
"def check_withdrawal(bal, amt):\n \n if float(bal - amt) > 0.00 and amt % 10 == 0:\n return True\n else:\n return... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
checks if notifyer includes the char '@' | def notifyer(notifyer):
if '@' in notifyer:
return True
else:
return False | [
"def mention(result):\n return result.text.find('@') != -1",
"def comprueba_mail(mail_usuario):\n arroba = mail_usuario.count('@')\n if arroba != 1 or mail_usuario.rfind('@') == (len(mail_usuario)-1):\n return False\n else: \n return True",
"def have_at_symbol(l):\n if \"@\" in str(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns heuristic cost estimate for path between two nodes. | def heuristic_cost_estimate(self, first_node_object, second_node_object):
(first_column, first_row) = first_node_object
(second_column, second_row) = second_node_object
return numpy.sqrt((first_row - second_row) ** 2 +
(first_column - second_column) ** 2) | [
"def calc_cost(self, node_a, node_b):\n if node_b.x - node_a.x == 0 or node_b.y - node_a.y == 0:\n # direct neighbor - distance is 1\n ng = 1\n else:\n # not a direct neighbor - diagonal movement\n ng = SQRT2\n\n # weight for weighted algorithms\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Executes the distutils code to build and install the pyccsm wrappers. | def run_distutils():
from distutils.core import setup, Extension
source_dir = os.getcwd()
build_dir = Params.cmake_binary_dir
gsched_module = Extension('_gsched',
sources=[build_dir+'/gsched_wrap.c',
build_dir+'/gsched.c'],
... | [
"def runBuildExt(opttree):\n\n if opttree.no_compile:\n return\n\n ct = opttree.cython\n\n extra_include_dirs = ct.extra_include_dirs\n extra_library_dirs = ct.extra_library_dirs\n libraries = ct.libraries\n library_map = ct.library_map\n extra_source_map = ct.extra_sou... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
generate a sales example with tables for customers, sales, products | def main():
s = content.DataFiles()
date_list = generate.get_list_dates(2016, 2016, 500)
prod_list = list(s.get_collist_by_name(os.path.join(content.data_fldr,'food','garden_produce.csv'), 'name')[0])
tbl_cust = generate.TableGenerator(8, ['STRING','PEOPLE', 'PEOPLE', 'PLACE'], ['Customer ID',... | [
"def create_data(self):\n \n if self.table not in metadata.tables.keys():\n return print(f\"{self.table} does not exist\")\n\n if self.table == \"customers\":\n with engine.begin() as conn:\n for _ in range(self.num_records):\n insert_stmt... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Parse the ADP page HTML and iterate out serializable rows. | def _parse_doc(self, html_doc):
c = itertools.count(start=1)
# load adp page and parse out stats table
doc = html.fromstring(html_doc)
rows = doc.xpath(
'//table[@id="adp_table"]/tr[contains(@class, "contentrow")]')
for row in rows:
text = [v.strip() fo... | [
"def scrap_result_page(html):\n soup = BeautifulSoup(html, \"html.parser\")\n table_div = soup.find(\"div\", {\"id\": Scraper.RESULT_TABLE_ID})\n header_row = True\n for row in table_div.find_all(\"tr\"):\n if header_row:\n header_row = False\n continue\n try:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a dictionary where the keys are the employee ID and the values associate with it are the employees name, salary, and email address | def make_employee_dict(names, ID_numbers, salaries, email_addresses):
d = dict()
for i in range(len(names)):
d[ID_numbers[i]] = Employee(names[i], ID_numbers[i], salaries[i], email_addresses[i])
return d | [
"def employee_id(self):\n for i in self.emp_dict:\n self.emp_id[i] = self.emp_dict[i][0]\n #print(self.emp_id)\n return self.emp_id",
"def create_employee_structure(employees):\n employees_dict = {}\n for employee in position_sort(employees):\n if not employee.is_secre... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return true if subject is serialized | def isDone(self, subject):
return subject in self._serialized | [
"def is_serializable(obj):\n try:\n PickleAppendixEncoder.encode(obj)\n return True\n except:\n return False",
"def serializable() -> bool:\n return False",
"def is_serializable(obj):\n try:\n JsonAppendixEncoder.encode(obj)\n re... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the number of times this node has been referenced in the object position | def refCount(self, node):
return self._references.get(node, 0) | [
"def count_ref(self, reference: str) -> int:\r\n return self.part_count[reference]",
"def visit(self, node):\n if node.getName() == \"$ref\":\n self.cnt = self.cnt + 1",
"def _obj_refcount(self, obj):\n cnt = 1 if (obj is self) else 0\n for subm in self.submembers():\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Build a hash key by predicate to a list of objects for the given subject | def buildPredicateHash(self, subject):
properties = {}
for s,p,o in self.store.triples((subject, None, None)):
oList = properties.get(p, [])
oList.append(o)
properties[p] = oList
return properties | [
"def build_predicate_index(self):\n self.predicate_index = {}\n for pred_grounding in self.body:\n if pred_grounding['name'] not in self.predicate_index:\n self.predicate_index[pred_grounding['name']] = []\n # print \"debug\", pred_grounding\n self.predi... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Take a hash from predicate uris to lists of values. Sort the lists of values. Return a sorted list of properties. | def sortProperties(self, properties):
# Sort object lists
for prop, objects in properties.items():
objects.sort()
# Make sorted list of properties
propList = []
seen = {}
for prop in self.predicateOrder:
if (prop in properties) and (prop not in se... | [
"def sortObjectList(source, prop):\n\n source.sort(key = attrgetter(prop))\n return source",
"def test_key_order_property_sorter(\n properties: list[str], expected: list[str]\n ) -> None:\n result = sorted(properties, key=functools.cmp_to_key(task_property_sorter))\n assert e... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Mark a subject as done. | def subjectDone(self, subject):
self._serialized[subject] = True | [
"def mark_done(self):\n self.done = True",
"def mark_as_done(self):\n self.status = \"DONE\"",
"def isDone(self, subject):\n return subject in self._serialized",
"def completed(self, completed):\n\n self._completed = completed",
"def action_set_done(self):\n self.ensure_on... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns indent string multiplied by the depth | def indent(self, modifier=0):
return (self.depth+modifier)*self.indentString | [
"def indent(depth):\n return DELIM * 2 * depth",
"def _indent(cls, depth: int) -> str:\n return cls.PREFIX * (depth + 1)",
"def _str_indented(self, depth: int) -> str:\n if self.is_empty():\n return ''\n else:\n answer = depth * ' ' + str(self._root) + '\\n'\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Write text in given encoding. | def write(self, text):
self.stream.write(text.encode(self.encoding, 'replace')) | [
"def write(text, filename, encoding='utf-8', mode='wb'):\r\n text, encoding = encode(text, encoding)\r\n with open(filename, mode) as textfile:\r\n textfile.write(text)\r\n return encoding",
"def write_text(self, text):\n self.write(self.render_text(text))",
"def write_text(self, data, en... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function will delete the article | def delete(self, request, slug=None, **kwargs):
article_delete = self.get_object()
article_delete.delete()
return Response({"message": {"Article was deleted successful"}},
status.HTTP_200_OK) | [
"def delete_article(self, selection_article_id):\n self.flush_articles(delete=True, selection_article_id=selection_article_id)",
"def delete_article(request):\n try:\n articles = request.POST.getlist('article_id')\n Article.objects.filter(pk__in=articles).delete()\n ActionLogger().l... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
THis function will update no of reads on an article by user | def update_read(self, article):
read_statistics = ReadingStatistics.objects.filter(
user=self.request.user, article=article)
if read_statistics:
read_time = read_statistics[0].article.read_time
read_time_int = int(read_time.split(' ')[0]) * 60
no_sec = rea... | [
"def update_author_views(cls, article=None, author=None, action='views'):\n query_field = article.author if article else author\n\n owner = ReadStats.objects.get(user=query_field)\n\n if action == 'views':\n owner.views += 1\n else:\n owner.reads += 1\n owner... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Overriding queryset to get only the article ratings | def get_queryset(self):
return ArticleRating.objects.filter(article=self.get_object()) | [
"def get_ratings(self):\n return Vote.objects.filter(content_type=self.get_content_type(), object_id=self.instance.pk, key=self.field.key)",
"def get_ratings(self):\n return self.ratings",
"def ratings(self):\n return self._ratings",
"def with_rating(self):\n return self.annotate(\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
>>> check_adj('самий вищий') ['❌ самий вищий\n✔️ потрібно використовувати префікс най'] >>> check_adj('сама краща', 'самі веселі') ['❌ сама краща\n✔️ потрібно використовувати префікс най', '❌ самі веселі\n✔️ потрібно використовувати префікс най'] >>> check_adj('саме довге') ['❌ саме довге\n✔️ потрібно використовувати п... | def check_adj(message: str) -> list:
result = []
sentence = message.lower().replace(',', '').split(' ')
for i in range(len(sentence) - 1):
if sentence[i] in {'самий', 'сама', 'самі'}:
check_word = sentence[i + 1]
check = morph.parse(check_word)[0]
if check.tag.POS... | [
"def get_adj(self, line):\n nlp = spacy.load(\"en_core_web_sm\")\n for token in nlp(line):\n if token.pos_ == \"ADJ\":\n return token.text",
"def checkGuide(seq, plen, pam, rpam, is_upstream_pam):\n if is_upstream_pam:\n if pam.match(seq[:plen]):\n yiel... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Parse json settings from file. | def parse_json_settings(file: str):
with open(file) as f:
return json.load(f) | [
"def _parse_settings(self, settings_path: str):\n try:\n with open(settings_path, 'r') as settings_fp:\n self.settings = json.load(settings_fp)\n except IOError as error:\n errmsg = (\n 'error: failed to open file \\'{fname}\\': '\n '{... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Parse websites settings from file. | def parse_websites_settings(file: str):
with open(file) as f:
data = json.load(f)
return mapping_to_website(data) | [
"def read_settings(site_name):\n siteid = _get_site_id(site_name)\n if siteid is None:\n raise FileNotFoundError('no_site')\n # cur = conn.cursor(cursor_factory=pgx.RealDictCursor)\n # querystring = 'select count(*) from sites where sitename = %s', (site_name,))\n # if cur.fetchone()['count'] ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Mapping map data to Website structs. | def mapping_to_website(data: list) -> [Website]:
return [
Website(
url=site['url'],
check_interval=site['check_interval'],
regexp_pattern=site['regexp_pattern'],
) for site in data
] | [
"def site_map(url):\n\n links = get_data_url(url)\n\n if links is None or len(links) == 0:\n return\n\n tmp_links = set()\n while True:\n for link in links:\n crawled = get_data_url(link)\n if crawled is not None and len(crawled) > 0:\n for crawl in cra... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |