id int32 0 252k | 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 51 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
229,100 | datastax/python-driver | cassandra/cqlengine/query.py | BatchQuery.add_callback | def add_callback(self, fn, *args, **kwargs):
"""Add a function and arguments to be passed to it to be executed after the batch executes.
A batch can support multiple callbacks.
Note, that if the batch does not execute, the callbacks are not executed.
A callback, thus, is an "on batch success" handler.
:param fn: Callable object
:type fn: callable
:param \*args: Positional arguments to be passed to the callback at the time of execution
:param \*\*kwargs: Named arguments to be passed to the callback at the time of execution
"""
if not callable(fn):
raise ValueError("Value for argument 'fn' is {0} and is not a callable object.".format(type(fn)))
self._callbacks.append((fn, args, kwargs)) | python | def add_callback(self, fn, *args, **kwargs):
if not callable(fn):
raise ValueError("Value for argument 'fn' is {0} and is not a callable object.".format(type(fn)))
self._callbacks.append((fn, args, kwargs)) | [
"def",
"add_callback",
"(",
"self",
",",
"fn",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"callable",
"(",
"fn",
")",
":",
"raise",
"ValueError",
"(",
"\"Value for argument 'fn' is {0} and is not a callable object.\"",
".",
"format",
"("... | Add a function and arguments to be passed to it to be executed after the batch executes.
A batch can support multiple callbacks.
Note, that if the batch does not execute, the callbacks are not executed.
A callback, thus, is an "on batch success" handler.
:param fn: Callable object
:type fn: callable
:param \*args: Positional arguments to be passed to the callback at the time of execution
:param \*\*kwargs: Named arguments to be passed to the callback at the time of execution | [
"Add",
"a",
"function",
"and",
"arguments",
"to",
"be",
"passed",
"to",
"it",
"to",
"be",
"executed",
"after",
"the",
"batch",
"executes",
"."
] | 30a80d0b798b1f45f8cb77163b1fa791f3e3ca29 | https://github.com/datastax/python-driver/blob/30a80d0b798b1f45f8cb77163b1fa791f3e3ca29/cassandra/cqlengine/query.py#L199-L214 |
229,101 | datastax/python-driver | cassandra/cqlengine/query.py | AbstractQuerySet._fill_result_cache | def _fill_result_cache(self):
"""
Fill the result cache with all results.
"""
idx = 0
try:
while True:
idx += 1000
self._fill_result_cache_to_idx(idx)
except StopIteration:
pass
self._count = len(self._result_cache) | python | def _fill_result_cache(self):
idx = 0
try:
while True:
idx += 1000
self._fill_result_cache_to_idx(idx)
except StopIteration:
pass
self._count = len(self._result_cache) | [
"def",
"_fill_result_cache",
"(",
"self",
")",
":",
"idx",
"=",
"0",
"try",
":",
"while",
"True",
":",
"idx",
"+=",
"1000",
"self",
".",
"_fill_result_cache_to_idx",
"(",
"idx",
")",
"except",
"StopIteration",
":",
"pass",
"self",
".",
"_count",
"=",
"le... | Fill the result cache with all results. | [
"Fill",
"the",
"result",
"cache",
"with",
"all",
"results",
"."
] | 30a80d0b798b1f45f8cb77163b1fa791f3e3ca29 | https://github.com/datastax/python-driver/blob/30a80d0b798b1f45f8cb77163b1fa791f3e3ca29/cassandra/cqlengine/query.py#L481-L494 |
229,102 | datastax/python-driver | cassandra/cqlengine/query.py | AbstractQuerySet.batch | def batch(self, batch_obj):
"""
Set a batch object to run the query on.
Note: running a select query with a batch object will raise an exception
"""
if self._connection:
raise CQLEngineException("Cannot specify the connection on model in batch mode.")
if batch_obj is not None and not isinstance(batch_obj, BatchQuery):
raise CQLEngineException('batch_obj must be a BatchQuery instance or None')
clone = copy.deepcopy(self)
clone._batch = batch_obj
return clone | python | def batch(self, batch_obj):
if self._connection:
raise CQLEngineException("Cannot specify the connection on model in batch mode.")
if batch_obj is not None and not isinstance(batch_obj, BatchQuery):
raise CQLEngineException('batch_obj must be a BatchQuery instance or None')
clone = copy.deepcopy(self)
clone._batch = batch_obj
return clone | [
"def",
"batch",
"(",
"self",
",",
"batch_obj",
")",
":",
"if",
"self",
".",
"_connection",
":",
"raise",
"CQLEngineException",
"(",
"\"Cannot specify the connection on model in batch mode.\"",
")",
"if",
"batch_obj",
"is",
"not",
"None",
"and",
"not",
"isinstance",
... | Set a batch object to run the query on.
Note: running a select query with a batch object will raise an exception | [
"Set",
"a",
"batch",
"object",
"to",
"run",
"the",
"query",
"on",
"."
] | 30a80d0b798b1f45f8cb77163b1fa791f3e3ca29 | https://github.com/datastax/python-driver/blob/30a80d0b798b1f45f8cb77163b1fa791f3e3ca29/cassandra/cqlengine/query.py#L590-L603 |
229,103 | datastax/python-driver | cassandra/cqlengine/query.py | AbstractQuerySet.count | def count(self):
"""
Returns the number of rows matched by this query.
*Note: This function executes a SELECT COUNT() and has a performance cost on large datasets*
"""
if self._batch:
raise CQLEngineException("Only inserts, updates, and deletes are available in batch mode")
if self._count is None:
query = self._select_query()
query.count = True
result = self._execute(query)
count_row = result.one().popitem()
self._count = count_row[1]
return self._count | python | def count(self):
if self._batch:
raise CQLEngineException("Only inserts, updates, and deletes are available in batch mode")
if self._count is None:
query = self._select_query()
query.count = True
result = self._execute(query)
count_row = result.one().popitem()
self._count = count_row[1]
return self._count | [
"def",
"count",
"(",
"self",
")",
":",
"if",
"self",
".",
"_batch",
":",
"raise",
"CQLEngineException",
"(",
"\"Only inserts, updates, and deletes are available in batch mode\"",
")",
"if",
"self",
".",
"_count",
"is",
"None",
":",
"query",
"=",
"self",
".",
"_s... | Returns the number of rows matched by this query.
*Note: This function executes a SELECT COUNT() and has a performance cost on large datasets* | [
"Returns",
"the",
"number",
"of",
"rows",
"matched",
"by",
"this",
"query",
"."
] | 30a80d0b798b1f45f8cb77163b1fa791f3e3ca29 | https://github.com/datastax/python-driver/blob/30a80d0b798b1f45f8cb77163b1fa791f3e3ca29/cassandra/cqlengine/query.py#L831-L846 |
229,104 | datastax/python-driver | cassandra/cqlengine/query.py | AbstractQuerySet.distinct | def distinct(self, distinct_fields=None):
"""
Returns the DISTINCT rows matched by this query.
distinct_fields default to the partition key fields if not specified.
*Note: distinct_fields must be a partition key or a static column*
.. code-block:: python
class Automobile(Model):
manufacturer = columns.Text(partition_key=True)
year = columns.Integer(primary_key=True)
model = columns.Text(primary_key=True)
price = columns.Decimal()
sync_table(Automobile)
# create rows
Automobile.objects.distinct()
# or
Automobile.objects.distinct(['manufacturer'])
"""
clone = copy.deepcopy(self)
if distinct_fields:
clone._distinct_fields = distinct_fields
else:
clone._distinct_fields = [x.column_name for x in self.model._partition_keys.values()]
return clone | python | def distinct(self, distinct_fields=None):
clone = copy.deepcopy(self)
if distinct_fields:
clone._distinct_fields = distinct_fields
else:
clone._distinct_fields = [x.column_name for x in self.model._partition_keys.values()]
return clone | [
"def",
"distinct",
"(",
"self",
",",
"distinct_fields",
"=",
"None",
")",
":",
"clone",
"=",
"copy",
".",
"deepcopy",
"(",
"self",
")",
"if",
"distinct_fields",
":",
"clone",
".",
"_distinct_fields",
"=",
"distinct_fields",
"else",
":",
"clone",
".",
"_dis... | Returns the DISTINCT rows matched by this query.
distinct_fields default to the partition key fields if not specified.
*Note: distinct_fields must be a partition key or a static column*
.. code-block:: python
class Automobile(Model):
manufacturer = columns.Text(partition_key=True)
year = columns.Integer(primary_key=True)
model = columns.Text(primary_key=True)
price = columns.Decimal()
sync_table(Automobile)
# create rows
Automobile.objects.distinct()
# or
Automobile.objects.distinct(['manufacturer']) | [
"Returns",
"the",
"DISTINCT",
"rows",
"matched",
"by",
"this",
"query",
"."
] | 30a80d0b798b1f45f8cb77163b1fa791f3e3ca29 | https://github.com/datastax/python-driver/blob/30a80d0b798b1f45f8cb77163b1fa791f3e3ca29/cassandra/cqlengine/query.py#L848-L882 |
229,105 | datastax/python-driver | cassandra/cqlengine/query.py | AbstractQuerySet.fetch_size | def fetch_size(self, v):
"""
Sets the number of rows that are fetched at a time.
*Note that driver's default fetch size is 5000.*
.. code-block:: python
for user in User.objects().fetch_size(500):
print(user)
"""
if not isinstance(v, six.integer_types):
raise TypeError
if v == self._fetch_size:
return self
if v < 1:
raise QueryException("fetch size less than 1 is not allowed")
clone = copy.deepcopy(self)
clone._fetch_size = v
return clone | python | def fetch_size(self, v):
if not isinstance(v, six.integer_types):
raise TypeError
if v == self._fetch_size:
return self
if v < 1:
raise QueryException("fetch size less than 1 is not allowed")
clone = copy.deepcopy(self)
clone._fetch_size = v
return clone | [
"def",
"fetch_size",
"(",
"self",
",",
"v",
")",
":",
"if",
"not",
"isinstance",
"(",
"v",
",",
"six",
".",
"integer_types",
")",
":",
"raise",
"TypeError",
"if",
"v",
"==",
"self",
".",
"_fetch_size",
":",
"return",
"self",
"if",
"v",
"<",
"1",
":... | Sets the number of rows that are fetched at a time.
*Note that driver's default fetch size is 5000.*
.. code-block:: python
for user in User.objects().fetch_size(500):
print(user) | [
"Sets",
"the",
"number",
"of",
"rows",
"that",
"are",
"fetched",
"at",
"a",
"time",
"."
] | 30a80d0b798b1f45f8cb77163b1fa791f3e3ca29 | https://github.com/datastax/python-driver/blob/30a80d0b798b1f45f8cb77163b1fa791f3e3ca29/cassandra/cqlengine/query.py#L916-L938 |
229,106 | datastax/python-driver | cassandra/cqlengine/query.py | ModelQuerySet.values_list | def values_list(self, *fields, **kwargs):
""" Instructs the query set to return tuples, not model instance """
flat = kwargs.pop('flat', False)
if kwargs:
raise TypeError('Unexpected keyword arguments to values_list: %s'
% (kwargs.keys(),))
if flat and len(fields) > 1:
raise TypeError("'flat' is not valid when values_list is called with more than one field.")
clone = self.only(fields)
clone._values_list = True
clone._flat_values_list = flat
return clone | python | def values_list(self, *fields, **kwargs):
flat = kwargs.pop('flat', False)
if kwargs:
raise TypeError('Unexpected keyword arguments to values_list: %s'
% (kwargs.keys(),))
if flat and len(fields) > 1:
raise TypeError("'flat' is not valid when values_list is called with more than one field.")
clone = self.only(fields)
clone._values_list = True
clone._flat_values_list = flat
return clone | [
"def",
"values_list",
"(",
"self",
",",
"*",
"fields",
",",
"*",
"*",
"kwargs",
")",
":",
"flat",
"=",
"kwargs",
".",
"pop",
"(",
"'flat'",
",",
"False",
")",
"if",
"kwargs",
":",
"raise",
"TypeError",
"(",
"'Unexpected keyword arguments to values_list: %s'"... | Instructs the query set to return tuples, not model instance | [
"Instructs",
"the",
"query",
"set",
"to",
"return",
"tuples",
"not",
"model",
"instance"
] | 30a80d0b798b1f45f8cb77163b1fa791f3e3ca29 | https://github.com/datastax/python-driver/blob/30a80d0b798b1f45f8cb77163b1fa791f3e3ca29/cassandra/cqlengine/query.py#L1147-L1158 |
229,107 | datastax/python-driver | cassandra/cqlengine/query.py | ModelQuerySet.timestamp | def timestamp(self, timestamp):
"""
Allows for custom timestamps to be saved with the record.
"""
clone = copy.deepcopy(self)
clone._timestamp = timestamp
return clone | python | def timestamp(self, timestamp):
clone = copy.deepcopy(self)
clone._timestamp = timestamp
return clone | [
"def",
"timestamp",
"(",
"self",
",",
"timestamp",
")",
":",
"clone",
"=",
"copy",
".",
"deepcopy",
"(",
"self",
")",
"clone",
".",
"_timestamp",
"=",
"timestamp",
"return",
"clone"
] | Allows for custom timestamps to be saved with the record. | [
"Allows",
"for",
"custom",
"timestamps",
"to",
"be",
"saved",
"with",
"the",
"record",
"."
] | 30a80d0b798b1f45f8cb77163b1fa791f3e3ca29 | https://github.com/datastax/python-driver/blob/30a80d0b798b1f45f8cb77163b1fa791f3e3ca29/cassandra/cqlengine/query.py#L1170-L1176 |
229,108 | datastax/python-driver | cassandra/cqlengine/query.py | ModelQuerySet.if_not_exists | def if_not_exists(self):
"""
Check the existence of an object before insertion.
If the insertion isn't applied, a LWTException is raised.
"""
if self.model._has_counter:
raise IfNotExistsWithCounterColumn('if_not_exists cannot be used with tables containing counter columns')
clone = copy.deepcopy(self)
clone._if_not_exists = True
return clone | python | def if_not_exists(self):
if self.model._has_counter:
raise IfNotExistsWithCounterColumn('if_not_exists cannot be used with tables containing counter columns')
clone = copy.deepcopy(self)
clone._if_not_exists = True
return clone | [
"def",
"if_not_exists",
"(",
"self",
")",
":",
"if",
"self",
".",
"model",
".",
"_has_counter",
":",
"raise",
"IfNotExistsWithCounterColumn",
"(",
"'if_not_exists cannot be used with tables containing counter columns'",
")",
"clone",
"=",
"copy",
".",
"deepcopy",
"(",
... | Check the existence of an object before insertion.
If the insertion isn't applied, a LWTException is raised. | [
"Check",
"the",
"existence",
"of",
"an",
"object",
"before",
"insertion",
"."
] | 30a80d0b798b1f45f8cb77163b1fa791f3e3ca29 | https://github.com/datastax/python-driver/blob/30a80d0b798b1f45f8cb77163b1fa791f3e3ca29/cassandra/cqlengine/query.py#L1178-L1188 |
229,109 | datastax/python-driver | cassandra/cqlengine/query.py | ModelQuerySet.if_exists | def if_exists(self):
"""
Check the existence of an object before an update or delete.
If the update or delete isn't applied, a LWTException is raised.
"""
if self.model._has_counter:
raise IfExistsWithCounterColumn('if_exists cannot be used with tables containing counter columns')
clone = copy.deepcopy(self)
clone._if_exists = True
return clone | python | def if_exists(self):
if self.model._has_counter:
raise IfExistsWithCounterColumn('if_exists cannot be used with tables containing counter columns')
clone = copy.deepcopy(self)
clone._if_exists = True
return clone | [
"def",
"if_exists",
"(",
"self",
")",
":",
"if",
"self",
".",
"model",
".",
"_has_counter",
":",
"raise",
"IfExistsWithCounterColumn",
"(",
"'if_exists cannot be used with tables containing counter columns'",
")",
"clone",
"=",
"copy",
".",
"deepcopy",
"(",
"self",
... | Check the existence of an object before an update or delete.
If the update or delete isn't applied, a LWTException is raised. | [
"Check",
"the",
"existence",
"of",
"an",
"object",
"before",
"an",
"update",
"or",
"delete",
"."
] | 30a80d0b798b1f45f8cb77163b1fa791f3e3ca29 | https://github.com/datastax/python-driver/blob/30a80d0b798b1f45f8cb77163b1fa791f3e3ca29/cassandra/cqlengine/query.py#L1190-L1200 |
229,110 | datastax/python-driver | cassandra/query.py | BatchStatement.clear | def clear(self):
"""
This is a convenience method to clear a batch statement for reuse.
*Note:* it should not be used concurrently with uncompleted execution futures executing the same
``BatchStatement``.
"""
del self._statements_and_parameters[:]
self.keyspace = None
self.routing_key = None
if self.custom_payload:
self.custom_payload.clear() | python | def clear(self):
del self._statements_and_parameters[:]
self.keyspace = None
self.routing_key = None
if self.custom_payload:
self.custom_payload.clear() | [
"def",
"clear",
"(",
"self",
")",
":",
"del",
"self",
".",
"_statements_and_parameters",
"[",
":",
"]",
"self",
".",
"keyspace",
"=",
"None",
"self",
".",
"routing_key",
"=",
"None",
"if",
"self",
".",
"custom_payload",
":",
"self",
".",
"custom_payload",
... | This is a convenience method to clear a batch statement for reuse.
*Note:* it should not be used concurrently with uncompleted execution futures executing the same
``BatchStatement``. | [
"This",
"is",
"a",
"convenience",
"method",
"to",
"clear",
"a",
"batch",
"statement",
"for",
"reuse",
"."
] | 30a80d0b798b1f45f8cb77163b1fa791f3e3ca29 | https://github.com/datastax/python-driver/blob/30a80d0b798b1f45f8cb77163b1fa791f3e3ca29/cassandra/query.py#L787-L798 |
229,111 | datastax/python-driver | cassandra/cqlengine/usertype.py | BaseUserType.type_name | def type_name(cls):
"""
Returns the type name if it's been defined
otherwise, it creates it from the class name
"""
if cls.__type_name__:
type_name = cls.__type_name__.lower()
else:
camelcase = re.compile(r'([a-z])([A-Z])')
ccase = lambda s: camelcase.sub(lambda v: '{0}_{1}'.format(v.group(1), v.group(2)), s)
type_name = ccase(cls.__name__)
# trim to less than 48 characters or cassandra will complain
type_name = type_name[-48:]
type_name = type_name.lower()
type_name = re.sub(r'^_+', '', type_name)
cls.__type_name__ = type_name
return type_name | python | def type_name(cls):
if cls.__type_name__:
type_name = cls.__type_name__.lower()
else:
camelcase = re.compile(r'([a-z])([A-Z])')
ccase = lambda s: camelcase.sub(lambda v: '{0}_{1}'.format(v.group(1), v.group(2)), s)
type_name = ccase(cls.__name__)
# trim to less than 48 characters or cassandra will complain
type_name = type_name[-48:]
type_name = type_name.lower()
type_name = re.sub(r'^_+', '', type_name)
cls.__type_name__ = type_name
return type_name | [
"def",
"type_name",
"(",
"cls",
")",
":",
"if",
"cls",
".",
"__type_name__",
":",
"type_name",
"=",
"cls",
".",
"__type_name__",
".",
"lower",
"(",
")",
"else",
":",
"camelcase",
"=",
"re",
".",
"compile",
"(",
"r'([a-z])([A-Z])'",
")",
"ccase",
"=",
"... | Returns the type name if it's been defined
otherwise, it creates it from the class name | [
"Returns",
"the",
"type",
"name",
"if",
"it",
"s",
"been",
"defined",
"otherwise",
"it",
"creates",
"it",
"from",
"the",
"class",
"name"
] | 30a80d0b798b1f45f8cb77163b1fa791f3e3ca29 | https://github.com/datastax/python-driver/blob/30a80d0b798b1f45f8cb77163b1fa791f3e3ca29/cassandra/cqlengine/usertype.py#L119-L137 |
229,112 | datastax/python-driver | cassandra/cqlengine/columns.py | BaseValueManager.changed | def changed(self):
"""
Indicates whether or not this value has changed.
:rtype: boolean
"""
if self.explicit:
return self.value != self.previous_value
if isinstance(self.column, BaseContainerColumn):
default_value = self.column.get_default()
if self.column._val_is_null(default_value):
return not self.column._val_is_null(self.value) and self.value != self.previous_value
elif self.previous_value is None:
return self.value != default_value
return self.value != self.previous_value
return False | python | def changed(self):
if self.explicit:
return self.value != self.previous_value
if isinstance(self.column, BaseContainerColumn):
default_value = self.column.get_default()
if self.column._val_is_null(default_value):
return not self.column._val_is_null(self.value) and self.value != self.previous_value
elif self.previous_value is None:
return self.value != default_value
return self.value != self.previous_value
return False | [
"def",
"changed",
"(",
"self",
")",
":",
"if",
"self",
".",
"explicit",
":",
"return",
"self",
".",
"value",
"!=",
"self",
".",
"previous_value",
"if",
"isinstance",
"(",
"self",
".",
"column",
",",
"BaseContainerColumn",
")",
":",
"default_value",
"=",
... | Indicates whether or not this value has changed.
:rtype: boolean | [
"Indicates",
"whether",
"or",
"not",
"this",
"value",
"has",
"changed",
"."
] | 30a80d0b798b1f45f8cb77163b1fa791f3e3ca29 | https://github.com/datastax/python-driver/blob/30a80d0b798b1f45f8cb77163b1fa791f3e3ca29/cassandra/cqlengine/columns.py#L44-L63 |
229,113 | datastax/python-driver | cassandra/cqlengine/columns.py | Ascii.validate | def validate(self, value):
""" Only allow ASCII and None values.
Check against US-ASCII, a.k.a. 7-bit ASCII, a.k.a. ISO646-US, a.k.a.
the Basic Latin block of the Unicode character set.
Source: https://github.com/apache/cassandra/blob
/3dcbe90e02440e6ee534f643c7603d50ca08482b/src/java/org/apache/cassandra
/serializers/AsciiSerializer.java#L29
"""
value = super(Ascii, self).validate(value)
if value:
charset = value if isinstance(
value, (bytearray, )) else map(ord, value)
if not set(range(128)).issuperset(charset):
raise ValidationError(
'{!r} is not an ASCII string.'.format(value))
return value | python | def validate(self, value):
value = super(Ascii, self).validate(value)
if value:
charset = value if isinstance(
value, (bytearray, )) else map(ord, value)
if not set(range(128)).issuperset(charset):
raise ValidationError(
'{!r} is not an ASCII string.'.format(value))
return value | [
"def",
"validate",
"(",
"self",
",",
"value",
")",
":",
"value",
"=",
"super",
"(",
"Ascii",
",",
"self",
")",
".",
"validate",
"(",
"value",
")",
"if",
"value",
":",
"charset",
"=",
"value",
"if",
"isinstance",
"(",
"value",
",",
"(",
"bytearray",
... | Only allow ASCII and None values.
Check against US-ASCII, a.k.a. 7-bit ASCII, a.k.a. ISO646-US, a.k.a.
the Basic Latin block of the Unicode character set.
Source: https://github.com/apache/cassandra/blob
/3dcbe90e02440e6ee534f643c7603d50ca08482b/src/java/org/apache/cassandra
/serializers/AsciiSerializer.java#L29 | [
"Only",
"allow",
"ASCII",
"and",
"None",
"values",
"."
] | 30a80d0b798b1f45f8cb77163b1fa791f3e3ca29 | https://github.com/datastax/python-driver/blob/30a80d0b798b1f45f8cb77163b1fa791f3e3ca29/cassandra/cqlengine/columns.py#L401-L418 |
229,114 | datastax/python-driver | cassandra/cqlengine/columns.py | Boolean.validate | def validate(self, value):
""" Always returns a Python boolean. """
value = super(Boolean, self).validate(value)
if value is not None:
value = bool(value)
return value | python | def validate(self, value):
value = super(Boolean, self).validate(value)
if value is not None:
value = bool(value)
return value | [
"def",
"validate",
"(",
"self",
",",
"value",
")",
":",
"value",
"=",
"super",
"(",
"Boolean",
",",
"self",
")",
".",
"validate",
"(",
"value",
")",
"if",
"value",
"is",
"not",
"None",
":",
"value",
"=",
"bool",
"(",
"value",
")",
"return",
"value"... | Always returns a Python boolean. | [
"Always",
"returns",
"a",
"Python",
"boolean",
"."
] | 30a80d0b798b1f45f8cb77163b1fa791f3e3ca29 | https://github.com/datastax/python-driver/blob/30a80d0b798b1f45f8cb77163b1fa791f3e3ca29/cassandra/cqlengine/columns.py#L688-L695 |
229,115 | datastax/python-driver | cassandra/cqlengine/management.py | _get_context | def _get_context(keyspaces, connections):
"""Return all the execution contexts"""
if keyspaces:
if not isinstance(keyspaces, (list, tuple)):
raise ValueError('keyspaces must be a list or a tuple.')
if connections:
if not isinstance(connections, (list, tuple)):
raise ValueError('connections must be a list or a tuple.')
keyspaces = keyspaces if keyspaces else [None]
connections = connections if connections else [None]
return product(connections, keyspaces) | python | def _get_context(keyspaces, connections):
if keyspaces:
if not isinstance(keyspaces, (list, tuple)):
raise ValueError('keyspaces must be a list or a tuple.')
if connections:
if not isinstance(connections, (list, tuple)):
raise ValueError('connections must be a list or a tuple.')
keyspaces = keyspaces if keyspaces else [None]
connections = connections if connections else [None]
return product(connections, keyspaces) | [
"def",
"_get_context",
"(",
"keyspaces",
",",
"connections",
")",
":",
"if",
"keyspaces",
":",
"if",
"not",
"isinstance",
"(",
"keyspaces",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"raise",
"ValueError",
"(",
"'keyspaces must be a list or a tuple.'",
")"... | Return all the execution contexts | [
"Return",
"all",
"the",
"execution",
"contexts"
] | 30a80d0b798b1f45f8cb77163b1fa791f3e3ca29 | https://github.com/datastax/python-driver/blob/30a80d0b798b1f45f8cb77163b1fa791f3e3ca29/cassandra/cqlengine/management.py#L41-L55 |
229,116 | datastax/python-driver | cassandra/cqlengine/management.py | create_keyspace_simple | def create_keyspace_simple(name, replication_factor, durable_writes=True, connections=None):
"""
Creates a keyspace with SimpleStrategy for replica placement
If the keyspace already exists, it will not be modified.
**This function should be used with caution, especially in production environments.
Take care to execute schema modifications in a single context (i.e. not concurrently with other clients).**
*There are plans to guard schema-modifying functions with an environment-driven conditional.*
:param str name: name of keyspace to create
:param int replication_factor: keyspace replication factor, used with :attr:`~.SimpleStrategy`
:param bool durable_writes: Write log is bypassed if set to False
:param list connections: List of connection names
"""
_create_keyspace(name, durable_writes, 'SimpleStrategy',
{'replication_factor': replication_factor}, connections=connections) | python | def create_keyspace_simple(name, replication_factor, durable_writes=True, connections=None):
_create_keyspace(name, durable_writes, 'SimpleStrategy',
{'replication_factor': replication_factor}, connections=connections) | [
"def",
"create_keyspace_simple",
"(",
"name",
",",
"replication_factor",
",",
"durable_writes",
"=",
"True",
",",
"connections",
"=",
"None",
")",
":",
"_create_keyspace",
"(",
"name",
",",
"durable_writes",
",",
"'SimpleStrategy'",
",",
"{",
"'replication_factor'",... | Creates a keyspace with SimpleStrategy for replica placement
If the keyspace already exists, it will not be modified.
**This function should be used with caution, especially in production environments.
Take care to execute schema modifications in a single context (i.e. not concurrently with other clients).**
*There are plans to guard schema-modifying functions with an environment-driven conditional.*
:param str name: name of keyspace to create
:param int replication_factor: keyspace replication factor, used with :attr:`~.SimpleStrategy`
:param bool durable_writes: Write log is bypassed if set to False
:param list connections: List of connection names | [
"Creates",
"a",
"keyspace",
"with",
"SimpleStrategy",
"for",
"replica",
"placement"
] | 30a80d0b798b1f45f8cb77163b1fa791f3e3ca29 | https://github.com/datastax/python-driver/blob/30a80d0b798b1f45f8cb77163b1fa791f3e3ca29/cassandra/cqlengine/management.py#L58-L75 |
229,117 | datastax/python-driver | cassandra/cqlengine/management.py | create_keyspace_network_topology | def create_keyspace_network_topology(name, dc_replication_map, durable_writes=True, connections=None):
"""
Creates a keyspace with NetworkTopologyStrategy for replica placement
If the keyspace already exists, it will not be modified.
**This function should be used with caution, especially in production environments.
Take care to execute schema modifications in a single context (i.e. not concurrently with other clients).**
*There are plans to guard schema-modifying functions with an environment-driven conditional.*
:param str name: name of keyspace to create
:param dict dc_replication_map: map of dc_names: replication_factor
:param bool durable_writes: Write log is bypassed if set to False
:param list connections: List of connection names
"""
_create_keyspace(name, durable_writes, 'NetworkTopologyStrategy', dc_replication_map, connections=connections) | python | def create_keyspace_network_topology(name, dc_replication_map, durable_writes=True, connections=None):
_create_keyspace(name, durable_writes, 'NetworkTopologyStrategy', dc_replication_map, connections=connections) | [
"def",
"create_keyspace_network_topology",
"(",
"name",
",",
"dc_replication_map",
",",
"durable_writes",
"=",
"True",
",",
"connections",
"=",
"None",
")",
":",
"_create_keyspace",
"(",
"name",
",",
"durable_writes",
",",
"'NetworkTopologyStrategy'",
",",
"dc_replica... | Creates a keyspace with NetworkTopologyStrategy for replica placement
If the keyspace already exists, it will not be modified.
**This function should be used with caution, especially in production environments.
Take care to execute schema modifications in a single context (i.e. not concurrently with other clients).**
*There are plans to guard schema-modifying functions with an environment-driven conditional.*
:param str name: name of keyspace to create
:param dict dc_replication_map: map of dc_names: replication_factor
:param bool durable_writes: Write log is bypassed if set to False
:param list connections: List of connection names | [
"Creates",
"a",
"keyspace",
"with",
"NetworkTopologyStrategy",
"for",
"replica",
"placement"
] | 30a80d0b798b1f45f8cb77163b1fa791f3e3ca29 | https://github.com/datastax/python-driver/blob/30a80d0b798b1f45f8cb77163b1fa791f3e3ca29/cassandra/cqlengine/management.py#L78-L94 |
229,118 | datastax/python-driver | cassandra/cqlengine/management.py | drop_keyspace | def drop_keyspace(name, connections=None):
"""
Drops a keyspace, if it exists.
*There are plans to guard schema-modifying functions with an environment-driven conditional.*
**This function should be used with caution, especially in production environments.
Take care to execute schema modifications in a single context (i.e. not concurrently with other clients).**
:param str name: name of keyspace to drop
:param list connections: List of connection names
"""
if not _allow_schema_modification():
return
if connections:
if not isinstance(connections, (list, tuple)):
raise ValueError('Connections must be a list or a tuple.')
def _drop_keyspace(name, connection=None):
cluster = get_cluster(connection)
if name in cluster.metadata.keyspaces:
execute("DROP KEYSPACE {0}".format(metadata.protect_name(name)), connection=connection)
if connections:
for connection in connections:
_drop_keyspace(name, connection)
else:
_drop_keyspace(name) | python | def drop_keyspace(name, connections=None):
if not _allow_schema_modification():
return
if connections:
if not isinstance(connections, (list, tuple)):
raise ValueError('Connections must be a list or a tuple.')
def _drop_keyspace(name, connection=None):
cluster = get_cluster(connection)
if name in cluster.metadata.keyspaces:
execute("DROP KEYSPACE {0}".format(metadata.protect_name(name)), connection=connection)
if connections:
for connection in connections:
_drop_keyspace(name, connection)
else:
_drop_keyspace(name) | [
"def",
"drop_keyspace",
"(",
"name",
",",
"connections",
"=",
"None",
")",
":",
"if",
"not",
"_allow_schema_modification",
"(",
")",
":",
"return",
"if",
"connections",
":",
"if",
"not",
"isinstance",
"(",
"connections",
",",
"(",
"list",
",",
"tuple",
")"... | Drops a keyspace, if it exists.
*There are plans to guard schema-modifying functions with an environment-driven conditional.*
**This function should be used with caution, especially in production environments.
Take care to execute schema modifications in a single context (i.e. not concurrently with other clients).**
:param str name: name of keyspace to drop
:param list connections: List of connection names | [
"Drops",
"a",
"keyspace",
"if",
"it",
"exists",
"."
] | 30a80d0b798b1f45f8cb77163b1fa791f3e3ca29 | https://github.com/datastax/python-driver/blob/30a80d0b798b1f45f8cb77163b1fa791f3e3ca29/cassandra/cqlengine/management.py#L122-L150 |
229,119 | datastax/python-driver | cassandra/cqlengine/management.py | _get_index_name_by_column | def _get_index_name_by_column(table, column_name):
"""
Find the index name for a given table and column.
"""
protected_name = metadata.protect_name(column_name)
possible_index_values = [protected_name, "values(%s)" % protected_name]
for index_metadata in table.indexes.values():
options = dict(index_metadata.index_options)
if options.get('target') in possible_index_values:
return index_metadata.name | python | def _get_index_name_by_column(table, column_name):
protected_name = metadata.protect_name(column_name)
possible_index_values = [protected_name, "values(%s)" % protected_name]
for index_metadata in table.indexes.values():
options = dict(index_metadata.index_options)
if options.get('target') in possible_index_values:
return index_metadata.name | [
"def",
"_get_index_name_by_column",
"(",
"table",
",",
"column_name",
")",
":",
"protected_name",
"=",
"metadata",
".",
"protect_name",
"(",
"column_name",
")",
"possible_index_values",
"=",
"[",
"protected_name",
",",
"\"values(%s)\"",
"%",
"protected_name",
"]",
"... | Find the index name for a given table and column. | [
"Find",
"the",
"index",
"name",
"for",
"a",
"given",
"table",
"and",
"column",
"."
] | 30a80d0b798b1f45f8cb77163b1fa791f3e3ca29 | https://github.com/datastax/python-driver/blob/30a80d0b798b1f45f8cb77163b1fa791f3e3ca29/cassandra/cqlengine/management.py#L152-L161 |
229,120 | datastax/python-driver | cassandra/cqlengine/management.py | _update_options | def _update_options(model, connection=None):
"""Updates the table options for the given model if necessary.
:param model: The model to update.
:param connection: Name of the connection to use
:return: `True`, if the options were modified in Cassandra,
`False` otherwise.
:rtype: bool
"""
ks_name = model._get_keyspace()
msg = format_log_context("Checking %s for option differences", keyspace=ks_name, connection=connection)
log.debug(msg, model)
model_options = model.__options__ or {}
table_meta = _get_table_metadata(model, connection=connection)
# go to CQL string first to normalize meta from different versions
existing_option_strings = set(table_meta._make_option_strings(table_meta.options))
existing_options = _options_map_from_strings(existing_option_strings)
model_option_strings = metadata.TableMetadataV3._make_option_strings(model_options)
model_options = _options_map_from_strings(model_option_strings)
update_options = {}
for name, value in model_options.items():
try:
existing_value = existing_options[name]
except KeyError:
msg = format_log_context("Invalid table option: '%s'; known options: %s", keyspace=ks_name, connection=connection)
raise KeyError(msg % (name, existing_options.keys()))
if isinstance(existing_value, six.string_types):
if value != existing_value:
update_options[name] = value
else:
try:
for k, v in value.items():
if existing_value[k] != v:
update_options[name] = value
break
except KeyError:
update_options[name] = value
if update_options:
options = ' AND '.join(metadata.TableMetadataV3._make_option_strings(update_options))
query = "ALTER TABLE {0} WITH {1}".format(model.column_family_name(), options)
execute(query, connection=connection)
return True
return False | python | def _update_options(model, connection=None):
ks_name = model._get_keyspace()
msg = format_log_context("Checking %s for option differences", keyspace=ks_name, connection=connection)
log.debug(msg, model)
model_options = model.__options__ or {}
table_meta = _get_table_metadata(model, connection=connection)
# go to CQL string first to normalize meta from different versions
existing_option_strings = set(table_meta._make_option_strings(table_meta.options))
existing_options = _options_map_from_strings(existing_option_strings)
model_option_strings = metadata.TableMetadataV3._make_option_strings(model_options)
model_options = _options_map_from_strings(model_option_strings)
update_options = {}
for name, value in model_options.items():
try:
existing_value = existing_options[name]
except KeyError:
msg = format_log_context("Invalid table option: '%s'; known options: %s", keyspace=ks_name, connection=connection)
raise KeyError(msg % (name, existing_options.keys()))
if isinstance(existing_value, six.string_types):
if value != existing_value:
update_options[name] = value
else:
try:
for k, v in value.items():
if existing_value[k] != v:
update_options[name] = value
break
except KeyError:
update_options[name] = value
if update_options:
options = ' AND '.join(metadata.TableMetadataV3._make_option_strings(update_options))
query = "ALTER TABLE {0} WITH {1}".format(model.column_family_name(), options)
execute(query, connection=connection)
return True
return False | [
"def",
"_update_options",
"(",
"model",
",",
"connection",
"=",
"None",
")",
":",
"ks_name",
"=",
"model",
".",
"_get_keyspace",
"(",
")",
"msg",
"=",
"format_log_context",
"(",
"\"Checking %s for option differences\"",
",",
"keyspace",
"=",
"ks_name",
",",
"con... | Updates the table options for the given model if necessary.
:param model: The model to update.
:param connection: Name of the connection to use
:return: `True`, if the options were modified in Cassandra,
`False` otherwise.
:rtype: bool | [
"Updates",
"the",
"table",
"options",
"for",
"the",
"given",
"model",
"if",
"necessary",
"."
] | 30a80d0b798b1f45f8cb77163b1fa791f3e3ca29 | https://github.com/datastax/python-driver/blob/30a80d0b798b1f45f8cb77163b1fa791f3e3ca29/cassandra/cqlengine/management.py#L451-L498 |
229,121 | datastax/python-driver | cassandra/cqlengine/management.py | drop_table | def drop_table(model, keyspaces=None, connections=None):
"""
Drops the table indicated by the model, if it exists.
If `keyspaces` is specified, the table will be dropped for all specified keyspaces. Note that the `Model.__keyspace__` is ignored in that case.
If `connections` is specified, the table will be synched for all specified connections. Note that the `Model.__connection__` is ignored in that case.
If not specified, it will try to get the connection from the Model.
**This function should be used with caution, especially in production environments.
Take care to execute schema modifications in a single context (i.e. not concurrently with other clients).**
*There are plans to guard schema-modifying functions with an environment-driven conditional.*
"""
context = _get_context(keyspaces, connections)
for connection, keyspace in context:
with query.ContextQuery(model, keyspace=keyspace) as m:
_drop_table(m, connection=connection) | python | def drop_table(model, keyspaces=None, connections=None):
context = _get_context(keyspaces, connections)
for connection, keyspace in context:
with query.ContextQuery(model, keyspace=keyspace) as m:
_drop_table(m, connection=connection) | [
"def",
"drop_table",
"(",
"model",
",",
"keyspaces",
"=",
"None",
",",
"connections",
"=",
"None",
")",
":",
"context",
"=",
"_get_context",
"(",
"keyspaces",
",",
"connections",
")",
"for",
"connection",
",",
"keyspace",
"in",
"context",
":",
"with",
"que... | Drops the table indicated by the model, if it exists.
If `keyspaces` is specified, the table will be dropped for all specified keyspaces. Note that the `Model.__keyspace__` is ignored in that case.
If `connections` is specified, the table will be synched for all specified connections. Note that the `Model.__connection__` is ignored in that case.
If not specified, it will try to get the connection from the Model.
**This function should be used with caution, especially in production environments.
Take care to execute schema modifications in a single context (i.e. not concurrently with other clients).**
*There are plans to guard schema-modifying functions with an environment-driven conditional.* | [
"Drops",
"the",
"table",
"indicated",
"by",
"the",
"model",
"if",
"it",
"exists",
"."
] | 30a80d0b798b1f45f8cb77163b1fa791f3e3ca29 | https://github.com/datastax/python-driver/blob/30a80d0b798b1f45f8cb77163b1fa791f3e3ca29/cassandra/cqlengine/management.py#L501-L520 |
229,122 | datastax/python-driver | cassandra/io/twistedreactor.py | TwistedConnectionProtocol.dataReceived | def dataReceived(self, data):
"""
Callback function that is called when data has been received
on the connection.
Reaches back to the Connection object and queues the data for
processing.
"""
self.connection._iobuf.write(data)
self.connection.handle_read() | python | def dataReceived(self, data):
self.connection._iobuf.write(data)
self.connection.handle_read() | [
"def",
"dataReceived",
"(",
"self",
",",
"data",
")",
":",
"self",
".",
"connection",
".",
"_iobuf",
".",
"write",
"(",
"data",
")",
"self",
".",
"connection",
".",
"handle_read",
"(",
")"
] | Callback function that is called when data has been received
on the connection.
Reaches back to the Connection object and queues the data for
processing. | [
"Callback",
"function",
"that",
"is",
"called",
"when",
"data",
"has",
"been",
"received",
"on",
"the",
"connection",
"."
] | 30a80d0b798b1f45f8cb77163b1fa791f3e3ca29 | https://github.com/datastax/python-driver/blob/30a80d0b798b1f45f8cb77163b1fa791f3e3ca29/cassandra/io/twistedreactor.py#L48-L57 |
229,123 | datastax/python-driver | cassandra/io/twistedreactor.py | TwistedConnectionProtocol.connectionMade | def connectionMade(self):
"""
Callback function that is called when a connection has succeeded.
Reaches back to the Connection object and confirms that the connection
is ready.
"""
try:
# Non SSL connection
self.connection = self.transport.connector.factory.conn
except AttributeError:
# SSL connection
self.connection = self.transport.connector.factory.wrappedFactory.conn
self.connection.client_connection_made(self.transport) | python | def connectionMade(self):
try:
# Non SSL connection
self.connection = self.transport.connector.factory.conn
except AttributeError:
# SSL connection
self.connection = self.transport.connector.factory.wrappedFactory.conn
self.connection.client_connection_made(self.transport) | [
"def",
"connectionMade",
"(",
"self",
")",
":",
"try",
":",
"# Non SSL connection",
"self",
".",
"connection",
"=",
"self",
".",
"transport",
".",
"connector",
".",
"factory",
".",
"conn",
"except",
"AttributeError",
":",
"# SSL connection",
"self",
".",
"conn... | Callback function that is called when a connection has succeeded.
Reaches back to the Connection object and confirms that the connection
is ready. | [
"Callback",
"function",
"that",
"is",
"called",
"when",
"a",
"connection",
"has",
"succeeded",
"."
] | 30a80d0b798b1f45f8cb77163b1fa791f3e3ca29 | https://github.com/datastax/python-driver/blob/30a80d0b798b1f45f8cb77163b1fa791f3e3ca29/cassandra/io/twistedreactor.py#L58-L72 |
229,124 | datastax/python-driver | cassandra/io/twistedreactor.py | TwistedConnectionClientFactory.clientConnectionFailed | def clientConnectionFailed(self, connector, reason):
"""
Overridden twisted callback which is called when the
connection attempt fails.
"""
log.debug("Connect failed: %s", reason)
self.conn.defunct(reason.value) | python | def clientConnectionFailed(self, connector, reason):
log.debug("Connect failed: %s", reason)
self.conn.defunct(reason.value) | [
"def",
"clientConnectionFailed",
"(",
"self",
",",
"connector",
",",
"reason",
")",
":",
"log",
".",
"debug",
"(",
"\"Connect failed: %s\"",
",",
"reason",
")",
"self",
".",
"conn",
".",
"defunct",
"(",
"reason",
".",
"value",
")"
] | Overridden twisted callback which is called when the
connection attempt fails. | [
"Overridden",
"twisted",
"callback",
"which",
"is",
"called",
"when",
"the",
"connection",
"attempt",
"fails",
"."
] | 30a80d0b798b1f45f8cb77163b1fa791f3e3ca29 | https://github.com/datastax/python-driver/blob/30a80d0b798b1f45f8cb77163b1fa791f3e3ca29/cassandra/io/twistedreactor.py#L93-L99 |
229,125 | datastax/python-driver | cassandra/io/twistedreactor.py | TwistedConnection.add_connection | def add_connection(self):
"""
Convenience function to connect and store the resulting
connector.
"""
if self.ssl_options:
if not _HAS_SSL:
raise ImportError(
str(e) +
', pyOpenSSL must be installed to enable SSL support with the Twisted event loop'
)
self.connector = reactor.connectSSL(
host=self.endpoint.address, port=self.port,
factory=TwistedConnectionClientFactory(self),
contextFactory=_SSLContextFactory(self.ssl_options, self._check_hostname, self.endpoint.address),
timeout=self.connect_timeout)
else:
self.connector = reactor.connectTCP(
host=self.endpoint.address, port=self.port,
factory=TwistedConnectionClientFactory(self),
timeout=self.connect_timeout) | python | def add_connection(self):
if self.ssl_options:
if not _HAS_SSL:
raise ImportError(
str(e) +
', pyOpenSSL must be installed to enable SSL support with the Twisted event loop'
)
self.connector = reactor.connectSSL(
host=self.endpoint.address, port=self.port,
factory=TwistedConnectionClientFactory(self),
contextFactory=_SSLContextFactory(self.ssl_options, self._check_hostname, self.endpoint.address),
timeout=self.connect_timeout)
else:
self.connector = reactor.connectTCP(
host=self.endpoint.address, port=self.port,
factory=TwistedConnectionClientFactory(self),
timeout=self.connect_timeout) | [
"def",
"add_connection",
"(",
"self",
")",
":",
"if",
"self",
".",
"ssl_options",
":",
"if",
"not",
"_HAS_SSL",
":",
"raise",
"ImportError",
"(",
"str",
"(",
"e",
")",
"+",
"', pyOpenSSL must be installed to enable SSL support with the Twisted event loop'",
")",
"se... | Convenience function to connect and store the resulting
connector. | [
"Convenience",
"function",
"to",
"connect",
"and",
"store",
"the",
"resulting",
"connector",
"."
] | 30a80d0b798b1f45f8cb77163b1fa791f3e3ca29 | https://github.com/datastax/python-driver/blob/30a80d0b798b1f45f8cb77163b1fa791f3e3ca29/cassandra/io/twistedreactor.py#L249-L271 |
229,126 | datastax/python-driver | cassandra/io/twistedreactor.py | TwistedConnection.client_connection_made | def client_connection_made(self, transport):
"""
Called by twisted protocol when a connection attempt has
succeeded.
"""
with self.lock:
self.is_closed = False
self.transport = transport
self._send_options_message() | python | def client_connection_made(self, transport):
with self.lock:
self.is_closed = False
self.transport = transport
self._send_options_message() | [
"def",
"client_connection_made",
"(",
"self",
",",
"transport",
")",
":",
"with",
"self",
".",
"lock",
":",
"self",
".",
"is_closed",
"=",
"False",
"self",
".",
"transport",
"=",
"transport",
"self",
".",
"_send_options_message",
"(",
")"
] | Called by twisted protocol when a connection attempt has
succeeded. | [
"Called",
"by",
"twisted",
"protocol",
"when",
"a",
"connection",
"attempt",
"has",
"succeeded",
"."
] | 30a80d0b798b1f45f8cb77163b1fa791f3e3ca29 | https://github.com/datastax/python-driver/blob/30a80d0b798b1f45f8cb77163b1fa791f3e3ca29/cassandra/io/twistedreactor.py#L273-L281 |
229,127 | datastax/python-driver | cassandra/io/twistedreactor.py | TwistedConnection.close | def close(self):
"""
Disconnect and error-out all requests.
"""
with self.lock:
if self.is_closed:
return
self.is_closed = True
log.debug("Closing connection (%s) to %s", id(self), self.endpoint)
reactor.callFromThread(self.connector.disconnect)
log.debug("Closed socket to %s", self.endpoint)
if not self.is_defunct:
self.error_all_requests(
ConnectionShutdown("Connection to %s was closed" % self.endpoint))
# don't leave in-progress operations hanging
self.connected_event.set() | python | def close(self):
with self.lock:
if self.is_closed:
return
self.is_closed = True
log.debug("Closing connection (%s) to %s", id(self), self.endpoint)
reactor.callFromThread(self.connector.disconnect)
log.debug("Closed socket to %s", self.endpoint)
if not self.is_defunct:
self.error_all_requests(
ConnectionShutdown("Connection to %s was closed" % self.endpoint))
# don't leave in-progress operations hanging
self.connected_event.set() | [
"def",
"close",
"(",
"self",
")",
":",
"with",
"self",
".",
"lock",
":",
"if",
"self",
".",
"is_closed",
":",
"return",
"self",
".",
"is_closed",
"=",
"True",
"log",
".",
"debug",
"(",
"\"Closing connection (%s) to %s\"",
",",
"id",
"(",
"self",
")",
"... | Disconnect and error-out all requests. | [
"Disconnect",
"and",
"error",
"-",
"out",
"all",
"requests",
"."
] | 30a80d0b798b1f45f8cb77163b1fa791f3e3ca29 | https://github.com/datastax/python-driver/blob/30a80d0b798b1f45f8cb77163b1fa791f3e3ca29/cassandra/io/twistedreactor.py#L283-L300 |
229,128 | datastax/python-driver | cassandra/timestamps.py | MonotonicTimestampGenerator._next_timestamp | def _next_timestamp(self, now, last):
"""
Returns the timestamp that should be used if ``now`` is the current
time and ``last`` is the last timestamp returned by this object.
Intended for internal and testing use only; to generate timestamps,
call an instantiated ``MonotonicTimestampGenerator`` object.
:param int now: an integer to be used as the current time, typically
representing the current time in microseconds since the UNIX epoch
:param int last: an integer representing the last timestamp returned by
this object
"""
if now > last:
self.last = now
return now
else:
self._maybe_warn(now=now)
self.last = last + 1
return self.last | python | def _next_timestamp(self, now, last):
if now > last:
self.last = now
return now
else:
self._maybe_warn(now=now)
self.last = last + 1
return self.last | [
"def",
"_next_timestamp",
"(",
"self",
",",
"now",
",",
"last",
")",
":",
"if",
"now",
">",
"last",
":",
"self",
".",
"last",
"=",
"now",
"return",
"now",
"else",
":",
"self",
".",
"_maybe_warn",
"(",
"now",
"=",
"now",
")",
"self",
".",
"last",
... | Returns the timestamp that should be used if ``now`` is the current
time and ``last`` is the last timestamp returned by this object.
Intended for internal and testing use only; to generate timestamps,
call an instantiated ``MonotonicTimestampGenerator`` object.
:param int now: an integer to be used as the current time, typically
representing the current time in microseconds since the UNIX epoch
:param int last: an integer representing the last timestamp returned by
this object | [
"Returns",
"the",
"timestamp",
"that",
"should",
"be",
"used",
"if",
"now",
"is",
"the",
"current",
"time",
"and",
"last",
"is",
"the",
"last",
"timestamp",
"returned",
"by",
"this",
"object",
".",
"Intended",
"for",
"internal",
"and",
"testing",
"use",
"o... | 30a80d0b798b1f45f8cb77163b1fa791f3e3ca29 | https://github.com/datastax/python-driver/blob/30a80d0b798b1f45f8cb77163b1fa791f3e3ca29/cassandra/timestamps.py#L65-L83 |
229,129 | datastax/python-driver | cassandra/cqlengine/models.py | BaseModel._get_column_by_db_name | def _get_column_by_db_name(cls, name):
"""
Returns the column, mapped by db_field name
"""
return cls._columns.get(cls._db_map.get(name, name)) | python | def _get_column_by_db_name(cls, name):
return cls._columns.get(cls._db_map.get(name, name)) | [
"def",
"_get_column_by_db_name",
"(",
"cls",
",",
"name",
")",
":",
"return",
"cls",
".",
"_columns",
".",
"get",
"(",
"cls",
".",
"_db_map",
".",
"get",
"(",
"name",
",",
"name",
")",
")"
] | Returns the column, mapped by db_field name | [
"Returns",
"the",
"column",
"mapped",
"by",
"db_field",
"name"
] | 30a80d0b798b1f45f8cb77163b1fa791f3e3ca29 | https://github.com/datastax/python-driver/blob/30a80d0b798b1f45f8cb77163b1fa791f3e3ca29/cassandra/cqlengine/models.py#L528-L532 |
229,130 | datastax/python-driver | cassandra/cqlengine/models.py | BaseModel._as_dict | def _as_dict(self):
""" Returns a map of column names to cleaned values """
values = self._dynamic_columns or {}
for name, col in self._columns.items():
values[name] = col.to_database(getattr(self, name, None))
return values | python | def _as_dict(self):
values = self._dynamic_columns or {}
for name, col in self._columns.items():
values[name] = col.to_database(getattr(self, name, None))
return values | [
"def",
"_as_dict",
"(",
"self",
")",
":",
"values",
"=",
"self",
".",
"_dynamic_columns",
"or",
"{",
"}",
"for",
"name",
",",
"col",
"in",
"self",
".",
"_columns",
".",
"items",
"(",
")",
":",
"values",
"[",
"name",
"]",
"=",
"col",
".",
"to_databa... | Returns a map of column names to cleaned values | [
"Returns",
"a",
"map",
"of",
"column",
"names",
"to",
"cleaned",
"values"
] | 30a80d0b798b1f45f8cb77163b1fa791f3e3ca29 | https://github.com/datastax/python-driver/blob/30a80d0b798b1f45f8cb77163b1fa791f3e3ca29/cassandra/cqlengine/models.py#L653-L658 |
229,131 | datastax/python-driver | cassandra/cqlengine/models.py | BaseModel.create | def create(cls, **kwargs):
"""
Create an instance of this model in the database.
Takes the model column values as keyword arguments. Setting a value to
`None` is equivalent to running a CQL `DELETE` on that column.
Returns the instance.
"""
extra_columns = set(kwargs.keys()) - set(cls._columns.keys())
if extra_columns:
raise ValidationError("Incorrect columns passed: {0}".format(extra_columns))
return cls.objects.create(**kwargs) | python | def create(cls, **kwargs):
extra_columns = set(kwargs.keys()) - set(cls._columns.keys())
if extra_columns:
raise ValidationError("Incorrect columns passed: {0}".format(extra_columns))
return cls.objects.create(**kwargs) | [
"def",
"create",
"(",
"cls",
",",
"*",
"*",
"kwargs",
")",
":",
"extra_columns",
"=",
"set",
"(",
"kwargs",
".",
"keys",
"(",
")",
")",
"-",
"set",
"(",
"cls",
".",
"_columns",
".",
"keys",
"(",
")",
")",
"if",
"extra_columns",
":",
"raise",
"Val... | Create an instance of this model in the database.
Takes the model column values as keyword arguments. Setting a value to
`None` is equivalent to running a CQL `DELETE` on that column.
Returns the instance. | [
"Create",
"an",
"instance",
"of",
"this",
"model",
"in",
"the",
"database",
"."
] | 30a80d0b798b1f45f8cb77163b1fa791f3e3ca29 | https://github.com/datastax/python-driver/blob/30a80d0b798b1f45f8cb77163b1fa791f3e3ca29/cassandra/cqlengine/models.py#L661-L673 |
229,132 | datastax/python-driver | cassandra/cqlengine/models.py | BaseModel.save | def save(self):
"""
Saves an object to the database.
.. code-block:: python
#create a person instance
person = Person(first_name='Kimberly', last_name='Eggleston')
#saves it to Cassandra
person.save()
"""
# handle polymorphic models
if self._is_polymorphic:
if self._is_polymorphic_base:
raise PolymorphicModelException('cannot save polymorphic base model')
else:
setattr(self, self._discriminator_column_name, self.__discriminator_value__)
self.validate()
self.__dmlquery__(self.__class__, self,
batch=self._batch,
ttl=self._ttl,
timestamp=self._timestamp,
consistency=self.__consistency__,
if_not_exists=self._if_not_exists,
conditional=self._conditional,
timeout=self._timeout,
if_exists=self._if_exists).save()
self._set_persisted()
self._timestamp = None
return self | python | def save(self):
# handle polymorphic models
if self._is_polymorphic:
if self._is_polymorphic_base:
raise PolymorphicModelException('cannot save polymorphic base model')
else:
setattr(self, self._discriminator_column_name, self.__discriminator_value__)
self.validate()
self.__dmlquery__(self.__class__, self,
batch=self._batch,
ttl=self._ttl,
timestamp=self._timestamp,
consistency=self.__consistency__,
if_not_exists=self._if_not_exists,
conditional=self._conditional,
timeout=self._timeout,
if_exists=self._if_exists).save()
self._set_persisted()
self._timestamp = None
return self | [
"def",
"save",
"(",
"self",
")",
":",
"# handle polymorphic models",
"if",
"self",
".",
"_is_polymorphic",
":",
"if",
"self",
".",
"_is_polymorphic_base",
":",
"raise",
"PolymorphicModelException",
"(",
"'cannot save polymorphic base model'",
")",
"else",
":",
"setatt... | Saves an object to the database.
.. code-block:: python
#create a person instance
person = Person(first_name='Kimberly', last_name='Eggleston')
#saves it to Cassandra
person.save() | [
"Saves",
"an",
"object",
"to",
"the",
"database",
"."
] | 30a80d0b798b1f45f8cb77163b1fa791f3e3ca29 | https://github.com/datastax/python-driver/blob/30a80d0b798b1f45f8cb77163b1fa791f3e3ca29/cassandra/cqlengine/models.py#L711-L745 |
229,133 | datastax/python-driver | cassandra/cqlengine/models.py | BaseModel.update | def update(self, **values):
"""
Performs an update on the model instance. You can pass in values to set on the model
for updating, or you can call without values to execute an update against any modified
fields. If no fields on the model have been modified since loading, no query will be
performed. Model validation is performed normally. Setting a value to `None` is
equivalent to running a CQL `DELETE` on that column.
It is possible to do a blind update, that is, to update a field without having first selected the object out of the database.
See :ref:`Blind Updates <blind_updates>`
"""
for column_id, v in values.items():
col = self._columns.get(column_id)
# check for nonexistant columns
if col is None:
raise ValidationError(
"{0}.{1} has no column named: {2}".format(
self.__module__, self.__class__.__name__, column_id))
# check for primary key update attempts
if col.is_primary_key:
current_value = getattr(self, column_id)
if v != current_value:
raise ValidationError(
"Cannot apply update to primary key '{0}' for {1}.{2}".format(
column_id, self.__module__, self.__class__.__name__))
setattr(self, column_id, v)
# handle polymorphic models
if self._is_polymorphic:
if self._is_polymorphic_base:
raise PolymorphicModelException('cannot update polymorphic base model')
else:
setattr(self, self._discriminator_column_name, self.__discriminator_value__)
self.validate()
self.__dmlquery__(self.__class__, self,
batch=self._batch,
ttl=self._ttl,
timestamp=self._timestamp,
consistency=self.__consistency__,
conditional=self._conditional,
timeout=self._timeout,
if_exists=self._if_exists).update()
self._set_persisted()
self._timestamp = None
return self | python | def update(self, **values):
for column_id, v in values.items():
col = self._columns.get(column_id)
# check for nonexistant columns
if col is None:
raise ValidationError(
"{0}.{1} has no column named: {2}".format(
self.__module__, self.__class__.__name__, column_id))
# check for primary key update attempts
if col.is_primary_key:
current_value = getattr(self, column_id)
if v != current_value:
raise ValidationError(
"Cannot apply update to primary key '{0}' for {1}.{2}".format(
column_id, self.__module__, self.__class__.__name__))
setattr(self, column_id, v)
# handle polymorphic models
if self._is_polymorphic:
if self._is_polymorphic_base:
raise PolymorphicModelException('cannot update polymorphic base model')
else:
setattr(self, self._discriminator_column_name, self.__discriminator_value__)
self.validate()
self.__dmlquery__(self.__class__, self,
batch=self._batch,
ttl=self._ttl,
timestamp=self._timestamp,
consistency=self.__consistency__,
conditional=self._conditional,
timeout=self._timeout,
if_exists=self._if_exists).update()
self._set_persisted()
self._timestamp = None
return self | [
"def",
"update",
"(",
"self",
",",
"*",
"*",
"values",
")",
":",
"for",
"column_id",
",",
"v",
"in",
"values",
".",
"items",
"(",
")",
":",
"col",
"=",
"self",
".",
"_columns",
".",
"get",
"(",
"column_id",
")",
"# check for nonexistant columns",
"if",... | Performs an update on the model instance. You can pass in values to set on the model
for updating, or you can call without values to execute an update against any modified
fields. If no fields on the model have been modified since loading, no query will be
performed. Model validation is performed normally. Setting a value to `None` is
equivalent to running a CQL `DELETE` on that column.
It is possible to do a blind update, that is, to update a field without having first selected the object out of the database.
See :ref:`Blind Updates <blind_updates>` | [
"Performs",
"an",
"update",
"on",
"the",
"model",
"instance",
".",
"You",
"can",
"pass",
"in",
"values",
"to",
"set",
"on",
"the",
"model",
"for",
"updating",
"or",
"you",
"can",
"call",
"without",
"values",
"to",
"execute",
"an",
"update",
"against",
"a... | 30a80d0b798b1f45f8cb77163b1fa791f3e3ca29 | https://github.com/datastax/python-driver/blob/30a80d0b798b1f45f8cb77163b1fa791f3e3ca29/cassandra/cqlengine/models.py#L747-L798 |
229,134 | datastax/python-driver | cassandra/cqlengine/models.py | BaseModel.delete | def delete(self):
"""
Deletes the object from the database
"""
self.__dmlquery__(self.__class__, self,
batch=self._batch,
timestamp=self._timestamp,
consistency=self.__consistency__,
timeout=self._timeout,
conditional=self._conditional,
if_exists=self._if_exists).delete() | python | def delete(self):
self.__dmlquery__(self.__class__, self,
batch=self._batch,
timestamp=self._timestamp,
consistency=self.__consistency__,
timeout=self._timeout,
conditional=self._conditional,
if_exists=self._if_exists).delete() | [
"def",
"delete",
"(",
"self",
")",
":",
"self",
".",
"__dmlquery__",
"(",
"self",
".",
"__class__",
",",
"self",
",",
"batch",
"=",
"self",
".",
"_batch",
",",
"timestamp",
"=",
"self",
".",
"_timestamp",
",",
"consistency",
"=",
"self",
".",
"__consis... | Deletes the object from the database | [
"Deletes",
"the",
"object",
"from",
"the",
"database"
] | 30a80d0b798b1f45f8cb77163b1fa791f3e3ca29 | https://github.com/datastax/python-driver/blob/30a80d0b798b1f45f8cb77163b1fa791f3e3ca29/cassandra/cqlengine/models.py#L800-L810 |
229,135 | datastax/python-driver | cassandra/cqlengine/models.py | BaseModel.get_changed_columns | def get_changed_columns(self):
"""
Returns a list of the columns that have been updated since instantiation or save
"""
return [k for k, v in self._values.items() if v.changed] | python | def get_changed_columns(self):
return [k for k, v in self._values.items() if v.changed] | [
"def",
"get_changed_columns",
"(",
"self",
")",
":",
"return",
"[",
"k",
"for",
"k",
",",
"v",
"in",
"self",
".",
"_values",
".",
"items",
"(",
")",
"if",
"v",
".",
"changed",
"]"
] | Returns a list of the columns that have been updated since instantiation or save | [
"Returns",
"a",
"list",
"of",
"the",
"columns",
"that",
"have",
"been",
"updated",
"since",
"instantiation",
"or",
"save"
] | 30a80d0b798b1f45f8cb77163b1fa791f3e3ca29 | https://github.com/datastax/python-driver/blob/30a80d0b798b1f45f8cb77163b1fa791f3e3ca29/cassandra/cqlengine/models.py#L812-L816 |
229,136 | datastax/python-driver | cassandra/__init__.py | ProtocolVersion.get_lower_supported | def get_lower_supported(cls, previous_version):
"""
Return the lower supported protocol version. Beta versions are omitted.
"""
try:
version = next(v for v in sorted(ProtocolVersion.SUPPORTED_VERSIONS, reverse=True) if
v not in ProtocolVersion.BETA_VERSIONS and v < previous_version)
except StopIteration:
version = 0
return version | python | def get_lower_supported(cls, previous_version):
try:
version = next(v for v in sorted(ProtocolVersion.SUPPORTED_VERSIONS, reverse=True) if
v not in ProtocolVersion.BETA_VERSIONS and v < previous_version)
except StopIteration:
version = 0
return version | [
"def",
"get_lower_supported",
"(",
"cls",
",",
"previous_version",
")",
":",
"try",
":",
"version",
"=",
"next",
"(",
"v",
"for",
"v",
"in",
"sorted",
"(",
"ProtocolVersion",
".",
"SUPPORTED_VERSIONS",
",",
"reverse",
"=",
"True",
")",
"if",
"v",
"not",
... | Return the lower supported protocol version. Beta versions are omitted. | [
"Return",
"the",
"lower",
"supported",
"protocol",
"version",
".",
"Beta",
"versions",
"are",
"omitted",
"."
] | 30a80d0b798b1f45f8cb77163b1fa791f3e3ca29 | https://github.com/datastax/python-driver/blob/30a80d0b798b1f45f8cb77163b1fa791f3e3ca29/cassandra/__init__.py#L188-L198 |
229,137 | datastax/python-driver | cassandra/cqlengine/statements.py | BaseClause.update_context | def update_context(self, ctx):
""" updates the query context with this clauses values """
assert isinstance(ctx, dict)
ctx[str(self.context_id)] = self.value | python | def update_context(self, ctx):
assert isinstance(ctx, dict)
ctx[str(self.context_id)] = self.value | [
"def",
"update_context",
"(",
"self",
",",
"ctx",
")",
":",
"assert",
"isinstance",
"(",
"ctx",
",",
"dict",
")",
"ctx",
"[",
"str",
"(",
"self",
".",
"context_id",
")",
"]",
"=",
"self",
".",
"value"
] | updates the query context with this clauses values | [
"updates",
"the",
"query",
"context",
"with",
"this",
"clauses",
"values"
] | 30a80d0b798b1f45f8cb77163b1fa791f3e3ca29 | https://github.com/datastax/python-driver/blob/30a80d0b798b1f45f8cb77163b1fa791f3e3ca29/cassandra/cqlengine/statements.py#L88-L91 |
229,138 | datastax/python-driver | cassandra/connection.py | Connection.get_request_id | def get_request_id(self):
"""
This must be called while self.lock is held.
"""
try:
return self.request_ids.popleft()
except IndexError:
new_request_id = self.highest_request_id + 1
# in_flight checks should guarantee this
assert new_request_id <= self.max_request_id
self.highest_request_id = new_request_id
return self.highest_request_id | python | def get_request_id(self):
try:
return self.request_ids.popleft()
except IndexError:
new_request_id = self.highest_request_id + 1
# in_flight checks should guarantee this
assert new_request_id <= self.max_request_id
self.highest_request_id = new_request_id
return self.highest_request_id | [
"def",
"get_request_id",
"(",
"self",
")",
":",
"try",
":",
"return",
"self",
".",
"request_ids",
".",
"popleft",
"(",
")",
"except",
"IndexError",
":",
"new_request_id",
"=",
"self",
".",
"highest_request_id",
"+",
"1",
"# in_flight checks should guarantee this",... | This must be called while self.lock is held. | [
"This",
"must",
"be",
"called",
"while",
"self",
".",
"lock",
"is",
"held",
"."
] | 30a80d0b798b1f45f8cb77163b1fa791f3e3ca29 | https://github.com/datastax/python-driver/blob/30a80d0b798b1f45f8cb77163b1fa791f3e3ca29/cassandra/connection.py#L583-L594 |
229,139 | datastax/python-driver | cassandra/connection.py | Connection.register_watcher | def register_watcher(self, event_type, callback, register_timeout=None):
"""
Register a callback for a given event type.
"""
self._push_watchers[event_type].add(callback)
self.wait_for_response(
RegisterMessage(event_list=[event_type]),
timeout=register_timeout) | python | def register_watcher(self, event_type, callback, register_timeout=None):
self._push_watchers[event_type].add(callback)
self.wait_for_response(
RegisterMessage(event_list=[event_type]),
timeout=register_timeout) | [
"def",
"register_watcher",
"(",
"self",
",",
"event_type",
",",
"callback",
",",
"register_timeout",
"=",
"None",
")",
":",
"self",
".",
"_push_watchers",
"[",
"event_type",
"]",
".",
"add",
"(",
"callback",
")",
"self",
".",
"wait_for_response",
"(",
"Regis... | Register a callback for a given event type. | [
"Register",
"a",
"callback",
"for",
"a",
"given",
"event",
"type",
"."
] | 30a80d0b798b1f45f8cb77163b1fa791f3e3ca29 | https://github.com/datastax/python-driver/blob/30a80d0b798b1f45f8cb77163b1fa791f3e3ca29/cassandra/connection.py#L667-L674 |
229,140 | datastax/python-driver | cassandra/metadata.py | Metadata.rebuild_token_map | def rebuild_token_map(self, partitioner, token_map):
"""
Rebuild our view of the topology from fresh rows from the
system topology tables.
For internal use only.
"""
self.partitioner = partitioner
if partitioner.endswith('RandomPartitioner'):
token_class = MD5Token
elif partitioner.endswith('Murmur3Partitioner'):
token_class = Murmur3Token
elif partitioner.endswith('ByteOrderedPartitioner'):
token_class = BytesToken
else:
self.token_map = None
return
token_to_host_owner = {}
ring = []
for host, token_strings in six.iteritems(token_map):
for token_string in token_strings:
token = token_class.from_string(token_string)
ring.append(token)
token_to_host_owner[token] = host
all_tokens = sorted(ring)
self.token_map = TokenMap(
token_class, token_to_host_owner, all_tokens, self) | python | def rebuild_token_map(self, partitioner, token_map):
self.partitioner = partitioner
if partitioner.endswith('RandomPartitioner'):
token_class = MD5Token
elif partitioner.endswith('Murmur3Partitioner'):
token_class = Murmur3Token
elif partitioner.endswith('ByteOrderedPartitioner'):
token_class = BytesToken
else:
self.token_map = None
return
token_to_host_owner = {}
ring = []
for host, token_strings in six.iteritems(token_map):
for token_string in token_strings:
token = token_class.from_string(token_string)
ring.append(token)
token_to_host_owner[token] = host
all_tokens = sorted(ring)
self.token_map = TokenMap(
token_class, token_to_host_owner, all_tokens, self) | [
"def",
"rebuild_token_map",
"(",
"self",
",",
"partitioner",
",",
"token_map",
")",
":",
"self",
".",
"partitioner",
"=",
"partitioner",
"if",
"partitioner",
".",
"endswith",
"(",
"'RandomPartitioner'",
")",
":",
"token_class",
"=",
"MD5Token",
"elif",
"partitio... | Rebuild our view of the topology from fresh rows from the
system topology tables.
For internal use only. | [
"Rebuild",
"our",
"view",
"of",
"the",
"topology",
"from",
"fresh",
"rows",
"from",
"the",
"system",
"topology",
"tables",
".",
"For",
"internal",
"use",
"only",
"."
] | 30a80d0b798b1f45f8cb77163b1fa791f3e3ca29 | https://github.com/datastax/python-driver/blob/30a80d0b798b1f45f8cb77163b1fa791f3e3ca29/cassandra/metadata.py#L264-L291 |
229,141 | datastax/python-driver | cassandra/metadata.py | KeyspaceMetadata.export_as_string | def export_as_string(self):
"""
Returns a CQL query string that can be used to recreate the entire keyspace,
including user-defined types and tables.
"""
cql = "\n\n".join([self.as_cql_query() + ';'] +
self.user_type_strings() +
[f.export_as_string() for f in self.functions.values()] +
[a.export_as_string() for a in self.aggregates.values()] +
[t.export_as_string() for t in self.tables.values()])
if self._exc_info:
import traceback
ret = "/*\nWarning: Keyspace %s is incomplete because of an error processing metadata.\n" % \
(self.name)
for line in traceback.format_exception(*self._exc_info):
ret += line
ret += "\nApproximate structure, for reference:\n(this should not be used to reproduce this schema)\n\n%s\n*/" % cql
return ret
if self.virtual:
return ("/*\nWarning: Keyspace {ks} is a virtual keyspace and cannot be recreated with CQL.\n"
"Structure, for reference:*/\n"
"{cql}\n"
"").format(ks=self.name, cql=cql)
return cql | python | def export_as_string(self):
cql = "\n\n".join([self.as_cql_query() + ';'] +
self.user_type_strings() +
[f.export_as_string() for f in self.functions.values()] +
[a.export_as_string() for a in self.aggregates.values()] +
[t.export_as_string() for t in self.tables.values()])
if self._exc_info:
import traceback
ret = "/*\nWarning: Keyspace %s is incomplete because of an error processing metadata.\n" % \
(self.name)
for line in traceback.format_exception(*self._exc_info):
ret += line
ret += "\nApproximate structure, for reference:\n(this should not be used to reproduce this schema)\n\n%s\n*/" % cql
return ret
if self.virtual:
return ("/*\nWarning: Keyspace {ks} is a virtual keyspace and cannot be recreated with CQL.\n"
"Structure, for reference:*/\n"
"{cql}\n"
"").format(ks=self.name, cql=cql)
return cql | [
"def",
"export_as_string",
"(",
"self",
")",
":",
"cql",
"=",
"\"\\n\\n\"",
".",
"join",
"(",
"[",
"self",
".",
"as_cql_query",
"(",
")",
"+",
"';'",
"]",
"+",
"self",
".",
"user_type_strings",
"(",
")",
"+",
"[",
"f",
".",
"export_as_string",
"(",
"... | Returns a CQL query string that can be used to recreate the entire keyspace,
including user-defined types and tables. | [
"Returns",
"a",
"CQL",
"query",
"string",
"that",
"can",
"be",
"used",
"to",
"recreate",
"the",
"entire",
"keyspace",
"including",
"user",
"-",
"defined",
"types",
"and",
"tables",
"."
] | 30a80d0b798b1f45f8cb77163b1fa791f3e3ca29 | https://github.com/datastax/python-driver/blob/30a80d0b798b1f45f8cb77163b1fa791f3e3ca29/cassandra/metadata.py#L677-L700 |
229,142 | datastax/python-driver | cassandra/metadata.py | KeyspaceMetadata.as_cql_query | def as_cql_query(self):
"""
Returns a CQL query string that can be used to recreate just this keyspace,
not including user-defined types and tables.
"""
if self.virtual:
return "// VIRTUAL KEYSPACE {}".format(protect_name(self.name))
ret = "CREATE KEYSPACE %s WITH replication = %s " % (
protect_name(self.name),
self.replication_strategy.export_for_schema())
return ret + (' AND durable_writes = %s' % ("true" if self.durable_writes else "false")) | python | def as_cql_query(self):
if self.virtual:
return "// VIRTUAL KEYSPACE {}".format(protect_name(self.name))
ret = "CREATE KEYSPACE %s WITH replication = %s " % (
protect_name(self.name),
self.replication_strategy.export_for_schema())
return ret + (' AND durable_writes = %s' % ("true" if self.durable_writes else "false")) | [
"def",
"as_cql_query",
"(",
"self",
")",
":",
"if",
"self",
".",
"virtual",
":",
"return",
"\"// VIRTUAL KEYSPACE {}\"",
".",
"format",
"(",
"protect_name",
"(",
"self",
".",
"name",
")",
")",
"ret",
"=",
"\"CREATE KEYSPACE %s WITH replication = %s \"",
"%",
"("... | Returns a CQL query string that can be used to recreate just this keyspace,
not including user-defined types and tables. | [
"Returns",
"a",
"CQL",
"query",
"string",
"that",
"can",
"be",
"used",
"to",
"recreate",
"just",
"this",
"keyspace",
"not",
"including",
"user",
"-",
"defined",
"types",
"and",
"tables",
"."
] | 30a80d0b798b1f45f8cb77163b1fa791f3e3ca29 | https://github.com/datastax/python-driver/blob/30a80d0b798b1f45f8cb77163b1fa791f3e3ca29/cassandra/metadata.py#L702-L712 |
229,143 | datastax/python-driver | cassandra/metadata.py | TableMetadata.is_cql_compatible | def is_cql_compatible(self):
"""
A boolean indicating if this table can be represented as CQL in export
"""
if self.virtual:
return False
comparator = getattr(self, 'comparator', None)
if comparator:
# no compact storage with more than one column beyond PK if there
# are clustering columns
incompatible = (self.is_compact_storage and
len(self.columns) > len(self.primary_key) + 1 and
len(self.clustering_key) >= 1)
return not incompatible
return True | python | def is_cql_compatible(self):
if self.virtual:
return False
comparator = getattr(self, 'comparator', None)
if comparator:
# no compact storage with more than one column beyond PK if there
# are clustering columns
incompatible = (self.is_compact_storage and
len(self.columns) > len(self.primary_key) + 1 and
len(self.clustering_key) >= 1)
return not incompatible
return True | [
"def",
"is_cql_compatible",
"(",
"self",
")",
":",
"if",
"self",
".",
"virtual",
":",
"return",
"False",
"comparator",
"=",
"getattr",
"(",
"self",
",",
"'comparator'",
",",
"None",
")",
"if",
"comparator",
":",
"# no compact storage with more than one column beyo... | A boolean indicating if this table can be represented as CQL in export | [
"A",
"boolean",
"indicating",
"if",
"this",
"table",
"can",
"be",
"represented",
"as",
"CQL",
"in",
"export"
] | 30a80d0b798b1f45f8cb77163b1fa791f3e3ca29 | https://github.com/datastax/python-driver/blob/30a80d0b798b1f45f8cb77163b1fa791f3e3ca29/cassandra/metadata.py#L1105-L1120 |
229,144 | datastax/python-driver | cassandra/metadata.py | TableMetadata.export_as_string | def export_as_string(self):
"""
Returns a string of CQL queries that can be used to recreate this table
along with all indexes on it. The returned string is formatted to
be human readable.
"""
if self._exc_info:
import traceback
ret = "/*\nWarning: Table %s.%s is incomplete because of an error processing metadata.\n" % \
(self.keyspace_name, self.name)
for line in traceback.format_exception(*self._exc_info):
ret += line
ret += "\nApproximate structure, for reference:\n(this should not be used to reproduce this schema)\n\n%s\n*/" % self._all_as_cql()
elif not self.is_cql_compatible:
# If we can't produce this table with CQL, comment inline
ret = "/*\nWarning: Table %s.%s omitted because it has constructs not compatible with CQL (was created via legacy API).\n" % \
(self.keyspace_name, self.name)
ret += "\nApproximate structure, for reference:\n(this should not be used to reproduce this schema)\n\n%s\n*/" % self._all_as_cql()
elif self.virtual:
ret = ('/*\nWarning: Table {ks}.{tab} is a virtual table and cannot be recreated with CQL.\n'
'Structure, for reference:\n'
'{cql}\n*/').format(ks=self.keyspace_name, tab=self.name, cql=self._all_as_cql())
else:
ret = self._all_as_cql()
return ret | python | def export_as_string(self):
if self._exc_info:
import traceback
ret = "/*\nWarning: Table %s.%s is incomplete because of an error processing metadata.\n" % \
(self.keyspace_name, self.name)
for line in traceback.format_exception(*self._exc_info):
ret += line
ret += "\nApproximate structure, for reference:\n(this should not be used to reproduce this schema)\n\n%s\n*/" % self._all_as_cql()
elif not self.is_cql_compatible:
# If we can't produce this table with CQL, comment inline
ret = "/*\nWarning: Table %s.%s omitted because it has constructs not compatible with CQL (was created via legacy API).\n" % \
(self.keyspace_name, self.name)
ret += "\nApproximate structure, for reference:\n(this should not be used to reproduce this schema)\n\n%s\n*/" % self._all_as_cql()
elif self.virtual:
ret = ('/*\nWarning: Table {ks}.{tab} is a virtual table and cannot be recreated with CQL.\n'
'Structure, for reference:\n'
'{cql}\n*/').format(ks=self.keyspace_name, tab=self.name, cql=self._all_as_cql())
else:
ret = self._all_as_cql()
return ret | [
"def",
"export_as_string",
"(",
"self",
")",
":",
"if",
"self",
".",
"_exc_info",
":",
"import",
"traceback",
"ret",
"=",
"\"/*\\nWarning: Table %s.%s is incomplete because of an error processing metadata.\\n\"",
"%",
"(",
"self",
".",
"keyspace_name",
",",
"self",
".",... | Returns a string of CQL queries that can be used to recreate this table
along with all indexes on it. The returned string is formatted to
be human readable. | [
"Returns",
"a",
"string",
"of",
"CQL",
"queries",
"that",
"can",
"be",
"used",
"to",
"recreate",
"this",
"table",
"along",
"with",
"all",
"indexes",
"on",
"it",
".",
"The",
"returned",
"string",
"is",
"formatted",
"to",
"be",
"human",
"readable",
"."
] | 30a80d0b798b1f45f8cb77163b1fa791f3e3ca29 | https://github.com/datastax/python-driver/blob/30a80d0b798b1f45f8cb77163b1fa791f3e3ca29/cassandra/metadata.py#L1140-L1166 |
229,145 | datastax/python-driver | cassandra/metadata.py | IndexMetadata.as_cql_query | def as_cql_query(self):
"""
Returns a CQL query that can be used to recreate this index.
"""
options = dict(self.index_options)
index_target = options.pop("target")
if self.kind != "CUSTOM":
return "CREATE INDEX %s ON %s.%s (%s)" % (
protect_name(self.name),
protect_name(self.keyspace_name),
protect_name(self.table_name),
index_target)
else:
class_name = options.pop("class_name")
ret = "CREATE CUSTOM INDEX %s ON %s.%s (%s) USING '%s'" % (
protect_name(self.name),
protect_name(self.keyspace_name),
protect_name(self.table_name),
index_target,
class_name)
if options:
# PYTHON-1008: `ret` will always be a unicode
opts_cql_encoded = _encoder.cql_encode_all_types(options, as_text_type=True)
ret += " WITH OPTIONS = %s" % opts_cql_encoded
return ret | python | def as_cql_query(self):
options = dict(self.index_options)
index_target = options.pop("target")
if self.kind != "CUSTOM":
return "CREATE INDEX %s ON %s.%s (%s)" % (
protect_name(self.name),
protect_name(self.keyspace_name),
protect_name(self.table_name),
index_target)
else:
class_name = options.pop("class_name")
ret = "CREATE CUSTOM INDEX %s ON %s.%s (%s) USING '%s'" % (
protect_name(self.name),
protect_name(self.keyspace_name),
protect_name(self.table_name),
index_target,
class_name)
if options:
# PYTHON-1008: `ret` will always be a unicode
opts_cql_encoded = _encoder.cql_encode_all_types(options, as_text_type=True)
ret += " WITH OPTIONS = %s" % opts_cql_encoded
return ret | [
"def",
"as_cql_query",
"(",
"self",
")",
":",
"options",
"=",
"dict",
"(",
"self",
".",
"index_options",
")",
"index_target",
"=",
"options",
".",
"pop",
"(",
"\"target\"",
")",
"if",
"self",
".",
"kind",
"!=",
"\"CUSTOM\"",
":",
"return",
"\"CREATE INDEX ... | Returns a CQL query that can be used to recreate this index. | [
"Returns",
"a",
"CQL",
"query",
"that",
"can",
"be",
"used",
"to",
"recreate",
"this",
"index",
"."
] | 30a80d0b798b1f45f8cb77163b1fa791f3e3ca29 | https://github.com/datastax/python-driver/blob/30a80d0b798b1f45f8cb77163b1fa791f3e3ca29/cassandra/metadata.py#L1430-L1454 |
229,146 | datastax/python-driver | cassandra/metadata.py | BytesToken.from_string | def from_string(cls, token_string):
""" `token_string` should be the string representation from the server. """
# unhexlify works fine with unicode input in everythin but pypy3, where it Raises "TypeError: 'str' does not support the buffer interface"
if isinstance(token_string, six.text_type):
token_string = token_string.encode('ascii')
# The BOP stores a hex string
return cls(unhexlify(token_string)) | python | def from_string(cls, token_string):
# unhexlify works fine with unicode input in everythin but pypy3, where it Raises "TypeError: 'str' does not support the buffer interface"
if isinstance(token_string, six.text_type):
token_string = token_string.encode('ascii')
# The BOP stores a hex string
return cls(unhexlify(token_string)) | [
"def",
"from_string",
"(",
"cls",
",",
"token_string",
")",
":",
"# unhexlify works fine with unicode input in everythin but pypy3, where it Raises \"TypeError: 'str' does not support the buffer interface\"",
"if",
"isinstance",
"(",
"token_string",
",",
"six",
".",
"text_type",
")... | `token_string` should be the string representation from the server. | [
"token_string",
"should",
"be",
"the",
"string",
"representation",
"from",
"the",
"server",
"."
] | 30a80d0b798b1f45f8cb77163b1fa791f3e3ca29 | https://github.com/datastax/python-driver/blob/30a80d0b798b1f45f8cb77163b1fa791f3e3ca29/cassandra/metadata.py#L1634-L1640 |
229,147 | datastax/python-driver | cassandra/io/eventletreactor.py | EventletConnection.service_timeouts | def service_timeouts(cls):
"""
cls._timeout_watcher runs in this loop forever.
It is usually waiting for the next timeout on the cls._new_timer Event.
When new timers are added, that event is set so that the watcher can
wake up and possibly set an earlier timeout.
"""
timer_manager = cls._timers
while True:
next_end = timer_manager.service_timeouts()
sleep_time = max(next_end - time.time(), 0) if next_end else 10000
cls._new_timer.wait(sleep_time)
cls._new_timer.clear() | python | def service_timeouts(cls):
timer_manager = cls._timers
while True:
next_end = timer_manager.service_timeouts()
sleep_time = max(next_end - time.time(), 0) if next_end else 10000
cls._new_timer.wait(sleep_time)
cls._new_timer.clear() | [
"def",
"service_timeouts",
"(",
"cls",
")",
":",
"timer_manager",
"=",
"cls",
".",
"_timers",
"while",
"True",
":",
"next_end",
"=",
"timer_manager",
".",
"service_timeouts",
"(",
")",
"sleep_time",
"=",
"max",
"(",
"next_end",
"-",
"time",
".",
"time",
"(... | cls._timeout_watcher runs in this loop forever.
It is usually waiting for the next timeout on the cls._new_timer Event.
When new timers are added, that event is set so that the watcher can
wake up and possibly set an earlier timeout. | [
"cls",
".",
"_timeout_watcher",
"runs",
"in",
"this",
"loop",
"forever",
".",
"It",
"is",
"usually",
"waiting",
"for",
"the",
"next",
"timeout",
"on",
"the",
"cls",
".",
"_new_timer",
"Event",
".",
"When",
"new",
"timers",
"are",
"added",
"that",
"event",
... | 30a80d0b798b1f45f8cb77163b1fa791f3e3ca29 | https://github.com/datastax/python-driver/blob/30a80d0b798b1f45f8cb77163b1fa791f3e3ca29/cassandra/io/eventletreactor.py#L68-L80 |
229,148 | datastax/python-driver | cassandra/policies.py | EC2MultiRegionTranslator.translate | def translate(self, addr):
"""
Reverse DNS the public broadcast_address, then lookup that hostname to get the AWS-resolved IP, which
will point to the private IP address within the same datacenter.
"""
# get family of this address so we translate to the same
family = socket.getaddrinfo(addr, 0, socket.AF_UNSPEC, socket.SOCK_STREAM)[0][0]
host = socket.getfqdn(addr)
for a in socket.getaddrinfo(host, 0, family, socket.SOCK_STREAM):
try:
return a[4][0]
except Exception:
pass
return addr | python | def translate(self, addr):
# get family of this address so we translate to the same
family = socket.getaddrinfo(addr, 0, socket.AF_UNSPEC, socket.SOCK_STREAM)[0][0]
host = socket.getfqdn(addr)
for a in socket.getaddrinfo(host, 0, family, socket.SOCK_STREAM):
try:
return a[4][0]
except Exception:
pass
return addr | [
"def",
"translate",
"(",
"self",
",",
"addr",
")",
":",
"# get family of this address so we translate to the same",
"family",
"=",
"socket",
".",
"getaddrinfo",
"(",
"addr",
",",
"0",
",",
"socket",
".",
"AF_UNSPEC",
",",
"socket",
".",
"SOCK_STREAM",
")",
"[",
... | Reverse DNS the public broadcast_address, then lookup that hostname to get the AWS-resolved IP, which
will point to the private IP address within the same datacenter. | [
"Reverse",
"DNS",
"the",
"public",
"broadcast_address",
"then",
"lookup",
"that",
"hostname",
"to",
"get",
"the",
"AWS",
"-",
"resolved",
"IP",
"which",
"will",
"point",
"to",
"the",
"private",
"IP",
"address",
"within",
"the",
"same",
"datacenter",
"."
] | 30a80d0b798b1f45f8cb77163b1fa791f3e3ca29 | https://github.com/datastax/python-driver/blob/30a80d0b798b1f45f8cb77163b1fa791f3e3ca29/cassandra/policies.py#L998-L1011 |
229,149 | datastax/python-driver | cassandra/encoder.py | Encoder.cql_encode_float | def cql_encode_float(self, val):
"""
Encode floats using repr to preserve precision
"""
if math.isinf(val):
return 'Infinity' if val > 0 else '-Infinity'
elif math.isnan(val):
return 'NaN'
else:
return repr(val) | python | def cql_encode_float(self, val):
if math.isinf(val):
return 'Infinity' if val > 0 else '-Infinity'
elif math.isnan(val):
return 'NaN'
else:
return repr(val) | [
"def",
"cql_encode_float",
"(",
"self",
",",
"val",
")",
":",
"if",
"math",
".",
"isinf",
"(",
"val",
")",
":",
"return",
"'Infinity'",
"if",
"val",
">",
"0",
"else",
"'-Infinity'",
"elif",
"math",
".",
"isnan",
"(",
"val",
")",
":",
"return",
"'NaN'... | Encode floats using repr to preserve precision | [
"Encode",
"floats",
"using",
"repr",
"to",
"preserve",
"precision"
] | 30a80d0b798b1f45f8cb77163b1fa791f3e3ca29 | https://github.com/datastax/python-driver/blob/30a80d0b798b1f45f8cb77163b1fa791f3e3ca29/cassandra/encoder.py#L149-L158 |
229,150 | datastax/python-driver | cassandra/protocol.py | cython_protocol_handler | def cython_protocol_handler(colparser):
"""
Given a column parser to deserialize ResultMessages, return a suitable
Cython-based protocol handler.
There are three Cython-based protocol handlers:
- obj_parser.ListParser
decodes result messages into a list of tuples
- obj_parser.LazyParser
decodes result messages lazily by returning an iterator
- numpy_parser.NumPyParser
decodes result messages into NumPy arrays
The default is to use obj_parser.ListParser
"""
from cassandra.row_parser import make_recv_results_rows
class FastResultMessage(ResultMessage):
"""
Cython version of Result Message that has a faster implementation of
recv_results_row.
"""
# type_codes = ResultMessage.type_codes.copy()
code_to_type = dict((v, k) for k, v in ResultMessage.type_codes.items())
recv_results_rows = classmethod(make_recv_results_rows(colparser))
class CythonProtocolHandler(_ProtocolHandler):
"""
Use FastResultMessage to decode query result message messages.
"""
my_opcodes = _ProtocolHandler.message_types_by_opcode.copy()
my_opcodes[FastResultMessage.opcode] = FastResultMessage
message_types_by_opcode = my_opcodes
col_parser = colparser
return CythonProtocolHandler | python | def cython_protocol_handler(colparser):
from cassandra.row_parser import make_recv_results_rows
class FastResultMessage(ResultMessage):
"""
Cython version of Result Message that has a faster implementation of
recv_results_row.
"""
# type_codes = ResultMessage.type_codes.copy()
code_to_type = dict((v, k) for k, v in ResultMessage.type_codes.items())
recv_results_rows = classmethod(make_recv_results_rows(colparser))
class CythonProtocolHandler(_ProtocolHandler):
"""
Use FastResultMessage to decode query result message messages.
"""
my_opcodes = _ProtocolHandler.message_types_by_opcode.copy()
my_opcodes[FastResultMessage.opcode] = FastResultMessage
message_types_by_opcode = my_opcodes
col_parser = colparser
return CythonProtocolHandler | [
"def",
"cython_protocol_handler",
"(",
"colparser",
")",
":",
"from",
"cassandra",
".",
"row_parser",
"import",
"make_recv_results_rows",
"class",
"FastResultMessage",
"(",
"ResultMessage",
")",
":",
"\"\"\"\n Cython version of Result Message that has a faster implementati... | Given a column parser to deserialize ResultMessages, return a suitable
Cython-based protocol handler.
There are three Cython-based protocol handlers:
- obj_parser.ListParser
decodes result messages into a list of tuples
- obj_parser.LazyParser
decodes result messages lazily by returning an iterator
- numpy_parser.NumPyParser
decodes result messages into NumPy arrays
The default is to use obj_parser.ListParser | [
"Given",
"a",
"column",
"parser",
"to",
"deserialize",
"ResultMessages",
"return",
"a",
"suitable",
"Cython",
"-",
"based",
"protocol",
"handler",
"."
] | 30a80d0b798b1f45f8cb77163b1fa791f3e3ca29 | https://github.com/datastax/python-driver/blob/30a80d0b798b1f45f8cb77163b1fa791f3e3ca29/cassandra/protocol.py#L1161-L1201 |
229,151 | datastax/python-driver | cassandra/protocol.py | _ProtocolHandler.encode_message | def encode_message(cls, msg, stream_id, protocol_version, compressor, allow_beta_protocol_version):
"""
Encodes a message using the specified frame parameters, and compressor
:param msg: the message, typically of cassandra.protocol._MessageType, generated by the driver
:param stream_id: protocol stream id for the frame header
:param protocol_version: version for the frame header, and used encoding contents
:param compressor: optional compression function to be used on the body
"""
flags = 0
body = io.BytesIO()
if msg.custom_payload:
if protocol_version < 4:
raise UnsupportedOperation("Custom key/value payloads can only be used with protocol version 4 or higher")
flags |= CUSTOM_PAYLOAD_FLAG
write_bytesmap(body, msg.custom_payload)
msg.send_body(body, protocol_version)
body = body.getvalue()
if compressor and len(body) > 0:
body = compressor(body)
flags |= COMPRESSED_FLAG
if msg.tracing:
flags |= TRACING_FLAG
if allow_beta_protocol_version:
flags |= USE_BETA_FLAG
buff = io.BytesIO()
cls._write_header(buff, protocol_version, flags, stream_id, msg.opcode, len(body))
buff.write(body)
return buff.getvalue() | python | def encode_message(cls, msg, stream_id, protocol_version, compressor, allow_beta_protocol_version):
flags = 0
body = io.BytesIO()
if msg.custom_payload:
if protocol_version < 4:
raise UnsupportedOperation("Custom key/value payloads can only be used with protocol version 4 or higher")
flags |= CUSTOM_PAYLOAD_FLAG
write_bytesmap(body, msg.custom_payload)
msg.send_body(body, protocol_version)
body = body.getvalue()
if compressor and len(body) > 0:
body = compressor(body)
flags |= COMPRESSED_FLAG
if msg.tracing:
flags |= TRACING_FLAG
if allow_beta_protocol_version:
flags |= USE_BETA_FLAG
buff = io.BytesIO()
cls._write_header(buff, protocol_version, flags, stream_id, msg.opcode, len(body))
buff.write(body)
return buff.getvalue() | [
"def",
"encode_message",
"(",
"cls",
",",
"msg",
",",
"stream_id",
",",
"protocol_version",
",",
"compressor",
",",
"allow_beta_protocol_version",
")",
":",
"flags",
"=",
"0",
"body",
"=",
"io",
".",
"BytesIO",
"(",
")",
"if",
"msg",
".",
"custom_payload",
... | Encodes a message using the specified frame parameters, and compressor
:param msg: the message, typically of cassandra.protocol._MessageType, generated by the driver
:param stream_id: protocol stream id for the frame header
:param protocol_version: version for the frame header, and used encoding contents
:param compressor: optional compression function to be used on the body | [
"Encodes",
"a",
"message",
"using",
"the",
"specified",
"frame",
"parameters",
"and",
"compressor"
] | 30a80d0b798b1f45f8cb77163b1fa791f3e3ca29 | https://github.com/datastax/python-driver/blob/30a80d0b798b1f45f8cb77163b1fa791f3e3ca29/cassandra/protocol.py#L1059-L1092 |
229,152 | datastax/python-driver | cassandra/protocol.py | _ProtocolHandler._write_header | def _write_header(f, version, flags, stream_id, opcode, length):
"""
Write a CQL protocol frame header.
"""
pack = v3_header_pack if version >= 3 else header_pack
f.write(pack(version, flags, stream_id, opcode))
write_int(f, length) | python | def _write_header(f, version, flags, stream_id, opcode, length):
pack = v3_header_pack if version >= 3 else header_pack
f.write(pack(version, flags, stream_id, opcode))
write_int(f, length) | [
"def",
"_write_header",
"(",
"f",
",",
"version",
",",
"flags",
",",
"stream_id",
",",
"opcode",
",",
"length",
")",
":",
"pack",
"=",
"v3_header_pack",
"if",
"version",
">=",
"3",
"else",
"header_pack",
"f",
".",
"write",
"(",
"pack",
"(",
"version",
... | Write a CQL protocol frame header. | [
"Write",
"a",
"CQL",
"protocol",
"frame",
"header",
"."
] | 30a80d0b798b1f45f8cb77163b1fa791f3e3ca29 | https://github.com/datastax/python-driver/blob/30a80d0b798b1f45f8cb77163b1fa791f3e3ca29/cassandra/protocol.py#L1095-L1101 |
229,153 | datastax/python-driver | cassandra/protocol.py | _ProtocolHandler.decode_message | def decode_message(cls, protocol_version, user_type_map, stream_id, flags, opcode, body,
decompressor, result_metadata):
"""
Decodes a native protocol message body
:param protocol_version: version to use decoding contents
:param user_type_map: map[keyspace name] = map[type name] = custom type to instantiate when deserializing this type
:param stream_id: native protocol stream id from the frame header
:param flags: native protocol flags bitmap from the header
:param opcode: native protocol opcode from the header
:param body: frame body
:param decompressor: optional decompression function to inflate the body
:return: a message decoded from the body and frame attributes
"""
if flags & COMPRESSED_FLAG:
if decompressor is None:
raise RuntimeError("No de-compressor available for compressed frame!")
body = decompressor(body)
flags ^= COMPRESSED_FLAG
body = io.BytesIO(body)
if flags & TRACING_FLAG:
trace_id = UUID(bytes=body.read(16))
flags ^= TRACING_FLAG
else:
trace_id = None
if flags & WARNING_FLAG:
warnings = read_stringlist(body)
flags ^= WARNING_FLAG
else:
warnings = None
if flags & CUSTOM_PAYLOAD_FLAG:
custom_payload = read_bytesmap(body)
flags ^= CUSTOM_PAYLOAD_FLAG
else:
custom_payload = None
flags &= USE_BETA_MASK # will only be set if we asserted it in connection estabishment
if flags:
log.warning("Unknown protocol flags set: %02x. May cause problems.", flags)
msg_class = cls.message_types_by_opcode[opcode]
msg = msg_class.recv_body(body, protocol_version, user_type_map, result_metadata)
msg.stream_id = stream_id
msg.trace_id = trace_id
msg.custom_payload = custom_payload
msg.warnings = warnings
if msg.warnings:
for w in msg.warnings:
log.warning("Server warning: %s", w)
return msg | python | def decode_message(cls, protocol_version, user_type_map, stream_id, flags, opcode, body,
decompressor, result_metadata):
if flags & COMPRESSED_FLAG:
if decompressor is None:
raise RuntimeError("No de-compressor available for compressed frame!")
body = decompressor(body)
flags ^= COMPRESSED_FLAG
body = io.BytesIO(body)
if flags & TRACING_FLAG:
trace_id = UUID(bytes=body.read(16))
flags ^= TRACING_FLAG
else:
trace_id = None
if flags & WARNING_FLAG:
warnings = read_stringlist(body)
flags ^= WARNING_FLAG
else:
warnings = None
if flags & CUSTOM_PAYLOAD_FLAG:
custom_payload = read_bytesmap(body)
flags ^= CUSTOM_PAYLOAD_FLAG
else:
custom_payload = None
flags &= USE_BETA_MASK # will only be set if we asserted it in connection estabishment
if flags:
log.warning("Unknown protocol flags set: %02x. May cause problems.", flags)
msg_class = cls.message_types_by_opcode[opcode]
msg = msg_class.recv_body(body, protocol_version, user_type_map, result_metadata)
msg.stream_id = stream_id
msg.trace_id = trace_id
msg.custom_payload = custom_payload
msg.warnings = warnings
if msg.warnings:
for w in msg.warnings:
log.warning("Server warning: %s", w)
return msg | [
"def",
"decode_message",
"(",
"cls",
",",
"protocol_version",
",",
"user_type_map",
",",
"stream_id",
",",
"flags",
",",
"opcode",
",",
"body",
",",
"decompressor",
",",
"result_metadata",
")",
":",
"if",
"flags",
"&",
"COMPRESSED_FLAG",
":",
"if",
"decompress... | Decodes a native protocol message body
:param protocol_version: version to use decoding contents
:param user_type_map: map[keyspace name] = map[type name] = custom type to instantiate when deserializing this type
:param stream_id: native protocol stream id from the frame header
:param flags: native protocol flags bitmap from the header
:param opcode: native protocol opcode from the header
:param body: frame body
:param decompressor: optional decompression function to inflate the body
:return: a message decoded from the body and frame attributes | [
"Decodes",
"a",
"native",
"protocol",
"message",
"body"
] | 30a80d0b798b1f45f8cb77163b1fa791f3e3ca29 | https://github.com/datastax/python-driver/blob/30a80d0b798b1f45f8cb77163b1fa791f3e3ca29/cassandra/protocol.py#L1104-L1159 |
229,154 | datastax/python-driver | cassandra/cqlengine/connection.py | format_log_context | def format_log_context(msg, connection=None, keyspace=None):
"""Format log message to add keyspace and connection context"""
connection_info = connection or 'DEFAULT_CONNECTION'
if keyspace:
msg = '[Connection: {0}, Keyspace: {1}] {2}'.format(connection_info, keyspace, msg)
else:
msg = '[Connection: {0}] {1}'.format(connection_info, msg)
return msg | python | def format_log_context(msg, connection=None, keyspace=None):
connection_info = connection or 'DEFAULT_CONNECTION'
if keyspace:
msg = '[Connection: {0}, Keyspace: {1}] {2}'.format(connection_info, keyspace, msg)
else:
msg = '[Connection: {0}] {1}'.format(connection_info, msg)
return msg | [
"def",
"format_log_context",
"(",
"msg",
",",
"connection",
"=",
"None",
",",
"keyspace",
"=",
"None",
")",
":",
"connection_info",
"=",
"connection",
"or",
"'DEFAULT_CONNECTION'",
"if",
"keyspace",
":",
"msg",
"=",
"'[Connection: {0}, Keyspace: {1}] {2}'",
".",
"... | Format log message to add keyspace and connection context | [
"Format",
"log",
"message",
"to",
"add",
"keyspace",
"and",
"connection",
"context"
] | 30a80d0b798b1f45f8cb77163b1fa791f3e3ca29 | https://github.com/datastax/python-driver/blob/30a80d0b798b1f45f8cb77163b1fa791f3e3ca29/cassandra/cqlengine/connection.py#L44-L52 |
229,155 | datastax/python-driver | cassandra/cqlengine/connection.py | setup | def setup(
hosts,
default_keyspace,
consistency=None,
lazy_connect=False,
retry_connect=False,
**kwargs):
"""
Setup a the driver connection used by the mapper
:param list hosts: list of hosts, (``contact_points`` for :class:`cassandra.cluster.Cluster`)
:param str default_keyspace: The default keyspace to use
:param int consistency: The global default :class:`~.ConsistencyLevel` - default is the same as :attr:`.Session.default_consistency_level`
:param bool lazy_connect: True if should not connect until first use
:param bool retry_connect: True if we should retry to connect even if there was a connection failure initially
:param \*\*kwargs: Pass-through keyword arguments for :class:`cassandra.cluster.Cluster`
"""
from cassandra.cqlengine import models
models.DEFAULT_KEYSPACE = default_keyspace
register_connection('default', hosts=hosts, consistency=consistency, lazy_connect=lazy_connect,
retry_connect=retry_connect, cluster_options=kwargs, default=True) | python | def setup(
hosts,
default_keyspace,
consistency=None,
lazy_connect=False,
retry_connect=False,
**kwargs):
from cassandra.cqlengine import models
models.DEFAULT_KEYSPACE = default_keyspace
register_connection('default', hosts=hosts, consistency=consistency, lazy_connect=lazy_connect,
retry_connect=retry_connect, cluster_options=kwargs, default=True) | [
"def",
"setup",
"(",
"hosts",
",",
"default_keyspace",
",",
"consistency",
"=",
"None",
",",
"lazy_connect",
"=",
"False",
",",
"retry_connect",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
"cassandra",
".",
"cqlengine",
"import",
"models",
"mo... | Setup a the driver connection used by the mapper
:param list hosts: list of hosts, (``contact_points`` for :class:`cassandra.cluster.Cluster`)
:param str default_keyspace: The default keyspace to use
:param int consistency: The global default :class:`~.ConsistencyLevel` - default is the same as :attr:`.Session.default_consistency_level`
:param bool lazy_connect: True if should not connect until first use
:param bool retry_connect: True if we should retry to connect even if there was a connection failure initially
:param \*\*kwargs: Pass-through keyword arguments for :class:`cassandra.cluster.Cluster` | [
"Setup",
"a",
"the",
"driver",
"connection",
"used",
"by",
"the",
"mapper"
] | 30a80d0b798b1f45f8cb77163b1fa791f3e3ca29 | https://github.com/datastax/python-driver/blob/30a80d0b798b1f45f8cb77163b1fa791f3e3ca29/cassandra/cqlengine/connection.py#L299-L321 |
229,156 | datastax/python-driver | cassandra/cqlengine/connection.py | Connection.setup | def setup(self):
"""Setup the connection"""
global cluster, session
if 'username' in self.cluster_options or 'password' in self.cluster_options:
raise CQLEngineException("Username & Password are now handled by using the native driver's auth_provider")
if self.lazy_connect:
return
self.cluster = Cluster(self.hosts, **self.cluster_options)
try:
self.session = self.cluster.connect()
log.debug(format_log_context("connection initialized with internally created session", connection=self.name))
except NoHostAvailable:
if self.retry_connect:
log.warning(format_log_context("connect failed, setting up for re-attempt on first use", connection=self.name))
self.lazy_connect = True
raise
if self.consistency is not None:
self.session.default_consistency_level = self.consistency
if DEFAULT_CONNECTION in _connections and _connections[DEFAULT_CONNECTION] == self:
cluster = _connections[DEFAULT_CONNECTION].cluster
session = _connections[DEFAULT_CONNECTION].session
self.setup_session() | python | def setup(self):
global cluster, session
if 'username' in self.cluster_options or 'password' in self.cluster_options:
raise CQLEngineException("Username & Password are now handled by using the native driver's auth_provider")
if self.lazy_connect:
return
self.cluster = Cluster(self.hosts, **self.cluster_options)
try:
self.session = self.cluster.connect()
log.debug(format_log_context("connection initialized with internally created session", connection=self.name))
except NoHostAvailable:
if self.retry_connect:
log.warning(format_log_context("connect failed, setting up for re-attempt on first use", connection=self.name))
self.lazy_connect = True
raise
if self.consistency is not None:
self.session.default_consistency_level = self.consistency
if DEFAULT_CONNECTION in _connections and _connections[DEFAULT_CONNECTION] == self:
cluster = _connections[DEFAULT_CONNECTION].cluster
session = _connections[DEFAULT_CONNECTION].session
self.setup_session() | [
"def",
"setup",
"(",
"self",
")",
":",
"global",
"cluster",
",",
"session",
"if",
"'username'",
"in",
"self",
".",
"cluster_options",
"or",
"'password'",
"in",
"self",
".",
"cluster_options",
":",
"raise",
"CQLEngineException",
"(",
"\"Username & Password are now ... | Setup the connection | [
"Setup",
"the",
"connection"
] | 30a80d0b798b1f45f8cb77163b1fa791f3e3ca29 | https://github.com/datastax/python-driver/blob/30a80d0b798b1f45f8cb77163b1fa791f3e3ca29/cassandra/cqlengine/connection.py#L91-L118 |
229,157 | datastax/python-driver | cassandra/cluster.py | run_in_executor | def run_in_executor(f):
"""
A decorator to run the given method in the ThreadPoolExecutor.
"""
@wraps(f)
def new_f(self, *args, **kwargs):
if self.is_shutdown:
return
try:
future = self.executor.submit(f, self, *args, **kwargs)
future.add_done_callback(_future_completed)
except Exception:
log.exception("Failed to submit task to executor")
return new_f | python | def run_in_executor(f):
@wraps(f)
def new_f(self, *args, **kwargs):
if self.is_shutdown:
return
try:
future = self.executor.submit(f, self, *args, **kwargs)
future.add_done_callback(_future_completed)
except Exception:
log.exception("Failed to submit task to executor")
return new_f | [
"def",
"run_in_executor",
"(",
"f",
")",
":",
"@",
"wraps",
"(",
"f",
")",
"def",
"new_f",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"is_shutdown",
":",
"return",
"try",
":",
"future",
"=",
"self",
".",
... | A decorator to run the given method in the ThreadPoolExecutor. | [
"A",
"decorator",
"to",
"run",
"the",
"given",
"method",
"in",
"the",
"ThreadPoolExecutor",
"."
] | 30a80d0b798b1f45f8cb77163b1fa791f3e3ca29 | https://github.com/datastax/python-driver/blob/30a80d0b798b1f45f8cb77163b1fa791f3e3ca29/cassandra/cluster.py#L152-L168 |
229,158 | datastax/python-driver | cassandra/cluster.py | _watch_callback | def _watch_callback(obj_weakref, method_name, *args, **kwargs):
"""
A callback handler for the ControlConnection that tolerates
weak references.
"""
obj = obj_weakref()
if obj is None:
return
getattr(obj, method_name)(*args, **kwargs) | python | def _watch_callback(obj_weakref, method_name, *args, **kwargs):
obj = obj_weakref()
if obj is None:
return
getattr(obj, method_name)(*args, **kwargs) | [
"def",
"_watch_callback",
"(",
"obj_weakref",
",",
"method_name",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"obj",
"=",
"obj_weakref",
"(",
")",
"if",
"obj",
"is",
"None",
":",
"return",
"getattr",
"(",
"obj",
",",
"method_name",
")",
"(",
... | A callback handler for the ControlConnection that tolerates
weak references. | [
"A",
"callback",
"handler",
"for",
"the",
"ControlConnection",
"that",
"tolerates",
"weak",
"references",
"."
] | 30a80d0b798b1f45f8cb77163b1fa791f3e3ca29 | https://github.com/datastax/python-driver/blob/30a80d0b798b1f45f8cb77163b1fa791f3e3ca29/cassandra/cluster.py#L2804-L2812 |
229,159 | datastax/python-driver | cassandra/cluster.py | Cluster.register_user_type | def register_user_type(self, keyspace, user_type, klass):
"""
Registers a class to use to represent a particular user-defined type.
Query parameters for this user-defined type will be assumed to be
instances of `klass`. Result sets for this user-defined type will
be instances of `klass`. If no class is registered for a user-defined
type, a namedtuple will be used for result sets, and non-prepared
statements may not encode parameters for this type correctly.
`keyspace` is the name of the keyspace that the UDT is defined in.
`user_type` is the string name of the UDT to register the mapping
for.
`klass` should be a class with attributes whose names match the
fields of the user-defined type. The constructor must accepts kwargs
for each of the fields in the UDT.
This method should only be called after the type has been created
within Cassandra.
Example::
cluster = Cluster(protocol_version=3)
session = cluster.connect()
session.set_keyspace('mykeyspace')
session.execute("CREATE TYPE address (street text, zipcode int)")
session.execute("CREATE TABLE users (id int PRIMARY KEY, location address)")
# create a class to map to the "address" UDT
class Address(object):
def __init__(self, street, zipcode):
self.street = street
self.zipcode = zipcode
cluster.register_user_type('mykeyspace', 'address', Address)
# insert a row using an instance of Address
session.execute("INSERT INTO users (id, location) VALUES (%s, %s)",
(0, Address("123 Main St.", 78723)))
# results will include Address instances
results = session.execute("SELECT * FROM users")
row = results[0]
print row.id, row.location.street, row.location.zipcode
"""
if self.protocol_version < 3:
log.warning("User Type serialization is only supported in native protocol version 3+ (%d in use). "
"CQL encoding for simple statements will still work, but named tuples will "
"be returned when reading type %s.%s.", self.protocol_version, keyspace, user_type)
self._user_types[keyspace][user_type] = klass
for session in tuple(self.sessions):
session.user_type_registered(keyspace, user_type, klass)
UserType.evict_udt_class(keyspace, user_type) | python | def register_user_type(self, keyspace, user_type, klass):
if self.protocol_version < 3:
log.warning("User Type serialization is only supported in native protocol version 3+ (%d in use). "
"CQL encoding for simple statements will still work, but named tuples will "
"be returned when reading type %s.%s.", self.protocol_version, keyspace, user_type)
self._user_types[keyspace][user_type] = klass
for session in tuple(self.sessions):
session.user_type_registered(keyspace, user_type, klass)
UserType.evict_udt_class(keyspace, user_type) | [
"def",
"register_user_type",
"(",
"self",
",",
"keyspace",
",",
"user_type",
",",
"klass",
")",
":",
"if",
"self",
".",
"protocol_version",
"<",
"3",
":",
"log",
".",
"warning",
"(",
"\"User Type serialization is only supported in native protocol version 3+ (%d in use).... | Registers a class to use to represent a particular user-defined type.
Query parameters for this user-defined type will be assumed to be
instances of `klass`. Result sets for this user-defined type will
be instances of `klass`. If no class is registered for a user-defined
type, a namedtuple will be used for result sets, and non-prepared
statements may not encode parameters for this type correctly.
`keyspace` is the name of the keyspace that the UDT is defined in.
`user_type` is the string name of the UDT to register the mapping
for.
`klass` should be a class with attributes whose names match the
fields of the user-defined type. The constructor must accepts kwargs
for each of the fields in the UDT.
This method should only be called after the type has been created
within Cassandra.
Example::
cluster = Cluster(protocol_version=3)
session = cluster.connect()
session.set_keyspace('mykeyspace')
session.execute("CREATE TYPE address (street text, zipcode int)")
session.execute("CREATE TABLE users (id int PRIMARY KEY, location address)")
# create a class to map to the "address" UDT
class Address(object):
def __init__(self, street, zipcode):
self.street = street
self.zipcode = zipcode
cluster.register_user_type('mykeyspace', 'address', Address)
# insert a row using an instance of Address
session.execute("INSERT INTO users (id, location) VALUES (%s, %s)",
(0, Address("123 Main St.", 78723)))
# results will include Address instances
results = session.execute("SELECT * FROM users")
row = results[0]
print row.id, row.location.street, row.location.zipcode | [
"Registers",
"a",
"class",
"to",
"use",
"to",
"represent",
"a",
"particular",
"user",
"-",
"defined",
"type",
".",
"Query",
"parameters",
"for",
"this",
"user",
"-",
"defined",
"type",
"will",
"be",
"assumed",
"to",
"be",
"instances",
"of",
"klass",
".",
... | 30a80d0b798b1f45f8cb77163b1fa791f3e3ca29 | https://github.com/datastax/python-driver/blob/30a80d0b798b1f45f8cb77163b1fa791f3e3ca29/cassandra/cluster.py#L1069-L1125 |
229,160 | datastax/python-driver | cassandra/cluster.py | Cluster.connection_factory | def connection_factory(self, endpoint, *args, **kwargs):
"""
Called to create a new connection with proper configuration.
Intended for internal use only.
"""
kwargs = self._make_connection_kwargs(endpoint, kwargs)
return self.connection_class.factory(endpoint, self.connect_timeout, *args, **kwargs) | python | def connection_factory(self, endpoint, *args, **kwargs):
kwargs = self._make_connection_kwargs(endpoint, kwargs)
return self.connection_class.factory(endpoint, self.connect_timeout, *args, **kwargs) | [
"def",
"connection_factory",
"(",
"self",
",",
"endpoint",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"=",
"self",
".",
"_make_connection_kwargs",
"(",
"endpoint",
",",
"kwargs",
")",
"return",
"self",
".",
"connection_class",
".",
"fac... | Called to create a new connection with proper configuration.
Intended for internal use only. | [
"Called",
"to",
"create",
"a",
"new",
"connection",
"with",
"proper",
"configuration",
".",
"Intended",
"for",
"internal",
"use",
"only",
"."
] | 30a80d0b798b1f45f8cb77163b1fa791f3e3ca29 | https://github.com/datastax/python-driver/blob/30a80d0b798b1f45f8cb77163b1fa791f3e3ca29/cassandra/cluster.py#L1283-L1289 |
229,161 | datastax/python-driver | cassandra/cluster.py | Cluster.add_host | def add_host(self, endpoint, datacenter=None, rack=None, signal=True, refresh_nodes=True):
"""
Called when adding initial contact points and when the control
connection subsequently discovers a new node.
Returns a Host instance, and a flag indicating whether it was new in
the metadata.
Intended for internal use only.
"""
host, new = self.metadata.add_or_return_host(Host(endpoint, self.conviction_policy_factory, datacenter, rack))
if new and signal:
log.info("New Cassandra host %r discovered", host)
self.on_add(host, refresh_nodes)
return host, new | python | def add_host(self, endpoint, datacenter=None, rack=None, signal=True, refresh_nodes=True):
host, new = self.metadata.add_or_return_host(Host(endpoint, self.conviction_policy_factory, datacenter, rack))
if new and signal:
log.info("New Cassandra host %r discovered", host)
self.on_add(host, refresh_nodes)
return host, new | [
"def",
"add_host",
"(",
"self",
",",
"endpoint",
",",
"datacenter",
"=",
"None",
",",
"rack",
"=",
"None",
",",
"signal",
"=",
"True",
",",
"refresh_nodes",
"=",
"True",
")",
":",
"host",
",",
"new",
"=",
"self",
".",
"metadata",
".",
"add_or_return_ho... | Called when adding initial contact points and when the control
connection subsequently discovers a new node.
Returns a Host instance, and a flag indicating whether it was new in
the metadata.
Intended for internal use only. | [
"Called",
"when",
"adding",
"initial",
"contact",
"points",
"and",
"when",
"the",
"control",
"connection",
"subsequently",
"discovers",
"a",
"new",
"node",
".",
"Returns",
"a",
"Host",
"instance",
"and",
"a",
"flag",
"indicating",
"whether",
"it",
"was",
"new"... | 30a80d0b798b1f45f8cb77163b1fa791f3e3ca29 | https://github.com/datastax/python-driver/blob/30a80d0b798b1f45f8cb77163b1fa791f3e3ca29/cassandra/cluster.py#L1706-L1719 |
229,162 | datastax/python-driver | cassandra/cluster.py | Cluster.remove_host | def remove_host(self, host):
"""
Called when the control connection observes that a node has left the
ring. Intended for internal use only.
"""
if host and self.metadata.remove_host(host):
log.info("Cassandra host %s removed", host)
self.on_remove(host) | python | def remove_host(self, host):
if host and self.metadata.remove_host(host):
log.info("Cassandra host %s removed", host)
self.on_remove(host) | [
"def",
"remove_host",
"(",
"self",
",",
"host",
")",
":",
"if",
"host",
"and",
"self",
".",
"metadata",
".",
"remove_host",
"(",
"host",
")",
":",
"log",
".",
"info",
"(",
"\"Cassandra host %s removed\"",
",",
"host",
")",
"self",
".",
"on_remove",
"(",
... | Called when the control connection observes that a node has left the
ring. Intended for internal use only. | [
"Called",
"when",
"the",
"control",
"connection",
"observes",
"that",
"a",
"node",
"has",
"left",
"the",
"ring",
".",
"Intended",
"for",
"internal",
"use",
"only",
"."
] | 30a80d0b798b1f45f8cb77163b1fa791f3e3ca29 | https://github.com/datastax/python-driver/blob/30a80d0b798b1f45f8cb77163b1fa791f3e3ca29/cassandra/cluster.py#L1721-L1728 |
229,163 | datastax/python-driver | cassandra/cluster.py | Cluster._ensure_core_connections | def _ensure_core_connections(self):
"""
If any host has fewer than the configured number of core connections
open, attempt to open connections until that number is met.
"""
for session in tuple(self.sessions):
for pool in tuple(session._pools.values()):
pool.ensure_core_connections() | python | def _ensure_core_connections(self):
for session in tuple(self.sessions):
for pool in tuple(session._pools.values()):
pool.ensure_core_connections() | [
"def",
"_ensure_core_connections",
"(",
"self",
")",
":",
"for",
"session",
"in",
"tuple",
"(",
"self",
".",
"sessions",
")",
":",
"for",
"pool",
"in",
"tuple",
"(",
"session",
".",
"_pools",
".",
"values",
"(",
")",
")",
":",
"pool",
".",
"ensure_core... | If any host has fewer than the configured number of core connections
open, attempt to open connections until that number is met. | [
"If",
"any",
"host",
"has",
"fewer",
"than",
"the",
"configured",
"number",
"of",
"core",
"connections",
"open",
"attempt",
"to",
"open",
"connections",
"until",
"that",
"number",
"is",
"met",
"."
] | 30a80d0b798b1f45f8cb77163b1fa791f3e3ca29 | https://github.com/datastax/python-driver/blob/30a80d0b798b1f45f8cb77163b1fa791f3e3ca29/cassandra/cluster.py#L1749-L1756 |
229,164 | datastax/python-driver | cassandra/cluster.py | Cluster.get_control_connection_host | def get_control_connection_host(self):
"""
Returns the control connection host metadata.
"""
connection = self.control_connection._connection
endpoint = connection.endpoint if connection else None
return self.metadata.get_host(endpoint) if endpoint else None | python | def get_control_connection_host(self):
connection = self.control_connection._connection
endpoint = connection.endpoint if connection else None
return self.metadata.get_host(endpoint) if endpoint else None | [
"def",
"get_control_connection_host",
"(",
"self",
")",
":",
"connection",
"=",
"self",
".",
"control_connection",
".",
"_connection",
"endpoint",
"=",
"connection",
".",
"endpoint",
"if",
"connection",
"else",
"None",
"return",
"self",
".",
"metadata",
".",
"ge... | Returns the control connection host metadata. | [
"Returns",
"the",
"control",
"connection",
"host",
"metadata",
"."
] | 30a80d0b798b1f45f8cb77163b1fa791f3e3ca29 | https://github.com/datastax/python-driver/blob/30a80d0b798b1f45f8cb77163b1fa791f3e3ca29/cassandra/cluster.py#L1780-L1786 |
229,165 | datastax/python-driver | cassandra/cluster.py | Cluster.refresh_schema_metadata | def refresh_schema_metadata(self, max_schema_agreement_wait=None):
"""
Synchronously refresh all schema metadata.
By default, the timeout for this operation is governed by :attr:`~.Cluster.max_schema_agreement_wait`
and :attr:`~.Cluster.control_connection_timeout`.
Passing max_schema_agreement_wait here overrides :attr:`~.Cluster.max_schema_agreement_wait`.
Setting max_schema_agreement_wait <= 0 will bypass schema agreement and refresh schema immediately.
An Exception is raised if schema refresh fails for any reason.
"""
if not self.control_connection.refresh_schema(schema_agreement_wait=max_schema_agreement_wait, force=True):
raise DriverException("Schema metadata was not refreshed. See log for details.") | python | def refresh_schema_metadata(self, max_schema_agreement_wait=None):
if not self.control_connection.refresh_schema(schema_agreement_wait=max_schema_agreement_wait, force=True):
raise DriverException("Schema metadata was not refreshed. See log for details.") | [
"def",
"refresh_schema_metadata",
"(",
"self",
",",
"max_schema_agreement_wait",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"control_connection",
".",
"refresh_schema",
"(",
"schema_agreement_wait",
"=",
"max_schema_agreement_wait",
",",
"force",
"=",
"True",
... | Synchronously refresh all schema metadata.
By default, the timeout for this operation is governed by :attr:`~.Cluster.max_schema_agreement_wait`
and :attr:`~.Cluster.control_connection_timeout`.
Passing max_schema_agreement_wait here overrides :attr:`~.Cluster.max_schema_agreement_wait`.
Setting max_schema_agreement_wait <= 0 will bypass schema agreement and refresh schema immediately.
An Exception is raised if schema refresh fails for any reason. | [
"Synchronously",
"refresh",
"all",
"schema",
"metadata",
"."
] | 30a80d0b798b1f45f8cb77163b1fa791f3e3ca29 | https://github.com/datastax/python-driver/blob/30a80d0b798b1f45f8cb77163b1fa791f3e3ca29/cassandra/cluster.py#L1788-L1802 |
229,166 | datastax/python-driver | cassandra/cluster.py | Cluster.refresh_keyspace_metadata | def refresh_keyspace_metadata(self, keyspace, max_schema_agreement_wait=None):
"""
Synchronously refresh keyspace metadata. This applies to keyspace-level information such as replication
and durability settings. It does not refresh tables, types, etc. contained in the keyspace.
See :meth:`~.Cluster.refresh_schema_metadata` for description of ``max_schema_agreement_wait`` behavior
"""
if not self.control_connection.refresh_schema(target_type=SchemaTargetType.KEYSPACE, keyspace=keyspace,
schema_agreement_wait=max_schema_agreement_wait, force=True):
raise DriverException("Keyspace metadata was not refreshed. See log for details.") | python | def refresh_keyspace_metadata(self, keyspace, max_schema_agreement_wait=None):
if not self.control_connection.refresh_schema(target_type=SchemaTargetType.KEYSPACE, keyspace=keyspace,
schema_agreement_wait=max_schema_agreement_wait, force=True):
raise DriverException("Keyspace metadata was not refreshed. See log for details.") | [
"def",
"refresh_keyspace_metadata",
"(",
"self",
",",
"keyspace",
",",
"max_schema_agreement_wait",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"control_connection",
".",
"refresh_schema",
"(",
"target_type",
"=",
"SchemaTargetType",
".",
"KEYSPACE",
",",
"ke... | Synchronously refresh keyspace metadata. This applies to keyspace-level information such as replication
and durability settings. It does not refresh tables, types, etc. contained in the keyspace.
See :meth:`~.Cluster.refresh_schema_metadata` for description of ``max_schema_agreement_wait`` behavior | [
"Synchronously",
"refresh",
"keyspace",
"metadata",
".",
"This",
"applies",
"to",
"keyspace",
"-",
"level",
"information",
"such",
"as",
"replication",
"and",
"durability",
"settings",
".",
"It",
"does",
"not",
"refresh",
"tables",
"types",
"etc",
".",
"containe... | 30a80d0b798b1f45f8cb77163b1fa791f3e3ca29 | https://github.com/datastax/python-driver/blob/30a80d0b798b1f45f8cb77163b1fa791f3e3ca29/cassandra/cluster.py#L1804-L1813 |
229,167 | datastax/python-driver | cassandra/cluster.py | Cluster.refresh_table_metadata | def refresh_table_metadata(self, keyspace, table, max_schema_agreement_wait=None):
"""
Synchronously refresh table metadata. This applies to a table, and any triggers or indexes attached
to the table.
See :meth:`~.Cluster.refresh_schema_metadata` for description of ``max_schema_agreement_wait`` behavior
"""
if not self.control_connection.refresh_schema(target_type=SchemaTargetType.TABLE, keyspace=keyspace, table=table,
schema_agreement_wait=max_schema_agreement_wait, force=True):
raise DriverException("Table metadata was not refreshed. See log for details.") | python | def refresh_table_metadata(self, keyspace, table, max_schema_agreement_wait=None):
if not self.control_connection.refresh_schema(target_type=SchemaTargetType.TABLE, keyspace=keyspace, table=table,
schema_agreement_wait=max_schema_agreement_wait, force=True):
raise DriverException("Table metadata was not refreshed. See log for details.") | [
"def",
"refresh_table_metadata",
"(",
"self",
",",
"keyspace",
",",
"table",
",",
"max_schema_agreement_wait",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"control_connection",
".",
"refresh_schema",
"(",
"target_type",
"=",
"SchemaTargetType",
".",
"TABLE",
... | Synchronously refresh table metadata. This applies to a table, and any triggers or indexes attached
to the table.
See :meth:`~.Cluster.refresh_schema_metadata` for description of ``max_schema_agreement_wait`` behavior | [
"Synchronously",
"refresh",
"table",
"metadata",
".",
"This",
"applies",
"to",
"a",
"table",
"and",
"any",
"triggers",
"or",
"indexes",
"attached",
"to",
"the",
"table",
"."
] | 30a80d0b798b1f45f8cb77163b1fa791f3e3ca29 | https://github.com/datastax/python-driver/blob/30a80d0b798b1f45f8cb77163b1fa791f3e3ca29/cassandra/cluster.py#L1815-L1824 |
229,168 | datastax/python-driver | cassandra/cluster.py | Cluster.refresh_user_type_metadata | def refresh_user_type_metadata(self, keyspace, user_type, max_schema_agreement_wait=None):
"""
Synchronously refresh user defined type metadata.
See :meth:`~.Cluster.refresh_schema_metadata` for description of ``max_schema_agreement_wait`` behavior
"""
if not self.control_connection.refresh_schema(target_type=SchemaTargetType.TYPE, keyspace=keyspace, type=user_type,
schema_agreement_wait=max_schema_agreement_wait, force=True):
raise DriverException("User Type metadata was not refreshed. See log for details.") | python | def refresh_user_type_metadata(self, keyspace, user_type, max_schema_agreement_wait=None):
if not self.control_connection.refresh_schema(target_type=SchemaTargetType.TYPE, keyspace=keyspace, type=user_type,
schema_agreement_wait=max_schema_agreement_wait, force=True):
raise DriverException("User Type metadata was not refreshed. See log for details.") | [
"def",
"refresh_user_type_metadata",
"(",
"self",
",",
"keyspace",
",",
"user_type",
",",
"max_schema_agreement_wait",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"control_connection",
".",
"refresh_schema",
"(",
"target_type",
"=",
"SchemaTargetType",
".",
"... | Synchronously refresh user defined type metadata.
See :meth:`~.Cluster.refresh_schema_metadata` for description of ``max_schema_agreement_wait`` behavior | [
"Synchronously",
"refresh",
"user",
"defined",
"type",
"metadata",
"."
] | 30a80d0b798b1f45f8cb77163b1fa791f3e3ca29 | https://github.com/datastax/python-driver/blob/30a80d0b798b1f45f8cb77163b1fa791f3e3ca29/cassandra/cluster.py#L1836-L1844 |
229,169 | datastax/python-driver | cassandra/cluster.py | Cluster.refresh_user_function_metadata | def refresh_user_function_metadata(self, keyspace, function, max_schema_agreement_wait=None):
"""
Synchronously refresh user defined function metadata.
``function`` is a :class:`cassandra.UserFunctionDescriptor`.
See :meth:`~.Cluster.refresh_schema_metadata` for description of ``max_schema_agreement_wait`` behavior
"""
if not self.control_connection.refresh_schema(target_type=SchemaTargetType.FUNCTION, keyspace=keyspace, function=function,
schema_agreement_wait=max_schema_agreement_wait, force=True):
raise DriverException("User Function metadata was not refreshed. See log for details.") | python | def refresh_user_function_metadata(self, keyspace, function, max_schema_agreement_wait=None):
if not self.control_connection.refresh_schema(target_type=SchemaTargetType.FUNCTION, keyspace=keyspace, function=function,
schema_agreement_wait=max_schema_agreement_wait, force=True):
raise DriverException("User Function metadata was not refreshed. See log for details.") | [
"def",
"refresh_user_function_metadata",
"(",
"self",
",",
"keyspace",
",",
"function",
",",
"max_schema_agreement_wait",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"control_connection",
".",
"refresh_schema",
"(",
"target_type",
"=",
"SchemaTargetType",
".",
... | Synchronously refresh user defined function metadata.
``function`` is a :class:`cassandra.UserFunctionDescriptor`.
See :meth:`~.Cluster.refresh_schema_metadata` for description of ``max_schema_agreement_wait`` behavior | [
"Synchronously",
"refresh",
"user",
"defined",
"function",
"metadata",
"."
] | 30a80d0b798b1f45f8cb77163b1fa791f3e3ca29 | https://github.com/datastax/python-driver/blob/30a80d0b798b1f45f8cb77163b1fa791f3e3ca29/cassandra/cluster.py#L1846-L1856 |
229,170 | datastax/python-driver | cassandra/cluster.py | Cluster.refresh_user_aggregate_metadata | def refresh_user_aggregate_metadata(self, keyspace, aggregate, max_schema_agreement_wait=None):
"""
Synchronously refresh user defined aggregate metadata.
``aggregate`` is a :class:`cassandra.UserAggregateDescriptor`.
See :meth:`~.Cluster.refresh_schema_metadata` for description of ``max_schema_agreement_wait`` behavior
"""
if not self.control_connection.refresh_schema(target_type=SchemaTargetType.AGGREGATE, keyspace=keyspace, aggregate=aggregate,
schema_agreement_wait=max_schema_agreement_wait, force=True):
raise DriverException("User Aggregate metadata was not refreshed. See log for details.") | python | def refresh_user_aggregate_metadata(self, keyspace, aggregate, max_schema_agreement_wait=None):
if not self.control_connection.refresh_schema(target_type=SchemaTargetType.AGGREGATE, keyspace=keyspace, aggregate=aggregate,
schema_agreement_wait=max_schema_agreement_wait, force=True):
raise DriverException("User Aggregate metadata was not refreshed. See log for details.") | [
"def",
"refresh_user_aggregate_metadata",
"(",
"self",
",",
"keyspace",
",",
"aggregate",
",",
"max_schema_agreement_wait",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"control_connection",
".",
"refresh_schema",
"(",
"target_type",
"=",
"SchemaTargetType",
"."... | Synchronously refresh user defined aggregate metadata.
``aggregate`` is a :class:`cassandra.UserAggregateDescriptor`.
See :meth:`~.Cluster.refresh_schema_metadata` for description of ``max_schema_agreement_wait`` behavior | [
"Synchronously",
"refresh",
"user",
"defined",
"aggregate",
"metadata",
"."
] | 30a80d0b798b1f45f8cb77163b1fa791f3e3ca29 | https://github.com/datastax/python-driver/blob/30a80d0b798b1f45f8cb77163b1fa791f3e3ca29/cassandra/cluster.py#L1858-L1868 |
229,171 | datastax/python-driver | cassandra/cluster.py | Session.execute | def execute(self, query, parameters=None, timeout=_NOT_SET, trace=False,
custom_payload=None, execution_profile=EXEC_PROFILE_DEFAULT,
paging_state=None, host=None):
"""
Execute the given query and synchronously wait for the response.
If an error is encountered while executing the query, an Exception
will be raised.
`query` may be a query string or an instance of :class:`cassandra.query.Statement`.
`parameters` may be a sequence or dict of parameters to bind. If a
sequence is used, ``%s`` should be used the placeholder for each
argument. If a dict is used, ``%(name)s`` style placeholders must
be used.
`timeout` should specify a floating-point timeout (in seconds) after
which an :exc:`.OperationTimedOut` exception will be raised if the query
has not completed. If not set, the timeout defaults to
:attr:`~.Session.default_timeout`. If set to :const:`None`, there is
no timeout. Please see :meth:`.ResponseFuture.result` for details on
the scope and effect of this timeout.
If `trace` is set to :const:`True`, the query will be sent with tracing enabled.
The trace details can be obtained using the returned :class:`.ResultSet` object.
`custom_payload` is a :ref:`custom_payload` dict to be passed to the server.
If `query` is a Statement with its own custom_payload. The message payload
will be a union of the two, with the values specified here taking precedence.
`execution_profile` is the execution profile to use for this request. It can be a key to a profile configured
via :meth:`Cluster.add_execution_profile` or an instance (from :meth:`Session.execution_profile_clone_update`,
for example
`paging_state` is an optional paging state, reused from a previous :class:`ResultSet`.
`host` is the :class:`pool.Host` that should handle the query. Using this is discouraged except in a few
cases, e.g., querying node-local tables and applying schema changes.
"""
return self.execute_async(query, parameters, trace, custom_payload,
timeout, execution_profile, paging_state, host).result() | python | def execute(self, query, parameters=None, timeout=_NOT_SET, trace=False,
custom_payload=None, execution_profile=EXEC_PROFILE_DEFAULT,
paging_state=None, host=None):
return self.execute_async(query, parameters, trace, custom_payload,
timeout, execution_profile, paging_state, host).result() | [
"def",
"execute",
"(",
"self",
",",
"query",
",",
"parameters",
"=",
"None",
",",
"timeout",
"=",
"_NOT_SET",
",",
"trace",
"=",
"False",
",",
"custom_payload",
"=",
"None",
",",
"execution_profile",
"=",
"EXEC_PROFILE_DEFAULT",
",",
"paging_state",
"=",
"No... | Execute the given query and synchronously wait for the response.
If an error is encountered while executing the query, an Exception
will be raised.
`query` may be a query string or an instance of :class:`cassandra.query.Statement`.
`parameters` may be a sequence or dict of parameters to bind. If a
sequence is used, ``%s`` should be used the placeholder for each
argument. If a dict is used, ``%(name)s`` style placeholders must
be used.
`timeout` should specify a floating-point timeout (in seconds) after
which an :exc:`.OperationTimedOut` exception will be raised if the query
has not completed. If not set, the timeout defaults to
:attr:`~.Session.default_timeout`. If set to :const:`None`, there is
no timeout. Please see :meth:`.ResponseFuture.result` for details on
the scope and effect of this timeout.
If `trace` is set to :const:`True`, the query will be sent with tracing enabled.
The trace details can be obtained using the returned :class:`.ResultSet` object.
`custom_payload` is a :ref:`custom_payload` dict to be passed to the server.
If `query` is a Statement with its own custom_payload. The message payload
will be a union of the two, with the values specified here taking precedence.
`execution_profile` is the execution profile to use for this request. It can be a key to a profile configured
via :meth:`Cluster.add_execution_profile` or an instance (from :meth:`Session.execution_profile_clone_update`,
for example
`paging_state` is an optional paging state, reused from a previous :class:`ResultSet`.
`host` is the :class:`pool.Host` that should handle the query. Using this is discouraged except in a few
cases, e.g., querying node-local tables and applying schema changes. | [
"Execute",
"the",
"given",
"query",
"and",
"synchronously",
"wait",
"for",
"the",
"response",
"."
] | 30a80d0b798b1f45f8cb77163b1fa791f3e3ca29 | https://github.com/datastax/python-driver/blob/30a80d0b798b1f45f8cb77163b1fa791f3e3ca29/cassandra/cluster.py#L2197-L2237 |
229,172 | datastax/python-driver | cassandra/cluster.py | Session.get_execution_profile | def get_execution_profile(self, name):
"""
Returns the execution profile associated with the provided ``name``.
:param name: The name (or key) of the execution profile.
"""
profiles = self.cluster.profile_manager.profiles
try:
return profiles[name]
except KeyError:
raise ValueError("Invalid execution_profile: '%s'; valid profiles are %s" % (name, profiles.keys())) | python | def get_execution_profile(self, name):
profiles = self.cluster.profile_manager.profiles
try:
return profiles[name]
except KeyError:
raise ValueError("Invalid execution_profile: '%s'; valid profiles are %s" % (name, profiles.keys())) | [
"def",
"get_execution_profile",
"(",
"self",
",",
"name",
")",
":",
"profiles",
"=",
"self",
".",
"cluster",
".",
"profile_manager",
".",
"profiles",
"try",
":",
"return",
"profiles",
"[",
"name",
"]",
"except",
"KeyError",
":",
"raise",
"ValueError",
"(",
... | Returns the execution profile associated with the provided ``name``.
:param name: The name (or key) of the execution profile. | [
"Returns",
"the",
"execution",
"profile",
"associated",
"with",
"the",
"provided",
"name",
"."
] | 30a80d0b798b1f45f8cb77163b1fa791f3e3ca29 | https://github.com/datastax/python-driver/blob/30a80d0b798b1f45f8cb77163b1fa791f3e3ca29/cassandra/cluster.py#L2377-L2387 |
229,173 | datastax/python-driver | cassandra/cluster.py | Session.execution_profile_clone_update | def execution_profile_clone_update(self, ep, **kwargs):
"""
Returns a clone of the ``ep`` profile. ``kwargs`` can be specified to update attributes
of the returned profile.
This is a shallow clone, so any objects referenced by the profile are shared. This means Load Balancing Policy
is maintained by inclusion in the active profiles. It also means updating any other rich objects will be seen
by the active profile. In cases where this is not desirable, be sure to replace the instance instead of manipulating
the shared object.
"""
clone = copy(self._maybe_get_execution_profile(ep))
for attr, value in kwargs.items():
setattr(clone, attr, value)
return clone | python | def execution_profile_clone_update(self, ep, **kwargs):
clone = copy(self._maybe_get_execution_profile(ep))
for attr, value in kwargs.items():
setattr(clone, attr, value)
return clone | [
"def",
"execution_profile_clone_update",
"(",
"self",
",",
"ep",
",",
"*",
"*",
"kwargs",
")",
":",
"clone",
"=",
"copy",
"(",
"self",
".",
"_maybe_get_execution_profile",
"(",
"ep",
")",
")",
"for",
"attr",
",",
"value",
"in",
"kwargs",
".",
"items",
"(... | Returns a clone of the ``ep`` profile. ``kwargs`` can be specified to update attributes
of the returned profile.
This is a shallow clone, so any objects referenced by the profile are shared. This means Load Balancing Policy
is maintained by inclusion in the active profiles. It also means updating any other rich objects will be seen
by the active profile. In cases where this is not desirable, be sure to replace the instance instead of manipulating
the shared object. | [
"Returns",
"a",
"clone",
"of",
"the",
"ep",
"profile",
".",
"kwargs",
"can",
"be",
"specified",
"to",
"update",
"attributes",
"of",
"the",
"returned",
"profile",
"."
] | 30a80d0b798b1f45f8cb77163b1fa791f3e3ca29 | https://github.com/datastax/python-driver/blob/30a80d0b798b1f45f8cb77163b1fa791f3e3ca29/cassandra/cluster.py#L2392-L2405 |
229,174 | datastax/python-driver | cassandra/cluster.py | Session.add_request_init_listener | def add_request_init_listener(self, fn, *args, **kwargs):
"""
Adds a callback with arguments to be called when any request is created.
It will be invoked as `fn(response_future, *args, **kwargs)` after each client request is created,
and before the request is sent\*. This can be used to create extensions by adding result callbacks to the
response future.
\* where `response_future` is the :class:`.ResponseFuture` for the request.
Note that the init callback is done on the client thread creating the request, so you may need to consider
synchronization if you have multiple threads. Any callbacks added to the response future will be executed
on the event loop thread, so the normal advice about minimizing cycles and avoiding blocking apply (see Note in
:meth:`.ResponseFuture.add_callbacks`.
See `this example <https://github.com/datastax/python-driver/blob/master/examples/request_init_listener.py>`_ in the
source tree for an example.
"""
self._request_init_callbacks.append((fn, args, kwargs)) | python | def add_request_init_listener(self, fn, *args, **kwargs):
self._request_init_callbacks.append((fn, args, kwargs)) | [
"def",
"add_request_init_listener",
"(",
"self",
",",
"fn",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"_request_init_callbacks",
".",
"append",
"(",
"(",
"fn",
",",
"args",
",",
"kwargs",
")",
")"
] | Adds a callback with arguments to be called when any request is created.
It will be invoked as `fn(response_future, *args, **kwargs)` after each client request is created,
and before the request is sent\*. This can be used to create extensions by adding result callbacks to the
response future.
\* where `response_future` is the :class:`.ResponseFuture` for the request.
Note that the init callback is done on the client thread creating the request, so you may need to consider
synchronization if you have multiple threads. Any callbacks added to the response future will be executed
on the event loop thread, so the normal advice about minimizing cycles and avoiding blocking apply (see Note in
:meth:`.ResponseFuture.add_callbacks`.
See `this example <https://github.com/datastax/python-driver/blob/master/examples/request_init_listener.py>`_ in the
source tree for an example. | [
"Adds",
"a",
"callback",
"with",
"arguments",
"to",
"be",
"called",
"when",
"any",
"request",
"is",
"created",
"."
] | 30a80d0b798b1f45f8cb77163b1fa791f3e3ca29 | https://github.com/datastax/python-driver/blob/30a80d0b798b1f45f8cb77163b1fa791f3e3ca29/cassandra/cluster.py#L2407-L2425 |
229,175 | datastax/python-driver | cassandra/cluster.py | Session.remove_request_init_listener | def remove_request_init_listener(self, fn, *args, **kwargs):
"""
Removes a callback and arguments from the list.
See :meth:`.Session.add_request_init_listener`.
"""
self._request_init_callbacks.remove((fn, args, kwargs)) | python | def remove_request_init_listener(self, fn, *args, **kwargs):
self._request_init_callbacks.remove((fn, args, kwargs)) | [
"def",
"remove_request_init_listener",
"(",
"self",
",",
"fn",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"_request_init_callbacks",
".",
"remove",
"(",
"(",
"fn",
",",
"args",
",",
"kwargs",
")",
")"
] | Removes a callback and arguments from the list.
See :meth:`.Session.add_request_init_listener`. | [
"Removes",
"a",
"callback",
"and",
"arguments",
"from",
"the",
"list",
"."
] | 30a80d0b798b1f45f8cb77163b1fa791f3e3ca29 | https://github.com/datastax/python-driver/blob/30a80d0b798b1f45f8cb77163b1fa791f3e3ca29/cassandra/cluster.py#L2427-L2433 |
229,176 | datastax/python-driver | cassandra/cluster.py | Session.prepare_on_all_hosts | def prepare_on_all_hosts(self, query, excluded_host, keyspace=None):
"""
Prepare the given query on all hosts, excluding ``excluded_host``.
Intended for internal use only.
"""
futures = []
for host in tuple(self._pools.keys()):
if host != excluded_host and host.is_up:
future = ResponseFuture(self, PrepareMessage(query=query, keyspace=keyspace),
None, self.default_timeout)
# we don't care about errors preparing against specific hosts,
# since we can always prepare them as needed when the prepared
# statement is used. Just log errors and continue on.
try:
request_id = future._query(host)
except Exception:
log.exception("Error preparing query for host %s:", host)
continue
if request_id is None:
# the error has already been logged by ResponsFuture
log.debug("Failed to prepare query for host %s: %r",
host, future._errors.get(host))
continue
futures.append((host, future))
for host, future in futures:
try:
future.result()
except Exception:
log.exception("Error preparing query for host %s:", host) | python | def prepare_on_all_hosts(self, query, excluded_host, keyspace=None):
futures = []
for host in tuple(self._pools.keys()):
if host != excluded_host and host.is_up:
future = ResponseFuture(self, PrepareMessage(query=query, keyspace=keyspace),
None, self.default_timeout)
# we don't care about errors preparing against specific hosts,
# since we can always prepare them as needed when the prepared
# statement is used. Just log errors and continue on.
try:
request_id = future._query(host)
except Exception:
log.exception("Error preparing query for host %s:", host)
continue
if request_id is None:
# the error has already been logged by ResponsFuture
log.debug("Failed to prepare query for host %s: %r",
host, future._errors.get(host))
continue
futures.append((host, future))
for host, future in futures:
try:
future.result()
except Exception:
log.exception("Error preparing query for host %s:", host) | [
"def",
"prepare_on_all_hosts",
"(",
"self",
",",
"query",
",",
"excluded_host",
",",
"keyspace",
"=",
"None",
")",
":",
"futures",
"=",
"[",
"]",
"for",
"host",
"in",
"tuple",
"(",
"self",
".",
"_pools",
".",
"keys",
"(",
")",
")",
":",
"if",
"host",... | Prepare the given query on all hosts, excluding ``excluded_host``.
Intended for internal use only. | [
"Prepare",
"the",
"given",
"query",
"on",
"all",
"hosts",
"excluding",
"excluded_host",
".",
"Intended",
"for",
"internal",
"use",
"only",
"."
] | 30a80d0b798b1f45f8cb77163b1fa791f3e3ca29 | https://github.com/datastax/python-driver/blob/30a80d0b798b1f45f8cb77163b1fa791f3e3ca29/cassandra/cluster.py#L2505-L2537 |
229,177 | datastax/python-driver | cassandra/cluster.py | Session.shutdown | def shutdown(self):
"""
Close all connections. ``Session`` instances should not be used
for any purpose after being shutdown.
"""
with self._lock:
if self.is_shutdown:
return
else:
self.is_shutdown = True
# PYTHON-673. If shutdown was called shortly after session init, avoid
# a race by cancelling any initial connection attempts haven't started,
# then blocking on any that have.
for future in self._initial_connect_futures:
future.cancel()
wait_futures(self._initial_connect_futures)
for pool in tuple(self._pools.values()):
pool.shutdown() | python | def shutdown(self):
with self._lock:
if self.is_shutdown:
return
else:
self.is_shutdown = True
# PYTHON-673. If shutdown was called shortly after session init, avoid
# a race by cancelling any initial connection attempts haven't started,
# then blocking on any that have.
for future in self._initial_connect_futures:
future.cancel()
wait_futures(self._initial_connect_futures)
for pool in tuple(self._pools.values()):
pool.shutdown() | [
"def",
"shutdown",
"(",
"self",
")",
":",
"with",
"self",
".",
"_lock",
":",
"if",
"self",
".",
"is_shutdown",
":",
"return",
"else",
":",
"self",
".",
"is_shutdown",
"=",
"True",
"# PYTHON-673. If shutdown was called shortly after session init, avoid",
"# a race by... | Close all connections. ``Session`` instances should not be used
for any purpose after being shutdown. | [
"Close",
"all",
"connections",
".",
"Session",
"instances",
"should",
"not",
"be",
"used",
"for",
"any",
"purpose",
"after",
"being",
"shutdown",
"."
] | 30a80d0b798b1f45f8cb77163b1fa791f3e3ca29 | https://github.com/datastax/python-driver/blob/30a80d0b798b1f45f8cb77163b1fa791f3e3ca29/cassandra/cluster.py#L2539-L2558 |
229,178 | datastax/python-driver | cassandra/cluster.py | Session.on_down | def on_down(self, host):
"""
Called by the parent Cluster instance when a node is marked down.
Only intended for internal use.
"""
future = self.remove_pool(host)
if future:
future.add_done_callback(lambda f: self.update_created_pools()) | python | def on_down(self, host):
future = self.remove_pool(host)
if future:
future.add_done_callback(lambda f: self.update_created_pools()) | [
"def",
"on_down",
"(",
"self",
",",
"host",
")",
":",
"future",
"=",
"self",
".",
"remove_pool",
"(",
"host",
")",
"if",
"future",
":",
"future",
".",
"add_done_callback",
"(",
"lambda",
"f",
":",
"self",
".",
"update_created_pools",
"(",
")",
")"
] | Called by the parent Cluster instance when a node is marked down.
Only intended for internal use. | [
"Called",
"by",
"the",
"parent",
"Cluster",
"instance",
"when",
"a",
"node",
"is",
"marked",
"down",
".",
"Only",
"intended",
"for",
"internal",
"use",
"."
] | 30a80d0b798b1f45f8cb77163b1fa791f3e3ca29 | https://github.com/datastax/python-driver/blob/30a80d0b798b1f45f8cb77163b1fa791f3e3ca29/cassandra/cluster.py#L2674-L2681 |
229,179 | datastax/python-driver | cassandra/cluster.py | Session._set_keyspace_for_all_pools | def _set_keyspace_for_all_pools(self, keyspace, callback):
"""
Asynchronously sets the keyspace on all pools. When all
pools have set all of their connections, `callback` will be
called with a dictionary of all errors that occurred, keyed
by the `Host` that they occurred against.
"""
with self._lock:
self.keyspace = keyspace
remaining_callbacks = set(self._pools.values())
errors = {}
if not remaining_callbacks:
callback(errors)
return
def pool_finished_setting_keyspace(pool, host_errors):
remaining_callbacks.remove(pool)
if host_errors:
errors[pool.host] = host_errors
if not remaining_callbacks:
callback(host_errors)
for pool in tuple(self._pools.values()):
pool._set_keyspace_for_all_conns(keyspace, pool_finished_setting_keyspace) | python | def _set_keyspace_for_all_pools(self, keyspace, callback):
with self._lock:
self.keyspace = keyspace
remaining_callbacks = set(self._pools.values())
errors = {}
if not remaining_callbacks:
callback(errors)
return
def pool_finished_setting_keyspace(pool, host_errors):
remaining_callbacks.remove(pool)
if host_errors:
errors[pool.host] = host_errors
if not remaining_callbacks:
callback(host_errors)
for pool in tuple(self._pools.values()):
pool._set_keyspace_for_all_conns(keyspace, pool_finished_setting_keyspace) | [
"def",
"_set_keyspace_for_all_pools",
"(",
"self",
",",
"keyspace",
",",
"callback",
")",
":",
"with",
"self",
".",
"_lock",
":",
"self",
".",
"keyspace",
"=",
"keyspace",
"remaining_callbacks",
"=",
"set",
"(",
"self",
".",
"_pools",
".",
"values",
"(",
"... | Asynchronously sets the keyspace on all pools. When all
pools have set all of their connections, `callback` will be
called with a dictionary of all errors that occurred, keyed
by the `Host` that they occurred against. | [
"Asynchronously",
"sets",
"the",
"keyspace",
"on",
"all",
"pools",
".",
"When",
"all",
"pools",
"have",
"set",
"all",
"of",
"their",
"connections",
"callback",
"will",
"be",
"called",
"with",
"a",
"dictionary",
"of",
"all",
"errors",
"that",
"occurred",
"key... | 30a80d0b798b1f45f8cb77163b1fa791f3e3ca29 | https://github.com/datastax/python-driver/blob/30a80d0b798b1f45f8cb77163b1fa791f3e3ca29/cassandra/cluster.py#L2694-L2719 |
229,180 | datastax/python-driver | cassandra/cluster.py | Session.user_type_registered | def user_type_registered(self, keyspace, user_type, klass):
"""
Called by the parent Cluster instance when the user registers a new
mapping from a user-defined type to a class. Intended for internal
use only.
"""
try:
ks_meta = self.cluster.metadata.keyspaces[keyspace]
except KeyError:
raise UserTypeDoesNotExist(
'Keyspace %s does not exist or has not been discovered by the driver' % (keyspace,))
try:
type_meta = ks_meta.user_types[user_type]
except KeyError:
raise UserTypeDoesNotExist(
'User type %s does not exist in keyspace %s' % (user_type, keyspace))
field_names = type_meta.field_names
if six.PY2:
# go from unicode to string to avoid decode errors from implicit
# decode when formatting non-ascii values
field_names = [fn.encode('utf-8') for fn in field_names]
def encode(val):
return '{ %s }' % ' , '.join('%s : %s' % (
field_name,
self.encoder.cql_encode_all_types(getattr(val, field_name, None))
) for field_name in field_names)
self.encoder.mapping[klass] = encode | python | def user_type_registered(self, keyspace, user_type, klass):
try:
ks_meta = self.cluster.metadata.keyspaces[keyspace]
except KeyError:
raise UserTypeDoesNotExist(
'Keyspace %s does not exist or has not been discovered by the driver' % (keyspace,))
try:
type_meta = ks_meta.user_types[user_type]
except KeyError:
raise UserTypeDoesNotExist(
'User type %s does not exist in keyspace %s' % (user_type, keyspace))
field_names = type_meta.field_names
if six.PY2:
# go from unicode to string to avoid decode errors from implicit
# decode when formatting non-ascii values
field_names = [fn.encode('utf-8') for fn in field_names]
def encode(val):
return '{ %s }' % ' , '.join('%s : %s' % (
field_name,
self.encoder.cql_encode_all_types(getattr(val, field_name, None))
) for field_name in field_names)
self.encoder.mapping[klass] = encode | [
"def",
"user_type_registered",
"(",
"self",
",",
"keyspace",
",",
"user_type",
",",
"klass",
")",
":",
"try",
":",
"ks_meta",
"=",
"self",
".",
"cluster",
".",
"metadata",
".",
"keyspaces",
"[",
"keyspace",
"]",
"except",
"KeyError",
":",
"raise",
"UserTyp... | Called by the parent Cluster instance when the user registers a new
mapping from a user-defined type to a class. Intended for internal
use only. | [
"Called",
"by",
"the",
"parent",
"Cluster",
"instance",
"when",
"the",
"user",
"registers",
"a",
"new",
"mapping",
"from",
"a",
"user",
"-",
"defined",
"type",
"to",
"a",
"class",
".",
"Intended",
"for",
"internal",
"use",
"only",
"."
] | 30a80d0b798b1f45f8cb77163b1fa791f3e3ca29 | https://github.com/datastax/python-driver/blob/30a80d0b798b1f45f8cb77163b1fa791f3e3ca29/cassandra/cluster.py#L2721-L2751 |
229,181 | datastax/python-driver | cassandra/cluster.py | ControlConnection._get_and_set_reconnection_handler | def _get_and_set_reconnection_handler(self, new_handler):
"""
Called by the _ControlReconnectionHandler when a new connection
is successfully created. Clears out the _reconnection_handler on
this ControlConnection.
"""
with self._reconnection_lock:
old = self._reconnection_handler
self._reconnection_handler = new_handler
return old | python | def _get_and_set_reconnection_handler(self, new_handler):
with self._reconnection_lock:
old = self._reconnection_handler
self._reconnection_handler = new_handler
return old | [
"def",
"_get_and_set_reconnection_handler",
"(",
"self",
",",
"new_handler",
")",
":",
"with",
"self",
".",
"_reconnection_lock",
":",
"old",
"=",
"self",
".",
"_reconnection_handler",
"self",
".",
"_reconnection_handler",
"=",
"new_handler",
"return",
"old"
] | Called by the _ControlReconnectionHandler when a new connection
is successfully created. Clears out the _reconnection_handler on
this ControlConnection. | [
"Called",
"by",
"the",
"_ControlReconnectionHandler",
"when",
"a",
"new",
"connection",
"is",
"successfully",
"created",
".",
"Clears",
"out",
"the",
"_reconnection_handler",
"on",
"this",
"ControlConnection",
"."
] | 30a80d0b798b1f45f8cb77163b1fa791f3e3ca29 | https://github.com/datastax/python-driver/blob/30a80d0b798b1f45f8cb77163b1fa791f3e3ca29/cassandra/cluster.py#L3011-L3020 |
229,182 | datastax/python-driver | cassandra/cluster.py | ControlConnection._address_from_row | def _address_from_row(self, row):
"""
Parse the broadcast rpc address from a row and return it untranslated.
"""
addr = None
if "rpc_address" in row:
addr = row.get("rpc_address") # peers and local
if "native_transport_address" in row:
addr = row.get("native_transport_address")
if not addr or addr in ["0.0.0.0", "::"]:
addr = row.get("peer")
return addr | python | def _address_from_row(self, row):
addr = None
if "rpc_address" in row:
addr = row.get("rpc_address") # peers and local
if "native_transport_address" in row:
addr = row.get("native_transport_address")
if not addr or addr in ["0.0.0.0", "::"]:
addr = row.get("peer")
return addr | [
"def",
"_address_from_row",
"(",
"self",
",",
"row",
")",
":",
"addr",
"=",
"None",
"if",
"\"rpc_address\"",
"in",
"row",
":",
"addr",
"=",
"row",
".",
"get",
"(",
"\"rpc_address\"",
")",
"# peers and local",
"if",
"\"native_transport_address\"",
"in",
"row",
... | Parse the broadcast rpc address from a row and return it untranslated. | [
"Parse",
"the",
"broadcast",
"rpc",
"address",
"from",
"a",
"row",
"and",
"return",
"it",
"untranslated",
"."
] | 30a80d0b798b1f45f8cb77163b1fa791f3e3ca29 | https://github.com/datastax/python-driver/blob/30a80d0b798b1f45f8cb77163b1fa791f3e3ca29/cassandra/cluster.py#L3366-L3378 |
229,183 | datastax/python-driver | cassandra/cluster.py | ResponseFuture._on_timeout | def _on_timeout(self, _attempts=0):
"""
Called when the request associated with this ResponseFuture times out.
This function may reschedule itself. The ``_attempts`` parameter tracks
the number of times this has happened. This parameter should only be
set in those cases, where ``_on_timeout`` reschedules itself.
"""
# PYTHON-853: for short timeouts, we sometimes race with our __init__
if self._connection is None and _attempts < 3:
self._timer = self.session.cluster.connection_class.create_timer(
0.01,
partial(self._on_timeout, _attempts=_attempts + 1)
)
return
if self._connection is not None:
try:
self._connection._requests.pop(self._req_id)
# This prevents the race condition of the
# event loop thread just receiving the waited message
# If it arrives after this, it will be ignored
except KeyError:
return
pool = self.session._pools.get(self._current_host)
if pool and not pool.is_shutdown:
with self._connection.lock:
self._connection.request_ids.append(self._req_id)
pool.return_connection(self._connection)
errors = self._errors
if not errors:
if self.is_schema_agreed:
key = str(self._current_host.endpoint) if self._current_host else 'no host queried before timeout'
errors = {key: "Client request timeout. See Session.execute[_async](timeout)"}
else:
connection = self.session.cluster.control_connection._connection
host = str(connection.endpoint) if connection else 'unknown'
errors = {host: "Request timed out while waiting for schema agreement. See Session.execute[_async](timeout) and Cluster.max_schema_agreement_wait."}
self._set_final_exception(OperationTimedOut(errors, self._current_host)) | python | def _on_timeout(self, _attempts=0):
# PYTHON-853: for short timeouts, we sometimes race with our __init__
if self._connection is None and _attempts < 3:
self._timer = self.session.cluster.connection_class.create_timer(
0.01,
partial(self._on_timeout, _attempts=_attempts + 1)
)
return
if self._connection is not None:
try:
self._connection._requests.pop(self._req_id)
# This prevents the race condition of the
# event loop thread just receiving the waited message
# If it arrives after this, it will be ignored
except KeyError:
return
pool = self.session._pools.get(self._current_host)
if pool and not pool.is_shutdown:
with self._connection.lock:
self._connection.request_ids.append(self._req_id)
pool.return_connection(self._connection)
errors = self._errors
if not errors:
if self.is_schema_agreed:
key = str(self._current_host.endpoint) if self._current_host else 'no host queried before timeout'
errors = {key: "Client request timeout. See Session.execute[_async](timeout)"}
else:
connection = self.session.cluster.control_connection._connection
host = str(connection.endpoint) if connection else 'unknown'
errors = {host: "Request timed out while waiting for schema agreement. See Session.execute[_async](timeout) and Cluster.max_schema_agreement_wait."}
self._set_final_exception(OperationTimedOut(errors, self._current_host)) | [
"def",
"_on_timeout",
"(",
"self",
",",
"_attempts",
"=",
"0",
")",
":",
"# PYTHON-853: for short timeouts, we sometimes race with our __init__",
"if",
"self",
".",
"_connection",
"is",
"None",
"and",
"_attempts",
"<",
"3",
":",
"self",
".",
"_timer",
"=",
"self",... | Called when the request associated with this ResponseFuture times out.
This function may reschedule itself. The ``_attempts`` parameter tracks
the number of times this has happened. This parameter should only be
set in those cases, where ``_on_timeout`` reschedules itself. | [
"Called",
"when",
"the",
"request",
"associated",
"with",
"this",
"ResponseFuture",
"times",
"out",
"."
] | 30a80d0b798b1f45f8cb77163b1fa791f3e3ca29 | https://github.com/datastax/python-driver/blob/30a80d0b798b1f45f8cb77163b1fa791f3e3ca29/cassandra/cluster.py#L3652-L3694 |
229,184 | datastax/python-driver | cassandra/cluster.py | ResponseFuture._execute_after_prepare | def _execute_after_prepare(self, host, connection, pool, response):
"""
Handle the response to our attempt to prepare a statement.
If it succeeded, run the original query again against the same host.
"""
if pool:
pool.return_connection(connection)
if self._final_exception:
return
if isinstance(response, ResultMessage):
if response.kind == RESULT_KIND_PREPARED:
if self.prepared_statement:
# result metadata is the only thing that could have
# changed from an alter
(_, _, _,
self.prepared_statement.result_metadata,
new_metadata_id) = response.results
if new_metadata_id is not None:
self.prepared_statement.result_metadata_id = new_metadata_id
# use self._query to re-use the same host and
# at the same time properly borrow the connection
request_id = self._query(host)
if request_id is None:
# this host errored out, move on to the next
self.send_request()
else:
self._set_final_exception(ConnectionException(
"Got unexpected response when preparing statement "
"on host %s: %s" % (host, response)))
elif isinstance(response, ErrorMessage):
if hasattr(response, 'to_exception'):
self._set_final_exception(response.to_exception())
else:
self._set_final_exception(response)
elif isinstance(response, ConnectionException):
log.debug("Connection error when preparing statement on host %s: %s",
host, response)
# try again on a different host, preparing again if necessary
self._errors[host] = response
self.send_request()
else:
self._set_final_exception(ConnectionException(
"Got unexpected response type when preparing "
"statement on host %s: %s" % (host, response))) | python | def _execute_after_prepare(self, host, connection, pool, response):
if pool:
pool.return_connection(connection)
if self._final_exception:
return
if isinstance(response, ResultMessage):
if response.kind == RESULT_KIND_PREPARED:
if self.prepared_statement:
# result metadata is the only thing that could have
# changed from an alter
(_, _, _,
self.prepared_statement.result_metadata,
new_metadata_id) = response.results
if new_metadata_id is not None:
self.prepared_statement.result_metadata_id = new_metadata_id
# use self._query to re-use the same host and
# at the same time properly borrow the connection
request_id = self._query(host)
if request_id is None:
# this host errored out, move on to the next
self.send_request()
else:
self._set_final_exception(ConnectionException(
"Got unexpected response when preparing statement "
"on host %s: %s" % (host, response)))
elif isinstance(response, ErrorMessage):
if hasattr(response, 'to_exception'):
self._set_final_exception(response.to_exception())
else:
self._set_final_exception(response)
elif isinstance(response, ConnectionException):
log.debug("Connection error when preparing statement on host %s: %s",
host, response)
# try again on a different host, preparing again if necessary
self._errors[host] = response
self.send_request()
else:
self._set_final_exception(ConnectionException(
"Got unexpected response type when preparing "
"statement on host %s: %s" % (host, response))) | [
"def",
"_execute_after_prepare",
"(",
"self",
",",
"host",
",",
"connection",
",",
"pool",
",",
"response",
")",
":",
"if",
"pool",
":",
"pool",
".",
"return_connection",
"(",
"connection",
")",
"if",
"self",
".",
"_final_exception",
":",
"return",
"if",
"... | Handle the response to our attempt to prepare a statement.
If it succeeded, run the original query again against the same host. | [
"Handle",
"the",
"response",
"to",
"our",
"attempt",
"to",
"prepare",
"a",
"statement",
".",
"If",
"it",
"succeeded",
"run",
"the",
"original",
"query",
"again",
"against",
"the",
"same",
"host",
"."
] | 30a80d0b798b1f45f8cb77163b1fa791f3e3ca29 | https://github.com/datastax/python-driver/blob/30a80d0b798b1f45f8cb77163b1fa791f3e3ca29/cassandra/cluster.py#L4033-L4079 |
229,185 | datastax/python-driver | cassandra/cluster.py | ResponseFuture.result | def result(self):
"""
Return the final result or raise an Exception if errors were
encountered. If the final result or error has not been set
yet, this method will block until it is set, or the timeout
set for the request expires.
Timeout is specified in the Session request execution functions.
If the timeout is exceeded, an :exc:`cassandra.OperationTimedOut` will be raised.
This is a client-side timeout. For more information
about server-side coordinator timeouts, see :class:`.policies.RetryPolicy`.
Example usage::
>>> future = session.execute_async("SELECT * FROM mycf")
>>> # do other stuff...
>>> try:
... rows = future.result()
... for row in rows:
... ... # process results
... except Exception:
... log.exception("Operation failed:")
"""
self._event.wait()
if self._final_result is not _NOT_SET:
return ResultSet(self, self._final_result)
else:
raise self._final_exception | python | def result(self):
self._event.wait()
if self._final_result is not _NOT_SET:
return ResultSet(self, self._final_result)
else:
raise self._final_exception | [
"def",
"result",
"(",
"self",
")",
":",
"self",
".",
"_event",
".",
"wait",
"(",
")",
"if",
"self",
".",
"_final_result",
"is",
"not",
"_NOT_SET",
":",
"return",
"ResultSet",
"(",
"self",
",",
"self",
".",
"_final_result",
")",
"else",
":",
"raise",
... | Return the final result or raise an Exception if errors were
encountered. If the final result or error has not been set
yet, this method will block until it is set, or the timeout
set for the request expires.
Timeout is specified in the Session request execution functions.
If the timeout is exceeded, an :exc:`cassandra.OperationTimedOut` will be raised.
This is a client-side timeout. For more information
about server-side coordinator timeouts, see :class:`.policies.RetryPolicy`.
Example usage::
>>> future = session.execute_async("SELECT * FROM mycf")
>>> # do other stuff...
>>> try:
... rows = future.result()
... for row in rows:
... ... # process results
... except Exception:
... log.exception("Operation failed:") | [
"Return",
"the",
"final",
"result",
"or",
"raise",
"an",
"Exception",
"if",
"errors",
"were",
"encountered",
".",
"If",
"the",
"final",
"result",
"or",
"error",
"has",
"not",
"been",
"set",
"yet",
"this",
"method",
"will",
"block",
"until",
"it",
"is",
"... | 30a80d0b798b1f45f8cb77163b1fa791f3e3ca29 | https://github.com/datastax/python-driver/blob/30a80d0b798b1f45f8cb77163b1fa791f3e3ca29/cassandra/cluster.py#L4150-L4179 |
229,186 | datastax/python-driver | cassandra/cluster.py | ResponseFuture.get_query_trace | def get_query_trace(self, max_wait=None, query_cl=ConsistencyLevel.LOCAL_ONE):
"""
Fetches and returns the query trace of the last response, or `None` if tracing was
not enabled.
Note that this may raise an exception if there are problems retrieving the trace
details from Cassandra. If the trace is not available after `max_wait`,
:exc:`cassandra.query.TraceUnavailable` will be raised.
If the ResponseFuture is not done (async execution) and you try to retrieve the trace,
:exc:`cassandra.query.TraceUnavailable` will be raised.
`query_cl` is the consistency level used to poll the trace tables.
"""
if self._final_result is _NOT_SET and self._final_exception is None:
raise TraceUnavailable(
"Trace information was not available. The ResponseFuture is not done.")
if self._query_traces:
return self._get_query_trace(len(self._query_traces) - 1, max_wait, query_cl) | python | def get_query_trace(self, max_wait=None, query_cl=ConsistencyLevel.LOCAL_ONE):
if self._final_result is _NOT_SET and self._final_exception is None:
raise TraceUnavailable(
"Trace information was not available. The ResponseFuture is not done.")
if self._query_traces:
return self._get_query_trace(len(self._query_traces) - 1, max_wait, query_cl) | [
"def",
"get_query_trace",
"(",
"self",
",",
"max_wait",
"=",
"None",
",",
"query_cl",
"=",
"ConsistencyLevel",
".",
"LOCAL_ONE",
")",
":",
"if",
"self",
".",
"_final_result",
"is",
"_NOT_SET",
"and",
"self",
".",
"_final_exception",
"is",
"None",
":",
"raise... | Fetches and returns the query trace of the last response, or `None` if tracing was
not enabled.
Note that this may raise an exception if there are problems retrieving the trace
details from Cassandra. If the trace is not available after `max_wait`,
:exc:`cassandra.query.TraceUnavailable` will be raised.
If the ResponseFuture is not done (async execution) and you try to retrieve the trace,
:exc:`cassandra.query.TraceUnavailable` will be raised.
`query_cl` is the consistency level used to poll the trace tables. | [
"Fetches",
"and",
"returns",
"the",
"query",
"trace",
"of",
"the",
"last",
"response",
"or",
"None",
"if",
"tracing",
"was",
"not",
"enabled",
"."
] | 30a80d0b798b1f45f8cb77163b1fa791f3e3ca29 | https://github.com/datastax/python-driver/blob/30a80d0b798b1f45f8cb77163b1fa791f3e3ca29/cassandra/cluster.py#L4187-L4206 |
229,187 | datastax/python-driver | cassandra/cluster.py | ResponseFuture.get_all_query_traces | def get_all_query_traces(self, max_wait_per=None, query_cl=ConsistencyLevel.LOCAL_ONE):
"""
Fetches and returns the query traces for all query pages, if tracing was enabled.
See note in :meth:`~.get_query_trace` regarding possible exceptions.
"""
if self._query_traces:
return [self._get_query_trace(i, max_wait_per, query_cl) for i in range(len(self._query_traces))]
return [] | python | def get_all_query_traces(self, max_wait_per=None, query_cl=ConsistencyLevel.LOCAL_ONE):
if self._query_traces:
return [self._get_query_trace(i, max_wait_per, query_cl) for i in range(len(self._query_traces))]
return [] | [
"def",
"get_all_query_traces",
"(",
"self",
",",
"max_wait_per",
"=",
"None",
",",
"query_cl",
"=",
"ConsistencyLevel",
".",
"LOCAL_ONE",
")",
":",
"if",
"self",
".",
"_query_traces",
":",
"return",
"[",
"self",
".",
"_get_query_trace",
"(",
"i",
",",
"max_w... | Fetches and returns the query traces for all query pages, if tracing was enabled.
See note in :meth:`~.get_query_trace` regarding possible exceptions. | [
"Fetches",
"and",
"returns",
"the",
"query",
"traces",
"for",
"all",
"query",
"pages",
"if",
"tracing",
"was",
"enabled",
"."
] | 30a80d0b798b1f45f8cb77163b1fa791f3e3ca29 | https://github.com/datastax/python-driver/blob/30a80d0b798b1f45f8cb77163b1fa791f3e3ca29/cassandra/cluster.py#L4208-L4216 |
229,188 | datastax/python-driver | cassandra/cluster.py | ResponseFuture.add_callback | def add_callback(self, fn, *args, **kwargs):
"""
Attaches a callback function to be called when the final results arrive.
By default, `fn` will be called with the results as the first and only
argument. If `*args` or `**kwargs` are supplied, they will be passed
through as additional positional or keyword arguments to `fn`.
If an error is hit while executing the operation, a callback attached
here will not be called. Use :meth:`.add_errback()` or :meth:`add_callbacks()`
if you wish to handle that case.
If the final result has already been seen when this method is called,
the callback will be called immediately (before this method returns).
Note: in the case that the result is not available when the callback is added,
the callback is executed by IO event thread. This means that the callback
should not block or attempt further synchronous requests, because no further
IO will be processed until the callback returns.
**Important**: if the callback you attach results in an exception being
raised, **the exception will be ignored**, so please ensure your
callback handles all error cases that you care about.
Usage example::
>>> session = cluster.connect("mykeyspace")
>>> def handle_results(rows, start_time, should_log=False):
... if should_log:
... log.info("Total time: %f", time.time() - start_time)
... ...
>>> future = session.execute_async("SELECT * FROM users")
>>> future.add_callback(handle_results, time.time(), should_log=True)
"""
run_now = False
with self._callback_lock:
# Always add fn to self._callbacks, even when we're about to
# execute it, to prevent races with functions like
# start_fetching_next_page that reset _final_result
self._callbacks.append((fn, args, kwargs))
if self._final_result is not _NOT_SET:
run_now = True
if run_now:
fn(self._final_result, *args, **kwargs)
return self | python | def add_callback(self, fn, *args, **kwargs):
run_now = False
with self._callback_lock:
# Always add fn to self._callbacks, even when we're about to
# execute it, to prevent races with functions like
# start_fetching_next_page that reset _final_result
self._callbacks.append((fn, args, kwargs))
if self._final_result is not _NOT_SET:
run_now = True
if run_now:
fn(self._final_result, *args, **kwargs)
return self | [
"def",
"add_callback",
"(",
"self",
",",
"fn",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"run_now",
"=",
"False",
"with",
"self",
".",
"_callback_lock",
":",
"# Always add fn to self._callbacks, even when we're about to",
"# execute it, to prevent races wit... | Attaches a callback function to be called when the final results arrive.
By default, `fn` will be called with the results as the first and only
argument. If `*args` or `**kwargs` are supplied, they will be passed
through as additional positional or keyword arguments to `fn`.
If an error is hit while executing the operation, a callback attached
here will not be called. Use :meth:`.add_errback()` or :meth:`add_callbacks()`
if you wish to handle that case.
If the final result has already been seen when this method is called,
the callback will be called immediately (before this method returns).
Note: in the case that the result is not available when the callback is added,
the callback is executed by IO event thread. This means that the callback
should not block or attempt further synchronous requests, because no further
IO will be processed until the callback returns.
**Important**: if the callback you attach results in an exception being
raised, **the exception will be ignored**, so please ensure your
callback handles all error cases that you care about.
Usage example::
>>> session = cluster.connect("mykeyspace")
>>> def handle_results(rows, start_time, should_log=False):
... if should_log:
... log.info("Total time: %f", time.time() - start_time)
... ...
>>> future = session.execute_async("SELECT * FROM users")
>>> future.add_callback(handle_results, time.time(), should_log=True) | [
"Attaches",
"a",
"callback",
"function",
"to",
"be",
"called",
"when",
"the",
"final",
"results",
"arrive",
"."
] | 30a80d0b798b1f45f8cb77163b1fa791f3e3ca29 | https://github.com/datastax/python-driver/blob/30a80d0b798b1f45f8cb77163b1fa791f3e3ca29/cassandra/cluster.py#L4224-L4271 |
229,189 | datastax/python-driver | cassandra/cluster.py | ResultSet.was_applied | def was_applied(self):
"""
For LWT results, returns whether the transaction was applied.
Result is indeterminate if called on a result that was not an LWT request or on
a :class:`.query.BatchStatement` containing LWT. In the latter case either all the batch
succeeds or fails.
Only valid when one of the of the internal row factories is in use.
"""
if self.response_future.row_factory not in (named_tuple_factory, dict_factory, tuple_factory):
raise RuntimeError("Cannot determine LWT result with row factory %s" % (self.response_future.row_factory,))
is_batch_statement = isinstance(self.response_future.query, BatchStatement)
if is_batch_statement and (not self.column_names or self.column_names[0] != "[applied]"):
raise RuntimeError("No LWT were present in the BatchStatement")
if not is_batch_statement and len(self.current_rows) != 1:
raise RuntimeError("LWT result should have exactly one row. This has %d." % (len(self.current_rows)))
row = self.current_rows[0]
if isinstance(row, tuple):
return row[0]
else:
return row['[applied]'] | python | def was_applied(self):
if self.response_future.row_factory not in (named_tuple_factory, dict_factory, tuple_factory):
raise RuntimeError("Cannot determine LWT result with row factory %s" % (self.response_future.row_factory,))
is_batch_statement = isinstance(self.response_future.query, BatchStatement)
if is_batch_statement and (not self.column_names or self.column_names[0] != "[applied]"):
raise RuntimeError("No LWT were present in the BatchStatement")
if not is_batch_statement and len(self.current_rows) != 1:
raise RuntimeError("LWT result should have exactly one row. This has %d." % (len(self.current_rows)))
row = self.current_rows[0]
if isinstance(row, tuple):
return row[0]
else:
return row['[applied]'] | [
"def",
"was_applied",
"(",
"self",
")",
":",
"if",
"self",
".",
"response_future",
".",
"row_factory",
"not",
"in",
"(",
"named_tuple_factory",
",",
"dict_factory",
",",
"tuple_factory",
")",
":",
"raise",
"RuntimeError",
"(",
"\"Cannot determine LWT result with row... | For LWT results, returns whether the transaction was applied.
Result is indeterminate if called on a result that was not an LWT request or on
a :class:`.query.BatchStatement` containing LWT. In the latter case either all the batch
succeeds or fails.
Only valid when one of the of the internal row factories is in use. | [
"For",
"LWT",
"results",
"returns",
"whether",
"the",
"transaction",
"was",
"applied",
"."
] | 30a80d0b798b1f45f8cb77163b1fa791f3e3ca29 | https://github.com/datastax/python-driver/blob/30a80d0b798b1f45f8cb77163b1fa791f3e3ca29/cassandra/cluster.py#L4492-L4516 |
229,190 | XuShaohua/bcloud | bcloud/Shutdown.py | Shutdown._prepair | def _prepair(self):
'''Try to connect to the given dbus services. If successful it will
return a callable dbus proxy and those arguments.
'''
try:
sessionbus = dbus.SessionBus()
systembus = dbus.SystemBus()
except:
return (None, None)
for dbus_props in self.DBUS_SHUTDOWN.values():
try:
if dbus_props['bus'] == SESSION_BUS:
bus = sessionbus
else:
bus = systembus
interface = bus.get_object(dbus_props['service'],
dbus_props['objectPath'])
proxy = interface.get_dbus_method(dbus_props['method'],
dbus_props['interface'])
return (proxy, dbus_props['arguments'])
except dbus.exceptions.DBusException:
continue
return (None, None) | python | def _prepair(self):
'''Try to connect to the given dbus services. If successful it will
return a callable dbus proxy and those arguments.
'''
try:
sessionbus = dbus.SessionBus()
systembus = dbus.SystemBus()
except:
return (None, None)
for dbus_props in self.DBUS_SHUTDOWN.values():
try:
if dbus_props['bus'] == SESSION_BUS:
bus = sessionbus
else:
bus = systembus
interface = bus.get_object(dbus_props['service'],
dbus_props['objectPath'])
proxy = interface.get_dbus_method(dbus_props['method'],
dbus_props['interface'])
return (proxy, dbus_props['arguments'])
except dbus.exceptions.DBusException:
continue
return (None, None) | [
"def",
"_prepair",
"(",
"self",
")",
":",
"try",
":",
"sessionbus",
"=",
"dbus",
".",
"SessionBus",
"(",
")",
"systembus",
"=",
"dbus",
".",
"SystemBus",
"(",
")",
"except",
":",
"return",
"(",
"None",
",",
"None",
")",
"for",
"dbus_props",
"in",
"se... | Try to connect to the given dbus services. If successful it will
return a callable dbus proxy and those arguments. | [
"Try",
"to",
"connect",
"to",
"the",
"given",
"dbus",
"services",
".",
"If",
"successful",
"it",
"will",
"return",
"a",
"callable",
"dbus",
"proxy",
"and",
"those",
"arguments",
"."
] | 4b54e0fdccf2b3013285fef05c97354cfa31697b | https://github.com/XuShaohua/bcloud/blob/4b54e0fdccf2b3013285fef05c97354cfa31697b/bcloud/Shutdown.py#L127-L149 |
229,191 | XuShaohua/bcloud | bcloud/Shutdown.py | Shutdown.shutdown | def shutdown(self):
'''Call the dbus proxy to start the shutdown.'''
if self._proxy:
os.sync()
self._proxy(*self._args) | python | def shutdown(self):
'''Call the dbus proxy to start the shutdown.'''
if self._proxy:
os.sync()
self._proxy(*self._args) | [
"def",
"shutdown",
"(",
"self",
")",
":",
"if",
"self",
".",
"_proxy",
":",
"os",
".",
"sync",
"(",
")",
"self",
".",
"_proxy",
"(",
"*",
"self",
".",
"_args",
")"
] | Call the dbus proxy to start the shutdown. | [
"Call",
"the",
"dbus",
"proxy",
"to",
"start",
"the",
"shutdown",
"."
] | 4b54e0fdccf2b3013285fef05c97354cfa31697b | https://github.com/XuShaohua/bcloud/blob/4b54e0fdccf2b3013285fef05c97354cfa31697b/bcloud/Shutdown.py#L151-L155 |
229,192 | XuShaohua/bcloud | bcloud/App.py | App.on_app_shutdown | def on_app_shutdown(self, app):
'''Dump profile content to disk'''
if self.filewatcher:
self.filewatcher.stop()
if self.profile:
self.upload_page.on_destroy()
self.download_page.on_destroy() | python | def on_app_shutdown(self, app):
'''Dump profile content to disk'''
if self.filewatcher:
self.filewatcher.stop()
if self.profile:
self.upload_page.on_destroy()
self.download_page.on_destroy() | [
"def",
"on_app_shutdown",
"(",
"self",
",",
"app",
")",
":",
"if",
"self",
".",
"filewatcher",
":",
"self",
".",
"filewatcher",
".",
"stop",
"(",
")",
"if",
"self",
".",
"profile",
":",
"self",
".",
"upload_page",
".",
"on_destroy",
"(",
")",
"self",
... | Dump profile content to disk | [
"Dump",
"profile",
"content",
"to",
"disk"
] | 4b54e0fdccf2b3013285fef05c97354cfa31697b | https://github.com/XuShaohua/bcloud/blob/4b54e0fdccf2b3013285fef05c97354cfa31697b/bcloud/App.py#L188-L195 |
229,193 | XuShaohua/bcloud | bcloud/gutil.py | async_call | def async_call(func, *args, callback=None):
'''Call `func` in background thread, and then call `callback` in Gtk main thread.
If error occurs in `func`, error will keep the traceback and passed to
`callback` as second parameter. Always check `error` is not None.
'''
def do_call():
result = None
error = None
try:
result = func(*args)
except Exception:
error = traceback.format_exc()
logger.error(error)
if callback:
GLib.idle_add(callback, result, error)
thread = threading.Thread(target=do_call)
thread.daemon = True
thread.start() | python | def async_call(func, *args, callback=None):
'''Call `func` in background thread, and then call `callback` in Gtk main thread.
If error occurs in `func`, error will keep the traceback and passed to
`callback` as second parameter. Always check `error` is not None.
'''
def do_call():
result = None
error = None
try:
result = func(*args)
except Exception:
error = traceback.format_exc()
logger.error(error)
if callback:
GLib.idle_add(callback, result, error)
thread = threading.Thread(target=do_call)
thread.daemon = True
thread.start() | [
"def",
"async_call",
"(",
"func",
",",
"*",
"args",
",",
"callback",
"=",
"None",
")",
":",
"def",
"do_call",
"(",
")",
":",
"result",
"=",
"None",
"error",
"=",
"None",
"try",
":",
"result",
"=",
"func",
"(",
"*",
"args",
")",
"except",
"Exception... | Call `func` in background thread, and then call `callback` in Gtk main thread.
If error occurs in `func`, error will keep the traceback and passed to
`callback` as second parameter. Always check `error` is not None. | [
"Call",
"func",
"in",
"background",
"thread",
"and",
"then",
"call",
"callback",
"in",
"Gtk",
"main",
"thread",
"."
] | 4b54e0fdccf2b3013285fef05c97354cfa31697b | https://github.com/XuShaohua/bcloud/blob/4b54e0fdccf2b3013285fef05c97354cfa31697b/bcloud/gutil.py#L102-L122 |
229,194 | onnx/onnxmltools | onnxmltools/convert/coreml/operator_converters/neural_network/Pool.py | calculate_legacy_pad_amount | def calculate_legacy_pad_amount(H_in, pad_h, k_h, s_h):
'''
This function calculate padding amount along H-axis. It can be applied to other axes. It should be only used with
pooling conversion.
:param H_in: input dimension along H-axis
:param pad_h: padding amount at H-axis
:param k_h: kernel's H-axis dimension
:param s_h: stride along H-axis
:return: (top_padding_amount, bottom_padding_amount)
'''
# Calculate a common variable
H_temp = H_in + 2 * pad_h - k_h
# Pooling output shape under CoerML IncludeLastPixel padding mode
H_include_last_pad_out = math.ceil(H_temp / s_h) + 1
# Pooling output shape under valid padding mode
H_valid_pad_out = math.floor(H_temp / s_h) + 1
# Amount of values padded at top boundary. For max pooling, the padded value should be "-inf."
# For average pooling, we should pad zeros.
pad_t = pad_h
# Amount of values padded at bottom boundary (add extra pixels so that H_include_last_pad_out = floor( (H_adjusted_out - k_h) / stride) + 1)
if H_include_last_pad_out > H_valid_pad_out:
pad_b = pad_h + (s_h - H_temp % s_h)
else:
pad_b = pad_h
# Intermediate result with pad_t values at top and pad_b valules at bottom of the original input
H_adjusted_out = H_in + pad_t + pad_b
# Adjust padded result if the original pooling wants to cut off the last output pixel.
if (H_include_last_pad_out - 1) * s_h >= H_in + pad_h:
if H_adjusted_out % s_h == 0:
H_adjusted_out -= s_h
else:
H_adjusted_out -= H_adjusted_out % s_h
return (pad_t, H_adjusted_out - pad_t - H_in) | python | def calculate_legacy_pad_amount(H_in, pad_h, k_h, s_h):
'''
This function calculate padding amount along H-axis. It can be applied to other axes. It should be only used with
pooling conversion.
:param H_in: input dimension along H-axis
:param pad_h: padding amount at H-axis
:param k_h: kernel's H-axis dimension
:param s_h: stride along H-axis
:return: (top_padding_amount, bottom_padding_amount)
'''
# Calculate a common variable
H_temp = H_in + 2 * pad_h - k_h
# Pooling output shape under CoerML IncludeLastPixel padding mode
H_include_last_pad_out = math.ceil(H_temp / s_h) + 1
# Pooling output shape under valid padding mode
H_valid_pad_out = math.floor(H_temp / s_h) + 1
# Amount of values padded at top boundary. For max pooling, the padded value should be "-inf."
# For average pooling, we should pad zeros.
pad_t = pad_h
# Amount of values padded at bottom boundary (add extra pixels so that H_include_last_pad_out = floor( (H_adjusted_out - k_h) / stride) + 1)
if H_include_last_pad_out > H_valid_pad_out:
pad_b = pad_h + (s_h - H_temp % s_h)
else:
pad_b = pad_h
# Intermediate result with pad_t values at top and pad_b valules at bottom of the original input
H_adjusted_out = H_in + pad_t + pad_b
# Adjust padded result if the original pooling wants to cut off the last output pixel.
if (H_include_last_pad_out - 1) * s_h >= H_in + pad_h:
if H_adjusted_out % s_h == 0:
H_adjusted_out -= s_h
else:
H_adjusted_out -= H_adjusted_out % s_h
return (pad_t, H_adjusted_out - pad_t - H_in) | [
"def",
"calculate_legacy_pad_amount",
"(",
"H_in",
",",
"pad_h",
",",
"k_h",
",",
"s_h",
")",
":",
"# Calculate a common variable",
"H_temp",
"=",
"H_in",
"+",
"2",
"*",
"pad_h",
"-",
"k_h",
"# Pooling output shape under CoerML IncludeLastPixel padding mode",
"H_include... | This function calculate padding amount along H-axis. It can be applied to other axes. It should be only used with
pooling conversion.
:param H_in: input dimension along H-axis
:param pad_h: padding amount at H-axis
:param k_h: kernel's H-axis dimension
:param s_h: stride along H-axis
:return: (top_padding_amount, bottom_padding_amount) | [
"This",
"function",
"calculate",
"padding",
"amount",
"along",
"H",
"-",
"axis",
".",
"It",
"can",
"be",
"applied",
"to",
"other",
"axes",
".",
"It",
"should",
"be",
"only",
"used",
"with",
"pooling",
"conversion",
"."
] | d4e4c31990fc2d9fd1f92139f497d360914c9df2 | https://github.com/onnx/onnxmltools/blob/d4e4c31990fc2d9fd1f92139f497d360914c9df2/onnxmltools/convert/coreml/operator_converters/neural_network/Pool.py#L13-L46 |
229,195 | onnx/onnxmltools | onnxmltools/convert/coreml/operator_converters/neural_network/Pool.py | create_legacy_pad | def create_legacy_pad(scope, input_name, output_name, H_in, W_in, k_h, k_w,
s_h, s_w, p_h, p_w, padded_value, container):
'''
This function adds one Pad operator into its last argument, which is a Container object. By feeding the output of
the created Pad operator into Pool operator under valid padding mode, we can achieve the same functionality of
CoreML' pooling under IncludeLastPixel padding mode.
:param scope:
:param input_name:
:param output_name:
:param H_in: input dimension along H-axis
:param W_in: input dimension along W-axis
:param k_h: kernel's H-axis dimension
:param k_w: kernel's W-axis dimension
:param s_h: stride along H-axis
:param s_w: stride along W-axis
:param p_h: padding amount at the beginning and the end of H-axis
:param p_w: padding amount at the beginning and the end of W-axis
:param padded_value: value used to fill padded area
:param container: Container object
'''
# Add a Pad operator to pre-process 4-D tensor
pad_t, pad_b = calculate_legacy_pad_amount(H_in, p_h, k_h, s_h)
pad_l, pad_r = calculate_legacy_pad_amount(W_in, p_w, k_w, s_w)
# CoreML pooling operator pads only their H- and W-axes. Here we assume the shape of the tensor to be padded
# is [N, C, H, W], so we have 8 padding amounts
# pads = [N_begin_index, C_begin_index, H_begin_index, W_begin_index,
# N_end_index, C_end_index, H_end_index, W_end_index]
# Because only H- and W-axes are padded in CoreML, we leave padding amounts of N- and C-axes zeros.
pads = [0, 0, pad_t, pad_l, 0, 0, pad_b, pad_r]
apply_pad(scope, input_name, output_name, container, pads=pads, value=padded_value) | python | def create_legacy_pad(scope, input_name, output_name, H_in, W_in, k_h, k_w,
s_h, s_w, p_h, p_w, padded_value, container):
'''
This function adds one Pad operator into its last argument, which is a Container object. By feeding the output of
the created Pad operator into Pool operator under valid padding mode, we can achieve the same functionality of
CoreML' pooling under IncludeLastPixel padding mode.
:param scope:
:param input_name:
:param output_name:
:param H_in: input dimension along H-axis
:param W_in: input dimension along W-axis
:param k_h: kernel's H-axis dimension
:param k_w: kernel's W-axis dimension
:param s_h: stride along H-axis
:param s_w: stride along W-axis
:param p_h: padding amount at the beginning and the end of H-axis
:param p_w: padding amount at the beginning and the end of W-axis
:param padded_value: value used to fill padded area
:param container: Container object
'''
# Add a Pad operator to pre-process 4-D tensor
pad_t, pad_b = calculate_legacy_pad_amount(H_in, p_h, k_h, s_h)
pad_l, pad_r = calculate_legacy_pad_amount(W_in, p_w, k_w, s_w)
# CoreML pooling operator pads only their H- and W-axes. Here we assume the shape of the tensor to be padded
# is [N, C, H, W], so we have 8 padding amounts
# pads = [N_begin_index, C_begin_index, H_begin_index, W_begin_index,
# N_end_index, C_end_index, H_end_index, W_end_index]
# Because only H- and W-axes are padded in CoreML, we leave padding amounts of N- and C-axes zeros.
pads = [0, 0, pad_t, pad_l, 0, 0, pad_b, pad_r]
apply_pad(scope, input_name, output_name, container, pads=pads, value=padded_value) | [
"def",
"create_legacy_pad",
"(",
"scope",
",",
"input_name",
",",
"output_name",
",",
"H_in",
",",
"W_in",
",",
"k_h",
",",
"k_w",
",",
"s_h",
",",
"s_w",
",",
"p_h",
",",
"p_w",
",",
"padded_value",
",",
"container",
")",
":",
"# Add a Pad operator to pre... | This function adds one Pad operator into its last argument, which is a Container object. By feeding the output of
the created Pad operator into Pool operator under valid padding mode, we can achieve the same functionality of
CoreML' pooling under IncludeLastPixel padding mode.
:param scope:
:param input_name:
:param output_name:
:param H_in: input dimension along H-axis
:param W_in: input dimension along W-axis
:param k_h: kernel's H-axis dimension
:param k_w: kernel's W-axis dimension
:param s_h: stride along H-axis
:param s_w: stride along W-axis
:param p_h: padding amount at the beginning and the end of H-axis
:param p_w: padding amount at the beginning and the end of W-axis
:param padded_value: value used to fill padded area
:param container: Container object | [
"This",
"function",
"adds",
"one",
"Pad",
"operator",
"into",
"its",
"last",
"argument",
"which",
"is",
"a",
"Container",
"object",
".",
"By",
"feeding",
"the",
"output",
"of",
"the",
"created",
"Pad",
"operator",
"into",
"Pool",
"operator",
"under",
"valid"... | d4e4c31990fc2d9fd1f92139f497d360914c9df2 | https://github.com/onnx/onnxmltools/blob/d4e4c31990fc2d9fd1f92139f497d360914c9df2/onnxmltools/convert/coreml/operator_converters/neural_network/Pool.py#L49-L80 |
229,196 | onnx/onnxmltools | onnxmltools/convert/coreml/_parse.py | _parse_model | def _parse_model(topology, scope, model, inputs=None, outputs=None):
'''
This is a delegate function of all top-level parsing functions. It does nothing but call a proper function
to parse the given model.
'''
if inputs is None:
inputs = list()
if outputs is None:
outputs = list()
model_type = model.WhichOneof('Type')
if model_type in ['pipeline', 'pipelineClassifier', 'pipelineRegressor']:
_parse_pipeline_model(topology, scope, model, inputs, outputs)
elif model_type in ['neuralNetworkClassifier', 'neuralNetworkRegressor', 'neuralNetwork']:
_parse_neural_network_model(topology, scope, model, inputs, outputs)
else:
_parse_simple_model(topology, scope, model, inputs, outputs) | python | def _parse_model(topology, scope, model, inputs=None, outputs=None):
'''
This is a delegate function of all top-level parsing functions. It does nothing but call a proper function
to parse the given model.
'''
if inputs is None:
inputs = list()
if outputs is None:
outputs = list()
model_type = model.WhichOneof('Type')
if model_type in ['pipeline', 'pipelineClassifier', 'pipelineRegressor']:
_parse_pipeline_model(topology, scope, model, inputs, outputs)
elif model_type in ['neuralNetworkClassifier', 'neuralNetworkRegressor', 'neuralNetwork']:
_parse_neural_network_model(topology, scope, model, inputs, outputs)
else:
_parse_simple_model(topology, scope, model, inputs, outputs) | [
"def",
"_parse_model",
"(",
"topology",
",",
"scope",
",",
"model",
",",
"inputs",
"=",
"None",
",",
"outputs",
"=",
"None",
")",
":",
"if",
"inputs",
"is",
"None",
":",
"inputs",
"=",
"list",
"(",
")",
"if",
"outputs",
"is",
"None",
":",
"outputs",
... | This is a delegate function of all top-level parsing functions. It does nothing but call a proper function
to parse the given model. | [
"This",
"is",
"a",
"delegate",
"function",
"of",
"all",
"top",
"-",
"level",
"parsing",
"functions",
".",
"It",
"does",
"nothing",
"but",
"call",
"a",
"proper",
"function",
"to",
"parse",
"the",
"given",
"model",
"."
] | d4e4c31990fc2d9fd1f92139f497d360914c9df2 | https://github.com/onnx/onnxmltools/blob/d4e4c31990fc2d9fd1f92139f497d360914c9df2/onnxmltools/convert/coreml/_parse.py#L103-L120 |
229,197 | onnx/onnxmltools | onnxmltools/convert/coreml/shape_calculators/neural_network/LSTM.py | calculate_lstm_output_shapes | def calculate_lstm_output_shapes(operator):
'''
See LSTM's conversion function for its output shapes.
'''
check_input_and_output_numbers(operator, input_count_range=[1, 3], output_count_range=[1, 3])
check_input_and_output_types(operator, good_input_types=[FloatTensorType])
input_shape = operator.inputs[0].type.shape
if len(input_shape) not in [2, 4]:
raise RuntimeError('Input must be a 2-D tensor')
params = operator.raw_operator.uniDirectionalLSTM
# The following line is more accurate but it may break some tests
# output_shape = ['None', params.outputVectorSize] if params.params.sequenceOutput else [1, params.outputVectorSize]
output_shape = ['None', params.outputVectorSize]
state_shape = [1, params.outputVectorSize]
# TODO: Changing input shapes of an operator is dangerous, this should be move to Topology's _fix_shapes function
if len(operator.inputs) > 1:
Y_h_in = operator.inputs[1] # The initial hidden state of a single sequence
Y_h_in.type.shape = state_shape
if len(operator.inputs) > 2:
Y_c_in = operator.inputs[2] # The initial cell state of a single sequence
Y_c_in.type.shape = state_shape
operator.outputs[0].type.shape = output_shape
if len(operator.outputs) > 1:
operator.outputs[1].type.shape = state_shape
if len(operator.outputs) > 2:
operator.outputs[2].type.shape = state_shape | python | def calculate_lstm_output_shapes(operator):
'''
See LSTM's conversion function for its output shapes.
'''
check_input_and_output_numbers(operator, input_count_range=[1, 3], output_count_range=[1, 3])
check_input_and_output_types(operator, good_input_types=[FloatTensorType])
input_shape = operator.inputs[0].type.shape
if len(input_shape) not in [2, 4]:
raise RuntimeError('Input must be a 2-D tensor')
params = operator.raw_operator.uniDirectionalLSTM
# The following line is more accurate but it may break some tests
# output_shape = ['None', params.outputVectorSize] if params.params.sequenceOutput else [1, params.outputVectorSize]
output_shape = ['None', params.outputVectorSize]
state_shape = [1, params.outputVectorSize]
# TODO: Changing input shapes of an operator is dangerous, this should be move to Topology's _fix_shapes function
if len(operator.inputs) > 1:
Y_h_in = operator.inputs[1] # The initial hidden state of a single sequence
Y_h_in.type.shape = state_shape
if len(operator.inputs) > 2:
Y_c_in = operator.inputs[2] # The initial cell state of a single sequence
Y_c_in.type.shape = state_shape
operator.outputs[0].type.shape = output_shape
if len(operator.outputs) > 1:
operator.outputs[1].type.shape = state_shape
if len(operator.outputs) > 2:
operator.outputs[2].type.shape = state_shape | [
"def",
"calculate_lstm_output_shapes",
"(",
"operator",
")",
":",
"check_input_and_output_numbers",
"(",
"operator",
",",
"input_count_range",
"=",
"[",
"1",
",",
"3",
"]",
",",
"output_count_range",
"=",
"[",
"1",
",",
"3",
"]",
")",
"check_input_and_output_types... | See LSTM's conversion function for its output shapes. | [
"See",
"LSTM",
"s",
"conversion",
"function",
"for",
"its",
"output",
"shapes",
"."
] | d4e4c31990fc2d9fd1f92139f497d360914c9df2 | https://github.com/onnx/onnxmltools/blob/d4e4c31990fc2d9fd1f92139f497d360914c9df2/onnxmltools/convert/coreml/shape_calculators/neural_network/LSTM.py#L12-L43 |
229,198 | onnx/onnxmltools | onnxmltools/convert/xgboost/common.py | get_xgb_params | def get_xgb_params(xgb_node):
"""
Retrieves parameters of a model.
"""
if hasattr(xgb_node, 'kwargs'):
# XGBoost >= 0.7
params = xgb_node.get_xgb_params()
else:
# XGBoost < 0.7
params = xgb_node.__dict__
return params | python | def get_xgb_params(xgb_node):
if hasattr(xgb_node, 'kwargs'):
# XGBoost >= 0.7
params = xgb_node.get_xgb_params()
else:
# XGBoost < 0.7
params = xgb_node.__dict__
return params | [
"def",
"get_xgb_params",
"(",
"xgb_node",
")",
":",
"if",
"hasattr",
"(",
"xgb_node",
",",
"'kwargs'",
")",
":",
"# XGBoost >= 0.7",
"params",
"=",
"xgb_node",
".",
"get_xgb_params",
"(",
")",
"else",
":",
"# XGBoost < 0.7",
"params",
"=",
"xgb_node",
".",
"... | Retrieves parameters of a model. | [
"Retrieves",
"parameters",
"of",
"a",
"model",
"."
] | d4e4c31990fc2d9fd1f92139f497d360914c9df2 | https://github.com/onnx/onnxmltools/blob/d4e4c31990fc2d9fd1f92139f497d360914c9df2/onnxmltools/convert/xgboost/common.py#L5-L16 |
229,199 | onnx/onnxmltools | onnxmltools/proto/__init__.py | _make_tensor_fixed | def _make_tensor_fixed(name, data_type, dims, vals, raw=False):
'''
Make a TensorProto with specified arguments. If raw is False, this
function will choose the corresponding proto field to store the
values based on data_type. If raw is True, use "raw_data" proto
field to store the values, and values should be of type bytes in
this case.
'''
tensor = TensorProto()
tensor.data_type = data_type
tensor.name = name
if (data_type == TensorProto.COMPLEX64 or
data_type == TensorProto.COMPLEX128):
vals = split_complex_to_pairs(vals)
if raw:
tensor.raw_data = vals
else:
field = mapping.STORAGE_TENSOR_TYPE_TO_FIELD[
mapping.TENSOR_TYPE_TO_STORAGE_TENSOR_TYPE[data_type]]
getattr(tensor, field).extend(vals)
tensor.dims.extend(dims)
return tensor | python | def _make_tensor_fixed(name, data_type, dims, vals, raw=False):
'''
Make a TensorProto with specified arguments. If raw is False, this
function will choose the corresponding proto field to store the
values based on data_type. If raw is True, use "raw_data" proto
field to store the values, and values should be of type bytes in
this case.
'''
tensor = TensorProto()
tensor.data_type = data_type
tensor.name = name
if (data_type == TensorProto.COMPLEX64 or
data_type == TensorProto.COMPLEX128):
vals = split_complex_to_pairs(vals)
if raw:
tensor.raw_data = vals
else:
field = mapping.STORAGE_TENSOR_TYPE_TO_FIELD[
mapping.TENSOR_TYPE_TO_STORAGE_TENSOR_TYPE[data_type]]
getattr(tensor, field).extend(vals)
tensor.dims.extend(dims)
return tensor | [
"def",
"_make_tensor_fixed",
"(",
"name",
",",
"data_type",
",",
"dims",
",",
"vals",
",",
"raw",
"=",
"False",
")",
":",
"tensor",
"=",
"TensorProto",
"(",
")",
"tensor",
".",
"data_type",
"=",
"data_type",
"tensor",
".",
"name",
"=",
"name",
"if",
"(... | Make a TensorProto with specified arguments. If raw is False, this
function will choose the corresponding proto field to store the
values based on data_type. If raw is True, use "raw_data" proto
field to store the values, and values should be of type bytes in
this case. | [
"Make",
"a",
"TensorProto",
"with",
"specified",
"arguments",
".",
"If",
"raw",
"is",
"False",
"this",
"function",
"will",
"choose",
"the",
"corresponding",
"proto",
"field",
"to",
"store",
"the",
"values",
"based",
"on",
"data_type",
".",
"If",
"raw",
"is",... | d4e4c31990fc2d9fd1f92139f497d360914c9df2 | https://github.com/onnx/onnxmltools/blob/d4e4c31990fc2d9fd1f92139f497d360914c9df2/onnxmltools/proto/__init__.py#L24-L47 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.