query stringlengths 9 9.05k | document stringlengths 10 222k | negatives listlengths 19 20 | metadata dict |
|---|---|---|---|
Applies each NER model passed in `ners` on `query`, taking the union set of their predictions. Ignores various types of entities not useful for the business case. | def apply_ners(query, ners):
ignore = ['CARDINAL', 'DATE', 'MONEY', 'ORDINAL', 'PERCENT', 'QUANTITY', 'TIME']
if not isinstance(ners, Iterable):
ners = [ners]
preds = set()
for ner in ners:
pred = ner(query)
preds.update({e.text for e in pred.ents if e.label_ not in ignore})
... | [
"def _process_related_model_searches(query: dict) -> dict:\n multi_terms = {\n \"collections\": \"collection\",\n \"publishers\": \"publisher\",\n \"repositories\": \"repository\",\n \"original_coverages\": \"coverage\",\n \"subjects\": \"subject\",\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Filters `df` by `tags` and streamlines DataFrame appearance in the UI, depending on whether `df` contains query or expert data. | def show_df_by_tags(df, tags):
return st.dataframe(filter_df(df, tags)) if not 'Expert' in df.columns else st.dataframe(filter_df(df, tags), height=150, width=450) | [
"def hacky_tagging(df):\n\n df['tag'] = 'none' # add tag column (set to 'none' by default)\n\n df_rtemp = df.query('name == \"ROOMTEMP\"') # tag 'room_temp'\n df.loc[df_rtemp.index, 'tag'] = 'room_temp'\n\n df_rvalve = df.query('name == \"R VALVE\"') # tag 'valve'\n df.loc[df_rvalve.index, 'tag'] ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
get a canonical for a specific contentid | def get_canonical(self, id):
canonical = None
if id in self.canonicals:
canonical = self.canonicals[id]
return canonical | [
"def get_canonical(self, request):\n if self.is_canonical():\n return self\n else:\n if self.canonical:\n obj = BaseContent.objects.get(pk=self.canonical.id)\n if self.has_permission(request.user, \"view\"):\n return obj\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
add a canonical there is a usecase where the id can already exist on the OOBTree | def add_canonical(self, id, canonical):
if not self.canonicals.insert(id, canonical):
# We are going to remove the language on a old canonical
# so we need to check if the canonical has other translation active
# before removing it
canonical_old = self.get_canonic... | [
"def get_canonical(self, id):\n canonical = None\n if id in self.canonicals:\n canonical = self.canonicals[id]\n return canonical",
"def make_content_id_unique(self):\n is_node_original = self.original_source_node_id is None or self.original_source_node_id == self.node_id\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Run a Caffe network on an input image after preprocessing it to prepare it for Caffe. | def caffe_preprocess_and_compute(pimg, caffe_transformer=None, caffe_net=None,
output_layers=None):
import caffe # noqa
if caffe_net is not None:
# Grab the default output names if none were requested specifically.
if output_layers is None:
output_... | [
"def caffe_preprocess_and_compute(pimg, caffe_transformer=None, caffe_net=None,\n output_layers=None):\n if caffe_net is not None:\n\n # Grab the default output names if none were requested specifically.\n if output_layers is None:\n output_layers = caffe_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the frequency_type of this MonthlyScheduleParameters. | def frequency_type(self, frequency_type):
allowed_values = ["day-of-month", "last-day-of-month", "custom"] # noqa: E501
if frequency_type not in allowed_values:
raise ValueError(
"Invalid value for `frequency_type` ({0}), must be one of {1}" # noqa: E501
.fo... | [
"def schedule_type(self, schedule_type):\n\n self._schedule_type = schedule_type",
"def recurrence_type(self, recurrence_type):\n allowed_values = [\"MONTHLY\", \"WEEKLY\"] # noqa: E501\n if recurrence_type not in allowed_values:\n raise ValueError(\n \"Invalid valu... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the day_of_month of this MonthlyScheduleParameters. | def day_of_month(self, day_of_month):
self._day_of_month = day_of_month | [
"def day_of_month(self, day_of_month):\n if day_of_month is None:\n raise ValueError(\"Invalid value for `day_of_month`, must not be `None`\") # noqa: E501\n\n self._day_of_month = day_of_month",
"def monthly_day(self, monthly_day):\n\n self._monthly_day = monthly_day",
"def bil... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the week_of_month of this MonthlyScheduleParameters. | def week_of_month(self, week_of_month):
allowed_values = ["first", "second", "third", "fourth", "last"] # noqa: E501
if week_of_month not in allowed_values:
raise ValueError(
"Invalid value for `week_of_month` ({0}), must be one of {1}" # noqa: E501
.format(... | [
"def week_of_month(self, week_of_month):\n allowed_values = [\"FIRST\", \"SECOND\", \"THIRD\", \"FOURTH\", \"LAST\"] # noqa: E501\n if week_of_month not in allowed_values:\n raise ValueError(\n \"Invalid value for `week_of_month` ({0}), must be one of {1}\" # noqa: E501\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the day_of_week of this MonthlyScheduleParameters. | def day_of_week(self, day_of_week):
allowed_values = ["sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday"] # noqa: E501
if day_of_week not in allowed_values:
raise ValueError(
"Invalid value for `day_of_week` ({0}), must be one of {1}" # noqa: E501
... | [
"def day_of_week(self, day_of_week):\n if day_of_week is None:\n raise ValueError(\"Invalid value for `day_of_week`, must not be `None`\") # noqa: E501\n\n self._day_of_week = day_of_week",
"def day_of_week(self, day_of_week):\n allowed_values = [\"MONDAY\", \"TUESDAY\", \"WEDNESD... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the months of this MonthlyScheduleParameters. | def months(self, months):
allowed_values = ["january", "feburary", "march", "april", "may", "june", "july", "august", "september", "october", "november", "december"] # noqa: E501
if not set(months).issubset(set(allowed_values)):
raise ValueError(
"Invalid values for `months`... | [
"def monthly_schedule_parameters(self, monthly_schedule_parameters):\n\n self._monthly_schedule_parameters = monthly_schedule_parameters",
"def _set_scaling_months(self,\r\n months):\r\n self.months = months",
"def setMonth(self, *args):\n return _libsbml.Date_set... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function built to load up private_link url string | def private_link_loader():
with open(Default_Location + Default_File, 'r') as f:
private_link = f.readline()
link_string = private_link.split('=')[1].replace("'", "").strip()
f.close()
return link_string | [
"def _associated_private_url(public_id):\n return _make_url(\"public/{}/associated_private_ids\", public_id)",
"def _associated_public_url(private_id):\n return _make_url(\"private/{}/associated_public_ids\", private_id)",
"def make_link(id_: str, is_public: bool):\n return id_[:8] if is_public els... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Mighty Ape private Wishlist web scraper function Scraper for parsing Might Ape private wishlist. Set up to build skeleton html code for each item to be output on webpage | def grab_mApe_wishList(id_string) :
returned_data = ""
mape_wishList_url = 'https://www.mightyape.co.nz/wishlist/'+id_string
print("Grabbing results from:",mape_wishList_url)
page = requests.get(mape_wishList_url)
print("Status:",page.status_code)
#print(page.content)
tree = html.fromstring(... | [
"def wishlist_games(self, wurl):\n wished = []\n count = 0\n sale = 0\n # get our wishlist url so we can make our get request\n request = requests.get(wurl)\n\n # take our returned request (raw html) and turn it into soup\n soup = BeautifulSoup(request.text)\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Find the repeating part of a fraction's decimal equivalent. | def repeating_decimal(numerator, divisor, min_length=5):
getcontext().prec = 10000
number_string = str(Decimal(numerator) / Decimal(divisor))[:-2]
size, stop_looking_size, found = min_length - 1, len(number_string) / 2, None
def trailing_chunks(length):
"""Return last two substrings of the give... | [
"def fraction(n: int, m: int):\n fr = str(n / m)\n integer, decimal = fr.split('.')\n # Check for repeating digits\n repeating = ''\n seen = set()\n # Iterate over decimal part\n for num in decimal:\n # Add new numbers to set and pattern string\n if num not in seen:\n r... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
function that counts linenumbers, and estimates the of comments in the supplied C++ sourceFile. The function returns a tuple with the format (numLines, numComments). | def analyzeCppCode(self, sourceFile):
numLines = 0 # Number of lines of code
numComments = 0 # Number of comments in the code
f=self.openFile(sourceFile)
for line in f:
numLines += 1;
loc = 0
while (loc != -1): #count the # of times t... | [
"def count(file_path):\r\n comment_line = 0\r\n blank_line = 0\r\n multi_comment_flag = False\r\n\r\n with open(file_path, \"r\") as f:\r\n for line in f.readlines():\r\n if line.startswith(\"#\"):\r\n comment_line += 1\r\n elif line.strip().startswith('\"\"\"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
function that counts linenumbers, and estimates the of comments and of tokens in the supplied Python sourceFile. The function returns a tuple with the format (numLines, numDocStr, numComments, numDefs, numClasses). | def analyzePythonCode(self, sourceFile):
numLines = 0 # Number of lines of code
numDocStr = 0 # Number of doc strings in code
numComments = 0 # Number of comments in the code
numDefs = 0 # Number of functions
numClasses = 0 # Number of classes
... | [
"def analyzeCppCode(self, sourceFile):\n numLines = 0 # Number of lines of code\n numComments = 0 # Number of comments in the code\n\n f=self.openFile(sourceFile)\n for line in f:\n numLines += 1;\n loc = 0\n while (loc != -1): #count the... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
create the html header in the supplied outputFile | def _MakeHtmlHeader(self, outputFile, language, title="AutoGrader", header_text=""):
if language == 'C++':
brush = shBrushCpp_js
if language == 'Python':
brush = shBrushPython_js
html_header = '''
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "htt... | [
"def common_html_header(outfile: TextIO, title: str, indexpath: str = \"\") -> None:\n common_header_part1(outfile, title, indexpath=indexpath)\n common_header_part2(outfile, indexpath=indexpath)",
"def generate_file():\n print(\"\\nGenerating the HTML file\")\n html = html_header.format(directory=arg... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
function that appends the first maxNumLines lines or first maxNumBytes bytes (whichever is smaller) from sourceFile to destFile. | def _fileHead(self, sourceFile, destFile, maxNumLines, maxNumBytes):
#os.system('head -n ' + str(numLines) +' "' + sourceFile +'" >> "' + destFile + '"')
os.system('head -c ' + str(maxNumBytes) + ' "' + sourceFile + '" | head -n ' + str(maxNumLines) + ' >> "' + destFile + '"') | [
"def copyfileobj(self, fsrc, fdst, length=(16*1024)):\n fsrcRead = fsrc.read\n fdstWrite = fdst.write\n while True:\n buf = fsrcRead(length)\n if not buf:\n break\n fdstWrite(buf)\n self.progressCallback(len(buf))",
"def truncate_text... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
function that gets and reports source code analytics to the destination file in the specified format (AutoGrader.Const.TEXT or AutoGrader.Const.HTML) | def _reportFileAnalytics(self, sourceFiles, outputFile, language):
#is this a single file or a set of files?
bSingleFile = len(sourceFiles) == 1
#open the output file for appending
f=self.openFile(outputFile, "a") #open for appending
f.write ('<font face="ver... | [
"def script_generator(self):\n analyze_tool = \"/home/haihuam/Projects/RepPoints/mmdetection/tools/analyze_logs.py\"\n ex_options = self.global_setting.get('analyze_options', str())\n py = self.global_setting.get('python', sys.executable)\n if os.access(py, os.X_OK):\n content... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
function that reports execution time to the output file in the specified format (AutoGrader.Const.TEXT or AutoGrader.Const.HTML) | def _reportExecTime(self, exec_time, outputFile):
f=self.openFile(outputFile, "a") #open for appending
f.write ('<font face="verdana" color="' + AutoGrader.Const.ANALYTICS_COLOR2 + '">[Execution Time: ' + format("%0.4f" % exec_time) + ' sec.]</font><br>\n')
f.close() | [
"def render_timing_report(self):\r\n report = ('Timing report\\n'\r\n '=============\\n')\r\n for phase, timings in self.timings.items():\r\n phase_time = None\r\n for goal, times in timings.items():\r\n if len(times) > 1:\r\n report += '[%(phase)s:%(goal)s(%(numsteps)d)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
function that reports the name of the input data file to the outputFile in the specified format. dataFileName = the name of the data file to be reported in the output file outputfile = the name of the output file (this is the same file that receives stdout and stderr from the executed script outputFileType = format of ... | def _reportDataFile(self, dataFileName, outputFile):
#subsequent access to the file should be open for "append"-ing
f=self.openFile(outputFile, "a") #open for appending
f.write ('<font face="verdana" color=" ' +AutoGrader.Const.HEADER_COLOR2 + '"><br>\n------------- ' + os.path.split(dataFile... | [
"def save_output(filename, data, **kwargs):\n filename = str(filename)\n if data is None:\n # need to save dummy output to satisfy Snakemake\n with open(filename, 'w') as fh:\n pass\n return\n \n if filename.endswith('.tif'):\n return save_tif(filename, data, **kwa... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
function that prints a separator in the output file | def _printSeparator(self, filePointer, color=Const.HEADER_COLOR1):
filePointer.write ('<font face="verdana" color=" ' + color + '"><br>\n=======================================================</font><br>\n') | [
"def output_sep_mark():\n print(sep_mark)",
"def _print_separator():\n print(\n \"───── ──────────────── ──────────────────────────────────────────────────────────────────────────────── ──────── ───────── ───── ──────── ──── ──── ──── ──── ──── ──── ──── ──── ──── ────... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
function that prints a separator in the output file after opening the file | def _openFileAndPrintSeparator(self, outputFile, color=Const.HEADER_COLOR1):
f=self.openFile(outputFile, "a") #open for appending
_printSeparator(f, color)
f.close() | [
"def _printSeparator(self, filePointer, color=Const.HEADER_COLOR1):\n filePointer.write ('<font face=\"verdana\" color=\" ' + color + '\"><br>\\n=======================================================</font><br>\\n')",
"def PrintSeparatorLine(self):\n self._output_writer.Write(u'{0:s}\\n'.format(u'-' * ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
function that searches the specified 'directory' for files with the supplied extention. The function returns a list of these files or appends to the supplied foundFiles list. | def _findFilesInDir(self, directory, extension=".py", foundFiles=None):
#mutable default arguments in Python are evaluated once when the function is defined, not each time the function is called.
if foundFiles == None:
foundFiles = []
filenames = os.listdir(directory)
... | [
"def searchfiles(directory, filenames, ext=None):\n if ext:\n filenames = [f'{file}{ext}' for file in filenames]\n return [\n file for file in Path(directory).glob('*')\n if file.name in filenames\n ]",
"def _findFiles(self, topLevelDirectory, extension=\".py\", foundFiles=None):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
function that searches the supplied topLevelDirectory and all subdirectories for files with the supplied extention. The function returns a list of these files or appends to the supplied foundFiles list. | def _findFiles(self, topLevelDirectory, extension=".py", foundFiles=None):
#mutable default arguments in Python are evaluated once when the function is defined, not each time the function is called.
if foundFiles == None:
foundFiles = []
for dirpath, dirnames, filen... | [
"def _findFilesInDir(self, directory, extension=\".py\", foundFiles=None):\n\n #mutable default arguments in Python are evaluated once when the function is defined, not each time the function is called.\n if foundFiles == None:\n foundFiles = []\n \n filenames = os.listdir... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
function that searches the supplied topLevelDirectory and all subdirectories for files with the supplied extention. The function returns a list of these files in the toplevel directory (self.TopLevelFilesFound) along with a list of subdirectories containing these files (self.SubDirsFound). | def _recursivelyFindFiles(self, topLevelDirectory, extension=".py"):
print ('finding ' + extension + '...\n')
tempFilesFound = []
tempSubDirs = {} #initialize temporary dictionary of sbudirectories
for dirpath, dirnames, filenames in os.walk(topLevelDirectory):
#p... | [
"def _findFiles(self, topLevelDirectory, extension=\".py\", foundFiles=None):\n \n #mutable default arguments in Python are evaluated once when the function is defined, not each time the function is called.\n if foundFiles == None:\n foundFiles = []\n \n for dirpath, di... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
function that searches the supplied topLevelDirectory and all subdirectories for a file with the supplied filename. The function returns a list of these subdirectories. | def _recursivelyFindFile(self, topLevelDirectory, filename):
print ('finding ' + filename + '...\n')
tempSubDirs = {} #initialize temporary dictionary of sbudirectories
for dirpath, dirnames, filenames in os.walk(topLevelDirectory):
#print '---dirpath---'
#pri... | [
"def _findFiles(self, topLevelDirectory, extension=\".py\", foundFiles=None):\n \n #mutable default arguments in Python are evaluated once when the function is defined, not each time the function is called.\n if foundFiles == None:\n foundFiles = []\n \n for dirpath, di... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
TestDataFiles list of test data files as full path strings sourceDirectory top level directory containing .py files (all sub directories will be searched) soruceFilename specifies the name of the .py file to search and execute. Set to "" or None to search/execute all .py files in the sourceDirectory. OutputFile destina... | def processFiles(self, testDataFiles, sourceDirectory, sourceFilename, outputFile, language, IncludeSourceInOutput, maxRunTime, interpreter, maxOutputLines, AutoGraderVersion):
print ("***Start***")
self.sourceDirectory = sourceDirectory
#self.TopLevelFilesFound = []
#self.subdi... | [
"def collect_and_run_test_files():\n test_dirs = glob.glob(\"./test/*/\")\n for test_dir in test_dirs:\n if test_dir.startswith(\"__\"):\n # Excludes __pycache__\n continue\n py_files = [f for f in glob.glob(test_dir + \"*\") if f.endswith(\".py\")]\n if not py_files... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Parse the returned assertion and extract the authorized roles | def get_roles(assertion):
awsroles = []
root = ET.fromstring(base64.b64decode(assertion))
for attr in root.iter('{urn:oasis:names:tc:SAML:2.0:assertion}Attribute'):
if attr.get('Name') == 'https://aws.amazon.com/SAML/Attributes/Role':
for value in attr.iter('{urn:oasis:names:tc:SAML:2.0:... | [
"def parse_roles_from_assertion(assertion):\n roles = []\n xml = base64.b64decode(assertion)\n root = ElementTree.fromstring(xml)\n role = 'https://aws.amazon.com/SAML/Attributes/Role'\n attr_base = '{urn:oasis:names:tc:SAML:2.0:assertion}Attribute'\n attr_value = '{}Value'.format(attr_base)\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
From given row id, return url that associated with it | def get_url_name(self, row_id):
return self.con.execute(
"SELECT url FROM urllist WHERE rowid={}".format(row_id)
).fetchone()[0] | [
"def getUrl(row):\n\n if row[\"url\"]:\n # Filter out API reference links\n urls = [url for url in row[\"url\"].split(\"; \") if \"https://api.\" not in url]\n if urls:\n return urls[0]\n\n # Default to DOI\n return \"https://doi.org/\" + row[\"d... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Explode a path into all its little giblets. _path_ should ideally be normalized first | def explode(self, path):
log(6, "explode")
gibs = []
head = path
while True:
if head == "/":
gibs.insert(0, head)
break
head, tail = os.path.split(head)
gibs.insert(0, tail)
return gibs | [
"def split_path(path):\n\n if type(path) != str:\n return []\n\n # replace multiple occurrences of \"/\" with just one,\n # i.e. \"page1//page2///page3\" -> \"page1/page2/page3\"\n path = re.sub('/+', '/', path)\n path = path.split(\"/\") # form a list of path steps\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The fuse filesystem is being destroyed. This means we need to unmount everything | def fsdestroy(self):
log(6, "fsdestroy")
try:
self.unmount_all()
log(1, "Finished unmounting all objects")
except Exception, ex:
log(1, "Exception while unmounting all: %s" % str(ex))
log(0, "AutoMounterManager stopped") | [
"def unmount(self, mount_point):\n self.fs.remove_nfs_share()\n self.fs.status()\n if self.fs.state == service_states.RUNNING or self.fs.state == service_states.SHUTTING_DOWN:\n log.debug(\"Unmounting volume-based FS from {0}\".format(mount_point))\n if self.fs._is_mounted... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Records the status after checking if the status is still valid because we might have manually changed it. If the status is "aborted" this will raise an exception | def _set_status(self):
result = self._get_status()
if result and result[0]['state'] == 'aborted':
raise Exception("Aborted because the status flag is set to 'aborted' in dynamodb")
# record the status
self.status['timestamp'] = time.strftime("%Y-%m-%dT%H:%M:%SZ")
sel... | [
"def status(self, status):\n self.__status = status",
"def update_status(self, status: str) -> None:\n initial_status = self._status\n if status not in (\n feconf.ALLOWED_TRAINING_JOB_STATUS_CHANGES[initial_status]):\n raise Exception(\n 'The status ch... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Checks if a resource has changed. The resource is considered changed if the modified_at value is newer than what's found in the tS catalog. | def _has_resource_changed(self, pid, lid, rid, modified_at):
# Check the language first
# TODO: this is dangerous, because it could accidentally hide resources that have
# been updated, but are not the most recent within the language or project.
# This would occur if content is created... | [
"def _has_project_changed(self, pid, modified_at):\n # look up the existing project entry\n if not self.ts_projects_cache:\n self.ts_projects_cache = self.get_url('https://cdn.door43.org/v2/ts/catalog.json', True)\n\n if not self.ts_projects_cache:\n # The cache could not ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Checks if a language has changed. The project is considered changed if the modified_at value is newer than what's found in the tS catalog. | def _has_language_changed(self, pid, lid, modified_at):
if not self._has_project_changed(pid, modified_at):
return False
# look up the existing language entry
cache_key = pid
if cache_key in self.ts_languages_cache:
ts_languages = self.ts_languages_cache[cache_ke... | [
"def _has_project_changed(self, pid, modified_at):\n # look up the existing project entry\n if not self.ts_projects_cache:\n self.ts_projects_cache = self.get_url('https://cdn.door43.org/v2/ts/catalog.json', True)\n\n if not self.ts_projects_cache:\n # The cache could not ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Checks if a project has changed. The project is considered changed if the modified_at value is newer than what's found in the tS catalog. | def _has_project_changed(self, pid, modified_at):
# look up the existing project entry
if not self.ts_projects_cache:
self.ts_projects_cache = self.get_url('https://cdn.door43.org/v2/ts/catalog.json', True)
if not self.ts_projects_cache:
# The cache could not be built, s... | [
"def _has_language_changed(self, pid, lid, modified_at):\n if not self._has_project_changed(pid, modified_at):\n return False\n\n # look up the existing language entry\n cache_key = pid\n if cache_key in self.ts_languages_cache:\n ts_languages = self.ts_languages_ca... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Retrieves the catalog status from AWS or generates a new status object | def _get_status(self):
status_results = self.db_handler.query_items({
'api_version': {
'condition': 'is_in',
'value': ['3', TsV2CatalogHandler.api_version]
}
})
source_status = None
status = None
for s in status_results:
... | [
"def check_for_existing_catalog(ip_address, headers):\n url = 'https://%s/api/UpdateService/Catalogs' % ip_address\n cat_response = requests.get(url, headers=headers, verify=False)\n if cat_response.status_code == 200:\n cat_json_resp = cat_response.json()\n if cat_json_resp['@odata.count'] >... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Converts a tsv tN to json This will write a bunch of files and return a list of files to be uploaded. Chunk definitions will be used to validate the note organization. | def _tn_tsv_to_json_file(self, lid, rid, resource, format, temp_dir):
rc_dir = None
tn_uploads = {}
for project in resource['projects']:
pid = Handler.sanitize_identifier(project['identifier'])
# skip re-processing notes that have not changed
if not self._ha... | [
"def tsv_to_json(tsv_file, json_file):\n import csv\n import json\n\n try:\n with open(tsv_file, 'r') as tsvFile:\n file_reader = csv.DictReader(tsvFile, dialect='excel-tab')\n row_list = list(file_reader)\n with open(json_file, 'w+') as jsonFile:\n jsonFile.w... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Converts a markdown tN to json This will write a bunch of files and return a list of files to be uploaded. Chunk definitions will be used to validate the note organization. | def _tn_md_to_json_file(self, lid, rid, resource, format, temp_dir):
rc_dir = None
# dc = manifest['dublin_core']
note_general_re = re.compile('^([^#]+)', re.UNICODE)
note_re = re.compile('^#+([^#\n]+)#*([^#]*)', re.UNICODE | re.MULTILINE | re.DOTALL)
tn_uploads = {}
for... | [
"def _tn_tsv_to_json_file(self, lid, rid, resource, format, temp_dir):\n rc_dir = None\n tn_uploads = {}\n\n for project in resource['projects']:\n pid = Handler.sanitize_identifier(project['identifier'])\n\n # skip re-processing notes that have not changed\n if... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Uploads an array or object of uploads | def _upload_all(self, uploads):
for upload in uploads:
if isinstance(upload, dict):
self._upload(upload)
elif upload in uploads and isinstance(uploads[upload], dict):
self._upload(uploads[upload])
else:
raise Exception('invalid ... | [
"def uploadData(self):",
"def upload(self, container, name, fileobj, metadata=None):",
"def handle_upload(request):\n results = []\n for name, fieldStorage in request.FILES.items():\n if type(fieldStorage) is unicode:\n continue\n result = {}\n result['name'] = re.sub(r'^.*... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Adds supplementary helps to the catalog nodes | def _add_supplement(self, catalog, language, resource, project, modified, rc_type):
lid = TsV2CatalogHandler.sanitize_identifier(language['identifier'], lower=False)
if rc_type == 'help':
pid = TsV2CatalogHandler.sanitize_identifier(project['identifier'])
# tricky some language... | [
"def addHelp(self, help):\n if help not in self.help:\n self.help.append(help)",
"def apply_toolbox_descriptions(self):\n self.set_description_in_xml(self.toolbox.description)\n self.set_summary_in_xml(self.toolbox.summary)\n\n # and do tools too\n for t in self.tools... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Initializes a node in the catalog. | def _init_catalog_node(catalog, pid, lid=None, rid=None):
if pid not in catalog: catalog[pid] = {'_langs': {}}
if lid is not None:
if lid not in catalog[pid]['_langs']: catalog[pid]['_langs'][lid] = {'_res': {}, 'language': {}}
if lid is not None and rid is not None:
if r... | [
"def __init__(self):\n self.initial_node = Node.Node()",
"def __init__(self, node: Dict):\n self._node = node",
"def __init__(self, nodes=None):\n # TODO",
"def __init__(self):\n\n\t\tself.root = None\n\t\tself.numNodes = 0",
"def testInit(self):\n\n self.assertEqual(\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Removes the last ratelimit rest time file | def _remove_last_reset(self):
if os.path.exists(Flag._PATH):
logger.id(logger.debug, self,
'Removing ratelimit reset time file \'{path}\' ...',
path=Flag._PATH,
)
try:
os.remove(Flag._PATH)
except (IOError,... | [
"def sleepshop(self):\n from datetime import datetime\n now = datetime.now()\n for filename, timestamp in dict(self.temp_files).iteritems():\n if now - timestamp > self.max_allowed_age:\n del self.temp_files[filename]",
"def _drop_old_data(self, current_time):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
If the reset_time is a positive value > 0, then this will set the internal event flag and assign the given value. If the reset_time is negative or zero then this will assign the value to 0.0 and clear the flag. | def value(self, reset_time):
# XXX: I'm not 100% sure locking is necessary. I suppose logging could
# become a bit confusing if 2+ processes raced in setting the value
# without it.
with self.__lock:
if (
isinstance(reset_time, integer_types + (float,))
... | [
"def hard_reset(self, reset_pin):\n # tDRESET, tRESET, figure 7 in datasheet\n if reset_pin is not None:\n reset_pin.value(0)\n utime.sleep_ms(1) #\n reset_pin.value(1)\n utime.sleep_ms(2) # tSTART, figure 7 in datasheet",
"def reset(self):\n if s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Waits the remaining ratelimit time, if any. event ({threading,multiprocessing}.Event, optional) The object to use to wait out the remaining time (with the object's .wait attribute). If this is not specified, waiting will take place with time.sleep (meaning processes will become unresponsive during the wait period). | def wait_out_ratelimit(self, event=None):
delay = self.remaining
if delay > 0:
if not (event or hasattr(event, 'wait')):
logger.id(logger.debug, self,
'No \'wait\' method found for event=\'{event}\'!'
' Using time.sleep ...',
... | [
"def _wait(self, args, now, cap, consumed_history, consumed_capacity):\n for key in [\"read\", \"write\"]:\n if key in cap and cap[key] > 0:\n consumed_history[key].add(now, consumed_capacity[key])\n consumed = consumed_history[key].value\n if consumed ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Handles a reddit ratelimit queued private massage Returns True if the pm was attempted | def _handle_pm(self, to, subject, body):
logger.id(logger.info, self,
'Sending pm \'{subject}\' to {color_to} ...',
subject=subject,
color_to=to,
)
success = self._reddit.do_send_pm(to, subject, body, self._killed)
if success or success is... | [
"def praw_timer(reddit):\n\n if reddit.auth.limits['remaining'] < 10:\n print(\"Waiting for PRAW API limit to reset...\", end=\"\\r\")\n time.sleep(4)",
"def _is_limited(request, rate, rl):\n def inner(*args, **kwargs):\n is_limited = rl.is_limited(*args, **kwargs)\n\n if is_limi... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Handles a reddit ratelimit queued reply Returns True if a reply was attempted for the thing | def _handle_reply(self, fullname, body):
handled = False
thing = self._reddit.get_thing_from_fullname(fullname)
if thing:
logger.id(logger.info, self,
'Processing {color_thing} ...',
color_thing=reddit.display_id(thing),
)
... | [
"def process_refill_questionnaire_response(self, sender, message, response):\n\t\tnow = datetime.datetime.now()\n\t\tmessage.datetime_responded = now\n\t\tmessage.save()\n\n\t\tdef process_response(return_message_type):\n\t\t\tfor feedback in message.feedbacks.all():\n\t\t\t\tfeedback.note = Message.REFILL_QUESTION... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Handles a reddit ratelimit queued submit Returns True if a submit was attempted | def _handle_submit(self, display_name, title, selftext, url):
logger.id(logger.info, self,
'Posting \'{title}\' to {subname} ...',
title=title,
subname=display_name,
)
if selftext:
logger.id(logger.debug, self,
'self... | [
"def checkSubmissions(limit=submission_read_limit):\n submissions = subreddit.get_new(limit=limit)\n internal_count = 0\n\n print(\"\\n---\\n%s - Checking latest submissions...\" % (datetime.now()))\n for submission in submissions:\n if submission.id in already_processed:\n print(\"%s - Skipping previou... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Add movie validation func | def add_movie_validation(movie):
if len(movie['title']) < 7:
raise ValueError('title must contain more than 7 characters')
if len(movie['year']) != 4:
raise ValueError('invalid year')
return AddMovie(movie['title'], movie['year']).add_movie_to_db() | [
"def validate_video(video):\n # check is correct format use extentions\n ext = os.path.splitext(video.name)[1].lower()\n if ext not in settings.VIDEO_EXT:\n raise ValidationError('Неверный формат видео.')\n # check maximum file size\n if not (settings.VIDEO_MIN_SIZE < video.size < settings.VID... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generates two concentric circular clusters. | def concentric_clusters(N = 1000, r1 = 1, r2 = 5, w1 = 0.8, w2 = 1.0/3, arms = 64):
#Number of samples in each cluster
N1 = int(np.floor(1.0*N/2))
N2 = N - N1
phi1 = np.random.rand(N1,1) * 2 * np.pi;
dist1 = r1 + 1.0*(np.random.randint(0,5,size =(N1,1)))/5*w1*r1
d1x = dist1* np.cos(phi... | [
"def connect_two_circles(c1, c2,\n rest_length=None,\n spring_constant=None,\n stiffness=None,\n tension=None,\n edge_type=None,\n connect_every=1,\n num_s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create a file for a solid image of color | def generate_image_file(color):
img = generate_image(color)
img.save(IMAGE_FILE)
return IMAGE_FILE | [
"def make_image_file(\n file_format: str,\n color_space: str,\n width: int,\n height: int,\n) -> io.BytesIO:\n image_buffer = io.BytesIO()\n image = Image.new(color_space, (width, height))\n # If this assertion ever fails, see\n # https://github.com/VWS-Python/vws-test-fixtures for what to d... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get color to start with on boot | def get_initial_color():
if os.path.isfile(DATA_FILE):
with open(DATA_FILE, 'r') as f:
data = f.readline()
print data
return int(data, base=16)
else:
return INITIAL_COLOR | [
"def getColor(self) -> None:\n color = askcolor()\n color = int(color[1][1:], 16)\n self.colorInt.set(color)\n try:\n self.lights.inQ.put_nowait((\"color\", color))\n except multiprocessing.queues.Full:\n pass",
"def get_color(self):\n return self._i... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Subroutine to extract bond label, site indices, and length from a LOBSTER header line. The site indices are zerobased, so they can be easily used with a Structure object. | def _get_bond_data(line):
orb_labs = ["s", "p_y", "p_z", "p_x", "d_xy", "d_yz", "d_z^2",
"d_xz", "d_x^2-y^2", "f_y(3x^2-y^2)", "f_xyz",
"f_yz^2", "f_z^3", "f_xz^2", "f_z(x^2-y^2)", "f_x(x^2-3y^2)"]
line = line.rsplit("(", 1)
# bondnumber = line[0].replac... | [
"def __read_header(self):\n\n # These for loops are consuming a lot of energy !\n # optimise it...!\n\n print ('Reading header file...')\n fname = self.directory + '/SeisHeader_sem2d.hdr'\n data = pd.read_csv(fname, names=('dt','npts','nsta'), delim_whitespace=True, header=0, nrows=1)\n self.dt = ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
get a Structure with Mulliken and Loewdin charges as site properties | def get_structure_with_charges(self, structure_filename):
struct = Structure.from_file(structure_filename)
Mulliken = self.Mulliken
Loewdin = self.Loewdin
site_properties = {"Mulliken Charges": Mulliken, "Loewdin Charges": Loewdin}
new_struct = struct.copy(site_properties=site_p... | [
"def get_site_attrib_template():\n return {\n \"pos\": \"0 0 0\",\n \"size\": \"0.002 0.002 0.002\",\n \"rgba\": \"1 0 0 1\",\n \"type\": \"sphere\",\n \"group\": \"0\",\n }",
"def extract_website_datas(website_container):\n website_info={}\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return limit for query | def get_limit(self):
return self.limit | [
"def _get_limit(self, query, limit): \n if limit < 0:\n raise ValueError(\"Query limit cannot be negative\")\n\n API._last_statement += \".limit(\" + str(limit) + \")\"\n return query.limit(limit)",
"def limit_results() -> int:\n limit = 10\n\n args = request.args\n if... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the current pager's max record limit. | def get_max_record_limit(self):
return self.max_record_limit | [
"def get_limit(self):\n return self.limit",
"def get_max_per_page(self):\n return self.max_per_page",
"def limit_num(self):\n return self._limit_num",
"def get_max_page(connection: DBConnection) -> int:\n return connection.execute(\"SELECT max_page FROM max_page\").fetchone()[0]",
"d... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the current pager's max record limit. | def set_max_record_limit(self, limit):
self.max_record_limit = limit | [
"def set_limit(self, limit: int) -> None:",
"def limit(self, limit):\n self._limit = limit",
"def set_max_per_page(self, max_per_page):\n if max_per_page > 0:\n self.max_per_page = max_per_page\n if self.page == 0:\n self.page = 1\n elif max_per_page == ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the current pager's max link | def get_current_max_link(self):
return self.current_max_link | [
"def max_num_links(self):\n return self._max_num_links",
"def MaximumReservableLink(self):\n if self.force_auto_sync:\n self.get('MaximumReservableLink')\n return self._MaximumReservableLink",
"def get_max_question_block_page(links):\n\n def only_numerics(page_block_no_string)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns an array of page numbers to use in pagination links. nb_links The maximum number of page numbers to return | def get_links(self, nb_links=5):
page = self.page
last_page = self.last_page
links = []
tmp = page - floor(nb_links / 2)
check = last_page - nb_links + 1
if check > 0:
limit = check
else:
limit = 1
if tmp > 0:
if tmp > ... | [
"def getAllPageNumbers(self):\n\t\tfor subpage in self.subpages:\n\t\t\thtmlcontent = self.HttpHandler.getHtmlContentFromLink(subpage.link)\n\t\t\tsoupPage = BeautifulSoup(htmlcontent, \"html.parser\")\n\t\t\tsubpage.setNbrPages( self.getNbrPages(soupPage) )",
"def pages(self):\n return range(1, self.total... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns true if the current query requires pagination. | def have_to_paginate(self):
if self.get_max_per_page() and self.get_nb_results() > self.get_max_per_page():
return True
return False | [
"def isPagination(self):\n if self.theFilter:\n return None != self.theFilter.limit or None != self.theFilter.offset\n return False",
"def _has_next_page(self):\n if self._search_data is None:\n return True\n begin_index = int(self._params['beginIndex'])\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the first index on the current page. | def get_first_indice(self):
if self.page == 0:
return 1
else:
return (self.page - 1) * self.max_per_page + 1 | [
"def get_first_page(self):\n return 1",
"def start_index(self):\n paginator = self.paginator\n # Special case, return zero if no items.\n if paginator.count == 0:\n return 0\n elif self.number == 1:\n return 1\n return (self.number - 2) * paginator.p... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the number of results. | def get_nb_results(self):
return self.nb_results | [
"def number_results(self):\n pass",
"def GetNumberOfResultsProcessed(self) -> int:\n return self.i",
"def get_result_size(self) -> int:\n\n # Modifie the query to count the number of answer\n if self.query.strip().startswith(\"SELECT\") or self.query.strip().startswith(\"select\"):\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the number of results. | def set_nb_results(self, nb):
self.nb_results = nb | [
"def set_NumResults(self, value):\n super(QueryInputSet, self)._set_input('NumResults', value)",
"def number_results(self):\n pass",
"def setCount(self, num):\n self.count=num",
"def result_count(self, result_count):\n\n self._result_count = result_count",
"def with_number_of_rec... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the first page number. | def get_first_page(self):
return 1 | [
"def get_first_indice(self):\n if self.page == 0:\n return 1\n else:\n return (self.page - 1) * self.max_per_page + 1",
"def get_page_start(page_number, page_size):\n if (page_number <= 1):\n return 0\n else:\n start_index = (page_number - 1) * page_size\n\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the last page number. | def get_last_page(self):
return self.last_page | [
"def last_page(self):\n lid = self.paginator.total / self.items_per_page\n if not lid:\n return 1\n if self.paginator.total % self.items_per_page:\n lid += 1\n return lid",
"def get_last_page_num():\r\n\r\n\t\t# Get Parser for the Given URL in the CONFIG to parse ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the last page number. | def set_last_page(self, page):
self.last_page = page
if self.get_page() > page:
self.set_page(page) | [
"def last_page(self, last_page):\n\n self._last_page = last_page",
"def last_page(self):\n if self.is_last_disabled:\n raise PaginationNavDisabled(\"last\")\n self._last.click()",
"def __goToLastPage(self):\n try:\n self.currenturi = self.__baseuri + self.soup.f... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the previous page. | def get_previous_page(self):
return max((self.get_page() - 1), self.get_first_page) | [
"def prev_page(self):\n if self.current_page - 1 >= 1:\n self.current_page -= 1\n return self.get_current_page()\n else:\n return None",
"def previous_page(self):\n \n return self._api.copy(url=URLObject.parse(self.paging.next))",
"def previous_page(s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the maximum number of results per page. | def get_max_per_page(self):
return self.max_per_page | [
"def pagecount(self):\r\n \r\n return len(self.results) // self.perpage + 1",
"def get_max_result_items(self) -> int:\n return int(self.preferences[\"max-results\"])",
"def pages(self):\n if not self.limit:\n return 0 # pragma: no cover\n else:\n return ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the maximum number of results per page. | def set_max_per_page(self, max_per_page):
if max_per_page > 0:
self.max_per_page = max_per_page
if self.page == 0:
self.page = 1
elif max_per_page == 0:
self.max_per_page = 0
self.page = 0
else:
self.max_per_page = 1
... | [
"def pages_max(self, pages_max):\n\n self._pages_max = pages_max",
"def max_results(self, max_results: int):\n\n self._max_results = max_results",
"def max_results(self, max_results):\n\n self._max_results = max_results",
"def set_max_rows(self, max_rows):\n if max_rows >= 1:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns true if on the first page. | def is_first_page(self):
return 1 == self.page | [
"def has_first(self):\n\n return self.page > 2",
"def get_first_page(self):\n return 1",
"def first_page(self):\n if self._start == 0:\n raise ValueError('Already at the first page.')\n self._start = 0",
"def __is_first(self, step=None):\n if not step:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns true if on the last page. | def is_last_page(self):
return self.page == self.last_page | [
"def is_last_page(self):\r\n \r\n return self.pagecount == 0 or self.pagenum == self.pagecount",
"def has_last(self):\n\n return self.page < (self.pages - 2)",
"def is_last_page(self):\n\n return self.pagecount == 0 or self.pagenum == self.pagecount",
"def is_last_page(soup):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Executes quicksort on inputList. | def quicksort(inputList):
if not inputList:
return []
else:
return quicksort(filter(lambda x: x < inputList[len(inputList)/2], inputList))+[inputList[len(inputList)/2]]+quicksort(filter(lambda x: x > inputList[len(inputList)/2], inputList)) | [
"def quick_sort(mylist):\n _inplace_quick_sort(mylist, 0, len(mylist)-1)",
"def quickSort(lst):\n quicksort(lst, 0, len(lst)-1)",
"def _quick_sort(list_of_items):\n # invoke recursive function to recursively split and partition\n _split_and_partition(list_of_items,0,len(list_of_items)-1)\n # retu... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Parallel equivalent of make. Uses multiprocessing.Process as a backend and a Python queue to communicate with the workers. | def parmake(job_list, context, cq,
n=DefaultsToConfig('max_parallel_jobs'),
recurse=DefaultsToConfig('recurse'),
new_process=DefaultsToConfig('new_process'),
echo=DefaultsToConfig('echo')):
publish(context, 'parmake-status', status='Obtaining job list')
job_list ... | [
"def _internal_worker_process(args: typing.Tuple[Queue, Queue, Queue, typing.Callable]) -> None:\n arguments_queue: Queue = args[0]\n result_queue: Queue = args[1]\n target: typing.Callable = args[2]\n log_queue: Queue = args[3]\n log_configurer: typing.Callable = args[4]\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Parallel equivalent of "remake". | def parremake(non_empty_job_list, context, cq,
n=DefaultsToConfig('max_parallel_jobs'),
recurse=DefaultsToConfig('recurse'),
new_process=DefaultsToConfig('new_process'),
echo=DefaultsToConfig('echo')):
# TODO: test this
db = context.get_compmake_db()
non_emp... | [
"def rparmake(job_list, context, cq,\n n=DefaultsToConfig('max_parallel_jobs'),\n new_process=DefaultsToConfig('new_process'),\n echo=DefaultsToConfig('echo')):\n return parmake(job_list=job_list, context=context,\n cq=cq, n=n, new_process=new_process, echo=echo... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Shortcut to parmake with default recurse = True. | def rparmake(job_list, context, cq,
n=DefaultsToConfig('max_parallel_jobs'),
new_process=DefaultsToConfig('new_process'),
echo=DefaultsToConfig('echo')):
return parmake(job_list=job_list, context=context,
cq=cq, n=n, new_process=new_process, echo=echo, recurse=... | [
"def recursive():\n with Local() as tun:\n tun.call(recursive)",
"def parremake(non_empty_job_list, context, cq,\n n=DefaultsToConfig('max_parallel_jobs'),\n recurse=DefaultsToConfig('recurse'),\n new_process=DefaultsToConfig('new_process'),\n echo=DefaultsT... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Receives list of emails and user args. Fetchs API keys from config file using user_args path and cli keys. For each target, launch target.methods() associated to found config artifacts. Handles the hunter.io chase logic with counters from enumerate() | def target_factory(targets, user_args):
finished = []
if user_args.config_file is not None or user_args.cli_apikeys is not None:
api_keys = get_config_from_file(user_args)
else:
api_keys = None
init_targets_len = len(targets)
for counter, t in enumerate(targets):
c.info_news... | [
"def PreProcessArgs( cls, config, method_name, args, kw, extras, lib ):\n \n if method_name in [\"read_user\", \"list_users\"]:\n # good to go \n \n if method_name == \"list_users\" and len(args) == 0:\n # empty query \n args.append({})\n \n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Adapts the specified list of features removing the features matching the specified tags Returns the adapted features list. | def adapt_features_list(self, features_list):
result = []
for features in features_list:
if features[1].lower() not in self.__tagList:
result.append(features)
return result | [
"def set_features(self, features):\r\n for var in self.features:\r\n self.remove_feature(var)\r\n\r\n for var in features:\r\n self.add_feature(var)",
"def apply_features(self, features):\n # feature_values is a multi-dimensional list\n # 1st dimension: Feature (c... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns an activities completed domain object given a activities completed model loaded from the datastore. | def get_completed_activities_from_model(completed_activities_model):
return user_domain.CompletedActivities(
completed_activities_model.id,
completed_activities_model.exploration_ids,
completed_activities_model.collection_ids) | [
"def get_incomplete_activities_from_model(incomplete_activities_model):\n return user_domain.IncompleteActivities(\n incomplete_activities_model.id,\n incomplete_activities_model.exploration_ids,\n incomplete_activities_model.collection_ids)",
"def save_completed_activities(activities_comp... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns an incomplete activities domain object given an incomplete activities model loaded from the datastore. | def get_incomplete_activities_from_model(incomplete_activities_model):
return user_domain.IncompleteActivities(
incomplete_activities_model.id,
incomplete_activities_model.exploration_ids,
incomplete_activities_model.collection_ids) | [
"def save_incomplete_activities(incomplete_activities):\n incomplete_activities_model = user_models.IncompleteActivitiesModel(\n id=incomplete_activities.id,\n exploration_ids=(\n incomplete_activities.exploration_ids),\n collection_ids=(\n incomplete_activities.collect... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns an ExpUserLastPlaythrough domain object given an ExpUserLastPlaythroughModel loaded from the datastore. | def get_last_playthrough_information(last_playthrough_model):
return user_domain.ExpUserLastPlaythrough(
last_playthrough_model.user_id,
last_playthrough_model.exploration_id,
last_playthrough_model.last_played_exp_version,
last_playthrough_model.last_updated,
last_playthroug... | [
"def save_last_playthrough_information(last_playthrough_information):\n last_playthrough_information_model = (\n user_models.ExpUserLastPlaythroughModel(\n id=last_playthrough_information.id,\n user_id=last_playthrough_information.user_id,\n exploration_id=last_playthrough... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Save an activities completed domain object as an CompletedActivitiesModel entity in the datastore. | def save_completed_activities(activities_completed):
completed_activities_model = user_models.CompletedActivitiesModel(
id=activities_completed.id,
exploration_ids=(
activities_completed.exploration_ids),
collection_ids=activities_completed.collection_ids)
completed_activiti... | [
"def save_incomplete_activities(incomplete_activities):\n incomplete_activities_model = user_models.IncompleteActivitiesModel(\n id=incomplete_activities.id,\n exploration_ids=(\n incomplete_activities.exploration_ids),\n collection_ids=(\n incomplete_activities.collect... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Save an incomplete activities domain object as an IncompleteActivitiesModel entity in the datastore. | def save_incomplete_activities(incomplete_activities):
incomplete_activities_model = user_models.IncompleteActivitiesModel(
id=incomplete_activities.id,
exploration_ids=(
incomplete_activities.exploration_ids),
collection_ids=(
incomplete_activities.collection_ids))
... | [
"def get_incomplete_activities_from_model(incomplete_activities_model):\n return user_domain.IncompleteActivities(\n incomplete_activities_model.id,\n incomplete_activities_model.exploration_ids,\n incomplete_activities_model.collection_ids)",
"def save_completed_activities(activities_comp... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Save an ExpUserLastPlaythrough domain object as an ExpUserLastPlaythroughModel entity in the datastore. | def save_last_playthrough_information(last_playthrough_information):
last_playthrough_information_model = (
user_models.ExpUserLastPlaythroughModel(
id=last_playthrough_information.id,
user_id=last_playthrough_information.user_id,
exploration_id=last_playthrough_informati... | [
"def get_last_playthrough_information(last_playthrough_model):\n return user_domain.ExpUserLastPlaythrough(\n last_playthrough_model.user_id,\n last_playthrough_model.exploration_id,\n last_playthrough_model.last_played_exp_version,\n last_playthrough_model.last_updated,\n last... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Adds the exploration id to the completed list of the user unless the exploration has already been completed or has been created/edited by the user. It is also removed from the incomplete list (if present). | def mark_exploration_as_completed(user_id, exp_id):
completed_activities_model = (
user_models.CompletedActivitiesModel.get(
user_id, strict=False))
if not completed_activities_model:
completed_activities_model = (
user_models.CompletedActivitiesModel(id=user_id))
# ... | [
"def remove_exp_from_completed_list(user_id, exploration_id):\n completed_activities_model = (\n user_models.CompletedActivitiesModel.get(\n user_id, strict=False))\n\n if completed_activities_model:\n activities_completed = get_completed_activities_from_model(\n completed_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Adds the collection id to the list of collections completed by the user unless the collection has already been completed or has been created/edited by the user. It is also removed from the incomplete list (if present). | def mark_collection_as_completed(user_id, collection_id):
completed_activities_model = (
user_models.CompletedActivitiesModel.get(
user_id, strict=False))
if not completed_activities_model:
completed_activities_model = (
user_models.CompletedActivitiesModel(id=user_id))
... | [
"def remove_collection_from_completed_list(user_id, collection_id):\n completed_activities_model = (\n user_models.CompletedActivitiesModel.get(\n user_id, strict=False))\n\n if completed_activities_model:\n activities_completed = get_completed_activities_from_model(\n comp... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Adds the exploration id to the incomplete list of the user unless the exploration has been already completed or has been created/edited by the user. If the exploration is already present in the incomplete list, just the details associated with it are updated. | def mark_exploration_as_incomplete(
user_id, exploration_id, state_name, exploration_version):
incomplete_activities_model = (
user_models.IncompleteActivitiesModel.get(
user_id, strict=False))
if not incomplete_activities_model:
incomplete_activities_model = (
us... | [
"def remove_exp_from_incomplete_list(user_id, exploration_id):\n incomplete_activities_model = (\n user_models.IncompleteActivitiesModel.get(user_id, strict=False))\n\n if incomplete_activities_model:\n incomplete_activities = get_incomplete_activities_from_model(\n incomplete_activit... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Adds the collection id to the list of collections partially completed by the user unless the collection has already been completed or has been created/edited by the user or is already present in the incomplete list. | def mark_collection_as_incomplete(user_id, collection_id):
incomplete_activities_model = (
user_models.IncompleteActivitiesModel.get(user_id, strict=False))
if not incomplete_activities_model:
incomplete_activities_model = (
user_models.IncompleteActivitiesModel(id=user_id))
col... | [
"def mark_collection_as_completed(user_id, collection_id):\n completed_activities_model = (\n user_models.CompletedActivitiesModel.get(\n user_id, strict=False))\n if not completed_activities_model:\n completed_activities_model = (\n user_models.CompletedActivitiesModel(id=... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Removes the exploration from the completed list of the user (if present). | def remove_exp_from_completed_list(user_id, exploration_id):
completed_activities_model = (
user_models.CompletedActivitiesModel.get(
user_id, strict=False))
if completed_activities_model:
activities_completed = get_completed_activities_from_model(
completed_activities_m... | [
"def remove_exp_from_incomplete_list(user_id, exploration_id):\n incomplete_activities_model = (\n user_models.IncompleteActivitiesModel.get(user_id, strict=False))\n\n if incomplete_activities_model:\n incomplete_activities = get_incomplete_activities_from_model(\n incomplete_activit... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Removes the collection id from the list of completed collections (if present). | def remove_collection_from_completed_list(user_id, collection_id):
completed_activities_model = (
user_models.CompletedActivitiesModel.get(
user_id, strict=False))
if completed_activities_model:
activities_completed = get_completed_activities_from_model(
completed_activi... | [
"def remove_collection_from_incomplete_list(user_id, collection_id):\n incomplete_activities_model = (\n user_models.IncompleteActivitiesModel.get(user_id, strict=False))\n\n if incomplete_activities_model:\n incomplete_activities = get_incomplete_activities_from_model(\n incomplete_a... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Removes the exploration from the incomplete list of the user (if present). | def remove_exp_from_incomplete_list(user_id, exploration_id):
incomplete_activities_model = (
user_models.IncompleteActivitiesModel.get(user_id, strict=False))
if incomplete_activities_model:
incomplete_activities = get_incomplete_activities_from_model(
incomplete_activities_model)
... | [
"def remove_exp_from_completed_list(user_id, exploration_id):\n completed_activities_model = (\n user_models.CompletedActivitiesModel.get(\n user_id, strict=False))\n\n if completed_activities_model:\n activities_completed = get_completed_activities_from_model(\n completed_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Removes the collection id from the list of incomplete collections (if present). | def remove_collection_from_incomplete_list(user_id, collection_id):
incomplete_activities_model = (
user_models.IncompleteActivitiesModel.get(user_id, strict=False))
if incomplete_activities_model:
incomplete_activities = get_incomplete_activities_from_model(
incomplete_activities_m... | [
"def remove_collection_from_completed_list(user_id, collection_id):\n completed_activities_model = (\n user_models.CompletedActivitiesModel.get(\n user_id, strict=False))\n\n if completed_activities_model:\n activities_completed = get_completed_activities_from_model(\n comp... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a list with the ids of all the explorations completed by the user. | def get_all_completed_exp_ids(user_id):
completed_activities_model = (
user_models.CompletedActivitiesModel.get(
user_id, strict=False))
if completed_activities_model:
activities_completed = get_completed_activities_from_model(
completed_activities_model)
return... | [
"def get_all_incomplete_exp_ids(user_id):\n incomplete_activities_model = (\n user_models.IncompleteActivitiesModel.get(\n user_id, strict=False))\n\n if incomplete_activities_model:\n incomplete_activities = get_incomplete_activities_from_model(\n incomplete_activities_mod... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a list of summaries of the completed exploration ids and the number of explorations deleted from the list as they are no longer present. | def get_completed_exp_summaries(user_id):
completed_exploration_ids = get_all_completed_exp_ids(user_id)
number_deleted = 0
for exploration_id in completed_exploration_ids:
if not exp_services.does_exploration_exists(exploration_id):
number_deleted = number_deleted + 1
remov... | [
"def get_incomplete_exp_summaries(user_id):\n incomplete_exploration_ids = get_all_incomplete_exp_ids(user_id)\n\n number_deleted = 0\n for exploration_id in incomplete_exploration_ids:\n if not exp_services.does_exploration_exists(exploration_id):\n number_deleted = number_deleted + 1\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a list with the ids of all the collections completed by the user. | def get_all_completed_collection_ids(user_id):
completed_activities_model = (
user_models.CompletedActivitiesModel.get(
user_id, strict=False))
if completed_activities_model:
activities_completed = get_completed_activities_from_model(
completed_activities_model)
... | [
"def get_all_incomplete_collection_ids(user_id):\n incomplete_activities_model = (\n user_models.IncompleteActivitiesModel.get(user_id, strict=False))\n\n if incomplete_activities_model:\n incomplete_activities = get_incomplete_activities_from_model(\n incomplete_activities_model)\n\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a list of summaries of the completed collection ids, the number of collections deleted from the list as they are no longer present and the number of collections being shifted to the incomplete section on account of new addition of explorations. | def get_completed_collection_summaries(user_id):
completed_collection_ids = get_all_completed_collection_ids(user_id)
number_deleted = 0
completed_to_incomplete_collections = []
for collection_id in completed_collection_ids:
if not collection_services.does_collection_exists(collection_id):
... | [
"def get_incomplete_collection_summaries(user_id):\n incomplete_collection_ids = get_all_incomplete_collection_ids(user_id)\n\n number_deleted = 0\n for collection_id in incomplete_collection_ids:\n if not collection_services.does_collection_exists(collection_id):\n number_deleted = numbe... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a list with the ids of all the explorations partially completed by the user. | def get_all_incomplete_exp_ids(user_id):
incomplete_activities_model = (
user_models.IncompleteActivitiesModel.get(
user_id, strict=False))
if incomplete_activities_model:
incomplete_activities = get_incomplete_activities_from_model(
incomplete_activities_model)
... | [
"def get_all_completed_exp_ids(user_id):\n completed_activities_model = (\n user_models.CompletedActivitiesModel.get(\n user_id, strict=False))\n\n if completed_activities_model:\n activities_completed = get_completed_activities_from_model(\n completed_activities_model)\n\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a list of summaries of the incomplete exploration ids and the number of explorations deleted from the list as they are no longer present. | def get_incomplete_exp_summaries(user_id):
incomplete_exploration_ids = get_all_incomplete_exp_ids(user_id)
number_deleted = 0
for exploration_id in incomplete_exploration_ids:
if not exp_services.does_exploration_exists(exploration_id):
number_deleted = number_deleted + 1
r... | [
"def get_completed_exp_summaries(user_id):\n completed_exploration_ids = get_all_completed_exp_ids(user_id)\n\n number_deleted = 0\n for exploration_id in completed_exploration_ids:\n if not exp_services.does_exploration_exists(exploration_id):\n number_deleted = number_deleted + 1\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a list with the ids of all the collections partially completed by the user. | def get_all_incomplete_collection_ids(user_id):
incomplete_activities_model = (
user_models.IncompleteActivitiesModel.get(user_id, strict=False))
if incomplete_activities_model:
incomplete_activities = get_incomplete_activities_from_model(
incomplete_activities_model)
retur... | [
"def get_all_completed_collection_ids(user_id):\n completed_activities_model = (\n user_models.CompletedActivitiesModel.get(\n user_id, strict=False))\n\n if completed_activities_model:\n activities_completed = get_completed_activities_from_model(\n completed_activities_mod... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a list of summaries of the incomplete collection ids and the number of collections deleted from the list as they are no longer present. | def get_incomplete_collection_summaries(user_id):
incomplete_collection_ids = get_all_incomplete_collection_ids(user_id)
number_deleted = 0
for collection_id in incomplete_collection_ids:
if not collection_services.does_collection_exists(collection_id):
number_deleted = number_deleted +... | [
"def get_completed_collection_summaries(user_id):\n completed_collection_ids = get_all_completed_collection_ids(user_id)\n\n number_deleted = 0\n completed_to_incomplete_collections = []\n for collection_id in completed_collection_ids:\n if not collection_services.does_collection_exists(collectio... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a displayable summary dict of the the collection summaries given to it. | def get_collection_summary_dicts(collection_summaries):
summary_dicts = []
for collection_summary in collection_summaries:
summary_dicts.append({
'id': collection_summary.id,
'title': collection_summary.title,
'category': collection_summary.category,
'obje... | [
"def summaries(self):\n return self._summaries",
"def to_dict(self) -> CollectionSummaryDict:\n return {\n 'id': self.id,\n 'title': self.title,\n 'category': self.category,\n 'objective': self.objective,\n 'language_code': self.language_code,\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
GRE gre input nodes not registerd unless configured | def test_gre_input_node(self):
pkt = (
Ether(dst=self.pg0.local_mac, src=self.pg0.remote_mac)
/ IP(src=self.pg0.remote_ip4, dst=self.pg0.local_ip4)
/ GRE()
)
self.pg0.add_stream(pkt)
self.pg_start()
# no tunnel created, gre-input not registere... | [
"def input_nodes(self):\n pass",
"def _install_gre_allow_flows(self, datapath):\n for peer in self.config.allowed_gre_peers:\n self._add_gre_tun_allow_flow(datapath, peer.ip, peer.key)",
"def add_nodes(self):\n for node_id in self.nodes:\n x = self.nodes[node_id][0]\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |