repo stringlengths 7 55 | path stringlengths 4 223 | func_name stringlengths 1 134 | original_string stringlengths 75 104k | language stringclasses 1 value | code stringlengths 75 104k | code_tokens listlengths 19 28.4k | docstring stringlengths 1 46.9k | docstring_tokens listlengths 1 1.97k | sha stringlengths 40 40 | url stringlengths 87 315 | partition stringclasses 1 value |
|---|---|---|---|---|---|---|---|---|---|---|---|
EmbodiedCognition/py-c3d | c3d.py | Manager.parameter_blocks | def parameter_blocks(self):
'''Compute the size (in 512B blocks) of the parameter section.'''
bytes = 4. + sum(g.binary_size() for g in self.groups.values())
return int(np.ceil(bytes / 512)) | python | def parameter_blocks(self):
'''Compute the size (in 512B blocks) of the parameter section.'''
bytes = 4. + sum(g.binary_size() for g in self.groups.values())
return int(np.ceil(bytes / 512)) | [
"def",
"parameter_blocks",
"(",
"self",
")",
":",
"bytes",
"=",
"4.",
"+",
"sum",
"(",
"g",
".",
"binary_size",
"(",
")",
"for",
"g",
"in",
"self",
".",
"groups",
".",
"values",
"(",
")",
")",
"return",
"int",
"(",
"np",
".",
"ceil",
"(",
"bytes"... | Compute the size (in 512B blocks) of the parameter section. | [
"Compute",
"the",
"size",
"(",
"in",
"512B",
"blocks",
")",
"of",
"the",
"parameter",
"section",
"."
] | 391493d9cb4c6b4aaeee4de2930685e3a67f5845 | https://github.com/EmbodiedCognition/py-c3d/blob/391493d9cb4c6b4aaeee4de2930685e3a67f5845/c3d.py#L669-L672 | train |
EmbodiedCognition/py-c3d | c3d.py | Reader.read_frames | def read_frames(self, copy=True):
'''Iterate over the data frames from our C3D file handle.
Parameters
----------
copy : bool
If False, the reader returns a reference to the same data buffers
for every frame. The default is True, which causes the reader to
return a unique data buffer for each frame. Set this to False if you
consume frames as you iterate over them, or True if you store them
for later.
Returns
-------
frames : sequence of (frame number, points, analog)
This method generates a sequence of (frame number, points, analog)
tuples, one tuple per frame. The first element of each tuple is the
frame number. The second is a numpy array of parsed, 5D point data
and the third element of each tuple is a numpy array of analog
values that were recorded during the frame. (Often the analog data
are sampled at a higher frequency than the 3D point data, resulting
in multiple analog frames per frame of point data.)
The first three columns in the returned point data are the (x, y, z)
coordinates of the observed motion capture point. The fourth column
is an estimate of the error for this particular point, and the fifth
column is the number of cameras that observed the point in question.
Both the fourth and fifth values are -1 if the point is considered
to be invalid.
'''
scale = abs(self.point_scale)
is_float = self.point_scale < 0
point_bytes = [2, 4][is_float]
point_dtype = [np.int16, np.float32][is_float]
point_scale = [scale, 1][is_float]
points = np.zeros((self.point_used, 5), float)
# TODO: handle ANALOG:BITS parameter here!
p = self.get('ANALOG:FORMAT')
analog_unsigned = p and p.string_value.strip().upper() == 'UNSIGNED'
analog_dtype = np.int16
analog_bytes = 2
if is_float:
analog_dtype = np.float32
analog_bytes = 4
elif analog_unsigned:
analog_dtype = np.uint16
analog_bytes = 2
analog = np.array([], float)
offsets = np.zeros((self.analog_used, 1), int)
param = self.get('ANALOG:OFFSET')
if param is not None:
offsets = param.int16_array[:self.analog_used, None]
scales = np.ones((self.analog_used, 1), float)
param = self.get('ANALOG:SCALE')
if param is not None:
scales = param.float_array[:self.analog_used, None]
gen_scale = 1.
param = self.get('ANALOG:GEN_SCALE')
if param is not None:
gen_scale = param.float_value
self._handle.seek((self.header.data_block - 1) * 512)
for frame_no in range(self.first_frame(), self.last_frame() + 1):
n = 4 * self.header.point_count
raw = np.fromstring(self._handle.read(n * point_bytes),
dtype=point_dtype,
count=n).reshape((self.point_used, 4))
points[:, :3] = raw[:, :3] * point_scale
valid = raw[:, 3] > -1
points[~valid, 3:5] = -1
c = raw[valid, 3].astype(np.uint16)
# fourth value is floating-point (scaled) error estimate
points[valid, 3] = (c & 0xff).astype(float) * scale
# fifth value is number of bits set in camera-observation byte
points[valid, 4] = sum((c & (1 << k)) >> k for k in range(8, 17))
if self.header.analog_count > 0:
n = self.header.analog_count
raw = np.fromstring(self._handle.read(n * analog_bytes),
dtype=analog_dtype,
count=n).reshape((-1, self.analog_used)).T
analog = (raw.astype(float) - offsets) * scales * gen_scale
if copy:
yield frame_no, points.copy(), analog.copy()
else:
yield frame_no, points, analog | python | def read_frames(self, copy=True):
'''Iterate over the data frames from our C3D file handle.
Parameters
----------
copy : bool
If False, the reader returns a reference to the same data buffers
for every frame. The default is True, which causes the reader to
return a unique data buffer for each frame. Set this to False if you
consume frames as you iterate over them, or True if you store them
for later.
Returns
-------
frames : sequence of (frame number, points, analog)
This method generates a sequence of (frame number, points, analog)
tuples, one tuple per frame. The first element of each tuple is the
frame number. The second is a numpy array of parsed, 5D point data
and the third element of each tuple is a numpy array of analog
values that were recorded during the frame. (Often the analog data
are sampled at a higher frequency than the 3D point data, resulting
in multiple analog frames per frame of point data.)
The first three columns in the returned point data are the (x, y, z)
coordinates of the observed motion capture point. The fourth column
is an estimate of the error for this particular point, and the fifth
column is the number of cameras that observed the point in question.
Both the fourth and fifth values are -1 if the point is considered
to be invalid.
'''
scale = abs(self.point_scale)
is_float = self.point_scale < 0
point_bytes = [2, 4][is_float]
point_dtype = [np.int16, np.float32][is_float]
point_scale = [scale, 1][is_float]
points = np.zeros((self.point_used, 5), float)
# TODO: handle ANALOG:BITS parameter here!
p = self.get('ANALOG:FORMAT')
analog_unsigned = p and p.string_value.strip().upper() == 'UNSIGNED'
analog_dtype = np.int16
analog_bytes = 2
if is_float:
analog_dtype = np.float32
analog_bytes = 4
elif analog_unsigned:
analog_dtype = np.uint16
analog_bytes = 2
analog = np.array([], float)
offsets = np.zeros((self.analog_used, 1), int)
param = self.get('ANALOG:OFFSET')
if param is not None:
offsets = param.int16_array[:self.analog_used, None]
scales = np.ones((self.analog_used, 1), float)
param = self.get('ANALOG:SCALE')
if param is not None:
scales = param.float_array[:self.analog_used, None]
gen_scale = 1.
param = self.get('ANALOG:GEN_SCALE')
if param is not None:
gen_scale = param.float_value
self._handle.seek((self.header.data_block - 1) * 512)
for frame_no in range(self.first_frame(), self.last_frame() + 1):
n = 4 * self.header.point_count
raw = np.fromstring(self._handle.read(n * point_bytes),
dtype=point_dtype,
count=n).reshape((self.point_used, 4))
points[:, :3] = raw[:, :3] * point_scale
valid = raw[:, 3] > -1
points[~valid, 3:5] = -1
c = raw[valid, 3].astype(np.uint16)
# fourth value is floating-point (scaled) error estimate
points[valid, 3] = (c & 0xff).astype(float) * scale
# fifth value is number of bits set in camera-observation byte
points[valid, 4] = sum((c & (1 << k)) >> k for k in range(8, 17))
if self.header.analog_count > 0:
n = self.header.analog_count
raw = np.fromstring(self._handle.read(n * analog_bytes),
dtype=analog_dtype,
count=n).reshape((-1, self.analog_used)).T
analog = (raw.astype(float) - offsets) * scales * gen_scale
if copy:
yield frame_no, points.copy(), analog.copy()
else:
yield frame_no, points, analog | [
"def",
"read_frames",
"(",
"self",
",",
"copy",
"=",
"True",
")",
":",
"scale",
"=",
"abs",
"(",
"self",
".",
"point_scale",
")",
"is_float",
"=",
"self",
".",
"point_scale",
"<",
"0",
"point_bytes",
"=",
"[",
"2",
",",
"4",
"]",
"[",
"is_float",
"... | Iterate over the data frames from our C3D file handle.
Parameters
----------
copy : bool
If False, the reader returns a reference to the same data buffers
for every frame. The default is True, which causes the reader to
return a unique data buffer for each frame. Set this to False if you
consume frames as you iterate over them, or True if you store them
for later.
Returns
-------
frames : sequence of (frame number, points, analog)
This method generates a sequence of (frame number, points, analog)
tuples, one tuple per frame. The first element of each tuple is the
frame number. The second is a numpy array of parsed, 5D point data
and the third element of each tuple is a numpy array of analog
values that were recorded during the frame. (Often the analog data
are sampled at a higher frequency than the 3D point data, resulting
in multiple analog frames per frame of point data.)
The first three columns in the returned point data are the (x, y, z)
coordinates of the observed motion capture point. The fourth column
is an estimate of the error for this particular point, and the fifth
column is the number of cameras that observed the point in question.
Both the fourth and fifth values are -1 if the point is considered
to be invalid. | [
"Iterate",
"over",
"the",
"data",
"frames",
"from",
"our",
"C3D",
"file",
"handle",
"."
] | 391493d9cb4c6b4aaeee4de2930685e3a67f5845 | https://github.com/EmbodiedCognition/py-c3d/blob/391493d9cb4c6b4aaeee4de2930685e3a67f5845/c3d.py#L804-L899 | train |
EmbodiedCognition/py-c3d | c3d.py | Writer._pad_block | def _pad_block(self, handle):
'''Pad the file with 0s to the end of the next block boundary.'''
extra = handle.tell() % 512
if extra:
handle.write(b'\x00' * (512 - extra)) | python | def _pad_block(self, handle):
'''Pad the file with 0s to the end of the next block boundary.'''
extra = handle.tell() % 512
if extra:
handle.write(b'\x00' * (512 - extra)) | [
"def",
"_pad_block",
"(",
"self",
",",
"handle",
")",
":",
"extra",
"=",
"handle",
".",
"tell",
"(",
")",
"%",
"512",
"if",
"extra",
":",
"handle",
".",
"write",
"(",
"b'\\x00'",
"*",
"(",
"512",
"-",
"extra",
")",
")"
] | Pad the file with 0s to the end of the next block boundary. | [
"Pad",
"the",
"file",
"with",
"0s",
"to",
"the",
"end",
"of",
"the",
"next",
"block",
"boundary",
"."
] | 391493d9cb4c6b4aaeee4de2930685e3a67f5845 | https://github.com/EmbodiedCognition/py-c3d/blob/391493d9cb4c6b4aaeee4de2930685e3a67f5845/c3d.py#L956-L960 | train |
EmbodiedCognition/py-c3d | c3d.py | Writer._write_metadata | def _write_metadata(self, handle):
'''Write metadata to a file handle.
Parameters
----------
handle : file
Write metadata and C3D motion frames to the given file handle. The
writer does not close the handle.
'''
self.check_metadata()
# header
self.header.write(handle)
self._pad_block(handle)
assert handle.tell() == 512
# groups
handle.write(struct.pack(
'BBBB', 0, 0, self.parameter_blocks(), PROCESSOR_INTEL))
id_groups = sorted(
(i, g) for i, g in self.groups.items() if isinstance(i, int))
for group_id, group in id_groups:
group.write(group_id, handle)
# padding
self._pad_block(handle)
while handle.tell() != 512 * (self.header.data_block - 1):
handle.write(b'\x00' * 512) | python | def _write_metadata(self, handle):
'''Write metadata to a file handle.
Parameters
----------
handle : file
Write metadata and C3D motion frames to the given file handle. The
writer does not close the handle.
'''
self.check_metadata()
# header
self.header.write(handle)
self._pad_block(handle)
assert handle.tell() == 512
# groups
handle.write(struct.pack(
'BBBB', 0, 0, self.parameter_blocks(), PROCESSOR_INTEL))
id_groups = sorted(
(i, g) for i, g in self.groups.items() if isinstance(i, int))
for group_id, group in id_groups:
group.write(group_id, handle)
# padding
self._pad_block(handle)
while handle.tell() != 512 * (self.header.data_block - 1):
handle.write(b'\x00' * 512) | [
"def",
"_write_metadata",
"(",
"self",
",",
"handle",
")",
":",
"self",
".",
"check_metadata",
"(",
")",
"# header",
"self",
".",
"header",
".",
"write",
"(",
"handle",
")",
"self",
".",
"_pad_block",
"(",
"handle",
")",
"assert",
"handle",
".",
"tell",
... | Write metadata to a file handle.
Parameters
----------
handle : file
Write metadata and C3D motion frames to the given file handle. The
writer does not close the handle. | [
"Write",
"metadata",
"to",
"a",
"file",
"handle",
"."
] | 391493d9cb4c6b4aaeee4de2930685e3a67f5845 | https://github.com/EmbodiedCognition/py-c3d/blob/391493d9cb4c6b4aaeee4de2930685e3a67f5845/c3d.py#L962-L989 | train |
EmbodiedCognition/py-c3d | c3d.py | Writer._write_frames | def _write_frames(self, handle):
'''Write our frame data to the given file handle.
Parameters
----------
handle : file
Write metadata and C3D motion frames to the given file handle. The
writer does not close the handle.
'''
assert handle.tell() == 512 * (self.header.data_block - 1)
scale = abs(self.point_scale)
is_float = self.point_scale < 0
point_dtype = [np.int16, np.float32][is_float]
point_scale = [scale, 1][is_float]
point_format = 'if'[is_float]
raw = np.empty((self.point_used, 4), point_dtype)
for points, analog in self._frames:
valid = points[:, 3] > -1
raw[~valid, 3] = -1
raw[valid, :3] = points[valid, :3] / self._point_scale
raw[valid, 3] = (
((points[valid, 4]).astype(np.uint8) << 8) |
(points[valid, 3] / scale).astype(np.uint16)
)
point = array.array(point_format)
point.extend(raw.flatten())
point.tofile(handle)
analog = array.array(point_format)
analog.extend(analog)
analog.tofile(handle)
self._pad_block(handle) | python | def _write_frames(self, handle):
'''Write our frame data to the given file handle.
Parameters
----------
handle : file
Write metadata and C3D motion frames to the given file handle. The
writer does not close the handle.
'''
assert handle.tell() == 512 * (self.header.data_block - 1)
scale = abs(self.point_scale)
is_float = self.point_scale < 0
point_dtype = [np.int16, np.float32][is_float]
point_scale = [scale, 1][is_float]
point_format = 'if'[is_float]
raw = np.empty((self.point_used, 4), point_dtype)
for points, analog in self._frames:
valid = points[:, 3] > -1
raw[~valid, 3] = -1
raw[valid, :3] = points[valid, :3] / self._point_scale
raw[valid, 3] = (
((points[valid, 4]).astype(np.uint8) << 8) |
(points[valid, 3] / scale).astype(np.uint16)
)
point = array.array(point_format)
point.extend(raw.flatten())
point.tofile(handle)
analog = array.array(point_format)
analog.extend(analog)
analog.tofile(handle)
self._pad_block(handle) | [
"def",
"_write_frames",
"(",
"self",
",",
"handle",
")",
":",
"assert",
"handle",
".",
"tell",
"(",
")",
"==",
"512",
"*",
"(",
"self",
".",
"header",
".",
"data_block",
"-",
"1",
")",
"scale",
"=",
"abs",
"(",
"self",
".",
"point_scale",
")",
"is_... | Write our frame data to the given file handle.
Parameters
----------
handle : file
Write metadata and C3D motion frames to the given file handle. The
writer does not close the handle. | [
"Write",
"our",
"frame",
"data",
"to",
"the",
"given",
"file",
"handle",
"."
] | 391493d9cb4c6b4aaeee4de2930685e3a67f5845 | https://github.com/EmbodiedCognition/py-c3d/blob/391493d9cb4c6b4aaeee4de2930685e3a67f5845/c3d.py#L991-L1021 | train |
EmbodiedCognition/py-c3d | c3d.py | Writer.write | def write(self, handle):
'''Write metadata and point + analog frames to a file handle.
Parameters
----------
handle : file
Write metadata and C3D motion frames to the given file handle. The
writer does not close the handle.
'''
if not self._frames:
return
def add(name, desc, bpe, format, bytes, *dimensions):
group.add_param(name,
desc=desc,
bytes_per_element=bpe,
bytes=struct.pack(format, bytes),
dimensions=list(dimensions))
def add_str(name, desc, bytes, *dimensions):
group.add_param(name,
desc=desc,
bytes_per_element=-1,
bytes=bytes.encode('utf-8'),
dimensions=list(dimensions))
def add_empty_array(name, desc, bpe):
group.add_param(name, desc=desc, bytes_per_element=bpe, dimensions=[0])
points, analog = self._frames[0]
ppf = len(points)
# POINT group
group = self.add_group(1, 'POINT', 'POINT group')
add('USED', 'Number of 3d markers', 2, '<H', ppf)
add('FRAMES', 'frame count', 2, '<H', min(65535, len(self._frames)))
add('DATA_START', 'data block number', 2, '<H', 0)
add('SCALE', '3d scale factor', 4, '<f', self._point_scale)
add('RATE', '3d data capture rate', 4, '<f', self._point_rate)
add_str('X_SCREEN', 'X_SCREEN parameter', '+X', 2)
add_str('Y_SCREEN', 'Y_SCREEN parameter', '+Y', 2)
add_str('UNITS', '3d data units', self._point_units, len(self._point_units))
add_str('LABELS', 'labels', ''.join('M%03d ' % i for i in range(ppf)), 5, ppf)
add_str('DESCRIPTIONS', 'descriptions', ' ' * 16 * ppf, 16, ppf)
# ANALOG group
group = self.add_group(2, 'ANALOG', 'ANALOG group')
add('USED', 'analog channel count', 2, '<H', analog.shape[0])
add('RATE', 'analog samples per 3d frame', 4, '<f', analog.shape[1])
add('GEN_SCALE', 'analog general scale factor', 4, '<f', self._gen_scale)
add_empty_array('SCALE', 'analog channel scale factors', 4)
add_empty_array('OFFSET', 'analog channel offsets', 2)
# TRIAL group
group = self.add_group(3, 'TRIAL', 'TRIAL group')
add('ACTUAL_START_FIELD', 'actual start frame', 2, '<I', 1, 2)
add('ACTUAL_END_FIELD', 'actual end frame', 2, '<I', len(self._frames), 2)
# sync parameter information to header.
blocks = self.parameter_blocks()
self.get('POINT:DATA_START').bytes = struct.pack('<H', 2 + blocks)
self.header.data_block = 2 + blocks
self.header.frame_rate = self._point_rate
self.header.last_frame = min(len(self._frames), 65535)
self.header.point_count = ppf
self.header.analog_count = np.prod(analog.shape)
self.header.analog_per_frame = analog.shape[0]
self.header.scale_factor = self._point_scale
self._write_metadata(handle)
self._write_frames(handle) | python | def write(self, handle):
'''Write metadata and point + analog frames to a file handle.
Parameters
----------
handle : file
Write metadata and C3D motion frames to the given file handle. The
writer does not close the handle.
'''
if not self._frames:
return
def add(name, desc, bpe, format, bytes, *dimensions):
group.add_param(name,
desc=desc,
bytes_per_element=bpe,
bytes=struct.pack(format, bytes),
dimensions=list(dimensions))
def add_str(name, desc, bytes, *dimensions):
group.add_param(name,
desc=desc,
bytes_per_element=-1,
bytes=bytes.encode('utf-8'),
dimensions=list(dimensions))
def add_empty_array(name, desc, bpe):
group.add_param(name, desc=desc, bytes_per_element=bpe, dimensions=[0])
points, analog = self._frames[0]
ppf = len(points)
# POINT group
group = self.add_group(1, 'POINT', 'POINT group')
add('USED', 'Number of 3d markers', 2, '<H', ppf)
add('FRAMES', 'frame count', 2, '<H', min(65535, len(self._frames)))
add('DATA_START', 'data block number', 2, '<H', 0)
add('SCALE', '3d scale factor', 4, '<f', self._point_scale)
add('RATE', '3d data capture rate', 4, '<f', self._point_rate)
add_str('X_SCREEN', 'X_SCREEN parameter', '+X', 2)
add_str('Y_SCREEN', 'Y_SCREEN parameter', '+Y', 2)
add_str('UNITS', '3d data units', self._point_units, len(self._point_units))
add_str('LABELS', 'labels', ''.join('M%03d ' % i for i in range(ppf)), 5, ppf)
add_str('DESCRIPTIONS', 'descriptions', ' ' * 16 * ppf, 16, ppf)
# ANALOG group
group = self.add_group(2, 'ANALOG', 'ANALOG group')
add('USED', 'analog channel count', 2, '<H', analog.shape[0])
add('RATE', 'analog samples per 3d frame', 4, '<f', analog.shape[1])
add('GEN_SCALE', 'analog general scale factor', 4, '<f', self._gen_scale)
add_empty_array('SCALE', 'analog channel scale factors', 4)
add_empty_array('OFFSET', 'analog channel offsets', 2)
# TRIAL group
group = self.add_group(3, 'TRIAL', 'TRIAL group')
add('ACTUAL_START_FIELD', 'actual start frame', 2, '<I', 1, 2)
add('ACTUAL_END_FIELD', 'actual end frame', 2, '<I', len(self._frames), 2)
# sync parameter information to header.
blocks = self.parameter_blocks()
self.get('POINT:DATA_START').bytes = struct.pack('<H', 2 + blocks)
self.header.data_block = 2 + blocks
self.header.frame_rate = self._point_rate
self.header.last_frame = min(len(self._frames), 65535)
self.header.point_count = ppf
self.header.analog_count = np.prod(analog.shape)
self.header.analog_per_frame = analog.shape[0]
self.header.scale_factor = self._point_scale
self._write_metadata(handle)
self._write_frames(handle) | [
"def",
"write",
"(",
"self",
",",
"handle",
")",
":",
"if",
"not",
"self",
".",
"_frames",
":",
"return",
"def",
"add",
"(",
"name",
",",
"desc",
",",
"bpe",
",",
"format",
",",
"bytes",
",",
"*",
"dimensions",
")",
":",
"group",
".",
"add_param",
... | Write metadata and point + analog frames to a file handle.
Parameters
----------
handle : file
Write metadata and C3D motion frames to the given file handle. The
writer does not close the handle. | [
"Write",
"metadata",
"and",
"point",
"+",
"analog",
"frames",
"to",
"a",
"file",
"handle",
"."
] | 391493d9cb4c6b4aaeee4de2930685e3a67f5845 | https://github.com/EmbodiedCognition/py-c3d/blob/391493d9cb4c6b4aaeee4de2930685e3a67f5845/c3d.py#L1023-L1094 | train |
dbarrosop/sir | sir/helpers/SQLite3Helper.py | SQLite3Helper.aggregate_per_prefix | def aggregate_per_prefix(self, start_time, end_time, limit=0, net_masks='', exclude_net_masks=False, filter_proto=None):
""" Given a time range aggregates bytes per prefix.
Args:
start_time: A string representing the starting time of the time range
end_time: A string representing the ending time of the time range
limit: An optional integer. If it's >0 it will limit the amount of prefixes returned.
filter_proto: Can be:
- None: Returns both ipv4 and ipv6
- 4: Returns only ipv4
- 6: Retruns only ipv6
Returns:
A list of prefixes sorted by sum_bytes. For example:
[
{'key': '192.168.1.0/25', 'sum_bytes': 3000, 'as_dst': 345},
{'key': '192.213.1.0/25', 'sum_bytes': 2000, 'as_dst': 123},
{'key': '231.168.1.0/25', 'sum_bytes': 1000, 'as_dst': 321},
]
"""
if net_masks == '':
net_mask_filter = ''
elif not exclude_net_masks:
net_mask_filter = 'AND mask_dst IN ({})'.format(net_masks)
elif exclude_net_masks:
net_mask_filter = 'AND mask_dst NOT IN ({})'.format(net_masks)
if filter_proto is None:
proto_filter = ''
elif int(filter_proto) == 4:
proto_filter = 'AND ip_dst NOT LIKE "%:%"'
elif int(filter_proto) == 6:
proto_filter = 'AND ip_dst LIKE "%:%"'
query = ''' SELECT ip_dst||'/'||mask_dst as key, SUM(bytes) as sum_bytes, as_dst
from acct
WHERE
datetime(stamp_updated) BETWEEN datetime(?) AND datetime(?, "+1 second")
{}
{}
GROUP by ip_dst,mask_dst
ORDER BY SUM(bytes) DESC
'''.format(net_mask_filter, proto_filter)
if limit > 0:
query += 'LIMIT %d' % limit
return self._execute_query(query, [start_time, end_time]) | python | def aggregate_per_prefix(self, start_time, end_time, limit=0, net_masks='', exclude_net_masks=False, filter_proto=None):
""" Given a time range aggregates bytes per prefix.
Args:
start_time: A string representing the starting time of the time range
end_time: A string representing the ending time of the time range
limit: An optional integer. If it's >0 it will limit the amount of prefixes returned.
filter_proto: Can be:
- None: Returns both ipv4 and ipv6
- 4: Returns only ipv4
- 6: Retruns only ipv6
Returns:
A list of prefixes sorted by sum_bytes. For example:
[
{'key': '192.168.1.0/25', 'sum_bytes': 3000, 'as_dst': 345},
{'key': '192.213.1.0/25', 'sum_bytes': 2000, 'as_dst': 123},
{'key': '231.168.1.0/25', 'sum_bytes': 1000, 'as_dst': 321},
]
"""
if net_masks == '':
net_mask_filter = ''
elif not exclude_net_masks:
net_mask_filter = 'AND mask_dst IN ({})'.format(net_masks)
elif exclude_net_masks:
net_mask_filter = 'AND mask_dst NOT IN ({})'.format(net_masks)
if filter_proto is None:
proto_filter = ''
elif int(filter_proto) == 4:
proto_filter = 'AND ip_dst NOT LIKE "%:%"'
elif int(filter_proto) == 6:
proto_filter = 'AND ip_dst LIKE "%:%"'
query = ''' SELECT ip_dst||'/'||mask_dst as key, SUM(bytes) as sum_bytes, as_dst
from acct
WHERE
datetime(stamp_updated) BETWEEN datetime(?) AND datetime(?, "+1 second")
{}
{}
GROUP by ip_dst,mask_dst
ORDER BY SUM(bytes) DESC
'''.format(net_mask_filter, proto_filter)
if limit > 0:
query += 'LIMIT %d' % limit
return self._execute_query(query, [start_time, end_time]) | [
"def",
"aggregate_per_prefix",
"(",
"self",
",",
"start_time",
",",
"end_time",
",",
"limit",
"=",
"0",
",",
"net_masks",
"=",
"''",
",",
"exclude_net_masks",
"=",
"False",
",",
"filter_proto",
"=",
"None",
")",
":",
"if",
"net_masks",
"==",
"''",
":",
"... | Given a time range aggregates bytes per prefix.
Args:
start_time: A string representing the starting time of the time range
end_time: A string representing the ending time of the time range
limit: An optional integer. If it's >0 it will limit the amount of prefixes returned.
filter_proto: Can be:
- None: Returns both ipv4 and ipv6
- 4: Returns only ipv4
- 6: Retruns only ipv6
Returns:
A list of prefixes sorted by sum_bytes. For example:
[
{'key': '192.168.1.0/25', 'sum_bytes': 3000, 'as_dst': 345},
{'key': '192.213.1.0/25', 'sum_bytes': 2000, 'as_dst': 123},
{'key': '231.168.1.0/25', 'sum_bytes': 1000, 'as_dst': 321},
] | [
"Given",
"a",
"time",
"range",
"aggregates",
"bytes",
"per",
"prefix",
"."
] | c1f4c086404b8474f0a560fcc6f49aa4c86f6916 | https://github.com/dbarrosop/sir/blob/c1f4c086404b8474f0a560fcc6f49aa4c86f6916/sir/helpers/SQLite3Helper.py#L43-L91 | train |
dbarrosop/sir | sir/helpers/SQLite3Helper.py | SQLite3Helper.aggregate_per_as | def aggregate_per_as(self, start_time, end_time):
""" Given a time range aggregates bytes per ASNs.
Args:
start_time: A string representing the starting time of the time range
end_time: A string representing the ending time of the time range
Returns:
A list of prefixes sorted by sum_bytes. For example:
[
{'key': '6500', 'sum_bytes': 3000},
{'key': '2310', 'sum_bytes': 2000},
{'key': '8182', 'sum_bytes': 1000},
]
"""
query = ''' SELECT as_dst as key, SUM(bytes) as sum_bytes
from acct
WHERE
datetime(stamp_updated) BETWEEN datetime(?) AND datetime(?, "+1 second")
GROUP by as_dst
ORDER BY SUM(bytes) DESC;
'''
return self._execute_query(query, [start_time, end_time]) | python | def aggregate_per_as(self, start_time, end_time):
""" Given a time range aggregates bytes per ASNs.
Args:
start_time: A string representing the starting time of the time range
end_time: A string representing the ending time of the time range
Returns:
A list of prefixes sorted by sum_bytes. For example:
[
{'key': '6500', 'sum_bytes': 3000},
{'key': '2310', 'sum_bytes': 2000},
{'key': '8182', 'sum_bytes': 1000},
]
"""
query = ''' SELECT as_dst as key, SUM(bytes) as sum_bytes
from acct
WHERE
datetime(stamp_updated) BETWEEN datetime(?) AND datetime(?, "+1 second")
GROUP by as_dst
ORDER BY SUM(bytes) DESC;
'''
return self._execute_query(query, [start_time, end_time]) | [
"def",
"aggregate_per_as",
"(",
"self",
",",
"start_time",
",",
"end_time",
")",
":",
"query",
"=",
"''' SELECT as_dst as key, SUM(bytes) as sum_bytes\n from acct\n WHERE\n datetime(stamp_updated) BETWEEN datetime(?) AND datetime(?, \"... | Given a time range aggregates bytes per ASNs.
Args:
start_time: A string representing the starting time of the time range
end_time: A string representing the ending time of the time range
Returns:
A list of prefixes sorted by sum_bytes. For example:
[
{'key': '6500', 'sum_bytes': 3000},
{'key': '2310', 'sum_bytes': 2000},
{'key': '8182', 'sum_bytes': 1000},
] | [
"Given",
"a",
"time",
"range",
"aggregates",
"bytes",
"per",
"ASNs",
"."
] | c1f4c086404b8474f0a560fcc6f49aa4c86f6916 | https://github.com/dbarrosop/sir/blob/c1f4c086404b8474f0a560fcc6f49aa4c86f6916/sir/helpers/SQLite3Helper.py#L93-L118 | train |
tjvr/kurt | kurt/plugin.py | _workaround_no_vector_images | def _workaround_no_vector_images(project):
"""Replace vector images with fake ones."""
RED = (255, 0, 0)
PLACEHOLDER = kurt.Image.new((32, 32), RED)
for scriptable in [project.stage] + project.sprites:
for costume in scriptable.costumes:
if costume.image.format == "SVG":
yield "%s - %s" % (scriptable.name, costume.name)
costume.image = PLACEHOLDER | python | def _workaround_no_vector_images(project):
"""Replace vector images with fake ones."""
RED = (255, 0, 0)
PLACEHOLDER = kurt.Image.new((32, 32), RED)
for scriptable in [project.stage] + project.sprites:
for costume in scriptable.costumes:
if costume.image.format == "SVG":
yield "%s - %s" % (scriptable.name, costume.name)
costume.image = PLACEHOLDER | [
"def",
"_workaround_no_vector_images",
"(",
"project",
")",
":",
"RED",
"=",
"(",
"255",
",",
"0",
",",
"0",
")",
"PLACEHOLDER",
"=",
"kurt",
".",
"Image",
".",
"new",
"(",
"(",
"32",
",",
"32",
")",
",",
"RED",
")",
"for",
"scriptable",
"in",
"[",... | Replace vector images with fake ones. | [
"Replace",
"vector",
"images",
"with",
"fake",
"ones",
"."
] | fcccd80cae11dc233f6dd02b40ec9a388c62f259 | https://github.com/tjvr/kurt/blob/fcccd80cae11dc233f6dd02b40ec9a388c62f259/kurt/plugin.py#L313-L321 | train |
tjvr/kurt | kurt/plugin.py | _workaround_no_stage_specific_variables | def _workaround_no_stage_specific_variables(project):
"""Make Stage-specific variables global (move them to Project)."""
for (name, var) in project.stage.variables.items():
yield "variable %s" % name
for (name, _list) in project.stage.lists.items():
yield "list %s" % name
project.variables.update(project.stage.variables)
project.lists.update(project.stage.lists)
project.stage.variables = {}
project.stage.lists = {} | python | def _workaround_no_stage_specific_variables(project):
"""Make Stage-specific variables global (move them to Project)."""
for (name, var) in project.stage.variables.items():
yield "variable %s" % name
for (name, _list) in project.stage.lists.items():
yield "list %s" % name
project.variables.update(project.stage.variables)
project.lists.update(project.stage.lists)
project.stage.variables = {}
project.stage.lists = {} | [
"def",
"_workaround_no_stage_specific_variables",
"(",
"project",
")",
":",
"for",
"(",
"name",
",",
"var",
")",
"in",
"project",
".",
"stage",
".",
"variables",
".",
"items",
"(",
")",
":",
"yield",
"\"variable %s\"",
"%",
"name",
"for",
"(",
"name",
",",... | Make Stage-specific variables global (move them to Project). | [
"Make",
"Stage",
"-",
"specific",
"variables",
"global",
"(",
"move",
"them",
"to",
"Project",
")",
"."
] | fcccd80cae11dc233f6dd02b40ec9a388c62f259 | https://github.com/tjvr/kurt/blob/fcccd80cae11dc233f6dd02b40ec9a388c62f259/kurt/plugin.py#L328-L337 | train |
tjvr/kurt | kurt/plugin.py | Kurt.register | def register(cls, plugin):
"""Register a new :class:`KurtPlugin`.
Once registered, the plugin can be used by :class:`Project`, when:
* :attr:`Project.load` sees a file with the right extension
* :attr:`Project.convert` is called with the format as a parameter
"""
cls.plugins[plugin.name] = plugin
# make features
plugin.features = map(Feature.get, plugin.features)
# fix blocks
blocks = []
for pbt in plugin.blocks:
if pbt:
pbt = pbt.copy()
pbt.format = plugin.name
blocks.append(pbt)
plugin.blocks = blocks
# add blocks
new_blocks = filter(None, plugin.blocks)
for pbt in new_blocks:
for bt in cls.blocks:
if (bt.has_command(pbt.command) or
bt.has_command(pbt._match)):
bt._add_conversion(plugin.name, pbt)
break
else:
if pbt._match:
raise ValueError, "Couldn't match %r" % pbt._match
cls.blocks.append(kurt.BlockType(pbt)) | python | def register(cls, plugin):
"""Register a new :class:`KurtPlugin`.
Once registered, the plugin can be used by :class:`Project`, when:
* :attr:`Project.load` sees a file with the right extension
* :attr:`Project.convert` is called with the format as a parameter
"""
cls.plugins[plugin.name] = plugin
# make features
plugin.features = map(Feature.get, plugin.features)
# fix blocks
blocks = []
for pbt in plugin.blocks:
if pbt:
pbt = pbt.copy()
pbt.format = plugin.name
blocks.append(pbt)
plugin.blocks = blocks
# add blocks
new_blocks = filter(None, plugin.blocks)
for pbt in new_blocks:
for bt in cls.blocks:
if (bt.has_command(pbt.command) or
bt.has_command(pbt._match)):
bt._add_conversion(plugin.name, pbt)
break
else:
if pbt._match:
raise ValueError, "Couldn't match %r" % pbt._match
cls.blocks.append(kurt.BlockType(pbt)) | [
"def",
"register",
"(",
"cls",
",",
"plugin",
")",
":",
"cls",
".",
"plugins",
"[",
"plugin",
".",
"name",
"]",
"=",
"plugin",
"# make features",
"plugin",
".",
"features",
"=",
"map",
"(",
"Feature",
".",
"get",
",",
"plugin",
".",
"features",
")",
... | Register a new :class:`KurtPlugin`.
Once registered, the plugin can be used by :class:`Project`, when:
* :attr:`Project.load` sees a file with the right extension
* :attr:`Project.convert` is called with the format as a parameter | [
"Register",
"a",
"new",
":",
"class",
":",
"KurtPlugin",
"."
] | fcccd80cae11dc233f6dd02b40ec9a388c62f259 | https://github.com/tjvr/kurt/blob/fcccd80cae11dc233f6dd02b40ec9a388c62f259/kurt/plugin.py#L150-L185 | train |
tjvr/kurt | kurt/plugin.py | Kurt.get_plugin | def get_plugin(cls, name=None, **kwargs):
"""Returns the first format plugin whose attributes match kwargs.
For example::
get_plugin(extension="scratch14")
Will return the :class:`KurtPlugin` whose :attr:`extension
<KurtPlugin.extension>` attribute is ``"scratch14"``.
The :attr:`name <KurtPlugin.name>` is used as the ``format`` parameter
to :attr:`Project.load` and :attr:`Project.save`.
:raises: :class:`ValueError` if the format doesn't exist.
:returns: :class:`KurtPlugin`
"""
if isinstance(name, KurtPlugin):
return name
if 'extension' in kwargs:
kwargs['extension'] = kwargs['extension'].lower()
if name:
kwargs["name"] = name
if not kwargs:
raise ValueError, "No arguments"
for plugin in cls.plugins.values():
for name in kwargs:
if getattr(plugin, name) != kwargs[name]:
break
else:
return plugin
raise ValueError, "Unknown format %r" % kwargs | python | def get_plugin(cls, name=None, **kwargs):
"""Returns the first format plugin whose attributes match kwargs.
For example::
get_plugin(extension="scratch14")
Will return the :class:`KurtPlugin` whose :attr:`extension
<KurtPlugin.extension>` attribute is ``"scratch14"``.
The :attr:`name <KurtPlugin.name>` is used as the ``format`` parameter
to :attr:`Project.load` and :attr:`Project.save`.
:raises: :class:`ValueError` if the format doesn't exist.
:returns: :class:`KurtPlugin`
"""
if isinstance(name, KurtPlugin):
return name
if 'extension' in kwargs:
kwargs['extension'] = kwargs['extension'].lower()
if name:
kwargs["name"] = name
if not kwargs:
raise ValueError, "No arguments"
for plugin in cls.plugins.values():
for name in kwargs:
if getattr(plugin, name) != kwargs[name]:
break
else:
return plugin
raise ValueError, "Unknown format %r" % kwargs | [
"def",
"get_plugin",
"(",
"cls",
",",
"name",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"isinstance",
"(",
"name",
",",
"KurtPlugin",
")",
":",
"return",
"name",
"if",
"'extension'",
"in",
"kwargs",
":",
"kwargs",
"[",
"'extension'",
"]",
... | Returns the first format plugin whose attributes match kwargs.
For example::
get_plugin(extension="scratch14")
Will return the :class:`KurtPlugin` whose :attr:`extension
<KurtPlugin.extension>` attribute is ``"scratch14"``.
The :attr:`name <KurtPlugin.name>` is used as the ``format`` parameter
to :attr:`Project.load` and :attr:`Project.save`.
:raises: :class:`ValueError` if the format doesn't exist.
:returns: :class:`KurtPlugin` | [
"Returns",
"the",
"first",
"format",
"plugin",
"whose",
"attributes",
"match",
"kwargs",
"."
] | fcccd80cae11dc233f6dd02b40ec9a388c62f259 | https://github.com/tjvr/kurt/blob/fcccd80cae11dc233f6dd02b40ec9a388c62f259/kurt/plugin.py#L188-L223 | train |
tjvr/kurt | kurt/plugin.py | Kurt.block_by_command | def block_by_command(cls, command):
"""Return the block with the given :attr:`command`.
Returns None if the block is not found.
"""
for block in cls.blocks:
if block.has_command(command):
return block | python | def block_by_command(cls, command):
"""Return the block with the given :attr:`command`.
Returns None if the block is not found.
"""
for block in cls.blocks:
if block.has_command(command):
return block | [
"def",
"block_by_command",
"(",
"cls",
",",
"command",
")",
":",
"for",
"block",
"in",
"cls",
".",
"blocks",
":",
"if",
"block",
".",
"has_command",
"(",
"command",
")",
":",
"return",
"block"
] | Return the block with the given :attr:`command`.
Returns None if the block is not found. | [
"Return",
"the",
"block",
"with",
"the",
"given",
":",
"attr",
":",
"command",
"."
] | fcccd80cae11dc233f6dd02b40ec9a388c62f259 | https://github.com/tjvr/kurt/blob/fcccd80cae11dc233f6dd02b40ec9a388c62f259/kurt/plugin.py#L226-L234 | train |
tjvr/kurt | kurt/plugin.py | Kurt.blocks_by_text | def blocks_by_text(cls, text):
"""Return a list of blocks matching the given :attr:`text`.
Capitalisation and spaces are ignored.
"""
text = kurt.BlockType._strip_text(text)
matches = []
for block in cls.blocks:
for pbt in block.conversions:
if pbt.stripped_text == text:
matches.append(block)
break
return matches | python | def blocks_by_text(cls, text):
"""Return a list of blocks matching the given :attr:`text`.
Capitalisation and spaces are ignored.
"""
text = kurt.BlockType._strip_text(text)
matches = []
for block in cls.blocks:
for pbt in block.conversions:
if pbt.stripped_text == text:
matches.append(block)
break
return matches | [
"def",
"blocks_by_text",
"(",
"cls",
",",
"text",
")",
":",
"text",
"=",
"kurt",
".",
"BlockType",
".",
"_strip_text",
"(",
"text",
")",
"matches",
"=",
"[",
"]",
"for",
"block",
"in",
"cls",
".",
"blocks",
":",
"for",
"pbt",
"in",
"block",
".",
"c... | Return a list of blocks matching the given :attr:`text`.
Capitalisation and spaces are ignored. | [
"Return",
"a",
"list",
"of",
"blocks",
"matching",
"the",
"given",
":",
"attr",
":",
"text",
"."
] | fcccd80cae11dc233f6dd02b40ec9a388c62f259 | https://github.com/tjvr/kurt/blob/fcccd80cae11dc233f6dd02b40ec9a388c62f259/kurt/plugin.py#L237-L250 | train |
tjvr/kurt | kurt/scratch14/heights.py | clean_up | def clean_up(scripts):
"""Clean up the given list of scripts in-place so none of the scripts
overlap.
"""
scripts_with_pos = [s for s in scripts if s.pos]
scripts_with_pos.sort(key=lambda s: (s.pos[1], s.pos[0]))
scripts = scripts_with_pos + [s for s in scripts if not s.pos]
y = 20
for script in scripts:
script.pos = (20, y)
if isinstance(script, kurt.Script):
y += stack_height(script.blocks)
elif isinstance(script, kurt.Comment):
y += 14
y += 15 | python | def clean_up(scripts):
"""Clean up the given list of scripts in-place so none of the scripts
overlap.
"""
scripts_with_pos = [s for s in scripts if s.pos]
scripts_with_pos.sort(key=lambda s: (s.pos[1], s.pos[0]))
scripts = scripts_with_pos + [s for s in scripts if not s.pos]
y = 20
for script in scripts:
script.pos = (20, y)
if isinstance(script, kurt.Script):
y += stack_height(script.blocks)
elif isinstance(script, kurt.Comment):
y += 14
y += 15 | [
"def",
"clean_up",
"(",
"scripts",
")",
":",
"scripts_with_pos",
"=",
"[",
"s",
"for",
"s",
"in",
"scripts",
"if",
"s",
".",
"pos",
"]",
"scripts_with_pos",
".",
"sort",
"(",
"key",
"=",
"lambda",
"s",
":",
"(",
"s",
".",
"pos",
"[",
"1",
"]",
",... | Clean up the given list of scripts in-place so none of the scripts
overlap. | [
"Clean",
"up",
"the",
"given",
"list",
"of",
"scripts",
"in",
"-",
"place",
"so",
"none",
"of",
"the",
"scripts",
"overlap",
"."
] | fcccd80cae11dc233f6dd02b40ec9a388c62f259 | https://github.com/tjvr/kurt/blob/fcccd80cae11dc233f6dd02b40ec9a388c62f259/kurt/scratch14/heights.py#L106-L122 | train |
tjvr/kurt | kurt/scratch14/objtable.py | obj_classes_from_module | def obj_classes_from_module(module):
"""Return a list of classes in a module that have a 'classID' attribute."""
for name in dir(module):
if not name.startswith('_'):
cls = getattr(module, name)
if getattr(cls, 'classID', None):
yield (name, cls) | python | def obj_classes_from_module(module):
"""Return a list of classes in a module that have a 'classID' attribute."""
for name in dir(module):
if not name.startswith('_'):
cls = getattr(module, name)
if getattr(cls, 'classID', None):
yield (name, cls) | [
"def",
"obj_classes_from_module",
"(",
"module",
")",
":",
"for",
"name",
"in",
"dir",
"(",
"module",
")",
":",
"if",
"not",
"name",
".",
"startswith",
"(",
"'_'",
")",
":",
"cls",
"=",
"getattr",
"(",
"module",
",",
"name",
")",
"if",
"getattr",
"("... | Return a list of classes in a module that have a 'classID' attribute. | [
"Return",
"a",
"list",
"of",
"classes",
"in",
"a",
"module",
"that",
"have",
"a",
"classID",
"attribute",
"."
] | fcccd80cae11dc233f6dd02b40ec9a388c62f259 | https://github.com/tjvr/kurt/blob/fcccd80cae11dc233f6dd02b40ec9a388c62f259/kurt/scratch14/objtable.py#L82-L88 | train |
tjvr/kurt | kurt/scratch14/objtable.py | decode_network | def decode_network(objects):
"""Return root object from ref-containing obj table entries"""
def resolve_ref(obj, objects=objects):
if isinstance(obj, Ref):
# first entry is 1
return objects[obj.index - 1]
else:
return obj
# Reading the ObjTable backwards somehow makes more sense.
for i in xrange(len(objects)-1, -1, -1):
obj = objects[i]
if isinstance(obj, Container):
obj.update((k, resolve_ref(v)) for (k, v) in obj.items())
elif isinstance(obj, Dictionary):
obj.value = dict(
(resolve_ref(field), resolve_ref(value))
for (field, value) in obj.value.items()
)
elif isinstance(obj, dict):
obj = dict(
(resolve_ref(field), resolve_ref(value))
for (field, value) in obj.items()
)
elif isinstance(obj, list):
obj = [resolve_ref(field) for field in obj]
elif isinstance(obj, Form):
for field in obj.value:
value = getattr(obj, field)
value = resolve_ref(value)
setattr(obj, field, value)
elif isinstance(obj, ContainsRefs):
obj.value = [resolve_ref(field) for field in obj.value]
objects[i] = obj
for obj in objects:
if isinstance(obj, Form):
obj.built()
root = objects[0]
return root | python | def decode_network(objects):
"""Return root object from ref-containing obj table entries"""
def resolve_ref(obj, objects=objects):
if isinstance(obj, Ref):
# first entry is 1
return objects[obj.index - 1]
else:
return obj
# Reading the ObjTable backwards somehow makes more sense.
for i in xrange(len(objects)-1, -1, -1):
obj = objects[i]
if isinstance(obj, Container):
obj.update((k, resolve_ref(v)) for (k, v) in obj.items())
elif isinstance(obj, Dictionary):
obj.value = dict(
(resolve_ref(field), resolve_ref(value))
for (field, value) in obj.value.items()
)
elif isinstance(obj, dict):
obj = dict(
(resolve_ref(field), resolve_ref(value))
for (field, value) in obj.items()
)
elif isinstance(obj, list):
obj = [resolve_ref(field) for field in obj]
elif isinstance(obj, Form):
for field in obj.value:
value = getattr(obj, field)
value = resolve_ref(value)
setattr(obj, field, value)
elif isinstance(obj, ContainsRefs):
obj.value = [resolve_ref(field) for field in obj.value]
objects[i] = obj
for obj in objects:
if isinstance(obj, Form):
obj.built()
root = objects[0]
return root | [
"def",
"decode_network",
"(",
"objects",
")",
":",
"def",
"resolve_ref",
"(",
"obj",
",",
"objects",
"=",
"objects",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"Ref",
")",
":",
"# first entry is 1",
"return",
"objects",
"[",
"obj",
".",
"index",
"-",... | Return root object from ref-containing obj table entries | [
"Return",
"root",
"object",
"from",
"ref",
"-",
"containing",
"obj",
"table",
"entries"
] | fcccd80cae11dc233f6dd02b40ec9a388c62f259 | https://github.com/tjvr/kurt/blob/fcccd80cae11dc233f6dd02b40ec9a388c62f259/kurt/scratch14/objtable.py#L251-L298 | train |
tjvr/kurt | kurt/scratch14/objtable.py | encode_network | def encode_network(root):
"""Yield ref-containing obj table entries from object network"""
orig_objects = []
objects = []
def get_ref(value, objects=objects):
"""Returns the index of the given object in the object table,
adding it if needed.
"""
value = PythonicAdapter(Pass)._encode(value, None)
# Convert strs to FixedObjects here to make sure they get encoded
# correctly
if isinstance(value, (Container, FixedObject)):
if getattr(value, '_tmp_index', None):
index = value._tmp_index
else:
objects.append(value)
index = len(objects)
value._tmp_index = index
orig_objects.append(value) # save the object so we can
# strip the _tmp_indexes later
return Ref(index)
else:
return value # Inline value
def fix_fields(obj):
obj = PythonicAdapter(Pass)._encode(obj, None)
# Convert strs to FixedObjects here to make sure they get encoded
# correctly
if isinstance(obj, Container):
obj.update((k, get_ref(v)) for (k, v) in obj.items()
if k != 'class_name')
fixed_obj = obj
elif isinstance(obj, Dictionary):
fixed_obj = obj.__class__(dict(
(get_ref(field), get_ref(value))
for (field, value) in obj.value.items()
))
elif isinstance(obj, dict):
fixed_obj = dict(
(get_ref(field), get_ref(value))
for (field, value) in obj.items()
)
elif isinstance(obj, list):
fixed_obj = [get_ref(field) for field in obj]
elif isinstance(obj, Form):
fixed_obj = obj.__class__(**dict(
(field, get_ref(value))
for (field, value) in obj.value.items()
))
elif isinstance(obj, ContainsRefs):
fixed_obj = obj.__class__([get_ref(field)
for field in obj.value])
else:
return obj
fixed_obj._made_from = obj
return fixed_obj
root = PythonicAdapter(Pass)._encode(root, None)
i = 0
objects = [root]
root._tmp_index = 1
while i < len(objects):
objects[i] = fix_fields(objects[i])
i += 1
for obj in orig_objects:
obj._tmp_index = None
# Strip indexes off objects in case we save again later
return objects | python | def encode_network(root):
"""Yield ref-containing obj table entries from object network"""
orig_objects = []
objects = []
def get_ref(value, objects=objects):
"""Returns the index of the given object in the object table,
adding it if needed.
"""
value = PythonicAdapter(Pass)._encode(value, None)
# Convert strs to FixedObjects here to make sure they get encoded
# correctly
if isinstance(value, (Container, FixedObject)):
if getattr(value, '_tmp_index', None):
index = value._tmp_index
else:
objects.append(value)
index = len(objects)
value._tmp_index = index
orig_objects.append(value) # save the object so we can
# strip the _tmp_indexes later
return Ref(index)
else:
return value # Inline value
def fix_fields(obj):
obj = PythonicAdapter(Pass)._encode(obj, None)
# Convert strs to FixedObjects here to make sure they get encoded
# correctly
if isinstance(obj, Container):
obj.update((k, get_ref(v)) for (k, v) in obj.items()
if k != 'class_name')
fixed_obj = obj
elif isinstance(obj, Dictionary):
fixed_obj = obj.__class__(dict(
(get_ref(field), get_ref(value))
for (field, value) in obj.value.items()
))
elif isinstance(obj, dict):
fixed_obj = dict(
(get_ref(field), get_ref(value))
for (field, value) in obj.items()
)
elif isinstance(obj, list):
fixed_obj = [get_ref(field) for field in obj]
elif isinstance(obj, Form):
fixed_obj = obj.__class__(**dict(
(field, get_ref(value))
for (field, value) in obj.value.items()
))
elif isinstance(obj, ContainsRefs):
fixed_obj = obj.__class__([get_ref(field)
for field in obj.value])
else:
return obj
fixed_obj._made_from = obj
return fixed_obj
root = PythonicAdapter(Pass)._encode(root, None)
i = 0
objects = [root]
root._tmp_index = 1
while i < len(objects):
objects[i] = fix_fields(objects[i])
i += 1
for obj in orig_objects:
obj._tmp_index = None
# Strip indexes off objects in case we save again later
return objects | [
"def",
"encode_network",
"(",
"root",
")",
":",
"orig_objects",
"=",
"[",
"]",
"objects",
"=",
"[",
"]",
"def",
"get_ref",
"(",
"value",
",",
"objects",
"=",
"objects",
")",
":",
"\"\"\"Returns the index of the given object in the object table,\n adding it if n... | Yield ref-containing obj table entries from object network | [
"Yield",
"ref",
"-",
"containing",
"obj",
"table",
"entries",
"from",
"object",
"network"
] | fcccd80cae11dc233f6dd02b40ec9a388c62f259 | https://github.com/tjvr/kurt/blob/fcccd80cae11dc233f6dd02b40ec9a388c62f259/kurt/scratch14/objtable.py#L300-L381 | train |
tjvr/kurt | kurt/scratch14/objtable.py | encode_network | def encode_network(root):
"""Yield ref-containing obj table entries from object network"""
def fix_values(obj):
if isinstance(obj, Container):
obj.update((k, get_ref(v)) for (k, v) in obj.items()
if k != 'class_name')
fixed_obj = obj
elif isinstance(obj, Dictionary):
fixed_obj = obj.__class__(dict(
(get_ref(field), get_ref(value))
for (field, value) in obj.value.items()
))
elif isinstance(obj, dict):
fixed_obj = dict(
(get_ref(field), get_ref(value))
for (field, value) in obj.items()
)
elif isinstance(obj, list):
fixed_obj = [get_ref(field) for field in obj]
elif isinstance(obj, Form):
fixed_obj = obj.__class__(**dict(
(field, get_ref(value))
for (field, value) in obj.value.items()
))
elif isinstance(obj, ContainsRefs):
fixed_obj = obj.__class__([get_ref(field)
for field in obj.value])
else:
return obj
fixed_obj._made_from = obj
return fixed_obj
objects = []
def get_ref(obj, objects=objects):
obj = PythonicAdapter(Pass)._encode(obj, None)
if isinstance(obj, (FixedObject, Container)):
if getattr(obj, '_index', None):
index = obj._index
else:
objects.append(None)
obj._index = index = len(objects)
objects[index - 1] = fix_values(obj)
return Ref(index)
else:
return obj # Inline value
get_ref(root)
for obj in objects:
if getattr(obj, '_index', None):
del obj._index
return objects | python | def encode_network(root):
"""Yield ref-containing obj table entries from object network"""
def fix_values(obj):
if isinstance(obj, Container):
obj.update((k, get_ref(v)) for (k, v) in obj.items()
if k != 'class_name')
fixed_obj = obj
elif isinstance(obj, Dictionary):
fixed_obj = obj.__class__(dict(
(get_ref(field), get_ref(value))
for (field, value) in obj.value.items()
))
elif isinstance(obj, dict):
fixed_obj = dict(
(get_ref(field), get_ref(value))
for (field, value) in obj.items()
)
elif isinstance(obj, list):
fixed_obj = [get_ref(field) for field in obj]
elif isinstance(obj, Form):
fixed_obj = obj.__class__(**dict(
(field, get_ref(value))
for (field, value) in obj.value.items()
))
elif isinstance(obj, ContainsRefs):
fixed_obj = obj.__class__([get_ref(field)
for field in obj.value])
else:
return obj
fixed_obj._made_from = obj
return fixed_obj
objects = []
def get_ref(obj, objects=objects):
obj = PythonicAdapter(Pass)._encode(obj, None)
if isinstance(obj, (FixedObject, Container)):
if getattr(obj, '_index', None):
index = obj._index
else:
objects.append(None)
obj._index = index = len(objects)
objects[index - 1] = fix_values(obj)
return Ref(index)
else:
return obj # Inline value
get_ref(root)
for obj in objects:
if getattr(obj, '_index', None):
del obj._index
return objects | [
"def",
"encode_network",
"(",
"root",
")",
":",
"def",
"fix_values",
"(",
"obj",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"Container",
")",
":",
"obj",
".",
"update",
"(",
"(",
"k",
",",
"get_ref",
"(",
"v",
")",
")",
"for",
"(",
"k",
",",
... | Yield ref-containing obj table entries from object network | [
"Yield",
"ref",
"-",
"containing",
"obj",
"table",
"entries",
"from",
"object",
"network"
] | fcccd80cae11dc233f6dd02b40ec9a388c62f259 | https://github.com/tjvr/kurt/blob/fcccd80cae11dc233f6dd02b40ec9a388c62f259/kurt/scratch14/objtable.py#L383-L443 | train |
tjvr/kurt | kurt/scratch14/objtable.py | decode_obj_table | def decode_obj_table(table_entries, plugin):
"""Return root of obj table. Converts user-class objects"""
entries = []
for entry in table_entries:
if isinstance(entry, Container):
assert not hasattr(entry, '__recursion_lock__')
user_obj_def = plugin.user_objects[entry.classID]
assert entry.version == user_obj_def.version
entry = Container(class_name=entry.classID,
**dict(zip(user_obj_def.defaults.keys(),
entry.values)))
entries.append(entry)
return decode_network(entries) | python | def decode_obj_table(table_entries, plugin):
"""Return root of obj table. Converts user-class objects"""
entries = []
for entry in table_entries:
if isinstance(entry, Container):
assert not hasattr(entry, '__recursion_lock__')
user_obj_def = plugin.user_objects[entry.classID]
assert entry.version == user_obj_def.version
entry = Container(class_name=entry.classID,
**dict(zip(user_obj_def.defaults.keys(),
entry.values)))
entries.append(entry)
return decode_network(entries) | [
"def",
"decode_obj_table",
"(",
"table_entries",
",",
"plugin",
")",
":",
"entries",
"=",
"[",
"]",
"for",
"entry",
"in",
"table_entries",
":",
"if",
"isinstance",
"(",
"entry",
",",
"Container",
")",
":",
"assert",
"not",
"hasattr",
"(",
"entry",
",",
"... | Return root of obj table. Converts user-class objects | [
"Return",
"root",
"of",
"obj",
"table",
".",
"Converts",
"user",
"-",
"class",
"objects"
] | fcccd80cae11dc233f6dd02b40ec9a388c62f259 | https://github.com/tjvr/kurt/blob/fcccd80cae11dc233f6dd02b40ec9a388c62f259/kurt/scratch14/objtable.py#L445-L458 | train |
tjvr/kurt | kurt/scratch14/objtable.py | encode_obj_table | def encode_obj_table(root, plugin):
"""Return list of obj table entries. Converts user-class objects"""
entries = encode_network(root)
table_entries = []
for entry in entries:
if isinstance(entry, Container):
assert not hasattr(entry, '__recursion_lock__')
user_obj_def = plugin.user_objects[entry.class_name]
attrs = OrderedDict()
for (key, default) in user_obj_def.defaults.items():
attrs[key] = entry.get(key, default)
entry = Container(classID=entry.class_name,
length=len(attrs),
version=user_obj_def.version,
values=attrs.values())
table_entries.append(entry)
return table_entries | python | def encode_obj_table(root, plugin):
"""Return list of obj table entries. Converts user-class objects"""
entries = encode_network(root)
table_entries = []
for entry in entries:
if isinstance(entry, Container):
assert not hasattr(entry, '__recursion_lock__')
user_obj_def = plugin.user_objects[entry.class_name]
attrs = OrderedDict()
for (key, default) in user_obj_def.defaults.items():
attrs[key] = entry.get(key, default)
entry = Container(classID=entry.class_name,
length=len(attrs),
version=user_obj_def.version,
values=attrs.values())
table_entries.append(entry)
return table_entries | [
"def",
"encode_obj_table",
"(",
"root",
",",
"plugin",
")",
":",
"entries",
"=",
"encode_network",
"(",
"root",
")",
"table_entries",
"=",
"[",
"]",
"for",
"entry",
"in",
"entries",
":",
"if",
"isinstance",
"(",
"entry",
",",
"Container",
")",
":",
"asse... | Return list of obj table entries. Converts user-class objects | [
"Return",
"list",
"of",
"obj",
"table",
"entries",
".",
"Converts",
"user",
"-",
"class",
"objects"
] | fcccd80cae11dc233f6dd02b40ec9a388c62f259 | https://github.com/tjvr/kurt/blob/fcccd80cae11dc233f6dd02b40ec9a388c62f259/kurt/scratch14/objtable.py#L460-L477 | train |
tjvr/kurt | kurt/scratch14/objtable.py | ObjectAdapter._encode | def _encode(self, obj, context):
"""Encodes a class to a lower-level object using the class' own
to_construct function.
If no such function is defined, returns the object unchanged.
"""
func = getattr(obj, 'to_construct', None)
if callable(func):
return func(context)
else:
return obj | python | def _encode(self, obj, context):
"""Encodes a class to a lower-level object using the class' own
to_construct function.
If no such function is defined, returns the object unchanged.
"""
func = getattr(obj, 'to_construct', None)
if callable(func):
return func(context)
else:
return obj | [
"def",
"_encode",
"(",
"self",
",",
"obj",
",",
"context",
")",
":",
"func",
"=",
"getattr",
"(",
"obj",
",",
"'to_construct'",
",",
"None",
")",
"if",
"callable",
"(",
"func",
")",
":",
"return",
"func",
"(",
"context",
")",
"else",
":",
"return",
... | Encodes a class to a lower-level object using the class' own
to_construct function.
If no such function is defined, returns the object unchanged. | [
"Encodes",
"a",
"class",
"to",
"a",
"lower",
"-",
"level",
"object",
"using",
"the",
"class",
"own",
"to_construct",
"function",
".",
"If",
"no",
"such",
"function",
"is",
"defined",
"returns",
"the",
"object",
"unchanged",
"."
] | fcccd80cae11dc233f6dd02b40ec9a388c62f259 | https://github.com/tjvr/kurt/blob/fcccd80cae11dc233f6dd02b40ec9a388c62f259/kurt/scratch14/objtable.py#L60-L69 | train |
tjvr/kurt | kurt/scratch14/objtable.py | ObjectAdapter._decode | def _decode(self, obj, context):
"""Initialises a new Python class from a construct using the mapping
passed to the adapter.
"""
cls = self._get_class(obj.classID)
return cls.from_construct(obj, context) | python | def _decode(self, obj, context):
"""Initialises a new Python class from a construct using the mapping
passed to the adapter.
"""
cls = self._get_class(obj.classID)
return cls.from_construct(obj, context) | [
"def",
"_decode",
"(",
"self",
",",
"obj",
",",
"context",
")",
":",
"cls",
"=",
"self",
".",
"_get_class",
"(",
"obj",
".",
"classID",
")",
"return",
"cls",
".",
"from_construct",
"(",
"obj",
",",
"context",
")"
] | Initialises a new Python class from a construct using the mapping
passed to the adapter. | [
"Initialises",
"a",
"new",
"Python",
"class",
"from",
"a",
"construct",
"using",
"the",
"mapping",
"passed",
"to",
"the",
"adapter",
"."
] | fcccd80cae11dc233f6dd02b40ec9a388c62f259 | https://github.com/tjvr/kurt/blob/fcccd80cae11dc233f6dd02b40ec9a388c62f259/kurt/scratch14/objtable.py#L71-L76 | train |
tjvr/kurt | kurt/scratch20/__init__.py | ZipWriter.write_file | def write_file(self, name, contents):
"""Write file contents string into archive."""
# TODO: find a way to make ZipFile accept a file object.
zi = zipfile.ZipInfo(name)
zi.date_time = time.localtime(time.time())[:6]
zi.compress_type = zipfile.ZIP_DEFLATED
zi.external_attr = 0777 << 16L
self.zip_file.writestr(zi, contents) | python | def write_file(self, name, contents):
"""Write file contents string into archive."""
# TODO: find a way to make ZipFile accept a file object.
zi = zipfile.ZipInfo(name)
zi.date_time = time.localtime(time.time())[:6]
zi.compress_type = zipfile.ZIP_DEFLATED
zi.external_attr = 0777 << 16L
self.zip_file.writestr(zi, contents) | [
"def",
"write_file",
"(",
"self",
",",
"name",
",",
"contents",
")",
":",
"# TODO: find a way to make ZipFile accept a file object.",
"zi",
"=",
"zipfile",
".",
"ZipInfo",
"(",
"name",
")",
"zi",
".",
"date_time",
"=",
"time",
".",
"localtime",
"(",
"time",
".... | Write file contents string into archive. | [
"Write",
"file",
"contents",
"string",
"into",
"archive",
"."
] | fcccd80cae11dc233f6dd02b40ec9a388c62f259 | https://github.com/tjvr/kurt/blob/fcccd80cae11dc233f6dd02b40ec9a388c62f259/kurt/scratch20/__init__.py#L348-L355 | train |
tjvr/kurt | examples/import_midi.py | load_midi_file | def load_midi_file(path):
"""Yield (pitch, start_beat, end_beat) for each note in midi file."""
midi_notes = []
def register_note(track, channel, pitch, velocity, start, end):
midi_notes.append((pitch, start, end))
midi.register_note = register_note
global m
m = midi.MidiFile()
m.open(midi_path)
m.read()
m.close()
for (pitch, start, end) in midi_notes:
start /= m.ticksPerQuarterNote
end /= m.ticksPerQuarterNote
yield (pitch, start, end) | python | def load_midi_file(path):
"""Yield (pitch, start_beat, end_beat) for each note in midi file."""
midi_notes = []
def register_note(track, channel, pitch, velocity, start, end):
midi_notes.append((pitch, start, end))
midi.register_note = register_note
global m
m = midi.MidiFile()
m.open(midi_path)
m.read()
m.close()
for (pitch, start, end) in midi_notes:
start /= m.ticksPerQuarterNote
end /= m.ticksPerQuarterNote
yield (pitch, start, end) | [
"def",
"load_midi_file",
"(",
"path",
")",
":",
"midi_notes",
"=",
"[",
"]",
"def",
"register_note",
"(",
"track",
",",
"channel",
",",
"pitch",
",",
"velocity",
",",
"start",
",",
"end",
")",
":",
"midi_notes",
".",
"append",
"(",
"(",
"pitch",
",",
... | Yield (pitch, start_beat, end_beat) for each note in midi file. | [
"Yield",
"(",
"pitch",
"start_beat",
"end_beat",
")",
"for",
"each",
"note",
"in",
"midi",
"file",
"."
] | fcccd80cae11dc233f6dd02b40ec9a388c62f259 | https://github.com/tjvr/kurt/blob/fcccd80cae11dc233f6dd02b40ec9a388c62f259/examples/import_midi.py#L24-L41 | train |
tjvr/kurt | kurt/scratch14/__init__.py | Serializer.get_media | def get_media(self, v14_scriptable):
"""Return (images, sounds)"""
images = []
sounds = []
for media in v14_scriptable.media:
if media.class_name == 'SoundMedia':
sounds.append(media)
elif media.class_name == 'ImageMedia':
images.append(media)
return (images, sounds) | python | def get_media(self, v14_scriptable):
"""Return (images, sounds)"""
images = []
sounds = []
for media in v14_scriptable.media:
if media.class_name == 'SoundMedia':
sounds.append(media)
elif media.class_name == 'ImageMedia':
images.append(media)
return (images, sounds) | [
"def",
"get_media",
"(",
"self",
",",
"v14_scriptable",
")",
":",
"images",
"=",
"[",
"]",
"sounds",
"=",
"[",
"]",
"for",
"media",
"in",
"v14_scriptable",
".",
"media",
":",
"if",
"media",
".",
"class_name",
"==",
"'SoundMedia'",
":",
"sounds",
".",
"... | Return (images, sounds) | [
"Return",
"(",
"images",
"sounds",
")"
] | fcccd80cae11dc233f6dd02b40ec9a388c62f259 | https://github.com/tjvr/kurt/blob/fcccd80cae11dc233f6dd02b40ec9a388c62f259/kurt/scratch14/__init__.py#L216-L225 | train |
tjvr/kurt | kurt/scratch14/fixed_objects.py | Bitmap.from_byte_array | def from_byte_array(cls, bytes_):
"""Decodes a run-length encoded ByteArray and returns a Bitmap.
The ByteArray decompresses to a sequence of 32-bit values, which are
stored as a byte string. (The specific encoding depends on Form.depth.)
"""
runs = cls._length_run_coding.parse(bytes_)
pixels = (run.pixels for run in runs.data)
data = "".join(itertools.chain.from_iterable(pixels))
return cls(data) | python | def from_byte_array(cls, bytes_):
"""Decodes a run-length encoded ByteArray and returns a Bitmap.
The ByteArray decompresses to a sequence of 32-bit values, which are
stored as a byte string. (The specific encoding depends on Form.depth.)
"""
runs = cls._length_run_coding.parse(bytes_)
pixels = (run.pixels for run in runs.data)
data = "".join(itertools.chain.from_iterable(pixels))
return cls(data) | [
"def",
"from_byte_array",
"(",
"cls",
",",
"bytes_",
")",
":",
"runs",
"=",
"cls",
".",
"_length_run_coding",
".",
"parse",
"(",
"bytes_",
")",
"pixels",
"=",
"(",
"run",
".",
"pixels",
"for",
"run",
"in",
"runs",
".",
"data",
")",
"data",
"=",
"\"\"... | Decodes a run-length encoded ByteArray and returns a Bitmap.
The ByteArray decompresses to a sequence of 32-bit values, which are
stored as a byte string. (The specific encoding depends on Form.depth.) | [
"Decodes",
"a",
"run",
"-",
"length",
"encoded",
"ByteArray",
"and",
"returns",
"a",
"Bitmap",
".",
"The",
"ByteArray",
"decompresses",
"to",
"a",
"sequence",
"of",
"32",
"-",
"bit",
"values",
"which",
"are",
"stored",
"as",
"a",
"byte",
"string",
".",
"... | fcccd80cae11dc233f6dd02b40ec9a388c62f259 | https://github.com/tjvr/kurt/blob/fcccd80cae11dc233f6dd02b40ec9a388c62f259/kurt/scratch14/fixed_objects.py#L521-L529 | train |
tjvr/kurt | kurt/scratch14/fixed_objects.py | Form.from_string | def from_string(cls, width, height, rgba_string):
"""Returns a Form with 32-bit RGBA pixels
Accepts string containing raw RGBA color values
"""
# Convert RGBA string to ARGB
raw = ""
for i in range(0, len(rgba_string), 4):
raw += rgba_string[i+3] # alpha
raw += rgba_string[i:i+3] # rgb
assert len(rgba_string) == width * height * 4
return Form(
width = width,
height = height,
depth = 32,
bits = Bitmap(raw),
) | python | def from_string(cls, width, height, rgba_string):
"""Returns a Form with 32-bit RGBA pixels
Accepts string containing raw RGBA color values
"""
# Convert RGBA string to ARGB
raw = ""
for i in range(0, len(rgba_string), 4):
raw += rgba_string[i+3] # alpha
raw += rgba_string[i:i+3] # rgb
assert len(rgba_string) == width * height * 4
return Form(
width = width,
height = height,
depth = 32,
bits = Bitmap(raw),
) | [
"def",
"from_string",
"(",
"cls",
",",
"width",
",",
"height",
",",
"rgba_string",
")",
":",
"# Convert RGBA string to ARGB",
"raw",
"=",
"\"\"",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"rgba_string",
")",
",",
"4",
")",
":",
"raw",
"+=",... | Returns a Form with 32-bit RGBA pixels
Accepts string containing raw RGBA color values | [
"Returns",
"a",
"Form",
"with",
"32",
"-",
"bit",
"RGBA",
"pixels",
"Accepts",
"string",
"containing",
"raw",
"RGBA",
"color",
"values"
] | fcccd80cae11dc233f6dd02b40ec9a388c62f259 | https://github.com/tjvr/kurt/blob/fcccd80cae11dc233f6dd02b40ec9a388c62f259/kurt/scratch14/fixed_objects.py#L642-L659 | train |
tjvr/kurt | util/kurtgui.py | open_file | def open_file(path):
"""Opens Explorer/Finder with given path, depending on platform"""
if sys.platform=='win32':
os.startfile(path)
#subprocess.Popen(['start', path], shell= True)
elif sys.platform=='darwin':
subprocess.Popen(['open', path])
else:
try:
subprocess.Popen(['xdg-open', path])
except OSError:
pass | python | def open_file(path):
"""Opens Explorer/Finder with given path, depending on platform"""
if sys.platform=='win32':
os.startfile(path)
#subprocess.Popen(['start', path], shell= True)
elif sys.platform=='darwin':
subprocess.Popen(['open', path])
else:
try:
subprocess.Popen(['xdg-open', path])
except OSError:
pass | [
"def",
"open_file",
"(",
"path",
")",
":",
"if",
"sys",
".",
"platform",
"==",
"'win32'",
":",
"os",
".",
"startfile",
"(",
"path",
")",
"#subprocess.Popen(['start', path], shell= True)",
"elif",
"sys",
".",
"platform",
"==",
"'darwin'",
":",
"subprocess",
"."... | Opens Explorer/Finder with given path, depending on platform | [
"Opens",
"Explorer",
"/",
"Finder",
"with",
"given",
"path",
"depending",
"on",
"platform"
] | fcccd80cae11dc233f6dd02b40ec9a388c62f259 | https://github.com/tjvr/kurt/blob/fcccd80cae11dc233f6dd02b40ec9a388c62f259/util/kurtgui.py#L60-L73 | train |
tjvr/kurt | util/kurtgui.py | App.set_file_path | def set_file_path(self, path):
"""Update the file_path Entry widget"""
self.file_path.delete(0, END)
self.file_path.insert(0, path) | python | def set_file_path(self, path):
"""Update the file_path Entry widget"""
self.file_path.delete(0, END)
self.file_path.insert(0, path) | [
"def",
"set_file_path",
"(",
"self",
",",
"path",
")",
":",
"self",
".",
"file_path",
".",
"delete",
"(",
"0",
",",
"END",
")",
"self",
".",
"file_path",
".",
"insert",
"(",
"0",
",",
"path",
")"
] | Update the file_path Entry widget | [
"Update",
"the",
"file_path",
"Entry",
"widget"
] | fcccd80cae11dc233f6dd02b40ec9a388c62f259 | https://github.com/tjvr/kurt/blob/fcccd80cae11dc233f6dd02b40ec9a388c62f259/util/kurtgui.py#L175-L178 | train |
tjvr/kurt | kurt/__init__.py | Project.load | def load(cls, path, format=None):
"""Load project from file.
Use ``format`` to specify the file format to use.
Path can be a file-like object, in which case format is required.
Otherwise, can guess the appropriate format from the extension.
If you pass a file-like object, you're responsible for closing the
file.
:param path: Path or file pointer.
:param format: :attr:`KurtFileFormat.name` eg. ``"scratch14"``.
Overrides the extension.
:raises: :class:`UnknownFormat` if the extension is unrecognised.
:raises: :py:class:`ValueError` if the format doesn't exist.
"""
path_was_string = isinstance(path, basestring)
if path_was_string:
(folder, filename) = os.path.split(path)
(name, extension) = os.path.splitext(filename)
if format is None:
plugin = kurt.plugin.Kurt.get_plugin(extension=extension)
if not plugin:
raise UnknownFormat(extension)
fp = open(path, "rb")
else:
fp = path
assert format, "Format is required"
plugin = kurt.plugin.Kurt.get_plugin(format)
if not plugin:
raise ValueError, "Unknown format %r" % format
project = plugin.load(fp)
if path_was_string:
fp.close()
project.convert(plugin)
if isinstance(path, basestring):
project.path = path
if not project.name:
project.name = name
return project | python | def load(cls, path, format=None):
"""Load project from file.
Use ``format`` to specify the file format to use.
Path can be a file-like object, in which case format is required.
Otherwise, can guess the appropriate format from the extension.
If you pass a file-like object, you're responsible for closing the
file.
:param path: Path or file pointer.
:param format: :attr:`KurtFileFormat.name` eg. ``"scratch14"``.
Overrides the extension.
:raises: :class:`UnknownFormat` if the extension is unrecognised.
:raises: :py:class:`ValueError` if the format doesn't exist.
"""
path_was_string = isinstance(path, basestring)
if path_was_string:
(folder, filename) = os.path.split(path)
(name, extension) = os.path.splitext(filename)
if format is None:
plugin = kurt.plugin.Kurt.get_plugin(extension=extension)
if not plugin:
raise UnknownFormat(extension)
fp = open(path, "rb")
else:
fp = path
assert format, "Format is required"
plugin = kurt.plugin.Kurt.get_plugin(format)
if not plugin:
raise ValueError, "Unknown format %r" % format
project = plugin.load(fp)
if path_was_string:
fp.close()
project.convert(plugin)
if isinstance(path, basestring):
project.path = path
if not project.name:
project.name = name
return project | [
"def",
"load",
"(",
"cls",
",",
"path",
",",
"format",
"=",
"None",
")",
":",
"path_was_string",
"=",
"isinstance",
"(",
"path",
",",
"basestring",
")",
"if",
"path_was_string",
":",
"(",
"folder",
",",
"filename",
")",
"=",
"os",
".",
"path",
".",
"... | Load project from file.
Use ``format`` to specify the file format to use.
Path can be a file-like object, in which case format is required.
Otherwise, can guess the appropriate format from the extension.
If you pass a file-like object, you're responsible for closing the
file.
:param path: Path or file pointer.
:param format: :attr:`KurtFileFormat.name` eg. ``"scratch14"``.
Overrides the extension.
:raises: :class:`UnknownFormat` if the extension is unrecognised.
:raises: :py:class:`ValueError` if the format doesn't exist. | [
"Load",
"project",
"from",
"file",
"."
] | fcccd80cae11dc233f6dd02b40ec9a388c62f259 | https://github.com/tjvr/kurt/blob/fcccd80cae11dc233f6dd02b40ec9a388c62f259/kurt/__init__.py#L232-L276 | train |
tjvr/kurt | kurt/__init__.py | Project.copy | def copy(self):
"""Return a new Project instance, deep-copying all the attributes."""
p = Project()
p.name = self.name
p.path = self.path
p._plugin = self._plugin
p.stage = self.stage.copy()
p.stage.project = p
for sprite in self.sprites:
s = sprite.copy()
s.project = p
p.sprites.append(s)
for actor in self.actors:
if isinstance(actor, Sprite):
p.actors.append(p.get_sprite(actor.name))
else:
a = actor.copy()
if isinstance(a, Watcher):
if isinstance(a.target, Project):
a.target = p
elif isinstance(a.target, Stage):
a.target = p.stage
else:
a.target = p.get_sprite(a.target.name)
p.actors.append(a)
p.variables = dict((n, v.copy()) for (n, v) in self.variables.items())
p.lists = dict((n, l.copy()) for (n, l) in self.lists.items())
p.thumbnail = self.thumbnail
p.tempo = self.tempo
p.notes = self.notes
p.author = self.author
return p | python | def copy(self):
"""Return a new Project instance, deep-copying all the attributes."""
p = Project()
p.name = self.name
p.path = self.path
p._plugin = self._plugin
p.stage = self.stage.copy()
p.stage.project = p
for sprite in self.sprites:
s = sprite.copy()
s.project = p
p.sprites.append(s)
for actor in self.actors:
if isinstance(actor, Sprite):
p.actors.append(p.get_sprite(actor.name))
else:
a = actor.copy()
if isinstance(a, Watcher):
if isinstance(a.target, Project):
a.target = p
elif isinstance(a.target, Stage):
a.target = p.stage
else:
a.target = p.get_sprite(a.target.name)
p.actors.append(a)
p.variables = dict((n, v.copy()) for (n, v) in self.variables.items())
p.lists = dict((n, l.copy()) for (n, l) in self.lists.items())
p.thumbnail = self.thumbnail
p.tempo = self.tempo
p.notes = self.notes
p.author = self.author
return p | [
"def",
"copy",
"(",
"self",
")",
":",
"p",
"=",
"Project",
"(",
")",
"p",
".",
"name",
"=",
"self",
".",
"name",
"p",
".",
"path",
"=",
"self",
".",
"path",
"p",
".",
"_plugin",
"=",
"self",
".",
"_plugin",
"p",
".",
"stage",
"=",
"self",
"."... | Return a new Project instance, deep-copying all the attributes. | [
"Return",
"a",
"new",
"Project",
"instance",
"deep",
"-",
"copying",
"all",
"the",
"attributes",
"."
] | fcccd80cae11dc233f6dd02b40ec9a388c62f259 | https://github.com/tjvr/kurt/blob/fcccd80cae11dc233f6dd02b40ec9a388c62f259/kurt/__init__.py#L278-L312 | train |
tjvr/kurt | kurt/__init__.py | Project.convert | def convert(self, format):
"""Convert the project in-place to a different file format.
Returns a list of :class:`UnsupportedFeature` objects, which may give
warnings about the conversion.
:param format: :attr:`KurtFileFormat.name` eg. ``"scratch14"``.
:raises: :class:`ValueError` if the format doesn't exist.
"""
self._plugin = kurt.plugin.Kurt.get_plugin(format)
return list(self._normalize()) | python | def convert(self, format):
"""Convert the project in-place to a different file format.
Returns a list of :class:`UnsupportedFeature` objects, which may give
warnings about the conversion.
:param format: :attr:`KurtFileFormat.name` eg. ``"scratch14"``.
:raises: :class:`ValueError` if the format doesn't exist.
"""
self._plugin = kurt.plugin.Kurt.get_plugin(format)
return list(self._normalize()) | [
"def",
"convert",
"(",
"self",
",",
"format",
")",
":",
"self",
".",
"_plugin",
"=",
"kurt",
".",
"plugin",
".",
"Kurt",
".",
"get_plugin",
"(",
"format",
")",
"return",
"list",
"(",
"self",
".",
"_normalize",
"(",
")",
")"
] | Convert the project in-place to a different file format.
Returns a list of :class:`UnsupportedFeature` objects, which may give
warnings about the conversion.
:param format: :attr:`KurtFileFormat.name` eg. ``"scratch14"``.
:raises: :class:`ValueError` if the format doesn't exist. | [
"Convert",
"the",
"project",
"in",
"-",
"place",
"to",
"a",
"different",
"file",
"format",
"."
] | fcccd80cae11dc233f6dd02b40ec9a388c62f259 | https://github.com/tjvr/kurt/blob/fcccd80cae11dc233f6dd02b40ec9a388c62f259/kurt/__init__.py#L314-L326 | train |
tjvr/kurt | kurt/__init__.py | Project.save | def save(self, path=None, debug=False):
"""Save project to file.
:param path: Path or file pointer.
If you pass a file pointer, you're responsible for closing
it.
If path is not given, the :attr:`path` attribute is used,
usually the original path given to :attr:`load()`.
If `path` has the extension of an existing plugin, the
project will be converted using :attr:`convert`.
Otherwise, the extension will be replaced with the
extension of the current plugin.
(Note that log output for the conversion will be printed
to stdout. If you want to deal with the output, call
:attr:`convert` directly.)
If the path ends in a folder instead of a file, the
filename is based on the project's :attr:`name`.
:param debug: If true, return debugging information from the format
plugin instead of the path.
:raises: :py:class:`ValueError` if there's no path or name.
:returns: path to the saved file.
"""
p = self.copy()
plugin = p._plugin
# require path
p.path = path or self.path
if not p.path:
raise ValueError, "path is required"
if isinstance(p.path, basestring):
# split path
(folder, filename) = os.path.split(p.path)
(name, extension) = os.path.splitext(filename)
# get plugin from extension
if path: # only if not using self.path
try:
plugin = kurt.plugin.Kurt.get_plugin(extension=extension)
except ValueError:
pass
# build output path
if not name:
name = _clean_filename(self.name)
if not name:
raise ValueError, "name is required"
filename = name + plugin.extension
p.path = os.path.join(folder, filename)
# open
fp = open(p.path, "wb")
else:
fp = p.path
path = None
if not plugin:
raise ValueError, "must convert project to a format before saving"
for m in p.convert(plugin):
print m
result = p._save(fp)
if path:
fp.close()
return result if debug else p.path | python | def save(self, path=None, debug=False):
"""Save project to file.
:param path: Path or file pointer.
If you pass a file pointer, you're responsible for closing
it.
If path is not given, the :attr:`path` attribute is used,
usually the original path given to :attr:`load()`.
If `path` has the extension of an existing plugin, the
project will be converted using :attr:`convert`.
Otherwise, the extension will be replaced with the
extension of the current plugin.
(Note that log output for the conversion will be printed
to stdout. If you want to deal with the output, call
:attr:`convert` directly.)
If the path ends in a folder instead of a file, the
filename is based on the project's :attr:`name`.
:param debug: If true, return debugging information from the format
plugin instead of the path.
:raises: :py:class:`ValueError` if there's no path or name.
:returns: path to the saved file.
"""
p = self.copy()
plugin = p._plugin
# require path
p.path = path or self.path
if not p.path:
raise ValueError, "path is required"
if isinstance(p.path, basestring):
# split path
(folder, filename) = os.path.split(p.path)
(name, extension) = os.path.splitext(filename)
# get plugin from extension
if path: # only if not using self.path
try:
plugin = kurt.plugin.Kurt.get_plugin(extension=extension)
except ValueError:
pass
# build output path
if not name:
name = _clean_filename(self.name)
if not name:
raise ValueError, "name is required"
filename = name + plugin.extension
p.path = os.path.join(folder, filename)
# open
fp = open(p.path, "wb")
else:
fp = p.path
path = None
if not plugin:
raise ValueError, "must convert project to a format before saving"
for m in p.convert(plugin):
print m
result = p._save(fp)
if path:
fp.close()
return result if debug else p.path | [
"def",
"save",
"(",
"self",
",",
"path",
"=",
"None",
",",
"debug",
"=",
"False",
")",
":",
"p",
"=",
"self",
".",
"copy",
"(",
")",
"plugin",
"=",
"p",
".",
"_plugin",
"# require path",
"p",
".",
"path",
"=",
"path",
"or",
"self",
".",
"path",
... | Save project to file.
:param path: Path or file pointer.
If you pass a file pointer, you're responsible for closing
it.
If path is not given, the :attr:`path` attribute is used,
usually the original path given to :attr:`load()`.
If `path` has the extension of an existing plugin, the
project will be converted using :attr:`convert`.
Otherwise, the extension will be replaced with the
extension of the current plugin.
(Note that log output for the conversion will be printed
to stdout. If you want to deal with the output, call
:attr:`convert` directly.)
If the path ends in a folder instead of a file, the
filename is based on the project's :attr:`name`.
:param debug: If true, return debugging information from the format
plugin instead of the path.
:raises: :py:class:`ValueError` if there's no path or name.
:returns: path to the saved file. | [
"Save",
"project",
"to",
"file",
"."
] | fcccd80cae11dc233f6dd02b40ec9a388c62f259 | https://github.com/tjvr/kurt/blob/fcccd80cae11dc233f6dd02b40ec9a388c62f259/kurt/__init__.py#L328-L402 | train |
tjvr/kurt | kurt/__init__.py | Project._normalize | def _normalize(self):
"""Convert the project to a standardised form for the current plugin.
Called after loading, before saving, and when converting to a new
format.
Yields UnsupportedFeature instances.
"""
unique_sprite_names = set(sprite.name for sprite in self.sprites)
if len(unique_sprite_names) < len(self.sprites):
raise ValueError, "Sprite names must be unique"
# sync self.sprites and self.actors
for sprite in self.sprites:
if sprite not in self.actors:
self.actors.append(sprite)
for actor in self.actors:
if isinstance(actor, Sprite):
if actor not in self.sprites:
raise ValueError, \
"Can't have sprite on stage that isn't in sprites"
# normalize Scriptables
self.stage._normalize()
for sprite in self.sprites:
sprite._normalize()
# normalize actors
for actor in self.actors:
if not isinstance(actor, Scriptable):
actor._normalize()
# make Watchers if needed
for thing in [self, self.stage] + self.sprites:
for (name, var) in thing.variables.items():
if not var.watcher:
var.watcher = kurt.Watcher(thing,
kurt.Block("var", name), is_visible=False)
self.actors.append(var.watcher)
for (name, list_) in thing.lists.items():
if not list_.watcher:
list_.watcher = kurt.Watcher(thing,
kurt.Block("list", name), is_visible=False)
self.actors.append(list_.watcher)
# notes - line endings
self.notes = self.notes.replace("\r\n", "\n").replace("\r", "\n")
# convert scripts
def convert_block(block):
# convert block
try:
if isinstance(block.type, CustomBlockType):
if "Custom Blocks" not in self._plugin.features:
raise BlockNotSupported(
"%s doesn't support custom blocks"
% self._plugin.display_name)
else: # BlockType
pbt = block.type.convert(self._plugin)
except BlockNotSupported, err:
err.message += ". Caused by: %r" % block
err.block = block
err.scriptable = scriptable
err.args = (err.message,)
if getattr(block.type, '_workaround', None):
block = block.type._workaround(block)
if not block:
raise
else:
raise
# convert args
args = []
for arg in block.args:
if isinstance(arg, Block):
arg = convert_block(arg)
elif isinstance(arg, list):
arg = map(convert_block, arg)
args.append(arg)
block.args = args
return block
for scriptable in [self.stage] + self.sprites:
for script in scriptable.scripts:
if isinstance(script, Script):
script.blocks = map(convert_block, script.blocks)
# workaround unsupported features
for feature in kurt.plugin.Feature.FEATURES.values():
if feature not in self._plugin.features:
for x in feature.workaround(self):
yield UnsupportedFeature(feature, x)
# normalize supported features
for feature in self._plugin.features:
feature.normalize(self) | python | def _normalize(self):
"""Convert the project to a standardised form for the current plugin.
Called after loading, before saving, and when converting to a new
format.
Yields UnsupportedFeature instances.
"""
unique_sprite_names = set(sprite.name for sprite in self.sprites)
if len(unique_sprite_names) < len(self.sprites):
raise ValueError, "Sprite names must be unique"
# sync self.sprites and self.actors
for sprite in self.sprites:
if sprite not in self.actors:
self.actors.append(sprite)
for actor in self.actors:
if isinstance(actor, Sprite):
if actor not in self.sprites:
raise ValueError, \
"Can't have sprite on stage that isn't in sprites"
# normalize Scriptables
self.stage._normalize()
for sprite in self.sprites:
sprite._normalize()
# normalize actors
for actor in self.actors:
if not isinstance(actor, Scriptable):
actor._normalize()
# make Watchers if needed
for thing in [self, self.stage] + self.sprites:
for (name, var) in thing.variables.items():
if not var.watcher:
var.watcher = kurt.Watcher(thing,
kurt.Block("var", name), is_visible=False)
self.actors.append(var.watcher)
for (name, list_) in thing.lists.items():
if not list_.watcher:
list_.watcher = kurt.Watcher(thing,
kurt.Block("list", name), is_visible=False)
self.actors.append(list_.watcher)
# notes - line endings
self.notes = self.notes.replace("\r\n", "\n").replace("\r", "\n")
# convert scripts
def convert_block(block):
# convert block
try:
if isinstance(block.type, CustomBlockType):
if "Custom Blocks" not in self._plugin.features:
raise BlockNotSupported(
"%s doesn't support custom blocks"
% self._plugin.display_name)
else: # BlockType
pbt = block.type.convert(self._plugin)
except BlockNotSupported, err:
err.message += ". Caused by: %r" % block
err.block = block
err.scriptable = scriptable
err.args = (err.message,)
if getattr(block.type, '_workaround', None):
block = block.type._workaround(block)
if not block:
raise
else:
raise
# convert args
args = []
for arg in block.args:
if isinstance(arg, Block):
arg = convert_block(arg)
elif isinstance(arg, list):
arg = map(convert_block, arg)
args.append(arg)
block.args = args
return block
for scriptable in [self.stage] + self.sprites:
for script in scriptable.scripts:
if isinstance(script, Script):
script.blocks = map(convert_block, script.blocks)
# workaround unsupported features
for feature in kurt.plugin.Feature.FEATURES.values():
if feature not in self._plugin.features:
for x in feature.workaround(self):
yield UnsupportedFeature(feature, x)
# normalize supported features
for feature in self._plugin.features:
feature.normalize(self) | [
"def",
"_normalize",
"(",
"self",
")",
":",
"unique_sprite_names",
"=",
"set",
"(",
"sprite",
".",
"name",
"for",
"sprite",
"in",
"self",
".",
"sprites",
")",
"if",
"len",
"(",
"unique_sprite_names",
")",
"<",
"len",
"(",
"self",
".",
"sprites",
")",
"... | Convert the project to a standardised form for the current plugin.
Called after loading, before saving, and when converting to a new
format.
Yields UnsupportedFeature instances. | [
"Convert",
"the",
"project",
"to",
"a",
"standardised",
"form",
"for",
"the",
"current",
"plugin",
"."
] | fcccd80cae11dc233f6dd02b40ec9a388c62f259 | https://github.com/tjvr/kurt/blob/fcccd80cae11dc233f6dd02b40ec9a388c62f259/kurt/__init__.py#L407-L506 | train |
tjvr/kurt | kurt/__init__.py | Scriptable.copy | def copy(self, o=None):
"""Return a new instance, deep-copying all the attributes."""
if o is None: o = self.__class__(self.project)
o.scripts = [s.copy() for s in self.scripts]
o.variables = dict((n, v.copy()) for (n, v) in self.variables.items())
o.lists = dict((n, l.copy()) for (n, l) in self.lists.items())
o.costumes = [c.copy() for c in self.costumes]
o.sounds = [s.copy() for s in self.sounds]
o.costume_index = self.costume_index
o.volume = self.volume
return o | python | def copy(self, o=None):
"""Return a new instance, deep-copying all the attributes."""
if o is None: o = self.__class__(self.project)
o.scripts = [s.copy() for s in self.scripts]
o.variables = dict((n, v.copy()) for (n, v) in self.variables.items())
o.lists = dict((n, l.copy()) for (n, l) in self.lists.items())
o.costumes = [c.copy() for c in self.costumes]
o.sounds = [s.copy() for s in self.sounds]
o.costume_index = self.costume_index
o.volume = self.volume
return o | [
"def",
"copy",
"(",
"self",
",",
"o",
"=",
"None",
")",
":",
"if",
"o",
"is",
"None",
":",
"o",
"=",
"self",
".",
"__class__",
"(",
"self",
".",
"project",
")",
"o",
".",
"scripts",
"=",
"[",
"s",
".",
"copy",
"(",
")",
"for",
"s",
"in",
"s... | Return a new instance, deep-copying all the attributes. | [
"Return",
"a",
"new",
"instance",
"deep",
"-",
"copying",
"all",
"the",
"attributes",
"."
] | fcccd80cae11dc233f6dd02b40ec9a388c62f259 | https://github.com/tjvr/kurt/blob/fcccd80cae11dc233f6dd02b40ec9a388c62f259/kurt/__init__.py#L675-L685 | train |
tjvr/kurt | kurt/__init__.py | Scriptable.parse | def parse(self, text):
"""Parse the given code and add it to :attr:`scripts`.
The syntax matches :attr:`Script.stringify()`. See :mod:`kurt.text` for
reference.
"""
self.scripts.append(kurt.text.parse(text, self)) | python | def parse(self, text):
"""Parse the given code and add it to :attr:`scripts`.
The syntax matches :attr:`Script.stringify()`. See :mod:`kurt.text` for
reference.
"""
self.scripts.append(kurt.text.parse(text, self)) | [
"def",
"parse",
"(",
"self",
",",
"text",
")",
":",
"self",
".",
"scripts",
".",
"append",
"(",
"kurt",
".",
"text",
".",
"parse",
"(",
"text",
",",
"self",
")",
")"
] | Parse the given code and add it to :attr:`scripts`.
The syntax matches :attr:`Script.stringify()`. See :mod:`kurt.text` for
reference. | [
"Parse",
"the",
"given",
"code",
"and",
"add",
"it",
"to",
":",
"attr",
":",
"scripts",
"."
] | fcccd80cae11dc233f6dd02b40ec9a388c62f259 | https://github.com/tjvr/kurt/blob/fcccd80cae11dc233f6dd02b40ec9a388c62f259/kurt/__init__.py#L704-L711 | train |
tjvr/kurt | kurt/__init__.py | Sprite.copy | def copy(self):
"""Return a new instance, deep-copying all the attributes."""
o = self.__class__(self.project, self.name)
Scriptable.copy(self, o)
o.position = tuple(self.position)
o.direction = self.direction
o.rotation_style = self.rotation_style
o.size = self.size
o.is_draggable = self.is_draggable
o.is_visible = self.is_visible
return o | python | def copy(self):
"""Return a new instance, deep-copying all the attributes."""
o = self.__class__(self.project, self.name)
Scriptable.copy(self, o)
o.position = tuple(self.position)
o.direction = self.direction
o.rotation_style = self.rotation_style
o.size = self.size
o.is_draggable = self.is_draggable
o.is_visible = self.is_visible
return o | [
"def",
"copy",
"(",
"self",
")",
":",
"o",
"=",
"self",
".",
"__class__",
"(",
"self",
".",
"project",
",",
"self",
".",
"name",
")",
"Scriptable",
".",
"copy",
"(",
"self",
",",
"o",
")",
"o",
".",
"position",
"=",
"tuple",
"(",
"self",
".",
"... | Return a new instance, deep-copying all the attributes. | [
"Return",
"a",
"new",
"instance",
"deep",
"-",
"copying",
"all",
"the",
"attributes",
"."
] | fcccd80cae11dc233f6dd02b40ec9a388c62f259 | https://github.com/tjvr/kurt/blob/fcccd80cae11dc233f6dd02b40ec9a388c62f259/kurt/__init__.py#L825-L835 | train |
tjvr/kurt | kurt/__init__.py | Watcher.copy | def copy(self):
"""Return a new instance with the same attributes."""
o = self.__class__(self.target,
self.block.copy(),
self.style,
self.is_visible,
self.pos)
o.slider_min = self.slider_min
o.slider_max = self.slider_max
return o | python | def copy(self):
"""Return a new instance with the same attributes."""
o = self.__class__(self.target,
self.block.copy(),
self.style,
self.is_visible,
self.pos)
o.slider_min = self.slider_min
o.slider_max = self.slider_max
return o | [
"def",
"copy",
"(",
"self",
")",
":",
"o",
"=",
"self",
".",
"__class__",
"(",
"self",
".",
"target",
",",
"self",
".",
"block",
".",
"copy",
"(",
")",
",",
"self",
".",
"style",
",",
"self",
".",
"is_visible",
",",
"self",
".",
"pos",
")",
"o"... | Return a new instance with the same attributes. | [
"Return",
"a",
"new",
"instance",
"with",
"the",
"same",
"attributes",
"."
] | fcccd80cae11dc233f6dd02b40ec9a388c62f259 | https://github.com/tjvr/kurt/blob/fcccd80cae11dc233f6dd02b40ec9a388c62f259/kurt/__init__.py#L918-L927 | train |
tjvr/kurt | kurt/__init__.py | Watcher.kind | def kind(self):
"""The type of value to watch, based on :attr:`block`.
One of ``variable``, ``list``, or ``block``.
``block`` watchers watch the value of a reporter block.
"""
if self.block.type.has_command('readVariable'):
return 'variable'
elif self.block.type.has_command('contentsOfList:'):
return 'list'
else:
return 'block' | python | def kind(self):
"""The type of value to watch, based on :attr:`block`.
One of ``variable``, ``list``, or ``block``.
``block`` watchers watch the value of a reporter block.
"""
if self.block.type.has_command('readVariable'):
return 'variable'
elif self.block.type.has_command('contentsOfList:'):
return 'list'
else:
return 'block' | [
"def",
"kind",
"(",
"self",
")",
":",
"if",
"self",
".",
"block",
".",
"type",
".",
"has_command",
"(",
"'readVariable'",
")",
":",
"return",
"'variable'",
"elif",
"self",
".",
"block",
".",
"type",
".",
"has_command",
"(",
"'contentsOfList:'",
")",
":",... | The type of value to watch, based on :attr:`block`.
One of ``variable``, ``list``, or ``block``.
``block`` watchers watch the value of a reporter block. | [
"The",
"type",
"of",
"value",
"to",
"watch",
"based",
"on",
":",
"attr",
":",
"block",
"."
] | fcccd80cae11dc233f6dd02b40ec9a388c62f259 | https://github.com/tjvr/kurt/blob/fcccd80cae11dc233f6dd02b40ec9a388c62f259/kurt/__init__.py#L930-L943 | train |
tjvr/kurt | kurt/__init__.py | Watcher.value | def value(self):
"""Return the :class:`Variable` or :class:`List` to watch.
Returns ``None`` if it's a block watcher.
"""
if self.kind == 'variable':
return self.target.variables[self.block.args[0]]
elif self.kind == 'list':
return self.target.lists[self.block.args[0]] | python | def value(self):
"""Return the :class:`Variable` or :class:`List` to watch.
Returns ``None`` if it's a block watcher.
"""
if self.kind == 'variable':
return self.target.variables[self.block.args[0]]
elif self.kind == 'list':
return self.target.lists[self.block.args[0]] | [
"def",
"value",
"(",
"self",
")",
":",
"if",
"self",
".",
"kind",
"==",
"'variable'",
":",
"return",
"self",
".",
"target",
".",
"variables",
"[",
"self",
".",
"block",
".",
"args",
"[",
"0",
"]",
"]",
"elif",
"self",
".",
"kind",
"==",
"'list'",
... | Return the :class:`Variable` or :class:`List` to watch.
Returns ``None`` if it's a block watcher. | [
"Return",
"the",
":",
"class",
":",
"Variable",
"or",
":",
"class",
":",
"List",
"to",
"watch",
"."
] | fcccd80cae11dc233f6dd02b40ec9a388c62f259 | https://github.com/tjvr/kurt/blob/fcccd80cae11dc233f6dd02b40ec9a388c62f259/kurt/__init__.py#L946-L955 | train |
tjvr/kurt | kurt/__init__.py | Color.stringify | def stringify(self):
"""Returns the color value in hexcode format.
eg. ``'#ff1056'``
"""
hexcode = "#"
for x in self.value:
part = hex(x)[2:]
if len(part) < 2: part = "0" + part
hexcode += part
return hexcode | python | def stringify(self):
"""Returns the color value in hexcode format.
eg. ``'#ff1056'``
"""
hexcode = "#"
for x in self.value:
part = hex(x)[2:]
if len(part) < 2: part = "0" + part
hexcode += part
return hexcode | [
"def",
"stringify",
"(",
"self",
")",
":",
"hexcode",
"=",
"\"#\"",
"for",
"x",
"in",
"self",
".",
"value",
":",
"part",
"=",
"hex",
"(",
"x",
")",
"[",
"2",
":",
"]",
"if",
"len",
"(",
"part",
")",
"<",
"2",
":",
"part",
"=",
"\"0\"",
"+",
... | Returns the color value in hexcode format.
eg. ``'#ff1056'`` | [
"Returns",
"the",
"color",
"value",
"in",
"hexcode",
"format",
"."
] | fcccd80cae11dc233f6dd02b40ec9a388c62f259 | https://github.com/tjvr/kurt/blob/fcccd80cae11dc233f6dd02b40ec9a388c62f259/kurt/__init__.py#L1123-L1134 | train |
tjvr/kurt | kurt/__init__.py | Insert.options | def options(self, scriptable=None):
"""Return a list of valid options to a menu insert, given a
Scriptable for context.
Mostly complete, excepting 'attribute'.
"""
options = list(Insert.KIND_OPTIONS.get(self.kind, []))
if scriptable:
if self.kind == 'var':
options += scriptable.variables.keys()
options += scriptable.project.variables.keys()
elif self.kind == 'list':
options += scriptable.lists.keys()
options += scriptable.project.lists.keys()
elif self.kind == 'costume':
options += [c.name for c in scriptable.costumes]
elif self.kind == 'backdrop':
options += [c.name for c in scriptable.project.stage.costumes]
elif self.kind == 'sound':
options += [c.name for c in scriptable.sounds]
options += [c.name for c in scriptable.project.stage.sounds]
elif self.kind in ('spriteOnly', 'spriteOrMouse', 'spriteOrStage',
'touching'):
options += [s.name for s in scriptable.project.sprites]
elif self.kind == 'attribute':
pass # TODO
elif self.kind == 'broadcast':
options += list(set(scriptable.project.get_broadcasts()))
return options | python | def options(self, scriptable=None):
"""Return a list of valid options to a menu insert, given a
Scriptable for context.
Mostly complete, excepting 'attribute'.
"""
options = list(Insert.KIND_OPTIONS.get(self.kind, []))
if scriptable:
if self.kind == 'var':
options += scriptable.variables.keys()
options += scriptable.project.variables.keys()
elif self.kind == 'list':
options += scriptable.lists.keys()
options += scriptable.project.lists.keys()
elif self.kind == 'costume':
options += [c.name for c in scriptable.costumes]
elif self.kind == 'backdrop':
options += [c.name for c in scriptable.project.stage.costumes]
elif self.kind == 'sound':
options += [c.name for c in scriptable.sounds]
options += [c.name for c in scriptable.project.stage.sounds]
elif self.kind in ('spriteOnly', 'spriteOrMouse', 'spriteOrStage',
'touching'):
options += [s.name for s in scriptable.project.sprites]
elif self.kind == 'attribute':
pass # TODO
elif self.kind == 'broadcast':
options += list(set(scriptable.project.get_broadcasts()))
return options | [
"def",
"options",
"(",
"self",
",",
"scriptable",
"=",
"None",
")",
":",
"options",
"=",
"list",
"(",
"Insert",
".",
"KIND_OPTIONS",
".",
"get",
"(",
"self",
".",
"kind",
",",
"[",
"]",
")",
")",
"if",
"scriptable",
":",
"if",
"self",
".",
"kind",
... | Return a list of valid options to a menu insert, given a
Scriptable for context.
Mostly complete, excepting 'attribute'. | [
"Return",
"a",
"list",
"of",
"valid",
"options",
"to",
"a",
"menu",
"insert",
"given",
"a",
"Scriptable",
"for",
"context",
"."
] | fcccd80cae11dc233f6dd02b40ec9a388c62f259 | https://github.com/tjvr/kurt/blob/fcccd80cae11dc233f6dd02b40ec9a388c62f259/kurt/__init__.py#L1372-L1401 | train |
tjvr/kurt | kurt/__init__.py | BaseBlockType.text | def text(self):
"""The text displayed on the block.
String containing ``"%s"`` in place of inserts.
eg. ``'say %s for %s secs'``
"""
parts = [("%s" if isinstance(p, Insert) else p) for p in self.parts]
parts = [("%%" if p == "%" else p) for p in parts] # escape percent
return "".join(parts) | python | def text(self):
"""The text displayed on the block.
String containing ``"%s"`` in place of inserts.
eg. ``'say %s for %s secs'``
"""
parts = [("%s" if isinstance(p, Insert) else p) for p in self.parts]
parts = [("%%" if p == "%" else p) for p in parts] # escape percent
return "".join(parts) | [
"def",
"text",
"(",
"self",
")",
":",
"parts",
"=",
"[",
"(",
"\"%s\"",
"if",
"isinstance",
"(",
"p",
",",
"Insert",
")",
"else",
"p",
")",
"for",
"p",
"in",
"self",
".",
"parts",
"]",
"parts",
"=",
"[",
"(",
"\"%%\"",
"if",
"p",
"==",
"\"%\"",... | The text displayed on the block.
String containing ``"%s"`` in place of inserts.
eg. ``'say %s for %s secs'`` | [
"The",
"text",
"displayed",
"on",
"the",
"block",
"."
] | fcccd80cae11dc233f6dd02b40ec9a388c62f259 | https://github.com/tjvr/kurt/blob/fcccd80cae11dc233f6dd02b40ec9a388c62f259/kurt/__init__.py#L1455-L1465 | train |
tjvr/kurt | kurt/__init__.py | BaseBlockType.stripped_text | def stripped_text(self):
"""The :attr:`text`, with spaces and inserts removed.
Used by :class:`BlockType.get` to look up blocks.
"""
return BaseBlockType._strip_text(
self.text % tuple((i.default if i.shape == 'inline' else '%s')
for i in self.inserts)) | python | def stripped_text(self):
"""The :attr:`text`, with spaces and inserts removed.
Used by :class:`BlockType.get` to look up blocks.
"""
return BaseBlockType._strip_text(
self.text % tuple((i.default if i.shape == 'inline' else '%s')
for i in self.inserts)) | [
"def",
"stripped_text",
"(",
"self",
")",
":",
"return",
"BaseBlockType",
".",
"_strip_text",
"(",
"self",
".",
"text",
"%",
"tuple",
"(",
"(",
"i",
".",
"default",
"if",
"i",
".",
"shape",
"==",
"'inline'",
"else",
"'%s'",
")",
"for",
"i",
"in",
"se... | The :attr:`text`, with spaces and inserts removed.
Used by :class:`BlockType.get` to look up blocks. | [
"The",
":",
"attr",
":",
"text",
"with",
"spaces",
"and",
"inserts",
"removed",
"."
] | fcccd80cae11dc233f6dd02b40ec9a388c62f259 | https://github.com/tjvr/kurt/blob/fcccd80cae11dc233f6dd02b40ec9a388c62f259/kurt/__init__.py#L1482-L1490 | train |
tjvr/kurt | kurt/__init__.py | BaseBlockType._strip_text | def _strip_text(text):
"""Returns text with spaces and inserts removed."""
text = re.sub(r'[ ,?:]|%s', "", text.lower())
for chr in "-%":
new_text = text.replace(chr, "")
if new_text:
text = new_text
return text.lower() | python | def _strip_text(text):
"""Returns text with spaces and inserts removed."""
text = re.sub(r'[ ,?:]|%s', "", text.lower())
for chr in "-%":
new_text = text.replace(chr, "")
if new_text:
text = new_text
return text.lower() | [
"def",
"_strip_text",
"(",
"text",
")",
":",
"text",
"=",
"re",
".",
"sub",
"(",
"r'[ ,?:]|%s'",
",",
"\"\"",
",",
"text",
".",
"lower",
"(",
")",
")",
"for",
"chr",
"in",
"\"-%\"",
":",
"new_text",
"=",
"text",
".",
"replace",
"(",
"chr",
",",
"... | Returns text with spaces and inserts removed. | [
"Returns",
"text",
"with",
"spaces",
"and",
"inserts",
"removed",
"."
] | fcccd80cae11dc233f6dd02b40ec9a388c62f259 | https://github.com/tjvr/kurt/blob/fcccd80cae11dc233f6dd02b40ec9a388c62f259/kurt/__init__.py#L1493-L1500 | train |
tjvr/kurt | kurt/__init__.py | BaseBlockType.has_insert | def has_insert(self, shape):
"""Returns True if any of the inserts have the given shape."""
for insert in self.inserts:
if insert.shape == shape:
return True
return False | python | def has_insert(self, shape):
"""Returns True if any of the inserts have the given shape."""
for insert in self.inserts:
if insert.shape == shape:
return True
return False | [
"def",
"has_insert",
"(",
"self",
",",
"shape",
")",
":",
"for",
"insert",
"in",
"self",
".",
"inserts",
":",
"if",
"insert",
".",
"shape",
"==",
"shape",
":",
"return",
"True",
"return",
"False"
] | Returns True if any of the inserts have the given shape. | [
"Returns",
"True",
"if",
"any",
"of",
"the",
"inserts",
"have",
"the",
"given",
"shape",
"."
] | fcccd80cae11dc233f6dd02b40ec9a388c62f259 | https://github.com/tjvr/kurt/blob/fcccd80cae11dc233f6dd02b40ec9a388c62f259/kurt/__init__.py#L1526-L1531 | train |
tjvr/kurt | kurt/__init__.py | BlockType._add_conversion | def _add_conversion(self, plugin, pbt):
"""Add a new PluginBlockType conversion.
If the plugin already exists, do nothing.
"""
assert self.shape == pbt.shape
assert len(self.inserts) == len(pbt.inserts)
for (i, o) in zip(self.inserts, pbt.inserts):
assert i.shape == o.shape
assert i.kind == o.kind
assert i.unevaluated == o.unevaluated
if plugin not in self._plugins:
self._plugins[plugin] = pbt | python | def _add_conversion(self, plugin, pbt):
"""Add a new PluginBlockType conversion.
If the plugin already exists, do nothing.
"""
assert self.shape == pbt.shape
assert len(self.inserts) == len(pbt.inserts)
for (i, o) in zip(self.inserts, pbt.inserts):
assert i.shape == o.shape
assert i.kind == o.kind
assert i.unevaluated == o.unevaluated
if plugin not in self._plugins:
self._plugins[plugin] = pbt | [
"def",
"_add_conversion",
"(",
"self",
",",
"plugin",
",",
"pbt",
")",
":",
"assert",
"self",
".",
"shape",
"==",
"pbt",
".",
"shape",
"assert",
"len",
"(",
"self",
".",
"inserts",
")",
"==",
"len",
"(",
"pbt",
".",
"inserts",
")",
"for",
"(",
"i",... | Add a new PluginBlockType conversion.
If the plugin already exists, do nothing. | [
"Add",
"a",
"new",
"PluginBlockType",
"conversion",
"."
] | fcccd80cae11dc233f6dd02b40ec9a388c62f259 | https://github.com/tjvr/kurt/blob/fcccd80cae11dc233f6dd02b40ec9a388c62f259/kurt/__init__.py#L1558-L1571 | train |
tjvr/kurt | kurt/__init__.py | BlockType.convert | def convert(self, plugin=None):
"""Return a :class:`PluginBlockType` for the given plugin name.
If plugin is ``None``, return the first registered plugin.
"""
if plugin:
plugin = kurt.plugin.Kurt.get_plugin(plugin)
if plugin.name in self._plugins:
return self._plugins[plugin.name]
else:
err = BlockNotSupported("%s doesn't have %r" %
(plugin.display_name, self))
err.block_type = self
raise err
else:
return self.conversions[0] | python | def convert(self, plugin=None):
"""Return a :class:`PluginBlockType` for the given plugin name.
If plugin is ``None``, return the first registered plugin.
"""
if plugin:
plugin = kurt.plugin.Kurt.get_plugin(plugin)
if plugin.name in self._plugins:
return self._plugins[plugin.name]
else:
err = BlockNotSupported("%s doesn't have %r" %
(plugin.display_name, self))
err.block_type = self
raise err
else:
return self.conversions[0] | [
"def",
"convert",
"(",
"self",
",",
"plugin",
"=",
"None",
")",
":",
"if",
"plugin",
":",
"plugin",
"=",
"kurt",
".",
"plugin",
".",
"Kurt",
".",
"get_plugin",
"(",
"plugin",
")",
"if",
"plugin",
".",
"name",
"in",
"self",
".",
"_plugins",
":",
"re... | Return a :class:`PluginBlockType` for the given plugin name.
If plugin is ``None``, return the first registered plugin. | [
"Return",
"a",
":",
"class",
":",
"PluginBlockType",
"for",
"the",
"given",
"plugin",
"name",
"."
] | fcccd80cae11dc233f6dd02b40ec9a388c62f259 | https://github.com/tjvr/kurt/blob/fcccd80cae11dc233f6dd02b40ec9a388c62f259/kurt/__init__.py#L1573-L1589 | train |
tjvr/kurt | kurt/__init__.py | BlockType.has_conversion | def has_conversion(self, plugin):
"""Return True if the plugin supports this block."""
plugin = kurt.plugin.Kurt.get_plugin(plugin)
return plugin.name in self._plugins | python | def has_conversion(self, plugin):
"""Return True if the plugin supports this block."""
plugin = kurt.plugin.Kurt.get_plugin(plugin)
return plugin.name in self._plugins | [
"def",
"has_conversion",
"(",
"self",
",",
"plugin",
")",
":",
"plugin",
"=",
"kurt",
".",
"plugin",
".",
"Kurt",
".",
"get_plugin",
"(",
"plugin",
")",
"return",
"plugin",
".",
"name",
"in",
"self",
".",
"_plugins"
] | Return True if the plugin supports this block. | [
"Return",
"True",
"if",
"the",
"plugin",
"supports",
"this",
"block",
"."
] | fcccd80cae11dc233f6dd02b40ec9a388c62f259 | https://github.com/tjvr/kurt/blob/fcccd80cae11dc233f6dd02b40ec9a388c62f259/kurt/__init__.py#L1596-L1599 | train |
tjvr/kurt | kurt/__init__.py | BlockType.has_command | def has_command(self, command):
"""Returns True if any of the plugins have the given command."""
for pbt in self._plugins.values():
if pbt.command == command:
return True
return False | python | def has_command(self, command):
"""Returns True if any of the plugins have the given command."""
for pbt in self._plugins.values():
if pbt.command == command:
return True
return False | [
"def",
"has_command",
"(",
"self",
",",
"command",
")",
":",
"for",
"pbt",
"in",
"self",
".",
"_plugins",
".",
"values",
"(",
")",
":",
"if",
"pbt",
".",
"command",
"==",
"command",
":",
"return",
"True",
"return",
"False"
] | Returns True if any of the plugins have the given command. | [
"Returns",
"True",
"if",
"any",
"of",
"the",
"plugins",
"have",
"the",
"given",
"command",
"."
] | fcccd80cae11dc233f6dd02b40ec9a388c62f259 | https://github.com/tjvr/kurt/blob/fcccd80cae11dc233f6dd02b40ec9a388c62f259/kurt/__init__.py#L1601-L1606 | train |
tjvr/kurt | kurt/__init__.py | BlockType.get | def get(cls, block_type):
"""Return a :class:`BlockType` instance from the given parameter.
* If it's already a BlockType instance, return that.
* If it exactly matches the command on a :class:`PluginBlockType`,
return the corresponding BlockType.
* If it loosely matches the text on a PluginBlockType, return the
corresponding BlockType.
* If it's a PluginBlockType instance, look for and return the
corresponding BlockType.
"""
if isinstance(block_type, (BlockType, CustomBlockType)):
return block_type
if isinstance(block_type, PluginBlockType):
block_type = block_type.command
block = kurt.plugin.Kurt.block_by_command(block_type)
if block:
return block
blocks = kurt.plugin.Kurt.blocks_by_text(block_type)
for block in blocks: # check the blocks' commands map to unique blocks
if kurt.plugin.Kurt.block_by_command(
block.convert().command) != blocks[0]:
raise ValueError(
"ambigious block text %r, use one of %r instead" %
(block_type, [b.convert().command for b in blocks]))
if blocks:
return blocks[0]
raise UnknownBlock, repr(block_type) | python | def get(cls, block_type):
"""Return a :class:`BlockType` instance from the given parameter.
* If it's already a BlockType instance, return that.
* If it exactly matches the command on a :class:`PluginBlockType`,
return the corresponding BlockType.
* If it loosely matches the text on a PluginBlockType, return the
corresponding BlockType.
* If it's a PluginBlockType instance, look for and return the
corresponding BlockType.
"""
if isinstance(block_type, (BlockType, CustomBlockType)):
return block_type
if isinstance(block_type, PluginBlockType):
block_type = block_type.command
block = kurt.plugin.Kurt.block_by_command(block_type)
if block:
return block
blocks = kurt.plugin.Kurt.blocks_by_text(block_type)
for block in blocks: # check the blocks' commands map to unique blocks
if kurt.plugin.Kurt.block_by_command(
block.convert().command) != blocks[0]:
raise ValueError(
"ambigious block text %r, use one of %r instead" %
(block_type, [b.convert().command for b in blocks]))
if blocks:
return blocks[0]
raise UnknownBlock, repr(block_type) | [
"def",
"get",
"(",
"cls",
",",
"block_type",
")",
":",
"if",
"isinstance",
"(",
"block_type",
",",
"(",
"BlockType",
",",
"CustomBlockType",
")",
")",
":",
"return",
"block_type",
"if",
"isinstance",
"(",
"block_type",
",",
"PluginBlockType",
")",
":",
"bl... | Return a :class:`BlockType` instance from the given parameter.
* If it's already a BlockType instance, return that.
* If it exactly matches the command on a :class:`PluginBlockType`,
return the corresponding BlockType.
* If it loosely matches the text on a PluginBlockType, return the
corresponding BlockType.
* If it's a PluginBlockType instance, look for and return the
corresponding BlockType. | [
"Return",
"a",
":",
"class",
":",
"BlockType",
"instance",
"from",
"the",
"given",
"parameter",
"."
] | fcccd80cae11dc233f6dd02b40ec9a388c62f259 | https://github.com/tjvr/kurt/blob/fcccd80cae11dc233f6dd02b40ec9a388c62f259/kurt/__init__.py#L1617-L1653 | train |
tjvr/kurt | kurt/__init__.py | Block.copy | def copy(self):
"""Return a new Block instance with the same attributes."""
args = []
for arg in self.args:
if isinstance(arg, Block):
arg = arg.copy()
elif isinstance(arg, list):
arg = [b.copy() for b in arg]
args.append(arg)
return Block(self.type, *args) | python | def copy(self):
"""Return a new Block instance with the same attributes."""
args = []
for arg in self.args:
if isinstance(arg, Block):
arg = arg.copy()
elif isinstance(arg, list):
arg = [b.copy() for b in arg]
args.append(arg)
return Block(self.type, *args) | [
"def",
"copy",
"(",
"self",
")",
":",
"args",
"=",
"[",
"]",
"for",
"arg",
"in",
"self",
".",
"args",
":",
"if",
"isinstance",
"(",
"arg",
",",
"Block",
")",
":",
"arg",
"=",
"arg",
".",
"copy",
"(",
")",
"elif",
"isinstance",
"(",
"arg",
",",
... | Return a new Block instance with the same attributes. | [
"Return",
"a",
"new",
"Block",
"instance",
"with",
"the",
"same",
"attributes",
"."
] | fcccd80cae11dc233f6dd02b40ec9a388c62f259 | https://github.com/tjvr/kurt/blob/fcccd80cae11dc233f6dd02b40ec9a388c62f259/kurt/__init__.py#L1844-L1853 | train |
tjvr/kurt | kurt/__init__.py | Script.copy | def copy(self):
"""Return a new instance with the same attributes."""
return self.__class__([b.copy() for b in self.blocks],
tuple(self.pos) if self.pos else None) | python | def copy(self):
"""Return a new instance with the same attributes."""
return self.__class__([b.copy() for b in self.blocks],
tuple(self.pos) if self.pos else None) | [
"def",
"copy",
"(",
"self",
")",
":",
"return",
"self",
".",
"__class__",
"(",
"[",
"b",
".",
"copy",
"(",
")",
"for",
"b",
"in",
"self",
".",
"blocks",
"]",
",",
"tuple",
"(",
"self",
".",
"pos",
")",
"if",
"self",
".",
"pos",
"else",
"None",
... | Return a new instance with the same attributes. | [
"Return",
"a",
"new",
"instance",
"with",
"the",
"same",
"attributes",
"."
] | fcccd80cae11dc233f6dd02b40ec9a388c62f259 | https://github.com/tjvr/kurt/blob/fcccd80cae11dc233f6dd02b40ec9a388c62f259/kurt/__init__.py#L1929-L1932 | train |
tjvr/kurt | kurt/__init__.py | Costume.load | def load(self, path):
"""Load costume from image file.
Uses :attr:`Image.load`, but will set the Costume's name based on the
image filename.
"""
(folder, filename) = os.path.split(path)
(name, extension) = os.path.splitext(filename)
return Costume(name, Image.load(path)) | python | def load(self, path):
"""Load costume from image file.
Uses :attr:`Image.load`, but will set the Costume's name based on the
image filename.
"""
(folder, filename) = os.path.split(path)
(name, extension) = os.path.splitext(filename)
return Costume(name, Image.load(path)) | [
"def",
"load",
"(",
"self",
",",
"path",
")",
":",
"(",
"folder",
",",
"filename",
")",
"=",
"os",
".",
"path",
".",
"split",
"(",
"path",
")",
"(",
"name",
",",
"extension",
")",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"filename",
")",
"... | Load costume from image file.
Uses :attr:`Image.load`, but will set the Costume's name based on the
image filename. | [
"Load",
"costume",
"from",
"image",
"file",
"."
] | fcccd80cae11dc233f6dd02b40ec9a388c62f259 | https://github.com/tjvr/kurt/blob/fcccd80cae11dc233f6dd02b40ec9a388c62f259/kurt/__init__.py#L2043-L2052 | train |
tjvr/kurt | kurt/__init__.py | Image.pil_image | def pil_image(self):
"""A :class:`PIL.Image.Image` instance containing the image data."""
if not self._pil_image:
if self._format == "SVG":
raise VectorImageError("can't rasterise vector images")
self._pil_image = PIL.Image.open(StringIO(self.contents))
return self._pil_image | python | def pil_image(self):
"""A :class:`PIL.Image.Image` instance containing the image data."""
if not self._pil_image:
if self._format == "SVG":
raise VectorImageError("can't rasterise vector images")
self._pil_image = PIL.Image.open(StringIO(self.contents))
return self._pil_image | [
"def",
"pil_image",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_pil_image",
":",
"if",
"self",
".",
"_format",
"==",
"\"SVG\"",
":",
"raise",
"VectorImageError",
"(",
"\"can't rasterise vector images\"",
")",
"self",
".",
"_pil_image",
"=",
"PIL",
"."... | A :class:`PIL.Image.Image` instance containing the image data. | [
"A",
":",
"class",
":",
"PIL",
".",
"Image",
".",
"Image",
"instance",
"containing",
"the",
"image",
"data",
"."
] | fcccd80cae11dc233f6dd02b40ec9a388c62f259 | https://github.com/tjvr/kurt/blob/fcccd80cae11dc233f6dd02b40ec9a388c62f259/kurt/__init__.py#L2145-L2151 | train |
tjvr/kurt | kurt/__init__.py | Image.contents | def contents(self):
"""The raw file contents as a string."""
if not self._contents:
if self._path:
# Read file into memory so we don't run out of file descriptors
f = open(self._path, "rb")
self._contents = f.read()
f.close()
elif self._pil_image:
# Write PIL image to string
f = StringIO()
self._pil_image.save(f, self.format)
self._contents = f.getvalue()
return self._contents | python | def contents(self):
"""The raw file contents as a string."""
if not self._contents:
if self._path:
# Read file into memory so we don't run out of file descriptors
f = open(self._path, "rb")
self._contents = f.read()
f.close()
elif self._pil_image:
# Write PIL image to string
f = StringIO()
self._pil_image.save(f, self.format)
self._contents = f.getvalue()
return self._contents | [
"def",
"contents",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_contents",
":",
"if",
"self",
".",
"_path",
":",
"# Read file into memory so we don't run out of file descriptors",
"f",
"=",
"open",
"(",
"self",
".",
"_path",
",",
"\"rb\"",
")",
"self",
... | The raw file contents as a string. | [
"The",
"raw",
"file",
"contents",
"as",
"a",
"string",
"."
] | fcccd80cae11dc233f6dd02b40ec9a388c62f259 | https://github.com/tjvr/kurt/blob/fcccd80cae11dc233f6dd02b40ec9a388c62f259/kurt/__init__.py#L2154-L2167 | train |
tjvr/kurt | kurt/__init__.py | Image.format | def format(self):
"""The format of the image file.
An uppercase string corresponding to the
:attr:`PIL.ImageFile.ImageFile.format` attribute. Valid values include
``"JPEG"`` and ``"PNG"``.
"""
if self._format:
return self._format
elif self.pil_image:
return self.pil_image.format | python | def format(self):
"""The format of the image file.
An uppercase string corresponding to the
:attr:`PIL.ImageFile.ImageFile.format` attribute. Valid values include
``"JPEG"`` and ``"PNG"``.
"""
if self._format:
return self._format
elif self.pil_image:
return self.pil_image.format | [
"def",
"format",
"(",
"self",
")",
":",
"if",
"self",
".",
"_format",
":",
"return",
"self",
".",
"_format",
"elif",
"self",
".",
"pil_image",
":",
"return",
"self",
".",
"pil_image",
".",
"format"
] | The format of the image file.
An uppercase string corresponding to the
:attr:`PIL.ImageFile.ImageFile.format` attribute. Valid values include
``"JPEG"`` and ``"PNG"``. | [
"The",
"format",
"of",
"the",
"image",
"file",
"."
] | fcccd80cae11dc233f6dd02b40ec9a388c62f259 | https://github.com/tjvr/kurt/blob/fcccd80cae11dc233f6dd02b40ec9a388c62f259/kurt/__init__.py#L2170-L2181 | train |
tjvr/kurt | kurt/__init__.py | Image.size | def size(self):
"""``(width, height)`` in pixels."""
if self._size and not self._pil_image:
return self._size
else:
return self.pil_image.size | python | def size(self):
"""``(width, height)`` in pixels."""
if self._size and not self._pil_image:
return self._size
else:
return self.pil_image.size | [
"def",
"size",
"(",
"self",
")",
":",
"if",
"self",
".",
"_size",
"and",
"not",
"self",
".",
"_pil_image",
":",
"return",
"self",
".",
"_size",
"else",
":",
"return",
"self",
".",
"pil_image",
".",
"size"
] | ``(width, height)`` in pixels. | [
"(",
"width",
"height",
")",
"in",
"pixels",
"."
] | fcccd80cae11dc233f6dd02b40ec9a388c62f259 | https://github.com/tjvr/kurt/blob/fcccd80cae11dc233f6dd02b40ec9a388c62f259/kurt/__init__.py#L2193-L2198 | train |
tjvr/kurt | kurt/__init__.py | Image.load | def load(cls, path):
"""Load image from file."""
assert os.path.exists(path), "No such file: %r" % path
(folder, filename) = os.path.split(path)
(name, extension) = os.path.splitext(filename)
image = Image(None)
image._path = path
image._format = Image.image_format(extension)
return image | python | def load(cls, path):
"""Load image from file."""
assert os.path.exists(path), "No such file: %r" % path
(folder, filename) = os.path.split(path)
(name, extension) = os.path.splitext(filename)
image = Image(None)
image._path = path
image._format = Image.image_format(extension)
return image | [
"def",
"load",
"(",
"cls",
",",
"path",
")",
":",
"assert",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
",",
"\"No such file: %r\"",
"%",
"path",
"(",
"folder",
",",
"filename",
")",
"=",
"os",
".",
"path",
".",
"split",
"(",
"path",
")",
... | Load image from file. | [
"Load",
"image",
"from",
"file",
"."
] | fcccd80cae11dc233f6dd02b40ec9a388c62f259 | https://github.com/tjvr/kurt/blob/fcccd80cae11dc233f6dd02b40ec9a388c62f259/kurt/__init__.py#L2211-L2222 | train |
tjvr/kurt | kurt/__init__.py | Image.convert | def convert(self, *formats):
"""Return an Image instance with the first matching format.
For each format in ``*args``: If the image's :attr:`format` attribute
is the same as the format, return self, otherwise try the next format.
If none of the formats match, return a new Image instance with the
last format.
"""
for format in formats:
format = Image.image_format(format)
if self.format == format:
return self
else:
return self._convert(format) | python | def convert(self, *formats):
"""Return an Image instance with the first matching format.
For each format in ``*args``: If the image's :attr:`format` attribute
is the same as the format, return self, otherwise try the next format.
If none of the formats match, return a new Image instance with the
last format.
"""
for format in formats:
format = Image.image_format(format)
if self.format == format:
return self
else:
return self._convert(format) | [
"def",
"convert",
"(",
"self",
",",
"*",
"formats",
")",
":",
"for",
"format",
"in",
"formats",
":",
"format",
"=",
"Image",
".",
"image_format",
"(",
"format",
")",
"if",
"self",
".",
"format",
"==",
"format",
":",
"return",
"self",
"else",
":",
"re... | Return an Image instance with the first matching format.
For each format in ``*args``: If the image's :attr:`format` attribute
is the same as the format, return self, otherwise try the next format.
If none of the formats match, return a new Image instance with the
last format. | [
"Return",
"an",
"Image",
"instance",
"with",
"the",
"first",
"matching",
"format",
"."
] | fcccd80cae11dc233f6dd02b40ec9a388c62f259 | https://github.com/tjvr/kurt/blob/fcccd80cae11dc233f6dd02b40ec9a388c62f259/kurt/__init__.py#L2224-L2239 | train |
tjvr/kurt | kurt/__init__.py | Image._convert | def _convert(self, format):
"""Return a new Image instance with the given format.
Returns self if the format is already the same.
"""
if self.format == format:
return self
else:
image = Image(self.pil_image)
image._format = format
return image | python | def _convert(self, format):
"""Return a new Image instance with the given format.
Returns self if the format is already the same.
"""
if self.format == format:
return self
else:
image = Image(self.pil_image)
image._format = format
return image | [
"def",
"_convert",
"(",
"self",
",",
"format",
")",
":",
"if",
"self",
".",
"format",
"==",
"format",
":",
"return",
"self",
"else",
":",
"image",
"=",
"Image",
"(",
"self",
".",
"pil_image",
")",
"image",
".",
"_format",
"=",
"format",
"return",
"im... | Return a new Image instance with the given format.
Returns self if the format is already the same. | [
"Return",
"a",
"new",
"Image",
"instance",
"with",
"the",
"given",
"format",
"."
] | fcccd80cae11dc233f6dd02b40ec9a388c62f259 | https://github.com/tjvr/kurt/blob/fcccd80cae11dc233f6dd02b40ec9a388c62f259/kurt/__init__.py#L2241-L2252 | train |
tjvr/kurt | kurt/__init__.py | Image.save | def save(self, path):
"""Save image to file path.
The image format is guessed from the extension. If path has no
extension, the image's :attr:`format` is used.
:returns: Path to the saved file.
"""
(folder, filename) = os.path.split(path)
(name, extension) = os.path.splitext(filename)
if not name:
raise ValueError, "name is required"
if extension:
format = Image.image_format(extension)
else:
format = self.format
filename = name + self.extension
path = os.path.join(folder, filename)
image = self.convert(format)
if image._contents:
f = open(path, "wb")
f.write(image._contents)
f.close()
else:
image.pil_image.save(path, format)
return path | python | def save(self, path):
"""Save image to file path.
The image format is guessed from the extension. If path has no
extension, the image's :attr:`format` is used.
:returns: Path to the saved file.
"""
(folder, filename) = os.path.split(path)
(name, extension) = os.path.splitext(filename)
if not name:
raise ValueError, "name is required"
if extension:
format = Image.image_format(extension)
else:
format = self.format
filename = name + self.extension
path = os.path.join(folder, filename)
image = self.convert(format)
if image._contents:
f = open(path, "wb")
f.write(image._contents)
f.close()
else:
image.pil_image.save(path, format)
return path | [
"def",
"save",
"(",
"self",
",",
"path",
")",
":",
"(",
"folder",
",",
"filename",
")",
"=",
"os",
".",
"path",
".",
"split",
"(",
"path",
")",
"(",
"name",
",",
"extension",
")",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"filename",
")",
"... | Save image to file path.
The image format is guessed from the extension. If path has no
extension, the image's :attr:`format` is used.
:returns: Path to the saved file. | [
"Save",
"image",
"to",
"file",
"path",
"."
] | fcccd80cae11dc233f6dd02b40ec9a388c62f259 | https://github.com/tjvr/kurt/blob/fcccd80cae11dc233f6dd02b40ec9a388c62f259/kurt/__init__.py#L2254-L2284 | train |
tjvr/kurt | kurt/__init__.py | Image.new | def new(self, size, fill):
"""Return a new Image instance filled with a color."""
return Image(PIL.Image.new("RGB", size, fill)) | python | def new(self, size, fill):
"""Return a new Image instance filled with a color."""
return Image(PIL.Image.new("RGB", size, fill)) | [
"def",
"new",
"(",
"self",
",",
"size",
",",
"fill",
")",
":",
"return",
"Image",
"(",
"PIL",
".",
"Image",
".",
"new",
"(",
"\"RGB\"",
",",
"size",
",",
"fill",
")",
")"
] | Return a new Image instance filled with a color. | [
"Return",
"a",
"new",
"Image",
"instance",
"filled",
"with",
"a",
"color",
"."
] | fcccd80cae11dc233f6dd02b40ec9a388c62f259 | https://github.com/tjvr/kurt/blob/fcccd80cae11dc233f6dd02b40ec9a388c62f259/kurt/__init__.py#L2287-L2289 | train |
tjvr/kurt | kurt/__init__.py | Image.resize | def resize(self, size):
"""Return a new Image instance with the given size."""
return Image(self.pil_image.resize(size, PIL.Image.ANTIALIAS)) | python | def resize(self, size):
"""Return a new Image instance with the given size."""
return Image(self.pil_image.resize(size, PIL.Image.ANTIALIAS)) | [
"def",
"resize",
"(",
"self",
",",
"size",
")",
":",
"return",
"Image",
"(",
"self",
".",
"pil_image",
".",
"resize",
"(",
"size",
",",
"PIL",
".",
"Image",
".",
"ANTIALIAS",
")",
")"
] | Return a new Image instance with the given size. | [
"Return",
"a",
"new",
"Image",
"instance",
"with",
"the",
"given",
"size",
"."
] | fcccd80cae11dc233f6dd02b40ec9a388c62f259 | https://github.com/tjvr/kurt/blob/fcccd80cae11dc233f6dd02b40ec9a388c62f259/kurt/__init__.py#L2291-L2293 | train |
tjvr/kurt | kurt/__init__.py | Image.paste | def paste(self, other):
"""Return a new Image with the given image pasted on top.
This image will show through transparent areas of the given image.
"""
r, g, b, alpha = other.pil_image.split()
pil_image = self.pil_image.copy()
pil_image.paste(other.pil_image, mask=alpha)
return kurt.Image(pil_image) | python | def paste(self, other):
"""Return a new Image with the given image pasted on top.
This image will show through transparent areas of the given image.
"""
r, g, b, alpha = other.pil_image.split()
pil_image = self.pil_image.copy()
pil_image.paste(other.pil_image, mask=alpha)
return kurt.Image(pil_image) | [
"def",
"paste",
"(",
"self",
",",
"other",
")",
":",
"r",
",",
"g",
",",
"b",
",",
"alpha",
"=",
"other",
".",
"pil_image",
".",
"split",
"(",
")",
"pil_image",
"=",
"self",
".",
"pil_image",
".",
"copy",
"(",
")",
"pil_image",
".",
"paste",
"(",... | Return a new Image with the given image pasted on top.
This image will show through transparent areas of the given image. | [
"Return",
"a",
"new",
"Image",
"with",
"the",
"given",
"image",
"pasted",
"on",
"top",
"."
] | fcccd80cae11dc233f6dd02b40ec9a388c62f259 | https://github.com/tjvr/kurt/blob/fcccd80cae11dc233f6dd02b40ec9a388c62f259/kurt/__init__.py#L2295-L2304 | train |
tjvr/kurt | kurt/__init__.py | Sound.load | def load(self, path):
"""Load sound from wave file.
Uses :attr:`Waveform.load`, but will set the Waveform's name based on
the sound filename.
"""
(folder, filename) = os.path.split(path)
(name, extension) = os.path.splitext(filename)
return Sound(name, Waveform.load(path)) | python | def load(self, path):
"""Load sound from wave file.
Uses :attr:`Waveform.load`, but will set the Waveform's name based on
the sound filename.
"""
(folder, filename) = os.path.split(path)
(name, extension) = os.path.splitext(filename)
return Sound(name, Waveform.load(path)) | [
"def",
"load",
"(",
"self",
",",
"path",
")",
":",
"(",
"folder",
",",
"filename",
")",
"=",
"os",
".",
"path",
".",
"split",
"(",
"path",
")",
"(",
"name",
",",
"extension",
")",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"filename",
")",
"... | Load sound from wave file.
Uses :attr:`Waveform.load`, but will set the Waveform's name based on
the sound filename. | [
"Load",
"sound",
"from",
"wave",
"file",
"."
] | fcccd80cae11dc233f6dd02b40ec9a388c62f259 | https://github.com/tjvr/kurt/blob/fcccd80cae11dc233f6dd02b40ec9a388c62f259/kurt/__init__.py#L2347-L2356 | train |
tjvr/kurt | kurt/__init__.py | Sound.save | def save(self, path):
"""Save the sound to a wave file at the given path.
Uses :attr:`Waveform.save`, but if the path ends in a folder instead of
a file, the filename is based on the project's :attr:`name`.
:returns: Path to the saved file.
"""
(folder, filename) = os.path.split(path)
if not filename:
filename = _clean_filename(self.name)
path = os.path.join(folder, filename)
return self.waveform.save(path) | python | def save(self, path):
"""Save the sound to a wave file at the given path.
Uses :attr:`Waveform.save`, but if the path ends in a folder instead of
a file, the filename is based on the project's :attr:`name`.
:returns: Path to the saved file.
"""
(folder, filename) = os.path.split(path)
if not filename:
filename = _clean_filename(self.name)
path = os.path.join(folder, filename)
return self.waveform.save(path) | [
"def",
"save",
"(",
"self",
",",
"path",
")",
":",
"(",
"folder",
",",
"filename",
")",
"=",
"os",
".",
"path",
".",
"split",
"(",
"path",
")",
"if",
"not",
"filename",
":",
"filename",
"=",
"_clean_filename",
"(",
"self",
".",
"name",
")",
"path",... | Save the sound to a wave file at the given path.
Uses :attr:`Waveform.save`, but if the path ends in a folder instead of
a file, the filename is based on the project's :attr:`name`.
:returns: Path to the saved file. | [
"Save",
"the",
"sound",
"to",
"a",
"wave",
"file",
"at",
"the",
"given",
"path",
"."
] | fcccd80cae11dc233f6dd02b40ec9a388c62f259 | https://github.com/tjvr/kurt/blob/fcccd80cae11dc233f6dd02b40ec9a388c62f259/kurt/__init__.py#L2358-L2371 | train |
tjvr/kurt | kurt/__init__.py | Waveform.contents | def contents(self):
"""The raw file contents as a string."""
if not self._contents:
if self._path:
# Read file into memory so we don't run out of file descriptors
f = open(self._path, "rb")
self._contents = f.read()
f.close()
return self._contents | python | def contents(self):
"""The raw file contents as a string."""
if not self._contents:
if self._path:
# Read file into memory so we don't run out of file descriptors
f = open(self._path, "rb")
self._contents = f.read()
f.close()
return self._contents | [
"def",
"contents",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_contents",
":",
"if",
"self",
".",
"_path",
":",
"# Read file into memory so we don't run out of file descriptors",
"f",
"=",
"open",
"(",
"self",
".",
"_path",
",",
"\"rb\"",
")",
"self",
... | The raw file contents as a string. | [
"The",
"raw",
"file",
"contents",
"as",
"a",
"string",
"."
] | fcccd80cae11dc233f6dd02b40ec9a388c62f259 | https://github.com/tjvr/kurt/blob/fcccd80cae11dc233f6dd02b40ec9a388c62f259/kurt/__init__.py#L2405-L2413 | train |
tjvr/kurt | kurt/__init__.py | Waveform._wave | def _wave(self):
"""Return a wave.Wave_read instance from the ``wave`` module."""
try:
return wave.open(StringIO(self.contents))
except wave.Error, err:
err.message += "\nInvalid wave file: %s" % self
err.args = (err.message,)
raise | python | def _wave(self):
"""Return a wave.Wave_read instance from the ``wave`` module."""
try:
return wave.open(StringIO(self.contents))
except wave.Error, err:
err.message += "\nInvalid wave file: %s" % self
err.args = (err.message,)
raise | [
"def",
"_wave",
"(",
"self",
")",
":",
"try",
":",
"return",
"wave",
".",
"open",
"(",
"StringIO",
"(",
"self",
".",
"contents",
")",
")",
"except",
"wave",
".",
"Error",
",",
"err",
":",
"err",
".",
"message",
"+=",
"\"\\nInvalid wave file: %s\"",
"%"... | Return a wave.Wave_read instance from the ``wave`` module. | [
"Return",
"a",
"wave",
".",
"Wave_read",
"instance",
"from",
"the",
"wave",
"module",
"."
] | fcccd80cae11dc233f6dd02b40ec9a388c62f259 | https://github.com/tjvr/kurt/blob/fcccd80cae11dc233f6dd02b40ec9a388c62f259/kurt/__init__.py#L2416-L2423 | train |
tjvr/kurt | kurt/__init__.py | Waveform.load | def load(cls, path):
"""Load Waveform from file."""
assert os.path.exists(path), "No such file: %r" % path
(folder, filename) = os.path.split(path)
(name, extension) = os.path.splitext(filename)
wave = Waveform(None)
wave._path = path
return wave | python | def load(cls, path):
"""Load Waveform from file."""
assert os.path.exists(path), "No such file: %r" % path
(folder, filename) = os.path.split(path)
(name, extension) = os.path.splitext(filename)
wave = Waveform(None)
wave._path = path
return wave | [
"def",
"load",
"(",
"cls",
",",
"path",
")",
":",
"assert",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
",",
"\"No such file: %r\"",
"%",
"path",
"(",
"folder",
",",
"filename",
")",
"=",
"os",
".",
"path",
".",
"split",
"(",
"path",
")",
... | Load Waveform from file. | [
"Load",
"Waveform",
"from",
"file",
"."
] | fcccd80cae11dc233f6dd02b40ec9a388c62f259 | https://github.com/tjvr/kurt/blob/fcccd80cae11dc233f6dd02b40ec9a388c62f259/kurt/__init__.py#L2445-L2454 | train |
tjvr/kurt | kurt/__init__.py | Waveform.save | def save(self, path):
"""Save waveform to file path as a WAV file.
:returns: Path to the saved file.
"""
(folder, filename) = os.path.split(path)
(name, extension) = os.path.splitext(filename)
if not name:
raise ValueError, "name is required"
path = os.path.join(folder, name + self.extension)
f = open(path, "wb")
f.write(self.contents)
f.close()
return path | python | def save(self, path):
"""Save waveform to file path as a WAV file.
:returns: Path to the saved file.
"""
(folder, filename) = os.path.split(path)
(name, extension) = os.path.splitext(filename)
if not name:
raise ValueError, "name is required"
path = os.path.join(folder, name + self.extension)
f = open(path, "wb")
f.write(self.contents)
f.close()
return path | [
"def",
"save",
"(",
"self",
",",
"path",
")",
":",
"(",
"folder",
",",
"filename",
")",
"=",
"os",
".",
"path",
".",
"split",
"(",
"path",
")",
"(",
"name",
",",
"extension",
")",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"filename",
")",
"... | Save waveform to file path as a WAV file.
:returns: Path to the saved file. | [
"Save",
"waveform",
"to",
"file",
"path",
"as",
"a",
"WAV",
"file",
"."
] | fcccd80cae11dc233f6dd02b40ec9a388c62f259 | https://github.com/tjvr/kurt/blob/fcccd80cae11dc233f6dd02b40ec9a388c62f259/kurt/__init__.py#L2456-L2473 | train |
tjvr/kurt | examples/images.py | sort_nicely | def sort_nicely(l):
"""Sort the given list in the way that humans expect."""
convert = lambda text: int(text) if text.isdigit() else text
alphanum_key = lambda key: [convert(c) for c in re.split('([0-9]+)', key)]
l.sort(key=alphanum_key) | python | def sort_nicely(l):
"""Sort the given list in the way that humans expect."""
convert = lambda text: int(text) if text.isdigit() else text
alphanum_key = lambda key: [convert(c) for c in re.split('([0-9]+)', key)]
l.sort(key=alphanum_key) | [
"def",
"sort_nicely",
"(",
"l",
")",
":",
"convert",
"=",
"lambda",
"text",
":",
"int",
"(",
"text",
")",
"if",
"text",
".",
"isdigit",
"(",
")",
"else",
"text",
"alphanum_key",
"=",
"lambda",
"key",
":",
"[",
"convert",
"(",
"c",
")",
"for",
"c",
... | Sort the given list in the way that humans expect. | [
"Sort",
"the",
"given",
"list",
"in",
"the",
"way",
"that",
"humans",
"expect",
"."
] | fcccd80cae11dc233f6dd02b40ec9a388c62f259 | https://github.com/tjvr/kurt/blob/fcccd80cae11dc233f6dd02b40ec9a388c62f259/examples/images.py#L22-L26 | train |
benjamin-hodgson/asynqp | src/asynqp/connection.py | Connection.open_channel | def open_channel(self):
"""
Open a new channel on this connection.
This method is a :ref:`coroutine <coroutine>`.
:return: The new :class:`Channel` object.
"""
if self._closing:
raise ConnectionClosed("Closed by application")
if self.closed.done():
raise self.closed.exception()
channel = yield from self.channel_factory.open()
return channel | python | def open_channel(self):
"""
Open a new channel on this connection.
This method is a :ref:`coroutine <coroutine>`.
:return: The new :class:`Channel` object.
"""
if self._closing:
raise ConnectionClosed("Closed by application")
if self.closed.done():
raise self.closed.exception()
channel = yield from self.channel_factory.open()
return channel | [
"def",
"open_channel",
"(",
"self",
")",
":",
"if",
"self",
".",
"_closing",
":",
"raise",
"ConnectionClosed",
"(",
"\"Closed by application\"",
")",
"if",
"self",
".",
"closed",
".",
"done",
"(",
")",
":",
"raise",
"self",
".",
"closed",
".",
"exception",... | Open a new channel on this connection.
This method is a :ref:`coroutine <coroutine>`.
:return: The new :class:`Channel` object. | [
"Open",
"a",
"new",
"channel",
"on",
"this",
"connection",
"."
] | ea8630d1803d10d4fd64b1a0e50f3097710b34d1 | https://github.com/benjamin-hodgson/asynqp/blob/ea8630d1803d10d4fd64b1a0e50f3097710b34d1/src/asynqp/connection.py#L50-L64 | train |
benjamin-hodgson/asynqp | src/asynqp/connection.py | Connection.close | def close(self):
"""
Close the connection by handshaking with the server.
This method is a :ref:`coroutine <coroutine>`.
"""
if not self.is_closed():
self._closing = True
# Let the ConnectionActor do the actual close operations.
# It will do the work on CloseOK
self.sender.send_Close(
0, 'Connection closed by application', 0, 0)
try:
yield from self.synchroniser.wait(spec.ConnectionCloseOK)
except AMQPConnectionError:
# For example if both sides want to close or the connection
# is closed.
pass
else:
if self._closing:
log.warn("Called `close` on already closing connection...")
# finish all pending tasks
yield from self.protocol.heartbeat_monitor.wait_closed() | python | def close(self):
"""
Close the connection by handshaking with the server.
This method is a :ref:`coroutine <coroutine>`.
"""
if not self.is_closed():
self._closing = True
# Let the ConnectionActor do the actual close operations.
# It will do the work on CloseOK
self.sender.send_Close(
0, 'Connection closed by application', 0, 0)
try:
yield from self.synchroniser.wait(spec.ConnectionCloseOK)
except AMQPConnectionError:
# For example if both sides want to close or the connection
# is closed.
pass
else:
if self._closing:
log.warn("Called `close` on already closing connection...")
# finish all pending tasks
yield from self.protocol.heartbeat_monitor.wait_closed() | [
"def",
"close",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"is_closed",
"(",
")",
":",
"self",
".",
"_closing",
"=",
"True",
"# Let the ConnectionActor do the actual close operations.",
"# It will do the work on CloseOK",
"self",
".",
"sender",
".",
"send_Clos... | Close the connection by handshaking with the server.
This method is a :ref:`coroutine <coroutine>`. | [
"Close",
"the",
"connection",
"by",
"handshaking",
"with",
"the",
"server",
"."
] | ea8630d1803d10d4fd64b1a0e50f3097710b34d1 | https://github.com/benjamin-hodgson/asynqp/blob/ea8630d1803d10d4fd64b1a0e50f3097710b34d1/src/asynqp/connection.py#L71-L93 | train |
benjamin-hodgson/asynqp | src/asynqp/connection.py | ConnectionActor.handle_PoisonPillFrame | def handle_PoisonPillFrame(self, frame):
""" Is sent in case protocol lost connection to server."""
# Will be delivered after Close or CloseOK handlers. It's for channels,
# so ignore it.
if self.connection.closed.done():
return
# If connection was not closed already - we lost connection.
# Protocol should already be closed
self._close_all(frame.exception) | python | def handle_PoisonPillFrame(self, frame):
""" Is sent in case protocol lost connection to server."""
# Will be delivered after Close or CloseOK handlers. It's for channels,
# so ignore it.
if self.connection.closed.done():
return
# If connection was not closed already - we lost connection.
# Protocol should already be closed
self._close_all(frame.exception) | [
"def",
"handle_PoisonPillFrame",
"(",
"self",
",",
"frame",
")",
":",
"# Will be delivered after Close or CloseOK handlers. It's for channels,",
"# so ignore it.",
"if",
"self",
".",
"connection",
".",
"closed",
".",
"done",
"(",
")",
":",
"return",
"# If connection was n... | Is sent in case protocol lost connection to server. | [
"Is",
"sent",
"in",
"case",
"protocol",
"lost",
"connection",
"to",
"server",
"."
] | ea8630d1803d10d4fd64b1a0e50f3097710b34d1 | https://github.com/benjamin-hodgson/asynqp/blob/ea8630d1803d10d4fd64b1a0e50f3097710b34d1/src/asynqp/connection.py#L174-L182 | train |
benjamin-hodgson/asynqp | src/asynqp/connection.py | ConnectionActor.handle_ConnectionClose | def handle_ConnectionClose(self, frame):
""" AMQP server closed the channel with an error """
# Notify server we are OK to close.
self.sender.send_CloseOK()
exc = ConnectionClosed(frame.payload.reply_text,
frame.payload.reply_code)
self._close_all(exc)
# This will not abort transport, it will try to flush remaining data
# asynchronously, as stated in `asyncio` docs.
self.protocol.close() | python | def handle_ConnectionClose(self, frame):
""" AMQP server closed the channel with an error """
# Notify server we are OK to close.
self.sender.send_CloseOK()
exc = ConnectionClosed(frame.payload.reply_text,
frame.payload.reply_code)
self._close_all(exc)
# This will not abort transport, it will try to flush remaining data
# asynchronously, as stated in `asyncio` docs.
self.protocol.close() | [
"def",
"handle_ConnectionClose",
"(",
"self",
",",
"frame",
")",
":",
"# Notify server we are OK to close.",
"self",
".",
"sender",
".",
"send_CloseOK",
"(",
")",
"exc",
"=",
"ConnectionClosed",
"(",
"frame",
".",
"payload",
".",
"reply_text",
",",
"frame",
".",... | AMQP server closed the channel with an error | [
"AMQP",
"server",
"closed",
"the",
"channel",
"with",
"an",
"error"
] | ea8630d1803d10d4fd64b1a0e50f3097710b34d1 | https://github.com/benjamin-hodgson/asynqp/blob/ea8630d1803d10d4fd64b1a0e50f3097710b34d1/src/asynqp/connection.py#L184-L194 | train |
benjamin-hodgson/asynqp | src/asynqp/exchange.py | Exchange.publish | def publish(self, message, routing_key, *, mandatory=True):
"""
Publish a message on the exchange, to be asynchronously delivered to queues.
:param asynqp.Message message: the message to send
:param str routing_key: the routing key with which to publish the message
:param bool mandatory: if True (the default) undeliverable messages result in an error (see also :meth:`Channel.set_return_handler`)
"""
self.sender.send_BasicPublish(self.name, routing_key, mandatory, message) | python | def publish(self, message, routing_key, *, mandatory=True):
"""
Publish a message on the exchange, to be asynchronously delivered to queues.
:param asynqp.Message message: the message to send
:param str routing_key: the routing key with which to publish the message
:param bool mandatory: if True (the default) undeliverable messages result in an error (see also :meth:`Channel.set_return_handler`)
"""
self.sender.send_BasicPublish(self.name, routing_key, mandatory, message) | [
"def",
"publish",
"(",
"self",
",",
"message",
",",
"routing_key",
",",
"*",
",",
"mandatory",
"=",
"True",
")",
":",
"self",
".",
"sender",
".",
"send_BasicPublish",
"(",
"self",
".",
"name",
",",
"routing_key",
",",
"mandatory",
",",
"message",
")"
] | Publish a message on the exchange, to be asynchronously delivered to queues.
:param asynqp.Message message: the message to send
:param str routing_key: the routing key with which to publish the message
:param bool mandatory: if True (the default) undeliverable messages result in an error (see also :meth:`Channel.set_return_handler`) | [
"Publish",
"a",
"message",
"on",
"the",
"exchange",
"to",
"be",
"asynchronously",
"delivered",
"to",
"queues",
"."
] | ea8630d1803d10d4fd64b1a0e50f3097710b34d1 | https://github.com/benjamin-hodgson/asynqp/blob/ea8630d1803d10d4fd64b1a0e50f3097710b34d1/src/asynqp/exchange.py#L35-L43 | train |
benjamin-hodgson/asynqp | src/asynqp/exchange.py | Exchange.delete | def delete(self, *, if_unused=True):
"""
Delete the exchange.
This method is a :ref:`coroutine <coroutine>`.
:keyword bool if_unused: If true, the exchange will only be deleted if
it has no queues bound to it.
"""
self.sender.send_ExchangeDelete(self.name, if_unused)
yield from self.synchroniser.wait(spec.ExchangeDeleteOK)
self.reader.ready() | python | def delete(self, *, if_unused=True):
"""
Delete the exchange.
This method is a :ref:`coroutine <coroutine>`.
:keyword bool if_unused: If true, the exchange will only be deleted if
it has no queues bound to it.
"""
self.sender.send_ExchangeDelete(self.name, if_unused)
yield from self.synchroniser.wait(spec.ExchangeDeleteOK)
self.reader.ready() | [
"def",
"delete",
"(",
"self",
",",
"*",
",",
"if_unused",
"=",
"True",
")",
":",
"self",
".",
"sender",
".",
"send_ExchangeDelete",
"(",
"self",
".",
"name",
",",
"if_unused",
")",
"yield",
"from",
"self",
".",
"synchroniser",
".",
"wait",
"(",
"spec",... | Delete the exchange.
This method is a :ref:`coroutine <coroutine>`.
:keyword bool if_unused: If true, the exchange will only be deleted if
it has no queues bound to it. | [
"Delete",
"the",
"exchange",
"."
] | ea8630d1803d10d4fd64b1a0e50f3097710b34d1 | https://github.com/benjamin-hodgson/asynqp/blob/ea8630d1803d10d4fd64b1a0e50f3097710b34d1/src/asynqp/exchange.py#L46-L57 | train |
benjamin-hodgson/asynqp | src/asynqp/message.py | IncomingMessage.reject | def reject(self, *, requeue=True):
"""
Reject the message.
:keyword bool requeue: if true, the broker will attempt to requeue the
message and deliver it to an alternate consumer.
"""
self.sender.send_BasicReject(self.delivery_tag, requeue) | python | def reject(self, *, requeue=True):
"""
Reject the message.
:keyword bool requeue: if true, the broker will attempt to requeue the
message and deliver it to an alternate consumer.
"""
self.sender.send_BasicReject(self.delivery_tag, requeue) | [
"def",
"reject",
"(",
"self",
",",
"*",
",",
"requeue",
"=",
"True",
")",
":",
"self",
".",
"sender",
".",
"send_BasicReject",
"(",
"self",
".",
"delivery_tag",
",",
"requeue",
")"
] | Reject the message.
:keyword bool requeue: if true, the broker will attempt to requeue the
message and deliver it to an alternate consumer. | [
"Reject",
"the",
"message",
"."
] | ea8630d1803d10d4fd64b1a0e50f3097710b34d1 | https://github.com/benjamin-hodgson/asynqp/blob/ea8630d1803d10d4fd64b1a0e50f3097710b34d1/src/asynqp/message.py#L144-L151 | train |
benjamin-hodgson/asynqp | src/asynqp/channel.py | Channel.declare_exchange | def declare_exchange(self, name, type, *, durable=True, auto_delete=False,
passive=False, internal=False, nowait=False,
arguments=None):
"""
Declare an :class:`Exchange` on the broker. If the exchange does not exist, it will be created.
This method is a :ref:`coroutine <coroutine>`.
:param str name: the name of the exchange.
:param str type: the type of the exchange
(usually one of ``'fanout'``, ``'direct'``, ``'topic'``, or ``'headers'``)
:keyword bool durable: If true, the exchange will be re-created when
the server restarts.
:keyword bool auto_delete: If true, the exchange will be
deleted when the last queue is un-bound from it.
:keyword bool passive: If `true` and exchange with such a name does
not exist it will raise a :class:`exceptions.NotFound`. If `false`
server will create it. Arguments ``durable``, ``auto_delete`` and
``internal`` are ignored if `passive=True`.
:keyword bool internal: If true, the exchange cannot be published to
directly; it can only be bound to other exchanges.
:keyword bool nowait: If true, the method will not wait for declare-ok
to arrive and return right away.
:keyword dict arguments: Table of optional parameters for extensions to
the AMQP protocol. See :ref:`extensions`.
:return: the new :class:`Exchange` object.
"""
if name == '':
return exchange.Exchange(self.reader, self.synchroniser, self.sender, name, 'direct', True, False, False)
if not VALID_EXCHANGE_NAME_RE.match(name):
raise ValueError(
"Invalid exchange name.\n"
"Valid names consist of letters, digits, hyphen, underscore, "
"period, or colon, and do not begin with 'amq.'")
self.sender.send_ExchangeDeclare(
name, type, passive, durable, auto_delete, internal, nowait,
arguments or {})
if not nowait:
yield from self.synchroniser.wait(spec.ExchangeDeclareOK)
self.reader.ready()
ex = exchange.Exchange(
self.reader, self.synchroniser, self.sender, name, type, durable,
auto_delete, internal)
return ex | python | def declare_exchange(self, name, type, *, durable=True, auto_delete=False,
passive=False, internal=False, nowait=False,
arguments=None):
"""
Declare an :class:`Exchange` on the broker. If the exchange does not exist, it will be created.
This method is a :ref:`coroutine <coroutine>`.
:param str name: the name of the exchange.
:param str type: the type of the exchange
(usually one of ``'fanout'``, ``'direct'``, ``'topic'``, or ``'headers'``)
:keyword bool durable: If true, the exchange will be re-created when
the server restarts.
:keyword bool auto_delete: If true, the exchange will be
deleted when the last queue is un-bound from it.
:keyword bool passive: If `true` and exchange with such a name does
not exist it will raise a :class:`exceptions.NotFound`. If `false`
server will create it. Arguments ``durable``, ``auto_delete`` and
``internal`` are ignored if `passive=True`.
:keyword bool internal: If true, the exchange cannot be published to
directly; it can only be bound to other exchanges.
:keyword bool nowait: If true, the method will not wait for declare-ok
to arrive and return right away.
:keyword dict arguments: Table of optional parameters for extensions to
the AMQP protocol. See :ref:`extensions`.
:return: the new :class:`Exchange` object.
"""
if name == '':
return exchange.Exchange(self.reader, self.synchroniser, self.sender, name, 'direct', True, False, False)
if not VALID_EXCHANGE_NAME_RE.match(name):
raise ValueError(
"Invalid exchange name.\n"
"Valid names consist of letters, digits, hyphen, underscore, "
"period, or colon, and do not begin with 'amq.'")
self.sender.send_ExchangeDeclare(
name, type, passive, durable, auto_delete, internal, nowait,
arguments or {})
if not nowait:
yield from self.synchroniser.wait(spec.ExchangeDeclareOK)
self.reader.ready()
ex = exchange.Exchange(
self.reader, self.synchroniser, self.sender, name, type, durable,
auto_delete, internal)
return ex | [
"def",
"declare_exchange",
"(",
"self",
",",
"name",
",",
"type",
",",
"*",
",",
"durable",
"=",
"True",
",",
"auto_delete",
"=",
"False",
",",
"passive",
"=",
"False",
",",
"internal",
"=",
"False",
",",
"nowait",
"=",
"False",
",",
"arguments",
"=",
... | Declare an :class:`Exchange` on the broker. If the exchange does not exist, it will be created.
This method is a :ref:`coroutine <coroutine>`.
:param str name: the name of the exchange.
:param str type: the type of the exchange
(usually one of ``'fanout'``, ``'direct'``, ``'topic'``, or ``'headers'``)
:keyword bool durable: If true, the exchange will be re-created when
the server restarts.
:keyword bool auto_delete: If true, the exchange will be
deleted when the last queue is un-bound from it.
:keyword bool passive: If `true` and exchange with such a name does
not exist it will raise a :class:`exceptions.NotFound`. If `false`
server will create it. Arguments ``durable``, ``auto_delete`` and
``internal`` are ignored if `passive=True`.
:keyword bool internal: If true, the exchange cannot be published to
directly; it can only be bound to other exchanges.
:keyword bool nowait: If true, the method will not wait for declare-ok
to arrive and return right away.
:keyword dict arguments: Table of optional parameters for extensions to
the AMQP protocol. See :ref:`extensions`.
:return: the new :class:`Exchange` object. | [
"Declare",
"an",
":",
"class",
":",
"Exchange",
"on",
"the",
"broker",
".",
"If",
"the",
"exchange",
"does",
"not",
"exist",
"it",
"will",
"be",
"created",
"."
] | ea8630d1803d10d4fd64b1a0e50f3097710b34d1 | https://github.com/benjamin-hodgson/asynqp/blob/ea8630d1803d10d4fd64b1a0e50f3097710b34d1/src/asynqp/channel.py#L47-L93 | train |
benjamin-hodgson/asynqp | src/asynqp/channel.py | Channel.declare_queue | def declare_queue(self, name='', *, durable=True, exclusive=False,
auto_delete=False, passive=False,
nowait=False, arguments=None):
"""
Declare a queue on the broker. If the queue does not exist, it will be created.
This method is a :ref:`coroutine <coroutine>`.
:param str name: the name of the queue.
Supplying a name of '' will create a queue with a unique name of the server's choosing.
:keyword bool durable: If true, the queue will be re-created when the server restarts.
:keyword bool exclusive: If true, the queue can only be accessed by the current connection,
and will be deleted when the connection is closed.
:keyword bool auto_delete: If true, the queue will be deleted when the last consumer is cancelled.
If there were never any conusmers, the queue won't be deleted.
:keyword bool passive: If true and queue with such a name does not
exist it will raise a :class:`exceptions.NotFound` instead of
creating it. Arguments ``durable``, ``auto_delete`` and
``exclusive`` are ignored if ``passive=True``.
:keyword bool nowait: If true, will not wait for a declare-ok to arrive.
:keyword dict arguments: Table of optional parameters for extensions to the AMQP protocol. See :ref:`extensions`.
:return: The new :class:`Queue` object.
"""
q = yield from self.queue_factory.declare(
name, durable, exclusive, auto_delete, passive, nowait,
arguments if arguments is not None else {})
return q | python | def declare_queue(self, name='', *, durable=True, exclusive=False,
auto_delete=False, passive=False,
nowait=False, arguments=None):
"""
Declare a queue on the broker. If the queue does not exist, it will be created.
This method is a :ref:`coroutine <coroutine>`.
:param str name: the name of the queue.
Supplying a name of '' will create a queue with a unique name of the server's choosing.
:keyword bool durable: If true, the queue will be re-created when the server restarts.
:keyword bool exclusive: If true, the queue can only be accessed by the current connection,
and will be deleted when the connection is closed.
:keyword bool auto_delete: If true, the queue will be deleted when the last consumer is cancelled.
If there were never any conusmers, the queue won't be deleted.
:keyword bool passive: If true and queue with such a name does not
exist it will raise a :class:`exceptions.NotFound` instead of
creating it. Arguments ``durable``, ``auto_delete`` and
``exclusive`` are ignored if ``passive=True``.
:keyword bool nowait: If true, will not wait for a declare-ok to arrive.
:keyword dict arguments: Table of optional parameters for extensions to the AMQP protocol. See :ref:`extensions`.
:return: The new :class:`Queue` object.
"""
q = yield from self.queue_factory.declare(
name, durable, exclusive, auto_delete, passive, nowait,
arguments if arguments is not None else {})
return q | [
"def",
"declare_queue",
"(",
"self",
",",
"name",
"=",
"''",
",",
"*",
",",
"durable",
"=",
"True",
",",
"exclusive",
"=",
"False",
",",
"auto_delete",
"=",
"False",
",",
"passive",
"=",
"False",
",",
"nowait",
"=",
"False",
",",
"arguments",
"=",
"N... | Declare a queue on the broker. If the queue does not exist, it will be created.
This method is a :ref:`coroutine <coroutine>`.
:param str name: the name of the queue.
Supplying a name of '' will create a queue with a unique name of the server's choosing.
:keyword bool durable: If true, the queue will be re-created when the server restarts.
:keyword bool exclusive: If true, the queue can only be accessed by the current connection,
and will be deleted when the connection is closed.
:keyword bool auto_delete: If true, the queue will be deleted when the last consumer is cancelled.
If there were never any conusmers, the queue won't be deleted.
:keyword bool passive: If true and queue with such a name does not
exist it will raise a :class:`exceptions.NotFound` instead of
creating it. Arguments ``durable``, ``auto_delete`` and
``exclusive`` are ignored if ``passive=True``.
:keyword bool nowait: If true, will not wait for a declare-ok to arrive.
:keyword dict arguments: Table of optional parameters for extensions to the AMQP protocol. See :ref:`extensions`.
:return: The new :class:`Queue` object. | [
"Declare",
"a",
"queue",
"on",
"the",
"broker",
".",
"If",
"the",
"queue",
"does",
"not",
"exist",
"it",
"will",
"be",
"created",
"."
] | ea8630d1803d10d4fd64b1a0e50f3097710b34d1 | https://github.com/benjamin-hodgson/asynqp/blob/ea8630d1803d10d4fd64b1a0e50f3097710b34d1/src/asynqp/channel.py#L96-L123 | train |
benjamin-hodgson/asynqp | src/asynqp/channel.py | Channel.set_qos | def set_qos(self, prefetch_size=0, prefetch_count=0, apply_globally=False):
"""
Specify quality of service by requesting that messages be pre-fetched
from the server. Pre-fetching means that the server will deliver messages
to the client while the client is still processing unacknowledged messages.
This method is a :ref:`coroutine <coroutine>`.
:param int prefetch_size: Specifies a prefetch window in bytes.
Messages smaller than this will be sent from the server in advance.
This value may be set to 0, which means "no specific limit".
:param int prefetch_count: Specifies a prefetch window in terms of whole messages.
:param bool apply_globally: If true, apply these QoS settings on a global level.
The meaning of this is implementation-dependent. From the
`RabbitMQ documentation <https://www.rabbitmq.com/amqp-0-9-1-reference.html#basic.qos.global>`_:
RabbitMQ has reinterpreted this field. The original specification said:
"By default the QoS settings apply to the current channel only.
If this field is set, they are applied to the entire connection."
Instead, RabbitMQ takes global=false to mean that the QoS settings should apply
per-consumer (for new consumers on the channel; existing ones being unaffected) and
global=true to mean that the QoS settings should apply per-channel.
"""
self.sender.send_BasicQos(prefetch_size, prefetch_count, apply_globally)
yield from self.synchroniser.wait(spec.BasicQosOK)
self.reader.ready() | python | def set_qos(self, prefetch_size=0, prefetch_count=0, apply_globally=False):
"""
Specify quality of service by requesting that messages be pre-fetched
from the server. Pre-fetching means that the server will deliver messages
to the client while the client is still processing unacknowledged messages.
This method is a :ref:`coroutine <coroutine>`.
:param int prefetch_size: Specifies a prefetch window in bytes.
Messages smaller than this will be sent from the server in advance.
This value may be set to 0, which means "no specific limit".
:param int prefetch_count: Specifies a prefetch window in terms of whole messages.
:param bool apply_globally: If true, apply these QoS settings on a global level.
The meaning of this is implementation-dependent. From the
`RabbitMQ documentation <https://www.rabbitmq.com/amqp-0-9-1-reference.html#basic.qos.global>`_:
RabbitMQ has reinterpreted this field. The original specification said:
"By default the QoS settings apply to the current channel only.
If this field is set, they are applied to the entire connection."
Instead, RabbitMQ takes global=false to mean that the QoS settings should apply
per-consumer (for new consumers on the channel; existing ones being unaffected) and
global=true to mean that the QoS settings should apply per-channel.
"""
self.sender.send_BasicQos(prefetch_size, prefetch_count, apply_globally)
yield from self.synchroniser.wait(spec.BasicQosOK)
self.reader.ready() | [
"def",
"set_qos",
"(",
"self",
",",
"prefetch_size",
"=",
"0",
",",
"prefetch_count",
"=",
"0",
",",
"apply_globally",
"=",
"False",
")",
":",
"self",
".",
"sender",
".",
"send_BasicQos",
"(",
"prefetch_size",
",",
"prefetch_count",
",",
"apply_globally",
")... | Specify quality of service by requesting that messages be pre-fetched
from the server. Pre-fetching means that the server will deliver messages
to the client while the client is still processing unacknowledged messages.
This method is a :ref:`coroutine <coroutine>`.
:param int prefetch_size: Specifies a prefetch window in bytes.
Messages smaller than this will be sent from the server in advance.
This value may be set to 0, which means "no specific limit".
:param int prefetch_count: Specifies a prefetch window in terms of whole messages.
:param bool apply_globally: If true, apply these QoS settings on a global level.
The meaning of this is implementation-dependent. From the
`RabbitMQ documentation <https://www.rabbitmq.com/amqp-0-9-1-reference.html#basic.qos.global>`_:
RabbitMQ has reinterpreted this field. The original specification said:
"By default the QoS settings apply to the current channel only.
If this field is set, they are applied to the entire connection."
Instead, RabbitMQ takes global=false to mean that the QoS settings should apply
per-consumer (for new consumers on the channel; existing ones being unaffected) and
global=true to mean that the QoS settings should apply per-channel. | [
"Specify",
"quality",
"of",
"service",
"by",
"requesting",
"that",
"messages",
"be",
"pre",
"-",
"fetched",
"from",
"the",
"server",
".",
"Pre",
"-",
"fetching",
"means",
"that",
"the",
"server",
"will",
"deliver",
"messages",
"to",
"the",
"client",
"while",... | ea8630d1803d10d4fd64b1a0e50f3097710b34d1 | https://github.com/benjamin-hodgson/asynqp/blob/ea8630d1803d10d4fd64b1a0e50f3097710b34d1/src/asynqp/channel.py#L126-L153 | train |
benjamin-hodgson/asynqp | src/asynqp/channel.py | Channel.close | def close(self):
"""
Close the channel by handshaking with the server.
This method is a :ref:`coroutine <coroutine>`.
"""
# If we aren't already closed ask for server to close
if not self.is_closed():
self._closing = True
# Let the ChannelActor do the actual close operations.
# It will do the work on CloseOK
self.sender.send_Close(
0, 'Channel closed by application', 0, 0)
try:
yield from self.synchroniser.wait(spec.ChannelCloseOK)
except AMQPError:
# For example if both sides want to close or the connection
# is closed.
pass
else:
if self._closing:
log.warn("Called `close` on already closing channel...") | python | def close(self):
"""
Close the channel by handshaking with the server.
This method is a :ref:`coroutine <coroutine>`.
"""
# If we aren't already closed ask for server to close
if not self.is_closed():
self._closing = True
# Let the ChannelActor do the actual close operations.
# It will do the work on CloseOK
self.sender.send_Close(
0, 'Channel closed by application', 0, 0)
try:
yield from self.synchroniser.wait(spec.ChannelCloseOK)
except AMQPError:
# For example if both sides want to close or the connection
# is closed.
pass
else:
if self._closing:
log.warn("Called `close` on already closing channel...") | [
"def",
"close",
"(",
"self",
")",
":",
"# If we aren't already closed ask for server to close",
"if",
"not",
"self",
".",
"is_closed",
"(",
")",
":",
"self",
".",
"_closing",
"=",
"True",
"# Let the ChannelActor do the actual close operations.",
"# It will do the work on Cl... | Close the channel by handshaking with the server.
This method is a :ref:`coroutine <coroutine>`. | [
"Close",
"the",
"channel",
"by",
"handshaking",
"with",
"the",
"server",
"."
] | ea8630d1803d10d4fd64b1a0e50f3097710b34d1 | https://github.com/benjamin-hodgson/asynqp/blob/ea8630d1803d10d4fd64b1a0e50f3097710b34d1/src/asynqp/channel.py#L173-L194 | train |
benjamin-hodgson/asynqp | src/asynqp/channel.py | ChannelActor.handle_ChannelClose | def handle_ChannelClose(self, frame):
""" AMQP server closed the channel with an error """
# By docs:
# The response to receiving a Close after sending Close must be to
# send Close-Ok.
#
# No need for additional checks
self.sender.send_CloseOK()
exc = exceptions._get_exception_type(frame.payload.reply_code)
self._close_all(exc) | python | def handle_ChannelClose(self, frame):
""" AMQP server closed the channel with an error """
# By docs:
# The response to receiving a Close after sending Close must be to
# send Close-Ok.
#
# No need for additional checks
self.sender.send_CloseOK()
exc = exceptions._get_exception_type(frame.payload.reply_code)
self._close_all(exc) | [
"def",
"handle_ChannelClose",
"(",
"self",
",",
"frame",
")",
":",
"# By docs:",
"# The response to receiving a Close after sending Close must be to",
"# send Close-Ok.",
"#",
"# No need for additional checks",
"self",
".",
"sender",
".",
"send_CloseOK",
"(",
")",
"exc",
"=... | AMQP server closed the channel with an error | [
"AMQP",
"server",
"closed",
"the",
"channel",
"with",
"an",
"error"
] | ea8630d1803d10d4fd64b1a0e50f3097710b34d1 | https://github.com/benjamin-hodgson/asynqp/blob/ea8630d1803d10d4fd64b1a0e50f3097710b34d1/src/asynqp/channel.py#L345-L355 | train |
benjamin-hodgson/asynqp | src/asynqp/channel.py | ChannelActor.handle_ChannelCloseOK | def handle_ChannelCloseOK(self, frame):
""" AMQP server closed channel as per our request """
assert self.channel._closing, "received a not expected CloseOk"
# Release the `close` method's future
self.synchroniser.notify(spec.ChannelCloseOK)
exc = ChannelClosed()
self._close_all(exc) | python | def handle_ChannelCloseOK(self, frame):
""" AMQP server closed channel as per our request """
assert self.channel._closing, "received a not expected CloseOk"
# Release the `close` method's future
self.synchroniser.notify(spec.ChannelCloseOK)
exc = ChannelClosed()
self._close_all(exc) | [
"def",
"handle_ChannelCloseOK",
"(",
"self",
",",
"frame",
")",
":",
"assert",
"self",
".",
"channel",
".",
"_closing",
",",
"\"received a not expected CloseOk\"",
"# Release the `close` method's future",
"self",
".",
"synchroniser",
".",
"notify",
"(",
"spec",
".",
... | AMQP server closed channel as per our request | [
"AMQP",
"server",
"closed",
"channel",
"as",
"per",
"our",
"request"
] | ea8630d1803d10d4fd64b1a0e50f3097710b34d1 | https://github.com/benjamin-hodgson/asynqp/blob/ea8630d1803d10d4fd64b1a0e50f3097710b34d1/src/asynqp/channel.py#L357-L364 | train |
benjamin-hodgson/asynqp | src/asynqp/queue.py | Queue.bind | def bind(self, exchange, routing_key, *, arguments=None):
"""
Bind a queue to an exchange, with the supplied routing key.
This action 'subscribes' the queue to the routing key; the precise meaning of this
varies with the exchange type.
This method is a :ref:`coroutine <coroutine>`.
:param asynqp.Exchange exchange: the :class:`Exchange` to bind to
:param str routing_key: the routing key under which to bind
:keyword dict arguments: Table of optional parameters for extensions to the AMQP protocol. See :ref:`extensions`.
:return: The new :class:`QueueBinding` object
"""
if self.deleted:
raise Deleted("Queue {} was deleted".format(self.name))
if not exchange:
raise InvalidExchangeName("Can't bind queue {} to the default exchange".format(self.name))
self.sender.send_QueueBind(self.name, exchange.name, routing_key, arguments or {})
yield from self.synchroniser.wait(spec.QueueBindOK)
b = QueueBinding(self.reader, self.sender, self.synchroniser, self, exchange, routing_key)
self.reader.ready()
return b | python | def bind(self, exchange, routing_key, *, arguments=None):
"""
Bind a queue to an exchange, with the supplied routing key.
This action 'subscribes' the queue to the routing key; the precise meaning of this
varies with the exchange type.
This method is a :ref:`coroutine <coroutine>`.
:param asynqp.Exchange exchange: the :class:`Exchange` to bind to
:param str routing_key: the routing key under which to bind
:keyword dict arguments: Table of optional parameters for extensions to the AMQP protocol. See :ref:`extensions`.
:return: The new :class:`QueueBinding` object
"""
if self.deleted:
raise Deleted("Queue {} was deleted".format(self.name))
if not exchange:
raise InvalidExchangeName("Can't bind queue {} to the default exchange".format(self.name))
self.sender.send_QueueBind(self.name, exchange.name, routing_key, arguments or {})
yield from self.synchroniser.wait(spec.QueueBindOK)
b = QueueBinding(self.reader, self.sender, self.synchroniser, self, exchange, routing_key)
self.reader.ready()
return b | [
"def",
"bind",
"(",
"self",
",",
"exchange",
",",
"routing_key",
",",
"*",
",",
"arguments",
"=",
"None",
")",
":",
"if",
"self",
".",
"deleted",
":",
"raise",
"Deleted",
"(",
"\"Queue {} was deleted\"",
".",
"format",
"(",
"self",
".",
"name",
")",
")... | Bind a queue to an exchange, with the supplied routing key.
This action 'subscribes' the queue to the routing key; the precise meaning of this
varies with the exchange type.
This method is a :ref:`coroutine <coroutine>`.
:param asynqp.Exchange exchange: the :class:`Exchange` to bind to
:param str routing_key: the routing key under which to bind
:keyword dict arguments: Table of optional parameters for extensions to the AMQP protocol. See :ref:`extensions`.
:return: The new :class:`QueueBinding` object | [
"Bind",
"a",
"queue",
"to",
"an",
"exchange",
"with",
"the",
"supplied",
"routing",
"key",
"."
] | ea8630d1803d10d4fd64b1a0e50f3097710b34d1 | https://github.com/benjamin-hodgson/asynqp/blob/ea8630d1803d10d4fd64b1a0e50f3097710b34d1/src/asynqp/queue.py#L54-L78 | train |
benjamin-hodgson/asynqp | src/asynqp/queue.py | Queue.consume | def consume(self, callback, *, no_local=False, no_ack=False, exclusive=False, arguments=None):
"""
Start a consumer on the queue. Messages will be delivered asynchronously to the consumer.
The callback function will be called whenever a new message arrives on the queue.
Advanced usage: the callback object must be callable
(it must be a function or define a ``__call__`` method),
but may also define some further methods:
* ``callback.on_cancel()``: called with no parameters when the consumer is successfully cancelled.
* ``callback.on_error(exc)``: called when the channel is closed due to an error.
The argument passed is the exception which caused the error.
This method is a :ref:`coroutine <coroutine>`.
:param callable callback: a callback to be called when a message is delivered.
The callback must accept a single argument (an instance of :class:`~asynqp.message.IncomingMessage`).
:keyword bool no_local: If true, the server will not deliver messages that were
published by this connection.
:keyword bool no_ack: If true, messages delivered to the consumer don't require acknowledgement.
:keyword bool exclusive: If true, only this consumer can access the queue.
:keyword dict arguments: Table of optional parameters for extensions to the AMQP protocol. See :ref:`extensions`.
:return: The newly created :class:`Consumer` object.
"""
if self.deleted:
raise Deleted("Queue {} was deleted".format(self.name))
self.sender.send_BasicConsume(self.name, no_local, no_ack, exclusive, arguments or {})
tag = yield from self.synchroniser.wait(spec.BasicConsumeOK)
consumer = Consumer(
tag, callback, self.sender, self.synchroniser, self.reader,
loop=self._loop)
self.consumers.add_consumer(consumer)
self.reader.ready()
return consumer | python | def consume(self, callback, *, no_local=False, no_ack=False, exclusive=False, arguments=None):
"""
Start a consumer on the queue. Messages will be delivered asynchronously to the consumer.
The callback function will be called whenever a new message arrives on the queue.
Advanced usage: the callback object must be callable
(it must be a function or define a ``__call__`` method),
but may also define some further methods:
* ``callback.on_cancel()``: called with no parameters when the consumer is successfully cancelled.
* ``callback.on_error(exc)``: called when the channel is closed due to an error.
The argument passed is the exception which caused the error.
This method is a :ref:`coroutine <coroutine>`.
:param callable callback: a callback to be called when a message is delivered.
The callback must accept a single argument (an instance of :class:`~asynqp.message.IncomingMessage`).
:keyword bool no_local: If true, the server will not deliver messages that were
published by this connection.
:keyword bool no_ack: If true, messages delivered to the consumer don't require acknowledgement.
:keyword bool exclusive: If true, only this consumer can access the queue.
:keyword dict arguments: Table of optional parameters for extensions to the AMQP protocol. See :ref:`extensions`.
:return: The newly created :class:`Consumer` object.
"""
if self.deleted:
raise Deleted("Queue {} was deleted".format(self.name))
self.sender.send_BasicConsume(self.name, no_local, no_ack, exclusive, arguments or {})
tag = yield from self.synchroniser.wait(spec.BasicConsumeOK)
consumer = Consumer(
tag, callback, self.sender, self.synchroniser, self.reader,
loop=self._loop)
self.consumers.add_consumer(consumer)
self.reader.ready()
return consumer | [
"def",
"consume",
"(",
"self",
",",
"callback",
",",
"*",
",",
"no_local",
"=",
"False",
",",
"no_ack",
"=",
"False",
",",
"exclusive",
"=",
"False",
",",
"arguments",
"=",
"None",
")",
":",
"if",
"self",
".",
"deleted",
":",
"raise",
"Deleted",
"(",... | Start a consumer on the queue. Messages will be delivered asynchronously to the consumer.
The callback function will be called whenever a new message arrives on the queue.
Advanced usage: the callback object must be callable
(it must be a function or define a ``__call__`` method),
but may also define some further methods:
* ``callback.on_cancel()``: called with no parameters when the consumer is successfully cancelled.
* ``callback.on_error(exc)``: called when the channel is closed due to an error.
The argument passed is the exception which caused the error.
This method is a :ref:`coroutine <coroutine>`.
:param callable callback: a callback to be called when a message is delivered.
The callback must accept a single argument (an instance of :class:`~asynqp.message.IncomingMessage`).
:keyword bool no_local: If true, the server will not deliver messages that were
published by this connection.
:keyword bool no_ack: If true, messages delivered to the consumer don't require acknowledgement.
:keyword bool exclusive: If true, only this consumer can access the queue.
:keyword dict arguments: Table of optional parameters for extensions to the AMQP protocol. See :ref:`extensions`.
:return: The newly created :class:`Consumer` object. | [
"Start",
"a",
"consumer",
"on",
"the",
"queue",
".",
"Messages",
"will",
"be",
"delivered",
"asynchronously",
"to",
"the",
"consumer",
".",
"The",
"callback",
"function",
"will",
"be",
"called",
"whenever",
"a",
"new",
"message",
"arrives",
"on",
"the",
"que... | ea8630d1803d10d4fd64b1a0e50f3097710b34d1 | https://github.com/benjamin-hodgson/asynqp/blob/ea8630d1803d10d4fd64b1a0e50f3097710b34d1/src/asynqp/queue.py#L81-L116 | train |
benjamin-hodgson/asynqp | src/asynqp/queue.py | Queue.get | def get(self, *, no_ack=False):
"""
Synchronously get a message from the queue.
This method is a :ref:`coroutine <coroutine>`.
:keyword bool no_ack: if true, the broker does not require acknowledgement of receipt of the message.
:return: an :class:`~asynqp.message.IncomingMessage`,
or ``None`` if there were no messages on the queue.
"""
if self.deleted:
raise Deleted("Queue {} was deleted".format(self.name))
self.sender.send_BasicGet(self.name, no_ack)
tag_msg = yield from self.synchroniser.wait(spec.BasicGetOK, spec.BasicGetEmpty)
if tag_msg is not None:
consumer_tag, msg = tag_msg
assert consumer_tag is None
else:
msg = None
self.reader.ready()
return msg | python | def get(self, *, no_ack=False):
"""
Synchronously get a message from the queue.
This method is a :ref:`coroutine <coroutine>`.
:keyword bool no_ack: if true, the broker does not require acknowledgement of receipt of the message.
:return: an :class:`~asynqp.message.IncomingMessage`,
or ``None`` if there were no messages on the queue.
"""
if self.deleted:
raise Deleted("Queue {} was deleted".format(self.name))
self.sender.send_BasicGet(self.name, no_ack)
tag_msg = yield from self.synchroniser.wait(spec.BasicGetOK, spec.BasicGetEmpty)
if tag_msg is not None:
consumer_tag, msg = tag_msg
assert consumer_tag is None
else:
msg = None
self.reader.ready()
return msg | [
"def",
"get",
"(",
"self",
",",
"*",
",",
"no_ack",
"=",
"False",
")",
":",
"if",
"self",
".",
"deleted",
":",
"raise",
"Deleted",
"(",
"\"Queue {} was deleted\"",
".",
"format",
"(",
"self",
".",
"name",
")",
")",
"self",
".",
"sender",
".",
"send_B... | Synchronously get a message from the queue.
This method is a :ref:`coroutine <coroutine>`.
:keyword bool no_ack: if true, the broker does not require acknowledgement of receipt of the message.
:return: an :class:`~asynqp.message.IncomingMessage`,
or ``None`` if there were no messages on the queue. | [
"Synchronously",
"get",
"a",
"message",
"from",
"the",
"queue",
"."
] | ea8630d1803d10d4fd64b1a0e50f3097710b34d1 | https://github.com/benjamin-hodgson/asynqp/blob/ea8630d1803d10d4fd64b1a0e50f3097710b34d1/src/asynqp/queue.py#L119-L142 | train |
benjamin-hodgson/asynqp | src/asynqp/queue.py | Queue.purge | def purge(self):
"""
Purge all undelivered messages from the queue.
This method is a :ref:`coroutine <coroutine>`.
"""
self.sender.send_QueuePurge(self.name)
yield from self.synchroniser.wait(spec.QueuePurgeOK)
self.reader.ready() | python | def purge(self):
"""
Purge all undelivered messages from the queue.
This method is a :ref:`coroutine <coroutine>`.
"""
self.sender.send_QueuePurge(self.name)
yield from self.synchroniser.wait(spec.QueuePurgeOK)
self.reader.ready() | [
"def",
"purge",
"(",
"self",
")",
":",
"self",
".",
"sender",
".",
"send_QueuePurge",
"(",
"self",
".",
"name",
")",
"yield",
"from",
"self",
".",
"synchroniser",
".",
"wait",
"(",
"spec",
".",
"QueuePurgeOK",
")",
"self",
".",
"reader",
".",
"ready",
... | Purge all undelivered messages from the queue.
This method is a :ref:`coroutine <coroutine>`. | [
"Purge",
"all",
"undelivered",
"messages",
"from",
"the",
"queue",
"."
] | ea8630d1803d10d4fd64b1a0e50f3097710b34d1 | https://github.com/benjamin-hodgson/asynqp/blob/ea8630d1803d10d4fd64b1a0e50f3097710b34d1/src/asynqp/queue.py#L145-L153 | train |
benjamin-hodgson/asynqp | src/asynqp/queue.py | Queue.delete | def delete(self, *, if_unused=True, if_empty=True):
"""
Delete the queue.
This method is a :ref:`coroutine <coroutine>`.
:keyword bool if_unused: If true, the queue will only be deleted
if it has no consumers.
:keyword bool if_empty: If true, the queue will only be deleted if
it has no unacknowledged messages.
"""
if self.deleted:
raise Deleted("Queue {} was already deleted".format(self.name))
self.sender.send_QueueDelete(self.name, if_unused, if_empty)
yield from self.synchroniser.wait(spec.QueueDeleteOK)
self.deleted = True
self.reader.ready() | python | def delete(self, *, if_unused=True, if_empty=True):
"""
Delete the queue.
This method is a :ref:`coroutine <coroutine>`.
:keyword bool if_unused: If true, the queue will only be deleted
if it has no consumers.
:keyword bool if_empty: If true, the queue will only be deleted if
it has no unacknowledged messages.
"""
if self.deleted:
raise Deleted("Queue {} was already deleted".format(self.name))
self.sender.send_QueueDelete(self.name, if_unused, if_empty)
yield from self.synchroniser.wait(spec.QueueDeleteOK)
self.deleted = True
self.reader.ready() | [
"def",
"delete",
"(",
"self",
",",
"*",
",",
"if_unused",
"=",
"True",
",",
"if_empty",
"=",
"True",
")",
":",
"if",
"self",
".",
"deleted",
":",
"raise",
"Deleted",
"(",
"\"Queue {} was already deleted\"",
".",
"format",
"(",
"self",
".",
"name",
")",
... | Delete the queue.
This method is a :ref:`coroutine <coroutine>`.
:keyword bool if_unused: If true, the queue will only be deleted
if it has no consumers.
:keyword bool if_empty: If true, the queue will only be deleted if
it has no unacknowledged messages. | [
"Delete",
"the",
"queue",
"."
] | ea8630d1803d10d4fd64b1a0e50f3097710b34d1 | https://github.com/benjamin-hodgson/asynqp/blob/ea8630d1803d10d4fd64b1a0e50f3097710b34d1/src/asynqp/queue.py#L156-L173 | train |
benjamin-hodgson/asynqp | src/asynqp/queue.py | QueueBinding.unbind | def unbind(self, arguments=None):
"""
Unbind the queue from the exchange.
This method is a :ref:`coroutine <coroutine>`.
"""
if self.deleted:
raise Deleted("Queue {} was already unbound from exchange {}".format(self.queue.name, self.exchange.name))
self.sender.send_QueueUnbind(self.queue.name, self.exchange.name, self.routing_key, arguments or {})
yield from self.synchroniser.wait(spec.QueueUnbindOK)
self.deleted = True
self.reader.ready() | python | def unbind(self, arguments=None):
"""
Unbind the queue from the exchange.
This method is a :ref:`coroutine <coroutine>`.
"""
if self.deleted:
raise Deleted("Queue {} was already unbound from exchange {}".format(self.queue.name, self.exchange.name))
self.sender.send_QueueUnbind(self.queue.name, self.exchange.name, self.routing_key, arguments or {})
yield from self.synchroniser.wait(spec.QueueUnbindOK)
self.deleted = True
self.reader.ready() | [
"def",
"unbind",
"(",
"self",
",",
"arguments",
"=",
"None",
")",
":",
"if",
"self",
".",
"deleted",
":",
"raise",
"Deleted",
"(",
"\"Queue {} was already unbound from exchange {}\"",
".",
"format",
"(",
"self",
".",
"queue",
".",
"name",
",",
"self",
".",
... | Unbind the queue from the exchange.
This method is a :ref:`coroutine <coroutine>`. | [
"Unbind",
"the",
"queue",
"from",
"the",
"exchange",
"."
] | ea8630d1803d10d4fd64b1a0e50f3097710b34d1 | https://github.com/benjamin-hodgson/asynqp/blob/ea8630d1803d10d4fd64b1a0e50f3097710b34d1/src/asynqp/queue.py#L209-L221 | train |
benjamin-hodgson/asynqp | src/asynqp/queue.py | Consumer.cancel | def cancel(self):
"""
Cancel the consumer and stop recieving messages.
This method is a :ref:`coroutine <coroutine>`.
"""
self.sender.send_BasicCancel(self.tag)
try:
yield from self.synchroniser.wait(spec.BasicCancelOK)
except AMQPError:
pass
else:
# No need to call ready if channel closed.
self.reader.ready()
self.cancelled = True
self.cancelled_future.set_result(self)
if hasattr(self.callback, 'on_cancel'):
self.callback.on_cancel() | python | def cancel(self):
"""
Cancel the consumer and stop recieving messages.
This method is a :ref:`coroutine <coroutine>`.
"""
self.sender.send_BasicCancel(self.tag)
try:
yield from self.synchroniser.wait(spec.BasicCancelOK)
except AMQPError:
pass
else:
# No need to call ready if channel closed.
self.reader.ready()
self.cancelled = True
self.cancelled_future.set_result(self)
if hasattr(self.callback, 'on_cancel'):
self.callback.on_cancel() | [
"def",
"cancel",
"(",
"self",
")",
":",
"self",
".",
"sender",
".",
"send_BasicCancel",
"(",
"self",
".",
"tag",
")",
"try",
":",
"yield",
"from",
"self",
".",
"synchroniser",
".",
"wait",
"(",
"spec",
".",
"BasicCancelOK",
")",
"except",
"AMQPError",
... | Cancel the consumer and stop recieving messages.
This method is a :ref:`coroutine <coroutine>`. | [
"Cancel",
"the",
"consumer",
"and",
"stop",
"recieving",
"messages",
"."
] | ea8630d1803d10d4fd64b1a0e50f3097710b34d1 | https://github.com/benjamin-hodgson/asynqp/blob/ea8630d1803d10d4fd64b1a0e50f3097710b34d1/src/asynqp/queue.py#L255-L272 | train |
benjamin-hodgson/asynqp | doc/examples/helloworld.py | hello_world | def hello_world():
"""
Sends a 'hello world' message and then reads it from the queue.
"""
# connect to the RabbitMQ broker
connection = yield from asynqp.connect('localhost', 5672, username='guest', password='guest')
# Open a communications channel
channel = yield from connection.open_channel()
# Create a queue and an exchange on the broker
exchange = yield from channel.declare_exchange('test.exchange', 'direct')
queue = yield from channel.declare_queue('test.queue')
# Bind the queue to the exchange, so the queue will get messages published to the exchange
yield from queue.bind(exchange, 'routing.key')
# If you pass in a dict it will be automatically converted to JSON
msg = asynqp.Message({'hello': 'world'})
exchange.publish(msg, 'routing.key')
# Synchronously get a message from the queue
received_message = yield from queue.get()
print(received_message.json()) # get JSON from incoming messages easily
# Acknowledge a delivered message
received_message.ack()
yield from channel.close()
yield from connection.close() | python | def hello_world():
"""
Sends a 'hello world' message and then reads it from the queue.
"""
# connect to the RabbitMQ broker
connection = yield from asynqp.connect('localhost', 5672, username='guest', password='guest')
# Open a communications channel
channel = yield from connection.open_channel()
# Create a queue and an exchange on the broker
exchange = yield from channel.declare_exchange('test.exchange', 'direct')
queue = yield from channel.declare_queue('test.queue')
# Bind the queue to the exchange, so the queue will get messages published to the exchange
yield from queue.bind(exchange, 'routing.key')
# If you pass in a dict it will be automatically converted to JSON
msg = asynqp.Message({'hello': 'world'})
exchange.publish(msg, 'routing.key')
# Synchronously get a message from the queue
received_message = yield from queue.get()
print(received_message.json()) # get JSON from incoming messages easily
# Acknowledge a delivered message
received_message.ack()
yield from channel.close()
yield from connection.close() | [
"def",
"hello_world",
"(",
")",
":",
"# connect to the RabbitMQ broker",
"connection",
"=",
"yield",
"from",
"asynqp",
".",
"connect",
"(",
"'localhost'",
",",
"5672",
",",
"username",
"=",
"'guest'",
",",
"password",
"=",
"'guest'",
")",
"# Open a communications ... | Sends a 'hello world' message and then reads it from the queue. | [
"Sends",
"a",
"hello",
"world",
"message",
"and",
"then",
"reads",
"it",
"from",
"the",
"queue",
"."
] | ea8630d1803d10d4fd64b1a0e50f3097710b34d1 | https://github.com/benjamin-hodgson/asynqp/blob/ea8630d1803d10d4fd64b1a0e50f3097710b34d1/doc/examples/helloworld.py#L6-L35 | train |
benjamin-hodgson/asynqp | src/asynqp/routing.py | Synchroniser.killall | def killall(self, exc):
""" Connection/Channel was closed. All subsequent and ongoing requests
should raise an error
"""
self.connection_exc = exc
# Set an exception for all others
for method, futs in self._futures.items():
for fut in futs:
if fut.done():
continue
fut.set_exception(exc)
self._futures.clear() | python | def killall(self, exc):
""" Connection/Channel was closed. All subsequent and ongoing requests
should raise an error
"""
self.connection_exc = exc
# Set an exception for all others
for method, futs in self._futures.items():
for fut in futs:
if fut.done():
continue
fut.set_exception(exc)
self._futures.clear() | [
"def",
"killall",
"(",
"self",
",",
"exc",
")",
":",
"self",
".",
"connection_exc",
"=",
"exc",
"# Set an exception for all others",
"for",
"method",
",",
"futs",
"in",
"self",
".",
"_futures",
".",
"items",
"(",
")",
":",
"for",
"fut",
"in",
"futs",
":"... | Connection/Channel was closed. All subsequent and ongoing requests
should raise an error | [
"Connection",
"/",
"Channel",
"was",
"closed",
".",
"All",
"subsequent",
"and",
"ongoing",
"requests",
"should",
"raise",
"an",
"error"
] | ea8630d1803d10d4fd64b1a0e50f3097710b34d1 | https://github.com/benjamin-hodgson/asynqp/blob/ea8630d1803d10d4fd64b1a0e50f3097710b34d1/src/asynqp/routing.py#L85-L96 | train |
benjamin-hodgson/asynqp | src/asynqp/__init__.py | connect | def connect(host='localhost',
port=5672,
username='guest', password='guest',
virtual_host='/',
on_connection_close=None, *,
loop=None, sock=None, **kwargs):
"""
Connect to an AMQP server on the given host and port.
Log in to the given virtual host using the supplied credentials.
This function is a :ref:`coroutine <coroutine>`.
:param str host: the host server to connect to.
:param int port: the port which the AMQP server is listening on.
:param str username: the username to authenticate with.
:param str password: the password to authenticate with.
:param str virtual_host: the AMQP virtual host to connect to.
:param func on_connection_close: function called after connection lost.
:keyword BaseEventLoop loop: An instance of :class:`~asyncio.BaseEventLoop` to use.
(Defaults to :func:`asyncio.get_event_loop()`)
:keyword socket sock: A :func:`~socket.socket` instance to use for the connection.
This is passed on to :meth:`loop.create_connection() <asyncio.BaseEventLoop.create_connection>`.
If ``sock`` is supplied then ``host`` and ``port`` will be ignored.
Further keyword arguments are passed on to :meth:`loop.create_connection() <asyncio.BaseEventLoop.create_connection>`.
This function will set TCP_NODELAY on TCP and TCP6 sockets either on supplied ``sock`` or created one.
:return: the :class:`Connection` object.
"""
from .protocol import AMQP
from .routing import Dispatcher
from .connection import open_connection
loop = asyncio.get_event_loop() if loop is None else loop
if sock is None:
kwargs['host'] = host
kwargs['port'] = port
else:
kwargs['sock'] = sock
dispatcher = Dispatcher()
def protocol_factory():
return AMQP(dispatcher, loop, close_callback=on_connection_close)
transport, protocol = yield from loop.create_connection(protocol_factory, **kwargs)
# RPC-like applications require TCP_NODELAY in order to acheive
# minimal response time. Actually, this library send data in one
# big chunk and so this will not affect TCP-performance.
sk = transport.get_extra_info('socket')
# 1. Unfortunatelly we cannot check socket type (sk.type == socket.SOCK_STREAM). https://bugs.python.org/issue21327
# 2. Proto remains zero, if not specified at creation of socket
if (sk.family in (socket.AF_INET, socket.AF_INET6)) and (sk.proto in (0, socket.IPPROTO_TCP)):
sk.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
connection_info = {
'username': username,
'password': password,
'virtual_host': virtual_host
}
connection = yield from open_connection(
loop, transport, protocol, dispatcher, connection_info)
return connection | python | def connect(host='localhost',
port=5672,
username='guest', password='guest',
virtual_host='/',
on_connection_close=None, *,
loop=None, sock=None, **kwargs):
"""
Connect to an AMQP server on the given host and port.
Log in to the given virtual host using the supplied credentials.
This function is a :ref:`coroutine <coroutine>`.
:param str host: the host server to connect to.
:param int port: the port which the AMQP server is listening on.
:param str username: the username to authenticate with.
:param str password: the password to authenticate with.
:param str virtual_host: the AMQP virtual host to connect to.
:param func on_connection_close: function called after connection lost.
:keyword BaseEventLoop loop: An instance of :class:`~asyncio.BaseEventLoop` to use.
(Defaults to :func:`asyncio.get_event_loop()`)
:keyword socket sock: A :func:`~socket.socket` instance to use for the connection.
This is passed on to :meth:`loop.create_connection() <asyncio.BaseEventLoop.create_connection>`.
If ``sock`` is supplied then ``host`` and ``port`` will be ignored.
Further keyword arguments are passed on to :meth:`loop.create_connection() <asyncio.BaseEventLoop.create_connection>`.
This function will set TCP_NODELAY on TCP and TCP6 sockets either on supplied ``sock`` or created one.
:return: the :class:`Connection` object.
"""
from .protocol import AMQP
from .routing import Dispatcher
from .connection import open_connection
loop = asyncio.get_event_loop() if loop is None else loop
if sock is None:
kwargs['host'] = host
kwargs['port'] = port
else:
kwargs['sock'] = sock
dispatcher = Dispatcher()
def protocol_factory():
return AMQP(dispatcher, loop, close_callback=on_connection_close)
transport, protocol = yield from loop.create_connection(protocol_factory, **kwargs)
# RPC-like applications require TCP_NODELAY in order to acheive
# minimal response time. Actually, this library send data in one
# big chunk and so this will not affect TCP-performance.
sk = transport.get_extra_info('socket')
# 1. Unfortunatelly we cannot check socket type (sk.type == socket.SOCK_STREAM). https://bugs.python.org/issue21327
# 2. Proto remains zero, if not specified at creation of socket
if (sk.family in (socket.AF_INET, socket.AF_INET6)) and (sk.proto in (0, socket.IPPROTO_TCP)):
sk.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
connection_info = {
'username': username,
'password': password,
'virtual_host': virtual_host
}
connection = yield from open_connection(
loop, transport, protocol, dispatcher, connection_info)
return connection | [
"def",
"connect",
"(",
"host",
"=",
"'localhost'",
",",
"port",
"=",
"5672",
",",
"username",
"=",
"'guest'",
",",
"password",
"=",
"'guest'",
",",
"virtual_host",
"=",
"'/'",
",",
"on_connection_close",
"=",
"None",
",",
"*",
",",
"loop",
"=",
"None",
... | Connect to an AMQP server on the given host and port.
Log in to the given virtual host using the supplied credentials.
This function is a :ref:`coroutine <coroutine>`.
:param str host: the host server to connect to.
:param int port: the port which the AMQP server is listening on.
:param str username: the username to authenticate with.
:param str password: the password to authenticate with.
:param str virtual_host: the AMQP virtual host to connect to.
:param func on_connection_close: function called after connection lost.
:keyword BaseEventLoop loop: An instance of :class:`~asyncio.BaseEventLoop` to use.
(Defaults to :func:`asyncio.get_event_loop()`)
:keyword socket sock: A :func:`~socket.socket` instance to use for the connection.
This is passed on to :meth:`loop.create_connection() <asyncio.BaseEventLoop.create_connection>`.
If ``sock`` is supplied then ``host`` and ``port`` will be ignored.
Further keyword arguments are passed on to :meth:`loop.create_connection() <asyncio.BaseEventLoop.create_connection>`.
This function will set TCP_NODELAY on TCP and TCP6 sockets either on supplied ``sock`` or created one.
:return: the :class:`Connection` object. | [
"Connect",
"to",
"an",
"AMQP",
"server",
"on",
"the",
"given",
"host",
"and",
"port",
"."
] | ea8630d1803d10d4fd64b1a0e50f3097710b34d1 | https://github.com/benjamin-hodgson/asynqp/blob/ea8630d1803d10d4fd64b1a0e50f3097710b34d1/src/asynqp/__init__.py#L22-L86 | train |
benjamin-hodgson/asynqp | src/asynqp/__init__.py | connect_and_open_channel | def connect_and_open_channel(host='localhost',
port=5672,
username='guest', password='guest',
virtual_host='/',
on_connection_close=None, *,
loop=None, **kwargs):
"""
Connect to an AMQP server and open a channel on the connection.
This function is a :ref:`coroutine <coroutine>`.
Parameters of this function are the same as :func:`connect`.
:return: a tuple of ``(connection, channel)``.
Equivalent to::
connection = yield from connect(host, port, username, password, virtual_host, on_connection_close, loop=loop, **kwargs)
channel = yield from connection.open_channel()
return connection, channel
"""
connection = yield from connect(host, port, username, password, virtual_host, on_connection_close, loop=loop, **kwargs)
channel = yield from connection.open_channel()
return connection, channel | python | def connect_and_open_channel(host='localhost',
port=5672,
username='guest', password='guest',
virtual_host='/',
on_connection_close=None, *,
loop=None, **kwargs):
"""
Connect to an AMQP server and open a channel on the connection.
This function is a :ref:`coroutine <coroutine>`.
Parameters of this function are the same as :func:`connect`.
:return: a tuple of ``(connection, channel)``.
Equivalent to::
connection = yield from connect(host, port, username, password, virtual_host, on_connection_close, loop=loop, **kwargs)
channel = yield from connection.open_channel()
return connection, channel
"""
connection = yield from connect(host, port, username, password, virtual_host, on_connection_close, loop=loop, **kwargs)
channel = yield from connection.open_channel()
return connection, channel | [
"def",
"connect_and_open_channel",
"(",
"host",
"=",
"'localhost'",
",",
"port",
"=",
"5672",
",",
"username",
"=",
"'guest'",
",",
"password",
"=",
"'guest'",
",",
"virtual_host",
"=",
"'/'",
",",
"on_connection_close",
"=",
"None",
",",
"*",
",",
"loop",
... | Connect to an AMQP server and open a channel on the connection.
This function is a :ref:`coroutine <coroutine>`.
Parameters of this function are the same as :func:`connect`.
:return: a tuple of ``(connection, channel)``.
Equivalent to::
connection = yield from connect(host, port, username, password, virtual_host, on_connection_close, loop=loop, **kwargs)
channel = yield from connection.open_channel()
return connection, channel | [
"Connect",
"to",
"an",
"AMQP",
"server",
"and",
"open",
"a",
"channel",
"on",
"the",
"connection",
".",
"This",
"function",
"is",
"a",
":",
"ref",
":",
"coroutine",
"<coroutine",
">",
"."
] | ea8630d1803d10d4fd64b1a0e50f3097710b34d1 | https://github.com/benjamin-hodgson/asynqp/blob/ea8630d1803d10d4fd64b1a0e50f3097710b34d1/src/asynqp/__init__.py#L90-L112 | train |
benjamin-hodgson/asynqp | src/asynqp/protocol.py | AMQP.heartbeat_timeout | def heartbeat_timeout(self):
""" Called by heartbeat_monitor on timeout """
assert not self._closed, "Did we not stop heartbeat_monitor on close?"
log.error("Heartbeat time out")
poison_exc = ConnectionLostError('Heartbeat timed out')
poison_frame = frames.PoisonPillFrame(poison_exc)
self.dispatcher.dispatch_all(poison_frame)
# Spec says to just close socket without ConnectionClose handshake.
self.close() | python | def heartbeat_timeout(self):
""" Called by heartbeat_monitor on timeout """
assert not self._closed, "Did we not stop heartbeat_monitor on close?"
log.error("Heartbeat time out")
poison_exc = ConnectionLostError('Heartbeat timed out')
poison_frame = frames.PoisonPillFrame(poison_exc)
self.dispatcher.dispatch_all(poison_frame)
# Spec says to just close socket without ConnectionClose handshake.
self.close() | [
"def",
"heartbeat_timeout",
"(",
"self",
")",
":",
"assert",
"not",
"self",
".",
"_closed",
",",
"\"Did we not stop heartbeat_monitor on close?\"",
"log",
".",
"error",
"(",
"\"Heartbeat time out\"",
")",
"poison_exc",
"=",
"ConnectionLostError",
"(",
"'Heartbeat timed ... | Called by heartbeat_monitor on timeout | [
"Called",
"by",
"heartbeat_monitor",
"on",
"timeout"
] | ea8630d1803d10d4fd64b1a0e50f3097710b34d1 | https://github.com/benjamin-hodgson/asynqp/blob/ea8630d1803d10d4fd64b1a0e50f3097710b34d1/src/asynqp/protocol.py#L66-L74 | train |
Damgaard/PyImgur | pyimgur/request.py | convert_general | def convert_general(value):
"""Take a python object and convert it to the format Imgur expects."""
if isinstance(value, bool):
return "true" if value else "false"
elif isinstance(value, list):
value = [convert_general(item) for item in value]
value = convert_to_imgur_list(value)
elif isinstance(value, Integral):
return str(value)
elif 'pyimgur' in str(type(value)):
return str(getattr(value, 'id', value))
return value | python | def convert_general(value):
"""Take a python object and convert it to the format Imgur expects."""
if isinstance(value, bool):
return "true" if value else "false"
elif isinstance(value, list):
value = [convert_general(item) for item in value]
value = convert_to_imgur_list(value)
elif isinstance(value, Integral):
return str(value)
elif 'pyimgur' in str(type(value)):
return str(getattr(value, 'id', value))
return value | [
"def",
"convert_general",
"(",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"bool",
")",
":",
"return",
"\"true\"",
"if",
"value",
"else",
"\"false\"",
"elif",
"isinstance",
"(",
"value",
",",
"list",
")",
":",
"value",
"=",
"[",
"convert_ge... | Take a python object and convert it to the format Imgur expects. | [
"Take",
"a",
"python",
"object",
"and",
"convert",
"it",
"to",
"the",
"format",
"Imgur",
"expects",
"."
] | 606f17078d24158632f807430f8d0b9b3cd8b312 | https://github.com/Damgaard/PyImgur/blob/606f17078d24158632f807430f8d0b9b3cd8b312/pyimgur/request.py#L32-L43 | train |
Damgaard/PyImgur | pyimgur/request.py | to_imgur_format | def to_imgur_format(params):
"""Convert the parameters to the format Imgur expects."""
if params is None:
return None
return dict((k, convert_general(val)) for (k, val) in params.items()) | python | def to_imgur_format(params):
"""Convert the parameters to the format Imgur expects."""
if params is None:
return None
return dict((k, convert_general(val)) for (k, val) in params.items()) | [
"def",
"to_imgur_format",
"(",
"params",
")",
":",
"if",
"params",
"is",
"None",
":",
"return",
"None",
"return",
"dict",
"(",
"(",
"k",
",",
"convert_general",
"(",
"val",
")",
")",
"for",
"(",
"k",
",",
"val",
")",
"in",
"params",
".",
"items",
"... | Convert the parameters to the format Imgur expects. | [
"Convert",
"the",
"parameters",
"to",
"the",
"format",
"Imgur",
"expects",
"."
] | 606f17078d24158632f807430f8d0b9b3cd8b312 | https://github.com/Damgaard/PyImgur/blob/606f17078d24158632f807430f8d0b9b3cd8b312/pyimgur/request.py#L53-L57 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.