repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
Accelize/pycosio | pycosio/storage/azure.py | _AzureBaseSystem._secured_storage_parameters | def _secured_storage_parameters(self):
"""
Updates storage parameters with unsecure mode.
Returns:
dict: Updated storage_parameters.
"""
parameters = self._storage_parameters or dict()
# Handles unsecure mode
if self._unsecure:
parameters = parameters.copy()
parameters['protocol'] = 'http'
return parameters | python | def _secured_storage_parameters(self):
"""
Updates storage parameters with unsecure mode.
Returns:
dict: Updated storage_parameters.
"""
parameters = self._storage_parameters or dict()
# Handles unsecure mode
if self._unsecure:
parameters = parameters.copy()
parameters['protocol'] = 'http'
return parameters | [
"def",
"_secured_storage_parameters",
"(",
"self",
")",
":",
"parameters",
"=",
"self",
".",
"_storage_parameters",
"or",
"dict",
"(",
")",
"# Handles unsecure mode",
"if",
"self",
".",
"_unsecure",
":",
"parameters",
"=",
"parameters",
".",
"copy",
"(",
")",
... | Updates storage parameters with unsecure mode.
Returns:
dict: Updated storage_parameters. | [
"Updates",
"storage",
"parameters",
"with",
"unsecure",
"mode",
"."
] | 1cc1f8fdf5394d92918b7bae2bfa682169ccc48c | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/storage/azure.py#L140-L154 | train | 48,000 |
Accelize/pycosio | pycosio/storage/azure.py | _AzureBaseSystem._format_src_url | def _format_src_url(self, path, caller_system):
"""
Ensure path is absolute and use the correct URL format for use with
cross Azure storage account copy function.
Args:
path (str): Path or URL.
caller_system (pycosio.storage.azure._AzureBaseSystem subclass):
System calling this method (Can be another Azure system).
Returns:
str: URL.
"""
path = '%s/%s' % (self._endpoint, self.relpath(path))
# If SAS token available, use it to give cross account copy access.
if caller_system is not self:
try:
path = '%s?%s' % (path, self._storage_parameters['sas_token'])
except KeyError:
pass
return path | python | def _format_src_url(self, path, caller_system):
"""
Ensure path is absolute and use the correct URL format for use with
cross Azure storage account copy function.
Args:
path (str): Path or URL.
caller_system (pycosio.storage.azure._AzureBaseSystem subclass):
System calling this method (Can be another Azure system).
Returns:
str: URL.
"""
path = '%s/%s' % (self._endpoint, self.relpath(path))
# If SAS token available, use it to give cross account copy access.
if caller_system is not self:
try:
path = '%s?%s' % (path, self._storage_parameters['sas_token'])
except KeyError:
pass
return path | [
"def",
"_format_src_url",
"(",
"self",
",",
"path",
",",
"caller_system",
")",
":",
"path",
"=",
"'%s/%s'",
"%",
"(",
"self",
".",
"_endpoint",
",",
"self",
".",
"relpath",
"(",
"path",
")",
")",
"# If SAS token available, use it to give cross account copy access.... | Ensure path is absolute and use the correct URL format for use with
cross Azure storage account copy function.
Args:
path (str): Path or URL.
caller_system (pycosio.storage.azure._AzureBaseSystem subclass):
System calling this method (Can be another Azure system).
Returns:
str: URL. | [
"Ensure",
"path",
"is",
"absolute",
"and",
"use",
"the",
"correct",
"URL",
"format",
"for",
"use",
"with",
"cross",
"Azure",
"storage",
"account",
"copy",
"function",
"."
] | 1cc1f8fdf5394d92918b7bae2bfa682169ccc48c | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/storage/azure.py#L156-L178 | train | 48,001 |
Accelize/pycosio | pycosio/storage/azure.py | _AzureBaseSystem._update_listing_client_kwargs | def _update_listing_client_kwargs(client_kwargs, max_request_entries):
"""
Updates client kwargs for listing functions.
Args:
client_kwargs (dict): Client arguments.
max_request_entries (int): If specified, maximum entries returned
by request.
Returns:
dict: Updated client_kwargs
"""
client_kwargs = client_kwargs.copy()
if max_request_entries:
client_kwargs['num_results'] = max_request_entries
return client_kwargs | python | def _update_listing_client_kwargs(client_kwargs, max_request_entries):
"""
Updates client kwargs for listing functions.
Args:
client_kwargs (dict): Client arguments.
max_request_entries (int): If specified, maximum entries returned
by request.
Returns:
dict: Updated client_kwargs
"""
client_kwargs = client_kwargs.copy()
if max_request_entries:
client_kwargs['num_results'] = max_request_entries
return client_kwargs | [
"def",
"_update_listing_client_kwargs",
"(",
"client_kwargs",
",",
"max_request_entries",
")",
":",
"client_kwargs",
"=",
"client_kwargs",
".",
"copy",
"(",
")",
"if",
"max_request_entries",
":",
"client_kwargs",
"[",
"'num_results'",
"]",
"=",
"max_request_entries",
... | Updates client kwargs for listing functions.
Args:
client_kwargs (dict): Client arguments.
max_request_entries (int): If specified, maximum entries returned
by request.
Returns:
dict: Updated client_kwargs | [
"Updates",
"client",
"kwargs",
"for",
"listing",
"functions",
"."
] | 1cc1f8fdf5394d92918b7bae2bfa682169ccc48c | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/storage/azure.py#L181-L196 | train | 48,002 |
Accelize/pycosio | pycosio/storage/azure.py | _AzureBaseSystem._model_to_dict | def _model_to_dict(obj):
"""
Convert object model to dict.
Args:
obj: Object model.
Returns:
dict: Converted model.
"""
result = _properties_model_to_dict(obj.properties)
for attribute in ('metadata', 'snapshot'):
try:
value = getattr(obj, attribute)
except AttributeError:
continue
if value:
result[attribute] = value
return result | python | def _model_to_dict(obj):
"""
Convert object model to dict.
Args:
obj: Object model.
Returns:
dict: Converted model.
"""
result = _properties_model_to_dict(obj.properties)
for attribute in ('metadata', 'snapshot'):
try:
value = getattr(obj, attribute)
except AttributeError:
continue
if value:
result[attribute] = value
return result | [
"def",
"_model_to_dict",
"(",
"obj",
")",
":",
"result",
"=",
"_properties_model_to_dict",
"(",
"obj",
".",
"properties",
")",
"for",
"attribute",
"in",
"(",
"'metadata'",
",",
"'snapshot'",
")",
":",
"try",
":",
"value",
"=",
"getattr",
"(",
"obj",
",",
... | Convert object model to dict.
Args:
obj: Object model.
Returns:
dict: Converted model. | [
"Convert",
"object",
"model",
"to",
"dict",
"."
] | 1cc1f8fdf5394d92918b7bae2bfa682169ccc48c | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/storage/azure.py#L199-L217 | train | 48,003 |
Accelize/pycosio | pycosio/storage/azure.py | _AzureStorageRawIORangeWriteBase._create | def _create(self):
"""
Create the file if not exists.
"""
# Create new file
with _handle_azure_exception():
self._create_from_size(
content_length=self._content_length, **self._client_kwargs) | python | def _create(self):
"""
Create the file if not exists.
"""
# Create new file
with _handle_azure_exception():
self._create_from_size(
content_length=self._content_length, **self._client_kwargs) | [
"def",
"_create",
"(",
"self",
")",
":",
"# Create new file",
"with",
"_handle_azure_exception",
"(",
")",
":",
"self",
".",
"_create_from_size",
"(",
"content_length",
"=",
"self",
".",
"_content_length",
",",
"*",
"*",
"self",
".",
"_client_kwargs",
")"
] | Create the file if not exists. | [
"Create",
"the",
"file",
"if",
"not",
"exists",
"."
] | 1cc1f8fdf5394d92918b7bae2bfa682169ccc48c | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/storage/azure.py#L331-L338 | train | 48,004 |
Accelize/pycosio | pycosio/storage/azure.py | _AzureStorageRawIORangeWriteBase._flush | def _flush(self, buffer, start, end):
"""
Flush the write buffer of the stream if applicable.
Args:
buffer (memoryview): Buffer content.
start (int): Start of buffer position to flush.
Supported only with page blobs.
end (int): End of buffer position to flush.
Supported only with page blobs.
"""
buffer_size = len(buffer)
if not buffer_size:
return
# Write range normally
with self._size_lock:
if end > self._size:
# Require to resize the blob if note enough space
with _handle_azure_exception():
self._resize(content_length=end, **self._client_kwargs)
self._reset_head()
if buffer_size > self.MAX_FLUSH_SIZE:
# Too large buffer, needs to split in multiples requests
futures = []
for part_start in range(0, buffer_size, self.MAX_FLUSH_SIZE):
# Split buffer
buffer_part = buffer[
part_start:part_start + self.MAX_FLUSH_SIZE]
if not len(buffer_part):
# No more data
break
# Upload split buffer in parallel
start_range = start + part_start
futures.append(self._workers.submit(
self._update_range, data=buffer_part.tobytes(),
start_range=start_range,
end_range=start_range + len(buffer_part) - 1,
**self._client_kwargs))
with _handle_azure_exception():
# Wait for upload completion
for future in _as_completed(futures):
future.result()
else:
# Buffer lower than limit, do one requests.
with _handle_azure_exception():
self._update_range(
data=buffer.tobytes(), start_range=start,
end_range=end - 1, **self._client_kwargs) | python | def _flush(self, buffer, start, end):
"""
Flush the write buffer of the stream if applicable.
Args:
buffer (memoryview): Buffer content.
start (int): Start of buffer position to flush.
Supported only with page blobs.
end (int): End of buffer position to flush.
Supported only with page blobs.
"""
buffer_size = len(buffer)
if not buffer_size:
return
# Write range normally
with self._size_lock:
if end > self._size:
# Require to resize the blob if note enough space
with _handle_azure_exception():
self._resize(content_length=end, **self._client_kwargs)
self._reset_head()
if buffer_size > self.MAX_FLUSH_SIZE:
# Too large buffer, needs to split in multiples requests
futures = []
for part_start in range(0, buffer_size, self.MAX_FLUSH_SIZE):
# Split buffer
buffer_part = buffer[
part_start:part_start + self.MAX_FLUSH_SIZE]
if not len(buffer_part):
# No more data
break
# Upload split buffer in parallel
start_range = start + part_start
futures.append(self._workers.submit(
self._update_range, data=buffer_part.tobytes(),
start_range=start_range,
end_range=start_range + len(buffer_part) - 1,
**self._client_kwargs))
with _handle_azure_exception():
# Wait for upload completion
for future in _as_completed(futures):
future.result()
else:
# Buffer lower than limit, do one requests.
with _handle_azure_exception():
self._update_range(
data=buffer.tobytes(), start_range=start,
end_range=end - 1, **self._client_kwargs) | [
"def",
"_flush",
"(",
"self",
",",
"buffer",
",",
"start",
",",
"end",
")",
":",
"buffer_size",
"=",
"len",
"(",
"buffer",
")",
"if",
"not",
"buffer_size",
":",
"return",
"# Write range normally",
"with",
"self",
".",
"_size_lock",
":",
"if",
"end",
">",... | Flush the write buffer of the stream if applicable.
Args:
buffer (memoryview): Buffer content.
start (int): Start of buffer position to flush.
Supported only with page blobs.
end (int): End of buffer position to flush.
Supported only with page blobs. | [
"Flush",
"the",
"write",
"buffer",
"of",
"the",
"stream",
"if",
"applicable",
"."
] | 1cc1f8fdf5394d92918b7bae2bfa682169ccc48c | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/storage/azure.py#L349-L402 | train | 48,005 |
Accelize/pycosio | pycosio/_core/io_base.py | memoizedmethod | def memoizedmethod(method):
"""
Decorator that caches method result.
Args:
method (function): Method
Returns:
function: Memoized method.
Notes:
Target method class needs as "_cache" attribute (dict).
It is the case of "ObjectIOBase" and all its subclasses.
"""
method_name = method.__name__
@wraps(method)
def patched(self, *args, **kwargs):
"""Patched method"""
# Gets value from cache
try:
return self._cache[method_name]
# Evaluates and cache value
except KeyError:
result = self._cache[method_name] = method(
self, *args, **kwargs)
return result
return patched | python | def memoizedmethod(method):
"""
Decorator that caches method result.
Args:
method (function): Method
Returns:
function: Memoized method.
Notes:
Target method class needs as "_cache" attribute (dict).
It is the case of "ObjectIOBase" and all its subclasses.
"""
method_name = method.__name__
@wraps(method)
def patched(self, *args, **kwargs):
"""Patched method"""
# Gets value from cache
try:
return self._cache[method_name]
# Evaluates and cache value
except KeyError:
result = self._cache[method_name] = method(
self, *args, **kwargs)
return result
return patched | [
"def",
"memoizedmethod",
"(",
"method",
")",
":",
"method_name",
"=",
"method",
".",
"__name__",
"@",
"wraps",
"(",
"method",
")",
"def",
"patched",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"\"\"\"Patched method\"\"\"",
"# Gets val... | Decorator that caches method result.
Args:
method (function): Method
Returns:
function: Memoized method.
Notes:
Target method class needs as "_cache" attribute (dict).
It is the case of "ObjectIOBase" and all its subclasses. | [
"Decorator",
"that",
"caches",
"method",
"result",
"."
] | 1cc1f8fdf5394d92918b7bae2bfa682169ccc48c | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/_core/io_base.py#L120-L150 | train | 48,006 |
Accelize/pycosio | pycosio/_core/io_base.py | WorkerPoolBase._generate_async | def _generate_async(self, generator):
"""
Return the previous generator object after having run the first element
evaluation as a background task.
Args:
generator (iterable): A generator function.
Returns:
iterable: The generator function with first element evaluated
in background.
"""
first_value_future = self._workers.submit(next, generator)
def get_first_element(future=first_value_future):
"""
Get first element value from future.
Args:
future (concurrent.futures._base.Future): First value future.
Returns:
Evaluated value
"""
try:
yield future.result()
except StopIteration:
return
return chain(get_first_element(), generator) | python | def _generate_async(self, generator):
"""
Return the previous generator object after having run the first element
evaluation as a background task.
Args:
generator (iterable): A generator function.
Returns:
iterable: The generator function with first element evaluated
in background.
"""
first_value_future = self._workers.submit(next, generator)
def get_first_element(future=first_value_future):
"""
Get first element value from future.
Args:
future (concurrent.futures._base.Future): First value future.
Returns:
Evaluated value
"""
try:
yield future.result()
except StopIteration:
return
return chain(get_first_element(), generator) | [
"def",
"_generate_async",
"(",
"self",
",",
"generator",
")",
":",
"first_value_future",
"=",
"self",
".",
"_workers",
".",
"submit",
"(",
"next",
",",
"generator",
")",
"def",
"get_first_element",
"(",
"future",
"=",
"first_value_future",
")",
":",
"\"\"\"\n ... | Return the previous generator object after having run the first element
evaluation as a background task.
Args:
generator (iterable): A generator function.
Returns:
iterable: The generator function with first element evaluated
in background. | [
"Return",
"the",
"previous",
"generator",
"object",
"after",
"having",
"run",
"the",
"first",
"element",
"evaluation",
"as",
"a",
"background",
"task",
"."
] | 1cc1f8fdf5394d92918b7bae2bfa682169ccc48c | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/_core/io_base.py#L174-L203 | train | 48,007 |
Accelize/pycosio | pycosio/storage/swift.py | _handle_client_exception | def _handle_client_exception():
"""
Handle Swift exception and convert to class
IO exceptions
Raises:
OSError subclasses: IO error.
"""
try:
yield
except _ClientException as exception:
if exception.http_status in _ERROR_CODES:
raise _ERROR_CODES[exception.http_status](
exception.http_reason)
raise | python | def _handle_client_exception():
"""
Handle Swift exception and convert to class
IO exceptions
Raises:
OSError subclasses: IO error.
"""
try:
yield
except _ClientException as exception:
if exception.http_status in _ERROR_CODES:
raise _ERROR_CODES[exception.http_status](
exception.http_reason)
raise | [
"def",
"_handle_client_exception",
"(",
")",
":",
"try",
":",
"yield",
"except",
"_ClientException",
"as",
"exception",
":",
"if",
"exception",
".",
"http_status",
"in",
"_ERROR_CODES",
":",
"raise",
"_ERROR_CODES",
"[",
"exception",
".",
"http_status",
"]",
"("... | Handle Swift exception and convert to class
IO exceptions
Raises:
OSError subclasses: IO error. | [
"Handle",
"Swift",
"exception",
"and",
"convert",
"to",
"class",
"IO",
"exceptions"
] | 1cc1f8fdf5394d92918b7bae2bfa682169ccc48c | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/storage/swift.py#L24-L39 | train | 48,008 |
Accelize/pycosio | pycosio/_core/io_base_raw.py | ObjectRawIOBase._update_seek | def _update_seek(self, offset, whence):
"""
Update seek value.
Args:
offset (int): Offset.
whence (int): Whence.
Returns:
int: Seek position.
"""
with self._seek_lock:
if whence == SEEK_SET:
self._seek = offset
elif whence == SEEK_CUR:
self._seek += offset
elif whence == SEEK_END:
self._seek = offset + self._size
else:
raise ValueError('whence value %s unsupported' % whence)
return self._seek | python | def _update_seek(self, offset, whence):
"""
Update seek value.
Args:
offset (int): Offset.
whence (int): Whence.
Returns:
int: Seek position.
"""
with self._seek_lock:
if whence == SEEK_SET:
self._seek = offset
elif whence == SEEK_CUR:
self._seek += offset
elif whence == SEEK_END:
self._seek = offset + self._size
else:
raise ValueError('whence value %s unsupported' % whence)
return self._seek | [
"def",
"_update_seek",
"(",
"self",
",",
"offset",
",",
"whence",
")",
":",
"with",
"self",
".",
"_seek_lock",
":",
"if",
"whence",
"==",
"SEEK_SET",
":",
"self",
".",
"_seek",
"=",
"offset",
"elif",
"whence",
"==",
"SEEK_CUR",
":",
"self",
".",
"_seek... | Update seek value.
Args:
offset (int): Offset.
whence (int): Whence.
Returns:
int: Seek position. | [
"Update",
"seek",
"value",
"."
] | 1cc1f8fdf5394d92918b7bae2bfa682169ccc48c | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/_core/io_base_raw.py#L379-L399 | train | 48,009 |
Accelize/pycosio | pycosio/storage/http.py | _handle_http_errors | def _handle_http_errors(response):
"""
Check for HTTP errors and raise
OSError if relevant.
Args:
response (requests.Response):
Returns:
requests.Response: response
"""
code = response.status_code
if 200 <= code < 400:
return response
elif code in (403, 404):
raise {403: _ObjectPermissionError,
404: _ObjectNotFoundError}[code](response.reason)
response.raise_for_status() | python | def _handle_http_errors(response):
"""
Check for HTTP errors and raise
OSError if relevant.
Args:
response (requests.Response):
Returns:
requests.Response: response
"""
code = response.status_code
if 200 <= code < 400:
return response
elif code in (403, 404):
raise {403: _ObjectPermissionError,
404: _ObjectNotFoundError}[code](response.reason)
response.raise_for_status() | [
"def",
"_handle_http_errors",
"(",
"response",
")",
":",
"code",
"=",
"response",
".",
"status_code",
"if",
"200",
"<=",
"code",
"<",
"400",
":",
"return",
"response",
"elif",
"code",
"in",
"(",
"403",
",",
"404",
")",
":",
"raise",
"{",
"403",
":",
... | Check for HTTP errors and raise
OSError if relevant.
Args:
response (requests.Response):
Returns:
requests.Response: response | [
"Check",
"for",
"HTTP",
"errors",
"and",
"raise",
"OSError",
"if",
"relevant",
"."
] | 1cc1f8fdf5394d92918b7bae2bfa682169ccc48c | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/storage/http.py#L16-L33 | train | 48,010 |
Accelize/pycosio | pycosio/_core/io_random_write.py | ObjectRawIORandomWriteBase.flush | def flush(self):
"""
Flush the write buffers of the stream if applicable and
save the object on the cloud.
"""
if self._writable:
with self._seek_lock:
buffer = self._get_buffer()
# Flush that part of the file
end = self._seek
start = end - len(buffer)
# Clear buffer
self._write_buffer = bytearray()
# Flush content
with handle_os_exceptions():
self._flush(buffer, start, end) | python | def flush(self):
"""
Flush the write buffers of the stream if applicable and
save the object on the cloud.
"""
if self._writable:
with self._seek_lock:
buffer = self._get_buffer()
# Flush that part of the file
end = self._seek
start = end - len(buffer)
# Clear buffer
self._write_buffer = bytearray()
# Flush content
with handle_os_exceptions():
self._flush(buffer, start, end) | [
"def",
"flush",
"(",
"self",
")",
":",
"if",
"self",
".",
"_writable",
":",
"with",
"self",
".",
"_seek_lock",
":",
"buffer",
"=",
"self",
".",
"_get_buffer",
"(",
")",
"# Flush that part of the file",
"end",
"=",
"self",
".",
"_seek",
"start",
"=",
"end... | Flush the write buffers of the stream if applicable and
save the object on the cloud. | [
"Flush",
"the",
"write",
"buffers",
"of",
"the",
"stream",
"if",
"applicable",
"and",
"save",
"the",
"object",
"on",
"the",
"cloud",
"."
] | 1cc1f8fdf5394d92918b7bae2bfa682169ccc48c | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/_core/io_random_write.py#L26-L44 | train | 48,011 |
Accelize/pycosio | pycosio/_core/io_random_write.py | ObjectBufferedIORandomWriteBase._update_size | def _update_size(self, size, future):
"""
Keep track of the file size during writing.
If specified size value is greater than the current size, update the
current size using specified value.
Used as callback in default "_flush" implementation for files supporting
random write access.
Args:
size (int): Size value.
future (concurrent.futures._base.Future): future.
"""
with self._size_lock:
# Update value
if size > self._size and future.done:
# Size can be lower if seek down on an 'a' mode open file.
self._size = size | python | def _update_size(self, size, future):
"""
Keep track of the file size during writing.
If specified size value is greater than the current size, update the
current size using specified value.
Used as callback in default "_flush" implementation for files supporting
random write access.
Args:
size (int): Size value.
future (concurrent.futures._base.Future): future.
"""
with self._size_lock:
# Update value
if size > self._size and future.done:
# Size can be lower if seek down on an 'a' mode open file.
self._size = size | [
"def",
"_update_size",
"(",
"self",
",",
"size",
",",
"future",
")",
":",
"with",
"self",
".",
"_size_lock",
":",
"# Update value",
"if",
"size",
">",
"self",
".",
"_size",
"and",
"future",
".",
"done",
":",
"# Size can be lower if seek down on an 'a' mode open ... | Keep track of the file size during writing.
If specified size value is greater than the current size, update the
current size using specified value.
Used as callback in default "_flush" implementation for files supporting
random write access.
Args:
size (int): Size value.
future (concurrent.futures._base.Future): future. | [
"Keep",
"track",
"of",
"the",
"file",
"size",
"during",
"writing",
"."
] | 1cc1f8fdf5394d92918b7bae2bfa682169ccc48c | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/_core/io_random_write.py#L117-L135 | train | 48,012 |
Accelize/pycosio | pycosio/_core/io_random_write.py | ObjectBufferedIORandomWriteBase._flush_range | def _flush_range(self, buffer, start, end):
"""
Flush a buffer to a range of the file.
Meant to be used asynchronously, used to provides parallel flushing of
file parts when applicable.
Args:
buffer (memoryview): Buffer content.
start (int): Start of buffer position to flush.
end (int): End of buffer position to flush.
"""
# On first call, Get file size if exists
with self._size_lock:
if not self._size_synched:
self._size_synched = True
try:
self._size = self.raw._size
except (ObjectNotFoundError, UnsupportedOperation):
self._size = 0
# It is not possible to flush a part if start > size:
# If it is the case, wait that previous parts are flushed before
# flushing this one
while start > self._size:
sleep(self._FLUSH_WAIT)
# Flush buffer using RAW IO
self._raw_flush(buffer, start, end) | python | def _flush_range(self, buffer, start, end):
"""
Flush a buffer to a range of the file.
Meant to be used asynchronously, used to provides parallel flushing of
file parts when applicable.
Args:
buffer (memoryview): Buffer content.
start (int): Start of buffer position to flush.
end (int): End of buffer position to flush.
"""
# On first call, Get file size if exists
with self._size_lock:
if not self._size_synched:
self._size_synched = True
try:
self._size = self.raw._size
except (ObjectNotFoundError, UnsupportedOperation):
self._size = 0
# It is not possible to flush a part if start > size:
# If it is the case, wait that previous parts are flushed before
# flushing this one
while start > self._size:
sleep(self._FLUSH_WAIT)
# Flush buffer using RAW IO
self._raw_flush(buffer, start, end) | [
"def",
"_flush_range",
"(",
"self",
",",
"buffer",
",",
"start",
",",
"end",
")",
":",
"# On first call, Get file size if exists",
"with",
"self",
".",
"_size_lock",
":",
"if",
"not",
"self",
".",
"_size_synched",
":",
"self",
".",
"_size_synched",
"=",
"True"... | Flush a buffer to a range of the file.
Meant to be used asynchronously, used to provides parallel flushing of
file parts when applicable.
Args:
buffer (memoryview): Buffer content.
start (int): Start of buffer position to flush.
end (int): End of buffer position to flush. | [
"Flush",
"a",
"buffer",
"to",
"a",
"range",
"of",
"the",
"file",
"."
] | 1cc1f8fdf5394d92918b7bae2bfa682169ccc48c | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/_core/io_random_write.py#L137-L165 | train | 48,013 |
Accelize/pycosio | pycosio/storage/azure_file.py | AzureFileRawIO._update_range | def _update_range(self, data, **kwargs):
"""
Update range with data
Args:
data (bytes): data.
"""
self._client.update_range(data=data, **kwargs) | python | def _update_range(self, data, **kwargs):
"""
Update range with data
Args:
data (bytes): data.
"""
self._client.update_range(data=data, **kwargs) | [
"def",
"_update_range",
"(",
"self",
",",
"data",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"_client",
".",
"update_range",
"(",
"data",
"=",
"data",
",",
"*",
"*",
"kwargs",
")"
] | Update range with data
Args:
data (bytes): data. | [
"Update",
"range",
"with",
"data"
] | 1cc1f8fdf5394d92918b7bae2bfa682169ccc48c | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/storage/azure_file.py#L267-L274 | train | 48,014 |
fedora-infra/datanommer | tools/active-contrib.py | handle_bodhi | def handle_bodhi(msg):
""" Given a bodhi message, return the FAS username. """
if 'bodhi.update.comment' in msg.topic:
username = msg.msg['comment']['author']
elif 'bodhi.buildroot_override' in msg.topic:
username = msg.msg['override']['submitter']
else:
username = msg.msg.get('update', {}).get('submitter')
return username | python | def handle_bodhi(msg):
""" Given a bodhi message, return the FAS username. """
if 'bodhi.update.comment' in msg.topic:
username = msg.msg['comment']['author']
elif 'bodhi.buildroot_override' in msg.topic:
username = msg.msg['override']['submitter']
else:
username = msg.msg.get('update', {}).get('submitter')
return username | [
"def",
"handle_bodhi",
"(",
"msg",
")",
":",
"if",
"'bodhi.update.comment'",
"in",
"msg",
".",
"topic",
":",
"username",
"=",
"msg",
".",
"msg",
"[",
"'comment'",
"]",
"[",
"'author'",
"]",
"elif",
"'bodhi.buildroot_override'",
"in",
"msg",
".",
"topic",
"... | Given a bodhi message, return the FAS username. | [
"Given",
"a",
"bodhi",
"message",
"return",
"the",
"FAS",
"username",
"."
] | 4a20e216bb404b14f76c7065518fd081e989764d | https://github.com/fedora-infra/datanommer/blob/4a20e216bb404b14f76c7065518fd081e989764d/tools/active-contrib.py#L64-L73 | train | 48,015 |
fedora-infra/datanommer | tools/active-contrib.py | handle_wiki | def handle_wiki(msg):
""" Given a wiki message, return the FAS username. """
if 'wiki.article.edit' in msg.topic:
username = msg.msg['user']
elif 'wiki.upload.complete' in msg.topic:
username = msg.msg['user_text']
else:
raise ValueError("Unhandled topic.")
return username | python | def handle_wiki(msg):
""" Given a wiki message, return the FAS username. """
if 'wiki.article.edit' in msg.topic:
username = msg.msg['user']
elif 'wiki.upload.complete' in msg.topic:
username = msg.msg['user_text']
else:
raise ValueError("Unhandled topic.")
return username | [
"def",
"handle_wiki",
"(",
"msg",
")",
":",
"if",
"'wiki.article.edit'",
"in",
"msg",
".",
"topic",
":",
"username",
"=",
"msg",
".",
"msg",
"[",
"'user'",
"]",
"elif",
"'wiki.upload.complete'",
"in",
"msg",
".",
"topic",
":",
"username",
"=",
"msg",
"."... | Given a wiki message, return the FAS username. | [
"Given",
"a",
"wiki",
"message",
"return",
"the",
"FAS",
"username",
"."
] | 4a20e216bb404b14f76c7065518fd081e989764d | https://github.com/fedora-infra/datanommer/blob/4a20e216bb404b14f76c7065518fd081e989764d/tools/active-contrib.py#L76-L86 | train | 48,016 |
Accelize/pycosio | pycosio/_core/functions_core.py | is_storage | def is_storage(url, storage=None):
"""
Check if file is a local file or a storage file.
File is considered local if:
- URL is a local path.
- URL starts by "file://"
- a "storage" is provided.
Args:
url (str): file path or URL
storage (str): Storage name.
Returns:
bool: return True if file is local.
"""
if storage:
return True
split_url = url.split('://', 1)
if len(split_url) == 2 and split_url[0].lower() != 'file':
return True
return False | python | def is_storage(url, storage=None):
"""
Check if file is a local file or a storage file.
File is considered local if:
- URL is a local path.
- URL starts by "file://"
- a "storage" is provided.
Args:
url (str): file path or URL
storage (str): Storage name.
Returns:
bool: return True if file is local.
"""
if storage:
return True
split_url = url.split('://', 1)
if len(split_url) == 2 and split_url[0].lower() != 'file':
return True
return False | [
"def",
"is_storage",
"(",
"url",
",",
"storage",
"=",
"None",
")",
":",
"if",
"storage",
":",
"return",
"True",
"split_url",
"=",
"url",
".",
"split",
"(",
"'://'",
",",
"1",
")",
"if",
"len",
"(",
"split_url",
")",
"==",
"2",
"and",
"split_url",
"... | Check if file is a local file or a storage file.
File is considered local if:
- URL is a local path.
- URL starts by "file://"
- a "storage" is provided.
Args:
url (str): file path or URL
storage (str): Storage name.
Returns:
bool: return True if file is local. | [
"Check",
"if",
"file",
"is",
"a",
"local",
"file",
"or",
"a",
"storage",
"file",
"."
] | 1cc1f8fdf5394d92918b7bae2bfa682169ccc48c | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/_core/functions_core.py#L10-L31 | train | 48,017 |
Accelize/pycosio | pycosio/_core/functions_core.py | format_and_is_storage | def format_and_is_storage(path):
"""
Checks if path is storage and format it.
If path is an opened file-like object, returns is storage as True.
Args:
path (path-like object or file-like object):
Returns:
tuple: str or file-like object (Updated path),
bool (True if is storage).
"""
if not hasattr(path, 'read'):
path = fsdecode(path).replace('\\', '/')
return path, is_storage(path)
return path, True | python | def format_and_is_storage(path):
"""
Checks if path is storage and format it.
If path is an opened file-like object, returns is storage as True.
Args:
path (path-like object or file-like object):
Returns:
tuple: str or file-like object (Updated path),
bool (True if is storage).
"""
if not hasattr(path, 'read'):
path = fsdecode(path).replace('\\', '/')
return path, is_storage(path)
return path, True | [
"def",
"format_and_is_storage",
"(",
"path",
")",
":",
"if",
"not",
"hasattr",
"(",
"path",
",",
"'read'",
")",
":",
"path",
"=",
"fsdecode",
"(",
"path",
")",
".",
"replace",
"(",
"'\\\\'",
",",
"'/'",
")",
"return",
"path",
",",
"is_storage",
"(",
... | Checks if path is storage and format it.
If path is an opened file-like object, returns is storage as True.
Args:
path (path-like object or file-like object):
Returns:
tuple: str or file-like object (Updated path),
bool (True if is storage). | [
"Checks",
"if",
"path",
"is",
"storage",
"and",
"format",
"it",
"."
] | 1cc1f8fdf5394d92918b7bae2bfa682169ccc48c | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/_core/functions_core.py#L34-L50 | train | 48,018 |
Accelize/pycosio | pycosio/_core/functions_core.py | equivalent_to | def equivalent_to(std_function):
"""
Decorates a cloud object compatible function
to provides fall back to standard function if
used on local files.
Args:
std_function (function): standard function to
used with local files.
Returns:
function: new function
"""
def decorate(cos_function):
"""Decorator argument handler"""
@wraps(cos_function)
def decorated(path, *args, **kwargs):
"""Decorated function"""
# Handles path-like objects
path = fsdecode(path).replace('\\', '/')
# Storage object: Handle with Cloud object storage
# function
if is_storage(path):
with handle_os_exceptions():
return cos_function(path, *args, **kwargs)
# Local file: Redirect to standard function
return std_function(path, *args, **kwargs)
return decorated
return decorate | python | def equivalent_to(std_function):
"""
Decorates a cloud object compatible function
to provides fall back to standard function if
used on local files.
Args:
std_function (function): standard function to
used with local files.
Returns:
function: new function
"""
def decorate(cos_function):
"""Decorator argument handler"""
@wraps(cos_function)
def decorated(path, *args, **kwargs):
"""Decorated function"""
# Handles path-like objects
path = fsdecode(path).replace('\\', '/')
# Storage object: Handle with Cloud object storage
# function
if is_storage(path):
with handle_os_exceptions():
return cos_function(path, *args, **kwargs)
# Local file: Redirect to standard function
return std_function(path, *args, **kwargs)
return decorated
return decorate | [
"def",
"equivalent_to",
"(",
"std_function",
")",
":",
"def",
"decorate",
"(",
"cos_function",
")",
":",
"\"\"\"Decorator argument handler\"\"\"",
"@",
"wraps",
"(",
"cos_function",
")",
"def",
"decorated",
"(",
"path",
",",
"*",
"args",
",",
"*",
"*",
"kwargs... | Decorates a cloud object compatible function
to provides fall back to standard function if
used on local files.
Args:
std_function (function): standard function to
used with local files.
Returns:
function: new function | [
"Decorates",
"a",
"cloud",
"object",
"compatible",
"function",
"to",
"provides",
"fall",
"back",
"to",
"standard",
"function",
"if",
"used",
"on",
"local",
"files",
"."
] | 1cc1f8fdf5394d92918b7bae2bfa682169ccc48c | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/_core/functions_core.py#L53-L88 | train | 48,019 |
Accelize/pycosio | pycosio/storage/oss.py | _handle_oss_error | def _handle_oss_error():
"""
Handle OSS exception and convert to class IO exceptions
Raises:
OSError subclasses: IO error.
"""
try:
yield
except _OssError as exception:
if exception.status in _ERROR_CODES:
raise _ERROR_CODES[exception.status](
exception.details.get('Message', ''))
raise | python | def _handle_oss_error():
"""
Handle OSS exception and convert to class IO exceptions
Raises:
OSError subclasses: IO error.
"""
try:
yield
except _OssError as exception:
if exception.status in _ERROR_CODES:
raise _ERROR_CODES[exception.status](
exception.details.get('Message', ''))
raise | [
"def",
"_handle_oss_error",
"(",
")",
":",
"try",
":",
"yield",
"except",
"_OssError",
"as",
"exception",
":",
"if",
"exception",
".",
"status",
"in",
"_ERROR_CODES",
":",
"raise",
"_ERROR_CODES",
"[",
"exception",
".",
"status",
"]",
"(",
"exception",
".",
... | Handle OSS exception and convert to class IO exceptions
Raises:
OSError subclasses: IO error. | [
"Handle",
"OSS",
"exception",
"and",
"convert",
"to",
"class",
"IO",
"exceptions"
] | 1cc1f8fdf5394d92918b7bae2bfa682169ccc48c | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/storage/oss.py#L25-L39 | train | 48,020 |
Accelize/pycosio | pycosio/storage/oss.py | _OSSSystem._get_client | def _get_client(self):
"""
OSS2 Auth client
Returns:
oss2.Auth or oss2.StsAuth: client
"""
return (_oss.StsAuth if 'security_token' in self._storage_parameters
else _oss.Auth if self._storage_parameters
else _oss.AnonymousAuth)(**self._storage_parameters) | python | def _get_client(self):
"""
OSS2 Auth client
Returns:
oss2.Auth or oss2.StsAuth: client
"""
return (_oss.StsAuth if 'security_token' in self._storage_parameters
else _oss.Auth if self._storage_parameters
else _oss.AnonymousAuth)(**self._storage_parameters) | [
"def",
"_get_client",
"(",
"self",
")",
":",
"return",
"(",
"_oss",
".",
"StsAuth",
"if",
"'security_token'",
"in",
"self",
".",
"_storage_parameters",
"else",
"_oss",
".",
"Auth",
"if",
"self",
".",
"_storage_parameters",
"else",
"_oss",
".",
"AnonymousAuth",... | OSS2 Auth client
Returns:
oss2.Auth or oss2.StsAuth: client | [
"OSS2",
"Auth",
"client"
] | 1cc1f8fdf5394d92918b7bae2bfa682169ccc48c | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/storage/oss.py#L102-L111 | train | 48,021 |
Accelize/pycosio | pycosio/storage/oss.py | _OSSSystem._get_bucket | def _get_bucket(self, client_kwargs):
"""
Get bucket object.
Returns:
oss2.Bucket
"""
return _oss.Bucket(self.client, endpoint=self._endpoint,
bucket_name=client_kwargs['bucket_name']) | python | def _get_bucket(self, client_kwargs):
"""
Get bucket object.
Returns:
oss2.Bucket
"""
return _oss.Bucket(self.client, endpoint=self._endpoint,
bucket_name=client_kwargs['bucket_name']) | [
"def",
"_get_bucket",
"(",
"self",
",",
"client_kwargs",
")",
":",
"return",
"_oss",
".",
"Bucket",
"(",
"self",
".",
"client",
",",
"endpoint",
"=",
"self",
".",
"_endpoint",
",",
"bucket_name",
"=",
"client_kwargs",
"[",
"'bucket_name'",
"]",
")"
] | Get bucket object.
Returns:
oss2.Bucket | [
"Get",
"bucket",
"object",
"."
] | 1cc1f8fdf5394d92918b7bae2bfa682169ccc48c | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/storage/oss.py#L136-L144 | train | 48,022 |
Accelize/pycosio | pycosio/storage/oss.py | _OSSSystem.islink | def islink(self, path=None, header=None):
"""
Returns True if object is a symbolic link.
Args:
path (str): File path or URL.
header (dict): Object header.
Returns:
bool: True if object is Symlink.
"""
if header is None:
header = self._head(self.get_client_kwargs(path))
for key in ('x-oss-object-type', 'type'):
try:
return header.pop(key) == 'Symlink'
except KeyError:
continue
return False | python | def islink(self, path=None, header=None):
"""
Returns True if object is a symbolic link.
Args:
path (str): File path or URL.
header (dict): Object header.
Returns:
bool: True if object is Symlink.
"""
if header is None:
header = self._head(self.get_client_kwargs(path))
for key in ('x-oss-object-type', 'type'):
try:
return header.pop(key) == 'Symlink'
except KeyError:
continue
return False | [
"def",
"islink",
"(",
"self",
",",
"path",
"=",
"None",
",",
"header",
"=",
"None",
")",
":",
"if",
"header",
"is",
"None",
":",
"header",
"=",
"self",
".",
"_head",
"(",
"self",
".",
"get_client_kwargs",
"(",
"path",
")",
")",
"for",
"key",
"in",
... | Returns True if object is a symbolic link.
Args:
path (str): File path or URL.
header (dict): Object header.
Returns:
bool: True if object is Symlink. | [
"Returns",
"True",
"if",
"object",
"is",
"a",
"symbolic",
"link",
"."
] | 1cc1f8fdf5394d92918b7bae2bfa682169ccc48c | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/storage/oss.py#L146-L165 | train | 48,023 |
Accelize/pycosio | pycosio/storage/oss.py | _OSSSystem._model_to_dict | def _model_to_dict(model, ignore):
"""
Convert OSS model to dict.
Args:
model (oss2.models.RequestResult): Model.
ignore (tuple of str): Keys to not insert to dict.
Returns:
dict: Model dict version.
"""
return {attr: value for attr, value in model.__dict__.items()
if not attr.startswith('_') and attr not in ignore} | python | def _model_to_dict(model, ignore):
"""
Convert OSS model to dict.
Args:
model (oss2.models.RequestResult): Model.
ignore (tuple of str): Keys to not insert to dict.
Returns:
dict: Model dict version.
"""
return {attr: value for attr, value in model.__dict__.items()
if not attr.startswith('_') and attr not in ignore} | [
"def",
"_model_to_dict",
"(",
"model",
",",
"ignore",
")",
":",
"return",
"{",
"attr",
":",
"value",
"for",
"attr",
",",
"value",
"in",
"model",
".",
"__dict__",
".",
"items",
"(",
")",
"if",
"not",
"attr",
".",
"startswith",
"(",
"'_'",
")",
"and",
... | Convert OSS model to dict.
Args:
model (oss2.models.RequestResult): Model.
ignore (tuple of str): Keys to not insert to dict.
Returns:
dict: Model dict version. | [
"Convert",
"OSS",
"model",
"to",
"dict",
"."
] | 1cc1f8fdf5394d92918b7bae2bfa682169ccc48c | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/storage/oss.py#L224-L236 | train | 48,024 |
Accelize/pycosio | pycosio/_core/functions_io.py | cos_open | def cos_open(file, mode='r', buffering=-1, encoding=None, errors=None,
newline=None, storage=None, storage_parameters=None, unsecure=None,
**kwargs):
"""
Open file and return a corresponding file object.
Equivalent to "io.open" or builtin "open".
File can also be binary opened file-like object.
Args:
file (path-like object or file-like object): File path, object URL or
opened file-like object.
mode (str): mode in which the file is opened (default to 'rb').
see "io.open" for all possible modes. Note that all modes may
not be supported by all kind of file and storage.
buffering (int): Set the buffering policy.
-1 to use default behavior,
0 to switch buffering off,
1 to select line buffering (only usable in text mode),
and an integer > 1 to indicate the size in bytes of a
fixed-size chunk buffer.
See "io.open" for more information.
encoding (str): The name of the encoding used to
decode or encode the file. This should only be used in text mode.
See "io.open" for more information.
errors (str): Specifies how encoding and decoding errors
are to be handled.
This should only be used in text mode.
See "io.open" for more information.
newline (str): Controls how universal newlines mode works.
This should only be used in text mode.
See "io.open" for more information.
storage (str): Storage name.
storage_parameters (dict): Storage configuration parameters.
Generally, client configuration and credentials.
unsecure (bool): If True, disables TLS/SSL to improves
transfer performance. But makes connection unsecure.
Default to False.
kwargs: Other arguments to pass to opened object.
Note that theses arguments may not be compatible with
all kind of file and storage.
Returns:
file-like object: opened file.
Raises:
OSError: If the file cannot be opened.
FileExistsError: File open in 'x' mode already exists.
"""
# Handles file-like objects:
if hasattr(file, 'read'):
with _text_io_wrapper(file, mode, encoding, errors, newline) as wrapped:
yield wrapped
return
# Handles path-like objects
file = fsdecode(file).replace('\\', '/')
# Storage object
if is_storage(file, storage):
with get_instance(
name=file, cls='raw' if buffering == 0 else 'buffered',
storage=storage, storage_parameters=storage_parameters,
mode=mode, unsecure=unsecure, **kwargs) as stream:
with _text_io_wrapper(stream, mode=mode, encoding=encoding,
errors=errors, newline=newline) as wrapped:
yield wrapped
# Local file: Redirect to "io.open"
else:
with io_open(file, mode, buffering, encoding, errors, newline,
**kwargs) as stream:
yield stream | python | def cos_open(file, mode='r', buffering=-1, encoding=None, errors=None,
newline=None, storage=None, storage_parameters=None, unsecure=None,
**kwargs):
"""
Open file and return a corresponding file object.
Equivalent to "io.open" or builtin "open".
File can also be binary opened file-like object.
Args:
file (path-like object or file-like object): File path, object URL or
opened file-like object.
mode (str): mode in which the file is opened (default to 'rb').
see "io.open" for all possible modes. Note that all modes may
not be supported by all kind of file and storage.
buffering (int): Set the buffering policy.
-1 to use default behavior,
0 to switch buffering off,
1 to select line buffering (only usable in text mode),
and an integer > 1 to indicate the size in bytes of a
fixed-size chunk buffer.
See "io.open" for more information.
encoding (str): The name of the encoding used to
decode or encode the file. This should only be used in text mode.
See "io.open" for more information.
errors (str): Specifies how encoding and decoding errors
are to be handled.
This should only be used in text mode.
See "io.open" for more information.
newline (str): Controls how universal newlines mode works.
This should only be used in text mode.
See "io.open" for more information.
storage (str): Storage name.
storage_parameters (dict): Storage configuration parameters.
Generally, client configuration and credentials.
unsecure (bool): If True, disables TLS/SSL to improves
transfer performance. But makes connection unsecure.
Default to False.
kwargs: Other arguments to pass to opened object.
Note that theses arguments may not be compatible with
all kind of file and storage.
Returns:
file-like object: opened file.
Raises:
OSError: If the file cannot be opened.
FileExistsError: File open in 'x' mode already exists.
"""
# Handles file-like objects:
if hasattr(file, 'read'):
with _text_io_wrapper(file, mode, encoding, errors, newline) as wrapped:
yield wrapped
return
# Handles path-like objects
file = fsdecode(file).replace('\\', '/')
# Storage object
if is_storage(file, storage):
with get_instance(
name=file, cls='raw' if buffering == 0 else 'buffered',
storage=storage, storage_parameters=storage_parameters,
mode=mode, unsecure=unsecure, **kwargs) as stream:
with _text_io_wrapper(stream, mode=mode, encoding=encoding,
errors=errors, newline=newline) as wrapped:
yield wrapped
# Local file: Redirect to "io.open"
else:
with io_open(file, mode, buffering, encoding, errors, newline,
**kwargs) as stream:
yield stream | [
"def",
"cos_open",
"(",
"file",
",",
"mode",
"=",
"'r'",
",",
"buffering",
"=",
"-",
"1",
",",
"encoding",
"=",
"None",
",",
"errors",
"=",
"None",
",",
"newline",
"=",
"None",
",",
"storage",
"=",
"None",
",",
"storage_parameters",
"=",
"None",
",",... | Open file and return a corresponding file object.
Equivalent to "io.open" or builtin "open".
File can also be binary opened file-like object.
Args:
file (path-like object or file-like object): File path, object URL or
opened file-like object.
mode (str): mode in which the file is opened (default to 'rb').
see "io.open" for all possible modes. Note that all modes may
not be supported by all kind of file and storage.
buffering (int): Set the buffering policy.
-1 to use default behavior,
0 to switch buffering off,
1 to select line buffering (only usable in text mode),
and an integer > 1 to indicate the size in bytes of a
fixed-size chunk buffer.
See "io.open" for more information.
encoding (str): The name of the encoding used to
decode or encode the file. This should only be used in text mode.
See "io.open" for more information.
errors (str): Specifies how encoding and decoding errors
are to be handled.
This should only be used in text mode.
See "io.open" for more information.
newline (str): Controls how universal newlines mode works.
This should only be used in text mode.
See "io.open" for more information.
storage (str): Storage name.
storage_parameters (dict): Storage configuration parameters.
Generally, client configuration and credentials.
unsecure (bool): If True, disables TLS/SSL to improves
transfer performance. But makes connection unsecure.
Default to False.
kwargs: Other arguments to pass to opened object.
Note that theses arguments may not be compatible with
all kind of file and storage.
Returns:
file-like object: opened file.
Raises:
OSError: If the file cannot be opened.
FileExistsError: File open in 'x' mode already exists. | [
"Open",
"file",
"and",
"return",
"a",
"corresponding",
"file",
"object",
"."
] | 1cc1f8fdf5394d92918b7bae2bfa682169ccc48c | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/_core/functions_io.py#L12-L85 | train | 48,025 |
Accelize/pycosio | pycosio/_core/functions_io.py | _text_io_wrapper | def _text_io_wrapper(stream, mode, encoding, errors, newline):
"""Wrap a binary stream to Text stream.
Args:
stream (file-like object): binary stream.
mode (str): Open mode.
encoding (str): Stream encoding.
errors (str): Decoding error handling.
newline (str): Universal newlines
"""
# Text mode, if not already a text stream
# That has the "encoding" attribute
if "t" in mode and not hasattr(stream, 'encoding'):
text_stream = TextIOWrapper(
stream, encoding=encoding, errors=errors, newline=newline)
yield text_stream
text_stream.flush()
# Binary mode (Or already text stream)
else:
yield stream | python | def _text_io_wrapper(stream, mode, encoding, errors, newline):
"""Wrap a binary stream to Text stream.
Args:
stream (file-like object): binary stream.
mode (str): Open mode.
encoding (str): Stream encoding.
errors (str): Decoding error handling.
newline (str): Universal newlines
"""
# Text mode, if not already a text stream
# That has the "encoding" attribute
if "t" in mode and not hasattr(stream, 'encoding'):
text_stream = TextIOWrapper(
stream, encoding=encoding, errors=errors, newline=newline)
yield text_stream
text_stream.flush()
# Binary mode (Or already text stream)
else:
yield stream | [
"def",
"_text_io_wrapper",
"(",
"stream",
",",
"mode",
",",
"encoding",
",",
"errors",
",",
"newline",
")",
":",
"# Text mode, if not already a text stream",
"# That has the \"encoding\" attribute",
"if",
"\"t\"",
"in",
"mode",
"and",
"not",
"hasattr",
"(",
"stream",
... | Wrap a binary stream to Text stream.
Args:
stream (file-like object): binary stream.
mode (str): Open mode.
encoding (str): Stream encoding.
errors (str): Decoding error handling.
newline (str): Universal newlines | [
"Wrap",
"a",
"binary",
"stream",
"to",
"Text",
"stream",
"."
] | 1cc1f8fdf5394d92918b7bae2bfa682169ccc48c | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/_core/functions_io.py#L89-L109 | train | 48,026 |
fedora-infra/datanommer | tools/first-week-of-datanommer/tstamptobuckets.py | CollisionDict.hash_key | def hash_key(self, key):
""" "Hash" all keys in a timerange to the same value. """
for i, destination_key in enumerate(self._dict):
if key < destination_key:
return destination_key
return key | python | def hash_key(self, key):
""" "Hash" all keys in a timerange to the same value. """
for i, destination_key in enumerate(self._dict):
if key < destination_key:
return destination_key
return key | [
"def",
"hash_key",
"(",
"self",
",",
"key",
")",
":",
"for",
"i",
",",
"destination_key",
"in",
"enumerate",
"(",
"self",
".",
"_dict",
")",
":",
"if",
"key",
"<",
"destination_key",
":",
"return",
"destination_key",
"return",
"key"
] | "Hash" all keys in a timerange to the same value. | [
"Hash",
"all",
"keys",
"in",
"a",
"timerange",
"to",
"the",
"same",
"value",
"."
] | 4a20e216bb404b14f76c7065518fd081e989764d | https://github.com/fedora-infra/datanommer/blob/4a20e216bb404b14f76c7065518fd081e989764d/tools/first-week-of-datanommer/tstamptobuckets.py#L31-L37 | train | 48,027 |
briancappello/py-yaml-fixtures | py_yaml_fixtures/fixtures_loader.py | FixturesLoader._load_from_yaml | def _load_from_yaml(self, filename: str, model_identifiers: Dict[str, List[str]]):
"""
Load fixtures from the given filename
"""
class_name = filename[:filename.rfind('.')]
rendered_yaml = self.env.get_template(filename).render(
model_identifiers=model_identifiers)
fixture_data, self.relationships[class_name] = self._post_process_yaml_data(
yaml.load(rendered_yaml),
self.factory.get_relationships(class_name))
for identifier_key, data in fixture_data.items():
self.model_fixtures[class_name][identifier_key] = data | python | def _load_from_yaml(self, filename: str, model_identifiers: Dict[str, List[str]]):
"""
Load fixtures from the given filename
"""
class_name = filename[:filename.rfind('.')]
rendered_yaml = self.env.get_template(filename).render(
model_identifiers=model_identifiers)
fixture_data, self.relationships[class_name] = self._post_process_yaml_data(
yaml.load(rendered_yaml),
self.factory.get_relationships(class_name))
for identifier_key, data in fixture_data.items():
self.model_fixtures[class_name][identifier_key] = data | [
"def",
"_load_from_yaml",
"(",
"self",
",",
"filename",
":",
"str",
",",
"model_identifiers",
":",
"Dict",
"[",
"str",
",",
"List",
"[",
"str",
"]",
"]",
")",
":",
"class_name",
"=",
"filename",
"[",
":",
"filename",
".",
"rfind",
"(",
"'.'",
")",
"]... | Load fixtures from the given filename | [
"Load",
"fixtures",
"from",
"the",
"given",
"filename"
] | 60c37daf58ec3b1c4bba637889949523a69b8a73 | https://github.com/briancappello/py-yaml-fixtures/blob/60c37daf58ec3b1c4bba637889949523a69b8a73/py_yaml_fixtures/fixtures_loader.py#L152-L164 | train | 48,028 |
briancappello/py-yaml-fixtures | py_yaml_fixtures/fixtures_loader.py | FixturesLoader._post_process_yaml_data | def _post_process_yaml_data(self,
fixture_data: Dict[str, Dict[str, Any]],
relationship_columns: Set[str],
) -> Tuple[Dict[str, Dict[str, Any]], List[str]]:
"""
Convert and normalize identifier strings to Identifiers, as well as determine
class relationships.
"""
rv = {}
relationships = set()
if not fixture_data:
return rv, relationships
for identifier_id, data in fixture_data.items():
new_data = {}
for col_name, value in data.items():
if col_name not in relationship_columns:
new_data[col_name] = value
continue
identifiers = normalize_identifiers(value)
if identifiers:
relationships.add(identifiers[0].class_name)
if isinstance(value, str) and len(identifiers) <= 1:
new_data[col_name] = identifiers[0] if identifiers else None
else:
new_data[col_name] = identifiers
rv[identifier_id] = new_data
return rv, list(relationships) | python | def _post_process_yaml_data(self,
fixture_data: Dict[str, Dict[str, Any]],
relationship_columns: Set[str],
) -> Tuple[Dict[str, Dict[str, Any]], List[str]]:
"""
Convert and normalize identifier strings to Identifiers, as well as determine
class relationships.
"""
rv = {}
relationships = set()
if not fixture_data:
return rv, relationships
for identifier_id, data in fixture_data.items():
new_data = {}
for col_name, value in data.items():
if col_name not in relationship_columns:
new_data[col_name] = value
continue
identifiers = normalize_identifiers(value)
if identifiers:
relationships.add(identifiers[0].class_name)
if isinstance(value, str) and len(identifiers) <= 1:
new_data[col_name] = identifiers[0] if identifiers else None
else:
new_data[col_name] = identifiers
rv[identifier_id] = new_data
return rv, list(relationships) | [
"def",
"_post_process_yaml_data",
"(",
"self",
",",
"fixture_data",
":",
"Dict",
"[",
"str",
",",
"Dict",
"[",
"str",
",",
"Any",
"]",
"]",
",",
"relationship_columns",
":",
"Set",
"[",
"str",
"]",
",",
")",
"->",
"Tuple",
"[",
"Dict",
"[",
"str",
",... | Convert and normalize identifier strings to Identifiers, as well as determine
class relationships. | [
"Convert",
"and",
"normalize",
"identifier",
"strings",
"to",
"Identifiers",
"as",
"well",
"as",
"determine",
"class",
"relationships",
"."
] | 60c37daf58ec3b1c4bba637889949523a69b8a73 | https://github.com/briancappello/py-yaml-fixtures/blob/60c37daf58ec3b1c4bba637889949523a69b8a73/py_yaml_fixtures/fixtures_loader.py#L166-L196 | train | 48,029 |
briancappello/py-yaml-fixtures | py_yaml_fixtures/fixtures_loader.py | FixturesLoader._ensure_env | def _ensure_env(self, env: Union[jinja2.Environment, None]):
"""
Make sure the jinja environment is minimally configured.
"""
if not env:
env = jinja2.Environment()
if not env.loader:
env.loader = jinja2.FunctionLoader(lambda filename: self._cache[filename])
if 'faker' not in env.globals:
faker = Faker()
faker.seed(1234)
env.globals['faker'] = faker
if 'random_model' not in env.globals:
env.globals['random_model'] = jinja2.contextfunction(random_model)
if 'random_models' not in env.globals:
env.globals['random_models'] = jinja2.contextfunction(random_models)
return env | python | def _ensure_env(self, env: Union[jinja2.Environment, None]):
"""
Make sure the jinja environment is minimally configured.
"""
if not env:
env = jinja2.Environment()
if not env.loader:
env.loader = jinja2.FunctionLoader(lambda filename: self._cache[filename])
if 'faker' not in env.globals:
faker = Faker()
faker.seed(1234)
env.globals['faker'] = faker
if 'random_model' not in env.globals:
env.globals['random_model'] = jinja2.contextfunction(random_model)
if 'random_models' not in env.globals:
env.globals['random_models'] = jinja2.contextfunction(random_models)
return env | [
"def",
"_ensure_env",
"(",
"self",
",",
"env",
":",
"Union",
"[",
"jinja2",
".",
"Environment",
",",
"None",
"]",
")",
":",
"if",
"not",
"env",
":",
"env",
"=",
"jinja2",
".",
"Environment",
"(",
")",
"if",
"not",
"env",
".",
"loader",
":",
"env",
... | Make sure the jinja environment is minimally configured. | [
"Make",
"sure",
"the",
"jinja",
"environment",
"is",
"minimally",
"configured",
"."
] | 60c37daf58ec3b1c4bba637889949523a69b8a73 | https://github.com/briancappello/py-yaml-fixtures/blob/60c37daf58ec3b1c4bba637889949523a69b8a73/py_yaml_fixtures/fixtures_loader.py#L198-L214 | train | 48,030 |
briancappello/py-yaml-fixtures | py_yaml_fixtures/fixtures_loader.py | FixturesLoader._preloading_env | def _preloading_env(self):
"""
A "stripped" jinja environment.
"""
ctx = self.env.globals
try:
ctx['random_model'] = lambda *a, **kw: None
ctx['random_models'] = lambda *a, **kw: None
yield self.env
finally:
ctx['random_model'] = jinja2.contextfunction(random_model)
ctx['random_models'] = jinja2.contextfunction(random_models) | python | def _preloading_env(self):
"""
A "stripped" jinja environment.
"""
ctx = self.env.globals
try:
ctx['random_model'] = lambda *a, **kw: None
ctx['random_models'] = lambda *a, **kw: None
yield self.env
finally:
ctx['random_model'] = jinja2.contextfunction(random_model)
ctx['random_models'] = jinja2.contextfunction(random_models) | [
"def",
"_preloading_env",
"(",
"self",
")",
":",
"ctx",
"=",
"self",
".",
"env",
".",
"globals",
"try",
":",
"ctx",
"[",
"'random_model'",
"]",
"=",
"lambda",
"*",
"a",
",",
"*",
"*",
"kw",
":",
"None",
"ctx",
"[",
"'random_models'",
"]",
"=",
"lam... | A "stripped" jinja environment. | [
"A",
"stripped",
"jinja",
"environment",
"."
] | 60c37daf58ec3b1c4bba637889949523a69b8a73 | https://github.com/briancappello/py-yaml-fixtures/blob/60c37daf58ec3b1c4bba637889949523a69b8a73/py_yaml_fixtures/fixtures_loader.py#L217-L228 | train | 48,031 |
Accelize/pycosio | pycosio/_core/storage_manager.py | get_instance | def get_instance(name, cls='system', storage=None, storage_parameters=None,
unsecure=None, *args, **kwargs):
"""
Get a cloud object storage instance.
Args:
name (str): File name, path or URL.
cls (str): Type of class to instantiate.
'raw', 'buffered' or 'system'.
storage (str): Storage name.
storage_parameters (dict): Storage configuration parameters.
Generally, client configuration and credentials.
unsecure (bool): If True, disables TLS/SSL to improves
transfer performance. But makes connection unsecure.
Default to False.
args, kwargs: Instance arguments
Returns:
pycosio._core.io_base.ObjectIOBase subclass: Instance
"""
system_parameters = _system_parameters(
unsecure=unsecure, storage_parameters=storage_parameters)
# Gets storage information
with _MOUNT_LOCK:
for root in MOUNTED:
if ((isinstance(root, Pattern) and root.match(name)) or
(not isinstance(root, Pattern) and
name.startswith(root))):
info = MOUNTED[root]
# Get stored storage parameters
stored_parameters = info.get('system_parameters') or dict()
if not system_parameters:
same_parameters = True
system_parameters = stored_parameters
elif system_parameters == stored_parameters:
same_parameters = True
else:
same_parameters = False
# Copy not specified parameters from default
system_parameters.update({
key: value for key, value in stored_parameters.items()
if key not in system_parameters})
break
# If not found, tries to mount before getting
else:
mount_info = mount(
storage=storage, name=name, **system_parameters)
info = mount_info[tuple(mount_info)[0]]
same_parameters = True
# Returns system class
if cls == 'system':
if same_parameters:
return info['system_cached']
else:
return info['system'](
roots=info['roots'], **system_parameters)
# Returns other classes
if same_parameters:
if 'storage_parameters' not in system_parameters:
system_parameters['storage_parameters'] = dict()
system_parameters['storage_parameters'][
'pycosio.system_cached'] = info['system_cached']
kwargs.update(system_parameters)
return info[cls](name=name, *args, **kwargs) | python | def get_instance(name, cls='system', storage=None, storage_parameters=None,
unsecure=None, *args, **kwargs):
"""
Get a cloud object storage instance.
Args:
name (str): File name, path or URL.
cls (str): Type of class to instantiate.
'raw', 'buffered' or 'system'.
storage (str): Storage name.
storage_parameters (dict): Storage configuration parameters.
Generally, client configuration and credentials.
unsecure (bool): If True, disables TLS/SSL to improves
transfer performance. But makes connection unsecure.
Default to False.
args, kwargs: Instance arguments
Returns:
pycosio._core.io_base.ObjectIOBase subclass: Instance
"""
system_parameters = _system_parameters(
unsecure=unsecure, storage_parameters=storage_parameters)
# Gets storage information
with _MOUNT_LOCK:
for root in MOUNTED:
if ((isinstance(root, Pattern) and root.match(name)) or
(not isinstance(root, Pattern) and
name.startswith(root))):
info = MOUNTED[root]
# Get stored storage parameters
stored_parameters = info.get('system_parameters') or dict()
if not system_parameters:
same_parameters = True
system_parameters = stored_parameters
elif system_parameters == stored_parameters:
same_parameters = True
else:
same_parameters = False
# Copy not specified parameters from default
system_parameters.update({
key: value for key, value in stored_parameters.items()
if key not in system_parameters})
break
# If not found, tries to mount before getting
else:
mount_info = mount(
storage=storage, name=name, **system_parameters)
info = mount_info[tuple(mount_info)[0]]
same_parameters = True
# Returns system class
if cls == 'system':
if same_parameters:
return info['system_cached']
else:
return info['system'](
roots=info['roots'], **system_parameters)
# Returns other classes
if same_parameters:
if 'storage_parameters' not in system_parameters:
system_parameters['storage_parameters'] = dict()
system_parameters['storage_parameters'][
'pycosio.system_cached'] = info['system_cached']
kwargs.update(system_parameters)
return info[cls](name=name, *args, **kwargs) | [
"def",
"get_instance",
"(",
"name",
",",
"cls",
"=",
"'system'",
",",
"storage",
"=",
"None",
",",
"storage_parameters",
"=",
"None",
",",
"unsecure",
"=",
"None",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"system_parameters",
"=",
"_system_pa... | Get a cloud object storage instance.
Args:
name (str): File name, path or URL.
cls (str): Type of class to instantiate.
'raw', 'buffered' or 'system'.
storage (str): Storage name.
storage_parameters (dict): Storage configuration parameters.
Generally, client configuration and credentials.
unsecure (bool): If True, disables TLS/SSL to improves
transfer performance. But makes connection unsecure.
Default to False.
args, kwargs: Instance arguments
Returns:
pycosio._core.io_base.ObjectIOBase subclass: Instance | [
"Get",
"a",
"cloud",
"object",
"storage",
"instance",
"."
] | 1cc1f8fdf5394d92918b7bae2bfa682169ccc48c | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/_core/storage_manager.py#L30-L99 | train | 48,032 |
Accelize/pycosio | pycosio/_core/storage_manager.py | mount | def mount(storage=None, name='', storage_parameters=None,
unsecure=None, extra_root=None):
"""
Mount a new storage.
Args:
storage (str): Storage name.
name (str): File URL. If storage is not specified,
URL scheme will be used as storage value.
storage_parameters (dict): Storage configuration parameters.
Generally, client configuration and credentials.
unsecure (bool): If True, disables TLS/SSL to improves
transfer performance. But makes connection unsecure.
Default to False.
extra_root (str): Extra root that can be used in
replacement of root in path. This can be used to
provides support for shorter URLS.
Example: with root "https://www.mycloud.com/user"
and extra_root "mycloud://" it is possible to access object
using "mycloud://container/object" instead of
"https://www.mycloud.com/user/container/object".
Returns:
dict: keys are mounted storage, values are dicts of storage information.
"""
# Tries to infer storage from name
if storage is None:
if '://' in name:
storage = name.split('://', 1)[0].lower()
# Alias HTTPS to HTTP
storage = 'http' if storage == 'https' else storage
else:
raise ValueError(
'No storage specified and unable to infer it from file name.')
# Saves get_storage_parameters
system_parameters = _system_parameters(
unsecure=unsecure, storage_parameters=storage_parameters)
storage_info = dict(storage=storage, system_parameters=system_parameters)
# Finds module containing target subclass
for package in STORAGE_PACKAGE:
try:
module = import_module('%s.%s' % (package, storage))
break
except ImportError:
continue
else:
raise ImportError('No storage named "%s" found' % storage)
# Case module is a mount redirection to mount multiple storage at once
if hasattr(module, 'MOUNT_REDIRECT'):
if extra_root:
raise ValueError(
("Can't define extra_root with %s. "
"%s can't have a common root.") % (
storage, ', '.join(extra_root)))
result = dict()
for storage in getattr(module, 'MOUNT_REDIRECT'):
result[storage] = mount(
storage=storage, storage_parameters=storage_parameters,
unsecure=unsecure)
return result
# Finds storage subclass
classes_items = tuple(_BASE_CLASSES.items())
for member_name in dir(module):
member = getattr(module, member_name)
for cls_name, cls in classes_items:
# Skip if not subclass of the target class
try:
if not issubclass(member, cls) or member is cls:
continue
except TypeError:
continue
# The class may have been flag as default or not-default
default_flag = '_%s__DEFAULT_CLASS' % member.__name__.strip('_')
try:
is_default = getattr(member, default_flag)
except AttributeError:
is_default = None
# Skip if explicitly flagged as non default
if is_default is False:
continue
# Skip if is an abstract class not explicitly flagged as default
elif is_default is not True and member.__abstractmethods__:
continue
# Is the default class
storage_info[cls_name] = member
break
# Caches a system instance
storage_info['system_cached'] = storage_info['system'](**system_parameters)
# Gets roots
roots = storage_info['system_cached'].roots
# Adds extra root
if extra_root:
roots = list(roots)
roots.append(extra_root)
roots = tuple(roots)
storage_info['system_cached'].roots = storage_info['roots'] = roots
# Mounts
with _MOUNT_LOCK:
for root in roots:
MOUNTED[root] = storage_info
# Reorder to have correct lookup
items = OrderedDict(
(key, MOUNTED[key]) for key in reversed(
sorted(MOUNTED, key=_compare_root)))
MOUNTED.clear()
MOUNTED.update(items)
return {storage: storage_info} | python | def mount(storage=None, name='', storage_parameters=None,
unsecure=None, extra_root=None):
"""
Mount a new storage.
Args:
storage (str): Storage name.
name (str): File URL. If storage is not specified,
URL scheme will be used as storage value.
storage_parameters (dict): Storage configuration parameters.
Generally, client configuration and credentials.
unsecure (bool): If True, disables TLS/SSL to improves
transfer performance. But makes connection unsecure.
Default to False.
extra_root (str): Extra root that can be used in
replacement of root in path. This can be used to
provides support for shorter URLS.
Example: with root "https://www.mycloud.com/user"
and extra_root "mycloud://" it is possible to access object
using "mycloud://container/object" instead of
"https://www.mycloud.com/user/container/object".
Returns:
dict: keys are mounted storage, values are dicts of storage information.
"""
# Tries to infer storage from name
if storage is None:
if '://' in name:
storage = name.split('://', 1)[0].lower()
# Alias HTTPS to HTTP
storage = 'http' if storage == 'https' else storage
else:
raise ValueError(
'No storage specified and unable to infer it from file name.')
# Saves get_storage_parameters
system_parameters = _system_parameters(
unsecure=unsecure, storage_parameters=storage_parameters)
storage_info = dict(storage=storage, system_parameters=system_parameters)
# Finds module containing target subclass
for package in STORAGE_PACKAGE:
try:
module = import_module('%s.%s' % (package, storage))
break
except ImportError:
continue
else:
raise ImportError('No storage named "%s" found' % storage)
# Case module is a mount redirection to mount multiple storage at once
if hasattr(module, 'MOUNT_REDIRECT'):
if extra_root:
raise ValueError(
("Can't define extra_root with %s. "
"%s can't have a common root.") % (
storage, ', '.join(extra_root)))
result = dict()
for storage in getattr(module, 'MOUNT_REDIRECT'):
result[storage] = mount(
storage=storage, storage_parameters=storage_parameters,
unsecure=unsecure)
return result
# Finds storage subclass
classes_items = tuple(_BASE_CLASSES.items())
for member_name in dir(module):
member = getattr(module, member_name)
for cls_name, cls in classes_items:
# Skip if not subclass of the target class
try:
if not issubclass(member, cls) or member is cls:
continue
except TypeError:
continue
# The class may have been flag as default or not-default
default_flag = '_%s__DEFAULT_CLASS' % member.__name__.strip('_')
try:
is_default = getattr(member, default_flag)
except AttributeError:
is_default = None
# Skip if explicitly flagged as non default
if is_default is False:
continue
# Skip if is an abstract class not explicitly flagged as default
elif is_default is not True and member.__abstractmethods__:
continue
# Is the default class
storage_info[cls_name] = member
break
# Caches a system instance
storage_info['system_cached'] = storage_info['system'](**system_parameters)
# Gets roots
roots = storage_info['system_cached'].roots
# Adds extra root
if extra_root:
roots = list(roots)
roots.append(extra_root)
roots = tuple(roots)
storage_info['system_cached'].roots = storage_info['roots'] = roots
# Mounts
with _MOUNT_LOCK:
for root in roots:
MOUNTED[root] = storage_info
# Reorder to have correct lookup
items = OrderedDict(
(key, MOUNTED[key]) for key in reversed(
sorted(MOUNTED, key=_compare_root)))
MOUNTED.clear()
MOUNTED.update(items)
return {storage: storage_info} | [
"def",
"mount",
"(",
"storage",
"=",
"None",
",",
"name",
"=",
"''",
",",
"storage_parameters",
"=",
"None",
",",
"unsecure",
"=",
"None",
",",
"extra_root",
"=",
"None",
")",
":",
"# Tries to infer storage from name",
"if",
"storage",
"is",
"None",
":",
"... | Mount a new storage.
Args:
storage (str): Storage name.
name (str): File URL. If storage is not specified,
URL scheme will be used as storage value.
storage_parameters (dict): Storage configuration parameters.
Generally, client configuration and credentials.
unsecure (bool): If True, disables TLS/SSL to improves
transfer performance. But makes connection unsecure.
Default to False.
extra_root (str): Extra root that can be used in
replacement of root in path. This can be used to
provides support for shorter URLS.
Example: with root "https://www.mycloud.com/user"
and extra_root "mycloud://" it is possible to access object
using "mycloud://container/object" instead of
"https://www.mycloud.com/user/container/object".
Returns:
dict: keys are mounted storage, values are dicts of storage information. | [
"Mount",
"a",
"new",
"storage",
"."
] | 1cc1f8fdf5394d92918b7bae2bfa682169ccc48c | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/_core/storage_manager.py#L102-L223 | train | 48,033 |
Accelize/pycosio | pycosio/_core/storage_manager.py | _system_parameters | def _system_parameters(**kwargs):
"""
Returns system keyword arguments removing Nones.
Args:
kwargs: system keyword arguments.
Returns:
dict: system keyword arguments.
"""
return {key: value for key, value in kwargs.items()
if (value is not None or value == {})} | python | def _system_parameters(**kwargs):
"""
Returns system keyword arguments removing Nones.
Args:
kwargs: system keyword arguments.
Returns:
dict: system keyword arguments.
"""
return {key: value for key, value in kwargs.items()
if (value is not None or value == {})} | [
"def",
"_system_parameters",
"(",
"*",
"*",
"kwargs",
")",
":",
"return",
"{",
"key",
":",
"value",
"for",
"key",
",",
"value",
"in",
"kwargs",
".",
"items",
"(",
")",
"if",
"(",
"value",
"is",
"not",
"None",
"or",
"value",
"==",
"{",
"}",
")",
"... | Returns system keyword arguments removing Nones.
Args:
kwargs: system keyword arguments.
Returns:
dict: system keyword arguments. | [
"Returns",
"system",
"keyword",
"arguments",
"removing",
"Nones",
"."
] | 1cc1f8fdf5394d92918b7bae2bfa682169ccc48c | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/_core/storage_manager.py#L226-L237 | train | 48,034 |
asottile/pymonkey | pymonkey.py | manual_argument_parsing | def manual_argument_parsing(argv):
"""sadness because argparse doesn't quite do what we want."""
# Special case these for a better error message
if not argv or argv == ['-h'] or argv == ['--help']:
print_help_and_exit()
try:
dashdash_index = argv.index('--')
except ValueError:
print_std_err('Must separate command by `--`')
print_help_and_exit()
patches, cmd = argv[:dashdash_index], argv[dashdash_index + 1:]
if '--help' in patches or '-h' in patches:
print_help_and_exit()
if '--all' in patches:
all_patches = True
patches.remove('--all')
else:
all_patches = False
unknown_options = [patch for patch in patches if patch.startswith('-')]
if unknown_options:
print_std_err('Unknown options: {!r}'.format(unknown_options))
print_help_and_exit()
if patches and all_patches:
print_std_err('--all and patches specified: {!r}'.format(patches))
print_help_and_exit()
return Arguments(all=all_patches, patches=tuple(patches), cmd=tuple(cmd)) | python | def manual_argument_parsing(argv):
"""sadness because argparse doesn't quite do what we want."""
# Special case these for a better error message
if not argv or argv == ['-h'] or argv == ['--help']:
print_help_and_exit()
try:
dashdash_index = argv.index('--')
except ValueError:
print_std_err('Must separate command by `--`')
print_help_and_exit()
patches, cmd = argv[:dashdash_index], argv[dashdash_index + 1:]
if '--help' in patches or '-h' in patches:
print_help_and_exit()
if '--all' in patches:
all_patches = True
patches.remove('--all')
else:
all_patches = False
unknown_options = [patch for patch in patches if patch.startswith('-')]
if unknown_options:
print_std_err('Unknown options: {!r}'.format(unknown_options))
print_help_and_exit()
if patches and all_patches:
print_std_err('--all and patches specified: {!r}'.format(patches))
print_help_and_exit()
return Arguments(all=all_patches, patches=tuple(patches), cmd=tuple(cmd)) | [
"def",
"manual_argument_parsing",
"(",
"argv",
")",
":",
"# Special case these for a better error message",
"if",
"not",
"argv",
"or",
"argv",
"==",
"[",
"'-h'",
"]",
"or",
"argv",
"==",
"[",
"'--help'",
"]",
":",
"print_help_and_exit",
"(",
")",
"try",
":",
"... | sadness because argparse doesn't quite do what we want. | [
"sadness",
"because",
"argparse",
"doesn",
"t",
"quite",
"do",
"what",
"we",
"want",
"."
] | f2e55590c7064019e928eddc41dad5d288722ce6 | https://github.com/asottile/pymonkey/blob/f2e55590c7064019e928eddc41dad5d288722ce6/pymonkey.py#L57-L90 | train | 48,035 |
Accelize/pycosio | pycosio/_core/io_base_system.py | SystemBase.exists | def exists(self, path=None, client_kwargs=None, assume_exists=None):
"""
Return True if path refers to an existing path.
Args:
path (str): Path or URL.
client_kwargs (dict): Client arguments.
assume_exists (bool or None): This value define the value to return
in the case there is no enough permission to determinate the
existing status of the file. If set to None, the permission
exception is reraised (Default behavior). if set to True or
False, return this value.
Returns:
bool: True if exists.
"""
try:
self.head(path, client_kwargs)
except ObjectNotFoundError:
return False
except ObjectPermissionError:
if assume_exists is None:
raise
return assume_exists
return True | python | def exists(self, path=None, client_kwargs=None, assume_exists=None):
"""
Return True if path refers to an existing path.
Args:
path (str): Path or URL.
client_kwargs (dict): Client arguments.
assume_exists (bool or None): This value define the value to return
in the case there is no enough permission to determinate the
existing status of the file. If set to None, the permission
exception is reraised (Default behavior). if set to True or
False, return this value.
Returns:
bool: True if exists.
"""
try:
self.head(path, client_kwargs)
except ObjectNotFoundError:
return False
except ObjectPermissionError:
if assume_exists is None:
raise
return assume_exists
return True | [
"def",
"exists",
"(",
"self",
",",
"path",
"=",
"None",
",",
"client_kwargs",
"=",
"None",
",",
"assume_exists",
"=",
"None",
")",
":",
"try",
":",
"self",
".",
"head",
"(",
"path",
",",
"client_kwargs",
")",
"except",
"ObjectNotFoundError",
":",
"return... | Return True if path refers to an existing path.
Args:
path (str): Path or URL.
client_kwargs (dict): Client arguments.
assume_exists (bool or None): This value define the value to return
in the case there is no enough permission to determinate the
existing status of the file. If set to None, the permission
exception is reraised (Default behavior). if set to True or
False, return this value.
Returns:
bool: True if exists. | [
"Return",
"True",
"if",
"path",
"refers",
"to",
"an",
"existing",
"path",
"."
] | 1cc1f8fdf5394d92918b7bae2bfa682169ccc48c | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/_core/io_base_system.py#L123-L147 | train | 48,036 |
Accelize/pycosio | pycosio/_core/io_base_system.py | SystemBase.getctime | def getctime(self, path=None, client_kwargs=None, header=None):
"""
Return the creation time of path.
Args:
path (str): File path or URL.
client_kwargs (dict): Client arguments.
header (dict): Object header.
Returns:
float: The number of seconds since the epoch
(see the time module).
"""
return self._getctime_from_header(
self.head(path, client_kwargs, header)) | python | def getctime(self, path=None, client_kwargs=None, header=None):
"""
Return the creation time of path.
Args:
path (str): File path or URL.
client_kwargs (dict): Client arguments.
header (dict): Object header.
Returns:
float: The number of seconds since the epoch
(see the time module).
"""
return self._getctime_from_header(
self.head(path, client_kwargs, header)) | [
"def",
"getctime",
"(",
"self",
",",
"path",
"=",
"None",
",",
"client_kwargs",
"=",
"None",
",",
"header",
"=",
"None",
")",
":",
"return",
"self",
".",
"_getctime_from_header",
"(",
"self",
".",
"head",
"(",
"path",
",",
"client_kwargs",
",",
"header",... | Return the creation time of path.
Args:
path (str): File path or URL.
client_kwargs (dict): Client arguments.
header (dict): Object header.
Returns:
float: The number of seconds since the epoch
(see the time module). | [
"Return",
"the",
"creation",
"time",
"of",
"path",
"."
] | 1cc1f8fdf5394d92918b7bae2bfa682169ccc48c | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/_core/io_base_system.py#L171-L185 | train | 48,037 |
Accelize/pycosio | pycosio/_core/io_base_system.py | SystemBase.getmtime | def getmtime(self, path=None, client_kwargs=None, header=None):
"""
Return the time of last access of path.
Args:
path (str): File path or URL.
client_kwargs (dict): Client arguments.
header (dict): Object header.
Returns:
float: The number of seconds since the epoch
(see the time module).
"""
return self._getmtime_from_header(
self.head(path, client_kwargs, header)) | python | def getmtime(self, path=None, client_kwargs=None, header=None):
"""
Return the time of last access of path.
Args:
path (str): File path or URL.
client_kwargs (dict): Client arguments.
header (dict): Object header.
Returns:
float: The number of seconds since the epoch
(see the time module).
"""
return self._getmtime_from_header(
self.head(path, client_kwargs, header)) | [
"def",
"getmtime",
"(",
"self",
",",
"path",
"=",
"None",
",",
"client_kwargs",
"=",
"None",
",",
"header",
"=",
"None",
")",
":",
"return",
"self",
".",
"_getmtime_from_header",
"(",
"self",
".",
"head",
"(",
"path",
",",
"client_kwargs",
",",
"header",... | Return the time of last access of path.
Args:
path (str): File path or URL.
client_kwargs (dict): Client arguments.
header (dict): Object header.
Returns:
float: The number of seconds since the epoch
(see the time module). | [
"Return",
"the",
"time",
"of",
"last",
"access",
"of",
"path",
"."
] | 1cc1f8fdf5394d92918b7bae2bfa682169ccc48c | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/_core/io_base_system.py#L199-L213 | train | 48,038 |
Accelize/pycosio | pycosio/_core/io_base_system.py | SystemBase.getsize | def getsize(self, path=None, client_kwargs=None, header=None):
"""
Return the size, in bytes, of path.
Args:
path (str): File path or URL.
client_kwargs (dict): Client arguments.
header (dict): Object header.
Returns:
int: Size in bytes.
"""
return self._getsize_from_header(self.head(path, client_kwargs, header)) | python | def getsize(self, path=None, client_kwargs=None, header=None):
"""
Return the size, in bytes, of path.
Args:
path (str): File path or URL.
client_kwargs (dict): Client arguments.
header (dict): Object header.
Returns:
int: Size in bytes.
"""
return self._getsize_from_header(self.head(path, client_kwargs, header)) | [
"def",
"getsize",
"(",
"self",
",",
"path",
"=",
"None",
",",
"client_kwargs",
"=",
"None",
",",
"header",
"=",
"None",
")",
":",
"return",
"self",
".",
"_getsize_from_header",
"(",
"self",
".",
"head",
"(",
"path",
",",
"client_kwargs",
",",
"header",
... | Return the size, in bytes, of path.
Args:
path (str): File path or URL.
client_kwargs (dict): Client arguments.
header (dict): Object header.
Returns:
int: Size in bytes. | [
"Return",
"the",
"size",
"in",
"bytes",
"of",
"path",
"."
] | 1cc1f8fdf5394d92918b7bae2bfa682169ccc48c | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/_core/io_base_system.py#L262-L274 | train | 48,039 |
Accelize/pycosio | pycosio/_core/io_base_system.py | SystemBase._getsize_from_header | def _getsize_from_header(self, header):
"""
Return the size from header
Args:
header (dict): Object header.
Returns:
int: Size in bytes.
"""
# By default, assumes that information are in a standard HTTP header
for key in self._SIZE_KEYS:
try:
return int(header.pop(key))
except KeyError:
continue
else:
raise UnsupportedOperation('getsize') | python | def _getsize_from_header(self, header):
"""
Return the size from header
Args:
header (dict): Object header.
Returns:
int: Size in bytes.
"""
# By default, assumes that information are in a standard HTTP header
for key in self._SIZE_KEYS:
try:
return int(header.pop(key))
except KeyError:
continue
else:
raise UnsupportedOperation('getsize') | [
"def",
"_getsize_from_header",
"(",
"self",
",",
"header",
")",
":",
"# By default, assumes that information are in a standard HTTP header",
"for",
"key",
"in",
"self",
".",
"_SIZE_KEYS",
":",
"try",
":",
"return",
"int",
"(",
"header",
".",
"pop",
"(",
"key",
")"... | Return the size from header
Args:
header (dict): Object header.
Returns:
int: Size in bytes. | [
"Return",
"the",
"size",
"from",
"header"
] | 1cc1f8fdf5394d92918b7bae2bfa682169ccc48c | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/_core/io_base_system.py#L276-L293 | train | 48,040 |
Accelize/pycosio | pycosio/_core/io_base_system.py | SystemBase.isfile | def isfile(self, path=None, client_kwargs=None, assume_exists=None):
"""
Return True if path is an existing regular file.
Args:
path (str): Path or URL.
client_kwargs (dict): Client arguments.
assume_exists (bool or None): This value define the value to return
in the case there is no enough permission to determinate the
existing status of the file. If set to None, the permission
exception is reraised (Default behavior). if set to True or
False, return this value.
Returns:
bool: True if file exists.
"""
relative = self.relpath(path)
if not relative:
# Root always exists and is a directory
return False
if path[-1] != '/' and not self.is_locator(path, relative=True):
return self.exists(path=path, client_kwargs=client_kwargs,
assume_exists=assume_exists)
return False | python | def isfile(self, path=None, client_kwargs=None, assume_exists=None):
"""
Return True if path is an existing regular file.
Args:
path (str): Path or URL.
client_kwargs (dict): Client arguments.
assume_exists (bool or None): This value define the value to return
in the case there is no enough permission to determinate the
existing status of the file. If set to None, the permission
exception is reraised (Default behavior). if set to True or
False, return this value.
Returns:
bool: True if file exists.
"""
relative = self.relpath(path)
if not relative:
# Root always exists and is a directory
return False
if path[-1] != '/' and not self.is_locator(path, relative=True):
return self.exists(path=path, client_kwargs=client_kwargs,
assume_exists=assume_exists)
return False | [
"def",
"isfile",
"(",
"self",
",",
"path",
"=",
"None",
",",
"client_kwargs",
"=",
"None",
",",
"assume_exists",
"=",
"None",
")",
":",
"relative",
"=",
"self",
".",
"relpath",
"(",
"path",
")",
"if",
"not",
"relative",
":",
"# Root always exists and is a ... | Return True if path is an existing regular file.
Args:
path (str): Path or URL.
client_kwargs (dict): Client arguments.
assume_exists (bool or None): This value define the value to return
in the case there is no enough permission to determinate the
existing status of the file. If set to None, the permission
exception is reraised (Default behavior). if set to True or
False, return this value.
Returns:
bool: True if file exists. | [
"Return",
"True",
"if",
"path",
"is",
"an",
"existing",
"regular",
"file",
"."
] | 1cc1f8fdf5394d92918b7bae2bfa682169ccc48c | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/_core/io_base_system.py#L337-L361 | train | 48,041 |
Accelize/pycosio | pycosio/_core/io_base_system.py | SystemBase.relpath | def relpath(self, path):
"""
Get path relative to storage.
args:
path (str): Absolute path or URL.
Returns:
str: relative path.
"""
for root in self.roots:
# Root is regex, convert to matching root string
if isinstance(root, Pattern):
match = root.match(path)
if not match:
continue
root = match.group(0)
# Split root and relative path
try:
relative = path.split(root, 1)[1]
# Strip "/" only at path start. "/" is used to known if
# path is a directory on some cloud storage.
return relative.lstrip('/')
except IndexError:
continue
return path | python | def relpath(self, path):
"""
Get path relative to storage.
args:
path (str): Absolute path or URL.
Returns:
str: relative path.
"""
for root in self.roots:
# Root is regex, convert to matching root string
if isinstance(root, Pattern):
match = root.match(path)
if not match:
continue
root = match.group(0)
# Split root and relative path
try:
relative = path.split(root, 1)[1]
# Strip "/" only at path start. "/" is used to known if
# path is a directory on some cloud storage.
return relative.lstrip('/')
except IndexError:
continue
return path | [
"def",
"relpath",
"(",
"self",
",",
"path",
")",
":",
"for",
"root",
"in",
"self",
".",
"roots",
":",
"# Root is regex, convert to matching root string",
"if",
"isinstance",
"(",
"root",
",",
"Pattern",
")",
":",
"match",
"=",
"root",
".",
"match",
"(",
"p... | Get path relative to storage.
args:
path (str): Absolute path or URL.
Returns:
str: relative path. | [
"Get",
"path",
"relative",
"to",
"storage",
"."
] | 1cc1f8fdf5394d92918b7bae2bfa682169ccc48c | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/_core/io_base_system.py#L423-L450 | train | 48,042 |
Accelize/pycosio | pycosio/_core/io_base_system.py | SystemBase.is_locator | def is_locator(self, path, relative=False):
"""
Returns True if path refer to a locator.
Depending the storage, locator may be a bucket or container name,
a hostname, ...
args:
path (str): path or URL.
relative (bool): Path is relative to current root.
Returns:
bool: True if locator.
"""
if not relative:
path = self.relpath(path)
# Bucket is the main directory
return path and '/' not in path.rstrip('/') | python | def is_locator(self, path, relative=False):
"""
Returns True if path refer to a locator.
Depending the storage, locator may be a bucket or container name,
a hostname, ...
args:
path (str): path or URL.
relative (bool): Path is relative to current root.
Returns:
bool: True if locator.
"""
if not relative:
path = self.relpath(path)
# Bucket is the main directory
return path and '/' not in path.rstrip('/') | [
"def",
"is_locator",
"(",
"self",
",",
"path",
",",
"relative",
"=",
"False",
")",
":",
"if",
"not",
"relative",
":",
"path",
"=",
"self",
".",
"relpath",
"(",
"path",
")",
"# Bucket is the main directory",
"return",
"path",
"and",
"'/'",
"not",
"in",
"p... | Returns True if path refer to a locator.
Depending the storage, locator may be a bucket or container name,
a hostname, ...
args:
path (str): path or URL.
relative (bool): Path is relative to current root.
Returns:
bool: True if locator. | [
"Returns",
"True",
"if",
"path",
"refer",
"to",
"a",
"locator",
"."
] | 1cc1f8fdf5394d92918b7bae2bfa682169ccc48c | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/_core/io_base_system.py#L452-L469 | train | 48,043 |
Accelize/pycosio | pycosio/_core/io_base_system.py | SystemBase.ensure_dir_path | def ensure_dir_path(self, path, relative=False):
"""
Ensure the path is a dir path.
Should end with '/' except for schemes and locators.
Args:
path (str): Path or URL.
relative (bool): Path is relative to current root.
Returns:
path: dir path
"""
if not relative:
rel_path = self.relpath(path)
else:
rel_path = path
# Locator
if self.is_locator(rel_path, relative=True):
path = path.rstrip('/')
# Directory
elif rel_path:
path = path.rstrip('/') + '/'
# else: root
return path | python | def ensure_dir_path(self, path, relative=False):
"""
Ensure the path is a dir path.
Should end with '/' except for schemes and locators.
Args:
path (str): Path or URL.
relative (bool): Path is relative to current root.
Returns:
path: dir path
"""
if not relative:
rel_path = self.relpath(path)
else:
rel_path = path
# Locator
if self.is_locator(rel_path, relative=True):
path = path.rstrip('/')
# Directory
elif rel_path:
path = path.rstrip('/') + '/'
# else: root
return path | [
"def",
"ensure_dir_path",
"(",
"self",
",",
"path",
",",
"relative",
"=",
"False",
")",
":",
"if",
"not",
"relative",
":",
"rel_path",
"=",
"self",
".",
"relpath",
"(",
"path",
")",
"else",
":",
"rel_path",
"=",
"path",
"# Locator",
"if",
"self",
".",
... | Ensure the path is a dir path.
Should end with '/' except for schemes and locators.
Args:
path (str): Path or URL.
relative (bool): Path is relative to current root.
Returns:
path: dir path | [
"Ensure",
"the",
"path",
"is",
"a",
"dir",
"path",
"."
] | 1cc1f8fdf5394d92918b7bae2bfa682169ccc48c | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/_core/io_base_system.py#L532-L558 | train | 48,044 |
Accelize/pycosio | pycosio/_core/io_base_system.py | SystemBase.stat | def stat(self, path=None, client_kwargs=None, header=None):
"""
Get the status of an object.
Args:
path (str): File path or URL.
client_kwargs (dict): Client arguments.
header (dict): Object header.
Returns:
os.stat_result: Stat result object
"""
# Should contain at least the strict minimum of os.stat_result
stat = OrderedDict((
("st_mode", 0), ("st_ino", 0), ("st_dev", 0), ("st_nlink", 0),
("st_uid", 0), ("st_gid", 0), ("st_size", 0), ("st_atime", 0),
("st_mtime", 0), ("st_ctime", 0)))
# Populate standard os.stat_result values with object header content
header = self.head(path, client_kwargs, header)
for key, method in (
('st_size', self._getsize_from_header),
('st_ctime', self._getctime_from_header),
('st_mtime', self._getmtime_from_header),):
try:
stat[key] = int(method(header))
except UnsupportedOperation:
continue
# File mode
if self.islink(path=path, header=header):
# Symlink
stat['st_mode'] = S_IFLNK
elif ((not path or path[-1] == '/' or self.is_locator(path)) and not
stat['st_size']):
# Directory
stat['st_mode'] = S_IFDIR
else:
# File
stat['st_mode'] = S_IFREG
# Add storage specific keys
sub = self._CHAR_FILTER.sub
for key, value in tuple(header.items()):
stat['st_' + sub('', key.lower())] = value
# Convert to "os.stat_result" like object
stat_result = namedtuple('stat_result', tuple(stat))
stat_result.__name__ = 'os.stat_result'
stat_result.__module__ = 'pycosio'
return stat_result(**stat) | python | def stat(self, path=None, client_kwargs=None, header=None):
"""
Get the status of an object.
Args:
path (str): File path or URL.
client_kwargs (dict): Client arguments.
header (dict): Object header.
Returns:
os.stat_result: Stat result object
"""
# Should contain at least the strict minimum of os.stat_result
stat = OrderedDict((
("st_mode", 0), ("st_ino", 0), ("st_dev", 0), ("st_nlink", 0),
("st_uid", 0), ("st_gid", 0), ("st_size", 0), ("st_atime", 0),
("st_mtime", 0), ("st_ctime", 0)))
# Populate standard os.stat_result values with object header content
header = self.head(path, client_kwargs, header)
for key, method in (
('st_size', self._getsize_from_header),
('st_ctime', self._getctime_from_header),
('st_mtime', self._getmtime_from_header),):
try:
stat[key] = int(method(header))
except UnsupportedOperation:
continue
# File mode
if self.islink(path=path, header=header):
# Symlink
stat['st_mode'] = S_IFLNK
elif ((not path or path[-1] == '/' or self.is_locator(path)) and not
stat['st_size']):
# Directory
stat['st_mode'] = S_IFDIR
else:
# File
stat['st_mode'] = S_IFREG
# Add storage specific keys
sub = self._CHAR_FILTER.sub
for key, value in tuple(header.items()):
stat['st_' + sub('', key.lower())] = value
# Convert to "os.stat_result" like object
stat_result = namedtuple('stat_result', tuple(stat))
stat_result.__name__ = 'os.stat_result'
stat_result.__module__ = 'pycosio'
return stat_result(**stat) | [
"def",
"stat",
"(",
"self",
",",
"path",
"=",
"None",
",",
"client_kwargs",
"=",
"None",
",",
"header",
"=",
"None",
")",
":",
"# Should contain at least the strict minimum of os.stat_result",
"stat",
"=",
"OrderedDict",
"(",
"(",
"(",
"\"st_mode\"",
",",
"0",
... | Get the status of an object.
Args:
path (str): File path or URL.
client_kwargs (dict): Client arguments.
header (dict): Object header.
Returns:
os.stat_result: Stat result object | [
"Get",
"the",
"status",
"of",
"an",
"object",
"."
] | 1cc1f8fdf5394d92918b7bae2bfa682169ccc48c | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/_core/io_base_system.py#L718-L768 | train | 48,045 |
fedora-infra/datanommer | datanommer.models/datanommer/models/__init__.py | init | def init(uri=None, alembic_ini=None, engine=None, create=False):
""" Initialize a connection. Create tables if requested."""
if uri and engine:
raise ValueError("uri and engine cannot both be specified")
if uri is None and not engine:
uri = 'sqlite:////tmp/datanommer.db'
log.warning("No db uri given. Using %r" % uri)
if uri and not engine:
engine = create_engine(uri)
if 'sqlite' in engine.driver:
# Enable nested transaction support under SQLite
# See https://stackoverflow.com/questions/1654857/nested-transactions-with-sqlalchemy-and-sqlite
@event.listens_for(engine, "connect")
def do_connect(dbapi_connection, connection_record):
# disable pysqlite's emitting of the BEGIN statement entirely.
# also stops it from emitting COMMIT before any DDL.
dbapi_connection.isolation_level = None
@event.listens_for(engine, "begin")
def do_begin(conn):
# emit our own BEGIN
conn.execute("BEGIN")
# We need to hang our own attribute on the sqlalchemy session to stop
# ourselves from initializing twice. That is only a problem is the code
# calling us isn't consistent.
if getattr(session, '_datanommer_initialized', None):
log.warning("Session already initialized. Bailing")
return
session._datanommer_initialized = True
session.configure(bind=engine)
DeclarativeBase.query = session.query_property()
# Loads the alembic configuration and generates the version table, with
# the most recent revision stamped as head
if alembic_ini is not None:
from alembic.config import Config
from alembic import command
alembic_cfg = Config(alembic_ini)
command.stamp(alembic_cfg, "head")
if create:
DeclarativeBase.metadata.create_all(engine) | python | def init(uri=None, alembic_ini=None, engine=None, create=False):
""" Initialize a connection. Create tables if requested."""
if uri and engine:
raise ValueError("uri and engine cannot both be specified")
if uri is None and not engine:
uri = 'sqlite:////tmp/datanommer.db'
log.warning("No db uri given. Using %r" % uri)
if uri and not engine:
engine = create_engine(uri)
if 'sqlite' in engine.driver:
# Enable nested transaction support under SQLite
# See https://stackoverflow.com/questions/1654857/nested-transactions-with-sqlalchemy-and-sqlite
@event.listens_for(engine, "connect")
def do_connect(dbapi_connection, connection_record):
# disable pysqlite's emitting of the BEGIN statement entirely.
# also stops it from emitting COMMIT before any DDL.
dbapi_connection.isolation_level = None
@event.listens_for(engine, "begin")
def do_begin(conn):
# emit our own BEGIN
conn.execute("BEGIN")
# We need to hang our own attribute on the sqlalchemy session to stop
# ourselves from initializing twice. That is only a problem is the code
# calling us isn't consistent.
if getattr(session, '_datanommer_initialized', None):
log.warning("Session already initialized. Bailing")
return
session._datanommer_initialized = True
session.configure(bind=engine)
DeclarativeBase.query = session.query_property()
# Loads the alembic configuration and generates the version table, with
# the most recent revision stamped as head
if alembic_ini is not None:
from alembic.config import Config
from alembic import command
alembic_cfg = Config(alembic_ini)
command.stamp(alembic_cfg, "head")
if create:
DeclarativeBase.metadata.create_all(engine) | [
"def",
"init",
"(",
"uri",
"=",
"None",
",",
"alembic_ini",
"=",
"None",
",",
"engine",
"=",
"None",
",",
"create",
"=",
"False",
")",
":",
"if",
"uri",
"and",
"engine",
":",
"raise",
"ValueError",
"(",
"\"uri and engine cannot both be specified\"",
")",
"... | Initialize a connection. Create tables if requested. | [
"Initialize",
"a",
"connection",
".",
"Create",
"tables",
"if",
"requested",
"."
] | 4a20e216bb404b14f76c7065518fd081e989764d | https://github.com/fedora-infra/datanommer/blob/4a20e216bb404b14f76c7065518fd081e989764d/datanommer.models/datanommer/models/__init__.py#L65-L112 | train | 48,046 |
fedora-infra/datanommer | datanommer.models/datanommer/models/__init__.py | add | def add(envelope):
""" Take a dict-like fedmsg envelope and store the headers and message
in the table.
"""
message = envelope['body']
timestamp = message.get('timestamp', None)
try:
if timestamp:
timestamp = datetime.datetime.utcfromtimestamp(timestamp)
else:
timestamp = datetime.datetime.utcnow()
except Exception:
pass
headers = envelope.get('headers', None)
msg_id = message.get('msg_id', None)
if not msg_id and headers:
msg_id = headers.get('message-id', None)
if not msg_id:
msg_id = six.text_type(timestamp.year) + six.u('-') + six.text_type(uuid.uuid4())
obj = Message(
i=message.get('i', 0),
msg_id=msg_id,
topic=message['topic'],
timestamp=timestamp,
username=message.get('username', None),
crypto=message.get('crypto', None),
certificate=message.get('certificate', None),
signature=message.get('signature', None),
)
obj.msg = message['msg']
obj.headers = headers
try:
session.add(obj)
session.flush()
except IntegrityError:
log.warning('Skipping message from %s with duplicate id: %s',
message['topic'], msg_id)
session.rollback()
return
usernames = fedmsg.meta.msg2usernames(message)
packages = fedmsg.meta.msg2packages(message)
# Do a little sanity checking on fedmsg.meta results
if None in usernames:
# Notify developers so they can fix msg2usernames
log.error('NoneType found in usernames of %r' % msg_id)
# And prune out the bad value
usernames = [name for name in usernames if name is not None]
if None in packages:
# Notify developers so they can fix msg2packages
log.error('NoneType found in packages of %r' % msg_id)
# And prune out the bad value
packages = [pkg for pkg in packages if pkg is not None]
# If we've never seen one of these users before, then:
# 1) make sure they exist in the db (create them if necessary)
# 2) mark an in memory cache so we can remember that they exist without
# having to hit the db.
for username in usernames:
if username not in _users_seen:
# Create the user in the DB if necessary
User.get_or_create(username)
# Then just mark an in memory cache noting that we've seen them.
_users_seen.add(username)
for package in packages:
if package not in _packages_seen:
Package.get_or_create(package)
_packages_seen.add(package)
session.flush()
# These two blocks would normally be a simple "obj.users.append(user)" kind
# of statement, but here we drop down out of sqlalchemy's ORM and into the
# sql abstraction in order to gain a little performance boost.
values = [{'username': username, 'msg': obj.id} for username in usernames]
if values:
session.execute(user_assoc_table.insert(), values)
values = [{'package': package, 'msg': obj.id} for package in packages]
if values:
session.execute(pack_assoc_table.insert(), values)
# TODO -- can we avoid committing every time?
session.flush()
session.commit() | python | def add(envelope):
""" Take a dict-like fedmsg envelope and store the headers and message
in the table.
"""
message = envelope['body']
timestamp = message.get('timestamp', None)
try:
if timestamp:
timestamp = datetime.datetime.utcfromtimestamp(timestamp)
else:
timestamp = datetime.datetime.utcnow()
except Exception:
pass
headers = envelope.get('headers', None)
msg_id = message.get('msg_id', None)
if not msg_id and headers:
msg_id = headers.get('message-id', None)
if not msg_id:
msg_id = six.text_type(timestamp.year) + six.u('-') + six.text_type(uuid.uuid4())
obj = Message(
i=message.get('i', 0),
msg_id=msg_id,
topic=message['topic'],
timestamp=timestamp,
username=message.get('username', None),
crypto=message.get('crypto', None),
certificate=message.get('certificate', None),
signature=message.get('signature', None),
)
obj.msg = message['msg']
obj.headers = headers
try:
session.add(obj)
session.flush()
except IntegrityError:
log.warning('Skipping message from %s with duplicate id: %s',
message['topic'], msg_id)
session.rollback()
return
usernames = fedmsg.meta.msg2usernames(message)
packages = fedmsg.meta.msg2packages(message)
# Do a little sanity checking on fedmsg.meta results
if None in usernames:
# Notify developers so they can fix msg2usernames
log.error('NoneType found in usernames of %r' % msg_id)
# And prune out the bad value
usernames = [name for name in usernames if name is not None]
if None in packages:
# Notify developers so they can fix msg2packages
log.error('NoneType found in packages of %r' % msg_id)
# And prune out the bad value
packages = [pkg for pkg in packages if pkg is not None]
# If we've never seen one of these users before, then:
# 1) make sure they exist in the db (create them if necessary)
# 2) mark an in memory cache so we can remember that they exist without
# having to hit the db.
for username in usernames:
if username not in _users_seen:
# Create the user in the DB if necessary
User.get_or_create(username)
# Then just mark an in memory cache noting that we've seen them.
_users_seen.add(username)
for package in packages:
if package not in _packages_seen:
Package.get_or_create(package)
_packages_seen.add(package)
session.flush()
# These two blocks would normally be a simple "obj.users.append(user)" kind
# of statement, but here we drop down out of sqlalchemy's ORM and into the
# sql abstraction in order to gain a little performance boost.
values = [{'username': username, 'msg': obj.id} for username in usernames]
if values:
session.execute(user_assoc_table.insert(), values)
values = [{'package': package, 'msg': obj.id} for package in packages]
if values:
session.execute(pack_assoc_table.insert(), values)
# TODO -- can we avoid committing every time?
session.flush()
session.commit() | [
"def",
"add",
"(",
"envelope",
")",
":",
"message",
"=",
"envelope",
"[",
"'body'",
"]",
"timestamp",
"=",
"message",
".",
"get",
"(",
"'timestamp'",
",",
"None",
")",
"try",
":",
"if",
"timestamp",
":",
"timestamp",
"=",
"datetime",
".",
"datetime",
"... | Take a dict-like fedmsg envelope and store the headers and message
in the table. | [
"Take",
"a",
"dict",
"-",
"like",
"fedmsg",
"envelope",
"and",
"store",
"the",
"headers",
"and",
"message",
"in",
"the",
"table",
"."
] | 4a20e216bb404b14f76c7065518fd081e989764d | https://github.com/fedora-infra/datanommer/blob/4a20e216bb404b14f76c7065518fd081e989764d/datanommer.models/datanommer/models/__init__.py#L115-L205 | train | 48,047 |
fedora-infra/datanommer | datanommer.models/datanommer/models/__init__.py | Singleton.get_or_create | def get_or_create(cls, name):
"""
Return the instance of the class with the specified name. If it doesn't
already exist, create it.
"""
obj = cls.query.filter_by(name=name).one_or_none()
if obj:
return obj
try:
with session.begin_nested():
obj = cls(name=name)
session.add(obj)
session.flush()
return obj
except IntegrityError:
log.debug('Collision when adding %s(name="%s"), returning existing object',
cls.__name__, name)
return cls.query.filter_by(name=name).one() | python | def get_or_create(cls, name):
"""
Return the instance of the class with the specified name. If it doesn't
already exist, create it.
"""
obj = cls.query.filter_by(name=name).one_or_none()
if obj:
return obj
try:
with session.begin_nested():
obj = cls(name=name)
session.add(obj)
session.flush()
return obj
except IntegrityError:
log.debug('Collision when adding %s(name="%s"), returning existing object',
cls.__name__, name)
return cls.query.filter_by(name=name).one() | [
"def",
"get_or_create",
"(",
"cls",
",",
"name",
")",
":",
"obj",
"=",
"cls",
".",
"query",
".",
"filter_by",
"(",
"name",
"=",
"name",
")",
".",
"one_or_none",
"(",
")",
"if",
"obj",
":",
"return",
"obj",
"try",
":",
"with",
"session",
".",
"begin... | Return the instance of the class with the specified name. If it doesn't
already exist, create it. | [
"Return",
"the",
"instance",
"of",
"the",
"class",
"with",
"the",
"specified",
"name",
".",
"If",
"it",
"doesn",
"t",
"already",
"exist",
"create",
"it",
"."
] | 4a20e216bb404b14f76c7065518fd081e989764d | https://github.com/fedora-infra/datanommer/blob/4a20e216bb404b14f76c7065518fd081e989764d/datanommer.models/datanommer/models/__init__.py#L295-L312 | train | 48,048 |
Accelize/pycosio | pycosio/_core/functions_os_path.py | relpath | def relpath(path, start=None):
"""
Return a relative file path to path either from the
current directory or from an optional start directory.
For storage objects, "path" and "start" are relative to
storage root.
"/" are not stripped on storage objects path. The ending slash is required
on some storage to signify that target is a directory.
Equivalent to "os.path.relpath".
Args:
path (path-like object): Path or URL.
start (path-like object): Relative from this optional directory.
Default to "os.curdir" for local files.
Returns:
str: Relative path.
"""
relative = get_instance(path).relpath(path)
if start:
# Storage relative path
# Replaces "\" by "/" for Windows.
return os_path_relpath(relative, start=start).replace('\\', '/')
return relative | python | def relpath(path, start=None):
"""
Return a relative file path to path either from the
current directory or from an optional start directory.
For storage objects, "path" and "start" are relative to
storage root.
"/" are not stripped on storage objects path. The ending slash is required
on some storage to signify that target is a directory.
Equivalent to "os.path.relpath".
Args:
path (path-like object): Path or URL.
start (path-like object): Relative from this optional directory.
Default to "os.curdir" for local files.
Returns:
str: Relative path.
"""
relative = get_instance(path).relpath(path)
if start:
# Storage relative path
# Replaces "\" by "/" for Windows.
return os_path_relpath(relative, start=start).replace('\\', '/')
return relative | [
"def",
"relpath",
"(",
"path",
",",
"start",
"=",
"None",
")",
":",
"relative",
"=",
"get_instance",
"(",
"path",
")",
".",
"relpath",
"(",
"path",
")",
"if",
"start",
":",
"# Storage relative path",
"# Replaces \"\\\" by \"/\" for Windows.",
"return",
"os_path_... | Return a relative file path to path either from the
current directory or from an optional start directory.
For storage objects, "path" and "start" are relative to
storage root.
"/" are not stripped on storage objects path. The ending slash is required
on some storage to signify that target is a directory.
Equivalent to "os.path.relpath".
Args:
path (path-like object): Path or URL.
start (path-like object): Relative from this optional directory.
Default to "os.curdir" for local files.
Returns:
str: Relative path. | [
"Return",
"a",
"relative",
"file",
"path",
"to",
"path",
"either",
"from",
"the",
"current",
"directory",
"or",
"from",
"an",
"optional",
"start",
"directory",
"."
] | 1cc1f8fdf5394d92918b7bae2bfa682169ccc48c | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/_core/functions_os_path.py#L176-L202 | train | 48,049 |
Accelize/pycosio | pycosio/_core/functions_os_path.py | samefile | def samefile(path1, path2):
"""
Return True if both pathname arguments refer to the same file or directory.
Equivalent to "os.path.samefile".
Args:
path1 (path-like object): Path or URL.
path2 (path-like object): Path or URL.
Returns:
bool: True if same file or directory.
"""
# Handles path-like objects and checks if storage
path1, path1_is_storage = format_and_is_storage(path1)
path2, path2_is_storage = format_and_is_storage(path2)
# Local files: Redirects to "os.path.samefile"
if not path1_is_storage and not path2_is_storage:
return os_path_samefile(path1, path2)
# One path is local, the other storage
if not path1_is_storage or not path2_is_storage:
return False
with handle_os_exceptions():
# Paths don't use same storage
system = get_instance(path1)
if system is not get_instance(path2):
return False
# Relative path are different
elif system.relpath(path1) != system.relpath(path2):
return False
# Same files
return True | python | def samefile(path1, path2):
"""
Return True if both pathname arguments refer to the same file or directory.
Equivalent to "os.path.samefile".
Args:
path1 (path-like object): Path or URL.
path2 (path-like object): Path or URL.
Returns:
bool: True if same file or directory.
"""
# Handles path-like objects and checks if storage
path1, path1_is_storage = format_and_is_storage(path1)
path2, path2_is_storage = format_and_is_storage(path2)
# Local files: Redirects to "os.path.samefile"
if not path1_is_storage and not path2_is_storage:
return os_path_samefile(path1, path2)
# One path is local, the other storage
if not path1_is_storage or not path2_is_storage:
return False
with handle_os_exceptions():
# Paths don't use same storage
system = get_instance(path1)
if system is not get_instance(path2):
return False
# Relative path are different
elif system.relpath(path1) != system.relpath(path2):
return False
# Same files
return True | [
"def",
"samefile",
"(",
"path1",
",",
"path2",
")",
":",
"# Handles path-like objects and checks if storage",
"path1",
",",
"path1_is_storage",
"=",
"format_and_is_storage",
"(",
"path1",
")",
"path2",
",",
"path2_is_storage",
"=",
"format_and_is_storage",
"(",
"path2",... | Return True if both pathname arguments refer to the same file or directory.
Equivalent to "os.path.samefile".
Args:
path1 (path-like object): Path or URL.
path2 (path-like object): Path or URL.
Returns:
bool: True if same file or directory. | [
"Return",
"True",
"if",
"both",
"pathname",
"arguments",
"refer",
"to",
"the",
"same",
"file",
"or",
"directory",
"."
] | 1cc1f8fdf5394d92918b7bae2bfa682169ccc48c | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/_core/functions_os_path.py#L205-L241 | train | 48,050 |
Accelize/pycosio | pycosio/_core/exceptions.py | handle_os_exceptions | def handle_os_exceptions():
"""
Handles pycosio exceptions and raise standard OS exceptions.
"""
try:
yield
# Convert pycosio exception to equivalent OSError
except ObjectException:
exc_type, exc_value, _ = exc_info()
raise _OS_EXCEPTIONS.get(exc_type, OSError)(exc_value)
# Re-raise generic exceptions
except (OSError, same_file_error, UnsupportedOperation):
raise
# Raise generic OSError for other exceptions
except Exception:
exc_type, exc_value, _ = exc_info()
raise OSError('%s%s' % (
exc_type, (', %s' % exc_value) if exc_value else '')) | python | def handle_os_exceptions():
"""
Handles pycosio exceptions and raise standard OS exceptions.
"""
try:
yield
# Convert pycosio exception to equivalent OSError
except ObjectException:
exc_type, exc_value, _ = exc_info()
raise _OS_EXCEPTIONS.get(exc_type, OSError)(exc_value)
# Re-raise generic exceptions
except (OSError, same_file_error, UnsupportedOperation):
raise
# Raise generic OSError for other exceptions
except Exception:
exc_type, exc_value, _ = exc_info()
raise OSError('%s%s' % (
exc_type, (', %s' % exc_value) if exc_value else '')) | [
"def",
"handle_os_exceptions",
"(",
")",
":",
"try",
":",
"yield",
"# Convert pycosio exception to equivalent OSError",
"except",
"ObjectException",
":",
"exc_type",
",",
"exc_value",
",",
"_",
"=",
"exc_info",
"(",
")",
"raise",
"_OS_EXCEPTIONS",
".",
"get",
"(",
... | Handles pycosio exceptions and raise standard OS exceptions. | [
"Handles",
"pycosio",
"exceptions",
"and",
"raise",
"standard",
"OS",
"exceptions",
"."
] | 1cc1f8fdf5394d92918b7bae2bfa682169ccc48c | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/_core/exceptions.py#L36-L56 | train | 48,051 |
Accelize/pycosio | pycosio/_core/functions_os.py | listdir | def listdir(path='.'):
"""
Return a list containing the names of the entries in the directory given by
path.
Equivalent to "os.listdir".
Args:
path (path-like object): Path or URL.
Returns:
list of str: Entries names.
"""
return [name.rstrip('/') for name, _ in
get_instance(path).list_objects(path, first_level=True)] | python | def listdir(path='.'):
"""
Return a list containing the names of the entries in the directory given by
path.
Equivalent to "os.listdir".
Args:
path (path-like object): Path or URL.
Returns:
list of str: Entries names.
"""
return [name.rstrip('/') for name, _ in
get_instance(path).list_objects(path, first_level=True)] | [
"def",
"listdir",
"(",
"path",
"=",
"'.'",
")",
":",
"return",
"[",
"name",
".",
"rstrip",
"(",
"'/'",
")",
"for",
"name",
",",
"_",
"in",
"get_instance",
"(",
"path",
")",
".",
"list_objects",
"(",
"path",
",",
"first_level",
"=",
"True",
")",
"]"... | Return a list containing the names of the entries in the directory given by
path.
Equivalent to "os.listdir".
Args:
path (path-like object): Path or URL.
Returns:
list of str: Entries names. | [
"Return",
"a",
"list",
"containing",
"the",
"names",
"of",
"the",
"entries",
"in",
"the",
"directory",
"given",
"by",
"path",
"."
] | 1cc1f8fdf5394d92918b7bae2bfa682169ccc48c | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/_core/functions_os.py#L20-L34 | train | 48,052 |
Accelize/pycosio | pycosio/_core/functions_os.py | mkdir | def mkdir(path, mode=0o777, dir_fd=None):
"""
Create a directory named path with numeric mode mode.
Equivalent to "os.mkdir".
Args:
path (path-like object): Path or URL.
mode (int): The mode parameter is passed to os.mkdir();
see the os.mkdir() description for how it is interpreted.
Not supported on cloud storage objects.
dir_fd: directory descriptors;
see the os.remove() description for how it is interpreted.
Not supported on cloud storage objects.
Raises:
FileExistsError : Directory already exists.
FileNotFoundError: Parent directory not exists.
"""
system = get_instance(path)
relative = system.relpath(path)
# Checks if parent directory exists
parent_dir = dirname(relative.rstrip('/'))
if parent_dir:
parent = path.rsplit(relative, 1)[0] + parent_dir + '/'
if not system.isdir(parent):
raise ObjectNotFoundError(
"No such file or directory: '%s'" % parent)
# Checks if directory not already exists
if system.isdir(system.ensure_dir_path(path)):
raise ObjectExistsError("File exists: '%s'" % path)
# Create directory
system.make_dir(relative, relative=True) | python | def mkdir(path, mode=0o777, dir_fd=None):
"""
Create a directory named path with numeric mode mode.
Equivalent to "os.mkdir".
Args:
path (path-like object): Path or URL.
mode (int): The mode parameter is passed to os.mkdir();
see the os.mkdir() description for how it is interpreted.
Not supported on cloud storage objects.
dir_fd: directory descriptors;
see the os.remove() description for how it is interpreted.
Not supported on cloud storage objects.
Raises:
FileExistsError : Directory already exists.
FileNotFoundError: Parent directory not exists.
"""
system = get_instance(path)
relative = system.relpath(path)
# Checks if parent directory exists
parent_dir = dirname(relative.rstrip('/'))
if parent_dir:
parent = path.rsplit(relative, 1)[0] + parent_dir + '/'
if not system.isdir(parent):
raise ObjectNotFoundError(
"No such file or directory: '%s'" % parent)
# Checks if directory not already exists
if system.isdir(system.ensure_dir_path(path)):
raise ObjectExistsError("File exists: '%s'" % path)
# Create directory
system.make_dir(relative, relative=True) | [
"def",
"mkdir",
"(",
"path",
",",
"mode",
"=",
"0o777",
",",
"dir_fd",
"=",
"None",
")",
":",
"system",
"=",
"get_instance",
"(",
"path",
")",
"relative",
"=",
"system",
".",
"relpath",
"(",
"path",
")",
"# Checks if parent directory exists",
"parent_dir",
... | Create a directory named path with numeric mode mode.
Equivalent to "os.mkdir".
Args:
path (path-like object): Path or URL.
mode (int): The mode parameter is passed to os.mkdir();
see the os.mkdir() description for how it is interpreted.
Not supported on cloud storage objects.
dir_fd: directory descriptors;
see the os.remove() description for how it is interpreted.
Not supported on cloud storage objects.
Raises:
FileExistsError : Directory already exists.
FileNotFoundError: Parent directory not exists. | [
"Create",
"a",
"directory",
"named",
"path",
"with",
"numeric",
"mode",
"mode",
"."
] | 1cc1f8fdf5394d92918b7bae2bfa682169ccc48c | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/_core/functions_os.py#L69-L104 | train | 48,053 |
Accelize/pycosio | pycosio/_core/functions_os.py | remove | def remove(path, dir_fd=None):
"""
Remove a file.
Equivalent to "os.remove" and "os.unlink".
Args:
path (path-like object): Path or URL.
dir_fd: directory descriptors;
see the os.remove() description for how it is interpreted.
Not supported on cloud storage objects.
"""
system = get_instance(path)
# Only support files
if system.is_locator(path) or path[-1] == '/':
raise is_a_directory_error("Is a directory: '%s'" % path)
# Remove
system.remove(path) | python | def remove(path, dir_fd=None):
"""
Remove a file.
Equivalent to "os.remove" and "os.unlink".
Args:
path (path-like object): Path or URL.
dir_fd: directory descriptors;
see the os.remove() description for how it is interpreted.
Not supported on cloud storage objects.
"""
system = get_instance(path)
# Only support files
if system.is_locator(path) or path[-1] == '/':
raise is_a_directory_error("Is a directory: '%s'" % path)
# Remove
system.remove(path) | [
"def",
"remove",
"(",
"path",
",",
"dir_fd",
"=",
"None",
")",
":",
"system",
"=",
"get_instance",
"(",
"path",
")",
"# Only support files",
"if",
"system",
".",
"is_locator",
"(",
"path",
")",
"or",
"path",
"[",
"-",
"1",
"]",
"==",
"'/'",
":",
"rai... | Remove a file.
Equivalent to "os.remove" and "os.unlink".
Args:
path (path-like object): Path or URL.
dir_fd: directory descriptors;
see the os.remove() description for how it is interpreted.
Not supported on cloud storage objects. | [
"Remove",
"a",
"file",
"."
] | 1cc1f8fdf5394d92918b7bae2bfa682169ccc48c | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/_core/functions_os.py#L108-L127 | train | 48,054 |
Accelize/pycosio | pycosio/_core/functions_os.py | rmdir | def rmdir(path, dir_fd=None):
"""
Remove a directory.
Equivalent to "os.rmdir".
Args:
path (path-like object): Path or URL.
dir_fd: directory descriptors;
see the os.rmdir() description for how it is interpreted.
Not supported on cloud storage objects.
"""
system = get_instance(path)
system.remove(system.ensure_dir_path(path)) | python | def rmdir(path, dir_fd=None):
"""
Remove a directory.
Equivalent to "os.rmdir".
Args:
path (path-like object): Path or URL.
dir_fd: directory descriptors;
see the os.rmdir() description for how it is interpreted.
Not supported on cloud storage objects.
"""
system = get_instance(path)
system.remove(system.ensure_dir_path(path)) | [
"def",
"rmdir",
"(",
"path",
",",
"dir_fd",
"=",
"None",
")",
":",
"system",
"=",
"get_instance",
"(",
"path",
")",
"system",
".",
"remove",
"(",
"system",
".",
"ensure_dir_path",
"(",
"path",
")",
")"
] | Remove a directory.
Equivalent to "os.rmdir".
Args:
path (path-like object): Path or URL.
dir_fd: directory descriptors;
see the os.rmdir() description for how it is interpreted.
Not supported on cloud storage objects. | [
"Remove",
"a",
"directory",
"."
] | 1cc1f8fdf5394d92918b7bae2bfa682169ccc48c | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/_core/functions_os.py#L135-L148 | train | 48,055 |
Accelize/pycosio | pycosio/_core/functions_os.py | scandir | def scandir(path='.'):
"""
Return an iterator of os.DirEntry objects corresponding to the entries in
the directory given by path. The entries are yielded in arbitrary order,
and the special entries '.' and '..' are not included.
Equivalent to "os.scandir".
Args:
path (path-like object): Path or URL.
If path is of type bytes (directly or indirectly through the
PathLike interface), the type of the name and path attributes
of each os.DirEntry will be bytes; in all other circumstances,
they will be of type str.
Returns:
Generator of os.DirEntry: Entries information.
"""
# Handles path-like objects
scandir_path = fsdecode(path).replace('\\', '/')
if not is_storage(scandir_path):
return os_scandir(scandir_path)
return _scandir_generator(
is_bytes=isinstance(fspath(path), (bytes, bytearray)),
scandir_path=scandir_path, system=get_instance(scandir_path)) | python | def scandir(path='.'):
"""
Return an iterator of os.DirEntry objects corresponding to the entries in
the directory given by path. The entries are yielded in arbitrary order,
and the special entries '.' and '..' are not included.
Equivalent to "os.scandir".
Args:
path (path-like object): Path or URL.
If path is of type bytes (directly or indirectly through the
PathLike interface), the type of the name and path attributes
of each os.DirEntry will be bytes; in all other circumstances,
they will be of type str.
Returns:
Generator of os.DirEntry: Entries information.
"""
# Handles path-like objects
scandir_path = fsdecode(path).replace('\\', '/')
if not is_storage(scandir_path):
return os_scandir(scandir_path)
return _scandir_generator(
is_bytes=isinstance(fspath(path), (bytes, bytearray)),
scandir_path=scandir_path, system=get_instance(scandir_path)) | [
"def",
"scandir",
"(",
"path",
"=",
"'.'",
")",
":",
"# Handles path-like objects",
"scandir_path",
"=",
"fsdecode",
"(",
"path",
")",
".",
"replace",
"(",
"'\\\\'",
",",
"'/'",
")",
"if",
"not",
"is_storage",
"(",
"scandir_path",
")",
":",
"return",
"os_s... | Return an iterator of os.DirEntry objects corresponding to the entries in
the directory given by path. The entries are yielded in arbitrary order,
and the special entries '.' and '..' are not included.
Equivalent to "os.scandir".
Args:
path (path-like object): Path or URL.
If path is of type bytes (directly or indirectly through the
PathLike interface), the type of the name and path attributes
of each os.DirEntry will be bytes; in all other circumstances,
they will be of type str.
Returns:
Generator of os.DirEntry: Entries information. | [
"Return",
"an",
"iterator",
"of",
"os",
".",
"DirEntry",
"objects",
"corresponding",
"to",
"the",
"entries",
"in",
"the",
"directory",
"given",
"by",
"path",
".",
"The",
"entries",
"are",
"yielded",
"in",
"arbitrary",
"order",
"and",
"the",
"special",
"entri... | 1cc1f8fdf5394d92918b7bae2bfa682169ccc48c | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/_core/functions_os.py#L374-L400 | train | 48,056 |
Accelize/pycosio | pycosio/_core/io_base_buffered.py | ObjectBufferedIOBase._flush_raw_or_buffered | def _flush_raw_or_buffered(self):
"""
Flush using raw of buffered methods.
"""
# Flush only if bytes written
# This avoid no required process/thread
# creation and network call.
# This step is performed by raw stream.
if self._buffer_seek and self._seek:
self._seek += 1
with handle_os_exceptions():
self._flush()
# If data lower than buffer size
# flush data with raw stream to reduce IO calls
elif self._buffer_seek:
self._raw._write_buffer = self._get_buffer()
self._raw._seek = self._buffer_seek
self._raw.flush() | python | def _flush_raw_or_buffered(self):
"""
Flush using raw of buffered methods.
"""
# Flush only if bytes written
# This avoid no required process/thread
# creation and network call.
# This step is performed by raw stream.
if self._buffer_seek and self._seek:
self._seek += 1
with handle_os_exceptions():
self._flush()
# If data lower than buffer size
# flush data with raw stream to reduce IO calls
elif self._buffer_seek:
self._raw._write_buffer = self._get_buffer()
self._raw._seek = self._buffer_seek
self._raw.flush() | [
"def",
"_flush_raw_or_buffered",
"(",
"self",
")",
":",
"# Flush only if bytes written",
"# This avoid no required process/thread",
"# creation and network call.",
"# This step is performed by raw stream.",
"if",
"self",
".",
"_buffer_seek",
"and",
"self",
".",
"_seek",
":",
"s... | Flush using raw of buffered methods. | [
"Flush",
"using",
"raw",
"of",
"buffered",
"methods",
"."
] | 1cc1f8fdf5394d92918b7bae2bfa682169ccc48c | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/_core/io_base_buffered.py#L156-L174 | train | 48,057 |
Accelize/pycosio | pycosio/_core/io_base_buffered.py | ObjectBufferedIOBase._preload_range | def _preload_range(self):
"""Preload data for reading"""
queue = self._read_queue
size = self._buffer_size
start = self._seek
end = int(start + size * self._max_buffers)
workers_submit = self._workers.submit
indexes = tuple(range(start, end, size))
# Drops buffer out of current range
for seek in tuple(queue):
if seek not in indexes:
del queue[seek]
# Launch buffer preloading for current range
read_range = self._read_range
for seek in indexes:
if seek not in queue:
queue[seek] = workers_submit(read_range, seek, seek + size) | python | def _preload_range(self):
"""Preload data for reading"""
queue = self._read_queue
size = self._buffer_size
start = self._seek
end = int(start + size * self._max_buffers)
workers_submit = self._workers.submit
indexes = tuple(range(start, end, size))
# Drops buffer out of current range
for seek in tuple(queue):
if seek not in indexes:
del queue[seek]
# Launch buffer preloading for current range
read_range = self._read_range
for seek in indexes:
if seek not in queue:
queue[seek] = workers_submit(read_range, seek, seek + size) | [
"def",
"_preload_range",
"(",
"self",
")",
":",
"queue",
"=",
"self",
".",
"_read_queue",
"size",
"=",
"self",
".",
"_buffer_size",
"start",
"=",
"self",
".",
"_seek",
"end",
"=",
"int",
"(",
"start",
"+",
"size",
"*",
"self",
".",
"_max_buffers",
")",... | Preload data for reading | [
"Preload",
"data",
"for",
"reading"
] | 1cc1f8fdf5394d92918b7bae2bfa682169ccc48c | https://github.com/Accelize/pycosio/blob/1cc1f8fdf5394d92918b7bae2bfa682169ccc48c/pycosio/_core/io_base_buffered.py#L212-L230 | train | 48,058 |
mnooner256/pyqrcode | pyqrcode/__init__.py | QRCode._detect_content_type | def _detect_content_type(self, content, encoding):
"""This method tries to auto-detect the type of the data. It first
tries to see if the data is a valid integer, in which case it returns
numeric. Next, it tests the data to see if it is 'alphanumeric.' QR
Codes use a special table with very limited range of ASCII characters.
The code's data is tested to make sure it fits inside this limited
range. If all else fails, the data is determined to be of type
'binary.'
Returns a tuple containing the detected mode and encoding.
Note, encoding ECI is not yet implemented.
"""
def two_bytes(c):
"""Output two byte character code as a single integer."""
def next_byte(b):
"""Make sure that character code is an int. Python 2 and
3 compatibility.
"""
if not isinstance(b, int):
return ord(b)
else:
return b
#Go through the data by looping to every other character
for i in range(0, len(c), 2):
yield (next_byte(c[i]) << 8) | next_byte(c[i+1])
#See if the data is a number
try:
if str(content).isdigit():
return 'numeric', encoding
except (TypeError, UnicodeError):
pass
#See if that data is alphanumeric based on the standards
#special ASCII table
valid_characters = ''.join(tables.ascii_codes.keys())
#Force the characters into a byte array
valid_characters = valid_characters.encode('ASCII')
try:
if isinstance(content, bytes):
c = content.decode('ASCII')
else:
c = str(content).encode('ASCII')
if all(map(lambda x: x in valid_characters, c)):
return 'alphanumeric', 'ASCII'
#This occurs if the content does not contain ASCII characters.
#Since the whole point of the if statement is to look for ASCII
#characters, the resulting mode should not be alphanumeric.
#Hence, this is not an error.
except TypeError:
pass
except UnicodeError:
pass
try:
if isinstance(content, bytes):
if encoding is None:
encoding = 'shiftjis'
c = content.decode(encoding).encode('shiftjis')
else:
c = content.encode('shiftjis')
#All kanji characters must be two bytes long, make sure the
#string length is not odd.
if len(c) % 2 != 0:
return 'binary', encoding
#Make sure the characters are actually in range.
for asint in two_bytes(c):
#Shift the two byte value as indicated by the standard
if not (0x8140 <= asint <= 0x9FFC or
0xE040 <= asint <= 0xEBBF):
return 'binary', encoding
return 'kanji', encoding
except UnicodeError:
#This occurs if the content does not contain Shift JIS kanji
#characters. Hence, the resulting mode should not be kanji.
#This is not an error.
pass
#All of the other attempts failed. The content can only be binary.
return 'binary', encoding | python | def _detect_content_type(self, content, encoding):
"""This method tries to auto-detect the type of the data. It first
tries to see if the data is a valid integer, in which case it returns
numeric. Next, it tests the data to see if it is 'alphanumeric.' QR
Codes use a special table with very limited range of ASCII characters.
The code's data is tested to make sure it fits inside this limited
range. If all else fails, the data is determined to be of type
'binary.'
Returns a tuple containing the detected mode and encoding.
Note, encoding ECI is not yet implemented.
"""
def two_bytes(c):
"""Output two byte character code as a single integer."""
def next_byte(b):
"""Make sure that character code is an int. Python 2 and
3 compatibility.
"""
if not isinstance(b, int):
return ord(b)
else:
return b
#Go through the data by looping to every other character
for i in range(0, len(c), 2):
yield (next_byte(c[i]) << 8) | next_byte(c[i+1])
#See if the data is a number
try:
if str(content).isdigit():
return 'numeric', encoding
except (TypeError, UnicodeError):
pass
#See if that data is alphanumeric based on the standards
#special ASCII table
valid_characters = ''.join(tables.ascii_codes.keys())
#Force the characters into a byte array
valid_characters = valid_characters.encode('ASCII')
try:
if isinstance(content, bytes):
c = content.decode('ASCII')
else:
c = str(content).encode('ASCII')
if all(map(lambda x: x in valid_characters, c)):
return 'alphanumeric', 'ASCII'
#This occurs if the content does not contain ASCII characters.
#Since the whole point of the if statement is to look for ASCII
#characters, the resulting mode should not be alphanumeric.
#Hence, this is not an error.
except TypeError:
pass
except UnicodeError:
pass
try:
if isinstance(content, bytes):
if encoding is None:
encoding = 'shiftjis'
c = content.decode(encoding).encode('shiftjis')
else:
c = content.encode('shiftjis')
#All kanji characters must be two bytes long, make sure the
#string length is not odd.
if len(c) % 2 != 0:
return 'binary', encoding
#Make sure the characters are actually in range.
for asint in two_bytes(c):
#Shift the two byte value as indicated by the standard
if not (0x8140 <= asint <= 0x9FFC or
0xE040 <= asint <= 0xEBBF):
return 'binary', encoding
return 'kanji', encoding
except UnicodeError:
#This occurs if the content does not contain Shift JIS kanji
#characters. Hence, the resulting mode should not be kanji.
#This is not an error.
pass
#All of the other attempts failed. The content can only be binary.
return 'binary', encoding | [
"def",
"_detect_content_type",
"(",
"self",
",",
"content",
",",
"encoding",
")",
":",
"def",
"two_bytes",
"(",
"c",
")",
":",
"\"\"\"Output two byte character code as a single integer.\"\"\"",
"def",
"next_byte",
"(",
"b",
")",
":",
"\"\"\"Make sure that character code... | This method tries to auto-detect the type of the data. It first
tries to see if the data is a valid integer, in which case it returns
numeric. Next, it tests the data to see if it is 'alphanumeric.' QR
Codes use a special table with very limited range of ASCII characters.
The code's data is tested to make sure it fits inside this limited
range. If all else fails, the data is determined to be of type
'binary.'
Returns a tuple containing the detected mode and encoding.
Note, encoding ECI is not yet implemented. | [
"This",
"method",
"tries",
"to",
"auto",
"-",
"detect",
"the",
"type",
"of",
"the",
"data",
".",
"It",
"first",
"tries",
"to",
"see",
"if",
"the",
"data",
"is",
"a",
"valid",
"integer",
"in",
"which",
"case",
"it",
"returns",
"numeric",
".",
"Next",
... | 674a77b5eaf850d063f518bd90c243ee34ad6b5d | https://github.com/mnooner256/pyqrcode/blob/674a77b5eaf850d063f518bd90c243ee34ad6b5d/pyqrcode/__init__.py#L240-L330 | train | 48,059 |
mnooner256/pyqrcode | pyqrcode/__init__.py | QRCode._pick_best_fit | def _pick_best_fit(self, content):
"""This method return the smallest possible QR code version number
that will fit the specified data with the given error level.
"""
import math
for version in range(1, 41):
#Get the maximum possible capacity
capacity = tables.data_capacity[version][self.error][self.mode_num]
#Check the capacity
#Kanji's count in the table is "characters" which are two bytes
if (self.mode_num == tables.modes['kanji'] and
capacity >= math.ceil(len(content) / 2)):
return version
if capacity >= len(content):
return version
raise ValueError('The data will not fit in any QR code version '
'with the given encoding and error level.') | python | def _pick_best_fit(self, content):
"""This method return the smallest possible QR code version number
that will fit the specified data with the given error level.
"""
import math
for version in range(1, 41):
#Get the maximum possible capacity
capacity = tables.data_capacity[version][self.error][self.mode_num]
#Check the capacity
#Kanji's count in the table is "characters" which are two bytes
if (self.mode_num == tables.modes['kanji'] and
capacity >= math.ceil(len(content) / 2)):
return version
if capacity >= len(content):
return version
raise ValueError('The data will not fit in any QR code version '
'with the given encoding and error level.') | [
"def",
"_pick_best_fit",
"(",
"self",
",",
"content",
")",
":",
"import",
"math",
"for",
"version",
"in",
"range",
"(",
"1",
",",
"41",
")",
":",
"#Get the maximum possible capacity",
"capacity",
"=",
"tables",
".",
"data_capacity",
"[",
"version",
"]",
"[",... | This method return the smallest possible QR code version number
that will fit the specified data with the given error level. | [
"This",
"method",
"return",
"the",
"smallest",
"possible",
"QR",
"code",
"version",
"number",
"that",
"will",
"fit",
"the",
"specified",
"data",
"with",
"the",
"given",
"error",
"level",
"."
] | 674a77b5eaf850d063f518bd90c243ee34ad6b5d | https://github.com/mnooner256/pyqrcode/blob/674a77b5eaf850d063f518bd90c243ee34ad6b5d/pyqrcode/__init__.py#L332-L351 | train | 48,060 |
mnooner256/pyqrcode | pyqrcode/__init__.py | QRCode.show | def show(self, wait=1.2, scale=10, module_color=(0, 0, 0, 255),
background=(255, 255, 255, 255), quiet_zone=4):
"""Displays this QR code.
This method is mainly intended for debugging purposes.
This method saves the output of the :py:meth:`png` method (with a default
scaling factor of 10) to a temporary file and opens it with the
standard PNG viewer application or within the standard webbrowser. The
temporary file is deleted afterwards.
If this method does not show any result, try to increase the `wait`
parameter. This parameter specifies the time in seconds to wait till
the temporary file is deleted. Note, that this method does not return
until the provided amount of seconds (default: 1.2) has passed.
The other parameters are simply passed on to the `png` method.
"""
import os
import time
import tempfile
import webbrowser
try: # Python 2
from urlparse import urljoin
from urllib import pathname2url
except ImportError: # Python 3
from urllib.parse import urljoin
from urllib.request import pathname2url
f = tempfile.NamedTemporaryFile('wb', suffix='.png', delete=False)
self.png(f, scale=scale, module_color=module_color,
background=background, quiet_zone=quiet_zone)
f.close()
webbrowser.open_new_tab(urljoin('file:', pathname2url(f.name)))
time.sleep(wait)
os.unlink(f.name) | python | def show(self, wait=1.2, scale=10, module_color=(0, 0, 0, 255),
background=(255, 255, 255, 255), quiet_zone=4):
"""Displays this QR code.
This method is mainly intended for debugging purposes.
This method saves the output of the :py:meth:`png` method (with a default
scaling factor of 10) to a temporary file and opens it with the
standard PNG viewer application or within the standard webbrowser. The
temporary file is deleted afterwards.
If this method does not show any result, try to increase the `wait`
parameter. This parameter specifies the time in seconds to wait till
the temporary file is deleted. Note, that this method does not return
until the provided amount of seconds (default: 1.2) has passed.
The other parameters are simply passed on to the `png` method.
"""
import os
import time
import tempfile
import webbrowser
try: # Python 2
from urlparse import urljoin
from urllib import pathname2url
except ImportError: # Python 3
from urllib.parse import urljoin
from urllib.request import pathname2url
f = tempfile.NamedTemporaryFile('wb', suffix='.png', delete=False)
self.png(f, scale=scale, module_color=module_color,
background=background, quiet_zone=quiet_zone)
f.close()
webbrowser.open_new_tab(urljoin('file:', pathname2url(f.name)))
time.sleep(wait)
os.unlink(f.name) | [
"def",
"show",
"(",
"self",
",",
"wait",
"=",
"1.2",
",",
"scale",
"=",
"10",
",",
"module_color",
"=",
"(",
"0",
",",
"0",
",",
"0",
",",
"255",
")",
",",
"background",
"=",
"(",
"255",
",",
"255",
",",
"255",
",",
"255",
")",
",",
"quiet_zo... | Displays this QR code.
This method is mainly intended for debugging purposes.
This method saves the output of the :py:meth:`png` method (with a default
scaling factor of 10) to a temporary file and opens it with the
standard PNG viewer application or within the standard webbrowser. The
temporary file is deleted afterwards.
If this method does not show any result, try to increase the `wait`
parameter. This parameter specifies the time in seconds to wait till
the temporary file is deleted. Note, that this method does not return
until the provided amount of seconds (default: 1.2) has passed.
The other parameters are simply passed on to the `png` method. | [
"Displays",
"this",
"QR",
"code",
"."
] | 674a77b5eaf850d063f518bd90c243ee34ad6b5d | https://github.com/mnooner256/pyqrcode/blob/674a77b5eaf850d063f518bd90c243ee34ad6b5d/pyqrcode/__init__.py#L353-L389 | train | 48,061 |
mnooner256/pyqrcode | pyqrcode/__init__.py | QRCode.png | def png(self, file, scale=1, module_color=(0, 0, 0, 255),
background=(255, 255, 255, 255), quiet_zone=4):
"""This method writes the QR code out as an PNG image. The resulting
PNG has a bit depth of 1. The file parameter is used to specify where
to write the image to. It can either be an writable stream or a
file path.
.. note::
This method depends on the pypng module to actually create the
PNG file.
This method will write the given *file* out as a PNG file. The file
can be either a string file path, or a writable stream. The file
will not be automatically closed if a stream is given.
The *scale* parameter sets how large to draw a single module. By
default one pixel is used to draw a single module. This may make the
code too small to be read efficiently. Increasing the scale will make
the code larger. Only integer scales are usable. This method will
attempt to coerce the parameter into an integer (e.g. 2.5 will become 2,
and '3' will become 3). You can use the :py:meth:`get_png_size` method
to calculate the actual pixel size of the resulting PNG image.
The *module_color* parameter sets what color to use for the encoded
modules (the black part on most QR codes). The *background* parameter
sets what color to use for the background (the white part on most
QR codes). If either parameter is set, then both must be
set or a ValueError is raised. Colors should be specified as either
a list or a tuple of length 3 or 4. The components of the list must
be integers between 0 and 255. The first three member give the RGB
color. The fourth member gives the alpha component, where 0 is
transparent and 255 is opaque. Note, many color
combinations are unreadable by scanners, so be judicious.
The *quiet_zone* parameter sets how wide the quiet zone around the code
should be. According to the standard this should be 4 modules. It is
left settable because such a wide quiet zone is unnecessary in many
applications where the QR code is not being printed.
Example:
>>> code = pyqrcode.create('Are you suggesting coconuts migrate?')
>>> code.png('swallow.png', scale=5)
>>> code.png('swallow.png', scale=5,
module_color=(0x66, 0x33, 0x0), #Dark brown
background=(0xff, 0xff, 0xff, 0x88)) #50% transparent white
"""
builder._png(self.code, self.version, file, scale,
module_color, background, quiet_zone) | python | def png(self, file, scale=1, module_color=(0, 0, 0, 255),
background=(255, 255, 255, 255), quiet_zone=4):
"""This method writes the QR code out as an PNG image. The resulting
PNG has a bit depth of 1. The file parameter is used to specify where
to write the image to. It can either be an writable stream or a
file path.
.. note::
This method depends on the pypng module to actually create the
PNG file.
This method will write the given *file* out as a PNG file. The file
can be either a string file path, or a writable stream. The file
will not be automatically closed if a stream is given.
The *scale* parameter sets how large to draw a single module. By
default one pixel is used to draw a single module. This may make the
code too small to be read efficiently. Increasing the scale will make
the code larger. Only integer scales are usable. This method will
attempt to coerce the parameter into an integer (e.g. 2.5 will become 2,
and '3' will become 3). You can use the :py:meth:`get_png_size` method
to calculate the actual pixel size of the resulting PNG image.
The *module_color* parameter sets what color to use for the encoded
modules (the black part on most QR codes). The *background* parameter
sets what color to use for the background (the white part on most
QR codes). If either parameter is set, then both must be
set or a ValueError is raised. Colors should be specified as either
a list or a tuple of length 3 or 4. The components of the list must
be integers between 0 and 255. The first three member give the RGB
color. The fourth member gives the alpha component, where 0 is
transparent and 255 is opaque. Note, many color
combinations are unreadable by scanners, so be judicious.
The *quiet_zone* parameter sets how wide the quiet zone around the code
should be. According to the standard this should be 4 modules. It is
left settable because such a wide quiet zone is unnecessary in many
applications where the QR code is not being printed.
Example:
>>> code = pyqrcode.create('Are you suggesting coconuts migrate?')
>>> code.png('swallow.png', scale=5)
>>> code.png('swallow.png', scale=5,
module_color=(0x66, 0x33, 0x0), #Dark brown
background=(0xff, 0xff, 0xff, 0x88)) #50% transparent white
"""
builder._png(self.code, self.version, file, scale,
module_color, background, quiet_zone) | [
"def",
"png",
"(",
"self",
",",
"file",
",",
"scale",
"=",
"1",
",",
"module_color",
"=",
"(",
"0",
",",
"0",
",",
"0",
",",
"255",
")",
",",
"background",
"=",
"(",
"255",
",",
"255",
",",
"255",
",",
"255",
")",
",",
"quiet_zone",
"=",
"4",... | This method writes the QR code out as an PNG image. The resulting
PNG has a bit depth of 1. The file parameter is used to specify where
to write the image to. It can either be an writable stream or a
file path.
.. note::
This method depends on the pypng module to actually create the
PNG file.
This method will write the given *file* out as a PNG file. The file
can be either a string file path, or a writable stream. The file
will not be automatically closed if a stream is given.
The *scale* parameter sets how large to draw a single module. By
default one pixel is used to draw a single module. This may make the
code too small to be read efficiently. Increasing the scale will make
the code larger. Only integer scales are usable. This method will
attempt to coerce the parameter into an integer (e.g. 2.5 will become 2,
and '3' will become 3). You can use the :py:meth:`get_png_size` method
to calculate the actual pixel size of the resulting PNG image.
The *module_color* parameter sets what color to use for the encoded
modules (the black part on most QR codes). The *background* parameter
sets what color to use for the background (the white part on most
QR codes). If either parameter is set, then both must be
set or a ValueError is raised. Colors should be specified as either
a list or a tuple of length 3 or 4. The components of the list must
be integers between 0 and 255. The first three member give the RGB
color. The fourth member gives the alpha component, where 0 is
transparent and 255 is opaque. Note, many color
combinations are unreadable by scanners, so be judicious.
The *quiet_zone* parameter sets how wide the quiet zone around the code
should be. According to the standard this should be 4 modules. It is
left settable because such a wide quiet zone is unnecessary in many
applications where the QR code is not being printed.
Example:
>>> code = pyqrcode.create('Are you suggesting coconuts migrate?')
>>> code.png('swallow.png', scale=5)
>>> code.png('swallow.png', scale=5,
module_color=(0x66, 0x33, 0x0), #Dark brown
background=(0xff, 0xff, 0xff, 0x88)) #50% transparent white | [
"This",
"method",
"writes",
"the",
"QR",
"code",
"out",
"as",
"an",
"PNG",
"image",
".",
"The",
"resulting",
"PNG",
"has",
"a",
"bit",
"depth",
"of",
"1",
".",
"The",
"file",
"parameter",
"is",
"used",
"to",
"specify",
"where",
"to",
"write",
"the",
... | 674a77b5eaf850d063f518bd90c243ee34ad6b5d | https://github.com/mnooner256/pyqrcode/blob/674a77b5eaf850d063f518bd90c243ee34ad6b5d/pyqrcode/__init__.py#L416-L463 | train | 48,062 |
mnooner256/pyqrcode | pyqrcode/__init__.py | QRCode.svg | def svg(self, file, scale=1, module_color='#000', background=None,
quiet_zone=4, xmldecl=True, svgns=True, title=None,
svgclass='pyqrcode', lineclass='pyqrline', omithw=False,
debug=False):
"""This method writes the QR code out as an SVG document. The
code is drawn by drawing only the modules corresponding to a 1. They
are drawn using a line, such that contiguous modules in a row
are drawn with a single line.
The *file* parameter is used to specify where to write the document
to. It can either be a writable stream or a file path.
The *scale* parameter sets how large to draw
a single module. By default one pixel is used to draw a single
module. This may make the code too small to be read efficiently.
Increasing the scale will make the code larger. Unlike the png() method,
this method will accept fractional scales (e.g. 2.5).
Note, three things are done to make the code more appropriate for
embedding in a HTML document. The "white" part of the code is actually
transparent. The code itself has a class given by *svgclass* parameter.
The path making up the QR code uses the class set using the *lineclass*.
These should make the code easier to style using CSS.
By default the output of this function is a complete SVG document. If
only the code itself is desired, set the *xmldecl* to false. This will
result in a fragment that contains only the "drawn" portion of the code.
Likewise, you can set the *title* of the document. The SVG name space
attribute can be suppressed by setting *svgns* to False.
When True the *omithw* indicates if width and height attributes should
be omitted. If these attributes are omitted, a ``viewBox`` attribute
will be added to the document.
You can also set the colors directly using the *module_color* and
*background* parameters. The *module_color* parameter sets what color to
use for the data modules (the black part on most QR codes). The
*background* parameter sets what color to use for the background (the
white part on most QR codes). The parameters can be set to any valid
SVG or HTML color. If the background is set to None, then no background
will be drawn, i.e. the background will be transparent. Note, many color
combinations are unreadable by scanners, so be careful.
The *quiet_zone* parameter sets how wide the quiet zone around the code
should be. According to the standard this should be 4 modules. It is
left settable because such a wide quiet zone is unnecessary in many
applications where the QR code is not being printed.
Example:
>>> code = pyqrcode.create('Hello. Uhh, can we have your liver?')
>>> code.svg('live-organ-transplants.svg', 3.6)
>>> code.svg('live-organ-transplants.svg', scale=4,
module_color='brown', background='0xFFFFFF')
"""
builder._svg(self.code, self.version, file, scale=scale,
module_color=module_color, background=background,
quiet_zone=quiet_zone, xmldecl=xmldecl, svgns=svgns,
title=title, svgclass=svgclass, lineclass=lineclass,
omithw=omithw, debug=debug) | python | def svg(self, file, scale=1, module_color='#000', background=None,
quiet_zone=4, xmldecl=True, svgns=True, title=None,
svgclass='pyqrcode', lineclass='pyqrline', omithw=False,
debug=False):
"""This method writes the QR code out as an SVG document. The
code is drawn by drawing only the modules corresponding to a 1. They
are drawn using a line, such that contiguous modules in a row
are drawn with a single line.
The *file* parameter is used to specify where to write the document
to. It can either be a writable stream or a file path.
The *scale* parameter sets how large to draw
a single module. By default one pixel is used to draw a single
module. This may make the code too small to be read efficiently.
Increasing the scale will make the code larger. Unlike the png() method,
this method will accept fractional scales (e.g. 2.5).
Note, three things are done to make the code more appropriate for
embedding in a HTML document. The "white" part of the code is actually
transparent. The code itself has a class given by *svgclass* parameter.
The path making up the QR code uses the class set using the *lineclass*.
These should make the code easier to style using CSS.
By default the output of this function is a complete SVG document. If
only the code itself is desired, set the *xmldecl* to false. This will
result in a fragment that contains only the "drawn" portion of the code.
Likewise, you can set the *title* of the document. The SVG name space
attribute can be suppressed by setting *svgns* to False.
When True the *omithw* indicates if width and height attributes should
be omitted. If these attributes are omitted, a ``viewBox`` attribute
will be added to the document.
You can also set the colors directly using the *module_color* and
*background* parameters. The *module_color* parameter sets what color to
use for the data modules (the black part on most QR codes). The
*background* parameter sets what color to use for the background (the
white part on most QR codes). The parameters can be set to any valid
SVG or HTML color. If the background is set to None, then no background
will be drawn, i.e. the background will be transparent. Note, many color
combinations are unreadable by scanners, so be careful.
The *quiet_zone* parameter sets how wide the quiet zone around the code
should be. According to the standard this should be 4 modules. It is
left settable because such a wide quiet zone is unnecessary in many
applications where the QR code is not being printed.
Example:
>>> code = pyqrcode.create('Hello. Uhh, can we have your liver?')
>>> code.svg('live-organ-transplants.svg', 3.6)
>>> code.svg('live-organ-transplants.svg', scale=4,
module_color='brown', background='0xFFFFFF')
"""
builder._svg(self.code, self.version, file, scale=scale,
module_color=module_color, background=background,
quiet_zone=quiet_zone, xmldecl=xmldecl, svgns=svgns,
title=title, svgclass=svgclass, lineclass=lineclass,
omithw=omithw, debug=debug) | [
"def",
"svg",
"(",
"self",
",",
"file",
",",
"scale",
"=",
"1",
",",
"module_color",
"=",
"'#000'",
",",
"background",
"=",
"None",
",",
"quiet_zone",
"=",
"4",
",",
"xmldecl",
"=",
"True",
",",
"svgns",
"=",
"True",
",",
"title",
"=",
"None",
",",... | This method writes the QR code out as an SVG document. The
code is drawn by drawing only the modules corresponding to a 1. They
are drawn using a line, such that contiguous modules in a row
are drawn with a single line.
The *file* parameter is used to specify where to write the document
to. It can either be a writable stream or a file path.
The *scale* parameter sets how large to draw
a single module. By default one pixel is used to draw a single
module. This may make the code too small to be read efficiently.
Increasing the scale will make the code larger. Unlike the png() method,
this method will accept fractional scales (e.g. 2.5).
Note, three things are done to make the code more appropriate for
embedding in a HTML document. The "white" part of the code is actually
transparent. The code itself has a class given by *svgclass* parameter.
The path making up the QR code uses the class set using the *lineclass*.
These should make the code easier to style using CSS.
By default the output of this function is a complete SVG document. If
only the code itself is desired, set the *xmldecl* to false. This will
result in a fragment that contains only the "drawn" portion of the code.
Likewise, you can set the *title* of the document. The SVG name space
attribute can be suppressed by setting *svgns* to False.
When True the *omithw* indicates if width and height attributes should
be omitted. If these attributes are omitted, a ``viewBox`` attribute
will be added to the document.
You can also set the colors directly using the *module_color* and
*background* parameters. The *module_color* parameter sets what color to
use for the data modules (the black part on most QR codes). The
*background* parameter sets what color to use for the background (the
white part on most QR codes). The parameters can be set to any valid
SVG or HTML color. If the background is set to None, then no background
will be drawn, i.e. the background will be transparent. Note, many color
combinations are unreadable by scanners, so be careful.
The *quiet_zone* parameter sets how wide the quiet zone around the code
should be. According to the standard this should be 4 modules. It is
left settable because such a wide quiet zone is unnecessary in many
applications where the QR code is not being printed.
Example:
>>> code = pyqrcode.create('Hello. Uhh, can we have your liver?')
>>> code.svg('live-organ-transplants.svg', 3.6)
>>> code.svg('live-organ-transplants.svg', scale=4,
module_color='brown', background='0xFFFFFF') | [
"This",
"method",
"writes",
"the",
"QR",
"code",
"out",
"as",
"an",
"SVG",
"document",
".",
"The",
"code",
"is",
"drawn",
"by",
"drawing",
"only",
"the",
"modules",
"corresponding",
"to",
"a",
"1",
".",
"They",
"are",
"drawn",
"using",
"a",
"line",
"su... | 674a77b5eaf850d063f518bd90c243ee34ad6b5d | https://github.com/mnooner256/pyqrcode/blob/674a77b5eaf850d063f518bd90c243ee34ad6b5d/pyqrcode/__init__.py#L531-L589 | train | 48,063 |
mnooner256/pyqrcode | pyqrcode/__init__.py | QRCode.eps | def eps(self, file, scale=1, module_color=(0, 0, 0),
background=None, quiet_zone=4):
"""This method writes the QR code out as an EPS document. The
code is drawn by only writing the data modules corresponding to a 1.
They are drawn using a line, such that contiguous modules in a row
are drawn with a single line.
The *file* parameter is used to specify where to write the document
to. It can either be a writable (text) stream or a file path.
The *scale* parameter sets how large to draw a single module. By
default one point (1/72 inch) is used to draw a single module. This may
make the code to small to be read efficiently. Increasing the scale
will make the code larger. This method will accept fractional scales
(e.g. 2.5).
The *module_color* parameter sets the color of the data modules. The
*background* parameter sets the background (page) color to use. They
are specified as either a triple of floats, e.g. (0.5, 0.5, 0.5), or a
triple of integers, e.g. (128, 128, 128). The default *module_color* is
black. The default *background* color is no background at all.
The *quiet_zone* parameter sets how large to draw the border around
the code. As per the standard, the default value is 4 modules.
Examples:
>>> qr = pyqrcode.create('Hello world')
>>> qr.eps('hello-world.eps', scale=2.5, module_color='#36C')
>>> qr.eps('hello-world2.eps', background='#eee')
>>> out = io.StringIO()
>>> qr.eps(out, module_color=(.4, .4, .4))
"""
builder._eps(self.code, self.version, file, scale, module_color,
background, quiet_zone) | python | def eps(self, file, scale=1, module_color=(0, 0, 0),
background=None, quiet_zone=4):
"""This method writes the QR code out as an EPS document. The
code is drawn by only writing the data modules corresponding to a 1.
They are drawn using a line, such that contiguous modules in a row
are drawn with a single line.
The *file* parameter is used to specify where to write the document
to. It can either be a writable (text) stream or a file path.
The *scale* parameter sets how large to draw a single module. By
default one point (1/72 inch) is used to draw a single module. This may
make the code to small to be read efficiently. Increasing the scale
will make the code larger. This method will accept fractional scales
(e.g. 2.5).
The *module_color* parameter sets the color of the data modules. The
*background* parameter sets the background (page) color to use. They
are specified as either a triple of floats, e.g. (0.5, 0.5, 0.5), or a
triple of integers, e.g. (128, 128, 128). The default *module_color* is
black. The default *background* color is no background at all.
The *quiet_zone* parameter sets how large to draw the border around
the code. As per the standard, the default value is 4 modules.
Examples:
>>> qr = pyqrcode.create('Hello world')
>>> qr.eps('hello-world.eps', scale=2.5, module_color='#36C')
>>> qr.eps('hello-world2.eps', background='#eee')
>>> out = io.StringIO()
>>> qr.eps(out, module_color=(.4, .4, .4))
"""
builder._eps(self.code, self.version, file, scale, module_color,
background, quiet_zone) | [
"def",
"eps",
"(",
"self",
",",
"file",
",",
"scale",
"=",
"1",
",",
"module_color",
"=",
"(",
"0",
",",
"0",
",",
"0",
")",
",",
"background",
"=",
"None",
",",
"quiet_zone",
"=",
"4",
")",
":",
"builder",
".",
"_eps",
"(",
"self",
".",
"code"... | This method writes the QR code out as an EPS document. The
code is drawn by only writing the data modules corresponding to a 1.
They are drawn using a line, such that contiguous modules in a row
are drawn with a single line.
The *file* parameter is used to specify where to write the document
to. It can either be a writable (text) stream or a file path.
The *scale* parameter sets how large to draw a single module. By
default one point (1/72 inch) is used to draw a single module. This may
make the code to small to be read efficiently. Increasing the scale
will make the code larger. This method will accept fractional scales
(e.g. 2.5).
The *module_color* parameter sets the color of the data modules. The
*background* parameter sets the background (page) color to use. They
are specified as either a triple of floats, e.g. (0.5, 0.5, 0.5), or a
triple of integers, e.g. (128, 128, 128). The default *module_color* is
black. The default *background* color is no background at all.
The *quiet_zone* parameter sets how large to draw the border around
the code. As per the standard, the default value is 4 modules.
Examples:
>>> qr = pyqrcode.create('Hello world')
>>> qr.eps('hello-world.eps', scale=2.5, module_color='#36C')
>>> qr.eps('hello-world2.eps', background='#eee')
>>> out = io.StringIO()
>>> qr.eps(out, module_color=(.4, .4, .4)) | [
"This",
"method",
"writes",
"the",
"QR",
"code",
"out",
"as",
"an",
"EPS",
"document",
".",
"The",
"code",
"is",
"drawn",
"by",
"only",
"writing",
"the",
"data",
"modules",
"corresponding",
"to",
"a",
"1",
".",
"They",
"are",
"drawn",
"using",
"a",
"li... | 674a77b5eaf850d063f518bd90c243ee34ad6b5d | https://github.com/mnooner256/pyqrcode/blob/674a77b5eaf850d063f518bd90c243ee34ad6b5d/pyqrcode/__init__.py#L591-L624 | train | 48,064 |
mnooner256/pyqrcode | pyqrcode/__init__.py | QRCode.terminal | def terminal(self, module_color='default', background='reverse',
quiet_zone=4):
"""This method returns a string containing ASCII escape codes,
such that if printed to a compatible terminal, it will display
a vaild QR code. The code is printed using ASCII escape
codes that alter the coloring of the background.
The *module_color* parameter sets what color to
use for the data modules (the black part on most QR codes).
Likewise, the *background* parameter sets what color to use
for the background (the white part on most QR codes).
There are two options for colors. The first, and most widely
supported, is to use the 8 or 16 color scheme. This scheme uses
eight to sixteen named colors. The following colors are
supported the most widely supported: black, red, green,
yellow, blue, magenta, and cyan. There are an some additional
named colors that are supported by most terminals: light gray,
dark gray, light red, light green, light blue, light yellow,
light magenta, light cyan, and white.
There are two special named colors. The first is the
"default" color. This color is the color the background of
the terminal is set to. The next color is the "reverse"
color. This is not really a color at all but a special
property that will reverse the current color. These two colors
are the default values for *module_color* and *background*
respectively. These values should work on most terminals.
Finally, there is one more way to specify the color. Some
terminals support 256 colors. The actual colors displayed in the
terminal is system dependent. This is the least transportable option.
To use the 256 color scheme set *module_color* and/or
*background* to a number between 0 and 256.
The *quiet_zone* parameter sets how wide the quiet zone around the code
should be. According to the standard this should be 4 modules. It is
left settable because such a wide quiet zone is unnecessary in many
applications.
Example:
>>> code = pyqrcode.create('Example')
>>> text = code.terminal()
>>> print(text)
"""
return builder._terminal(self.code, module_color, background,
quiet_zone) | python | def terminal(self, module_color='default', background='reverse',
quiet_zone=4):
"""This method returns a string containing ASCII escape codes,
such that if printed to a compatible terminal, it will display
a vaild QR code. The code is printed using ASCII escape
codes that alter the coloring of the background.
The *module_color* parameter sets what color to
use for the data modules (the black part on most QR codes).
Likewise, the *background* parameter sets what color to use
for the background (the white part on most QR codes).
There are two options for colors. The first, and most widely
supported, is to use the 8 or 16 color scheme. This scheme uses
eight to sixteen named colors. The following colors are
supported the most widely supported: black, red, green,
yellow, blue, magenta, and cyan. There are an some additional
named colors that are supported by most terminals: light gray,
dark gray, light red, light green, light blue, light yellow,
light magenta, light cyan, and white.
There are two special named colors. The first is the
"default" color. This color is the color the background of
the terminal is set to. The next color is the "reverse"
color. This is not really a color at all but a special
property that will reverse the current color. These two colors
are the default values for *module_color* and *background*
respectively. These values should work on most terminals.
Finally, there is one more way to specify the color. Some
terminals support 256 colors. The actual colors displayed in the
terminal is system dependent. This is the least transportable option.
To use the 256 color scheme set *module_color* and/or
*background* to a number between 0 and 256.
The *quiet_zone* parameter sets how wide the quiet zone around the code
should be. According to the standard this should be 4 modules. It is
left settable because such a wide quiet zone is unnecessary in many
applications.
Example:
>>> code = pyqrcode.create('Example')
>>> text = code.terminal()
>>> print(text)
"""
return builder._terminal(self.code, module_color, background,
quiet_zone) | [
"def",
"terminal",
"(",
"self",
",",
"module_color",
"=",
"'default'",
",",
"background",
"=",
"'reverse'",
",",
"quiet_zone",
"=",
"4",
")",
":",
"return",
"builder",
".",
"_terminal",
"(",
"self",
".",
"code",
",",
"module_color",
",",
"background",
",",... | This method returns a string containing ASCII escape codes,
such that if printed to a compatible terminal, it will display
a vaild QR code. The code is printed using ASCII escape
codes that alter the coloring of the background.
The *module_color* parameter sets what color to
use for the data modules (the black part on most QR codes).
Likewise, the *background* parameter sets what color to use
for the background (the white part on most QR codes).
There are two options for colors. The first, and most widely
supported, is to use the 8 or 16 color scheme. This scheme uses
eight to sixteen named colors. The following colors are
supported the most widely supported: black, red, green,
yellow, blue, magenta, and cyan. There are an some additional
named colors that are supported by most terminals: light gray,
dark gray, light red, light green, light blue, light yellow,
light magenta, light cyan, and white.
There are two special named colors. The first is the
"default" color. This color is the color the background of
the terminal is set to. The next color is the "reverse"
color. This is not really a color at all but a special
property that will reverse the current color. These two colors
are the default values for *module_color* and *background*
respectively. These values should work on most terminals.
Finally, there is one more way to specify the color. Some
terminals support 256 colors. The actual colors displayed in the
terminal is system dependent. This is the least transportable option.
To use the 256 color scheme set *module_color* and/or
*background* to a number between 0 and 256.
The *quiet_zone* parameter sets how wide the quiet zone around the code
should be. According to the standard this should be 4 modules. It is
left settable because such a wide quiet zone is unnecessary in many
applications.
Example:
>>> code = pyqrcode.create('Example')
>>> text = code.terminal()
>>> print(text) | [
"This",
"method",
"returns",
"a",
"string",
"containing",
"ASCII",
"escape",
"codes",
"such",
"that",
"if",
"printed",
"to",
"a",
"compatible",
"terminal",
"it",
"will",
"display",
"a",
"vaild",
"QR",
"code",
".",
"The",
"code",
"is",
"printed",
"using",
"... | 674a77b5eaf850d063f518bd90c243ee34ad6b5d | https://github.com/mnooner256/pyqrcode/blob/674a77b5eaf850d063f518bd90c243ee34ad6b5d/pyqrcode/__init__.py#L626-L672 | train | 48,065 |
mnooner256/pyqrcode | pyqrcode/builder.py | _get_writable | def _get_writable(stream_or_path, mode):
"""This method returns a tuple containing the stream and a flag to indicate
if the stream should be automatically closed.
The `stream_or_path` parameter is returned if it is an open writable stream.
Otherwise, it treats the `stream_or_path` parameter as a file path and
opens it with the given mode.
It is used by the svg and png methods to interpret the file parameter.
:type stream_or_path: str | io.BufferedIOBase
:type mode: str | unicode
:rtype: (io.BufferedIOBase, bool)
"""
is_stream = hasattr(stream_or_path, 'write')
if not is_stream:
# No stream provided, treat "stream_or_path" as path
stream_or_path = open(stream_or_path, mode)
return stream_or_path, not is_stream | python | def _get_writable(stream_or_path, mode):
"""This method returns a tuple containing the stream and a flag to indicate
if the stream should be automatically closed.
The `stream_or_path` parameter is returned if it is an open writable stream.
Otherwise, it treats the `stream_or_path` parameter as a file path and
opens it with the given mode.
It is used by the svg and png methods to interpret the file parameter.
:type stream_or_path: str | io.BufferedIOBase
:type mode: str | unicode
:rtype: (io.BufferedIOBase, bool)
"""
is_stream = hasattr(stream_or_path, 'write')
if not is_stream:
# No stream provided, treat "stream_or_path" as path
stream_or_path = open(stream_or_path, mode)
return stream_or_path, not is_stream | [
"def",
"_get_writable",
"(",
"stream_or_path",
",",
"mode",
")",
":",
"is_stream",
"=",
"hasattr",
"(",
"stream_or_path",
",",
"'write'",
")",
"if",
"not",
"is_stream",
":",
"# No stream provided, treat \"stream_or_path\" as path",
"stream_or_path",
"=",
"open",
"(",
... | This method returns a tuple containing the stream and a flag to indicate
if the stream should be automatically closed.
The `stream_or_path` parameter is returned if it is an open writable stream.
Otherwise, it treats the `stream_or_path` parameter as a file path and
opens it with the given mode.
It is used by the svg and png methods to interpret the file parameter.
:type stream_or_path: str | io.BufferedIOBase
:type mode: str | unicode
:rtype: (io.BufferedIOBase, bool) | [
"This",
"method",
"returns",
"a",
"tuple",
"containing",
"the",
"stream",
"and",
"a",
"flag",
"to",
"indicate",
"if",
"the",
"stream",
"should",
"be",
"automatically",
"closed",
"."
] | 674a77b5eaf850d063f518bd90c243ee34ad6b5d | https://github.com/mnooner256/pyqrcode/blob/674a77b5eaf850d063f518bd90c243ee34ad6b5d/pyqrcode/builder.py#L907-L925 | train | 48,066 |
mnooner256/pyqrcode | pyqrcode/builder.py | _text | def _text(code, quiet_zone=4):
"""This method returns a text based representation of the QR code.
This is useful for debugging purposes.
"""
buf = io.StringIO()
border_row = '0' * (len(code[0]) + (quiet_zone*2))
#Every QR code start with a quiet zone at the top
for b in range(quiet_zone):
buf.write(border_row)
buf.write('\n')
for row in code:
#Draw the starting quiet zone
for b in range(quiet_zone):
buf.write('0')
#Actually draw the QR code
for bit in row:
if bit == 1:
buf.write('1')
elif bit == 0:
buf.write('0')
#This is for debugging unfinished QR codes,
#unset pixels will be spaces.
else:
buf.write(' ')
#Draw the ending quiet zone
for b in range(quiet_zone):
buf.write('0')
buf.write('\n')
#Every QR code ends with a quiet zone at the bottom
for b in range(quiet_zone):
buf.write(border_row)
buf.write('\n')
return buf.getvalue() | python | def _text(code, quiet_zone=4):
"""This method returns a text based representation of the QR code.
This is useful for debugging purposes.
"""
buf = io.StringIO()
border_row = '0' * (len(code[0]) + (quiet_zone*2))
#Every QR code start with a quiet zone at the top
for b in range(quiet_zone):
buf.write(border_row)
buf.write('\n')
for row in code:
#Draw the starting quiet zone
for b in range(quiet_zone):
buf.write('0')
#Actually draw the QR code
for bit in row:
if bit == 1:
buf.write('1')
elif bit == 0:
buf.write('0')
#This is for debugging unfinished QR codes,
#unset pixels will be spaces.
else:
buf.write(' ')
#Draw the ending quiet zone
for b in range(quiet_zone):
buf.write('0')
buf.write('\n')
#Every QR code ends with a quiet zone at the bottom
for b in range(quiet_zone):
buf.write(border_row)
buf.write('\n')
return buf.getvalue() | [
"def",
"_text",
"(",
"code",
",",
"quiet_zone",
"=",
"4",
")",
":",
"buf",
"=",
"io",
".",
"StringIO",
"(",
")",
"border_row",
"=",
"'0'",
"*",
"(",
"len",
"(",
"code",
"[",
"0",
"]",
")",
"+",
"(",
"quiet_zone",
"*",
"2",
")",
")",
"#Every QR ... | This method returns a text based representation of the QR code.
This is useful for debugging purposes. | [
"This",
"method",
"returns",
"a",
"text",
"based",
"representation",
"of",
"the",
"QR",
"code",
".",
"This",
"is",
"useful",
"for",
"debugging",
"purposes",
"."
] | 674a77b5eaf850d063f518bd90c243ee34ad6b5d | https://github.com/mnooner256/pyqrcode/blob/674a77b5eaf850d063f518bd90c243ee34ad6b5d/pyqrcode/builder.py#L1016-L1055 | train | 48,067 |
mnooner256/pyqrcode | pyqrcode/builder.py | _xbm | def _xbm(code, scale=1, quiet_zone=4):
"""This function will format the QR code as a X BitMap.
This can be used to display the QR code with Tkinter.
"""
try:
str = unicode # Python 2
except NameError:
str = __builtins__['str']
buf = io.StringIO()
# Calculate the width in pixels
pixel_width = (len(code[0]) + quiet_zone * 2) * scale
# Add the size information and open the pixel data section
buf.write('#define im_width ')
buf.write(str(pixel_width))
buf.write('\n')
buf.write('#define im_height ')
buf.write(str(pixel_width))
buf.write('\n')
buf.write('static char im_bits[] = {\n')
# Calculate the number of bytes per row
byte_width = int(math.ceil(pixel_width / 8.0))
# Add the top quiet zone
buf.write(('0x00,' * byte_width + '\n') * quiet_zone * scale)
for row in code:
# Add the left quiet zone
row_bits = '0' * quiet_zone * scale
# Add the actual QR code
for pixel in row:
row_bits += str(pixel) * scale
# Add the right quiet zone
row_bits += '0' * quiet_zone * scale
# Format the row
formated_row = ''
for b in range(byte_width):
formated_row += '0x{0:02x},'.format(int(row_bits[:8][::-1], 2))
row_bits = row_bits[8:]
formated_row += '\n'
# Add the formatted row
buf.write(formated_row * scale)
# Add the bottom quiet zone and close the pixel data section
buf.write(('0x00,' * byte_width + '\n') * quiet_zone * scale)
buf.write('};')
return buf.getvalue() | python | def _xbm(code, scale=1, quiet_zone=4):
"""This function will format the QR code as a X BitMap.
This can be used to display the QR code with Tkinter.
"""
try:
str = unicode # Python 2
except NameError:
str = __builtins__['str']
buf = io.StringIO()
# Calculate the width in pixels
pixel_width = (len(code[0]) + quiet_zone * 2) * scale
# Add the size information and open the pixel data section
buf.write('#define im_width ')
buf.write(str(pixel_width))
buf.write('\n')
buf.write('#define im_height ')
buf.write(str(pixel_width))
buf.write('\n')
buf.write('static char im_bits[] = {\n')
# Calculate the number of bytes per row
byte_width = int(math.ceil(pixel_width / 8.0))
# Add the top quiet zone
buf.write(('0x00,' * byte_width + '\n') * quiet_zone * scale)
for row in code:
# Add the left quiet zone
row_bits = '0' * quiet_zone * scale
# Add the actual QR code
for pixel in row:
row_bits += str(pixel) * scale
# Add the right quiet zone
row_bits += '0' * quiet_zone * scale
# Format the row
formated_row = ''
for b in range(byte_width):
formated_row += '0x{0:02x},'.format(int(row_bits[:8][::-1], 2))
row_bits = row_bits[8:]
formated_row += '\n'
# Add the formatted row
buf.write(formated_row * scale)
# Add the bottom quiet zone and close the pixel data section
buf.write(('0x00,' * byte_width + '\n') * quiet_zone * scale)
buf.write('};')
return buf.getvalue() | [
"def",
"_xbm",
"(",
"code",
",",
"scale",
"=",
"1",
",",
"quiet_zone",
"=",
"4",
")",
":",
"try",
":",
"str",
"=",
"unicode",
"# Python 2",
"except",
"NameError",
":",
"str",
"=",
"__builtins__",
"[",
"'str'",
"]",
"buf",
"=",
"io",
".",
"StringIO",
... | This function will format the QR code as a X BitMap.
This can be used to display the QR code with Tkinter. | [
"This",
"function",
"will",
"format",
"the",
"QR",
"code",
"as",
"a",
"X",
"BitMap",
".",
"This",
"can",
"be",
"used",
"to",
"display",
"the",
"QR",
"code",
"with",
"Tkinter",
"."
] | 674a77b5eaf850d063f518bd90c243ee34ad6b5d | https://github.com/mnooner256/pyqrcode/blob/674a77b5eaf850d063f518bd90c243ee34ad6b5d/pyqrcode/builder.py#L1057-L1105 | train | 48,068 |
mnooner256/pyqrcode | pyqrcode/builder.py | _hex_to_rgb | def _hex_to_rgb(color):
"""\
Helper function to convert a color provided in hexadecimal format
as RGB triple.
"""
if color[0] == '#':
color = color[1:]
if len(color) == 3:
color = color[0] * 2 + color[1] * 2 + color[2] * 2
if len(color) != 6:
raise ValueError('Input #{0} is not in #RRGGBB format'.format(color))
return [int(n, 16) for n in (color[:2], color[2:4], color[4:])] | python | def _hex_to_rgb(color):
"""\
Helper function to convert a color provided in hexadecimal format
as RGB triple.
"""
if color[0] == '#':
color = color[1:]
if len(color) == 3:
color = color[0] * 2 + color[1] * 2 + color[2] * 2
if len(color) != 6:
raise ValueError('Input #{0} is not in #RRGGBB format'.format(color))
return [int(n, 16) for n in (color[:2], color[2:4], color[4:])] | [
"def",
"_hex_to_rgb",
"(",
"color",
")",
":",
"if",
"color",
"[",
"0",
"]",
"==",
"'#'",
":",
"color",
"=",
"color",
"[",
"1",
":",
"]",
"if",
"len",
"(",
"color",
")",
"==",
"3",
":",
"color",
"=",
"color",
"[",
"0",
"]",
"*",
"2",
"+",
"c... | \
Helper function to convert a color provided in hexadecimal format
as RGB triple. | [
"\\",
"Helper",
"function",
"to",
"convert",
"a",
"color",
"provided",
"in",
"hexadecimal",
"format",
"as",
"RGB",
"triple",
"."
] | 674a77b5eaf850d063f518bd90c243ee34ad6b5d | https://github.com/mnooner256/pyqrcode/blob/674a77b5eaf850d063f518bd90c243ee34ad6b5d/pyqrcode/builder.py#L1517-L1528 | train | 48,069 |
mnooner256/pyqrcode | pyqrcode/builder.py | QRCodeBuilder.grouper | def grouper(self, n, iterable, fillvalue=None):
"""This generator yields a set of tuples, where the
iterable is broken into n sized chunks. If the
iterable is not evenly sized then fillvalue will
be appended to the last tuple to make up the difference.
This function is copied from the standard docs on
itertools.
"""
args = [iter(iterable)] * n
if hasattr(itertools, 'zip_longest'):
return itertools.zip_longest(*args, fillvalue=fillvalue)
return itertools.izip_longest(*args, fillvalue=fillvalue) | python | def grouper(self, n, iterable, fillvalue=None):
"""This generator yields a set of tuples, where the
iterable is broken into n sized chunks. If the
iterable is not evenly sized then fillvalue will
be appended to the last tuple to make up the difference.
This function is copied from the standard docs on
itertools.
"""
args = [iter(iterable)] * n
if hasattr(itertools, 'zip_longest'):
return itertools.zip_longest(*args, fillvalue=fillvalue)
return itertools.izip_longest(*args, fillvalue=fillvalue) | [
"def",
"grouper",
"(",
"self",
",",
"n",
",",
"iterable",
",",
"fillvalue",
"=",
"None",
")",
":",
"args",
"=",
"[",
"iter",
"(",
"iterable",
")",
"]",
"*",
"n",
"if",
"hasattr",
"(",
"itertools",
",",
"'zip_longest'",
")",
":",
"return",
"itertools"... | This generator yields a set of tuples, where the
iterable is broken into n sized chunks. If the
iterable is not evenly sized then fillvalue will
be appended to the last tuple to make up the difference.
This function is copied from the standard docs on
itertools. | [
"This",
"generator",
"yields",
"a",
"set",
"of",
"tuples",
"where",
"the",
"iterable",
"is",
"broken",
"into",
"n",
"sized",
"chunks",
".",
"If",
"the",
"iterable",
"is",
"not",
"evenly",
"sized",
"then",
"fillvalue",
"will",
"be",
"appended",
"to",
"the",... | 674a77b5eaf850d063f518bd90c243ee34ad6b5d | https://github.com/mnooner256/pyqrcode/blob/674a77b5eaf850d063f518bd90c243ee34ad6b5d/pyqrcode/builder.py#L98-L110 | train | 48,070 |
mnooner256/pyqrcode | pyqrcode/builder.py | QRCodeBuilder.get_data_length | def get_data_length(self):
"""QR codes contain a "data length" field. This method creates this
field. A binary string representing the appropriate length is
returned.
"""
#The "data length" field varies by the type of code and its mode.
#discover how long the "data length" field should be.
if 1 <= self.version <= 9:
max_version = 9
elif 10 <= self.version <= 26:
max_version = 26
elif 27 <= self.version <= 40:
max_version = 40
data_length = tables.data_length_field[max_version][self.mode]
if self.mode != tables.modes['kanji']:
length_string = self.binary_string(len(self.data), data_length)
else:
length_string = self.binary_string(len(self.data) / 2, data_length)
if len(length_string) > data_length:
raise ValueError('The supplied data will not fit '
'within this version of a QRCode.')
return length_string | python | def get_data_length(self):
"""QR codes contain a "data length" field. This method creates this
field. A binary string representing the appropriate length is
returned.
"""
#The "data length" field varies by the type of code and its mode.
#discover how long the "data length" field should be.
if 1 <= self.version <= 9:
max_version = 9
elif 10 <= self.version <= 26:
max_version = 26
elif 27 <= self.version <= 40:
max_version = 40
data_length = tables.data_length_field[max_version][self.mode]
if self.mode != tables.modes['kanji']:
length_string = self.binary_string(len(self.data), data_length)
else:
length_string = self.binary_string(len(self.data) / 2, data_length)
if len(length_string) > data_length:
raise ValueError('The supplied data will not fit '
'within this version of a QRCode.')
return length_string | [
"def",
"get_data_length",
"(",
"self",
")",
":",
"#The \"data length\" field varies by the type of code and its mode.",
"#discover how long the \"data length\" field should be.",
"if",
"1",
"<=",
"self",
".",
"version",
"<=",
"9",
":",
"max_version",
"=",
"9",
"elif",
"10",... | QR codes contain a "data length" field. This method creates this
field. A binary string representing the appropriate length is
returned. | [
"QR",
"codes",
"contain",
"a",
"data",
"length",
"field",
".",
"This",
"method",
"creates",
"this",
"field",
".",
"A",
"binary",
"string",
"representing",
"the",
"appropriate",
"length",
"is",
"returned",
"."
] | 674a77b5eaf850d063f518bd90c243ee34ad6b5d | https://github.com/mnooner256/pyqrcode/blob/674a77b5eaf850d063f518bd90c243ee34ad6b5d/pyqrcode/builder.py#L119-L144 | train | 48,071 |
mnooner256/pyqrcode | pyqrcode/builder.py | QRCodeBuilder.encode | def encode(self):
"""This method encodes the data into a binary string using
the appropriate algorithm specified by the mode.
"""
if self.mode == tables.modes['alphanumeric']:
encoded = self.encode_alphanumeric()
elif self.mode == tables.modes['numeric']:
encoded = self.encode_numeric()
elif self.mode == tables.modes['binary']:
encoded = self.encode_bytes()
elif self.mode == tables.modes['kanji']:
encoded = self.encode_kanji()
return encoded | python | def encode(self):
"""This method encodes the data into a binary string using
the appropriate algorithm specified by the mode.
"""
if self.mode == tables.modes['alphanumeric']:
encoded = self.encode_alphanumeric()
elif self.mode == tables.modes['numeric']:
encoded = self.encode_numeric()
elif self.mode == tables.modes['binary']:
encoded = self.encode_bytes()
elif self.mode == tables.modes['kanji']:
encoded = self.encode_kanji()
return encoded | [
"def",
"encode",
"(",
"self",
")",
":",
"if",
"self",
".",
"mode",
"==",
"tables",
".",
"modes",
"[",
"'alphanumeric'",
"]",
":",
"encoded",
"=",
"self",
".",
"encode_alphanumeric",
"(",
")",
"elif",
"self",
".",
"mode",
"==",
"tables",
".",
"modes",
... | This method encodes the data into a binary string using
the appropriate algorithm specified by the mode. | [
"This",
"method",
"encodes",
"the",
"data",
"into",
"a",
"binary",
"string",
"using",
"the",
"appropriate",
"algorithm",
"specified",
"by",
"the",
"mode",
"."
] | 674a77b5eaf850d063f518bd90c243ee34ad6b5d | https://github.com/mnooner256/pyqrcode/blob/674a77b5eaf850d063f518bd90c243ee34ad6b5d/pyqrcode/builder.py#L146-L158 | train | 48,072 |
mnooner256/pyqrcode | pyqrcode/builder.py | QRCodeBuilder.encode_alphanumeric | def encode_alphanumeric(self):
"""This method encodes the QR code's data if its mode is
alphanumeric. It returns the data encoded as a binary string.
"""
#Convert the string to upper case
self.data = self.data.upper()
#Change the data such that it uses a QR code ascii table
ascii = []
for char in self.data:
if isinstance(char, int):
ascii.append(tables.ascii_codes[chr(char)])
else:
ascii.append(tables.ascii_codes[char])
#Now perform the algorithm that will make the ascii into bit fields
with io.StringIO() as buf:
for (a,b) in self.grouper(2, ascii):
if b is not None:
buf.write(self.binary_string((45*a)+b, 11))
else:
#This occurs when there is an odd number
#of characters in the data
buf.write(self.binary_string(a, 6))
#Return the binary string
return buf.getvalue() | python | def encode_alphanumeric(self):
"""This method encodes the QR code's data if its mode is
alphanumeric. It returns the data encoded as a binary string.
"""
#Convert the string to upper case
self.data = self.data.upper()
#Change the data such that it uses a QR code ascii table
ascii = []
for char in self.data:
if isinstance(char, int):
ascii.append(tables.ascii_codes[chr(char)])
else:
ascii.append(tables.ascii_codes[char])
#Now perform the algorithm that will make the ascii into bit fields
with io.StringIO() as buf:
for (a,b) in self.grouper(2, ascii):
if b is not None:
buf.write(self.binary_string((45*a)+b, 11))
else:
#This occurs when there is an odd number
#of characters in the data
buf.write(self.binary_string(a, 6))
#Return the binary string
return buf.getvalue() | [
"def",
"encode_alphanumeric",
"(",
"self",
")",
":",
"#Convert the string to upper case",
"self",
".",
"data",
"=",
"self",
".",
"data",
".",
"upper",
"(",
")",
"#Change the data such that it uses a QR code ascii table",
"ascii",
"=",
"[",
"]",
"for",
"char",
"in",
... | This method encodes the QR code's data if its mode is
alphanumeric. It returns the data encoded as a binary string. | [
"This",
"method",
"encodes",
"the",
"QR",
"code",
"s",
"data",
"if",
"its",
"mode",
"is",
"alphanumeric",
".",
"It",
"returns",
"the",
"data",
"encoded",
"as",
"a",
"binary",
"string",
"."
] | 674a77b5eaf850d063f518bd90c243ee34ad6b5d | https://github.com/mnooner256/pyqrcode/blob/674a77b5eaf850d063f518bd90c243ee34ad6b5d/pyqrcode/builder.py#L160-L186 | train | 48,073 |
mnooner256/pyqrcode | pyqrcode/builder.py | QRCodeBuilder.encode_numeric | def encode_numeric(self):
"""This method encodes the QR code's data if its mode is
numeric. It returns the data encoded as a binary string.
"""
with io.StringIO() as buf:
#Break the number into groups of three digits
for triplet in self.grouper(3, self.data):
number = ''
for digit in triplet:
if isinstance(digit, int):
digit = chr(digit)
#Only build the string if digit is not None
if digit:
number = ''.join([number, digit])
else:
break
#If the number is one digits, make a 4 bit field
if len(number) == 1:
bin = self.binary_string(number, 4)
#If the number is two digits, make a 7 bit field
elif len(number) == 2:
bin = self.binary_string(number, 7)
#Three digit numbers use a 10 bit field
else:
bin = self.binary_string(number, 10)
buf.write(bin)
return buf.getvalue() | python | def encode_numeric(self):
"""This method encodes the QR code's data if its mode is
numeric. It returns the data encoded as a binary string.
"""
with io.StringIO() as buf:
#Break the number into groups of three digits
for triplet in self.grouper(3, self.data):
number = ''
for digit in triplet:
if isinstance(digit, int):
digit = chr(digit)
#Only build the string if digit is not None
if digit:
number = ''.join([number, digit])
else:
break
#If the number is one digits, make a 4 bit field
if len(number) == 1:
bin = self.binary_string(number, 4)
#If the number is two digits, make a 7 bit field
elif len(number) == 2:
bin = self.binary_string(number, 7)
#Three digit numbers use a 10 bit field
else:
bin = self.binary_string(number, 10)
buf.write(bin)
return buf.getvalue() | [
"def",
"encode_numeric",
"(",
"self",
")",
":",
"with",
"io",
".",
"StringIO",
"(",
")",
"as",
"buf",
":",
"#Break the number into groups of three digits",
"for",
"triplet",
"in",
"self",
".",
"grouper",
"(",
"3",
",",
"self",
".",
"data",
")",
":",
"numbe... | This method encodes the QR code's data if its mode is
numeric. It returns the data encoded as a binary string. | [
"This",
"method",
"encodes",
"the",
"QR",
"code",
"s",
"data",
"if",
"its",
"mode",
"is",
"numeric",
".",
"It",
"returns",
"the",
"data",
"encoded",
"as",
"a",
"binary",
"string",
"."
] | 674a77b5eaf850d063f518bd90c243ee34ad6b5d | https://github.com/mnooner256/pyqrcode/blob/674a77b5eaf850d063f518bd90c243ee34ad6b5d/pyqrcode/builder.py#L188-L219 | train | 48,074 |
mnooner256/pyqrcode | pyqrcode/builder.py | QRCodeBuilder.encode_bytes | def encode_bytes(self):
"""This method encodes the QR code's data if its mode is
8 bit mode. It returns the data encoded as a binary string.
"""
with io.StringIO() as buf:
for char in self.data:
if not isinstance(char, int):
buf.write('{{0:0{0}b}}'.format(8).format(ord(char)))
else:
buf.write('{{0:0{0}b}}'.format(8).format(char))
return buf.getvalue() | python | def encode_bytes(self):
"""This method encodes the QR code's data if its mode is
8 bit mode. It returns the data encoded as a binary string.
"""
with io.StringIO() as buf:
for char in self.data:
if not isinstance(char, int):
buf.write('{{0:0{0}b}}'.format(8).format(ord(char)))
else:
buf.write('{{0:0{0}b}}'.format(8).format(char))
return buf.getvalue() | [
"def",
"encode_bytes",
"(",
"self",
")",
":",
"with",
"io",
".",
"StringIO",
"(",
")",
"as",
"buf",
":",
"for",
"char",
"in",
"self",
".",
"data",
":",
"if",
"not",
"isinstance",
"(",
"char",
",",
"int",
")",
":",
"buf",
".",
"write",
"(",
"'{{0:... | This method encodes the QR code's data if its mode is
8 bit mode. It returns the data encoded as a binary string. | [
"This",
"method",
"encodes",
"the",
"QR",
"code",
"s",
"data",
"if",
"its",
"mode",
"is",
"8",
"bit",
"mode",
".",
"It",
"returns",
"the",
"data",
"encoded",
"as",
"a",
"binary",
"string",
"."
] | 674a77b5eaf850d063f518bd90c243ee34ad6b5d | https://github.com/mnooner256/pyqrcode/blob/674a77b5eaf850d063f518bd90c243ee34ad6b5d/pyqrcode/builder.py#L221-L231 | train | 48,075 |
mnooner256/pyqrcode | pyqrcode/builder.py | QRCodeBuilder.encode_kanji | def encode_kanji(self):
"""This method encodes the QR code's data if its mode is
kanji. It returns the data encoded as a binary string.
"""
def two_bytes(data):
"""Output two byte character code as a single integer."""
def next_byte(b):
"""Make sure that character code is an int. Python 2 and
3 compatibility.
"""
if not isinstance(b, int):
return ord(b)
else:
return b
#Go through the data by looping to every other character
for i in range(0, len(data), 2):
yield (next_byte(data[i]) << 8) | next_byte(data[i+1])
#Force the data into Kanji encoded bytes
if isinstance(self.data, bytes):
data = self.data.decode('shiftjis').encode('shiftjis')
else:
data = self.data.encode('shiftjis')
#Now perform the algorithm that will make the kanji into 13 bit fields
with io.StringIO() as buf:
for asint in two_bytes(data):
#Shift the two byte value as indicated by the standard
if 0x8140 <= asint <= 0x9FFC:
difference = asint - 0x8140
elif 0xE040 <= asint <= 0xEBBF:
difference = asint - 0xC140
#Split the new value into most and least significant bytes
msb = (difference >> 8)
lsb = (difference & 0x00FF)
#Calculate the actual 13 bit binary value
buf.write('{0:013b}'.format((msb * 0xC0) + lsb))
#Return the binary string
return buf.getvalue() | python | def encode_kanji(self):
"""This method encodes the QR code's data if its mode is
kanji. It returns the data encoded as a binary string.
"""
def two_bytes(data):
"""Output two byte character code as a single integer."""
def next_byte(b):
"""Make sure that character code is an int. Python 2 and
3 compatibility.
"""
if not isinstance(b, int):
return ord(b)
else:
return b
#Go through the data by looping to every other character
for i in range(0, len(data), 2):
yield (next_byte(data[i]) << 8) | next_byte(data[i+1])
#Force the data into Kanji encoded bytes
if isinstance(self.data, bytes):
data = self.data.decode('shiftjis').encode('shiftjis')
else:
data = self.data.encode('shiftjis')
#Now perform the algorithm that will make the kanji into 13 bit fields
with io.StringIO() as buf:
for asint in two_bytes(data):
#Shift the two byte value as indicated by the standard
if 0x8140 <= asint <= 0x9FFC:
difference = asint - 0x8140
elif 0xE040 <= asint <= 0xEBBF:
difference = asint - 0xC140
#Split the new value into most and least significant bytes
msb = (difference >> 8)
lsb = (difference & 0x00FF)
#Calculate the actual 13 bit binary value
buf.write('{0:013b}'.format((msb * 0xC0) + lsb))
#Return the binary string
return buf.getvalue() | [
"def",
"encode_kanji",
"(",
"self",
")",
":",
"def",
"two_bytes",
"(",
"data",
")",
":",
"\"\"\"Output two byte character code as a single integer.\"\"\"",
"def",
"next_byte",
"(",
"b",
")",
":",
"\"\"\"Make sure that character code is an int. Python 2 and\n 3 co... | This method encodes the QR code's data if its mode is
kanji. It returns the data encoded as a binary string. | [
"This",
"method",
"encodes",
"the",
"QR",
"code",
"s",
"data",
"if",
"its",
"mode",
"is",
"kanji",
".",
"It",
"returns",
"the",
"data",
"encoded",
"as",
"a",
"binary",
"string",
"."
] | 674a77b5eaf850d063f518bd90c243ee34ad6b5d | https://github.com/mnooner256/pyqrcode/blob/674a77b5eaf850d063f518bd90c243ee34ad6b5d/pyqrcode/builder.py#L233-L274 | train | 48,076 |
mnooner256/pyqrcode | pyqrcode/builder.py | QRCodeBuilder.add_data | def add_data(self):
"""This function properly constructs a QR code's data string. It takes
into account the interleaving pattern required by the standard.
"""
#Encode the data into a QR code
self.buffer.write(self.binary_string(self.mode, 4))
self.buffer.write(self.get_data_length())
self.buffer.write(self.encode())
#Converts the buffer into "code word" integers.
#The online debugger outputs them this way, makes
#for easier comparisons.
#s = self.buffer.getvalue()
#for i in range(0, len(s), 8):
# print(int(s[i:i+8], 2), end=',')
#print()
#Fix for issue #3: https://github.com/mnooner256/pyqrcode/issues/3#
#I was performing the terminate_bits() part in the encoding.
#As per the standard, terminating bits are only supposed to
#be added after the bit stream is complete. I took that to
#mean after the encoding, but actually it is after the entire
#bit stream has been constructed.
bits = self.terminate_bits(self.buffer.getvalue())
if bits is not None:
self.buffer.write(bits)
#delimit_words and add_words can return None
add_bits = self.delimit_words()
if add_bits:
self.buffer.write(add_bits)
fill_bytes = self.add_words()
if fill_bytes:
self.buffer.write(fill_bytes)
#Get a numeric representation of the data
data = [int(''.join(x),2)
for x in self.grouper(8, self.buffer.getvalue())]
#This is the error information for the code
error_info = tables.eccwbi[self.version][self.error]
#This will hold our data blocks
data_blocks = []
#This will hold our error blocks
error_blocks = []
#Some codes have the data sliced into two different sized blocks
#for example, first two 14 word sized blocks, then four 15 word
#sized blocks. This means that slicing size can change over time.
data_block_sizes = [error_info[2]] * error_info[1]
if error_info[3] != 0:
data_block_sizes.extend([error_info[4]] * error_info[3])
#For every block of data, slice the data into the appropriate
#sized block
current_byte = 0
for n_data_blocks in data_block_sizes:
data_blocks.append(data[current_byte:current_byte+n_data_blocks])
current_byte += n_data_blocks
#I am not sure about the test after the "and". This was added to
#fix a bug where after delimit_words padded the bit stream, a zero
#byte ends up being added. After checking around, it seems this extra
#byte is supposed to be chopped off, but I cannot find that in the
#standard! I am adding it to solve the bug, I believe it is correct.
if current_byte < len(data):
raise ValueError('Too much data for this code version.')
#DEBUG CODE!!!!
#Print out the data blocks
#print('Data Blocks:\n{0}'.format(data_blocks))
#Calculate the error blocks
for n, block in enumerate(data_blocks):
error_blocks.append(self.make_error_block(block, n))
#DEBUG CODE!!!!
#Print out the error blocks
#print('Error Blocks:\n{0}'.format(error_blocks))
#Buffer we will write our data blocks into
data_buffer = io.StringIO()
#Add the data blocks
#Write the buffer such that: block 1 byte 1, block 2 byte 1, etc.
largest_block = max(error_info[2], error_info[4])+error_info[0]
for i in range(largest_block):
for block in data_blocks:
if i < len(block):
data_buffer.write(self.binary_string(block[i], 8))
#Add the error code blocks.
#Write the buffer such that: block 1 byte 1, block 2 byte 2, etc.
for i in range(error_info[0]):
for block in error_blocks:
data_buffer.write(self.binary_string(block[i], 8))
self.buffer = data_buffer | python | def add_data(self):
"""This function properly constructs a QR code's data string. It takes
into account the interleaving pattern required by the standard.
"""
#Encode the data into a QR code
self.buffer.write(self.binary_string(self.mode, 4))
self.buffer.write(self.get_data_length())
self.buffer.write(self.encode())
#Converts the buffer into "code word" integers.
#The online debugger outputs them this way, makes
#for easier comparisons.
#s = self.buffer.getvalue()
#for i in range(0, len(s), 8):
# print(int(s[i:i+8], 2), end=',')
#print()
#Fix for issue #3: https://github.com/mnooner256/pyqrcode/issues/3#
#I was performing the terminate_bits() part in the encoding.
#As per the standard, terminating bits are only supposed to
#be added after the bit stream is complete. I took that to
#mean after the encoding, but actually it is after the entire
#bit stream has been constructed.
bits = self.terminate_bits(self.buffer.getvalue())
if bits is not None:
self.buffer.write(bits)
#delimit_words and add_words can return None
add_bits = self.delimit_words()
if add_bits:
self.buffer.write(add_bits)
fill_bytes = self.add_words()
if fill_bytes:
self.buffer.write(fill_bytes)
#Get a numeric representation of the data
data = [int(''.join(x),2)
for x in self.grouper(8, self.buffer.getvalue())]
#This is the error information for the code
error_info = tables.eccwbi[self.version][self.error]
#This will hold our data blocks
data_blocks = []
#This will hold our error blocks
error_blocks = []
#Some codes have the data sliced into two different sized blocks
#for example, first two 14 word sized blocks, then four 15 word
#sized blocks. This means that slicing size can change over time.
data_block_sizes = [error_info[2]] * error_info[1]
if error_info[3] != 0:
data_block_sizes.extend([error_info[4]] * error_info[3])
#For every block of data, slice the data into the appropriate
#sized block
current_byte = 0
for n_data_blocks in data_block_sizes:
data_blocks.append(data[current_byte:current_byte+n_data_blocks])
current_byte += n_data_blocks
#I am not sure about the test after the "and". This was added to
#fix a bug where after delimit_words padded the bit stream, a zero
#byte ends up being added. After checking around, it seems this extra
#byte is supposed to be chopped off, but I cannot find that in the
#standard! I am adding it to solve the bug, I believe it is correct.
if current_byte < len(data):
raise ValueError('Too much data for this code version.')
#DEBUG CODE!!!!
#Print out the data blocks
#print('Data Blocks:\n{0}'.format(data_blocks))
#Calculate the error blocks
for n, block in enumerate(data_blocks):
error_blocks.append(self.make_error_block(block, n))
#DEBUG CODE!!!!
#Print out the error blocks
#print('Error Blocks:\n{0}'.format(error_blocks))
#Buffer we will write our data blocks into
data_buffer = io.StringIO()
#Add the data blocks
#Write the buffer such that: block 1 byte 1, block 2 byte 1, etc.
largest_block = max(error_info[2], error_info[4])+error_info[0]
for i in range(largest_block):
for block in data_blocks:
if i < len(block):
data_buffer.write(self.binary_string(block[i], 8))
#Add the error code blocks.
#Write the buffer such that: block 1 byte 1, block 2 byte 2, etc.
for i in range(error_info[0]):
for block in error_blocks:
data_buffer.write(self.binary_string(block[i], 8))
self.buffer = data_buffer | [
"def",
"add_data",
"(",
"self",
")",
":",
"#Encode the data into a QR code",
"self",
".",
"buffer",
".",
"write",
"(",
"self",
".",
"binary_string",
"(",
"self",
".",
"mode",
",",
"4",
")",
")",
"self",
".",
"buffer",
".",
"write",
"(",
"self",
".",
"g... | This function properly constructs a QR code's data string. It takes
into account the interleaving pattern required by the standard. | [
"This",
"function",
"properly",
"constructs",
"a",
"QR",
"code",
"s",
"data",
"string",
".",
"It",
"takes",
"into",
"account",
"the",
"interleaving",
"pattern",
"required",
"by",
"the",
"standard",
"."
] | 674a77b5eaf850d063f518bd90c243ee34ad6b5d | https://github.com/mnooner256/pyqrcode/blob/674a77b5eaf850d063f518bd90c243ee34ad6b5d/pyqrcode/builder.py#L277-L377 | train | 48,077 |
mnooner256/pyqrcode | pyqrcode/builder.py | QRCodeBuilder.terminate_bits | def terminate_bits(self, payload):
"""This method adds zeros to the end of the encoded data so that the
encoded data is of the correct length. It returns a binary string
containing the bits to be added.
"""
data_capacity = tables.data_capacity[self.version][self.error][0]
if len(payload) > data_capacity:
raise ValueError('The supplied data will not fit '
'within this version of a QR code.')
#We must add up to 4 zeros to make up for any shortfall in the
#length of the data field.
if len(payload) == data_capacity:
return None
elif len(payload) <= data_capacity-4:
bits = self.binary_string(0,4)
else:
#Make up any shortfall need with less than 4 zeros
bits = self.binary_string(0, data_capacity - len(payload))
return bits | python | def terminate_bits(self, payload):
"""This method adds zeros to the end of the encoded data so that the
encoded data is of the correct length. It returns a binary string
containing the bits to be added.
"""
data_capacity = tables.data_capacity[self.version][self.error][0]
if len(payload) > data_capacity:
raise ValueError('The supplied data will not fit '
'within this version of a QR code.')
#We must add up to 4 zeros to make up for any shortfall in the
#length of the data field.
if len(payload) == data_capacity:
return None
elif len(payload) <= data_capacity-4:
bits = self.binary_string(0,4)
else:
#Make up any shortfall need with less than 4 zeros
bits = self.binary_string(0, data_capacity - len(payload))
return bits | [
"def",
"terminate_bits",
"(",
"self",
",",
"payload",
")",
":",
"data_capacity",
"=",
"tables",
".",
"data_capacity",
"[",
"self",
".",
"version",
"]",
"[",
"self",
".",
"error",
"]",
"[",
"0",
"]",
"if",
"len",
"(",
"payload",
")",
">",
"data_capacity... | This method adds zeros to the end of the encoded data so that the
encoded data is of the correct length. It returns a binary string
containing the bits to be added. | [
"This",
"method",
"adds",
"zeros",
"to",
"the",
"end",
"of",
"the",
"encoded",
"data",
"so",
"that",
"the",
"encoded",
"data",
"is",
"of",
"the",
"correct",
"length",
".",
"It",
"returns",
"a",
"binary",
"string",
"containing",
"the",
"bits",
"to",
"be",... | 674a77b5eaf850d063f518bd90c243ee34ad6b5d | https://github.com/mnooner256/pyqrcode/blob/674a77b5eaf850d063f518bd90c243ee34ad6b5d/pyqrcode/builder.py#L379-L400 | train | 48,078 |
mnooner256/pyqrcode | pyqrcode/builder.py | QRCodeBuilder.delimit_words | def delimit_words(self):
"""This method takes the existing encoded binary string
and returns a binary string that will pad it such that
the encoded string contains only full bytes.
"""
bits_short = 8 - (len(self.buffer.getvalue()) % 8)
#The string already falls on an byte boundary do nothing
if bits_short == 0 or bits_short == 8:
return None
else:
return self.binary_string(0, bits_short) | python | def delimit_words(self):
"""This method takes the existing encoded binary string
and returns a binary string that will pad it such that
the encoded string contains only full bytes.
"""
bits_short = 8 - (len(self.buffer.getvalue()) % 8)
#The string already falls on an byte boundary do nothing
if bits_short == 0 or bits_short == 8:
return None
else:
return self.binary_string(0, bits_short) | [
"def",
"delimit_words",
"(",
"self",
")",
":",
"bits_short",
"=",
"8",
"-",
"(",
"len",
"(",
"self",
".",
"buffer",
".",
"getvalue",
"(",
")",
")",
"%",
"8",
")",
"#The string already falls on an byte boundary do nothing",
"if",
"bits_short",
"==",
"0",
"or"... | This method takes the existing encoded binary string
and returns a binary string that will pad it such that
the encoded string contains only full bytes. | [
"This",
"method",
"takes",
"the",
"existing",
"encoded",
"binary",
"string",
"and",
"returns",
"a",
"binary",
"string",
"that",
"will",
"pad",
"it",
"such",
"that",
"the",
"encoded",
"string",
"contains",
"only",
"full",
"bytes",
"."
] | 674a77b5eaf850d063f518bd90c243ee34ad6b5d | https://github.com/mnooner256/pyqrcode/blob/674a77b5eaf850d063f518bd90c243ee34ad6b5d/pyqrcode/builder.py#L402-L413 | train | 48,079 |
mnooner256/pyqrcode | pyqrcode/builder.py | QRCodeBuilder.add_words | def add_words(self):
"""The data block must fill the entire data capacity of the QR code.
If we fall short, then we must add bytes to the end of the encoded
data field. The value of these bytes are specified in the standard.
"""
data_blocks = len(self.buffer.getvalue()) // 8
total_blocks = tables.data_capacity[self.version][self.error][0] // 8
needed_blocks = total_blocks - data_blocks
if needed_blocks == 0:
return None
#This will return item1, item2, item1, item2, etc.
block = itertools.cycle(['11101100', '00010001'])
#Create a string of the needed blocks
return ''.join([next(block) for x in range(needed_blocks)]) | python | def add_words(self):
"""The data block must fill the entire data capacity of the QR code.
If we fall short, then we must add bytes to the end of the encoded
data field. The value of these bytes are specified in the standard.
"""
data_blocks = len(self.buffer.getvalue()) // 8
total_blocks = tables.data_capacity[self.version][self.error][0] // 8
needed_blocks = total_blocks - data_blocks
if needed_blocks == 0:
return None
#This will return item1, item2, item1, item2, etc.
block = itertools.cycle(['11101100', '00010001'])
#Create a string of the needed blocks
return ''.join([next(block) for x in range(needed_blocks)]) | [
"def",
"add_words",
"(",
"self",
")",
":",
"data_blocks",
"=",
"len",
"(",
"self",
".",
"buffer",
".",
"getvalue",
"(",
")",
")",
"//",
"8",
"total_blocks",
"=",
"tables",
".",
"data_capacity",
"[",
"self",
".",
"version",
"]",
"[",
"self",
".",
"err... | The data block must fill the entire data capacity of the QR code.
If we fall short, then we must add bytes to the end of the encoded
data field. The value of these bytes are specified in the standard. | [
"The",
"data",
"block",
"must",
"fill",
"the",
"entire",
"data",
"capacity",
"of",
"the",
"QR",
"code",
".",
"If",
"we",
"fall",
"short",
"then",
"we",
"must",
"add",
"bytes",
"to",
"the",
"end",
"of",
"the",
"encoded",
"data",
"field",
".",
"The",
"... | 674a77b5eaf850d063f518bd90c243ee34ad6b5d | https://github.com/mnooner256/pyqrcode/blob/674a77b5eaf850d063f518bd90c243ee34ad6b5d/pyqrcode/builder.py#L415-L432 | train | 48,080 |
mnooner256/pyqrcode | pyqrcode/builder.py | QRCodeBuilder.make_code | def make_code(self):
"""This method returns the best possible QR code."""
from copy import deepcopy
#Get the size of the underlying matrix
matrix_size = tables.version_size[self.version]
#Create a template matrix we will build the codes with
row = [' ' for x in range(matrix_size)]
template = [deepcopy(row) for x in range(matrix_size)]
#Add mandatory information to the template
self.add_detection_pattern(template)
self.add_position_pattern(template)
self.add_version_pattern(template)
#Create the various types of masks of the template
self.masks = self.make_masks(template)
self.best_mask = self.choose_best_mask()
self.code = self.masks[self.best_mask] | python | def make_code(self):
"""This method returns the best possible QR code."""
from copy import deepcopy
#Get the size of the underlying matrix
matrix_size = tables.version_size[self.version]
#Create a template matrix we will build the codes with
row = [' ' for x in range(matrix_size)]
template = [deepcopy(row) for x in range(matrix_size)]
#Add mandatory information to the template
self.add_detection_pattern(template)
self.add_position_pattern(template)
self.add_version_pattern(template)
#Create the various types of masks of the template
self.masks = self.make_masks(template)
self.best_mask = self.choose_best_mask()
self.code = self.masks[self.best_mask] | [
"def",
"make_code",
"(",
"self",
")",
":",
"from",
"copy",
"import",
"deepcopy",
"#Get the size of the underlying matrix",
"matrix_size",
"=",
"tables",
".",
"version_size",
"[",
"self",
".",
"version",
"]",
"#Create a template matrix we will build the codes with",
"row",... | This method returns the best possible QR code. | [
"This",
"method",
"returns",
"the",
"best",
"possible",
"QR",
"code",
"."
] | 674a77b5eaf850d063f518bd90c243ee34ad6b5d | https://github.com/mnooner256/pyqrcode/blob/674a77b5eaf850d063f518bd90c243ee34ad6b5d/pyqrcode/builder.py#L497-L517 | train | 48,081 |
mnooner256/pyqrcode | pyqrcode/builder.py | QRCodeBuilder.add_detection_pattern | def add_detection_pattern(self, m):
"""This method add the detection patterns to the QR code. This lets
the scanner orient the pattern. It is required for all QR codes.
The detection pattern consists of three boxes located at the upper
left, upper right, and lower left corners of the matrix. Also, two
special lines called the timing pattern is also necessary. Finally,
a single black pixel is added just above the lower left black box.
"""
#Draw outer black box
for i in range(7):
inv = -(i+1)
for j in [0,6,-1,-7]:
m[j][i] = 1
m[i][j] = 1
m[inv][j] = 1
m[j][inv] = 1
#Draw inner white box
for i in range(1, 6):
inv = -(i+1)
for j in [1, 5, -2, -6]:
m[j][i] = 0
m[i][j] = 0
m[inv][j] = 0
m[j][inv] = 0
#Draw inner black box
for i in range(2, 5):
for j in range(2, 5):
inv = -(i+1)
m[i][j] = 1
m[inv][j] = 1
m[j][inv] = 1
#Draw white border
for i in range(8):
inv = -(i+1)
for j in [7, -8]:
m[i][j] = 0
m[j][i] = 0
m[inv][j] = 0
m[j][inv] = 0
#To keep the code short, it draws an extra box
#in the lower right corner, this removes it.
for i in range(-8, 0):
for j in range(-8, 0):
m[i][j] = ' '
#Add the timing pattern
bit = itertools.cycle([1,0])
for i in range(8, (len(m)-8)):
b = next(bit)
m[i][6] = b
m[6][i] = b
#Add the extra black pixel
m[-8][8] = 1 | python | def add_detection_pattern(self, m):
"""This method add the detection patterns to the QR code. This lets
the scanner orient the pattern. It is required for all QR codes.
The detection pattern consists of three boxes located at the upper
left, upper right, and lower left corners of the matrix. Also, two
special lines called the timing pattern is also necessary. Finally,
a single black pixel is added just above the lower left black box.
"""
#Draw outer black box
for i in range(7):
inv = -(i+1)
for j in [0,6,-1,-7]:
m[j][i] = 1
m[i][j] = 1
m[inv][j] = 1
m[j][inv] = 1
#Draw inner white box
for i in range(1, 6):
inv = -(i+1)
for j in [1, 5, -2, -6]:
m[j][i] = 0
m[i][j] = 0
m[inv][j] = 0
m[j][inv] = 0
#Draw inner black box
for i in range(2, 5):
for j in range(2, 5):
inv = -(i+1)
m[i][j] = 1
m[inv][j] = 1
m[j][inv] = 1
#Draw white border
for i in range(8):
inv = -(i+1)
for j in [7, -8]:
m[i][j] = 0
m[j][i] = 0
m[inv][j] = 0
m[j][inv] = 0
#To keep the code short, it draws an extra box
#in the lower right corner, this removes it.
for i in range(-8, 0):
for j in range(-8, 0):
m[i][j] = ' '
#Add the timing pattern
bit = itertools.cycle([1,0])
for i in range(8, (len(m)-8)):
b = next(bit)
m[i][6] = b
m[6][i] = b
#Add the extra black pixel
m[-8][8] = 1 | [
"def",
"add_detection_pattern",
"(",
"self",
",",
"m",
")",
":",
"#Draw outer black box",
"for",
"i",
"in",
"range",
"(",
"7",
")",
":",
"inv",
"=",
"-",
"(",
"i",
"+",
"1",
")",
"for",
"j",
"in",
"[",
"0",
",",
"6",
",",
"-",
"1",
",",
"-",
... | This method add the detection patterns to the QR code. This lets
the scanner orient the pattern. It is required for all QR codes.
The detection pattern consists of three boxes located at the upper
left, upper right, and lower left corners of the matrix. Also, two
special lines called the timing pattern is also necessary. Finally,
a single black pixel is added just above the lower left black box. | [
"This",
"method",
"add",
"the",
"detection",
"patterns",
"to",
"the",
"QR",
"code",
".",
"This",
"lets",
"the",
"scanner",
"orient",
"the",
"pattern",
".",
"It",
"is",
"required",
"for",
"all",
"QR",
"codes",
".",
"The",
"detection",
"pattern",
"consists",... | 674a77b5eaf850d063f518bd90c243ee34ad6b5d | https://github.com/mnooner256/pyqrcode/blob/674a77b5eaf850d063f518bd90c243ee34ad6b5d/pyqrcode/builder.py#L519-L577 | train | 48,082 |
mnooner256/pyqrcode | pyqrcode/builder.py | QRCodeBuilder.add_position_pattern | def add_position_pattern(self, m):
"""This method draws the position adjustment patterns onto the QR
Code. All QR code versions larger than one require these special boxes
called position adjustment patterns.
"""
#Version 1 does not have a position adjustment pattern
if self.version == 1:
return
#Get the coordinates for where to place the boxes
coordinates = tables.position_adjustment[self.version]
#Get the max and min coordinates to handle special cases
min_coord = coordinates[0]
max_coord = coordinates[-1]
#Draw a box at each intersection of the coordinates
for i in coordinates:
for j in coordinates:
#Do not draw these boxes because they would
#interfere with the detection pattern
if (i == min_coord and j == min_coord) or \
(i == min_coord and j == max_coord) or \
(i == max_coord and j == min_coord):
continue
#Center black pixel
m[i][j] = 1
#Surround the pixel with a white box
for x in [-1,1]:
m[i+x][j+x] = 0
m[i+x][j] = 0
m[i][j+x] = 0
m[i-x][j+x] = 0
m[i+x][j-x] = 0
#Surround the white box with a black box
for x in [-2,2]:
for y in [0,-1,1]:
m[i+x][j+x] = 1
m[i+x][j+y] = 1
m[i+y][j+x] = 1
m[i-x][j+x] = 1
m[i+x][j-x] = 1 | python | def add_position_pattern(self, m):
"""This method draws the position adjustment patterns onto the QR
Code. All QR code versions larger than one require these special boxes
called position adjustment patterns.
"""
#Version 1 does not have a position adjustment pattern
if self.version == 1:
return
#Get the coordinates for where to place the boxes
coordinates = tables.position_adjustment[self.version]
#Get the max and min coordinates to handle special cases
min_coord = coordinates[0]
max_coord = coordinates[-1]
#Draw a box at each intersection of the coordinates
for i in coordinates:
for j in coordinates:
#Do not draw these boxes because they would
#interfere with the detection pattern
if (i == min_coord and j == min_coord) or \
(i == min_coord and j == max_coord) or \
(i == max_coord and j == min_coord):
continue
#Center black pixel
m[i][j] = 1
#Surround the pixel with a white box
for x in [-1,1]:
m[i+x][j+x] = 0
m[i+x][j] = 0
m[i][j+x] = 0
m[i-x][j+x] = 0
m[i+x][j-x] = 0
#Surround the white box with a black box
for x in [-2,2]:
for y in [0,-1,1]:
m[i+x][j+x] = 1
m[i+x][j+y] = 1
m[i+y][j+x] = 1
m[i-x][j+x] = 1
m[i+x][j-x] = 1 | [
"def",
"add_position_pattern",
"(",
"self",
",",
"m",
")",
":",
"#Version 1 does not have a position adjustment pattern",
"if",
"self",
".",
"version",
"==",
"1",
":",
"return",
"#Get the coordinates for where to place the boxes",
"coordinates",
"=",
"tables",
".",
"posit... | This method draws the position adjustment patterns onto the QR
Code. All QR code versions larger than one require these special boxes
called position adjustment patterns. | [
"This",
"method",
"draws",
"the",
"position",
"adjustment",
"patterns",
"onto",
"the",
"QR",
"Code",
".",
"All",
"QR",
"code",
"versions",
"larger",
"than",
"one",
"require",
"these",
"special",
"boxes",
"called",
"position",
"adjustment",
"patterns",
"."
] | 674a77b5eaf850d063f518bd90c243ee34ad6b5d | https://github.com/mnooner256/pyqrcode/blob/674a77b5eaf850d063f518bd90c243ee34ad6b5d/pyqrcode/builder.py#L579-L623 | train | 48,083 |
mnooner256/pyqrcode | pyqrcode/builder.py | QRCodeBuilder.add_version_pattern | def add_version_pattern(self, m):
"""For QR codes with a version 7 or higher, a special pattern
specifying the code's version is required.
For further information see:
http://www.thonky.com/qr-code-tutorial/format-version-information/#example-of-version-7-information-string
"""
if self.version < 7:
return
#Get the bit fields for this code's version
#We will iterate across the string, the bit string
#needs the least significant digit in the zero-th position
field = iter(tables.version_pattern[self.version][::-1])
#Where to start placing the pattern
start = len(m)-11
#The version pattern is pretty odd looking
for i in range(6):
#The pattern is three modules wide
for j in range(start, start+3):
bit = int(next(field))
#Bottom Left
m[i][j] = bit
#Upper right
m[j][i] = bit | python | def add_version_pattern(self, m):
"""For QR codes with a version 7 or higher, a special pattern
specifying the code's version is required.
For further information see:
http://www.thonky.com/qr-code-tutorial/format-version-information/#example-of-version-7-information-string
"""
if self.version < 7:
return
#Get the bit fields for this code's version
#We will iterate across the string, the bit string
#needs the least significant digit in the zero-th position
field = iter(tables.version_pattern[self.version][::-1])
#Where to start placing the pattern
start = len(m)-11
#The version pattern is pretty odd looking
for i in range(6):
#The pattern is three modules wide
for j in range(start, start+3):
bit = int(next(field))
#Bottom Left
m[i][j] = bit
#Upper right
m[j][i] = bit | [
"def",
"add_version_pattern",
"(",
"self",
",",
"m",
")",
":",
"if",
"self",
".",
"version",
"<",
"7",
":",
"return",
"#Get the bit fields for this code's version",
"#We will iterate across the string, the bit string",
"#needs the least significant digit in the zero-th position",... | For QR codes with a version 7 or higher, a special pattern
specifying the code's version is required.
For further information see:
http://www.thonky.com/qr-code-tutorial/format-version-information/#example-of-version-7-information-string | [
"For",
"QR",
"codes",
"with",
"a",
"version",
"7",
"or",
"higher",
"a",
"special",
"pattern",
"specifying",
"the",
"code",
"s",
"version",
"is",
"required",
"."
] | 674a77b5eaf850d063f518bd90c243ee34ad6b5d | https://github.com/mnooner256/pyqrcode/blob/674a77b5eaf850d063f518bd90c243ee34ad6b5d/pyqrcode/builder.py#L625-L653 | train | 48,084 |
mnooner256/pyqrcode | pyqrcode/builder.py | QRCodeBuilder.make_masks | def make_masks(self, template):
"""This method generates all seven masks so that the best mask can
be determined. The template parameter is a code matrix that will
server as the base for all the generated masks.
"""
from copy import deepcopy
nmasks = len(tables.mask_patterns)
masks = [''] * nmasks
count = 0
for n in range(nmasks):
cur_mask = deepcopy(template)
masks[n] = cur_mask
#Add the type pattern bits to the code
self.add_type_pattern(cur_mask, tables.type_bits[self.error][n])
#Get the mask pattern
pattern = tables.mask_patterns[n]
#This will read the 1's and 0's one at a time
bits = iter(self.buffer.getvalue())
#These will help us do the up, down, up, down pattern
row_start = itertools.cycle([len(cur_mask)-1, 0])
row_stop = itertools.cycle([-1,len(cur_mask)])
direction = itertools.cycle([-1, 1])
#The data pattern is added using pairs of columns
for column in range(len(cur_mask)-1, 0, -2):
#The vertical timing pattern is an exception to the rules,
#move the column counter over by one
if column <= 6:
column = column - 1
#This will let us fill in the pattern
#right-left, right-left, etc.
column_pair = itertools.cycle([column, column-1])
#Go through each row in the pattern moving up, then down
for row in range(next(row_start), next(row_stop),
next(direction)):
#Fill in the right then left column
for i in range(2):
col = next(column_pair)
#Go to the next column if we encounter a
#preexisting pattern (usually an alignment pattern)
if cur_mask[row][col] != ' ':
continue
#Some versions don't have enough bits. You then fill
#in the rest of the pattern with 0's. These are
#called "remainder bits."
try:
bit = int(next(bits))
except:
bit = 0
#If the pattern is True then flip the bit
if pattern(row, col):
cur_mask[row][col] = bit ^ 1
else:
cur_mask[row][col] = bit
#DEBUG CODE!!!
#Save all of the masks as png files
#for i, m in enumerate(masks):
# _png(m, self.version, 'mask-{0}.png'.format(i), 5)
return masks | python | def make_masks(self, template):
"""This method generates all seven masks so that the best mask can
be determined. The template parameter is a code matrix that will
server as the base for all the generated masks.
"""
from copy import deepcopy
nmasks = len(tables.mask_patterns)
masks = [''] * nmasks
count = 0
for n in range(nmasks):
cur_mask = deepcopy(template)
masks[n] = cur_mask
#Add the type pattern bits to the code
self.add_type_pattern(cur_mask, tables.type_bits[self.error][n])
#Get the mask pattern
pattern = tables.mask_patterns[n]
#This will read the 1's and 0's one at a time
bits = iter(self.buffer.getvalue())
#These will help us do the up, down, up, down pattern
row_start = itertools.cycle([len(cur_mask)-1, 0])
row_stop = itertools.cycle([-1,len(cur_mask)])
direction = itertools.cycle([-1, 1])
#The data pattern is added using pairs of columns
for column in range(len(cur_mask)-1, 0, -2):
#The vertical timing pattern is an exception to the rules,
#move the column counter over by one
if column <= 6:
column = column - 1
#This will let us fill in the pattern
#right-left, right-left, etc.
column_pair = itertools.cycle([column, column-1])
#Go through each row in the pattern moving up, then down
for row in range(next(row_start), next(row_stop),
next(direction)):
#Fill in the right then left column
for i in range(2):
col = next(column_pair)
#Go to the next column if we encounter a
#preexisting pattern (usually an alignment pattern)
if cur_mask[row][col] != ' ':
continue
#Some versions don't have enough bits. You then fill
#in the rest of the pattern with 0's. These are
#called "remainder bits."
try:
bit = int(next(bits))
except:
bit = 0
#If the pattern is True then flip the bit
if pattern(row, col):
cur_mask[row][col] = bit ^ 1
else:
cur_mask[row][col] = bit
#DEBUG CODE!!!
#Save all of the masks as png files
#for i, m in enumerate(masks):
# _png(m, self.version, 'mask-{0}.png'.format(i), 5)
return masks | [
"def",
"make_masks",
"(",
"self",
",",
"template",
")",
":",
"from",
"copy",
"import",
"deepcopy",
"nmasks",
"=",
"len",
"(",
"tables",
".",
"mask_patterns",
")",
"masks",
"=",
"[",
"''",
"]",
"*",
"nmasks",
"count",
"=",
"0",
"for",
"n",
"in",
"rang... | This method generates all seven masks so that the best mask can
be determined. The template parameter is a code matrix that will
server as the base for all the generated masks. | [
"This",
"method",
"generates",
"all",
"seven",
"masks",
"so",
"that",
"the",
"best",
"mask",
"can",
"be",
"determined",
".",
"The",
"template",
"parameter",
"is",
"a",
"code",
"matrix",
"that",
"will",
"server",
"as",
"the",
"base",
"for",
"all",
"the",
... | 674a77b5eaf850d063f518bd90c243ee34ad6b5d | https://github.com/mnooner256/pyqrcode/blob/674a77b5eaf850d063f518bd90c243ee34ad6b5d/pyqrcode/builder.py#L655-L729 | train | 48,085 |
mnooner256/pyqrcode | pyqrcode/builder.py | QRCodeBuilder.add_type_pattern | def add_type_pattern(self, m, type_bits):
"""This will add the pattern to the QR code that represents the error
level and the type of mask used to make the code.
"""
field = iter(type_bits)
for i in range(7):
bit = int(next(field))
#Skip the timing bits
if i < 6:
m[8][i] = bit
else:
m[8][i+1] = bit
if -8 < -(i+1):
m[-(i+1)][8] = bit
for i in range(-8,0):
bit = int(next(field))
m[8][i] = bit
i = -i
#Skip timing column
if i > 6:
m[i][8] = bit
else:
m[i-1][8] = bit | python | def add_type_pattern(self, m, type_bits):
"""This will add the pattern to the QR code that represents the error
level and the type of mask used to make the code.
"""
field = iter(type_bits)
for i in range(7):
bit = int(next(field))
#Skip the timing bits
if i < 6:
m[8][i] = bit
else:
m[8][i+1] = bit
if -8 < -(i+1):
m[-(i+1)][8] = bit
for i in range(-8,0):
bit = int(next(field))
m[8][i] = bit
i = -i
#Skip timing column
if i > 6:
m[i][8] = bit
else:
m[i-1][8] = bit | [
"def",
"add_type_pattern",
"(",
"self",
",",
"m",
",",
"type_bits",
")",
":",
"field",
"=",
"iter",
"(",
"type_bits",
")",
"for",
"i",
"in",
"range",
"(",
"7",
")",
":",
"bit",
"=",
"int",
"(",
"next",
"(",
"field",
")",
")",
"#Skip the timing bits",... | This will add the pattern to the QR code that represents the error
level and the type of mask used to make the code. | [
"This",
"will",
"add",
"the",
"pattern",
"to",
"the",
"QR",
"code",
"that",
"represents",
"the",
"error",
"level",
"and",
"the",
"type",
"of",
"mask",
"used",
"to",
"make",
"the",
"code",
"."
] | 674a77b5eaf850d063f518bd90c243ee34ad6b5d | https://github.com/mnooner256/pyqrcode/blob/674a77b5eaf850d063f518bd90c243ee34ad6b5d/pyqrcode/builder.py#L870-L897 | train | 48,086 |
arokem/python-matlab-bridge | tools/github_stats.py | split_pulls | def split_pulls(all_issues, project="arokem/python-matlab-bridge"):
"""split a list of closed issues into non-PR Issues and Pull Requests"""
pulls = []
issues = []
for i in all_issues:
if is_pull_request(i):
pull = get_pull_request(project, i['number'], auth=True)
pulls.append(pull)
else:
issues.append(i)
return issues, pulls | python | def split_pulls(all_issues, project="arokem/python-matlab-bridge"):
"""split a list of closed issues into non-PR Issues and Pull Requests"""
pulls = []
issues = []
for i in all_issues:
if is_pull_request(i):
pull = get_pull_request(project, i['number'], auth=True)
pulls.append(pull)
else:
issues.append(i)
return issues, pulls | [
"def",
"split_pulls",
"(",
"all_issues",
",",
"project",
"=",
"\"arokem/python-matlab-bridge\"",
")",
":",
"pulls",
"=",
"[",
"]",
"issues",
"=",
"[",
"]",
"for",
"i",
"in",
"all_issues",
":",
"if",
"is_pull_request",
"(",
"i",
")",
":",
"pull",
"=",
"ge... | split a list of closed issues into non-PR Issues and Pull Requests | [
"split",
"a",
"list",
"of",
"closed",
"issues",
"into",
"non",
"-",
"PR",
"Issues",
"and",
"Pull",
"Requests"
] | 9822c7b55435662f4f033c5479cc03fea2255755 | https://github.com/arokem/python-matlab-bridge/blob/9822c7b55435662f4f033c5479cc03fea2255755/tools/github_stats.py#L53-L63 | train | 48,087 |
arokem/python-matlab-bridge | tools/github_stats.py | issues_closed_since | def issues_closed_since(period=timedelta(days=365), project="arokem/python-matlab-bridge", pulls=False):
"""Get all issues closed since a particular point in time. period
can either be a datetime object, or a timedelta object. In the
latter case, it is used as a time before the present.
"""
which = 'pulls' if pulls else 'issues'
if isinstance(period, timedelta):
since = round_hour(datetime.utcnow() - period)
else:
since = period
url = "https://api.github.com/repos/%s/%s?state=closed&sort=updated&since=%s&per_page=%i" % (project, which, since.strftime(ISO8601), PER_PAGE)
allclosed = get_paged_request(url, headers=make_auth_header())
filtered = [ i for i in allclosed if _parse_datetime(i['closed_at']) > since ]
if pulls:
filtered = [ i for i in filtered if _parse_datetime(i['merged_at']) > since ]
# filter out PRs not against master (backports)
filtered = [ i for i in filtered if i['base']['ref'] == 'master' ]
else:
filtered = [ i for i in filtered if not is_pull_request(i) ]
return filtered | python | def issues_closed_since(period=timedelta(days=365), project="arokem/python-matlab-bridge", pulls=False):
"""Get all issues closed since a particular point in time. period
can either be a datetime object, or a timedelta object. In the
latter case, it is used as a time before the present.
"""
which = 'pulls' if pulls else 'issues'
if isinstance(period, timedelta):
since = round_hour(datetime.utcnow() - period)
else:
since = period
url = "https://api.github.com/repos/%s/%s?state=closed&sort=updated&since=%s&per_page=%i" % (project, which, since.strftime(ISO8601), PER_PAGE)
allclosed = get_paged_request(url, headers=make_auth_header())
filtered = [ i for i in allclosed if _parse_datetime(i['closed_at']) > since ]
if pulls:
filtered = [ i for i in filtered if _parse_datetime(i['merged_at']) > since ]
# filter out PRs not against master (backports)
filtered = [ i for i in filtered if i['base']['ref'] == 'master' ]
else:
filtered = [ i for i in filtered if not is_pull_request(i) ]
return filtered | [
"def",
"issues_closed_since",
"(",
"period",
"=",
"timedelta",
"(",
"days",
"=",
"365",
")",
",",
"project",
"=",
"\"arokem/python-matlab-bridge\"",
",",
"pulls",
"=",
"False",
")",
":",
"which",
"=",
"'pulls'",
"if",
"pulls",
"else",
"'issues'",
"if",
"isin... | Get all issues closed since a particular point in time. period
can either be a datetime object, or a timedelta object. In the
latter case, it is used as a time before the present. | [
"Get",
"all",
"issues",
"closed",
"since",
"a",
"particular",
"point",
"in",
"time",
".",
"period",
"can",
"either",
"be",
"a",
"datetime",
"object",
"or",
"a",
"timedelta",
"object",
".",
"In",
"the",
"latter",
"case",
"it",
"is",
"used",
"as",
"a",
"... | 9822c7b55435662f4f033c5479cc03fea2255755 | https://github.com/arokem/python-matlab-bridge/blob/9822c7b55435662f4f033c5479cc03fea2255755/tools/github_stats.py#L66-L89 | train | 48,088 |
arokem/python-matlab-bridge | tools/github_stats.py | sorted_by_field | def sorted_by_field(issues, field='closed_at', reverse=False):
"""Return a list of issues sorted by closing date date."""
return sorted(issues, key = lambda i:i[field], reverse=reverse) | python | def sorted_by_field(issues, field='closed_at', reverse=False):
"""Return a list of issues sorted by closing date date."""
return sorted(issues, key = lambda i:i[field], reverse=reverse) | [
"def",
"sorted_by_field",
"(",
"issues",
",",
"field",
"=",
"'closed_at'",
",",
"reverse",
"=",
"False",
")",
":",
"return",
"sorted",
"(",
"issues",
",",
"key",
"=",
"lambda",
"i",
":",
"i",
"[",
"field",
"]",
",",
"reverse",
"=",
"reverse",
")"
] | Return a list of issues sorted by closing date date. | [
"Return",
"a",
"list",
"of",
"issues",
"sorted",
"by",
"closing",
"date",
"date",
"."
] | 9822c7b55435662f4f033c5479cc03fea2255755 | https://github.com/arokem/python-matlab-bridge/blob/9822c7b55435662f4f033c5479cc03fea2255755/tools/github_stats.py#L92-L94 | train | 48,089 |
arokem/python-matlab-bridge | tools/github_stats.py | report | def report(issues, show_urls=False):
"""Summary report about a list of issues, printing number and title.
"""
# titles may have unicode in them, so we must encode everything below
if show_urls:
for i in issues:
print(u'#%d: %s' % (i['number'],
i['title'].replace(u'`', u'``')))
else:
for i in issues:
print(u'* %d: %s' % (i['number'], i['title'].replace(u'`', u'``'))) | python | def report(issues, show_urls=False):
"""Summary report about a list of issues, printing number and title.
"""
# titles may have unicode in them, so we must encode everything below
if show_urls:
for i in issues:
print(u'#%d: %s' % (i['number'],
i['title'].replace(u'`', u'``')))
else:
for i in issues:
print(u'* %d: %s' % (i['number'], i['title'].replace(u'`', u'``'))) | [
"def",
"report",
"(",
"issues",
",",
"show_urls",
"=",
"False",
")",
":",
"# titles may have unicode in them, so we must encode everything below",
"if",
"show_urls",
":",
"for",
"i",
"in",
"issues",
":",
"print",
"(",
"u'#%d: %s'",
"%",
"(",
"i",
"[",
"'number'",
... | Summary report about a list of issues, printing number and title. | [
"Summary",
"report",
"about",
"a",
"list",
"of",
"issues",
"printing",
"number",
"and",
"title",
"."
] | 9822c7b55435662f4f033c5479cc03fea2255755 | https://github.com/arokem/python-matlab-bridge/blob/9822c7b55435662f4f033c5479cc03fea2255755/tools/github_stats.py#L97-L107 | train | 48,090 |
arokem/python-matlab-bridge | pymatbridge/pymatbridge.py | encode_ndarray | def encode_ndarray(obj):
"""Write a numpy array and its shape to base64 buffers"""
shape = obj.shape
if len(shape) == 1:
shape = (1, obj.shape[0])
if obj.flags.c_contiguous:
obj = obj.T
elif not obj.flags.f_contiguous:
obj = asfortranarray(obj.T)
else:
obj = obj.T
try:
data = obj.astype(float64).tobytes()
except AttributeError:
data = obj.astype(float64).tostring()
data = base64.b64encode(data).decode('utf-8')
return data, shape | python | def encode_ndarray(obj):
"""Write a numpy array and its shape to base64 buffers"""
shape = obj.shape
if len(shape) == 1:
shape = (1, obj.shape[0])
if obj.flags.c_contiguous:
obj = obj.T
elif not obj.flags.f_contiguous:
obj = asfortranarray(obj.T)
else:
obj = obj.T
try:
data = obj.astype(float64).tobytes()
except AttributeError:
data = obj.astype(float64).tostring()
data = base64.b64encode(data).decode('utf-8')
return data, shape | [
"def",
"encode_ndarray",
"(",
"obj",
")",
":",
"shape",
"=",
"obj",
".",
"shape",
"if",
"len",
"(",
"shape",
")",
"==",
"1",
":",
"shape",
"=",
"(",
"1",
",",
"obj",
".",
"shape",
"[",
"0",
"]",
")",
"if",
"obj",
".",
"flags",
".",
"c_contiguou... | Write a numpy array and its shape to base64 buffers | [
"Write",
"a",
"numpy",
"array",
"and",
"its",
"shape",
"to",
"base64",
"buffers"
] | 9822c7b55435662f4f033c5479cc03fea2255755 | https://github.com/arokem/python-matlab-bridge/blob/9822c7b55435662f4f033c5479cc03fea2255755/pymatbridge/pymatbridge.py#L46-L63 | train | 48,091 |
arokem/python-matlab-bridge | pymatbridge/pymatbridge.py | decode_arr | def decode_arr(data):
"""Extract a numpy array from a base64 buffer"""
data = data.encode('utf-8')
return frombuffer(base64.b64decode(data), float64) | python | def decode_arr(data):
"""Extract a numpy array from a base64 buffer"""
data = data.encode('utf-8')
return frombuffer(base64.b64decode(data), float64) | [
"def",
"decode_arr",
"(",
"data",
")",
":",
"data",
"=",
"data",
".",
"encode",
"(",
"'utf-8'",
")",
"return",
"frombuffer",
"(",
"base64",
".",
"b64decode",
"(",
"data",
")",
",",
"float64",
")"
] | Extract a numpy array from a base64 buffer | [
"Extract",
"a",
"numpy",
"array",
"from",
"a",
"base64",
"buffer"
] | 9822c7b55435662f4f033c5479cc03fea2255755 | https://github.com/arokem/python-matlab-bridge/blob/9822c7b55435662f4f033c5479cc03fea2255755/pymatbridge/pymatbridge.py#L88-L91 | train | 48,092 |
arokem/python-matlab-bridge | pymatbridge/pymatbridge.py | _Session.run_func | def run_func(self, func_path, *func_args, **kwargs):
"""Run a function in Matlab and return the result.
Parameters
----------
func_path: str
Name of function to run or a path to an m-file.
func_args: object, optional
Function args to send to the function.
nargout: int, optional
Desired number of return arguments.
kwargs:
Keyword arguments are passed to Matlab in the form [key, val] so
that matlab.plot(x, y, '--', LineWidth=2) would be translated into
plot(x, y, '--', 'LineWidth', 2)
Returns
-------
Result dictionary with keys: 'message', 'result', and 'success'
"""
if not self.started:
raise ValueError('Session not started, use start()')
nargout = kwargs.pop('nargout', 1)
func_args += tuple(item for pair in zip(kwargs.keys(), kwargs.values())
for item in pair)
dname = os.path.dirname(func_path)
fname = os.path.basename(func_path)
func_name, ext = os.path.splitext(fname)
if ext and not ext == '.m':
raise TypeError('Need to give path to .m file')
return self._json_response(cmd='eval',
func_name=func_name,
func_args=func_args or '',
dname=dname,
nargout=nargout) | python | def run_func(self, func_path, *func_args, **kwargs):
"""Run a function in Matlab and return the result.
Parameters
----------
func_path: str
Name of function to run or a path to an m-file.
func_args: object, optional
Function args to send to the function.
nargout: int, optional
Desired number of return arguments.
kwargs:
Keyword arguments are passed to Matlab in the form [key, val] so
that matlab.plot(x, y, '--', LineWidth=2) would be translated into
plot(x, y, '--', 'LineWidth', 2)
Returns
-------
Result dictionary with keys: 'message', 'result', and 'success'
"""
if not self.started:
raise ValueError('Session not started, use start()')
nargout = kwargs.pop('nargout', 1)
func_args += tuple(item for pair in zip(kwargs.keys(), kwargs.values())
for item in pair)
dname = os.path.dirname(func_path)
fname = os.path.basename(func_path)
func_name, ext = os.path.splitext(fname)
if ext and not ext == '.m':
raise TypeError('Need to give path to .m file')
return self._json_response(cmd='eval',
func_name=func_name,
func_args=func_args or '',
dname=dname,
nargout=nargout) | [
"def",
"run_func",
"(",
"self",
",",
"func_path",
",",
"*",
"func_args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"self",
".",
"started",
":",
"raise",
"ValueError",
"(",
"'Session not started, use start()'",
")",
"nargout",
"=",
"kwargs",
".",
"pop... | Run a function in Matlab and return the result.
Parameters
----------
func_path: str
Name of function to run or a path to an m-file.
func_args: object, optional
Function args to send to the function.
nargout: int, optional
Desired number of return arguments.
kwargs:
Keyword arguments are passed to Matlab in the form [key, val] so
that matlab.plot(x, y, '--', LineWidth=2) would be translated into
plot(x, y, '--', 'LineWidth', 2)
Returns
-------
Result dictionary with keys: 'message', 'result', and 'success' | [
"Run",
"a",
"function",
"in",
"Matlab",
"and",
"return",
"the",
"result",
"."
] | 9822c7b55435662f4f033c5479cc03fea2255755 | https://github.com/arokem/python-matlab-bridge/blob/9822c7b55435662f4f033c5479cc03fea2255755/pymatbridge/pymatbridge.py#L276-L311 | train | 48,093 |
arokem/python-matlab-bridge | pymatbridge/pymatbridge.py | _Session._bind_method | def _bind_method(self, name, unconditionally=False):
"""Generate a Matlab function and bind it to the instance
This is where the magic happens. When an unknown attribute of the
Matlab class is requested, it is assumed to be a call to a
Matlab function, and is generated and bound to the instance.
This works because getattr() falls back to __getattr__ only if no
attributes of the requested name can be found through normal
routes (__getattribute__, __dict__, class tree).
bind_method first checks whether the requested name is a callable
Matlab function before generating a binding.
Parameters
----------
name : str
The name of the Matlab function to call
e.g. 'sqrt', 'sum', 'svd', etc
unconditionally : bool, optional
Bind the method without performing
checks. Used to bootstrap methods that are required and
know to exist
Returns
-------
MatlabFunction
A reference to a newly bound MatlabFunction instance if the
requested name is determined to be a callable function
Raises
------
AttributeError: if the requested name is not a callable
Matlab function
"""
# TODO: This does not work if the function is a mex function inside a folder of the same name
exists = self.run_func('exist', name)['result'] in [2, 3, 5]
if not unconditionally and not exists:
raise AttributeError("'Matlab' object has no attribute '%s'" % name)
# create a new method instance
method_instance = MatlabFunction(weakref.ref(self), name)
method_instance.__name__ = name
# bind to the Matlab instance with a weakref (to avoid circular references)
if sys.version.startswith('3'):
method = types.MethodType(method_instance, weakref.ref(self))
else:
method = types.MethodType(method_instance, weakref.ref(self),
_Session)
setattr(self, name, method)
return getattr(self, name) | python | def _bind_method(self, name, unconditionally=False):
"""Generate a Matlab function and bind it to the instance
This is where the magic happens. When an unknown attribute of the
Matlab class is requested, it is assumed to be a call to a
Matlab function, and is generated and bound to the instance.
This works because getattr() falls back to __getattr__ only if no
attributes of the requested name can be found through normal
routes (__getattribute__, __dict__, class tree).
bind_method first checks whether the requested name is a callable
Matlab function before generating a binding.
Parameters
----------
name : str
The name of the Matlab function to call
e.g. 'sqrt', 'sum', 'svd', etc
unconditionally : bool, optional
Bind the method without performing
checks. Used to bootstrap methods that are required and
know to exist
Returns
-------
MatlabFunction
A reference to a newly bound MatlabFunction instance if the
requested name is determined to be a callable function
Raises
------
AttributeError: if the requested name is not a callable
Matlab function
"""
# TODO: This does not work if the function is a mex function inside a folder of the same name
exists = self.run_func('exist', name)['result'] in [2, 3, 5]
if not unconditionally and not exists:
raise AttributeError("'Matlab' object has no attribute '%s'" % name)
# create a new method instance
method_instance = MatlabFunction(weakref.ref(self), name)
method_instance.__name__ = name
# bind to the Matlab instance with a weakref (to avoid circular references)
if sys.version.startswith('3'):
method = types.MethodType(method_instance, weakref.ref(self))
else:
method = types.MethodType(method_instance, weakref.ref(self),
_Session)
setattr(self, name, method)
return getattr(self, name) | [
"def",
"_bind_method",
"(",
"self",
",",
"name",
",",
"unconditionally",
"=",
"False",
")",
":",
"# TODO: This does not work if the function is a mex function inside a folder of the same name",
"exists",
"=",
"self",
".",
"run_func",
"(",
"'exist'",
",",
"name",
")",
"[... | Generate a Matlab function and bind it to the instance
This is where the magic happens. When an unknown attribute of the
Matlab class is requested, it is assumed to be a call to a
Matlab function, and is generated and bound to the instance.
This works because getattr() falls back to __getattr__ only if no
attributes of the requested name can be found through normal
routes (__getattribute__, __dict__, class tree).
bind_method first checks whether the requested name is a callable
Matlab function before generating a binding.
Parameters
----------
name : str
The name of the Matlab function to call
e.g. 'sqrt', 'sum', 'svd', etc
unconditionally : bool, optional
Bind the method without performing
checks. Used to bootstrap methods that are required and
know to exist
Returns
-------
MatlabFunction
A reference to a newly bound MatlabFunction instance if the
requested name is determined to be a callable function
Raises
------
AttributeError: if the requested name is not a callable
Matlab function | [
"Generate",
"a",
"Matlab",
"function",
"and",
"bind",
"it",
"to",
"the",
"instance"
] | 9822c7b55435662f4f033c5479cc03fea2255755 | https://github.com/arokem/python-matlab-bridge/blob/9822c7b55435662f4f033c5479cc03fea2255755/pymatbridge/pymatbridge.py#L359-L411 | train | 48,094 |
arokem/python-matlab-bridge | pymatbridge/publish.py | format_line | def format_line(line):
"""
Format a line of Matlab into either a markdown line or a code line.
Parameters
----------
line : str
The line of code to be formatted. Formatting occurs according to the
following rules:
- If the line starts with (at least) two %% signs, a new cell will be
started.
- If the line doesn't start with a '%' sign, it is assumed to be legit
matlab code. We will continue to add to the same cell until reaching
the next comment line
"""
if line.startswith('%%'):
md = True
new_cell = True
source = line.split('%%')[1] + '\n' # line-breaks in md require a line
# gap!
elif line.startswith('%'):
md = True
new_cell = False
source = line.split('%')[1] + '\n'
else:
md = False
new_cell = False
source = line
return new_cell, md, source | python | def format_line(line):
"""
Format a line of Matlab into either a markdown line or a code line.
Parameters
----------
line : str
The line of code to be formatted. Formatting occurs according to the
following rules:
- If the line starts with (at least) two %% signs, a new cell will be
started.
- If the line doesn't start with a '%' sign, it is assumed to be legit
matlab code. We will continue to add to the same cell until reaching
the next comment line
"""
if line.startswith('%%'):
md = True
new_cell = True
source = line.split('%%')[1] + '\n' # line-breaks in md require a line
# gap!
elif line.startswith('%'):
md = True
new_cell = False
source = line.split('%')[1] + '\n'
else:
md = False
new_cell = False
source = line
return new_cell, md, source | [
"def",
"format_line",
"(",
"line",
")",
":",
"if",
"line",
".",
"startswith",
"(",
"'%%'",
")",
":",
"md",
"=",
"True",
"new_cell",
"=",
"True",
"source",
"=",
"line",
".",
"split",
"(",
"'%%'",
")",
"[",
"1",
"]",
"+",
"'\\n'",
"# line-breaks in md ... | Format a line of Matlab into either a markdown line or a code line.
Parameters
----------
line : str
The line of code to be formatted. Formatting occurs according to the
following rules:
- If the line starts with (at least) two %% signs, a new cell will be
started.
- If the line doesn't start with a '%' sign, it is assumed to be legit
matlab code. We will continue to add to the same cell until reaching
the next comment line | [
"Format",
"a",
"line",
"of",
"Matlab",
"into",
"either",
"a",
"markdown",
"line",
"or",
"a",
"code",
"line",
"."
] | 9822c7b55435662f4f033c5479cc03fea2255755 | https://github.com/arokem/python-matlab-bridge/blob/9822c7b55435662f4f033c5479cc03fea2255755/pymatbridge/publish.py#L11-L45 | train | 48,095 |
arokem/python-matlab-bridge | pymatbridge/publish.py | lines_to_notebook | def lines_to_notebook(lines, name=None):
"""
Convert the lines of an m file into an IPython notebook
Parameters
----------
lines : list
A list of strings. Each element is a line in the m file
Returns
-------
notebook : an IPython NotebookNode class instance, containing the
information required to create a file
"""
source = []
md = np.empty(len(lines), dtype=object)
new_cell = np.empty(len(lines), dtype=object)
for idx, l in enumerate(lines):
new_cell[idx], md[idx], this_source = format_line(l)
# Transitions between markdown and code and vice-versa merit a new
# cell, even if no newline, or "%%" is found. Make sure not to do this
# check for the very first line!
if idx>1 and not new_cell[idx]:
if md[idx] != md[idx-1]:
new_cell[idx] = True
source.append(this_source)
# This defines the breaking points between cells:
new_cell_idx = np.hstack([np.where(new_cell)[0], -1])
# Listify the sources:
cell_source = [source[new_cell_idx[i]:new_cell_idx[i+1]]
for i in range(len(new_cell_idx)-1)]
cell_md = [md[new_cell_idx[i]] for i in range(len(new_cell_idx)-1)]
cells = []
# Append the notebook with loading matlab magic extension
notebook_head = "import pymatbridge as pymat\n" + "ip = get_ipython()\n" \
+ "pymat.load_ipython_extension(ip)"
cells.append(nbformat.new_code_cell(notebook_head))#, language='python'))
for cell_idx, cell_s in enumerate(cell_source):
if cell_md[cell_idx]:
cells.append(nbformat.new_markdown_cell(cell_s))
else:
cell_s.insert(0, '%%matlab\n')
cells.append(nbformat.new_code_cell(cell_s))#, language='matlab'))
#ws = nbformat.new_worksheet(cells=cells)
notebook = nbformat.new_notebook(cells=cells)
return notebook | python | def lines_to_notebook(lines, name=None):
"""
Convert the lines of an m file into an IPython notebook
Parameters
----------
lines : list
A list of strings. Each element is a line in the m file
Returns
-------
notebook : an IPython NotebookNode class instance, containing the
information required to create a file
"""
source = []
md = np.empty(len(lines), dtype=object)
new_cell = np.empty(len(lines), dtype=object)
for idx, l in enumerate(lines):
new_cell[idx], md[idx], this_source = format_line(l)
# Transitions between markdown and code and vice-versa merit a new
# cell, even if no newline, or "%%" is found. Make sure not to do this
# check for the very first line!
if idx>1 and not new_cell[idx]:
if md[idx] != md[idx-1]:
new_cell[idx] = True
source.append(this_source)
# This defines the breaking points between cells:
new_cell_idx = np.hstack([np.where(new_cell)[0], -1])
# Listify the sources:
cell_source = [source[new_cell_idx[i]:new_cell_idx[i+1]]
for i in range(len(new_cell_idx)-1)]
cell_md = [md[new_cell_idx[i]] for i in range(len(new_cell_idx)-1)]
cells = []
# Append the notebook with loading matlab magic extension
notebook_head = "import pymatbridge as pymat\n" + "ip = get_ipython()\n" \
+ "pymat.load_ipython_extension(ip)"
cells.append(nbformat.new_code_cell(notebook_head))#, language='python'))
for cell_idx, cell_s in enumerate(cell_source):
if cell_md[cell_idx]:
cells.append(nbformat.new_markdown_cell(cell_s))
else:
cell_s.insert(0, '%%matlab\n')
cells.append(nbformat.new_code_cell(cell_s))#, language='matlab'))
#ws = nbformat.new_worksheet(cells=cells)
notebook = nbformat.new_notebook(cells=cells)
return notebook | [
"def",
"lines_to_notebook",
"(",
"lines",
",",
"name",
"=",
"None",
")",
":",
"source",
"=",
"[",
"]",
"md",
"=",
"np",
".",
"empty",
"(",
"len",
"(",
"lines",
")",
",",
"dtype",
"=",
"object",
")",
"new_cell",
"=",
"np",
".",
"empty",
"(",
"len"... | Convert the lines of an m file into an IPython notebook
Parameters
----------
lines : list
A list of strings. Each element is a line in the m file
Returns
-------
notebook : an IPython NotebookNode class instance, containing the
information required to create a file | [
"Convert",
"the",
"lines",
"of",
"an",
"m",
"file",
"into",
"an",
"IPython",
"notebook"
] | 9822c7b55435662f4f033c5479cc03fea2255755 | https://github.com/arokem/python-matlab-bridge/blob/9822c7b55435662f4f033c5479cc03fea2255755/pymatbridge/publish.py#L62-L114 | train | 48,096 |
arokem/python-matlab-bridge | pymatbridge/publish.py | convert_mfile | def convert_mfile(mfile, outfile=None):
"""
Convert a Matlab m-file into a Matlab notebook in ipynb format
Parameters
----------
mfile : string
Full path to a matlab m file to convert
outfile : string (optional)
Full path to the output ipynb file
"""
lines = mfile_to_lines(mfile)
nb = lines_to_notebook(lines)
if outfile is None:
outfile = mfile.split('.m')[0] + '.ipynb'
with open(outfile, 'w') as fid:
nbwrite(nb, fid) | python | def convert_mfile(mfile, outfile=None):
"""
Convert a Matlab m-file into a Matlab notebook in ipynb format
Parameters
----------
mfile : string
Full path to a matlab m file to convert
outfile : string (optional)
Full path to the output ipynb file
"""
lines = mfile_to_lines(mfile)
nb = lines_to_notebook(lines)
if outfile is None:
outfile = mfile.split('.m')[0] + '.ipynb'
with open(outfile, 'w') as fid:
nbwrite(nb, fid) | [
"def",
"convert_mfile",
"(",
"mfile",
",",
"outfile",
"=",
"None",
")",
":",
"lines",
"=",
"mfile_to_lines",
"(",
"mfile",
")",
"nb",
"=",
"lines_to_notebook",
"(",
"lines",
")",
"if",
"outfile",
"is",
"None",
":",
"outfile",
"=",
"mfile",
".",
"split",
... | Convert a Matlab m-file into a Matlab notebook in ipynb format
Parameters
----------
mfile : string
Full path to a matlab m file to convert
outfile : string (optional)
Full path to the output ipynb file | [
"Convert",
"a",
"Matlab",
"m",
"-",
"file",
"into",
"a",
"Matlab",
"notebook",
"in",
"ipynb",
"format"
] | 9822c7b55435662f4f033c5479cc03fea2255755 | https://github.com/arokem/python-matlab-bridge/blob/9822c7b55435662f4f033c5479cc03fea2255755/pymatbridge/publish.py#L117-L135 | train | 48,097 |
arokem/python-matlab-bridge | tools/gh_api.py | post_gist | def post_gist(content, description='', filename='file', auth=False):
"""Post some text to a Gist, and return the URL."""
post_data = json.dumps({
"description": description,
"public": True,
"files": {
filename: {
"content": content
}
}
}).encode('utf-8')
headers = make_auth_header() if auth else {}
response = requests.post("https://api.github.com/gists", data=post_data, headers=headers)
response.raise_for_status()
response_data = json.loads(response.text)
return response_data['html_url'] | python | def post_gist(content, description='', filename='file', auth=False):
"""Post some text to a Gist, and return the URL."""
post_data = json.dumps({
"description": description,
"public": True,
"files": {
filename: {
"content": content
}
}
}).encode('utf-8')
headers = make_auth_header() if auth else {}
response = requests.post("https://api.github.com/gists", data=post_data, headers=headers)
response.raise_for_status()
response_data = json.loads(response.text)
return response_data['html_url'] | [
"def",
"post_gist",
"(",
"content",
",",
"description",
"=",
"''",
",",
"filename",
"=",
"'file'",
",",
"auth",
"=",
"False",
")",
":",
"post_data",
"=",
"json",
".",
"dumps",
"(",
"{",
"\"description\"",
":",
"description",
",",
"\"public\"",
":",
"True... | Post some text to a Gist, and return the URL. | [
"Post",
"some",
"text",
"to",
"a",
"Gist",
"and",
"return",
"the",
"URL",
"."
] | 9822c7b55435662f4f033c5479cc03fea2255755 | https://github.com/arokem/python-matlab-bridge/blob/9822c7b55435662f4f033c5479cc03fea2255755/tools/gh_api.py#L80-L96 | train | 48,098 |
arokem/python-matlab-bridge | tools/gh_api.py | get_pull_request | def get_pull_request(project, num, auth=False):
"""get pull request info by number
"""
url = "https://api.github.com/repos/{project}/pulls/{num}".format(project=project, num=num)
if auth:
header = make_auth_header()
else:
header = None
response = requests.get(url, headers=header)
response.raise_for_status()
return json.loads(response.text, object_hook=Obj) | python | def get_pull_request(project, num, auth=False):
"""get pull request info by number
"""
url = "https://api.github.com/repos/{project}/pulls/{num}".format(project=project, num=num)
if auth:
header = make_auth_header()
else:
header = None
response = requests.get(url, headers=header)
response.raise_for_status()
return json.loads(response.text, object_hook=Obj) | [
"def",
"get_pull_request",
"(",
"project",
",",
"num",
",",
"auth",
"=",
"False",
")",
":",
"url",
"=",
"\"https://api.github.com/repos/{project}/pulls/{num}\"",
".",
"format",
"(",
"project",
"=",
"project",
",",
"num",
"=",
"num",
")",
"if",
"auth",
":",
"... | get pull request info by number | [
"get",
"pull",
"request",
"info",
"by",
"number"
] | 9822c7b55435662f4f033c5479cc03fea2255755 | https://github.com/arokem/python-matlab-bridge/blob/9822c7b55435662f4f033c5479cc03fea2255755/tools/gh_api.py#L98-L108 | train | 48,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.