code
stringlengths 12
2.05k
| label_name
stringclasses 5
values | label
int64 0
4
|
---|---|---|
def __init__(
self,
*,
resource_group: str,
location: str,
application_name: str,
owner: str,
client_id: Optional[str],
client_secret: Optional[str],
app_zip: str,
tools: str,
instance_specific: str,
third_party: str,
arm_template: str,
workbook_data: str,
create_registration: bool,
migrations: List[str],
export_appinsights: bool,
log_service_principal: bool,
multi_tenant_domain: str,
upgrade: bool,
subscription_id: Optional[str],
admins: List[UUID] | Class | 2 |
def make_homeserver(self, reactor, clock):
self.http_client = Mock()
return self.setup_test_homeserver(http_client=self.http_client) | Base | 1 |
def test_received_nonsense_nothing(self):
data = b"""\
"""
result = self.parser.received(data)
self.assertEqual(result, 2)
self.assertTrue(self.parser.completed)
self.assertEqual(self.parser.headers, {}) | Base | 1 |
def __init__(
self, cache, safe=safename | Class | 2 |
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 _create(self):
url = urljoin(recurly.base_uri(), self.collection_path)
return self.post(url) | Base | 1 |
def get_absolute_path(path):
import os
script_dir = os.path.dirname(__file__) # <-- absolute dir the script is in
rel_path = path
abs_file_path = os.path.join(script_dir, rel_path)
return abs_file_path | Base | 1 |
def render(self, name, value, attrs=None):
html = super(AdminURLFieldWidget, self).render(name, value, attrs)
if value:
value = force_text(self._format_value(value))
final_attrs = {'href': mark_safe(smart_urlquote(value))}
html = format_html(
'<p class="url">{0} <a {1}>{2}</a><br />{3} {4}</p>',
_('Currently:'), flatatt(final_attrs), value,
_('Change:'), html
)
return html | Base | 1 |
def make_homeserver(self, reactor, clock):
self.mock_federation = Mock()
self.mock_registry = Mock()
self.query_handlers = {}
def register_query_handler(query_type, handler):
self.query_handlers[query_type] = handler
self.mock_registry.register_query_handler = register_query_handler
hs = self.setup_test_homeserver(
http_client=None,
resource_for_federation=Mock(),
federation_client=self.mock_federation,
federation_registry=self.mock_registry,
)
self.handler = hs.get_directory_handler()
self.store = hs.get_datastore()
self.my_room = RoomAlias.from_string("#my-room:test")
self.your_room = RoomAlias.from_string("#your-room:test")
self.remote_room = RoomAlias.from_string("#another:remote")
return hs | Base | 1 |
def test_keepalive_http11_explicit(self):
# Explicitly set keep-alive
data = "Default: Keep me alive"
s = tobytes(
"GET / HTTP/1.1\n"
"Connection: keep-alive\n"
"Content-Length: %d\n"
"\n"
"%s" % (len(data), data)
)
self.connect()
self.sock.send(s)
response = httplib.HTTPResponse(self.sock)
response.begin()
self.assertEqual(int(response.status), 200)
self.assertTrue(response.getheader("connection") != "close") | Base | 1 |
def is_2fa_enabled(self):
return self.totp_status == TOTPStatus.ENABLED | Class | 2 |
def _decompress(compressed_path: Text, target_path: Text) -> None:
with tarfile.open(compressed_path, "r:gz") as tar:
tar.extractall(target_path) # target dir will be created if it not exists | Base | 1 |
def test_get_problem_responses_successful(self):
"""
Test whether get_problem_responses returns an appropriate status
message if CSV generation was started successfully.
"""
url = reverse(
'get_problem_responses',
kwargs={'course_id': unicode(self.course.id)}
)
problem_location = ''
response = self.client.get(url, {'problem_location': problem_location})
res_json = json.loads(response.content)
self.assertIn('status', res_json)
status = res_json['status']
self.assertIn('is being created', status)
self.assertNotIn('already in progress', status) | Compound | 4 |
def execute_cmd(cmd, from_async=False):
"""execute a request as python module"""
for hook in frappe.get_hooks("override_whitelisted_methods", {}).get(cmd, []):
# override using the first hook
cmd = hook
break
# via server script
if run_server_script_api(cmd):
return None
try:
method = get_attr(cmd)
except Exception as e:
if frappe.local.conf.developer_mode:
raise e
else:
frappe.respond_as_web_page(title='Invalid Method', html='Method not found',
indicator_color='red', http_status_code=404)
return
if from_async:
method = method.queue
is_whitelisted(method)
is_valid_http_method(method)
return frappe.call(method, **frappe.form_dict) | Base | 1 |
def test_get_mpi_implementation(self):
def test(output, expected, exit_code=0):
ret = (output, exit_code) if output is not None else None
env = {'VAR': 'val'}
with mock.patch("horovod.runner.mpi_run.tiny_shell_exec.execute", return_value=ret) as m:
implementation = _get_mpi_implementation(env)
self.assertEqual(expected, implementation)
m.assert_called_once_with('mpirun --version', env)
test(("mpirun (Open MPI) 2.1.1\n"
"Report bugs to http://www.open-mpi.org/community/help/\n"), _OMPI_IMPL)
test("OpenRTE", _OMPI_IMPL)
test("IBM Spectrum MPI", _SMPI_IMPL)
test(("HYDRA build details:\n"
" Version: 3.3a2\n"
" Configure options: 'MPICHLIB_CFLAGS=-g -O2'\n"), _MPICH_IMPL)
test("Intel(R) MPI", _IMPI_IMPL)
test("Unknown MPI v1.00", _UNKNOWN_IMPL)
test("output", exit_code=1, expected=_MISSING_IMPL)
test(None, _MISSING_IMPL) | Class | 2 |
def test_received_chunked_completed_sets_content_length(self):
data = b"""\
GET /foobar HTTP/1.1
Transfer-Encoding: chunked
X-Foo: 1
20;\r\n
This string has 32 characters\r\n
0\r\n\r\n"""
result = self.parser.received(data)
self.assertEqual(result, 58)
data = data[result:]
result = self.parser.received(data)
self.assertTrue(self.parser.completed)
self.assertTrue(self.parser.error is None)
self.assertEqual(self.parser.headers["CONTENT_LENGTH"], "32") | Base | 1 |
def ready(self):
pass | Base | 1 |
def test_it_works_with_explicit_external_host(self, app, monkeypatch):
with app.test_request_context():
monkeypatch.setattr('flask.request.host_url', 'http://example.com')
result = _validate_redirect_url('http://works.com',
_external_host='works.com')
assert result is True
monkeypatch.undo() | Base | 1 |
def _affinity_host(self, context, instance_id):
return self.compute_api.get(context, instance_id)['host'] | Class | 2 |
def test_keepalive_http_10(self):
# Handling of Keep-Alive within HTTP 1.0
data = "Default: Don't keep me alive"
s = tobytes(
"GET / HTTP/1.0\n" "Content-Length: %d\n" "\n" "%s" % (len(data), data)
)
self.connect()
self.sock.send(s)
response = httplib.HTTPResponse(self.sock)
response.begin()
self.assertEqual(int(response.status), 200)
connection = response.getheader("Connection", "")
# We sent no Connection: Keep-Alive header
# Connection: close (or no header) is default.
self.assertTrue(connection != "Keep-Alive") | Base | 1 |
def atom_timestamp(self):
return (self.timestamp.strftime('%Y-%m-%dT%H:%M:%S+00:00') or '') | Base | 1 |
def put_file(self, in_path, out_path):
''' transfer a file from local to chroot '''
if not out_path.startswith(os.path.sep):
out_path = os.path.join(os.path.sep, out_path)
normpath = os.path.normpath(out_path)
out_path = os.path.join(self.chroot, normpath[1:])
vvv("PUT %s TO %s" % (in_path, out_path), host=self.chroot)
if not os.path.exists(in_path):
raise errors.AnsibleFileNotFound("file or module does not exist: %s" % in_path)
try:
shutil.copyfile(in_path, out_path)
except shutil.Error:
traceback.print_exc()
raise errors.AnsibleError("failed to copy: %s and %s are the same" % (in_path, out_path))
except IOError:
traceback.print_exc()
raise errors.AnsibleError("failed to transfer file to %s" % out_path) | Base | 1 |
def snake_case(value: str) -> str:
return stringcase.snakecase(group_title(_sanitize(value))) | Base | 1 |
def logout():
if current_user is not None and current_user.is_authenticated:
ub.delete_user_session(current_user.id, flask_session.get('_id',""))
logout_user()
if feature_support['oauth'] and (config.config_login_type == 2 or config.config_login_type == 3):
logout_oauth_user()
log.debug(u"User logged out")
return redirect(url_for('web.login')) | Base | 1 |
def fetch_file(self, in_path, out_path):
''' fetch a file from zone to local '''
in_path = self._normalize_path(in_path, self.get_zone_path())
vvv("FETCH %s TO %s" % (in_path, out_path), host=self.zone)
self._copy_file(in_path, out_path) | Base | 1 |
def test_adjust_timeout():
mw = _get_mw()
req1 = scrapy.Request("http://example.com", meta = {
'splash': {'args': {'timeout': 60, 'html': 1}},
# download_timeout is always present,
# it is set by DownloadTimeoutMiddleware
'download_timeout': 30,
})
req1 = mw.process_request(req1, None)
assert req1.meta['download_timeout'] > 60
req2 = scrapy.Request("http://example.com", meta = {
'splash': {'args': {'html': 1}},
'download_timeout': 30,
})
req2 = mw.process_request(req2, None)
assert req2.meta['download_timeout'] == 30 | Class | 2 |
def _glob_to_re(glob: str, word_boundary: bool) -> Pattern:
"""Generates regex for a given glob.
Args:
glob
word_boundary: Whether to match against word boundaries or entire string.
"""
if IS_GLOB.search(glob):
r = re.escape(glob)
r = r.replace(r"\*", ".*?")
r = r.replace(r"\?", ".")
# handle [abc], [a-z] and [!a-z] style ranges.
r = GLOB_REGEX.sub(
lambda x: (
"[%s%s]" % (x.group(1) and "^" or "", x.group(2).replace(r"\\\-", "-"))
),
r,
)
if word_boundary:
r = _re_word_boundary(r)
return re.compile(r, flags=re.IGNORECASE)
else:
r = "^" + r + "$"
return re.compile(r, flags=re.IGNORECASE)
elif word_boundary:
r = re.escape(glob)
r = _re_word_boundary(r)
return re.compile(r, flags=re.IGNORECASE)
else:
r = "^" + re.escape(glob) + "$"
return re.compile(r, flags=re.IGNORECASE) | Base | 1 |
def is_valid_client_secret(client_secret):
"""Validate that a given string matches the client_secret regex defined by the spec
:param client_secret: The client_secret to validate
:type client_secret: unicode
:return: Whether the client_secret is valid
:rtype: bool
"""
return client_secret_regex.match(client_secret) is not None | Class | 2 |
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]) | Class | 2 |
def get_release_file(root, request):
session = DBSession()
f = ReleaseFile.by_id(session, int(request.matchdict['file_id']))
rv = {'id': f.id,
'url': f.url,
'filename': f.filename,
}
f.downloads += 1
f.release.downloads += 1
f.release.package.downloads += 1
session.add(f.release.package)
session.add(f.release)
session.add(f)
return rv | Class | 2 |
def sync_tree(self):
LOGGER.info("sync tree to host")
self.transfer_inst.tree.remote(self.tree_,
role=consts.HOST,
idx=-1)
"""
federation.remote(obj=self.tree_,
name=self.transfer_inst.tree.name,
tag=self.transfer_inst.generate_transferid(self.transfer_inst.tree),
role=consts.HOST,
idx=-1)
""" | Class | 2 |
def from_dict(d: Dict[str, Any]) -> AModel:
an_enum_value = AnEnum(d["an_enum_value"])
def _parse_a_camel_date_time(data: Dict[str, Any]) -> Union[datetime, date]:
a_camel_date_time: Union[datetime, date]
try:
a_camel_date_time = datetime.fromisoformat(d["aCamelDateTime"])
return a_camel_date_time
except:
pass
a_camel_date_time = date.fromisoformat(d["aCamelDateTime"])
return a_camel_date_time
a_camel_date_time = _parse_a_camel_date_time(d["aCamelDateTime"])
a_date = date.fromisoformat(d["a_date"])
nested_list_of_enums = []
for nested_list_of_enums_item_data in d.get("nested_list_of_enums") or []:
nested_list_of_enums_item = []
for nested_list_of_enums_item_item_data in nested_list_of_enums_item_data:
nested_list_of_enums_item_item = DifferentEnum(nested_list_of_enums_item_item_data)
nested_list_of_enums_item.append(nested_list_of_enums_item_item)
nested_list_of_enums.append(nested_list_of_enums_item)
some_dict = d.get("some_dict")
return AModel(
an_enum_value=an_enum_value,
a_camel_date_time=a_camel_date_time,
a_date=a_date,
nested_list_of_enums=nested_list_of_enums,
some_dict=some_dict,
) | Base | 1 |
def test_module(self):
body = [ast.Num(42)]
x = ast.Module(body)
self.assertEqual(x.body, body) | Base | 1 |
def __init__(self, hs):
super().__init__(hs)
self.clock = hs.get_clock()
self.client = hs.get_http_client()
self.key_servers = self.config.key_servers | Base | 1 |
def make_homeserver(self, reactor, clock):
hs = self.setup_test_homeserver(
resource_for_federation=Mock(), http_client=None
)
return hs | Base | 1 |
def test_modify_access_revoke_with_username(self):
url = reverse('modify_access', kwargs={'course_id': self.course.id.to_deprecated_string()})
response = self.client.get(url, {
'unique_student_identifier': self.other_staff.username,
'rolename': 'staff',
'action': 'revoke',
})
self.assertEqual(response.status_code, 200) | Compound | 4 |
def _re_word_boundary(r: str) -> str:
"""
Adds word boundary characters to the start and end of an
expression to require that the match occur as a whole word,
but do so respecting the fact that strings starting or ending
with non-word characters will change word boundaries.
"""
# we can't use \b as it chokes on unicode. however \W seems to be okay
# as shorthand for [^0-9A-Za-z_].
return r"(^|\W)%s(\W|$)" % (r,) | Base | 1 |
def test_equal_body(self):
# check server doesnt close connection when body is equal to
# cl header
to_send = tobytes(
"GET /equal_body 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, headers, response_body = read_http(fp)
content_length = int(headers.get("content-length")) or None
self.assertEqual(content_length, 9)
self.assertline(line, "200", "OK", "HTTP/1.0")
self.assertEqual(content_length, len(response_body))
self.assertEqual(response_body, tobytes("abcdefghi"))
# remote does not close connection (keepalive header)
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.0") | Base | 1 |
def language_overview():
if current_user.check_visibility(constants.SIDEBAR_LANGUAGE) and current_user.filter_language() == u"all":
order_no = 0 if current_user.get_view_property('language', 'dir') == 'desc' else 1
charlist = list()
languages = calibre_db.speaking_language(reverse_order=not order_no, with_count=True)
for lang in languages:
upper_lang = lang[0].name[0].upper()
if upper_lang not in charlist:
charlist.append(upper_lang)
return render_title_template('languages.html', languages=languages,
charlist=charlist, title=_(u"Languages"), page="langlist",
data="language", order=order_no)
else:
abort(404) | Base | 1 |
def respond_error(self, context, exception):
context.respond_server_error()
stack = traceback.format_exc()
return """
<html>
<body>
<style>
body {
font-family: sans-serif;
color: #888;
text-align: center;
}
body pre {
width: 600px;
text-align: left;
margin: auto;
font-family: monospace;
}
</style>
<img src="/ajenti:static/main/error.jpeg" />
<br/>
<p>
Server error
</p>
<pre>
%s
</pre>
</body>
</html>
""" % stack | Base | 1 |
def __init__(self, private_key):
self.signer = Signer(private_key)
self.public_key = self.signer.public_key | Class | 2 |
def test_reset_student_attempts_nonsense(self):
""" Test failure with both unique_student_identifier and all_students. """
url = reverse('reset_student_attempts', kwargs={'course_id': self.course.id.to_deprecated_string()})
response = self.client.get(url, {
'problem_to_reset': self.problem_urlname,
'unique_student_identifier': self.student.email,
'all_students': True,
})
self.assertEqual(response.status_code, 400) | Compound | 4 |
def skip(self, type):
if type == TType.STOP:
return
elif type == TType.BOOL:
self.readBool()
elif type == TType.BYTE:
self.readByte()
elif type == TType.I16:
self.readI16()
elif type == TType.I32:
self.readI32()
elif type == TType.I64:
self.readI64()
elif type == TType.DOUBLE:
self.readDouble()
elif type == TType.FLOAT:
self.readFloat()
elif type == TType.STRING:
self.readString()
elif type == TType.STRUCT:
name = self.readStructBegin()
while True:
(name, type, id) = self.readFieldBegin()
if type == TType.STOP:
break
self.skip(type)
self.readFieldEnd()
self.readStructEnd()
elif type == TType.MAP:
(ktype, vtype, size) = self.readMapBegin()
for _ in range(size):
self.skip(ktype)
self.skip(vtype)
self.readMapEnd()
elif type == TType.SET:
(etype, size) = self.readSetBegin()
for _ in range(size):
self.skip(etype)
self.readSetEnd()
elif type == TType.LIST:
(etype, size) = self.readListBegin()
for _ in range(size):
self.skip(etype)
self.readListEnd() | Class | 2 |
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=forms.SelectMultiple(attrs={"size": 10}),
)
except Exception:
self.fields["image"] = GroupModelMultipleChoiceField(
queryset=kwargs["initial"]["images"],
widget=forms.SelectMultiple(attrs={"size": 10}),
) | Base | 1 |
def test_before_start_response_http_10(self):
to_send = "GET /before_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, "500", "Internal Server Error", "HTTP/1.0")
cl = int(headers["content-length"])
self.assertEqual(cl, len(response_body))
self.assertTrue(response_body.startswith(b"Internal Server Error"))
self.assertEqual(headers["connection"], "close")
# connection has been closed
self.send_check_error(to_send)
self.assertRaises(ConnectionClosed, read_http, fp) | Base | 1 |
def __setstate__(self, state):
"""Restore from pickled state."""
self.__dict__ = state
self._lock = threading.Lock()
self._descriptor_cache = weakref.WeakKeyDictionary()
self._key_for_call_stats = self._get_key_for_call_stats() | Class | 2 |
def _getKeysForServer(self, server_name):
"""Get the signing key data from a homeserver.
:param server_name: The name of the server to request the keys from.
:type server_name: unicode
:return: The verification keys returned by the server.
:rtype: twisted.internet.defer.Deferred[dict[unicode, dict[unicode, unicode]]]
"""
if server_name in self.cache:
cached = self.cache[server_name]
now = int(time.time() * 1000)
if cached['valid_until_ts'] > now:
defer.returnValue(self.cache[server_name]['verify_keys'])
client = FederationHttpClient(self.sydent)
result = yield client.get_json("matrix://%s/_matrix/key/v2/server/" % server_name)
if 'verify_keys' not in result:
raise SignatureVerifyException("No key found in response")
if 'valid_until_ts' in result:
# Don't cache anything without a valid_until_ts or we wouldn't
# know when to expire it.
logger.info("Got keys for %s: caching until %s", server_name, result['valid_until_ts'])
self.cache[server_name] = result
defer.returnValue(result['verify_keys']) | Base | 1 |
def test_received_control_line_finished_all_chunks_received(self):
buf = DummyBuffer()
inst = self._makeOne(buf)
result = inst.received(b"0;discard\n")
self.assertEqual(inst.control_line, b"")
self.assertEqual(inst.all_chunks_received, True)
self.assertEqual(result, 10)
self.assertEqual(inst.completed, False) | Base | 1 |
def test_list_entrance_exam_instructor_tasks_student(self):
""" Test list task history for entrance exam AND student. """
# create a re-score entrance exam task
url = reverse('rescore_entrance_exam', kwargs={'course_id': unicode(self.course.id)})
response = self.client.get(url, {
'unique_student_identifier': self.student.email,
})
self.assertEqual(response.status_code, 200)
url = reverse('list_entrance_exam_instructor_tasks', kwargs={'course_id': unicode(self.course.id)})
response = self.client.get(url, {
'unique_student_identifier': self.student.email,
})
self.assertEqual(response.status_code, 200)
# check response
tasks = json.loads(response.content)['tasks']
self.assertEqual(len(tasks), 1)
self.assertEqual(tasks[0]['status'], _('Complete')) | Compound | 4 |
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:
frappe.throw(_("Not permitted"), frappe.PermissionError) | Base | 1 |
def testColocation(self):
gpu_dev = test.gpu_device_name()
with ops.Graph().as_default() as G:
with ops.device('/cpu:0'):
x = array_ops.placeholder(dtypes.float32)
v = 2. * (array_ops.zeros([128, 128]) + x)
with ops.device(gpu_dev):
stager = data_flow_ops.MapStagingArea([dtypes.float32])
y = stager.put(1, [v], [0])
expected_name = gpu_dev if 'gpu' not in gpu_dev else '/device:GPU:0'
self.assertEqual(y.device, expected_name)
with ops.device('/cpu:0'):
_, x = stager.get(1)
y = stager.peek(1)[0]
_, z = stager.get()
self.assertEqual(x[0].device, '/device:CPU:0')
self.assertEqual(y.device, '/device:CPU:0')
self.assertEqual(z[0].device, '/device:CPU:0')
G.finalize() | Base | 1 |
def delete(self, location, connection=None):
location = location.store_location
if not connection:
connection = self.get_connection(location)
try:
# We request the manifest for the object. If one exists,
# that means the object was uploaded in chunks/segments,
# and we need to delete all the chunks as well as the
# manifest.
manifest = None
try:
headers = connection.head_object(
location.container, location.obj)
manifest = headers.get('x-object-manifest')
except swiftclient.ClientException, e:
if e.http_status != httplib.NOT_FOUND:
raise
if manifest:
# Delete all the chunks before the object manifest itself
obj_container, obj_prefix = manifest.split('/', 1)
segments = connection.get_container(
obj_container, prefix=obj_prefix)[1]
for segment in segments:
# TODO(jaypipes): This would be an easy area to parallelize
# since we're simply sending off parallelizable requests
# to Swift to delete stuff. It's not like we're going to
# be hogging up network or file I/O here...
connection.delete_object(
obj_container, segment['name'])
else:
connection.delete_object(location.container, location.obj)
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 | 2 |
def get_cms_details(url):
# this function will fetch cms details using cms_detector
response = {}
cms_detector_command = 'python3 /usr/src/github/CMSeeK/cmseek.py -u {} --random-agent --batch --follow-redirect'.format(url)
os.system(cms_detector_command)
response['status'] = False
response['message'] = 'Could not detect CMS!'
parsed_url = urlparse(url)
domain_name = parsed_url.hostname
port = parsed_url.port
find_dir = domain_name
if port:
find_dir += '_{}'.format(port)
print(url)
print(find_dir)
# subdomain may also have port number, and is stored in dir as _port
cms_dir_path = '/usr/src/github/CMSeeK/Result/{}'.format(find_dir)
cms_json_path = cms_dir_path + '/cms.json'
if os.path.isfile(cms_json_path):
cms_file_content = json.loads(open(cms_json_path, 'r').read())
if not cms_file_content.get('cms_id'):
return response
response = {}
response = cms_file_content
response['status'] = True
# remove cms dir path
try:
shutil.rmtree(cms_dir_path)
except Exception as e:
print(e)
return response | Base | 1 |
def test_process_request__no_location(self, rf, settings):
settings.AWS_LOCATION = ""
uploaded_file = SimpleUploadedFile("uploaded_file.txt", b"uploaded")
request = rf.post("/", data={"file": uploaded_file})
S3FileMiddleware(lambda x: None)(request)
assert request.FILES.getlist("file")
assert request.FILES.get("file").read() == b"uploaded"
storage.save("tmp/s3file/s3_file.txt", ContentFile(b"s3file"))
request = rf.post(
"/", data={"file": "tmp/s3file/s3_file.txt", "s3file": "file"}
)
S3FileMiddleware(lambda x: None)(request)
assert request.FILES.getlist("file")
assert request.FILES.get("file").read() == b"s3file" | Base | 1 |
def set(self, key, value, serialize=True, timeout=0):
"""
Set a key/value pair in memcache
:param key: key
:param value: value
:param serialize: if True, value is pickled before sending to memcache
:param timeout: ttl in memcache
"""
key = md5hash(key)
if timeout > 0:
timeout += time.time()
flags = 0
if serialize:
value = pickle.dumps(value, PICKLE_PROTOCOL)
flags |= PICKLE_FLAG
for (server, fp, sock) in self._get_conns(key):
try:
sock.sendall('set %s %d %d %s noreply\r\n%s\r\n' % \
(key, flags, timeout, len(value), value))
self._return_conn(server, fp, sock)
return
except Exception, e:
self._exception_occurred(server, e) | Base | 1 |
def testStringNGramsBadDataSplits(self, splits):
data = ["aa", "bb", "cc", "dd", "ee", "ff"]
with self.assertRaisesRegex(errors.InvalidArgumentError,
"Invalid split value"):
self.evaluate(
gen_string_ops.string_n_grams(
data=data,
data_splits=splits,
separator="",
ngram_widths=[2],
left_pad="",
right_pad="",
pad_width=0,
preserve_short_sequences=False)) | Base | 1 |
def test_logout_get(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 get_config(p, section, key, env_var, default, boolean=False, integer=False, floating=False):
''' return a configuration variable with casting '''
value = _get_config(p, section, key, env_var, default)
if boolean:
return mk_boolean(value)
if value and integer:
return int(value)
if value and floating:
return float(value)
return value | Class | 2 |
def test_basic_auth_invalid_credentials(self):
with self.assertRaises(InvalidStatusCode) as raised:
self.start_client(user_info=("hello", "ihateyou"))
self.assertEqual(raised.exception.status_code, 401) | Base | 1 |
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))
) | Class | 2 |
def crawl_items(spider_cls, resource_cls, settings, spider_kwargs=None):
""" Use spider_cls to crawl resource_cls. URL of the resource is passed
to the spider as ``url`` argument.
Return ``(items, resource_url, crawler)`` tuple.
"""
spider_kwargs = {} if spider_kwargs is None else spider_kwargs
crawler = make_crawler(spider_cls, settings)
with MockServer(resource_cls) as s:
root_url = s.root_url
yield crawler.crawl(url=root_url, **spider_kwargs)
result = crawler.spider.collected_items, s.root_url, crawler
returnValue(result) | Class | 2 |
def test_register(self) -> None:
reset_emails_in_zulip_realm()
realm = get_realm("zulip")
stream_names = [f"stream_{i}" for i in range(40)]
for stream_name in stream_names:
stream = self.make_stream(stream_name, realm=realm)
DefaultStream.objects.create(stream=stream, realm=realm)
# Clear all the caches.
flush_per_request_caches()
ContentType.objects.clear_cache()
with queries_captured() as queries, cache_tries_captured() as cache_tries:
self.register(self.nonreg_email("test"), "test")
# Ensure the number of queries we make is not O(streams)
self.assert_length(queries, 89)
# We can probably avoid a couple cache hits here, but there doesn't
# seem to be any O(N) behavior. Some of the cache hits are related
# to sending messages, such as getting the welcome bot, looking up
# the alert words for a realm, etc.
self.assert_length(cache_tries, 21)
user_profile = self.nonreg_user("test")
self.assert_logged_in_user_id(user_profile.id)
self.assertFalse(user_profile.enable_stream_desktop_notifications) | Base | 1 |
def create(request, topic_id):
topic = get_object_or_404(Topic, pk=topic_id)
form = FavoriteForm(user=request.user, topic=topic, data=request.POST)
if form.is_valid():
form.save()
else:
messages.error(request, utils.render_form_errors(form))
return redirect(request.POST.get('next', topic.get_absolute_url())) | 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 _get_obj_abosolute_path(dataset, rel_path):
return os.path.join(DATAROOT, dataset, rel_path) | Base | 1 |
def _request(self, method, path, queries=(), body=None, ensure_encoding=True,
log_request_body=True): | Base | 1 |
def _inject_key_into_fs(key, fs, execute=None):
"""Add the given public ssh key to root's authorized_keys.
key is an ssh key string.
fs is the path to the base of the filesystem into which to inject the key.
"""
sshdir = os.path.join(fs, 'root', '.ssh')
utils.execute('mkdir', '-p', sshdir, run_as_root=True)
utils.execute('chown', 'root', sshdir, run_as_root=True)
utils.execute('chmod', '700', sshdir, run_as_root=True)
keyfile = os.path.join(sshdir, 'authorized_keys')
key_data = [
'\n',
'# The following ssh key was injected by Nova',
'\n',
key.strip(),
'\n',
]
utils.execute('tee', '-a', keyfile,
process_input=''.join(key_data), run_as_root=True) | Base | 1 |
def test_filelike_nocl_http10(self):
to_send = "GET /filelike_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", "OK", "HTTP/1.0")
cl = int(headers["content-length"])
self.assertEqual(cl, len(response_body))
ct = headers["content-type"]
self.assertEqual(ct, "image/jpeg")
self.assertTrue(b"\377\330\377" in response_body)
# connection has been closed
self.send_check_error(to_send)
self.assertRaises(ConnectionClosed, read_http, fp) | Base | 1 |
def connect(self, port=None):
''' connect to the chroot; nothing to do here '''
vvv("THIS IS A LOCAL CHROOT DIR", host=self.jail)
return self | Base | 1 |
def is_safe_url(url, host=None):
"""
Return ``True`` if the url is a safe redirection (i.e. it doesn't point to
a different host and uses a safe scheme).
Always returns ``False`` on an empty url.
"""
if url is not None:
url = url.strip()
if not url:
return False
# Chrome treats \ completely as /
url = url.replace('\\', '/')
# Chrome considers any URL with more than two slashes to be absolute, but
# urlparse is not so flexible. Treat any url with three slashes as unsafe.
if url.startswith('///'):
return False
url_info = urlparse(url)
# Forbid URLs like http:///example.com - with a scheme, but without a hostname.
# In that URL, example.com is not the hostname but, a path component. However,
# Chrome will still consider example.com to be the hostname, so we must not
# allow this syntax.
if not url_info.netloc and url_info.scheme:
return False
# Forbid URLs that start with control characters. Some browsers (like
# Chrome) ignore quite a few control characters at the start of a
# URL and might consider the URL as scheme relative.
if unicodedata.category(url[0])[0] == 'C':
return False
return ((not url_info.netloc or url_info.netloc == host) and
(not url_info.scheme or url_info.scheme in ['http', 'https'])) | Base | 1 |
def test_get_student_exam_results(self):
"""
Test whether get_proctored_exam_results returns an appropriate
status message when users request a CSV file.
"""
url = reverse(
'get_proctored_exam_results',
kwargs={'course_id': unicode(self.course.id)}
)
# Successful case:
response = self.client.get(url, {})
res_json = json.loads(response.content)
self.assertIn('status', res_json)
self.assertNotIn('currently being created', res_json['status'])
# CSV generation already in progress:
with patch('instructor_task.api.submit_proctored_exam_results_report') as submit_task_function:
error = AlreadyRunningError()
submit_task_function.side_effect = error
response = self.client.get(url, {})
res_json = json.loads(response.content)
self.assertIn('status', res_json)
self.assertIn('currently being created', res_json['status']) | Compound | 4 |
def test_credits_view_html(self):
response = self.get_credits("html")
self.assertEqual(response.status_code, 200)
self.assertHTMLEqual(
response.content.decode(),
"<table>\n"
"<tr>\n<th>Czech</th>\n"
'<td><ul><li><a href="mailto:[email protected]">'
"Weblate Test</a> (1)</li></ul></td>\n</tr>\n"
"</table>",
) | Base | 1 |
def test_certificates_features_group_by_mode(self):
"""
Test for certificate csv features against mode. Certificates should be group by 'mode' in reponse.
"""
url = reverse('get_issued_certificates', kwargs={'course_id': unicode(self.course.id)})
# firstly generating downloadable certificates with 'honor' mode
certificate_count = 3
for __ in xrange(certificate_count):
self.generate_certificate(course_id=self.course.id, mode='honor', status=CertificateStatuses.downloadable)
response = self.client.get(url)
res_json = json.loads(response.content)
self.assertIn('certificates', res_json)
self.assertEqual(len(res_json['certificates']), 1)
# retrieve the first certificate from the list, there should be 3 certificates for 'honor' mode.
certificate = res_json['certificates'][0]
self.assertEqual(certificate.get('total_issued_certificate'), 3)
self.assertEqual(certificate.get('mode'), 'honor')
self.assertEqual(certificate.get('course_id'), str(self.course.id))
# Now generating downloadable certificates with 'verified' mode
for __ in xrange(certificate_count):
self.generate_certificate(
course_id=self.course.id,
mode='verified',
status=CertificateStatuses.downloadable
)
response = self.client.get(url)
res_json = json.loads(response.content)
self.assertIn('certificates', res_json)
# total certificate count should be 2 for 'verified' mode.
self.assertEqual(len(res_json['certificates']), 2)
# retrieve the second certificate from the list
certificate = res_json['certificates'][1]
self.assertEqual(certificate.get('total_issued_certificate'), 3)
self.assertEqual(certificate.get('mode'), 'verified') | Compound | 4 |
def make_homeserver(self, reactor, clock):
hs = self.setup_test_homeserver(
http_client=None, homeserver_to_use=GenericWorkerServer
)
return hs | Base | 1 |
def sanitized_join(path: str, root: pathlib.Path) -> pathlib.Path:
result = (root / path).absolute()
if not str(result).startswith(str(root) + "/"):
raise ValueError("resulting path is outside root")
return result | Base | 1 |
def read_config(self, config, **kwargs):
consent_config = config.get("user_consent")
self.terms_template = self.read_templates(["terms.html"], autoescape=True)[0]
if consent_config is None:
return
self.user_consent_version = str(consent_config["version"])
self.user_consent_template_dir = self.abspath(consent_config["template_dir"])
if not path.isdir(self.user_consent_template_dir):
raise ConfigError(
"Could not find template directory '%s'"
% (self.user_consent_template_dir,)
)
self.user_consent_server_notice_content = consent_config.get(
"server_notice_content"
)
self.block_events_without_consent_error = consent_config.get(
"block_events_error"
)
self.user_consent_server_notice_to_guests = bool(
consent_config.get("send_server_notice_to_guests", False)
)
self.user_consent_at_registration = bool(
consent_config.get("require_at_registration", False)
)
self.user_consent_policy_name = consent_config.get(
"policy_name", "Privacy Policy"
) | Base | 1 |
def get_list(an_enum_value: List[AnEnum] = Query(...), some_date: Union[date, datetime] = Query(...)):
""" Get a list of things """
return | Base | 1 |
def test_request_body_too_large_with_no_cl_http10_keepalive(self):
body = "a" * self.toobig
to_send = "GET / HTTP/1.0\nConnection: Keep-Alive\n\n"
to_send += body
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)
# server trusts the content-length header (assumed zero)
self.assertline(line, "200", "OK", "HTTP/1.0")
cl = int(headers["content-length"])
self.assertEqual(cl, len(response_body))
line, headers, response_body = read_http(fp)
# next response overruns because the extra data appears to be
# header data
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 |
async def on_PUT(self, origin, content, query, context, event_id):
# TODO(paul): assert that context/event_id parsed from path actually
# match those given in content
content = await self.handler.on_send_join_request(origin, content, context)
return 200, (200, content) | Class | 2 |
def __init__(self, method, uri, headers, bodyProducer, persistent=False):
"""
@param method: The HTTP method for this request, ex: b'GET', b'HEAD',
b'POST', etc.
@type method: L{bytes}
@param uri: The relative URI of the resource to request. For example,
C{b'/foo/bar?baz=quux'}.
@type uri: L{bytes}
@param headers: Headers to be sent to the server. It is important to
note that this object does not create any implicit headers. So it
is up to the HTTP Client to add required headers such as 'Host'.
@type headers: L{twisted.web.http_headers.Headers}
@param bodyProducer: L{None} or an L{IBodyProducer} provider which
produces the content body to send to the remote HTTP server.
@param persistent: Set to C{True} when you use HTTP persistent
connection, defaults to C{False}.
@type persistent: L{bool}
"""
self.method = method
self.uri = uri
self.headers = headers
self.bodyProducer = bodyProducer
self.persistent = persistent
self._parsedURI = None | Class | 2 |
def _handle_carbon_sent(self, msg):
self.xmpp.event('carbon_sent', msg) | Class | 2 |
def clean_code(self):
code = self.cleaned_data['code']
username = code.user.get_username()
user = authenticate(self.request, **{
get_user_model().USERNAME_FIELD: username,
'code': code.code,
})
if not user:
raise forms.ValidationError(
self.error_messages['invalid_code'],
code='invalid_code',
)
self.cleaned_data['user'] = user
return code | Base | 1 |
def field_names(ctx, rd, field):
'''
Get a list of all names for the specified field
Optional: ?library_id=<default library>
'''
db, library_id = get_library_data(ctx, rd)[:2]
return tuple(db.all_field_names(field)) | Base | 1 |
def from_yaml(self, content):
"""
Given some YAML data, returns a Python dictionary of the decoded data.
"""
if yaml is None:
raise ImproperlyConfigured("Usage of the YAML aspects requires yaml.")
return yaml.load(content) | Class | 2 |
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)]
mod = ast.Module(body)
with self.assertRaises(ValueError) as cm:
compile(mod, 'test', 'exec')
self.assertIn("invalid integer value: None", str(cm.exception)) | Base | 1 |
def extra_view_dispatch(request, view):
"""
Dispatch to an Xtheme extra view.
:param request: A request.
:type request: django.http.HttpRequest
:param view: View name.
:type view: str
:return: A response of some kind.
:rtype: django.http.HttpResponse
"""
theme = getattr(request, "theme", None) or get_current_theme(request.shop)
view_func = get_view_by_name(theme, view)
if not view_func:
msg = "Error! %s/%s: Not found." % (getattr(theme, "identifier", None), view)
return HttpResponseNotFound(msg)
return view_func(request) | Base | 1 |
def async_run(prog, args):
pid = os.fork()
if pid:
os.waitpid(pid, 0)
else:
dpid = os.fork()
if not dpid:
os.system(" ".join([prog] + args))
os._exit(0) | Base | 1 |
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 cookies(self, jar: RequestsCookieJar):
# <https://docs.python.org/3/library/cookielib.html#cookie-objects>
stored_attrs = ['value', 'path', 'secure', 'expires']
self['cookies'] = {}
for cookie in jar:
self['cookies'][cookie.name] = {
attname: getattr(cookie, attname)
for attname in stored_attrs
} | Class | 2 |
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
self.assertEqual(ast.dump(src, include_attributes=True),
"Module(body=[Expr(value=Call(func=Name(id='write', ctx=Load(), "
"lineno=1, col_offset=0, end_lineno=1, end_col_offset=5), "
"args=[Constant(value='spam', lineno=1, col_offset=6, end_lineno=1, "
"end_col_offset=12)], keywords=[], lineno=1, col_offset=0, end_lineno=1, "
"end_col_offset=13), lineno=1, col_offset=0, end_lineno=1, "
"end_col_offset=13), Expr(value=Call(func=Name(id='spam', ctx=Load(), "
"lineno=1, col_offset=0, end_lineno=1, end_col_offset=0), "
"args=[Constant(value='eggs', lineno=1, col_offset=0, end_lineno=1, "
"end_col_offset=0)], keywords=[], lineno=1, col_offset=0, end_lineno=1, "
"end_col_offset=0), lineno=1, col_offset=0, end_lineno=1, end_col_offset=0)])"
) | Base | 1 |
def init_app(app):
from redash.authentication import (
google_oauth,
saml_auth,
remote_user_auth,
ldap_auth,
)
login_manager.init_app(app)
login_manager.anonymous_user = models.AnonymousUser
login_manager.REMEMBER_COOKIE_DURATION = settings.REMEMBER_COOKIE_DURATION
@app.before_request
def extend_session():
session.permanent = True
app.permanent_session_lifetime = timedelta(seconds=settings.SESSION_EXPIRY_TIME)
from redash.security import csrf
for auth in [google_oauth, saml_auth, remote_user_auth, ldap_auth]:
blueprint = auth.blueprint
csrf.exempt(blueprint)
app.register_blueprint(blueprint)
user_logged_in.connect(log_user_logged_in)
login_manager.request_loader(request_loader) | Base | 1 |
def test_get_frontend_context_variables_xss(component):
# Set component.name to a potential XSS attack
component.name = '<a><style>@keyframes x{}</style><a style="animation-name:x" onanimationend="alert(1)"></a>'
frontend_context_variables = component.get_frontend_context_variables()
frontend_context_variables_dict = orjson.loads(frontend_context_variables)
assert len(frontend_context_variables_dict) == 1
assert (
frontend_context_variables_dict.get("name")
== "<a><style>@keyframes x{}</style><a style="animation-name:x" onanimationend="alert(1)"></a>"
) | Base | 1 |
def rename_all_authors(first_author, renamed_author, calibre_path="", localbook=None, gdrive=False):
# Create new_author_dir from parameter or from database
# Create new title_dir from database and add id
if first_author:
new_authordir = get_valid_filename(first_author, chars=96)
for r in renamed_author:
new_author = calibre_db.session.query(db.Authors).filter(db.Authors.name == r).first()
old_author_dir = get_valid_filename(r, chars=96)
new_author_rename_dir = get_valid_filename(new_author.name, chars=96)
if gdrive:
gFile = gd.getFileFromEbooksFolder(None, old_author_dir)
if gFile:
gd.moveGdriveFolderRemote(gFile, new_author_rename_dir)
else:
if os.path.isdir(os.path.join(calibre_path, old_author_dir)):
try:
old_author_path = os.path.join(calibre_path, old_author_dir)
new_author_path = os.path.join(calibre_path, new_author_rename_dir)
shutil.move(os.path.normcase(old_author_path), os.path.normcase(new_author_path))
except (OSError) as ex:
log.error("Rename author from: %s to %s: %s", old_author_path, new_author_path, ex)
log.debug(ex, exc_info=True)
return _("Rename author from: '%(src)s' to '%(dest)s' failed with error: %(error)s",
src=old_author_path, dest=new_author_path, error=str(ex))
else:
new_authordir = get_valid_filename(localbook.authors[0].name, chars=96)
return new_authordir | Base | 1 |
def verify(self, password, encoded):
algorithm, data = encoded.split('$', 1)
assert algorithm == self.algorithm
bcrypt = self._load_library()
# Hash the password prior to using bcrypt to prevent password
# truncation as described in #20138.
if self.digest is not None:
# Use binascii.hexlify() because a hex encoded bytestring is
# Unicode on Python 3.
password = binascii.hexlify(self.digest(force_bytes(password)).digest())
else:
password = force_bytes(password)
# Ensure that our data is a bytestring
data = force_bytes(data)
# force_bytes() necessary for py-bcrypt compatibility
hashpw = force_bytes(bcrypt.hashpw(password, data))
return constant_time_compare(data, hashpw) | Class | 2 |
def test_get_files_from_storage(self):
content = b"test_get_files_from_storage"
name = storage.save(
"tmp/s3file/test_get_files_from_storage", ContentFile(content)
)
files = S3FileMiddleware.get_files_from_storage(
[os.path.join(storage.aws_location, name)]
)
file = next(files)
assert file.read() == content | Base | 1 |
def insensitive_exact(field: Term, value: str) -> Criterion:
return Upper(field).eq(Upper(f"{value}")) | Base | 1 |
def _configuration_oauth_helper(to_save):
active_oauths = 0
reboot_required = False
for element in oauthblueprints:
if to_save["config_" + str(element['id']) + "_oauth_client_id"] != element['oauth_client_id'] \
or to_save["config_" + str(element['id']) + "_oauth_client_secret"] != element['oauth_client_secret']:
reboot_required = True
element['oauth_client_id'] = to_save["config_" + str(element['id']) + "_oauth_client_id"]
element['oauth_client_secret'] = to_save["config_" + str(element['id']) + "_oauth_client_secret"]
if to_save["config_" + str(element['id']) + "_oauth_client_id"] \
and to_save["config_" + str(element['id']) + "_oauth_client_secret"]:
active_oauths += 1
element["active"] = 1
else:
element["active"] = 0
ub.session.query(ub.OAuthProvider).filter(ub.OAuthProvider.id == element['id']).update(
{"oauth_client_id": to_save["config_" + str(element['id']) + "_oauth_client_id"],
"oauth_client_secret": to_save["config_" + str(element['id']) + "_oauth_client_secret"],
"active": element["active"]})
return reboot_required | Base | 1 |
def is_whitelisted(method):
# check if whitelisted
if frappe.session['user'] == 'Guest':
if (method not in frappe.guest_methods):
frappe.throw(_("Not permitted"), frappe.PermissionError)
if method not in frappe.xss_safe_methods:
# strictly sanitize form_dict
# escapes html characters like <> except for predefined tags like a, b, ul etc.
for key, value in frappe.form_dict.items():
if isinstance(value, string_types):
frappe.form_dict[key] = frappe.utils.sanitize_html(value)
else:
if not method in frappe.whitelisted:
frappe.throw(_("Not permitted"), frappe.PermissionError) | Base | 1 |
def get_search_results(self, term, offset=None, order=None, limit=None, allow_show_archived=False,
config_read_column=False, *join): | Base | 1 |
def basic_parser(xml):
return parse(BytesIO(xml)) | Base | 1 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.