query
stringlengths
9
9.05k
document
stringlengths
10
222k
negatives
listlengths
19
20
metadata
dict
Takes beautiful soup object, tries to find and append item guests count to collected_dic dictionary. If it doesn't exist appends None value.
def get_item_guests(self, soup: BeautifulSoup) -> None: try: guests = ( soup.find("div", class_="_kqh46o") .find_all("span", class_="_3hmsj")[0] .get_text() ) guests = re.findall("[0-9]+", guests)[0] except (AttributeErr...
[ "def get_item_reviews(self, soup: BeautifulSoup) -> None:\n try:\n reviews = soup.find(\"span\", class_=\"_a7a5sx\").get_text()\n reviews = re.findall(\"[0-9]+\", reviews)[0]\n except AttributeError:\n reviews = None\n self.__collected_dic[\"reviews\"].append(re...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Takes beautiful soup object, tries to find and append item bedroom count, studio type, to collected_dic dictionary. If it doesn't exist appends None value.
def get_item_bedrooms(self, soup: BeautifulSoup) -> None: try: bedrooms = ( soup.find("div", class_="_kqh46o") .find_all("span", class_="_3hmsj")[1] .get_text() ) try: bedrooms = re.findall("[0-9]+", bedrooms)[0]...
[ "def get_item_beds(self, soup: BeautifulSoup) -> None:\n try:\n beds = (\n soup.find(\"div\", class_=\"_kqh46o\")\n .find_all(\"span\", class_=\"_3hmsj\")[2]\n .get_text()\n )\n beds = re.findall(\"[0-9]+\", beds)[0]\n excep...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Takes beautiful soup object, tries to find and append item beds count to collected_dic dictionary. If it doesn't exist appends None value.
def get_item_beds(self, soup: BeautifulSoup) -> None: try: beds = ( soup.find("div", class_="_kqh46o") .find_all("span", class_="_3hmsj")[2] .get_text() ) beds = re.findall("[0-9]+", beds)[0] except (AttributeError, Inde...
[ "def get_number_of_beds(Beautiful_Soup_object):\n try:\n number_of_beds_html = Beautiful_Soup_object.findChild(\"ul\", {\"class\":\"info\"}) # gets the part of html with the beds\n number_of_beds = number_of_beds_html.li.next_sibling.next_sibling.text.strip()[:-1] # selects only the number of beds\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Takes beautiful soup object, tries to find and append item baths count,type to collected_dic dictionary. If it doesn't exist appends None value.
def get_item_baths(self, soup: BeautifulSoup) -> None: shared_bath = 0 try: baths = ( soup.find("div", class_="_kqh46o") .find_all("span", class_="_3hmsj")[3] .get_text() ) try: baths_number = re.findall(...
[ "def get_item_beds(self, soup: BeautifulSoup) -> None:\n try:\n beds = (\n soup.find(\"div\", class_=\"_kqh46o\")\n .find_all(\"span\", class_=\"_3hmsj\")[2]\n .get_text()\n )\n beds = re.findall(\"[0-9]+\", beds)[0]\n excep...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Takes beautiful soup object, tries to find and append item coordinates to collected_dic dictionary. If it doesn't exist appends None value.
def get_coordinates(self, soup: BeautifulSoup) -> None: try: url = soup.find( "a", {"title": "Open this area in Google Maps (opens a new window)"} )["href"] coordinates = url[url.find("=") + 1 : url.find("&")] coordinates = [float(n) for n in coord...
[ "def get_item_location(self, soup: BeautifulSoup) -> None:\n try:\n location = soup.find(\"div\", class_=\"_b14dlit\").get_text()\n location = location.split(\" \")\n index = location.index(\"in\")\n location = \" \".join(location[index + 1 :])\n except (Att...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Takes html parsed text string and tries to find if wifi is included into amenities or not.
def get_amenity_wifi(self, amenities: str) -> None: wifi = 0 if "Wifi" in amenities: if "Unavailable: Wifi" not in amenities: wifi = 1 self.__collected_dic["wifi"].append(wifi)
[ "def classify_rss(text):\n accident_words = [\"תאונ\"]\n working_accidents_words = [\"תאונת עבודה\", \"תאונות עבודה\"]\n involved_words = [\n \"רכב\",\n \"אוטובוס\",\n \"ג'יפ\",\n \"משאית\",\n \"קטנוע\",\n \"טרקטור\",\n \"אופנוע\",\n \"אופניים\",\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Takes html parsed text string and tries to find if parking is included into amenities or not.
def get_amenity_parking(self, amenities: str) -> None: parking = 0 if "Free parking on premises" in amenities: if "Unavailable: Free parking on premises" not in amenities: parking = 1 self.__collected_dic["parking"].append(parking)
[ "def check_text_inclusion(self, url, anchor_text):\n response = requests.get(url, timeout=3)\n if response.status_code == 200:\n text = response.text\n response.close()\n return anchor_text in text", "def find_text_page(html):\n parser = TextHTMLParser()\n pars...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
go from yaml to method. Need to be here for accesing local variables.
def _from_yaml_to_func(method, params): prm = dict() if params is not None: for key, val in params.items(): prm[key] = eval(str(val)) return eval(method)(**prm)
[ "def _from_yaml_to_func(method, params):\n prm = dict()\n if params is not None:\n for key, val in params.iteritems():\n prm[key] = eval(str(val))\n return eval(method)(**prm)", "def _create_yaml_map(self):", "def test_parse_yaml(self) -> None:\n pass", "def setupFromYml(self...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
args 传入用户参数列表,可传入:proposer, verifier, operator 返回传入用户的邮箱地址
def get_user_email(self, *args): obj = self.obj.objects.get(pk=self.latest_id) user_list = [] if 'proposer' in args: user_list.append(obj.proposer) if 'verifier' in args: user_list.append(obj.verifier) if 'operator' in args: user_list.append(ob...
[ "def piEmail() :\n return email", "def get_user(self, service, email):", "def _checkEmailOption(args, stderr = None) :\n if stderr is None :\n stderr = sys.stderr\n if args.email is None :\n stderr.write(\"To make use of NCBI's E-utilities, NCBI requires you to specify\\n\"\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Represents raw documents as a Domain; a domain contains the tfidf weighted cooccurrence matrices of the labeled and unlabeled documents (with consistent Vocabulary).
def as_domain(labeled_docs, labels, issource, domain, unlabeled_docs=None, unlabeled_y=None, tokken_pattern=r"(?u)\b\w\w+\b", min_df=1): if issource: counter = CountVectorizer(token_pattern=tokken_pattern, min_df=min_df) v = counter.fit(labeled_docs).vocabulary_ tfidf = TfidfVectorizer(subli...
[ "def raw_domains(self):\n return schema_utils.schema_as_feature_spec(\n self.raw_metadata.schema).domains", "def infer_domain(self):\n row_count, col_count = self.metadata.get_matrix_size(0)\n sequence_size = self.metadata.get_sequence_size()\n channel_to_index_map = dict(self.metadata.get_chan...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given a source and a target domain, returns two new versions of them in which the feature spaces are common, by trivially juxtapossing the two vocabularies
def unify_feat_space(source, target): word_set = source.V.term_set().union(target.V.term_set()) word2idx = {w:i for i,w in enumerate(word_set)} Vshared = Vocabulary(word2idx) def reindexDomain(domain, sharedV): V = domain.V nD=domain.X.shape[0] nF=len(sharedV) newX = lil...
[ "def get_common(self, other, mapping):\n\n self_oov = defaultdict(lambda: 0)\n other_oov = defaultdict(lambda: 0)\n self_word_id = deepcopy(self.word_id)\n other_word_id = deepcopy(other.word_id)\n new_words = []\n map_ = mapping.map\n for i, w in enumerate(self.word...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
tests that the endpoint will correctly retrieve issues resolved in a release from the GroupResolution model
def test_shows_issues_from_groupresolution(self): GroupResolution.objects.create( group=self.group, release=self.release, type=GroupResolution.Type.in_release, ) response = self.client.get(self.path) assert response.status_code == 200, response.conten...
[ "def test_index_response_descriptor_projects_release_release_resource(self):\n pass", "def test_load_response_descriptor_projects_release_release_resource(self):\n pass", "def test_modify_response_descriptor_projects_release_release_resource(self):\n pass", "def test_issue_get_issue(self)...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
tests that the endpoint will correctly retrieve issues resolved in a release from the GroupLink model
def test_shows_issues_from_grouplink(self): repo = Repository.objects.create( organization_id=self.org.id, name=self.project.name, ) commit = Commit.objects.create( organization_id=self.org.id, repository_id=repo.id, key='a' * 40, ...
[ "def test_shows_issues_from_groupresolution(self):\n GroupResolution.objects.create(\n group=self.group,\n release=self.release,\n type=GroupResolution.Type.in_release,\n )\n response = self.client.get(self.path)\n\n assert response.status_code == 200, re...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
tests that the endpoint will correctly retrieve issues resolved in a release from the GroupLink and GroupResolution model but will not return the groups twice if they appear in both
def test_does_not_return_duplicate_groups(self): repo = Repository.objects.create( organization_id=self.org.id, name=self.project.name, ) commit = Commit.objects.create( organization_id=self.org.id, repository_id=repo.id, key='a' * 40, ...
[ "def test_shows_issues_from_groupresolution(self):\n GroupResolution.objects.create(\n group=self.group,\n release=self.release,\n type=GroupResolution.Type.in_release,\n )\n response = self.client.get(self.path)\n\n assert response.status_code == 200, re...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given a list of edges, finds the shortest subtour
def _subtour(edges,n): visited = [False]*n cycles = [] costs = [] selected = [[] for i in range(n)] for x,y in edges: selected[x].append(y) while True: current = visited.index(False) thiscycle = [current] while True: visited[current] = True neighbors = [x for x in selected[curren...
[ "def subtour(edges):\n unvisited = list(range(n))\n cycle = range(n + 1) # initial length has 1 more city\n while unvisited: # true if list is non-empty\n thiscycle = []\n neighbors = unvisited\n while neighbors:\n current = neighbors[0]\n thiscycle.append(curre...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
evaluate the numerical range of Comparison node, if any else returns None
def evaluate_comparison_range(node): return None
[ "def evaluate_range(optree):\n init_interval = optree.get_interval()\n if not init_interval is None:\n return init_interval\n else:\n if isinstance(optree, ML_LeafNode):\n return optree.get_interval()\n elif is_comparison(optree):\n return evaluate_comparison_ran...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
test if node is a Comparison node or not
def is_comparison(node): return isinstance(node, Comparison)
[ "def compare(self, node, new_node):\n if new_node.get_value() == node.get_value():\n return 0\n elif new_node.get_value() < node.get_value():\n return -1 # traverse left\n else: # new_node > node\n return 1 # traverse right", "def compare(self,node, new_nod...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
forward compatible attributes from src node to dst node
def forward_attributes(src, dst): dst.set_tag(src.get_tag()) dst.set_debug(src.get_debug()) dst.set_handle(src.get_handle()) if hasattr(src.attributes, "init_stage"): forward_stage_attributes(src, dst) if isinstance(src, BooleanOperation) and isinstance(dst, BooleanOperation): dst.li...
[ "def forward_attributes(src, dst):\n dst.set_tag(src.get_tag())\n dst.set_debug(src.get_debug())\n dst.set_handle(src.get_handle())\n if hasattr(src.attributes, \"init_stage\"):\n forward_stage_attributes(src, dst)", "def update_attr(dest: Node, src: Union[Node, Tuple[Node, ...]], root: RootNod...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
copy node's stage attributes from src node to dst node
def forward_stage_attributes(src, dst): dst.attributes.init_stage = src.attributes.init_stage
[ "def forward_attributes(src, dst):\n dst.set_tag(src.get_tag())\n dst.set_debug(src.get_debug())\n dst.set_handle(src.get_handle())\n if hasattr(src.attributes, \"init_stage\"):\n forward_stage_attributes(src, dst)", "def forward_attributes(src, dst):\n dst.set_tag(src.get_tag())\n dst.se...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
order the node between root start_node end end_nodes by depth (root first, starting with start_node)
def depth_node_ordering(start_node, end_nodes): ordered_list = [] ordered_set = set() working_list = [start_node] while working_list != []: node = working_list.pop(0) if not node in ordered_set: ordered_set.add(node) ordered_list.append(node) if not is_lea...
[ "def descending_depth_list(nodes, root): \n q = Queue.Queue()\n level_order = Queue.LifoQueue()\n s = Set()\n q.put(root)\n s.add(root)\n while not q.empty():\n current = nodes[q.get()]\n level_order.put(current)\n if current.left is not None and current.left not in s:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Logical/Boolean operand list reduction
def logical_reduce(op_list, op_ctor=LogicalOr, precision=ML_Bool, **kw): local_list = [node for node in op_list] while len(local_list) > 1: op0 = local_list.pop(0) op1 = local_list.pop(0) local_list.append( op_ctor(op0, op1, precision=precision) ) # assigning attr...
[ "def and_list(conditionList):\n return functools.reduce(numpy.logical_and, conditionList)", "def boolean_join(items):\n if not items or len(items) == 0:\n return None\n expr = ''\n for item in items:\n if item == '&' or item == 'and' or item == '+':\n expr += ' and '\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check that value_list is made of only a single value replicated in each element
def uniform_list_check(value_list): return reduce((lambda acc, value: acc and value == value_list[0]), value_list, True)
[ "def eval_list(self, value):\n\n okay = True\n count = 0\n for v in value.elts:\n if not self.eval_value(v):\n okay = False\n break\n count += 1\n return okay", "def hasUniqueValues(list):\r\n for i, item in enumerate(list):\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
check whether optree is a uniform vector constant
def uniform_vector_constant_check(optree): if isinstance(optree, Constant) and not optree.get_precision() is None \ and optree.get_precision().is_vector_format(): return uniform_list_check(optree.get_value()) return False
[ "def is_vector_uniform_cst(node, scalar_value):\n return isinstance(node, Constant) and node.get_precision().is_vector_format() and node.get_value() == [scalar_value] * node.get_precision().get_vector_size()", "def constraint(arg: tp.Any) -> bool: # pylint: disable=unused-argument\n return bool(optimiz...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
check whether optree is a bit shift by a uniform vector constant
def uniform_shift_check(optree): if isinstance(optree, (BitLogicLeftShift, BitLogicRightShift, BitArithmeticRightShift)): return uniform_vector_constant_check(optree.get_input(1)) \ or not optree.get_input(1).get_precision().is_vector_format() return False
[ "def check_bits(value, shift, mask=0b1):\n return (((value & U32) >> shift) & mask)", "def test_bit_and_offset_bit_size_larger_than_val(self):\n value = bytearray()\n value.append(0)\n ops = [bitwise_operations.bit_and(self.five_255_bin, 0, 16, 1, value, None)]\n\n with pytest.raise...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
check if node is a Constant node whose value is equal to boolean False
def is_false(node): return is_scalar_cst(node, False) or is_vector_uniform_cst(node, False)
[ "def is_constant(node):\n return isinstance(node, gast.Constant)", "def _is_constant_boolean(attr, module_source_file):\n if not attr.value.expression.type.boolean.HasField(\"value\"):\n return [[error.error(module_source_file,\n attr.value.source_location,\n _...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
check if node is a Constant node whose value is equal to boolean True
def is_true(node): return is_scalar_cst(node, True) or is_vector_uniform_cst(node, True)
[ "def is_constant(node):\n return isinstance(node, gast.Constant)", "def _is_constant_boolean(attr, module_source_file):\n if not attr.value.expression.type.boolean.HasField(\"value\"):\n return [[error.error(module_source_file,\n attr.value.source_location,\n _...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
check if node is a constant node with value equals to value
def is_scalar_cst(node, value): return isinstance(node, Constant) and not node.get_precision().is_vector_format() and node.get_value() == value
[ "def is_constant(node):\n return isinstance(node, gast.Constant)", "def isConstant(self):\n return _libsbml.ASTNode_isConstant(self)", "def get_node_value(node: Node):\n if node.type != 'Const':\n raise Exception('Can\\'t get value for non-constant node {}'.format(node.name))\n return node....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
check if node is a vector constant node with each value equals to scalar_value
def is_vector_uniform_cst(node, scalar_value): return isinstance(node, Constant) and node.get_precision().is_vector_format() and node.get_value() == [scalar_value] * node.get_precision().get_vector_size()
[ "def is_scalar_cst(node, value):\n return isinstance(node, Constant) and not node.get_precision().is_vector_format() and node.get_value() == value", "def uniform_vector_constant_check(optree):\n if isinstance(optree, Constant) and not optree.get_precision() is None \\\n and optree.get_precision()...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
extract the set of all ML_Table nodes in the graph rooted at node
def extract_tables(node): processed_set = set([node]) table_set = set() working_set = [node] while working_set: elt = working_set.pop(0) if isinstance(elt, ML_NewTable): table_set.add(elt) elif not isinstance(elt, ML_LeafNode): for op_node in elt.inputs: ...
[ "def get_all_nodes(self):\n pass", "def _nodes(self):\n G = self.monodromy_graph()\n return [n for n,data in G.nodes(data=True) if data['type']=='node']", "def retrieve_all_nodes(self):\r\n sql = \"\"\"SELECT node_id, sigfox_id, active\r\n FROM node\"\"\"\r\n rows = se...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
If a page failed, only print summary for individual passing pages.
def test_basic_summary_pass_and_fail_page(self): test_page_set = _MakePageSet() measurement_results = SummarySavingPageMeasurementResults() measurement_results.WillMeasurePage(test_page_set.pages[0]) measurement_results.Add('a', 'seconds', 3) measurement_results.DidMeasurePage() measurement_res...
[ "def test_repeated_pageset_one_iteration_one_page_error(self):\n test_page_set = _MakePageSet()\n\n measurement_results = SummarySavingPageMeasurementResults()\n measurement_results.WillMeasurePage(test_page_set.pages[0])\n measurement_results.Add('a', 'seconds', 3)\n measurement_results.DidMeasurePa...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Page error on one iteration, no results for that page should print.
def test_repeated_pageset_one_iteration_one_page_error(self): test_page_set = _MakePageSet() measurement_results = SummarySavingPageMeasurementResults() measurement_results.WillMeasurePage(test_page_set.pages[0]) measurement_results.Add('a', 'seconds', 3) measurement_results.DidMeasurePage() me...
[ "def printError(queryResults):\n print (queryResults[1])\n # For loop created for the httpErrors array\n for results in queryResults[0]:\n print (\n results[0], \"-\",\n str(results[1]) + \"% errors\")", "def test_batch_list_with_bad_pagination(self):\n response = sel...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Finds golden files and returns Test cases for each.
def FindTests(): for root, _, files in os.walk(GOLDEN_CASES_DIR): path_parts = root.split('/') if path_parts[-3] == 'golden': language = path_parts[-2] variant = path_parts[-1] for golden_file in files: input, _ = golden_file.split('.') options = None if input.endswit...
[ "def match_files(gold_folder, sys_folder):\n\n print \"Compiling files...\"\n # Get a list of files in the folders supplied.\n gold_files = compile_files(gold_folder) # nnnnG.xml\n sys_files = compile_files(sys_folder) # nnnnXXN.xml\n\n print \"%d gold files found in %s\" % (len(gold_files), base_n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Element indexing to a cat column must give the underlying object not the numerical index.
def test_categorical_element_indexing(): cat = pd.Categorical(["a", "a", "b", "c", "a"], categories=["a", "b", "c"]) pdsr = pd.Series(cat) sr = cudf.Series(cat) assert_eq(pdsr, sr) assert_eq(pdsr.cat.codes, sr.cat.codes, check_dtype=False)
[ "def cat_index(self): \n df = self.get_prepared_df()\n df.drop('price',axis = 1,inplace = True)\n categorical_features_indices = np.where(\n (df.dtypes != np.int)&(df.dtypes != np.float))[0]\n \n index = categorical_features_indices.reshape(1,-1).tolist()[0]\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the config for the given class
def find(self, cls): for currentClass in self._classesToCheck(cls): if currentClass in self.config: return self.config[currentClass] else: return None
[ "def get_config(config_class_string):\n config_module, config_class = config_class_string.rsplit('.', 1)\n\n config_class_object = getattr(import_module(config_module), config_class)\n config_obj = config_class_object()\n\n return config_obj", "def get_config():\n config_imports = os.environ['APP_S...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generator to return the classes to check
def _classesToCheck(self, cls): yield cls yield from inspect.getmro(cls)
[ "def return_classes(self):\n\n\t\t \n\t\t \n\t\treturn self.classes", "def classes(self):\n m = self.module\n for m in self.modules():\n for klass_name, klass in inspect.getmembers(m, inspect.isclass):\n yield klass", "def iter_cls(*classes, blacklist=tuple()):\n f...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a new Converter for the given value
def newConverter(self, value): return JsonConverter(value, self)
[ "def do_conversion(self, value):\n converter, found = self.find_converter()\n if not found:\n return value, False\n else:\n converted = converter(self, value)\n self.converters.done(self, converted)\n if hasattr(converted, \"post_setup\"):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test the paste_app_factory method
def test_paste_app_factory(conf_options: dict) -> None: pypiserver.paste_app_factory({}, **conf_options) # type: ignore
[ "def paste(*_, **settings):\n\n hook_exceptions()\n return app", "def testCreateApplication(self):\n main.create_application()", "def test_app_is_created(app):\n assert app.name == \"myapp.app\"", "def test_apps(self):\n import main.apps", "def setUp(self):\n self.app = create_app(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test converting legacy kwargs to modern ones.
def test_backwards_compat_kwargs_conversion( incoming: t.Dict[str, t.Any], updated: t.Dict[str, t.Any] ) -> None: assert pypiserver.backwards_compat_kwargs(incoming) == updated
[ "def test_backwards_compat_kwargs_duplicate_check(\n kwargs: t.Dict[str, t.Any]\n) -> None:\n with pytest.raises(ValueError) as err:\n pypiserver.backwards_compat_kwargs(kwargs)\n assert \"('redirect_to_fallback', 'disable_fallback')\" in str(err.value)", "def test_kwargs(self):\n def f(**k...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Duplicate legacy and modern kwargs cause an error.
def test_backwards_compat_kwargs_duplicate_check( kwargs: t.Dict[str, t.Any] ) -> None: with pytest.raises(ValueError) as err: pypiserver.backwards_compat_kwargs(kwargs) assert "('redirect_to_fallback', 'disable_fallback')" in str(err.value)
[ "def test_backwards_compat_kwargs_conversion(\n incoming: t.Dict[str, t.Any], updated: t.Dict[str, t.Any]\n) -> None:\n assert pypiserver.backwards_compat_kwargs(incoming) == updated", "def _deprecated_kwargs(kwargs, arg_newarg):\n warn_for = []\n for (arg, new_kw) in arg_newarg:\n if arg in kw...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets hyperparam from eta. eta is always given as natural scale (i.e., not as in log scale). If self.use_log_eta is True, hyperparam is set as log10 of eta, otherwise, just as eta.
def _eta_to_hyperparam(self, eta): # If logscale is used, output hyperparam is log of eta. if self.use_log_eta: hyperparam = numpy.log10(numpy.abs(eta)) else: hyperparam = numpy.abs(eta) return hyperparam
[ "def eta(self, eta):\n\n self._eta = eta", "def set_eta(self, eta, recalc=True):\n self.photon.set_eta(eta, recalc)\n if recalc:\n self.dt, self.dr, self.dtheta, self.dphi = self.photon.get_ic()", "def setLearningRate(self, learningRate):\n # Set learning rate\n if ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets hyperparam from scale. scale is always given with no logscale If self.use_log_scale is True, hyperparam is set as log10 of scale, otherwise, just as scale.
def _scale_to_hyperparam(self, scale): # If logscale is used, output hyperparam is log of scale. if self.use_log_scale: hyperparam = numpy.log10(numpy.abs(scale)) else: hyperparam = numpy.abs(scale) return hyperparam
[ "def _hyperparam_to_scale(self, hyperparam):\n\n # If logscale is used, input hyperparam is log of the scale.\n if self.use_log_scale:\n scale = 10.0**hyperparam\n else:\n scale = numpy.abs(hyperparam)\n\n return scale", "def set_log_scale(self, log_scale = True):...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets scale from hyperparam. If self.use_log_eta is True, hyperparam is the log10 of scale, hence, 10hyperparam is set to scale. If self.use_log_eta is False, hyperparam is directly set to scale.
def _hyperparam_to_scale(self, hyperparam): # If logscale is used, input hyperparam is log of the scale. if self.use_log_scale: scale = 10.0**hyperparam else: scale = numpy.abs(hyperparam) return scale
[ "def set_scale(self, scale):\n scale = float(scale)\n if scale <= 1:\n raise ValueError('The scale parameter must exceed 1.')\n self._a = scale", "def scale(self, scale):\n\n self._scale = scale", "def _scale_to_hyperparam(self, scale):\n\n # If logscale is used, ou...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Converts the input hyperparameters to their log10, if this is enabled by ``self.use_log_eta`` and ``self.use_scale``. If is assumed that the input hyperparam is not in log scale, and it
def hyperparam_to_log_hyperparam(self, hyperparam): if numpy.isscalar(hyperparam): hyperparam_ = numpy.array([hyperparam], dtype=float) elif isinstance(hyperparam, list): hyperparam_ = numpy.array(hyperparam, dtype=float) else: # Copy to avoid overwriting inp...
[ "def get_in_log10p(self):\n assert self.ptype == '', \"predict not in bare parametrization.\"\n \n def _f_log10p(log10p):\n p = np.power(10, np.array(log10p))\n return self.f(p)\n \n def _Df_log10p(log10p):\n p = np.power(10, np.array(log10p))\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Computes Y, C, Cinv, and Mz. These variables are shared among many of the functions, hence their values are stored as the class attribute to avoid recomputation when the hyperparam is the same.
def _update_Y_C_Mz(self, hyperparam): if numpy.isscalar(hyperparam): hyperparam_ = numpy.array([hyperparam], dtype=float) else: hyperparam_ = hyperparam # Check if likelihood is already computed for an identical hyperparam if (self.Y is None) or \ ...
[ "def estimacao_parametros(self, X, y):\n check_is_fitted(self)\n # Armazena os vetores de médias e a matrizes de variância e covariância\n \n \n #Estimação do vetor de médias\n \n for k in range(len(self.classes_)): \n for i in rang...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Based on a given eta, finds optimal sigma and sigma0.
def _find_optimal_sigma_sigma0(self, hyperparam): # Get eta eta = self._hyperparam_to_eta(hyperparam) if numpy.abs(eta) > self.max_eta: # eta is very large. Use Asymptotic relation sigma02 = self._find_optimal_sigma02() if numpy.isinf(eta): ...
[ "def _find_optimal_sigma02(self):\n\n # Note: this sigma0 is only when eta is at infinity. Hence, computing\n # it does not require eta, update of self.mixed_cor, or update of Y, C,\n # Mz. Hence, once it is computed, it can be reused even if other\n # variables like eta changed. Here, i...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Finds optimal sigma2 either if eta is large or not. As a product, this function also computes Y, C, and Mz and stores them into the class attribute.
def _find_optimal_sigma2(self, hyperparam): # Get eta eta = self._hyperparam_to_eta(hyperparam) if numpy.isinf(eta): self.sigma2 = 0.0 elif numpy.abs(eta) > self.max_eta: # eta is very large. Use Asymptotic relation sigma02 = self._find_optimal_sig...
[ "def _find_optimal_sigma02(self):\n\n # Note: this sigma0 is only when eta is at infinity. Hence, computing\n # it does not require eta, update of self.mixed_cor, or update of Y, C,\n # Mz. Hence, once it is computed, it can be reused even if other\n # variables like eta changed. Here, i...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
When eta is very large, we assume sigma is zero. Thus, sigma0 is computed by this function. This is the Ordinary Least Square (OLS) solution of the regression problem where we assume there is no correlation between points, hence sigma is assumed to be zero. This function does not require update of self.mixed_cor with h...
def _find_optimal_sigma02(self): # Note: this sigma0 is only when eta is at infinity. Hence, computing # it does not require eta, update of self.mixed_cor, or update of Y, C, # Mz. Hence, once it is computed, it can be reused even if other # variables like eta changed. Here, it suffice ...
[ "def _find_optimal_sigma_sigma0(self, hyperparam):\n\n # Get eta\n eta = self._hyperparam_to_eta(hyperparam)\n\n if numpy.abs(eta) > self.max_eta:\n\n # eta is very large. Use Asymptotic relation\n sigma02 = self._find_optimal_sigma02()\n\n if numpy.isinf(eta):\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Log likelihood function L = (1/2) log det(S) (1/2) log det(X.TSinvX) (1/2) sigma^(2) z.T M1 z where S = sigma^2 Kn is the covariance Sinv is the inverse of S M1 = Sinv = SinvX(X.TSinvX)^(1)X.TSinv hyperparam = [eta, scale[0], scale[1], ...] sign_switch changes the sign of the output from ell to ell. When True, this is ...
def likelihood(self, sign_switch, hyperparam): self.timer.tic() if numpy.isscalar(hyperparam): hyperparam_ = numpy.array([hyperparam], dtype=float) else: hyperparam_ = hyperparam # Check if likelihood is already computed for an identical hyperparam if (...
[ "def loglikelihood_norminv(parameters, X):\n alpha = parameters[0]\n beta = parameters[1]\n mu = parameters[2]\n delta = parameters[3]\n likelihood = norminvgauss.pdf(X, alpha, beta, mu, delta)\n loglik = -sum(np.log(likelihood))\n return loglik", "def log_likelihood(self) -> tf.Tensor:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
ell is the log likelihood probability. dell_deta is d(ell)/d(eta), which is the derivative of ell with respect to eta when the optimal value of sigma is substituted in the likelihood function per given eta.
def _likelihood_der1_eta(self, hyperparam): # Get eta eta = self._hyperparam_to_eta(hyperparam) # Include derivative w.r.t scale if (not numpy.isscalar(hyperparam)) and \ (hyperparam.size > self.scale_index): # Set scale of the covariance object ...
[ "def differential_entropy(samples, parameters, nb_points_per_interval, nb_intervals_per_side):\n approximate_prob = approximate_probability(samples,\n parameters,\n nb_points_per_interval,\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The second derivative of ell is computed as a function of only eta. Here, we substituted optimal value of sigma, which is self is a function of eta.
def _likelihood_der2_eta(self, hyperparam): # Get eta eta = self._hyperparam_to_eta(hyperparam) # Include derivative w.r.t scale if (not numpy.isscalar(hyperparam)) and \ (hyperparam.size > self.scale_index): # Set scale of the covariance object ...
[ "def _likelihood_der1_eta(self, hyperparam):\n\n # Get eta\n eta = self._hyperparam_to_eta(hyperparam)\n\n # Include derivative w.r.t scale\n if (not numpy.isscalar(hyperparam)) and \\\n (hyperparam.size > self.scale_index):\n\n # Set scale of the covariance obj...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
ell is the log likelihood probability. der2_scale is d2(ell)/d(theta2), is the second derivative of ell with respect to the distance scale (theta). The output is a 2D array of the size of scale.
def _likelihood_der2_scale(self, hyperparam): # Get eta eta = self._hyperparam_to_eta(hyperparam) # Set scale of the covariance object scale = self._hyperparam_to_scale(hyperparam[self.scale_index:]) self.mixed_cor.set_scale(scale) # Initialize Hessian d2ell_ds...
[ "def __dNdlog2dN(self,Dp,dNdlogDp):\n \n x = np.log10(Dp)\n y = (x[1:]+x[:-1])/2.\n y = np.pad(y,1,'constant',constant_values=(x[0]-(y[0]-x[0]),x[-1]+(x[-1]-y[-1])))\n dlogDp = np.diff(y)\n return dNdlogDp*dlogDp # cm-3", "def l2_error(dist_orig, dist_proj):\n return...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This method send bypass captcha requests to server.
def bypass_captcha(self, rps): viewstate_pattern = r"id=\"__VIEWSTATE\".*\"(.*)\"" viewstategenerator_pattern = r"id=\"__VIEWSTATEGENERATOR\".*\"(.*)\"" CAPTCHA_PATTERN = r"id=\"ctl00_ContentPlaceHolder1_ctl00_lblCapcha\".*?>(.*?)<\/span>" viewstate = re.search(viewstate_pattern, rps) ...
[ "def process_captcha(self, req, resp):\n self.logger.debug(\n \"RPM over Anti-Automation threshold %s\",\n self.cfg.MAX_RPM\n )\n # test the aa cookie if they provided it\n if 'aa' in req.cookies and self.web_util.test_captcha(req.cookies['aa']):\n se...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Configure MFA for a supported method. This endpoint allows you to turn on multifactor authentication with a given backend. Currently only Duo is supported.
def configure(self, mount_point, mfa_type="duo", force=False): if mfa_type != "duo" and not force: # The situation described via this exception is not likely to change in the future. # However we provided that flexibility here just in case. error_msg = 'Unsupported mfa_type a...
[ "def set_tdlib_mfa_code(self, code: str):\n if self._auth_state == TelegramAuthState.WAIT_MFA_CODE:\n logging.debug(f\"TDLib JSON sending MFA code.\")\n self._td_client_send({'@type': 'checkAuthenticationCode', 'code': code})\n self._auth_state = TelegramAuthState.WAIT_REQUES...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Read the MFA configuration.
def read_configuration(self, mount_point): api_path = utils.format_url( "/v1/auth/{mount_point}/mfa_config", mount_point=mount_point, ) return self._adapter.get(url=api_path)
[ "def readConfig(self):\n buf = self.read(1, 2)\n if buf:\n self.config = buf\n else:\n raise IOError(\"Failed to read configuration\")", "def ReadConfig(self):\n\t\tr = self.ADSReadWord(0x01)\n\t\treturn r", "def read_ampq_config(fname):\n config = ConfigParser.Conf...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Configure the access keys and host for Duo API connections. To authenticate users with Duo, the backend needs to know what host to connect to and must authenticate with an integration key and secret key. This endpoint is used to configure that information.
def configure_duo_access(self, mount_point, host, integration_key, secret_key): params = { "host": host, "ikey": integration_key, "skey": secret_key, } api_path = utils.format_url( "/v1/auth/{mount_point}/duo/access", mount_point=mount_...
[ "def connect(self, params):\n self.logger.info(\"Connect: Connecting...\")\n\n api_key = params.get(Input.API_KEY).get(\"secretKey\")\n region_string = params.get(Input.REGION)\n\n self.api = ApiConnection(api_key, region_string, self.logger)\n\n self.logger.info(\"Setup Complete\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Read the Duo second factor behavior configuration.
def read_duo_behavior_configuration(self, mount_point): api_path = utils.format_url( "/v1/auth/{mount_point}/duo/config", mount_point=mount_point, ) return self._adapter.get(url=api_path)
[ "def ReadConfig(self):\n\t\tr = self.ADSReadWord(0x01)\n\t\treturn r", "def generate_config_mixed_second(self):\n for model_name in self.profile_models[:1]:\n del self.config['profile_models'][model_name]\n self.config['profile_models'][\n self.profile_models[1]]['parameters'][...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
1.验证update kyc,publish kyc 2.验证kyc在table rule_kyc_reject_reason更新 3.验证kyc在table rule_kyc_reject_reason_operation更新 4.验证kyc在table rule_kyc_reject_reason_snapshot更新
def verify_kyc_update(self, test_payload): if config.COUNTRY == constants.US: table_prefix = "usrisk" elif config.COUNTRY == constants.JP: table_prefix = "jprisk" elif config.COUNTRY == constants.CN: table_prefix = "cnrisk" else: table_pref...
[ "def test_update_rule(self):\n pass", "def update_error_reasons(reasons):", "def process_update_policy_rule_set(self, session, data, result):\n pass", "def process_update_policy_rule(self, session, data, result):\n pass", "def update_rules():\n update_all_rules()\n return \"OK\"",...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
LM score between entity field and query (JM smoothing, lambda=0.1).
def lm_score(self, entity_id, field=Lucene.FIELDNAME_CONTENTS): params = {'field': field} score = ScorerLM(econfig.LUCENE, self.query, params).score_doc(entity_id) if score is None: return None return math.exp(score)
[ "def nllr_lm_score(self, entity_id, field=Lucene.FIELDNAME_CONTENTS):\n if self.DEBUG:\n print entity_id\n weights = {field: 1}\n return self.nllr_mlm_score(entity_id, weights)", "def tm_score(somme, l):\n return(somme/l)", "def MMRScore(sentence, query, summary, lambta=0.5):\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
NLLRLM score between entity field and query (JM smoothing, lambda=0.1).
def nllr_lm_score(self, entity_id, field=Lucene.FIELDNAME_CONTENTS): if self.DEBUG: print entity_id weights = {field: 1} return self.nllr_mlm_score(entity_id, weights)
[ "def lm_score(self, entity_id, field=Lucene.FIELDNAME_CONTENTS):\n params = {'field': field}\n score = ScorerLM(econfig.LUCENE, self.query, params).score_doc(entity_id)\n if score is None:\n return None\n return math.exp(score)", "def MMRScore(sentence, query, summary, lambt...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
LM score of entity to the context of query (context means query mention) E.g. given the query "uss yorktown charleston" and mention "uss", query context is " yorktown charleston"
def context_sim(self, entity_id, mention, field=Lucene.FIELDNAME_CONTENTS): # get query context match = re.search(mention, self.query) if match is None: raise Exception("NOTE: Mention \"" + mention + "\" is not found in the query \"" + self.query + "\"") mention_scope = match...
[ "def logscore(self, word, context: Optional[Any] = ...):\n ...", "def score(self, model, context):\n pass", "def compute_candidate_scores(self, entity, tagged_text):\n entity = {**entity}\n mention_label = \" \".join(entity['tokens'])\n entity['linkings'] = [{**l} for l in ent...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculates similarity between query and set. sim(q|e1, e2, ..., en) = Mul_i (Sum_j ( p(t_i|e_j) ) ) = Mul_i (Sum_j ( Sum_f (weight_f p(t_i|theta_e_j_f))))
def query_set_sim(self, en_ids, weights): # fielded_weights = self.__get_weights(weights) scorer = ScorerMLM(econfig.LUCENE, self.query, {}) # {'field_weights': fielded_weights}) p_t_theta_d = {} for t in set(self.query.split()): p_t_theta_d[t] = 0 for en in en_...
[ "def compute_sim(query, database):\n return np.dot(database, query.T)", "def mp_similarity_fn(q, d):\n return mp_model.predict([q], [[d]])[0][0]", "def test_similarity_for_request(self):\n request1 = factories.RequestFactory(audit_id=self.audit.id)\n request2 = factories.RequestFactory(audit_id=self...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function launches a new thread that will periodically poll the total memory usage of the tool that is being run. If it goes over the limit will kill it
def _memoryLimitPolling(self, process): assert self.memoryLimitPollTimePeriodInSeconds > 0 assert self._outOfMemory == False # Other parts of the runner can can set on this to prevent this thread # from waiting on this Event object. self._eventObj = threading.Event() sel...
[ "def __init__(self):\n super(MemoryMonitoringThread, self).__init__()\n self.daemon = True", "def memory_monitor(queue: Queue, outfile_prefix: str) -> None:\n tracemalloc.start()\n old_max = 0\n snapshot = None\n wait_time = 0.1\n\n fout = open(\"{}_MAX_TRACKER\".format(outfile_prefix...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
PythonPsUtilBackend runs directly on the host so all files are available so just return the requested `hostPath`.
def getFilePathInBackend(self, hostPath): return hostPath
[ "def host_path(self):\n return self._host_path", "def get_hosts_path():\n return config.get(\"app\", \"hosts_path\")", "def get_host_outfiles(self):\n\n raise NotImplementedError", "def getVirtualHostRoot():", "def mitogen_lxc_attach_path(self):", "def get_host_list_file_path(self):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
returns insee code corresponding to dpt, city
def match_city(self, city, dpt_code, zip_code = None): city = format_str_city_insee(city) dpt_code = dpt_code.rjust(2, '0') if zip_code: zip_code.rjust(5, '0') # Based on zip code and city name ls_matching = [] found_indicator = False if zip_code: if zip_code in self.dict_corr_zi...
[ "def get_iata_code(city: str) -> str:\n parameters = {'apikey': API_KEY,\n 'term': city}\n response = requests.get(url=LOCATIONS_ENDPOINT, params=parameters)\n city_code = response.json()['locations'][0]['code']\n return city_code", "def postalcode_area_studies():\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
returns dict of (insee_code, insee_code_ardt) hence should be used with dict_refine_ic.get(some_ic, (None, None))
def get_dict_refine_insee_code(ls_valid_ic): dict_refine_ic = {x: (x, x) for x in ls_valid_ic} ls_valid_ic_corse = [x for x in ls_valid_ic if re.match('2[AB]', x)] for ic in ls_valid_ic_corse: dict_refine_ic[ic[:1] + u'0' + ic[2:]] = (ic, ic) # assumed unicity was checked dict_ic_ardts = dict(list(itertools...
[ "def read_icd_indication_dict(icd10map):\n\n icd_dict = {}\n junk_words = ['OTHER', 'UNSPECIFIED', 'UNKNOWN']\n split_words = ['AND', 'WITH']\n truncate_words = ['WITHOUT']\n junk_phrases = ['PERSONAL_HISTORY_OF_', 'SITE_NOT_SPECIFIED', 'NOT_SPECIFIED', \\\n 'NOT_ELSEWHERE_CLASSIFI...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a unique version of the name indicated by incrementing a numeral at the end. Stop when the name no longer appears in the indicated list of elements.
def GetUniqueName( name, elems ): digits = [] for c in reversed( name ): if c.isdigit(): digits.append( c ) else: break stem = name[0:len( name ) - len( digits )] val = ''.join( digits )[::-1] or 0 i = int( val ) while True: i += 1 ...
[ "def unique_name(name, names):\n while name in names or not name:\n digits = re.search(r'\\d+$', name)\n if name and digits:\n digits = digits.group()\n n_digits = len(digits)\n name = name[:-n_digits] + str(int(digits) + 1)\n else:\n name = name +...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Parse linux kernel command line
def _parse_kernel_cmdline(): with open('/proc/cmdline', 'rt') as f: cmdline = f.read() parameters = {} for p in cmdline.split(): name, _, value = p.partition('=') parameters[name] = value return parameters
[ "def _parse_kernel_cmdline():\n with open('/proc/cmdline', 'rt') as f:\n cmdline = f.read()\n return {k: v for k, v in [opt.split('=', 1) for opt in cmdline.split()]}", "def parse_line(self, line):\n command, _, arg = line.strip().partition(\" \")\n return command, arg.strip()", "def ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get IP address of interface by mac.
def _get_interface_ip(mac_addr): interfaces = netifaces.interfaces() for iface in interfaces: addresses = netifaces.ifaddresses(iface) link_addresses = addresses.get(netifaces.AF_LINK, []) for link_addr in link_addresses: if link_addr.get('addr') == mac_addr: ...
[ "def get_ip_address(interface):\n try:\n import netifaces\n detail = netifaces.ifaddresses(interface)\n if netifaces.AF_INET in detail:\n ip = detail[netifaces.AF_INET][0]['addr']\n else:\n ip = 'unavailable'\n if netifaces.AF_LINK in detail:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates the replay buffer used by the agent.
def _build_replay_buffer(self, use_staging): return circular_replay_buffer.WrappedReplayBuffer( observation_shape=self.observation_shape, stack_size=self.stack_size, use_staging=use_staging, update_horizon=self.update_horizon, observation_dtype=self.observation_dtype.as_numpy...
[ "def build_replay_buffer(agent, batch_size, steps_per_loop):\n buf = tf_uniform_replay_buffer.TFUniformReplayBuffer(\n data_spec=agent.policy.trajectory_spec,\n batch_size=batch_size,\n max_length=steps_per_loop)\n return buf", "def _build_replay_buffer(self, use_staging):\n return replay_buff...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Build an op used as a target for the Qvalue.
def _build_target_q_op(self): targets = [] for gamma, target_q in zip(self.gammas, self._replay_next_target_net_outputs.q_values): # Get the maximum Q-value across the actions dimension. replay_next_qt_max = tf.reduce_max(target_q, 1) # Calculate the Bellman tar...
[ "def _build_target_q_op(self):\n q_values_next = self.online_convnet(self._replay.next_states)\n best_actions = tf.math.argmax(tf.squeeze(q_values_next), axis=1)\n q_values_next_target = self.target_convnet(self._replay.next_states)\n bb = tf.stack([np.arange(best_actions.get_shape().as_list()[0]), tf.s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Got tweet text and make links to and keywords >>> _make_links(' looks good')
def _make_links(tweet): for pattern, repl in (USER_SUB, KEYWORD_SUB): tweet = re.sub(pattern, repl, tweet) return tweet
[ "def convert_links(text, trim_url_limit=None, nofollow=False, autoescape=False):\n\n safe_input = isinstance(text, SafeData)\n words = word_split_re.split(force_text(text))\n for i, word in enumerate(words):\n if '.' in word or ':' in word:\n # Deal with punctuation.\n lead, mi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return tweet number by it's url
def _get_tweet_number(tweet_url): path = urlparse.urlparse(tweet_url)[2] number = path.split('/')[-1] return '#%s' % (number,)
[ "def extract_twitter_id(url):\n if 'twitter.com/' in url:\n status_id = url.partition(\"/status/\")[2]\n try:\n int(status_id)\n return str(status_id)\n except ValueError:\n print('Please submit URL for particular tweet (ending in /status/somenumber)')\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Adapt Twitter update from feed to appropriate form
def adapt_tweet(feedpost): tweet = feedpost['title'] for action in (_make_links, _clean_name, urlize): tweet = action(tweet) feedpost['title'] = _get_tweet_number(feedpost['link']) feedpost['body'] = u'<p>%s</p>' % tweet return feedpost
[ "def post_to_twitter(self):\n\n\ttry:\n\t # Call the twitter api\n \tapi = twitter.Api()\n\n \tapi = twitter.Api(\n\t\t\tconsumer_key=settings[\"twitter\"][\"consumer_key\"],\n\t\t\tconsumer_secret=settings[\"twitter\"][\"consumer_secret\"],\n\t\t\taccess_token_key=settings[\"twitter\"][\"acces...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Apply a series of functions to images, in order
def noise_pipeline(images, funcs, DIFFICULTY): if DIFFICULTY == 0: return images else: for func in funcs: images = func(images, DIFFICULTY) return images
[ "def IPA_apply(fun, *imgs):\n shp=imgs[0].shape\n for x in imgs:\n if x.shape!=shp:\n raise Exception(\"Images must have the same shape\")\n y,x=shp\n nim=np.zeros((y,x))\n for j in range(y):\n for i in range(x):\n params=[p.item(j,i) for p in imgs] # Pick the j,i pixel of each image in imgs\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create new header in BigWig, with UCSC chromosome names.
def create_new_header(infile, mappings, outfile): with pyBigWig.open(infile) as bw: if set(bw.chroms().keys()).issubset(mappings.values()): # If chromosome names are already UCSC, just rename input file to output name. # Exit with status 0 since this is normal behavior. o...
[ "def _make_header(self):\n header = fits.Header()\n header[\"COMP\"] = (\"Galactic supernova remnants (SNRs)\",\n \"Emission component\")\n header[\"UNIT\"] = (\"Kelvin\", \"Map unit\")\n header[\"CREATOR\"] = (__name__, \"File creator\")\n # TODO:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test add book and author for this book
def test_basic_book(self): ernest_author = Author.objects.create(FIO="Ernest Miller Hemingway", birthday = "1899-07-21") create_book = Book.objects.create(title="The Old Man And The Sea", yearbook="2012-07-07", short_describe="The Old Man and the Sea is the story of an epic battle between an old, experi...
[ "def test_add_book(self):\n\n first_book_list = BookList()\n first_book = Book()\n\n first_book.create_book({\n \"title\": \"First Man\",\n \"author\": \"James R. Hansen\",\n \"year\": 2005,\n \"publisher_name\": \"Simon & Schuster\",\n \"publication_date\": \"01/01/2018\",\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Doing image geometric transform Proposed image to have the following configurations [H x W x C + CL] Where CL is the number of channels for the label. It is NOT in onehot form
def transform_with_label(aug): geometric_tfx = get_geometric_transformer(aug) intensity_tfx = get_intensity_transformer(aug) def transform(comp, c_label, c_img, use_onehot, nclass, **kwargs): """ Args comp: a numpy array with shape [H x W x C + c_label] c_labe...
[ "def generated_connected_component_img(self) -> None :\n self.labelled_img = sitk.ConnectedComponent(self.binary_img)\n self.labelled_array = sitk.GetArrayFromImage(self.labelled_img) #(z,y,x)\n self.number_of_cc = int(np.max(self.labelled_array))", "def testonehot():\n carr = colorarr()\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sample "length" letters from the "letters" set at random. Sampling with replacement since Python doesn't have a helper for it.
def SampleLetters(letters, length): chosen_letters = [None]*length for i in xrange(length): index = random.randint(0, len(letters)-1) chosen_letters[i] = letters[index] return ''.join(chosen_letters)
[ "def random_letter(letters):\n return random.choice(letters)", "def random_letter_freq():\n return choice(['a']*8 +\n ['b']*1 +\n ['c']*3 +\n ['d']*4 +\n ['e']*12 +\n ['f']*2 +\n ['g']*2 +\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Initialize a randomized sequence of the given length.
def __init__(self, length, alphabet=IUPAC.unambiguous_dna): seq_str = self.SampleLetters(alphabet.letters, length) Seq.__init__(self, seq_str.upper(), alphabet)
[ "def sample(self, sequence_length):", "def generate_random_sequence(length, pool, rand_func=generate_random_bytes):\n if not builtins.is_integer(length):\n raise TypeError(\"Length must be a positive integer: got `%r`\" %\n type(length).__name__)\n if length <= 0:\n raise ValueError(\"l...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
New() > itkStatisticsLabelMapFilterLM2ID2 Create a new object of the class itkStatisticsLabelMapFilterLM2ID2 and set the input and the parameters if some named or nonnamed arguments are passed to that method. New() tries to assign all the non named parameters to the input of the new objects the first non named paramete...
def New(*args, **kargs): obj = itkStatisticsLabelMapFilterLM2ID2.__New_orig__() import itkTemplate itkTemplate.New(obj, *args, **kargs) return obj
[ "def New(*args, **kargs):\n obj = itkStatisticsLabelMapFilterLM2IF2.__New_orig__()\n import itkTemplate\n itkTemplate.New(obj, *args, **kargs)\n return obj", "def New(*args, **kargs):\n obj = itkStatisticsLabelMapFilterLM2IUL2.__New_orig__()\n import itkTemplate\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
itkStatisticsLabelMapFilterLM2ID2_cast(itkLightObject obj) > itkStatisticsLabelMapFilterLM2ID2
def itkStatisticsLabelMapFilterLM2ID2_cast(*args): return _itkStatisticsLabelMapFilterPython.itkStatisticsLabelMapFilterLM2ID2_cast(*args)
[ "def itkStatisticsLabelMapFilterLM2IF2_cast(*args):\n return _itkStatisticsLabelMapFilterPython.itkStatisticsLabelMapFilterLM2IF2_cast(*args)", "def itkLabelStatisticsImageFilterIF2IUS2_cast(obj: 'itkLightObject') -> \"itkLabelStatisticsImageFilterIF2IUS2 *\":\n return _itkLabelStatisticsImageFilterPython.itk...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
New() > itkStatisticsLabelMapFilterLM2IF2 Create a new object of the class itkStatisticsLabelMapFilterLM2IF2 and set the input and the parameters if some named or nonnamed arguments are passed to that method. New() tries to assign all the non named parameters to the input of the new objects the first non named paramete...
def New(*args, **kargs): obj = itkStatisticsLabelMapFilterLM2IF2.__New_orig__() import itkTemplate itkTemplate.New(obj, *args, **kargs) return obj
[ "def New(*args, **kargs):\n obj = itkStatisticsLabelMapFilterLM2ID2.__New_orig__()\n import itkTemplate\n itkTemplate.New(obj, *args, **kargs)\n return obj", "def New(*args, **kargs):\n obj = itkStatisticsLabelMapFilterLM2IUL2.__New_orig__()\n import itkTemplate\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
itkStatisticsLabelMapFilterLM2IF2_cast(itkLightObject obj) > itkStatisticsLabelMapFilterLM2IF2
def itkStatisticsLabelMapFilterLM2IF2_cast(*args): return _itkStatisticsLabelMapFilterPython.itkStatisticsLabelMapFilterLM2IF2_cast(*args)
[ "def itkLabelStatisticsImageFilterIF2IUS2_cast(obj: 'itkLightObject') -> \"itkLabelStatisticsImageFilterIF2IUS2 *\":\n return _itkLabelStatisticsImageFilterPython.itkLabelStatisticsImageFilterIF2IUS2_cast(obj)", "def itkLabelStatisticsImageFilterIF2IUC2_cast(obj: 'itkLightObject') -> \"itkLabelStatisticsImageF...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
GetNumberOfBins(self) > unsigned int
def GetNumberOfBins(self): return _itkStatisticsLabelMapFilterPython.itkStatisticsLabelMapFilterLM2IUC2_GetNumberOfBins(self)
[ "def n_bins(self):\n return len(self.bins) - 1", "def GetNumberOfBins(self):\n return _itkStatisticsLabelMapFilterPython.itkStatisticsLabelMapFilterLM2IUL2_GetNumberOfBins(self)", "def calcnBins(self,binlen):\n nbins = np.int_(self._Dom.getLens()/binlen);\n return nbins;", "def n_b...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
New() > itkStatisticsLabelMapFilterLM2IUC2 Create a new object of the class itkStatisticsLabelMapFilterLM2IUC2 and set the input and the parameters if some named or nonnamed arguments are passed to that method. New() tries to assign all the non named parameters to the input of the new objects the first non named parame...
def New(*args, **kargs): obj = itkStatisticsLabelMapFilterLM2IUC2.__New_orig__() import itkTemplate itkTemplate.New(obj, *args, **kargs) return obj
[ "def New(*args, **kargs):\n obj = itkStatisticsLabelMapFilterLM2IUL2.__New_orig__()\n import itkTemplate\n itkTemplate.New(obj, *args, **kargs)\n return obj", "def New(*args, **kargs):\n obj = itkStatisticsLabelMapFilterLM2ID2.__New_orig__()\n import itkTemplate\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
SetNumberOfBins(self, unsigned int _arg)
def SetNumberOfBins(self, *args): return _itkStatisticsLabelMapFilterPython.itkStatisticsLabelMapFilterLM2IUL2_SetNumberOfBins(self, *args)
[ "def numBinsChanged(self, val):\n self.numBins = val", "def set_bins(self, *args, **kwargs):\n return _qtgui_swig.histogram_sink_f_sptr_set_bins(self, *args, **kwargs)", "def SetNumberOfBinsPerAxis(self, arg0: 'unsigned int') -> \"void\":\n return _itkScalarImageToRunLengthFeaturesFilterPyt...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
GetNumberOfBins(self) > unsigned int
def GetNumberOfBins(self): return _itkStatisticsLabelMapFilterPython.itkStatisticsLabelMapFilterLM2IUL2_GetNumberOfBins(self)
[ "def n_bins(self):\n return len(self.bins) - 1", "def GetNumberOfBins(self):\n return _itkStatisticsLabelMapFilterPython.itkStatisticsLabelMapFilterLM2IUC2_GetNumberOfBins(self)", "def calcnBins(self,binlen):\n nbins = np.int_(self._Dom.getLens()/binlen);\n return nbins;", "def n_b...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
New() > itkStatisticsLabelMapFilterLM2IUL2 Create a new object of the class itkStatisticsLabelMapFilterLM2IUL2 and set the input and the parameters if some named or nonnamed arguments are passed to that method. New() tries to assign all the non named parameters to the input of the new objects the first non named parame...
def New(*args, **kargs): obj = itkStatisticsLabelMapFilterLM2IUL2.__New_orig__() import itkTemplate itkTemplate.New(obj, *args, **kargs) return obj
[ "def New(*args, **kargs):\n obj = itkStatisticsLabelMapFilterLM2ID2.__New_orig__()\n import itkTemplate\n itkTemplate.New(obj, *args, **kargs)\n return obj", "def New(*args, **kargs):\n obj = itkStatisticsLabelMapFilterLM2IF2.__New_orig__()\n import itkTemplate\n i...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
New() > itkStatisticsLabelMapFilterLM2IUS2 Create a new object of the class itkStatisticsLabelMapFilterLM2IUS2 and set the input and the parameters if some named or nonnamed arguments are passed to that method. New() tries to assign all the non named parameters to the input of the new objects the first non named parame...
def New(*args, **kargs): obj = itkStatisticsLabelMapFilterLM2IUS2.__New_orig__() import itkTemplate itkTemplate.New(obj, *args, **kargs) return obj
[ "def New(*args, **kargs):\n obj = itkStatisticsLabelMapFilterLM2ID2.__New_orig__()\n import itkTemplate\n itkTemplate.New(obj, *args, **kargs)\n return obj", "def New(*args, **kargs):\n obj = itkStatisticsLabelMapFilterLM2IF2.__New_orig__()\n import itkTemplate\n i...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
New() > itkStatisticsLabelMapFilterLM3ID3 Create a new object of the class itkStatisticsLabelMapFilterLM3ID3 and set the input and the parameters if some named or nonnamed arguments are passed to that method. New() tries to assign all the non named parameters to the input of the new objects the first non named paramete...
def New(*args, **kargs): obj = itkStatisticsLabelMapFilterLM3ID3.__New_orig__() import itkTemplate itkTemplate.New(obj, *args, **kargs) return obj
[ "def New(*args, **kargs):\n obj = itkStatisticsLabelMapFilterLM3IF3.__New_orig__()\n import itkTemplate\n itkTemplate.New(obj, *args, **kargs)\n return obj", "def New(*args, **kargs):\n obj = itkStatisticsLabelMapFilterLM3IUL3.__New_orig__()\n import itkTemplate\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
New() > itkStatisticsLabelMapFilterLM3IF3 Create a new object of the class itkStatisticsLabelMapFilterLM3IF3 and set the input and the parameters if some named or nonnamed arguments are passed to that method. New() tries to assign all the non named parameters to the input of the new objects the first non named paramete...
def New(*args, **kargs): obj = itkStatisticsLabelMapFilterLM3IF3.__New_orig__() import itkTemplate itkTemplate.New(obj, *args, **kargs) return obj
[ "def New(*args, **kargs):\n obj = itkStatisticsLabelMapFilterLM3ID3.__New_orig__()\n import itkTemplate\n itkTemplate.New(obj, *args, **kargs)\n return obj", "def New(*args, **kargs):\n obj = itkStatisticsLabelMapFilterLM3IUL3.__New_orig__()\n import itkTemplate\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
New() > itkStatisticsLabelMapFilterLM3IUC3 Create a new object of the class itkStatisticsLabelMapFilterLM3IUC3 and set the input and the parameters if some named or nonnamed arguments are passed to that method. New() tries to assign all the non named parameters to the input of the new objects the first non named parame...
def New(*args, **kargs): obj = itkStatisticsLabelMapFilterLM3IUC3.__New_orig__() import itkTemplate itkTemplate.New(obj, *args, **kargs) return obj
[ "def New(*args, **kargs):\n obj = itkStatisticsLabelMapFilterLM3IUL3.__New_orig__()\n import itkTemplate\n itkTemplate.New(obj, *args, **kargs)\n return obj", "def New(*args, **kargs):\n obj = itkStatisticsLabelMapFilterLM3ID3.__New_orig__()\n import itkTemplate\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
New() > itkStatisticsLabelMapFilterLM3IUL3 Create a new object of the class itkStatisticsLabelMapFilterLM3IUL3 and set the input and the parameters if some named or nonnamed arguments are passed to that method. New() tries to assign all the non named parameters to the input of the new objects the first non named parame...
def New(*args, **kargs): obj = itkStatisticsLabelMapFilterLM3IUL3.__New_orig__() import itkTemplate itkTemplate.New(obj, *args, **kargs) return obj
[ "def New(*args, **kargs):\n obj = itkStatisticsLabelMapFilterLM3IF3.__New_orig__()\n import itkTemplate\n itkTemplate.New(obj, *args, **kargs)\n return obj", "def New(*args, **kargs):\n obj = itkStatisticsLabelMapFilterLM3IUC3.__New_orig__()\n import itkTemplate\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
New() > itkStatisticsLabelMapFilterLM3IUS3 Create a new object of the class itkStatisticsLabelMapFilterLM3IUS3 and set the input and the parameters if some named or nonnamed arguments are passed to that method. New() tries to assign all the non named parameters to the input of the new objects the first non named parame...
def New(*args, **kargs): obj = itkStatisticsLabelMapFilterLM3IUS3.__New_orig__() import itkTemplate itkTemplate.New(obj, *args, **kargs) return obj
[ "def New(*args, **kargs):\n obj = itkStatisticsLabelMapFilterLM3IUL3.__New_orig__()\n import itkTemplate\n itkTemplate.New(obj, *args, **kargs)\n return obj", "def New(*args, **kargs):\n obj = itkStatisticsLabelMapFilterLM3IF3.__New_orig__()\n import itkTemplate\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test to see if parse redis raises value error if bad input.
def test_parse_redis_data_error(): with pytest.raises(ValueError): redis_data.parse_redis_data(b"this is some data")
[ "def __parse_error(self):\n def get_badvalue(data_string, data):\n elements = re.sub(r'[\\'\\]]', '', data_string).split('[')\n elements.pop(0) # Get rid of data as the first element\n value = None\n for k in elements:\n try:\n key...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test to see if get redis data returns data dictionary.
def test_get_redis_data_good_redis_key(from_url): mock_method = from_url().get mock_method.return_value = GOOD_REDIS_RETURN assert redis_data.get_redis_data('trends') == {'trend1': 'url1', 'trend2': 'url2', ...
[ "def test_if_call_success_key_is_stored_in_redis_correctly(self):\n self.data[OS_KEY] = 'iOS'\n self.data[OS_VERSION_KEY] = '5.0.1'\n self.data[APP_VERSION_KEY] = '2.0'\n self.data[NETWORK_KEY] = 'WiFi'\n self.data[CONNECTION_TYPE_KEY] = 'TLS'\n self.data[DIRECTION_KEY] = '...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test to see if set redis data is called.
def test_set_redis_data(from_url): mock_method = from_url().set redis_data.set_redis_data('trends', 'val') assert mock_method.call_count == 1
[ "def test_set_redis_data_empty(from_url):\n mock_method = from_url().set\n redis_data.set_redis_data('trends', {})\n assert mock_method.call_count == 1", "def test_set(self):\n self.assertFalse(sdb.set_(\"sdb://mymemcached/foo\", \"bar\"))", "def test_config_set(self):\n self.assertEqual(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test to see if set redis data is called with empty data.
def test_set_redis_data_empty(from_url): mock_method = from_url().set redis_data.set_redis_data('trends', {}) assert mock_method.call_count == 1
[ "def empty_datastore():\r\n return datastore.Client().get(datastore.Client().key(\"Data\", 1)) is None", "def shouldClearDefinedData(self) -> bool:\n ...", "def test_insert_empty_data(self):\n self.engine.insert_data(self.empty_data)\n self.assertDictEqual(self.ds.store, {})", "def tes...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Redirect to the Authentication Server
def to_auth_server(allowed_paths): if allowed_paths is not None: # 308 - Permanent Redirect, but preserve the content of your request return redirect("http://"+ ip + ":5005/auth/%s" % allowed_paths, code=308) # 301 - Moved Permanently return redirect("http://"+ ip + ":5005/auth/", code...
[ "def redirect_login():\n return redirect('/agent/login')", "def handle_redirect(self, r, **kwargs):\n if r.is_redirect:\n self._thread_local.auth_attempted = False", "def auth_step_1(request):\n print(\"Auth Step 1 ..... \")\n credentials = getattr(settings, \"ZERODHA_CREDENTIALS\")\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Redirect to the Service Server
def to_service_server(allowed_paths): if allowed_paths is not None: # 308 - Permanent Redirect, but preserve the content of your request return redirect("http://"+ ip + ":5007/service/%s" % allowed_paths, code=308) # 301 - Moved Permanently return redirect("http://"+ ip + ":5007/servic...
[ "def redirect_catchall():\n return redirect(\"/\")", "def redirect_client(requested_uri):\n return redirect(requested_uri['value'], 301)", "def perform_redirect_request():\n # HINT: you should use the allow_redirects parameter while doing the request\n url = 'https://httpbin.org/redirect/1'\n pas...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }