code
stringlengths
12
2.05k
label_name
stringclasses
5 values
label
int64
0
4
def create_access(request, topic_id): topic_private = TopicPrivate.objects.for_create_or_404(topic_id, request.user) form = TopicPrivateInviteForm( topic=topic_private.topic, data=post_data(request)) if form.is_valid(): form.save() notify_access(user=form.get_user(), topic_p...
Base
1
def test_get_ora2_responses_already_running(self): url = reverse('export_ora2_data', kwargs={'course_id': unicode(self.course.id)}) with patch('instructor_task.api.submit_export_ora2_data') as mock_submit_ora2_task: mock_submit_ora2_task.side_effect = AlreadyRunningError() r...
Compound
4
def generic_visit(self, node): if type(node) not in SAFE_NODES: #raise Exception("invalid expression (%s) type=%s" % (expr, type(node))) raise Exception("invalid expression (%s)" % expr) super(CleansingNodeVisitor, self).generic_visit(node)
Class
2
def test_keepalive_http11_connclose(self): # specifying Connection: close explicitly data = "Don't keep me alive" s = tobytes( "GET / HTTP/1.1\n" "Connection: close\n" "Content-Length: %d\n" "\n" "%s" % (len(data), data) ) ...
Base
1
def get_by_name(self, name, project): return ( Person.query.filter(Person.name == name) .filter(Project.id == project.id) .one() )
Class
2
def setup_db(cls, config_calibre_dir, app_db_path): cls.dispose() if not config_calibre_dir: cls.config.invalidate() return False dbpath = os.path.join(config_calibre_dir, "metadata.db") if not os.path.exists(dbpath): cls.config.invalidate() ...
Base
1
def test_get_imports(self, mocker): from openapi_python_client.parser.properties import DateTimeProperty name = mocker.MagicMock() mocker.patch("openapi_python_client.utils.snake_case") p = DateTimeProperty(name=name, required=True, default=None) assert p.get_imports(prefix=...
Base
1
def category_list(): if current_user.check_visibility(constants.SIDEBAR_CATEGORY): if current_user.get_view_property('category', 'dir') == 'desc': order = db.Tags.name.desc() order_no = 0 else: order = db.Tags.name.asc() order_no = 1 entries = ...
Base
1
def do_download_file(book, book_format, client, data, headers): if config.config_use_google_drive: #startTime = time.time() df = gd.getFileFromEbooksFolder(book.path, data.name + "." + book_format) #log.debug('%s', time.time() - startTime) if df: return gd.do_gdrive_downl...
Base
1
def download(url, location): """ Download files to the specified location. :param url: The file URL. :type url: str :param location: The absolute path to where the downloaded file is to be stored. :type location: str """ request = urllib2.urlopen(url) try: content = r...
Base
1
def test_double_linefeed(self): self.assertEqual(self._callFUT(b"\n\n"), 2)
Base
1
def auth_role_public(self): return self.appbuilder.get_app.config["AUTH_ROLE_PUBLIC"]
Class
2
def guest_only(view_func): # TODO: test! @wraps(view_func) def wrapper(request, *args, **kwargs): if request.user.is_authenticated: return redirect(request.GET.get('next', request.user.st.get_absolute_url())) return view_func(request, *args, **kwargs) return wrapper
Base
1
def render_POST(self, request): """ Register with the Identity Server """ send_cors(request) args = get_args(request, ('matrix_server_name', 'access_token')) result = yield self.client.get_json( "matrix://%s/_matrix/federation/v1/openid/userinfo?access_t...
Class
2
def test_basic_for_domain(): # Test Basic Authentication http = httplib2.Http() password = tests.gen_password() handler = tests.http_reflect_with_auth( allow_scheme="basic", allow_credentials=(("joe", password),) ) with tests.server_request(handler, request_count=4) as uri: respo...
Class
2
def test_coupon_redeem_count_in_ecommerce_section(self): """ Test that checks the redeem count in the instructor_dashboard coupon section """ # add the coupon code for the course coupon = Coupon( code='test_code', description='test_description', course_id=self.cou...
Compound
4
def test_conf_set_no_read(self): orig_parser = memcache.ConfigParser memcache.ConfigParser = ExcConfigParser exc = None try: app = memcache.MemcacheMiddleware( FakeApp(), {'memcache_servers': '1.2.3.4:5'}) except Exception, err: exc...
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 test_more_custom_templates(self): """ Test custom templates and metadata Template is relative to collection-specific dir Add custom metadata and test its presence in custom search page """ custom_search = os.path.join(self.root_dir, COLLECTIONS, 'test', ...
Base
1
def model_from_yaml(yaml_string, custom_objects=None): """Parses a yaml model configuration file and returns a model instance. Usage: >>> model = tf.keras.Sequential([ ... tf.keras.layers.Dense(5, input_shape=(3,)), ... tf.keras.layers.Softmax()]) >>> try: ... import yaml ... config = mode...
Base
1
def test_unicorn_render_kwarg(): token = Token( TokenType.TEXT, "unicorn 'tests.templatetags.test_unicorn_render.FakeComponentKwargs' test_kwarg='tested!'", ) unicorn_node = unicorn(None, token) context = {} actual = unicorn_node.render(context) assert "->tested!<-" in actual
Base
1
def open_soap_envelope(text): """ :param text: SOAP message :return: dictionary with two keys "body"/"header" """ try: envelope = ElementTree.fromstring(text) except Exception as exc: raise XmlParseError("%s" % exc) assert envelope.tag == '{%s}Envelope' % soapenv.NAMESPACE ...
Base
1
def set_multi(self, mapping, server_key, serialize=True, timeout=0): """ Sets multiple key/value pairs in memcache. :param mapping: dictonary of keys and values to be set in memcache :param servery_key: key to use in determining which server in the ring i...
Base
1
def _resolve_orders(orders): requester = get_user_or_app_from_context(info.context) if not requester.has_perm(OrderPermissions.MANAGE_ORDERS): orders = list( filter(lambda order: order.status != OrderStatus.DRAFT, orders) ) ...
Class
2
def _sqrt(x): if isinstance(x, complex) or x < 0: return cmath.sqrt(x) else: return math.sqrt(x)
Base
1
def initSession(self, expire_on_commit=True): self.session = self.session_factory() self.session.expire_on_commit = expire_on_commit self.update_title_sort(self.config)
Base
1
async def get_resolved_ref(self): if hasattr(self, 'resolved_ref'): return self.resolved_ref try: # Check if the reference is a valid SHA hash self.sha1_validate(self.unresolved_ref) except ValueError: # The ref is a head/tag and we resolve it...
Base
1
def test_entrance_exam_sttudent_delete_state(self): """ Test delete single student entrance exam state. """ url = reverse('reset_student_attempts_for_entrance_exam', kwargs={'course_id': unicode(self.course.id)}) response = self.client.get(url, { 'unique_stu...
Compound
4
def freeze(self, monkeypatch): """Freeze datetime and UUID.""" monkeypatch.setattr( "s3file.forms.S3FileInputMixin.upload_folder", os.path.join(storage.aws_location, "tmp"), )
Base
1
def test_is_valid_hostname(self): """Tests that the is_valid_hostname function accepts only valid hostnames (or domain names), with optional port number. """ self.assertTrue(is_valid_hostname("example.com")) self.assertTrue(is_valid_hostname("EXAMPLE.COM")) self.asse...
Class
2
def test_received_preq_completed_empty(self): inst, sock, map = self._makeOneWithMap() inst.server = DummyServer() preq = DummyParser() inst.request = preq preq.completed = True preq.empty = True inst.received(b"GET / HTTP/1.1\n\n") self.assertEqual(in...
Base
1
def require_query_params(*args, **kwargs): """ Checks for required paremters or renders a 400 error. (decorator with arguments) `args` is a *list of required GET parameter names. `kwargs` is a **dict of required GET parameter names to string explanations of the parameter """ require...
Compound
4
def _inject_file_into_fs(fs, path, contents): absolute_path = os.path.join(fs, path.lstrip('/')) parent_dir = os.path.dirname(absolute_path) utils.execute('mkdir', '-p', parent_dir, run_as_root=True) utils.execute('tee', absolute_path, process_input=contents, run_as_root=True)
Base
1
def _websocket_mask_python(mask, data): """Websocket masking function. `mask` is a `bytes` object of length 4; `data` is a `bytes` object of any length. Returns a `bytes` object of the same length as `data` with the mask applied as specified in section 5.3 of RFC 6455. This pure-python implementat...
Base
1
def render_GET(self, request): request.setHeader(b'content-type', to_bytes(self.content_type)) for name, value in self.extra_headers.items(): request.setHeader(to_bytes(name), to_bytes(value)) request.setResponseCode(self.status_code) return to_bytes(self.html)
Class
2
def show_book(book_id): entries = calibre_db.get_book_read_archived(book_id, config.config_read_column, allow_show_archived=True) if entries: read_book = entries[1] archived_book = entries[2] entry = entries[0] entry.read_status = read_book == ub.ReadBook.STATUS_FINISHED ...
Base
1
def __init__( self, proxy_type, proxy_host, proxy_port, proxy_rdns=True, proxy_user=None, proxy_pass=None, proxy_headers=None,
Class
2
def _remove_javascript_link(self, link): # links like "j a v a s c r i p t:" might be interpreted in IE new = _substitute_whitespace('', link) if _is_javascript_scheme(new): # FIXME: should this be None to delete? return '' return link
Base
1
def test_remote_cors(app): """Test endpoint that serves as a proxy to the actual remote track on the cloud""" cloud_track_url = "http://google.com" # GIVEN an initialized app # GIVEN a valid user and institute with app.test_client() as client: # GIVEN that the user could be logged in ...
Base
1
def test_in_generator(self): to_send = "GET /in_generator 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(line, "200", "OK", "HTTP/1.1...
Base
1
def test_get_problem_responses_invalid_location(self): """ Test whether get_problem_responses returns an appropriate status message when users submit an invalid problem location. """ url = reverse( 'get_problem_responses', kwargs={'course_id': unicode(...
Compound
4
def register_with_redemption_code(self, user, code): """ enroll user using a registration code """ redeem_url = reverse('register_code_redemption', args=[code]) self.client.login(username=user.username, password='test') response = self.client.get(redeem_url) s...
Compound
4
def test_list_email_content_error(self, task_history_request): """ Test handling of error retrieving email """ invalid_task = FakeContentTask(0, 0, 0, 'test') invalid_task.make_invalid_input() task_history_request.return_value = [invalid_task] url = reverse('list_email_conten...
Compound
4
def _writeHeaders(self, transport, TEorCL): hosts = self.headers.getRawHeaders(b'host', ()) if len(hosts) != 1: raise BadHeaders(u"Exactly one Host header required") # In the future, having the protocol version be a parameter to this # method would probably be good. It ...
Class
2
def safe_text(raw_text: str) -> jinja2.Markup: """ Process text: treat it as HTML but escape any tags (ie. just escape the HTML) then linkify it. """ return jinja2.Markup( bleach.linkify(bleach.clean(raw_text, tags=[], attributes={}, strip=False)) )
Base
1
def innerfn(fn): global whitelisted, guest_methods, xss_safe_methods, allowed_http_methods_for_whitelisted_func whitelisted.append(fn) allowed_http_methods_for_whitelisted_func[fn] = methods if allow_guest: guest_methods.append(fn) if xss_safe: xss_safe_methods.append(fn) return fn
Base
1
def receivePing(): vrequest = request.form['id'] db.sentences_victim('report_online', [vrequest]) return json.dumps({'status' : 'OK', 'vId' : vrequest});
Base
1
def test_fix_missing_locations(self): src = ast.parse('write("spam")') src.body.append(ast.Expr(ast.Call(ast.Name('spam', ast.Load()), [ast.Str('eggs')], []))) self.assertEqual(src, ast.fix_missing_locations(src)) self.maxDiff = None ...
Base
1
def tearDown(self): if os.path.isfile(self.filename): os.unlink(self.filename)
Class
2
def make_homeserver(self, reactor, clock): hs = self.setup_test_homeserver("server", http_client=None) return hs
Base
1
inline void AveragePool(const uint8* input_data, const Dims<4>& input_dims, int stride_width, int stride_height, int pad_width, int pad_height, int filter_width, int filter_height, int32 output_activation_min, int32 output_a...
Base
1
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 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 fetch(cls) -> "InstanceConfig": entry = cls.get(get_instance_name()) if entry is None: entry = cls() entry.save() return entry
Class
2
def test_scatter_ops_even_partition(self, op): v = variables_lib.Variable(array_ops.zeros((30, 1))) sparse_delta = ops.IndexedSlices( values=constant_op.constant([[0.], [1.], [2.], [3.], [4.]]), indices=constant_op.constant([0, 10, 12, 21, 22])) v0 = variables_lib.Variable(array_ops.zeros...
Base
1
def _inject_metadata_into_fs(metadata, fs, execute=None): metadata_path = os.path.join(fs, "meta.js") metadata = dict([(m.key, m.value) for m in metadata]) utils.execute('tee', metadata_path, process_input=jsonutils.dumps(metadata), run_as_root=True)
Base
1
def resend_activation_email(request): if request.user.is_authenticated: return redirect(request.GET.get('next', reverse('spirit:user:update'))) form = ResendActivationForm(data=post_data(request)) if is_post(request): if not request.is_limited() and form.is_valid(): user = form....
Base
1
def unarchive(byte_array: bytes, directory: Text) -> Text: """Tries to unpack a byte array interpreting it as an archive. Tries to use tar first to unpack, if that fails, zip will be used.""" try: tar = tarfile.open(fileobj=IOReader(byte_array)) tar.extractall(directory) tar.close(...
Base
1
def _normalize_headers(headers): return dict( [ ( _convert_byte_str(key).lower(), NORMALIZE_SPACE.sub(_convert_byte_str(value), " ").strip(), ) for (key, value) in headers.items() ] )
Class
2
def author_list(): if current_user.check_visibility(constants.SIDEBAR_AUTHOR): if current_user.get_view_property('author', 'dir') == 'desc': order = db.Authors.sort.desc() order_no = 0 else: order = db.Authors.sort.asc() order_no = 1 entries = ...
Base
1
def __init__( self, credentials, host, request_uri, headers, response, content, http
Class
2
def escape_text(text: EscapableEntity) -> str: """Escape HTML text We only strip some tags and allow some simple tags such as <h1>, <b> or <i> to be part of the string. This is useful for messages where we want to keep formatting options. (Formerly known as 'permissive_attrencode') Args: ...
Base
1
def test_change_due_date(self): url = reverse('change_due_date', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.get(url, { 'student': self.user1.username, 'url': self.week1.location.to_deprecated_string(), 'due_datetime': '12/3...
Compound
4
def testRuntimeError(self, inputs, exception=errors.InvalidArgumentError, message=None):
Base
1
def testCapacity(self): capacity = 3 with ops.Graph().as_default() as G: with ops.device('/cpu:0'): x = array_ops.placeholder(dtypes.int32, name='x') pi = array_ops.placeholder(dtypes.int64, name='pi') gi = array_ops.placeholder(dtypes.int64, name='gi') with ops.device(tes...
Base
1
def get_cc_columns(filter_config_custom_read=False): tmpcc = calibre_db.session.query(db.Custom_Columns)\ .filter(db.Custom_Columns.datatype.notin_(db.cc_exceptions)).all() cc = [] r = None if config.config_columns_to_ignore: r = re.compile(config.config_columns_to_ignore) for col i...
Base
1
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 get_student_progress_url(request, course_id): """ Get the progress url of a student. Limited to staff access. Takes query paremeter unique_student_identifier and if the student exists returns e.g. { 'progress_url': '/../...' } """ course_id = SlashSeparatedCourseKey.from_dep...
Compound
4
def whitelist(allow_guest=False, xss_safe=False, methods=None): """ Decorator for whitelisting a function and making it accessible via HTTP. Standard request will be `/api/method/[path.to.method]` :param allow_guest: Allow non logged-in user to access this method. :param methods: Allowed http method to access the...
Base
1
def testProxyGET(self): data = b"""\ GET https://example.com:8080/foobar HTTP/8.4 content-length: 7 Hello. """ parser = self.parser self.feed(data) self.assertTrue(parser.completed) self.assertEqual(parser.version, "8.4") self.assertFalse(parser.empty) self.a...
Base
1
def _moderate(request, pk, field_name, to_value, action=None, message=None): topic = get_object_or_404(Topic, pk=pk) if is_post(request): count = ( Topic.objects .filter(pk=pk) .exclude(**{field_name: to_value}) .update(**{ field_name: to_...
Base
1
def shutdown(): task = int(request.args.get("parameter").strip()) showtext = {} if task in (0, 1): # valid commandos received # close all database connections calibre_db.dispose() ub.dispose() if task == 0: showtext['text'] = _(u'Server restarted, please reload ...
Compound
4
def test_modify_access_noparams(self): """ Test missing all query parameters. """ url = reverse('modify_access', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.get(url) self.assertEqual(response.status_code, 400)
Compound
4
def _on_ssl_errors(self, error): self._has_ssl_errors = True url = error.url() log.webview.debug("Certificate error: {}".format(error)) if error.is_overridable(): error.ignore = shared.ignore_certificate_errors( url, [error], abort_on=[self.abort_questio...
Class
2
def prepare_key(self, key): key = force_bytes(key) invalid_strings = [ b"-----BEGIN PUBLIC KEY-----", b"-----BEGIN CERTIFICATE-----", b"-----BEGIN RSA PUBLIC KEY-----", b"ssh-rsa", ] if any(string_value in key for string_value in inva...
Class
2
def testUnravelIndexZeroDim(self): with self.cached_session(): for dtype in [dtypes.int32, dtypes.int64]: with self.assertRaisesRegex(errors.InvalidArgumentError, "index is out of bound as with dims"): indices = constant_op.constant([2, 5, 7], dtype=dtyp...
Base
1
def load(doc): code = config.retrieveBoilerplateFile(doc, "bs-extensions") exec(code, globals())
Base
1
def test_http10_generator(self): body = string.ascii_letters to_send = ( "GET / HTTP/1.0\n" "Connection: Keep-Alive\n" "Content-Length: %d\n\n" % len(body) ) to_send += body to_send = tobytes(to_send) self.connect() self.soc...
Base
1
def get_info_for_package(pkg, channel_id, org_id): log_debug(3, pkg) pkg = map(str, pkg) params = {'name': pkg[0], 'ver': pkg[1], 'rel': pkg[2], 'epoch': pkg[3], 'arch': pkg[4], 'channel_id': channel_id, 'org_id': org_id} ...
Base
1
async def tenorkey(self, ctx): """ Sets a Tenor GIF API key to enable reaction gifs with act commands. You can obtain a key from here: https://tenor.com/developer/dashboard """ instructions = [ "Go to the Tenor developer dashboard: https://tenor.com/develo...
Base
1
def test_enrollment_report_features_csv(self): """ test to generate enrollment report. enroll users, admin staff using registration codes. """ InvoiceTransaction.objects.create( invoice=self.sale_invoice_1, amount=self.sale_invoice_1.total_amount, ...
Compound
4
def render_hot_books(page, order): if current_user.check_visibility(constants.SIDEBAR_HOT): if order[1] not in ['hotasc', 'hotdesc']: # Unary expression comparsion only working (for this expression) in sqlalchemy 1.4+ #if not (order[0][0].compare(func.count(ub.Downloads.book_id).desc()) or ...
Base
1
def runTest(self): for mode in (self.module.MODE_ECB, self.module.MODE_CBC, self.module.MODE_CFB, self.module.MODE_OFB, self.module.MODE_OPENPGP): encryption_cipher = self.module.new(a2b_hex(self.key), mode, self.iv) ciphertext = encryption_cipher.encrypt(self.plaintext) ...
Class
2
def get_type_string(data): """ Translates a Python data type into a string format. """ data_type = type(data) if data_type in (int, long): return 'integer' elif data_type == float: return 'float' elif data_type == bool: return 'boolean' elif data_type in (lis...
Class
2
def delete_scan(request, id): obj = get_object_or_404(ScanHistory, id=id) if request.method == "POST": delete_dir = obj.domain.name + '_' + \ str(datetime.datetime.strftime(obj.start_scan_date, '%Y_%m_%d_%H_%M_%S')) delete_path = settings.TOOL_LOCATION + 'scan_results/' + delete_dir ...
Class
2
def get_valid_filename(value, replace_whitespace=True, chars=128): """ Returns the given string converted to a string that can be used for a clean filename. Limits num characters to 128 max. """ if value[-1:] == u'.': value = value[:-1]+u'_' value = value.replace("/", "_").replace(":", "...
Base
1
def _normalize_headers(headers): return dict( [ (key.lower(), NORMALIZE_SPACE.sub(value, " ").strip()) for (key, value) in headers.iteritems() ] )
Class
2
def load_metadata_preview(request, c_type, c_id, conn=None, share_id=None, **kwargs): """ This is the image 'Preview' tab for the right-hand panel. """ context = {} # the index of a field within a well index = getIntOrDefault(request, "index", 0) manager = BaseContainer(conn, **{str(c_type...
Base
1
def __init__(self, *args, **kwargs): super(BasketShareForm, self).__init__(*args, **kwargs) try: self.fields["image"] = GroupModelMultipleChoiceField( queryset=kwargs["initial"]["images"], initial=kwargs["initial"]["selected"], widget=form...
Class
2
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
def get(self, request, name=None): if name is None: if request.user.is_staff: return FormattedResponse(config.get_all()) return FormattedResponse(config.get_all_non_sensitive()) return FormattedResponse(config.get(name))
Class
2
def format_help_for_context(self, ctx: commands.Context) -> str: #Thanks Sinbad! And Trusty in whose cogs I found this. pre_processed = super().format_help_for_context(ctx) return f"{pre_processed}\n\nVersion: {self.__version__}"
Class
2
def show_student_extensions(request, course_id): """ Shows all of the due date extensions granted to a particular student in a particular course. """ student = require_student_from_identifier(request.GET.get('student')) course = get_course_by_id(SlashSeparatedCourseKey.from_deprecated_string(cou...
Compound
4
def update(request, pk): topic = Topic.objects.for_update_or_404(pk, request.user) category_id = topic.category_id form = TopicForm( user=request.user, data=post_data(request), instance=topic) if is_post(request) and form.is_valid(): topic = form.save() if topic.c...
Base
1
def test_received_control_line_finished_garbage_in_input(self): buf = DummyBuffer() inst = self._makeOne(buf) result = inst.received(b"garbage\n") self.assertEqual(result, 8) self.assertTrue(inst.error)
Base
1
def test_list_instructor_tasks_problem_student(self, act): """ Test list task history for problem AND student. """ act.return_value = self.tasks url = reverse('list_instructor_tasks', kwargs={'course_id': self.course.id.to_deprecated_string()}) mock_factory = MockCompletionInfo() ...
Compound
4
def test_rescore_entrance_exam_with_invalid_exam(self): """ Test course has entrance exam id set while re-scoring. """ 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 make_homeserver(self, reactor, clock): hs = self.setup_test_homeserver( "red", http_client=None, federation_client=Mock(), ) self.event_source = hs.get_event_sources().sources["typing"] hs.get_federation_handler = Mock() async def get_user_by_access_token(...
Base
1
def handler(request): """Handler for a file:// URL. Args: request: QNetworkRequest to answer to. Return: A QNetworkReply for directories, None for files. """ path = request.url().toLocalFile() try: if os.path.isdir(path): data = dirbrowser_html(path) ...
Compound
4
def POST(self, path, body=None, ensure_encoding=True, log_request_body=True): return self._request('POST', path, body=body, ensure_encoding=ensure_encoding, log_request_body=log_request_body)
Base
1