Instruction stringlengths 362 7.83k | output_code stringlengths 1 945 |
|---|---|
Next line prediction: <|code_start|>
MAP = {
'C': ['C', 'C/C++ Header'],
'C++': ['C++', 'C/C++ Header'],
'Objective C': ['Objective C', 'C/C++ Header']
}
def run(project_id, repo_path, cursor, **options):
threshold = options.get('threshold', 0)
query = 'SELECT language FROM projects WHERE id = %... | _sloc = utilities.get_loc(repo_path) |
Given the following code snippet before the placeholder: <|code_start|>
class DatabaseTestCase(unittest.TestCase):
def setUp(self):
path = (
os.path.join(
os.path.abspath(
os.path.join(
os.path.dirname(os.path.realpath(__file__)),
... | self.database = database.Database(settings) |
Predict the next line after this snippet: <|code_start|> yield kwargs
def chunker(sweeper, num_chunks=10, confirm=True):
chunks = [ [] for _ in range(num_chunks) ]
print('computing chunks')
configs = [config for config in sweeper]
random.shuffle(configs, random.random)
for i, config in ... | target_mount = mount.MountLocal(local_dir=target_dir, mount_point=target_mount_dir) |
Given snippet: <|code_start|>def chunker(sweeper, num_chunks=10, confirm=True):
chunks = [ [] for _ in range(num_chunks) ]
print('computing chunks')
configs = [config for config in sweeper]
random.shuffle(configs, random.random)
for i, config in enumerate(configs):
chunks[i % num_chunks].app... | command = launch_api.make_python_command( |
Next line prediction: <|code_start|> print('num chunks: ', num_chunks)
print('chunk sizes: ', [len(chunk) for chunk in chunks])
print('total jobs: ', sum([len(chunk) for chunk in chunks]))
resp = 'y'
if confirm:
print('continue?(y/n)')
resp = str(input())
if resp == 'y':
... | with archive_builder.temp_archive_file() as archive_file: |
Using the snippet: <|code_start|> verbose=verbose,
use_nvidia_docker=use_gpu_image)
elif container_type == 'docker':
write_docker_hook(archive_dir, docker_image, mounts,
extra_flags=extra_container_fla... | builder = cmd_builder.CommandBuilder() |
Given snippet: <|code_start|>
if atk_check.result.success:
hit_event = events.HitEvent(**atk_event.kwargs)
hit_event.def_mod = atk_check.result.dos
event.dispatch(hit_event)
else:
event.dispatch(events.MessageEvent("You missed!"))
@event.event_handle... | dmg = random.roll_dice(n) + strength - m |
Here is a snippet: <|code_start|> self._name = name
self._key = key
self._attr = attr
self._parent = parent
@property
def name(self):
return self._name
@property
def key(self):
return self._key
@property
def attr(self):
return self._attr
... | class SkillTree(file_obj.FileObj): |
Next line prediction: <|code_start|>
class EntityManager(object):
"""The EntityManager is responsible for creating and maintaining Entities
It accomplishes its job by creating monotonically increasing Entity IDs, as
well as maintaining a list of all the Component managers which, in turn,
keep track of... | entity = Entity(self._next_eid) |
Given the following code snippet before the placeholder: <|code_start|> @property
def pc(self):
return self._pc
def create_entity(self):
"""Creates and returns a new Entity."""
entity = Entity(self._next_eid)
self._next_eid += 1
return entity
def destroy_entity(s... | if not isinstance(component, ComponentBase): |
Given the code snippet: <|code_start|> exist.
"""
# We can't iterate directly over the dict, as we're modifying it
ctypes = self._components.keys()
for ctype in ctypes:
# We already have logic to do this, so be DRY
self.remove_component(entity, ctype)
... | raise NoComponentForEntityError(entity, component_type) |
Continue the code snippet: <|code_start|> return self._pc
def create_entity(self):
"""Creates and returns a new Entity."""
entity = Entity(self._next_eid)
self._next_eid += 1
return entity
def destroy_entity(self, entity):
"""Remove an Entity and all its Componen... | raise NotAComponentError(component) |
Continue the code snippet: <|code_start|>
class FileObj(object):
def __init__(self, conf_file, obj_key=None):
self._data = {}
self._load_file(conf_file, obj_key)
def keys(self):
return self._data.keys()
<|code_end|>
. Use current file imports:
import json
from glob import glob
from... | def random(self, rand=None): |
Given the following code snippet before the placeholder: <|code_start|>
class Mob(file_obj.MultiFileObj):
def __init__(self):
super().__init__('data/mobs/*.json')
def _process_item(self, item):
<|code_end|>
, predict the next line using imports from the current file:
from roglick.engine import colors... | item['sprite']['color'] = getattr(colors, item['sprite']['color']) |
Predict the next line for this snippet: <|code_start|>
class Terrain(file_obj.FileObj):
def __init__(self, key):
super().__init__('data/terrain.json', key)
def _process_item(self, item):
<|code_end|>
with the help of current file imports:
from roglick.engine import colors,file_obj
and context from ... | item['color'] = getattr(colors, item['color']) |
Continue the code snippet: <|code_start|>
class PositionComponent(ComponentBase):
_properties = (('x', 0), ('y', 0))
class SpriteComponent(ComponentBase):
<|code_end|>
. Use current file imports:
from roglick.engine import colors
from roglick.engine.ecs import ComponentBase
and context (classes, functions, or ... | _properties = (('glyph', ' '), ('color', colors.white)) |
Given the code snippet: <|code_start|>
def smoothstep(a, b, x):
"""Basic S-curve interpolation function.
Based on reference implementation available at
https://en.wikipedia.org/wiki/Smoothstep
"""
x = clamp((x - a)/(b - a), 0.0, 1.0)
return x*x*(3 - 2*x)
def smootherstep(a, b, x):
"""Impr... | seed = random.get_int() |
Predict the next line after this snippet: <|code_start|>
def smoothstep(a, b, x):
"""Basic S-curve interpolation function.
Based on reference implementation available at
https://en.wikipedia.org/wiki/Smoothstep
"""
<|code_end|>
using the current file's imports:
from roglick.engine import random
from... | x = clamp((x - a)/(b - a), 0.0, 1.0) |
Next line prediction: <|code_start|> 'include_files': [],
'packages': ['asyncio'],
'excludes': ['tkinter']
},
'bdist_mac': {
'iconfile': 'icon-256.icns',
'bundle_name': 'Crazyflie client',
},
},
... | VERSION = get_version() |
Here is a snippet: <|code_start|>
class TestStagDesnityRatio(unittest.TestCase):
"""Unit tests for isentropic.stag_density_ratio"""
def test_still(self):
"""Check that the ratio is 1 when Mach=0."""
self.assertEqual(1, isentropic.stag_density_ratio(0, 1.2))
def test_sonic(self):
""... | m_molar = R_univ / 345.7 |
Using the snippet: <|code_start|>"""Unit tests for solid rocket motor equations."""
class TestBurnAreaRatio(unittest.TestCase):
"""Unit tests for solid.burn_area_ratio."""
def test_ex_12_3(self):
"""Test against example problem 12-3 from Rocket Propulsion Elements."""
gamma = 1.26 # Given ... | K = solid.burn_area_ratio(p_c, a, n, rho_solid, c_star) |
Given snippet: <|code_start|>def stag_density_ratio(M, gamma):
"""Stagnation density / static density ratio.
Arguments:
M (scalar): Mach number [units: dimensionless].
gamma (scalar): Heat capacity ratio [units: dimensionless].
Returns:
scalar: the stagnation density ratio :math:`\... | return ((2 * gamma) / (gamma - 1) * R_univ * T_1 / m_molar |
Predict the next line for this snippet: <|code_start|>"""Plot the thrust curve of a solid rocket motor with a cylindrical propellant grain."""
# Grain geometry (Clinder with circular port)
r_in = 0.15 # Grain inner radius [units: meter].
r_out = 0.20 # Grain outer radius [units: meter].
length = 1.0 # Grain... | t, p_c, F = solid.thrust_curve(A_b, x, A_t, A_e, p_a, a, n, rho_solid, c_star, gamma) |
Predict the next line after this snippet: <|code_start|>"""Plot C_F vs altitude."""
p_c = 10e6 # Chamber pressure [units: pascal]
gamma = 1.2 # Exhaust heat capacity ratio [units: dimensionless]
p_e_1 = 100e3 # Nozzle exit pressure, 1st stage [units: pascal]
<|code_end|>
using the current file's imports:
imp... | exp_ratio_1 = nozzle.er_from_p(p_c, p_e_1, gamma) # Nozzle expansion ratio [units: dimensionless] |
Given the code snippet: <|code_start|>"""Find the chamber pressure and thrust of a solid rocket motor."""
# Propellant properties
gamma = 1.26 # Exhaust gas ratio of specific heats [units: dimensionless].
rho_solid = 1510. # Solid propellant density [units: kilogram meter**-3].
n = 0.5 # Propellant burn rate ... | p_c = solid.chamber_pressure(A_b / A_t, a, n, rho_solid, c_star) |
Here is a snippet: <|code_start|>"""Find the chamber pressure and thrust of a solid rocket motor."""
# Propellant properties
gamma = 1.26 # Exhaust gas ratio of specific heats [units: dimensionless].
rho_solid = 1510. # Solid propellant density [units: kilogram meter**-3].
n = 0.5 # Propellant burn rate expon... | F = nozzle.thrust(A_t, p_c, p_e, gamma) |
Predict the next line after this snippet: <|code_start|> M[i] = y[1]
i += 1
choked = False
if not solver.successful() and abs(solver.y[1] - 1) < 1e-3:
choked = True
return (T_o, M, choked)
def main():
def f_f(x):
return 0
def f_q(x):
return 0
def f_A(x):
... | A_t = nozzle.throat_area(mdot, p_o_in, T_o_in, gamma, nozzle.R_univ / R) |
Here is a snippet: <|code_start|>
class TestStringMethods(unittest.TestCase):
def test_sample_8_3(self):
# Do sample problem 8-3 from Huzel and Huang.
stress = psi2pascal(38e3)
a = inch2meter(41.0)
b = inch2meter(29.4)
l_c = inch2meter(46.9)
E = psi2pascal(10.4e6)
... | self.assertAlmostEqual(0.8, ts.knuckle_factor(a / b), delta=0.02) |
Here is a snippet: <|code_start|>
class TestStringMethods(unittest.TestCase):
def test_sample_8_3(self):
# Do sample problem 8-3 from Huzel and Huang.
stress = psi2pascal(38e3)
<|code_end|>
. Write the next line using the current file imports:
import unittest
from proptools import tank_structure ... | a = inch2meter(41.0) |
Using the snippet: <|code_start|> self.assertAlmostEqual(inch2meter(0.183), ts.cylinder_thickness(
p_tf, a, stress, weld_eff), delta=inch2meter(0.005))
# Ellipse design factor E' = 4.56
self.assertAlmostEqual(4.56, ts.ellipse_design_factor(a / b), delta = 0.005)
# Oxidizer t... | self.assertAlmostEqual(lbf2newton(823900), ts.max_axial_load( |
Given the code snippet: <|code_start|>
class TestStringMethods(unittest.TestCase):
def test_sample_8_3(self):
# Do sample problem 8-3 from Huzel and Huang.
stress = psi2pascal(38e3)
a = inch2meter(41.0)
b = inch2meter(29.4)
l_c = inch2meter(46.9)
E = psi2pascal(10.4... | rho = 0.101 * lbm2kilogram(1) / inch2meter(1)**3 |
Using the snippet: <|code_start|>"""Unit tests for nozzle flow."""
class TestMassFlow(unittest.TestCase):
"""Unit tests for nozzle.mass_flow."""
def test_rpe_3_3(self):
"""Test against example problem 3-3 from Rocket Propulsion Elements."""
T_c = 2800.
gamma = 1.2
m_molar = R_... | m_dot = nozzle.mass_flow(A_t, p_c, T_c, gamma, m_molar) |
Predict the next line after this snippet: <|code_start|>"""Unit tests for nozzle flow."""
class TestMassFlow(unittest.TestCase):
"""Unit tests for nozzle.mass_flow."""
def test_rpe_3_3(self):
"""Test against example problem 3-3 from Rocket Propulsion Elements."""
T_c = 2800.
gamma = 1... | m_molar = R_univ / 360. |
Next line prediction: <|code_start|>"""Unit tests for convection models."""
class TestTaw(unittest.TestCase):
"""Unit tests for convection.adiabatic_wall_temperature"""
def test_ssme(self):
"""Test against the SSME example from 16.512 Lecture 7."""
# The T_aw given in the example (3400 K) doe... | h = convection.long_tube_coeff(mass_flux, D, c_p, mu, k) |
Given the following code snippet before the placeholder: <|code_start|>
class TestBartzSigmaHuzel(unittest.TestCase):
"""Unit tests for convection.bartz_sigma_huzel."""
def test_huzel_43_a1_throat(self):
"""Test against Huzel and Huang example problem 4-3, for the A-1 engine
at the throat."""
... | M = nozzle.mach_from_er(5., gamma) # Expansion ratio of 5 |
Predict the next line for this snippet: <|code_start|>"""Unit tests for valve flow."""
class TestValveGasCv(unittest.TestCase):
def test_methane_example(self):
"""Test the methane example from
http://www.idealvalve.com/pdf/Flow-Calculation-for-Gases.pdf
"""
# Setup
p_1 = 79... | m_dot = valve.scfh_to_m_dot(flow_scfh, m_molar) |
Based on the snippet: <|code_start|>"""Compute the expansion ratio for a given pressure ratio."""
p_c = 10e6 # Chamber pressure [units: pascal]
p_e = 100e3 # Exit pressure [units: pascal]
gamma = 1.2 # Exhaust heat capacity ratio [units: dimensionless]
# Solve for the expansion ratio [units: dimensionless]
<... | exp_ratio = nozzle.er_from_p(p_c, p_e, gamma) |
Next line prediction: <|code_start|>"""Compute the pressure ratio from a given expansion ratio."""
p_c = 10e6 # Chamber pressure [units: pascal]
gamma = 1.2 # Exhaust heat capacity ratio [units: dimensionless]
exp_ratio = 11.9 # Expansion ratio [units: dimensionless]
# Solve for the exit pressure [units: pas... | p_e = p_c * nozzle.pressure_from_er(exp_ratio, gamma) |
Predict the next line after this snippet: <|code_start|>"""Plot thrust vs ambient pressure."""
p_c = 10e6 # Chamber pressure [units: pascal]
p_e = 100e3 # Exit pressure [units: pascal]
p_a = np.linspace(0, 100e3) # Ambient pressure [units: pascal]
gamma = 1.2 # Exhaust heat capacity ratio [units: dimensionl... | F = nozzle.thrust(A_t, p_c, p_e, gamma, |
Predict the next line after this snippet: <|code_start|>"""Estimate exit velocity."""
# Declare engine design parameters
p_c = 10e6 # Chamber pressure [units: pascal]
p_e = 100e3 # Exit pressure [units: pascal]
gamma = 1.2 # Exhaust heat capacity ratio [units: dimensionless]
m_molar = 20e-3 # Exhaust molar... | v_e = isentropic.velocity(v_1=0, p_1=p_c, T_1=T_c, p_2=p_e, gamma=gamma, m_molar=m_molar) |
Given the following code snippet before the placeholder: <|code_start|>"""Film cooting example"""
T_aw = 3200 # Adiabatic wall temperature of core flow [units: kelvin].
T_f = 1600 # Film temperature [units: kelvin].
T_w = 700 # Wall temperature [units: kelvin].
x = np.linspace(0, 1) # Distance downstream ... | convection.film_efficiency(x_, D, m_dot_core, m_dot_film, |
Given snippet: <|code_start|>"""Effect of expansion ratio on thrust coefficient."""
p_c = 10e6 # Chamber pressure [units: pascal]
p_a = 100e3 # Ambient pressure [units: pascal]
gamma = 1.2 # Exhaust heat capacity ratio [units: dimensionless]
p_e = np.linspace(0.4 * p_a, 2 * p_a) # Exit pressure [units: pas... | exp_ratio = nozzle.er_from_p(p_c, p_e, gamma) |
Given snippet: <|code_start|>"""Generic electric propulsion design equations."""
from __future__ import division
def thrust(I_b, V_b, m_ion):
"""Thrust of an electric thruster.
Compute the ideal thrust of an electric thruster from the beam current and voltage,
assuming singly charged ions and no beam div... | return (2 * (m_ion / charge) * V_b)**0.5 * I_b |
Here is a snippet: <|code_start|> If only ``V_b`` and ``m_ion`` are provided, the ideal specific impulse will be computed.
If ``divergence_correction``, ``double_fraction``, or ``mass_utilization`` are provided,
the specific impulse will be reduced by the corresponding efficiency factors.
Reference: Goe... | I_sp_ideal = 1 / g * (2 * (charge / m_ion) * V_b)**0.5 |
Continue the code snippet: <|code_start|> gamma: working gas ratio of specific heats [units: none].
c_p: working gas heat capacity at const pressure
[units: joule kilogram**-1 kelvin**-1].
'''
# Turbine specific enthalpy drop [units: joule kilogram**-1]
dh_turb_ideal = turbine_ent... | C_f = nozzle.thrust_coef(p_c=p_te, p_e=p_ne, gamma=gamma) |
Using the snippet: <|code_start|>"""Ideal characteristic velocity."""
gamma = 1.2 # Exhaust heat capacity ratio [units: dimensionless]
m_molar = 20e-3 # Exhaust molar mass [units: kilogram mole**1]
T_c = 3000. # Chamber temperature [units: kelvin]
# Compute the characteristic velocity [units: meter second**-... | c_star = nozzle.c_star(gamma, m_molar, T_c) |
Given the following code snippet before the placeholder: <|code_start|>"""Estimate specific impulse, thrust and mass flow."""
# Declare engine design parameters
p_c = 10e6 # Chamber pressure [units: pascal]
p_e = 100e3 # Exit pressure [units: pascal]
gamma = 1.2 # Exhaust heat capacity ratio [units: dimension... | C_f = nozzle.thrust_coef(p_c, p_e, gamma) # Thrust coefficient [units: dimensionless] |
Given the code snippet: <|code_start|>"""Plot thrust vs chmaber pressure."""
p_c = np.linspace(1e6, 20e6) # Chamber pressure [units: pascal]
p_e = 100e3 # Exit pressure [units: pascal]
p_a = 100e3 # Ambient pressure [units: pascal]
gamma = 1.2 # Exhaust heat capacity ratio [units: dimensionless]
A_t = np.... | F = nozzle.thrust(A_t, p_c, p_e, gamma) |
Given snippet: <|code_start|> c_star (scalar): Propellant combustion characteristic velocity [units: meter second**-1].
Returns:
scalar: Ratio of burning area to throat area, :math:`K = A_b/A_t` [units: dimensionless].
"""
return p_c**(1 - n) / (rho_solid * a * c_star)
def burn_and_throat_... | C_F = nozzle.thrust_coef(p_c, p_e, gamma) |
Here is a snippet: <|code_start|>"""Check that the nozzle is choked and find the mass flow."""
# Declare engine design parameters
p_c = 10e6 # Chamber pressure [units: pascal]
p_e = 100e3 # Exit pressure [units: pascal]
gamma = 1.2 # Exhaust heat capacity ratio [units: dimensionless]
m_molar = 20e-3 # Exha... | if nozzle.is_choked(p_c, p_e, gamma): |
Given snippet: <|code_start|>try:
except ImportError:
logger = my_logger.get_logger('FormulaCalcTest')
class FormulaCalcTest(asynctest.TestCase):
loop = None # make pycharm happy
def setUp(self):
super(FormulaCalcTest, self).setUp()
self.redis_client = redis.StrictRedis(db=config.getint('RE... | mock_data.generate() |
Here is a snippet: <|code_start|> config.getint('REDIS', 'port', fallback=6379)),
db=config.getint('REDIS', 'db', fallback=1))
sub_client = await aioredis.create_redis((config.get('REDIS', 'host', fallback='127.0.0... | mock_data.generate() |
Using the snippet: <|code_start|> sub_client = await aioredis.create_redis((config.get('REDIS', 'host', fallback='127.0.0.1'),
config.getint('REDIS', 'port', fallback=6379)),
db=config.getint('REDIS', 'db', fallbac... | self.server_list = iec104device.create_servers(self.loop) |
Predict the next line after this snippet: <|code_start|> config.getint('REDIS', 'port', fallback=6379)),
db=config.getint('REDIS', 'db', fallback=1))
res = await sub_client.subscribe('channel:foo')
ch1 = re... | self.api_server = api_server.APIServer(io_loop=self.loop, port=8080) |
Using the snippet: <|code_start|> {'username': '',
'password': password},
# Invalid password
{'username': user_id,
'password': None}
]
for data in bad_data:
self.api.post("/sessions",
data=data,
... | verify_password({'password': hashed}, "some_pw") |
Using the snippet: <|code_start|># -*- coding: utf-8 -*-
#
# license: AGPLv3, see LICENSE for details. In addition we strongly encourage
# you to buy us beer if we meet and you like the software.
"""Sentry integration tests."""
# Get test dsn from environment
SENTRY_DSN = getenv('SENTRY_TEST_DSN')
class... | @skip_if_false(SENTRY_DSN, "Sentry test requires environment variable " |
Given the following code snippet before the placeholder: <|code_start|>Send emails to users when they have a new entry on the blacklist or one of their
entries get resolved/deleted.
"""
def _get_email(item):
"""Retrieve the user email for a blacklist entry."""
id_field = current_app.config['ID_FIELD']
... | mail(email, |
Continue the code snippet: <|code_start|># -*- coding: utf-8 -*-
#
# license: AGPLv3, see LICENSE for details. In addition we strongly encourage
# you to buy us beer if we meet and you like the software.
"""Logic to send emails on blacklist changes.
Send emails to users when they have a new entry on the black... | @schedulable |
Based on the snippet: <|code_start|> return # Entry was patched to last indefinitely, so no mail to send.
if _item['end_time'].replace(tzinfo=None) != item['end_time']:
return # Entry was edited, so this is outdated.
email = _get_email(_item)
fields = {'reason': _item['reason']}
mail(e... | schedule_task(item['end_time'], send_removed_mail, item) |
Here is a snippet: <|code_start|> u"male" if int(data['swissEduPersonGender']) == 1 else u"female"
# See file docstring for explanation of `deparmentNumber` field
# In some rare cases, the departmentNumber field is either empty
# or missing -> normalize to empty string
department_info = next(ite... | with admin_permissions(): |
Here is a snippet: <|code_start|> def create_user_lookup_filter(self, user_id):
"""Create a filter for item lookup.
Not a member: Can see only himself
A Member: Can see everyone
Note: Users will only see complete info for themselves.
But excluding other fields will be done i... | @on_post_hook |
Next line prediction: <|code_start|> 'nullable': False,
'unique_combination': ['event'],
'required': True,
'excludes': 'email',
},
'additional_fields': {
"description": "Additional signup information, must match the "... | 'regex': EMAIL_REGEX, |
Given the following code snippet before the placeholder: <|code_start|> },
"required": ["SBB_Abo"]
}
```
> Currently, we only support JSON Schema
> [Draft 4](https://json-schema.org/specification-links.html#draft-4) and
> additionally require `additionalProperties` to be `false`.
An event can now provide t... | 'authentication': EventAuth, |
Using the snippet: <|code_start|> 'or unconfirmed email signups.',
'readonly': True,
'type': 'integer'
},
'moderator': {
'description': '`_id` of a user which will be the event '
'modera... | 'authentication': EventSignupAuth, |
Based on the snippet: <|code_start|> """Read permission allows get, but no writing."""
key = self.new_object("apikeys", permissions={'apikeys': 'read'})
token = key['token']
item_url = '/apikeys/%s' % key['_id']
self.api.get('/apikeys', token=token, status_code=200)
self.... | class ApiKeyModelTests(WebTestNoAuth): |
Given the following code snippet before the placeholder: <|code_start|> event = self.new_object('events', spots=1,
selection_strategy='fcfs')
user1 = self.new_object('users')
user2 = self.new_object('users')
user1_signup = self.api.post('/eventsignups', d... | class EventsignupQueueTest(WebTestNoAuth): |
Predict the next line for this snippet: <|code_start|>"""Delete cascading system.
This adds an option 'cascade_delete' to data_relations in the schema. If it is
set to true, then deleting the referenced object will also delete the
referencing object. If false, the reference will be set to NULL, when the
referenced obj... | with admin_permissions(): |
Based on the snippet: <|code_start|> 'not_patchable_unless_admin': True,
'nullable': True,
'default': None,
'example': 'itet'
},
'gender': {
'type': 'string',
'allowed': ['male', 'female'],
... | 'regex': EMAIL_REGEX, |
Given the following code snippet before the placeholder: <|code_start|><br />
## Security
In addition to the usual
[permissions](#section/Authentication-and-Authorization/Authorization),
some further constraints are in place:
- Passwords are salted and hashed, and they are *never* returned by the API,
not even to ... | 'authentication': UserAuth, |
Predict the next line after this snippet: <|code_start|>(this would grant the API key rights to see all users and see
and modify/delete all sessions).
> **IMPORTANT: The most powerful permission**
>
> If you grant an API key `readwrite` permissions to API keys, this key will
> be able to create new API keys with any p... | 'authentication': AdminOnlyAuth, |
Using the snippet: <|code_start|> 'example': 'Xfh3abXzLoezpwO9WT7oRw',
},
'permissions': {
'description': 'The permissions the API key grants. The value '
'is an object with resources as keys and the '
'... | register_domain(app, apikeydomain) |
Based on the snippet: <|code_start|>Contains model for blacklist.
"""
blacklist_description = ("""
People normally get blacklisted if they don't appear to an event they signed up
for, but other cases could be possible (Bad behaviour, etc). Once on the
blacklist, they shouldn't be able to sign up for any event until t... | 'authentication': BlacklistAuth, |
Next line prediction: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# license: AGPLv3, see LICENSE for details. In addition we strongly encourage
# you to buy us beer if we meet and you like the software.
""" Test that sessions get cleaned up after enough time passed. """
class TestSession... | run_scheduled_tasks() |
Given the code snippet: <|code_start|> response = make_response(render_template("loginpage.html",
client_id=client_id,
user=user,
error_msg=error_msg))
response.set_cookie('token... | 'authentication': AdminOnlyAuth, |
Given snippet: <|code_start|> client = db.find_one({'client_id': client_id})
if not client:
abort(422, 'Unknown client_id. Please contact the author of the page '
'that sent you here.')
if not redirect_uri:
redirect_uri = client['redirect_uri']
if not redirect_uri.sta... | authenticate_token(token) |
Continue the code snippet: <|code_start|>def _append_url_params(url, **params):
"""Helper to add addtional parameters to an url query string."""
if '?' not in url:
url += '?'
return '%s&%s' % (url, urlencode(params))
def validate_oauth_authorization_request(response_type, client_id,
... | 'regex': REDIRECT_URI_REGEX |
Continue the code snippet: <|code_start|>
'type': 'string',
'required': True,
'nullable': False,
'empty': False,
'unique': True,
'no_html': True,
'maxlength': 100,
},
'redirect_uri': {... | register_domain(app, oauthclients_domain) |
Given the following code snippet before the placeholder: <|code_start|> },
'uploader': {
'description': 'The user who uploaded the files (read-only).',
'example': 'ea059fa90df4703316da25d8',
'type': 'objectid',
'data_relation': {
... | 'example': DEPARTMENT_LIST[0], |
Continue the code snippet: <|code_start|> Prof. Okay: 5
...
lecture:
...
...
```
The summary is only computed for documents matching the current `where` query,
e.g. when searching for ITET documents, only professors related to ITET
documents will show up in the summary.
""")
class Stud... | 'authentication': StudydocsAuth, |
Based on the snippet: <|code_start|># -*- coding: utf-8 -*-
#
# license: AGPLv3, see LICENSE for details. In addition we strongly encourage
# you to buy us beer if we meet and you like the software.
"""Tests for purchases module"""
pdfpath = join(dirname(__file__), "../fixtures", 'test.pdf')
lenapath = join... | time_end = (datetime.utcnow() + timedelta(days=2)).strftime(DATE_FORMAT) |
Here is a snippet: <|code_start|> run_scheduled_tasks()
self.assertTrue(CronTest.has_run)
self.assertEqual(CronTest.received_arg, "arg")
def test_periodic_func(self):
with self.app.app_context(), freeze_time(
"2016-01-01 00:00:00") as frozen_time:
... | cron.periodic_functions.remove(periodic_function) |
Next line prediction: <|code_start|> "2016-01-01 00:00:00") as frozen_time:
# We need to define the function in here to make sure the first
# call is scheduled to the frozen time
@periodic(timedelta(minutes=5), "arg")
def periodic_function(arg):
... | with self.assertRaises(NotSchedulable): |
Given snippet: <|code_start|>
super().setUp()
def test_scheduled_function_gets_called(self):
with self.app.app_context(), freeze_time(
"2016-01-01 00:00:00") as frozen_time:
@schedulable
def scheduled_function(arg):
CronTest.has_run = True
... | @periodic(timedelta(minutes=5), "arg") |
Continue the code snippet: <|code_start|>""" Test scheduler """
class CronTest(WebTestNoAuth):
has_run = False
received_arg = None
run_count = 0
def setUp(self):
CronTest.has_run = False
CronTest.received_arg = None
CronTest.run_count = 0
super().setUp()
def t... | run_scheduled_tasks() |
Given the code snippet: <|code_start|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# license: AGPLv3, see LICENSE for details. In addition we strongly encourage
# you to buy us beer if we meet and you like the software.
""" Test scheduler """
class CronTest(WebTestNoAuth):
has_run = False
rece... | @schedulable |
Given snippet: <|code_start|> # Check the function has run and got the correct argument
self.assertEqual(CronTest.run_count, 1)
self.assertEqual(CronTest.received_arg, "arg")
# Now check that it is called at correct intervals
for _ in range(0, 32):
... | schedule_once_soon(inc) |
Continue the code snippet: <|code_start|>#
# license: AGPLv3, see LICENSE for details. In addition we strongly encourage
# you to buy us beer if we meet and you like the software.
""" Test scheduler """
class CronTest(WebTestNoAuth):
has_run = False
received_arg = None
run_count = 0
def ... | schedule_task(datetime(2016, 1, 1, 1, 0, 0), |
Based on the snippet: <|code_start|>
@schedulable
def inc():
CronTest.run_count += 1
schedule_once_soon(inc)
print("nmow")
schedule_once_soon(inc)
run_scheduled_tasks()
self.assertEqual(CronTest.run_count, 1)
def... | update_scheduled_task(datetime(2016, 1, 1, 3, 20, 0), |
Next line prediction: <|code_start|>
# Check mail
mail = self.app.test_mails[1]
self.assertEqual(mail['receivers'], 'bla@bla.bl')
expected_text = (
"Congratulations, your blacklist entry with the following reason "
"has been removed:\n\nTest1\n\nBest Regards,\nAMI... | run_scheduled_tasks() |
Given the code snippet: <|code_start|> database. We accept all registered users instantly, others need to click the
confirmation link first"""
for item in items:
if item.get('user', None) is None:
item['confirmed'] = False
else:
item['confirmed'] = True
@email_bluepr... | update_waiting_list(signup['event']) |
Using the snippet: <|code_start|># license: AGPLv3, see LICENSE for details. In addition we strongly encourage
# you to buy us beer if we meet and you like the software.
"""Email confirmation logic.
Needed when external users want to sign up for public events or users want to
sign off via links.
"""
email_b... | s = URLSafeSerializer(get_token_secret()) |
Next line prediction: <|code_start|>"""A command line interface for AMIVApi."""
try:
except ImportError:
bjoern = False
@group()
def cli():
"""Manage amivapi."""
config_option = option("--config",
type=Path(exists=True, dir_okay=False, readable=True),
help="u... | app = create_app(config_file=config) |
Predict the next line after this snippet: <|code_start|>
2. Create new mailing list files.
For every group, we call the update_group function for this
"""
app = create_app(config_file=config)
directory = app.config.get('MAILING_LIST_DIR')
prefix = app.config['MAILING_LIST_FILE_PREFIX']
if ... | run_scheduled_tasks() |
Given the following code snippet before the placeholder: <|code_start|> run_cron(app)
execution_time = dt.utcnow() - checkpoint
echo('Tasks executed, total execution time: %.3f seconds.'
% execution_time.total_seconds())
if execution_time > interval:
... | res = ldap.sync_all() |
Given snippet: <|code_start|>
@cli.command()
@config_option
def recreate_mailing_lists(config):
"""(Re-)create mailing lists for all groups.
1. Delete all mailing list files.
2. Create new mailing list files.
For every group, we call the update_group function for this
"""
app = create_app(con... | updated_group(g, g) # Use group as update and original |
Given the code snippet: <|code_start|> SECRET_KEY: {'$exists': True}
})
self.assertIsNone(db_item)
def test_create_secret(self):
"""Test that init_secret creates a secret token & adds it to the db."""
super().setUp()
with self.app.app_context():
... | create_token_secret_on_startup(self.app) |
Predict the next line after this snippet: <|code_start|> self.assertIsNone(db_item)
def test_create_secret(self):
"""Test that init_secret creates a secret token & adds it to the db."""
super().setUp()
with self.app.app_context():
db_item = self.db['config'].find_one({
... | self.assertEqual(get_token_secret(), old_secret) |
Predict the next line for this snippet: <|code_start|> return
raise BadFixtureException("Requested eventsignup creation, but no "
"unique user/event combination is "
"available anymore. Parsed object: %s"
... | if definition['regex'] == EMAIL_REGEX: |
Given snippet: <|code_start|> """Add title to JobOffers to make them valid. """
obj.setdefault(
'title_de',
self.create_random_value(schema['title_de']))
obj.setdefault(
'description_de',
self.create_random_value(schema['description_de']))
def ... | elif definition['regex'] == REDIRECT_URI_REGEX: |
Given the code snippet: <|code_start|> }
],
'events': [
{
'title': 'mytestevent'
}
]
})
"""
added_objects = []
# Check that all resources are valid
fixture_resources = set(fixt... | with admin_permissions(), self.writeable_id(schema): |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.