query stringlengths 9 9.05k | document stringlengths 10 222k | negatives listlengths 19 20 | metadata dict |
|---|---|---|---|
Returns a text representation of the candidate at the given index. | def get_candidate_text(json_dict, idx):
# No candidate at this index.
if idx < 0 or idx >= len(json_dict["passage_answer_candidates"]):
raise ValueError("Invalid index for passage candidate: {}".format(idx))
return get_text_span(json_dict, json_dict["passage_answer_candidates"][idx]) | [
"def get_text(self, index=str) -> str:\n level = len(index) - 1 # Gets the number of numbers in the index\n return self.get_block(index=index)[1][index][0]\n\n # ToDo implement what happens if it's not there",
"def get_block_text(self, index=str) -> str:\n level = len(index) - 1 # Ge... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Converts a TyDi 'entry' from `create_entry_from_json` to `TyDiExample`. | def to_tydi_example(entry, is_training):
if is_training:
answer = make_tydi_answer(entry["contexts"], entry["answer"])
start_byte_offset = answer.offset
end_byte_offset = answer.offset + byte_len(answer.text)
else:
answer = None
start_byte_offset = None
end_byte_... | [
"def api_create_example(meaning_id, example):\r\n p_validate_argument('meaning_id', meaning_id, int, 'example', example, str)\r\n\r\n example = p_filter_example(example)\r\n\r\n new_example = Example(meaning_id = meaning_id, text = example)\r\n new_example.save()\r\n return new_example",
"def creat... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Representacion en cadena de la clase Parroquia. | def __unicode__(self):
return self.parroquia | [
"def parcela(self):\n return self._parcela",
"def __init__(self, pais, tipo):\n\t\tself.pais = pais\n\t\tself.tipo = tipo",
"def __init__(self):\n self.vida : int = 60;\n self.hechizos : int = 3;\n self.flechas : int = 7;",
"def __init__(self, diccionario):\n self.numero = d... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return True if this element is an instance of the given subclass. If a category string is specified, then both subclass and category matches are required. | def _isA(self, elementClass, category = ''):
if not isinstance(self, elementClass):
return False
if category and self.getCategory() != category:
return False
return True | [
"def is_subclass(parent_class, child_class_name):\n for child_class in parent_class.__subclasses__():\n if child_class.__name__ == child_class_name:\n return True\n return False",
"def __subclasscheck__(self, subclass):\n\n if isinstance(subclass, ObjCClass):\n return boo... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set the typed value of an input by its name, creating a child element to hold the input if needed. | def _setInputValue(self, name, value, typeString = ''):
method = getattr(self.__class__, "_setInputValue" + getTypeString(value))
return method(self, name, value, typeString) | [
"def set_input(self, name, value):\n\n if self._lxml_form is None:\n self.choose_form_by_element('.//*[@name=\"%s\"]' % name)\n elem = self.form.inputs[name]\n\n processed = False\n if getattr(elem, 'type', None) == 'checkbox':\n if isinstance(value, bool):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
(Deprecated) Return a vector of all Parameter elements. | def _getParameters(self):
warnings.warn("This function is deprecated; parameters have been replaced with uniform inputs in 1.38.", DeprecationWarning, stacklevel = 2)
return list() | [
"def to_vector(self):\n return self.params",
"def parameters_to_vector(self) -> np.ndarray:\n return th.nn.utils.parameters_to_vector(self.parameters()).detach().cpu().numpy()",
"def parameters_to_vector(self) -> np.ndarray:\n return nn.utils.parameters_to_vector(self.parameters()).detach()... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
(Deprecated) Return the value string of a parameter by its name. | def _getParameterValueString(self, name):
warnings.warn("This function is deprecated; parameters have been replaced with uniform inputs in 1.38.", DeprecationWarning, stacklevel = 2)
return "" | [
"def ParameterName(self) -> str:",
"def getvalue(self,name):\n return self._parameters[name].value",
"def get_param_with_name(self, param_name):\n return self.params[param_name]",
"def getParameter(self, name):",
"def format_parameter(self, name):\n return self._param_dict[name].f_forma... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
(Deprecated) Add a BindInput to this shader reference. | def _addBindInput(self, name, type = DEFAULT_TYPE_STRING):
warnings.warn("This function is deprecated; shader references have been replaced with shader nodes in 1.38.", DeprecationWarning, stacklevel = 2)
return self.addInput(name, type) | [
"def _addBindParam(self, name, type = DEFAULT_TYPE_STRING):\n warnings.warn(\"This function is deprecated; shader references have been replaced with shader nodes in 1.38.\", DeprecationWarning, stacklevel = 2)\n return self.addInput(name, type)",
"def _getBindInputs(self):\n warnings.warn(\"This function... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
(Deprecated) Return a vector of all BindInput elements in this shader reference. | def _getBindInputs(self):
warnings.warn("This function is deprecated; shader references have been replaced with shader nodes in 1.38.", DeprecationWarning, stacklevel = 2)
return self.getInputs() | [
"def _getBindParams(self):\n warnings.warn(\"This function is deprecated; shader references have been replaced with shader nodes in 1.38.\", DeprecationWarning, stacklevel = 2)\n return list()",
"def _getBindTokens(self):\n warnings.warn(\"This function is deprecated; shader references have been replaced... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
(Deprecated) Add a BindParam to this shader reference. | def _addBindParam(self, name, type = DEFAULT_TYPE_STRING):
warnings.warn("This function is deprecated; shader references have been replaced with shader nodes in 1.38.", DeprecationWarning, stacklevel = 2)
return self.addInput(name, type) | [
"def _addBindInput(self, name, type = DEFAULT_TYPE_STRING):\n warnings.warn(\"This function is deprecated; shader references have been replaced with shader nodes in 1.38.\", DeprecationWarning, stacklevel = 2)\n return self.addInput(name, type)",
"def _getBindParams(self):\n warnings.warn(\"This function... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
(Deprecated) Return a vector of all BindParam elements in this shader reference. | def _getBindParams(self):
warnings.warn("This function is deprecated; shader references have been replaced with shader nodes in 1.38.", DeprecationWarning, stacklevel = 2)
return list() | [
"def _getBindInputs(self):\n warnings.warn(\"This function is deprecated; shader references have been replaced with shader nodes in 1.38.\", DeprecationWarning, stacklevel = 2)\n return self.getInputs()",
"def _getBindTokens(self):\n warnings.warn(\"This function is deprecated; shader references have bee... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
(Deprecated) Return a vector of all BindToken elements in this shader reference. | def _getBindTokens(self):
warnings.warn("This function is deprecated; shader references have been replaced with shader nodes in 1.38.", DeprecationWarning, stacklevel = 2)
return list() | [
"def _getBindParams(self):\n warnings.warn(\"This function is deprecated; shader references have been replaced with shader nodes in 1.38.\", DeprecationWarning, stacklevel = 2)\n return list()",
"def _getBindInputs(self):\n warnings.warn(\"This function is deprecated; shader references have been replaced... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
(Deprecated) Return a vector of all shader references in this material element. | def _getShaderRefs(self):
warnings.warn("This function is deprecated; shader references have been replaced with shader nodes in 1.38.", DeprecationWarning, stacklevel = 2)
return getShaderNodes(self) | [
"def _getActiveShaderRefs(self):\n warnings.warn(\"This function is deprecated; shader references have been replaced with shader nodes in 1.38.\", DeprecationWarning, stacklevel = 2)\n return getShaderNodes(self)",
"def shaders(self):\n\n shaders = []\n shaders.extend(self._verts)\n sha... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
(Deprecated) Return a vector of all shader references in this material element, taking material inheritance into account. | def _getActiveShaderRefs(self):
warnings.warn("This function is deprecated; shader references have been replaced with shader nodes in 1.38.", DeprecationWarning, stacklevel = 2)
return getShaderNodes(self) | [
"def _getShaderRefs(self):\n warnings.warn(\"This function is deprecated; shader references have been replaced with shader nodes in 1.38.\", DeprecationWarning, stacklevel = 2)\n return getShaderNodes(self)",
"def shaders(self):\n\n shaders = []\n shaders.extend(self._verts)\n shaders.e... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set the value of a geomprop by its name, creating a child element to hold the geomprop if needed. | def _setGeomPropValue(self, name, value, typeString = ''):
method = getattr(self.__class__, "_setGeomPropValue" + getTypeString(value))
return method(self, name, value, typeString) | [
"def update_simple(parent, name, value):\n element = parent.find('./' + name) \n\n if element is None:\n element = ET.SubElement(parent, name)\n element.text = value\n else:\n element.text = value",
"def add_geomean_to_product_data(product, prop_name, geomean_val):\n\tfor prop_data_list in product['da... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
(Deprecated) Add a material element to the document. | def _addMaterial(self, name):
warnings.warn("This function is deprecated; call Document.addMaterialNode() instead.", DeprecationWarning, stacklevel = 2)
return self.addMaterialNode(name) | [
"def addMaterial(self, material):\n\n return self.__fig.addMaterial(material)",
"def add_material(self, material):\n\n material.index = len(self.materials)\n self.materials[material.name] = material",
"def append_material(self, material):\n # First check if asset attribute exists; if... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
(Deprecated) Return a vector of all materials in the document. | def _getMaterials(self):
warnings.warn("This function is deprecated; call Document.getMaterialNodes() instead.", DeprecationWarning, stacklevel = 2)
return self.getMaterialNodes() | [
"def collect_materials(self):\n materials = []\n for term in self.terms:\n materials.extend(term.get_materials(join=True))\n\n return materials",
"def get_all_materials():\n return ['cinderblock', 'paper', 'carpet', 'drywall', 'wood', 'soil', 'none']",
"def info_materials_poly... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the default data search path. | def getDefaultDataSearchPath():
return FileSearchPath(os.path.dirname(__file__)) | [
"def _get_default_path(self):\n return os.path.join(cfg.DATA_DIR, 'visual_genome')",
"def get_default_data_dir(self):\n data_dir_path = os.path.join(self.comicsite.short_name,self.folder_prefix,self.cleantitle)\n return data_dir_path",
"def get_default_data_dir(self):\n return self._curr... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return list of default data library folders | def getDefaultDataLibraryFolders():
return [ 'libraries' ] | [
"def get_default_paths():\n DATA_ROOT = os.environ.get(\"DATA_ROOT\", \"data\")\n defaults = {\n \"TOKENIZE_DATA_DIR\": DATA_ROOT + \"/tokenize\",\n \"MWT_DATA_DIR\": DATA_ROOT + \"/mwt\",\n \"LEMMA_DATA_DIR\": DATA_ROOT + \"/lemma\",\n \"POS_DATA_DIR\": DATA_ROOT + \"/pos\",\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get a list of objects labeled as frame guides in the current 3D scene. | def get_guides(data):
return data.groups["Frames"].objects | [
"def get_selected_faces(obj):\n out = []\n for i in range(len(obj.data.polygons)):\n # get selected faces\n poly = obj.data.polygons[i]\n if poly.select:\n face_info = SelectedFaceInfo(\n poly.normal.copy(), list(poly.loop_indices))\n out.append(face_i... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the reference frame type corresponding to a particular guide. | def get_guide_type(guide):
# Maintained by naming convention in the Blender files. Sub-optimal.
try:
return guide.name[guide.name.rindex(".") + 1:]
except:
return None | [
"def getComponentType(cls):\n\n return 'Guide'",
"def get_type(self):\n try:\n return Message.FRAMES[self.get_frame_id()]\n except KeyError:\n return 'invalid'",
"def _GetReferenceObject(type_name: str) -> SchemaReference:\n return {\n \"$ref\": f\"#/components/s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Randomize the position of an object `obj` along some linear guide path `guide`. | def randomize_position(obj, guide):
p1, p2 = get_guide_endpoints(guide)
t = random.random()
target_point = p1 + t * (p2 - p1)
# update X and Y coordinates.
obj.location[0] = target_point[0]
obj.location[1] = target_point[1]
return t | [
"def randomize_distance(obj, guide, scale_bounds=(-2, 0)):\n p1, p2 = get_guide_endpoints(guide)\n midpoint = p1 / 2 + p2 / 2\n\n # Get vector perpendicular to the guide.\n diff_rot = Matrix.Rotation(math.pi / 2, 3, 'Z') * (p2 - p1)\n\n scale_factor = scale_bounds[0] + random.random() * (scale_bounds... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Center the position of an object `obj` along a linear guide path `guide`, and randomize its distance on the axis perpendicular to that guide. | def randomize_distance(obj, guide, scale_bounds=(-2, 0)):
p1, p2 = get_guide_endpoints(guide)
midpoint = p1 / 2 + p2 / 2
# Get vector perpendicular to the guide.
diff_rot = Matrix.Rotation(math.pi / 2, 3, 'Z') * (p2 - p1)
scale_factor = scale_bounds[0] + random.random() * (scale_bounds[1] - scale_... | [
"def randomize_position(obj, guide):\n p1, p2 = get_guide_endpoints(guide)\n t = random.random()\n target_point = p1 + t * (p2 - p1)\n\n # update X and Y coordinates.\n obj.location[0] = target_point[0]\n obj.location[1] = target_point[1]\n\n return t",
"def center(self, obj):\n return... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Move candidate referents to random positions in the given reference frames. `candidate_setting` is of the form `[(person, guide_path), (person2, guide_path), ...]` | def prepare_scene(data, candidate_setting, randomization_mode):
manipulations = defaultdict(dict)
for person, guide in candidate_setting.items():
if randomization_mode == "none":
# Center the candidate along the guide.
p1, p2 = get_guide_endpoints(guide)
target = p1 /... | [
"def switch_points(mutated_genome,index):\n point_index1 = random.randint(0,max(0,len(mutated_genome[index][2])-1))\n point_index2 = random.randint(0,max(0,len(mutated_genome[index][2])-1))\n temp = mutated_genome[index][2][point_index1]\n mutated_genome[index][2][point_index1] = mutated_genome[index][2][po... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Allows leastsq to take bounds if minimize function is missing. | def myleastsq(errfunc0,x0,args=None,bounds=None,**exkw):
from scipy import optimize
if hasattr(optimize,'minimize'):
def errfunc(x,*iargs):
return sum(errfunc0(x,*iargs)**2)
if args is not None: exkw['args'] = args
res = optimize.minimize(errfunc,x0[:],bounds=bounds,**exkw)
... | [
"def fit_leastsq(self, leastsq_args: dict):\n try:\n opt_res = optimize.least_squares(**leastsq_args)\n except ValueError as err:\n raise CalculationError(\n f\"Fitting routine for {self.name} failed with error:\\n\\t{err}\"\n ) from err\n if not ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns spherical radii for provided volumes. | def sphrad(vol):
return (3.*vol/(4.*np.pi))**(1./3.) | [
"def sphere_volume(r):\n return (4/3) * 3.14159 * r**3",
"def sphere_volume(r):\n return 4*3.14159*(r**3)/3",
"def sphere_volume(r) :\n return (4 / 3) * np.pi * r ** 3",
"def get_sphere_volume(radius):\n import math\n return (4/3)*math.pi*radius**3",
"def sphere_volume(r):\n return (4/... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Change Karma Make sure that the user can make a karma change using rate limiting and return whether or not the karma value was added or changed | def _change_karma(self, name, change):
can_change = self._apply_rate_limit()
if not can_change: return False
res = self.bot.db.execute('SELECT target, karma FROM karma')
for target in res.fetchall():
if target[0].lower() == name.lower():
self.bot.db.execute('U... | [
"def karmaChanged(objectType, objectKey, karma):",
"def _change_karma(self, nick, target, mode):\n if nick == target:\n return \"You can't modify your own karma.\"\n if target in self.karma and (datetime.datetime.now() -\n self.karma[target][2]).seconds < 5:\n re... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Apply Rate Limit Check how frequently the current user has run karma commands and, if they exceed a certain threshold (30 seconds) return False so they don't make any karma changes | def _apply_rate_limit(self):
update_time = time()
user_name = self.bot.user.full_name
if user_name in self.tokens.keys():
last_change = self.tokens[user_name][0]
# Add 1 token for every 30 seconds from the last change
added_tokens = int((update_time - last_cha... | [
"def _rate_limiter(self):\n delta_t_passed = datetime.now() - self.last_save\n self.rate_allowance += delta_t_passed.total_seconds() * self.rate_limit\n if (self.rate_allowance < 1.0): # needs to be float (i.e not an integer)\n return False\n else:\n self.last_save ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Compute the total duty percentage for each purchase line. there is an extra duty for some vendors.If the 'extra_duty' field's value is true,then we use a duty perc(0.288 most probably) for each 144 qtys | def compute_total_customs_duty(self):
for rec in self:
total = 0.0
extra_duty = 0.0
price_total = rec.quantity * rec.unit_price
# total = (price_total * duty_percentage)/100
rec.price_total = price_total
# for hts in rec.hts_ids:
# ... | [
"def get_duty_percentage(self):\n container_line_ids = self\n hbl_customs_obj = self.env['hbl.customs.duty']\n for line in container_line_ids:\n p_line = line.purchase_line\n #Get the supplier from product by using po supplier id.\n product_supplier_id = p_line.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get information related to a specific Smart Group. Get information related to a specific Smart Group. | def get_by_id(
self, smart_group_id, custom_headers=None, raw=False, **operation_config):
# Construct URL
url = self.get_by_id.metadata['url']
path_format_arguments = {
'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str'... | [
"def get_by_id(\n self,\n smart_group_id, # type: str\n **kwargs # type: Any\n ):\n # type: (...) -> \"models.SmartGroup\"\n cls = kwargs.pop('cls', None) # type: ClsType[\"models.SmartGroup\"]\n error_map = {\n 401: ClientAuthenticationError, 404: Resource... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the history a smart group, which captures any Smart Group state changes (New/Acknowledged/Closed) . | def get_history(
self, smart_group_id, custom_headers=None, raw=False, **operation_config):
# Construct URL
url = self.get_history.metadata['url']
path_format_arguments = {
'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, '... | [
"def get_history(\n self,\n smart_group_id, # type: str\n **kwargs # type: Any\n ):\n # type: (...) -> \"models.SmartGroupModification\"\n cls = kwargs.pop('cls', None) # type: ClsType[\"models.SmartGroupModification\"]\n error_map = {\n 401: ClientAuthenti... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Attenuators out, beamstop in, | def alignment_stop():
smi = SMI_Beamline()
yield from smi.modeMeasurement()
proposal_id('2023_2', '311564_Pettersson') | [
"def beam_align():\n\n # do nothing if there is a sample mounted to avoid collisions\n if smart_magnet.sample_detect.get() == 0:\n raise Exception(\"Sample mounted on gonio! Avoided collision\")\n\n # wait for attenuators to finish moving\n yield from bps.abs_set(mxatten, 0.002)\n yield from b... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
RE(run_loop_measurement(t=1, name='1bl_PEI_10mM', loops=7, pump_t=210, total_t=720, jump_x=10)) Take measurements in the loop Sample has to be aligned before starting the script and theta angle at 0 deg (flat sample). | def run_loop_measurement(t=0.5, name='test', loops=4, pump_t=180, total_t=600, jump_x=10):
incident_angles = [0.1, 0.4]
waxs_arc = [20, 0]
user = "TP"
condition = (
( -1 < waxs.arc.position )
and ( waxs.arc.position < 1 )
and (waxs_arc[0] == 20)
)
if condition:
... | [
"def MotorDimensionsCal(LoopSignal):\n # Variable defintion \n BAirgap = LoopSignal['BAirgap']\n L = LoopSignal['L']\n D = LoopSignal['D']\n hm = LoopSignal['hm']\n J = LoopSignal['J']\n g = LoopSignal['g']\n Np = LoopSignal['Np']\n Nm = LoopSignal['Nm']\n f = LoopSignal['f']\n m = ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
LZW komprese dict_of_abc je vstupni slovnik dat na kazdem indexu slovniku je list v prubehu komprese se do nej pridavaji polozky list_of_data je posloupnost cisel ke kompresi | def do_LZW_Compression(dict_of_abc, list_of_data):
# rozdil mezi None a [] je v pouziti metody extend na listu
result = []
P = []
C = [] # C je vzdy jeden prvek ze vstupu
PC = []
#how it works video xplanation https://www.youtube.com/watch?v=MQ4ObKv2L_M
for i in range(len... | [
"def do_LZW_DeCompression(dict_of_abc, list_of_data):\n \n #https://www.youtube.com/watch?v=MQM_DsX-LBI\n \n out = []\n predchozi_out = []\n for i in range(len(list_of_data)):\n new = []\n new.extend(predchozi_out)\n if list_of_data[i] in dict_of_abc:\n o = dict_of_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
LZW Dekomprese dict_of_abc je vstupni slovnik dat na kazdem indexu slovniku je list v prubehu komprese se do nej pridavaji polozky list_of_data je posloupnost cisel pro dekompresi | def do_LZW_DeCompression(dict_of_abc, list_of_data):
#https://www.youtube.com/watch?v=MQM_DsX-LBI
out = []
predchozi_out = []
for i in range(len(list_of_data)):
new = []
new.extend(predchozi_out)
if list_of_data[i] in dict_of_abc:
o = dict_of_abc[list_of_dat... | [
"def do_LZW_Compression(dict_of_abc, list_of_data):\n \n # rozdil mezi None a [] je v pouziti metody extend na listu\n \n result = []\n P = []\n C = [] # C je vzdy jeden prvek ze vstupu\n PC = []\n \n #how it works video xplanation https://www.youtube.com/watch?v=MQ4ObKv2L_M\n \n fo... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
dict_of_abc vypada napriklad takto | def dict_cointains_list(dict_of_abc, item_list):
values = list(dict_of_abc.values())
#projdu vsecky listy ve slovniku
for i in range(len(values)):
#predpokladam ze ve slovniku je
finded = True
for j in range(len(values[i])):
if len(item_list) == len(values[i]):... | [
"def test_get_cases_for_dict(self):\n pass",
"def test_init_kwargs(self):\n x = adict(z=5, y='0', a='x', B=[])\n self.assertEqual([k for k in x.keys()], ['a', 'B', 'y', 'z'])\n self.assertEqual([v for v in x.values()], ['x', [], '0', 5])",
"def test_init_dict(self):\n x = adic... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Load truncation parameters from config or container defaults. | def _get_params(self, container):
if container in TRUNC_SPEC:
self.log.info("Truncating from preset for container {}".format(container))
for key in [
"dataset",
"weight_dataset",
"fixed_precision",
"variance_increase",
... | [
"def load_defaults_for_env_var(self):\n self.parameters = self.defaults",
"def _load_config(self, config):\n\n\n # now config for this class\n # first the defaults\n this_config = {}\n this_config.update(DEFAULT_MAKER_CONFIG)\n\n # now override\n if config is not N... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a telescope object out of the input (either `ProductManager`, `BeamTransfer` or `TransitTelescope`). | def get_telescope(obj):
from drift.core import telescope
try:
return get_beamtransfer(obj).telescope
except RuntimeError:
if isinstance(obj, telescope.TransitTelescope):
return obj
raise RuntimeError("Could not get telescope instance out of %s" % repr(obj)) | [
"def get_beamtransfer(obj):\n from drift.core import manager, beamtransfer\n\n if isinstance(obj, beamtransfer.BeamTransfer):\n return obj\n\n if isinstance(obj, manager.ProductManager):\n return obj.beamtransfer\n\n raise RuntimeError(\"Could not get BeamTransfer instance out of %s\" % re... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a BeamTransfer object out of the input (either `ProductManager`, `BeamTransfer`). | def get_beamtransfer(obj):
from drift.core import manager, beamtransfer
if isinstance(obj, beamtransfer.BeamTransfer):
return obj
if isinstance(obj, manager.ProductManager):
return obj.beamtransfer
raise RuntimeError("Could not get BeamTransfer instance out of %s" % repr(obj)) | [
"def _beam_from_dict(obj):\n return BeamFactory.from_dict(obj)",
"def item(from_, txs):\n return sp.set_type_expr(sp.record(from_ = from_, txs = txs), Transfer.get_type())",
"def _transformation(self) -> Transformation:\n cls = self['transform']\n\n try:\n obj = cls(**{key... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The main function that finds all solutions for a single clue. Uses parser to find all possible parse trees, then calls the solving function for each parsing tree according to its clue type. Returns an ordered list of all possible solutions with score > MIN_SOLUTION VALUE | def solve(clue, solution_format):
# Define parser
grammar_str = GrammarDefinitions.define_grammar(clue)
grammar = nltk.CFG.fromstring(grammar_str)
parser = nltk.ChartParser(grammar)
solutions = []
# Get all possible solutions
for tree in parser.parse(clue):
_handle_abbreviations(tr... | [
"def get_solutions(board, move_list, cur_row, cur_moves):\n\n global ALL_SOLS\n ALL_SOLS = []\n find_solutions_naive(board, move_list, cur_row, cur_moves)\n return ALL_SOLS",
"def solve_complete(puzzle, verbose=False):\n sol = puzzle.extensions()\n s = []\n for i in sol:\n if verbose =... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Solver for double synonym clues | def _solve_double_synonym(parse_tree, solution_format=None):
def _get_value(solution_list, word):
# Gets the value of a word in a solution list
for solution in solution_list:
if solution[0] == word:
return solution[1]
return 0
# Get the two synonym parts
... | [
"def solve(self):",
"def test_synonym(self): \n pass",
"def test_syndome_LUT(self):\r\n syns = []\r\n errvecs = golay._make_3bit_errors()\r\n for errvec in errvecs:\r\n syn = tuple(numpy.mod(numpy.dot(errvec, golay.DEFAULT_H.T), 2))\r\n syns.append(syn)\r\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Solver for anagram clues | def _solve_anagram(parse_tree, solution_format=None):
anag, syn = _get_parts_ignore_EQU(parse_tree)
# Get the anagramed word
anag_word = anag[0]
if not anag_word.label() == 'ANAG_WORD':
anag_word = anag[1]
anag_word = _create_sentence(anag_word, space=False)
syn_sent = _create_sentence... | [
"def anagram_solver(lst):\n for i in range(0, len(lst) + 1):\n for subset in itertools.permutations(lst, i):\n possible = ''\n for letter in subset:\n possible += letter\n if len(possible) == len(lst):\n # itertools.permutations returns smalle... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Solver for hidden word clues | def _solve_hidden_word(parse_tree, solution_format=None):
hidden, syn = _get_parts_ignore_EQU(parse_tree)
# Get the hiding word
hiding_word = hidden[0]
if not hiding_word.label() == 'HID_WORD':
hiding_word = hidden[1]
hiding_word = _create_sentence(hiding_word, space=False)
syn_sent =... | [
"def search_clues(self):\r\n print(\"\\n************Searching Clues************\\n\")\r\n for word_id in self.words.keys():\r\n if not self.words[word_id].see and not self.words[word_id].wth:\r\n clue = pop_backslash(self.words[word_id].clue)\r\n temp = word_d... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given a parse tree with 2 parts, with a possible EQU part in the middle, finds the synonym part and the other part | def _get_parts_ignore_EQU(parse_tree):
first_part = parse_tree[0]
second_part = parse_tree[1]
if second_part.label() == 'EQU':
second_part = parse_tree[2]
if first_part.label() == 'SYN':
syn = first_part
other = second_part
else:
syn = second_part
other = fir... | [
"def _solve_double_synonym(parse_tree, solution_format=None):\n def _get_value(solution_list, word):\n # Gets the value of a word in a solution list\n for solution in solution_list:\n if solution[0] == word:\n return solution[1]\n\n return 0\n\n # Get the two syn... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Parses the abbreviation file to find all possible abbreviations, then calls helper function to update the tree | def _handle_abbreviations(parse_tree):
path = os.path.join(GrammarDefinitions.FOLDER, GrammarDefinitions.ABBREVIATION_FILE)
with open(path, "r") as f:
lines = f.read().splitlines()
abbr_dict = {line.split(GrammarDefinitions.ABBR_SEP)[0]: line.split(GrammarDefinitions.ABBR_SEP)[1] for line in
... | [
"def _replace_abbreviation(parse_tree, abbr_dict):\n if not isinstance(parse_tree, nltk.Tree):\n # Reached a leaf\n return\n\n if parse_tree.label() == 'ABBR':\n # Replace word with its abbreviation\n word = parse_tree[0]\n parse_tree.set_label('WORD')\n parse_tree[0]... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Updates the given tree by replacing the word with its abbreviated form | def _replace_abbreviation(parse_tree, abbr_dict):
if not isinstance(parse_tree, nltk.Tree):
# Reached a leaf
return
if parse_tree.label() == 'ABBR':
# Replace word with its abbreviation
word = parse_tree[0]
parse_tree.set_label('WORD')
parse_tree[0] = abbr_dict[w... | [
"def abbreviate(match_tree, statement):\n\n result = statement\n current_node = match_tree\n for position, letter in enumerate(statement.upper()):\n current_node = current_node.get(letter)\n if not isinstance(current_node, dict):\n if isinstance(current_node, str):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a common python list of object, no matter what information are supported by the parsed xml file for test results junit(). | def parse(self):
def parse_testcase(xml_object):
testcase = xml_object
tc_dict = {
"classname": testcase.attrib.get("classname", "unknown"),
"file": testcase.attrib.get("file", "unknown"),
"line": int(testcase.attrib.get("line", -1)),
... | [
"def list_from_result(cls, xmldoc):\n allResults = [];\n importresults = xmldoc.getElementsByTagName(\"importresult\")\n for ir in importresults:\n allResults.append(cls(ir))\n return allResults",
"def load_data(self):\n try:\n data = etree.parse(self.resul... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Manual assignment of a (stopped) times object as a subdivision of running timer. Use cases are expected to be very limited (mainly provided as a oneTimes variant of attach_par_subdivision). | def attach_subdivision(times):
t = timer()
if not isinstance(times, Times):
raise TypeError("Expected Times object for param 'times'.")
assert times.total > 0., "Attached subdivision has total time 0, appears empty."
name = times.name
f.r.self_agg += times.self_agg
if name not in f.t.sub... | [
"def __set_time_elements(*args):\n args[0].TimeState.delay_elements = args[1]\n args[0].TimeState.set_delay_elements()",
"def setNumTimeSubSteps(*argv):",
"def time_step():\n return TimeStep()",
"def set_times(self, times):\n self.times = times",
"def setTimepoint(self, tp):\n\t\tpass",
"def... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Serialize and / or save a Times data object using pickle (cPickle). | def save_pkl(filename=None, times=None):
if times is None:
if not f.root.stopped:
times = collapse.collapse_times()
else:
times = f.root.times
else:
if isinstance(times, (list, tuple)):
for t in times:
if not isinstance(t, Times):
... | [
"def save(self):\n\n # Save pickled telescope object\n if mpiutil.rank0:\n with open(self._picklefile, 'w') as f:\n print \"=== Saving Timestream object. ===\"\n pickle.dump(self, f)",
"def pickle_tds(self):\n\n import pickle\n\n now = datetime.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
对[LINEAR> RELU] (L1) > LINEAR > SIGMOID组执行反向传播,就是多层网络的向后传播 参数: AL 概率向量,正向传播的输出(L_model_forward()) Y 标签向量(例如:如果不是猫,则为0,如果是猫则为1),维度为(1,数量) caches 包含以下内容的cache列表: linear_activation_forward("relu")的cache,不包含输出层 linear_activation_forward("sigmoid")的cache 返回: grads 具有梯度值的字典 grads ["dA"+ str(l)] = ... grads ["dW"+ str(l)] = .... | def L_model_backward(AL, Y, caches,lambd):
grads = {}
L = len(caches)
m = AL.shape[1]
Y = Y.reshape(AL.shape)
#用于回归的dAL
dAL = AL-Y
#用于分类的dAL
#dAL = - (np.divide(Y, AL) - np.divide(1 - Y, 1 - AL))
current_cache = caches[L - 1]
# 用于分类是sigmoid,用于回归是linef
grads["dA" + ... | [
"def L_model_forward(X,parameters):\r\n caches = []\r\n A = X\r\n L = len(parameters) // 2\r\n for l in range(1,L):\r\n A_prev = A\r\n A,cache = linear_activation_forward(A_prev,parameters['W' + str(l)],parameters['b' + str(l)],\"relu\")\r\n caches.append(cache)\r\n \r\n A... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This method validates the input file. Returns true if the JSON is valid, false otherwise. | def validate_input(update_file):
try:
json.load(open(update_file))
print "\nValid JSON"
return True
except ValueError:
print "\nInvalid JSON"
exit(-1)
return False | [
"def validate_input(update_file):\n try:\n json.load(open(update_file))\n #print \"Valid JSON\"\n return True\n except ValueError:\n print \"Invalid JSON. Exiting.\"\n exit(-1)\n return False",
"def valid_is_json(self):\n return self.file_name.endswith('.json... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This method prints the current contents of an api_key riak bucket when passed a valid url | def get_current_key(url):
r=requests.get(url)
#return json.dumps(r.json(), sort_keys=True, indent=4)
return json.dumps(r.json(), sort_keys=True, indent=4, separators=(',', ': ')) | [
"def list_bucket_contents(bucket_name):\n\n click.echo(\"Your bucket name: %s\" % (bucket_name))\n for obj in bucket_name.objects.all():\n click.echo(obj.key)",
"def analysis_summary(bucket_url, replay):\n\n logger = logging.getLogger(\"SimpleReplayLogger\")\n\n bucket = bucket_dict(bucket_url)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This method saves the current contents of the riak bucket/key to be updated into a file called .original | def save_current_contents(url,update_file):
r=requests.get(url)
save_file=update_file+'.original'
json.dump(r.json(), open(save_file,'w'))
print "\nSaved contents of: \n\n\t%s \n\nto \n\n\t%s\n" % (url,save_file) | [
"def overwrite_original(self) -> None:\n self._write_save_file(self._file_path, \"wb\")",
"def _s3_stash(self):\n s3_url = 's3://{}/{}'.format(BUCKET, self.atom_file)\n bucketpath = BUCKET.strip(\"/\")\n bucketbase = BUCKET.split(\"/\")[0]\n parts = urlparse.urlsplit(s3_url)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Export the accumulate QA info | def export_QA(qa: QA):
# TODO: implement
log.info("assess_quality.export_QA: not yet implemented") | [
"def dump_qa(self):\n #- QA level outputs\n #qa_outfile = {}\n qa_outfig = {}\n for PA in self.palist:\n for QA in self.qalist[PA]:\n #qa_outfile[QA] = self.io_qa(QA)[0]\n qa_outfig[QA] = self.io_qa(QA)[1]\n \n #- mak... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Computes boundary indices for each of the splits in split_probs. | def _compute_split_boundaries(split_probs, n_items):
if len(split_probs) > n_items:
raise ValueError(
'Not enough items for the splits. There are {splits} '
'splits while there are only {items} items'.format(
splits=len(split_probs), items=n_items
)
)
total_probs = sum(p ... | [
"def indices_of_split(self, split_name='train'):\n return self.indices_of('split', split_name)",
"def _get_indices_split ( indices, number_of_folds ):\n # Split the indicies by the number of folds\n return np.array_split ( indices, indices_or_sections = number_of_folds )\n # End get_indice... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test parsing and streaming of DPTValue1Ucount 50. | def test_value_50(self):
self.assertEqual(DPTValue1Ucount().to_knx(50), (0x32,))
self.assertEqual(DPTValue1Ucount().from_knx((0x32,)), 50) | [
"def test_unit(self):\n assert DPTSignedRelativeValue.unit == \"\"\n assert DPTPercentV8.unit == \"%\"\n assert DPTValue1Count.unit == \"counter pulses\"",
"def test_unit(self):\n self.assertEqual(DPTSignedRelativeValue.unit, \"\")\n self.assertEqual(DPTPercentV8.unit, \"%\")\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test parsing and streaming of DPTValue1Ucount 255. | def test_value_max(self):
self.assertEqual(DPTValue1Ucount().to_knx(255), (0xFF,))
self.assertEqual(DPTValue1Ucount().from_knx((0xFF,)), 255) | [
"def test_value_50(self):\n self.assertEqual(DPTValue1Ucount().to_knx(50), (0x32,))\n self.assertEqual(DPTValue1Ucount().from_knx((0x32,)), 50)",
"def test_unit(self):\n assert DPTSignedRelativeValue.unit == \"\"\n assert DPTPercentV8.unit == \"%\"\n assert DPTValue1Count.unit =... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test parsing and streaming of DPTValue1Ucount 0. | def test_value_min(self):
self.assertEqual(DPTValue1Ucount().to_knx(0), (0x00,))
self.assertEqual(DPTValue1Ucount().from_knx((0x00,)), 0) | [
"def test_unit(self):\n assert DPTSignedRelativeValue.unit == \"\"\n assert DPTPercentV8.unit == \"%\"\n assert DPTValue1Count.unit == \"counter pulses\"",
"def test_unit(self):\n self.assertEqual(DPTSignedRelativeValue.unit, \"\")\n self.assertEqual(DPTPercentV8.unit, \"%\")\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test parsing of DPTValue1Ucount with wrong value (3 byte array). | def test_from_knx_wrong_parameter(self):
with self.assertRaises(ConversionError):
DPTValue1Ucount().from_knx((0x01, 0x02, 0x03)) | [
"def test_value_min(self):\n self.assertEqual(DPTValue1Ucount().to_knx(0), (0x00,))\n self.assertEqual(DPTValue1Ucount().from_knx((0x00,)), 0)",
"def test_unit(self):\n self.assertEqual(DPTSignedRelativeValue.unit, \"\")\n self.assertEqual(DPTPercentV8.unit, \"%\")\n self.assert... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the eopatch with the new grouping of the LPIS data. A column "GROUP_1_ID", is also added, with the ID associated to the groups. col_cropN_lpis is the name of the column of the crop type in the lpis dataframe. col_cropN_lpistogroup is the name of the column of the crop type in the csv file specified by self.lpis... | def execute(self, eopatch, col_cropN_lpis, col_cropN_lpistogroup):
# Group LPIS classes
lpis = eopatch.vector_timeless["LPIS_{}".format(self.year)]
mapping = pd.read_csv(self.lpis_to_group_file, sep=";")
result = pd.merge(lpis, mapping, how="left", left_on=[col_cropN_lpis], right_on=[col... | [
"def create_new_Group(config, oldgroup):\n path = config['file_inputs']['oligos']\n # path = config\n with open(path) as o, open(oldgroup) as g:\n # parse the oligo file and use the barcode_label (4th column) as\n # search pattern, to remove the temp files from m.chimera.vsearch\n oldg... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
mask out labels that are not in both train and test data and also mask out samples where features include NaN values | def masking(X_train, X_test, y_train, y_test):
# create mask to exclude NaN-values from train data
mask_train = np.zeros(X_train.shape[0], dtype=np.bool)
for i, subfeat in enumerate(X_train):
if True in np.isnan(subfeat):
mask_train[i] = True
else:
mask_train[i] = Fa... | [
"def omit_nans(self, data, label):\n maskarray=np.full(data.shape[0], True)\n masker=np.unique(np.argwhere(np.isnan(data))[:,0])\n maskarray[masker]=False\n traindata=data[maskarray,:,:,:]\n trainlabel=label[maskarray]\n return traindata, trainlabel",
"def _remove_samples... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns mapping between Geopedia's crop index and crop id for Slovenia. | def get_slovenia_crop_geopedia_idx_to_crop_id_mapping():
gpd_session = GeopediaSession()
to_crop_id = list(GeopediaFeatureIterator(layer='2036', gpd_session=gpd_session))
to_crop_id = [{'crop_geopedia_idx': code['id'], **code['properties']} for code in to_crop_id]
to_crop_id = pd.DataFrame(to_crop_id)
... | [
"def get_austria_crop_geopedia_idx_to_crop_id_mapping():\n gpd_session = GeopediaSession()\n to_crop_id = list(GeopediaFeatureIterator(layer='2032', gpd_session=gpd_session))\n to_crop_id = [{'crop_geopedia_idx': code['id'], **code['properties']} for code in to_crop_id]\n to_crop_id = pd.DataFrame(to_cr... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns mapping between Geopedia's crop index and crop id for Austria. | def get_austria_crop_geopedia_idx_to_crop_id_mapping():
gpd_session = GeopediaSession()
to_crop_id = list(GeopediaFeatureIterator(layer='2032', gpd_session=gpd_session))
to_crop_id = [{'crop_geopedia_idx': code['id'], **code['properties']} for code in to_crop_id]
to_crop_id = pd.DataFrame(to_crop_id)
... | [
"def get_slovenia_crop_geopedia_idx_to_crop_id_mapping():\n gpd_session = GeopediaSession()\n to_crop_id = list(GeopediaFeatureIterator(layer='2036', gpd_session=gpd_session))\n to_crop_id = [{'crop_geopedia_idx': code['id'], **code['properties']} for code in to_crop_id]\n to_crop_id = pd.DataFrame(to_c... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Query oVirt for hosts and place them in env.hosts | def query(oquery='', sure='no', ovirt=None):
hosts = oVirtObjectType.all_types['host'].query(ovirt, oquery)
env.hosts = [host.address for host in hosts]
puts(yellow(
"Got %d hosts: \n\t" % len(env.hosts)
+ '\n\t'.join(env.hosts)
))
if sure != 'yes' and not env.parallel:
if pr... | [
"def setup_hosts():\n if not getattr(env, 'hostname', None):\n print \"setup_hosts requires env.hostname. Skipping.\"\n return None\n ## the following stuff will only be necessary if we need to put entries\n ## like \"1.2.3.4 lrz15\" into /etc/hosts, but that may not be necessary.\n ## i'l... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
List walks, or create a new walks. | def walk_list_api(request):
if request.method == 'GET':
walks = Walk.objects.filter(user=request.user).order_by("-date")
serializer = WalkSerializer(walks, many=True)
return Response(serializer.data)
elif request.method == 'POST':
serializer = WalkSerializer(data=request.data)
... | [
"def _generate_walks(self):\n return parallel_generate_walks(\n self.d_graph,\n self.walk_length,\n self.num_walks,\n 'Single process!',\n self.sampling_strategy,\n self.NUM_WALKS_KEY,\n self.WALK_LENGTH_KEY,\n self.NEIGH... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Python script to read information from a public API returns employess an their completed tasks | def main():
number = sys.argv[1]
url_user = "https://jsonplaceholder.typicode.com/users/{}".format(number)
url_tasks = ("https://jsonplaceholder.typicode.com/users/{}/todos".
format(number))
response = requests.get(url_tasks)
tasks = response.json()
user_info = requests.get(url_... | [
"def show_tasks(complete):\n\n userid = input(\"Enter user ID: \")\n query = {\n \"userId\": int(userid),\n \"complete\": complete\n }\n response = requests.get(base_url + \"/tasks\", params=query)\n data = response.json()\n print([x[\"name\"] + ': ' + x[\"description\"] for x in dat... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Pads episodes to all be the same length by repeating the last exp. | def pad(episodes):
max_len = max(len(episode) for episode in episodes)
mask = torch.zeros((len(episodes), max_len), dtype=torch.bool)
padded_episodes = []
for i, episode in enumerate(episodes):
padded = episode + [episode[-1]] * (max_len - len(episode))
padded_episodes.append(padded)
mask[i, :len(ep... | [
"def _add_target_n_step_q_to_episode(self, episode):\n horizon = len(episode)\n for t in range(horizon):\n end_idx = min(t + self.n, horizon)\n discount = self.gamma ** (end_idx - t)\n mask = episode[end_idx - 1][\"nonterminal\"]\n episode[t][\"n_step_q\"] =... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the environment class specified by the type. | def get_env_class(environment_type):
if environment_type == "vanilla":
return city.CityGridEnv
elif environment_type == "distraction":
return city.DistractionGridEnv
elif environment_type == "map":
return city.MapGridEnv
elif environment_type == "cooking":
return cooking.CookingGridEnv
elif en... | [
"def get_environment_class_by_name(environment_type):\n for cls in util.iter_subclasses(Environment):\n if cls.tool_name == environment_type:\n return cls\n raise EnvironmentUnavailable(\n f\"Unknown environment type '{environment_type}'\")",
"def get_env_class(env_type):\n asser... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Two sketches can be merged only if their gamma and min_values are equal. | def mergeable(self, other):
return self.gamma == other.gamma and self.min_value == other.min_value | [
"def _mergeable(self, other):\n # type: (BaseDDSketch) -> bool\n return self._mapping.gamma == other._mapping.gamma",
"def test_merge_configuration():\n\n one = {\"alpha\": [0, 1], BernoulliNB: {\"fit_prior\": [True, False]}}\n two = {\"alpha\": [0, 2], GaussianNB: {\"fit_prior\": [True, False... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Takes a list of revision dicts and extracts globals, includes, and pages Expects revision dict to be sorted already Returns 3tuple | def extract_data(data, rev=0):
globs = {'_pages' : {}}
includes = []
pages = []
pages_list = []
for datum in data:
globs.update(datum.get('globals', {}))
includes += datum.get('includes', [])
datum_pages = datum.get('pages', [])
for page in datum_pages:
if... | [
"def find_revision_pages(url_text):\n\trevision_links = []\n\tgrammar_indices = [m.start() for m in re.finditer(\"grammar\", url_text.lower())]\n\t# print(\"Grammar indices:\",grammar_indices)\n\n\tfor i in range(len(grammar_indices)):\n\t\tgrammar_index = grammar_indices[i] \n\t\tprev_index = url_text[:grammar_ind... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
r"""Distributed version of Stochastic Dual Coordinate Ascent (SDCA) optimizer for linear models with L1 + L2 regularization. As global optimization objective is stronglyconvex, the optimizer optimizes the dual objective at each step. The optimizer applies each update one example at a time. Examples are sampled uniforml... | def _sdca_optimizer(sparse_example_indices, sparse_feature_indices,
sparse_feature_values, dense_features, example_weights,
example_labels, sparse_indices, sparse_weights,
dense_weights, example_state_data, loss_type, l1, l2,
num_loss_parti... | [
"def optimize_sgd(beta, X, y, num_iterations, step_size):\n \n N = X.shape[0]\n P = X.shape[1]\n costs = []\n #variable step size\n if step_size == 'rm': #Robbins–Monro rule\n t0 = 2\n C = 1\n alpha = 0.5\n for i in range(num_iterations): \n j = random.ran... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
r"""Applies L1 regularization shrink step on the parameters. | def _sdca_shrink_l1(weights, l1, l2, name=None):
result = _op_def_lib.apply_op("SdcaShrinkL1", weights=weights, l1=l1, l2=l2,
name=name)
return result | [
"def cost_L1_regularizer(w, lamb):\r\n\r\n w_reg = w[1:]\r\n D = w_reg.shape[0]\r\n regularizer = (lamb / D) * np.sum(np.abs(w_reg))\r\n\r\n return regularizer",
"def l1_regularizer(scale):\n if isinstance(scale, numbers.Integral):\n raise ValueError('scale cannot be an integer: %s' % scale)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This class holds the windows which shows the create experiment widget. | def __init__(self,currentExperiment):
super(AmoebaCreateExperimentWindow,self).__init__()
self.currentExperiment = currentExperiment
#Create the window
self.subWindow = QMdiSubWindow()
self.widget = AmoebaCreateExperiment(self.subWindow,self.currentExperiment)
... | [
"def createWindows(self):\n self.setupSplashScreen()\n\n # This is so that we don't import too many things before we\n # have to. Otherwise, requirements are checked too late.\n # from gui.builder_window import QBuilderWindow\n from vistrails.gui.vistrails_window import QVistrails... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Testing Tuna is not null | def test_Tuna(self):
tuna = Tuna("1", "2", "3", "4")
self.assertIsNotNone(tuna) | [
"def IsNone(self) -> bool:",
"def test_non_thesis(non_thesis):\n assert non_thesis is None",
"def _test_empty(t):\n return t.is_empty()",
"def compare_with_none():\n value = {};\n if value is not None:\n print(\"value is not none\")\n else:\n print(\"value is none\")",
"def l_as... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Testing Tuna's setTunasFeatures method works | def test_setTunaFeatures(self):
tuna = Tuna()
array = ["1", "2", "3", "4"]
tuna.setTunaFeatures(array)
self.assertEqual(tuna.getTunaFeatures(), array) | [
"def setTunaFeatures(self, array=[]):\n pass",
"def test_getTunaFeatures(self):\n tuna = Tuna(\"1\", \"2\", \"3\", \"4\")\n array = [\"1\", \"2\", \"3\", \"4\"]\n self.assertEqual(tuna.getTunaFeatures(), array)",
"def init_features():\n TEST_FEATURES.append(feature_1)",
"def set... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Testing Tuna's getTunasFeatures method works | def test_getTunaFeatures(self):
tuna = Tuna("1", "2", "3", "4")
array = ["1", "2", "3", "4"]
self.assertEqual(tuna.getTunaFeatures(), array) | [
"def test_setTunaFeatures(self):\n tuna = Tuna()\n array = [\"1\", \"2\", \"3\", \"4\"]\n tuna.setTunaFeatures(array)\n self.assertEqual(tuna.getTunaFeatures(), array)",
"def setTunaFeatures(self, array=[]):\n pass",
"def test__extract_features(self):\n text_sample = \"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create "can_approve_estimated_completion_date" permission and add it to the "Admin" group. | def add_permissions(apps, schema_editor):
Permission = apps.get_model("auth", "Permission")
Group = apps.get_model("auth", "Group")
ContentType = apps.get_model("contenttypes", "ContentType")
permission, created = Permission.objects.get_or_create(
codename="can_approve_estimated_completion_dat... | [
"def add_user_with_status_granted(caller, user):\r\n if _add_user(user, CourseCreator.GRANTED):\r\n update_course_creator_group(caller, user, True)",
"def need_admin_approval(self, need_admin_approval):\n\n self._need_admin_approval = need_admin_approval",
"def assignment_approve(event):\n a... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Remove "can_approve_estimated_completion_date" permission and remove it from the "Admin" group. | def remove_permissions(apps, schema_editor):
Permission = apps.get_model("auth", "Permission")
Group = apps.get_model("auth", "Group")
permission = Permission.objects.get(
codename="can_approve_estimated_completion_date",
)
admin_group = Group.objects.get(name="Administrator")
admin_g... | [
"def remove_permission(actionGroup=None, profilingGroupName=None, revisionId=None):\n pass",
"def delPermission(self,request):\n request.needAuthType(request.ADMIN)\n request.checkArgs(\"admin_username\",\"perm_name\")\n request.getAuthNameObj().canDo(\"CHANGE ADMIN PERMISSIONS\")\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
export GPU for AD | def export_gpu(entity=None):
status = False
exportGrp = config.geoGrp
res = entity.task_res()
libPath = entity.libPath()
if res:
abcName = entity.libName(config.libName.get('gpu'), res, ext='abc')
# name without ext
basename = os.path.splitext(abcName)[0]
gpuName = '{0}/{1}'.format(libPath, abcNam... | [
"def setup_gpu(gpu=False):\n if gpu:\n os.environ[\"CUDA_DEVICE_ORDER\"] = \"PCI_BUS_ID\"\n os.environ['CUDA_VISIBLE_DEVICES'] = '0'\n else:\n os.environ[\"CUDA_DEVICE_ORDER\"] = \"PCI_BUS_ID\" \n os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"\"",
"def _to_gpu(self):\n self._ge... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test to see if profile for leothelion can be viewed anon and logged in | def test_view_profile(self):
LOGGER.debug("Test GET /rango/view/leothelion/ for anon user")
anon_view_response = self.client.get('/rango/view/leothelion/')
self.assertContains(anon_view_response, "leothelion@hotmail.com")
LOGGER.debug("Test GET /rango/view/leothelion/ for logged in use... | [
"def test_is_profile_visible_with_public(self):\n user1 = User.objects.get(username='admin')\n user2 = User.objects.get(username='doc')\n\n self.assertTrue(user1.is_profile_visible(user2))",
"def test_profile_route_does_have_counts_for_loggedin_user(self):\n self.client.login(username=... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Takes in the direction the camera is pointing and the camera origin and returns a cam2world matrix. | def create_cam2world_matrix(forward_vector,
origin,
device=None):
""""""
forward_vector = normalize_vecs(forward_vector)
up_vector = torch.tensor([0, 1, 0], dtype=torch.float, device=device) \
.expand_as(forward_vector)
left_vector = normalize_vecs(
... | [
"def get_4x4_cam_to_world_mat(self):\n # M = [R^T c]\n # [0 1]\n homogeneous_mat = np.identity(4, dtype=float)\n homogeneous_mat[\n 0:3, 0:3\n ] = self.get_rotation_as_rotation_mat().transpose()\n homogeneous_mat[0:3, 3] = self.get_camera_center()\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Perturb z_vals and points; Samples a camera position and maps points in camera space to world space. | def transform_sampled_points(points,
z_vals,
ray_directions,
device,
h_stddev=1,
v_stddev=1,
h_mean=math.pi * 0.5,
v_... | [
"def transform_sampled_points(points,\n z_vals,\n ray_directions,\n device,\n h_stddev=1,\n v_stddev=1,\n h_mean=math.pi * 0.5,\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Converts an Rmd document as a string into a list of ``Cell`` objects for easier handling with code designed originally for Jupyter notebooks. | def rmd_to_cells(rmd_string):
cells, cell_lines, cell_type, in_block, in_begin = [], [], "markdown", False, False
for line in rmd_string.split("\n"):
if in_block and (line.strip() == "```" or re.match(END_REGEX, line)):
in_block = False
# collect cell_lines into a new cell
... | [
"def markdown_cells(notebook):\n cells = all_cells(notebook)\n return [cell[\"source\"] for cell in cells if cell[\"cell_type\"] == \"markdown\"]",
"def prepare_markdown_cell(cell):\n assert isinstance(cell, list)\n assert isinstance(cell[0], str)\n\n cell2 = []\n\n for line in cell:\n li... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Collapses all runs of cells with empty sources into a single cell with an empty source | def collapse_empty_cells(cells):
in_run, run_start = False, 0
replacements = []
for i, cell in enumerate(cells):
if in_run and cell["source"].strip():
if (run_start > 0 and cells[run_start-1]["source"].endswith("\n")) or cell["source"].startswith("\n"):
replacement = []
... | [
"def remove_empty_slices(target):\n target.scan = target.scan[np.where(target.scan.sum(axis=(1, 2)) > 0)]\n return target",
"def collapseUp(self):\n retval = False\n for cStartInd in range(self.col):\n lst = [self.get_cell(i) for i in range(cStartInd, self.length, self.col)]... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Storage service is unavailable. | def test_store_is_unavailable(self, mock_current_session):
mock_store = mock.MagicMock()
mock_store.is_available.return_value = False
mock_current_session.return_value = mock_store
with self.assertRaises(ServiceUnavailable):
controllers.service_status() | [
"def print_service_unavailable():\n if WithingsDataManager.service_available is not False:\n _LOGGER.error(\"Looks like the service is not available at the moment\")\n WithingsDataManager.service_available = False\n return True",
"def service_not_available(error):\r\n re... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The preview already exists. | def test_already_exists(self, mock_current_session):
mock_store = mock.MagicMock()
mock_store.deposit.side_effect = store.PreviewAlreadyExists
mock_current_session.return_value = mock_store
with self.assertRaises(Conflict): # 409 Conflict
controllers.deposit_preview(self.s... | [
"def has_pdf_preview(self) -> bool:\n return True",
"def removePreview(self):\n logger.debug(\"Func: removePreview\")\n\n if self._currentPreviewCamera:\n previewName = self._currentPreviewCamera\n previewFile = self._currentPreviewsDict[self._currentPreviewCamera]\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The preview is deposited successfully. | def test_deposit_successful(self, mock_current_session):
mock_store = mock.MagicMock()
added = datetime.now(UTC)
def mock_deposit(obj, overwrite, **kwargs):
"""Deposit implementation sets metadata on Preview."""
return Preview(source_id=obj.source_id,
... | [
"def deposita(self):\n backend.database.deposita(int(self.somma_deposito_entry.get()),self.cliente_entry.get())\n messagebox.showinfo(\"Deposito\",\"Deposito Effettuato con Successo\")",
"def mock_deposit(obj, overwrite, **kwargs):\n return Preview(source_id=obj.source_id,\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Deposit implementation sets metadata on Preview. | def mock_deposit(obj, overwrite, **kwargs):
return Preview(source_id=obj.source_id,
checksum=obj.checksum,
metadata=Metadata(added=added,
checksum='foopdfchex==',
s... | [
"def test_deposit_successful(self, mock_current_session):\n mock_store = mock.MagicMock()\n added = datetime.now(UTC)\n\n def mock_deposit(obj, overwrite, **kwargs):\n \"\"\"Deposit implementation sets metadata on Preview.\"\"\"\n return Preview(source_id=obj.source_id,\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Empty the linked list O(n) | def clear(self):
trav = self.head
while trav is not None:
nxt = trav.nxt
trav.prev = trav.nxt
trav.data = None
trav = nxt
self.head = None
self.tail = None
trav = None
self.size = 0 | [
"def delete_node_at_start(self):\n if not self.head:\n print('List already empty.')\n return\n self.head = self.head.next",
"def __remove_first(self):\n if self.__head is not None:\n self.__length -= 1\n self.__head = self.__head.next()\n if ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Obtain data from head of linked list O(1) | def peek_first(self):
if self.is_empty(): raise RuntimeError("Empty list")
return self.head.data | [
"def head_element(self):\r\n return self.data[self.head]",
"def find(self, head):\n return self._get_head(head)",
"def get(self, index):\n length = self.len()\n if index < 1 or index > length:\n return None\n temp = self.head\n counter = 1\n while temp... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Obtain data from tail of linked list O(1) | def peek_last(self):
if self.is_empty(): raise RuntimeError("Empty list")
return self.tail.data | [
"def tail_element(self):\r\n return self.data[self.tail-1]",
"def tail(lst):\n precondition(type(lst) == type([]))\n return lst[1:]",
"def pop_back(self):\n if self.empty():\n return \"Empty Linked List\"\n\n h = self.head\n while h is not None:\n if h.nex... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Convert from ParseResults to normal list. | def result2list(foo):
if isinstance(foo, ParseResults):
return [result2list(bar) for bar in foo]
else:
return foo | [
"def _make_result_list(self,res):\n res_list = []\n for r in res:\n res_list.append(r)\n\n return res_list",
"def __to_list(__results):\n rows = []\n for row in __results:\n rows.append(row)\n \n __results.c... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
My delimited list. Allows for length zero list and uses no delimiter by default. | def List(expr, delim=""):
if not delim:
return Group(ZeroOrMore(expr))
else:
return Group(Optional(expr + ZeroOrMore( Suppress(delim) + expr))) | [
"def make_list(self, s, list_delim = ','):\n return [x.strip() for x in s.split(list_delim) if x.strip() != '']",
"def string_list(delimiter):\n return lambda argument: [v.strip() for v in argument.split(delimiter)]",
"def test_string_to_list_string_delimiter(self):\n assert_equals(\n st... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns True if the user has the specified permission. This method queries all available auth backends, but returns immediately if any backend returns True. Thus, a user who has permission from a single auth backend is assumed to have permission in general. If an object is provided, permissions for this specific object... | def has_perm(self, user, perm, obj=None):
# Active superusers have all permissions.
if user.is_active and user.is_superuser:
return True
# Otherwise we need to check the backends.
return _user_has_perm(user, perm, obj) | [
"def has_perm(self, perm, obj=None):\n\n # Active superusers have all permissions.\n if self.is_active and self.is_superuser:\n return True\n\n # Otherwise we need to check the backends.\n return _user_has_perm(self, perm, obj)",
"def has_perm(self, perm, obj=None):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test scenario where branch is deleted by someone. | def test_branch_deleted(local):
pytest.run(local, ['git', 'checkout', 'feature'])
pytest.run(local, ['git', 'push', 'origin', '--delete', 'feature'])
local.join('README').write('Changed by local.')
# Run.
actual = commit_and_push(str(local), 'origin', Versions(REMOTES))
assert actual is True
... | [
"async def test_delete_branch_comment(cli):\n req_data = {\n 'user_id': 4,\n 'i_id': 4,\n 'itype_id': 4,\n 'content': 'branch comment'\n }\n branch = await create_comment(cli, req_data)\n\n req_data = {\n 'user_id': 4,\n 'i_id': branch['id'],\n 'itype_id'... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get and validate user input for a bounded number. Loops until true. Uses GLOBAL BOUNDS | def get_number():
valid_input = False
while not valid_input:
try:
user_num = int(input("Enter a number between {} and {}: ".format(LOWER_BOUND, UPPER_BOUND)))
if LOWER_BOUND <= user_num <= UPPER_BOUND:
return user_num
except ValueError:
pass
... | [
"def check_guess(message, lower_bound, upper_bound):\n guess = int(input(message))\n \n while guess < lower_bound or guess > upper_bound:\n guess = int(input(L[\"guess_outwith_bounds\"]))\n \n return guess",
"def prompt() -> int:\n msg: str = \"How many ranges to generate - (default={}) \... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets the xml element by name (if there are multiple elements, only the first one is returned). Use 'get_element_list' for that. | def get_element( self, element_name, base_element = None ):
if base_element is not None:
if not etree.iselement( base_element ):
return None
else:
base_element = self.xml_root
element = base_element.find( element_name )
if element == 'None':
... | [
"def get_element_by_name(self, name):\n for e in self.E:\n if e.name == name:\n return e",
"def find_element_by_name(self, name):\n return self.driver.find_element_by_name(name)",
"def get_element(self, element_name=None):\n try:\n if element_name in sel... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Bind to the ``IID_str`` with the given ``version`` | def bind(self, IID_str, version=(1,0)):
IID = windows.com.IID.from_string(IID_str)
request = self._forge_bind_request(IID, version, self.number_of_bind_if)
response = self._send_request(request)
# Parse reponse
request_type = self._get_request_type(response)
if request_ty... | [
"def version_number(version_str):\n raise NotImplementedError",
"def _handle_version(self, iq):\n iq.reply()\n iq['software_version']['name'] = self.software_name\n iq['software_version']['version'] = self.version\n iq['software_version']['os'] = self.os\n iq.send()",
"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Craft an ALPC message containing an RPC request to call ``method_offset`` of interface ``IID` with ``params``. Can be used to craft request without directly sending it | def forge_alpc_request(self, IID, method_offset, params, ipid=None):
iid_hash = hash(buffer(IID)[:])
interface_nb = self.if_bind_number[iid_hash] # TODO: add __hash__ to IID
if len(params) > 0x900: # 0x1000 - size of meta-data
request = self._forge_call_request_in_view(interface_nb, ... | [
"def call(self, IID, method_offset, params, ipid=None):\n request = self.forge_alpc_request(IID, method_offset, params, ipid=ipid)\n response = self._send_request(request)\n # Parse reponse\n request_type = self._get_request_type(response)\n if request_type != gdef.RPC_RESPONSE_TY... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Call method number ``method_offset`` of interface ``IID`` with mashalled ``params`` | def call(self, IID, method_offset, params, ipid=None):
request = self.forge_alpc_request(IID, method_offset, params, ipid=ipid)
response = self._send_request(request)
# Parse reponse
request_type = self._get_request_type(response)
if request_type != gdef.RPC_RESPONSE_TYPE_SUCCESS... | [
"def forge_alpc_request(self, IID, method_offset, params, ipid=None):\n iid_hash = hash(buffer(IID)[:])\n interface_nb = self.if_bind_number[iid_hash] # TODO: add __hash__ to IID\n if len(params) > 0x900: # 0x1000 - size of meta-data\n request = self._forge_call_request_in_view(inter... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |