query stringlengths 9 9.05k | document stringlengths 10 222k | negatives listlengths 19 20 | metadata dict |
|---|---|---|---|
Get the first storage varnode for this variable the first storage varnode associated with this variable getVariableStorage() | def getFirstStorageVarnode(self) -> ghidra.program.model.pcode.Varnode:
... | [
"def getVariableStorage(self) -> ghidra.program.model.listing.VariableStorage:\n ...",
"def getLastStorageVarnode(self) -> ghidra.program.model.pcode.Varnode:\n ...",
"def get_storage_variable(self, path):\n raise NotImplementedError(\"get_storage_variable has not been implemented!\")",
"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
the first use offset relative to the function entry point. | def getFirstUseOffset(self) -> int:
... | [
"def min_file_offset(self):\t\n\t\treturn idaapi.get_fileregion_offset(MinEA())",
"def _cal_offset_local(func_name,var_type_map):\n local_vars = func_dict[func_name][\"local_var\"]\n offset = -4\n var_offset = {}\n for var in local_vars:\n if var in var_offset:\n raise SystemError(\"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the last storage varnode for this variable the last storage varnode associated with this variable getVariableStorage() | def getLastStorageVarnode(self) -> ghidra.program.model.pcode.Varnode:
... | [
"def getVariableStorage(self) -> ghidra.program.model.listing.VariableStorage:\n ...",
"def getFirstStorageVarnode(self) -> ghidra.program.model.pcode.Varnode:\n ...",
"def get_storage_variable(self, path):\n raise NotImplementedError(\"get_storage_variable has not been implemented!\")",
... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
the minimum address corresponding to the first varnode of this storage | def getMinAddress(self) -> ghidra.program.model.address.Address:
... | [
"def getFirstStorageVarnode(self) -> ghidra.program.model.pcode.Varnode:\n ...",
"def _get_min_addr(self) -> Optional[int]:\n\n if not self._regions:\n if self.project.arch.name != \"Soot\":\n l.error(\"self._regions is empty or not properly set.\")\n return None... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
the stack offset associated with simple stack variable (i.e., { isStackVariable()} returns true). UnsupportedOperationException if storage is not a simple stack variable | def getStackOffset(self) -> int:
... | [
"def getVariableOffset(self) -> ghidra.program.model.listing.VariableOffset:\n ...",
"def stack_pointer(self):\n return self._stack_pointer",
"def getStackIndex(self) -> \"int\":\n return _coin.SoElement_getStackIndex(self)",
"def _find_thunk_offset(self, codeobj, instructions):\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the variable storage associated with this variable. the variable storage for this variable | def getVariableStorage(self) -> ghidra.program.model.listing.VariableStorage:
... | [
"def get_storage_variable(self, path):\n raise NotImplementedError(\"get_storage_variable has not been implemented!\")",
"def storage(self):\n try:\n return self._storage\n\n except AttributeError:\n return MissingComponent(self, \"Vessel Storage\")",
"def storage(self... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
true if this variable has been assigned storage. This is equivalent to { getVariableStorage()} != null | def hasAssignedStorage(self) -> bool:
... | [
"def hasVar(self):\n return hasattr(self, 'v') and self.v is not None",
"def vars_inited(self):\n inited, init_sess = self._var_inited\n return inited and init_sess == self.session",
"def isMemoryVariable(self) -> bool:\n ...",
"def has_storage(self, cls):\r\n return True",
... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
true if this variable uses simple or compound storage which contains a stack element. If true, the last storage varnode will always be the stack element. getLastStorageVarnode() | def hasStackStorage(self) -> bool:
... | [
"def getLastStorageVarnode(self) -> ghidra.program.model.pcode.Varnode:\n ...",
"def is_last_node(self, node):\n return True if self.get_last_node() == node else False",
"def getFirstStorageVarnode(self) -> ghidra.program.model.pcode.Varnode:\n ...",
"def has_storage(self, cls):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
true if this variable uses compound storage consisting of two or more storage elements which will be returned by the { getVariableStorage()} method. Compound variables will always use a register(s) optionally followed by other storage (i.e., stack). | def isCompoundVariable(self) -> bool:
... | [
"def hasAssignedStorage(self) -> bool:\n ...",
"def should_store_locals(node):\n types = (AliasExpr, Binding, FuncDef)\n for item in node.body:\n if isinstance(item, types):\n return True\n if isinstance(item, StorageExpr) and item.expr is not None:\n return True\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
true if the specified variable is equivalent to this variable | def isEquivalent(self, variable: ghidra.program.model.listing.Variable) -> bool:
... | [
"def flag_instvar(inst: Entity, flag: Property) -> bool:\n values = flag.value.split(' ', 3)\n if len(values) == 3:\n val_a, op, val_b = values\n op = inst.fixup.substitute(op)\n comp_func = INSTVAR_COMP.get(op, operator.eq)\n elif len(values) == 2:\n val_a, val_b = values\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
true if this is a simple variable consisting of a single storage memory element which will be returned by either the { getFirstStorageVarnode()} or { getVariableStorage()} methods. | def isMemoryVariable(self) -> bool:
... | [
"def getFirstStorageVarnode(self) -> ghidra.program.model.pcode.Varnode:\n ...",
"def isVariable(self):\n return (len(self) == 1)",
"def is_stvar(self):\n return self.ty == Type.STVAR",
"def hasAssignedStorage(self) -> bool:\n ...",
"def getVariableStorage(self) -> ghidra.program... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
true if this is a simple variable consisting of a single register varnode which will be returned by either the { getFirstStorageVarnode()} or { getLastStorageVarnode()} methods. The register can be obtained using the { getRegister()} method. | def isRegisterVariable(self) -> bool:
... | [
"def getFirstStorageVarnode(self) -> ghidra.program.model.pcode.Varnode:\n ...",
"def isVariable(self):\n return (len(self) == 1)",
"def isMemoryVariable(self) -> bool:\n ...",
"def is_stvar(self):\n return self.ty == Type.STVAR",
"def hasVar(self):\n return hasattr(self, ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
true if this is a simple variable consisting of a single storage unique/hash element which will be returned by either the { getFirstStorageVarnode()} or { getVariableStorage()} methods. The unique hash can be obtained from the storage address offset corresponding to the single storage element. | def isUniqueVariable(self) -> bool:
... | [
"def getFirstStorageVarnode(self) -> ghidra.program.model.pcode.Varnode:\n ...",
"def isVariable(self):\n return (len(self) == 1)",
"def isMemoryVariable(self) -> bool:\n ...",
"def isEquivalent(self, variable: ghidra.program.model.listing.Variable) -> bool:\n ...",
"def isRegist... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set the comment for this variable comment the comment | def setComment(self, comment: unicode) -> None:
... | [
"def comment(self, comment):\n self._comment = comment",
"def comment(self, comment):\n if comment is None:\n raise ValueError(\"Invalid value for `comment`, must not be `None`\")\n\n self._comment = comment",
"def set_comment(self, cmt):\n if cmt and cmt[:8] == 'Ansible:'... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set the Data Type of this variable. The given dataType must have a fixed length. type the data type alignStack maintain proper stack alignment/justification if supported by implementation. If false and this is a stack variable, the current stack address/offset will not change. If true, the affect is implementation depe... | def setDataType(self, type: ghidra.program.model.data.DataType, alignStack: bool, force: bool, source: ghidra.program.model.symbol.SourceType) -> None:
... | [
"def setDataType(self, type: ghidra.program.model.data.DataType, storage: ghidra.program.model.listing.VariableStorage, force: bool, source: ghidra.program.model.symbol.SourceType) -> None:\n ...",
"def setDataType(self, dt: ghidra.program.model.data.DataType) -> None:\n ...",
"def set_data_type(s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set the Data Type of this variable and the associated storage whose size matches the data type length. | def setDataType(self, type: ghidra.program.model.data.DataType, storage: ghidra.program.model.listing.VariableStorage, force: bool, source: ghidra.program.model.symbol.SourceType) -> None:
... | [
"def set_dtype(self, value):\n self._dtype = value\n for x in (self._position, self._orientation, self._velocity,\n self._mass, self._charge, self._diameter,\n self._moment_inertia, self._angmom):\n if x is not None:\n x = x.astype(value)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Adds a 3D point | def addPoint(self,x,y,z):
self.x = x
self.y = y
self.z = z | [
"def point_3d(self, x, y, z):\n self._point_3d(x, y, z)",
"def add_point(self, point):\n\t\tself.vertices.append(point)",
"def add_point(self, point):\n\t\tself.cloud[point.get_coords()] = point",
"def addPoint(x, y, z, meshSize=0., tag=-1):\n ierr = c_int()\n api__result__ = lib.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Query the video categories endpoint. | def get_video_categories(key: str, category_ids: List[str], localization_code: str = None) -> dict:
param_dict = {
"key": key,
"part": "snippet",
"id": ",".join(category_ids)}
if localization_code:
param_dict["hl"] = localization_code
return query_endpoint("videoCategories", ... | [
"def test_api_v3_categories_get(self):\n pass",
"def __send_get_categories(self):\n self.__send_command(CommandsBytes.GET_CATEGORIES)",
"def test_tv_categories_get(self):\n pass",
"def get_categories():\n # URL example: https://channelstore.roku.com/api/v6/channels/categories?country=U... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Query the video categories endpoint for video categories in a specific region. | def get_video_categories_in_region(key: str, region_code: str, localization_code: str = None) -> dict:
param_dict = {
"key": key,
"part": "snippet",
"regionCode": region_code}
if localization_code:
param_dict["hl"] = localization_code
return query_endpoint("videoCategories", ... | [
"def get_video_categories(\n self,\n *,\n category_id: Optional[Union[str, list, tuple, set]] = None,\n region_code: Optional[str] = None,\n parts: Optional[Union[str, list, tuple, set]] = None,\n hl: Optional[str] = \"en_US\",\n return_json: Optional[bool] = False,\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set a value v at index i in list l. | def set_list(l, i, v):
try:
l[i] = v
except IndexError:
for _ in range(i - len(l) + 1):
l.append(None)
l[i] = v | [
"def modify_list(lst, i, val):\r\n if len(lst) > i:\r\n lst[i] = val\r\n return None",
"def __setitem__(self, i, value):\n self.set(i, value)\n return self",
"def SetCount(self, i, val):\n self.countList[i] = val",
"def set(self, i: 'int const', ptr: 'SoBase') -> \"void\":\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function is used to access the tab preceding the active tab (global TABS list). Given an active_tab (corresponding to one of START, DATASET, ...), it returns the previous element of the array. | def previous_tab(active_tab):
return TABS[TABS_INDEXES[active_tab] - 1] | [
"def next_tab(active_tab):\n return TABS[TABS_INDEXES[active_tab] + 1]",
"def prev_next_tabs(tablist):\n prev_tab = None\n next_tab = None\n current_tab = None\n for ix, tab in enumerate(tablist):\n if tab[0] == request.endpoint:\n current_tab = ix\n break\n\n if cur... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function is used to access the tab following the active tab (global TABS list). Given an active_tab (corresponding to one of START, DATASET, ...), it returns the previous element of the array. | def next_tab(active_tab):
return TABS[TABS_INDEXES[active_tab] + 1] | [
"def previous_tab(active_tab):\n return TABS[TABS_INDEXES[active_tab] - 1]",
"def prev_next_tabs(tablist):\n prev_tab = None\n next_tab = None\n current_tab = None\n for ix, tab in enumerate(tablist):\n if tab[0] == request.endpoint:\n current_tab = ix\n break\n\n if... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Start form (job creation) | def start(request):
active_tab = START
if request.method == 'POST':
form = FORMS_NEW[active_tab](request.POST, request=request)
active_tab = save_form(form, request, active_tab)
else:
form = FORMS_NEW[active_tab](request=request)
if active_tab == START:
return render(
... | [
"def quick_jobpost(context):\n context[\"form\"] = JobPostForm()\n return context",
"def launch(request, id):\n\n active_tab = LAUNCH\n active_tab, forms, views = act_on_request_method_edit(request, active_tab, id)\n\n if active_tab != SUBMITTED:\n return render(\n request,\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Form to edit the job basic information (name, description). It also returns forms to be rendered in other tabs (models). | def edit_job_name(request, id):
active_tab = START
active_tab, forms, views = act_on_request_method_edit(request, active_tab, id)
return render(
request,
"job/edit.html",
{
'job_id': id,
'active_tab': active_tab,
'disable_other_tabs': False,
... | [
"def edit_job_data_model(request, id):\n active_tab = DMODEL\n active_tab, forms, views = act_on_request_method_edit(request, active_tab, id)\n\n return render(\n request,\n \"job/edit.html\",\n {\n 'job_id': id,\n 'active_tab': active_tab,\n 'disable_o... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Form to edit the data model information. It also returns forms to be rendered in other tabs (models). | def edit_job_data_model(request, id):
active_tab = DMODEL
active_tab, forms, views = act_on_request_method_edit(request, active_tab, id)
return render(
request,
"job/edit.html",
{
'job_id': id,
'active_tab': active_tab,
'disable_other_tabs': False... | [
"def edit_form(self, resource):\n fs = FieldSet(resource.model)\n return fs.render()",
"def editForm(self,id,table=1):\t\n\t\tif table:\n\t\t\tform=tableForm(server['query'] + '&action=do')\n\t\telse:\n\t\t\tform=Form(server['query'] + '&action=do')\n\t\ttables=[ i for i in self.db.query('SHOW TABLE... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Form to edit the dataset information. It also returns forms to be rendered in other tabs (models). | def edit_job_dataset(request, id):
active_tab = DATASET
active_tab, forms, views = act_on_request_method_edit(request, active_tab, id)
return render(
request,
"job/edit.html",
{
'job_id': id,
'active_tab': active_tab,
'disable_other_tabs': False,... | [
"def edit_form(self, resource):\n fs = FieldSet(resource.model)\n return fs.render()",
"def edit_job_data_model(request, id):\n active_tab = DMODEL\n active_tab, forms, views = act_on_request_method_edit(request, active_tab, id)\n\n return render(\n request,\n \"job/edit.html\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Form to edit the PSF information. It also returns forms to be rendered in other tabs (models). | def edit_job_psf(request, id):
active_tab = PSF
active_tab, forms, views = act_on_request_method_edit(request, active_tab, id)
return render(
request,
"job/edit.html",
{
'job_id': id,
'active_tab': active_tab,
'disable_other_tabs': False,
... | [
"def edit_form(self, resource):\n fs = FieldSet(resource.model)\n return fs.render()",
"def show_update_form():\n\n current_user = session.get('current_user')\n user_obj = crud.get_user_by_id(current_user)\n\n return render_template(\"update_info.html\")",
"def edit_formazione(self, event... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Form to edit the LSF information. It also returns forms to be rendered in other tabs (models). | def edit_job_lsf(request, id):
active_tab = LSF
active_tab, forms, views = act_on_request_method_edit(request, active_tab, id)
return render(
request,
"job/edit.html",
{
'job_id': id,
'active_tab': active_tab,
'disable_other_tabs': False,
... | [
"def edit_form(self, resource):\n fs = FieldSet(resource.model)\n return fs.render()",
"def edit_job_psf(request, id):\n\n active_tab = PSF\n active_tab, forms, views = act_on_request_method_edit(request, active_tab, id)\n\n return render(\n request,\n \"job/edit.html\",\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Form to edit the galaxy model information. It also returns forms to be rendered in other tabs (models). | def edit_job_galaxy_model(request, id):
active_tab = GMODEL
active_tab, forms, views = act_on_request_method_edit(request, active_tab, id)
return render(
request,
"job/edit.html",
{
'job_id': id,
'active_tab': active_tab,
'disable_other_tabs': Fa... | [
"def ShowForm(self, _):\n return {'layer_model': model.Layer}",
"def edit_form(self, resource):\n fs = FieldSet(resource.model)\n return fs.render()",
"def edit_formazione(self, event):\n self.Disable()\n ViewFormazione(parent=self, title='Formazione')",
"def getEditgameUpdateFo... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Form to edit the fitter information. It also returns forms to be rendered in other tabs (models). | def edit_job_fitter(request, id):
active_tab = FITTER
active_tab, forms, views = act_on_request_method_edit(request, active_tab, id)
return render(
request,
"job/edit.html",
{
'job_id': id,
'active_tab': active_tab,
'disable_other_tabs': False,
... | [
"def edit_form(self, resource):\n fs = FieldSet(resource.model)\n return fs.render()",
"def browse_edit():\n # if user is creating a new empty deck, render only the deckname field with newtermfield and newdeffield\n # if user is editing a preexisting deck, render the deckname field, all cards ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Form to edit the params information. It also returns forms to be rendered in other tabs (models). | def edit_job_params(request, id):
active_tab = PARAMS
active_tab, forms, views = act_on_request_method_edit(request, active_tab, id)
return render(
request,
"job/edit.html",
{
'job_id': id,
'active_tab': active_tab,
'disable_other_tabs': False,
... | [
"def get_parameters_form():",
"def ShowForm(self, _):\n return {'layer_model': model.Layer}",
"def edit_job_psf(request, id):\n\n active_tab = PSF\n active_tab, forms, views = act_on_request_method_edit(request, active_tab, id)\n\n return render(\n request,\n \"job/edit.html\",\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Form to launch a job (changes the job status to submitted) It also returns forms to be rendered in other tabs (models). | def launch(request, id):
active_tab = LAUNCH
active_tab, forms, views = act_on_request_method_edit(request, active_tab, id)
if active_tab != SUBMITTED:
return render(
request,
"job/edit.html",
{
'job_id': id,
'active_tab': active_... | [
"def quick_jobpost(context):\n context[\"form\"] = JobPostForm()\n return context",
"def start(request):\n active_tab = START\n if request.method == 'POST':\n form = FORMS_NEW[active_tab](request.POST, request=request)\n active_tab = save_form(form, request, active_tab)\n else:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function to handle the overview view of a job | def job_overview(request, id):
active_tab = LAUNCH
# This could be cleaned to avoid getting forms and only gather views.
active_tab, forms, views = act_on_request_method_edit(request, active_tab, id)
return render(
request,
"job/job_overview.html",
{
'job_id': id,
... | [
"def overview(self):\n return _execute_rest_request(url=f\"{self.prefix}/overview\")[\"jobs\"]",
"def seejob(request):\n return render(\n request, 'beweb/view_job.html'\n )",
"def show(self):\n return self._job",
"def info(job_id):\n print(json.dumps(API().info(job_id), indent=Tr... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Transfer the date input information to corresponding frequency | def date_freq_transfer(date,freq):
year = (date[0:4])
month = (date[5:7])
day = (date[8:10])
if(freq == 'monthly'):
date2 = str(year)+'-'+str(month)
if(freq == 'quarterly'):
quarter = (math.ceil(int(month)/3))
date2 = str(year)+'Q'+str(quarter)
if(freq == 'daily'):
... | [
"def get_model_data_per_date(date):",
"def convertfreq(freq):\r\n\r\n freq = freq.upper()\r\n\r\n days = ['MON', 'TUE', 'WED', 'THU', 'FRI', 'SAT', 'SUN']\r\n months = ['JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEP',\r\n 'OCT', 'NOV', 'DEC']\r\n\r\n weekoffsets = ['W-%s' % ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
select stocks which meet the criteria for user input stock factors The criteria should only be some filter conditions for value of factor e.g. user choose to select the stock which santisfies the net_profit>=100000; | def stock_screener_filter_condition(conn_path,var_list,date,condition_list,threshold_list,industry='None',since_ipo = {'min': 0, 'max': 30},view_all = True,top = 30):
var_mapping= pd.read_excel(conn_path+'value_mapping.xlsx')
var2 = var_mapping[var_mapping['Chinese'].isin(var_list)]
var2 = (var2.iloc[:,0])... | [
"def screen_stocks(df, **kwargs):\r\n\r\n for column, thresholds in kwargs.items():\r\n df = df[(df[column] > thresholds[0]) & (df[column] < thresholds[1]) | (df[column].isnull())]\r\n\r\n ticker_list = list(df.symbol)\r\n\r\n return ticker_list",
"def stock_screener_filter_top(conn_path,var_list,... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
select several stocks which meet the creteria for user input stock factors The creteria should only be some ranking conditions for value of factor e.g. user would like to choose to select the stock which has the top 30 net_profit and top 10 roe over all stocks as of that date | def stock_screener_filter_top(conn_path,var_list,date,order,top,industry='None',since_ipo = {'condition': '>=', 't': 0},in_universe = False):
var_mapping= pd.read_excel(conn_path+'value_mapping.xlsx')
var2 = var_mapping[var_mapping['Chinese'].isin(var_list)]
var2 = (var2.iloc[:,0])
if in_universe... | [
"def stock_screener_ranking(conn_path,var_list,date,rank_by,industry='None',since_ipo = {'condition': '>=', 't': 2},in_universe=False,top=50,order='ascending'): \n if in_universe == True:\n industry2 = 'None'\n since_ipo['min'] = 0\n since_ipo['max'] = 30\n else:\n industry2 = ind... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
select stocks as well as user input stock factors with rank on one primary factor e.g. user would like to see the roe,net_profit,and capital ratio for stocks but with net_profit ranked in top 30 over all stocks at that time | def stock_screener_ranking(conn_path,var_list,date,rank_by,industry='None',since_ipo = {'condition': '>=', 't': 2},in_universe=False,top=50,order='ascending'):
if in_universe == True:
industry2 = 'None'
since_ipo['min'] = 0
since_ipo['max'] = 30
else:
industry2 = industry
c... | [
"def display_stock():",
"def rank_stock(self):\n stock_list = []\n for player in self.player_list:\n stock_list.extend(player.stock_list)\n\n stock_list.sort(key=lambda stock: stock.transaction_count,\n reverse=True)\n\n for stock in stock_list[:100]:\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Convert .NET ticks to formatted ISO8601 time | def convert_dotnet_tick(ticks):
_date = datetime.datetime(1, 1, 1) + datetime.timedelta(microseconds=ticks // 10)
if _date.year < 1900: # strftime() requires year >= 1900
_date = _date.replace(year=_date.year + 1900)
return _date.strftime("%Y-%m-%dT%H:%M:%S.%fZ")[:-3] | [
"def encode_datetime(o):\n r = o.isoformat()\n if o.microsecond:\n r = r[:19] + r[26:]\n if r.endswith('+00:00'):\n r = r[:-6] + 'Z'\n return r",
"def datetime_to_iso8601(dt):\n return '%s.%03dZ' % (dt.strftime('%Y-%m-%dT%H:%M:%S'),\n int(dt.microsecond / 1000)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Determine if a point is in the 'crash zone' | def is_in_crash_zone(pos):
return Processor.CRASH_ZONE_START < pos[0] < Processor.CRASH_ZONE_END | [
"def crash_check():\n global CURRENT\n # Grab status\n stat = grab_status()\n\n # Check for seg\n if \"SIGSEGV\" in stat:\n return True\n return False",
"def contains(self, coord):\n try:\n pixel = self.getWcs().skyToPixel(coord)\n except (lsst.pex.exceptions.Doma... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Documentation Assign the barriers for the object graph | def __init__(self, barriers: list):
self.barriers = barriers | [
"def barrier_ref(self):\n return self._barrier_ref",
"def _barrier_worker(self):\n pass",
"def make_barriers():\n mouth = curve(pos=[(23,3, 10),(18,2.5, 15),(12,2,20),(7,.5,21),(0,0,23),(-7,.5,21),(-12,2,20),(-18,2.5,15),(-23,3,10)], radius= 2, color=color.black)\n T_hat = box(pos=(26.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Documentation Return the neighbouring points according to the four movements in front, right, left and back | def get_vertex_neighbours(self, pos: tuple):
n = []
# Allowed movements are left, front, right and back
for dx, dy in [(1, 0), (-1, 0), (0, 1), (0, -1)]:
x2 = pos[0] + dx
y2 = pos[1] + dy
# if x2 < 0 or x2 > 7 or y2 < 0 or y2 > 7:
# ... | [
"def neighbours(self):# по отиз начин работи по - бързо от колкото с up.left, left... etc\n\t\tres = []\n\t\tfor x in xrange(self.x - 1, self.x + 2):\n\t\t\tres.append( Point( x, self.y+1 ) )\n\t\t\tres.append( Point( x, self.y - 1 ) )\n\t\tres.append( Point(self.x -1, self.y) )\n\t\tres.append( Point(self.x+1, sel... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Find user by session ID | def get_user_from_session_id(self, session_id: str) -> str:
if session_id:
user = self._db.find_user_by(session_id=session_id)
return user | [
"def find_by_id(_id):\n if not _id:\n raise ValueError('Please provide the id')\n for user in USERS:\n if user['id'] == _id:\n return user\n return None",
"def get_user_from_session_id(session_id):\n try:\n session = Session.objects.get(session_k... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Initialize the var set manager. | def __init__(self):
self.variable_sets = {}
self.reserved_keys = []
self.reserved_keys.extend(self.VAR_SETS) | [
"def init_vars(self):\n pass",
"def init_vars(self):\n if self.session is None:\n self.set_session()\n\n self.session.run(global_variables_initializer())\n self._var_inited = (True, self.session)",
"def _initialize_track_vars(self):\n self.__log.call()\n\n tr... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Add a new variable set to this variable set manager. Variables in the set can then be retrieved by complex key. | def add_var_set(self, name, value_dict):
if name not in self.reserved_keys:
raise ValueError("Unknown variable set name: '{}'".format(name))
if name in self.variable_sets:
raise ValueError(
"Variable set '{}' already initialized.".format(name))
try:
... | [
"def _add_set_object(self, set_obj: Union[SET1, SET2, SET3]) -> None:\n key = set_obj.sid\n assert key >= 0\n if key in self.sets:\n self.sets[key].add_set(set_obj)\n else:\n self.sets[key] = set_obj\n self._type_to_id_map[set_obj.type].append(key)",
"d... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
For every combination of permutation variables (that were used), return a new var_set manager. | def get_permutations(self, used_per_vars):
# Get every a dictionary of var:idx for every combination of used
# permutation variables.
permutations = [{}]
for per_var in used_per_vars:
new_perms = []
for old_perm in permutations:
for i in range(se... | [
"def sub_var_bindings_set(triples, bindings_set) :\n\t\n\t#print 'triples',prettyquery(triples)\n\t#print 'bindings',prettyquery(bindings_set)\n\t\n\tfor bindings in bindings_set :\n\t\tyield sub_var_bindings(triples, bindings)",
"def variables(self):\n # Task 4.1\n var_set = set()\n var_set.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Parse the given complex key, and return a reasonable (var_set, var, index, sub_var) tuple. | def parse_key(cls, key):
if isinstance(key, list) or isinstance(key, tuple):
parts = list(key)
elif isinstance(key, str):
parts = key.split('.')
else:
raise TypeError("Only str keys or tuples/lists are allowed.")
var_set = None
if parts[0] in... | [
"def _process_data_var(string):\n key, var = string.split(\"<-\")\n if \"structure\" in var:\n var, dim = var.replace(\"structure(\", \"\").replace(\",\", \"\").split(\".Dim\")\n # dtype = int if '.' not in var and 'e' not in var.lower() else float\n dtype = float\n var = var.repla... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Resolve the given key using this known var sets. Unlike parse_key, the var_set returned will never be None, as the key must correspond to a found variable in a var_set. In case of conflicts, the var_set will be resolved in order. | def resolve_key(self, key):
var_set, var, index, sub_var = self.parse_key(key)
# If we didn't get an explicit var_set, find the first matching one
# with the given var.
if var_set is None:
for res_vs in self.reserved_keys:
if (res_vs in self.variable_sets an... | [
"def parse_key(cls, key):\n\n if isinstance(key, list) or isinstance(key, tuple):\n parts = list(key)\n elif isinstance(key, str):\n parts = key.split('.')\n else:\n raise TypeError(\"Only str keys or tuples/lists are allowed.\")\n\n var_set = None\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return whether the given variable in the given varset is a deferred variable. | def is_deferred(self, var_set, var):
return isinstance(self.variable_sets[var_set].data[var],
DeferredVariable) | [
"def _hasVarBeenDeclared(self, var_name, group=None):\n\n has_been_declared = False\n\n if isinstance(var_name, list) is not True:\n\n var_name = [var_name]\n\n if group is not None:\n\n where_to_look = self._equation_groups[group]\n\n else:\n\n where_to_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return True if the config structure contains any deferred variables. | def has_deferred(cls, struct):
if isinstance(struct, str):
if '[\x1b' in struct and '\x1b]' in struct:
return True
else:
return False
elif isinstance(struct, list):
return any([cls.has_deferred(val) for val in struct])
elif isi... | [
"def is_deferred(self, var_set, var):\n\n return isinstance(self.variable_sets[var_set].data[var],\n DeferredVariable)",
"def _needs_expansion(value):\n return Config.RE_HAS_VAR_REF.match(value) is not None",
"def has_variable(self, varname):\n return varname in self._f... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Traverse the given config structure and resolve any deferred variables found. | def resolve_deferred(self, struct):
if isinstance(struct, str):
return self.resolve_deferred_str(struct)
elif isinstance(struct, list):
for i in range(len(struct)):
struct[i] = self.resolve_deferred(struct)
return struct
elif isinstance(struct... | [
"def interpolate(self):\n # self.log.debug('Interpolating replacement strings')\n self.build_dependencies()\n while not self.resolved:\n # self.log.debug('CONFIG NOT RESOLVED, MAKING PASS')\n # Now we can actually perform any resolutions\n for ref, ref_data in s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Resolve any deferred variables in the given string, and return the result. | def resolve_deferred_str(self, line):
resolved_line = []
offset = 0
match = self.DEFERRED_VAR_RE.search(line, offset)
# Walk through the line, and lookup the real value of
# each matched deferred variable.
while match is not None:
resolved_line.append(line[... | [
"def resolve(self, text):\n\t\tprev_text = text\n\t\twhile True:\n\t\t\tfor k, v in self.vars.iteritems():\n\t\t\t\tif v is None:\n\t\t\t\t\tv = \"\"\n\t\t\t\ttext = text.replace(\"${%s}\" % k, v)\n\t\t\tif not XMLParser.RE_VAR.match(text) or text == prev_text:\n\t\t\t\tbreak\n\t\treturn text",
"def resolve(self,... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the all variable sets as a single dictionary. This is for testing and bug resolution, not production code. | def as_dict(self):
var_sets = {}
for var_set in self.variable_sets.values():
var_sets[var_set.name] = {}
for key in var_set.data.keys():
var_sets[key] = []
item = var_set.data[key]
if isinstance(item, DeferredVariable):
... | [
"def get_mutable_vars() -> Dict:\n return {name: VarInfo(type_()) for name, type_ in MUTABLE_ENVIRONMENT_VARS.items()}",
"def variables(self):\n # Task 4.1\n var_set = set()\n var_set.update(self.conclusion.vars)\n for assumption in self.assumptions:\n var_set.update(assu... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Initialize the variable set from a config dictionary. | def _init_from_config(self, reserved_keys, value_dict):
for key, value in value_dict.items():
if key in reserved_keys:
raise VariableError("Var name '{}' is reserved.".format(key),
var=key)
if isinstance(value, DeferredVariable):
... | [
"def _init_from_config(self, values):\n\n sub_vars = None\n\n if not isinstance(values, list):\n values = [values]\n\n for idx in range(len(values)):\n value_pairs = values[idx]\n if not isinstance(value_pairs, dict):\n value_pairs = {None: value_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the value of the var given the var name, index, and sub_var name. | def get(self, var, index, sub_var):
if var in self.data:
return self.data[var].get(index, sub_var)
else:
raise KeyError(
"Variable set '{}' does not contain a variable named '{}'. "
"Available variables are: {}"
.format(self.name, ... | [
"def get(self, index, sub_var):\n\n if index is None:\n index = 0\n else:\n if not isinstance(index, int):\n raise KeyError(\"Non-integer index given: '{}'\".format(index))\n\n if not -len(self.data) <= index < len(self.data):\n raise KeyError(\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Initialize the variable list from the given config values. | def _init_from_config(self, values):
sub_vars = None
if not isinstance(values, list):
values = [values]
for idx in range(len(values)):
value_pairs = values[idx]
if not isinstance(value_pairs, dict):
value_pairs = {None: value_pairs}
... | [
"def _init_from_config(self, reserved_keys, value_dict):\n\n for key, value in value_dict.items():\n if key in reserved_keys:\n raise VariableError(\"Var name '{}' is reserved.\".format(key),\n var=key)\n\n if isinstance(value, DeferredV... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the variable value at the given index and sub_var. | def get(self, index, sub_var):
if index is None:
index = 0
else:
if not isinstance(index, int):
raise KeyError("Non-integer index given: '{}'".format(index))
if not -len(self.data) <= index < len(self.data):
raise KeyError(
"I... | [
"def get(self, var, index, sub_var):\n\n if var in self.data:\n return self.data[var].get(index, sub_var)\n else:\n raise KeyError(\n \"Variable set '{}' does not contain a variable named '{}'. \"\n \"Available variables are: {}\"\n .f... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a AppointmentDatabase instance for accessing the database. If the database file does not yet exist, it creates a new database. | def get_db():
if not hasattr(g, 'app_db'):
g.apps_db = AppointmentDatabase(app.config['DATABASE'])
return g.apps_db | [
"def get_db():\n db = getattr(g, '_database', None)\n if db is None:\n with app.app_context():\n if app.config.get('TESTING'):\n db = g._database = sqlite3.connect(app.config['DATABASE'])\n db.row_factory = sqlite3.Row\n db.execute('PRAGMA foreign... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create a Response object containing the error message as JSON. | def to_response(self):
response = jsonify({'error': self.error_message})
response.status = self.status_code
return response | [
"def _build_error_response(message, status_code, error_id, **kwargs):\n\n return make_response(\n jsonify({\n \"status_code\": status_code,\n \"error\": {\n \"message\": message,\n \"id\": error_id\n },\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a dictionary containing appointments indexed by doctor. The dictionary keys are doctor names, and the values are lists of appointments. Each appointment is represented by a sqlite row object, which can be used like a dictionary. | def get_app_by_doctor():
cur = get_db().conn.cursor()
# By using an OrderedDict we will preserve alphabetical order of
# doctors
app_by_doctor = OrderedDict()
query = '''
SELECT doctors.doctor as doctor, patients.FirstN as FirstN,
patients.LastN as LastN, patients.gender as gender, patie... | [
"def get_appointments(doc_id: int, cur) -> json:\n return cur.execute(\n \"SELECT appointment FROM Doctors where UID = ?;\", (doc_id,)\n ).fetchone()[0]",
"def populate_appointments(endpoint, doctor):\n date = timezone.now().strftime('%Y-%m-%d')\n\n appointments = endpoint.list({'doctor... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a dictionary containing appointments indexed by month. The dictionary keys are month names, and the values are lists of appointments. Each appointment is represented by a sqlite row object, which can be used like a dictionary. | def get_app_by_month():
cur = get_db().conn.cursor()
# By using an OrderedDict we will preserve alphabetical order of month
app_by_month = OrderedDict()
query = '''
SELECT app.month as month, patients.FirstN as FirstN, patients.LastN as
LastN, patients.gender as gender, patients.age as age,
... | [
"def appointment_db_query(self):\n \n appointments = []\n sql = \"\"\"\n SELECT appt.id AS appt_id, appt.customer_id AS cust_id,\n DATE_FORMAT(appt.startDate, '%W %m/%d/%Y %l:%i %p') AS appt_lt,\n CONVERT_TZ(DATE_SUB(appt.startDate, INTERVAL 2 HOUR), pref.value, 'UTC') AS r... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Serves a page which shows all the appointments in the database. | def get(self):
return render_template("appointments.html",
apps=get_db().get_all_apps()) | [
"def my_appts():\n\n\tform = MyAppointmentSearch()\n\tappointments = Appointment.query.filter_by(date=str(datetime.date.today())).all()\n\n\tif form.validate_on_submit():\n\t\tselection = form.filter_menu.data\n\t\tif selection == '2':\n\t\t\tcurrent_date = date_tool.get_current_date()\n\t\t\tendof_week = date_tool... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Serves a page which shows all doctors in the database. | def get(self):
return render_template("doctors.html",
doctors=get_db().get_all_doctors()) | [
"def get(self):\n return make_response(jsonify(doctorDAO.get_doctors(db.con_pool)), 200)",
"def get_doctors():\n all_doctors = schema.Doctor.query.all()\n result = schema.doctors_schema.dump(all_doctors)\n return jsonify(result.data)",
"def doctor_main_page(request, doctor_id):\n doctor = get... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Serves the page for showing all patients in the database. | def get(self):
return render_template("patients.html",
patients=get_db().get_all_patients()) | [
"def get_all():\n return jsonify(patients.get_all())",
"def get_all_patient_detailed(request, *args, **kwargs):\n user = request.user\n patient_id = kwargs['id']\n if not patient_id: raise PermissionDenied({'detail': \"mention the patient\", \"error_code\": 609})\n panel = get_my_partner_panel(user... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Serves the page for showing all symptoms in the database. | def get(self):
return render_template("symptoms.html",
symptoms=get_db().get_all_symptoms()) | [
"def show_isps():\n isps = db_session.query(ISP).order_by(ISP.name)\n return render_template(\n \"isps.html\",\n isps=isps,\n location=\"home\",\n title=\"ISPs\")",
"def all_music():\n if notLoggedIn(): # check if logged in\n return redirect( url_for('index'))\n conn... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
On or off music in game. | def turn_music(self):
if self.config.getboolean('audio', 'music'):
self.config.set('audio', 'music', 'false')
pygame.mixer.music.stop()
self.speech.speak(self.phrases['music_off'])
else:
self.config.set('audio', 'music', 'true')
self.music_play... | [
"def play_menu_music(self):\n if not self.muted:\n self.menumusic.play(-1) # infinite loop",
"def setMusic(self, on = True, musicClass = None):\n\n command = 'SET MUSIC {}'.format(['OFF', 'ON'][on])\n if musicClass is not None:\n command += ' {}'.format(musicClass)\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Change language for phrases. | def change_language(self):
if 'ru' == self.config.get('total', 'language'):
self.config.set('total', 'language', 'en')
with open('languages.dat', 'rb') as lang_file:
self.phrases = pickle.load(lang_file)['en']
else:
self.config.set('total', 'language',... | [
"def change_lang(self, new_lang: str):\r\n self.lang = new_lang",
"def on_action_english_triggered(self):\n self.set_language('en_US')",
"def lang_change():\n global lang, current_lang\n if lang == 'english':\n lang = 'polish'\n elif lang == 'polish':\n lang = 'english'\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Uses a players dictionary to create a countries dictionary in which countries are key and a list of player names are values | def create_country_dict(player_dict):
country_dict = dict()
for chess_player, chess_player_data in player_dict.items():
country = chess_player_data[COUNTRY]
if country in country_dict:
name_list = country_dict[country]
name_list.append(chess_player)
else:
... | [
"def build_player_lookup_table(self):\n players = {}\n for player in self.sport_player_model_class.objects.all():\n player_data = LookupItem(player).get_data()\n player_name = '%s %s' % (player.first_name, player.last_name)\n players[player_name] = player_data\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the average ratings for the given players | def get_average_rating(players, player_dict):
ratings = [player_dict[player][RATING] for player in players]
average = sum(ratings)/len(ratings)
return average | [
"def average_rating(self):\n ratings = GameRating.objects.filter(game=self)\n\n # Sum all of the ratings for the game\n total_rating = 0\n for rating in ratings:\n total_rating += rating.rating\n\n if len(ratings):\n return total_rating / len(ratings)\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Prints information sorted on the key of a_dict | def print_sorted(a_dict, player_dict):
sorted_dict = sorted(a_dict.items())
for key, players in sorted_dict:
average_rating = get_average_rating(players, player_dict)
print("{} ({}) ({:.1f}):".format(key, len(players), average_rating))
for player in players:
rating = player_d... | [
"def print_sorted_dictionary(dictionary):\n\n alpha_rest_list = sorted(dictionary.keys())\n\n for rest in alpha_rest_list:\n print \"%s is rated at %s.\" % (rest, dictionary[rest])",
"def sort_and_print(rating_dict):\n for key, value in sorted(rating_dict.items()):\n print(f\"{key} is rated... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Compute the expected value based on held_dice given that there are num_free_dice to be rolled, each with num_die_sides. | def expected_value(held_dice, num_die_sides, num_free_dice):
outcomes = range(1, num_die_sides + 1, 1)
all_free_dices = gen_all_sequences(outcomes, num_free_dice)
total_score = 0
for dummy_free_dice in all_free_dices:
total_score += score(held_dice + dummy_free_dice)
return float(total_score... | [
"def expected_value(held_dice, num_die_sides, num_free_dice):\n current_expected_value = 0\n # Generate possible sequences from free dice\n possible_sequences = gen_all_sequences(list(range(1, num_die_sides + 1)), num_free_dice)\n # Score every sequence with current hold dice\n for sequence in possib... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Compute the hold that maximizes the expected value when the discarded dice are rolled. | def strategy(hand, num_die_sides):
all_holds_set = gen_all_holds(hand)
final_expected_value = 0
final_held_dice = tuple()
for held_dice in all_holds_set:
temp_expected_value = expected_value(held_dice, num_die_sides, len(hand) - len(held_dice))
if temp_expected_value > final_expected_val... | [
"def strategy(hand, num_die_sides):\n all_holds = gen_all_holds(hand)\n max_value = 0\n req_hold = None\n for each_hold in all_holds:\n value = expected_value(each_hold, num_die_sides, len(hand) - len(each_hold))\n if value > max_value:\n max_value = value\n req_hold ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get elements inside a nested dict, based on a dict query. The query is defined by a string separated by '__'. traverse_dict(foo, 'a__b__c') is roughly equivalent to foo[a][b][c] but will short circuit to return None if something on the query is None. | def traverse_dict(obj: T.Mapping[str, _T], query: str) -> T.Optional[_T]:
query_split = query.split('__')
cur_obj: T.Optional[T.Union[_T, T.Mapping[str, _T]]] = obj
for name in query_split:
assert isinstance(cur_obj, Mapping) # help mypy
cur_obj = cur_obj.get(name, None)
if cur_obj... | [
"def access(dictionary, nested_keys):\r\n\r\n for index, key in enumerate(nested_keys):\r\n\r\n print index, key\r\n\r\n try:\r\n if dictionary.has_key(key):\r\n if nested_keys[index + 1:] != []:\r\n return access(dictionary[key], nested_keys[index + 1:]... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Scans the log folder for missing files | def scan_logfiles(self):
import os
import re
import itertools
def ranges(i):
for a, b in itertools.groupby(enumerate(i), lambda x_y: x_y[1] - x_y[0]):
b = list(b)
yield b[0][1], b[-1][1]
expected = list(range(1, self.njobs + 1))
... | [
"def _purge_useless_logs(self):\n for logf in os.listdir(self.resultsdir):\n\n log_path = os.path.join(self.resultsdir, logf)\n\n # Remove empty files\n if os.path.isfile(log_path) and os.path.getsize(log_path) == 0:\n os.remove(log_path)\n\n # Remov... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Scans the output folder for missing files | def scan_output(self):
import os
import re
import itertools
def ranges(i):
for a, b in itertools.groupby(enumerate(i), lambda x_y1: x_y1[1] - x_y1[0]):
b = list(b)
yield b[0][1], b[-1][1]
expected = list(range(1, self.njobs + 1))
... | [
"def check_output_empty(self):\n # src_directory_list = os.listdir(self.src_directory)\n is_empty_output = True\n for root, dirs, files in os.walk(self.src_directory):\n if len(files) > 0:\n is_empty_output = False\n break\n if is_empty_output:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Run the calculations for a subset of the parameter space | def run_subset(self, jobid, outputfile):
import numpy as np
import itertools as it
# Runs the function supplied by config on a a fraction of the parameter space
# Fraction depends on the number of total jobs
setup = self.conf['setup_func']()
results = []
from tim... | [
"def executeParamStudy(self):\n\n # --- Create vectors of varying values for each respective parameter that was selected for the study\n if self.inputData.c['paramA']:\n aRange = np.linspace(self.inputData.c['aStart'], self.inputData.c['aEnd'], self.inputData.paramSteps)\n else:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Send genre then mood. e.g. !letschill action silly | def letschill(self, message, args):
movie_list = []
genre = args[0].lower()
try:
mood = args[1].lower()
except:
mood = None
if not mood:
mood = random.choice(moods)
elif mood not in moods:
return "Please use the moods comman... | [
"def mood():",
"def genrephrase(self, category, genre):\n\n s = self.simplenlg.SPhraseSpec(self.simplenlg.nlgfactory)\n s.setSubject(self.pronoun)\n s.setVerb(\"like\")\n\n if category == 'books and literature':\n clause = self.simplenlg.nlgfactory.createClause()\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Our goal is to get the edges split into high/low groups but we do not care what the final orienation is of the edges. Each edge can either be in its final orientation or not so there are (2^12)/2 or 2048 possible permutations. The /2 is because there cannot be an odd number of edges not in their final orientation. | def eo_edges(self):
permutations = []
original_state = self.state[:]
original_solution = self.solution[:]
tmp_solution_len = len(self.solution)
# Build a list of the wing strings at each midge
wing_strs = []
for (_, square_index, partner_index) in midges_recolor... | [
"def groupsizes(total, len):\n if len == 1:\n yield (total,)\n else:\n for i in range(1, total - len + 1 + 1):\n for perm in groupsizes(total - i, len - 1):\n yield (i,) + perm",
"def get_seed_chunks(\n graph: nx.Graph,\n num_chunks: int,\n num_dists: int,\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
phase5 requires a 4edge combo where none of the edges are in the zplane. phase4 will put a 4edge combo into that state. There are 12!/(4!8!) or 495 different 4edge combinations. Try them all and see which one has the lowest phase4 cost. | def find_first_four_edges_to_pair(self):
original_state = self.state[:]
original_solution = self.solution[:]
original_solution_len = len(self.solution)
results = []
min_phase4_solution_len = 99
min_phase4_high_low_count = 0
for (wing_str_index, wing_str_combo) i... | [
"def stage_first_four_edges_555(self):\n\n # return if they are already staged\n if self.x_plane_edges_are_l4e():\n log.info(\"%s: first L4E group in x-plane\" % self)\n return\n\n if self.y_plane_edges_are_l4e():\n log.info(\"%s: first L4E group in y-plane, mov... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
returns the OID for row | def oid(self):
if self.oid_field_ob:
return self.atts[self.oid_field_ob.name]
return None | [
"def get_nature_id(row):\n return row[\"NVRID\"]",
"def oid_column_name(self):\n raise NotImplementedError()",
"def _get_col_id(self):",
"def orcid_identity(self):\n from api.models.inspirehep import OrcidIdentity\n try:\n return OrcidIdentity.objects.get(orcid_value=self['v... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
method to return MapService Object, supports wildcards | def get_MapService(self, name_or_wildcard):
full_path = self.get_service_url(name_or_wildcard)
if full_path:
return MapService(full_path, token=self.token) | [
"def service_mapping():\n return \"/foo/{anything}/bar\"",
"def get_map_search(self):\n return # osid.mapping.MapSearch",
"def _map_service_to_driver(self, service):\n\n if service in mapper:\n return mapper[service]\n return service",
"def request_map():\n rospy.logi... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return memory location in string | def memory_location(value):
return hex(id(value)) | [
"def string_read( self, mem_addr ):\n\t\tstorage_length = self.byte_read( mem_addr )\n\t\tbin = struct.unpack(\"%is\"%storage_length, self.read(mem_addr+1, storage_length) )[0]\n\t\treturn bin.decode(\"UTF-8\").rstrip('\\x00')",
"def string_get(self, ypos, xpos, length):\n # the screen's co-ordinates are 1... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Downloads the quickdraw data for the supplied class_name | def download_examples_for_class(class_name, temp_dir):
class_url = class_name.replace('_', '%20')
download_url = QUICKDRAW_NUMPY_BASE_URL + f'{class_url}.npy'
download_filepath = os.path.join(temp_dir, f'{class_name}.npy')
file_already_exists = os.path.isfile(download_filepath)
if (not file_already_exists):
... | [
"def get_class_data(classname, fname=None, **kwargs):\n \n # options for filter and page size\n flt = kwargs.get(\"flt\", \"\")\n page_size = kwargs.get(\"page_size\", 75000)\n page = kwargs.get(\"page\", 0)\n if len(flt)>0: flt=\"&%s\" % flt\n if \"order-by\" not in flt: flt=\"&order-by=%s.dn%s\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Loads the quickdraw training data for the supplied class_name into a numpy array in mmap mode The data will not be loaded into memory, instead just reading from disk which allows reading a smal set of examples without loading all the examples into memory | def load_examples_for_class(class_name, examples_dir, mmap_mode='r'):
examples_filepath = os.path.join(examples_dir, f'{class_name}.npy')
return np.load(examples_filepath, mmap_mode=mmap_mode) | [
"def download_examples_for_class(class_name, temp_dir):\n class_url = class_name.replace('_', '%20')\n download_url = QUICKDRAW_NUMPY_BASE_URL + f'{class_url}.npy'\n download_filepath = os.path.join(temp_dir, f'{class_name}.npy')\n file_already_exists = os.path.isfile(download_filepath)\n\n if (not file_alread... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the current transaction id stored in session, otherwise generate one. | def _get_transaction(self, request):
guid = request.session.get('transaction_id', None)
if not guid:
guid = str(uuid.uuid4())
request.session['transaction_id'] = guid
return guid | [
"def GetNextTransactionID():\r\n global TransactionID\r\n\r\n # Wrap the ID around.\r\n if TransactionID <= -32767:\r\n TransactionID = 0\r\n\r\n # Decrement it.\r\n TransactionID = TransactionID - 1\r\n\r\n return TransactionID",
"def _get_next_transaction_id(self):\r\n transactio... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Does an initial upload of documents and gets the generated eFiling Hub url. | def upload(self, request, files, parties=None):
# Find the transaction id .. this will be a unique guid generated by eDivorce thats passed to Efiling Hub. We
# will tie it to the session.
transaction_id = self._get_transaction(request)
bce_id = self._get_bceid(request)
# if bce... | [
"def get_blob_upload_url():\n\n return '{blob_api_path}/uploadblob'.format(blob_api_path=BLOB_API_COMMON_PATH)",
"def get_file_upload_url(self):\n res = self.instamojo_api_request(method='GET', path='offer/get_file_upload_url/')\n return res",
"def get_upload_url(self):\n context = aq_in... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
A factory for DetectBlanksWrapper classes. | def DetectBlanks(DriverType=None):
from xia2.Driver.DriverFactory import DriverFactory
DriverInstance = DriverFactory.Driver(DriverType)
class DetectBlanksWrapper(DriverInstance.__class__):
def __init__(self):
super(DetectBlanksWrapper, self).__init__()
self.set_executabl... | [
"def _create_wrapper(cls_spec, element_info, myself):\n # only use the meta class to find the wrapper for BaseWrapper\n # so allow users to force the wrapper if they want\n if cls_spec != myself:\n obj = object.__new__(cls_spec)\n obj.__init__(element_info)\n re... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
build wordnets from standard list | def main():
word_nets = []
mood_list = open("mood_list.txt","r").readlines()
for m in mood_list:
m = m.replace('\n', '')
raw_input()
print "MOOD :", m
synonyms = wn.synsets(m, pos=wn.ADJ)
print synonyms
for synonym in synonyms:
for lem in synonym.lemmas:
print lem.name | [
"def make_vocab(word_list):\n vocab = {}\n for i, word in enumerate(word_list):\n vocab[word] = Vocab(count=1, index=i)\n return vocab",
"def getWordEmbeddings(self, sentence, train):\n \n for root in sentence:\n c = float(self.wordsCount.get(root.norm, 0))\n dr... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Parses the document for answers to the question why. | def extract(self, document):
candidate_list = []
for i in range(document.length):
for candidate in self._evaluate_tree(document.posTrees[i]):
candidate_list.append([candidate[0], candidate[1], i])
candidate_list = self._evaluate_candidates(document, candidate_list)
... | [
"def parse_question_answers(self):\n output = {}\n zfile = zipfile.ZipFile(self.filename)\n form = zfile.read('word/document.xml')\n xmlroot = ET.fromstring(form)\n for field in xmlroot.getiterator():\n field_tag = field.find(self.TAG_FIELDPROP+'/'+self.TAG_FIELDTAG)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Put each pulse in a separate bin, mimicking the first pass | def prebin_pulses(pulses, readout_window):
edges = [readout_window.start]
charges = [0]
for p in pulses:
# Add one bin containing the pulse followed by
# a second that continues to the next pulse
edges.append(p.time)
charges.append(p.charge)
edges.append(p.time+p.width)
charges.append(0)
edges.append(re... | [
"def pulse_simple(self):\r\n # All time are in us\r\n t1_laser = 100 # First time to turn ON the laser\r\n t2_laser = 650 # Last time to turn ON the laser\r\n dt_laser = 30 # Pulse duration of the laser \r\n dt_trig = 10 # Duration of the pulse for the trigger\r\n dt_pulse... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Print crossword assignment to the terminal. | def print(self, assignment):
letters = self.letter_grid(assignment)
for i in range(self.crossword.height):
for j in range(self.crossword.width):
if self.crossword.structure[i][j]:
print(letters[i][j] or " ", end="")
else:
... | [
"def echo() -> None:\n from efro.terminal import Clr\n clrnames = {n for n in dir(Clr) if n.isupper() and not n.startswith('_')}\n first = True\n out: List[str] = []\n for arg in sys.argv[2:]:\n if arg in clrnames:\n out.append(getattr(Clr, arg))\n else:\n if not f... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Save crossword assignment to an image file. | def save(self, assignment, filename):
from PIL import Image, ImageDraw, ImageFont
cell_size = 100
cell_border = 2
interior_size = cell_size - 2 * cell_border
letters = self.letter_grid(assignment)
# Create a blank canvas
img = Image.new(
"RGBA",
... | [
"def save_image(img, filename):\n cv2.imwrite(filename, img)",
"def save(self, filename):\n assert(self.canvas is not None)\n self.canvas.update()\n self.canvas.postscript(file=f'{filename}.eps')\n img = Image.open(f'{filename}.eps')\n img.save(f'{filename}.png', 'png')",
"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Update `self.domains` such that each variable is nodeconsistent. (Remove any values that are inconsistent with a variable's unary constraints; in this case, the length of the word.) | def enforce_node_consistency(self):
# loop thru self.domain to access each variable
for var, domain in self.domains.items():
# remove words that do not fit the length of the space
inconsistent = []
for word in domain:
if len(word) != var.length:
... | [
"def preProcess(self, variables, domains, constraints, vconstraints):\n if len(variables) == 1:\n variable = variables[0]\n domain = domains[variable]\n for value in domain[:]:\n if not self(variables, domains, {variable: value}):\n domain.re... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Make variable `x` arc consistent with variable `y`. To do so, remove values from `self.domains[x]` for which there is no possible corresponding value for `y` in `self.domains[y]`. Return True if a revision was made to the domain of `x`; return False if no revision was made. | def revise(self, x, y):
revised = False
# binary constraint: neighbor overlap
# assess domain of x for consistency with domain of y (i.e. is overlap the same letter?)
if self.crossword.overlaps[x, y] is None:
# then no overlap between x and y, no revisions made
... | [
"def __check_possible_domain(self, curr_variable, assignment, variables_copy):\n var_obj = variables_copy[curr_variable]\n # if the variable has an assignment already - do not check it!\n if var_obj.value is not None:\n return False\n copy_of_possible_domain = deepcopy(var_obj... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Update `self.domains` such that each variable is arc consistent. If `arcs` is None, begin with initial list of all arcs in the problem. Otherwise, use `arcs` as the initial list of arcs to make consistent. Return True if arc consistency is enforced and no domains are empty; return False if one or more domains end up em... | def ac3(self, arcs=None):
# setup
# queue = arcs
if arcs is None:
arcs = []
# grab all neighbor pairs in the problem and add them to arcs
for pair, overlaps in self.crossword.overlaps.items():
# Crossword.overlaps is dict of ALL pairs, need jus... | [
"def ac3(csp, arcs=None):\n\n queue_arcs = deque(arcs if arcs is not None else csp.constraints.arcs())\n\n # TODO implement this\n while queue_arcs:\n var = queue_arcs.popleft()\n\n rev = False\n cs = csp.constraints[var[0]]\n\n for i in var[0].domain:\n satisfied = F... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return True if `assignment` is complete (i.e., assigns a value to each crossword variable); return False otherwise. | def assignment_complete(self, assignment):
if len(assignment) == len(self.crossword.variables):
return True
return False | [
"def partial_assignment(self, assignment: Iterable) -> bool:\n for literal in assignment:\n # Remove corresponding variable from the unassigned set of the formula and add literal to assignment stack\n self.unassigned.remove(abs(literal))\n self.assignment_stack.append(literal... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return True if `assignment` is consistent (i.e., words fit in crossword puzzle without conflicting characters); return False otherwise. | def consistent(self, assignment):
# check each assigned word for length, uniqueness, proper overlap
# unique
if list(assignment.values()) != list(set(assignment.values)):
return False
for var, word in assignment:
# length
if len(word) != var.length:
... | [
"def assignment_complete(self, assignment):\n\n if len(assignment) == len(self.crossword.variables):\n return True\n return False",
"def is_consistent(self, value: int, assignment: dict):\n if self.is_col_occupied(value) or self.is_row_occupied(value) \\\n or self.is... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return an unassigned variable not already part of `assignment`. Choose the variable with the minimum number of remaining values in its domain. If there is a tie, choose the variable with the highest degree. If there is a tie, any of the tied variables are acceptable return values. | def select_unassigned_variable(self, assignment):
# setup
mrv_hueristic = {var: 0 for var in self.crossword.variables if var not in assignment.keys()}
ld_hueristic = {var: 0 for var in self.crossword.variables if var not in assignment.keys()}
# loop
for var in self.crossword.var... | [
"def get_next_unassigned_var(self):\n # No heuristic\n if self.ordering_choice == 0: \n return self.unassigned_vars[0]\n \n # Heuristic 1\n if self.ordering_choice == 1:\n return self.get_most_constrained()\n \n # Heuristic 2\n if self.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
return nearest indx group | def group_idx(self, x):
centers = self.centers
dist = [self.dist_func(x, center) for center in centers]
dist = np.array(dist)
group = np.argmin(dist)
return group | [
"def nearest_clusteroid_index(idx, clusteroids):\n\n clusteroid_dists = clusteroids[:, idx]\n min_dist_val = np.nanmin(clusteroid_dists)\n min_dist_idxs = np.nonzero(clusteroid_dists == min_dist_val)[0]\n if not min_dist_idxs.any():\n return np.random.choice(clusteroids.shape[0])\n return np.n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Show rate of notification by weekday. | def weekday_rate(self, disease=None, **kwargs):
data = self.region.pydemic.epidemic_curve(disease, diff=True)
data = trim_weeks(data)
return plt.weekday_rates(data, **kwargs) | [
"def week():",
"def weekday_chart(flts):\n global HTML_FILE\n if START_WITH.lower() in [\"sun\", \"sunday\", \"sonntag\", \"so\"]: # accept different entries for Sunday ...\n wd_order = WEEKDAY_DICT_SUN\n else:\n wd_order = WEEKDAY_DICT_MON\n flts_by_dow = flts[\"WEEKDAY\"].value_counts... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a plot of cases and deaths | def cases_and_deaths(self, disease=None, **kwargs):
curves = self.region.pydemic.epidemic_curve(disease)
kwargs.setdefault("tight_layout", True)
return plt.cases_and_deaths(curves, **kwargs) | [
"def death_and_cases_plot(cases_dataframe, death_dataframe, country_name, y_axis_type):\n # create a figure object with width and height\n death_and_cases_fig = figure(x_axis_type=\"datetime\", y_axis_type=y_axis_type,\n width=1000, height=400, sizing_mode='fixed')\n # creat... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |