repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
Yelp/kafka-utils
kafka_utils/kafka_cluster_manager/cluster_info/rg.py
ReplicationGroup.add_broker
def add_broker(self, broker): """Add broker to current broker-list.""" if broker not in self._brokers: self._brokers.add(broker) else: self.log.warning( 'Broker {broker_id} already present in ' 'replication-group {rg_id}'.format( broker_id=broker.id, rg_id=self._id, ) )
python
def add_broker(self, broker): """Add broker to current broker-list.""" if broker not in self._brokers: self._brokers.add(broker) else: self.log.warning( 'Broker {broker_id} already present in ' 'replication-group {rg_id}'.format( broker_id=broker.id, rg_id=self._id, ) )
[ "def", "add_broker", "(", "self", ",", "broker", ")", ":", "if", "broker", "not", "in", "self", ".", "_brokers", ":", "self", ".", "_brokers", ".", "add", "(", "broker", ")", "else", ":", "self", ".", "log", ".", "warning", "(", "'Broker {broker_id} al...
Add broker to current broker-list.
[ "Add", "broker", "to", "current", "broker", "-", "list", "." ]
cdb4d64308f3079ee0873250bf7b34d0d94eca50
https://github.com/Yelp/kafka-utils/blob/cdb4d64308f3079ee0873250bf7b34d0d94eca50/kafka_utils/kafka_cluster_manager/cluster_info/rg.py#L64-L75
train
202,700
Yelp/kafka-utils
kafka_utils/kafka_cluster_manager/cluster_info/rg.py
ReplicationGroup.count_replica
def count_replica(self, partition): """Return count of replicas of given partition.""" return sum(1 for b in partition.replicas if b in self.brokers)
python
def count_replica(self, partition): """Return count of replicas of given partition.""" return sum(1 for b in partition.replicas if b in self.brokers)
[ "def", "count_replica", "(", "self", ",", "partition", ")", ":", "return", "sum", "(", "1", "for", "b", "in", "partition", ".", "replicas", "if", "b", "in", "self", ".", "brokers", ")" ]
Return count of replicas of given partition.
[ "Return", "count", "of", "replicas", "of", "given", "partition", "." ]
cdb4d64308f3079ee0873250bf7b34d0d94eca50
https://github.com/Yelp/kafka-utils/blob/cdb4d64308f3079ee0873250bf7b34d0d94eca50/kafka_utils/kafka_cluster_manager/cluster_info/rg.py#L88-L90
train
202,701
Yelp/kafka-utils
kafka_utils/kafka_cluster_manager/cluster_info/rg.py
ReplicationGroup.acquire_partition
def acquire_partition(self, partition, source_broker): """Move a partition from a broker to any of the eligible brokers of the replication group. :param partition: Partition to move :param source_broker: Broker the partition currently belongs to """ broker_dest = self._elect_dest_broker(partition) if not broker_dest: raise NotEligibleGroupError( "No eligible brokers to accept partition {p}".format(p=partition), ) source_broker.move_partition(partition, broker_dest)
python
def acquire_partition(self, partition, source_broker): """Move a partition from a broker to any of the eligible brokers of the replication group. :param partition: Partition to move :param source_broker: Broker the partition currently belongs to """ broker_dest = self._elect_dest_broker(partition) if not broker_dest: raise NotEligibleGroupError( "No eligible brokers to accept partition {p}".format(p=partition), ) source_broker.move_partition(partition, broker_dest)
[ "def", "acquire_partition", "(", "self", ",", "partition", ",", "source_broker", ")", ":", "broker_dest", "=", "self", ".", "_elect_dest_broker", "(", "partition", ")", "if", "not", "broker_dest", ":", "raise", "NotEligibleGroupError", "(", "\"No eligible brokers to...
Move a partition from a broker to any of the eligible brokers of the replication group. :param partition: Partition to move :param source_broker: Broker the partition currently belongs to
[ "Move", "a", "partition", "from", "a", "broker", "to", "any", "of", "the", "eligible", "brokers", "of", "the", "replication", "group", "." ]
cdb4d64308f3079ee0873250bf7b34d0d94eca50
https://github.com/Yelp/kafka-utils/blob/cdb4d64308f3079ee0873250bf7b34d0d94eca50/kafka_utils/kafka_cluster_manager/cluster_info/rg.py#L92-L104
train
202,702
Yelp/kafka-utils
kafka_utils/kafka_cluster_manager/cluster_info/rg.py
ReplicationGroup._select_broker_pair
def _select_broker_pair(self, rg_destination, victim_partition): """Select best-fit source and destination brokers based on partition count and presence of partition over the broker. * Get overloaded and underloaded brokers Best-fit Selection Criteria: Source broker: Select broker containing the victim-partition with maximum partitions. Destination broker: NOT containing the victim-partition with minimum partitions. If no such broker found, return first broker. This helps in ensuring:- * Topic-partitions are distributed across brokers. * Partition-count is balanced across replication-groups. """ broker_source = self._elect_source_broker(victim_partition) broker_destination = rg_destination._elect_dest_broker(victim_partition) return broker_source, broker_destination
python
def _select_broker_pair(self, rg_destination, victim_partition): """Select best-fit source and destination brokers based on partition count and presence of partition over the broker. * Get overloaded and underloaded brokers Best-fit Selection Criteria: Source broker: Select broker containing the victim-partition with maximum partitions. Destination broker: NOT containing the victim-partition with minimum partitions. If no such broker found, return first broker. This helps in ensuring:- * Topic-partitions are distributed across brokers. * Partition-count is balanced across replication-groups. """ broker_source = self._elect_source_broker(victim_partition) broker_destination = rg_destination._elect_dest_broker(victim_partition) return broker_source, broker_destination
[ "def", "_select_broker_pair", "(", "self", ",", "rg_destination", ",", "victim_partition", ")", ":", "broker_source", "=", "self", ".", "_elect_source_broker", "(", "victim_partition", ")", "broker_destination", "=", "rg_destination", ".", "_elect_dest_broker", "(", "...
Select best-fit source and destination brokers based on partition count and presence of partition over the broker. * Get overloaded and underloaded brokers Best-fit Selection Criteria: Source broker: Select broker containing the victim-partition with maximum partitions. Destination broker: NOT containing the victim-partition with minimum partitions. If no such broker found, return first broker. This helps in ensuring:- * Topic-partitions are distributed across brokers. * Partition-count is balanced across replication-groups.
[ "Select", "best", "-", "fit", "source", "and", "destination", "brokers", "based", "on", "partition", "count", "and", "presence", "of", "partition", "over", "the", "broker", "." ]
cdb4d64308f3079ee0873250bf7b34d0d94eca50
https://github.com/Yelp/kafka-utils/blob/cdb4d64308f3079ee0873250bf7b34d0d94eca50/kafka_utils/kafka_cluster_manager/cluster_info/rg.py#L132-L149
train
202,703
Yelp/kafka-utils
kafka_utils/kafka_cluster_manager/cluster_info/rg.py
ReplicationGroup._elect_source_broker
def _elect_source_broker(self, victim_partition, broker_subset=None): """Select first over loaded broker having victim_partition. Note: The broker with maximum siblings of victim-partitions (same topic) is selected to reduce topic-partition imbalance. """ broker_subset = broker_subset or self._brokers over_loaded_brokers = sorted( [ broker for broker in broker_subset if victim_partition in broker.partitions and not broker.inactive ], key=lambda b: len(b.partitions), reverse=True, ) if not over_loaded_brokers: return None broker_topic_partition_cnt = [ (broker, broker.count_partitions(victim_partition.topic)) for broker in over_loaded_brokers ] max_count_pair = max( broker_topic_partition_cnt, key=lambda ele: ele[1], ) return max_count_pair[0]
python
def _elect_source_broker(self, victim_partition, broker_subset=None): """Select first over loaded broker having victim_partition. Note: The broker with maximum siblings of victim-partitions (same topic) is selected to reduce topic-partition imbalance. """ broker_subset = broker_subset or self._brokers over_loaded_brokers = sorted( [ broker for broker in broker_subset if victim_partition in broker.partitions and not broker.inactive ], key=lambda b: len(b.partitions), reverse=True, ) if not over_loaded_brokers: return None broker_topic_partition_cnt = [ (broker, broker.count_partitions(victim_partition.topic)) for broker in over_loaded_brokers ] max_count_pair = max( broker_topic_partition_cnt, key=lambda ele: ele[1], ) return max_count_pair[0]
[ "def", "_elect_source_broker", "(", "self", ",", "victim_partition", ",", "broker_subset", "=", "None", ")", ":", "broker_subset", "=", "broker_subset", "or", "self", ".", "_brokers", "over_loaded_brokers", "=", "sorted", "(", "[", "broker", "for", "broker", "in...
Select first over loaded broker having victim_partition. Note: The broker with maximum siblings of victim-partitions (same topic) is selected to reduce topic-partition imbalance.
[ "Select", "first", "over", "loaded", "broker", "having", "victim_partition", "." ]
cdb4d64308f3079ee0873250bf7b34d0d94eca50
https://github.com/Yelp/kafka-utils/blob/cdb4d64308f3079ee0873250bf7b34d0d94eca50/kafka_utils/kafka_cluster_manager/cluster_info/rg.py#L151-L178
train
202,704
Yelp/kafka-utils
kafka_utils/kafka_cluster_manager/cluster_info/rg.py
ReplicationGroup._elect_dest_broker
def _elect_dest_broker(self, victim_partition): """Select first under loaded brokers preferring not having partition of same topic as victim partition. """ under_loaded_brokers = sorted( [ broker for broker in self._brokers if (victim_partition not in broker.partitions and not broker.inactive and not broker.decommissioned) ], key=lambda b: len(b.partitions) ) if not under_loaded_brokers: return None broker_topic_partition_cnt = [ (broker, broker.count_partitions(victim_partition.topic)) for broker in under_loaded_brokers if victim_partition not in broker.partitions ] min_count_pair = min( broker_topic_partition_cnt, key=lambda ele: ele[1], ) return min_count_pair[0]
python
def _elect_dest_broker(self, victim_partition): """Select first under loaded brokers preferring not having partition of same topic as victim partition. """ under_loaded_brokers = sorted( [ broker for broker in self._brokers if (victim_partition not in broker.partitions and not broker.inactive and not broker.decommissioned) ], key=lambda b: len(b.partitions) ) if not under_loaded_brokers: return None broker_topic_partition_cnt = [ (broker, broker.count_partitions(victim_partition.topic)) for broker in under_loaded_brokers if victim_partition not in broker.partitions ] min_count_pair = min( broker_topic_partition_cnt, key=lambda ele: ele[1], ) return min_count_pair[0]
[ "def", "_elect_dest_broker", "(", "self", ",", "victim_partition", ")", ":", "under_loaded_brokers", "=", "sorted", "(", "[", "broker", "for", "broker", "in", "self", ".", "_brokers", "if", "(", "victim_partition", "not", "in", "broker", ".", "partitions", "an...
Select first under loaded brokers preferring not having partition of same topic as victim partition.
[ "Select", "first", "under", "loaded", "brokers", "preferring", "not", "having", "partition", "of", "same", "topic", "as", "victim", "partition", "." ]
cdb4d64308f3079ee0873250bf7b34d0d94eca50
https://github.com/Yelp/kafka-utils/blob/cdb4d64308f3079ee0873250bf7b34d0d94eca50/kafka_utils/kafka_cluster_manager/cluster_info/rg.py#L180-L206
train
202,705
Yelp/kafka-utils
kafka_utils/kafka_cluster_manager/cluster_info/rg.py
ReplicationGroup.rebalance_brokers
def rebalance_brokers(self): """Rebalance partition-count across brokers.""" total_partitions = sum(len(b.partitions) for b in self.brokers) blacklist = set(b for b in self.brokers if b.decommissioned) active_brokers = self.get_active_brokers() - blacklist if not active_brokers: raise EmptyReplicationGroupError("No active brokers in %s", self._id) # Separate brokers based on partition count over_loaded_brokers, under_loaded_brokers = separate_groups( active_brokers, lambda b: len(b.partitions), total_partitions, ) # Decommissioned brokers are considered overloaded until they have # no more partitions assigned. over_loaded_brokers += [b for b in blacklist if not b.empty()] if not over_loaded_brokers and not under_loaded_brokers: self.log.info( 'Brokers of replication-group: %s already balanced for ' 'partition-count.', self._id, ) return sibling_distance = self.generate_sibling_distance() while under_loaded_brokers and over_loaded_brokers: # Get best-fit source-broker, destination-broker and partition broker_source, broker_destination, victim_partition = \ self._get_target_brokers( over_loaded_brokers, under_loaded_brokers, sibling_distance, ) # No valid source or target brokers found if broker_source and broker_destination: # Move partition self.log.debug( 'Moving partition {p_name} from broker {broker_source} to ' 'broker {broker_destination}' .format( p_name=victim_partition.name, broker_source=broker_source.id, broker_destination=broker_destination.id, ), ) broker_source.move_partition(victim_partition, broker_destination) sibling_distance = self.update_sibling_distance( sibling_distance, broker_destination, victim_partition.topic, ) else: # Brokers are balanced or could not be balanced further break # Re-evaluate under and over-loaded brokers over_loaded_brokers, under_loaded_brokers = separate_groups( active_brokers, lambda b: len(b.partitions), total_partitions, ) # As before add brokers to decommission. over_loaded_brokers += [b for b in blacklist if not b.empty()]
python
def rebalance_brokers(self): """Rebalance partition-count across brokers.""" total_partitions = sum(len(b.partitions) for b in self.brokers) blacklist = set(b for b in self.brokers if b.decommissioned) active_brokers = self.get_active_brokers() - blacklist if not active_brokers: raise EmptyReplicationGroupError("No active brokers in %s", self._id) # Separate brokers based on partition count over_loaded_brokers, under_loaded_brokers = separate_groups( active_brokers, lambda b: len(b.partitions), total_partitions, ) # Decommissioned brokers are considered overloaded until they have # no more partitions assigned. over_loaded_brokers += [b for b in blacklist if not b.empty()] if not over_loaded_brokers and not under_loaded_brokers: self.log.info( 'Brokers of replication-group: %s already balanced for ' 'partition-count.', self._id, ) return sibling_distance = self.generate_sibling_distance() while under_loaded_brokers and over_loaded_brokers: # Get best-fit source-broker, destination-broker and partition broker_source, broker_destination, victim_partition = \ self._get_target_brokers( over_loaded_brokers, under_loaded_brokers, sibling_distance, ) # No valid source or target brokers found if broker_source and broker_destination: # Move partition self.log.debug( 'Moving partition {p_name} from broker {broker_source} to ' 'broker {broker_destination}' .format( p_name=victim_partition.name, broker_source=broker_source.id, broker_destination=broker_destination.id, ), ) broker_source.move_partition(victim_partition, broker_destination) sibling_distance = self.update_sibling_distance( sibling_distance, broker_destination, victim_partition.topic, ) else: # Brokers are balanced or could not be balanced further break # Re-evaluate under and over-loaded brokers over_loaded_brokers, under_loaded_brokers = separate_groups( active_brokers, lambda b: len(b.partitions), total_partitions, ) # As before add brokers to decommission. over_loaded_brokers += [b for b in blacklist if not b.empty()]
[ "def", "rebalance_brokers", "(", "self", ")", ":", "total_partitions", "=", "sum", "(", "len", "(", "b", ".", "partitions", ")", "for", "b", "in", "self", ".", "brokers", ")", "blacklist", "=", "set", "(", "b", "for", "b", "in", "self", ".", "brokers...
Rebalance partition-count across brokers.
[ "Rebalance", "partition", "-", "count", "across", "brokers", "." ]
cdb4d64308f3079ee0873250bf7b34d0d94eca50
https://github.com/Yelp/kafka-utils/blob/cdb4d64308f3079ee0873250bf7b34d0d94eca50/kafka_utils/kafka_cluster_manager/cluster_info/rg.py#L212-L273
train
202,706
Yelp/kafka-utils
kafka_utils/kafka_cluster_manager/cluster_info/rg.py
ReplicationGroup._get_target_brokers
def _get_target_brokers(self, over_loaded_brokers, under_loaded_brokers, sibling_distance): """Pick best-suitable source-broker, destination-broker and partition to balance partition-count over brokers in given replication-group. """ # Sort given brokers to ensure determinism over_loaded_brokers = sorted( over_loaded_brokers, key=lambda b: len(b.partitions), reverse=True, ) under_loaded_brokers = sorted( under_loaded_brokers, key=lambda b: len(b.partitions), ) # pick pair of brokers from source and destination brokers with # minimum same-partition-count # Set result in format: (source, dest, preferred-partition) target = (None, None, None) min_distance = sys.maxsize best_partition = None for source in over_loaded_brokers: for dest in under_loaded_brokers: # A decommissioned broker can have less partitions than # destination. We consider it a valid source because we want to # move all the partitions out from it. if (len(source.partitions) - len(dest.partitions) > 1 or source.decommissioned): best_partition = source.get_preferred_partition( dest, sibling_distance[dest][source], ) # If no eligible partition continue with next broker. if best_partition is None: continue distance = sibling_distance[dest][source][best_partition.topic] if distance < min_distance: min_distance = distance target = (source, dest, best_partition) else: # If relatively-unbalanced then all brokers in destination # will be thereafter, return from here. break return target
python
def _get_target_brokers(self, over_loaded_brokers, under_loaded_brokers, sibling_distance): """Pick best-suitable source-broker, destination-broker and partition to balance partition-count over brokers in given replication-group. """ # Sort given brokers to ensure determinism over_loaded_brokers = sorted( over_loaded_brokers, key=lambda b: len(b.partitions), reverse=True, ) under_loaded_brokers = sorted( under_loaded_brokers, key=lambda b: len(b.partitions), ) # pick pair of brokers from source and destination brokers with # minimum same-partition-count # Set result in format: (source, dest, preferred-partition) target = (None, None, None) min_distance = sys.maxsize best_partition = None for source in over_loaded_brokers: for dest in under_loaded_brokers: # A decommissioned broker can have less partitions than # destination. We consider it a valid source because we want to # move all the partitions out from it. if (len(source.partitions) - len(dest.partitions) > 1 or source.decommissioned): best_partition = source.get_preferred_partition( dest, sibling_distance[dest][source], ) # If no eligible partition continue with next broker. if best_partition is None: continue distance = sibling_distance[dest][source][best_partition.topic] if distance < min_distance: min_distance = distance target = (source, dest, best_partition) else: # If relatively-unbalanced then all brokers in destination # will be thereafter, return from here. break return target
[ "def", "_get_target_brokers", "(", "self", ",", "over_loaded_brokers", ",", "under_loaded_brokers", ",", "sibling_distance", ")", ":", "# Sort given brokers to ensure determinism", "over_loaded_brokers", "=", "sorted", "(", "over_loaded_brokers", ",", "key", "=", "lambda", ...
Pick best-suitable source-broker, destination-broker and partition to balance partition-count over brokers in given replication-group.
[ "Pick", "best", "-", "suitable", "source", "-", "broker", "destination", "-", "broker", "and", "partition", "to", "balance", "partition", "-", "count", "over", "brokers", "in", "given", "replication", "-", "group", "." ]
cdb4d64308f3079ee0873250bf7b34d0d94eca50
https://github.com/Yelp/kafka-utils/blob/cdb4d64308f3079ee0873250bf7b34d0d94eca50/kafka_utils/kafka_cluster_manager/cluster_info/rg.py#L275-L317
train
202,707
Yelp/kafka-utils
kafka_utils/kafka_cluster_manager/cluster_info/rg.py
ReplicationGroup.generate_sibling_distance
def generate_sibling_distance(self): """Generate a dict containing the distance computed as difference in in number of partitions of each topic from under_loaded_brokers to over_loaded_brokers. Negative distance means that the destination broker has got less partitions of a certain topic than the source broker. returns: dict {dest: {source: {topic: distance}}} """ sibling_distance = defaultdict(lambda: defaultdict(dict)) topics = {p.topic for p in self.partitions} for source in self.brokers: for dest in self.brokers: if source != dest: for topic in topics: sibling_distance[dest][source][topic] = \ dest.count_partitions(topic) - \ source.count_partitions(topic) return sibling_distance
python
def generate_sibling_distance(self): """Generate a dict containing the distance computed as difference in in number of partitions of each topic from under_loaded_brokers to over_loaded_brokers. Negative distance means that the destination broker has got less partitions of a certain topic than the source broker. returns: dict {dest: {source: {topic: distance}}} """ sibling_distance = defaultdict(lambda: defaultdict(dict)) topics = {p.topic for p in self.partitions} for source in self.brokers: for dest in self.brokers: if source != dest: for topic in topics: sibling_distance[dest][source][topic] = \ dest.count_partitions(topic) - \ source.count_partitions(topic) return sibling_distance
[ "def", "generate_sibling_distance", "(", "self", ")", ":", "sibling_distance", "=", "defaultdict", "(", "lambda", ":", "defaultdict", "(", "dict", ")", ")", "topics", "=", "{", "p", ".", "topic", "for", "p", "in", "self", ".", "partitions", "}", "for", "...
Generate a dict containing the distance computed as difference in in number of partitions of each topic from under_loaded_brokers to over_loaded_brokers. Negative distance means that the destination broker has got less partitions of a certain topic than the source broker. returns: dict {dest: {source: {topic: distance}}}
[ "Generate", "a", "dict", "containing", "the", "distance", "computed", "as", "difference", "in", "in", "number", "of", "partitions", "of", "each", "topic", "from", "under_loaded_brokers", "to", "over_loaded_brokers", "." ]
cdb4d64308f3079ee0873250bf7b34d0d94eca50
https://github.com/Yelp/kafka-utils/blob/cdb4d64308f3079ee0873250bf7b34d0d94eca50/kafka_utils/kafka_cluster_manager/cluster_info/rg.py#L319-L338
train
202,708
Yelp/kafka-utils
kafka_utils/kafka_cluster_manager/cluster_info/rg.py
ReplicationGroup.update_sibling_distance
def update_sibling_distance(self, sibling_distance, dest, topic): """Update the sibling distance for topic and destination broker.""" for source in six.iterkeys(sibling_distance[dest]): sibling_distance[dest][source][topic] = \ dest.count_partitions(topic) - \ source.count_partitions(topic) return sibling_distance
python
def update_sibling_distance(self, sibling_distance, dest, topic): """Update the sibling distance for topic and destination broker.""" for source in six.iterkeys(sibling_distance[dest]): sibling_distance[dest][source][topic] = \ dest.count_partitions(topic) - \ source.count_partitions(topic) return sibling_distance
[ "def", "update_sibling_distance", "(", "self", ",", "sibling_distance", ",", "dest", ",", "topic", ")", ":", "for", "source", "in", "six", ".", "iterkeys", "(", "sibling_distance", "[", "dest", "]", ")", ":", "sibling_distance", "[", "dest", "]", "[", "sou...
Update the sibling distance for topic and destination broker.
[ "Update", "the", "sibling", "distance", "for", "topic", "and", "destination", "broker", "." ]
cdb4d64308f3079ee0873250bf7b34d0d94eca50
https://github.com/Yelp/kafka-utils/blob/cdb4d64308f3079ee0873250bf7b34d0d94eca50/kafka_utils/kafka_cluster_manager/cluster_info/rg.py#L340-L346
train
202,709
Yelp/kafka-utils
kafka_utils/kafka_cluster_manager/cluster_info/rg.py
ReplicationGroup.move_partition_replica
def move_partition_replica(self, under_loaded_rg, eligible_partition): """Move partition to under-loaded replication-group if possible.""" # Evaluate possible source and destination-broker source_broker, dest_broker = self._get_eligible_broker_pair( under_loaded_rg, eligible_partition, ) if source_broker and dest_broker: self.log.debug( 'Moving partition {p_name} from broker {source_broker} to ' 'replication-group:broker {rg_dest}:{dest_broker}'.format( p_name=eligible_partition.name, source_broker=source_broker.id, dest_broker=dest_broker.id, rg_dest=under_loaded_rg.id, ), ) # Move partition if eligible brokers found source_broker.move_partition(eligible_partition, dest_broker)
python
def move_partition_replica(self, under_loaded_rg, eligible_partition): """Move partition to under-loaded replication-group if possible.""" # Evaluate possible source and destination-broker source_broker, dest_broker = self._get_eligible_broker_pair( under_loaded_rg, eligible_partition, ) if source_broker and dest_broker: self.log.debug( 'Moving partition {p_name} from broker {source_broker} to ' 'replication-group:broker {rg_dest}:{dest_broker}'.format( p_name=eligible_partition.name, source_broker=source_broker.id, dest_broker=dest_broker.id, rg_dest=under_loaded_rg.id, ), ) # Move partition if eligible brokers found source_broker.move_partition(eligible_partition, dest_broker)
[ "def", "move_partition_replica", "(", "self", ",", "under_loaded_rg", ",", "eligible_partition", ")", ":", "# Evaluate possible source and destination-broker", "source_broker", ",", "dest_broker", "=", "self", ".", "_get_eligible_broker_pair", "(", "under_loaded_rg", ",", "...
Move partition to under-loaded replication-group if possible.
[ "Move", "partition", "to", "under", "-", "loaded", "replication", "-", "group", "if", "possible", "." ]
cdb4d64308f3079ee0873250bf7b34d0d94eca50
https://github.com/Yelp/kafka-utils/blob/cdb4d64308f3079ee0873250bf7b34d0d94eca50/kafka_utils/kafka_cluster_manager/cluster_info/rg.py#L348-L366
train
202,710
Yelp/kafka-utils
kafka_utils/kafka_cluster_manager/cluster_info/rg.py
ReplicationGroup._get_eligible_broker_pair
def _get_eligible_broker_pair(self, under_loaded_rg, eligible_partition): """Evaluate and return source and destination broker-pair from over-loaded and under-loaded replication-group if possible, return None otherwise. Return source broker with maximum partitions and destination broker with minimum partitions based on following conditions:- 1) At-least one broker in under-loaded group which does not have victim-partition. This is because a broker cannot have duplicate replica. 2) At-least one broker in over-loaded group which has victim-partition """ under_brokers = list(filter( lambda b: eligible_partition not in b.partitions, under_loaded_rg.brokers, )) over_brokers = list(filter( lambda b: eligible_partition in b.partitions, self.brokers, )) # Get source and destination broker source_broker, dest_broker = None, None if over_brokers: source_broker = max( over_brokers, key=lambda broker: len(broker.partitions), ) if under_brokers: dest_broker = min( under_brokers, key=lambda broker: len(broker.partitions), ) return (source_broker, dest_broker)
python
def _get_eligible_broker_pair(self, under_loaded_rg, eligible_partition): """Evaluate and return source and destination broker-pair from over-loaded and under-loaded replication-group if possible, return None otherwise. Return source broker with maximum partitions and destination broker with minimum partitions based on following conditions:- 1) At-least one broker in under-loaded group which does not have victim-partition. This is because a broker cannot have duplicate replica. 2) At-least one broker in over-loaded group which has victim-partition """ under_brokers = list(filter( lambda b: eligible_partition not in b.partitions, under_loaded_rg.brokers, )) over_brokers = list(filter( lambda b: eligible_partition in b.partitions, self.brokers, )) # Get source and destination broker source_broker, dest_broker = None, None if over_brokers: source_broker = max( over_brokers, key=lambda broker: len(broker.partitions), ) if under_brokers: dest_broker = min( under_brokers, key=lambda broker: len(broker.partitions), ) return (source_broker, dest_broker)
[ "def", "_get_eligible_broker_pair", "(", "self", ",", "under_loaded_rg", ",", "eligible_partition", ")", ":", "under_brokers", "=", "list", "(", "filter", "(", "lambda", "b", ":", "eligible_partition", "not", "in", "b", ".", "partitions", ",", "under_loaded_rg", ...
Evaluate and return source and destination broker-pair from over-loaded and under-loaded replication-group if possible, return None otherwise. Return source broker with maximum partitions and destination broker with minimum partitions based on following conditions:- 1) At-least one broker in under-loaded group which does not have victim-partition. This is because a broker cannot have duplicate replica. 2) At-least one broker in over-loaded group which has victim-partition
[ "Evaluate", "and", "return", "source", "and", "destination", "broker", "-", "pair", "from", "over", "-", "loaded", "and", "under", "-", "loaded", "replication", "-", "group", "if", "possible", "return", "None", "otherwise", "." ]
cdb4d64308f3079ee0873250bf7b34d0d94eca50
https://github.com/Yelp/kafka-utils/blob/cdb4d64308f3079ee0873250bf7b34d0d94eca50/kafka_utils/kafka_cluster_manager/cluster_info/rg.py#L368-L399
train
202,711
NoneGG/aredis
aredis/utils.py
merge_result
def merge_result(res): """ Merge all items in `res` into a list. This command is used when sending a command to multiple nodes and they result from each node should be merged into a single list. """ if not isinstance(res, dict): raise ValueError('Value should be of dict type') result = set([]) for _, v in res.items(): for value in v: result.add(value) return list(result)
python
def merge_result(res): """ Merge all items in `res` into a list. This command is used when sending a command to multiple nodes and they result from each node should be merged into a single list. """ if not isinstance(res, dict): raise ValueError('Value should be of dict type') result = set([]) for _, v in res.items(): for value in v: result.add(value) return list(result)
[ "def", "merge_result", "(", "res", ")", ":", "if", "not", "isinstance", "(", "res", ",", "dict", ")", ":", "raise", "ValueError", "(", "'Value should be of dict type'", ")", "result", "=", "set", "(", "[", "]", ")", "for", "_", ",", "v", "in", "res", ...
Merge all items in `res` into a list. This command is used when sending a command to multiple nodes and they result from each node should be merged into a single list.
[ "Merge", "all", "items", "in", "res", "into", "a", "list", "." ]
204caad740ac13e5760d46444a2ba7632982a046
https://github.com/NoneGG/aredis/blob/204caad740ac13e5760d46444a2ba7632982a046/aredis/utils.py#L110-L126
train
202,712
NoneGG/aredis
aredis/utils.py
first_key
def first_key(res): """ Returns the first result for the given command. If more then 1 result is returned then a `RedisClusterException` is raised. """ if not isinstance(res, dict): raise ValueError('Value should be of dict type') if len(res.keys()) != 1: raise RedisClusterException("More then 1 result from command") return list(res.values())[0]
python
def first_key(res): """ Returns the first result for the given command. If more then 1 result is returned then a `RedisClusterException` is raised. """ if not isinstance(res, dict): raise ValueError('Value should be of dict type') if len(res.keys()) != 1: raise RedisClusterException("More then 1 result from command") return list(res.values())[0]
[ "def", "first_key", "(", "res", ")", ":", "if", "not", "isinstance", "(", "res", ",", "dict", ")", ":", "raise", "ValueError", "(", "'Value should be of dict type'", ")", "if", "len", "(", "res", ".", "keys", "(", ")", ")", "!=", "1", ":", "raise", "...
Returns the first result for the given command. If more then 1 result is returned then a `RedisClusterException` is raised.
[ "Returns", "the", "first", "result", "for", "the", "given", "command", "." ]
204caad740ac13e5760d46444a2ba7632982a046
https://github.com/NoneGG/aredis/blob/204caad740ac13e5760d46444a2ba7632982a046/aredis/utils.py#L129-L141
train
202,713
NoneGG/aredis
aredis/utils.py
clusterdown_wrapper
def clusterdown_wrapper(func): """ Wrapper for CLUSTERDOWN error handling. If the cluster reports it is down it is assumed that: - connection_pool was disconnected - connection_pool was reseted - refereh_table_asap set to True It will try 3 times to rerun the command and raises ClusterDownException if it continues to fail. """ @wraps(func) async def inner(*args, **kwargs): for _ in range(0, 3): try: return await func(*args, **kwargs) except ClusterDownError: # Try again with the new cluster setup. All other errors # should be raised. pass # If it fails 3 times then raise exception back to caller raise ClusterDownError("CLUSTERDOWN error. Unable to rebuild the cluster") return inner
python
def clusterdown_wrapper(func): """ Wrapper for CLUSTERDOWN error handling. If the cluster reports it is down it is assumed that: - connection_pool was disconnected - connection_pool was reseted - refereh_table_asap set to True It will try 3 times to rerun the command and raises ClusterDownException if it continues to fail. """ @wraps(func) async def inner(*args, **kwargs): for _ in range(0, 3): try: return await func(*args, **kwargs) except ClusterDownError: # Try again with the new cluster setup. All other errors # should be raised. pass # If it fails 3 times then raise exception back to caller raise ClusterDownError("CLUSTERDOWN error. Unable to rebuild the cluster") return inner
[ "def", "clusterdown_wrapper", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "async", "def", "inner", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "for", "_", "in", "range", "(", "0", ",", "3", ")", ":", "try", ":", "return", "a...
Wrapper for CLUSTERDOWN error handling. If the cluster reports it is down it is assumed that: - connection_pool was disconnected - connection_pool was reseted - refereh_table_asap set to True It will try 3 times to rerun the command and raises ClusterDownException if it continues to fail.
[ "Wrapper", "for", "CLUSTERDOWN", "error", "handling", "." ]
204caad740ac13e5760d46444a2ba7632982a046
https://github.com/NoneGG/aredis/blob/204caad740ac13e5760d46444a2ba7632982a046/aredis/utils.py#L151-L176
train
202,714
NoneGG/aredis
aredis/commands/server.py
parse_debug_object
def parse_debug_object(response): "Parse the results of Redis's DEBUG OBJECT command into a Python dict" # The 'type' of the object is the first item in the response, but isn't # prefixed with a name response = nativestr(response) response = 'type:' + response response = dict([kv.split(':') for kv in response.split()]) # parse some expected int values from the string response # note: this cmd isn't spec'd so these may not appear in all redis versions int_fields = ('refcount', 'serializedlength', 'lru', 'lru_seconds_idle') for field in int_fields: if field in response: response[field] = int(response[field]) return response
python
def parse_debug_object(response): "Parse the results of Redis's DEBUG OBJECT command into a Python dict" # The 'type' of the object is the first item in the response, but isn't # prefixed with a name response = nativestr(response) response = 'type:' + response response = dict([kv.split(':') for kv in response.split()]) # parse some expected int values from the string response # note: this cmd isn't spec'd so these may not appear in all redis versions int_fields = ('refcount', 'serializedlength', 'lru', 'lru_seconds_idle') for field in int_fields: if field in response: response[field] = int(response[field]) return response
[ "def", "parse_debug_object", "(", "response", ")", ":", "# The 'type' of the object is the first item in the response, but isn't", "# prefixed with a name", "response", "=", "nativestr", "(", "response", ")", "response", "=", "'type:'", "+", "response", "response", "=", "di...
Parse the results of Redis's DEBUG OBJECT command into a Python dict
[ "Parse", "the", "results", "of", "Redis", "s", "DEBUG", "OBJECT", "command", "into", "a", "Python", "dict" ]
204caad740ac13e5760d46444a2ba7632982a046
https://github.com/NoneGG/aredis/blob/204caad740ac13e5760d46444a2ba7632982a046/aredis/commands/server.py#L44-L59
train
202,715
NoneGG/aredis
aredis/commands/server.py
parse_info
def parse_info(response): "Parse the result of Redis's INFO command into a Python dict" info = {} response = nativestr(response) def get_value(value): if ',' not in value or '=' not in value: try: if '.' in value: return float(value) else: return int(value) except ValueError: return value else: sub_dict = {} for item in value.split(','): k, v = item.rsplit('=', 1) sub_dict[k] = get_value(v) return sub_dict for line in response.splitlines(): if line and not line.startswith('#'): if line.find(':') != -1: key, value = line.split(':', 1) info[key] = get_value(value) else: # if the line isn't splittable, append it to the "__raw__" key info.setdefault('__raw__', []).append(line) return info
python
def parse_info(response): "Parse the result of Redis's INFO command into a Python dict" info = {} response = nativestr(response) def get_value(value): if ',' not in value or '=' not in value: try: if '.' in value: return float(value) else: return int(value) except ValueError: return value else: sub_dict = {} for item in value.split(','): k, v = item.rsplit('=', 1) sub_dict[k] = get_value(v) return sub_dict for line in response.splitlines(): if line and not line.startswith('#'): if line.find(':') != -1: key, value = line.split(':', 1) info[key] = get_value(value) else: # if the line isn't splittable, append it to the "__raw__" key info.setdefault('__raw__', []).append(line) return info
[ "def", "parse_info", "(", "response", ")", ":", "info", "=", "{", "}", "response", "=", "nativestr", "(", "response", ")", "def", "get_value", "(", "value", ")", ":", "if", "','", "not", "in", "value", "or", "'='", "not", "in", "value", ":", "try", ...
Parse the result of Redis's INFO command into a Python dict
[ "Parse", "the", "result", "of", "Redis", "s", "INFO", "command", "into", "a", "Python", "dict" ]
204caad740ac13e5760d46444a2ba7632982a046
https://github.com/NoneGG/aredis/blob/204caad740ac13e5760d46444a2ba7632982a046/aredis/commands/server.py#L62-L92
train
202,716
NoneGG/aredis
aredis/commands/server.py
ServerCommandMixin.slowlog_get
async def slowlog_get(self, num=None): """ Get the entries from the slowlog. If ``num`` is specified, get the most recent ``num`` items. """ args = ['SLOWLOG GET'] if num is not None: args.append(num) return await self.execute_command(*args)
python
async def slowlog_get(self, num=None): """ Get the entries from the slowlog. If ``num`` is specified, get the most recent ``num`` items. """ args = ['SLOWLOG GET'] if num is not None: args.append(num) return await self.execute_command(*args)
[ "async", "def", "slowlog_get", "(", "self", ",", "num", "=", "None", ")", ":", "args", "=", "[", "'SLOWLOG GET'", "]", "if", "num", "is", "not", "None", ":", "args", ".", "append", "(", "num", ")", "return", "await", "self", ".", "execute_command", "...
Get the entries from the slowlog. If ``num`` is specified, get the most recent ``num`` items.
[ "Get", "the", "entries", "from", "the", "slowlog", ".", "If", "num", "is", "specified", "get", "the", "most", "recent", "num", "items", "." ]
204caad740ac13e5760d46444a2ba7632982a046
https://github.com/NoneGG/aredis/blob/204caad740ac13e5760d46444a2ba7632982a046/aredis/commands/server.py#L276-L284
train
202,717
NoneGG/aredis
aredis/commands/extra.py
ExtraCommandMixin.cache
def cache(self, name, cache_class=Cache, identity_generator_class=IdentityGenerator, compressor_class=Compressor, serializer_class=Serializer, *args, **kwargs): """ Return a cache object using default identity generator, serializer and compressor. ``name`` is used to identify the series of your cache ``cache_class`` Cache is for normal use and HerdCache is used in case of Thundering Herd Problem ``identity_generator_class`` is the class used to generate the real unique key in cache, can be overwritten to meet your special needs. It should provide `generate` API ``compressor_class`` is the class used to compress cache in redis, can be overwritten with API `compress` and `decompress` retained. ``serializer_class`` is the class used to serialize content before compress, can be overwritten with API `serialize` and `deserialize` retained. """ return cache_class(self, app=name, identity_generator_class=identity_generator_class, compressor_class=compressor_class, serializer_class=serializer_class, *args, **kwargs)
python
def cache(self, name, cache_class=Cache, identity_generator_class=IdentityGenerator, compressor_class=Compressor, serializer_class=Serializer, *args, **kwargs): """ Return a cache object using default identity generator, serializer and compressor. ``name`` is used to identify the series of your cache ``cache_class`` Cache is for normal use and HerdCache is used in case of Thundering Herd Problem ``identity_generator_class`` is the class used to generate the real unique key in cache, can be overwritten to meet your special needs. It should provide `generate` API ``compressor_class`` is the class used to compress cache in redis, can be overwritten with API `compress` and `decompress` retained. ``serializer_class`` is the class used to serialize content before compress, can be overwritten with API `serialize` and `deserialize` retained. """ return cache_class(self, app=name, identity_generator_class=identity_generator_class, compressor_class=compressor_class, serializer_class=serializer_class, *args, **kwargs)
[ "def", "cache", "(", "self", ",", "name", ",", "cache_class", "=", "Cache", ",", "identity_generator_class", "=", "IdentityGenerator", ",", "compressor_class", "=", "Compressor", ",", "serializer_class", "=", "Serializer", ",", "*", "args", ",", "*", "*", "kwa...
Return a cache object using default identity generator, serializer and compressor. ``name`` is used to identify the series of your cache ``cache_class`` Cache is for normal use and HerdCache is used in case of Thundering Herd Problem ``identity_generator_class`` is the class used to generate the real unique key in cache, can be overwritten to meet your special needs. It should provide `generate` API ``compressor_class`` is the class used to compress cache in redis, can be overwritten with API `compress` and `decompress` retained. ``serializer_class`` is the class used to serialize content before compress, can be overwritten with API `serialize` and `deserialize` retained.
[ "Return", "a", "cache", "object", "using", "default", "identity", "generator", "serializer", "and", "compressor", "." ]
204caad740ac13e5760d46444a2ba7632982a046
https://github.com/NoneGG/aredis/blob/204caad740ac13e5760d46444a2ba7632982a046/aredis/commands/extra.py#L11-L35
train
202,718
NoneGG/aredis
aredis/commands/hash.py
HashCommandMixin.hincrby
async def hincrby(self, name, key, amount=1): "Increment the value of ``key`` in hash ``name`` by ``amount``" return await self.execute_command('HINCRBY', name, key, amount)
python
async def hincrby(self, name, key, amount=1): "Increment the value of ``key`` in hash ``name`` by ``amount``" return await self.execute_command('HINCRBY', name, key, amount)
[ "async", "def", "hincrby", "(", "self", ",", "name", ",", "key", ",", "amount", "=", "1", ")", ":", "return", "await", "self", ".", "execute_command", "(", "'HINCRBY'", ",", "name", ",", "key", ",", "amount", ")" ]
Increment the value of ``key`` in hash ``name`` by ``amount``
[ "Increment", "the", "value", "of", "key", "in", "hash", "name", "by", "amount" ]
204caad740ac13e5760d46444a2ba7632982a046
https://github.com/NoneGG/aredis/blob/204caad740ac13e5760d46444a2ba7632982a046/aredis/commands/hash.py#L43-L45
train
202,719
NoneGG/aredis
aredis/commands/hash.py
HashCommandMixin.hincrbyfloat
async def hincrbyfloat(self, name, key, amount=1.0): """ Increment the value of ``key`` in hash ``name`` by floating ``amount`` """ return await self.execute_command('HINCRBYFLOAT', name, key, amount)
python
async def hincrbyfloat(self, name, key, amount=1.0): """ Increment the value of ``key`` in hash ``name`` by floating ``amount`` """ return await self.execute_command('HINCRBYFLOAT', name, key, amount)
[ "async", "def", "hincrbyfloat", "(", "self", ",", "name", ",", "key", ",", "amount", "=", "1.0", ")", ":", "return", "await", "self", ".", "execute_command", "(", "'HINCRBYFLOAT'", ",", "name", ",", "key", ",", "amount", ")" ]
Increment the value of ``key`` in hash ``name`` by floating ``amount``
[ "Increment", "the", "value", "of", "key", "in", "hash", "name", "by", "floating", "amount" ]
204caad740ac13e5760d46444a2ba7632982a046
https://github.com/NoneGG/aredis/blob/204caad740ac13e5760d46444a2ba7632982a046/aredis/commands/hash.py#L47-L51
train
202,720
NoneGG/aredis
aredis/commands/hash.py
HashCommandMixin.hset
async def hset(self, name, key, value): """ Set ``key`` to ``value`` within hash ``name`` Returns 1 if HSET created a new field, otherwise 0 """ return await self.execute_command('HSET', name, key, value)
python
async def hset(self, name, key, value): """ Set ``key`` to ``value`` within hash ``name`` Returns 1 if HSET created a new field, otherwise 0 """ return await self.execute_command('HSET', name, key, value)
[ "async", "def", "hset", "(", "self", ",", "name", ",", "key", ",", "value", ")", ":", "return", "await", "self", ".", "execute_command", "(", "'HSET'", ",", "name", ",", "key", ",", "value", ")" ]
Set ``key`` to ``value`` within hash ``name`` Returns 1 if HSET created a new field, otherwise 0
[ "Set", "key", "to", "value", "within", "hash", "name", "Returns", "1", "if", "HSET", "created", "a", "new", "field", "otherwise", "0" ]
204caad740ac13e5760d46444a2ba7632982a046
https://github.com/NoneGG/aredis/blob/204caad740ac13e5760d46444a2ba7632982a046/aredis/commands/hash.py#L61-L66
train
202,721
NoneGG/aredis
aredis/commands/hash.py
HashCommandMixin.hsetnx
async def hsetnx(self, name, key, value): """ Set ``key`` to ``value`` within hash ``name`` if ``key`` does not exist. Returns 1 if HSETNX created a field, otherwise 0. """ return await self.execute_command('HSETNX', name, key, value)
python
async def hsetnx(self, name, key, value): """ Set ``key`` to ``value`` within hash ``name`` if ``key`` does not exist. Returns 1 if HSETNX created a field, otherwise 0. """ return await self.execute_command('HSETNX', name, key, value)
[ "async", "def", "hsetnx", "(", "self", ",", "name", ",", "key", ",", "value", ")", ":", "return", "await", "self", ".", "execute_command", "(", "'HSETNX'", ",", "name", ",", "key", ",", "value", ")" ]
Set ``key`` to ``value`` within hash ``name`` if ``key`` does not exist. Returns 1 if HSETNX created a field, otherwise 0.
[ "Set", "key", "to", "value", "within", "hash", "name", "if", "key", "does", "not", "exist", ".", "Returns", "1", "if", "HSETNX", "created", "a", "field", "otherwise", "0", "." ]
204caad740ac13e5760d46444a2ba7632982a046
https://github.com/NoneGG/aredis/blob/204caad740ac13e5760d46444a2ba7632982a046/aredis/commands/hash.py#L68-L73
train
202,722
NoneGG/aredis
aredis/commands/hash.py
HashCommandMixin.hmset
async def hmset(self, name, mapping): """ Set key to value within hash ``name`` for each corresponding key and value from the ``mapping`` dict. """ if not mapping: raise DataError("'hmset' with 'mapping' of length 0") items = [] for pair in iteritems(mapping): items.extend(pair) return await self.execute_command('HMSET', name, *items)
python
async def hmset(self, name, mapping): """ Set key to value within hash ``name`` for each corresponding key and value from the ``mapping`` dict. """ if not mapping: raise DataError("'hmset' with 'mapping' of length 0") items = [] for pair in iteritems(mapping): items.extend(pair) return await self.execute_command('HMSET', name, *items)
[ "async", "def", "hmset", "(", "self", ",", "name", ",", "mapping", ")", ":", "if", "not", "mapping", ":", "raise", "DataError", "(", "\"'hmset' with 'mapping' of length 0\"", ")", "items", "=", "[", "]", "for", "pair", "in", "iteritems", "(", "mapping", ")...
Set key to value within hash ``name`` for each corresponding key and value from the ``mapping`` dict.
[ "Set", "key", "to", "value", "within", "hash", "name", "for", "each", "corresponding", "key", "and", "value", "from", "the", "mapping", "dict", "." ]
204caad740ac13e5760d46444a2ba7632982a046
https://github.com/NoneGG/aredis/blob/204caad740ac13e5760d46444a2ba7632982a046/aredis/commands/hash.py#L75-L85
train
202,723
NoneGG/aredis
aredis/commands/transaction.py
TransactionCommandMixin.transaction
async def transaction(self, func, *watches, **kwargs): """ Convenience method for executing the callable `func` as a transaction while watching all keys specified in `watches`. The 'func' callable should expect a single argument which is a Pipeline object. """ shard_hint = kwargs.pop('shard_hint', None) value_from_callable = kwargs.pop('value_from_callable', False) watch_delay = kwargs.pop('watch_delay', None) async with await self.pipeline(True, shard_hint) as pipe: while True: try: if watches: await pipe.watch(*watches) func_value = await func(pipe) exec_value = await pipe.execute() return func_value if value_from_callable else exec_value except WatchError: if watch_delay is not None and watch_delay > 0: await asyncio.sleep( watch_delay, loop=self.connection_pool.loop ) continue
python
async def transaction(self, func, *watches, **kwargs): """ Convenience method for executing the callable `func` as a transaction while watching all keys specified in `watches`. The 'func' callable should expect a single argument which is a Pipeline object. """ shard_hint = kwargs.pop('shard_hint', None) value_from_callable = kwargs.pop('value_from_callable', False) watch_delay = kwargs.pop('watch_delay', None) async with await self.pipeline(True, shard_hint) as pipe: while True: try: if watches: await pipe.watch(*watches) func_value = await func(pipe) exec_value = await pipe.execute() return func_value if value_from_callable else exec_value except WatchError: if watch_delay is not None and watch_delay > 0: await asyncio.sleep( watch_delay, loop=self.connection_pool.loop ) continue
[ "async", "def", "transaction", "(", "self", ",", "func", ",", "*", "watches", ",", "*", "*", "kwargs", ")", ":", "shard_hint", "=", "kwargs", ".", "pop", "(", "'shard_hint'", ",", "None", ")", "value_from_callable", "=", "kwargs", ".", "pop", "(", "'va...
Convenience method for executing the callable `func` as a transaction while watching all keys specified in `watches`. The 'func' callable should expect a single argument which is a Pipeline object.
[ "Convenience", "method", "for", "executing", "the", "callable", "func", "as", "a", "transaction", "while", "watching", "all", "keys", "specified", "in", "watches", ".", "The", "func", "callable", "should", "expect", "a", "single", "argument", "which", "is", "a...
204caad740ac13e5760d46444a2ba7632982a046
https://github.com/NoneGG/aredis/blob/204caad740ac13e5760d46444a2ba7632982a046/aredis/commands/transaction.py#L16-L39
train
202,724
NoneGG/aredis
aredis/nodemanager.py
NodeManager.initialize
async def initialize(self): """ Init the slots cache by asking all startup nodes what the current cluster configuration is TODO: Currently the last node will have the last say about how the configuration is setup. Maybe it should stop to try after it have correctly covered all slots or when one node is reached and it could execute CLUSTER SLOTS command. """ nodes_cache = {} tmp_slots = {} all_slots_covered = False disagreements = [] startup_nodes_reachable = False nodes = self.orig_startup_nodes # With this option the client will attempt to connect to any of the previous set of nodes instead of the original set of nodes if self.nodemanager_follow_cluster: nodes = self.startup_nodes for node in nodes: try: r = self.get_redis_link(host=node['host'], port=node['port']) cluster_slots = await r.cluster_slots() startup_nodes_reachable = True except ConnectionError: continue except Exception: raise RedisClusterException('ERROR sending "cluster slots" command to redis server: {0}'.format(node)) all_slots_covered = True # If there's only one server in the cluster, its ``host`` is '' # Fix it to the host in startup_nodes if len(cluster_slots) == 1 and len(self.startup_nodes) == 1: single_node_slots = cluster_slots.get((0, self.RedisClusterHashSlots - 1))[0] if len(single_node_slots['host']) == 0: single_node_slots['host'] = self.startup_nodes[0]['host'] single_node_slots['server_type'] = 'master' # No need to decode response because StrictRedis should handle that for us... for min_slot, max_slot in cluster_slots: nodes = cluster_slots.get((min_slot, max_slot)) master_node, slave_nodes = nodes[0], nodes[1:] if master_node['host'] == '': master_node['host'] = node['host'] self.set_node_name(master_node) nodes_cache[master_node['name']] = master_node for i in range(min_slot, max_slot + 1): if i not in tmp_slots: tmp_slots[i] = [master_node] for slave_node in slave_nodes: self.set_node_name(slave_node) nodes_cache[slave_node['name']] = slave_node tmp_slots[i].append(slave_node) else: # Validate that 2 nodes want to use the same slot cache setup if tmp_slots[i][0]['name'] != node['name']: disagreements.append('{0} vs {1} on slot: {2}'.format( tmp_slots[i][0]['name'], node['name'], i), ) if len(disagreements) > 5: raise RedisClusterException('startup_nodes could not agree on a valid slots cache. {0}' .format(', '.join(disagreements))) self.populate_startup_nodes() self.refresh_table_asap = False if self._skip_full_coverage_check: need_full_slots_coverage = False else: need_full_slots_coverage = await self.cluster_require_full_coverage(nodes_cache) # Validate if all slots are covered or if we should try next startup node for i in range(0, self.RedisClusterHashSlots): if i not in tmp_slots and need_full_slots_coverage: all_slots_covered = False if all_slots_covered: # All slots are covered and application can continue to execute break if not startup_nodes_reachable: raise RedisClusterException('Redis Cluster cannot be connected. ' 'Please provide at least one reachable node.') if not all_slots_covered: raise RedisClusterException('Not all slots are covered after query all startup_nodes. ' '{0} of {1} covered...'.format(len(tmp_slots), self.RedisClusterHashSlots)) # Set the tmp variables to the real variables self.slots = tmp_slots self.nodes = nodes_cache self.reinitialize_counter = 0
python
async def initialize(self): """ Init the slots cache by asking all startup nodes what the current cluster configuration is TODO: Currently the last node will have the last say about how the configuration is setup. Maybe it should stop to try after it have correctly covered all slots or when one node is reached and it could execute CLUSTER SLOTS command. """ nodes_cache = {} tmp_slots = {} all_slots_covered = False disagreements = [] startup_nodes_reachable = False nodes = self.orig_startup_nodes # With this option the client will attempt to connect to any of the previous set of nodes instead of the original set of nodes if self.nodemanager_follow_cluster: nodes = self.startup_nodes for node in nodes: try: r = self.get_redis_link(host=node['host'], port=node['port']) cluster_slots = await r.cluster_slots() startup_nodes_reachable = True except ConnectionError: continue except Exception: raise RedisClusterException('ERROR sending "cluster slots" command to redis server: {0}'.format(node)) all_slots_covered = True # If there's only one server in the cluster, its ``host`` is '' # Fix it to the host in startup_nodes if len(cluster_slots) == 1 and len(self.startup_nodes) == 1: single_node_slots = cluster_slots.get((0, self.RedisClusterHashSlots - 1))[0] if len(single_node_slots['host']) == 0: single_node_slots['host'] = self.startup_nodes[0]['host'] single_node_slots['server_type'] = 'master' # No need to decode response because StrictRedis should handle that for us... for min_slot, max_slot in cluster_slots: nodes = cluster_slots.get((min_slot, max_slot)) master_node, slave_nodes = nodes[0], nodes[1:] if master_node['host'] == '': master_node['host'] = node['host'] self.set_node_name(master_node) nodes_cache[master_node['name']] = master_node for i in range(min_slot, max_slot + 1): if i not in tmp_slots: tmp_slots[i] = [master_node] for slave_node in slave_nodes: self.set_node_name(slave_node) nodes_cache[slave_node['name']] = slave_node tmp_slots[i].append(slave_node) else: # Validate that 2 nodes want to use the same slot cache setup if tmp_slots[i][0]['name'] != node['name']: disagreements.append('{0} vs {1} on slot: {2}'.format( tmp_slots[i][0]['name'], node['name'], i), ) if len(disagreements) > 5: raise RedisClusterException('startup_nodes could not agree on a valid slots cache. {0}' .format(', '.join(disagreements))) self.populate_startup_nodes() self.refresh_table_asap = False if self._skip_full_coverage_check: need_full_slots_coverage = False else: need_full_slots_coverage = await self.cluster_require_full_coverage(nodes_cache) # Validate if all slots are covered or if we should try next startup node for i in range(0, self.RedisClusterHashSlots): if i not in tmp_slots and need_full_slots_coverage: all_slots_covered = False if all_slots_covered: # All slots are covered and application can continue to execute break if not startup_nodes_reachable: raise RedisClusterException('Redis Cluster cannot be connected. ' 'Please provide at least one reachable node.') if not all_slots_covered: raise RedisClusterException('Not all slots are covered after query all startup_nodes. ' '{0} of {1} covered...'.format(len(tmp_slots), self.RedisClusterHashSlots)) # Set the tmp variables to the real variables self.slots = tmp_slots self.nodes = nodes_cache self.reinitialize_counter = 0
[ "async", "def", "initialize", "(", "self", ")", ":", "nodes_cache", "=", "{", "}", "tmp_slots", "=", "{", "}", "all_slots_covered", "=", "False", "disagreements", "=", "[", "]", "startup_nodes_reachable", "=", "False", "nodes", "=", "self", ".", "orig_startu...
Init the slots cache by asking all startup nodes what the current cluster configuration is TODO: Currently the last node will have the last say about how the configuration is setup. Maybe it should stop to try after it have correctly covered all slots or when one node is reached and it could execute CLUSTER SLOTS command.
[ "Init", "the", "slots", "cache", "by", "asking", "all", "startup", "nodes", "what", "the", "current", "cluster", "configuration", "is" ]
204caad740ac13e5760d46444a2ba7632982a046
https://github.com/NoneGG/aredis/blob/204caad740ac13e5760d46444a2ba7632982a046/aredis/nodemanager.py#L100-L198
train
202,725
NoneGG/aredis
aredis/nodemanager.py
NodeManager.cluster_require_full_coverage
async def cluster_require_full_coverage(self, nodes_cache): """ if exists 'cluster-require-full-coverage no' config on redis servers, then even all slots are not covered, cluster still will be able to respond """ nodes = nodes_cache or self.nodes async def node_require_full_coverage(node): r_node = self.get_redis_link(host=node['host'], port=node['port']) node_config = await r_node.config_get('cluster-require-full-coverage') return 'yes' in node_config.values() # at least one node should have cluster-require-full-coverage yes for node in nodes.values(): if await node_require_full_coverage(node): return True return False
python
async def cluster_require_full_coverage(self, nodes_cache): """ if exists 'cluster-require-full-coverage no' config on redis servers, then even all slots are not covered, cluster still will be able to respond """ nodes = nodes_cache or self.nodes async def node_require_full_coverage(node): r_node = self.get_redis_link(host=node['host'], port=node['port']) node_config = await r_node.config_get('cluster-require-full-coverage') return 'yes' in node_config.values() # at least one node should have cluster-require-full-coverage yes for node in nodes.values(): if await node_require_full_coverage(node): return True return False
[ "async", "def", "cluster_require_full_coverage", "(", "self", ",", "nodes_cache", ")", ":", "nodes", "=", "nodes_cache", "or", "self", ".", "nodes", "async", "def", "node_require_full_coverage", "(", "node", ")", ":", "r_node", "=", "self", ".", "get_redis_link"...
if exists 'cluster-require-full-coverage no' config on redis servers, then even all slots are not covered, cluster still will be able to respond
[ "if", "exists", "cluster", "-", "require", "-", "full", "-", "coverage", "no", "config", "on", "redis", "servers", "then", "even", "all", "slots", "are", "not", "covered", "cluster", "still", "will", "be", "able", "to", "respond" ]
204caad740ac13e5760d46444a2ba7632982a046
https://github.com/NoneGG/aredis/blob/204caad740ac13e5760d46444a2ba7632982a046/aredis/nodemanager.py#L206-L223
train
202,726
NoneGG/aredis
aredis/nodemanager.py
NodeManager.set_node
def set_node(self, host, port, server_type=None): """ Update data for a node. """ node_name = "{0}:{1}".format(host, port) node = { 'host': host, 'port': port, 'name': node_name, 'server_type': server_type } self.nodes[node_name] = node return node
python
def set_node(self, host, port, server_type=None): """ Update data for a node. """ node_name = "{0}:{1}".format(host, port) node = { 'host': host, 'port': port, 'name': node_name, 'server_type': server_type } self.nodes[node_name] = node return node
[ "def", "set_node", "(", "self", ",", "host", ",", "port", ",", "server_type", "=", "None", ")", ":", "node_name", "=", "\"{0}:{1}\"", ".", "format", "(", "host", ",", "port", ")", "node", "=", "{", "'host'", ":", "host", ",", "'port'", ":", "port", ...
Update data for a node.
[ "Update", "data", "for", "a", "node", "." ]
204caad740ac13e5760d46444a2ba7632982a046
https://github.com/NoneGG/aredis/blob/204caad740ac13e5760d46444a2ba7632982a046/aredis/nodemanager.py#L234-L246
train
202,727
NoneGG/aredis
aredis/nodemanager.py
NodeManager.populate_startup_nodes
def populate_startup_nodes(self): """ Do something with all startup nodes and filters out any duplicates """ for item in self.startup_nodes: self.set_node_name(item) for n in self.nodes.values(): if n not in self.startup_nodes: self.startup_nodes.append(n) # freeze it so we can set() it uniq = {frozenset(node.items()) for node in self.startup_nodes} # then thaw it back out into a list of dicts self.startup_nodes = [dict(node) for node in uniq]
python
def populate_startup_nodes(self): """ Do something with all startup nodes and filters out any duplicates """ for item in self.startup_nodes: self.set_node_name(item) for n in self.nodes.values(): if n not in self.startup_nodes: self.startup_nodes.append(n) # freeze it so we can set() it uniq = {frozenset(node.items()) for node in self.startup_nodes} # then thaw it back out into a list of dicts self.startup_nodes = [dict(node) for node in uniq]
[ "def", "populate_startup_nodes", "(", "self", ")", ":", "for", "item", "in", "self", ".", "startup_nodes", ":", "self", ".", "set_node_name", "(", "item", ")", "for", "n", "in", "self", ".", "nodes", ".", "values", "(", ")", ":", "if", "n", "not", "i...
Do something with all startup nodes and filters out any duplicates
[ "Do", "something", "with", "all", "startup", "nodes", "and", "filters", "out", "any", "duplicates" ]
204caad740ac13e5760d46444a2ba7632982a046
https://github.com/NoneGG/aredis/blob/204caad740ac13e5760d46444a2ba7632982a046/aredis/nodemanager.py#L248-L262
train
202,728
NoneGG/aredis
aredis/pool.py
ClusterConnectionPool.reset
def reset(self): """ Resets the connection pool back to a clean state. """ self.pid = os.getpid() self._created_connections = 0 self._created_connections_per_node = {} # Dict(Node, Int) self._available_connections = {} # Dict(Node, List) self._in_use_connections = {} # Dict(Node, Set) self._check_lock = threading.Lock() self.initialized = False
python
def reset(self): """ Resets the connection pool back to a clean state. """ self.pid = os.getpid() self._created_connections = 0 self._created_connections_per_node = {} # Dict(Node, Int) self._available_connections = {} # Dict(Node, List) self._in_use_connections = {} # Dict(Node, Set) self._check_lock = threading.Lock() self.initialized = False
[ "def", "reset", "(", "self", ")", ":", "self", ".", "pid", "=", "os", ".", "getpid", "(", ")", "self", ".", "_created_connections", "=", "0", "self", ".", "_created_connections_per_node", "=", "{", "}", "# Dict(Node, Int)", "self", ".", "_available_connectio...
Resets the connection pool back to a clean state.
[ "Resets", "the", "connection", "pool", "back", "to", "a", "clean", "state", "." ]
204caad740ac13e5760d46444a2ba7632982a046
https://github.com/NoneGG/aredis/blob/204caad740ac13e5760d46444a2ba7632982a046/aredis/pool.py#L302-L312
train
202,729
NoneGG/aredis
aredis/pool.py
ClusterConnectionPool.disconnect
def disconnect(self): """ Nothing that requires any overwrite. """ all_conns = chain( self._available_connections.values(), self._in_use_connections.values(), ) for node_connections in all_conns: for connection in node_connections: connection.disconnect()
python
def disconnect(self): """ Nothing that requires any overwrite. """ all_conns = chain( self._available_connections.values(), self._in_use_connections.values(), ) for node_connections in all_conns: for connection in node_connections: connection.disconnect()
[ "def", "disconnect", "(", "self", ")", ":", "all_conns", "=", "chain", "(", "self", ".", "_available_connections", ".", "values", "(", ")", ",", "self", ".", "_in_use_connections", ".", "values", "(", ")", ",", ")", "for", "node_connections", "in", "all_co...
Nothing that requires any overwrite.
[ "Nothing", "that", "requires", "any", "overwrite", "." ]
204caad740ac13e5760d46444a2ba7632982a046
https://github.com/NoneGG/aredis/blob/204caad740ac13e5760d46444a2ba7632982a046/aredis/pool.py#L401-L412
train
202,730
NoneGG/aredis
aredis/pool.py
ClusterConnectionPool.get_random_connection
def get_random_connection(self): """ Open new connection to random redis server. """ if self._available_connections: node_name = random.choice(list(self._available_connections.keys())) conn_list = self._available_connections[node_name] # check it in case of empty connection list if conn_list: return conn_list.pop() for node in self.nodes.random_startup_node_iter(): connection = self.get_connection_by_node(node) if connection: return connection raise Exception("Cant reach a single startup node.")
python
def get_random_connection(self): """ Open new connection to random redis server. """ if self._available_connections: node_name = random.choice(list(self._available_connections.keys())) conn_list = self._available_connections[node_name] # check it in case of empty connection list if conn_list: return conn_list.pop() for node in self.nodes.random_startup_node_iter(): connection = self.get_connection_by_node(node) if connection: return connection raise Exception("Cant reach a single startup node.")
[ "def", "get_random_connection", "(", "self", ")", ":", "if", "self", ".", "_available_connections", ":", "node_name", "=", "random", ".", "choice", "(", "list", "(", "self", ".", "_available_connections", ".", "keys", "(", ")", ")", ")", "conn_list", "=", ...
Open new connection to random redis server.
[ "Open", "new", "connection", "to", "random", "redis", "server", "." ]
204caad740ac13e5760d46444a2ba7632982a046
https://github.com/NoneGG/aredis/blob/204caad740ac13e5760d46444a2ba7632982a046/aredis/pool.py#L422-L438
train
202,731
NoneGG/aredis
aredis/pool.py
ClusterConnectionPool.get_connection_by_slot
def get_connection_by_slot(self, slot): """ Determine what server a specific slot belongs to and return a redis object that is connected """ self._checkpid() try: return self.get_connection_by_node(self.get_node_by_slot(slot)) except KeyError: return self.get_random_connection()
python
def get_connection_by_slot(self, slot): """ Determine what server a specific slot belongs to and return a redis object that is connected """ self._checkpid() try: return self.get_connection_by_node(self.get_node_by_slot(slot)) except KeyError: return self.get_random_connection()
[ "def", "get_connection_by_slot", "(", "self", ",", "slot", ")", ":", "self", ".", "_checkpid", "(", ")", "try", ":", "return", "self", ".", "get_connection_by_node", "(", "self", ".", "get_node_by_slot", "(", "slot", ")", ")", "except", "KeyError", ":", "r...
Determine what server a specific slot belongs to and return a redis object that is connected
[ "Determine", "what", "server", "a", "specific", "slot", "belongs", "to", "and", "return", "a", "redis", "object", "that", "is", "connected" ]
204caad740ac13e5760d46444a2ba7632982a046
https://github.com/NoneGG/aredis/blob/204caad740ac13e5760d46444a2ba7632982a046/aredis/pool.py#L448-L457
train
202,732
NoneGG/aredis
aredis/pool.py
ClusterConnectionPool.get_connection_by_node
def get_connection_by_node(self, node): """ get a connection by node """ self._checkpid() self.nodes.set_node_name(node) try: # Try to get connection from existing pool connection = self._available_connections.get(node["name"], []).pop() except IndexError: connection = self.make_connection(node) self._in_use_connections.setdefault(node["name"], set()).add(connection) return connection
python
def get_connection_by_node(self, node): """ get a connection by node """ self._checkpid() self.nodes.set_node_name(node) try: # Try to get connection from existing pool connection = self._available_connections.get(node["name"], []).pop() except IndexError: connection = self.make_connection(node) self._in_use_connections.setdefault(node["name"], set()).add(connection) return connection
[ "def", "get_connection_by_node", "(", "self", ",", "node", ")", ":", "self", ".", "_checkpid", "(", ")", "self", ".", "nodes", ".", "set_node_name", "(", "node", ")", "try", ":", "# Try to get connection from existing pool", "connection", "=", "self", ".", "_a...
get a connection by node
[ "get", "a", "connection", "by", "node" ]
204caad740ac13e5760d46444a2ba7632982a046
https://github.com/NoneGG/aredis/blob/204caad740ac13e5760d46444a2ba7632982a046/aredis/pool.py#L459-L474
train
202,733
NoneGG/aredis
aredis/pubsub.py
PubSub.encode
def encode(self, value): """ Encode the value so that it's identical to what we'll read off the connection """ if self.decode_responses and isinstance(value, bytes): value = value.decode(self.encoding) elif not self.decode_responses and isinstance(value, str): value = value.encode(self.encoding) return value
python
def encode(self, value): """ Encode the value so that it's identical to what we'll read off the connection """ if self.decode_responses and isinstance(value, bytes): value = value.decode(self.encoding) elif not self.decode_responses and isinstance(value, str): value = value.encode(self.encoding) return value
[ "def", "encode", "(", "self", ",", "value", ")", ":", "if", "self", ".", "decode_responses", "and", "isinstance", "(", "value", ",", "bytes", ")", ":", "value", "=", "value", ".", "decode", "(", "self", ".", "encoding", ")", "elif", "not", "self", "....
Encode the value so that it's identical to what we'll read off the connection
[ "Encode", "the", "value", "so", "that", "it", "s", "identical", "to", "what", "we", "ll", "read", "off", "the", "connection" ]
204caad740ac13e5760d46444a2ba7632982a046
https://github.com/NoneGG/aredis/blob/204caad740ac13e5760d46444a2ba7632982a046/aredis/pubsub.py#L78-L87
train
202,734
NoneGG/aredis
aredis/pubsub.py
PubSub.punsubscribe
async def punsubscribe(self, *args): """ Unsubscribe from the supplied patterns. If empy, unsubscribe from all patterns. """ if args: args = list_or_args(args[0], args[1:]) return await self.execute_command('PUNSUBSCRIBE', *args)
python
async def punsubscribe(self, *args): """ Unsubscribe from the supplied patterns. If empy, unsubscribe from all patterns. """ if args: args = list_or_args(args[0], args[1:]) return await self.execute_command('PUNSUBSCRIBE', *args)
[ "async", "def", "punsubscribe", "(", "self", ",", "*", "args", ")", ":", "if", "args", ":", "args", "=", "list_or_args", "(", "args", "[", "0", "]", ",", "args", "[", "1", ":", "]", ")", "return", "await", "self", ".", "execute_command", "(", "'PUN...
Unsubscribe from the supplied patterns. If empy, unsubscribe from all patterns.
[ "Unsubscribe", "from", "the", "supplied", "patterns", ".", "If", "empy", "unsubscribe", "from", "all", "patterns", "." ]
204caad740ac13e5760d46444a2ba7632982a046
https://github.com/NoneGG/aredis/blob/204caad740ac13e5760d46444a2ba7632982a046/aredis/pubsub.py#L167-L174
train
202,735
NoneGG/aredis
aredis/pubsub.py
PubSub.listen
async def listen(self): "Listen for messages on channels this client has been subscribed to" if self.subscribed: return self.handle_message(await self.parse_response(block=True))
python
async def listen(self): "Listen for messages on channels this client has been subscribed to" if self.subscribed: return self.handle_message(await self.parse_response(block=True))
[ "async", "def", "listen", "(", "self", ")", ":", "if", "self", ".", "subscribed", ":", "return", "self", ".", "handle_message", "(", "await", "self", ".", "parse_response", "(", "block", "=", "True", ")", ")" ]
Listen for messages on channels this client has been subscribed to
[ "Listen", "for", "messages", "on", "channels", "this", "client", "has", "been", "subscribed", "to" ]
204caad740ac13e5760d46444a2ba7632982a046
https://github.com/NoneGG/aredis/blob/204caad740ac13e5760d46444a2ba7632982a046/aredis/pubsub.py#L206-L209
train
202,736
NoneGG/aredis
aredis/pubsub.py
PubSub.get_message
async def get_message(self, ignore_subscribe_messages=False, timeout=0): """ Get the next message if one is available, otherwise None. If timeout is specified, the system will wait for `timeout` seconds before returning. Timeout should be specified as a floating point number. """ response = await self.parse_response(block=False, timeout=timeout) if response: return self.handle_message(response, ignore_subscribe_messages) return None
python
async def get_message(self, ignore_subscribe_messages=False, timeout=0): """ Get the next message if one is available, otherwise None. If timeout is specified, the system will wait for `timeout` seconds before returning. Timeout should be specified as a floating point number. """ response = await self.parse_response(block=False, timeout=timeout) if response: return self.handle_message(response, ignore_subscribe_messages) return None
[ "async", "def", "get_message", "(", "self", ",", "ignore_subscribe_messages", "=", "False", ",", "timeout", "=", "0", ")", ":", "response", "=", "await", "self", ".", "parse_response", "(", "block", "=", "False", ",", "timeout", "=", "timeout", ")", "if", ...
Get the next message if one is available, otherwise None. If timeout is specified, the system will wait for `timeout` seconds before returning. Timeout should be specified as a floating point number.
[ "Get", "the", "next", "message", "if", "one", "is", "available", "otherwise", "None", "." ]
204caad740ac13e5760d46444a2ba7632982a046
https://github.com/NoneGG/aredis/blob/204caad740ac13e5760d46444a2ba7632982a046/aredis/pubsub.py#L211-L222
train
202,737
NoneGG/aredis
aredis/cache.py
BasicCache._gen_identity
def _gen_identity(self, key, param=None): """generate identity according to key and param given""" if self.identity_generator and param is not None: if self.serializer: param = self.serializer.serialize(param) if self.compressor: param = self.compressor.compress(param) identity = self.identity_generator.generate(key, param) else: identity = key return identity
python
def _gen_identity(self, key, param=None): """generate identity according to key and param given""" if self.identity_generator and param is not None: if self.serializer: param = self.serializer.serialize(param) if self.compressor: param = self.compressor.compress(param) identity = self.identity_generator.generate(key, param) else: identity = key return identity
[ "def", "_gen_identity", "(", "self", ",", "key", ",", "param", "=", "None", ")", ":", "if", "self", ".", "identity_generator", "and", "param", "is", "not", "None", ":", "if", "self", ".", "serializer", ":", "param", "=", "self", ".", "serializer", ".",...
generate identity according to key and param given
[ "generate", "identity", "according", "to", "key", "and", "param", "given" ]
204caad740ac13e5760d46444a2ba7632982a046
https://github.com/NoneGG/aredis/blob/204caad740ac13e5760d46444a2ba7632982a046/aredis/cache.py#L136-L146
train
202,738
NoneGG/aredis
aredis/cache.py
BasicCache._pack
def _pack(self, content): """pack the content using serializer and compressor""" if self.serializer: content = self.serializer.serialize(content) if self.compressor: content = self.compressor.compress(content) return content
python
def _pack(self, content): """pack the content using serializer and compressor""" if self.serializer: content = self.serializer.serialize(content) if self.compressor: content = self.compressor.compress(content) return content
[ "def", "_pack", "(", "self", ",", "content", ")", ":", "if", "self", ".", "serializer", ":", "content", "=", "self", ".", "serializer", ".", "serialize", "(", "content", ")", "if", "self", ".", "compressor", ":", "content", "=", "self", ".", "compresso...
pack the content using serializer and compressor
[ "pack", "the", "content", "using", "serializer", "and", "compressor" ]
204caad740ac13e5760d46444a2ba7632982a046
https://github.com/NoneGG/aredis/blob/204caad740ac13e5760d46444a2ba7632982a046/aredis/cache.py#L148-L154
train
202,739
NoneGG/aredis
aredis/cache.py
BasicCache._unpack
def _unpack(self, content): """unpack cache using serializer and compressor""" if self.compressor: try: content = self.compressor.decompress(content) except CompressError: pass if self.serializer: content = self.serializer.deserialize(content) return content
python
def _unpack(self, content): """unpack cache using serializer and compressor""" if self.compressor: try: content = self.compressor.decompress(content) except CompressError: pass if self.serializer: content = self.serializer.deserialize(content) return content
[ "def", "_unpack", "(", "self", ",", "content", ")", ":", "if", "self", ".", "compressor", ":", "try", ":", "content", "=", "self", ".", "compressor", ".", "decompress", "(", "content", ")", "except", "CompressError", ":", "pass", "if", "self", ".", "se...
unpack cache using serializer and compressor
[ "unpack", "cache", "using", "serializer", "and", "compressor" ]
204caad740ac13e5760d46444a2ba7632982a046
https://github.com/NoneGG/aredis/blob/204caad740ac13e5760d46444a2ba7632982a046/aredis/cache.py#L156-L165
train
202,740
NoneGG/aredis
aredis/cache.py
BasicCache.delete
async def delete(self, key, param=None): """ delete cache corresponding to identity generated from key and param """ identity = self._gen_identity(key, param) return await self.client.delete(identity)
python
async def delete(self, key, param=None): """ delete cache corresponding to identity generated from key and param """ identity = self._gen_identity(key, param) return await self.client.delete(identity)
[ "async", "def", "delete", "(", "self", ",", "key", ",", "param", "=", "None", ")", ":", "identity", "=", "self", ".", "_gen_identity", "(", "key", ",", "param", ")", "return", "await", "self", ".", "client", ".", "delete", "(", "identity", ")" ]
delete cache corresponding to identity generated from key and param
[ "delete", "cache", "corresponding", "to", "identity", "generated", "from", "key", "and", "param" ]
204caad740ac13e5760d46444a2ba7632982a046
https://github.com/NoneGG/aredis/blob/204caad740ac13e5760d46444a2ba7632982a046/aredis/cache.py#L167-L173
train
202,741
NoneGG/aredis
aredis/cache.py
BasicCache.delete_pattern
async def delete_pattern(self, pattern, count=None): """ delete cache according to pattern in redis, delete `count` keys each time """ cursor = '0' count_deleted = 0 while cursor != 0: cursor, identities = await self.client.scan( cursor=cursor, match=pattern, count=count ) count_deleted += await self.client.delete(*identities) return count_deleted
python
async def delete_pattern(self, pattern, count=None): """ delete cache according to pattern in redis, delete `count` keys each time """ cursor = '0' count_deleted = 0 while cursor != 0: cursor, identities = await self.client.scan( cursor=cursor, match=pattern, count=count ) count_deleted += await self.client.delete(*identities) return count_deleted
[ "async", "def", "delete_pattern", "(", "self", ",", "pattern", ",", "count", "=", "None", ")", ":", "cursor", "=", "'0'", "count_deleted", "=", "0", "while", "cursor", "!=", "0", ":", "cursor", ",", "identities", "=", "await", "self", ".", "client", "....
delete cache according to pattern in redis, delete `count` keys each time
[ "delete", "cache", "according", "to", "pattern", "in", "redis", "delete", "count", "keys", "each", "time" ]
204caad740ac13e5760d46444a2ba7632982a046
https://github.com/NoneGG/aredis/blob/204caad740ac13e5760d46444a2ba7632982a046/aredis/cache.py#L175-L187
train
202,742
NoneGG/aredis
aredis/cache.py
BasicCache.exist
async def exist(self, key, param=None): """see if specific identity exists""" identity = self._gen_identity(key, param) return await self.client.exists(identity)
python
async def exist(self, key, param=None): """see if specific identity exists""" identity = self._gen_identity(key, param) return await self.client.exists(identity)
[ "async", "def", "exist", "(", "self", ",", "key", ",", "param", "=", "None", ")", ":", "identity", "=", "self", ".", "_gen_identity", "(", "key", ",", "param", ")", "return", "await", "self", ".", "client", ".", "exists", "(", "identity", ")" ]
see if specific identity exists
[ "see", "if", "specific", "identity", "exists" ]
204caad740ac13e5760d46444a2ba7632982a046
https://github.com/NoneGG/aredis/blob/204caad740ac13e5760d46444a2ba7632982a046/aredis/cache.py#L189-L192
train
202,743
NoneGG/aredis
aredis/cache.py
BasicCache.ttl
async def ttl(self, key, param=None): """get time to live of a specific identity""" identity = self._gen_identity(key, param) return await self.client.ttl(identity)
python
async def ttl(self, key, param=None): """get time to live of a specific identity""" identity = self._gen_identity(key, param) return await self.client.ttl(identity)
[ "async", "def", "ttl", "(", "self", ",", "key", ",", "param", "=", "None", ")", ":", "identity", "=", "self", ".", "_gen_identity", "(", "key", ",", "param", ")", "return", "await", "self", ".", "client", ".", "ttl", "(", "identity", ")" ]
get time to live of a specific identity
[ "get", "time", "to", "live", "of", "a", "specific", "identity" ]
204caad740ac13e5760d46444a2ba7632982a046
https://github.com/NoneGG/aredis/blob/204caad740ac13e5760d46444a2ba7632982a046/aredis/cache.py#L194-L197
train
202,744
NoneGG/aredis
aredis/cache.py
HerdCache.set
async def set(self, key, value, param=None, expire_time=None, herd_timeout=None): """ Use key and param to generate identity and pack the content, expire the key within real_timeout if expire_time is given. real_timeout is equal to the sum of expire_time and herd_time. The content is cached with expire_time. """ identity = self._gen_identity(key, param) expected_expired_ts = int(time.time()) if expire_time: expected_expired_ts += expire_time expected_expired_ts += herd_timeout or self.default_herd_timeout value = self._pack([value, expected_expired_ts]) return await self.client.set(identity, value, ex=expire_time)
python
async def set(self, key, value, param=None, expire_time=None, herd_timeout=None): """ Use key and param to generate identity and pack the content, expire the key within real_timeout if expire_time is given. real_timeout is equal to the sum of expire_time and herd_time. The content is cached with expire_time. """ identity = self._gen_identity(key, param) expected_expired_ts = int(time.time()) if expire_time: expected_expired_ts += expire_time expected_expired_ts += herd_timeout or self.default_herd_timeout value = self._pack([value, expected_expired_ts]) return await self.client.set(identity, value, ex=expire_time)
[ "async", "def", "set", "(", "self", ",", "key", ",", "value", ",", "param", "=", "None", ",", "expire_time", "=", "None", ",", "herd_timeout", "=", "None", ")", ":", "identity", "=", "self", ".", "_gen_identity", "(", "key", ",", "param", ")", "expec...
Use key and param to generate identity and pack the content, expire the key within real_timeout if expire_time is given. real_timeout is equal to the sum of expire_time and herd_time. The content is cached with expire_time.
[ "Use", "key", "and", "param", "to", "generate", "identity", "and", "pack", "the", "content", "expire", "the", "key", "within", "real_timeout", "if", "expire_time", "is", "given", ".", "real_timeout", "is", "equal", "to", "the", "sum", "of", "expire_time", "a...
204caad740ac13e5760d46444a2ba7632982a046
https://github.com/NoneGG/aredis/blob/204caad740ac13e5760d46444a2ba7632982a046/aredis/cache.py#L243-L256
train
202,745
NoneGG/aredis
aredis/commands/streams.py
StreamsCommandMixin.xrange
async def xrange(self, name: str, start='-', end='+', count=None) -> list: """ Read stream values within an interval. Available since 5.0.0. Time complexity: O(log(N)+M) with N being the number of elements in the stream and M the number of elements being returned. If M is constant (e.g. always asking for the first 10 elements with COUNT), you can consider it O(log(N)). :param name: name of the stream. :param start: first stream ID. defaults to '-', meaning the earliest available. :param end: last stream ID. defaults to '+', meaning the latest available. :param count: if set, only return this many items, beginning with the earliest available. :return list of (stream_id, entry(k-v pair)) """ pieces = [start, end] if count is not None: if not isinstance(count, int) or count < 1: raise RedisError("XRANGE count must be a positive integer") pieces.append("COUNT") pieces.append(str(count)) return await self.execute_command('XRANGE', name, *pieces)
python
async def xrange(self, name: str, start='-', end='+', count=None) -> list: """ Read stream values within an interval. Available since 5.0.0. Time complexity: O(log(N)+M) with N being the number of elements in the stream and M the number of elements being returned. If M is constant (e.g. always asking for the first 10 elements with COUNT), you can consider it O(log(N)). :param name: name of the stream. :param start: first stream ID. defaults to '-', meaning the earliest available. :param end: last stream ID. defaults to '+', meaning the latest available. :param count: if set, only return this many items, beginning with the earliest available. :return list of (stream_id, entry(k-v pair)) """ pieces = [start, end] if count is not None: if not isinstance(count, int) or count < 1: raise RedisError("XRANGE count must be a positive integer") pieces.append("COUNT") pieces.append(str(count)) return await self.execute_command('XRANGE', name, *pieces)
[ "async", "def", "xrange", "(", "self", ",", "name", ":", "str", ",", "start", "=", "'-'", ",", "end", "=", "'+'", ",", "count", "=", "None", ")", "->", "list", ":", "pieces", "=", "[", "start", ",", "end", "]", "if", "count", "is", "not", "None...
Read stream values within an interval. Available since 5.0.0. Time complexity: O(log(N)+M) with N being the number of elements in the stream and M the number of elements being returned. If M is constant (e.g. always asking for the first 10 elements with COUNT), you can consider it O(log(N)). :param name: name of the stream. :param start: first stream ID. defaults to '-', meaning the earliest available. :param end: last stream ID. defaults to '+', meaning the latest available. :param count: if set, only return this many items, beginning with the earliest available. :return list of (stream_id, entry(k-v pair))
[ "Read", "stream", "values", "within", "an", "interval", "." ]
204caad740ac13e5760d46444a2ba7632982a046
https://github.com/NoneGG/aredis/blob/204caad740ac13e5760d46444a2ba7632982a046/aredis/commands/streams.py#L101-L126
train
202,746
NoneGG/aredis
aredis/commands/lists.py
ListsCommandMixin.ltrim
async def ltrim(self, name, start, end): """ Trim the list ``name``, removing all values not within the slice between ``start`` and ``end`` ``start`` and ``end`` can be negative numbers just like Python slicing notation """ return await self.execute_command('LTRIM', name, start, end)
python
async def ltrim(self, name, start, end): """ Trim the list ``name``, removing all values not within the slice between ``start`` and ``end`` ``start`` and ``end`` can be negative numbers just like Python slicing notation """ return await self.execute_command('LTRIM', name, start, end)
[ "async", "def", "ltrim", "(", "self", ",", "name", ",", "start", ",", "end", ")", ":", "return", "await", "self", ".", "execute_command", "(", "'LTRIM'", ",", "name", ",", "start", ",", "end", ")" ]
Trim the list ``name``, removing all values not within the slice between ``start`` and ``end`` ``start`` and ``end`` can be negative numbers just like Python slicing notation
[ "Trim", "the", "list", "name", "removing", "all", "values", "not", "within", "the", "slice", "between", "start", "and", "end" ]
204caad740ac13e5760d46444a2ba7632982a046
https://github.com/NoneGG/aredis/blob/204caad740ac13e5760d46444a2ba7632982a046/aredis/commands/lists.py#L139-L147
train
202,747
NoneGG/aredis
aredis/pipeline.py
block_pipeline_command
def block_pipeline_command(func): """ Prints error because some pipelined commands should be blocked when running in cluster-mode """ def inner(*args, **kwargs): raise RedisClusterException( "ERROR: Calling pipelined function {0} is blocked when running redis in cluster mode...".format( func.__name__)) return inner
python
def block_pipeline_command(func): """ Prints error because some pipelined commands should be blocked when running in cluster-mode """ def inner(*args, **kwargs): raise RedisClusterException( "ERROR: Calling pipelined function {0} is blocked when running redis in cluster mode...".format( func.__name__)) return inner
[ "def", "block_pipeline_command", "(", "func", ")", ":", "def", "inner", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "raise", "RedisClusterException", "(", "\"ERROR: Calling pipelined function {0} is blocked when running redis in cluster mode...\"", ".", "format",...
Prints error because some pipelined commands should be blocked when running in cluster-mode
[ "Prints", "error", "because", "some", "pipelined", "commands", "should", "be", "blocked", "when", "running", "in", "cluster", "-", "mode" ]
204caad740ac13e5760d46444a2ba7632982a046
https://github.com/NoneGG/aredis/blob/204caad740ac13e5760d46444a2ba7632982a046/aredis/pipeline.py#L633-L643
train
202,748
NoneGG/aredis
aredis/pipeline.py
BasePipeline.immediate_execute_command
async def immediate_execute_command(self, *args, **options): """ Execute a command immediately, but don't auto-retry on a ConnectionError if we're already WATCHing a variable. Used when issuing WATCH or subsequent commands retrieving their values but before MULTI is called. """ command_name = args[0] conn = self.connection # if this is the first call, we need a connection if not conn: conn = self.connection_pool.get_connection() self.connection = conn try: await conn.send_command(*args) return await self.parse_response(conn, command_name, **options) except (ConnectionError, TimeoutError) as e: conn.disconnect() if not conn.retry_on_timeout and isinstance(e, TimeoutError): raise # if we're not already watching, we can safely retry the command try: if not self.watching: await conn.send_command(*args) return await self.parse_response(conn, command_name, **options) except ConnectionError: # the retry failed so cleanup. conn.disconnect() await self.reset() raise
python
async def immediate_execute_command(self, *args, **options): """ Execute a command immediately, but don't auto-retry on a ConnectionError if we're already WATCHing a variable. Used when issuing WATCH or subsequent commands retrieving their values but before MULTI is called. """ command_name = args[0] conn = self.connection # if this is the first call, we need a connection if not conn: conn = self.connection_pool.get_connection() self.connection = conn try: await conn.send_command(*args) return await self.parse_response(conn, command_name, **options) except (ConnectionError, TimeoutError) as e: conn.disconnect() if not conn.retry_on_timeout and isinstance(e, TimeoutError): raise # if we're not already watching, we can safely retry the command try: if not self.watching: await conn.send_command(*args) return await self.parse_response(conn, command_name, **options) except ConnectionError: # the retry failed so cleanup. conn.disconnect() await self.reset() raise
[ "async", "def", "immediate_execute_command", "(", "self", ",", "*", "args", ",", "*", "*", "options", ")", ":", "command_name", "=", "args", "[", "0", "]", "conn", "=", "self", ".", "connection", "# if this is the first call, we need a connection", "if", "not", ...
Execute a command immediately, but don't auto-retry on a ConnectionError if we're already WATCHing a variable. Used when issuing WATCH or subsequent commands retrieving their values but before MULTI is called.
[ "Execute", "a", "command", "immediately", "but", "don", "t", "auto", "-", "retry", "on", "a", "ConnectionError", "if", "we", "re", "already", "WATCHing", "a", "variable", ".", "Used", "when", "issuing", "WATCH", "or", "subsequent", "commands", "retrieving", ...
204caad740ac13e5760d46444a2ba7632982a046
https://github.com/NoneGG/aredis/blob/204caad740ac13e5760d46444a2ba7632982a046/aredis/pipeline.py#L99-L128
train
202,749
NoneGG/aredis
aredis/pipeline.py
StrictClusterPipeline._determine_slot
def _determine_slot(self, *args): """ figure out what slot based on command and args """ if len(args) <= 1: raise RedisClusterException("No way to dispatch this command to Redis Cluster. Missing key.") command = args[0] if command in ['EVAL', 'EVALSHA']: numkeys = args[2] keys = args[3: 3 + numkeys] slots = {self.connection_pool.nodes.keyslot(key) for key in keys} if len(slots) != 1: raise RedisClusterException("{0} - all keys must map to the same key slot".format(command)) return slots.pop() key = args[1] return self.connection_pool.nodes.keyslot(key)
python
def _determine_slot(self, *args): """ figure out what slot based on command and args """ if len(args) <= 1: raise RedisClusterException("No way to dispatch this command to Redis Cluster. Missing key.") command = args[0] if command in ['EVAL', 'EVALSHA']: numkeys = args[2] keys = args[3: 3 + numkeys] slots = {self.connection_pool.nodes.keyslot(key) for key in keys} if len(slots) != 1: raise RedisClusterException("{0} - all keys must map to the same key slot".format(command)) return slots.pop() key = args[1] return self.connection_pool.nodes.keyslot(key)
[ "def", "_determine_slot", "(", "self", ",", "*", "args", ")", ":", "if", "len", "(", "args", ")", "<=", "1", ":", "raise", "RedisClusterException", "(", "\"No way to dispatch this command to Redis Cluster. Missing key.\"", ")", "command", "=", "args", "[", "0", ...
figure out what slot based on command and args
[ "figure", "out", "what", "slot", "based", "on", "command", "and", "args" ]
204caad740ac13e5760d46444a2ba7632982a046
https://github.com/NoneGG/aredis/blob/204caad740ac13e5760d46444a2ba7632982a046/aredis/pipeline.py#L362-L380
train
202,750
NoneGG/aredis
aredis/pipeline.py
StrictClusterPipeline.reset
def reset(self): """ Reset back to empty pipeline. """ self.command_stack = [] self.scripts = set() self.watches = [] # clean up the other instance attributes self.watching = False self.explicit_transaction = False
python
def reset(self): """ Reset back to empty pipeline. """ self.command_stack = [] self.scripts = set() self.watches = [] # clean up the other instance attributes self.watching = False self.explicit_transaction = False
[ "def", "reset", "(", "self", ")", ":", "self", ".", "command_stack", "=", "[", "]", "self", ".", "scripts", "=", "set", "(", ")", "self", ".", "watches", "=", "[", "]", "# clean up the other instance attributes", "self", ".", "watching", "=", "False", "s...
Reset back to empty pipeline.
[ "Reset", "back", "to", "empty", "pipeline", "." ]
204caad740ac13e5760d46444a2ba7632982a046
https://github.com/NoneGG/aredis/blob/204caad740ac13e5760d46444a2ba7632982a046/aredis/pipeline.py#L417-L427
train
202,751
NoneGG/aredis
aredis/pipeline.py
StrictClusterPipeline.send_cluster_commands
async def send_cluster_commands(self, stack, raise_on_error=True, allow_redirections=True): """ Send a bunch of cluster commands to the redis cluster. `allow_redirections` If the pipeline should follow `ASK` & `MOVED` responses automatically. If set to false it will raise RedisClusterException. """ # the first time sending the commands we send all of the commands that were queued up. # if we have to run through it again, we only retry the commands that failed. attempt = sorted(stack, key=lambda x: x.position) # build a list of node objects based on node names we need to nodes = {} # as we move through each command that still needs to be processed, # we figure out the slot number that command maps to, then from the slot determine the node. for c in attempt: # refer to our internal node -> slot table that tells us where a given # command should route to. slot = self._determine_slot(*c.args) node = self.connection_pool.get_node_by_slot(slot) # little hack to make sure the node name is populated. probably could clean this up. self.connection_pool.nodes.set_node_name(node) # now that we know the name of the node ( it's just a string in the form of host:port ) # we can build a list of commands for each node. node_name = node['name'] if node_name not in nodes: nodes[node_name] = NodeCommands(self.parse_response, self.connection_pool.get_connection_by_node(node)) nodes[node_name].append(c) # send the commands in sequence. # we write to all the open sockets for each node first, before reading anything # this allows us to flush all the requests out across the network essentially in parallel # so that we can read them all in parallel as they come back. # we dont' multiplex on the sockets as they come available, but that shouldn't make too much difference. node_commands = nodes.values() for n in node_commands: await n.write() for n in node_commands: await n.read() # release all of the redis connections we allocated earlier back into the connection pool. # we used to do this step as part of a try/finally block, but it is really dangerous to # release connections back into the pool if for some reason the socket has data still left in it # from a previous operation. The write and read operations already have try/catch around them for # all known types of errors including connection and socket level errors. # So if we hit an exception, something really bad happened and putting any of # these connections back into the pool is a very bad idea. # the socket might have unread buffer still sitting in it, and then the # next time we read from it we pass the buffered result back from a previous # command and every single request after to that connection will always get # a mismatched result. (not just theoretical, I saw this happen on production x.x). for n in nodes.values(): self.connection_pool.release(n.connection) # if the response isn't an exception it is a valid response from the node # we're all done with that command, YAY! # if we have more commands to attempt, we've run into problems. # collect all the commands we are allowed to retry. # (MOVED, ASK, or connection errors or timeout errors) attempt = sorted([c for c in attempt if isinstance(c.result, ERRORS_ALLOW_RETRY)], key=lambda x: x.position) if attempt and allow_redirections: # RETRY MAGIC HAPPENS HERE! # send these remaing comamnds one at a time using `execute_command` # in the main client. This keeps our retry logic in one place mostly, # and allows us to be more confident in correctness of behavior. # at this point any speed gains from pipelining have been lost # anyway, so we might as well make the best attempt to get the correct # behavior. # # The client command will handle retries for each individual command # sequentially as we pass each one into `execute_command`. Any exceptions # that bubble out should only appear once all retries have been exhausted. # # If a lot of commands have failed, we'll be setting the # flag to rebuild the slots table from scratch. So MOVED errors should # correct themselves fairly quickly. await self.connection_pool.nodes.increment_reinitialize_counter(len(attempt)) for c in attempt: try: # send each command individually like we do in the main client. c.result = await super(StrictClusterPipeline, self).execute_command(*c.args, **c.options) except RedisError as e: c.result = e # turn the response back into a simple flat array that corresponds # to the sequence of commands issued in the stack in pipeline.execute() response = [c.result for c in sorted(stack, key=lambda x: x.position)] if raise_on_error: self.raise_first_error(stack) return response
python
async def send_cluster_commands(self, stack, raise_on_error=True, allow_redirections=True): """ Send a bunch of cluster commands to the redis cluster. `allow_redirections` If the pipeline should follow `ASK` & `MOVED` responses automatically. If set to false it will raise RedisClusterException. """ # the first time sending the commands we send all of the commands that were queued up. # if we have to run through it again, we only retry the commands that failed. attempt = sorted(stack, key=lambda x: x.position) # build a list of node objects based on node names we need to nodes = {} # as we move through each command that still needs to be processed, # we figure out the slot number that command maps to, then from the slot determine the node. for c in attempt: # refer to our internal node -> slot table that tells us where a given # command should route to. slot = self._determine_slot(*c.args) node = self.connection_pool.get_node_by_slot(slot) # little hack to make sure the node name is populated. probably could clean this up. self.connection_pool.nodes.set_node_name(node) # now that we know the name of the node ( it's just a string in the form of host:port ) # we can build a list of commands for each node. node_name = node['name'] if node_name not in nodes: nodes[node_name] = NodeCommands(self.parse_response, self.connection_pool.get_connection_by_node(node)) nodes[node_name].append(c) # send the commands in sequence. # we write to all the open sockets for each node first, before reading anything # this allows us to flush all the requests out across the network essentially in parallel # so that we can read them all in parallel as they come back. # we dont' multiplex on the sockets as they come available, but that shouldn't make too much difference. node_commands = nodes.values() for n in node_commands: await n.write() for n in node_commands: await n.read() # release all of the redis connections we allocated earlier back into the connection pool. # we used to do this step as part of a try/finally block, but it is really dangerous to # release connections back into the pool if for some reason the socket has data still left in it # from a previous operation. The write and read operations already have try/catch around them for # all known types of errors including connection and socket level errors. # So if we hit an exception, something really bad happened and putting any of # these connections back into the pool is a very bad idea. # the socket might have unread buffer still sitting in it, and then the # next time we read from it we pass the buffered result back from a previous # command and every single request after to that connection will always get # a mismatched result. (not just theoretical, I saw this happen on production x.x). for n in nodes.values(): self.connection_pool.release(n.connection) # if the response isn't an exception it is a valid response from the node # we're all done with that command, YAY! # if we have more commands to attempt, we've run into problems. # collect all the commands we are allowed to retry. # (MOVED, ASK, or connection errors or timeout errors) attempt = sorted([c for c in attempt if isinstance(c.result, ERRORS_ALLOW_RETRY)], key=lambda x: x.position) if attempt and allow_redirections: # RETRY MAGIC HAPPENS HERE! # send these remaing comamnds one at a time using `execute_command` # in the main client. This keeps our retry logic in one place mostly, # and allows us to be more confident in correctness of behavior. # at this point any speed gains from pipelining have been lost # anyway, so we might as well make the best attempt to get the correct # behavior. # # The client command will handle retries for each individual command # sequentially as we pass each one into `execute_command`. Any exceptions # that bubble out should only appear once all retries have been exhausted. # # If a lot of commands have failed, we'll be setting the # flag to rebuild the slots table from scratch. So MOVED errors should # correct themselves fairly quickly. await self.connection_pool.nodes.increment_reinitialize_counter(len(attempt)) for c in attempt: try: # send each command individually like we do in the main client. c.result = await super(StrictClusterPipeline, self).execute_command(*c.args, **c.options) except RedisError as e: c.result = e # turn the response back into a simple flat array that corresponds # to the sequence of commands issued in the stack in pipeline.execute() response = [c.result for c in sorted(stack, key=lambda x: x.position)] if raise_on_error: self.raise_first_error(stack) return response
[ "async", "def", "send_cluster_commands", "(", "self", ",", "stack", ",", "raise_on_error", "=", "True", ",", "allow_redirections", "=", "True", ")", ":", "# the first time sending the commands we send all of the commands that were queued up.", "# if we have to run through it agai...
Send a bunch of cluster commands to the redis cluster. `allow_redirections` If the pipeline should follow `ASK` & `MOVED` responses automatically. If set to false it will raise RedisClusterException.
[ "Send", "a", "bunch", "of", "cluster", "commands", "to", "the", "redis", "cluster", "." ]
204caad740ac13e5760d46444a2ba7632982a046
https://github.com/NoneGG/aredis/blob/204caad740ac13e5760d46444a2ba7632982a046/aredis/pipeline.py#L481-L577
train
202,752
NoneGG/aredis
aredis/pipeline.py
StrictClusterPipeline._watch
async def _watch(self, node, conn, names): "Watches the values at keys ``names``" for name in names: slot = self._determine_slot('WATCH', name) dist_node = self.connection_pool.get_node_by_slot(slot) if node.get('name') != dist_node['name']: # raise error if commands in a transaction can not hash to same node if len(node) > 0: raise ClusterTransactionError("Keys in request don't hash to the same node") if self.explicit_transaction: raise RedisError('Cannot issue a WATCH after a MULTI') await conn.send_command('WATCH', *names) return await conn.read_response()
python
async def _watch(self, node, conn, names): "Watches the values at keys ``names``" for name in names: slot = self._determine_slot('WATCH', name) dist_node = self.connection_pool.get_node_by_slot(slot) if node.get('name') != dist_node['name']: # raise error if commands in a transaction can not hash to same node if len(node) > 0: raise ClusterTransactionError("Keys in request don't hash to the same node") if self.explicit_transaction: raise RedisError('Cannot issue a WATCH after a MULTI') await conn.send_command('WATCH', *names) return await conn.read_response()
[ "async", "def", "_watch", "(", "self", ",", "node", ",", "conn", ",", "names", ")", ":", "for", "name", "in", "names", ":", "slot", "=", "self", ".", "_determine_slot", "(", "'WATCH'", ",", "name", ")", "dist_node", "=", "self", ".", "connection_pool",...
Watches the values at keys ``names``
[ "Watches", "the", "values", "at", "keys", "names" ]
204caad740ac13e5760d46444a2ba7632982a046
https://github.com/NoneGG/aredis/blob/204caad740ac13e5760d46444a2ba7632982a046/aredis/pipeline.py#L598-L610
train
202,753
NoneGG/aredis
aredis/pipeline.py
StrictClusterPipeline._unwatch
async def _unwatch(self, conn): "Unwatches all previously specified keys" await conn.send_command('UNWATCH') res = await conn.read_response() return self.watching and res or True
python
async def _unwatch(self, conn): "Unwatches all previously specified keys" await conn.send_command('UNWATCH') res = await conn.read_response() return self.watching and res or True
[ "async", "def", "_unwatch", "(", "self", ",", "conn", ")", ":", "await", "conn", ".", "send_command", "(", "'UNWATCH'", ")", "res", "=", "await", "conn", ".", "read_response", "(", ")", "return", "self", ".", "watching", "and", "res", "or", "True" ]
Unwatches all previously specified keys
[ "Unwatches", "all", "previously", "specified", "keys" ]
204caad740ac13e5760d46444a2ba7632982a046
https://github.com/NoneGG/aredis/blob/204caad740ac13e5760d46444a2ba7632982a046/aredis/pipeline.py#L612-L616
train
202,754
NoneGG/aredis
aredis/pipeline.py
NodeCommands.write
async def write(self): """ Code borrowed from StrictRedis so it can be fixed """ connection = self.connection commands = self.commands # We are going to clobber the commands with the write, so go ahead # and ensure that nothing is sitting there from a previous run. for c in commands: c.result = None # build up all commands into a single request to increase network perf # send all the commands and catch connection and timeout errors. try: await connection.send_packed_command(connection.pack_commands([c.args for c in commands])) except (ConnectionError, TimeoutError) as e: for c in commands: c.result = e
python
async def write(self): """ Code borrowed from StrictRedis so it can be fixed """ connection = self.connection commands = self.commands # We are going to clobber the commands with the write, so go ahead # and ensure that nothing is sitting there from a previous run. for c in commands: c.result = None # build up all commands into a single request to increase network perf # send all the commands and catch connection and timeout errors. try: await connection.send_packed_command(connection.pack_commands([c.args for c in commands])) except (ConnectionError, TimeoutError) as e: for c in commands: c.result = e
[ "async", "def", "write", "(", "self", ")", ":", "connection", "=", "self", ".", "connection", "commands", "=", "self", ".", "commands", "# We are going to clobber the commands with the write, so go ahead", "# and ensure that nothing is sitting there from a previous run.", "for"...
Code borrowed from StrictRedis so it can be fixed
[ "Code", "borrowed", "from", "StrictRedis", "so", "it", "can", "be", "fixed" ]
204caad740ac13e5760d46444a2ba7632982a046
https://github.com/NoneGG/aredis/blob/204caad740ac13e5760d46444a2ba7632982a046/aredis/pipeline.py#L745-L763
train
202,755
NoneGG/aredis
aredis/commands/strings.py
BitField.set
def set(self, type, offset, value): """ Set the specified bit field and returns its old value. """ self._command_stack.extend(['SET', type, offset, value]) return self
python
def set(self, type, offset, value): """ Set the specified bit field and returns its old value. """ self._command_stack.extend(['SET', type, offset, value]) return self
[ "def", "set", "(", "self", ",", "type", ",", "offset", ",", "value", ")", ":", "self", ".", "_command_stack", ".", "extend", "(", "[", "'SET'", ",", "type", ",", "offset", ",", "value", "]", ")", "return", "self" ]
Set the specified bit field and returns its old value.
[ "Set", "the", "specified", "bit", "field", "and", "returns", "its", "old", "value", "." ]
204caad740ac13e5760d46444a2ba7632982a046
https://github.com/NoneGG/aredis/blob/204caad740ac13e5760d46444a2ba7632982a046/aredis/commands/strings.py#L31-L36
train
202,756
NoneGG/aredis
aredis/commands/strings.py
BitField.get
def get(self, type, offset): """ Returns the specified bit field. """ self._command_stack.extend(['GET', type, offset]) return self
python
def get(self, type, offset): """ Returns the specified bit field. """ self._command_stack.extend(['GET', type, offset]) return self
[ "def", "get", "(", "self", ",", "type", ",", "offset", ")", ":", "self", ".", "_command_stack", ".", "extend", "(", "[", "'GET'", ",", "type", ",", "offset", "]", ")", "return", "self" ]
Returns the specified bit field.
[ "Returns", "the", "specified", "bit", "field", "." ]
204caad740ac13e5760d46444a2ba7632982a046
https://github.com/NoneGG/aredis/blob/204caad740ac13e5760d46444a2ba7632982a046/aredis/commands/strings.py#L38-L43
train
202,757
NoneGG/aredis
aredis/commands/sorted_set.py
SortedSetCommandMixin.zrange
async def zrange(self, name, start, end, desc=False, withscores=False, score_cast_func=float): """ Return a range of values from sorted set ``name`` between ``start`` and ``end`` sorted in ascending order. ``start`` and ``end`` can be negative, indicating the end of the range. ``desc`` a boolean indicating whether to sort the results descendingly ``withscores`` indicates to return the scores along with the values. The return type is a list of (value, score) pairs ``score_cast_func`` a callable used to cast the score return value """ if desc: return await self.zrevrange(name, start, end, withscores, score_cast_func) pieces = ['ZRANGE', name, start, end] if withscores: pieces.append(b('WITHSCORES')) options = { 'withscores': withscores, 'score_cast_func': score_cast_func } return await self.execute_command(*pieces, **options)
python
async def zrange(self, name, start, end, desc=False, withscores=False, score_cast_func=float): """ Return a range of values from sorted set ``name`` between ``start`` and ``end`` sorted in ascending order. ``start`` and ``end`` can be negative, indicating the end of the range. ``desc`` a boolean indicating whether to sort the results descendingly ``withscores`` indicates to return the scores along with the values. The return type is a list of (value, score) pairs ``score_cast_func`` a callable used to cast the score return value """ if desc: return await self.zrevrange(name, start, end, withscores, score_cast_func) pieces = ['ZRANGE', name, start, end] if withscores: pieces.append(b('WITHSCORES')) options = { 'withscores': withscores, 'score_cast_func': score_cast_func } return await self.execute_command(*pieces, **options)
[ "async", "def", "zrange", "(", "self", ",", "name", ",", "start", ",", "end", ",", "desc", "=", "False", ",", "withscores", "=", "False", ",", "score_cast_func", "=", "float", ")", ":", "if", "desc", ":", "return", "await", "self", ".", "zrevrange", ...
Return a range of values from sorted set ``name`` between ``start`` and ``end`` sorted in ascending order. ``start`` and ``end`` can be negative, indicating the end of the range. ``desc`` a boolean indicating whether to sort the results descendingly ``withscores`` indicates to return the scores along with the values. The return type is a list of (value, score) pairs ``score_cast_func`` a callable used to cast the score return value
[ "Return", "a", "range", "of", "values", "from", "sorted", "set", "name", "between", "start", "and", "end", "sorted", "in", "ascending", "order", "." ]
204caad740ac13e5760d46444a2ba7632982a046
https://github.com/NoneGG/aredis/blob/204caad740ac13e5760d46444a2ba7632982a046/aredis/commands/sorted_set.py#L142-L167
train
202,758
NoneGG/aredis
aredis/commands/sorted_set.py
SortedSetCommandMixin.zremrangebyscore
async def zremrangebyscore(self, name, min, max): """ Remove all elements in the sorted set ``name`` with scores between ``min`` and ``max``. Returns the number of elements removed. """ return await self.execute_command('ZREMRANGEBYSCORE', name, min, max)
python
async def zremrangebyscore(self, name, min, max): """ Remove all elements in the sorted set ``name`` with scores between ``min`` and ``max``. Returns the number of elements removed. """ return await self.execute_command('ZREMRANGEBYSCORE', name, min, max)
[ "async", "def", "zremrangebyscore", "(", "self", ",", "name", ",", "min", ",", "max", ")", ":", "return", "await", "self", ".", "execute_command", "(", "'ZREMRANGEBYSCORE'", ",", "name", ",", "min", ",", "max", ")" ]
Remove all elements in the sorted set ``name`` with scores between ``min`` and ``max``. Returns the number of elements removed.
[ "Remove", "all", "elements", "in", "the", "sorted", "set", "name", "with", "scores", "between", "min", "and", "max", ".", "Returns", "the", "number", "of", "elements", "removed", "." ]
204caad740ac13e5760d46444a2ba7632982a046
https://github.com/NoneGG/aredis/blob/204caad740ac13e5760d46444a2ba7632982a046/aredis/commands/sorted_set.py#L258-L263
train
202,759
NoneGG/aredis
aredis/commands/keys.py
KeysCommandMixin.expire
async def expire(self, name, time): """ Set an expire flag on key ``name`` for ``time`` seconds. ``time`` can be represented by an integer or a Python timedelta object. """ if isinstance(time, datetime.timedelta): time = time.seconds + time.days * 24 * 3600 return await self.execute_command('EXPIRE', name, time)
python
async def expire(self, name, time): """ Set an expire flag on key ``name`` for ``time`` seconds. ``time`` can be represented by an integer or a Python timedelta object. """ if isinstance(time, datetime.timedelta): time = time.seconds + time.days * 24 * 3600 return await self.execute_command('EXPIRE', name, time)
[ "async", "def", "expire", "(", "self", ",", "name", ",", "time", ")", ":", "if", "isinstance", "(", "time", ",", "datetime", ".", "timedelta", ")", ":", "time", "=", "time", ".", "seconds", "+", "time", ".", "days", "*", "24", "*", "3600", "return"...
Set an expire flag on key ``name`` for ``time`` seconds. ``time`` can be represented by an integer or a Python timedelta object.
[ "Set", "an", "expire", "flag", "on", "key", "name", "for", "time", "seconds", ".", "time", "can", "be", "represented", "by", "an", "integer", "or", "a", "Python", "timedelta", "object", "." ]
204caad740ac13e5760d46444a2ba7632982a046
https://github.com/NoneGG/aredis/blob/204caad740ac13e5760d46444a2ba7632982a046/aredis/commands/keys.py#L71-L78
train
202,760
NoneGG/aredis
aredis/commands/keys.py
ClusterKeysCommandMixin.delete
async def delete(self, *names): """ "Delete one or more keys specified by ``names``" Cluster impl: Iterate all keys and send DELETE for each key. This will go a lot slower than a normal delete call in StrictRedis. Operation is no longer atomic. """ count = 0 for arg in names: count += await self.execute_command('DEL', arg) return count
python
async def delete(self, *names): """ "Delete one or more keys specified by ``names``" Cluster impl: Iterate all keys and send DELETE for each key. This will go a lot slower than a normal delete call in StrictRedis. Operation is no longer atomic. """ count = 0 for arg in names: count += await self.execute_command('DEL', arg) return count
[ "async", "def", "delete", "(", "self", ",", "*", "names", ")", ":", "count", "=", "0", "for", "arg", "in", "names", ":", "count", "+=", "await", "self", ".", "execute_command", "(", "'DEL'", ",", "arg", ")", "return", "count" ]
"Delete one or more keys specified by ``names``" Cluster impl: Iterate all keys and send DELETE for each key. This will go a lot slower than a normal delete call in StrictRedis. Operation is no longer atomic.
[ "Delete", "one", "or", "more", "keys", "specified", "by", "names" ]
204caad740ac13e5760d46444a2ba7632982a046
https://github.com/NoneGG/aredis/blob/204caad740ac13e5760d46444a2ba7632982a046/aredis/commands/keys.py#L314-L329
train
202,761
NoneGG/aredis
aredis/commands/geo.py
GeoCommandMixin.geoadd
async def geoadd(self, name, *values): """ Add the specified geospatial items to the specified key identified by the ``name`` argument. The Geospatial items are given as ordered members of the ``values`` argument, each item or place is formed by the triad latitude, longitude and name. """ if len(values) % 3 != 0: raise RedisError("GEOADD requires places with lon, lat and name" " values") return await self.execute_command('GEOADD', name, *values)
python
async def geoadd(self, name, *values): """ Add the specified geospatial items to the specified key identified by the ``name`` argument. The Geospatial items are given as ordered members of the ``values`` argument, each item or place is formed by the triad latitude, longitude and name. """ if len(values) % 3 != 0: raise RedisError("GEOADD requires places with lon, lat and name" " values") return await self.execute_command('GEOADD', name, *values)
[ "async", "def", "geoadd", "(", "self", ",", "name", ",", "*", "values", ")", ":", "if", "len", "(", "values", ")", "%", "3", "!=", "0", ":", "raise", "RedisError", "(", "\"GEOADD requires places with lon, lat and name\"", "\" values\"", ")", "return", "await...
Add the specified geospatial items to the specified key identified by the ``name`` argument. The Geospatial items are given as ordered members of the ``values`` argument, each item or place is formed by the triad latitude, longitude and name.
[ "Add", "the", "specified", "geospatial", "items", "to", "the", "specified", "key", "identified", "by", "the", "name", "argument", ".", "The", "Geospatial", "items", "are", "given", "as", "ordered", "members", "of", "the", "values", "argument", "each", "item", ...
204caad740ac13e5760d46444a2ba7632982a046
https://github.com/NoneGG/aredis/blob/204caad740ac13e5760d46444a2ba7632982a046/aredis/commands/geo.py#L50-L60
train
202,762
NoneGG/aredis
aredis/commands/geo.py
GeoCommandMixin.georadius
async def georadius(self, name, longitude, latitude, radius, unit=None, withdist=False, withcoord=False, withhash=False, count=None, sort=None, store=None, store_dist=None): """ Return the members of the specified key identified by the ``name`` argument which are within the borders of the area specified with the ``latitude`` and ``longitude`` location and the maximum distance from the center specified by the ``radius`` value. The units must be one of the following : m, km mi, ft. By default ``withdist`` indicates to return the distances of each place. ``withcoord`` indicates to return the latitude and longitude of each place. ``withhash`` indicates to return the geohash string of each place. ``count`` indicates to return the number of elements up to N. ``sort`` indicates to return the places in a sorted way, ASC for nearest to fairest and DESC for fairest to nearest. ``store`` indicates to save the places names in a sorted set named with a specific key, each element of the destination sorted set is populated with the score got from the original geo sorted set. ``store_dist`` indicates to save the places names in a sorted set named with a specific key, instead of ``store`` the sorted set destination score is set with the distance. """ return await self._georadiusgeneric('GEORADIUS', name, longitude, latitude, radius, unit=unit, withdist=withdist, withcoord=withcoord, withhash=withhash, count=count, sort=sort, store=store, store_dist=store_dist)
python
async def georadius(self, name, longitude, latitude, radius, unit=None, withdist=False, withcoord=False, withhash=False, count=None, sort=None, store=None, store_dist=None): """ Return the members of the specified key identified by the ``name`` argument which are within the borders of the area specified with the ``latitude`` and ``longitude`` location and the maximum distance from the center specified by the ``radius`` value. The units must be one of the following : m, km mi, ft. By default ``withdist`` indicates to return the distances of each place. ``withcoord`` indicates to return the latitude and longitude of each place. ``withhash`` indicates to return the geohash string of each place. ``count`` indicates to return the number of elements up to N. ``sort`` indicates to return the places in a sorted way, ASC for nearest to fairest and DESC for fairest to nearest. ``store`` indicates to save the places names in a sorted set named with a specific key, each element of the destination sorted set is populated with the score got from the original geo sorted set. ``store_dist`` indicates to save the places names in a sorted set named with a specific key, instead of ``store`` the sorted set destination score is set with the distance. """ return await self._georadiusgeneric('GEORADIUS', name, longitude, latitude, radius, unit=unit, withdist=withdist, withcoord=withcoord, withhash=withhash, count=count, sort=sort, store=store, store_dist=store_dist)
[ "async", "def", "georadius", "(", "self", ",", "name", ",", "longitude", ",", "latitude", ",", "radius", ",", "unit", "=", "None", ",", "withdist", "=", "False", ",", "withcoord", "=", "False", ",", "withhash", "=", "False", ",", "count", "=", "None", ...
Return the members of the specified key identified by the ``name`` argument which are within the borders of the area specified with the ``latitude`` and ``longitude`` location and the maximum distance from the center specified by the ``radius`` value. The units must be one of the following : m, km mi, ft. By default ``withdist`` indicates to return the distances of each place. ``withcoord`` indicates to return the latitude and longitude of each place. ``withhash`` indicates to return the geohash string of each place. ``count`` indicates to return the number of elements up to N. ``sort`` indicates to return the places in a sorted way, ASC for nearest to fairest and DESC for fairest to nearest. ``store`` indicates to save the places names in a sorted set named with a specific key, each element of the destination sorted set is populated with the score got from the original geo sorted set. ``store_dist`` indicates to save the places names in a sorted set named with a specific key, instead of ``store`` the sorted set destination score is set with the distance.
[ "Return", "the", "members", "of", "the", "specified", "key", "identified", "by", "the", "name", "argument", "which", "are", "within", "the", "borders", "of", "the", "area", "specified", "with", "the", "latitude", "and", "longitude", "location", "and", "the", ...
204caad740ac13e5760d46444a2ba7632982a046
https://github.com/NoneGG/aredis/blob/204caad740ac13e5760d46444a2ba7632982a046/aredis/commands/geo.py#L91-L127
train
202,763
NoneGG/aredis
aredis/commands/geo.py
GeoCommandMixin.georadiusbymember
async def georadiusbymember(self, name, member, radius, unit=None, withdist=False, withcoord=False, withhash=False, count=None, sort=None, store=None, store_dist=None): """ This command is exactly like ``georadius`` with the sole difference that instead of taking, as the center of the area to query, a longitude and latitude value, it takes the name of a member already existing inside the geospatial index represented by the sorted set. """ return await self._georadiusgeneric('GEORADIUSBYMEMBER', name, member, radius, unit=unit, withdist=withdist, withcoord=withcoord, withhash=withhash, count=count, sort=sort, store=store, store_dist=store_dist)
python
async def georadiusbymember(self, name, member, radius, unit=None, withdist=False, withcoord=False, withhash=False, count=None, sort=None, store=None, store_dist=None): """ This command is exactly like ``georadius`` with the sole difference that instead of taking, as the center of the area to query, a longitude and latitude value, it takes the name of a member already existing inside the geospatial index represented by the sorted set. """ return await self._georadiusgeneric('GEORADIUSBYMEMBER', name, member, radius, unit=unit, withdist=withdist, withcoord=withcoord, withhash=withhash, count=count, sort=sort, store=store, store_dist=store_dist)
[ "async", "def", "georadiusbymember", "(", "self", ",", "name", ",", "member", ",", "radius", ",", "unit", "=", "None", ",", "withdist", "=", "False", ",", "withcoord", "=", "False", ",", "withhash", "=", "False", ",", "count", "=", "None", ",", "sort",...
This command is exactly like ``georadius`` with the sole difference that instead of taking, as the center of the area to query, a longitude and latitude value, it takes the name of a member already existing inside the geospatial index represented by the sorted set.
[ "This", "command", "is", "exactly", "like", "georadius", "with", "the", "sole", "difference", "that", "instead", "of", "taking", "as", "the", "center", "of", "the", "area", "to", "query", "a", "longitude", "and", "latitude", "value", "it", "takes", "the", ...
204caad740ac13e5760d46444a2ba7632982a046
https://github.com/NoneGG/aredis/blob/204caad740ac13e5760d46444a2ba7632982a046/aredis/commands/geo.py#L129-L143
train
202,764
NoneGG/aredis
aredis/sentinel.py
Sentinel.master_for
def master_for(self, service_name, redis_class=StrictRedis, connection_pool_class=SentinelConnectionPool, **kwargs): """ Returns a redis client instance for the ``service_name`` master. A SentinelConnectionPool class is used to retrive the master's address before establishing a new connection. NOTE: If the master's address has changed, any cached connections to the old master are closed. By default clients will be a redis.StrictRedis instance. Specify a different class to the ``redis_class`` argument if you desire something different. The ``connection_pool_class`` specifies the connection pool to use. The SentinelConnectionPool will be used by default. All other keyword arguments are merged with any connection_kwargs passed to this class and passed to the connection pool as keyword arguments to be used to initialize Redis connections. """ kwargs['is_master'] = True connection_kwargs = dict(self.connection_kwargs) connection_kwargs.update(kwargs) return redis_class(connection_pool=connection_pool_class( service_name, self, **connection_kwargs))
python
def master_for(self, service_name, redis_class=StrictRedis, connection_pool_class=SentinelConnectionPool, **kwargs): """ Returns a redis client instance for the ``service_name`` master. A SentinelConnectionPool class is used to retrive the master's address before establishing a new connection. NOTE: If the master's address has changed, any cached connections to the old master are closed. By default clients will be a redis.StrictRedis instance. Specify a different class to the ``redis_class`` argument if you desire something different. The ``connection_pool_class`` specifies the connection pool to use. The SentinelConnectionPool will be used by default. All other keyword arguments are merged with any connection_kwargs passed to this class and passed to the connection pool as keyword arguments to be used to initialize Redis connections. """ kwargs['is_master'] = True connection_kwargs = dict(self.connection_kwargs) connection_kwargs.update(kwargs) return redis_class(connection_pool=connection_pool_class( service_name, self, **connection_kwargs))
[ "def", "master_for", "(", "self", ",", "service_name", ",", "redis_class", "=", "StrictRedis", ",", "connection_pool_class", "=", "SentinelConnectionPool", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'is_master'", "]", "=", "True", "connection_kwargs", "=...
Returns a redis client instance for the ``service_name`` master. A SentinelConnectionPool class is used to retrive the master's address before establishing a new connection. NOTE: If the master's address has changed, any cached connections to the old master are closed. By default clients will be a redis.StrictRedis instance. Specify a different class to the ``redis_class`` argument if you desire something different. The ``connection_pool_class`` specifies the connection pool to use. The SentinelConnectionPool will be used by default. All other keyword arguments are merged with any connection_kwargs passed to this class and passed to the connection pool as keyword arguments to be used to initialize Redis connections.
[ "Returns", "a", "redis", "client", "instance", "for", "the", "service_name", "master", "." ]
204caad740ac13e5760d46444a2ba7632982a046
https://github.com/NoneGG/aredis/blob/204caad740ac13e5760d46444a2ba7632982a046/aredis/sentinel.py#L248-L274
train
202,765
NoneGG/aredis
aredis/lock.py
Lock.extend
async def extend(self, additional_time): """ Adds more time to an already acquired lock. ``additional_time`` can be specified as an integer or a float, both representing the number of seconds to add. """ if self.local.token is None: raise LockError("Cannot extend an unlocked lock") if self.timeout is None: raise LockError("Cannot extend a lock with no timeout") return await self.do_extend(additional_time)
python
async def extend(self, additional_time): """ Adds more time to an already acquired lock. ``additional_time`` can be specified as an integer or a float, both representing the number of seconds to add. """ if self.local.token is None: raise LockError("Cannot extend an unlocked lock") if self.timeout is None: raise LockError("Cannot extend a lock with no timeout") return await self.do_extend(additional_time)
[ "async", "def", "extend", "(", "self", ",", "additional_time", ")", ":", "if", "self", ".", "local", ".", "token", "is", "None", ":", "raise", "LockError", "(", "\"Cannot extend an unlocked lock\"", ")", "if", "self", ".", "timeout", "is", "None", ":", "ra...
Adds more time to an already acquired lock. ``additional_time`` can be specified as an integer or a float, both representing the number of seconds to add.
[ "Adds", "more", "time", "to", "an", "already", "acquired", "lock", "." ]
204caad740ac13e5760d46444a2ba7632982a046
https://github.com/NoneGG/aredis/blob/204caad740ac13e5760d46444a2ba7632982a046/aredis/lock.py#L151-L162
train
202,766
NoneGG/aredis
aredis/commands/cluster.py
ClusterCommandMixin.cluster_delslots
async def cluster_delslots(self, *slots): """ Set hash slots as unbound in the cluster. It determines by it self what node the slot is in and sends it there Returns a list of the results for each processed slot. """ cluster_nodes = self._nodes_slots_to_slots_nodes(await self.cluster_nodes()) res = list() for slot in slots: res.append(await self.execute_command('CLUSTER DELSLOTS', slot, node_id=cluster_nodes[slot])) return res
python
async def cluster_delslots(self, *slots): """ Set hash slots as unbound in the cluster. It determines by it self what node the slot is in and sends it there Returns a list of the results for each processed slot. """ cluster_nodes = self._nodes_slots_to_slots_nodes(await self.cluster_nodes()) res = list() for slot in slots: res.append(await self.execute_command('CLUSTER DELSLOTS', slot, node_id=cluster_nodes[slot])) return res
[ "async", "def", "cluster_delslots", "(", "self", ",", "*", "slots", ")", ":", "cluster_nodes", "=", "self", ".", "_nodes_slots_to_slots_nodes", "(", "await", "self", ".", "cluster_nodes", "(", ")", ")", "res", "=", "list", "(", ")", "for", "slot", "in", ...
Set hash slots as unbound in the cluster. It determines by it self what node the slot is in and sends it there Returns a list of the results for each processed slot.
[ "Set", "hash", "slots", "as", "unbound", "in", "the", "cluster", ".", "It", "determines", "by", "it", "self", "what", "node", "the", "slot", "is", "in", "and", "sends", "it", "there" ]
204caad740ac13e5760d46444a2ba7632982a046
https://github.com/NoneGG/aredis/blob/204caad740ac13e5760d46444a2ba7632982a046/aredis/commands/cluster.py#L181-L192
train
202,767
NoneGG/aredis
aredis/commands/cluster.py
ClusterCommandMixin.cluster_failover
async def cluster_failover(self, node_id, option): """ Forces a slave to perform a manual failover of its master Sends to specefied node """ if not isinstance(option, str) or option.upper() not in {'FORCE', 'TAKEOVER'}: raise ClusterError('Wrong option provided') return await self.execute_command('CLUSTER FAILOVER', option, node_id=node_id)
python
async def cluster_failover(self, node_id, option): """ Forces a slave to perform a manual failover of its master Sends to specefied node """ if not isinstance(option, str) or option.upper() not in {'FORCE', 'TAKEOVER'}: raise ClusterError('Wrong option provided') return await self.execute_command('CLUSTER FAILOVER', option, node_id=node_id)
[ "async", "def", "cluster_failover", "(", "self", ",", "node_id", ",", "option", ")", ":", "if", "not", "isinstance", "(", "option", ",", "str", ")", "or", "option", ".", "upper", "(", ")", "not", "in", "{", "'FORCE'", ",", "'TAKEOVER'", "}", ":", "ra...
Forces a slave to perform a manual failover of its master Sends to specefied node
[ "Forces", "a", "slave", "to", "perform", "a", "manual", "failover", "of", "its", "master" ]
204caad740ac13e5760d46444a2ba7632982a046
https://github.com/NoneGG/aredis/blob/204caad740ac13e5760d46444a2ba7632982a046/aredis/commands/cluster.py#L194-L202
train
202,768
NoneGG/aredis
aredis/commands/cluster.py
ClusterCommandMixin.cluster_reset
async def cluster_reset(self, node_id, soft=True): """ Reset a Redis Cluster node If 'soft' is True then it will send 'SOFT' argument If 'soft' is False then it will send 'HARD' argument Sends to specefied node """ option = 'SOFT' if soft else 'HARD' return await self.execute_command('CLUSTER RESET', option, node_id=node_id)
python
async def cluster_reset(self, node_id, soft=True): """ Reset a Redis Cluster node If 'soft' is True then it will send 'SOFT' argument If 'soft' is False then it will send 'HARD' argument Sends to specefied node """ option = 'SOFT' if soft else 'HARD' return await self.execute_command('CLUSTER RESET', option, node_id=node_id)
[ "async", "def", "cluster_reset", "(", "self", ",", "node_id", ",", "soft", "=", "True", ")", ":", "option", "=", "'SOFT'", "if", "soft", "else", "'HARD'", "return", "await", "self", ".", "execute_command", "(", "'CLUSTER RESET'", ",", "option", ",", "node_...
Reset a Redis Cluster node If 'soft' is True then it will send 'SOFT' argument If 'soft' is False then it will send 'HARD' argument Sends to specefied node
[ "Reset", "a", "Redis", "Cluster", "node" ]
204caad740ac13e5760d46444a2ba7632982a046
https://github.com/NoneGG/aredis/blob/204caad740ac13e5760d46444a2ba7632982a046/aredis/commands/cluster.py#L253-L263
train
202,769
NoneGG/aredis
aredis/commands/cluster.py
ClusterCommandMixin.cluster_reset_all_nodes
async def cluster_reset_all_nodes(self, soft=True): """ Send CLUSTER RESET to all nodes in the cluster If 'soft' is True then it will send 'SOFT' argument If 'soft' is False then it will send 'HARD' argument Sends to all nodes in the cluster """ option = 'SOFT' if soft else 'HARD' res = list() for node in await self.cluster_nodes(): res.append( await self.execute_command( 'CLUSTER RESET', option, node_id=node['id'] )) return res
python
async def cluster_reset_all_nodes(self, soft=True): """ Send CLUSTER RESET to all nodes in the cluster If 'soft' is True then it will send 'SOFT' argument If 'soft' is False then it will send 'HARD' argument Sends to all nodes in the cluster """ option = 'SOFT' if soft else 'HARD' res = list() for node in await self.cluster_nodes(): res.append( await self.execute_command( 'CLUSTER RESET', option, node_id=node['id'] )) return res
[ "async", "def", "cluster_reset_all_nodes", "(", "self", ",", "soft", "=", "True", ")", ":", "option", "=", "'SOFT'", "if", "soft", "else", "'HARD'", "res", "=", "list", "(", ")", "for", "node", "in", "await", "self", ".", "cluster_nodes", "(", ")", ":"...
Send CLUSTER RESET to all nodes in the cluster If 'soft' is True then it will send 'SOFT' argument If 'soft' is False then it will send 'HARD' argument Sends to all nodes in the cluster
[ "Send", "CLUSTER", "RESET", "to", "all", "nodes", "in", "the", "cluster" ]
204caad740ac13e5760d46444a2ba7632982a046
https://github.com/NoneGG/aredis/blob/204caad740ac13e5760d46444a2ba7632982a046/aredis/commands/cluster.py#L265-L281
train
202,770
NoneGG/aredis
aredis/commands/cluster.py
ClusterCommandMixin.cluster_setslot
async def cluster_setslot(self, node_id, slot_id, state): """ Bind an hash slot to a specific node Sends to specified node """ if state.upper() in {'IMPORTING', 'MIGRATING', 'NODE'} and node_id is not None: return await self.execute_command('CLUSTER SETSLOT', slot_id, state, node_id) elif state.upper() == 'STABLE': return await self.execute_command('CLUSTER SETSLOT', slot_id, 'STABLE') else: raise RedisError('Invalid slot state: {0}'.format(state))
python
async def cluster_setslot(self, node_id, slot_id, state): """ Bind an hash slot to a specific node Sends to specified node """ if state.upper() in {'IMPORTING', 'MIGRATING', 'NODE'} and node_id is not None: return await self.execute_command('CLUSTER SETSLOT', slot_id, state, node_id) elif state.upper() == 'STABLE': return await self.execute_command('CLUSTER SETSLOT', slot_id, 'STABLE') else: raise RedisError('Invalid slot state: {0}'.format(state))
[ "async", "def", "cluster_setslot", "(", "self", ",", "node_id", ",", "slot_id", ",", "state", ")", ":", "if", "state", ".", "upper", "(", ")", "in", "{", "'IMPORTING'", ",", "'MIGRATING'", ",", "'NODE'", "}", "and", "node_id", "is", "not", "None", ":",...
Bind an hash slot to a specific node Sends to specified node
[ "Bind", "an", "hash", "slot", "to", "a", "specific", "node" ]
204caad740ac13e5760d46444a2ba7632982a046
https://github.com/NoneGG/aredis/blob/204caad740ac13e5760d46444a2ba7632982a046/aredis/commands/cluster.py#L300-L311
train
202,771
NoneGG/aredis
aredis/scripting.py
Script.execute
async def execute(self, keys=[], args=[], client=None): "Execute the script, passing any required ``args``" if client is None: client = self.registered_client args = tuple(keys) + tuple(args) # make sure the Redis server knows about the script if isinstance(client, BasePipeline): # make sure this script is good to go on pipeline client.scripts.add(self) try: return await client.evalsha(self.sha, len(keys), *args) except NoScriptError: # Maybe the client is pointed to a differnet server than the client # that created this instance? # Overwrite the sha just in case there was a discrepancy. self.sha = await client.script_load(self.script) return await client.evalsha(self.sha, len(keys), *args)
python
async def execute(self, keys=[], args=[], client=None): "Execute the script, passing any required ``args``" if client is None: client = self.registered_client args = tuple(keys) + tuple(args) # make sure the Redis server knows about the script if isinstance(client, BasePipeline): # make sure this script is good to go on pipeline client.scripts.add(self) try: return await client.evalsha(self.sha, len(keys), *args) except NoScriptError: # Maybe the client is pointed to a differnet server than the client # that created this instance? # Overwrite the sha just in case there was a discrepancy. self.sha = await client.script_load(self.script) return await client.evalsha(self.sha, len(keys), *args)
[ "async", "def", "execute", "(", "self", ",", "keys", "=", "[", "]", ",", "args", "=", "[", "]", ",", "client", "=", "None", ")", ":", "if", "client", "is", "None", ":", "client", "=", "self", ".", "registered_client", "args", "=", "tuple", "(", "...
Execute the script, passing any required ``args``
[ "Execute", "the", "script", "passing", "any", "required", "args" ]
204caad740ac13e5760d46444a2ba7632982a046
https://github.com/NoneGG/aredis/blob/204caad740ac13e5760d46444a2ba7632982a046/aredis/scripting.py#L15-L31
train
202,772
NoneGG/aredis
aredis/commands/hyperlog.py
ClusterHyperLogCommandMixin._random_id
def _random_id(self, size=16, chars=string.ascii_uppercase + string.digits): """ Generates a random id based on `size` and `chars` variable. By default it will generate a 16 character long string based on ascii uppercase letters and digits. """ return ''.join(random.choice(chars) for _ in range(size))
python
def _random_id(self, size=16, chars=string.ascii_uppercase + string.digits): """ Generates a random id based on `size` and `chars` variable. By default it will generate a 16 character long string based on ascii uppercase letters and digits. """ return ''.join(random.choice(chars) for _ in range(size))
[ "def", "_random_id", "(", "self", ",", "size", "=", "16", ",", "chars", "=", "string", ".", "ascii_uppercase", "+", "string", ".", "digits", ")", ":", "return", "''", ".", "join", "(", "random", ".", "choice", "(", "chars", ")", "for", "_", "in", "...
Generates a random id based on `size` and `chars` variable. By default it will generate a 16 character long string based on ascii uppercase letters and digits.
[ "Generates", "a", "random", "id", "based", "on", "size", "and", "chars", "variable", "." ]
204caad740ac13e5760d46444a2ba7632982a046
https://github.com/NoneGG/aredis/blob/204caad740ac13e5760d46444a2ba7632982a046/aredis/commands/hyperlog.py#L96-L103
train
202,773
NoneGG/aredis
aredis/commands/sentinel.py
SentinelCommandMixin.sentinel_monitor
async def sentinel_monitor(self, name, ip, port, quorum): "Add a new master to Sentinel to be monitored" return await self.execute_command('SENTINEL MONITOR', name, ip, port, quorum)
python
async def sentinel_monitor(self, name, ip, port, quorum): "Add a new master to Sentinel to be monitored" return await self.execute_command('SENTINEL MONITOR', name, ip, port, quorum)
[ "async", "def", "sentinel_monitor", "(", "self", ",", "name", ",", "ip", ",", "port", ",", "quorum", ")", ":", "return", "await", "self", ".", "execute_command", "(", "'SENTINEL MONITOR'", ",", "name", ",", "ip", ",", "port", ",", "quorum", ")" ]
Add a new master to Sentinel to be monitored
[ "Add", "a", "new", "master", "to", "Sentinel", "to", "be", "monitored" ]
204caad740ac13e5760d46444a2ba7632982a046
https://github.com/NoneGG/aredis/blob/204caad740ac13e5760d46444a2ba7632982a046/aredis/commands/sentinel.py#L110-L112
train
202,774
NoneGG/aredis
aredis/commands/sentinel.py
SentinelCommandMixin.sentinel_set
async def sentinel_set(self, name, option, value): "Set Sentinel monitoring parameters for a given master" return await self.execute_command('SENTINEL SET', name, option, value)
python
async def sentinel_set(self, name, option, value): "Set Sentinel monitoring parameters for a given master" return await self.execute_command('SENTINEL SET', name, option, value)
[ "async", "def", "sentinel_set", "(", "self", ",", "name", ",", "option", ",", "value", ")", ":", "return", "await", "self", ".", "execute_command", "(", "'SENTINEL SET'", ",", "name", ",", "option", ",", "value", ")" ]
Set Sentinel monitoring parameters for a given master
[ "Set", "Sentinel", "monitoring", "parameters", "for", "a", "given", "master" ]
204caad740ac13e5760d46444a2ba7632982a046
https://github.com/NoneGG/aredis/blob/204caad740ac13e5760d46444a2ba7632982a046/aredis/commands/sentinel.py#L122-L124
train
202,775
NoneGG/aredis
aredis/commands/sets.py
SetsCommandMixin.sdiff
async def sdiff(self, keys, *args): "Return the difference of sets specified by ``keys``" args = list_or_args(keys, args) return await self.execute_command('SDIFF', *args)
python
async def sdiff(self, keys, *args): "Return the difference of sets specified by ``keys``" args = list_or_args(keys, args) return await self.execute_command('SDIFF', *args)
[ "async", "def", "sdiff", "(", "self", ",", "keys", ",", "*", "args", ")", ":", "args", "=", "list_or_args", "(", "keys", ",", "args", ")", "return", "await", "self", ".", "execute_command", "(", "'SDIFF'", ",", "*", "args", ")" ]
Return the difference of sets specified by ``keys``
[ "Return", "the", "difference", "of", "sets", "specified", "by", "keys" ]
204caad740ac13e5760d46444a2ba7632982a046
https://github.com/NoneGG/aredis/blob/204caad740ac13e5760d46444a2ba7632982a046/aredis/commands/sets.py#L40-L43
train
202,776
NoneGG/aredis
aredis/commands/sets.py
SetsCommandMixin.spop
async def spop(self, name, count=None): """ Remove and return a random member of set ``name`` ``count`` should be type of int and default set to 1. If ``count`` is supplied, pops a list of ``count`` random + members of set ``name`` """ if count and isinstance(count, int): return await self.execute_command('SPOP', name, count) else: return await self.execute_command('SPOP', name)
python
async def spop(self, name, count=None): """ Remove and return a random member of set ``name`` ``count`` should be type of int and default set to 1. If ``count`` is supplied, pops a list of ``count`` random + members of set ``name`` """ if count and isinstance(count, int): return await self.execute_command('SPOP', name, count) else: return await self.execute_command('SPOP', name)
[ "async", "def", "spop", "(", "self", ",", "name", ",", "count", "=", "None", ")", ":", "if", "count", "and", "isinstance", "(", "count", ",", "int", ")", ":", "return", "await", "self", ".", "execute_command", "(", "'SPOP'", ",", "name", ",", "count"...
Remove and return a random member of set ``name`` ``count`` should be type of int and default set to 1. If ``count`` is supplied, pops a list of ``count`` random + members of set ``name``
[ "Remove", "and", "return", "a", "random", "member", "of", "set", "name", "count", "should", "be", "type", "of", "int", "and", "default", "set", "to", "1", ".", "If", "count", "is", "supplied", "pops", "a", "list", "of", "count", "random", "+", "members...
204caad740ac13e5760d46444a2ba7632982a046
https://github.com/NoneGG/aredis/blob/204caad740ac13e5760d46444a2ba7632982a046/aredis/commands/sets.py#L78-L88
train
202,777
NoneGG/aredis
aredis/commands/sets.py
SetsCommandMixin.srandmember
async def srandmember(self, name, number=None): """ If ``number`` is None, returns a random member of set ``name``. If ``number`` is supplied, returns a list of ``number`` random memebers of set ``name``. Note this is only available when running Redis 2.6+. """ args = number and [number] or [] return await self.execute_command('SRANDMEMBER', name, *args)
python
async def srandmember(self, name, number=None): """ If ``number`` is None, returns a random member of set ``name``. If ``number`` is supplied, returns a list of ``number`` random memebers of set ``name``. Note this is only available when running Redis 2.6+. """ args = number and [number] or [] return await self.execute_command('SRANDMEMBER', name, *args)
[ "async", "def", "srandmember", "(", "self", ",", "name", ",", "number", "=", "None", ")", ":", "args", "=", "number", "and", "[", "number", "]", "or", "[", "]", "return", "await", "self", ".", "execute_command", "(", "'SRANDMEMBER'", ",", "name", ",", ...
If ``number`` is None, returns a random member of set ``name``. If ``number`` is supplied, returns a list of ``number`` random memebers of set ``name``. Note this is only available when running Redis 2.6+.
[ "If", "number", "is", "None", "returns", "a", "random", "member", "of", "set", "name", "." ]
204caad740ac13e5760d46444a2ba7632982a046
https://github.com/NoneGG/aredis/blob/204caad740ac13e5760d46444a2ba7632982a046/aredis/commands/sets.py#L90-L99
train
202,778
NoneGG/aredis
aredis/commands/sets.py
SetsCommandMixin.sunion
async def sunion(self, keys, *args): "Return the union of sets specified by ``keys``" args = list_or_args(keys, args) return await self.execute_command('SUNION', *args)
python
async def sunion(self, keys, *args): "Return the union of sets specified by ``keys``" args = list_or_args(keys, args) return await self.execute_command('SUNION', *args)
[ "async", "def", "sunion", "(", "self", ",", "keys", ",", "*", "args", ")", ":", "args", "=", "list_or_args", "(", "keys", ",", "args", ")", "return", "await", "self", ".", "execute_command", "(", "'SUNION'", ",", "*", "args", ")" ]
Return the union of sets specified by ``keys``
[ "Return", "the", "union", "of", "sets", "specified", "by", "keys" ]
204caad740ac13e5760d46444a2ba7632982a046
https://github.com/NoneGG/aredis/blob/204caad740ac13e5760d46444a2ba7632982a046/aredis/commands/sets.py#L105-L108
train
202,779
NoneGG/aredis
aredis/commands/sets.py
ClusterSetsCommandMixin.sdiffstore
async def sdiffstore(self, dest, keys, *args): """ Store the difference of sets specified by ``keys`` into a new set named ``dest``. Returns the number of keys in the new set. Overwrites dest key if it exists. Cluster impl: Use sdiff() --> Delete dest key --> store result in dest key """ res = await self.sdiff(keys, *args) await self.delete(dest) if not res: return 0 return await self.sadd(dest, *res)
python
async def sdiffstore(self, dest, keys, *args): """ Store the difference of sets specified by ``keys`` into a new set named ``dest``. Returns the number of keys in the new set. Overwrites dest key if it exists. Cluster impl: Use sdiff() --> Delete dest key --> store result in dest key """ res = await self.sdiff(keys, *args) await self.delete(dest) if not res: return 0 return await self.sadd(dest, *res)
[ "async", "def", "sdiffstore", "(", "self", ",", "dest", ",", "keys", ",", "*", "args", ")", ":", "res", "=", "await", "self", ".", "sdiff", "(", "keys", ",", "*", "args", ")", "await", "self", ".", "delete", "(", "dest", ")", "if", "not", "res", ...
Store the difference of sets specified by ``keys`` into a new set named ``dest``. Returns the number of keys in the new set. Overwrites dest key if it exists. Cluster impl: Use sdiff() --> Delete dest key --> store result in dest key
[ "Store", "the", "difference", "of", "sets", "specified", "by", "keys", "into", "a", "new", "set", "named", "dest", ".", "Returns", "the", "number", "of", "keys", "in", "the", "new", "set", ".", "Overwrites", "dest", "key", "if", "it", "exists", "." ]
204caad740ac13e5760d46444a2ba7632982a046
https://github.com/NoneGG/aredis/blob/204caad740ac13e5760d46444a2ba7632982a046/aredis/commands/sets.py#L160-L174
train
202,780
NoneGG/aredis
aredis/client.py
StrictRedisCluster.execute_command
async def execute_command(self, *args, **kwargs): """ Send a command to a node in the cluster """ if not self.connection_pool.initialized: await self.connection_pool.initialize() if not args: raise RedisClusterException("Unable to determine command to use") command = args[0] node = self.determine_node(*args, **kwargs) if node: return await self.execute_command_on_nodes(node, *args, **kwargs) # If set externally we must update it before calling any commands if self.refresh_table_asap: await self.connection_pool.nodes.initialize() self.refresh_table_asap = False redirect_addr = None asking = False try_random_node = False slot = self._determine_slot(*args) ttl = int(self.RedisClusterRequestTTL) while ttl > 0: ttl -= 1 if asking: node = self.connection_pool.nodes.nodes[redirect_addr] r = self.connection_pool.get_connection_by_node(node) elif try_random_node: r = self.connection_pool.get_random_connection() try_random_node = False else: if self.refresh_table_asap: # MOVED node = self.connection_pool.get_master_node_by_slot(slot) else: node = self.connection_pool.get_node_by_slot(slot) r = self.connection_pool.get_connection_by_node(node) try: if asking: await r.send_command('ASKING') await self.parse_response(r, "ASKING", **kwargs) asking = False await r.send_command(*args) return await self.parse_response(r, command, **kwargs) except (RedisClusterException, BusyLoadingError): raise except (CancelledError, ConnectionError, TimeoutError): try_random_node = True if ttl < self.RedisClusterRequestTTL / 2: await asyncio.sleep(0.1) except ClusterDownError as e: self.connection_pool.disconnect() self.connection_pool.reset() self.refresh_table_asap = True raise e except MovedError as e: # Reinitialize on ever x number of MovedError. # This counter will increase faster when the same client object # is shared between multiple threads. To reduce the frequency you # can set the variable 'reinitialize_steps' in the constructor. self.refresh_table_asap = True await self.connection_pool.nodes.increment_reinitialize_counter() node = self.connection_pool.nodes.set_node(e.host, e.port, server_type='master') self.connection_pool.nodes.slots[e.slot_id][0] = node except TryAgainError as e: if ttl < self.RedisClusterRequestTTL / 2: await asyncio.sleep(0.05) except AskError as e: redirect_addr, asking = "{0}:{1}".format(e.host, e.port), True finally: self.connection_pool.release(r) raise ClusterError('TTL exhausted.')
python
async def execute_command(self, *args, **kwargs): """ Send a command to a node in the cluster """ if not self.connection_pool.initialized: await self.connection_pool.initialize() if not args: raise RedisClusterException("Unable to determine command to use") command = args[0] node = self.determine_node(*args, **kwargs) if node: return await self.execute_command_on_nodes(node, *args, **kwargs) # If set externally we must update it before calling any commands if self.refresh_table_asap: await self.connection_pool.nodes.initialize() self.refresh_table_asap = False redirect_addr = None asking = False try_random_node = False slot = self._determine_slot(*args) ttl = int(self.RedisClusterRequestTTL) while ttl > 0: ttl -= 1 if asking: node = self.connection_pool.nodes.nodes[redirect_addr] r = self.connection_pool.get_connection_by_node(node) elif try_random_node: r = self.connection_pool.get_random_connection() try_random_node = False else: if self.refresh_table_asap: # MOVED node = self.connection_pool.get_master_node_by_slot(slot) else: node = self.connection_pool.get_node_by_slot(slot) r = self.connection_pool.get_connection_by_node(node) try: if asking: await r.send_command('ASKING') await self.parse_response(r, "ASKING", **kwargs) asking = False await r.send_command(*args) return await self.parse_response(r, command, **kwargs) except (RedisClusterException, BusyLoadingError): raise except (CancelledError, ConnectionError, TimeoutError): try_random_node = True if ttl < self.RedisClusterRequestTTL / 2: await asyncio.sleep(0.1) except ClusterDownError as e: self.connection_pool.disconnect() self.connection_pool.reset() self.refresh_table_asap = True raise e except MovedError as e: # Reinitialize on ever x number of MovedError. # This counter will increase faster when the same client object # is shared between multiple threads. To reduce the frequency you # can set the variable 'reinitialize_steps' in the constructor. self.refresh_table_asap = True await self.connection_pool.nodes.increment_reinitialize_counter() node = self.connection_pool.nodes.set_node(e.host, e.port, server_type='master') self.connection_pool.nodes.slots[e.slot_id][0] = node except TryAgainError as e: if ttl < self.RedisClusterRequestTTL / 2: await asyncio.sleep(0.05) except AskError as e: redirect_addr, asking = "{0}:{1}".format(e.host, e.port), True finally: self.connection_pool.release(r) raise ClusterError('TTL exhausted.')
[ "async", "def", "execute_command", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "not", "self", ".", "connection_pool", ".", "initialized", ":", "await", "self", ".", "connection_pool", ".", "initialize", "(", ")", "if", "not", ...
Send a command to a node in the cluster
[ "Send", "a", "command", "to", "a", "node", "in", "the", "cluster" ]
204caad740ac13e5760d46444a2ba7632982a046
https://github.com/NoneGG/aredis/blob/204caad740ac13e5760d46444a2ba7632982a046/aredis/client.py#L352-L435
train
202,781
NoneGG/aredis
aredis/connection.py
PythonParser.on_connect
def on_connect(self, connection): "Called when the stream connects" self._stream = connection._reader self._buffer = SocketBuffer(self._stream, self._read_size) if connection.decode_responses: self.encoding = connection.encoding
python
def on_connect(self, connection): "Called when the stream connects" self._stream = connection._reader self._buffer = SocketBuffer(self._stream, self._read_size) if connection.decode_responses: self.encoding = connection.encoding
[ "def", "on_connect", "(", "self", ",", "connection", ")", ":", "self", ".", "_stream", "=", "connection", ".", "_reader", "self", ".", "_buffer", "=", "SocketBuffer", "(", "self", ".", "_stream", ",", "self", ".", "_read_size", ")", "if", "connection", "...
Called when the stream connects
[ "Called", "when", "the", "stream", "connects" ]
204caad740ac13e5760d46444a2ba7632982a046
https://github.com/NoneGG/aredis/blob/204caad740ac13e5760d46444a2ba7632982a046/aredis/connection.py#L180-L185
train
202,782
NoneGG/aredis
aredis/connection.py
PythonParser.on_disconnect
def on_disconnect(self): "Called when the stream disconnects" if self._stream is not None: self._stream = None if self._buffer is not None: self._buffer.close() self._buffer = None self.encoding = None
python
def on_disconnect(self): "Called when the stream disconnects" if self._stream is not None: self._stream = None if self._buffer is not None: self._buffer.close() self._buffer = None self.encoding = None
[ "def", "on_disconnect", "(", "self", ")", ":", "if", "self", ".", "_stream", "is", "not", "None", ":", "self", ".", "_stream", "=", "None", "if", "self", ".", "_buffer", "is", "not", "None", ":", "self", ".", "_buffer", ".", "close", "(", ")", "sel...
Called when the stream disconnects
[ "Called", "when", "the", "stream", "disconnects" ]
204caad740ac13e5760d46444a2ba7632982a046
https://github.com/NoneGG/aredis/blob/204caad740ac13e5760d46444a2ba7632982a046/aredis/connection.py#L187-L194
train
202,783
NoneGG/aredis
aredis/connection.py
BaseConnection.can_read
async def can_read(self): "See if there's data that can be read." if not (self._reader and self._writer): await self.connect() return self._parser.can_read()
python
async def can_read(self): "See if there's data that can be read." if not (self._reader and self._writer): await self.connect() return self._parser.can_read()
[ "async", "def", "can_read", "(", "self", ")", ":", "if", "not", "(", "self", ".", "_reader", "and", "self", ".", "_writer", ")", ":", "await", "self", ".", "connect", "(", ")", "return", "self", ".", "_parser", ".", "can_read", "(", ")" ]
See if there's data that can be read.
[ "See", "if", "there", "s", "data", "that", "can", "be", "read", "." ]
204caad740ac13e5760d46444a2ba7632982a046
https://github.com/NoneGG/aredis/blob/204caad740ac13e5760d46444a2ba7632982a046/aredis/connection.py#L398-L402
train
202,784
NoneGG/aredis
aredis/connection.py
BaseConnection.pack_commands
def pack_commands(self, commands): "Pack multiple commands into the Redis protocol" output = [] pieces = [] buffer_length = 0 for cmd in commands: for chunk in self.pack_command(*cmd): pieces.append(chunk) buffer_length += len(chunk) if buffer_length > 6000: output.append(SYM_EMPTY.join(pieces)) buffer_length = 0 pieces = [] if pieces: output.append(SYM_EMPTY.join(pieces)) return output
python
def pack_commands(self, commands): "Pack multiple commands into the Redis protocol" output = [] pieces = [] buffer_length = 0 for cmd in commands: for chunk in self.pack_command(*cmd): pieces.append(chunk) buffer_length += len(chunk) if buffer_length > 6000: output.append(SYM_EMPTY.join(pieces)) buffer_length = 0 pieces = [] if pieces: output.append(SYM_EMPTY.join(pieces)) return output
[ "def", "pack_commands", "(", "self", ",", "commands", ")", ":", "output", "=", "[", "]", "pieces", "=", "[", "]", "buffer_length", "=", "0", "for", "cmd", "in", "commands", ":", "for", "chunk", "in", "self", ".", "pack_command", "(", "*", "cmd", ")",...
Pack multiple commands into the Redis protocol
[ "Pack", "multiple", "commands", "into", "the", "Redis", "protocol" ]
204caad740ac13e5760d46444a2ba7632982a046
https://github.com/NoneGG/aredis/blob/204caad740ac13e5760d46444a2ba7632982a046/aredis/connection.py#L534-L552
train
202,785
NoneGG/aredis
aredis/connection.py
ClusterConnection.on_connect
async def on_connect(self): """ Initialize the connection, authenticate and select a database and send READONLY if it is set during object initialization. """ if self.db: warnings.warn('SELECT DB is not allowed in cluster mode') self.db = '' await super(ClusterConnection, self).on_connect() if self.readonly: await self.send_command('READONLY') if nativestr(await self.read_response()) != 'OK': raise ConnectionError('READONLY command failed')
python
async def on_connect(self): """ Initialize the connection, authenticate and select a database and send READONLY if it is set during object initialization. """ if self.db: warnings.warn('SELECT DB is not allowed in cluster mode') self.db = '' await super(ClusterConnection, self).on_connect() if self.readonly: await self.send_command('READONLY') if nativestr(await self.read_response()) != 'OK': raise ConnectionError('READONLY command failed')
[ "async", "def", "on_connect", "(", "self", ")", ":", "if", "self", ".", "db", ":", "warnings", ".", "warn", "(", "'SELECT DB is not allowed in cluster mode'", ")", "self", ".", "db", "=", "''", "await", "super", "(", "ClusterConnection", ",", "self", ")", ...
Initialize the connection, authenticate and select a database and send READONLY if it is set during object initialization.
[ "Initialize", "the", "connection", "authenticate", "and", "select", "a", "database", "and", "send", "READONLY", "if", "it", "is", "set", "during", "object", "initialization", "." ]
204caad740ac13e5760d46444a2ba7632982a046
https://github.com/NoneGG/aredis/blob/204caad740ac13e5760d46444a2ba7632982a046/aredis/connection.py#L651-L663
train
202,786
wolverdude/GenSON
genson/schema/builder.py
SchemaBuilder.add_schema
def add_schema(self, schema): """ Merge in a JSON schema. This can be a ``dict`` or another ``SchemaBuilder`` :param schema: a JSON Schema .. note:: There is no schema validation. If you pass in a bad schema, you might get back a bad schema. """ if isinstance(schema, SchemaBuilder): schema_uri = schema.schema_uri schema = schema.to_schema() if schema_uri is None: del schema['$schema'] elif isinstance(schema, SchemaNode): schema = schema.to_schema() if '$schema' in schema: self.schema_uri = self.schema_uri or schema['$schema'] schema = dict(schema) del schema['$schema'] self._root_node.add_schema(schema)
python
def add_schema(self, schema): """ Merge in a JSON schema. This can be a ``dict`` or another ``SchemaBuilder`` :param schema: a JSON Schema .. note:: There is no schema validation. If you pass in a bad schema, you might get back a bad schema. """ if isinstance(schema, SchemaBuilder): schema_uri = schema.schema_uri schema = schema.to_schema() if schema_uri is None: del schema['$schema'] elif isinstance(schema, SchemaNode): schema = schema.to_schema() if '$schema' in schema: self.schema_uri = self.schema_uri or schema['$schema'] schema = dict(schema) del schema['$schema'] self._root_node.add_schema(schema)
[ "def", "add_schema", "(", "self", ",", "schema", ")", ":", "if", "isinstance", "(", "schema", ",", "SchemaBuilder", ")", ":", "schema_uri", "=", "schema", ".", "schema_uri", "schema", "=", "schema", ".", "to_schema", "(", ")", "if", "schema_uri", "is", "...
Merge in a JSON schema. This can be a ``dict`` or another ``SchemaBuilder`` :param schema: a JSON Schema .. note:: There is no schema validation. If you pass in a bad schema, you might get back a bad schema.
[ "Merge", "in", "a", "JSON", "schema", ".", "This", "can", "be", "a", "dict", "or", "another", "SchemaBuilder" ]
76552d23cf9202e8e7c262cb018eb3cb3df686b9
https://github.com/wolverdude/GenSON/blob/76552d23cf9202e8e7c262cb018eb3cb3df686b9/genson/schema/builder.py#L33-L56
train
202,787
wolverdude/GenSON
genson/schema/builder.py
SchemaBuilder.to_schema
def to_schema(self): """ Generate a schema based on previous inputs. :rtype: ``dict`` """ schema = self._base_schema() schema.update(self._root_node.to_schema()) return schema
python
def to_schema(self): """ Generate a schema based on previous inputs. :rtype: ``dict`` """ schema = self._base_schema() schema.update(self._root_node.to_schema()) return schema
[ "def", "to_schema", "(", "self", ")", ":", "schema", "=", "self", ".", "_base_schema", "(", ")", "schema", ".", "update", "(", "self", ".", "_root_node", ".", "to_schema", "(", ")", ")", "return", "schema" ]
Generate a schema based on previous inputs. :rtype: ``dict``
[ "Generate", "a", "schema", "based", "on", "previous", "inputs", "." ]
76552d23cf9202e8e7c262cb018eb3cb3df686b9
https://github.com/wolverdude/GenSON/blob/76552d23cf9202e8e7c262cb018eb3cb3df686b9/genson/schema/builder.py#L66-L74
train
202,788
wolverdude/GenSON
genson/schema/builder.py
SchemaBuilder.to_json
def to_json(self, *args, **kwargs): """ Generate a schema and convert it directly to serialized JSON. :rtype: ``str`` """ return json.dumps(self.to_schema(), *args, **kwargs)
python
def to_json(self, *args, **kwargs): """ Generate a schema and convert it directly to serialized JSON. :rtype: ``str`` """ return json.dumps(self.to_schema(), *args, **kwargs)
[ "def", "to_json", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "json", ".", "dumps", "(", "self", ".", "to_schema", "(", ")", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
Generate a schema and convert it directly to serialized JSON. :rtype: ``str``
[ "Generate", "a", "schema", "and", "convert", "it", "directly", "to", "serialized", "JSON", "." ]
76552d23cf9202e8e7c262cb018eb3cb3df686b9
https://github.com/wolverdude/GenSON/blob/76552d23cf9202e8e7c262cb018eb3cb3df686b9/genson/schema/builder.py#L76-L82
train
202,789
wolverdude/GenSON
setup.py
get_long_docs
def get_long_docs(*filenames): """Build rst description from a set of files.""" docs = [] for filename in filenames: with open(filename, 'r') as f: docs.append(f.read()) return "\n\n".join(docs)
python
def get_long_docs(*filenames): """Build rst description from a set of files.""" docs = [] for filename in filenames: with open(filename, 'r') as f: docs.append(f.read()) return "\n\n".join(docs)
[ "def", "get_long_docs", "(", "*", "filenames", ")", ":", "docs", "=", "[", "]", "for", "filename", "in", "filenames", ":", "with", "open", "(", "filename", ",", "'r'", ")", "as", "f", ":", "docs", ".", "append", "(", "f", ".", "read", "(", ")", "...
Build rst description from a set of files.
[ "Build", "rst", "description", "from", "a", "set", "of", "files", "." ]
76552d23cf9202e8e7c262cb018eb3cb3df686b9
https://github.com/wolverdude/GenSON/blob/76552d23cf9202e8e7c262cb018eb3cb3df686b9/setup.py#L5-L12
train
202,790
wolverdude/GenSON
genson/schema/node.py
SchemaNode.add_schema
def add_schema(self, schema): """ Merges in an existing schema. arguments: * `schema` (required - `dict` or `SchemaNode`): an existing JSON Schema to merge. """ # serialize instances of SchemaNode before parsing if isinstance(schema, SchemaNode): schema = schema.to_schema() for subschema in self._get_subschemas(schema): # delegate to SchemaType object schema_generator = self._get_generator_for_schema(subschema) schema_generator.add_schema(subschema) # return self for easy method chaining return self
python
def add_schema(self, schema): """ Merges in an existing schema. arguments: * `schema` (required - `dict` or `SchemaNode`): an existing JSON Schema to merge. """ # serialize instances of SchemaNode before parsing if isinstance(schema, SchemaNode): schema = schema.to_schema() for subschema in self._get_subschemas(schema): # delegate to SchemaType object schema_generator = self._get_generator_for_schema(subschema) schema_generator.add_schema(subschema) # return self for easy method chaining return self
[ "def", "add_schema", "(", "self", ",", "schema", ")", ":", "# serialize instances of SchemaNode before parsing", "if", "isinstance", "(", "schema", ",", "SchemaNode", ")", ":", "schema", "=", "schema", ".", "to_schema", "(", ")", "for", "subschema", "in", "self"...
Merges in an existing schema. arguments: * `schema` (required - `dict` or `SchemaNode`): an existing JSON Schema to merge.
[ "Merges", "in", "an", "existing", "schema", "." ]
76552d23cf9202e8e7c262cb018eb3cb3df686b9
https://github.com/wolverdude/GenSON/blob/76552d23cf9202e8e7c262cb018eb3cb3df686b9/genson/schema/node.py#L18-L37
train
202,791
wolverdude/GenSON
genson/schema/node.py
SchemaNode.add_object
def add_object(self, obj): """ Modify the schema to accommodate an object. arguments: * `obj` (required - `dict`): a JSON object to use in generating the schema. """ # delegate to SchemaType object schema_generator = self._get_generator_for_object(obj) schema_generator.add_object(obj) # return self for easy method chaining return self
python
def add_object(self, obj): """ Modify the schema to accommodate an object. arguments: * `obj` (required - `dict`): a JSON object to use in generating the schema. """ # delegate to SchemaType object schema_generator = self._get_generator_for_object(obj) schema_generator.add_object(obj) # return self for easy method chaining return self
[ "def", "add_object", "(", "self", ",", "obj", ")", ":", "# delegate to SchemaType object", "schema_generator", "=", "self", ".", "_get_generator_for_object", "(", "obj", ")", "schema_generator", ".", "add_object", "(", "obj", ")", "# return self for easy method chaining...
Modify the schema to accommodate an object. arguments: * `obj` (required - `dict`): a JSON object to use in generating the schema.
[ "Modify", "the", "schema", "to", "accommodate", "an", "object", "." ]
76552d23cf9202e8e7c262cb018eb3cb3df686b9
https://github.com/wolverdude/GenSON/blob/76552d23cf9202e8e7c262cb018eb3cb3df686b9/genson/schema/node.py#L39-L53
train
202,792
wolverdude/GenSON
genson/schema/node.py
SchemaNode.to_schema
def to_schema(self): """ Convert the current schema to a `dict`. """ types = set() generated_schemas = [] for schema_generator in self._schema_generators: generated_schema = schema_generator.to_schema() if len(generated_schema) == 1 and 'type' in generated_schema: types.add(generated_schema['type']) else: generated_schemas.append(generated_schema) if types: if len(types) == 1: (types,) = types else: types = sorted(types) generated_schemas = [{'type': types}] + generated_schemas if len(generated_schemas) == 1: (result_schema,) = generated_schemas elif generated_schemas: result_schema = {'anyOf': generated_schemas} else: result_schema = {} return result_schema
python
def to_schema(self): """ Convert the current schema to a `dict`. """ types = set() generated_schemas = [] for schema_generator in self._schema_generators: generated_schema = schema_generator.to_schema() if len(generated_schema) == 1 and 'type' in generated_schema: types.add(generated_schema['type']) else: generated_schemas.append(generated_schema) if types: if len(types) == 1: (types,) = types else: types = sorted(types) generated_schemas = [{'type': types}] + generated_schemas if len(generated_schemas) == 1: (result_schema,) = generated_schemas elif generated_schemas: result_schema = {'anyOf': generated_schemas} else: result_schema = {} return result_schema
[ "def", "to_schema", "(", "self", ")", ":", "types", "=", "set", "(", ")", "generated_schemas", "=", "[", "]", "for", "schema_generator", "in", "self", ".", "_schema_generators", ":", "generated_schema", "=", "schema_generator", ".", "to_schema", "(", ")", "i...
Convert the current schema to a `dict`.
[ "Convert", "the", "current", "schema", "to", "a", "dict", "." ]
76552d23cf9202e8e7c262cb018eb3cb3df686b9
https://github.com/wolverdude/GenSON/blob/76552d23cf9202e8e7c262cb018eb3cb3df686b9/genson/schema/node.py#L55-L81
train
202,793
kennethreitz/flask-sslify
flask_sslify.py
SSLify.hsts_header
def hsts_header(self): """Returns the proper HSTS policy.""" hsts_policy = 'max-age={0}'.format(self.hsts_age) if self.hsts_include_subdomains: hsts_policy += '; includeSubDomains' return hsts_policy
python
def hsts_header(self): """Returns the proper HSTS policy.""" hsts_policy = 'max-age={0}'.format(self.hsts_age) if self.hsts_include_subdomains: hsts_policy += '; includeSubDomains' return hsts_policy
[ "def", "hsts_header", "(", "self", ")", ":", "hsts_policy", "=", "'max-age={0}'", ".", "format", "(", "self", ".", "hsts_age", ")", "if", "self", ".", "hsts_include_subdomains", ":", "hsts_policy", "+=", "'; includeSubDomains'", "return", "hsts_policy" ]
Returns the proper HSTS policy.
[ "Returns", "the", "proper", "HSTS", "policy", "." ]
425a1deb4a1a8f693319f4b97134196e0235848c
https://github.com/kennethreitz/flask-sslify/blob/425a1deb4a1a8f693319f4b97134196e0235848c/flask_sslify.py#L52-L59
train
202,794
kennethreitz/flask-sslify
flask_sslify.py
SSLify.skip
def skip(self): """Checks the skip list.""" # Should we skip? if self.skip_list and isinstance(self.skip_list, list): for skip in self.skip_list: if request.path.startswith('/{0}'.format(skip)): return True return False
python
def skip(self): """Checks the skip list.""" # Should we skip? if self.skip_list and isinstance(self.skip_list, list): for skip in self.skip_list: if request.path.startswith('/{0}'.format(skip)): return True return False
[ "def", "skip", "(", "self", ")", ":", "# Should we skip?", "if", "self", ".", "skip_list", "and", "isinstance", "(", "self", ".", "skip_list", ",", "list", ")", ":", "for", "skip", "in", "self", ".", "skip_list", ":", "if", "request", ".", "path", ".",...
Checks the skip list.
[ "Checks", "the", "skip", "list", "." ]
425a1deb4a1a8f693319f4b97134196e0235848c
https://github.com/kennethreitz/flask-sslify/blob/425a1deb4a1a8f693319f4b97134196e0235848c/flask_sslify.py#L62-L69
train
202,795
kennethreitz/flask-sslify
flask_sslify.py
SSLify.redirect_to_ssl
def redirect_to_ssl(self): """Redirect incoming requests to HTTPS.""" # Should we redirect? criteria = [ request.is_secure, current_app.debug, current_app.testing, request.headers.get('X-Forwarded-Proto', 'http') == 'https' ] if not any(criteria) and not self.skip: if request.url.startswith('http://'): url = request.url.replace('http://', 'https://', 1) code = 302 if self.permanent: code = 301 r = redirect(url, code=code) return r
python
def redirect_to_ssl(self): """Redirect incoming requests to HTTPS.""" # Should we redirect? criteria = [ request.is_secure, current_app.debug, current_app.testing, request.headers.get('X-Forwarded-Proto', 'http') == 'https' ] if not any(criteria) and not self.skip: if request.url.startswith('http://'): url = request.url.replace('http://', 'https://', 1) code = 302 if self.permanent: code = 301 r = redirect(url, code=code) return r
[ "def", "redirect_to_ssl", "(", "self", ")", ":", "# Should we redirect?", "criteria", "=", "[", "request", ".", "is_secure", ",", "current_app", ".", "debug", ",", "current_app", ".", "testing", ",", "request", ".", "headers", ".", "get", "(", "'X-Forwarded-Pr...
Redirect incoming requests to HTTPS.
[ "Redirect", "incoming", "requests", "to", "HTTPS", "." ]
425a1deb4a1a8f693319f4b97134196e0235848c
https://github.com/kennethreitz/flask-sslify/blob/425a1deb4a1a8f693319f4b97134196e0235848c/flask_sslify.py#L71-L88
train
202,796
mclarkk/lifxlan
lifxlan/light.py
Light.set_hue
def set_hue(self, hue, duration=0, rapid=False): """ hue to set duration in ms""" color = self.get_color() color2 = (hue, color[1], color[2], color[3]) try: if rapid: self.fire_and_forget(LightSetColor, {"color": color2, "duration": duration}, num_repeats=1) else: self.req_with_ack(LightSetColor, {"color": color2, "duration": duration}) except WorkflowException as e: raise
python
def set_hue(self, hue, duration=0, rapid=False): """ hue to set duration in ms""" color = self.get_color() color2 = (hue, color[1], color[2], color[3]) try: if rapid: self.fire_and_forget(LightSetColor, {"color": color2, "duration": duration}, num_repeats=1) else: self.req_with_ack(LightSetColor, {"color": color2, "duration": duration}) except WorkflowException as e: raise
[ "def", "set_hue", "(", "self", ",", "hue", ",", "duration", "=", "0", ",", "rapid", "=", "False", ")", ":", "color", "=", "self", ".", "get_color", "(", ")", "color2", "=", "(", "hue", ",", "color", "[", "1", "]", ",", "color", "[", "2", "]", ...
hue to set duration in ms
[ "hue", "to", "set", "duration", "in", "ms" ]
ead0e3114d6aa2e5e77dab1191c13c16066c32b0
https://github.com/mclarkk/lifxlan/blob/ead0e3114d6aa2e5e77dab1191c13c16066c32b0/lifxlan/light.py#L97-L108
train
202,797
mclarkk/lifxlan
lifxlan/light.py
Light.set_saturation
def set_saturation(self, saturation, duration=0, rapid=False): """ saturation to set duration in ms""" color = self.get_color() color2 = (color[0], saturation, color[2], color[3]) try: if rapid: self.fire_and_forget(LightSetColor, {"color": color2, "duration": duration}, num_repeats=1) else: self.req_with_ack(LightSetColor, {"color": color2, "duration": duration}) except WorkflowException as e: raise
python
def set_saturation(self, saturation, duration=0, rapid=False): """ saturation to set duration in ms""" color = self.get_color() color2 = (color[0], saturation, color[2], color[3]) try: if rapid: self.fire_and_forget(LightSetColor, {"color": color2, "duration": duration}, num_repeats=1) else: self.req_with_ack(LightSetColor, {"color": color2, "duration": duration}) except WorkflowException as e: raise
[ "def", "set_saturation", "(", "self", ",", "saturation", ",", "duration", "=", "0", ",", "rapid", "=", "False", ")", ":", "color", "=", "self", ".", "get_color", "(", ")", "color2", "=", "(", "color", "[", "0", "]", ",", "saturation", ",", "color", ...
saturation to set duration in ms
[ "saturation", "to", "set", "duration", "in", "ms" ]
ead0e3114d6aa2e5e77dab1191c13c16066c32b0
https://github.com/mclarkk/lifxlan/blob/ead0e3114d6aa2e5e77dab1191c13c16066c32b0/lifxlan/light.py#L111-L122
train
202,798
mclarkk/lifxlan
lifxlan/light.py
Light.set_brightness
def set_brightness(self, brightness, duration=0, rapid=False): """ brightness to set duration in ms""" color = self.get_color() color2 = (color[0], color[1], brightness, color[3]) try: if rapid: self.fire_and_forget(LightSetColor, {"color": color2, "duration": duration}, num_repeats=1) else: self.req_with_ack(LightSetColor, {"color": color2, "duration": duration}) except WorkflowException as e: raise
python
def set_brightness(self, brightness, duration=0, rapid=False): """ brightness to set duration in ms""" color = self.get_color() color2 = (color[0], color[1], brightness, color[3]) try: if rapid: self.fire_and_forget(LightSetColor, {"color": color2, "duration": duration}, num_repeats=1) else: self.req_with_ack(LightSetColor, {"color": color2, "duration": duration}) except WorkflowException as e: raise
[ "def", "set_brightness", "(", "self", ",", "brightness", ",", "duration", "=", "0", ",", "rapid", "=", "False", ")", ":", "color", "=", "self", ".", "get_color", "(", ")", "color2", "=", "(", "color", "[", "0", "]", ",", "color", "[", "1", "]", "...
brightness to set duration in ms
[ "brightness", "to", "set", "duration", "in", "ms" ]
ead0e3114d6aa2e5e77dab1191c13c16066c32b0
https://github.com/mclarkk/lifxlan/blob/ead0e3114d6aa2e5e77dab1191c13c16066c32b0/lifxlan/light.py#L125-L136
train
202,799