Code stringlengths 103 85.9k | Summary listlengths 0 94 |
|---|---|
Please provide a description of the function:def task_annotate(self, task, annotation):
self._execute(
task['uuid'],
'annotate',
'--',
annotation
)
id, annotated_task = self.get_task(uuid=task[six.u('uuid')])
return annotated_task | [
" Annotates a task. "
] |
Please provide a description of the function:def task_denotate(self, task, annotation):
self._execute(
task['uuid'],
'denotate',
'--',
annotation
)
id, denotated_task = self.get_task(uuid=task[six.u('uuid')])
return denotated_task | [
" Removes an annotation from a task. "
] |
Please provide a description of the function:def task_delete(self, **kw):
id, task = self.get_task(**kw)
if task['status'] == Status.DELETED:
raise ValueError("Task is already deleted.")
self._execute(id, 'delete')
return self.get_task(uuid=task['uuid'])[1] | [
" Marks a task as deleted. "
] |
Please provide a description of the function:def task_start(self, **kw):
id, task = self.get_task(**kw)
self._execute(id, 'start')
return self.get_task(uuid=task['uuid'])[1] | [
" Marks a task as started. "
] |
Please provide a description of the function:def task_stop(self, **kw):
id, task = self.get_task(**kw)
self._execute(id, 'stop')
return self.get_task(uuid=task['uuid'])[1] | [
" Marks a task as stopped. "
] |
Please provide a description of the function:def to_file(cls, status):
return {
Status.PENDING: DataFile.PENDING,
Status.WAITING: DataFile.PENDING,
Status.COMPLETED: DataFile.COMPLETED,
Status.DELETED: DataFile.COMPLETED
}[status] | [
" Returns the file in which this task is stored. "
] |
Please provide a description of the function:def from_stub(cls, data, udas=None):
udas = udas or {}
fields = cls.FIELDS.copy()
fields.update(udas)
processed = {}
for k, v in six.iteritems(data):
processed[k] = cls._serialize(k, v, fields)
return cl... | [
" Create a Task from an already deserialized dict. "
] |
Please provide a description of the function:def from_input(cls, input_file=sys.stdin, modify=False, udas=None):
original_task = input_file.readline().strip()
if modify:
modified_task = input_file.readline().strip()
return cls(json.loads(modified_task), udas=udas)
... | [
"\n Create a Task directly from stdin by reading one line. If modify=True,\n two lines are expected, which is consistent with the Taskwarrior hook\n system. The first line is interpreted as the original state of the Task,\n and the second one as the new, modified state.\n\n :param... |
Please provide a description of the function:def _deserialize(cls, key, value, fields):
converter = cls._get_converter_for_field(key, None, fields)
return converter.deserialize(value) | [
" Marshal incoming data into Python objects."
] |
Please provide a description of the function:def _serialize(cls, key, value, fields):
converter = cls._get_converter_for_field(key, None, fields)
return converter.serialize(value) | [
" Marshal outgoing data into Taskwarrior's JSON format."
] |
Please provide a description of the function:def get_changes(self, serialized=False, keep=False):
results = {}
# Check for explicitly-registered changes
for k, f, t in self._changes:
if k not in results:
results[k] = [f, None]
results[k][1] = (
... | [
" Get a journal of changes that have occurred\n\n :param `serialized`:\n Return changes in the serialized format used by TaskWarrior.\n :param `keep_changes`:\n By default, the list of changes is reset after running\n ``.get_changes``; set this to `True` if you would l... |
Please provide a description of the function:def update(self, values, force=False):
results = {}
for k, v in six.iteritems(values):
results[k] = self.__setitem__(k, v, force=force)
return results | [
" Update this task dictionary\n\n :returns: A dictionary mapping field names specified to be updated\n and a boolean value indicating whether the field was changed.\n\n "
] |
Please provide a description of the function:def set(self, key, value):
return self.__setitem__(key, value, force=True) | [
" Set a key's value regardless of whether a change is seen."
] |
Please provide a description of the function:def serialized(self):
serialized = {}
for k, v in six.iteritems(self):
serialized[k] = self._serialize(k, v, self._fields)
return serialized | [
" Returns a serialized representation of this task."
] |
Please provide a description of the function:def encode_task_experimental(task):
# First, clean the task:
task = task.copy()
if 'tags' in task:
task['tags'] = ','.join(task['tags'])
for k in task:
task[k] = encode_task_value(k, task[k])
# Then, format it as a string
return ... | [
" Convert a dict-like task to its string representation\n Used for adding a task via `task add`\n "
] |
Please provide a description of the function:def encode_task(task):
# First, clean the task:
task = task.copy()
if 'tags' in task:
task['tags'] = ','.join(task['tags'])
for k in task:
for unsafe, safe in six.iteritems(encode_replacements):
if isinstance(task[k], six.stri... | [
" Convert a dict-like task to its string representation "
] |
Please provide a description of the function:def decode_task(line):
task = {}
for key, value in re.findall(r'(\w+):"(.*?)(?<!\\)"', line):
value = value.replace('\\"', '"') # unescape quotes
task[key] = value
for unsafe, safe in six.iteritems(decode_replacements):
task... | [
" Parse a single record (task) from a task database file.\n\n I don't understand why they don't just use JSON or YAML. But\n that's okay.\n\n >>> decode_task('[description:\"Make a python API for taskwarrior\"]')\n {'description': 'Make a python API for taskwarrior'}\n\n "
] |
Please provide a description of the function:def convert_dict_to_override_args(config, prefix=''):
args = []
for k, v in six.iteritems(config):
if isinstance(v, dict):
args.extend(
convert_dict_to_override_args(
v,
prefix='.'.join(... | [
" Converts a dictionary of override arguments into CLI arguments.\n\n * Converts leaf nodes into dot paths of key names leading to the leaf\n node.\n * Does not include paths to leaf nodes not being non-dictionary type.\n\n See `taskw.test.test_utils.TestUtils.test_convert_dict_to_override_args`\n ... |
Please provide a description of the function:def stats_per_chunk(chunk):
for block_id in chunk.iter_block():
try:
block_counts[block_id] += 1
except KeyError:
block_counts[block_id] = 1 | [
"Given a chunk, increment the block types with the number of blocks found"
] |
Please provide a description of the function:def bounded_stats_per_chunk(chunk, block_counts, start, stop):
chunk_z, chunk_x = chunk.get_coords()
for z in range(16):
world_z = z + chunk_z*16
if ( (start != None and world_z < int(start[2])) or (stop != None and world_z > int(stop[2])) ):
... | [
"Given a chunk, return the number of blocks types within the specified selection"
] |
Please provide a description of the function:def process_region_file(region, start, stop):
rx = region.loc.x
rz = region.loc.z
# Does the region overlap the bounding box at all?
if (start != None):
if ( (rx+1)*512-1 < int(start[0]) or (rz+1)*512-1 < int(start[2]) ):
return
... | [
"Given a region, return the number of blocks of each ID in that region"
] |
Please provide a description of the function:def get_filenames(self):
# Warning: glob returns a empty list if the directory is unreadable, without raising an Exception
return list(glob.glob(os.path.join(self.worldfolder,'region','r.*.*.'+self.extension))) | [
"Find all matching file names in the world folder.\n \n This method is private, and it's use it deprecated. Use get_regionfiles() instead."
] |
Please provide a description of the function:def set_regionfiles(self, filenames):
for filename in filenames:
# Assume that filenames have the name r.<x-digit>.<z-digit>.<extension>
m = re.match(r"r.(\-?\d+).(\-?\d+)."+self.extension, os.path.basename(filename))
if m... | [
"\n This method directly sets the region files for this instance to use.\n It assumes the filenames are in the form r.<x-digit>.<z-digit>.<extension>\n "
] |
Please provide a description of the function:def get_region(self, x,z):
if (x,z) not in self.regions:
if (x,z) in self.regionfiles:
self.regions[(x,z)] = region.RegionFile(self.regionfiles[(x,z)])
else:
# Return an empty RegionFile object
... | [
"Get a region using x,z coordinates of a region. Cache results."
] |
Please provide a description of the function:def iter_regions(self):
# TODO: Implement BoundingBox
# TODO: Implement sort order
for x,z in self.regionfiles.keys():
close_after_use = False
if (x,z) in self.regions:
regionfile = self.regions[(x,z)]
... | [
"\n Return an iterable list of all region files. Use this function if you only\n want to loop through each region files once, and do not want to cache the results.\n "
] |
Please provide a description of the function:def get_nbt(self,x,z):
rx,cx = divmod(x,32)
rz,cz = divmod(z,32)
if (rx,rz) not in self.regions and (rx,rz) not in self.regionfiles:
raise InconceivedChunk("Chunk %s,%s is not present in world" % (x,z))
nbt = self.get_regi... | [
"\n Return a NBT specified by the chunk coordinates x,z. Raise InconceivedChunk\n if the NBT file is not yet generated. To get a Chunk object, use get_chunk.\n "
] |
Please provide a description of the function:def get_chunk(self,x,z):
return self.chunkclass(self.get_nbt(x, z)) | [
"\n Return a chunk specified by the chunk coordinates x,z. Raise InconceivedChunk\n if the chunk is not yet generated. To get the raw NBT data, use get_nbt.\n "
] |
Please provide a description of the function:def get_chunks(self, boundingbox=None):
if self.chunks == None:
self.chunks = list(self.iter_chunks())
return self.chunks | [
"\n Return a list of all chunks. Use this function if you access the chunk\n list frequently and want to cache the result.\n Use iter_chunks() if you only want to loop through the chunks once or have a\n very large world.\n "
] |
Please provide a description of the function:def chunk_count(self):
c = 0
for r in self.iter_regions():
c += r.chunk_count()
return c | [
"Return a count of the chunks in this world folder."
] |
Please provide a description of the function:def get_boundingbox(self):
b = BoundingBox()
for rx,rz in self.regionfiles.keys():
region = self.get_region(rx,rz)
rx,rz = 32*rx,32*rz
for cc in region.get_chunk_coords():
x,z = (rx+cc['x'],rz+cc['z... | [
"\n Return minimum and maximum x and z coordinates of the chunks that\n make up this world save\n "
] |
Please provide a description of the function:def expand(self,x,y,z):
if x != None:
if self.minx is None or x < self.minx:
self.minx = x
if self.maxx is None or x > self.maxx:
self.maxx = x
if y != None:
if self.miny is None or ... | [
"\n Expands the bounding\n "
] |
Please provide a description of the function:def unpack_nbt(tag):
if isinstance(tag, TAG_List):
return [unpack_nbt(i) for i in tag.tags]
elif isinstance(tag, TAG_Compound):
return dict((i.name, unpack_nbt(i)) for i in tag.tags)
else:
return tag.value | [
"\n Unpack an NBT tag into a native Python data structure.\n "
] |
Please provide a description of the function:def pack_nbt(s):
if isinstance(s, int):
return TAG_Long(s)
elif isinstance(s, float):
return TAG_Double(s)
elif isinstance(s, (str, unicode)):
return TAG_String(s)
elif isinstance(s, dict):
tag = TAG_Compound()
fo... | [
"\n Pack a native Python data structure into an NBT tag. Only the following\n structures and types are supported:\n\n * int\n * float\n * str\n * unicode\n * dict\n\n Additionally, arbitrary iterables are supported.\n\n Packing is not lossless. In order to avoid data loss, TAG_Long a... |
Please provide a description of the function:def _bytes_to_sector(bsize, sectorlength=SECTOR_LENGTH):
sectors, remainder = divmod(bsize, sectorlength)
return sectors if remainder == 0 else sectors + 1 | [
"Given a size in bytes, return how many sections of length sectorlen are required to contain it.\n This is equivalent to ceil(bsize/sectorlen), if Python would use floating\n points for division, and integers for ceil(), rather than the other way around."
] |
Please provide a description of the function:def _init_file(self):
header_length = 2*SECTOR_LENGTH
if self.size > header_length:
self.file.truncate(header_length)
self.file.seek(0)
self.file.write(header_length*b'\x00')
self.size = header_length | [
"Initialise the file header. This will erase any data previously in the file."
] |
Please provide a description of the function:def _parse_header(self):
# update the file size, needed when parse_header is called after
# we have unlinked a chunk or writed a new one
self.size = self.get_size()
if self.size == 0:
# Some region files seems to have 0 b... | [
"Read the region header and stores: offset, length and status."
] |
Please provide a description of the function:def _sectors(self, ignore_chunk=None):
sectorsize = self._bytes_to_sector(self.size)
sectors = [[] for s in range(sectorsize)]
sectors[0] = True # locations
sectors[1] = True # timestamps
for m in self.metadata.values():
... | [
"\n Return a list of all sectors, each sector is a list of chunks occupying the block.\n "
] |
Please provide a description of the function:def _locate_free_sectors(self, ignore_chunk=None):
sectors = self._sectors(ignore_chunk=ignore_chunk)
# Sectors are considered free, if the value is an empty list.
return [not i for i in sectors] | [
"Return a list of booleans, indicating the free sectors."
] |
Please provide a description of the function:def _find_free_location(self, free_locations, required_sectors=1, preferred=None):
# check preferred (current) location
if preferred and all(free_locations[preferred:preferred+required_sectors]):
return preferred
# check ... | [
"\n Given a list of booleans, find a list of <required_sectors> consecutive True values.\n If no such list is found, return length(free_locations).\n Assumes first two values are always False.\n "
] |
Please provide a description of the function:def get_chunk_coords(self):
chunks = []
for x in range(32):
for z in range(32):
m = self.metadata[x,z]
if m.is_created():
chunks.append({'x': x, 'z': z, 'length': m.blocklength})
... | [
"\n Return the x,z coordinates and length of the chunks that are defined in te regionfile.\n This includes chunks which may not be readable for whatever reason.\n \n This method is deprecated. Use :meth:`get_metadata` instead.\n "
] |
Please provide a description of the function:def iter_chunks(self):
for m in self.get_metadata():
try:
yield self.get_chunk(m.x, m.z)
except RegionFileFormatError:
pass | [
"\n Yield each readable chunk present in the region.\n Chunks that can not be read for whatever reason are silently skipped.\n Warning: this function returns a :class:`nbt.nbt.NBTFile` object, use ``Chunk(nbtfile)`` to get a\n :class:`nbt.chunk.Chunk` instance.\n "
] |
Please provide a description of the function:def iter_chunks_class(self):
for m in self.get_metadata():
try:
yield self.chunkclass(self.get_chunk(m.x, m.z))
except RegionFileFormatError:
pass | [
"\n Yield each readable chunk present in the region.\n Chunks that can not be read for whatever reason are silently skipped.\n This function returns a :class:`nbt.chunk.Chunk` instance.\n "
] |
Please provide a description of the function:def get_blockdata(self, x, z):
# read metadata block
m = self.metadata[x, z]
if m.status == STATUS_CHUNK_NOT_CREATED:
raise InconceivedChunk("Chunk %d,%d is not present in region" % (x,z))
elif m.status == STATUS_CHUNK_IN_... | [
"\n Return the decompressed binary data representing a chunk.\n \n May raise a RegionFileFormatError().\n If decompression of the data succeeds, all available data is returned, \n even if it is shorter than what is specified in the header (e.g. in case\n of a truncated whil... |
Please provide a description of the function:def get_nbt(self, x, z):
# TODO: cache results?
data = self.get_blockdata(x, z) # This may raise a RegionFileFormatError.
data = BytesIO(data)
err = None
try:
nbt = NBTFile(buffer=data)
if self.loc.x !=... | [
"\n Return a NBTFile of the specified chunk.\n Raise InconceivedChunk if the chunk is not included in the file.\n "
] |
Please provide a description of the function:def write_blockdata(self, x, z, data, compression=COMPRESSION_ZLIB):
if compression == COMPRESSION_GZIP:
# Python 3.1 and earlier do not yet support `data = gzip.compress(data)`.
compressed_file = BytesIO()
f = gzip.GzipFi... | [
"\n Compress the data, write it to file, and add pointers in the header so it \n can be found as chunk(x,z).\n "
] |
Please provide a description of the function:def write_chunk(self, x, z, nbt_file):
data = BytesIO()
nbt_file.write_file(buffer=data) # render to buffer; uncompressed
self.write_blockdata(x, z, data.getvalue()) | [
"\n Pack the NBT file as binary data, and write to file in a compressed format.\n "
] |
Please provide a description of the function:def unlink_chunk(self, x, z):
# This function fails for an empty file. If that is the case, just return.
if self.size < 2*SECTOR_LENGTH:
return
# zero the region header for the chunk (offset length and time)
self.file.see... | [
"\n Remove a chunk from the header of the region file.\n Fragmentation is not a problem, chunks are written to free sectors when possible.\n "
] |
Please provide a description of the function:def _classname(self):
if self.__class__.__module__ in (None,):
return self.__class__.__name__
else:
return "%s.%s" % (self.__class__.__module__, self.__class__.__name__) | [
"Return the fully qualified class name."
] |
Please provide a description of the function:def entities_per_chunk(chunk):
entities = []
for entity in chunk['Entities']:
x,y,z = entity["Pos"]
entities.append(Entity(entity["id"].value, (x.value,y.value,z.value)))
return entities | [
"Given a chunk, find all entities (mobs, items, vehicles)"
] |
Please provide a description of the function:def chests_per_chunk(chunk):
chests = []
for entity in chunk['Entities']:
eid = entity["id"].value
if eid == "Minecart" and entity["type"].value == 1 or eid == "minecraft:chest_minecart":
x,y,z = entity["Pos"]
x,y,z = x.... | [
"Find chests and get contents in a given chunk."
] |
Please provide a description of the function:def get_block(self, x, y, z):
sy,by = divmod(y, 16)
section = self.get_section(sy)
if section == None:
return None
return section.get_block(x, by, z) | [
"Get a block from relative x,y,z."
] |
Please provide a description of the function:def get_blocks_struct(self):
cur_x = 0
cur_y = 0
cur_z = 0
blocks = {}
for block_id in self.blocksList:
blocks[(cur_x,cur_y,cur_z)] = block_id
cur_y += 1
if (cur_y > 127):
cu... | [
"Return a dictionary with block ids keyed to (x, y, z)."
] |
Please provide a description of the function:def get_blocks_byte_array(self, buffer=False):
if buffer:
length = len(self.blocksList)
return BytesIO(pack(">i", length)+self.get_blocks_byte_array())
else:
return array.array('B', self.blocksList).tostring() | [
"Return a list of all blocks in this chunk."
] |
Please provide a description of the function:def get_data_byte_array(self, buffer=False):
if buffer:
length = len(self.dataList)
return BytesIO(pack(">i", length)+self.get_data_byte_array())
else:
return array.array('B', self.dataList).tostring() | [
"Return a list of data for all blocks in this chunk."
] |
Please provide a description of the function:def generate_heightmap(self, buffer=False, as_array=False):
non_solids = [0, 8, 9, 10, 11, 38, 37, 32, 31]
if buffer:
return BytesIO(pack(">i", 256)+self.generate_heightmap()) # Length + Heightmap, ready for insertion into Chunk NBT
... | [
"Return a heightmap, representing the highest solid blocks in this chunk."
] |
Please provide a description of the function:def set_blocks(self, list=None, dict=None, fill_air=False):
if list:
# Inputting a list like self.blocksList
self.blocksList = list
elif dict:
# Inputting a dictionary like result of self.get_blocks_struct()
... | [
"\n Sets all blocks in this chunk, using either a list or dictionary. \n Blocks not explicitly set can be filled to air by setting fill_air to True.\n "
] |
Please provide a description of the function:def set_block(self, x,y,z, id, data=0):
offset = y + z*128 + x*128*16
self.blocksList[offset] = id
if (offset % 2 == 1):
# offset is odd
index = (offset-1)//2
b = self.dataList[index]
self.dataL... | [
"Sets the block a x, y, z to the specified id, and optionally data."
] |
Please provide a description of the function:def get_block(self, x,y,z, coord=False):
offset = y + z*128 + x*128*16 if (coord == False) else coord[1] + coord[2]*128 + coord[0]*128*16
return self.blocksList[offset] | [
"Return the id of the block at x, y, z.",
"\n Laid out like:\n (0,0,0), (0,1,0), (0,2,0) ... (0,127,0), (0,0,1), (0,1,1), (0,2,1) ... (0,127,1), (0,0,2) ... (0,127,15), (1,0,0), (1,1,0) ... (15,127,15)\n \n ::\n \n blocks = []\n for x in range(15):\n ... |
Please provide a description of the function:def tag_info(self):
return self.__class__.__name__ + (
'(%r)' % self.name if self.name
else "") + ": " + self.valuestr() | [
"Return Unicode string with class, name and unnested value."
] |
Please provide a description of the function:def parse_file(self, filename=None, buffer=None, fileobj=None):
if filename:
self.file = GzipFile(filename, 'rb')
elif buffer:
if hasattr(buffer, 'name'):
self.filename = buffer.name
self.file = buf... | [
"Completely parse a file, extracting all tags."
] |
Please provide a description of the function:def write_file(self, filename=None, buffer=None, fileobj=None):
closefile = True
if buffer:
self.filename = None
self.file = buffer
closefile = False
elif filename:
self.filename = filename
... | [
"Write this NBT file to a file."
] |
Please provide a description of the function:def read(*parts):
try:
return io.open(os.path.join(*parts), 'r', encoding='utf-8').read()
except IOError:
return '' | [
"Reads the content of the file located at path created from *parts*."
] |
Please provide a description of the function:def loads(self, value):
raw = False if self.encoding == "utf-8" else True
if value is None:
return None
return msgpack.loads(value, raw=raw, use_list=self.use_list) | [
"\n Deserialize value using ``msgpack.loads``.\n\n :param value: bytes\n :returns: obj\n "
] |
Please provide a description of the function:def parse_uri_path(self, path):
options = {}
db, *_ = path[1:].split("/")
if db:
options["db"] = db
return options | [
"\n Given a uri path, return the Redis specific configuration\n options in that path string according to iana definition\n http://www.iana.org/assignments/uri-schemes/prov/redis\n\n :param path: string containing the path. Example: \"/0\"\n :return: mapping containing the options.... |
Please provide a description of the function:def timeout(cls, func):
NOT_SET = "NOT_SET"
@functools.wraps(func)
async def _timeout(self, *args, timeout=NOT_SET, **kwargs):
timeout = self.timeout if timeout == NOT_SET else timeout
if timeout == 0 or timeout is No... | [
"\n This decorator sets a maximum timeout for a coroutine to execute. The timeout can be both\n set in the ``self.timeout`` attribute or in the ``timeout`` kwarg of the function call.\n I.e if you have a function ``get(self, key)``, if its decorated with this decorator, you\n will be abl... |
Please provide a description of the function:def aiocache_enabled(cls, fake_return=None):
def enabled(func):
@functools.wraps(func)
async def _enabled(*args, **kwargs):
if os.getenv("AIOCACHE_DISABLE") == "1":
return fake_return
... | [
"\n Use this decorator to be able to fake the return of the function by setting the\n ``AIOCACHE_DISABLE`` environment variable\n "
] |
Please provide a description of the function:async def add(self, key, value, ttl=SENTINEL, dumps_fn=None, namespace=None, _conn=None):
start = time.monotonic()
dumps = dumps_fn or self._serializer.dumps
ns_key = self.build_key(key, namespace=namespace)
await self._add(ns_key, d... | [
"\n Stores the value in the given key with ttl if specified. Raises an error if the\n key already exists.\n\n :param key: str\n :param value: obj\n :param ttl: int the expiration time in seconds. Due to memcached\n restrictions if you want compatibility use int. In case... |
Please provide a description of the function:async def get(self, key, default=None, loads_fn=None, namespace=None, _conn=None):
start = time.monotonic()
loads = loads_fn or self._serializer.loads
ns_key = self.build_key(key, namespace=namespace)
value = loads(await self._get(ns... | [
"\n Get a value from the cache. Returns default if not found.\n\n :param key: str\n :param default: obj to return when key is not found\n :param loads_fn: callable alternative to use as loads function\n :param namespace: str alternative namespace to use\n :param timeout: in... |
Please provide a description of the function:async def multi_get(self, keys, loads_fn=None, namespace=None, _conn=None):
start = time.monotonic()
loads = loads_fn or self._serializer.loads
ns_keys = [self.build_key(key, namespace=namespace) for key in keys]
values = [
... | [
"\n Get multiple values from the cache, values not found are Nones.\n\n :param keys: list of str\n :param loads_fn: callable alternative to use as loads function\n :param namespace: str alternative namespace to use\n :param timeout: int or float in seconds specifying maximum timeo... |
Please provide a description of the function:async def set(
self, key, value, ttl=SENTINEL, dumps_fn=None, namespace=None, _cas_token=None, _conn=None
):
start = time.monotonic()
dumps = dumps_fn or self._serializer.dumps
ns_key = self.build_key(key, namespace=namespace)
... | [
"\n Stores the value in the given key with ttl if specified\n\n :param key: str\n :param value: obj\n :param ttl: int the expiration time in seconds. Due to memcached\n restrictions if you want compatibility use int. In case you\n need miliseconds, redis and memory ... |
Please provide a description of the function:async def multi_set(self, pairs, ttl=SENTINEL, dumps_fn=None, namespace=None, _conn=None):
start = time.monotonic()
dumps = dumps_fn or self._serializer.dumps
tmp_pairs = []
for key, value in pairs:
tmp_pairs.append((self... | [
"\n Stores multiple values in the given keys.\n\n :param pairs: list of two element iterables. First is key and second is value\n :param ttl: int the expiration time in seconds. Due to memcached\n restrictions if you want compatibility use int. In case you\n need milisecon... |
Please provide a description of the function:async def delete(self, key, namespace=None, _conn=None):
start = time.monotonic()
ns_key = self.build_key(key, namespace=namespace)
ret = await self._delete(ns_key, _conn=_conn)
logger.debug("DELETE %s %d (%.4f)s", ns_key, ret, time.m... | [
"\n Deletes the given key.\n\n :param key: Key to be deleted\n :param namespace: str alternative namespace to use\n :param timeout: int or float in seconds specifying maximum timeout\n for the operations to last\n :returns: int number of deleted keys\n :raises: :... |
Please provide a description of the function:async def exists(self, key, namespace=None, _conn=None):
start = time.monotonic()
ns_key = self.build_key(key, namespace=namespace)
ret = await self._exists(ns_key, _conn=_conn)
logger.debug("EXISTS %s %d (%.4f)s", ns_key, ret, time.m... | [
"\n Check key exists in the cache.\n\n :param key: str key to check\n :param namespace: str alternative namespace to use\n :param timeout: int or float in seconds specifying maximum timeout\n for the operations to last\n :returns: True if key exists otherwise False\n ... |
Please provide a description of the function:async def increment(self, key, delta=1, namespace=None, _conn=None):
start = time.monotonic()
ns_key = self.build_key(key, namespace=namespace)
ret = await self._increment(ns_key, delta, _conn=_conn)
logger.debug("INCREMENT %s %d (%.4... | [
"\n Increments value stored in key by delta (can be negative). If key doesn't\n exist, it creates the key with delta as value.\n\n :param key: str key to check\n :param delta: int amount to increment/decrement\n :param namespace: str alternative namespace to use\n :param ti... |
Please provide a description of the function:async def expire(self, key, ttl, namespace=None, _conn=None):
start = time.monotonic()
ns_key = self.build_key(key, namespace=namespace)
ret = await self._expire(ns_key, ttl, _conn=_conn)
logger.debug("EXPIRE %s %d (%.4f)s", ns_key, r... | [
"\n Set the ttl to the given key. By setting it to 0, it will disable it\n\n :param key: str key to expire\n :param ttl: int number of seconds for expiration. If 0, ttl is disabled\n :param namespace: str alternative namespace to use\n :param timeout: int or float in seconds speci... |
Please provide a description of the function:async def clear(self, namespace=None, _conn=None):
start = time.monotonic()
ret = await self._clear(namespace, _conn=_conn)
logger.debug("CLEAR %s %d (%.4f)s", namespace, ret, time.monotonic() - start)
return ret | [
"\n Clears the cache in the cache namespace. If an alternative namespace is given, it will\n clear those ones instead.\n\n :param namespace: str alternative namespace to use\n :param timeout: int or float in seconds specifying maximum timeout\n for the operations to last\n ... |
Please provide a description of the function:async def raw(self, command, *args, _conn=None, **kwargs):
start = time.monotonic()
ret = await self._raw(
command, *args, encoding=self.serializer.encoding, _conn=_conn, **kwargs
)
logger.debug("%s (%.4f)s", command, time... | [
"\n Send the raw command to the underlying client. Note that by using this CMD you\n will lose compatibility with other backends.\n\n Due to limitations with aiomcache client, args have to be provided as bytes.\n For rest of backends, str.\n\n :param command: str with the command.... |
Please provide a description of the function:async def close(self, *args, _conn=None, **kwargs):
start = time.monotonic()
ret = await self._close(*args, _conn=_conn, **kwargs)
logger.debug("CLOSE (%.4f)s", time.monotonic() - start)
return ret | [
"\n Perform any resource clean up necessary to exit the program safely.\n After closing, cmd execution is still possible but you will have to\n close again before exiting.\n\n :raises: :class:`asyncio.TimeoutError` if it lasts more than self.timeout\n "
] |
Please provide a description of the function:async def cas(self, value: Any, **kwargs) -> bool:
success = await self.client.set(self.key, value, _cas_token=self._token, **kwargs)
if not success:
raise OptimisticLockError("Value has changed since the lock started")
return Tru... | [
"\n Checks and sets the specified value for the locked key. If the value has changed\n since the lock was created, it will raise an :class:`aiocache.lock.OptimisticLockError`\n exception.\n\n :raises: :class:`aiocache.lock.OptimisticLockError`\n "
] |
Please provide a description of the function:def from_url(cls, url):
parsed_url = urllib.parse.urlparse(url)
kwargs = dict(urllib.parse.parse_qsl(parsed_url.query))
cache_class = Cache.get_scheme_class(parsed_url.scheme)
if parsed_url.path:
kwargs.update(cache_class... | [
"\n Given a resource uri, return an instance of that cache initialized with the given\n parameters. An example usage:\n\n >>> from aiocache import Cache\n >>> Cache.from_url('memory://')\n <aiocache.backends.memory.SimpleMemoryCache object at 0x1081dbb00>\n\n a more advance... |
Please provide a description of the function:def add(self, alias: str, config: dict) -> None:
self._config[alias] = config | [
"\n Add a cache to the current config. If the key already exists, it\n will overwrite it::\n\n >>> caches.add('default', {\n 'cache': \"aiocache.SimpleMemoryCache\",\n 'serializer': {\n 'class': \"aiocache.serializers.StringSerial... |
Please provide a description of the function:def get(self, alias: str):
try:
return self._caches[alias]
except KeyError:
pass
config = self.get_alias_config(alias)
cache = _create_cache(**deepcopy(config))
self._caches[alias] = cache
retu... | [
"\n Retrieve cache identified by alias. Will return always the same instance\n\n If the cache was not instantiated yet, it will do it lazily the first time\n this is called.\n\n :param alias: str cache alias\n :return: cache instance\n "
] |
Please provide a description of the function:def create(self, alias=None, cache=None, **kwargs):
if alias:
config = self.get_alias_config(alias)
elif cache:
warnings.warn(
"Creating a cache with an explicit config is deprecated, use 'aiocache.Cache'",
... | [
"\n Create a new cache. Either alias or cache params are required. You can use\n kwargs to pass extra parameters to configure the cache.\n\n .. deprecated:: 0.11.0\n Only creating a cache passing an alias is supported. If you want to\n create a cache passing explicit cache... |
Please provide a description of the function:def set_config(self, config):
if "default" not in config:
raise ValueError("default config must be provided")
for config_name in config.keys():
self._caches.pop(config_name, None)
self._config = config | [
"\n Set (override) the default config for cache aliases from a dict-like structure.\n The structure is the following::\n\n {\n 'default': {\n 'cache': \"aiocache.SimpleMemoryCache\",\n 'serializer': {\n 'class': \"a... |
Please provide a description of the function:async def async_poller(client, initial_response, deserialization_callback, polling_method):
try:
client = client if isinstance(client, ServiceClientAsync) else client._client
except AttributeError:
raise ValueError("Poller client parameter must ... | [
"Async Poller for long running operations.\n\n :param client: A msrest service client. Can be a SDK client and it will be casted to a ServiceClient.\n :type client: msrest.service_client.ServiceClient\n :param initial_response: The initial call response\n :type initial_response: msrest.universal_http.Cl... |
Please provide a description of the function:async def send(self, request: Request[HTTPRequestType], **config: Any) -> Response[HTTPRequestType, AsyncHTTPResponseType]:
pass | [
"Send the request using this HTTP sender.\n "
] |
Please provide a description of the function:def send(self, request, **kwargs):
session = request.context.session
old_max_redirects = None
if 'max_redirects' in kwargs:
warnings.warn("max_redirects in operation kwargs is deprecated, use config.redirect_policy instead",
... | [
"Patch the current session with Request level operation config.\n\n This is deprecated, we shouldn't patch the session with\n arguments at the Request, and \"config\" should be used.\n "
] |
Please provide a description of the function:def _request(self, method, url, params, headers, content, form_content):
# type: (str, str, Optional[Dict[str, str]], Optional[Dict[str, str]], Any, Optional[Dict[str, Any]]) -> ClientRequest
request = ClientRequest(method, self.format_url(url))
... | [
"Create ClientRequest object.\n\n :param str url: URL for the request.\n :param dict params: URL query parameters.\n :param dict headers: Headers\n :param dict form_content: Form content\n "
] |
Please provide a description of the function:def stream_upload(self, data, callback):
while True:
chunk = data.read(self.config.connection.data_block_size)
if not chunk:
break
if callback and callable(callback):
callback(chunk, respons... | [
"Generator for streaming request body data.\n\n :param data: A file-like object to be streamed.\n :param callback: Custom callback for monitoring progress.\n "
] |
Please provide a description of the function:def format_url(self, url, **kwargs):
# type: (str, Any) -> str
url = url.format(**kwargs)
parsed = urlparse(url)
if not parsed.scheme or not parsed.netloc:
url = url.lstrip('/')
base = self.config.base_url.form... | [
"Format request URL with the client base URL, unless the\n supplied URL is already absolute.\n\n :param str url: The request URL to be formatted if necessary.\n "
] |
Please provide a description of the function:def get(self, url, params=None, headers=None, content=None, form_content=None):
# type: (str, Optional[Dict[str, str]], Optional[Dict[str, str]], Any, Optional[Dict[str, Any]]) -> ClientRequest
request = self._request('GET', url, params, headers, con... | [
"Create a GET request object.\n\n :param str url: The request URL.\n :param dict params: Request URL parameters.\n :param dict headers: Headers\n :param dict form_content: Form content\n "
] |
Please provide a description of the function:def put(self, url, params=None, headers=None, content=None, form_content=None):
# type: (str, Optional[Dict[str, str]], Optional[Dict[str, str]], Any, Optional[Dict[str, Any]]) -> ClientRequest
request = self._request('PUT', url, params, headers, con... | [
"Create a PUT request object.\n\n :param str url: The request URL.\n :param dict params: Request URL parameters.\n :param dict headers: Headers\n :param dict form_content: Form content\n "
] |
Please provide a description of the function:def send_formdata(self, request, headers=None, content=None, **config):
request.headers = headers
request.add_formdata(content)
return self.send(request, **config) | [
"Send data as a multipart form-data request.\n We only deal with file-like objects or strings at this point.\n The requests is not yet streamed.\n\n This method is deprecated, and shouldn't be used anymore.\n\n :param ClientRequest request: The request object to be sent.\n :param ... |
Please provide a description of the function:def send(self, request, headers=None, content=None, **kwargs):
# "content" and "headers" are deprecated, only old SDK
if headers:
request.headers.update(headers)
if not request.files and request.data is None and content is not Non... | [
"Prepare and send request object according to configuration.\n\n :param ClientRequest request: The request object to be sent.\n :param dict headers: Any headers to add to the request.\n :param content: Any body data to add to the request.\n :param config: Any specific config overrides\n ... |
Please provide a description of the function:def stream_download(self, data, callback):
# type: (Union[requests.Response, ClientResponse], Callable) -> Iterator[bytes]
block = self.config.connection.data_block_size
try:
# Assume this is ClientResponse, which it should be if ... | [
"Generator for streaming request body data.\n\n :param data: A response object to be streamed.\n :param callback: Custom callback for monitoring progress.\n "
] |
Please provide a description of the function:def add_header(self, header, value):
# type: (str, str) -> None
warnings.warn("Private attribute _client.add_header is deprecated. Use config.headers instead.",
DeprecationWarning)
self.config.headers[header] = value | [
"Add a persistent header - this header will be applied to all\n requests sent during the current client session.\n\n .. deprecated:: 0.5.0\n Use config.headers instead\n\n :param str header: The header name.\n :param str value: The header value.\n "
] |
Please provide a description of the function:def signed_session(self, session=None):
# type: (Optional[requests.Session]) -> requests.Session
session = super(BasicAuthentication, self).signed_session(session)
session.auth = HTTPBasicAuth(self.username, self.password)
return sess... | [
"Create requests session with any required auth headers\n applied.\n\n If a session object is provided, configure it directly. Otherwise,\n create a new session and return it.\n\n :param session: The session to configure for authentication\n :type session: requests.Session\n ... |
Please provide a description of the function:def signed_session(self, session=None):
# type: (Optional[requests.Session]) -> requests.Session
session = super(BasicTokenAuthentication, self).signed_session(session)
header = "{} {}".format(self.scheme, self.token['access_token'])
... | [
"Create requests session with any required auth headers\n applied.\n\n If a session object is provided, configure it directly. Otherwise,\n create a new session and return it.\n\n :param session: The session to configure for authentication\n :type session: requests.Session\n ... |
Please provide a description of the function:def signed_session(self, session=None):
# type: (Optional[requests.Session]) -> requests.Session
session = session or requests.Session() # Don't call super on purpose, let's "auth" manage the headers.
session.auth = oauth.OAuth2(self.id, tok... | [
"Create requests session with any required auth headers applied.\n\n If a session object is provided, configure it directly. Otherwise,\n create a new session and return it.\n\n :param session: The session to configure for authentication\n :type session: requests.Session\n :rtype:... |
Please provide a description of the function:def signed_session(self, session=None):
# type: (Optional[requests.Session]) -> requests.Session
session = super(ApiKeyCredentials, self).signed_session(session)
session.headers.update(self.in_headers)
try:
# params is act... | [
"Create requests session with ApiKey.\n\n If a session object is provided, configure it directly. Otherwise,\n create a new session and return it.\n\n :param session: The session to configure for authentication\n :type session: requests.Session\n :rtype: requests.Session\n ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.