code
stringlengths
12
2.05k
label_name
stringclasses
5 values
label
int64
0
4
def test_http11_listlentwo(self): body = string.ascii_letters to_send = "GET /list_lentwo HTTP/1.1\n" "Content-Length: %s\n\n" % len(body) to_send += body to_send = tobytes(to_send) self.connect() self.sock.send(to_send) fp = self.sock.makefile("rb") l...
Base
1
def test_rescore_entrance_exam_all_student_and_single(self): """ Test re-scoring with both all students and single student parameters. """ url = reverse('rescore_entrance_exam', kwargs={'course_id': unicode(self.course.id)}) response = self.client.get(url, { 'unique_student_ident...
Compound
4
def write_data_table(self, report, report_data, has_totals=True): self.data.append([c["title"] for c in report.schema]) for datum in report_data: datum = report.read_datum(datum) self.data.append([format_data(data, format_iso_dates=True) for data in datum]) if has_to...
Base
1
def GET(self, path, queries=()): return self._request('GET', path, queries)
Base
1
def test_chunking_request_with_content(self): control_line = b"20;\r\n" # 20 hex = 32 dec s = b"This string has 32 characters.\r\n" expected = s * 12 header = tobytes("GET / HTTP/1.1\n" "Transfer-Encoding: chunked\n\n") self.connect() self.sock.send(header) f...
Base
1
def decorator(func): # pylint: disable=missing-docstring def wrapped(*args, **kwargs): # pylint: disable=missing-docstring request = args[0] error_response_data = { 'error': 'Missing required query parameter(s)', 'parameters': [], 'i...
Compound
4
def feed_ratingindex(): off = request.args.get("offset") or 0 entries = calibre_db.session.query(db.Ratings, func.count('books_ratings_link.book').label('count'), (db.Ratings.rating / 2).label('name')) \ .join(db.books_ratings_link)\ .join(db.Books)\ .filte...
Base
1
def _lookup(self, name, *args, **kwargs): instance = self._lookup_loader.get(name.lower(), loader=self._loader, templar=self) if instance is not None: wantlist = kwargs.pop('wantlist', False) from ansible.utils.listify import listify_lookup_plugin_terms loop_ter...
Class
2
def save_cover_from_url(url, book_path): try: if not cli.allow_localhost: # 127.0.x.x, localhost, [::1], [::ffff:7f00:1] ip = socket.getaddrinfo(urlparse(url).hostname, 0)[0][4][0] if ip.startswith("127.") or ip.startswith('::ffff:7f') or ip == "::1" or ip == "0.0.0.0" or...
Base
1
def test_auth_plugin_prompt_password_in_session(self, httpbin): self.start_session(httpbin) session_path = self.config_dir / 'test-session.json' class Plugin(AuthPlugin): auth_type = 'test-prompted' def get_auth(self, username=None, password=None): b...
Class
2
def test_post_only(self): """ Verify that we can't call the view when we aren't using POST. """ self.client.login(username=self.staff_user.username, password='test') response = self.call_add_users_to_cohorts('', method='GET') self.assertEqual(response.status_code, 405...
Compound
4
def relative(self, relativePath) -> FileInputSource: return FileInputSource(os.path.join(self.directory(), relativePath))
Base
1
def analyze(self, avc): import commands if avc.has_any_access_in(['execmod']): # MATCH if (commands.getstatusoutput("eu-readelf -d %s | fgrep -q TEXTREL" % avc.tpath)[0] == 1): return self.report(("unsafe")) mcon = selinux.matchpathcon(avc.tpath.s...
Class
2
def create_book_on_upload(modif_date, meta): title = meta.title authr = meta.author sort_authors, input_authors, db_author, renamed_authors = prepare_authors_on_upload(title, authr) title_dir = helper.get_valid_filename(title, chars=96) author_dir = helper.get_valid_filename(db_author.name, chars=9...
Base
1
def read_fixed_bytes(self, num_bytes: int) -> bytes: """Reads a fixed number of bytes from the underlying bytestream. Args: num_bytes The number of bytes to read. Returns: The read bytes. Raises: EOFError: Fewer than ``num_bytes`...
Base
1
def test_replay_banner_metadata(self, fmod): """ Test adding metadata in replay banner (both framed and non-frame) """ resp = self.get('/test/20140103030321{0}/http://example.com/?example=1', fmod) assert '<div>Custom Banner Here!</div>' in resp.text assert '"some":"value"' i...
Base
1
def test_file_position_after_fromfile(self): # gh-4118 sizes = [io.DEFAULT_BUFFER_SIZE//8, io.DEFAULT_BUFFER_SIZE, io.DEFAULT_BUFFER_SIZE*8] for size in sizes: f = open(self.filename, 'wb') f.seek(size-1) f.write(b'\0') ...
Base
1
def test_build_attr(self): assert set(ClearableFileInput().build_attrs({}).keys()) == { "class", "data-url", "data-fields-x-amz-algorithm", "data-fields-x-amz-date", "data-fields-x-amz-signature", "data-fields-x-amz-credential", ...
Base
1
def file(path): path = secure_filename(path) if app.interface.encrypt and isinstance(app.interface.examples, str) and path.startswith(app.interface.examples): with open(os.path.join(app.cwd, path), "rb") as encrypted_file: encrypted_data = encrypted_file.read() file_data = encryptor....
Base
1
def test_request_body_too_large_with_no_cl_http11(self): body = "a" * self.toobig to_send = "GET / HTTP/1.1\n\n" to_send += body to_send = tobytes(to_send) self.connect() self.sock.send(to_send) fp = self.sock.makefile("rb") # server trusts the content...
Base
1
def test_get_students_features_cohorted(self, is_cohorted): """ Test that get_students_features includes cohort info when the course is cohorted, and does not when the course is not cohorted. """ url = reverse('get_students_features', kwargs={'course_id': unicode(self.course....
Compound
4
def command(self): res = self._gnupg().list_secret_keys() return self._success("Searched for secret keys", res)
Class
2
def make_homeserver(self, reactor, clock): self.fetches = [] async def get_file(destination, path, output_stream, args=None, max_size=None): """ Returns tuple[int,dict,str,int] of file length, response headers, absolute URI, and response code. """ ...
Base
1
def _keyify(key): return _key_pattern.sub(' ', key.lower())
Base
1
def mysql_insensitive_exact(field: Field, value: str) -> Criterion: return functions.Upper(functions.Cast(field, SqlTypes.CHAR)).eq(functions.Upper(f"{value}"))
Base
1
def test_file_position_after_fromfile(self): # gh-4118 sizes = [io.DEFAULT_BUFFER_SIZE//8, io.DEFAULT_BUFFER_SIZE, io.DEFAULT_BUFFER_SIZE*8] for size in sizes: f = open(self.filename, 'wb') f.seek(size-1) f.write(b'\0') ...
Class
2
def create_code_for_user(cls, user, next=None): if not user.is_active: return None code = cls.generate_code() login_code = LoginCode(user=user, code=code) if next is not None: login_code.next = next login_code.save() return login_code
Base
1
def render_archived_books(page, sort_param): order = sort_param[0] or [] archived_books = ( ub.session.query(ub.ArchivedBook) .filter(ub.ArchivedBook.user_id == int(current_user.id)) .filter(ub.ArchivedBook.is_archived == True) .all() ) archived_book_ids = [archived_book....
Base
1
def auth_role_admin(self): return self.appbuilder.get_app.config["AUTH_ROLE_ADMIN"]
Class
2
def adv_search_serie(q, include_series_inputs, exclude_series_inputs): for serie in include_series_inputs: q = q.filter(db.Books.series.any(db.Series.id == serie)) for serie in exclude_series_inputs: q = q.filter(not_(db.Books.series.any(db.Series.id == serie))) return q
Base
1
def test_login_inactive_user(self): self.user.is_active = False self.user.save() login_code = LoginCode.objects.create(user=self.user, code='foobar') response = self.client.post('/accounts-rest/login/code/', { 'code': login_code.code, }) self.assertEqua...
Base
1
def generate_code(cls): hash_algorithm = getattr(settings, 'NOPASSWORD_HASH_ALGORITHM', 'sha256') m = getattr(hashlib, hash_algorithm)() m.update(getattr(settings, 'SECRET_KEY', None).encode('utf-8')) m.update(os.urandom(16)) if getattr(settings, 'NOPASSWORD_NUMERIC_CODES', F...
Base
1
def testValuesInVariable(self): indices = constant_op.constant([[1]], dtype=dtypes.int64) values = variables.Variable([1], trainable=False, dtype=dtypes.float32) shape = constant_op.constant([1], dtype=dtypes.int64) sp_input = sparse_tensor.SparseTensor(indices, values, shape) sp_output = sparse_...
Base
1
def emit(self, s, depth, reflow=True): # XXX reflow long lines? if reflow: lines = reflow_lines(s, depth) else: lines = [s] for line in lines: line = (" " * TABSIZE * depth) + line + "\n" self.file.write(line)
Base
1
def test_get_student_progress_url_from_uname(self): """ Test that progress_url is in the successful response. """ url = reverse('get_student_progress_url', kwargs={'course_id': self.course.id.to_deprecated_string()}) url += "?unique_student_identifier={}".format( quote(self.stude...
Compound
4
def test_digest_next_nonce_nc(): # Test that if the server sets nextnonce that we reset # the nonce count back to 1 http = httplib2.Http() password = tests.gen_password() grenew_nonce = [None] handler = tests.http_reflect_with_auth( allow_scheme="digest", allow_credentials=(("joe...
Class
2
def needs_clamp(t, encoding): if encoding not in (Encoding.ABI, Encoding.JSON_ABI): return False if isinstance(t, (ByteArrayLike, DArrayType)): if encoding == Encoding.JSON_ABI: # don't have bytestring size bound from json, don't clamp return False return True ...
Base
1
def tearDown(self): if os.path.isfile(self.filename): os.unlink(self.filename)
Base
1
def testInputParserBoth(self): x0 = np.array([[1], [2]]) input_path = os.path.join(test.get_temp_dir(), 'input.npz') np.savez(input_path, a=x0) x1 = np.ones([2, 10]) input_str = 'x0=' + input_path + '[a]' input_expr_str = 'x1=np.ones([2,10])' feed_dict = saved_model_cli.load_inputs_from_in...
Base
1
def CreateID(self): """Create a packet ID. All RADIUS requests have a ID which is used to identify a request. This is used to detect retries and replay attacks. This function returns a suitable random number that can be used as ID. :return: ID number :rtype: integer ...
Class
2
def test_render_idn(self): w = widgets.AdminURLFieldWidget() self.assertHTMLEqual( conditional_escape(w.render('test', 'http://example-äüö.com')), '<p class="url">Currently:<a href="http://xn--example--7za4pnc.com">http://example-äüö.com</a><br />Change:<input class="vURLFiel...
Base
1
def _slices_from_text(self, text): last_break = 0 for match in self._lang_vars.period_context_re().finditer(text): context = match.group() + match.group("after_tok") if self.text_contains_sentbreak(context): yield slice(last_break, match.end()) ...
Class
2
def remove_dir(self,d): import distutils.dir_util distutils.dir_util.remove_tree(d)
Class
2
async def on_send_leave_request( self, origin: str, content: JsonDict, room_id: str
Class
2
def get_markdown(text): if not text: return "" pattern = fr'([\[\s\S\]]*?)\(([\s\S]*?):([\[\s\S\]]*?)\)' # Regex check if re.match(pattern, text): # get get value of group regex scheme = re.search(pattern, text, re.IGNORECASE).group(2) # scheme check if scheme in...
Base
1
def _updateCache(request_headers, response_headers, content, cache, cachekey): if cachekey: cc = _parse_cache_control(request_headers) cc_response = _parse_cache_control(response_headers) if "no-store" in cc or "no-store" in cc_response: cache.delete(cachekey) else: ...
Class
2
def test_underscore_traversal(self): t = self.folder.t t.write('<p tal:define="p context/__class__" />') with self.assertRaises(NotFound): t() t.write('<p tal:define="p nocall: random/_itertools/repeat"/>') with self.assertRaises(NotFound): t() ...
Base
1
def test_received_error_from_parser(self): from waitress.utilities import BadRequest data = b"""\ GET /foobar HTTP/1.1 Transfer-Encoding: chunked X-Foo: 1 garbage """ # header result = self.parser.received(data) # body result = self.parser.received(data[result:]) ...
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 test_change_response_class_to_json_binary(): mw = _get_mw() # We set magic_response to False, because it's not a kind of data we would # expect from splash: we just return binary data. # If we set magic_response to True, the middleware will fail, # but this is ok because magic_response presumes ...
Class
2
def CreateAuthenticator(): """Create a packet autenticator. All RADIUS packets contain a sixteen byte authenticator which is used to authenticate replies from the RADIUS server and in the password hiding algorithm. This function returns a suitable random string that can be used as an...
Class
2
def delete_auth_token(user_id): # Invalidate any prevously generated Kobo Auth token for this user. ub.session.query(ub.RemoteAuthToken).filter(ub.RemoteAuthToken.user_id == user_id)\ .filter(ub.RemoteAuthToken.token_type==1).delete() return ub.session_commit()
Pillar
3
def HEAD(self, path): return self._request('HEAD', path)
Base
1
def format_runtime(runtime): retVal = "" if runtime.days: retVal = format_unit(runtime.days, 'duration-day', length="long", locale=get_locale()) + ', ' mins, seconds = divmod(runtime.seconds, 60) hours, minutes = divmod(mins, 60) # ToDo: locale.number_symbols._data['timeSeparator'] -> locali...
Base
1
def malt_regex_tagger(): from nltk.tag import RegexpTagger _tagger = RegexpTagger( [ (r"\.$", "."), (r"\,$", ","), (r"\?$", "?"), # fullstop, comma, Qmark (r"\($", "("), (r"\)$", ")"), # round brackets (r"\[$", "["), ...
Base
1
def load_module(name): if os.path.exists(name) and os.path.splitext(name)[1] == '.py': sys.path.insert(0, os.path.dirname(os.path.abspath(name))) try: m = os.path.splitext(os.path.basename(name))[0] module = importlib.import_module(m) finally: sys.path.pop...
Class
2
def check_read_formats(entry): EXTENSIONS_READER = {'TXT', 'PDF', 'EPUB', 'CBZ', 'CBT', 'CBR', 'DJVU'} bookformats = list() if len(entry.data): for ele in iter(entry.data): if ele.format.upper() in EXTENSIONS_READER: bookformats.append(ele.format.lower()) return bookf...
Base
1
def convert_bookformat(book_id): # check to see if we have form fields to work with - if not send user back book_format_from = request.form.get('book_format_from', None) book_format_to = request.form.get('book_format_to', None) if (book_format_from is None) or (book_format_to is None): flash(_...
Base
1
def edit_single_cc_data(book_id, book, column_id, to_save): cc = (calibre_db.session.query(db.Custom_Columns) .filter(db.Custom_Columns.datatype.notin_(db.cc_exceptions)) .filter(db.Custom_Columns.id == column_id) .all()) return edit_cc_data(book_id, book, to_save, cc)
Base
1
void AveragePool(const float* input_data, const Dims<4>& input_dims, int stride, int pad_width, int pad_height, int filter_width, int filter_height, float* output_data, const Dims<4>& output_dims) { AveragePool<Ac>(input_data, input_dims, stride, stride, pad_width, p...
Base
1
def get(self, location, connection=None): location = location.store_location if not connection: connection = self.get_connection(location) try: resp_headers, resp_body = connection.get_object( container=location.container, obj=location.obj, ...
Class
2
def home_get_dat(): d = db.sentences_stats('get_data') n = db.sentences_stats('all_networks') ('clean_online') rows = db.sentences_stats('get_clicks') c = rows[0][0] rows = db.sentences_stats('get_sessions') s = rows[0][0] rows = db.sentences_stats('get_online') o = rows[0][0] ...
Base
1
def test_invalid_identitifer(self): m = ast.Module([ast.Expr(ast.Name(42, ast.Load()))]) ast.fix_missing_locations(m) with self.assertRaises(TypeError) as cm: compile(m, "<test>", "exec") self.assertIn("identifier must be of type str", str(cm.exception))
Base
1
def test_manage_pools(self) -> None: user1 = uuid4() user2 = uuid4() # by default, any can modify self.assertIsNone( check_can_manage_pools_impl( InstanceConfig(allow_pool_management=True), UserInfo() ) ) # with oid, but no ad...
Class
2
async def on_context_state_request( self, origin: str, room_id: str, event_id: str
Class
2
def test_received_bad_host_header(self): from waitress.utilities import BadRequest data = b"""\ HTTP/1.0 GET /foobar Host: foo """ result = self.parser.received(data) self.assertEqual(result, 33) self.assertTrue(self.parser.completed) self.assertEqual(self.parser....
Base
1
def __init__(self, sydent): self.sydent = sydent # The default endpoint factory in Twisted 14.0.0 (which we require) uses the # BrowserLikePolicyForHTTPS context factory which will do regular cert validation # 'like a browser' self.agent = Agent( self.sydent.react...
Base
1
def get(self, key): """ Gets the object specified by key. It will also unpickle the object before returning if it is pickled in memcache. :param key: key :returns: value of the key in memcache """ key = md5hash(key) value = None for (server, ...
Base
1
def _get_index_absolute_path(index): return os.path.join(INDEXDIR, index)
Base
1
def to_plist(self, data, options=None): """ Given some Python data, produces binary plist output. """ options = options or {} if biplist is None: raise ImproperlyConfigured("Usage of the plist aspects requires biplist.") return biplist.wr...
Class
2
def read_templates( self, filenames: List[str], custom_template_directory: Optional[str] = None, autoescape: bool = False,
Base
1
def test_parse_header_bad_content_length(self): data = b"GET /foobar HTTP/8.4\r\ncontent-length: abc\r\n" self.parser.parse_header(data) self.assertEqual(self.parser.body_rcv, None)
Base
1
def _on_ssl_errors(self): self._has_ssl_errors = True
Class
2
async def apiui_command_help(request, user): template = env.get_template('apiui_command_help.html') if len(request.query_args) != 0: data = urllib.parse.unquote(request.query_args[0][1]) print(data) else: data = "" if use_ssl: content = template.render(links=await respect...
Base
1
def edit_book_languages(languages, book, upload=False, invalid=None): input_languages = languages.split(',') unknown_languages = [] if not upload: input_l = isoLanguages.get_language_codes(get_locale(), input_languages, unknown_languages) else: input_l = isoLanguages.get_valid_language_c...
Base
1
def test_logout_post(self): login_code = LoginCode.objects.create(user=self.user, code='foobar') self.client.login(username=self.user.username, code=login_code.code) response = self.client.post('/accounts/logout/?next=/accounts/login/') self.assertEqual(response.status_code, 302) ...
Base
1
def delete_access(request, pk): topic_private = TopicPrivate.objects.for_delete_or_404(pk, request.user) if request.method == 'POST': topic_private.delete() if request.user.pk == topic_private.user_id: return redirect(reverse("spirit:topic:private:index")) return redirect(...
Base
1
def test_magic_response_http_error(): mw = _get_mw() req = SplashRequest('http://example.com/foo') req = mw.process_request(req, None) resp_data = { "info": { "error": "http404", "message": "Lua error: [string \"function main(splash)\r...\"]:3: http404", "lin...
Class
2
def __init__(self, pidfile=None): if not pidfile: self.pidfile = "/tmp/%s.pid" % self.__class__.__name__.lower() else: self.pidfile = pidfile
Base
1
def read_http(fp): # pragma: no cover try: response_line = fp.readline() except socket.error as exc: fp.close() # errno 104 is ENOTRECOVERABLE, In WinSock 10054 is ECONNRESET if get_errno(exc) in (errno.ECONNABORTED, errno.ECONNRESET, 104, 10054): raise ConnectionClo...
Base
1
def delete_auth_token(user_id): # Invalidate any prevously generated Kobo Auth token for this user. ub.session.query(ub.RemoteAuthToken).filter(ub.RemoteAuthToken.user_id == user_id)\ .filter(ub.RemoteAuthToken.token_type==1).delete() return ub.session_commit()
Base
1
def is_gae_instance(): server_software = os.environ.get('SERVER_SOFTWARE', '') if (server_software.startswith('Google App Engine/') or server_software.startswith('Development/') or server_software.startswith('testutil/')): return True return False
Class
2
def parse_html_description(tree: "etree.Element") -> Optional[str]: """ Calculate a text description based on an HTML document. Grabs any text nodes which are inside the <body/> tag, unless they are within an HTML5 semantic markup tag (<header/>, <nav/>, <aside/>, <footer/>), or if they are within ...
Class
2
def _get_obj_absolute_path(obj_path): return os.path.join(DATAROOT, obj_path)
Base
1
def test_no_content_length(self): # wtf happens when there's no content-length to_send = tobytes( "GET /no_content_length HTTP/1.0\n" "Connection: Keep-Alive\n" "Content-Length: 0\n" "\n" ) self.connect() self.sock.send(to_send)...
Base
1
def test_challenge(self): rc, root, folder, object = self._makeTree() response = FauxCookieResponse() testURL = 'http://test' request = FauxRequest(RESPONSE=response, URL=testURL, ACTUAL_URL=testURL) root.REQUEST = request helper = self....
Base
1
def feed_authorindex(): shift = 0 off = int(request.args.get("offset") or 0) entries = calibre_db.session.query(func.upper(func.substr(db.Authors.sort, 1, 1)).label('id'))\ .join(db.books_authors_link).join(db.Books).filter(calibre_db.common_filters())\ .group_by(func.upper(func.substr(db.Au...
Base
1
async def on_GET(self, origin, content, query, context, event_id): return await self.handler.on_event_auth(origin, context, event_id)
Class
2
def fixed_fetch( url, payload=None, method="GET", headers={}, allow_truncated=False, follow_redirects=True, deadline=None,
Class
2
def feed_authorindex(): shift = 0 off = int(request.args.get("offset") or 0) entries = calibre_db.session.query(func.upper(func.substr(db.Authors.sort, 1, 1)).label('id'))\ .join(db.books_authors_link).join(db.Books).filter(calibre_db.common_filters())\ .group_by(func.upper(func.substr(db.Au...
Base
1
def modify_identifiers(input_identifiers, db_identifiers, db_session): """Modify Identifiers to match input information. input_identifiers is a list of read-to-persist Identifiers objects. db_identifiers is a list of already persisted list of Identifiers objects.""" changed = False error = Fal...
Base
1
def runserverobj(method, docs=None, dt=None, dn=None, arg=None, args=None): frappe.desk.form.run_method.runserverobj(method, docs=docs, dt=dt, dn=dn, arg=arg, args=args)
Base
1
def test_uses_existing_file_and_ignores_xdg(self): with WindowsSafeTempDir() as d: default_db_file_location = os.path.join(self.home, '.b2_account_info') open(default_db_file_location, 'a').close() account_info = self._make_sqlite_account_info( env={ ...
Base
1
def test_list_course_role_members_beta(self): url = reverse('list_course_role_members', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.get(url, { 'rolename': 'beta', }) self.assertEqual(response.status_code, 200) # check respo...
Compound
4
def test_confirmation_expired(self) -> None: email = self.nonreg_email("alice") realm = get_realm("zulip") inviter = self.example_user("iago") prereg_user = PreregistrationUser.objects.create( email=email, referred_by=inviter, realm=realm ) date_sent = tim...
Base
1
def request(self, method, request_uri, headers, content): """Modify the request headers to add the appropriate Authorization header.""" headers["authorization"] = ( "Basic " + base64.b64encode("%s:%s" % self.credentials).strip() )
Class
2
def get_json(self, uri): """Make a GET request to an endpoint returning JSON and parse result :param uri: The URI to make a GET request to. :type uri: unicode :return: A deferred containing JSON parsed into a Python object. :rtype: twisted.internet.defer.Deferred[dict[any, ...
Base
1
def __getattr__(_self, attr): if attr == "nameResolver": return nameResolver else: return getattr(real_reactor, attr)
Base
1
def test_level_as_none(self): body = [ast.ImportFrom(module='time', names=[ast.alias(name='sleep')], level=None, lineno=0, col_offset=0)] mod = ast.Module(body) code = compile(mod, 'test', 'exec') ...
Base
1
def _wsse_username_token(cnonce, iso_now, password): return base64.b64encode( _sha(("%s%s%s" % (cnonce, iso_now, password)).encode("utf-8")).digest() ).strip().decode("utf-8")
Class
2