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") line, headers, response_body = read_http(fp) self.assertline(line, "200", "OK", "HTTP/1.1") expected = b"" for chunk in (body[0], body[1:]): expected += tobytes( "%s\r\n%s\r\n" % (str(hex(len(chunk))[2:].upper()), chunk) ) expected += b"0\r\n\r\n" self.assertEqual(response_body, expected) # connection is always closed at the end of a chunked response self.send_check_error(to_send) self.assertRaises(ConnectionClosed, read_http, fp)
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_identifier': self.student.email, 'all_students': True, }) self.assertEqual(response.status_code, 400)
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_totals: for datum in report.get_totals(report_data): datum = report.read_datum(datum) self.data.append([format_data(data) for data in datum])
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) fp = self.sock.makefile("rb", 0) for n in range(12): self.sock.send(control_line) self.sock.send(s) self.sock.send(b"0\r\n\r\n") line, headers, echo = self._read_echo(fp) self.assertline(line, "200", "OK", "HTTP/1.1") self.assertEqual(echo.body, expected) self.assertEqual(echo.content_length, str(len(expected))) self.assertFalse("transfer-encoding" in headers)
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': [], 'info': {}, } for (param, extra) in required_params: default = object() if request.GET.get(param, default) == default: error_response_data['parameters'].append(param) error_response_data['info'][param] = extra if len(error_response_data['parameters']) > 0: return JsonResponse(error_response_data, status=400) else: return func(*args, **kwargs) return wrapped
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)\ .filter(calibre_db.common_filters()) \ .group_by(text('books_ratings_link.rating'))\ .order_by(db.Ratings.rating).all() pagination = Pagination((int(off) / (int(config.config_books_per_page)) + 1), config.config_books_per_page, len(entries)) element = list() for entry in entries: element.append(FeedObject(entry[0].id, _("{} Stars").format(entry.name))) return render_xml_template('feed.xml', listelements=element, folder='opds.feed_ratings', pagination=pagination)
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_terms = listify_lookup_plugin_terms(terms=args, templar=self, loader=self._loader, fail_on_undefined=True, convert_bare=False) # safely catch run failures per #5059 try: ran = instance.run(loop_terms, variables=self._available_variables, **kwargs) except (AnsibleUndefinedVariable, UndefinedError) as e: raise AnsibleUndefinedVariable(e) except Exception as e: if self._fail_on_lookup_errors: raise AnsibleError("An unhandled exception occurred while running the lookup plugin '%s'. Error was a %s, " "original message: %s" % (name, type(e), e)) ran = None if ran: if wantlist: ran = wrap_var(ran) else: try: ran = UnsafeProxy(",".join(ran)) except TypeError: if isinstance(ran, list) and len(ran) == 1: ran = wrap_var(ran[0]) else: ran = wrap_var(ran) return ran else: raise AnsibleError("lookup plugin (%s) not found" % name)
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 ip == "::": log.error("Localhost was accessed for cover upload") return False, _("You are not allowed to access localhost for cover uploads") img = requests.get(url, timeout=(10, 200), allow_redirects=False) # ToDo: Error Handling img.raise_for_status() return save_cover(img, book_path) except (socket.gaierror, requests.exceptions.HTTPError, requests.exceptions.ConnectionError, requests.exceptions.Timeout) as ex: log.info(u'Cover Download Error %s', ex) return False, _("Error Downloading Cover") except MissingDelegateError as ex: log.info(u'File Format Error %s', ex) return False, _("Cover Format Error")
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): basic_auth_header = "Basic " + b64encode(self.raw_auth.encode()).strip().decode('latin1') return basic_auth(basic_auth_header) plugin_manager.register(Plugin) with mock.patch( 'httpie.cli.argtypes.AuthCredentials._getpass', new=lambda self, prompt: 'password' ): r1 = http( '--session', str(session_path), httpbin + '/basic-auth/user/password', '--auth-type', Plugin.auth_type, '--auth', 'user', ) r2 = http( '--session', str(session_path), httpbin + '/basic-auth/user/password', ) assert HTTP_OK in r1 assert HTTP_OK in r2 # additional test for issue: https://github.com/httpie/httpie/issues/1098 with open(session_path) as session_file: session_file_lines = ''.join(session_file.readlines()) assert "\"type\": \"test-prompted\"" in session_file_lines assert "\"raw_auth\": \"user:password\"" in session_file_lines plugin_manager.unregister(Plugin)
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.strip('"'), S_IFREG)[1] if mcon.split(":")[2] == "lib_t": return self.report() return None
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=96) # combine path and normalize path from windows systems path = os.path.join(author_dir, title_dir).replace('\\', '/') # Calibre adds books with utc as timezone db_book = db.Books(title, "", sort_authors, datetime.utcnow(), datetime(101, 1, 1), '1', datetime.utcnow(), path, meta.cover, db_author, [], "") modif_date |= modify_database_object(input_authors, db_book.authors, db.Authors, calibre_db.session, 'author') # Add series_index to book modif_date |= edit_book_series_index(meta.series_id, db_book) # add languages invalid=[] modif_date |= edit_book_languages(meta.languages, db_book, upload=True, invalid=invalid) if invalid: for l in invalid: flash(_(u"'%(langname)s' is not a valid language", langname=l), category="warning") # handle tags modif_date |= edit_book_tags(meta.tags, db_book) # handle publisher modif_date |= edit_book_publisher(meta.publisher, db_book) # handle series modif_date |= edit_book_series(meta.series, db_book) # Add file to book file_size = os.path.getsize(meta.file_path) db_data = db.Data(db_book, meta.extension.upper()[1:], file_size, title_dir) db_book.data.append(db_data) calibre_db.session.add(db_book) # flush content, get db_book.id available calibre_db.session.flush() return db_book, input_authors, title_dir, renamed_authors
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`` bytes remained in the underlying bytestream. """ read_bytes = self.read(num_bytes) if len(read_bytes) < num_bytes: raise EOFError(read_bytes) return read_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"' in resp.text
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') f.close() for mode in ['rb', 'r+b']: err_msg = "%d %s" % (size, mode) f = open(self.filename, mode) f.read(2) np.fromfile(f, dtype=np.float64, count=1) pos = f.tell() f.close() assert_equal(pos, 10, err_msg=err_msg) os.unlink(self.filename)
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", "data-fields-policy", "data-fields-key", } assert ClearableFileInput().build_attrs({})["class"] == "s3file" assert ( ClearableFileInput().build_attrs({"class": "my-class"})["class"] == "my-class s3file" )
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.decrypt( app.interface.encryption_key, encrypted_data) return send_file(io.BytesIO(file_data), attachment_filename=os.path.basename(path)) else: return send_file(os.path.join(app.cwd, path))
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-length header (assumed 0) line, headers, response_body = read_http(fp) self.assertline(line, "200", "OK", "HTTP/1.1") cl = int(headers["content-length"]) self.assertEqual(cl, len(response_body)) # server assumes pipelined requests due to http/1.1, and the first # request was assumed c-l 0 because it had no content-length header, # so entire body looks like the header of the subsequent request # second response is an error response line, headers, response_body = read_http(fp) self.assertline(line, "431", "Request Header Fields Too Large", "HTTP/1.0") cl = int(headers["content-length"]) self.assertEqual(cl, len(response_body)) # connection has been closed self.send_check_error(to_send) self.assertRaises(ConnectionClosed, read_http, fp)
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.id)}) set_course_cohort_settings(self.course.id, is_cohorted=is_cohorted) response = self.client.get(url, {}) res_json = json.loads(response.content) self.assertEqual('cohort' in res_json['feature_names'], is_cohorted)
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. """ def write_to(r): data, response = r output_stream.write(data) return response d = Deferred() d.addCallback(write_to) self.fetches.append((d, destination, path, args)) return await make_deferred_yieldable(d) client = Mock() client.get_file = get_file self.storage_path = self.mktemp() self.media_store_path = self.mktemp() os.mkdir(self.storage_path) os.mkdir(self.media_store_path) config = self.default_config() config["media_store_path"] = self.media_store_path config["thumbnail_requirements"] = {} config["max_image_pixels"] = 2000000 provider_config = { "module": "synapse.rest.media.v1.storage_provider.FileStorageProviderBackend", "store_local": True, "store_synchronous": False, "store_remote": True, "config": {"directory": self.storage_path}, } config["media_storage_providers"] = [provider_config] hs = self.setup_test_homeserver(config=config, http_client=client) return hs
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') f.close() for mode in ['rb', 'r+b']: err_msg = "%d %s" % (size, mode) f = open(self.filename, mode) f.read(2) np.fromfile(f, dtype=np.float64, count=1) pos = f.tell() f.close() assert_equal(pos, 10, err_msg=err_msg) os.unlink(self.filename)
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.book_id for archived_book in archived_books] archived_filter = db.Books.id.in_(archived_book_ids) entries, random, pagination = calibre_db.fill_indexpage_with_archived_books(page, db.Books, 0, archived_filter, order, True, False, 0) name = _(u'Archived Books') + ' (' + str(len(archived_book_ids)) + ')' pagename = "archived" return render_title_template('index.html', random=random, entries=entries, pagination=pagination, title=name, page=pagename, order=sort_param[1])
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.assertEqual(response.status_code, 400) self.assertEqual(response.json(), { 'code': ['Unable to log in with provided login code.'], })
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', False): hashed = str(int(m.hexdigest(), 16)) else: hashed = m.hexdigest() return hashed
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_ops.sparse_add(sp_input, sp_input) with test_util.force_cpu(): self.evaluate(variables.global_variables_initializer()) output = self.evaluate(sp_output) self.assertAllEqual(output.values, [2])
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.students[0].username.encode("utf-8")) ) response = self.client.get(url) self.assertEqual(response.status_code, 200) res_json = json.loads(response.content) self.assertIn('progress_url', res_json)
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", password),), out_renew_nonce=grenew_nonce, ) with tests.server_request(handler, request_count=5) as uri: http.add_credentials("joe", password) response1, _ = http.request(uri, "GET") info = httplib2._parse_www_authenticate(response1, "authentication-info") assert response1.status == 200 assert info.get("digest", {}).get("nc") == "00000001", info assert not info.get("digest", {}).get("nextnonce"), info response2, _ = http.request(uri, "GET") info2 = httplib2._parse_www_authenticate(response2, "authentication-info") assert info2.get("digest", {}).get("nc") == "00000002", info2 grenew_nonce[0]() response3, content = http.request(uri, "GET") info3 = httplib2._parse_www_authenticate(response3, "authentication-info") assert response3.status == 200 assert info3.get("digest", {}).get("nc") == "00000001", info3
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 if isinstance(t, BaseType) and t.typ not in ("int256", "uint256", "bytes32"): return True if isinstance(t, SArrayType): return needs_clamp(t.subtype, encoding) if isinstance(t, TupleLike): return any(needs_clamp(m, encoding) for m in t.tuple_members()) return False
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_input_arg_string( input_str, input_expr_str, '') self.assertTrue(np.all(feed_dict['x0'] == x0)) self.assertTrue(np.all(feed_dict['x1'] == x1))
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 """ return random.randrange(0, 256)
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="vURLField" name="test" type="url" value="http://example-äüö.com" /></p>' )
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()) if match.group("next_tok"): # next sentence starts after whitespace last_break = match.start("next_tok") else: # next sentence starts at following punctuation last_break = match.end() # The last sentence should not contain trailing whitespace. yield slice(last_break, len(text.rstrip()))
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 helpdesk_settings.ALLOWED_URL_SCHEMES: replacement = '\\1(\\2:\\3)' else: replacement = '\\1(\\3)' text = re.sub(pattern, replacement, text, flags=re.IGNORECASE) return mark_safe( markdown( text, extensions=[ EscapeHtml(), 'markdown.extensions.nl2br', 'markdown.extensions.fenced_code' ] ) )
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: info = email.message.Message() for key, value in response_headers.items(): if key not in ["status", "content-encoding", "transfer-encoding"]: info[key] = value # Add annotations to the cache to indicate what headers # are variant for this request. vary = response_headers.get("vary", None) if vary: vary_headers = vary.lower().replace(" ", "").split(",") for header in vary_headers: key = "-varied-%s" % header try: info[key] = request_headers[header] except KeyError: pass status = response_headers.status if status == 304: status = 200 status_header = "status: %d\r\n" % status try: header_str = info.as_string() except UnicodeEncodeError: setattr(info, "_write_headers", _bind_write_headers(info)) header_str = info.as_string() header_str = re.sub("\r(?!\n)|(?<!\r)\n", "\r\n", header_str) text = b"".join( [status_header.encode("utf-8"), header_str.encode("utf-8"), content] ) cache.set(cachekey, text)
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() t.write('<p tal:content="random/_itertools/repeat/foobar"/>') 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:]) self.assertEqual(result, 8) self.assertTrue(self.parser.completed) self.assertTrue(isinstance(self.parser.error, BadRequest))
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 we are expecting # a valid splash json response. req = SplashRequest('http://example.com/', magic_response=False) req = mw.process_request(req, None) resp = Response('http://mysplash.example.com/execute', headers={b'Content-Type': b'application/json'}, body=b'non-decodable data: \x98\x11\xe7\x17\x8f', ) resp2 = mw.process_response(req, resp, None) assert isinstance(resp2, Response) assert resp2.url == 'http://example.com/' assert resp2.headers == {b'Content-Type': [b'application/json']} assert resp2.body == b'non-decodable data: \x98\x11\xe7\x17\x8f'
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 authenticator. :return: valid packet authenticator :rtype: binary string """ data = [] for i in range(16): data.append(random.randrange(0, 256)) if six.PY3: return bytes(data) else: return ''.join(chr(b) for b in data)
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'] -> localize time separator ? if hours: retVal += '{:d}:{:02d}:{:02d}s'.format(hours, minutes, seconds) elif minutes: retVal += '{:2d}:{:02d}s'.format(minutes, seconds) else: retVal += '{:2d}s'.format(seconds) return retVal
Base
1
def malt_regex_tagger(): from nltk.tag import RegexpTagger _tagger = RegexpTagger( [ (r"\.$", "."), (r"\,$", ","), (r"\?$", "?"), # fullstop, comma, Qmark (r"\($", "("), (r"\)$", ")"), # round brackets (r"\[$", "["), (r"\]$", "]"), # square brackets (r"^-?[0-9]+(.[0-9]+)?$", "CD"), # cardinal numbers (r"(The|the|A|a|An|an)$", "DT"), # articles (r"(He|he|She|she|It|it|I|me|Me|You|you)$", "PRP"), # pronouns (r"(His|his|Her|her|Its|its)$", "PRP$"), # possessive (r"(my|Your|your|Yours|yours)$", "PRP$"), # possessive (r"(on|On|in|In|at|At|since|Since)$", "IN"), # time prepopsitions (r"(for|For|ago|Ago|before|Before)$", "IN"), # time prepopsitions (r"(till|Till|until|Until)$", "IN"), # time prepopsitions (r"(by|By|beside|Beside)$", "IN"), # space prepopsitions (r"(under|Under|below|Below)$", "IN"), # space prepopsitions (r"(over|Over|above|Above)$", "IN"), # space prepopsitions (r"(across|Across|through|Through)$", "IN"), # space prepopsitions (r"(into|Into|towards|Towards)$", "IN"), # space prepopsitions (r"(onto|Onto|from|From)$", "IN"), # space prepopsitions (r".*able$", "JJ"), # adjectives (r".*ness$", "NN"), # nouns formed from adjectives (r".*ly$", "RB"), # adverbs (r".*s$", "NNS"), # plural nouns (r".*ing$", "VBG"), # gerunds (r".*ed$", "VBD"), # past tense verbs (r".*", "NN"), # nouns (default) ] ) return _tagger.tag
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(0) return module return importlib.import_module('dbusmock.templates.' + name)
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 bookformats
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(_(u"Source or destination format for conversion missing"), category="error") return redirect(url_for('editbook.edit_book', book_id=book_id)) log.info('converting: book id: %s from: %s to: %s', book_id, book_format_from, book_format_to) rtn = helper.convert_book_format(book_id, config.config_calibre_dir, book_format_from.upper(), book_format_to.upper(), current_user.name) if rtn is None: flash(_(u"Book successfully queued for converting to %(book_format)s", book_format=book_format_to), category="success") else: flash(_(u"There was an error converting this book: %(res)s", res=rtn), category="error") return redirect(url_for('editbook.edit_book', book_id=book_id))
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, pad_height, filter_width, filter_height, output_data, output_dims); }
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, resp_chunk_size=self.CHUNKSIZE) except swiftclient.ClientException, e: if e.http_status == httplib.NOT_FOUND: uri = location.get_uri() raise exception.NotFound(_("Swift could not find image at " "uri %(uri)s") % locals()) else: raise class ResponseIndexable(glance.store.Indexable): def another(self): try: return self.wrapped.next() except StopIteration: return '' length = int(resp_headers.get('content-length', 0)) return (ResponseIndexable(resp_body, length), length)
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] return json.dumps({'status' : 'OK', 'd' : d, 'n' : n, 'c' : c, 's' : s, 'o' : o});
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 admin self.assertIsNone( check_can_manage_pools_impl( InstanceConfig(allow_pool_management=True), UserInfo(object_id=user1) ) ) # is admin self.assertIsNone( check_can_manage_pools_impl( InstanceConfig(allow_pool_management=False, admins=[user1]), UserInfo(object_id=user1), ) ) # no user oid set self.assertIsNotNone( check_can_manage_pools_impl( InstanceConfig(allow_pool_management=False, admins=[user1]), UserInfo() ) ) # not an admin self.assertIsNotNone( check_can_manage_pools_impl( InstanceConfig(allow_pool_management=False, admins=[user1]), UserInfo(object_id=user2), ) )
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.error.__class__, BadRequest)
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.reactor, connectTimeout=15, )
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, fp, sock) in self._get_conns(key): try: sock.sendall('get %s\r\n' % key) line = fp.readline().strip().split() while line[0].upper() != 'END': if line[0].upper() == 'VALUE' and line[1] == key: size = int(line[3]) value = fp.read(size) if int(line[2]) & PICKLE_FLAG: value = pickle.loads(value) fp.readline() line = fp.readline().strip().split() self._return_conn(server, fp, sock) return value except Exception, e: self._exception_occurred(server, e)
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.writePlistToString(self.to_simple(data, options))
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_pivot(links, request), name=user['username'], http="https", ws="wss", config=user['ui_config'], view_utc_time=user['view_utc_time'], agent=data) else: content = template.render(links=await respect_pivot(links, request), name=user['username'], http="http", ws="ws", config=user['ui_config'], view_utc_time=user['view_utc_time'], agent=data) return response.html(content)
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_codes(get_locale(), input_languages, unknown_languages) for l in unknown_languages: log.error("'%s' is not a valid language", l) if isinstance(invalid, list): invalid.append(l) else: raise ValueError(_(u"'%(langname)s' is not a valid language", langname=l)) # ToDo: Not working correct if upload and len(input_l) == 1: # If the language of the file is excluded from the users view, it's not imported, to allow the user to view # the book it's language is set to the filter language if input_l[0] != current_user.filter_language() and current_user.filter_language() != "all": input_l[0] = calibre_db.session.query(db.Languages). \ filter(db.Languages.lang_code == current_user.filter_language()).first().lang_code # Remove duplicates input_l = helper.uniq(input_l) return modify_database_object(input_l, book.languages, db.Languages, calibre_db.session, 'languages')
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) self.assertEqual(response['Location'], '/accounts/login/') self.assertTrue(response.wsgi_request.user.is_anonymous)
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(request.POST.get('next', topic_private.get_absolute_url())) return render( request=request, template_name='spirit/topic/private/delete.html', context={'topic_private': topic_private})
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", "line_number": 3, "type": "LUA_ERROR", "source": "[string \"function main(splash)\r...\"]" }, "description": "Error happened while executing Lua script", "error": 400, "type": "ScriptError" } resp = TextResponse("http://mysplash.example.com/execute", status=400, headers={b'Content-Type': b'application/json'}, body=json.dumps(resp_data).encode('utf8')) resp = mw.process_response(req, resp, None) assert resp.data == resp_data assert resp.status == 404 assert resp.splash_response_status == 400 assert resp.url == "http://example.com/foo"
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 ConnectionClosed raise if not response_line: raise ConnectionClosed header_lines = [] while True: line = fp.readline() if line in (b"\r\n", b"\n", b""): break else: header_lines.append(line) headers = dict() for x in header_lines: x = x.strip() if not x: continue key, value = x.split(b": ", 1) key = key.decode("iso-8859-1").lower() value = value.decode("iso-8859-1") assert key not in headers, "%s header duplicated" % key headers[key] = value if "content-length" in headers: num = int(headers["content-length"]) body = b"" left = num while left > 0: data = fp.read(left) if not data: break body += data left -= len(data) else: # read until EOF body = fp.read() return response_line, headers, body
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 a <script/>, <svg/> or <style/> tag, or if they are within a tag whose content is usually only shown to old browsers (<iframe/>, <video/>, <canvas/>, <picture/>). This is a very very very coarse approximation to a plain text render of the page. Args: tree: The parsed HTML document. Returns: The plain text description, or None if one cannot be generated. """ # We don't just use XPATH here as that is slow on some machines. from lxml import etree TAGS_TO_REMOVE = ( "header", "nav", "aside", "footer", "script", "noscript", "style", "svg", "iframe", "video", "canvas", "img", "picture", etree.Comment, ) # Split all the text nodes into paragraphs (by splitting on new # lines) text_nodes = ( re.sub(r"\s+", "\n", el).strip() for el in _iterate_over_text(tree.find("body"), *TAGS_TO_REMOVE) ) return summarize_paragraphs(text_nodes)
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) fp = self.sock.makefile("rb", 0) line = fp.readline() # status line line, headers, response_body = read_http(fp) content_length = headers.get("content-length") self.assertEqual(content_length, None) self.assertEqual(response_body, tobytes("abcdefghi")) # remote closed connection (despite keepalive header) self.send_check_error(to_send) self.assertRaises(ConnectionClosed, read_http, fp)
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._makeOne().__of__(root) helper.challenge(request, response) self.assertEqual(response.status, 302) self.assertEqual(len(response.headers), 3) self.assertTrue(response.headers['Location'].endswith(quote(testURL))) self.assertEqual(response.headers['Cache-Control'], 'no-cache') self.assertEqual(response.headers['Expires'], 'Sat, 01 Jan 2000 00:00:00 GMT')
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.Authors.sort, 1, 1))).all() elements = [] if off == 0: elements.append({'id': "00", 'name':_("All")}) shift = 1 for entry in entries[ off + shift - 1: int(off + int(config.config_books_per_page) - shift)]: elements.append({'id': entry.id, 'name': entry.id}) pagination = Pagination((int(off) / (int(config.config_books_per_page)) + 1), config.config_books_per_page, len(entries) + 1) return render_xml_template('feed.xml', letterelements=elements, folder='opds.feed_letter_author', pagination=pagination)
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.Authors.sort, 1, 1))).all() elements = [] if off == 0: elements.append({'id': "00", 'name':_("All")}) shift = 1 for entry in entries[ off + shift - 1: int(off + int(config.config_books_per_page) - shift)]: elements.append({'id': entry.id, 'name': entry.id}) pagination = Pagination((int(off) / (int(config.config_books_per_page)) + 1), config.config_books_per_page, len(entries) + 1) return render_xml_template('feed.xml', letterelements=elements, folder='opds.feed_letter_author', pagination=pagination)
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 = False input_dict = dict([(identifier.type.lower(), identifier) for identifier in input_identifiers]) if len(input_identifiers) != len(input_dict): error = True db_dict = dict([(identifier.type.lower(), identifier) for identifier in db_identifiers ]) # delete db identifiers not present in input or modify them with input val for identifier_type, identifier in db_dict.items(): if identifier_type not in input_dict.keys(): db_session.delete(identifier) changed = True else: input_identifier = input_dict[identifier_type] identifier.type = input_identifier.type identifier.val = input_identifier.val # add input identifiers not present in db for identifier_type, identifier in input_dict.items(): if identifier_type not in db_dict.keys(): db_session.add(identifier) changed = True return changed, error
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={ 'HOME': self.home, 'USERPROFILE': self.home, XDG_CONFIG_HOME_ENV_VAR: d, } ) actual_path = os.path.abspath(account_info.filename) assert default_db_file_location == actual_path assert not os.path.exists(os.path.join(d, 'b2'))
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 response content expected = { 'course_id': self.course.id.to_deprecated_string(), 'beta': [] } res_json = json.loads(response.content) self.assertEqual(res_json, expected)
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 = timezone_now() - datetime.timedelta(weeks=3) with patch("confirmation.models.timezone_now", return_value=date_sent): url = create_confirmation_link(prereg_user, Confirmation.USER_REGISTRATION) target_url = "/" + url.split("/", 3)[3] result = self.client_get(target_url) self.assertEqual(result.status_code, 404) self.assert_in_response( "Whoops. The confirmation link has expired or been deactivated.", result )
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, any]] """ logger.debug("HTTP GET %s", uri) response = yield self.agent.request( b"GET", uri.encode("utf8"), ) body = yield readBody(response) try: # json.loads doesn't allow bytes in Python 3.5 json_body = json.loads(body.decode("UTF-8")) except Exception as e: logger.exception("Error parsing JSON from %s", uri) raise defer.returnValue(json_body)
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') ns = {} exec(code, ns) self.assertIn('sleep', ns)
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