text_prompt
stringlengths 157
13.1k
| code_prompt
stringlengths 7
19.8k
⌀ |
---|---|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_if_changed(self, resource):
"""Add resource if change is not None else ChangeTypeError."""
|
if (resource.change is not None):
self.resources.append(resource)
else:
raise ChangeTypeError(resource.change)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add(self, resource):
"""Add a resource change or an iterable collection of them. Allows multiple resource_change objects for the same resource (ie. URI) and preserves the order of addition. """
|
if isinstance(resource, collections.Iterable):
for r in resource:
self.add_if_changed(r)
else:
self.add_if_changed(resource)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_changed_resources(self, resources, change=None):
"""Add items from a ResourceContainer resources. If change is specified then the attribute is set in the Resource objects created. """
|
for resource in resources:
rc = Resource(resource=resource, change=change)
self.add(rc)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def run(self, lines):
""" Match and store Fenced Code Blocks in the HtmlStash. """
|
text = "\n".join(lines)
while 1:
m = FENCED_BLOCK_RE.search(text)
if not m:
break
lang = m.group('lang')
linenums = bool(m.group('linenums'))
html = highlight_syntax(m.group('code'), lang, linenums=linenums)
placeholder = self.markdown.htmlStash.store(html, safe=True)
text = '{}\n{}\n{}'.format(
text[:m.start()],
placeholder,
text[m.end():]
)
return text.split("\n")
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def initialize_hashes(self):
"""Create new hashlib objects for each hash we are going to calculate."""
|
if ('md5' in self.hashes):
self.md5_calc = hashlib.md5()
if ('sha-1' in self.hashes):
self.sha1_calc = hashlib.sha1()
if ('sha-256' in self.hashes):
self.sha256_calc = hashlib.sha256()
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def compute_for_file(self, file, block_size=2**14):
"""Compute hash digests for a file. Calculate the hashes based on one read through the file. Optional block_size parameter controls memory used to do calculations. This should be a multiple of 128 bytes. """
|
self.initialize_hashes()
f = open(file, 'rb')
while True:
data = f.read(block_size)
if not data:
break
if (self.md5_calc is not None):
self.md5_calc.update(data)
if (self.sha1_calc is not None):
self.sha1_calc.update(data)
if (self.sha256_calc is not None):
self.sha256_calc.update(data)
f.close()
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pre_save(self, model_instance, add):
"""Remove dashes, spaces, and convert isbn to uppercase before saving when clean_isbn is enabled"""
|
value = getattr(model_instance, self.attname)
if self.clean_isbn and value not in EMPTY_VALUES:
cleaned_isbn = value.replace(' ', '').replace('-', '').upper()
setattr(model_instance, self.attname, cleaned_isbn)
return super(ISBNField, self).pre_save(model_instance, add)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def update(self, dt):
""" Updates game engine each tick """
|
# if not playing dont update model
if self.win_status != 'undecided':
return
# Step known time for agents
if self.force_fps > 0:
dt = 1 / self.force_fps
# update target
self.player.update_rotation(dt, self.buttons)
# Get planned update
newVel = self.player.do_move(dt, self.buttons)
# Position collision rects
oldRect = self.player.get_rect()
newRect = oldRect.copy()
oldPos = self.player.cshape.center
remaining_dt = dt
newPos = oldPos.copy()
# So WorldLayer is given `bumped` attributes at startup.
if dt == 0:
newVel.x, newVel.y = self.collide_map(self.map_layer, oldRect, oldRect, newVel.x, newVel.y)
# Get planned velocity result
def get_new_rect(pos, width, height, dt, velocity):
targetPos = pos + dt * velocity
x = targetPos.x - width/2
y = targetPos.y - height/2
return x, y
while remaining_dt > 1.e-6:
#print('remaining_dt', remaining_dt)
newRect.x, newRect.y = get_new_rect(oldPos, newRect.width, newRect.height, remaining_dt, newVel)
newVel.x, newVel.y = self.collide_map(self.map_layer, oldRect, newRect, newVel.x, newVel.y)
remaining_dt -= self.consumed_dt
newRect.x, newRect.y = get_new_rect(oldPos, newRect.width, newRect.height, dt, newVel)
# Ensure player can't escape borders
border = False
if newRect.top > self.height:
newRect.top = self.height
border = True
if newRect.bottom < self.map_layer.th:
newRect.bottom = self.map_layer.th
border = True
if newRect.left < self.map_layer.th:
newRect.left = self.map_layer.th
border = True
if newRect.right > self.width:
newRect.right = self.width
border = True
newPos = self.player.cshape.center
newPos.x, newPos.y = newRect.center
self.player.velocity = newVel
self.player.update_center(newPos)
# Collision detected
if border or self.bumped_x or self.bumped_y:
#print('bumped')
self.reward_wall()
# In WorldLayer so we can access map
self.update_visited()
self.update_sensors()
self.reward_battery()
self.reward_proximity()
# TODO: Display messages for humans at some point
#if self.player.game_over:
# self.level_losed()
self.update_collisions()
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def update_visited(self):
""" Updates exploration map visited status """
|
assert isinstance(self.player.cshape.center, eu.Vector2)
pos = self.player.cshape.center
# Helper function
def set_visited(layer, cell):
if cell and not cell.properties.get('visited') and cell.tile and cell.tile.id > 0:
cell.properties['visited'] = True
self.reward_explore()
# TODO: Decouple into view rendering
# Change colour of visited cells
key = layer.get_key_at_pixel(cell.x, cell.y)
#layer.set_cell_color(key[0], key[1], [155,155,155])
layer.set_cell_opacity(key[0], key[1], 255*0.8)
# End Helper
# Get the current tile under player
current = self.visit_layer.get_at_pixel(pos.x, pos.y)
if current:
# In spawn square
if current == self.visit_layer.get_at_pixel(self.spawn.x, self.spawn.y):
self.reward_goal()
# Only record/reward exploration when battery is above 50%
#if self.player.stats['battery'] > 50:
set_visited(self.visit_layer, current)
neighbours = self.visit_layer.get_neighbors(current)
for cell in neighbours:
neighbour = neighbours[cell]
set_visited(self.visit_layer, neighbour)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def update_sensors(self):
""" Check path for each sensor and record wall proximity """
|
assert isinstance(self.player.cshape.center, eu.Vector2)
pos = self.player.cshape.center
a = math.radians(self.player.rotation)
for sensor in self.player.sensors:
sensor.sensed_type = 'wall'
rad = a + sensor.angle
dis = min(self.distance_to_tile(pos, rad), sensor.max_range)
# Keep state of sensed range, `dis` is from center
sensor.proximity = dis - self.player.radius
# Check for collisions with items
# List of items within sensor range, do for each sensor's range
if self.mode['items'] and len(self.mode['items']) > 0:
nears = self.collman.ranked_objs_near(self.player, sensor.max_range)
for near in nears:
other, other_dis = near
# Distances are from edge to edge see #2
other_dis += self.player.radius
# Skip if further
if other_dis > dis:
continue
# Determine if within `fov`
other_rad = math.atan2(other.x - self.player.x, other.y - self.player.y)
# Round to bearing within one revolution
other_rad = other_rad % (math.pi*2)
round_rad = rad % (math.pi*2)
if abs(other_rad - round_rad) < (sensor.fov/2):
sensor.proximity = other_dis - self.player.radius
sensor.sensed_type = other.btype
dis = other_dis
# Redirect sensor lines
# TODO: Decouple into view rendering
end = pos.copy()
end.x += math.sin(rad) * dis
end.y += math.cos(rad) * dis
sensor.line.start = pos
sensor.line.end = end
sensor.line.color = self.player.palette[sensor.sensed_type] + (int(255*0.5),)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_state(self):
""" Create state from sensors and battery """
|
# Include battery level in state
battery = self.player.stats['battery']/100
# Create observation from sensor proximities
# TODO: Have state persist, then update columns by `sensed_type`
# Multi-channel; detecting `items`
if len(self.mode['items']) > 0:
observation = []
for sensor in self.player.sensors:
col = []
# Always include range in channel 0
col.append(sensor.proximity_norm())
for item_type in self.mode['items']:
if sensor.sensed_type == item_type:
col.append(sensor.proximity_norm())
else:
# Default to 1 (`max_range/max_range`)
col.append(1)
observation.append(col)
if 'battery' in self.mode:
observation.append([battery,1,1])
# Single-channel; walls only
else:
observation = [o.proximity_norm() for o in self.player.sensors]
if 'battery' in self.mode:
observation.append(battery)
return observation
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def update_rotation(self, dt, buttons):
""" Updates rotation and impulse direction """
|
assert isinstance(buttons, dict)
ma = buttons['right'] - buttons['left']
if ma != 0:
self.stats['battery'] -= self.battery_use['angular']
self.rotation += ma * dt * self.angular_velocity
# Redirect velocity in new direction
a = math.radians(self.rotation)
self.impulse_dir = eu.Vector2(math.sin(a), math.cos(a))
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
|
def read(*paths):
'''read and return txt content of file'''
with open(os.path.join(os.path.dirname(__file__), *paths)) as fp:
return fp.read()
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def compile_excludes(self):
"""Compile a set of regexps for files to be exlcuded from scans."""
|
self.compiled_exclude_files = []
for pattern in self.exclude_files:
try:
self.compiled_exclude_files.append(re.compile(pattern))
except re.error as e:
raise ValueError(
"Bad python regex in exclude '%s': %s" % (pattern, str(e)))
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def exclude_file(self, file):
"""True if file should be exclude based on name pattern."""
|
for pattern in self.compiled_exclude_files:
if (pattern.match(file)):
return(True)
return(False)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def from_disk(self, resource_list=None, paths=None):
"""Create or extend resource_list with resources from disk scan. Assumes very simple disk path to URL mapping (in self.mapping):
chop path and replace with url_path. Returns the new or extended ResourceList object. If a resource_list is specified then items are added to that rather than creating a new one. If paths is specified then these are used instead of the set of local paths in self.mapping. Example usage with mapping start paths: mapper=Mapper('http://example.org/path','/path/to/files') rlb = ResourceListBuilder(mapper=mapper) m = rlb.from_disk() Example usage with explicit paths: mapper=Mapper('http://example.org/path','/path/to/files') rlb = ResourceListBuilder(mapper=mapper) m = rlb.from_disk(paths=['/path/to/files/a','/path/to/files/b']) """
|
num = 0
# Either use resource_list passed in or make a new one
if (resource_list is None):
resource_list = ResourceList()
# Compile exclude pattern matches
self.compile_excludes()
# Work out start paths from map if not explicitly specified
if (paths is None):
paths = []
for map in self.mapper.mappings:
paths.append(map.dst_path)
# Set start time unless already set (perhaps because building in
# chunks)
if (resource_list.md_at is None):
resource_list.md_at = datetime_to_str()
# Run for each map in the mappings
for path in paths:
self.logger.info("Scanning disk from %s" % (path))
self.from_disk_add_path(path=path, resource_list=resource_list)
# Set end time
resource_list.md_completed = datetime_to_str()
return(resource_list)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def from_disk_add_path(self, path=None, resource_list=None):
"""Add to resource_list with resources from disk scan starting at path."""
|
# sanity
if (path is None or resource_list is None or self.mapper is None):
raise ValueError("Must specify path, resource_list and mapper")
# is path a directory or a file? for each file: create Resource object,
# add, increment counter
if (sys.version_info < (3, 0)):
path = path.decode('utf-8')
if os.path.isdir(path):
num_files = 0
for dirpath, dirs, files in os.walk(path, topdown=True):
for file_in_dirpath in files:
num_files += 1
if (num_files % 50000 == 0):
self.logger.info(
"ResourceListBuilder.from_disk_add_path: %d files..." % (num_files))
self.add_file(resource_list=resource_list,
dir=dirpath, file=file_in_dirpath)
# prune list of dirs based on self.exclude_dirs
for exclude in self.exclude_dirs:
if exclude in dirs:
self.logger.debug("Excluding dir %s" % (exclude))
dirs.remove(exclude)
else:
# single file
self.add_file(resource_list=resource_list, file=path)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_file(self, resource_list=None, dir=None, file=None):
"""Add a single file to resource_list. Follows object settings of set_path, set_hashes and set_length. """
|
try:
if self.exclude_file(file):
self.logger.debug("Excluding file %s" % (file))
return
# get abs filename and also URL
if (dir is not None):
file = os.path.join(dir, file)
if (not os.path.isfile(file) or not (
self.include_symlinks or not os.path.islink(file))):
return
uri = self.mapper.dst_to_src(file)
if (uri is None):
raise Exception("Internal error, mapping failed")
file_stat = os.stat(file)
except OSError as e:
sys.stderr.write("Ignoring file %s (error: %s)" % (file, str(e)))
return
timestamp = file_stat.st_mtime # UTC
r = Resource(uri=uri, timestamp=timestamp)
if (self.set_path):
# add full local path
r.path = file
if (self.set_hashes):
hasher = Hashes(self.set_hashes, file)
if ('md5' in self.set_hashes):
r.md5 = hasher.md5
if ('sha-1' in self.set_hashes):
r.sha1 = hasher.sha1
if ('sha-256' in self.set_hashes):
r.sha256 = hasher.sha256
if (self.set_length):
# add length
r.length = file_stat.st_size
resource_list.add(r)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
|
def has_file_extension(filepath, ext_required):
'''Assert that a filepath has the required file extension
:param filepath: string filepath presumably containing a file extension
:param ext_required: the expected file extension
examples: ".pdf", ".html", ".tex"
'''
ext = os.path.splitext(filepath)[-1]
if ext != ext_required:
msg_tmpl = "The extension for {}, which is {}, does not equal {}"
msg_format = msg_tmpl.format(filepath, ext, ext_required)
raise ValueError(msg_format)
return True
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
|
def is_binary(system_binary_str):
'''Assert that a string represents a system binary
Return true if a string represents a system binary
Raise TypeError if the system_binary_str is not a string
Raise ValueError if the system_binary_str is not a system binary
:param system_binary_str: STR string representing a system binary
'''
if not isinstance(system_binary_str, str):
raise TypeError("{} must be of type STR".format(system_binary_str))
binary_str = shutil.which(system_binary_str)
if not binary_str:
msg = "{} is not valid system binary".format(system_binary_str)
raise ValueError(msg)
return True
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
|
def list_is_type(ls, t):
'''Assert that a list contains only elements of type t
Return True if list contains elements of type t
Raise TypeError if t is not a class
Raise TypeError if ls is not a list
Raise TypeError if ls contains non-t elements
:param ls: LIST
:param t: python class
'''
if not isclass(t):
raise TypeError("{} is not a class".format(t))
elif not isinstance(ls, list):
raise TypeError("{} is not a list".format(ls))
else:
ls_bad_types = [i for i in ls if not isinstance(i, t)]
if len(ls_bad_types) > 0:
raise TypeError("{} are not {}".format(ls_bad_types, t))
return True
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def require_api_auth(allow_anonymous=False):
"""Decorator to require API authentication using OAuth token. :param allow_anonymous: Allow access without OAuth token (default: ``False``). """
|
def wrapper(f):
"""Wrap function with oauth require decorator."""
f_oauth_required = oauth2.require_oauth()(f)
@wraps(f)
def decorated(*args, **kwargs):
"""Require OAuth 2.0 Authentication."""
if not hasattr(current_user, 'login_via_oauth2'):
if not current_user.is_authenticated:
if allow_anonymous:
return f(*args, **kwargs)
abort(401)
if current_app.config['ACCOUNTS_JWT_ENABLE']:
# Verify the token
current_oauth2server.jwt_veryfication_factory(
request.headers)
# fully logged in with normal session
return f(*args, **kwargs)
else:
# otherwise, try oauth2
return f_oauth_required(*args, **kwargs)
return decorated
return wrapper
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def require_oauth_scopes(*scopes):
r"""Decorator to require a list of OAuth scopes. Decorator must be preceded by a ``require_api_auth()`` decorator. Note, API key authentication is bypassing this check. :param \*scopes: List of scopes required. """
|
required_scopes = set(scopes)
def wrapper(f):
@wraps(f)
def decorated(*args, **kwargs):
# Variable requests.oauth is only defined for oauth requests (see
# require_api_auth() above).
if hasattr(request, 'oauth') and request.oauth is not None:
token_scopes = set(request.oauth.access_token.scopes)
if not required_scopes.issubset(token_scopes):
abort(403)
return f(*args, **kwargs)
return decorated
return wrapper
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def indx_table(node_dict, tbl_mode=False):
"""Print Table for dict=formatted list conditionally include numbers."""
|
nt = PrettyTable()
nt.header = False
nt.padding_width = 2
nt.border = False
clr_num = C_TI + "NUM"
clr_name = C_TI + "NAME"
clr_state = "STATE" + C_NORM
t_lu = {True: [clr_num, "NAME", "REGION", "CLOUD",
"SIZE", "PUBLIC IP", clr_state],
False: [clr_name, "REGION", "CLOUD", "SIZE",
"PUBLIC IP", clr_state]}
nt.add_row(t_lu[tbl_mode])
for i, node in node_dict.items():
state = C_STAT[node.state] + node.state + C_NORM
inum = C_WARN + str(i) + C_NORM
if node.public_ips:
n_ip = node.public_ips
else:
n_ip = "-"
r_lu = {True: [inum, node.name, node.zone, node.cloud,
node.size, n_ip, state],
False: [node.name, node.zone, node.cloud,
node.size, n_ip, state]}
nt.add_row(r_lu[tbl_mode])
if not tbl_mode:
print(nt)
else:
idx_tbl = nt.get_string()
return idx_tbl
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def run(host=DEFAULT_HOST, port=DEFAULT_PORT, path='.'):
"""Run the development server """
|
path = abspath(path)
c = Clay(path)
c.run(host=host, port=port)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def build(pattern=None, path='.'):
"""Generates a static copy of the sources """
|
path = abspath(path)
c = Clay(path)
c.build(pattern)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def frequency_to_probability(frequency_map, decorator=lambda f: f):
"""Transform a ``frequency_map`` into a map of probability using the sum of all frequencies as the total. Example: {'a': 0.5, 'b': 0.5} Args: frequency_map (dict):
The dictionary to transform decorator (function):
A function to manipulate the probability Returns: Dictionary of ngrams to probability """
|
total = sum(frequency_map.values())
return {k: decorator(v / total) for k, v in frequency_map.items()}
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def index_of_coincidence(*texts):
"""Calculate the index of coincidence for one or more ``texts``. The results are averaged over multiple texts to return the delta index of coincidence. Examples: 0.2 0.2 Args: *texts (variable length argument list):
The texts to analyze Returns: Decimal value of the index of coincidence Raises: ValueError: If texts is empty ValueError: If any text is less that 2 character long """
|
if not texts:
raise ValueError("texts must not be empty")
return statistics.mean(_calculate_index_of_coincidence(frequency_analyze(text), len(text)) for text in texts)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _calculate_index_of_coincidence(frequency_map, length):
"""A measure of how similar frequency_map is to the uniform distribution. Or the probability that two letters picked randomly are alike. """
|
if length <= 1:
return 0
# We cannot error here as length can legitimiately be 1.
# Imagine a ciphertext of length 3 and a key of length 2.
# Spliting this text up and calculating the index of coincidence results in ['AC', 'B']
# IOC of B will be calcuated for the 2nd column of the key. We could represent the same
# encryption with a key of length 3 but then we encounter the same problem. This is also
# legitimiate encryption scheme we cannot ignore. Hence we have to deal with this fact here
# A value of 0 will impact the overall mean, however it does make some sense when you ask the question
# How many ways to choose 2 letters from the text, if theres only 1 letter then the answer is 0.
# Mathemtical combination, number of ways to choose 2 letters, no replacement, order doesnt matter
combination_of_letters = sum(freq * (freq - 1) for freq in frequency_map.values())
return combination_of_letters / (length * (length - 1))
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def chi_squared(source_frequency, target_frequency):
"""Calculate the Chi Squared statistic by comparing ``source_frequency`` with ``target_frequency``. Example: 0.1 Args: source_frequency (dict):
Frequency map of the text you are analyzing target_frequency (dict):
Frequency map of the target language to compare with Returns: Decimal value of the chi-squared statistic """
|
# Ignore any symbols from source that are not in target.
# TODO: raise Error if source_len is 0?
target_prob = frequency_to_probability(target_frequency)
source_len = sum(v for k, v in source_frequency.items() if k in target_frequency)
result = 0
for symbol, prob in target_prob.items():
symbol_frequency = source_frequency.get(symbol, 0) # Frequecy is 0 if it doesnt appear in source
result += _calculate_chi_squared(symbol_frequency, prob, source_len)
return result
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _calculate_chi_squared(source_freq, target_prob, source_len):
"""A measure of the observed frequency of the symbol versus the expected frequency. If the value is 0 then the texts are exactly alike for that symbol. """
|
expected = source_len * target_prob
return (source_freq - expected)**2 / expected
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _load_ngram(name):
"""Dynamically import the python module with the ngram defined as a dictionary. Since bigger ngrams are large files its wasteful to always statically import them if they're not used. """
|
module = importlib.import_module('lantern.analysis.english_ngrams.{}'.format(name))
return getattr(module, name)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def score(text, *score_functions):
"""Score ``text`` using ``score_functions``. Examples: Args: text (str):
The text to score *score_functions (variable length argument list):
functions to score with Returns: Arithmetic mean of scores Raises: ValueError: If score_functions is empty """
|
if not score_functions:
raise ValueError("score_functions must not be empty")
return statistics.mean(func(text) for func in score_functions)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def PatternMatch(regex):
"""Compute the score of a text by determing if a pattern matches. Example: 0 -1 Args: regex (str):
regular expression string to use as a pattern """
|
pattern = re.compile(regex)
return lambda text: -1 if pattern.search(text) is None else 0
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _request(self, url, params={}):
"""Makes a request using the currently open session. :param url: A url fragment to use in the creation of the master url """
|
r = self._session.get(url=url, params=params, headers=DEFAULT_ORIGIN)
return r
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def emit(self, event, *args, **kwargs):
"""Send out an event and call it's associated functions :param event: Name of the event to trigger """
|
for func in self._registered_events[event].values():
func(*args, **kwargs)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def remove_all_listeners(self, event=None):
"""Remove all functions for all events, or one event if one is specifed. :param event: Optional event you wish to remove all functions from """
|
if event is not None:
self._registered_events[event] = OrderedDict()
else:
self._registered_events = defaultdict(OrderedDict)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def version(self):
"""Spotify version information"""
|
url: str = get_url("/service/version.json")
params = {"service": "remote"}
r = self._request(url=url, params=params)
return r.json()
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_current_status(self):
"""Returns the current state of the local spotify client"""
|
url = get_url("/remote/status.json")
params = {"oauth": self._oauth_token, "csrf": self._csrf_token}
r = self._request(url=url, params=params)
return r.json()
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def pause(self, pause=True):
"""Pauses the spotify player :param pause: boolean value to choose the pause/play state """
|
url: str = get_url("/remote/pause.json")
params = {
"oauth": self._oauth_token,
"csrf": self._csrf_token,
"pause": "true" if pause else "false",
}
self._request(url=url, params=params)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def authenticate(self):
""" Authenticate with the api """
|
resp = self.session.get(self.api_url, auth=self.auth)
resp = self._process_response(resp)
return resp
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def generate_screenshots(self):
""" Take a config file as input and generate screenshots """
|
headers = {'content-type': 'application/json', 'Accept': 'application/json'}
resp = requests.post(self.api_url, data=json.dumps(self.config), \
headers=headers, auth=self.auth)
resp = self._process_response(resp)
return resp.json()
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def screenshots_done(self, jobid):
""" Return true if the screenshots job is done """
|
resp = self.session.get(os.path.join(self.api_url, '{0}.json'.format(jobid)))
resp = self._process_response(resp)
return True if resp.json()['state'] == 'done' else False
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create_items(self):
""" Create collidable items """
|
if not self.mode['items'] or len(self.mode['items']) == 0: return
# FIXME: Check if already contains
self.collman.add(self.player)
for k in self.mode['items']:
item = self.mode['items'][k]
#{'terminal': False, 'num': 50, 'scale': 1.0, 'reward': 2.0}
radius = item['scale'] * self.player.radius
for i in range(item['num']):
self.add_item(radius, k)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_item(self, radius, item_type):
""" Add a single item in random open position """
|
assert isinstance(radius, int) or isinstance(radius, float)
assert isinstance(item_type, str)
separation_scale = 1.1
min_separation = separation_scale * radius
# Removable item
item = Collidable(0, 0, radius, item_type, self.pics[item_type], True)
cntTrys = 0
while cntTrys < 100:
cx = radius + random.random() * (self.width - 2.0 * radius)
cy = radius + random.random() * (self.height - 2.0 * radius)
# Test if colliding with wall.
# Top left
cells = []
cells.append(self.map_layer.get_at_pixel(cx-radius, cy-radius))
# Top right
cells.append(self.map_layer.get_at_pixel(cx+radius, cy-radius))
# Bottom left
cells.append(self.map_layer.get_at_pixel(cx-radius, cy+radius))
# Bottom right
cells.append(self.map_layer.get_at_pixel(cx+radius, cy+radius))
wall = False
for cell in cells:
wall = cell and cell.tile and cell.tile.id > 0
if wall:
break
if wall:
continue
item.update_center(eu.Vector2(cx, cy))
if self.collman.any_near(item, min_separation) is None:
self.add(item, z=self.z)
self.z += 1
self.collman.add(item)
break
cntTrys += 1
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def update_collisions(self):
""" Test player for collisions with items """
|
if not self.mode['items'] or len(self.mode['items']) == 0: return
# update collman
# FIXME: Why update each frame?
self.collman.clear()
for z, node in self.children:
if hasattr(node, 'cshape') and type(node.cshape) == cm.CircleShape:
self.collman.add(node)
# interactions player - others
for other in self.collman.iter_colliding(self.player):
typeball = other.btype
self.logger.debug('collision', typeball)
# TODO: Limit player position on non-removable items
#if not other.removable:
# pass
if other.removable:
self.to_remove.append(other)
self.reward_item(typeball)
#
# elif (typeball == 'wall' or
# typeball == 'gate' and self.cnt_food > 0):
# self.level_losed()
#
# elif typeball == 'gate':
# self.level_conquered()
self.remove_items()
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def register_view(self, view_class, *args, **kwargs):
"""Register an admin view on this admin instance. :param view_class: The view class name passed to the view factory. :param args: Positional arugments for view class. :param kwargs: Keyword arguments to view class. """
|
protected_view_class = self.view_class_factory(view_class)
if 'endpoint' not in kwargs:
kwargs['endpoint'] = view_class(*args, **kwargs).endpoint
self.admin.add_view(protected_view_class(*args, **kwargs))
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def load_entry_point_group(self, entry_point_group):
"""Load administration interface from entry point group. :param str entry_point_group: Name of the entry point group. """
|
for ep in pkg_resources.iter_entry_points(group=entry_point_group):
admin_ep = dict(ep.load())
keys = tuple(
k in admin_ep for k in ('model', 'modelview', 'view_class'))
if keys == (False, False, True):
self.register_view(
admin_ep.pop('view_class'),
*admin_ep.pop('args', []),
**admin_ep.pop('kwargs', {})
)
elif keys == (True, True, False):
warnings.warn(
'Usage of model and modelview kwargs are deprecated in '
'favor of view_class, args and kwargs.',
PendingDeprecationWarning
)
self.register_view(
admin_ep.pop('modelview'),
admin_ep.pop('model'),
admin_ep.pop('session', db.session),
**admin_ep
)
else:
raise Exception(
'Admin entry point dictionary must contain '
'either "view_class" OR "model" and "modelview" keys.')
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_url(url):
"""Ranomdly generates a url for use in requests. Generates a hostname with the port and the provided suffix url provided :param url: A url fragment to use in the creation of the master url """
|
sub = "{0}.spotilocal.com".format("".join(choices(ascii_lowercase, k=10)))
return "http://{0}:{1}{2}".format(sub, DEFAULT_PORT, url)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_oauth_token():
"""Retrieve a simple OAuth Token for use with the local http client."""
|
url = "{0}/token".format(DEFAULT_ORIGIN["Origin"])
r = s.get(url=url)
return r.json()["t"]
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_csrf_token():
"""Retrieve a simple csrf token for to prevent cross site request forgery."""
|
url = get_url("/simplecsrf/token.json")
r = s.get(url=url, headers=DEFAULT_ORIGIN)
return r.json()["token"]
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def protected_adminview_factory(base_class):
"""Factory for creating protected admin view classes. The factory will ensure that the admin view will check if a user is authenticated and has the necessary permissions (as defined by the permission factory). The factory creates a new class using the provided class as base class and overwrites ``is_accessible()`` and ``inaccessible_callback()`` methods. Super is called for both methods, so the base class can implement further restrictions if needed. :param base_class: Class to use as base class. :type base_class: :class:`flask_admin.base.BaseView` :returns: Admin view class which provides authentication and authorization. """
|
class ProtectedAdminView(base_class):
"""Admin view class protected by authentication."""
def _handle_view(self, name, **kwargs):
"""Override Talisman CSP header configuration for admin views.
Flask-Admin extension is not CSP compliant (see:
https://github.com/flask-admin/flask-admin/issues/1135).
To avoid UI malfunctions, the CSP header (globally set on each
request by Talisman extension) must be overridden and removed.
Remove this code if and when Flask-Admin will be completely CSP
compliant.
"""
invenio_app = current_app.extensions.get('invenio-app', None)
if invenio_app:
setattr(invenio_app.talisman.local_options,
'content_security_policy', None)
return super(ProtectedAdminView, self)._handle_view(name, **kwargs)
def is_accessible(self):
"""Require authentication and authorization."""
return current_user.is_authenticated and \
current_admin.permission_factory(self).can() and \
super(ProtectedAdminView, self).is_accessible()
def inaccessible_callback(self, name, **kwargs):
"""Redirect to login if user is not logged in.
:param name: View function name.
:param kwargs: Passed to the superclass' `inaccessible_callback`.
"""
if not current_user.is_authenticated:
# Redirect to login page if user is not logged in.
return redirect(url_for(
current_app.config['ADMIN_LOGIN_ENDPOINT'],
next=request.url))
super(ProtectedAdminView, self).inaccessible_callback(
name, **kwargs)
return ProtectedAdminView
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def client_getter():
"""Decorator to retrieve Client object and check user permission."""
|
def wrapper(f):
@wraps(f)
def decorated(*args, **kwargs):
if 'client_id' not in kwargs:
abort(500)
client = Client.query.filter_by(
client_id=kwargs.pop('client_id'),
user_id=current_user.get_id(),
).first()
if client is None:
abort(404)
return f(client, *args, **kwargs)
return decorated
return wrapper
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def token_getter(is_personal=True, is_internal=False):
"""Decorator to retrieve Token object and check user permission. :param is_personal: Search for a personal token. (Default: ``True``) :param is_internal: Search for a internal token. (Default: ``False``) """
|
def wrapper(f):
@wraps(f)
def decorated(*args, **kwargs):
if 'token_id' not in kwargs:
abort(500)
token = Token.query.filter_by(
id=kwargs.pop('token_id'),
user_id=current_user.get_id(),
is_personal=is_personal,
is_internal=is_internal,
).first()
if token is None:
abort(404)
return f(token, *args, **kwargs)
return decorated
return wrapper
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def index():
"""List user tokens."""
|
clients = Client.query.filter_by(
user_id=current_user.get_id(),
is_internal=False,
).all()
tokens = Token.query.options(db.joinedload('client')).filter(
Token.user_id == current_user.get_id(),
Token.is_personal == True, # noqa
Token.is_internal == False,
Client.is_internal == True,
).all()
authorized_apps = Token.query.options(db.joinedload('client')).filter(
Token.user_id == current_user.get_id(),
Token.is_personal == False, # noqa
Token.is_internal == False,
Client.is_internal == False,
).all()
return render_template(
'invenio_oauth2server/settings/index.html',
clients=clients,
tokens=tokens,
authorized_apps=authorized_apps,
)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def client_new():
"""Create new client."""
|
form = ClientForm(request.form)
if form.validate_on_submit():
c = Client(user_id=current_user.get_id())
c.gen_salt()
form.populate_obj(c)
db.session.add(c)
db.session.commit()
return redirect(url_for('.client_view', client_id=c.client_id))
return render_template(
'invenio_oauth2server/settings/client_new.html',
form=form,
)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def client_view(client):
"""Show client's detail."""
|
if request.method == 'POST' and 'delete' in request.form:
db.session.delete(client)
db.session.commit()
return redirect(url_for('.index'))
form = ClientForm(request.form, obj=client)
if form.validate_on_submit():
form.populate_obj(client)
db.session.commit()
return render_template(
'invenio_oauth2server/settings/client_view.html',
client=client,
form=form,
)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def client_reset(client):
"""Reset client's secret."""
|
if request.form.get('reset') == 'yes':
client.reset_client_secret()
db.session.commit()
return redirect(url_for('.client_view', client_id=client.client_id))
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def token_new():
"""Create new token."""
|
form = TokenForm(request.form)
form.scopes.choices = current_oauth2server.scope_choices()
if form.validate_on_submit():
t = Token.create_personal(
form.data['name'], current_user.get_id(), scopes=form.scopes.data
)
db.session.commit()
session['show_personal_access_token'] = True
return redirect(url_for(".token_view", token_id=t.id))
if len(current_oauth2server.scope_choices()) == 0:
del(form.scopes)
return render_template(
"invenio_oauth2server/settings/token_new.html",
form=form,
)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def token_view(token):
"""Show token details."""
|
if request.method == "POST" and 'delete' in request.form:
db.session.delete(token)
db.session.commit()
return redirect(url_for('.index'))
show_token = session.pop('show_personal_access_token', False)
form = TokenForm(request.form, name=token.client.name, scopes=token.scopes)
form.scopes.choices = current_oauth2server.scope_choices()
if form.validate_on_submit():
token.client.name = form.data['name']
token.scopes = form.data['scopes']
db.session.commit()
if len(current_oauth2server.scope_choices()) == 0:
del(form.scopes)
return render_template(
"invenio_oauth2server/settings/token_view.html",
token=token,
form=form,
show_token=show_token,
)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def token_revoke(token):
"""Revoke Authorized Application token."""
|
db.session.delete(token)
db.session.commit()
return redirect(url_for('.index'))
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def token_permission_view(token):
"""Show permission garanted to authorized application token."""
|
scopes = [current_oauth2server.scopes[x] for x in token.scopes]
return render_template(
"invenio_oauth2server/settings/token_permission_view.html",
token=token,
scopes=scopes,
)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def extendMarkdown(self, md, md_globals):
"""Modifies inline patterns."""
|
md.inlinePatterns.add('del', SimpleTagPattern(DEL_RE, 'del'), '<not_strong')
md.inlinePatterns.add('ins', SimpleTagPattern(INS_RE, 'ins'), '<not_strong')
md.inlinePatterns.add('mark', SimpleTagPattern(MARK_RE, 'mark'), '<not_strong')
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_state(self, site, timestamp=None):
"""Write status dict to client status file. FIXME - should have some file lock to avoid race """
|
parser = ConfigParser()
parser.read(self.status_file)
status_section = 'incremental'
if (not parser.has_section(status_section)):
parser.add_section(status_section)
if (timestamp is None):
parser.remove_option(
status_section,
self.config_site_to_name(site))
else:
parser.set(
status_section,
self.config_site_to_name(site),
str(timestamp))
with open(self.status_file, 'w') as configfile:
parser.write(configfile)
configfile.close()
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_state(self, site):
"""Read client status file and return dict."""
|
parser = ConfigParser()
status_section = 'incremental'
parser.read(self.status_file)
timestamp = None
try:
timestamp = float(
parser.get(
status_section,
self.config_site_to_name(site)))
except NoSectionError as e:
pass
except NoOptionError as e:
pass
return(timestamp)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
|
def escape_latex_str_if_str(value):
'''Escape a latex string'''
if not isinstance(value, str):
return value
for regex, replace_text in REGEX_ESCAPE_CHARS:
value = re.sub(regex, replace_text, value)
value = re.sub(REGEX_BACKSLASH, r'\\\\', value)
return value
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def resources_as_xml(self, resources, sitemapindex=False, fh=None):
"""Write or return XML for a set of resources in sitemap format. Arguments: - resources - either an iterable or iterator of Resource objects; if there an md attribute this will go to <rs:md> if there an ln attribute this will go to <rs:ln> - sitemapindex - set True to write sitemapindex instead of sitemap - fh - write to filehandle fh instead of returning string """
|
# element names depending on sitemapindex or not
root_element = ('sitemapindex' if (sitemapindex) else 'urlset')
item_element = ('sitemap' if (sitemapindex) else 'url')
# namespaces and other settings
namespaces = {'xmlns': SITEMAP_NS, 'xmlns:rs': RS_NS}
root = Element(root_element, namespaces)
if (self.pretty_xml):
root.text = "\n"
# <rs:ln>
if (hasattr(resources, 'ln')):
for ln in resources.ln:
self.add_element_with_atts_to_etree(root, 'rs:ln', ln)
# <rs:md>
if (hasattr(resources, 'md')):
self.add_element_with_atts_to_etree(root, 'rs:md', resources.md)
# <url> entries from either an iterable or an iterator
for r in resources:
e = self.resource_etree_element(r, element_name=item_element)
root.append(e)
# have tree, now serialize
tree = ElementTree(root)
xml_buf = None
if (fh is None):
xml_buf = io.StringIO()
fh = xml_buf
if (sys.version_info >= (3, 0)):
tree.write(
fh,
encoding='unicode',
xml_declaration=True,
method='xml')
elif (sys.version_info >= (2, 7)):
tree.write(
fh,
encoding='UTF-8',
xml_declaration=True,
method='xml')
else: # python2.6
tree.write(fh, encoding='UTF-8')
if (xml_buf is not None):
if (sys.version_info >= (3, 0)):
return(xml_buf.getvalue())
else:
return(xml_buf.getvalue().decode('utf-8'))
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parse_xml(self, fh=None, etree=None, resources=None, capability=None, sitemapindex=None):
"""Parse XML Sitemap and add to resources object. Reads from fh or etree and adds resources to a resorces object (which must support the add method). Returns the resources object. Also sets self.resources_created to be the number of resources created. We adopt a very lax approach here. The parsing is properly namespace aware but we search just for the elements wanted and leave everything else alone. This method will read either sitemap or sitemapindex documents. Behavior depends on the sitemapindex parameter: - None - will read either - False - SitemapIndexError exception if sitemapindex detected - True - SitemapIndexError exception if sitemap detected Will set self.parsed_index based on whether a sitemap or sitemapindex document was read: - False - sitemap - True - sitemapindex """
|
if (resources is None):
resources = ResourceContainer()
if (fh is not None):
etree = parse(fh)
elif (etree is None):
raise ValueError("Neither fh or etree set")
# check root element: urlset (for sitemap), sitemapindex or bad
root_tag = etree.getroot().tag
resource_tag = None # will be <url> or <sitemap> depending on type
self.parsed_index = None
if (root_tag == '{' + SITEMAP_NS + "}urlset"):
self.parsed_index = False
if (sitemapindex is not None and sitemapindex):
raise SitemapIndexError(
"Got sitemap when expecting sitemapindex", etree)
resource_tag = '{' + SITEMAP_NS + "}url"
elif (root_tag == '{' + SITEMAP_NS + "}sitemapindex"):
self.parsed_index = True
if (sitemapindex is not None and not sitemapindex):
raise SitemapIndexError(
"Got sitemapindex when expecting sitemap", etree)
resource_tag = '{' + SITEMAP_NS + "}sitemap"
else:
raise SitemapParseError(
"XML is not sitemap or sitemapindex (root element is <%s>)" %
root_tag)
# have what we expect, read it
in_preamble = True
self.resources_created = 0
seen_top_level_md = False
for e in etree.getroot().getchildren():
# look for <rs:md> and <rs:ln>, first <url> ends
# then look for resources in <url> blocks
if (e.tag == resource_tag):
in_preamble = False # any later rs:md or rs:ln is error
r = self.resource_from_etree(e, self.resource_class)
try:
resources.add(r)
except SitemapDupeError:
self.logger.warning(
"dupe of: %s (lastmod=%s)" %
(r.uri, r.lastmod))
self.resources_created += 1
elif (e.tag == "{" + RS_NS + "}md"):
if (in_preamble):
if (seen_top_level_md):
raise SitemapParseError(
"Multiple <rs:md> at top level of sitemap")
else:
resources.md = self.md_from_etree(e, 'preamble')
seen_top_level_md = True
else:
raise SitemapParseError(
"Found <rs:md> after first <url> in sitemap")
elif (e.tag == "{" + RS_NS + "}ln"):
if (in_preamble):
resources.ln.append(self.ln_from_etree(e, 'preamble'))
else:
raise SitemapParseError(
"Found <rs:ln> after first <url> in sitemap")
else:
# element we don't recognize, ignore
pass
# check that we read to right capability document
if (capability is not None):
if ('capability' not in resources.md):
if (capability == 'resourcelist'):
self.logger.warning(
'No capability specified in sitemap, assuming resourcelist')
resources.md['capability'] = 'resourcelist'
else:
raise SitemapParseError("Expected to read a %s document, but no capability specified in sitemap" %
(capability))
if (resources.md['capability'] != capability):
raise SitemapParseError("Expected to read a %s document, got %s" %
(capability, resources.md['capability']))
# return the resource container object
return(resources)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def resource_etree_element(self, resource, element_name='url'):
"""Return xml.etree.ElementTree.Element representing the resource. Returns and element for the specified resource, of the form <url> with enclosed properties that are based on the sitemap with extensions for ResourceSync. """
|
e = Element(element_name)
sub = Element('loc')
sub.text = resource.uri
e.append(sub)
if (resource.timestamp is not None):
# Create appriate element for timestamp
sub = Element('lastmod')
sub.text = str(resource.lastmod) # W3C Datetime in UTC
e.append(sub)
md_atts = {}
for att in ('capability', 'change', 'hash', 'length', 'path', 'mime_type',
'md_at', 'md_completed', 'md_from', 'md_until'):
val = getattr(resource, att, None)
if (val is not None):
md_atts[self._xml_att_name(att)] = str(val)
if (len(md_atts) > 0):
md = Element('rs:md', md_atts)
e.append(md)
# add any <rs:ln>
if (hasattr(resource, 'ln') and
resource.ln is not None):
for ln in resource.ln:
self.add_element_with_atts_to_etree(e, 'rs:ln', ln)
if (self.pretty_xml):
e.tail = "\n"
return(e)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def resource_as_xml(self, resource):
"""Return string for the resource as part of an XML sitemap. Returns a string with the XML snippet representing the resource, without any XML declaration. """
|
e = self.resource_etree_element(resource)
if (sys.version_info >= (3, 0)):
# python3.x
return(tostring(e, encoding='unicode', method='xml'))
elif (sys.version_info >= (2, 7)):
s = tostring(e, encoding='UTF-8', method='xml')
else:
# must not specify method='xml' in python2.6
s = tostring(e, encoding='UTF-8')
# Chop off XML declaration that is added in 2.x... sigh
return(s.replace("<?xml version='1.0' encoding='UTF-8'?>\n", ''))
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def resource_from_etree(self, etree, resource_class):
"""Construct a Resource from an etree. Parameters: etree - the etree to parse resource_class - class of Resource object to create The parsing is properly namespace aware but we search just for the elements wanted and leave everything else alone. Will raise an error if there are multiple <loc> or multiple <lastmod> elements. Otherwise, provided there is a <loc> element then will go ahead and extract as much as possible. All errors raised are SitemapParseError with messages intended to help debug problematic sitemap XML. """
|
loc_elements = etree.findall('{' + SITEMAP_NS + "}loc")
if (len(loc_elements) > 1):
raise SitemapParseError(
"Multiple <loc> elements while parsing <url> in sitemap")
elif (len(loc_elements) == 0):
raise SitemapParseError(
"Missing <loc> element while parsing <url> in sitemap")
else:
loc = loc_elements[0].text
if (loc is None or loc == ''):
raise SitemapParseError(
"Bad <loc> element with no content while parsing <url> in sitemap")
# must at least have a URI, make this object
resource = resource_class(uri=loc)
# and hopefully a lastmod datetime (but none is OK)
lastmod_elements = etree.findall('{' + SITEMAP_NS + "}lastmod")
if (len(lastmod_elements) > 1):
raise SitemapParseError(
"Multiple <lastmod> elements while parsing <url> in sitemap")
elif (len(lastmod_elements) == 1):
resource.lastmod = lastmod_elements[0].text
# proceed to look for other resource attributes in an rs:md element
md_elements = etree.findall('{' + RS_NS + "}md")
if (len(md_elements) > 1):
raise SitemapParseError(
"Found multiple (%d) <rs:md> elements for %s", (len(md_elements), loc))
elif (len(md_elements) == 1):
# have on element, look at attributes
md = self.md_from_etree(md_elements[0], context=loc)
# simple attributes that map directly to Resource object attributes
for att in ('capability', 'change', 'length', 'path', 'mime_type'):
if (att in md):
setattr(resource, att, md[att])
# The ResourceSync beta spec lists md5, sha-1 and sha-256 fixity
# digest types. Parse and warn of errors ignored.
if ('hash' in md):
try:
resource.hash = md['hash']
except ValueError as e:
self.logger.warning("%s in <rs:md> for %s" % (str(e), loc))
# look for rs:ln elements (optional)
ln_elements = etree.findall('{' + RS_NS + "}ln")
if (len(ln_elements) > 0):
resource.ln = []
for ln_element in ln_elements:
resource.ln.append(self.ln_from_etree(ln_element, loc))
return(resource)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_element_with_atts_to_etree(self, etree, name, atts):
"""Add element with name and atts to etree iff there are any atts. Parameters: etree - an etree object name - XML element name atts - dicts of attribute values. Attribute names are transformed """
|
xml_atts = {}
for att in atts.keys():
val = atts[att]
if (val is not None):
xml_atts[self._xml_att_name(att)] = str(val)
if (len(xml_atts) > 0):
e = Element(name, xml_atts)
if (self.pretty_xml):
e.tail = "\n"
etree.append(e)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def dst_to_src(self, dst_file):
"""Map destination path to source URI."""
|
for map in self.mappings:
src_uri = map.dst_to_src(dst_file)
if (src_uri is not None):
return(src_uri)
# Must have failed if loop exited
raise MapperError(
"Unable to translate destination path (%s) "
"into a source URI." % (dst_file))
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def src_to_dst(self, src_uri):
"""Map source URI to destination path."""
|
for map in self.mappings:
dst_path = map.src_to_dst(src_uri)
if (dst_path is not None):
return(dst_path)
# Must have failed if loop exited
raise MapperError(
"Unable to translate source URI (%s) into "
"a destination path." % (src_uri))
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def path_from_uri(self, uri):
"""Make a safe path name from uri. In the case that uri is already a local path then the same path is returned. """
|
(scheme, netloc, path, params, query, frag) = urlparse(uri)
if (netloc == ''):
return(uri)
path = '/'.join([netloc, path])
path = re.sub('[^\w\-\.]', '_', path)
path = re.sub('__+', '_', path)
path = re.sub('[_\.]+$', '', path)
path = re.sub('^[_\.]+', '', path)
return(path)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def strip_trailing_slashes(self, path):
"""Return input path minus any trailing slashes."""
|
m = re.match(r"(.*)/+$", path)
if (m is None):
return(path)
return(m.group(1))
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def dst_to_src(self, dst_file):
"""Return the src URI from the dst filepath. This does not rely on the destination filepath actually existing on the local filesystem, just on pattern matching. Return source URI on success, None on failure. """
|
m = re.match(self.dst_path + "/(.*)$", dst_file)
if (m is None):
return(None)
rel_path = m.group(1)
return(self.src_uri + '/' + rel_path)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def src_to_dst(self, src_uri):
"""Return the dst filepath from the src URI. Returns None on failure, destination path on success. """
|
m = re.match(self.src_uri + "/(.*)$", src_uri)
if (m is None):
return(None)
rel_path = m.group(1)
return(self.dst_path + '/' + rel_path)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def unsafe(self):
"""True if the mapping is unsafe for an update. Applies only to local source. Returns True if the paths for source and destination are the same, or if one is a component of the other path. """
|
(scheme, netloc, path, params, query, frag) = urlparse(self.src_uri)
if (scheme != ''):
return(False)
s = os.path.normpath(self.src_uri)
d = os.path.normpath(self.dst_path)
lcp = os.path.commonprefix([s, d])
return(s == lcp or d == lcp)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def remove(text, exclude):
"""Remove ``exclude`` symbols from ``text``. Example: 'exampletext' Args: text (str):
The text to modify exclude (iterable):
The symbols to exclude Returns: ``text`` with ``exclude`` symbols removed """
|
exclude = ''.join(str(symbol) for symbol in exclude)
return text.translate(str.maketrans('', '', exclude))
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def split_columns(text, n_columns):
"""Split ``text`` into ``n_columns`` many columns. Example: ['eape', 'xml'] Args: text (str):
The text to split n_columns (int):
The number of columns to create Returns: List of columns Raises: ValueError: If n_cols is <= 0 or >= len(text) """
|
if n_columns <= 0 or n_columns > len(text):
raise ValueError("n_columns must be within the bounds of 1 and text length")
return [text[i::n_columns] for i in range(n_columns)]
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def combine_columns(columns):
"""Combine ``columns`` into a single string. Example: 'example' Args: columns (iterable):
ordered columns to combine Returns: String of combined columns """
|
columns_zipped = itertools.zip_longest(*columns)
return ''.join(x for zipped in columns_zipped for x in zipped if x)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def iterate_ngrams(text, n):
"""Generator to yield ngrams in ``text``. Example: exam xamp ampl mple Args: text (str):
text to iterate over n (int):
size of window for iteration Returns: Generator expression to yield the next ngram in the text Raises: ValueError: If n is non positive """
|
if n <= 0:
raise ValueError("n must be a positive integer")
return [text[i: i + n] for i in range(len(text) - n + 1)]
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def group(text, size):
"""Group ``text`` into blocks of ``size``. Example: ['te', 'st'] Args: text (str):
text to separate size (int):
size of groups to split the text into Returns: List of n-sized groups of text Raises: ValueError: If n is non positive """
|
if size <= 0:
raise ValueError("n must be a positive integer")
return [text[i:i + size] for i in range(0, len(text), size)]
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _evaluate_rhs(cls, funcs, nodes, problem):
""" Compute the value of the right-hand side of the system of ODEs. Parameters basis_funcs : list(function) nodes : numpy.ndarray problem : TwoPointBVPLike Returns ------- evaluated_rhs : list(float) """
|
evald_funcs = cls._evaluate_functions(funcs, nodes)
evald_rhs = problem.rhs(nodes, *evald_funcs, **problem.params)
return evald_rhs
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _compute_residuals(self, coefs_array, basis_kwargs, boundary_points, nodes, problem):
""" Return collocation residuals. Parameters coefs_array : numpy.ndarray basis_kwargs : dict problem : TwoPointBVPLike Returns ------- resids : numpy.ndarray """
|
coefs_list = self._array_to_list(coefs_array, problem.number_odes)
derivs, funcs = self._construct_approximation(basis_kwargs, coefs_list)
resids = self._assess_approximation(boundary_points, derivs, funcs,
nodes, problem)
return resids
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _construct_approximation(self, basis_kwargs, coefs_list):
""" Construct a collection of derivatives and functions that approximate the solution to the boundary value problem. Parameters basis_kwargs : dict(str: ) coefs_list : list(numpy.ndarray) Returns ------- basis_derivs : list(function) basis_funcs : list(function) """
|
derivs = self._construct_derivatives(coefs_list, **basis_kwargs)
funcs = self._construct_functions(coefs_list, **basis_kwargs)
return derivs, funcs
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _construct_derivatives(self, coefs, **kwargs):
"""Return a list of derivatives given a list of coefficients."""
|
return [self.basis_functions.derivatives_factory(coef, **kwargs) for coef in coefs]
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _construct_functions(self, coefs, **kwargs):
"""Return a list of functions given a list of coefficients."""
|
return [self.basis_functions.functions_factory(coef, **kwargs) for coef in coefs]
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _solution_factory(self, basis_kwargs, coefs_array, nodes, problem, result):
""" Construct a representation of the solution to the boundary value problem. Parameters basis_kwargs : dict(str : ) coefs_array : numpy.ndarray problem : TwoPointBVPLike result : OptimizeResult Returns ------- solution : SolutionLike """
|
soln_coefs = self._array_to_list(coefs_array, problem.number_odes)
soln_derivs = self._construct_derivatives(soln_coefs, **basis_kwargs)
soln_funcs = self._construct_functions(soln_coefs, **basis_kwargs)
soln_residual_func = self._interior_residuals_factory(soln_derivs,
soln_funcs,
problem)
solution = solutions.Solution(basis_kwargs, soln_funcs, nodes, problem,
soln_residual_func, result)
return solution
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def solve(self, basis_kwargs, boundary_points, coefs_array, nodes, problem, **solver_options):
""" Solve a boundary value problem using the collocation method. Parameters basis_kwargs : dict Dictionary of keyword arguments used to build basis functions. coefs_array : numpy.ndarray Array of coefficients for basis functions defining the initial condition. problem : bvp.TwoPointBVPLike A two-point boundary value problem (BVP) to solve. solver_options : dict Dictionary of options to pass to the non-linear equation solver. Return ------ solution: solutions.SolutionLike An instance of the SolutionLike class representing the solution to the two-point boundary value problem (BVP) Notes ----- """
|
result = optimize.root(self._compute_residuals,
x0=coefs_array,
args=(basis_kwargs, boundary_points, nodes, problem),
**solver_options)
solution = self._solution_factory(basis_kwargs, result.x, nodes,
problem, result)
return solution
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def datetime_to_str(dt='now', no_fractions=False):
"""The Last-Modified data in ISO8601 syntax, Z notation. The lastmod is stored as unix timestamp which is already in UTC. At preesent this code will return 6 decimal digits if any fraction of a second is given. It would perhaps be better to return only the number of decimal digits necessary, up to a resultion of 1 microsecond. Special cases: - Returns datetime str for now if no parameter given. - Returns None if None is supplied. """
|
if (dt is None):
return None
elif (dt == 'now'):
dt = time.time()
if (no_fractions):
dt = int(dt)
else:
dt += 0.0000001 # improve rounding to microseconds
return datetime.utcfromtimestamp(dt).isoformat() + 'Z'
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def str_to_datetime(s, context='datetime'):
"""Set timestamp from an W3C Datetime Last-Modified value. The sitemaps.org specification says that <lastmod> values must comply with the W3C Datetime format (http://www.w3.org/TR/NOTE-datetime). This is a restricted subset of ISO8601. In particular, all forms that include a time must include a timezone indication so there is no notion of local time (which would be tricky on the web). The forms allowed are: Year: YYYY (eg 1997) Year and month: YYYY-MM (eg 1997-07) Complete date: YYYY-MM-DD (eg 1997-07-16) Complete date plus hours and minutes: YYYY-MM-DDThh:mmTZD (eg 1997-07-16T19:20+01:00) Complete date plus hours, minutes and seconds: YYYY-MM-DDThh:mm:ssTZD (eg 1997-07-16T19:20:30+01:00) Complete date plus hours, minutes, seconds and a decimal fraction of a second YYYY-MM-DDThh:mm:ss.sTZD (eg 1997-07-16T19:20:30.45+01:00) where: TZD = time zone designator (Z or +hh:mm or -hh:mm) We do not anticipate the YYYY and YYYY-MM forms being used but interpret them as YYYY-01-01 and YYYY-MM-01 respectively. All dates are interpreted as having time 00:00:00.0 UTC. Datetimes not specified to the level of seconds are intepreted as 00.0 seconds. """
|
t = None
if (s is None):
return(t)
if (s == ''):
raise ValueError('Attempt to set empty %s' % (context))
# Make a date into a full datetime
m = re.match(r"\d\d\d\d(\-\d\d(\-\d\d)?)?$", s)
if (m is not None):
if (m.group(1) is None):
s += '-01-01'
elif (m.group(2) is None):
s += '-01'
s += 'T00:00:00Z'
# Now have datetime with timezone info
m = re.match(r"(.*\d{2}:\d{2}:\d{2})(\.\d+)([^\d].*)?$", s)
# Chop out fractional seconds if present
fractional_seconds = 0
if (m is not None):
s = m.group(1)
if (m.group(3) is not None):
s += m.group(3)
fractional_seconds = float(m.group(2))
# Now check that only allowed formats supplied (the parse
# function in dateutil is rather lax) and separate out
# timezone information to be handled separately
#
# Seems that one should be able to handle timezone offset
# with dt.tzinfo module but this has variation in behavior
# between python 2.6 and 2.7... so do here for now
m = re.match(r"(\d\d\d\d\-\d\d\-\d\dT\d\d:\d\d(:\d\d)?)(Z|([+-])"
"(\d\d):(\d\d))$", s)
if (m is None):
raise ValueError("Bad datetime format (%s)" % s)
str = m.group(1) + 'Z'
dt = dateutil_parser.parse(str)
offset_seconds = 0
if (m.group(3) != 'Z'):
hh = int(m.group(5))
mm = int(m.group(6))
if (hh > 23 or mm > 59):
raise ValueError("Bad timezone offset (%s)" % s)
offset_seconds = hh * 3600 + mm * 60
if (m.group(4) == '-'):
offset_seconds = -offset_seconds
# timetuple() ignores timezone information so we have to add in
# the offset here, and any fractional component of the seconds
return(timegm(dt.timetuple()) + offset_seconds + fractional_seconds)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def need_geocoding(self):
""" Returns True if any of the required address components is missing """
|
need_geocoding = False
for attribute, component in self.required_address_components.items():
if not getattr(self, attribute):
need_geocoding = True
break # skip extra loops
return need_geocoding
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def geocode(self, commit=False, force=False):
""" Do a backend geocoding if needed """
|
if self.need_geocoding() or force:
result = get_cached(getattr(self, self.geocoded_by), provider='google')
if result.status == 'OK':
for attribute, components in self.required_address_components.items():
for component in components:
if not getattr(self, attribute) or force:
attr_val = getattr(result, component, None)
if attr_val:
setattr(self, attribute, attr_val)
if commit:
self.save()
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def link(self, rel):
"""Look for link with specified rel, return else None."""
|
for link in self.ln:
if ('rel' in link and
link['rel'] == rel):
return(link)
return(None)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def link_href(self, rel):
"""Look for link with specified rel, return href from it or None."""
|
link = self.link(rel)
if (link is not None):
link = link['href']
return(link)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def default_capability(self):
"""Set capability name in md. Every ResourceSync document should have the top-level capability attributes. """
|
if ('capability' not in self.md and self.capability_name is not None):
self.md['capability'] = self.capability_name
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add(self, resource):
"""Add a resource or an iterable collection of resources to this container. Must be implemented in derived class. """
|
if isinstance(resource, collections.Iterable):
for r in resource:
self.resources.append(r)
else:
self.resources.append(resource)
|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def prune_before(self, timestamp):
"""Remove all resources with timestamp earlier than that given. Returns the number of entries removed. Will raise an excpetion if there are any entries without a timestamp. """
|
n = 0
pruned = []
for r in self.resources:
if (r.timestamp is None):
raise Exception("Entry %s has no timestamp" % (r.uri))
elif (r.timestamp >= timestamp):
pruned.append(r)
else:
n += 1
self.resources = pruned
return(n)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.