code
stringlengths
12
2.05k
label_name
stringclasses
5 values
label
int64
0
4
def toggle_archived(book_id): is_archived = change_archived_books(book_id, message="Book {} archivebit toggled".format(book_id)) if is_archived: remove_synced_book(book_id) return ""
Base
1
def show_unit_extensions(request, course_id): """ Shows all of the students which have due date extensions for the given unit. """ course = get_course_by_id(SlashSeparatedCourseKey.from_deprecated_string(course_id)) unit = find_unit(course, request.GET.get('url')) return JsonResponse(dump_module...
Compound
4
def response(self, response, content): if "authentication-info" not in response: challenge = _parse_www_authenticate(response, "www-authenticate").get( "digest", {} ) if "true" == challenge.get("stale"): self.challenge["nonce"] = challenge[...
Class
2
def reset_due_date(request, course_id): """ Rescinds a due date extension for a student on a particular unit. """ course = get_course_by_id(SlashSeparatedCourseKey.from_deprecated_string(course_id)) student = require_student_from_identifier(request.GET.get('student')) unit = find_unit(course, re...
Compound
4
def get_pos_tagger(self): from nltk.corpus import brown regexp_tagger = RegexpTagger( [ (r"^-?[0-9]+(.[0-9]+)?$", "CD"), # cardinal numbers (r"(The|the|A|a|An|an)$", "AT"), # articles (r".*able$", "JJ"), # adjectives (r"...
Base
1
def parse_http_message(kind, buf): if buf._end: return None try: start_line = buf.readline() except EOFError: return None msg = kind() msg.raw = start_line if kind is HttpRequest: assert re.match( br".+ HTTP/\d\.\d\r\n$", start_line ), "Start l...
Class
2
def get_vars_next(self): next = current.request.vars._next host = current.request.env.http_host if isinstance(next, (list, tuple)): next = next[0] if next and self.settings.prevent_open_redirect_attacks: return self.prevent_open_redirect(next, host) re...
Base
1
def test_slot_policy_scrapy_default(): mw = _get_mw() req = scrapy.Request("http://example.com", meta = {'splash': { 'slot_policy': scrapy_splash.SlotPolicy.SCRAPY_DEFAULT }}) req = mw.process_request(req, None) assert 'download_slot' not in req.meta
Class
2
def test_received_no_doublecr(self): data = b"""\ GET /foobar HTTP/8.4 """ result = self.parser.received(data) self.assertEqual(result, 21) self.assertFalse(self.parser.completed) self.assertEqual(self.parser.headers, {})
Base
1
def get_imports(self, *, prefix: str) -> Set[str]: """ Get a set of import strings that should be included when this property is used somewhere Args: prefix: A prefix to put before any relative (local) module names. """ imports = super().get_imports(prefix=prefix...
Base
1
def test_login_unknown_code(self): response = self.client.post('/accounts/login/code/', { 'code': 'unknown', }) self.assertEqual(response.status_code, 200) self.assertEqual(response.context['form'].errors, { 'code': ['Login code is invalid. It might have expi...
Base
1
def _returndata_encoding(contract_sig): if contract_sig.is_from_json: return Encoding.JSON_ABI return Encoding.ABI
Base
1
def test_underscore_traversal(self): # Prevent traversal to names starting with an underscore (_) ec = self._makeContext() with self.assertRaises(NotFound): ec.evaluate("context/__class__") with self.assertRaises(NotFound): ec.evaluate("nocall: random/_itert...
Base
1
def serialize(self, bundle, format='application/json', options={}): """ Given some data and a format, calls the correct method to serialize the data and returns the result. """ desired_format = None for short_format, long_format in self.content_types.items():...
Class
2
def publish(request, category_id=None): if category_id: get_object_or_404( Category.objects.visible(), pk=category_id) user = request.user form = TopicForm( user=user, data=post_data(request), initial={'category': category_id}) cform = CommentForm...
Base
1
def sql_insert(self, sentence): self.cursor.execute(sentence) self.conn.commit() return True
Base
1
def test_list_entrance_exam_instructor_tasks_all_student(self): """ Test list task history for entrance exam AND all student. """ url = reverse('list_entrance_exam_instructor_tasks', kwargs={'course_id': unicode(self.course.id)}) response = self.client.get(url, {}) self.assertEqual(r...
Compound
4
def from_plist(self, content): """ Given some binary plist data, returns a Python dictionary of the decoded data. """ if biplist is None: raise ImproperlyConfigured("Usage of the plist aspects requires biplist.") return biplist.readPlistFromString(content...
Class
2
def is_writable(dir): """Determine whether a given directory is writable in a portable manner. Parameters ---------- dir : str A string represeting a path to a directory on the filesystem. Returns ------- res : bool True or False. """ if not os.path.isdir(dir): ...
Class
2
def test_reset_entrance_exam_student_attempts_deletall(self): """ Make sure no one can delete all students state on entrance exam. """ url = reverse('reset_student_attempts_for_entrance_exam', kwargs={'course_id': unicode(self.course.id)}) response = self.client.get(url...
Compound
4
def _checknetloc(netloc): if not netloc or netloc.isascii(): return # looking for characters like \u2100 that expand to 'a/c' # IDNA uses NFKC equivalence, so normalize for this check import unicodedata n = netloc.rpartition('@')[2] # ignore anything to the left of '@' n = n.replace(':',...
Class
2
def list_users(): off = int(request.args.get("offset") or 0) limit = int(request.args.get("limit") or 10) search = request.args.get("search") sort = request.args.get("sort", "id") state = None if sort == "state": state = json.loads(request.args.get("state", "[]")) else: if so...
Base
1
def __init__(self, hs): super().__init__(hs) self.hs = hs self.is_mine_id = hs.is_mine_id self.http_client = hs.get_simple_http_client() self._presence_enabled = hs.config.use_presence # The number of ongoing syncs on this process, by user id. # Empty if _pr...
Base
1
def check_prereg_key_and_redirect( request: HttpRequest, confirmation_key: str, full_name: Optional[str] = REQ(default=None)
Base
1
def test_spinal_case(): assert utils.spinal_case("keep_alive") == "keep-alive"
Base
1
def parse(source, filename='<unknown>', mode='exec'): """ Parse the source into an AST node. Equivalent to compile(source, filename, mode, PyCF_ONLY_AST). """ return compile(source, filename, mode, PyCF_ONLY_AST)
Base
1
def stmt(self, stmt, msg=None): mod = ast.Module([stmt]) self.mod(mod, msg)
Base
1
def __init__(self): self.reqparse = reqparse.RequestParser() super(AuthenticatedService, self).__init__() self.auth_dict = dict() if current_user.is_authenticated(): roles_marshal = [] for role in current_user.roles: roles_marshal.append(marsha...
Base
1
def close_or_open(request, pk, close=True): # todo: moderators should be able to close it poll = get_object_or_404( CommentPoll, pk=pk, comment__user=request.user ) if close: close_at = timezone.now() else: close_at = None (CommentPoll.objects .filt...
Base
1
def testSpoofedHeadersDropped(self): data = b"""\ GET /foobar HTTP/8.4 x-auth_user: bob content-length: 7 Hello. """ self.feed(data) self.assertTrue(self.parser.completed) self.assertEqual(self.parser.headers, {"CONTENT_LENGTH": "7",})
Base
1
def _get_insert_token(token): """Returns either a whitespace or the line breaks from token.""" # See issue484 why line breaks should be preserved. m = re.search(r'((\r\n|\r|\n)+) *$', token.value) if m is not None: return sql.Token(T.Whitespace.New...
Class
2
def show_book(book_id): entries = calibre_db.get_book_read_archived(book_id, config.config_read_column, allow_show_archived=True) if entries: read_book = entries[1] archived_book = entries[2] entry = entries[0] entry.read_status = read_book == ub.ReadBook.STATUS_FINISHED ...
Base
1
def _load_from(self, data: bytes) -> None: if data.strip() == b'': data = XMP_EMPTY # on some platforms lxml chokes on empty documents def basic_parser(xml): return parse(BytesIO(xml)) def strip_illegal_bytes_parser(xml): return parse(BytesIO(re_xml_ill...
Base
1
def edit_all_cc_data(book_id, book, to_save): cc = calibre_db.session.query(db.Custom_Columns).filter(db.Custom_Columns.datatype.notin_(db.cc_exceptions)).all() return edit_cc_data(book_id, book, to_save, cc)
Base
1
def test_parse_header_11_expect_continue(self): data = b"GET /foobar HTTP/1.1\nexpect: 100-continue" self.parser.parse_header(data) self.assertEqual(self.parser.expect_continue, True)
Base
1
def auth_ldap_server(self): return self.appbuilder.get_app.config["AUTH_LDAP_SERVER"]
Class
2
def testPeek(self): with ops.Graph().as_default() as G: with ops.device('/cpu:0'): x = array_ops.placeholder(dtypes.int32, name='x') pi = array_ops.placeholder(dtypes.int64) gi = array_ops.placeholder(dtypes.int64) p = array_ops.placeholder(dtypes.int32, name='p') with ...
Base
1
def set_bookmark(book_id, book_format): bookmark_key = request.form["bookmark"] ub.session.query(ub.Bookmark).filter(and_(ub.Bookmark.user_id == int(current_user.id), ub.Bookmark.book_id == book_id, ub.Bookmark.format ==...
Base
1
def _iterate_over_text( tree: "etree.Element", *tags_to_ignore: Union[str, "etree.Comment"]
Class
2
def model_from_config(config, custom_objects=None): """Instantiates a Keras model from its config. Usage: ``` # for a Functional API model tf.keras.Model().from_config(model.get_config()) # for a Sequential model tf.keras.Sequential().from_config(model.get_config()) ``` Args: config: Configu...
Base
1
def require_post_params(*args, **kwargs): """ Checks for required parameters or renders a 400 error. (decorator with arguments) Functions like 'require_query_params', but checks for POST parameters rather than GET parameters. """ required_params = [] required_params += [(arg, None) for ...
Compound
4
def group_title(value: str) -> str: value = re.sub(r"([A-Z]{2,})([A-Z][a-z]|[ -_]|$)", lambda m: m.group(1).title() + m.group(2), value.strip()) value = re.sub(r"(^|[ _-])([A-Z])", lambda m: m.group(1) + m.group(2).lower(), value) return value
Base
1
def __init__(self, text, book): self.text = text self.book = book
Base
1
def main(req: func.HttpRequest) -> func.HttpResponse: response = ok( Info( resource_group=get_base_resource_group(), region=get_base_region(), subscription=get_subscription(), versions=versions(), instance_id=get_instance_id(), insights...
Class
2
def _glob_matches(glob: str, value: str, word_boundary: bool = False) -> bool: """Tests if value matches glob. Args: glob value: String to test against glob. word_boundary: Whether to match against word boundaries or entire string. Defaults to False. """ try: ...
Base
1
def testPartialIndexGets(self): with ops.Graph().as_default() as G: with ops.device('/cpu:0'): x = array_ops.placeholder(dtypes.float32) f = array_ops.placeholder(dtypes.float32) v = array_ops.placeholder(dtypes.float32) pi = array_ops.placeholder(dtypes.int64) pei = ...
Base
1
def extension_element_from_string(xml_string): element_tree = ElementTree.fromstring(xml_string) return _extension_element_from_element_tree(element_tree)
Base
1
def to_html(self, data, options=None): """ Reserved for future usage. The desire is to provide HTML output of a resource, making an API available to a browser. This is on the TODO list but not currently implemented. """ options = options or {} ...
Class
2
def test_keepalive_http10_explicit(self): # If header Connection: Keep-Alive is explicitly sent, # we want to keept the connection open, we also need to return # the corresponding header data = "Keep me alive" s = tobytes( "GET / HTTP/1.0\n" "Connectio...
Base
1
def test_filelike_longcl_http11(self): to_send = "GET /filelike_longcl HTTP/1.1\n\n" to_send = tobytes(to_send) self.connect() for t in range(0, 2): self.sock.send(to_send) fp = self.sock.makefile("rb", 0) line, headers, response_body = read_http...
Base
1
def rename_all_authors(first_author, renamed_author, calibre_path="", localbook=None, gdrive=False): # Create new_author_dir from parameter or from database # Create new title_dir from database and add id if first_author: new_authordir = get_valid_filename(first_author, chars=96) for r in re...
Base
1
def extract_messages(obj_list): """ Extract "messages" from a list of exceptions or other objects. For ValidationErrors, `messages` are flattened into the output. For Exceptions, `args[0]` is added into the output. For other objects, `force_text` is called. :param obj_list: List of exceptions ...
Base
1
def make_homeserver(self, reactor, clock): hs = self.setup_test_homeserver("server", http_client=None) self.store = hs.get_datastore() return hs
Base
1
def update(request, pk): comment = Comment.objects.for_update_or_404(pk, request.user) form = CommentForm(data=post_data(request), instance=comment) if is_post(request) and form.is_valid(): pre_comment_update(comment=Comment.objects.get(pk=comment.pk)) comment = form.save() post_comm...
Base
1
def test_without_crlf(self): data = "Echo\nthis\r\nplease" s = tobytes( "GET / HTTP/1.0\n" "Connection: close\n" "Content-Length: %d\n" "\n" "%s" % (len(data), data) ) self.connect() self.sock.send(s) fp = se...
Base
1
def test_started_typing_remote_send(self): self.room_members = [U_APPLE, U_ONION] self.get_success( self.handler.started_typing( target_user=U_APPLE, requester=create_requester(U_APPLE), room_id=ROOM_ID, timeout=20000, ...
Base
1
def test_reset_student_attempts_single(self): """ Test reset single student attempts. """ url = reverse('reset_student_attempts', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.get(url, { 'problem_to_reset': self.problem_urlname, '...
Compound
4
def test_request_body_too_large_with_wrong_cl_http10(self): body = "a" * self.toobig to_send = "GET / HTTP/1.0\n" "Content-Length: 5\n\n" to_send += body to_send = tobytes(to_send) self.connect() self.sock.send(to_send) fp = self.sock.makefile("rb") # ...
Base
1
def test_before_start_response_http_11_close(self): to_send = tobytes( "GET /before_start_response HTTP/1.1\n" "Connection: close\n\n" ) self.connect() self.sock.send(to_send) fp = self.sock.makefile("rb", 0) line, headers, response_body = read_http(fp) ...
Base
1
def testInputPreProcessFormats(self): input_str = 'input1=/path/file.txt[ab3];input2=file2' input_expr_str = 'input3=np.zeros([2,2]);input4=[4,5]' input_dict = saved_model_cli.preprocess_inputs_arg_string(input_str) input_expr_dict = saved_model_cli.preprocess_input_exprs_arg_string( input_exp...
Base
1
def get_info(path: str, root: pathlib.Path) -> typing.Tuple[ pathlib.Path, dict]:
Base
1
def is_safe_url(url, host=None): """ Return ``True`` if the url is a safe redirection (i.e. it doesn't point to a different host). Always returns ``False`` on an empty url. """ if not url: return False netloc = urllib_parse.urlparse(url)[1] return not netloc or netloc == host
Base
1
def build_key(self, filename, entry, metadata): """ generates a new key according the the specification """ type = self.key_specs[entry.get('name')]['type'] bits = self.key_specs[entry.get('name')]['bits'] if type == 'rsa': cmd = "openssl genrsa %s " % bit...
Class
2
def __init__( self, cache, safe=safename
Class
2
def _handle_carbon_received(self, msg): self.xmpp.event('carbon_received', msg)
Class
2
def feed_booksindex(): shift = 0 off = int(request.args.get("offset") or 0) entries = calibre_db.session.query(func.upper(func.substr(db.Books.sort, 1, 1)).label('id'))\ .filter(calibre_db.common_filters()).group_by(func.upper(func.substr(db.Books.sort, 1, 1))).all() elements = [] if off ==...
Base
1
def _create_database(self, last_upgrade_to_run): """ Make sure that the database is created and sets the file permissions. This should be done before storing any sensitive data in it. """ # Create the tables in the database conn = self._connect() try: ...
Base
1
def main(req: func.HttpRequest) -> func.HttpResponse: response = ok( Info( resource_group=get_base_resource_group(), region=get_base_region(), subscription=get_subscription(), versions=versions(), instance_id=get_instance_id(), insights...
Class
2
def _get_element_ptr_tuplelike(parent, key): typ = parent.typ assert isinstance(typ, TupleLike) if isinstance(typ, StructType): assert isinstance(key, str) subtype = typ.members[key] attrs = list(typ.tuple_keys()) index = attrs.index(key) annotation = key else: ...
Class
2
def parse_soap_enveloped_saml_thingy(text, expected_tags): """Parses a SOAP enveloped SAML thing and returns the thing as a string. :param text: The SOAP object as XML string :param expected_tags: What the tag of the SAML thingy is expected to be. :return: SAML thingy as a string """ envelo...
Base
1
def test_can_read_token_from_query_parameters(self): """Tests that Sydent correct extracts an auth token from query parameters""" self.sydent.run() request, _ = make_request( self.sydent.reactor, "GET", "/_matrix/identity/v2/hash_details?access_token=" + self.test_to...
Base
1
def contains(field: Term, value: str) -> Criterion: return field.like(f"%{value}%")
Base
1
def dataReceived(self, data: bytes) -> None: self.stream.write(data) self.length += len(data) if self.max_size is not None and self.length >= self.max_size: self.deferred.errback( SynapseError( 502, "Requested file is too la...
Class
2
def test_datetime_parsing(value, result): if result == errors.DateTimeError: with pytest.raises(errors.DateTimeError): parse_datetime(value) else: assert parse_datetime(value) == result
Base
1
def test_basic_two_credentials(): # Test Basic Authentication with multiple sets of credentials http = httplib2.Http() password1 = tests.gen_password() password2 = tests.gen_password() allowed = [("joe", password1)] # exploit shared mutable list handler = tests.http_reflect_with_auth( a...
Class
2
def test_login_get_non_idempotent(self): login_code = LoginCode.objects.create(user=self.user, code='foobar', next='/private/') response = self.client.get('/accounts/login/code/', { 'code': login_code.code, }) self.assertEqual(response.status_code, 302) self.ass...
Base
1
def test_urlsplit_normalization(self): # Certain characters should never occur in the netloc, # including under normalization. # Ensure that ALL of them are detected and cause an error illegal_chars = '/:#?@' hex_chars = {'{:04X}'.format(ord(c)) for c in illegal_chars} ...
Class
2
def formatType(self): format_type = self.type.lower() if format_type == 'amazon': return u"Amazon" elif format_type.startswith("amazon_"): return u"Amazon.{0}".format(format_type[7:]) elif format_type == "isbn": return u"ISBN" elif format_t...
Base
1
def _w(self, content): self.output.append(format_data(content, format_money_values=True))
Base
1
def test_change_to_invalid_due_date(self): url = reverse('change_due_date', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.get(url, { 'student': self.user1.username, 'url': self.week1.location.to_deprecated_string(), 'due_datet...
Compound
4
def __init__( self, credentials, host, request_uri, headers, response, content, http
Class
2
def test_basic(): # Test Basic Authentication http = httplib2.Http() password = tests.gen_password() handler = tests.http_reflect_with_auth( allow_scheme="basic", allow_credentials=(("joe", password),) ) with tests.server_request(handler, request_count=3) as uri: response, conten...
Class
2
def test_received_headers_finished_expect_continue_true_sent_true(self): inst, sock, map = self._makeOneWithMap() inst.server = DummyServer() preq = DummyParser() inst.request = preq preq.expect_continue = True preq.headers_finished = True preq.completed = Fal...
Base
1
def glob_to_regex(glob): """Converts a glob to a compiled regex object. The regex is anchored at the beginning and end of the string. Args: glob (str) Returns: re.RegexObject """ res = "" for c in glob: if c == "*": res = res + ".*" elif c == "?...
Base
1
def parse_line(s): s = s.rstrip() r = re.sub(REG_LINE_GPERF, '', s) if r != s: return r r = re.sub(REG_HASH_FUNC, 'hash(OnigCodePoint codes[])', s) if r != s: return r r = re.sub(REG_STR_AT, 'onig_codes_byte_at(codes, \\1)', s) if r != s: return r r = re.sub(REG_UNFOLD_KEY, 'unicode_unf...
Base
1
def move(request, topic_id): topic = get_object_or_404(Topic, pk=topic_id) form = CommentMoveForm(topic=topic, data=request.POST) if form.is_valid(): comments = form.save() for comment in comments: comment_posted(comment=comment, mentions=None) topic.decrease_commen...
Base
1
def get_recipe_from_file(self, file): recipe_html = file.getvalue().decode("utf-8") recipe_json, recipe_tree, html_data, images = get_recipe_from_source(recipe_html, 'CookBookApp', self.request) recipe = Recipe.objects.create( name=recipe_json['name'].strip(), creat...
Base
1
def test_received_headers_finished_expect_continue_true(self): inst, sock, map = self._makeOneWithMap() inst.server = DummyServer() preq = DummyParser() inst.request = preq preq.expect_continue = True preq.headers_finished = True preq.completed = False ...
Base
1
def read_config(self, config, **kwargs): consent_config = config.get("user_consent") self.terms_template = self.read_templates(["terms.html"], autoescape=True)[0] if consent_config is None: return self.user_consent_version = str(consent_config["version"]) self.us...
Class
2
def edit_book_series_index(series_index, book): # Add default series_index to book modif_date = False series_index = series_index or '1' if not series_index.replace('.', '', 1).isdigit(): flash(_("%(seriesindex)s is not a valid number, skipping", seriesindex=series_index), category="warning") ...
Base
1
def request( self, uri, method="GET", body=None, headers=None, redirections=DEFAULT_MAX_REDIRECTS, connection_type=None,
Class
2
def validate_and_sanitize_search_inputs(fn, instance, args, kwargs): kwargs.update(dict(zip(fn.__code__.co_varnames, args))) sanitize_searchfield(kwargs['searchfield']) kwargs['start'] = cint(kwargs['start']) kwargs['page_len'] = cint(kwargs['page_len']) if kwargs['doctype'] and not frappe.db.exists('DocType', kw...
Base
1
def adv_search_extension(q, include_extension_inputs, exclude_extension_inputs): for extension in include_extension_inputs: q = q.filter(db.Books.data.any(db.Data.format == extension)) for extension in exclude_extension_inputs: q = q.filter(not_(db.Books.data.any(db.Data.format == extension))) ...
Base
1
def opds_download_link(book_id, book_format): # I gave up with this: With enabled ldap login, the user doesn't get logged in, therefore it's always guest # workaround, loading the user from the request and checking it's download rights here # in case of anonymous browsing user is None user = load_user_f...
Base
1
async def ignore(self, ctx, command: str.lower): """ Ignore or unignore the specified action. The bot will no longer respond to these actions. """ try: custom = await self.config.guild(ctx.guild).get_raw("custom", command) except KeyError: ...
Base
1
def parse(source, filename='<unknown>', mode='exec'): """ Parse the source into an AST node. Equivalent to compile(source, filename, mode, PyCF_ONLY_AST). """ return compile(source, filename, mode, PyCF_ONLY_AST)
Base
1
def __init__(self, sourceName: str): self.sourceName = sourceName self.type = "file" self.content = None
Base
1
def feed_author(book_id): off = request.args.get("offset") or 0 entries, __, pagination = calibre_db.fill_indexpage((int(off) / (int(config.config_books_per_page)) + 1), 0, db.Books, db.Books.authors....
Base
1
def test_roundtrip_file(self): f = open(self.filename, 'wb') self.x.tofile(f) f.close() # NB. doesn't work with flush+seek, due to use of C stdio f = open(self.filename, 'rb') y = np.fromfile(f, dtype=self.dtype) f.close() assert_array_equal(y, self.x....
Class
2
def publisher_list(): if current_user.get_view_property('publisher', 'dir') == 'desc': order = db.Publishers.name.desc() order_no = 0 else: order = db.Publishers.name.asc() order_no = 1 if current_user.check_visibility(constants.SIDEBAR_PUBLISHER): entries = calibre_d...
Base
1