_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 31 13.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q265600 | DescriptorPool.FindEnumTypeByName | validation | def FindEnumTypeByName(self, full_name):
"""Loads the named enum descriptor from the pool.
Args:
full_name: The full name of the enum descriptor to load.
Returns:
| python | {
"resource": ""
} |
q265601 | DescriptorPool.FindExtensionByName | validation | def FindExtensionByName(self, full_name):
"""Loads the named extension descriptor from the pool.
Args:
full_name: The full name of the extension descriptor to load.
Returns:
A FieldDescriptor, describing the named extension.
"""
full_name = _NormalizeFullyQualifiedName(full_name)
message_name, _, extension_name = full_name.rpartition('.')
try:
# Most extensions are nested inside a message.
| python | {
"resource": ""
} |
q265602 | DescriptorPool._ConvertEnumDescriptor | validation | def _ConvertEnumDescriptor(self, enum_proto, package=None, file_desc=None,
containing_type=None, scope=None):
"""Make a protobuf EnumDescriptor given an EnumDescriptorProto protobuf.
Args:
enum_proto: The descriptor_pb2.EnumDescriptorProto protobuf message.
package: Optional package name for the new message EnumDescriptor.
file_desc: The file containing the enum descriptor.
containing_type: The type containing this enum.
scope: Scope containing available types.
Returns:
The added descriptor
"""
| python | {
"resource": ""
} |
q265603 | DescriptorPool._MakeFieldDescriptor | validation | def _MakeFieldDescriptor(self, field_proto, message_name, index,
is_extension=False):
"""Creates a field descriptor from a FieldDescriptorProto.
For message and enum type fields, this method will do a look up
in the pool for the appropriate descriptor for that type. If it
is unavailable, it will fall back to the _source function to
create it. If this type is still unavailable, construction will
fail.
Args:
field_proto: The proto describing the field.
message_name: The name of the containing message.
index: Index of the field
is_extension: Indication that this field is for an extension.
Returns:
An initialized FieldDescriptor object
"""
if message_name:
full_name = '.'.join((message_name, field_proto.name))
| python | {
"resource": ""
} |
q265604 | get_tm_session | validation | def get_tm_session(session_factory, transaction_manager):
"""
Get a ``sqlalchemy.orm.Session`` instance backed by a transaction.
This function will hook the session to the transaction manager which
will take care of committing any changes.
- When using pyramid_tm it will automatically be committed or aborted
depending on whether an exception is raised.
- When using scripts you should wrap the session in a manager yourself.
For example::
import transaction
engine = get_engine(settings)
session_factory = get_session_factory(engine)
| python | {
"resource": ""
} |
q265605 | generate | validation | def generate(length=DEFAULT_LENGTH):
"""
Generate a random string of the specified length.
The returned string is composed of an alphabet that shouldn't include any
characters that are easily mistakeable for one another (I, 1, O, 0), and
| python | {
"resource": ""
} |
q265606 | require | validation | def require(name, field, data_type):
"""Require that the named `field` has the right `data_type`"""
if not isinstance(field, data_type):
msg = | python | {
"resource": ""
} |
q265607 | Client.flush | validation | def flush(self):
"""Forces a flush from the internal queue to the server"""
queue = self.queue
size = queue.qsize()
| python | {
"resource": ""
} |
q265608 | open | validation | def open(name=None, fileobj=None, closefd=True):
"""
Use all decompressor possible | python | {
"resource": ""
} |
q265609 | marv | validation | def marv(ctx, config, loglevel, logfilter, verbosity):
"""Manage a Marv site"""
if config is None:
cwd = os.path.abspath(os.path.curdir)
while cwd != os.path.sep:
config = os.path.join(cwd, 'marv.conf')
| python | {
"resource": ""
} |
q265610 | MessageSetItemDecoder | validation | def MessageSetItemDecoder(extensions_by_number):
"""Returns a decoder for a MessageSet item.
The parameter is the _extensions_by_number map for the message class.
The message set message looks like this:
message MessageSet {
repeated group Item = 1 {
required int32 type_id = 2;
required string message = 3;
}
}
"""
type_id_tag_bytes = encoder.TagBytes(2, wire_format.WIRETYPE_VARINT)
message_tag_bytes = encoder.TagBytes(3, wire_format.WIRETYPE_LENGTH_DELIMITED)
item_end_tag_bytes = encoder.TagBytes(1, wire_format.WIRETYPE_END_GROUP)
local_ReadTag = ReadTag
local_DecodeVarint = _DecodeVarint
local_SkipField = SkipField
def DecodeItem(buffer, pos, end, message, field_dict):
message_set_item_start = pos
type_id = -1
message_start = -1
message_end = -1
# Technically, type_id and message can appear in any order, so we need
# a little loop here.
while 1:
(tag_bytes, pos) = local_ReadTag(buffer, pos)
if tag_bytes == type_id_tag_bytes:
(type_id, pos) = local_DecodeVarint(buffer, pos)
elif tag_bytes == message_tag_bytes:
(size, message_start) = local_DecodeVarint(buffer, pos)
pos = message_end = message_start + size
elif tag_bytes == item_end_tag_bytes:
break
else:
pos = SkipField(buffer, pos, end, tag_bytes)
if pos == -1:
raise _DecodeError('Missing group end tag.')
if pos > end:
raise _DecodeError('Truncated | python | {
"resource": ""
} |
q265611 | get_app_name | validation | def get_app_name():
"""Flask like implementation of getting the applicaiton name via
the filename of the including file
"""
fn = getattr(sys.modules['__main__'], '__file__', None)
| python | {
"resource": ""
} |
q265612 | get_function | validation | def get_function(function_name):
"""
Given a Python function name, return the function it refers to.
"""
module, basename = str(function_name).rsplit('.', 1)
try:
return getattr(__import__(module, | python | {
"resource": ""
} |
q265613 | ViewServerRequestHandler.handle_add_fun | validation | def handle_add_fun(self, function_name):
"""Add a function to the function list, in order."""
function_name = function_name.strip()
try:
function = get_function(function_name)
except Exception, exc:
self.wfile.write(js_error(exc) + NEWLINE)
return
# This tests to see if the function has been decorated with the view
# server synchronisation decorator (``decorate_view``).
if not getattr(function, | python | {
"resource": ""
} |
q265614 | ViewServerRequestHandler.handle_map_doc | validation | def handle_map_doc(self, document):
"""Return the mapping of a document according to the function list."""
# This uses the stored set of functions, sorted by order of addition.
for function in sorted(self.functions.values(), key=lambda x: x[0]):
try:
# It has to be run through ``list``, because it may be a
# generator function.
| python | {
"resource": ""
} |
q265615 | ViewServerRequestHandler.handle_reduce | validation | def handle_reduce(self, reduce_function_names, mapped_docs):
"""Reduce several mapped documents by several reduction functions."""
reduce_functions = []
# This gets a large list of reduction functions, given their names.
for reduce_function_name in reduce_function_names:
try:
reduce_function = get_function(reduce_function_name)
if getattr(reduce_function, 'view_decorated', None):
reduce_function = reduce_function(self.log)
reduce_functions.append(reduce_function)
except Exception, exc:
self.log(repr(exc))
reduce_functions.append(lambda *args, **kwargs: None)
| python | {
"resource": ""
} |
q265616 | ViewServerRequestHandler.handle_rereduce | validation | def handle_rereduce(self, reduce_function_names, values):
"""Re-reduce a set of values, with a list of rereduction functions."""
# This gets a large list of reduction functions, given their names.
reduce_functions = []
for reduce_function_name in reduce_function_names:
try:
reduce_function = get_function(reduce_function_name)
if getattr(reduce_function, 'view_decorated', None):
reduce_function = reduce_function(self.log)
reduce_functions.append(reduce_function)
except Exception, exc:
self.log(repr(exc)) | python | {
"resource": ""
} |
q265617 | ViewServerRequestHandler.handle_validate | validation | def handle_validate(self, function_name, new_doc, old_doc, user_ctx):
"""Validate...this function is undocumented, but still in CouchDB."""
try:
function = get_function(function_name)
except Exception, exc:
self.log(repr(exc))
| python | {
"resource": ""
} |
q265618 | ViewServerRequestHandler.handle | validation | def handle(self):
"""The main function called to handle a request."""
while True:
try:
line = self.rfile.readline()
try:
# All input data are lines of JSON like the following:
# ["<cmd_name>" "<cmd_arg1>" "<cmd_arg2>" ...]
# So I handle this by dispatching to various methods.
cmd = json.loads(line)
except Exception, exc:
# Sometimes errors come up. Once again, I can't predict
# anything, but can at least tell CouchDB about the error.
self.wfile.write(repr(exc) + NEWLINE)
continue
else:
# Automagically get the command handler.
handler = getattr(self, 'handle_' + cmd[0], None)
if not handler:
| python | {
"resource": ""
} |
q265619 | ViewServerRequestHandler.log | validation | def log(self, string):
"""Log an event on the CouchDB server."""
| python | {
"resource": ""
} |
q265620 | guid | validation | def guid(*args):
"""
Generates a universally unique ID.
Any arguments only create more randomness.
"""
t = float(time.time() * 1000)
r = float(random.random()*10000000000000)
a = random.random() * 10000000000000
| python | {
"resource": ""
} |
q265621 | AsyncProauth2.revoke_token | validation | def revoke_token(self, token, callback):
'''
revoke_token removes the access token from the data_store
'''
| python | {
"resource": ""
} |
q265622 | AsyncProauth2._auth | validation | def _auth(self, client_id, key, method, callback):
'''
_auth - internal method to ensure the client_id and client_secret passed with
the nonce match
'''
available = auth_methods.keys()
if method not in available:
raise Proauth2Error('invalid_request',
'unsupported authentication method: %s'
'available methods: %s' % \
| python | {
"resource": ""
} |
q265623 | AsyncProauth2._validate_request_code | validation | def _validate_request_code(self, code, client_id, callback):
'''
_validate_request_code - internal method for verifying the the given nonce.
also removes the nonce from the data_store, as they are intended for
one-time use.
'''
nonce = yield Task(self.data_store.fetch, 'nonce_codes', code=code)
if not nonce:
raise Proauth2Error('access_denied', 'invalid request code: %s' % code)
if client_id != nonce['client_id']:
raise Proauth2Error('access_denied', 'invalid request code: %s' % code)
user_id = nonce['user_id']
expires | python | {
"resource": ""
} |
q265624 | AsyncProauth2._generate_token | validation | def _generate_token(self, length=32):
'''
_generate_token - internal function for generating randomized alphanumberic
strings of a given length
| python | {
"resource": ""
} |
q265625 | merge_ordered | validation | def merge_ordered(ordereds: typing.Iterable[typing.Any]) -> typing.Iterable[typing.Any]:
"""Merge multiple ordered so that within-ordered order is preserved
"""
seen_set = set()
add_seen = seen_set.add
return reversed(tuple(map(
lambda obj: add_seen(obj) or obj,
| python | {
"resource": ""
} |
q265626 | validate_params | validation | def validate_params(required, optional, params):
"""
Helps us validate the parameters for the request
:param valid_options: a list of strings of valid options for the
api request
:param params: a dict, the key-value store which we really only care about
the key which has tells us what the user is using for the
API request
:returns: None or throws an exception if the validation fails
"""
missing_fields = [x for x in required if x not in params]
if missing_fields:
| python | {
"resource": ""
} |
q265627 | FileAge.__get_current_datetime | validation | def __get_current_datetime(self):
"""Get current datetime for every file."""
self.wql_time = "SELECT LocalDateTime FROM Win32_OperatingSystem"
self.current_time = self.query(self.wql_time)
# [{'LocalDateTime': '20160824161431.977000+480'}]'
self.current_time_string = str(
self.current_time[0].get('LocalDateTime').split('.')[0])
# '20160824161431'
| python | {
"resource": ""
} |
q265628 | BranchThread.run | validation | def run(self):
"""run your main spider here
as for branch spider result data, you can return everything or do whatever with it
in your own code
:return: None
"""
config = config_creator()
debug = config.debug
branch_thread_sleep = config.branch_thread_sleep
while 1:
url = self.branch_queue.get()
if debug:
print('branch thread-{} start'.format(url))
branch_spider = | python | {
"resource": ""
} |
q265629 | get_version | validation | def get_version(relpath):
"""Read version info from a file without importing it"""
from os.path import dirname, join
if '__file__' not in globals():
# Allow to use function interactively
root = '.'
else:
root = dirname(__file__)
# The code below reads text file with unknown encoding in
# in Python2/3 compatible way. Reading this text file
# without specifying encoding will fail in Python 3 on some
# systems (see http://goo.gl/5XmOH). Specifying encoding as
# open() parameter is incompatible with Python 2
| python | {
"resource": ""
} |
q265630 | MakeDescriptor | validation | def MakeDescriptor(desc_proto, package='', build_file_if_cpp=True,
syntax=None):
"""Make a protobuf Descriptor given a DescriptorProto protobuf.
Handles nested descriptors. Note that this is limited to the scope of defining
a message inside of another message. Composite fields can currently only be
resolved if the message is defined in the same scope as the field.
Args:
desc_proto: The descriptor_pb2.DescriptorProto protobuf message.
package: Optional package name for the new message Descriptor (string).
build_file_if_cpp: Update the C++ descriptor pool if api matches.
Set to False on recursion, so no duplicates are created.
syntax: The syntax/semantics that should be used. Set to "proto3" to get
proto3 field presence semantics.
Returns:
A Descriptor for protobuf messages.
"""
if api_implementation.Type() == 'cpp' and build_file_if_cpp:
# The C++ implementation requires all descriptors to be backed by the same
# definition in the C++ descriptor pool. To do this, we build a
# FileDescriptorProto with the same definition as this descriptor and build
# it into the pool.
from typy.google.protobuf import descriptor_pb2
file_descriptor_proto = descriptor_pb2.FileDescriptorProto()
file_descriptor_proto.message_type.add().MergeFrom(desc_proto)
# Generate a random name for this proto file to prevent conflicts with any
# imported ones. We need to specify a file name so the descriptor pool
# accepts our FileDescriptorProto, but it is not important what that file
# name is actually set to.
proto_name = str(uuid.uuid4())
if package:
file_descriptor_proto.name = os.path.join(package.replace('.', '/'),
proto_name + '.proto')
file_descriptor_proto.package = package
else:
file_descriptor_proto.name = proto_name + '.proto'
_message.default_pool.Add(file_descriptor_proto)
result = _message.default_pool.FindFileByName(file_descriptor_proto.name)
if _USE_C_DESCRIPTORS:
return result.message_types_by_name[desc_proto.name]
full_message_name = [desc_proto.name]
if package: full_message_name.insert(0, package)
# Create Descriptors for enum types
enum_types = {}
for enum_proto in desc_proto.enum_type:
full_name = '.'.join(full_message_name + [enum_proto.name])
enum_desc = EnumDescriptor(
enum_proto.name, full_name, None, [
EnumValueDescriptor(enum_val.name, ii, enum_val.number)
for ii, enum_val in enumerate(enum_proto.value)])
enum_types[full_name] = enum_desc
# Create Descriptors for nested types
nested_types = {}
for nested_proto in desc_proto.nested_type:
full_name = '.'.join(full_message_name + [nested_proto.name])
# Nested types are just those defined inside of the message, not all types
# used by fields in the message, so no loops are possible here.
nested_desc = MakeDescriptor(nested_proto,
package='.'.join(full_message_name),
| python | {
"resource": ""
} |
q265631 | _NestedDescriptorBase.GetTopLevelContainingType | validation | def GetTopLevelContainingType(self):
"""Returns the root if this is a nested type, or itself if | python | {
"resource": ""
} |
q265632 | ServiceDescriptor.FindMethodByName | validation | def FindMethodByName(self, name):
"""Searches for the specified method, and returns its | python | {
"resource": ""
} |
q265633 | MessageToJson | validation | def MessageToJson(message, including_default_value_fields=False):
"""Converts protobuf message to JSON format.
Args:
message: The protocol buffers message instance to serialize.
including_default_value_fields: If True, singular primitive fields,
repeated fields, and map fields will always be serialized. If
False, only serialize non-empty fields. Singular message fields
| python | {
"resource": ""
} |
q265634 | _MessageToJsonObject | validation | def _MessageToJsonObject(message, including_default_value_fields):
"""Converts message to an object according to Proto3 JSON Specification."""
message_descriptor = message.DESCRIPTOR
full_name = message_descriptor.full_name
if _IsWrapperMessage(message_descriptor):
return _WrapperMessageToJsonObject(message)
if full_name in _WKTJSONMETHODS:
| python | {
"resource": ""
} |
q265635 | _StructMessageToJsonObject | validation | def _StructMessageToJsonObject(message, unused_including_default=False):
"""Converts Struct message according to | python | {
"resource": ""
} |
q265636 | Parse | validation | def Parse(text, message):
"""Parses a JSON representation of a protocol message into a message.
Args:
text: Message JSON representation.
message: A protocol beffer message to merge into.
Returns:
The same message passed as argument.
Raises::
ParseError: On JSON parsing problems.
"""
if not isinstance(text, six.text_type): text = text.decode('utf-8')
try:
if sys.version_info < (2, 7):
# object_pair_hook is not supported | python | {
"resource": ""
} |
q265637 | _ConvertFieldValuePair | validation | def _ConvertFieldValuePair(js, message):
"""Convert field value pairs into regular message.
Args:
js: A JSON object to convert the field value pairs.
message: A regular protocol message to record the data.
Raises:
ParseError: In case of problems converting.
"""
names = []
message_descriptor = message.DESCRIPTOR
for name in js:
try:
field = message_descriptor.fields_by_camelcase_name.get(name, None)
if not field:
raise ParseError(
'Message type "{0}" has no field named "{1}".'.format(
message_descriptor.full_name, name))
if name in names:
raise ParseError(
'Message type "{0}" should not have multiple "{1}" fields.'.format(
message.DESCRIPTOR.full_name, name))
names.append(name)
# Check no other oneof field is parsed.
if field.containing_oneof is not None:
oneof_name = field.containing_oneof.name
if oneof_name in names:
raise ParseError('Message type "{0}" should not have multiple "{1}" '
'oneof fields.'.format(
message.DESCRIPTOR.full_name, oneof_name))
names.append(oneof_name)
value = js[name]
if value is None:
message.ClearField(field.name)
continue
# Parse field value.
if _IsMapEntry(field):
message.ClearField(field.name)
_ConvertMapFieldValue(value, message, field)
elif field.label == descriptor.FieldDescriptor.LABEL_REPEATED:
message.ClearField(field.name)
if not isinstance(value, list):
raise ParseError('repeated field {0} must be in [] which is '
'{1}.'.format(name, value))
if field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_MESSAGE:
# Repeated message field.
for item in value:
sub_message = getattr(message, field.name).add()
# None is a null_value in Value.
if (item is None and
sub_message.DESCRIPTOR.full_name != 'google.protobuf.Value'):
raise ParseError('null is not allowed to be used as an element'
' in | python | {
"resource": ""
} |
q265638 | _ConvertMessage | validation | def _ConvertMessage(value, message):
"""Convert a JSON object into a message.
Args:
value: A JSON object.
message: A WKT or regular protocol message to record the data.
Raises:
ParseError: In case of convert problems.
"""
message_descriptor = message.DESCRIPTOR
full_name = message_descriptor.full_name
if _IsWrapperMessage(message_descriptor): | python | {
"resource": ""
} |
q265639 | _ConvertValueMessage | validation | def _ConvertValueMessage(value, message):
"""Convert a JSON representation into Value message."""
if isinstance(value, dict):
_ConvertStructMessage(value, message.struct_value)
elif isinstance(value, list):
_ConvertListValueMessage(value, message.list_value)
elif value is None:
message.null_value = 0
elif isinstance(value, | python | {
"resource": ""
} |
q265640 | _ConvertListValueMessage | validation | def _ConvertListValueMessage(value, message):
"""Convert a JSON representation into ListValue message."""
if not isinstance(value, list):
raise ParseError(
'ListValue must be | python | {
"resource": ""
} |
q265641 | _ConvertStructMessage | validation | def _ConvertStructMessage(value, message):
"""Convert a JSON representation into Struct message."""
if not isinstance(value, dict):
raise ParseError(
'Struct must be | python | {
"resource": ""
} |
q265642 | update_config | validation | def update_config(new_config):
""" Update config options with the provided dictionary of options.
"""
flask_app.base_config.update(new_config)
# Check for changed working directory.
if new_config.has_key('working_directory'):
wd = os.path.abspath(new_config['working_directory'])
| python | {
"resource": ""
} |
q265643 | Timing.end_timing | validation | def end_timing(self):
"""
Completes measuring time interval and updates counter.
"""
if self._callback != None:
| python | {
"resource": ""
} |
q265644 | Duration.ToJsonString | validation | def ToJsonString(self):
"""Converts Duration to string format.
Returns:
A string converted from self. The string format will contains
3, 6, or 9 fractional digits depending on the precision required to
represent the exact Duration value. For example: "1s", "1.010s",
"1.000000100s", "-3.100s"
"""
if self.seconds < 0 or self.nanos < 0:
result = '-'
seconds = - self.seconds + int((0 - self.nanos) // 1e9)
nanos = (0 - self.nanos) % 1e9
else:
result = ''
seconds = self.seconds + int(self.nanos // 1e9)
nanos = self.nanos % 1e9
result += '%d' % seconds
if (nanos % 1e9) == 0:
| python | {
"resource": ""
} |
q265645 | Duration.FromJsonString | validation | def FromJsonString(self, value):
"""Converts a string to Duration.
Args:
value: A string to be converted. The string must end with 's'. Any
fractional digits (or none) are accepted as long as they fit into
precision. For example: "1s", "1.01s", "1.0000001s", "-3.100s
Raises:
ParseError: On parsing problems.
"""
if len(value) < 1 or value[-1] != 's':
raise ParseError(
'Duration must end with letter "s": {0}.'.format(value))
try:
pos = value.find('.')
if pos == -1:
self.seconds = int(value[:-1])
self.nanos = | python | {
"resource": ""
} |
q265646 | FieldMask.FromJsonString | validation | def FromJsonString(self, value):
"""Converts string to FieldMask according to proto3 JSON spec."""
self.Clear() | python | {
"resource": ""
} |
q265647 | get_doc | validation | def get_doc(doc_id, db_name, server_url='http://127.0.0.1:5984/', rev=None):
"""Return a CouchDB document, given its ID, revision and database name."""
db = get_server(server_url)[db_name]
if rev:
| python | {
"resource": ""
} |
q265648 | read | validation | def read(readme):
"""Give reST format README for pypi."""
extend = os.path.splitext(readme)[1]
if (extend == '.rst'):
import codecs
| python | {
"resource": ""
} |
q265649 | DataStore.remove | validation | def remove(self, collection, **kwargs):
'''
remove records from collection whose parameters match kwargs
'''
| python | {
"resource": ""
} |
q265650 | TrelloAPI._url | validation | def _url(self):
"""
Resolve the URL to this point.
>>> trello = TrelloAPIV1('APIKEY')
>>> trello.batch._url
'1/batch'
>>> trello.boards(board_id='BOARD_ID')._url
'1/boards/BOARD_ID'
>>> trello.boards(board_id='BOARD_ID')(field='FIELD')._url
'1/boards/BOARD_ID/FIELD'
>>> trello.boards(board_id='BOARD_ID').cards(filter='FILTER')._url
'1/boards/BOARD_ID/cards/FILTER'
| python | {
"resource": ""
} |
q265651 | TrelloAPI._api_call | validation | def _api_call(self, method_name, *args, **kwargs):
"""
Makes the HTTP request.
"""
params = kwargs.setdefault('params', {})
params.update({'key': self._apikey})
if self._token is not None:
| python | {
"resource": ""
} |
q265652 | _SkipFieldValue | validation | def _SkipFieldValue(tokenizer):
"""Skips over a field value.
Args:
tokenizer: A tokenizer to parse the field name and values.
Raises:
ParseError: In case an invalid field value is found.
"""
# String/bytes tokens can come in multiple adjacent string literals.
# If we can consume one, consume as many as we can.
if tokenizer.TryConsumeByteString():
while tokenizer.TryConsumeByteString():
pass
return | python | {
"resource": ""
} |
q265653 | ParseInteger | validation | def ParseInteger(text, is_signed=False, is_long=False):
"""Parses an integer.
Args:
text: The text to parse.
is_signed: True if a signed integer must be parsed.
is_long: True if a long integer must be parsed.
Returns:
The integer value.
Raises:
ValueError: Thrown Iff the text is not a valid integer.
"""
# Do the actual parsing. Exception handling is propagated to caller. | python | {
"resource": ""
} |
q265654 | _Printer.PrintMessage | validation | def PrintMessage(self, message):
"""Convert protobuf message to text format.
Args:
message: The protocol buffers message.
"""
fields = message.ListFields()
if self.use_index_order:
fields.sort(key=lambda x: x[0].index)
for field, value in fields:
if _IsMapEntry(field):
for key in sorted(value):
# This is slow for maps with submessage entires because it copies the
# entire tree. Unfortunately this would take significant refactoring
# of this file to work around.
#
# TODO(haberman): refactor and optimize if this becomes an issue. | python | {
"resource": ""
} |
q265655 | _Parser._ParseOrMerge | validation | def _ParseOrMerge(self, lines, message):
"""Converts an text representation of a protocol message into a message.
Args:
lines: Lines of a message's text representation.
| python | {
"resource": ""
} |
q265656 | _Parser._MergeMessageField | validation | def _MergeMessageField(self, tokenizer, message, field):
"""Merges a single scalar field into a message.
Args:
tokenizer: A tokenizer to parse the field value.
message: The message of which field is a member.
field: The descriptor of the field to be merged.
Raises:
ParseError: In case of text parsing problems.
"""
is_map_entry = _IsMapEntry(field)
if tokenizer.TryConsume('<'):
end_token = '>'
else:
tokenizer.Consume('{')
end_token = '}'
if field.label == descriptor.FieldDescriptor.LABEL_REPEATED:
if field.is_extension:
sub_message = message.Extensions[field].add()
elif is_map_entry:
# pylint: disable=protected-access
sub_message = field.message_type._concrete_class()
else:
sub_message = getattr(message, field.name).add()
else:
if field.is_extension:
sub_message = message.Extensions[field] | python | {
"resource": ""
} |
q265657 | _Tokenizer.ConsumeIdentifier | validation | def ConsumeIdentifier(self):
"""Consumes protocol message field identifier.
Returns:
Identifier string.
Raises:
ParseError: If an identifier couldn't be consumed.
"""
result = self.token | python | {
"resource": ""
} |
q265658 | _Tokenizer.ConsumeInt32 | validation | def ConsumeInt32(self):
"""Consumes a signed 32bit integer number.
Returns:
The integer parsed.
Raises:
ParseError: If a signed 32bit integer couldn't be consumed.
"""
try:
| python | {
"resource": ""
} |
q265659 | _Tokenizer.ConsumeFloat | validation | def ConsumeFloat(self):
"""Consumes an floating point number.
Returns:
The number parsed.
Raises:
ParseError: If a floating point number couldn't be consumed.
"""
try:
| python | {
"resource": ""
} |
q265660 | _Tokenizer.ConsumeBool | validation | def ConsumeBool(self):
"""Consumes a boolean value.
Returns:
The bool parsed.
Raises:
ParseError: If a boolean value couldn't be consumed.
"""
try:
| python | {
"resource": ""
} |
q265661 | _Tokenizer._ConsumeSingleByteString | validation | def _ConsumeSingleByteString(self):
"""Consume one token of a string literal.
String literals (whether bytes or text) can come in multiple adjacent
tokens which are automatically concatenated, like in C or Python. This
method only consumes one token.
Returns:
The token parsed.
Raises:
ParseError: When the wrong format data is found.
"""
text = self.token
if len(text) < 1 or text[0] not in _QUOTES:
| python | {
"resource": ""
} |
q265662 | arkt_to_unixt | validation | def arkt_to_unixt(ark_timestamp):
""" convert ark timestamp to unix timestamp"""
res = datetime.datetime(2017, 3, 21, | python | {
"resource": ""
} |
q265663 | Mssql.close | validation | def close(self):
"""Close the connection."""
try:
self.conn.close()
self.logger.debug("Close connect succeed.")
| python | {
"resource": ""
} |
q265664 | Preprocessor.process_macros | validation | def process_macros(self, content: str) -> str:
'''Replace macros with content defined in the config.
:param content: Markdown content
:returns: Markdown content without macros
'''
def _sub(macro):
name = | python | {
"resource": ""
} |
q265665 | get_unique_pathname | validation | def get_unique_pathname(path, root=''):
"""Return a pathname possibly with a number appended to it so that it is
unique in the directory."""
path = os.path.join(root, path)
| python | {
"resource": ""
} |
q265666 | __get_numbered_paths | validation | def __get_numbered_paths(filepath):
"""Append numbers in sequential order to the filename or folder name
Numbers should be appended before the extension on a filename."""
| python | {
"resource": ""
} |
q265667 | splitext_files_only | validation | def splitext_files_only(filepath):
"Custom version of splitext that doesn't perform splitext on directories"
return (
(filepath, | python | {
"resource": ""
} |
q265668 | set_time | validation | def set_time(filename, mod_time):
"""
Set the modified time of a file
"""
log.debug('Setting modified time to %s', mod_time)
mtime = calendar.timegm(mod_time.utctimetuple())
# utctimetuple discards microseconds, so restore it (for | python | {
"resource": ""
} |
q265669 | get_time | validation | def get_time(filename):
"""
Get the modified time for a file as a datetime instance
"""
| python | {
"resource": ""
} |
q265670 | ensure_dir_exists | validation | def ensure_dir_exists(func):
"wrap a function that returns a dir, making sure it exists"
@functools.wraps(func)
def make_if_not_present():
dir = func()
| python | {
"resource": ""
} |
q265671 | is_hidden | validation | def is_hidden(path):
"""
Check whether a file is presumed hidden, either because
the pathname starts with dot or because the platform
indicates such.
"""
| python | {
"resource": ""
} |
q265672 | SerialReader.age | validation | def age(self):
"""
Get closer to your EOL
"""
# 0 means this composer will never decompose
if self.rounds == 1:
| python | {
"resource": ""
} |
q265673 | SerialReader.run | validation | def run(self):
"""
Open a connection over the serial line and receive data lines
"""
if not self.device:
return
try:
data = ""
while (self.do_run):
try:
if (self.device.inWaiting() > 1):
l = self.device.readline()[:-2]
l = l.decode("UTF-8")
if (l == "["):
# start recording
data = "["
elif (l == "]") and (len(data) > 4) and (data[0] == "["):
# now parse the input
data = data + "]"
self.store.register_json(data)
self.age()
elif (l[0:3] == " {"):
# this is a data line
data = data + " " + l
else:
# this is a slow interface - give it some time
| python | {
"resource": ""
} |
q265674 | ThreadCreator.append_main_thread | validation | def append_main_thread(self):
"""create & start main thread
:return: None
"""
thread = MainThread(main_queue=self.main_queue,
main_spider=self.main_spider,
| python | {
"resource": ""
} |
q265675 | getTextFromNode | validation | def getTextFromNode(node):
"""
Scans through all children of node and gathers the
text. If node has non-text child-nodes then
NotTextNodeError is raised.
"""
t = ""
for n in node.childNodes:
if n.nodeType | python | {
"resource": ""
} |
q265676 | AmbientSMS.getbalance | validation | def getbalance(self, url='http://services.ambientmobile.co.za/credits'):
"""
Get the number of credits remaining at AmbientSMS
"""
postXMLList = []
postXMLList.append("<api-key>%s</api-key>" % self.api_key)
postXMLList.append("<password>%s</password>" % self.password)
postXML = '<sms>%s</sms>' % "".join(postXMLList)
result = | python | {
"resource": ""
} |
q265677 | AmbientSMS.sendmsg | validation | def sendmsg(self,
message,
recipient_mobiles=[],
url='http://services.ambientmobile.co.za/sms',
concatenate_message=True,
message_id=str(time()).replace(".", ""),
reply_path=None,
allow_duplicates=True,
allow_invalid_numbers=True,
):
"""
Send a mesage via the AmbientSMS API server
"""
if not recipient_mobiles or not(isinstance(recipient_mobiles, list) \
or isinstance(recipient_mobiles, tuple)):
raise AmbientSMSError("Missing recipients")
if not message or not len(message):
raise AmbientSMSError("Missing message")
postXMLList = []
postXMLList.append("<api-key>%s</api-key>" % self.api_key)
| python | {
"resource": ""
} |
q265678 | AmbientSMS.curl | validation | def curl(self, url, post):
"""
Inteface for sending web requests to the AmbientSMS API Server
"""
try:
req = urllib2.Request(url)
req.add_header("Content-type", "application/xml")
| python | {
"resource": ""
} |
q265679 | DefaultMinifier.contents | validation | def contents(self, f, text):
"""
Called for each file
Must return file content
Can be wrapped
:type f: static_bundle.files.StaticFileResult
:type | python | {
"resource": ""
} |
q265680 | is_date_type | validation | def is_date_type(cls):
"""Return True if the class is a date type."""
if not | python | {
"resource": ""
} |
q265681 | to_datetime | validation | def to_datetime(when):
"""
Convert a date or time to a datetime. If when is a date then it sets the time to midnight. If
when is a time it sets the date to the epoch. If when is None or a datetime it returns when.
Otherwise a TypeError is raised. Returned datetimes have tzinfo set to None unless when is a
datetime with tzinfo set in which case it remains the same.
"""
if when is | python | {
"resource": ""
} |
q265682 | totz | validation | def totz(when, tz=None):
"""
Return a date, time, or datetime converted to a datetime in the given timezone. If when is a
datetime and has no timezone it is assumed to be local time. Date and time objects are also
assumed to be UTC. The tz value defaults to UTC. Raise TypeError if when cannot be converted to
a datetime.
"""
| python | {
"resource": ""
} |
q265683 | ts | validation | def ts(when, tz=None):
"""
Return a Unix timestamp in seconds for the provided datetime. The `totz` function is called
on the datetime to convert it to the provided timezone. It will be converted to UTC if no
| python | {
"resource": ""
} |
q265684 | tsms | validation | def tsms(when, tz=None):
"""
Return a Unix timestamp in milliseconds for the provided datetime. The `totz` function is
called on the datetime to convert it to the provided timezone. It will be converted to UTC if
no timezone is provided.
"""
if not when:
| python | {
"resource": ""
} |
q265685 | fromts | validation | def fromts(ts, tzin=None, tzout=None):
"""
Return the datetime representation of the provided Unix timestamp. By defaults the timestamp is
interpreted as UTC. If tzin is set it will be interpreted as this | python | {
"resource": ""
} |
q265686 | fromtsms | validation | def fromtsms(ts, tzin=None, tzout=None):
"""
Return the Unix timestamp in milliseconds as a datetime object. If tz is set it will be
converted to the requested timezone otherwise | python | {
"resource": ""
} |
q265687 | truncate | validation | def truncate(when, unit, week_start=mon):
"""Return the datetime truncated to the precision of the provided unit."""
if is_datetime(when):
if unit == millisecond:
return when.replace(microsecond=int(round(when.microsecond / 1000.0)) * 1000)
elif unit == second:
return when.replace(microsecond=0)
elif unit == minute:
return when.replace(second=0, microsecond=0)
elif unit == hour:
return when.replace(minute=0, second=0, microsecond=0)
elif unit == day:
return when.replace(hour=0, minute=0, second=0, microsecond=0)
elif unit == week:
weekday = prevweekday(when, week_start)
return when.replace(year=weekday.year, month=weekday.month, day=weekday.day,
hour=0, minute=0, second=0, microsecond=0)
elif unit == month:
return when.replace(day=1, hour=0, minute=0, second=0, microsecond=0)
elif unit == year:
return when.replace(month=1, day=1, hour=0, minute=0, second=0, microsecond=0)
elif is_date(when):
if unit == week:
| python | {
"resource": ""
} |
q265688 | weekday | validation | def weekday(when, weekday, start=mon):
"""Return the date for the day of this week."""
if isinstance(when, datetime):
when = when.date()
today = when.weekday()
delta = weekday - today
if weekday < start and today >= start:
| python | {
"resource": ""
} |
q265689 | _GetNativeEolStyle | validation | def _GetNativeEolStyle(platform=sys.platform):
'''
Internal function that determines EOL_STYLE_NATIVE constant with the proper value for the
current platform.
'''
_NATIVE_EOL_STYLE_MAP = {
'win32' : EOL_STYLE_WINDOWS,
'linux2' : EOL_STYLE_UNIX,
'linux' : EOL_STYLE_UNIX,
'darwin' : EOL_STYLE_MAC,
| python | {
"resource": ""
} |
q265690 | NormalizePath | validation | def NormalizePath(path):
'''
Normalizes a path maintaining the final slashes.
Some environment variables need the final slash in order to work.
Ex. The SOURCES_DIR set by subversion must end with a slash because of the way it is used
in the Visual Studio projects.
:param unicode path:
The path to normalize.
| python | {
"resource": ""
} |
q265691 | CanonicalPath | validation | def CanonicalPath(path):
'''
Returns a version of a path that is unique.
Given two paths path1 and path2:
CanonicalPath(path1) == CanonicalPath(path2) if and only if they represent the same file on
the host OS. Takes account of case, slashes and relative paths.
:param unicode path:
| python | {
"resource": ""
} |
q265692 | StandardizePath | validation | def StandardizePath(path, strip=False):
'''
Replaces all slashes and backslashes with the target separator
StandardPath:
We are defining that the standard-path is the one with only back-slashes in it, either
on Windows or any other platform.
:param bool strip:
If True, | python | {
"resource": ""
} |
q265693 | CopyFile | validation | def CopyFile(source_filename, target_filename, override=True, md5_check=False, copy_symlink=True):
'''
Copy a file from source to target.
:param source_filename:
@see _DoCopyFile
:param target_filename:
@see _DoCopyFile
:param bool md5_check:
If True, checks md5 files (of both source and target files), if they match, skip this copy
and return MD5_SKIP
Md5 files are assumed to be {source, target} + '.md5'
If any file is missing (source, target or md5), the copy will always be made.
:param copy_symlink:
@see _DoCopyFile
:raises FileAlreadyExistsError:
If target_filename already exists, and override is False
:raises NotImplementedProtocol:
If file protocol is not accepted
Protocols allowed are:
source_filename: local, ftp, http
target_filename: local, ftp
:rtype: None | MD5_SKIP
:returns:
MD5_SKIP if the file was not copied because there was a matching .md5 file
.. seealso:: FTP LIMITATIONS at this module's doc for performance issues information
'''
from ._exceptions import FileNotFoundError
# Check override
if not override and Exists(target_filename):
from ._exceptions import FileAlreadyExistsError
raise FileAlreadyExistsError(target_filename)
# Don't do md5 check for md5 files themselves.
md5_check = md5_check and not target_filename.endswith('.md5')
# If we enabled md5 checks, ignore copy of files that haven't changed their md5 contents.
if md5_check:
source_md5_filename = source_filename + '.md5'
target_md5_filename | python | {
"resource": ""
} |
q265694 | _CopyFileLocal | validation | def _CopyFileLocal(source_filename, target_filename, copy_symlink=True):
'''
Copy a file locally to a directory.
:param unicode source_filename:
The filename to copy from.
:param unicode target_filename:
The filename to copy to.
:param bool copy_symlink:
If True and source_filename is a symlink, target_filename will also be created as
a symlink.
If False, the file being linked will be copied instead.
'''
import shutil
try:
# >>> Create the target_filename directory if necessary
dir_name = os.path.dirname(target_filename)
if dir_name and not os.path.isdir(dir_name):
os.makedirs(dir_name)
if copy_symlink and IsLink(source_filename):
# >>> Delete the target_filename if it already exists
if os.path.isfile(target_filename) or IsLink(target_filename):
DeleteFile(target_filename)
# >>> Obtain the relative path from link to source_filename (linkto)
source_filename = ReadLink(source_filename)
CreateLink(source_filename, target_filename)
else:
# shutil can't copy links in Windows, so we must find the real file manually
| python | {
"resource": ""
} |
q265695 | CopyFiles | validation | def CopyFiles(source_dir, target_dir, create_target_dir=False, md5_check=False):
'''
Copy files from the given source to the target.
:param unicode source_dir:
A filename, URL or a file mask.
Ex.
x:\coilib50
x:\coilib50\*
http://server/directory/file
ftp://server/directory/file
:param unicode target_dir:
A directory or an URL
Ex.
d:\Temp
ftp://server/directory
:param bool create_target_dir:
If True, creates the target path if it doesn't exists.
:param bool md5_check:
.. seealso:: CopyFile
:raises DirectoryNotFoundError:
If target_dir does not exist, and create_target_dir is False
.. seealso:: CopyFile for documentation on accepted protocols
.. seealso:: FTP LIMITATIONS at this module's doc for performance issues information
'''
import fnmatch
# Check if we were given a directory or a directory with mask
if IsDir(source_dir):
# Yes, it's a directory, copy everything from it
source_mask = '*'
else:
# Split directory and mask
source_dir, source_mask = os.path.split(source_dir)
# Create directory if necessary
if not IsDir(target_dir):
if create_target_dir:
CreateDirectory(target_dir)
else:
| python | {
"resource": ""
} |
q265696 | CopyFilesX | validation | def CopyFilesX(file_mapping):
'''
Copies files into directories, according to a file mapping
:param list(tuple(unicode,unicode)) file_mapping:
A list of mappings between the directory in the target and the source.
For syntax, @see: ExtendedPathMask
:rtype: list(tuple(unicode,unicode))
:returns:
List of files copied. (source_filename, target_filename)
.. seealso:: FTP LIMITATIONS at this module's doc for performance issues information
'''
# List files that match the mapping
files = []
for i_target_path, i_source_path_mask in file_mapping:
tree_recurse, flat_recurse, dirname, in_filters, out_filters = ExtendedPathMask.Split(i_source_path_mask)
| python | {
"resource": ""
} |
q265697 | CopyDirectory | validation | def CopyDirectory(source_dir, target_dir, override=False):
'''
Recursively copy a directory tree.
:param unicode source_dir:
Where files will come from
:param unicode target_dir:
Where files will go to
:param bool override:
If True and target_dir already exists, it will be deleted before copying.
:raises NotImplementedForRemotePathError:
If trying to copy to/from remote directories
| python | {
"resource": ""
} |
q265698 | DeleteFile | validation | def DeleteFile(target_filename):
'''
Deletes the given local filename.
.. note:: If file doesn't exist this method has no effect.
:param unicode target_filename:
A local filename
:raises NotImplementedForRemotePathError:
If trying to delete a non-local path
:raises FileOnlyActionError:
Raised when filename refers to a directory.
'''
_AssertIsLocal(target_filename)
try:
if IsLink(target_filename):
DeleteLink(target_filename)
elif IsFile(target_filename):
os.remove(target_filename)
| python | {
"resource": ""
} |
q265699 | AppendToFile | validation | def AppendToFile(filename, contents, eol_style=EOL_STYLE_NATIVE, encoding=None, binary=False):
'''
Appends content to a local file.
:param unicode filename:
:param unicode contents:
:type eol_style: EOL_STYLE_XXX constant
:param eol_style:
Replaces the EOL by the appropriate EOL depending on the eol_style value.
Considers that all content is using only "\n" as EOL.
:param unicode encoding:
Target file's content encoding.
Defaults to sys.getfilesystemencoding()
:param bool binary:
If True, content is appended in binary mode. In this case, `contents` must be `bytes` and not
`unicode`
:raises NotImplementedForRemotePathError:
If trying to modify a non-local path
:raises ValueError:
If trying to mix unicode `contents` without `encoding`, or `encoding` without
| python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.