_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 31 13.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q261100 | passcode | validation | def passcode(callsign):
"""
Takes a CALLSIGN and returns passcode
"""
assert isinstance(callsign, str)
callsign = callsign.split('-')[0].upper()
code = 0x73e2
for | python | {
"resource": ""
} |
q261101 | parse_header | validation | def parse_header(head):
"""
Parses the header part of packet
Returns a dict
"""
try:
(fromcall, path) = head.split('>', 1)
except:
raise ParseError("invalid packet header")
if (not 1 <= len(fromcall) <= 9 or
not re.findall(r"^[a-z0-9]{0,9}(\-[a-z0-9]{1,8})?$", fromcall, re.I)):
raise ParseError("fromcallsign is invalid")
path = path.split(',')
if len(path[0]) == 0:
raise ParseError("no tocallsign in header")
tocall = path[0]
path = path[1:]
validate_callsign(tocall, "tocallsign")
for digi in path:
if not re.findall(r"^[A-Z0-9\-]{1,9}\*?$", digi, re.I):
| python | {
"resource": ""
} |
q261102 | IS.set_filter | validation | def set_filter(self, filter_text):
"""
Set a specified aprs-is filter for this connection
"""
self.filter = filter_text
self.logger.info("Setting | python | {
"resource": ""
} |
q261103 | IS.set_login | validation | def set_login(self, callsign, passwd="-1", skip_login=False):
"""
Set callsign and | python | {
"resource": ""
} |
q261104 | IS.connect | validation | def connect(self, blocking=False, retry=30):
"""
Initiate connection to APRS server and attempt to login
blocking = False - Should we block until connected and logged-in
retry = 30 - Retry interval in seconds
"""
if self._connected:
return
while True:
try:
self._connect()
if not self.skip_login: | python | {
"resource": ""
} |
q261105 | IS.close | validation | def close(self):
"""
Closes the socket
Called internally when Exceptions are raised | python | {
"resource": ""
} |
q261106 | IS.sendall | validation | def sendall(self, line):
"""
Send a line, or multiple lines sperapted by '\\r\\n'
"""
if isinstance(line, APRSPacket):
line = str(line)
elif not isinstance(line, string_type):
raise TypeError("Expected line to be str or APRSPacket, got %s", type(line))
if not self._connected:
raise ConnectionError("not connected")
if line == "":
return
line = line.rstrip("\r\n") + "\r\n"
| python | {
"resource": ""
} |
q261107 | IS.consumer | validation | def consumer(self, callback, blocking=True, immortal=False, raw=False):
"""
When a position sentence is received, it will be passed to the callback function
blocking: if true (default), runs forever, otherwise will return after one sentence
You can still exit the loop, by raising StopIteration in the callback function
immortal: When true, consumer will try to reconnect and stop propagation of Parse exceptions
if false (default), consumer will return
raw: when true, raw packet is passed to callback, otherwise the result from aprs.parse()
"""
if not self._connected:
raise ConnectionError("not connected to a server")
line = b''
while True:
try:
for line in self._socket_readlines(blocking):
if line[0:1] != b'#':
if raw:
callback(line)
else:
callback(self._parse(line))
else:
self.logger.debug("Server: %s", line.decode('utf8'))
except ParseError as exp:
self.logger.log(11, "%s\n Packet: %s", exp.message, exp.packet)
except UnknownFormat as exp:
self.logger.log(9, "%s\n Packet: %s", exp.message, exp.packet)
except LoginError as exp:
| python | {
"resource": ""
} |
q261108 | IS._connect | validation | def _connect(self):
"""
Attemps connection to the server
"""
self.logger.info("Attempting connection to %s:%s", self.server[0], self.server[1])
try:
self._open_socket()
peer = self.sock.getpeername()
self.logger.info("Connected to %s", str(peer))
# 5 second timeout to receive server banner
self.sock.setblocking(1)
self.sock.settimeout(5)
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
| python | {
"resource": ""
} |
q261109 | IS._send_login | validation | def _send_login(self):
"""
Sends login string to server
"""
login_str = "user {0} pass {1} vers aprslib {3}{2}\r\n"
login_str = login_str.format(
self.callsign,
self.passwd,
(" filter " + self.filter) if self.filter != "" else "",
__version__
)
self.logger.info("Sending login information")
try:
self._sendall(login_str)
self.sock.settimeout(5)
test = self.sock.recv(len(login_str) + 100)
if is_py3:
test = test.decode('latin-1')
test = test.rstrip()
self.logger.debug("Server: %s", test)
_, _, callsign, status, _ = test.split(' ', 4)
if callsign == "":
raise LoginError("Server responded with empty callsign???")
if callsign != self.callsign:
raise LoginError("Server: %s" % test)
if status != "verified," and | python | {
"resource": ""
} |
q261110 | IS._socket_readlines | validation | def _socket_readlines(self, blocking=False):
"""
Generator for complete lines, received from the server
"""
try:
self.sock.setblocking(0)
except socket.error as e:
self.logger.error("socket error when setblocking(0): %s" % str(e))
raise ConnectionDrop("connection dropped")
while True:
short_buf = b''
newline = b'\r\n'
select.select([self.sock], [], [], None if blocking else 0)
try:
short_buf = self.sock.recv(4096)
# sock.recv returns empty if the connection drops
if not short_buf:
self.logger.error("socket.recv(): returned empty")
raise ConnectionDrop("connection dropped")
except socket.error as e:
| python | {
"resource": ""
} |
q261111 | OrderedUUIDField.db_value | validation | def db_value(self, value):
"""
Convert UUID to binary blob
"""
# ensure we have a valid UUID
if not isinstance(value, UUID):
value = UUID(value)
# reconstruct for optimal indexing
parts = str(value).split("-")
reordered = ''.join([parts[2], | python | {
"resource": ""
} |
q261112 | OrderedUUIDField.python_value | validation | def python_value(self, value):
"""
Convert binary blob to UUID instance
"""
value = super(OrderedUUIDField, self).python_value(value)
u = binascii.b2a_hex(value)
| python | {
"resource": ""
} |
q261113 | HashField.db_value | validation | def db_value(self, value):
"""Convert the python value for storage in the database."""
value = self.transform_value(value)
| python | {
"resource": ""
} |
q261114 | HashField.python_value | validation | def python_value(self, value):
"""Convert the database value to a pythonic value."""
value = coerce_to_bytes(value)
| python | {
"resource": ""
} |
q261115 | DatabaseManager.disconnect | validation | def disconnect(self):
"""Disconnect from all databases"""
for name, connection in self.items():
if not | python | {
"resource": ""
} |
q261116 | DatabaseManager.get_database | validation | def get_database(self, model):
"""Find matching database router"""
for router in self.routers:
r = router.get_database(model)
| python | {
"resource": ""
} |
q261117 | Model.to_cursor_ref | validation | def to_cursor_ref(self):
"""Returns dict of values to uniquely reference this item"""
fields = self._meta.get_primary_keys()
assert fields
| python | {
"resource": ""
} |
q261118 | PrimaryKeyPagination.paginate_query | validation | def paginate_query(self, query, count, offset=None, sort=None):
"""
Apply pagination to query
:attr query: Instance of `peewee.Query`
:attr count: Max rows to return
:attr offset: Pagination offset, str/int
:attr sort: List of tuples, e.g. [('id', 'asc')]
:returns: Instance of `peewee.Query`
"""
assert isinstance(query, peewee.Query)
assert isinstance(count, int)
assert isinstance(offset, (str, int, type(None)))
assert isinstance(sort, (list, set, tuple, type(None)))
# ensure our model has a primary key
fields = query.model._meta.get_primary_keys()
if len(fields) == 0:
raise peewee.ProgrammingError(
'Cannot apply pagination on model without primary key')
# ensure our model doesn't use a compound primary key
if len(fields) > 1:
raise peewee.ProgrammingError(
'Cannot apply pagination on model with compound primary key')
# apply offset
if offset is not None:
query = query.where(fields[0] >= offset)
# do we need to apply sorting?
order_bys = []
if sort:
| python | {
"resource": ""
} |
q261119 | ModelCRUD.apply_filters | validation | def apply_filters(self, query, filters):
"""
Apply user specified filters to query
"""
| python | {
"resource": ""
} |
q261120 | ModelCRUD.list | validation | def list(self, filters, cursor, count):
"""
List items from query
"""
assert isinstance(filters, dict), "expected filters type 'dict'"
assert isinstance(cursor, dict), "expected cursor type 'dict'"
# start with our base query
query = self.get_query()
assert isinstance(query, peewee.Query)
# XXX: convert and apply user specified filters
#filters = {field.name: cursor[field.name] for field in fields}
#query.where(
paginator = self.get_paginator()
assert isinstance(paginator, Pagination)
# always include an extra row for next cursor position
count += 1
| python | {
"resource": ""
} |
q261121 | ModelCRUD.retrieve | validation | def retrieve(self, cursor):
"""
Retrieve items from query
"""
assert isinstance(cursor, dict), "expected cursor type 'dict'"
# look for record in query | python | {
"resource": ""
} |
q261122 | AWS4Auth.regenerate_signing_key | validation | def regenerate_signing_key(self, secret_key=None, region=None,
service=None, date=None):
"""
Regenerate the signing key for this instance. Store the new key in
signing_key property.
Take scope elements of the new key from the equivalent properties
(region, service, date) of the current AWS4Auth instance. Scope
elements can be overridden for the new key by supplying arguments to
this function. If overrides are supplied update the current AWS4Auth
instance's equivalent properties to match the new values.
If secret_key is not specified use the value of the secret_key property
of the current AWS4Auth instance's signing key. If the existing signing
key is not storing its secret key (i.e. store_secret_key was set to
False at instantiation) then raise a NoSecretKeyError and do not
regenerate the key. In order to regenerate a key which is not storing
its secret key, secret_key must be supplied to this function.
Use the value of the existing key's store_secret_key property when
generating the new key. If there is no existing key, then default
to setting store_secret_key to True for new key.
"""
if secret_key is None and (self.signing_key is None or
| python | {
"resource": ""
} |
q261123 | AWS4Auth.get_request_date | validation | def get_request_date(cls, req):
"""
Try to pull a date from the request by looking first at the
x-amz-date header, and if that's not present then the Date header.
Return a datetime.date object, or None if neither date header
is found or is in a recognisable format.
req -- a requests PreparedRequest object
"""
date = None
for header in ['x-amz-date', 'date']:
if header not in req.headers:
continue
| python | {
"resource": ""
} |
q261124 | AWS4Auth.parse_date | validation | def parse_date(date_str):
"""
Check if date_str is in a recognised format and return an ISO
yyyy-mm-dd format version if so. Raise DateFormatError if not.
Recognised formats are:
* RFC 7231 (e.g. Mon, 09 Sep 2011 23:36:00 GMT)
* RFC 850 (e.g. Sunday, 06-Nov-94 08:49:37 GMT)
* C time (e.g. Wed Dec 4 00:00:00 2002)
* Amz-Date format (e.g. 20090325T010101Z)
* ISO 8601 / RFC 3339 (e.g. 2009-03-25T10:11:12.13-01:00)
date_str -- Str containing a date and optional time
"""
months = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug',
'sep', 'oct', 'nov', 'dec']
formats = {
# RFC 7231, e.g. 'Mon, 09 Sep 2011 23:36:00 GMT'
r'^(?:\w{3}, )?(\d{2}) (\w{3}) (\d{4})\D.*$':
lambda m: '{}-{:02d}-{}'.format(
m.group(3),
months.index(m.group(2).lower())+1,
m.group(1)),
# RFC 850 (e.g. Sunday, 06-Nov-94 08:49:37 GMT)
# assumes current century
r'^\w+day, (\d{2})-(\w{3})-(\d{2})\D.*$':
lambda m: '{}{}-{:02d}-{}'.format(
str(datetime.date.today().year)[:2],
m.group(3),
months.index(m.group(2).lower())+1,
m.group(1)),
# C | python | {
"resource": ""
} |
q261125 | AWS4Auth.handle_date_mismatch | validation | def handle_date_mismatch(self, req):
"""
Handle a request whose date doesn't match the signing key scope date.
This AWS4Auth class implementation regenerates the signing key. See
StrictAWS4Auth class if you would prefer an exception to be raised.
req -- a requests prepared request object
| python | {
"resource": ""
} |
q261126 | AWS4Auth.encode_body | validation | def encode_body(req):
"""
Encode body of request to bytes and update content-type if required.
If the body of req is Unicode then encode to the charset found in
content-type header if present, otherwise UTF-8, or ASCII if
content-type is application/x-www-form-urlencoded. If encoding to UTF-8
then add charset to content-type. Modifies req directly, does not
return a modified copy.
req -- Requests PreparedRequest object
| python | {
"resource": ""
} |
q261127 | AWS4Auth.get_canonical_request | validation | def get_canonical_request(self, req, cano_headers, signed_headers):
"""
Create the AWS authentication Canonical Request string.
req -- Requests PreparedRequest object. Should already
include an x-amz-content-sha256 header
cano_headers -- Canonical Headers section of Canonical Request, as
returned by get_canonical_headers()
signed_headers -- Signed Headers, as returned by
get_canonical_headers()
"""
url = urlparse(req.url)
path = self.amz_cano_path(url.path)
# AWS | python | {
"resource": ""
} |
q261128 | AWS4Auth.get_canonical_headers | validation | def get_canonical_headers(cls, req, include=None):
"""
Generate the Canonical Headers section of the Canonical Request.
Return the Canonical Headers and the Signed Headers strs as a tuple
(canonical_headers, signed_headers).
req -- Requests PreparedRequest object
include -- List of headers to include in the canonical and signed
headers. It's primarily included to allow testing against
specific examples from Amazon. If omitted or None it
includes host, content-type and any header starting 'x-amz-'
except for x-amz-client context, which appears to break
mobile analytics auth if included. Except for the
x-amz-client-context exclusion these defaults are per the
AWS documentation.
"""
if include is None:
include = cls.default_include_headers
include = [x.lower() for x in include]
headers = req.headers.copy()
# Temporarily include the host header - AWS requires it to be included
# in the signed headers, but Requests doesn't include it in a
# PreparedRequest
if 'host' not in headers:
headers['host'] = urlparse(req.url).netloc.split(':')[0]
# Aggregate for upper/lowercase header name collisions in header names,
# AMZ requires values of colliding headers be concatenated into a
# single header with lowercase name. Although this is not possible with
# | python | {
"resource": ""
} |
q261129 | AWS4Auth.get_sig_string | validation | def get_sig_string(req, cano_req, scope):
"""
Generate the AWS4 auth string to sign for the request.
req -- Requests PreparedRequest object. This should already
include an x-amz-date header.
| python | {
"resource": ""
} |
q261130 | AWS4Auth.amz_cano_path | validation | def amz_cano_path(self, path):
"""
Generate the canonical path as per AWS4 auth requirements.
Not documented anywhere, determined from aws4_testsuite examples,
problem reports and testing against the live services.
path -- request path
"""
safe_chars = '/~'
qs = ''
fixed_path = path
if '?' in fixed_path:
fixed_path, qs = fixed_path.split('?', 1)
fixed_path = posixpath.normpath(fixed_path)
fixed_path = re.sub('/+', '/', fixed_path)
| python | {
"resource": ""
} |
q261131 | AWS4Auth.amz_cano_querystring | validation | def amz_cano_querystring(qs):
"""
Parse and format querystring as per AWS4 auth requirements.
Perform percent quoting as needed.
qs -- querystring
"""
safe_qs_amz_chars = '&=+'
safe_qs_unresvd = '-_.~'
# If Python 2, switch to working entirely in str
# as quote() has problems with Unicode
if PY2:
qs = qs.encode('utf-8')
safe_qs_amz_chars = safe_qs_amz_chars.encode()
safe_qs_unresvd = safe_qs_unresvd.encode()
qs = unquote(qs)
space = b' ' if PY2 else ' '
qs = qs.split(space)[0]
qs = quote(qs, safe=safe_qs_amz_chars)
| python | {
"resource": ""
} |
q261132 | AWS4SigningKey.generate_key | validation | def generate_key(cls, secret_key, region, service, date,
intermediates=False):
"""
Generate the signing key string as bytes.
If intermediate is set to True, returns a 4-tuple containing the key
and the intermediate keys:
( signing_key, date_key, region_key, service_key )
| python | {
"resource": ""
} |
q261133 | AWS4SigningKey.sign_sha256 | validation | def sign_sha256(key, msg):
"""
Generate an SHA256 HMAC, encoding msg to UTF-8 if not
already encoded.
key -- signing key. bytes.
msg -- message to sign. unicode or bytes.
"""
| python | {
"resource": ""
} |
q261134 | _format_datetime | validation | def _format_datetime(dttm):
"""Convert a datetime object into a valid STIX timestamp string.
1. Convert to timezone-aware
2. Convert to UTC
3. Format in ISO format
4. Ensure correct precision
a. Add subsecond value if non-zero and precision not defined
5. Add "Z"
"""
if dttm.tzinfo is None or dttm.tzinfo.utcoffset(dttm) is None:
| python | {
"resource": ""
} |
q261135 | _ensure_datetime_to_string | validation | def _ensure_datetime_to_string(maybe_dttm):
"""If maybe_dttm is a datetime instance, convert to a STIX-compliant
string representation. Otherwise return the value unchanged."""
| python | {
"resource": ""
} |
q261136 | _to_json | validation | def _to_json(resp):
"""
Factors out some JSON parse code with error handling, to hopefully improve
error messages.
:param resp: A "requests" library response
:return: Parsed JSON.
:raises: InvalidJSONError If JSON parsing failed.
"""
try:
return resp.json()
except ValueError as e: | python | {
"resource": ""
} |
q261137 | Status.refresh | validation | def refresh(self, accept=MEDIA_TYPE_TAXII_V20):
"""Updates Status information"""
response = self.__raw = self._conn.get(self.url,
| python | {
"resource": ""
} |
q261138 | Status.wait_until_final | validation | def wait_until_final(self, poll_interval=1, timeout=60):
"""It will poll the URL to grab the latest status resource in a given
timeout and time interval.
Args:
poll_interval (int): how often to poll the status service.
timeout (int): how long to poll the URL until giving up. Use <= 0
to wait forever
"""
start_time = time.time()
| python | {
"resource": ""
} |
q261139 | Status._validate_status | validation | def _validate_status(self):
"""Validates Status information. Raises errors for required
properties."""
if not self.id:
msg = "No 'id' in Status for request '{}'"
raise ValidationError(msg.format(self.url))
if not self.status:
msg = "No 'status' in Status for request '{}'"
raise ValidationError(msg.format(self.url))
if self.total_count is None:
msg = "No 'total_count' in Status for request '{}'"
raise ValidationError(msg.format(self.url))
if self.success_count is None:
msg = "No 'success_count' in Status for request '{}'"
raise ValidationError(msg.format(self.url))
if self.failure_count is None:
msg = "No 'failure_count' in Status for request '{}'"
raise ValidationError(msg.format(self.url))
if self.pending_count is None:
msg = "No 'pending_count' in Status for request '{}'"
raise ValidationError(msg.format(self.url))
if len(self.successes) != self.success_count:
msg = "Found successes={}, but success_count={} in status '{}'"
raise ValidationError(msg.format(self.successes,
self.success_count,
self.id))
if len(self.pendings) != self.pending_count:
msg = "Found pendings={}, but pending_count={} in status '{}'"
raise ValidationError(msg.format(self.pendings,
self.pending_count,
self.id))
if len(self.failures) != | python | {
"resource": ""
} |
q261140 | Collection._validate_collection | validation | def _validate_collection(self):
"""Validates Collection information. Raises errors for required
properties."""
if not self._id:
msg = "No 'id' in Collection for request '{}'"
raise ValidationError(msg.format(self.url))
if not self._title:
msg = "No 'title' in Collection for request '{}'"
raise ValidationError(msg.format(self.url))
if self._can_read is None:
msg = "No 'can_read' in Collection for request '{}'"
raise ValidationError(msg.format(self.url))
if self._can_write is None:
| python | {
"resource": ""
} |
q261141 | ApiRoot._validate_api_root | validation | def _validate_api_root(self):
"""Validates API Root information. Raises errors for required
properties."""
if not self._title:
msg = "No 'title' in API Root for request '{}'"
raise ValidationError(msg.format(self.url))
if not self._versions:
msg = "No 'versions' in API Root for request '{}'"
| python | {
"resource": ""
} |
q261142 | ApiRoot.refresh | validation | def refresh(self, accept=MEDIA_TYPE_TAXII_V20):
"""Update the API Root's information and list of Collections"""
| python | {
"resource": ""
} |
q261143 | ApiRoot.refresh_information | validation | def refresh_information(self, accept=MEDIA_TYPE_TAXII_V20):
"""Update the properties of this API Root.
This invokes the ``Get API Root Information`` endpoint.
"""
response = self.__raw = self._conn.get(self.url,
| python | {
"resource": ""
} |
q261144 | ApiRoot.refresh_collections | validation | def refresh_collections(self, accept=MEDIA_TYPE_TAXII_V20):
"""Update the list of Collections contained by this API Root.
This invokes the ``Get Collections`` endpoint.
"""
url = self.url + "collections/"
response = self._conn.get(url, headers={"Accept": accept})
self._collections = []
for item in response.get("collections", []): # optional
| python | {
"resource": ""
} |
q261145 | Server._validate_server | validation | def _validate_server(self):
"""Validates server information. Raises errors for required properties.
"""
if not self._title:
msg = "No 'title' in | python | {
"resource": ""
} |
q261146 | Server.refresh | validation | def refresh(self):
"""Update the Server information and list of API Roots"""
response = self.__raw = self._conn.get(self.url)
| python | {
"resource": ""
} |
q261147 | _HTTPConnection.valid_content_type | validation | def valid_content_type(self, content_type, accept):
"""Check that the server is returning a valid Content-Type
Args:
content_type (str): ``Content-Type:`` header value
accept (str): media type to include in the ``Accept:`` header.
"""
accept_tokens = accept.replace(' ', '').split(';')
content_type_tokens = content_type.replace(' ', '').split(';') | python | {
"resource": ""
} |
q261148 | _HTTPConnection.get | validation | def get(self, url, headers=None, params=None):
"""Perform an HTTP GET, using the saved requests.Session and auth info.
If "Accept" isn't one of the given headers, a default TAXII mime type is
used. Regardless, the response type is checked against the accept
header value, and an exception is raised if they don't match.
Args:
url (str): URL to retrieve
headers (dict): Any other headers to be added to the request.
params: dictionary or bytes to be sent in the query string for the
request. (optional)
"""
merged_headers = self._merge_headers(headers)
if "Accept" not in merged_headers:
| python | {
"resource": ""
} |
q261149 | _HTTPConnection.post | validation | def post(self, url, headers=None, params=None, **kwargs):
"""Send a JSON POST request with the given request headers, additional
URL query parameters, and the given JSON in the request body. The
extra query parameters are merged with any which already exist in the
URL. The 'json' and 'data' parameters may not both be given.
Args:
url (str): URL to retrieve
headers (dict): Any other headers to be added to the request.
params: dictionary or bytes to be sent in the query string for the
request. (optional)
json: json to send in the body of the Request. This must be a
JSON-serializable object. (optional)
data: raw request body data. May be a dictionary, list of tuples,
bytes, or file-like object to send in the body of the Request.
(optional)
"""
| python | {
"resource": ""
} |
q261150 | total_memory | validation | def total_memory():
""" Returns the the amount of memory available for use.
The memory is obtained from MemTotal entry in /proc/meminfo.
Notes
=====
This function is not very useful and not very portable.
"""
with file('/proc/meminfo', 'r') as f:
| python | {
"resource": ""
} |
q261151 | cpu_count | validation | def cpu_count():
""" Returns the default number of slave processes to be spawned.
The default value is the number of physical cpu cores seen by python.
:code:`OMP_NUM_THREADS` environment variable overrides it.
On PBS/torque systems if OMP_NUM_THREADS is empty, we try to
| python | {
"resource": ""
} |
q261152 | empty_like | validation | def empty_like(array, dtype=None):
""" Create a shared memory array from the shape of array.
"""
array = numpy.asarray(array)
if dtype | python | {
"resource": ""
} |
q261153 | full_like | validation | def full_like(array, value, dtype=None):
""" Create a shared memory array with the same shape and type as a given array, filled with `value`.
"""
| python | {
"resource": ""
} |
q261154 | full | validation | def full(shape, value, dtype='f8'):
""" Create a shared memory array of given shape | python | {
"resource": ""
} |
q261155 | copy | validation | def copy(a):
""" Copy an array to the shared memory.
Notes
-----
copy is not always necessary because the private memory is always copy-on-write.
Use :code:`a = copy(a)` to immediately | python | {
"resource": ""
} |
q261156 | ProcessGroup.get | validation | def get(self, Q):
""" Protected get. Get an item from Q.
Will block. but if the process group has errors,
raise an StopProcessGroup exception.
A slave process will terminate upon StopProcessGroup.
The master process shall read the error from the process group.
"""
while self.Errors.empty():
try:
| python | {
"resource": ""
} |
q261157 | background.wait | validation | def wait(self):
""" Wait and join the child process.
The return value of the function call is returned.
If any exception occurred it is wrapped and raised.
"""
e, r = self.result.get()
self.slave.join()
| python | {
"resource": ""
} |
q261158 | MapReduce.map | validation | def map(self, func, sequence, reduce=None, star=False, minlength=0):
""" Map-reduce with multile processes.
Apply func to each item on the sequence, in parallel.
As the results are collected, reduce is called on the result.
The reduced result is returned as a list.
Parameters
----------
func : callable
The function to call. It must accept the same number of
arguments as the length of an item in the sequence.
.. warning::
func is not supposed to use exceptions for flow control.
In non-debug mode all exceptions will be wrapped into
a :py:class:`SlaveException`.
sequence : list or array_like
The sequence of arguments to be applied to func.
reduce : callable, optional
Apply an reduction operation on the
return values of func. If func returns a tuple, they
are treated as positional arguments of reduce.
star : boolean
if True, the items in sequence are treated as positional
arguments of reduce.
minlength: integer
Minimal length of `sequence` to start parallel processing.
if len(sequence) < minlength, fall back to sequential
processing. This can be used to avoid the overhead of starting
the worker processes when there is little work.
Returns
-------
results : list
The list of reduced results from the map operation, in
the order of the arguments of sequence.
Raises
------
SlaveException
If any of the slave process encounters
an exception. Inspect :py:attr:`SlaveException.reason` for the underlying exception.
"""
def realreduce(r):
if reduce:
if isinstance(r, tuple):
return reduce(*r)
else:
return reduce(r)
return r
def realfunc(i):
if star: return func(*i)
else: return func(i)
if len(sequence) <= 0 or self.np == 0 or get_debug():
# Do this in serial
self.local = lambda : None
self.local.rank = 0
rt = [realreduce(realfunc(i)) for i in sequence]
self.local = None
return rt
# never use more than len(sequence) processes
np = min([self.np, len(sequence)])
Q = self.backend.QueueFactory(64)
R = self.backend.QueueFactory(64)
self.ordered.reset()
pg = ProcessGroup(main=self._main, np=np,
backend=self.backend,
args=(Q, R, sequence, realfunc))
pg.start()
L = []
N = []
def feeder(pg, Q, N):
# will fail silently if any error occurs.
j = 0
try:
for i, work in enumerate(sequence):
if not hasattr(sequence, '__getitem__'):
| python | {
"resource": ""
} |
q261159 | loadtxt2 | validation | def loadtxt2(fname, dtype=None, delimiter=' ', newline='\n', comment_character='#',
skiplines=0):
""" Known issues delimiter and newline is not respected.
string quotation with space is broken.
"""
dtypert = [None, None, None]
def preparedtype(dtype):
dtypert[0] = dtype
flatten = flatten_dtype(dtype)
dtypert[1] = flatten
dtypert[2] = numpy.dtype([('a', (numpy.int8,
flatten.itemsize))])
buf = numpy.empty((), dtype=dtypert[1])
converters = [_default_conv[flatten[name].char] for name in flatten.names]
return buf, converters, flatten.names
def fileiter(fh):
converters = []
buf = None
if dtype is not None:
buf, converters, names = preparedtype(dtype)
yield None
for lineno, line in enumerate(fh):
if lineno < skiplines: continue
if line[0] in comment_character:
if buf is None and line[1] == '?':
| python | {
"resource": ""
} |
q261160 | flatten_dtype | validation | def flatten_dtype(dtype, _next=None):
""" Unpack a structured data-type. """
types = []
if _next is None:
_next = [0, '']
primary = True
else:
primary = False
prefix = _next[1]
if dtype.names is None:
for i in numpy.ndindex(dtype.shape):
if dtype.base == dtype:
types.append(('%s%s' % (prefix, simplerepr(i)), dtype))
_next[0] += 1
else:
_next[1] = '%s%s' % (prefix, simplerepr(i))
types.extend(flatten_dtype(dtype.base, _next))
| python | {
"resource": ""
} |
q261161 | MetaOrdered | validation | def MetaOrdered(parallel, done, turnstile):
"""meta class for Ordered construct."""
class Ordered:
def __init__(self, iterref):
if parallel.master:
done[...] = 0
self.iterref = iterref
parallel.barrier()
@classmethod
def abort(self):
turnstile.release()
def __enter__(self):
while self.iterref != done:
| python | {
"resource": ""
} |
q261162 | SlaveMonitor.kill_all | validation | def kill_all(self):
"""kill all slaves and reap the monitor """
for pid in self.children:
| python | {
"resource": ""
} |
q261163 | Barrier.abort | validation | def abort(self):
""" ensure the master exit from Barrier """
self.mutex.release()
self.turnstile.release() | python | {
"resource": ""
} |
q261164 | MultiPartStream.read | validation | def read(self, n):
""" return at most n array items, move the cursor.
"""
while len(self.pool) < n:
self.cur = self.files.next()
self.pool = numpy.append(self.pool,
self.fetch(self.cur), axis=0)
| python | {
"resource": ""
} |
q261165 | pufunc.call | validation | def call(self, args, axis=0, out=None, chunksize=1024 * 1024, **kwargs):
""" axis is the axis to chop it off.
if self.altreduce is set, the results will
be reduced with altreduce and returned
otherwise will be saved to out, then return out.
"""
if self.altreduce is not None:
ret = [None]
else:
if out is None :
if self.outdtype is not None:
dtype = self.outdtype
else:
try:
dtype = numpy.result_type(*[args[i] for i in self.ins] * 2)
except:
dtype = None
out = sharedmem.empty(
numpy.broadcast(*[args[i] for i in self.ins] * 2).shape,
dtype=dtype)
if axis != 0:
for i in self.ins:
args[i] = numpy.rollaxis(args[i], axis)
out = numpy.rollaxis(out, axis)
size = numpy.max([len(args[i]) for i in self.ins])
with sharedmem.MapReduce() as pool:
def work(i):
sl = slice(i, i+chunksize)
myargs = args[:]
for j in self.ins:
try:
tmp = myargs[j][sl]
a, b, c = sl.indices(len(args[j]))
myargs[j] = tmp
except Exception as e:
print tmp
| python | {
"resource": ""
} |
q261166 | packarray.adapt | validation | def adapt(cls, source, template):
""" adapt source to a packarray according to the layout of template """ | python | {
"resource": ""
} |
q261167 | argsort | validation | def argsort(data, out=None, chunksize=None,
baseargsort=None,
argmerge=None, np=None):
"""
parallel argsort, like numpy.argsort
use sizeof(intp) * len(data) as scratch space
use baseargsort for serial sort
ind = baseargsort(data)
use argmerge to merge
def argmerge(data, A, B, out):
ensure data[out] is sorted
and out[:] = A join B
TODO: shall try to use the inplace merge mentioned in
http://keithschwarz.com/interesting/code/?dir=inplace-merge.
"""
if baseargsort is None:
baseargsort = lambda x:x.argsort()
if argmerge is None:
argmerge = default_argmerge
if chunksize is None:
chunksize = 1024 * 1024 * 16
if out is None:
arg1 = numpy.empty(len(data), dtype='intp')
out = arg1
else:
assert out.dtype == numpy.dtype('intp')
assert len(out) == len(data)
arg1 = out
if np is None:
np = sharedmem.cpu_count()
if np <= 1 or len(data) < chunksize:
out[:] = baseargsort(data)
return out
CHK = [slice(i, i + chunksize) for i in range(0, len(data), chunksize)]
DUMMY = slice(len(data), len(data))
if len(CHK) % 2: CHK.append(DUMMY)
with sharedmem.TPool() as pool:
def work(i):
C = CHK[i]
start, stop, step = C.indices(len(data))
| python | {
"resource": ""
} |
q261168 | year | validation | def year(past=False, min_delta=0, max_delta=20):
"""Return | python | {
"resource": ""
} |
q261169 | date | validation | def date(past=False, min_delta=0, max_delta=20):
"""Return a random `dt.date` object. Delta args are days."""
timedelta | python | {
"resource": ""
} |
q261170 | check_digit | validation | def check_digit(num):
"""Return a check digit of the given credit card number.
Check digit calculated using Luhn algorithm ("modulus 10")
See: http://www.darkcoding.net/credit-card/luhn-formula/
"""
sum = 0
# drop last digit, then reverse the number
| python | {
"resource": ""
} |
q261171 | number | validation | def number(type=None, length=None, prefixes=None):
"""
Return a random credit card number.
:param type: credit card type. Defaults to a random selection.
:param length: length of the credit card number.
Defaults to the length for the selected card type.
:param prefixes: allowed prefixes for the card number.
Defaults to prefixes for the selected card type.
:return: credit card randomly generated number (int)
"""
# select credit card type
if type and type in CARDS:
card = type
else:
card = random.choice(list(CARDS.keys()))
# select a credit card number's prefix
if not prefixes:
| python | {
"resource": ""
} |
q261172 | street_number | validation | def street_number():
"""Return a random street number."""
length = int(random.choice(string.digits[1:6]))
| python | {
"resource": ""
} |
q261173 | job_title | validation | def job_title():
"""Return a random job title."""
result = random.choice(get_dictionary('job_titles')).strip()
| python | {
"resource": ""
} |
q261174 | body | validation | def body(quantity=2, separator='\n\n', wrap_start='', wrap_end='',
html=False, sentences_quantity=3, as_list=False):
"""Return a random email text."""
return lorem_ipsum.paragraphs(quantity=quantity, separator=separator,
wrap_start=wrap_start, | python | {
"resource": ""
} |
q261175 | money | validation | def money(min=0, max=10):
"""Return a str of decimal with two digits after a decimal mark."""
value = | python | {
"resource": ""
} |
q261176 | words | validation | def words(quantity=10, as_list=False):
"""Return random words."""
global _words
if not _words:
_words = ' '.join(get_dictionary('lorem_ipsum')).lower().\
replace('\n', '')
_words = re.sub(r'\.|,|;/', '', _words)
_words | python | {
"resource": ""
} |
q261177 | sentences | validation | def sentences(quantity=2, as_list=False):
"""Return random sentences."""
result = [sntc.strip() for sntc in
random.sample(get_dictionary('lorem_ipsum'), quantity)] | python | {
"resource": ""
} |
q261178 | paragraph | validation | def paragraph(separator='\n\n', wrap_start='', wrap_end='',
html=False, sentences_quantity=3):
"""Return a random paragraph."""
return paragraphs(quantity=1, separator=separator, wrap_start=wrap_start,
| python | {
"resource": ""
} |
q261179 | paragraphs | validation | def paragraphs(quantity=2, separator='\n\n', wrap_start='', wrap_end='',
html=False, sentences_quantity=3, as_list=False):
"""Return random paragraphs."""
if html:
wrap_start = '<p>'
wrap_end = '</p>'
separator = '\n\n'
result = []
try:
for _ in xrange(0, quantity):
result.append(wrap_start +
sentences(sentences_quantity) +
wrap_end)
| python | {
"resource": ""
} |
q261180 | _to_lower_alpha_only | validation | def _to_lower_alpha_only(s):
"""Return a lowercased string with non alphabetic chars removed.
White spaces are not to be removed."""
s | python | {
"resource": ""
} |
q261181 | characters | validation | def characters(quantity=10):
"""Return random characters."""
line = map(_to_lower_alpha_only,
| python | {
"resource": ""
} |
q261182 | text | validation | def text(what="sentence", *args, **kwargs):
"""An aggregator for all above defined public methods."""
if what == "character":
return character(*args, **kwargs)
elif what == "characters":
return characters(*args, **kwargs)
elif what == "word":
return word(*args, **kwargs)
| python | {
"resource": ""
} |
q261183 | user_name | validation | def user_name(with_num=False):
"""Return a random user name.
Basically it's lowercased result of
:py:func:`~forgery_py.forgery.name.first_name()` with a number appended
if `with_num`.
"""
| python | {
"resource": ""
} |
q261184 | domain_name | validation | def domain_name():
"""Return a random domain name.
Lowercased result of :py:func:`~forgery_py.forgery.name.company_name()`
| python | {
"resource": ""
} |
q261185 | email_address | validation | def email_address(user=None):
"""Return random e-mail address in a hopefully imaginary domain.
If `user` is ``None`` :py:func:`~user_name()` will be used. Otherwise it
will be lowercased and will have spaces replaced with ``_``.
Domain name is created | python | {
"resource": ""
} |
q261186 | account_number | validation | def account_number():
"""Return a random bank account number."""
account = [random.randint(1, 9) for | python | {
"resource": ""
} |
q261187 | bik | validation | def bik():
"""Return a random bank identification number."""
return '04' + | python | {
"resource": ""
} |
q261188 | legal_inn | validation | def legal_inn():
"""Return a random taxation ID number for a company."""
mask = [2, 4, 10, 3, 5, 9, 4, 6, 8]
inn = [random.randint(1, 9) for _ in range(10)]
weighted = [v * mask[i] for | python | {
"resource": ""
} |
q261189 | legal_ogrn | validation | def legal_ogrn():
"""Return a random government registration ID for a company."""
ogrn = "".join(map(str, [random.randint(1, 9) | python | {
"resource": ""
} |
q261190 | person_inn | validation | def person_inn():
"""Return a random taxation ID number for a natural person."""
mask11 = [7, 2, 4, 10, 3, 5, 9, 4, 6, 8]
mask12 = [3, 7, 2, 4, 10, 3, 5, 9, 4, 6, 8]
inn = [random.randint(1, 9) for _ in range(12)]
# get the 11th digit of the INN
weighted11 = [v * mask11[i] for i, v in enumerate(inn[:-2])]
inn[10] = sum(weighted11) % 11 | python | {
"resource": ""
} |
q261191 | password | validation | def password(at_least=6, at_most=12, lowercase=True,
uppercase=True, digits=True, spaces=False, punctuation=False):
"""Return a random string for use as a password."""
| python | {
"resource": ""
} |
q261192 | read_stream | validation | def read_stream(schema, stream, *, buffer_size=io.DEFAULT_BUFFER_SIZE):
"""Using a schema, deserialize a stream of consecutive Avro values.
:param str schema: json string representing the Avro schema
:param file-like stream: a buffered stream of binary input
:param int buffer_size: size of bytes to read from the stream each time
:return: yields a sequence of python data structures deserialized
from the stream
"""
reader = _lancaster.Reader(schema)
buf = stream.read(buffer_size)
remainder = b''
while len(buf) > 0:
values, n = reader.read_seq(buf)
yield from values
| python | {
"resource": ""
} |
q261193 | is_valid_url | validation | def is_valid_url(url):
"""
Check if a given string is in the correct URL format or not
:param str url:
:return: True or False
"""
regex = re.compile(r'^(?:http|ftp)s?://'
r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|'
| python | {
"resource": ""
} |
q261194 | download_file | validation | def download_file(url):
"""
Download a file pointed to by url to a temp file on local disk
:param str url:
:return: local_file
"""
try:
(local_file, headers) = urllib.urlretrieve(url)
except:
| python | {
"resource": ""
} |
q261195 | get_run_time_period | validation | def get_run_time_period(run_steps):
"""
This method finds the time range which covers all the Run_Steps
:param run_steps: list of Run_Step objects
:return: tuple of start and end timestamps
"""
init_ts_start = get_standardized_timestamp('now', None)
ts_start = init_ts_start
ts_end = '0'
for run_step in run_steps:
if run_step.ts_start and run_step.ts_end:
if run_step.ts_start < ts_start:
ts_start = | python | {
"resource": ""
} |
q261196 | extract_diff_sla_from_config_file | validation | def extract_diff_sla_from_config_file(obj, options_file):
"""
Helper function to parse diff config file, which contains SLA rules for diff comparisons
"""
rule_strings = {}
config_obj = ConfigParser.ConfigParser()
config_obj.optionxform = str
config_obj.read(options_file)
for section in config_obj.sections():
| python | {
"resource": ""
} |
q261197 | calculate_stats | validation | def calculate_stats(data_list, stats_to_calculate=['mean', 'std'], percentiles_to_calculate=[]):
"""
Calculate statistics for given data.
:param list data_list: List of floats
:param list stats_to_calculate: List of strings with statistics to calculate. Supported stats are defined in constant stats_to_numpy_method_map
:param list percentiles_to_calculate: List of floats that defined which percentiles to calculate.
:return: tuple of dictionaries containing calculated statistics and percentiles
"""
stats_to_numpy_method_map = {
'mean': numpy.mean,
'avg': numpy.mean,
'std': numpy.std,
'standard_deviation': numpy.std,
'median': numpy.median,
'min': numpy.amin,
'max': numpy.amax
}
calculated_stats = {}
calculated_percentiles = {}
if len(data_list) == 0:
return calculated_stats, calculated_percentiles
for stat in stats_to_calculate: | python | {
"resource": ""
} |
q261198 | is_valid_file | validation | def is_valid_file(filename):
"""
Check if the specifed file exists and is not empty
:param filename: full path to the file that needs to be checked
:return: Status, Message
"""
if os.path.exists(filename):
if not os.path.getsize(filename):
| python | {
"resource": ""
} |
q261199 | detect_timestamp_format | validation | def detect_timestamp_format(timestamp):
"""
Given an input timestamp string, determine what format is it likely in.
:param string timestamp: the timestamp string for which we need to determine format
:return: best guess timestamp format
"""
time_formats = {
'epoch': re.compile(r'^[0-9]{10}$'),
'epoch_ms': re.compile(r'^[0-9]{13}$'),
'epoch_fraction': re.compile(r'^[0-9]{10}\.[0-9]{3,9}$'),
'%Y-%m-%d %H:%M:%S': re.compile(r'^[0-9]{4}-[0-1][0-9]-[0-3][0-9] [0-2][0-9]:[0-5][0-9]:[0-5][0-9]$'),
'%Y-%m-%dT%H:%M:%S': re.compile(r'^[0-9]{4}-[0-1][0-9]-[0-3][0-9]T[0-2][0-9]:[0-5][0-9]:[0-5][0-9]$'),
'%Y-%m-%d_%H:%M:%S': re.compile(r'^[0-9]{4}-[0-1][0-9]-[0-3][0-9]_[0-2][0-9]:[0-5][0-9]:[0-5][0-9]$'),
'%Y-%m-%d %H:%M:%S.%f': re.compile(r'^[0-9]{4}-[0-1][0-9]-[0-3][0-9] [0-2][0-9]:[0-5][0-9]:[0-5][0-9].[0-9]+$'),
'%Y-%m-%dT%H:%M:%S.%f': re.compile(r'^[0-9]{4}-[0-1][0-9]-[0-3][0-9]T[0-2][0-9]:[0-5][0-9]:[0-5][0-9].[0-9]+$'),
'%Y-%m-%d_%H:%M:%S.%f': re.compile(r'^[0-9]{4}-[0-1][0-9]-[0-3][0-9]_[0-2][0-9]:[0-5][0-9]:[0-5][0-9].[0-9]+$'),
'%Y%m%d %H:%M:%S': re.compile(r'^[0-9]{4}[0-1][0-9][0-3][0-9] [0-2][0-9]:[0-5][0-9]:[0-5][0-9]$'),
'%Y%m%dT%H:%M:%S': re.compile(r'^[0-9]{4}[0-1][0-9][0-3][0-9]T[0-2][0-9]:[0-5][0-9]:[0-5][0-9]$'),
'%Y%m%d_%H:%M:%S': | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.