code
stringlengths
12
2.05k
label_name
stringclasses
5 values
label
int64
0
4
def test_template_render_with_noautoescape(self): """ Test if the autoescape value is getting passed to urlize_quoted_links filter. """ template = Template("{% load rest_framework %}" "{% autoescape off %}{{ content|urlize_quoted_links }}" ...
Base
1
def new_user(): content = ub.User() languages = calibre_db.speaking_language() translations = [LC('en')] + babel.list_translations() kobo_support = feature_support['kobo'] and config.config_kobo_sync if request.method == "POST": to_save = request.form.to_dict() _handle_new_user(to_sa...
Base
1
async def on_GET(self, origin, content, query, context, user_id): content = await self.handler.on_make_leave_request(origin, context, user_id) return 200, content
Class
2
def test_bind_invalid_entry(topology_st): """Test the failing bind does not return information about the entry :id: 5cd9b083-eea6-426b-84ca-83c26fc49a6f :customerscenario: True :setup: Standalone instance :steps: 1: bind as non existing entry 2: check that bind info does not report 'No s...
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 list_entrance_exam_instructor_tasks(request, course_id): # pylint: disable=invalid-name """ List entrance exam related instructor tasks. Takes either of the following query parameters - unique_student_identifier is an email or username - all_students is a boolean """ course_id ...
Compound
4
def setUp(self): shape = (2, 4, 3) rand = np.random.random self.x = rand(shape) + rand(shape).astype(np.complex)*1j self.x[0,:, 1] = [nan, inf, -inf, nan] self.dtype = self.x.dtype self.filename = tempfile.mktemp()
Base
1
def delete_book_gdrive(book, book_format): error = None if book_format: name = '' for entry in book.data: if entry.format.upper() == book_format: name = entry.name + '.' + book_format gFile = gd.getFileFromEbooksFolder(book.path, name) else: gFile ...
Base
1
def verify_password(plain_password, user_password): if plain_password == user_password: LOG.debug("password true") return True return False
Class
2
def __init__(self, expire_on_commit=True): """ Initialize a new CalibreDB session """ self.session = None if self._init: self.initSession(expire_on_commit) self.instances.add(self)
Base
1
def test_list_email_with_no_successes(self, task_history_request): task_info = FakeContentTask(0, 0, 10, 'expected') email = FakeEmail(0) email_info = FakeEmailInfo(email, 0, 10) task_history_request.return_value = [task_info] url = reverse('list_email_content', kwargs={'cour...
Compound
4
def process_statistics(self, metadata, _): args = [metadata.hostname, '-p', metadata.profile, '-g', ':'.join([g for g in metadata.groups])] for notifier in os.listdir(self.data): if ((notifier[-1] == '~') or (notifier[:2] == '.#') or (notif...
Base
1
def get_response(self, url, auth=None, http_method="get", **kwargs): if is_private_address(url) and settings.ENFORCE_PRIVATE_ADDRESS_BLOCK: raise Exception("Can't query private addresses.") # Get authentication values if not given if auth is None: auth = self.get_aut...
Base
1
def parse_soap_enveloped_saml(text, body_class, header_class=None): """Parses a SOAP enveloped SAML thing and returns header parts and body :param text: The SOAP object as XML :return: header parts and body as saml.samlbase instances """ envelope = ElementTree.fromstring(text) assert envelope.t...
Base
1
def test_credits_view_rst(self): response = self.get_credits("rst") self.assertEqual(response.status_code, 200) self.assertEqual( response.content.decode(), "\n\n* Czech\n\n * Weblate Test <weblate@example.org> (1)\n\n", )
Base
1
def fetch_file(self, in_path, out_path): ''' fetch a file from chroot to local ''' if not in_path.startswith(os.path.sep): in_path = os.path.join(os.path.sep, in_path) normpath = os.path.normpath(in_path) in_path = os.path.join(self.chroot, normpath[1:]) vvv("FE...
Base
1
def from_xml(self, content): """ Given some XML data, returns a Python dictionary of the decoded data. """ if lxml is None: raise ImproperlyConfigured("Usage of the XML aspects requires lxml.") return self.from_etree(parse_xml(StringIO(content)).getroot()...
Class
2
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 is_private_address(url): hostname = urlparse(url).hostname ip_address = socket.gethostbyname(hostname) return ipaddress.ip_address(text_type(ip_address)).is_private
Base
1
def auth_ldap_use_tls(self): return self.appbuilder.get_app.config["AUTH_LDAP_USE_TLS"]
Class
2
def _hkey(s): return s.title().replace('_', '-')
Base
1
def render_entries(self, entries: Entries) -> Generator[str, None, None]: """Return entries in Beancount format. Only renders :class:`.Balance` and :class:`.Transaction`. Args: entries: A list of entries. Yields: The entries rendered in Beancount format. ...
Base
1
def setUp(self): self.reactor = ThreadedMemoryReactorClock() self.hs_clock = Clock(self.reactor) self.homeserver = setup_test_homeserver( self.addCleanup, http_client=None, clock=self.hs_clock, reactor=self.reactor )
Base
1
def test_modify_config(self) -> None: user1 = uuid4() user2 = uuid4() # no admins set self.assertTrue(can_modify_config_impl(InstanceConfig(), UserInfo())) # with oid, but no admin self.assertTrue( can_modify_config_impl(InstanceConfig(), UserInfo(object...
Class
2
def test___post_init__(self): from openapi_python_client.parser.properties import StringProperty sp = StringProperty(name="test", required=True, default="A Default Value",) assert sp.default == '"A Default Value"'
Base
1
def get_field_options(self, field): options = {} options['label'] = field.label options['help_text'] = field.help_text options['required'] = field.required options['initial'] = field.default_value return options
Base
1
def __init__(self, path: Union[str, Path]): super().__init__(path=Path(path)) self['headers'] = {} self['cookies'] = {} self['auth'] = { 'type': None, 'username': None, 'password': None }
Class
2
def add_original_file(self, filename, original_filename, version): with open(filename, 'rb') as f: sample = base64.b64encode(f.read()).decode('utf-8') original_file = MISPObject('original-imported-file') original_file.add_attribute(**{'type': 'attachment', 'value': original_filen...
Base
1
def test_received_headers_too_large(self): from waitress.utilities import RequestHeaderFieldsTooLarge self.parser.adj.max_request_header_size = 2 data = b"""\ GET /foobar HTTP/8.4 X-Foo: 1 """ result = self.parser.received(data) self.assertEqual(result, 30) self.asse...
Base
1
def _write_headers(self): # Self refers to the Generator object. for h, v in msg.items(): print("%s:" % h, end=" ", file=self._fp) if isinstance(v, header.Header): print(v.encode(maxlinelen=self._maxheaderlen), file=self._fp) else: ...
Class
2
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 test_okp_ed25519_should_reject_non_string_key(self): algo = OKPAlgorithm() with pytest.raises(TypeError): algo.prepare_key(None) with open(key_path("testkey_ed25519")) as keyfile: algo.prepare_key(keyfile.read()) with open(key_path("testkey_ed25519.pub"...
Class
2
def run_custom_method(doctype, name, custom_method): """cmd=run_custom_method&doctype={doctype}&name={name}&custom_method={custom_method}""" doc = frappe.get_doc(doctype, name) if getattr(doc, custom_method, frappe._dict()).is_whitelisted: frappe.call(getattr(doc, custom_method), **frappe.local.form_dict) else: ...
Base
1
def run_query(self, query, user): query = parse_query(query) if not isinstance(query, dict): raise QueryParseError( "Query should be a YAML object describing the URL to query." ) if "url" not in query: raise QueryParseError("Query must in...
Base
1
def upload_cover(request, book): if 'btn-upload-cover' in request.files: requested_file = request.files['btn-upload-cover'] # check for empty request if requested_file.filename != '': if not current_user.role_upload(): abort(403) ret, message = helper....
Base
1
def test_filelike_shortcl_http11(self): to_send = "GET /filelike_shortcl 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_ht...
Base
1
def test_after_start_response_http10(self): to_send = "GET /after_start_response HTTP/1.0\n\n" to_send = tobytes(to_send) self.connect() self.sock.send(to_send) fp = self.sock.makefile("rb", 0) line, headers, response_body = read_http(fp) self.assertline(line,...
Base
1
def setup_logging(): """Configure the python logging appropriately for the tests. (Logs will end up in _trial_temp.) """ root_logger = logging.getLogger() log_format = ( "%(asctime)s - %(name)s - %(lineno)d - %(levelname)s" " - %(message)s" ) handler = ToTwistedHandler() ...
Class
2
def insensitive_starts_with(field: Term, value: str) -> Criterion: return Upper(field).like(Upper(f"{value}%"))
Base
1
def download_check_files(self, filelist): # only admins and allowed users may download if not cherrypy.session['admin']: uo = self.useroptions.forUser(self.getUserId()) if not uo.getOptionValue('media.may_download'): return 'not_permitted' # make sure ...
Base
1
def testRunCommandInvalidSignature(self, use_tfrt): self.parser = saved_model_cli.create_parser() base_path = test.test_src_dir_path(SAVED_MODEL_PATH) args = self.parser.parse_args([ 'run', '--dir', base_path, '--tag_set', 'serve', '--signature_def', 'INVALID_SIGNATURE', '--input_exprs', '...
Base
1
def test_bad_integer(self): # issue13436: Bad error message with invalid numeric values body = [ast.ImportFrom(module='time', names=[ast.alias(name='sleep')], level=None, lineno=None, col_offset=None)] ...
Base
1
def _auth_from_challenge(self, host, request_uri, headers, response, content): """A generator that creates Authorization objects that can be applied to requests. """ challenges = _parse_www_authenticate(response, "www-authenticate") for cred in self.credentials.iter(host):...
Class
2
async def on_GET(self, origin, _content, query, context, user_id): """ Args: origin (unicode): The authenticated server_name of the calling server _content (None): (GETs don't have bodies) query (dict[bytes, list[bytes]]): Query params from the request. ...
Class
2
def test_list_report_downloads(self): url = reverse('list_report_downloads', kwargs={'course_id': self.course.id.to_deprecated_string()}) with patch('instructor_task.models.LocalFSReportStore.links_for') as mock_links_for: mock_links_for.return_value = [ ('mock_file_name_...
Compound
4
def delete(request, pk, remove=True): comment = get_object_or_404(Comment, pk=pk) if is_post(request): (Comment.objects .filter(pk=pk) .update(is_removed=remove)) return redirect(request.GET.get('next', comment.get_absolute_url())) return render( request=request, ...
Base
1
def _parse_www_authenticate(headers, headername="www-authenticate"): """Returns a dictionary of dictionaries, one dict per auth_scheme.""" retval = {} if headername in headers: try: authenticate = headers[headername].strip() www_auth = ( USE_WWW_AUTH_STRIC...
Class
2
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 valid_id(opts, id_): ''' Returns if the passed id is valid ''' try: return bool(clean_path(opts['pki_dir'], id_)) and clean_id(id_) except (AttributeError, KeyError, TypeError) as e: return False
Base
1
def is_valid_hostname(string: str) -> bool: """Validate that a given string is a valid hostname or domain name, with an optional port number. For domain names, this only validates that the form is right (for instance, it doesn't check that the TLD is valid). If a port is specified, it has to be a v...
Class
2
def _get_obj_absolute_path(obj_path): return os.path.join(DATAROOT, obj_path)
Base
1
def test_certificates_features_against_status(self): """ Test certificates with status 'downloadable' should be in the response. """ url = reverse('get_issued_certificates', kwargs={'course_id': unicode(self.course.id)}) # firstly generating downloadable certificates with 'ho...
Compound
4
def json_dumps(value, indent=None): if isinstance(value, QuerySet): result = serialize('json', value, indent=indent) else: result = json.dumps(value, indent=indent, cls=DjbletsJSONEncoder) return mark_safe(result)
Base
1
def bm_to_item(self, bm): return bytearray(cPickle.dumps(bm, -1))
Base
1
def google_remote_app(): if "google" not in oauth.remote_apps: oauth.remote_app( "google", base_url="https://www.google.com/accounts/", authorize_url="https://accounts.google.com/o/oauth2/auth?prompt=select_account+consent", request_token_url=None, ...
Base
1
def change_due_date(request, course_id): """ Grants a due date extension to a student for 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, req...
Compound
4
def save(self): self.cleaned_data['code'].delete()
Base
1
def delete(request, pk): favorite = get_object_or_404(TopicFavorite, pk=pk, user=request.user) favorite.delete() return redirect(request.POST.get('next', favorite.topic.get_absolute_url()))
Base
1
def auth_user_registration_role(self): return self.appbuilder.get_app.config["AUTH_USER_REGISTRATION_ROLE"]
Class
2
def intermediate_dir(): """ Location in temp dir for storing .cpp and .o files during builds. """ python_name = "python%d%d_intermediate" % tuple(sys.version_info[:2]) path = os.path.join(tempfile.gettempdir(),"%s"%whoami(),python_name) if not os.path.exists(path): os.makedirs(path,...
Class
2
def test_received_nonsense_with_double_cr(self): data = b"""\ HTTP/1.0 GET /foobar """ result = self.parser.received(data) self.assertEqual(result, 22) self.assertTrue(self.parser.completed) self.assertEqual(self.parser.headers, {})
Base
1
def parse_json(raw_data): ''' this version for module return data only ''' orig_data = raw_data # ignore stuff like tcgetattr spewage or other warnings data = filter_leading_non_json_lines(raw_data) try: return json.loads(data) except: # not JSON, but try "Baby JSON" which all...
Class
2
def mysql_contains(field: Field, value: str) -> Criterion: return functions.Cast(field, SqlTypes.CHAR).like(f"%{value}%")
Base
1
def test_received(self): inst, sock, map = self._makeOneWithMap() inst.server = DummyServer() inst.received(b"GET / HTTP/1.1\n\n") self.assertEqual(inst.server.tasks, [inst]) self.assertTrue(inst.requests)
Base
1
def job_cancel(request, client_id, project_name, job_id): """ cancel a job :param request: request object :param client_id: client id :param project_name: project name :param job_id: job id :return: json of cancel """ if request.method == 'GET': client = Client.objects.get(id...
Base
1
def login(): from flask_login import current_user redirect_url = request.args.get("redirect", request.script_root + url_for("index")) permissions = sorted( filter( lambda x: x is not None and isinstance(x, OctoPrintPermission), map( lambda x: getattr(Permissi...
Base
1
def download_list(): if current_user.get_view_property('download', 'dir') == 'desc': order = ub.User.name.desc() order_no = 0 else: order = ub.User.name.asc() order_no = 1 if current_user.check_visibility(constants.SIDEBAR_DOWNLOAD) and current_user.role_admin(): entr...
Base
1
def feed_seriesindex(): shift = 0 off = int(request.args.get("offset") or 0) entries = calibre_db.session.query(func.upper(func.substr(db.Series.sort, 1, 1)).label('id'))\ .join(db.books_series_link).join(db.Books).filter(calibre_db.common_filters())\ .group_by(func.upper(func.substr(db.Seri...
Base
1
def handler(request): """Scheme handler for qute:// URLs. Args: request: QNetworkRequest to answer to. Return: A QNetworkReply. """ try: mimetype, data = qutescheme.data_for_url(request.url()) except qutescheme.NoHandlerFound: errorstr = "No handler found for {}...
Compound
4
def edit_user(user_id): content = ub.session.query(ub.User).filter(ub.User.id == int(user_id)).first() # type: ub.User if not content or (not config.config_anonbrowse and content.name == "Guest"): flash(_(u"User not found"), category="error") return redirect(url_for('admin.admin')) language...
Base
1
async def on_GET(self, origin, content, query, context): return await self.handler.on_context_state_request( origin, context, parse_string_from_args(query, "event_id", None, required=False), )
Class
2
def test_rescore_entrance_exam_single_student(self, act): """ Test re-scoring of entrance exam for single student. """ url = reverse('rescore_entrance_exam', kwargs={'course_id': unicode(self.course.id)}) response = self.client.get(url, { 'unique_student_identifier': self.student...
Compound
4
def profile(): languages = calibre_db.speaking_language() translations = babel.list_translations() + [LC('en')] kobo_support = feature_support['kobo'] and config.config_kobo_sync if feature_support['oauth'] and config.config_login_type == 2: oauth_status = get_oauth_status() local_oauth_...
Base
1
def make_homeserver(self, reactor, clock): presence_handler = Mock() presence_handler.set_state.return_value = defer.succeed(None) hs = self.setup_test_homeserver( "red", http_client=None, federation_client=Mock(), presence_handler=presence_h...
Base
1
async def start_verification(self, client_id, username): async with self.lock: await self.db.execute('SELECT code FROM scratchverifier_usage WHERE \ client_id=? AND username=?', (client_id, username)) row = await self.db.fetchone() if row is not None: await self.d...
Class
2
def __init__(self, bot): super().__init__() self.bot = bot self.config = Config.get_conf(self, identifier=2_113_674_295, force_registration=True) self.config.register_global(custom={}, tenorkey=None) self.config.register_guild(custom={}) self.try_after = None
Base
1
def handleMatch(m): s = m.group(1) if s.startswith('0x'): i = int(s, 16) elif s.startswith('0') and '.' not in s: try: i = int(s, 8) except ValueError: i = int(s) else: ...
Base
1
def Ghostscript(tile, size, fp, scale=1): """Render an image using Ghostscript""" # Unpack decoder tile decoder, tile, offset, data = tile[0] length, bbox = data #Hack to support hi-res rendering scale = int(scale) or 1 orig_size = size orig_bbox = bbox size = (size[0] * scale, siz...
Base
1
def test_get_students_features_teams(self, has_teams): """ Test that get_students_features includes team info when the course is has teams enabled, and does not when the course does not have teams enabled """ if has_teams: self.course = CourseFactory.create(teams_...
Compound
4
def test_notfilelike_nocl_http10(self): to_send = "GET /notfilelike_nocl HTTP/1.0\n\n" to_send = tobytes(to_send) self.connect() self.sock.send(to_send) fp = self.sock.makefile("rb", 0) line, headers, response_body = read_http(fp) self.assertline(line, "200"...
Base
1
def get_files_from_storage(paths): """Return S3 file where the name does not include the path.""" for path in paths: path = pathlib.PurePosixPath(path) try: location = storage.aws_location except AttributeError: location = storage.l...
Base
1
def test_received_control_line_finished_all_chunks_not_received(self): buf = DummyBuffer() inst = self._makeOne(buf) result = inst.received(b"a;discard\n") self.assertEqual(inst.control_line, b"") self.assertEqual(inst.chunk_remainder, 10) self.assertEqual(inst.all_ch...
Base
1
def test_date_and_server(self): to_send = "GET / HTTP/1.0\n" "Content-Length: 0\n\n" to_send = tobytes(to_send) self.connect() self.sock.send(to_send) fp = self.sock.makefile("rb", 0) line, headers, echo = self._read_echo(fp) self.assertline(line, "200", "OK",...
Base
1
def encode_non_url_reserved_characters(url): # safe url reserved characters: https://datatracker.ietf.org/doc/html/rfc3986#section-2.2 return urlquote(url, safe=":/?#[]@!$&'()*+,;=")
Base
1
async def check_credentials(username: str, password: str) -> bool: return (username, password) == credentials
Base
1
def _bind_write_headers(msg): def _write_headers(self): # Self refers to the Generator object. for h, v in msg.items(): print("%s:" % h, end=" ", file=self._fp) if isinstance(v, header.Header): print(v.encode(maxlinelen=self._maxheaderlen), file=self._fp) ...
Class
2
def subscribe_for_tags(request): """process subscription of users by tags""" #todo - use special separator to split tags tag_names = request.REQUEST.get('tags','').strip().split() pure_tag_names, wildcards = forms.clean_marked_tagnames(tag_names) if request.user.is_authenticated(): if reques...
Base
1
def test_before_start_response_http_11(self): to_send = "GET /before_start_response HTTP/1.1\n\n" to_send = tobytes(to_send) self.connect() self.sock.send(to_send) fp = self.sock.makefile("rb", 0) line, headers, response_body = read_http(fp) self.assertline(li...
Base
1
def test_credits_one(self, expected_count=1): self.add_change() data = generate_credits( None, timezone.now() - timedelta(days=1), timezone.now() + timedelta(days=1), translation__component=self.component, ) self.assertEqual( ...
Base
1
def class_instances_from_soap_enveloped_saml_thingies(text, modules): """Parses a SOAP enveloped header and body SAML thing and returns the thing as a dictionary class instance. :param text: The SOAP object as XML :param modules: modules representing xsd schemas :return: The body and headers as cla...
Base
1
def pascal_case(value: str) -> str: return stringcase.pascalcase(_sanitize(value))
Base
1
def test_digest_object(): credentials = ("joe", "password") host = None request_uri = "/test/digest/" headers = {} response = { "www-authenticate": 'Digest realm="myrealm", nonce="KBAA=35", algorithm=MD5, qop="auth"' } content = b"" d = httplib2.DigestAuthentication( cre...
Class
2
def keccak256_helper(expr, ir_arg, context): sub = ir_arg # TODO get rid of useless variable _check_byteslike(sub.typ, expr) # Can hash literals # TODO this is dead code. if isinstance(sub, bytes): return IRnode.from_list(bytes_to_int(keccak256(sub)), typ=BaseType("bytes32")) # Can ha...
Pillar
3
def test_short_body(self): # check to see if server closes connection when body is too short # for cl header to_send = tobytes( "GET /short_body HTTP/1.0\n" "Connection: Keep-Alive\n" "Content-Length: 0\n" "\n" ) self.connect() ...
Base
1
def test_rescore_problem_single(self, act): """ Test rescoring of a single student. """ url = reverse('rescore_problem', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.get(url, { 'problem_to_reset': self.problem_urlname, 'unique_st...
Compound
4
def starts_with(field: Term, value: str) -> Criterion: return field.like(f"{value}%")
Base
1
def __init__(self, hs): super().__init__(hs) self.http_client = SimpleHttpClient(hs) # We create a blacklisting instance of SimpleHttpClient for contacting identity # servers specified by clients self.blacklisting_http_client = SimpleHttpClient( hs, ip_blacklist=...
Base
1
def test_patch_bot_role(self) -> None: self.login("desdemona") email = "default-bot@zulip.com" user_profile = self.get_bot_user(email) do_change_user_role(user_profile, UserProfile.ROLE_MEMBER, acting_user=user_profile) req = dict(role=UserProfile.ROLE_GUEST) resu...
Class
2
def make_homeserver(self, reactor, clock): self.http_client = Mock() hs = self.setup_test_homeserver(http_client=self.http_client) return hs
Base
1
def feed_get_cover(book_id): return get_book_cover(book_id)
Base
1