repository_name stringclasses 316
values | func_path_in_repository stringlengths 6 223 | func_name stringlengths 1 134 | language stringclasses 1
value | func_code_string stringlengths 57 65.5k | func_documentation_string stringlengths 1 46.3k | split_name stringclasses 1
value | func_code_url stringlengths 91 315 | called_functions listlengths 1 156 ⌀ | enclosing_scope stringlengths 2 1.48M |
|---|---|---|---|---|---|---|---|---|---|
NickMonzillo/SmartCloud | SmartCloud/__init__.py | Cloud.directory_cloud | python | def directory_cloud(self,directory,max_text_size=72,min_text_size=12,expand_width=50,expand_height=50,max_count=100000):
'''Creates a word cloud using files from a directory.
The color of the words correspond to the amount of documents the word occurs in.'''
worddict = assign_fonts(tuplecount(re... | Creates a word cloud using files from a directory.
The color of the words correspond to the amount of documents the word occurs in. | train | https://github.com/NickMonzillo/SmartCloud/blob/481d1ef428427b452a8a787999c1d4a8868a3824/SmartCloud/__init__.py#L60-L85 | [
"def tuplecount(text):\n '''Changes a dictionary into a list of tuples.'''\n worddict = wordcount(text)\n countlist = []\n for key in worddict.keys():\n countlist.append((key,worddict[key]))\n countlist = list(reversed(sorted(countlist,key = lambda x: x[1])))\n return countlist\n",
"def d... | class Cloud(object):
def __init__(self,width=500,height=500):
pygame.init()
pygame.font.init()
self.width = width
self.height = height
self.cloud = pygame.Surface((width,height))
self.used_pos = []
def render_word(self,word,size,color):
'''Creates a surfa... |
NickMonzillo/SmartCloud | SmartCloud/__init__.py | Cloud.text_cloud | python | def text_cloud(self,text,max_text_size=72,min_text_size=12,expand_width=50,expand_height=50,max_count=100000):
'''Creates a word cloud using plain text.'''
worddict = assign_fonts(tuplecount(text),max_text_size,min_text_size,self.exclude_words)
sorted_worddict = list(reversed(sorted(worddict.key... | Creates a word cloud using plain text. | train | https://github.com/NickMonzillo/SmartCloud/blob/481d1ef428427b452a8a787999c1d4a8868a3824/SmartCloud/__init__.py#L87-L107 | [
"def tuplecount(text):\n '''Changes a dictionary into a list of tuples.'''\n worddict = wordcount(text)\n countlist = []\n for key in worddict.keys():\n countlist.append((key,worddict[key]))\n countlist = list(reversed(sorted(countlist,key = lambda x: x[1])))\n return countlist\n",
"def a... | class Cloud(object):
def __init__(self,width=500,height=500):
pygame.init()
pygame.font.init()
self.width = width
self.height = height
self.cloud = pygame.Surface((width,height))
self.used_pos = []
def render_word(self,word,size,color):
'''Creates a surfa... |
NickMonzillo/SmartCloud | SmartCloud/__init__.py | Cloud.display | python | def display(self):
'''Displays the word cloud to the screen.'''
pygame.init()
self.display = pygame.display.set_mode((self.width,self.height))
self.display.blit(self.cloud,(0,0))
pygame.display.update()
while True:
for event in pygame.event.get():
... | Displays the word cloud to the screen. | train | https://github.com/NickMonzillo/SmartCloud/blob/481d1ef428427b452a8a787999c1d4a8868a3824/SmartCloud/__init__.py#L109-L119 | null | class Cloud(object):
def __init__(self,width=500,height=500):
pygame.init()
pygame.font.init()
self.width = width
self.height = height
self.cloud = pygame.Surface((width,height))
self.used_pos = []
def render_word(self,word,size,color):
'''Creates a surfa... |
NickMonzillo/SmartCloud | SmartCloud/utils.py | dir_freq | python | def dir_freq(directory):
'''Returns a list of tuples of (word,# of directories it occurs)'''
content = dir_list(directory)
i = 0
freqdict = {}
for filename in content:
filewords = eliminate_repeats(read_file(directory + '/' + filename))
for word in filewords:
if freqdict.... | Returns a list of tuples of (word,# of directories it occurs) | train | https://github.com/NickMonzillo/SmartCloud/blob/481d1ef428427b452a8a787999c1d4a8868a3824/SmartCloud/utils.py#L3-L19 | [
"def read_file(filename):\n '''Reads in a .txt file.'''\n with open(filename,'r') as f:\n content = f.read()\n return content\n",
"def dir_list(directory):\n '''Returns the list of all files in the directory.'''\n try:\n content = listdir(directory)\n return content\n except... | from os import listdir
from wordplay import eliminate_repeats, read_file
def dir_list(directory):
'''Returns the list of all files in the directory.'''
try:
content = listdir(directory)
return content
except WindowsError as winErr:
print("Directory error: " + str((winErr)))
def re... |
NickMonzillo/SmartCloud | SmartCloud/utils.py | dir_list | python | def dir_list(directory):
'''Returns the list of all files in the directory.'''
try:
content = listdir(directory)
return content
except WindowsError as winErr:
print("Directory error: " + str((winErr))) | Returns the list of all files in the directory. | train | https://github.com/NickMonzillo/SmartCloud/blob/481d1ef428427b452a8a787999c1d4a8868a3824/SmartCloud/utils.py#L21-L27 | null | from os import listdir
from wordplay import eliminate_repeats, read_file
def dir_freq(directory):
'''Returns a list of tuples of (word,# of directories it occurs)'''
content = dir_list(directory)
i = 0
freqdict = {}
for filename in content:
filewords = eliminate_repeats(read_file(directory +... |
NickMonzillo/SmartCloud | SmartCloud/utils.py | read_dir | python | def read_dir(directory):
'''Returns the text of all files in a directory.'''
content = dir_list(directory)
text = ''
for filename in content:
text += read_file(directory + '/' + filename)
text += ' '
return text | Returns the text of all files in a directory. | train | https://github.com/NickMonzillo/SmartCloud/blob/481d1ef428427b452a8a787999c1d4a8868a3824/SmartCloud/utils.py#L29-L36 | [
"def read_file(filename):\n '''Reads in a .txt file.'''\n with open(filename,'r') as f:\n content = f.read()\n return content\n",
"def dir_list(directory):\n '''Returns the list of all files in the directory.'''\n try:\n content = listdir(directory)\n return content\n except... | from os import listdir
from wordplay import eliminate_repeats, read_file
def dir_freq(directory):
'''Returns a list of tuples of (word,# of directories it occurs)'''
content = dir_list(directory)
i = 0
freqdict = {}
for filename in content:
filewords = eliminate_repeats(read_file(directory +... |
NickMonzillo/SmartCloud | SmartCloud/utils.py | assign_colors | python | def assign_colors(dir_counts):
'''Defines the color of a word in the cloud.
Counts is a list of tuples in the form (word,occurences)
The more files a word occurs in, the more red it appears in the cloud.'''
frequencies = map(lambda x: x[1],dir_counts)
words = map(lambda x: x[0],dir_counts)
maxoc... | Defines the color of a word in the cloud.
Counts is a list of tuples in the form (word,occurences)
The more files a word occurs in, the more red it appears in the cloud. | train | https://github.com/NickMonzillo/SmartCloud/blob/481d1ef428427b452a8a787999c1d4a8868a3824/SmartCloud/utils.py#L38-L48 | null | from os import listdir
from wordplay import eliminate_repeats, read_file
def dir_freq(directory):
'''Returns a list of tuples of (word,# of directories it occurs)'''
content = dir_list(directory)
i = 0
freqdict = {}
for filename in content:
filewords = eliminate_repeats(read_file(directory +... |
NickMonzillo/SmartCloud | SmartCloud/utils.py | colorize | python | def colorize(occurence,maxoccurence,minoccurence):
'''A formula for determining colors.'''
if occurence == maxoccurence:
color = (255,0,0)
elif occurence == minoccurence:
color = (0,0,255)
else:
color = (int((float(occurence)/maxoccurence*255)),0,int(float(minoccurence)/occurence... | A formula for determining colors. | train | https://github.com/NickMonzillo/SmartCloud/blob/481d1ef428427b452a8a787999c1d4a8868a3824/SmartCloud/utils.py#L50-L58 | null | from os import listdir
from wordplay import eliminate_repeats, read_file
def dir_freq(directory):
'''Returns a list of tuples of (word,# of directories it occurs)'''
content = dir_list(directory)
i = 0
freqdict = {}
for filename in content:
filewords = eliminate_repeats(read_file(directory +... |
NickMonzillo/SmartCloud | SmartCloud/utils.py | assign_fonts | python | def assign_fonts(counts,maxsize,minsize,exclude_words):
'''Defines the font size of a word in the cloud.
Counts is a list of tuples in the form (word,count)'''
valid_counts = []
if exclude_words:
for i in counts:
if i[1] != 1:
valid_counts.append(i)
else:
... | Defines the font size of a word in the cloud.
Counts is a list of tuples in the form (word,count) | train | https://github.com/NickMonzillo/SmartCloud/blob/481d1ef428427b452a8a787999c1d4a8868a3824/SmartCloud/utils.py#L60-L75 | null | from os import listdir
from wordplay import eliminate_repeats, read_file
def dir_freq(directory):
'''Returns a list of tuples of (word,# of directories it occurs)'''
content = dir_list(directory)
i = 0
freqdict = {}
for filename in content:
filewords = eliminate_repeats(read_file(directory +... |
NickMonzillo/SmartCloud | SmartCloud/utils.py | fontsize | python | def fontsize(count,maxsize,minsize,maxcount):
'''A formula for determining font sizes.'''
size = int(maxsize - (maxsize)*((float(maxcount-count)/maxcount)))
if size < minsize:
size = minsize
return size | A formula for determining font sizes. | train | https://github.com/NickMonzillo/SmartCloud/blob/481d1ef428427b452a8a787999c1d4a8868a3824/SmartCloud/utils.py#L77-L82 | null | from os import listdir
from wordplay import eliminate_repeats, read_file
def dir_freq(directory):
'''Returns a list of tuples of (word,# of directories it occurs)'''
content = dir_list(directory)
i = 0
freqdict = {}
for filename in content:
filewords = eliminate_repeats(read_file(directory +... |
ONSdigital/sdc-rabbit | sdc/rabbit/publishers.py | Publisher._connect | python | def _connect(self):
logger.info("Connecting to rabbit")
for url in self._urls:
try:
self._connection = pika.BlockingConnection(pika.URLParameters(url))
self._channel = self._connection.channel()
self._declare()
if self._confirm_... | Connect to a RabbitMQ instance
:returns: Boolean corresponding to success of connection
:rtype: bool | train | https://github.com/ONSdigital/sdc-rabbit/blob/985adfdb09cf1b263a1f311438baeb42cbcb503a/sdc/rabbit/publishers.py#L38-L65 | [
"def _declare(self):\n raise NotImplementedError('_declare not implemented')\n",
"def _declare(self):\n self._channel.exchange_declare(exchange=self._exchange,\n exchange_type=self._exchange_type,\n durable=self._durable_exchange,\n ... | class Publisher(object):
"""Base class for publishers to RabbitMQ."""
def __init__(self, urls, **kwargs):
"""Create a new instance of a Publisher class
:param urls: List of RabbitMQ cluster URLs
:param confirm_delivery: Delivery confirmations toggle
:param **kwargs: Custom key/... |
ONSdigital/sdc-rabbit | sdc/rabbit/publishers.py | Publisher._disconnect | python | def _disconnect(self):
try:
self._connection.close()
logger.debug("Disconnected from rabbit")
except Exception:
logger.exception("Unable to close connection") | Cleanly close a RabbitMQ connection.
:returns: None | train | https://github.com/ONSdigital/sdc-rabbit/blob/985adfdb09cf1b263a1f311438baeb42cbcb503a/sdc/rabbit/publishers.py#L67-L78 | null | class Publisher(object):
"""Base class for publishers to RabbitMQ."""
def __init__(self, urls, **kwargs):
"""Create a new instance of a Publisher class
:param urls: List of RabbitMQ cluster URLs
:param confirm_delivery: Delivery confirmations toggle
:param **kwargs: Custom key/... |
ONSdigital/sdc-rabbit | sdc/rabbit/publishers.py | Publisher.publish_message | python | def publish_message(self, message, content_type=None, headers=None, mandatory=False, immediate=False):
logger.debug("Publishing message")
try:
self._connect()
return self._do_publish(mandatory=mandatory,
immediate=immediate,
... | Publish a response message to a RabbitMQ instance.
:param message: Response message
:param content_type: Pika BasicProperties content_type value
:param headers: Message header properties
:param mandatory: The mandatory flag
:param immediate: The immediate flag
:returns:... | train | https://github.com/ONSdigital/sdc-rabbit/blob/985adfdb09cf1b263a1f311438baeb42cbcb503a/sdc/rabbit/publishers.py#L83-L120 | [
"def _connect(self):\n \"\"\"\n Connect to a RabbitMQ instance\n\n :returns: Boolean corresponding to success of connection\n :rtype: bool\n\n \"\"\"\n logger.info(\"Connecting to rabbit\")\n for url in self._urls:\n try:\n self._connection = pika.BlockingConnection(pika.URLPa... | class Publisher(object):
"""Base class for publishers to RabbitMQ."""
def __init__(self, urls, **kwargs):
"""Create a new instance of a Publisher class
:param urls: List of RabbitMQ cluster URLs
:param confirm_delivery: Delivery confirmations toggle
:param **kwargs: Custom key/... |
ONSdigital/sdc-rabbit | sdc/rabbit/consumers.py | AsyncConsumer.connect | python | def connect(self):
count = 1
no_of_servers = len(self._rabbit_urls)
while True:
server_choice = (count % no_of_servers) - 1
self._url = self._rabbit_urls[server_choice]
try:
logger.info('Connecting', attempt=count)
return pi... | This method connects to RabbitMQ using a SelectConnection object,
returning the connection handle.
When the connection is established, the on_connection_open method
will be invoked by pika.
:rtype: pika.SelectConnection | train | https://github.com/ONSdigital/sdc-rabbit/blob/985adfdb09cf1b263a1f311438baeb42cbcb503a/sdc/rabbit/consumers.py#L58-L88 | null | class AsyncConsumer:
"""This is an example consumer that will handle unexpected interactions
with RabbitMQ such as channel and connection closures.
If RabbitMQ closes the connection, it will reopen it. You should
look at the output, as there are limited reasons why the connection may
be closed, whi... |
ONSdigital/sdc-rabbit | sdc/rabbit/consumers.py | AsyncConsumer.on_channel_open | python | def on_channel_open(self, channel):
logger.info('Channel opened', channel=channel)
self._channel = channel
self.add_on_channel_close_callback()
self.setup_exchange(self._exchange) | This method is invoked by pika when the channel has been opened.
The channel object is passed in so we can make use of it.
Since the channel is now open, we'll declare the exchange to use.
:param pika.channel.Channel channel: The channel object | train | https://github.com/ONSdigital/sdc-rabbit/blob/985adfdb09cf1b263a1f311438baeb42cbcb503a/sdc/rabbit/consumers.py#L172-L184 | [
"def add_on_channel_close_callback(self):\n \"\"\"This method tells pika to call the on_channel_closed method if\n RabbitMQ unexpectedly closes the channel.\n\n \"\"\"\n logger.info('Adding channel close callback')\n self._channel.add_on_close_callback(self.on_channel_closed)\n",
"def setup_exchang... | class AsyncConsumer:
"""This is an example consumer that will handle unexpected interactions
with RabbitMQ such as channel and connection closures.
If RabbitMQ closes the connection, it will reopen it. You should
look at the output, as there are limited reasons why the connection may
be closed, whi... |
ONSdigital/sdc-rabbit | sdc/rabbit/consumers.py | AsyncConsumer.setup_exchange | python | def setup_exchange(self, exchange_name):
logger.info('Declaring exchange', name=exchange_name)
self._channel.exchange_declare(self.on_exchange_declareok,
exchange_name,
self._exchange_type) | Setup the exchange on RabbitMQ by invoking the Exchange.Declare RPC
command. When it is complete, the on_exchange_declareok method will
be invoked by pika.
:param str|unicode exchange_name: The name of the exchange to declare | train | https://github.com/ONSdigital/sdc-rabbit/blob/985adfdb09cf1b263a1f311438baeb42cbcb503a/sdc/rabbit/consumers.py#L186-L197 | null | class AsyncConsumer:
"""This is an example consumer that will handle unexpected interactions
with RabbitMQ such as channel and connection closures.
If RabbitMQ closes the connection, it will reopen it. You should
look at the output, as there are limited reasons why the connection may
be closed, whi... |
ONSdigital/sdc-rabbit | sdc/rabbit/consumers.py | AsyncConsumer.setup_queue | python | def setup_queue(self, queue_name):
logger.info('Declaring queue', name=queue_name)
self._channel.queue_declare(
self.on_queue_declareok, queue_name, durable=self._durable_queue
) | Setup the queue on RabbitMQ by invoking the Queue.Declare RPC
command. When it is complete, the on_queue_declareok method will
be invoked by pika.
:param str|unicode queue_name: The name of the queue to declare. | train | https://github.com/ONSdigital/sdc-rabbit/blob/985adfdb09cf1b263a1f311438baeb42cbcb503a/sdc/rabbit/consumers.py#L209-L220 | null | class AsyncConsumer:
"""This is an example consumer that will handle unexpected interactions
with RabbitMQ such as channel and connection closures.
If RabbitMQ closes the connection, it will reopen it. You should
look at the output, as there are limited reasons why the connection may
be closed, whi... |
ONSdigital/sdc-rabbit | sdc/rabbit/consumers.py | AsyncConsumer.on_queue_declareok | python | def on_queue_declareok(self, method_frame):
logger.info('Binding to rabbit', exchange=self._exchange, queue=self._queue)
self._channel.queue_bind(self.on_bindok, self._queue, self._exchange) | Method invoked by pika when the Queue.Declare RPC call made in
setup_queue has completed. In this method we will bind the queue
and exchange together with the routing key by issuing the Queue.Bind
RPC command. When this command is complete, the on_bindok method will
be invoked by pika.
... | train | https://github.com/ONSdigital/sdc-rabbit/blob/985adfdb09cf1b263a1f311438baeb42cbcb503a/sdc/rabbit/consumers.py#L222-L233 | null | class AsyncConsumer:
"""This is an example consumer that will handle unexpected interactions
with RabbitMQ such as channel and connection closures.
If RabbitMQ closes the connection, it will reopen it. You should
look at the output, as there are limited reasons why the connection may
be closed, whi... |
ONSdigital/sdc-rabbit | sdc/rabbit/consumers.py | AsyncConsumer.on_consumer_cancelled | python | def on_consumer_cancelled(self, method_frame):
msg = 'Consumer was cancelled remotely, shutting down: {0!r}'
logger.info(msg.format(method_frame))
if self._channel:
self._channel.close() | Invoked by pika when RabbitMQ sends a Basic.Cancel for a consumer
receiving messages.
:param pika.frame.Method method_frame: The Basic.Cancel frame | train | https://github.com/ONSdigital/sdc-rabbit/blob/985adfdb09cf1b263a1f311438baeb42cbcb503a/sdc/rabbit/consumers.py#L244-L254 | null | class AsyncConsumer:
"""This is an example consumer that will handle unexpected interactions
with RabbitMQ such as channel and connection closures.
If RabbitMQ closes the connection, it will reopen it. You should
look at the output, as there are limited reasons why the connection may
be closed, whi... |
ONSdigital/sdc-rabbit | sdc/rabbit/consumers.py | AsyncConsumer.acknowledge_message | python | def acknowledge_message(self, delivery_tag, **kwargs):
logger.info('Acknowledging message', delivery_tag=delivery_tag, **kwargs)
self._channel.basic_ack(delivery_tag) | Acknowledge the message delivery from RabbitMQ by sending a
Basic.Ack RPC method for the delivery tag.
:param int delivery_tag: The delivery tag from the Basic.Deliver frame | train | https://github.com/ONSdigital/sdc-rabbit/blob/985adfdb09cf1b263a1f311438baeb42cbcb503a/sdc/rabbit/consumers.py#L256-L264 | null | class AsyncConsumer:
"""This is an example consumer that will handle unexpected interactions
with RabbitMQ such as channel and connection closures.
If RabbitMQ closes the connection, it will reopen it. You should
look at the output, as there are limited reasons why the connection may
be closed, whi... |
ONSdigital/sdc-rabbit | sdc/rabbit/consumers.py | AsyncConsumer.nack_message | python | def nack_message(self, delivery_tag, **kwargs):
logger.info('Nacking message', delivery_tag=delivery_tag, **kwargs)
self._channel.basic_nack(delivery_tag) | Negative acknowledge a message
:param int delivery_tag: The deliver tag from the Basic.Deliver frame | train | https://github.com/ONSdigital/sdc-rabbit/blob/985adfdb09cf1b263a1f311438baeb42cbcb503a/sdc/rabbit/consumers.py#L266-L273 | null | class AsyncConsumer:
"""This is an example consumer that will handle unexpected interactions
with RabbitMQ such as channel and connection closures.
If RabbitMQ closes the connection, it will reopen it. You should
look at the output, as there are limited reasons why the connection may
be closed, whi... |
ONSdigital/sdc-rabbit | sdc/rabbit/consumers.py | AsyncConsumer.reject_message | python | def reject_message(self, delivery_tag, requeue=False, **kwargs):
logger.info('Rejecting message', delivery_tag=delivery_tag, **kwargs)
self._channel.basic_reject(delivery_tag, requeue=requeue) | Reject the message delivery from RabbitMQ by sending a
Basic.Reject RPC method for the delivery tag.
:param int delivery_tag: The delivery tag from the Basic.Deliver frame | train | https://github.com/ONSdigital/sdc-rabbit/blob/985adfdb09cf1b263a1f311438baeb42cbcb503a/sdc/rabbit/consumers.py#L275-L282 | null | class AsyncConsumer:
"""This is an example consumer that will handle unexpected interactions
with RabbitMQ such as channel and connection closures.
If RabbitMQ closes the connection, it will reopen it. You should
look at the output, as there are limited reasons why the connection may
be closed, whi... |
ONSdigital/sdc-rabbit | sdc/rabbit/consumers.py | AsyncConsumer.on_message | python | def on_message(self, unused_channel, basic_deliver, properties, body):
logger.info(
'Received message',
delivery_tag=basic_deliver.delivery_tag,
app_id=properties.app_id,
msg=body,
)
self.acknowledge_message(basic_deliver.delivery_tag) | Invoked by pika when a message is delivered from RabbitMQ. The
channel is passed for your convenience. The basic_deliver object that
is passed in carries the exchange, routing key, delivery tag and
a redelivered flag for the message. The properties passed in is an
instance of BasicProper... | train | https://github.com/ONSdigital/sdc-rabbit/blob/985adfdb09cf1b263a1f311438baeb42cbcb503a/sdc/rabbit/consumers.py#L284-L304 | [
"def acknowledge_message(self, delivery_tag, **kwargs):\n \"\"\"Acknowledge the message delivery from RabbitMQ by sending a\n Basic.Ack RPC method for the delivery tag.\n\n :param int delivery_tag: The delivery tag from the Basic.Deliver frame\n\n \"\"\"\n logger.info('Acknowledging message', deliver... | class AsyncConsumer:
"""This is an example consumer that will handle unexpected interactions
with RabbitMQ such as channel and connection closures.
If RabbitMQ closes the connection, it will reopen it. You should
look at the output, as there are limited reasons why the connection may
be closed, whi... |
ONSdigital/sdc-rabbit | sdc/rabbit/consumers.py | AsyncConsumer.stop_consuming | python | def stop_consuming(self):
if self._channel:
logger.info('Sending a Basic.Cancel RPC command to RabbitMQ')
self._channel.basic_cancel(self.on_cancelok, self._consumer_tag) | Tell RabbitMQ that you would like to stop consuming by sending the
Basic.Cancel RPC command. | train | https://github.com/ONSdigital/sdc-rabbit/blob/985adfdb09cf1b263a1f311438baeb42cbcb503a/sdc/rabbit/consumers.py#L318-L325 | null | class AsyncConsumer:
"""This is an example consumer that will handle unexpected interactions
with RabbitMQ such as channel and connection closures.
If RabbitMQ closes the connection, it will reopen it. You should
look at the output, as there are limited reasons why the connection may
be closed, whi... |
ONSdigital/sdc-rabbit | sdc/rabbit/consumers.py | AsyncConsumer.open_channel | python | def open_channel(self):
logger.info('Creating a new channel')
self._connection.channel(on_open_callback=self.on_channel_open) | Open a new channel with RabbitMQ by issuing the Channel.Open RPC
command. When RabbitMQ responds that the channel is open, the
on_channel_open callback will be invoked by pika. | train | https://github.com/ONSdigital/sdc-rabbit/blob/985adfdb09cf1b263a1f311438baeb42cbcb503a/sdc/rabbit/consumers.py#L362-L369 | null | class AsyncConsumer:
"""This is an example consumer that will handle unexpected interactions
with RabbitMQ such as channel and connection closures.
If RabbitMQ closes the connection, it will reopen it. You should
look at the output, as there are limited reasons why the connection may
be closed, whi... |
ONSdigital/sdc-rabbit | sdc/rabbit/consumers.py | AsyncConsumer.run | python | def run(self):
logger.debug('Running rabbit consumer')
self._connection = self.connect()
self._connection.ioloop.start() | Run the example consumer by connecting to RabbitMQ and then
starting the IOLoop to block and allow the SelectConnection to operate. | train | https://github.com/ONSdigital/sdc-rabbit/blob/985adfdb09cf1b263a1f311438baeb42cbcb503a/sdc/rabbit/consumers.py#L371-L378 | [
"def connect(self):\n \"\"\"This method connects to RabbitMQ using a SelectConnection object,\n returning the connection handle.\n\n When the connection is established, the on_connection_open method\n will be invoked by pika.\n\n :rtype: pika.SelectConnection\n\n \"\"\"\n\n count = 1\n no_of... | class AsyncConsumer:
"""This is an example consumer that will handle unexpected interactions
with RabbitMQ such as channel and connection closures.
If RabbitMQ closes the connection, it will reopen it. You should
look at the output, as there are limited reasons why the connection may
be closed, whi... |
ONSdigital/sdc-rabbit | sdc/rabbit/consumers.py | AsyncConsumer.stop | python | def stop(self):
logger.info('Stopping')
self._closing = True
self.stop_consuming()
logger.info('Stopped') | Cleanly shutdown the connection to RabbitMQ by stopping the consumer
with RabbitMQ. When RabbitMQ confirms the cancellation, on_cancelok
will be invoked by pika, which will then closing the channel and
connection. The IOLoop is started again because this method is invoked
when CTRL-C is ... | train | https://github.com/ONSdigital/sdc-rabbit/blob/985adfdb09cf1b263a1f311438baeb42cbcb503a/sdc/rabbit/consumers.py#L380-L394 | [
"def stop_consuming(self):\n \"\"\"Tell RabbitMQ that you would like to stop consuming by sending the\n Basic.Cancel RPC command.\n\n \"\"\"\n if self._channel:\n logger.info('Sending a Basic.Cancel RPC command to RabbitMQ')\n self._channel.basic_cancel(self.on_cancelok, self._consumer_tag... | class AsyncConsumer:
"""This is an example consumer that will handle unexpected interactions
with RabbitMQ such as channel and connection closures.
If RabbitMQ closes the connection, it will reopen it. You should
look at the output, as there are limited reasons why the connection may
be closed, whi... |
ONSdigital/sdc-rabbit | sdc/rabbit/consumers.py | MessageConsumer.tx_id | python | def tx_id(properties):
tx_id = properties.headers['tx_id']
logger.info("Retrieved tx_id from message properties: tx_id={}".format(tx_id))
return tx_id | Gets the tx_id for a message from a rabbit queue, using the
message properties. Will raise KeyError if tx_id is missing from message
headers.
: param properties: Message properties
: returns: tx_id of survey response
: rtype: str | train | https://github.com/ONSdigital/sdc-rabbit/blob/985adfdb09cf1b263a1f311438baeb42cbcb503a/sdc/rabbit/consumers.py#L444-L457 | null | class MessageConsumer(TornadoConsumer):
"""This is a queue consumer that handles messages from RabbitMQ message queues.
On receipt of a message it takes a number of params from the message
properties, processes the message, and (if successful) positively
acknowledges the publishing queue.
If a mes... |
ONSdigital/sdc-rabbit | sdc/rabbit/consumers.py | MessageConsumer.on_message | python | def on_message(self, unused_channel, basic_deliver, properties, body):
if self.check_tx_id:
try:
tx_id = self.tx_id(properties)
logger.info('Received message',
queue=self._queue,
delivery_tag=basic_deliver.deliv... | Called on receipt of a message from a queue.
Processes the message using the self._process method or function and positively
acknowledges the queue if successful. If processing is not succesful,
the message can either be rejected, quarantined or negatively acknowledged,
depending on the... | train | https://github.com/ONSdigital/sdc-rabbit/blob/985adfdb09cf1b263a1f311438baeb42cbcb503a/sdc/rabbit/consumers.py#L500-L580 | [
"def acknowledge_message(self, delivery_tag, **kwargs):\n \"\"\"Acknowledge the message delivery from RabbitMQ by sending a\n Basic.Ack RPC method for the delivery tag.\n\n :param int delivery_tag: The delivery tag from the Basic.Deliver frame\n\n \"\"\"\n logger.info('Acknowledging message', deliver... | class MessageConsumer(TornadoConsumer):
"""This is a queue consumer that handles messages from RabbitMQ message queues.
On receipt of a message it takes a number of params from the message
properties, processes the message, and (if successful) positively
acknowledges the publishing queue.
If a mes... |
erikvw/django-collect-offline-files | django_collect_offline_files/file_queues/file_queue_handlers.py | RegexFileQueueHandlerIncoming.process | python | def process(self, event):
logger.info(f"{self}: put {event.src_path}")
self.queue.put(os.path.basename(event.src_path)) | Put and process tasks in queue. | train | https://github.com/erikvw/django-collect-offline-files/blob/78f61c823ea3926eb88206b019b5dca3c36017da/django_collect_offline_files/file_queues/file_queue_handlers.py#L26-L30 | null | class RegexFileQueueHandlerIncoming(RegexMatchingEventHandler):
def __init__(self, queue=None, regexes=None, **kwargs):
super().__init__(regexes=regexes)
self.queue = queue
def __repr__(self, queue=None, regexes=None, **kwargs):
return f"{self.__class__.__name__}({self.queue})"
def... |
erikvw/django-collect-offline-files | django_collect_offline_files/confirmation.py | Confirmation.confirm | python | def confirm(self, batch_id=None, filename=None):
if batch_id or filename:
export_history = self.history_model.objects.using(self.using).filter(
Q(batch_id=batch_id) | Q(filename=filename),
sent=True,
confirmation_code__isnull=True,
)
... | Flags the batch as confirmed by updating
confirmation_datetime on the history model for this batch. | train | https://github.com/erikvw/django-collect-offline-files/blob/78f61c823ea3926eb88206b019b5dca3c36017da/django_collect_offline_files/confirmation.py#L24-L48 | null | class Confirmation:
"""A class to manage confirmation of sent / transferred transaction files.
"""
def __init__(self, history_model=None, using=None, **kwargs):
self.history_model = history_model
self.using = using
|
erikvw/django-collect-offline-files | django_collect_offline_files/file_queues/base_file_queue.py | BaseFileQueue.reload | python | def reload(self, regexes=None, **kwargs):
combined = re.compile("(" + ")|(".join(regexes) + ")", re.I)
pending_files = os.listdir(self.src_path) or []
pending_files.sort()
for filename in pending_files:
if re.match(combined, filename):
self.put(os.path.join(se... | Reloads /path/to/filenames into the queue
that match the regexes. | train | https://github.com/erikvw/django-collect-offline-files/blob/78f61c823ea3926eb88206b019b5dca3c36017da/django_collect_offline_files/file_queues/base_file_queue.py#L34-L43 | null | class BaseFileQueue(Queue):
file_archiver_cls = FileArchiver
def __init__(self, src_path=None, dst_path=None, **kwargs):
super().__init__(maxsize=kwargs.get("maxsize", 0))
self.src_path = src_path
self.dst_path = dst_path
try:
self.file_archiver = self.file_archiver... |
erikvw/django-collect-offline-files | django_collect_offline_files/transaction/transaction_file_sender.py | TransactionFileSender.send | python | def send(self, filenames=None):
try:
with self.ssh_client.connect() as ssh_conn:
with self.sftp_client.connect(ssh_conn) as sftp_conn:
for filename in filenames:
sftp_conn.copy(filename=filename)
self.archive(filenam... | Sends the file to the remote host and archives
the sent file locally. | train | https://github.com/erikvw/django-collect-offline-files/blob/78f61c823ea3926eb88206b019b5dca3c36017da/django_collect_offline_files/transaction/transaction_file_sender.py#L39-L55 | [
"def update_history(self, filename=None):\n try:\n obj = self.history_model.objects.using(self.using).get(filename=filename)\n except self.history_model.DoesNotExist as e:\n raise TransactionFileSenderError(\n f\"History does not exist for file '{filename}'. Got {e}\"\n ) from ... | class TransactionFileSender:
def __init__(
self,
remote_host=None,
username=None,
src_path=None,
dst_tmp=None,
dst_path=None,
archive_path=None,
history_model=None,
using=None,
update_history_model=None,
**kwargs,
):
... |
erikvw/django-collect-offline-files | django_collect_offline_files/sftp_client.py | SFTPClient.copy | python | def copy(self, filename=None):
dst = os.path.join(self.dst_path, filename)
src = os.path.join(self.src_path, filename)
dst_tmp = os.path.join(self.dst_tmp, filename)
self.put(src=src, dst=dst_tmp, callback=self.update_progress, confirm=True)
self.rename(src=dst_tmp, dst=dst) | Puts on destination as a temp file, renames on
the destination. | train | https://github.com/erikvw/django-collect-offline-files/blob/78f61c823ea3926eb88206b019b5dca3c36017da/django_collect_offline_files/sftp_client.py#L38-L46 | null | class SFTPClient(ClosingContextManager):
"""Wraps open_sftp with folder defaults for copy.
Copy is two steps; put then rename.
"""
def __init__(
self, src_path=None, dst_path=None, dst_tmp=None, verbose=None, **kwargs
):
self.src_path = src_path
self.dst_tmp = dst_tmp
... |
erikvw/django-collect-offline-files | django_collect_offline_files/file_queues/process_queue.py | process_queue | python | def process_queue(queue=None, **kwargs):
while True:
item = queue.get()
if item is None:
queue.task_done()
logger.info(f"{queue}: exiting process queue.")
break
filename = os.path.basename(item)
try:
queue.next_task(item, **kwargs)
... | Loops and waits on queue calling queue's `next_task` method.
If an exception occurs, log the error, log the exception,
and break. | train | https://github.com/erikvw/django-collect-offline-files/blob/78f61c823ea3926eb88206b019b5dca3c36017da/django_collect_offline_files/file_queues/process_queue.py#L11-L39 | [
"def next_task(self, item, raise_exceptions=None, **kwargs):\n \"\"\"Deserializes all transactions for this batch and\n archives the file.\n \"\"\"\n filename = os.path.basename(item)\n batch = self.get_batch(filename)\n tx_deserializer = self.tx_deserializer_cls(\n allow_self=self.allow_se... | import os
import logging
import sys
from django.core.management.color import color_style
logger = logging.getLogger("django_collect_offline_files")
style = color_style()
|
erikvw/django-collect-offline-files | django_collect_offline_files/file_queues/incoming_transactions_file_queue.py | IncomingTransactionsFileQueue.next_task | python | def next_task(self, item, **kwargs):
filename = os.path.basename(item)
try:
self.tx_importer.import_batch(filename=filename)
except TransactionImporterError as e:
raise TransactionsFileQueueError(e) from e
else:
self.archive(filename) | Calls import_batch for the next filename in the queue
and "archives" the file.
The archive folder is typically the folder for the deserializer queue. | train | https://github.com/erikvw/django-collect-offline-files/blob/78f61c823ea3926eb88206b019b5dca3c36017da/django_collect_offline_files/file_queues/incoming_transactions_file_queue.py#L17-L29 | [
"def archive(self, filename=None):\n try:\n self.file_archiver.archive(filename)\n except FileArchiverError as e:\n raise TransactionsFileQueueError(e) from e\n"
] | class IncomingTransactionsFileQueue(BaseFileQueue):
tx_importer_cls = TransactionImporter
def __init__(self, src_path=None, raise_exceptions=None, **kwargs):
super().__init__(src_path=src_path, **kwargs)
self.tx_importer = self.tx_importer_cls(import_path=src_path, **kwargs)
self.raise... |
erikvw/django-collect-offline-files | django_collect_offline_files/transaction/transaction_importer.py | JSONLoadFile.read | python | def read(self):
p = os.path.join(self.path, self.name)
try:
with open(p) as f:
json_text = f.read()
except FileNotFoundError as e:
raise JSONFileError(e) from e
try:
json.loads(json_text)
except (json.JSONDecodeError, TypeError)... | Returns the file contents as validated JSON text. | train | https://github.com/erikvw/django-collect-offline-files/blob/78f61c823ea3926eb88206b019b5dca3c36017da/django_collect_offline_files/transaction/transaction_importer.py#L62-L75 | null | class JSONLoadFile:
def __init__(self, name=None, path=None, **kwargs):
self._deserialized_objects = None
self.deserialize = deserialize
self.name = name
self.path = path
def __str__(self):
return os.path.join(self.path, self.name)
def __repr__(self):
return... |
erikvw/django-collect-offline-files | django_collect_offline_files/transaction/transaction_importer.py | JSONLoadFile.deserialized_objects | python | def deserialized_objects(self):
if not self._deserialized_objects:
json_text = self.read()
self._deserialized_objects = self.deserialize(json_text=json_text)
return self._deserialized_objects | Returns a generator of deserialized objects. | train | https://github.com/erikvw/django-collect-offline-files/blob/78f61c823ea3926eb88206b019b5dca3c36017da/django_collect_offline_files/transaction/transaction_importer.py#L78-L84 | [
"def read(self):\n \"\"\"Returns the file contents as validated JSON text.\n \"\"\"\n p = os.path.join(self.path, self.name)\n try:\n with open(p) as f:\n json_text = f.read()\n except FileNotFoundError as e:\n raise JSONFileError(e) from e\n try:\n json.loads(json_... | class JSONLoadFile:
def __init__(self, name=None, path=None, **kwargs):
self._deserialized_objects = None
self.deserialize = deserialize
self.name = name
self.path = path
def __str__(self):
return os.path.join(self.path, self.name)
def __repr__(self):
return... |
erikvw/django-collect-offline-files | django_collect_offline_files/transaction/transaction_importer.py | BatchHistory.exists | python | def exists(self, batch_id=None):
try:
self.model.objects.get(batch_id=batch_id)
except self.model.DoesNotExist:
return False
return True | Returns True if batch_id exists in the history. | train | https://github.com/erikvw/django-collect-offline-files/blob/78f61c823ea3926eb88206b019b5dca3c36017da/django_collect_offline_files/transaction/transaction_importer.py#L91-L98 | null | class BatchHistory:
def __init__(self, model=None):
self.model = model or ImportedTransactionFileHistory
def close(self, batch_id):
obj = self.model.objects.get(batch_id=batch_id)
obj.consumed = True
obj.consumed_datetime = get_utcnow()
obj.save()
def update(
... |
erikvw/django-collect-offline-files | django_collect_offline_files/transaction/transaction_importer.py | BatchHistory.update | python | def update(
self,
filename=None,
batch_id=None,
prev_batch_id=None,
producer=None,
count=None,
):
# TODO: refactor model enforce unique batch_id
# TODO: refactor model to not allow NULLs
if not filename:
raise BatchHistoryError("Inv... | Creates an history model instance. | train | https://github.com/erikvw/django-collect-offline-files/blob/78f61c823ea3926eb88206b019b5dca3c36017da/django_collect_offline_files/transaction/transaction_importer.py#L106-L140 | [
"def exists(self, batch_id=None):\n \"\"\"Returns True if batch_id exists in the history.\n \"\"\"\n try:\n self.model.objects.get(batch_id=batch_id)\n except self.model.DoesNotExist:\n return False\n return True\n"
] | class BatchHistory:
def __init__(self, model=None):
self.model = model or ImportedTransactionFileHistory
def exists(self, batch_id=None):
"""Returns True if batch_id exists in the history.
"""
try:
self.model.objects.get(batch_id=batch_id)
except self.model.D... |
erikvw/django-collect-offline-files | django_collect_offline_files/transaction/transaction_importer.py | ImportBatch.populate | python | def populate(self, deserialized_txs=None, filename=None, retry=None):
if not deserialized_txs:
raise BatchError("Failed to populate batch. There are no objects to add.")
self.filename = filename
if not self.filename:
raise BatchError("Invalid filename. Got None")
... | Populates the batch with unsaved model instances
from a generator of deserialized objects. | train | https://github.com/erikvw/django-collect-offline-files/blob/78f61c823ea3926eb88206b019b5dca3c36017da/django_collect_offline_files/transaction/transaction_importer.py#L160-L179 | [
"def peek(self, deserialized_tx):\n \"\"\"Peeks into first tx and sets self attrs or raise.\n \"\"\"\n self.batch_id = deserialized_tx.object.batch_id\n self.prev_batch_id = deserialized_tx.object.prev_batch_id\n self.producer = deserialized_tx.object.producer\n if self.batch_history.exists(batch_... | class ImportBatch:
def __init__(self, **kwargs):
self._valid_sequence = None
self.filename = None
self.batch_id = None
self.prev_batch_id = None
self.producer = None
self.objects = []
self.batch_history = BatchHistory()
self.model = IncomingTransaction... |
erikvw/django-collect-offline-files | django_collect_offline_files/transaction/transaction_importer.py | ImportBatch.peek | python | def peek(self, deserialized_tx):
self.batch_id = deserialized_tx.object.batch_id
self.prev_batch_id = deserialized_tx.object.prev_batch_id
self.producer = deserialized_tx.object.producer
if self.batch_history.exists(batch_id=self.batch_id):
raise BatchAlreadyProcessed(
... | Peeks into first tx and sets self attrs or raise. | train | https://github.com/erikvw/django-collect-offline-files/blob/78f61c823ea3926eb88206b019b5dca3c36017da/django_collect_offline_files/transaction/transaction_importer.py#L181-L197 | null | class ImportBatch:
def __init__(self, **kwargs):
self._valid_sequence = None
self.filename = None
self.batch_id = None
self.prev_batch_id = None
self.producer = None
self.objects = []
self.batch_history = BatchHistory()
self.model = IncomingTransaction... |
erikvw/django-collect-offline-files | django_collect_offline_files/transaction/transaction_importer.py | ImportBatch.save | python | def save(self):
saved = 0
if not self.objects:
raise BatchError("Save failed. Batch is empty")
for deserialized_tx in self.objects:
try:
self.model.objects.get(pk=deserialized_tx.pk)
except self.model.DoesNotExist:
data = {}
... | Saves all model instances in the batch as model. | train | https://github.com/erikvw/django-collect-offline-files/blob/78f61c823ea3926eb88206b019b5dca3c36017da/django_collect_offline_files/transaction/transaction_importer.py#L199-L217 | null | class ImportBatch:
def __init__(self, **kwargs):
self._valid_sequence = None
self.filename = None
self.batch_id = None
self.prev_batch_id = None
self.producer = None
self.objects = []
self.batch_history = BatchHistory()
self.model = IncomingTransaction... |
erikvw/django-collect-offline-files | django_collect_offline_files/transaction/transaction_importer.py | TransactionImporter.import_batch | python | def import_batch(self, filename):
batch = self.batch_cls()
json_file = self.json_file_cls(name=filename, path=self.path)
try:
deserialized_txs = json_file.deserialized_objects
except JSONFileError as e:
raise TransactionImporterError(e) from e
try:
... | Imports the batch of outgoing transactions into
model IncomingTransaction. | train | https://github.com/erikvw/django-collect-offline-files/blob/78f61c823ea3926eb88206b019b5dca3c36017da/django_collect_offline_files/transaction/transaction_importer.py#L264-L284 | null | class TransactionImporter:
"""Imports transactions from a file as incoming transaction.
"""
batch_cls = ImportBatch
json_file_cls = JSONLoadFile
def __init__(self, import_path=None, **kwargs):
self.path = import_path
|
erikvw/django-collect-offline-files | django_collect_offline_files/file_queues/deserialize_transactions_file_queue.py | DeserializeTransactionsFileQueue.next_task | python | def next_task(self, item, raise_exceptions=None, **kwargs):
filename = os.path.basename(item)
batch = self.get_batch(filename)
tx_deserializer = self.tx_deserializer_cls(
allow_self=self.allow_self, override_role=self.override_role
)
try:
tx_deserializer.d... | Deserializes all transactions for this batch and
archives the file. | train | https://github.com/erikvw/django-collect-offline-files/blob/78f61c823ea3926eb88206b019b5dca3c36017da/django_collect_offline_files/file_queues/deserialize_transactions_file_queue.py#L25-L42 | [
"def archive(self, filename=None):\n try:\n self.file_archiver.archive(filename)\n except FileArchiverError as e:\n raise TransactionsFileQueueError(e) from e\n",
"def get_batch(self, filename=None):\n \"\"\"Returns a batch instance given the filename.\n \"\"\"\n try:\n history... | class DeserializeTransactionsFileQueue(BaseFileQueue):
batch_cls = TransactionImporterBatch
tx_deserializer_cls = TransactionDeserializer
def __init__(
self, history_model=None, allow_self=None, override_role=None, **kwargs
):
super().__init__(**kwargs)
self.history_model = his... |
erikvw/django-collect-offline-files | django_collect_offline_files/file_queues/deserialize_transactions_file_queue.py | DeserializeTransactionsFileQueue.get_batch | python | def get_batch(self, filename=None):
try:
history = self.history_model.objects.get(filename=filename)
except self.history_model.DoesNotExist as e:
raise TransactionsFileQueueError(
f"Batch history not found for '{filename}'."
) from e
if history... | Returns a batch instance given the filename. | train | https://github.com/erikvw/django-collect-offline-files/blob/78f61c823ea3926eb88206b019b5dca3c36017da/django_collect_offline_files/file_queues/deserialize_transactions_file_queue.py#L44-L60 | null | class DeserializeTransactionsFileQueue(BaseFileQueue):
batch_cls = TransactionImporterBatch
tx_deserializer_cls = TransactionDeserializer
def __init__(
self, history_model=None, allow_self=None, override_role=None, **kwargs
):
super().__init__(**kwargs)
self.history_model = his... |
erikvw/django-collect-offline-files | django_collect_offline_files/transaction/transaction_exporter.py | TransactionExporter.export_batch | python | def export_batch(self):
batch = self.batch_cls(
model=self.model, history_model=self.history_model, using=self.using
)
if batch.items:
try:
json_file = self.json_file_cls(batch=batch, path=self.path)
json_file.write()
except JSO... | Returns a batch instance after exporting a batch of txs. | train | https://github.com/erikvw/django-collect-offline-files/blob/78f61c823ea3926eb88206b019b5dca3c36017da/django_collect_offline_files/transaction/transaction_exporter.py#L179-L193 | null | class TransactionExporter:
"""Export pending OutgoingTransactions to a file in JSON format
and update the export `History` model.
"""
batch_cls = ExportBatch
json_file_cls = JSONDumpFile
model = OutgoingTransaction
history_model = ExportedTransactionFileHistory
def __init__(self, expo... |
erikvw/django-collect-offline-files | django_collect_offline_files/apps.py | AppConfig.make_required_folders | python | def make_required_folders(self):
for folder in [
self.pending_folder,
self.usb_incoming_folder,
self.outgoing_folder,
self.incoming_folder,
self.archive_folder,
self.tmp_folder,
self.log_folder,
]:
if not os.... | Makes all folders declared in the config if they
do not exist. | train | https://github.com/erikvw/django-collect-offline-files/blob/78f61c823ea3926eb88206b019b5dca3c36017da/django_collect_offline_files/apps.py#L31-L45 | null | class AppConfig(DjangoAppConfig):
name = "django_collect_offline_files"
verbose_name = "File support for data synchronization"
django_collect_offline_files_using = True
user = settings.DJANGO_COLLECT_OFFLINE_FILES_USER
remote_host = settings.DJANGO_COLLECT_OFFLINE_FILES_REMOTE_HOST
usb_volume =... |
GGiecold/Concurrent_AP | Concurrent_AP.py | chunk_generator | python | def chunk_generator(N, n):
chunk_size = get_chunk_size(N, n)
for start in range(0, N, chunk_size):
yield slice(start, min(start + chunk_size, N)) | Returns a generator of slice objects.
Parameters
----------
N : int
The size of one of the dimensions of a two-dimensional array.
n : int
The number of arrays of shape ('N', 'get_chunk_size(N, n)') that fit into
memory.
Returns
-------
Slice objects of... | train | https://github.com/GGiecold/Concurrent_AP/blob/d4cebe06268b5d520352a83cadb2f7520650460c/Concurrent_AP.py#L118-L139 | [
"def get_chunk_size(N, n):\n \"\"\"Given a two-dimensional array with a dimension of size 'N', \n determine the number of rows or columns that can fit into memory.\n\n Parameters\n ----------\n N : int\n The size of one of the dimensions of a two-dimensional array. \n\n n : int\n ... | #!/usr/bin/env python
# Concurrent_AP/Concurrent_AP.py
# Author: Gregory Giecold for the GC Yuan Lab
# Affiliation: Harvard University
# Contact: g.giecold@gmail.com, ggiecold@jimmy.harvard.edu
"""Concurrent_AP is a scalable and concurrent programming implementation
of Affinity Propagation clustering.
Affinity ... |
GGiecold/Concurrent_AP | Concurrent_AP.py | parse_options | python | def parse_options():
parser = optparse.OptionParser(
usage = "Usage: %prog [options] file_name\n\n"
"file_name denotes the path where the data to be "
"processed by affinity propagation clustering is stored"
)
parse... | Specify the command line options to parse.
Returns
-------
opts : optparse.Values instance
Contains the option values in its 'dict' member variable.
args[0] : string or file-handler
The name of the file storing the data-set submitted
for Affinity Propagation clustering. | train | https://github.com/GGiecold/Concurrent_AP/blob/d4cebe06268b5d520352a83cadb2f7520650460c/Concurrent_AP.py#L142-L229 | null | #!/usr/bin/env python
# Concurrent_AP/Concurrent_AP.py
# Author: Gregory Giecold for the GC Yuan Lab
# Affiliation: Harvard University
# Contact: g.giecold@gmail.com, ggiecold@jimmy.harvard.edu
"""Concurrent_AP is a scalable and concurrent programming implementation
of Affinity Propagation clustering.
Affinity ... |
GGiecold/Concurrent_AP | Concurrent_AP.py | check_HDF5_arrays | python | def check_HDF5_arrays(hdf5_file, N, convergence_iter):
Worker.hdf5_lock.acquire()
with tables.open_file(hdf5_file, 'r+') as fileh:
if not hasattr(fileh.root, 'aff_prop_group'):
fileh.create_group(fileh.root, "aff_prop_group")
atom = tables.Float32Atom()
filters = None
... | Check that the HDF5 data structure of file handle 'hdf5_file'
has all the required nodes organizing the various two-dimensional
arrays required for Affinity Propagation clustering
('Responsibility' matrix, 'Availability', etc.).
Parameters
----------
hdf5_file : string or fil... | train | https://github.com/GGiecold/Concurrent_AP/blob/d4cebe06268b5d520352a83cadb2f7520650460c/Concurrent_AP.py#L232-L276 | null | #!/usr/bin/env python
# Concurrent_AP/Concurrent_AP.py
# Author: Gregory Giecold for the GC Yuan Lab
# Affiliation: Harvard University
# Contact: g.giecold@gmail.com, ggiecold@jimmy.harvard.edu
"""Concurrent_AP is a scalable and concurrent programming implementation
of Affinity Propagation clustering.
Affinity ... |
GGiecold/Concurrent_AP | Concurrent_AP.py | get_sum | python | def get_sum(hdf5_file, path, array_out, out_lock, rows_slice):
Worker.hdf5_lock.acquire()
with tables.open_file(hdf5_file, 'r+') as fileh:
hdf5_array = fileh.get_node(path)
tmp = hdf5_array[rows_slice, ...]
Worker.hdf5_lock.release()
szum = np.sum(tmp, axis = 0)
... | Access an array at node 'path' of the 'hdf5_file', compute the sums
along a slice of rows specified by 'rows_slice' and add the resulting
vector to 'array_out'.
Parameters
----------
hdf5_file : string or file handle
The location of the HDF5 data structure containing the matri... | train | https://github.com/GGiecold/Concurrent_AP/blob/d4cebe06268b5d520352a83cadb2f7520650460c/Concurrent_AP.py#L433-L471 | null | #!/usr/bin/env python
# Concurrent_AP/Concurrent_AP.py
# Author: Gregory Giecold for the GC Yuan Lab
# Affiliation: Harvard University
# Contact: g.giecold@gmail.com, ggiecold@jimmy.harvard.edu
"""Concurrent_AP is a scalable and concurrent programming implementation
of Affinity Propagation clustering.
Affinity ... |
GGiecold/Concurrent_AP | Concurrent_AP.py | terminate_processes | python | def terminate_processes(pid_list):
for proc in psutil.process_iter():
if proc.pid in pid_list:
proc.terminate() | Terminate a list of processes by sending to each of them a SIGTERM signal,
pre-emptively checking if its PID might have been reused.
Parameters
----------
pid_list : list
A list of process identifiers identifying active processes. | train | https://github.com/GGiecold/Concurrent_AP/blob/d4cebe06268b5d520352a83cadb2f7520650460c/Concurrent_AP.py#L522-L534 | null | #!/usr/bin/env python
# Concurrent_AP/Concurrent_AP.py
# Author: Gregory Giecold for the GC Yuan Lab
# Affiliation: Harvard University
# Contact: g.giecold@gmail.com, ggiecold@jimmy.harvard.edu
"""Concurrent_AP is a scalable and concurrent programming implementation
of Affinity Propagation clustering.
Affinity ... |
GGiecold/Concurrent_AP | Concurrent_AP.py | compute_similarities | python | def compute_similarities(hdf5_file, data, N_processes):
slice_queue = multiprocessing.JoinableQueue()
pid_list = []
for i in range(N_processes):
worker = Similarities_worker(hdf5_file, '/aff_prop_group/similarities',
data, slice_queue)
worker.daemon... | Compute a matrix of pairwise L2 Euclidean distances among samples from 'data'.
This computation is to be done in parallel by 'N_processes' distinct processes.
Those processes (which are instances of the class 'Similarities_worker')
are prevented from simultaneously accessing the HDF5 data stru... | train | https://github.com/GGiecold/Concurrent_AP/blob/d4cebe06268b5d520352a83cadb2f7520650460c/Concurrent_AP.py#L537-L562 | [
"def chunk_generator(N, n):\n \"\"\"Returns a generator of slice objects.\n\n Parameters\n ----------\n N : int\n The size of one of the dimensions of a two-dimensional array. \n\n n : int\n The number of arrays of shape ('N', 'get_chunk_size(N, n)') that fit into\n memory.\n\n ... | #!/usr/bin/env python
# Concurrent_AP/Concurrent_AP.py
# Author: Gregory Giecold for the GC Yuan Lab
# Affiliation: Harvard University
# Contact: g.giecold@gmail.com, ggiecold@jimmy.harvard.edu
"""Concurrent_AP is a scalable and concurrent programming implementation
of Affinity Propagation clustering.
Affinity ... |
GGiecold/Concurrent_AP | Concurrent_AP.py | add_preference | python | def add_preference(hdf5_file, preference):
Worker.hdf5_lock.acquire()
with tables.open_file(hdf5_file, 'r+') as fileh:
S = fileh.root.aff_prop_group.similarities
diag_ind = np.diag_indices(S.nrows)
S[diag_ind] = preference
Worker.hdf5_lock.release() | Assign the value 'preference' to the diagonal entries
of the matrix of similarities stored in the HDF5 data structure
at 'hdf5_file'. | train | https://github.com/GGiecold/Concurrent_AP/blob/d4cebe06268b5d520352a83cadb2f7520650460c/Concurrent_AP.py#L565-L578 | null | #!/usr/bin/env python
# Concurrent_AP/Concurrent_AP.py
# Author: Gregory Giecold for the GC Yuan Lab
# Affiliation: Harvard University
# Contact: g.giecold@gmail.com, ggiecold@jimmy.harvard.edu
"""Concurrent_AP is a scalable and concurrent programming implementation
of Affinity Propagation clustering.
Affinity ... |
GGiecold/Concurrent_AP | Concurrent_AP.py | add_fluctuations | python | def add_fluctuations(hdf5_file, N_columns, N_processes):
random_state = np.random.RandomState(0)
slice_queue = multiprocessing.JoinableQueue()
pid_list = []
for i in range(N_processes):
worker = Fluctuations_worker(hdf5_file,
'/aff_prop_group/similarities', ... | This procedure organizes the addition of small fluctuations on top of
a matrix of similarities at 'hdf5_file' across 'N_processes'
different processes. Each of those processes is an instance of the
class 'Fluctuations_Worker' defined elsewhere in this module. | train | https://github.com/GGiecold/Concurrent_AP/blob/d4cebe06268b5d520352a83cadb2f7520650460c/Concurrent_AP.py#L581-L608 | [
"def chunk_generator(N, n):\n \"\"\"Returns a generator of slice objects.\n\n Parameters\n ----------\n N : int\n The size of one of the dimensions of a two-dimensional array. \n\n n : int\n The number of arrays of shape ('N', 'get_chunk_size(N, n)') that fit into\n memory.\n\n ... | #!/usr/bin/env python
# Concurrent_AP/Concurrent_AP.py
# Author: Gregory Giecold for the GC Yuan Lab
# Affiliation: Harvard University
# Contact: g.giecold@gmail.com, ggiecold@jimmy.harvard.edu
"""Concurrent_AP is a scalable and concurrent programming implementation
of Affinity Propagation clustering.
Affinity ... |
GGiecold/Concurrent_AP | Concurrent_AP.py | compute_responsibilities | python | def compute_responsibilities(hdf5_file, N_columns, damping, N_processes):
slice_queue = multiprocessing.JoinableQueue()
pid_list = []
for i in range(N_processes):
worker = Responsibilities_worker(hdf5_file, '/aff_prop_group',
N_columns, damping, slice_queue)
worker.d... | Organize the computation and update of the responsibility matrix
for Affinity Propagation clustering with 'damping' as the eponymous
damping parameter. Each of the processes concurrently involved in this task
is an instance of the class 'Responsibilities_worker' defined above. | train | https://github.com/GGiecold/Concurrent_AP/blob/d4cebe06268b5d520352a83cadb2f7520650460c/Concurrent_AP.py#L611-L634 | [
"def chunk_generator(N, n):\n \"\"\"Returns a generator of slice objects.\n\n Parameters\n ----------\n N : int\n The size of one of the dimensions of a two-dimensional array. \n\n n : int\n The number of arrays of shape ('N', 'get_chunk_size(N, n)') that fit into\n memory.\n\n ... | #!/usr/bin/env python
# Concurrent_AP/Concurrent_AP.py
# Author: Gregory Giecold for the GC Yuan Lab
# Affiliation: Harvard University
# Contact: g.giecold@gmail.com, ggiecold@jimmy.harvard.edu
"""Concurrent_AP is a scalable and concurrent programming implementation
of Affinity Propagation clustering.
Affinity ... |
GGiecold/Concurrent_AP | Concurrent_AP.py | rows_sum_init | python | def rows_sum_init(hdf5_file, path, out_lock, *numpy_args):
global g_hdf5_file, g_path, g_out, g_out_lock
g_hdf5_file, g_path, g_out_lock = hdf5_file, path, out_lock
g_out = to_numpy_array(*numpy_args) | Create global variables sharing the same object as the one pointed by
'hdf5_file', 'path' and 'out_lock'.
Also Create a NumPy array copy of a multiprocessing.Array ctypes array
specified by '*numpy_args'. | train | https://github.com/GGiecold/Concurrent_AP/blob/d4cebe06268b5d520352a83cadb2f7520650460c/Concurrent_AP.py#L637-L647 | [
"def to_numpy_array(multiprocessing_array, shape, dtype):\n \"\"\"Convert a share multiprocessing array to a numpy array.\n No data copying involved.\n \"\"\"\n\n return np.frombuffer(multiprocessing_array.get_obj(),\n dtype = dtype).reshape(shape)\n"
] | #!/usr/bin/env python
# Concurrent_AP/Concurrent_AP.py
# Author: Gregory Giecold for the GC Yuan Lab
# Affiliation: Harvard University
# Contact: g.giecold@gmail.com, ggiecold@jimmy.harvard.edu
"""Concurrent_AP is a scalable and concurrent programming implementation
of Affinity Propagation clustering.
Affinity ... |
GGiecold/Concurrent_AP | Concurrent_AP.py | to_numpy_array | python | def to_numpy_array(multiprocessing_array, shape, dtype):
return np.frombuffer(multiprocessing_array.get_obj(),
dtype = dtype).reshape(shape) | Convert a share multiprocessing array to a numpy array.
No data copying involved. | train | https://github.com/GGiecold/Concurrent_AP/blob/d4cebe06268b5d520352a83cadb2f7520650460c/Concurrent_AP.py#L655-L661 | null | #!/usr/bin/env python
# Concurrent_AP/Concurrent_AP.py
# Author: Gregory Giecold for the GC Yuan Lab
# Affiliation: Harvard University
# Contact: g.giecold@gmail.com, ggiecold@jimmy.harvard.edu
"""Concurrent_AP is a scalable and concurrent programming implementation
of Affinity Propagation clustering.
Affinity ... |
GGiecold/Concurrent_AP | Concurrent_AP.py | compute_rows_sum | python | def compute_rows_sum(hdf5_file, path, N_columns, N_processes, method = 'Process'):
"""Parallel computation of the sums across the rows of two-dimensional array
accessible at the node specified by 'path' in the 'hdf5_file'
hierarchical data format.
"""
assert isinstance(me... | Parallel computation of the sums across the rows of two-dimensional array
accessible at the node specified by 'path' in the 'hdf5_file'
hierarchical data format. | train | https://github.com/GGiecold/Concurrent_AP/blob/d4cebe06268b5d520352a83cadb2f7520650460c/Concurrent_AP.py#L664-L709 | [
"def get_chunk_size(N, n):\n \"\"\"Given a two-dimensional array with a dimension of size 'N', \n determine the number of rows or columns that can fit into memory.\n\n Parameters\n ----------\n N : int\n The size of one of the dimensions of a two-dimensional array. \n\n n : int\n ... | #!/usr/bin/env python
# Concurrent_AP/Concurrent_AP.py
# Author: Gregory Giecold for the GC Yuan Lab
# Affiliation: Harvard University
# Contact: g.giecold@gmail.com, ggiecold@jimmy.harvard.edu
"""Concurrent_AP is a scalable and concurrent programming implementation
of Affinity Propagation clustering.
Affinity ... |
GGiecold/Concurrent_AP | Concurrent_AP.py | compute_availabilities | python | def compute_availabilities(hdf5_file, N_columns, damping, N_processes, rows_sum):
slice_queue = multiprocessing.JoinableQueue()
pid_list = []
for i in range(N_processes):
worker = Availabilities_worker(hdf5_file, '/aff_prop_group',
N_columns, damping, slice_queue, rows_s... | Coordinates the computation and update of the availability matrix
for Affinity Propagation clustering.
Parameters
----------
hdf5_file : string or file handle
Specify access to the hierarchical data format used throughout all the iterations
of message-passing between data-point... | train | https://github.com/GGiecold/Concurrent_AP/blob/d4cebe06268b5d520352a83cadb2f7520650460c/Concurrent_AP.py#L712-L754 | [
"def chunk_generator(N, n):\n \"\"\"Returns a generator of slice objects.\n\n Parameters\n ----------\n N : int\n The size of one of the dimensions of a two-dimensional array. \n\n n : int\n The number of arrays of shape ('N', 'get_chunk_size(N, n)') that fit into\n memory.\n\n ... | #!/usr/bin/env python
# Concurrent_AP/Concurrent_AP.py
# Author: Gregory Giecold for the GC Yuan Lab
# Affiliation: Harvard University
# Contact: g.giecold@gmail.com, ggiecold@jimmy.harvard.edu
"""Concurrent_AP is a scalable and concurrent programming implementation
of Affinity Propagation clustering.
Affinity ... |
GGiecold/Concurrent_AP | Concurrent_AP.py | check_convergence | python | def check_convergence(hdf5_file, iteration, convergence_iter, max_iter):
Worker.hdf5_lock.acquire()
with tables.open_file(hdf5_file, 'r+') as fileh:
A = fileh.root.aff_prop_group.availabilities
R = fileh.root.aff_prop_group.responsibilities
P = fileh.root.aff_prop_group.parallel_up... | If the estimated number of clusters has not changed for 'convergence_iter'
consecutive iterations in a total of 'max_iter' rounds of message-passing,
the procedure herewith returns 'True'.
Otherwise, returns 'False'.
Parameter 'iteration' identifies the run of message-passing
t... | train | https://github.com/GGiecold/Concurrent_AP/blob/d4cebe06268b5d520352a83cadb2f7520650460c/Concurrent_AP.py#L757-L790 | null | #!/usr/bin/env python
# Concurrent_AP/Concurrent_AP.py
# Author: Gregory Giecold for the GC Yuan Lab
# Affiliation: Harvard University
# Contact: g.giecold@gmail.com, ggiecold@jimmy.harvard.edu
"""Concurrent_AP is a scalable and concurrent programming implementation
of Affinity Propagation clustering.
Affinity ... |
GGiecold/Concurrent_AP | Concurrent_AP.py | cluster_labels_A | python | def cluster_labels_A(hdf5_file, c, lock, I, rows_slice):
with Worker.hdf5_lock:
with tables.open_file(hdf5_file, 'r+') as fileh:
S = fileh.root.aff_prop_group.similarities
s = S[rows_slice, ...]
s = np.argmax(s[:, I], axis = 1)
with lock:
... | One of the task to be performed by a pool of subprocesses, as the first
step in identifying the cluster labels and indices of the cluster centers
for Affinity Propagation clustering. | train | https://github.com/GGiecold/Concurrent_AP/blob/d4cebe06268b5d520352a83cadb2f7520650460c/Concurrent_AP.py#L827-L843 | null | #!/usr/bin/env python
# Concurrent_AP/Concurrent_AP.py
# Author: Gregory Giecold for the GC Yuan Lab
# Affiliation: Harvard University
# Contact: g.giecold@gmail.com, ggiecold@jimmy.harvard.edu
"""Concurrent_AP is a scalable and concurrent programming implementation
of Affinity Propagation clustering.
Affinity ... |
GGiecold/Concurrent_AP | Concurrent_AP.py | cluster_labels_B | python | def cluster_labels_B(hdf5_file, s_reduced, lock, I, ii, iix, rows_slice):
with Worker.hdf5_lock:
with tables.open_file(hdf5_file, 'r+') as fileh:
S = fileh.root.aff_prop_group.similarities
s = S[rows_slice, ...]
s = s[:, ii]
s = s[iix[rows_slice]]
with l... | Second task to be performed by a pool of subprocesses before
the cluster labels and cluster center indices can be identified. | train | https://github.com/GGiecold/Concurrent_AP/blob/d4cebe06268b5d520352a83cadb2f7520650460c/Concurrent_AP.py#L846-L862 | null | #!/usr/bin/env python
# Concurrent_AP/Concurrent_AP.py
# Author: Gregory Giecold for the GC Yuan Lab
# Affiliation: Harvard University
# Contact: g.giecold@gmail.com, ggiecold@jimmy.harvard.edu
"""Concurrent_AP is a scalable and concurrent programming implementation
of Affinity Propagation clustering.
Affinity ... |
GGiecold/Concurrent_AP | Concurrent_AP.py | get_cluster_labels | python | def get_cluster_labels(hdf5_file, N_processes):
with Worker.hdf5_lock:
with tables.open_file(hdf5_file, 'r+') as fileh:
A = fileh.root.aff_prop_group.availabilities
R = fileh.root.aff_prop_group.responsibilities
N = A.nrows
diag_ind = np.diag_indices(N)
... | Returns
-------
cluster_centers_indices : array of shape (n_clusters,)
Indices of cluster centers
labels : array of shape (n_samples,)
Specify the label of the cluster to which each point has been assigned. | train | https://github.com/GGiecold/Concurrent_AP/blob/d4cebe06268b5d520352a83cadb2f7520650460c/Concurrent_AP.py#L884-L990 | null | #!/usr/bin/env python
# Concurrent_AP/Concurrent_AP.py
# Author: Gregory Giecold for the GC Yuan Lab
# Affiliation: Harvard University
# Contact: g.giecold@gmail.com, ggiecold@jimmy.harvard.edu
"""Concurrent_AP is a scalable and concurrent programming implementation
of Affinity Propagation clustering.
Affinity ... |
GGiecold/Concurrent_AP | Concurrent_AP.py | output_clusters | python | def output_clusters(labels, cluster_centers_indices):
here = os.getcwd()
try:
output_directory = os.path.join(here, 'concurrent_AP_output')
os.makedirs(output_directory)
except OSError:
if not os.path.isdir(output_directory):
print("ERROR: concurrent_AP: outp... | Write in tab-separated files the vectors of cluster identities and
of indices of cluster centers. | train | https://github.com/GGiecold/Concurrent_AP/blob/d4cebe06268b5d520352a83cadb2f7520650460c/Concurrent_AP.py#L993-L1020 | null | #!/usr/bin/env python
# Concurrent_AP/Concurrent_AP.py
# Author: Gregory Giecold for the GC Yuan Lab
# Affiliation: Harvard University
# Contact: g.giecold@gmail.com, ggiecold@jimmy.harvard.edu
"""Concurrent_AP is a scalable and concurrent programming implementation
of Affinity Propagation clustering.
Affinity ... |
GGiecold/Concurrent_AP | Concurrent_AP.py | set_preference | python | def set_preference(data, chunk_size):
N_samples, N_features = data.shape
rng = np.arange(0, N_samples, dtype = int)
medians = []
for i in range(15):
selected_samples = np.random.choice(N_samples, size = chunk_size, replace = False)
samples = data[selected_samples, :]
... | Return the median of the distribution of pairwise L2 Euclidean distances
between samples (the rows of 'data') as the default preference parameter
for Affinity Propagation clustering.
Parameters
----------
data : array of shape (N_samples, N_features)
The data-set submitted for Affi... | train | https://github.com/GGiecold/Concurrent_AP/blob/d4cebe06268b5d520352a83cadb2f7520650460c/Concurrent_AP.py#L1023-L1080 | null | #!/usr/bin/env python
# Concurrent_AP/Concurrent_AP.py
# Author: Gregory Giecold for the GC Yuan Lab
# Affiliation: Harvard University
# Contact: g.giecold@gmail.com, ggiecold@jimmy.harvard.edu
"""Concurrent_AP is a scalable and concurrent programming implementation
of Affinity Propagation clustering.
Affinity ... |
ultradns/python_rest_api_client | ultra_rest_client/ultra_rest_client.py | RestApiClient.create_primary_zone | python | def create_primary_zone(self, account_name, zone_name):
zone_properties = {"name": zone_name, "accountName": account_name, "type": "PRIMARY"}
primary_zone_info = {"forceImport": True, "createType": "NEW"}
zone_data = {"properties": zone_properties, "primaryCreateInfo": primary_zone_info}
... | Creates a new primary zone.
Arguments:
account_name -- The name of the account that will contain this zone.
zone_name -- The name of the zone. It must be unique. | train | https://github.com/ultradns/python_rest_api_client/blob/e4095f28f5cb5e258b768c06ef7cf8b1915aa5ec/ultra_rest_client/ultra_rest_client.py#L29-L40 | [
"def post(self, uri, json=None):\n if json is not None:\n return self._do_call(uri, \"POST\", body=json)\n else:\n return self._do_call(uri, \"POST\")\n"
] | class RestApiClient:
def __init__(self, username, password, use_http=False, host="restapi.ultradns.com"):
"""Initialize a Rest API Client.
Arguments:
username -- The username of the user
password -- The password of the user
Keyword Arguments:
use_http -- For interna... |
ultradns/python_rest_api_client | ultra_rest_client/ultra_rest_client.py | RestApiClient.create_primary_zone_by_upload | python | def create_primary_zone_by_upload(self, account_name, zone_name, bind_file):
zone_properties = {"name": zone_name, "accountName": account_name, "type": "PRIMARY"}
primary_zone_info = {"forceImport": True, "createType": "UPLOAD"}
zone_data = {"properties": zone_properties, "primaryCreateInfo": pr... | Creates a new primary zone by uploading a bind file
Arguments:
account_name -- The name of the account that will contain this zone.
zone_name -- The name of the zone. It must be unique.
bind_file -- The file to upload. | train | https://github.com/ultradns/python_rest_api_client/blob/e4095f28f5cb5e258b768c06ef7cf8b1915aa5ec/ultra_rest_client/ultra_rest_client.py#L43-L57 | [
"def post_multi_part(self, uri, files):\n #use empty string for content type so we don't set it\n return self._do_call(uri, \"POST\", files=files, content_type=\"\")\n"
] | class RestApiClient:
def __init__(self, username, password, use_http=False, host="restapi.ultradns.com"):
"""Initialize a Rest API Client.
Arguments:
username -- The username of the user
password -- The password of the user
Keyword Arguments:
use_http -- For interna... |
ultradns/python_rest_api_client | ultra_rest_client/ultra_rest_client.py | RestApiClient.create_primary_zone_by_axfr | python | def create_primary_zone_by_axfr(self, account_name, zone_name, master, tsig_key=None, key_value=None):
zone_properties = {"name": zone_name, "accountName": account_name, "type": "PRIMARY"}
if tsig_key is not None and key_value is not None:
name_server_info = {"ip": master, "tsigKey": tsig_ke... | Creates a new primary zone by zone transferring off a master.
Arguments:
account_name -- The name of the account that will contain this zone.
zone_name -- The name of the zone. It must be unique.
master -- Primary name server IP address.
Keyword Arguments:
tsig_key -- ... | train | https://github.com/ultradns/python_rest_api_client/blob/e4095f28f5cb5e258b768c06ef7cf8b1915aa5ec/ultra_rest_client/ultra_rest_client.py#L60-L81 | null | class RestApiClient:
def __init__(self, username, password, use_http=False, host="restapi.ultradns.com"):
"""Initialize a Rest API Client.
Arguments:
username -- The username of the user
password -- The password of the user
Keyword Arguments:
use_http -- For interna... |
ultradns/python_rest_api_client | ultra_rest_client/ultra_rest_client.py | RestApiClient.create_secondary_zone | python | def create_secondary_zone(self, account_name, zone_name, master, tsig_key=None, key_value=None):
zone_properties = {"name": zone_name, "accountName": account_name, "type": "SECONDARY"}
if tsig_key is not None and key_value is not None:
name_server_info = {"ip": master, "tsigKey": tsig_key, "... | Creates a new secondary zone.
Arguments:
account_name -- The name of the account.
zone_name -- The name of the zone.
master -- Primary name server IP address.
Keyword Arguments:
tsig_key -- For TSIG-enabled zones: The transaction signature key.
NOTE:... | train | https://github.com/ultradns/python_rest_api_client/blob/e4095f28f5cb5e258b768c06ef7cf8b1915aa5ec/ultra_rest_client/ultra_rest_client.py#L84-L107 | null | class RestApiClient:
def __init__(self, username, password, use_http=False, host="restapi.ultradns.com"):
"""Initialize a Rest API Client.
Arguments:
username -- The username of the user
password -- The password of the user
Keyword Arguments:
use_http -- For interna... |
ultradns/python_rest_api_client | ultra_rest_client/ultra_rest_client.py | RestApiClient.get_zones_of_account | python | def get_zones_of_account(self, account_name, q=None, **kwargs):
uri = "/v1/accounts/" + account_name + "/zones"
params = build_params(q, kwargs)
return self.rest_api_connection.get(uri, params) | Returns a list of zones for the specified account.
Arguments:
account_name -- The name of the account.
Keyword Arguments:
q -- The search parameters, in a dict. Valid keys are:
name - substring match of the zone name
zone_type - one of:
PRIMAR... | train | https://github.com/ultradns/python_rest_api_client/blob/e4095f28f5cb5e258b768c06ef7cf8b1915aa5ec/ultra_rest_client/ultra_rest_client.py#L130-L155 | [
"def build_params(q, args):\n params = {}\n params.update(args)\n if q is not None:\n all = []\n for k in q:\n all.append(\"%s:%s\" % (k, q[k]))\n params['q']= ' '.join(all)\n return params\n",
"def get(self, uri, params=None):\n if params is None:\n params = ... | class RestApiClient:
def __init__(self, username, password, use_http=False, host="restapi.ultradns.com"):
"""Initialize a Rest API Client.
Arguments:
username -- The username of the user
password -- The password of the user
Keyword Arguments:
use_http -- For interna... |
ultradns/python_rest_api_client | ultra_rest_client/ultra_rest_client.py | RestApiClient.get_zones | python | def get_zones(self, q=None, **kwargs):
uri = "/v1/zones"
params = build_params(q, kwargs)
return self.rest_api_connection.get(uri, params) | Returns a list of zones across all of the user's accounts.
Keyword Arguments:
q -- The search parameters, in a dict. Valid keys are:
name - substring match of the zone name
zone_type - one of:
PRIMARY
SECONDARY
ALIAS
sor... | train | https://github.com/ultradns/python_rest_api_client/blob/e4095f28f5cb5e258b768c06ef7cf8b1915aa5ec/ultra_rest_client/ultra_rest_client.py#L158-L180 | [
"def build_params(q, args):\n params = {}\n params.update(args)\n if q is not None:\n all = []\n for k in q:\n all.append(\"%s:%s\" % (k, q[k]))\n params['q']= ' '.join(all)\n return params\n",
"def get(self, uri, params=None):\n if params is None:\n params = ... | class RestApiClient:
def __init__(self, username, password, use_http=False, host="restapi.ultradns.com"):
"""Initialize a Rest API Client.
Arguments:
username -- The username of the user
password -- The password of the user
Keyword Arguments:
use_http -- For interna... |
ultradns/python_rest_api_client | ultra_rest_client/ultra_rest_client.py | RestApiClient.edit_secondary_name_server | python | def edit_secondary_name_server(self, zone_name, primary=None, backup=None, second_backup=None):
name_server_info = {}
if primary is not None:
name_server_info['nameServerIp1'] = {'ip':primary}
if backup is not None:
name_server_info['nameServerIp2'] = {'ip':backup}
... | Edit the axfr name servers of a secondary zone.
Arguments:
zone_name -- The name of the secondary zone being edited.
primary -- The primary name server value.
Keyword Arguments:
backup -- The backup name server if any.
second_backup -- The second backup name server. | train | https://github.com/ultradns/python_rest_api_client/blob/e4095f28f5cb5e258b768c06ef7cf8b1915aa5ec/ultra_rest_client/ultra_rest_client.py#L203-L225 | null | class RestApiClient:
def __init__(self, username, password, use_http=False, host="restapi.ultradns.com"):
"""Initialize a Rest API Client.
Arguments:
username -- The username of the user
password -- The password of the user
Keyword Arguments:
use_http -- For interna... |
ultradns/python_rest_api_client | ultra_rest_client/ultra_rest_client.py | RestApiClient.get_rrsets | python | def get_rrsets(self, zone_name, q=None, **kwargs):
uri = "/v1/zones/" + zone_name + "/rrsets"
params = build_params(q, kwargs)
return self.rest_api_connection.get(uri, params) | Returns the list of RRSets in the specified zone.
Arguments:
zone_name -- The name of the zone.
Keyword Arguments:
q -- The search parameters, in a dict. Valid keys are:
ttl - must match the TTL for the rrset
owner - substring match of the owner name
... | train | https://github.com/ultradns/python_rest_api_client/blob/e4095f28f5cb5e258b768c06ef7cf8b1915aa5ec/ultra_rest_client/ultra_rest_client.py#L229-L251 | [
"def build_params(q, args):\n params = {}\n params.update(args)\n if q is not None:\n all = []\n for k in q:\n all.append(\"%s:%s\" % (k, q[k]))\n params['q']= ' '.join(all)\n return params\n",
"def get(self, uri, params=None):\n if params is None:\n params = ... | class RestApiClient:
def __init__(self, username, password, use_http=False, host="restapi.ultradns.com"):
"""Initialize a Rest API Client.
Arguments:
username -- The username of the user
password -- The password of the user
Keyword Arguments:
use_http -- For interna... |
ultradns/python_rest_api_client | ultra_rest_client/ultra_rest_client.py | RestApiClient.get_rrsets_by_type | python | def get_rrsets_by_type(self, zone_name, rtype, q=None, **kwargs):
uri = "/v1/zones/" + zone_name + "/rrsets/" + rtype
params = build_params(q, kwargs)
return self.rest_api_connection.get(uri, params) | Returns the list of RRSets in the specified zone of the specified type.
Arguments:
zone_name -- The name of the zone.
rtype -- The type of the RRSets. This can be numeric (1) or
if a well-known name is defined for the type (A), you can use it instead.
Keyword Argument... | train | https://github.com/ultradns/python_rest_api_client/blob/e4095f28f5cb5e258b768c06ef7cf8b1915aa5ec/ultra_rest_client/ultra_rest_client.py#L255-L279 | [
"def build_params(q, args):\n params = {}\n params.update(args)\n if q is not None:\n all = []\n for k in q:\n all.append(\"%s:%s\" % (k, q[k]))\n params['q']= ' '.join(all)\n return params\n",
"def get(self, uri, params=None):\n if params is None:\n params = ... | class RestApiClient:
def __init__(self, username, password, use_http=False, host="restapi.ultradns.com"):
"""Initialize a Rest API Client.
Arguments:
username -- The username of the user
password -- The password of the user
Keyword Arguments:
use_http -- For interna... |
ultradns/python_rest_api_client | ultra_rest_client/ultra_rest_client.py | RestApiClient.get_rrsets_by_type_owner | python | def get_rrsets_by_type_owner(self, zone_name, rtype, owner_name, q=None, **kwargs):
uri = "/v1/zones/" + zone_name + "/rrsets/" + rtype + "/" + owner_name
params = build_params(q, kwargs)
return self.rest_api_connection.get(uri, params) | Returns the list of RRSets in the specified zone of the specified type.
Arguments:
zone_name -- The name of the zone.
rtype -- The type of the RRSets. This can be numeric (1) or
if a well-known name is defined for the type (A), you can use it instead.
owner_name -- The... | train | https://github.com/ultradns/python_rest_api_client/blob/e4095f28f5cb5e258b768c06ef7cf8b1915aa5ec/ultra_rest_client/ultra_rest_client.py#L283-L308 | [
"def build_params(q, args):\n params = {}\n params.update(args)\n if q is not None:\n all = []\n for k in q:\n all.append(\"%s:%s\" % (k, q[k]))\n params['q']= ' '.join(all)\n return params\n",
"def get(self, uri, params=None):\n if params is None:\n params = ... | class RestApiClient:
def __init__(self, username, password, use_http=False, host="restapi.ultradns.com"):
"""Initialize a Rest API Client.
Arguments:
username -- The username of the user
password -- The password of the user
Keyword Arguments:
use_http -- For interna... |
ultradns/python_rest_api_client | ultra_rest_client/ultra_rest_client.py | RestApiClient.create_rrset | python | def create_rrset(self, zone_name, rtype, owner_name, ttl, rdata):
if type(rdata) is not list:
rdata = [rdata]
rrset = {"ttl": ttl, "rdata": rdata}
return self.rest_api_connection.post("/v1/zones/" + zone_name + "/rrsets/" + rtype + "/" + owner_name, json.dumps(rrset)) | Creates a new RRSet in the specified zone.
Arguments:
zone_name -- The zone that will contain the new RRSet. The trailing dot is optional.
rtype -- The type of the RRSet. This can be numeric (1) or
if a well-known name is defined for the type (A), you can use it instead.
... | train | https://github.com/ultradns/python_rest_api_client/blob/e4095f28f5cb5e258b768c06ef7cf8b1915aa5ec/ultra_rest_client/ultra_rest_client.py#L311-L330 | [
"def post(self, uri, json=None):\n if json is not None:\n return self._do_call(uri, \"POST\", body=json)\n else:\n return self._do_call(uri, \"POST\")\n"
] | class RestApiClient:
def __init__(self, username, password, use_http=False, host="restapi.ultradns.com"):
"""Initialize a Rest API Client.
Arguments:
username -- The username of the user
password -- The password of the user
Keyword Arguments:
use_http -- For interna... |
ultradns/python_rest_api_client | ultra_rest_client/ultra_rest_client.py | RestApiClient.edit_rrset | python | def edit_rrset(self, zone_name, rtype, owner_name, ttl, rdata, profile=None):
if type(rdata) is not list:
rdata = [rdata]
rrset = {"ttl": ttl, "rdata": rdata}
if profile:
rrset["profile"] = profile
uri = "/v1/zones/" + zone_name + "/rrsets/" + rtype + "/" + owner_... | Updates an existing RRSet in the specified zone.
Arguments:
zone_name -- The zone that contains the RRSet. The trailing dot is optional.
rtype -- The type of the RRSet. This can be numeric (1) or
if a well-known name is defined for the type (A), you can use it instead.
... | train | https://github.com/ultradns/python_rest_api_client/blob/e4095f28f5cb5e258b768c06ef7cf8b1915aa5ec/ultra_rest_client/ultra_rest_client.py#L333-L356 | [
"def put(self, uri, json):\n return self._do_call(uri, \"PUT\", body=json)\n"
] | class RestApiClient:
def __init__(self, username, password, use_http=False, host="restapi.ultradns.com"):
"""Initialize a Rest API Client.
Arguments:
username -- The username of the user
password -- The password of the user
Keyword Arguments:
use_http -- For interna... |
ultradns/python_rest_api_client | ultra_rest_client/ultra_rest_client.py | RestApiClient.edit_rrset_rdata | python | def edit_rrset_rdata(self, zone_name, rtype, owner_name, rdata, profile=None):
if type(rdata) is not list:
rdata = [rdata]
rrset = {"rdata": rdata}
method = "patch"
if profile:
rrset["profile"] = profile
method = "put"
uri = "/v1/zones/" + zone... | Updates an existing RRSet's Rdata in the specified zone.
Arguments:
zone_name -- The zone that contains the RRSet. The trailing dot is optional.
rtype -- The type of the RRSet. This can be numeric (1) or
if a well-known name is defined for the type (A), you can use it instead... | train | https://github.com/ultradns/python_rest_api_client/blob/e4095f28f5cb5e258b768c06ef7cf8b1915aa5ec/ultra_rest_client/ultra_rest_client.py#L359-L383 | null | class RestApiClient:
def __init__(self, username, password, use_http=False, host="restapi.ultradns.com"):
"""Initialize a Rest API Client.
Arguments:
username -- The username of the user
password -- The password of the user
Keyword Arguments:
use_http -- For interna... |
ultradns/python_rest_api_client | ultra_rest_client/ultra_rest_client.py | RestApiClient.delete_rrset | python | def delete_rrset(self, zone_name, rtype, owner_name):
return self.rest_api_connection.delete("/v1/zones/" + zone_name + "/rrsets/" + rtype + "/" + owner_name) | Deletes an RRSet.
Arguments:
zone_name -- The zone containing the RRSet to be deleted. The trailing dot is optional.
rtype -- The type of the RRSet. This can be numeric (1) or
if a well-known name is defined for the type (A), you can use it instead.
owner_name -- The ... | train | https://github.com/ultradns/python_rest_api_client/blob/e4095f28f5cb5e258b768c06ef7cf8b1915aa5ec/ultra_rest_client/ultra_rest_client.py#L386-L398 | [
"def delete(self, uri):\n return self._do_call(uri, \"DELETE\")\n"
] | class RestApiClient:
def __init__(self, username, password, use_http=False, host="restapi.ultradns.com"):
"""Initialize a Rest API Client.
Arguments:
username -- The username of the user
password -- The password of the user
Keyword Arguments:
use_http -- For interna... |
ultradns/python_rest_api_client | ultra_rest_client/ultra_rest_client.py | RestApiClient.create_web_forward | python | def create_web_forward(self, zone_name, request_to, redirect_to, forward_type):
web_forward = {"requestTo": request_to, "defaultRedirectTo": redirect_to, "defaultForwardType": forward_type}
return self.rest_api_connection.post("/v1/zones/" + zone_name + "/webforwards", json.dumps(web_forward)) | Create a web forward record.
Arguments:
zone_name -- The zone in which the web forward is to be created.
request_to -- The URL to be redirected. You may use http:// and ftp://.
forward_type -- The type of forward. Valid options include:
Framed
... | train | https://github.com/ultradns/python_rest_api_client/blob/e4095f28f5cb5e258b768c06ef7cf8b1915aa5ec/ultra_rest_client/ultra_rest_client.py#L413-L428 | null | class RestApiClient:
def __init__(self, username, password, use_http=False, host="restapi.ultradns.com"):
"""Initialize a Rest API Client.
Arguments:
username -- The username of the user
password -- The password of the user
Keyword Arguments:
use_http -- For interna... |
ultradns/python_rest_api_client | ultra_rest_client/ultra_rest_client.py | RestApiClient.create_sb_pool | python | def create_sb_pool(self, zone_name, owner_name, ttl, pool_info, rdata_info, backup_record_list):
rrset = self._build_sb_rrset(backup_record_list, pool_info, rdata_info, ttl)
return self.rest_api_connection.post("/v1/zones/" + zone_name + "/rrsets/A/" + owner_name, json.dumps(rrset)) | Creates a new SB Pool.
Arguments:
zone_name -- The zone that contains the RRSet. The trailing dot is optional.
owner_name -- The owner name for the RRSet.
If no trailing dot is supplied, the owner_name is assumed to be relative (foo).
If a trailing d... | train | https://github.com/ultradns/python_rest_api_client/blob/e4095f28f5cb5e258b768c06ef7cf8b1915aa5ec/ultra_rest_client/ultra_rest_client.py#L551-L571 | [
"def _build_sb_rrset(self, backup_record_list, pool_info, rdata_info, ttl):\n rdata = []\n rdata_info_list = []\n for rr in rdata_info:\n rdata.append(rr)\n rdata_info_list.append(rdata_info[rr])\n profile = {\"@context\": \"http://schemas.ultradns.com/SBPool.jsonschema\"}\n for p in po... | class RestApiClient:
def __init__(self, username, password, use_http=False, host="restapi.ultradns.com"):
"""Initialize a Rest API Client.
Arguments:
username -- The username of the user
password -- The password of the user
Keyword Arguments:
use_http -- For interna... |
ultradns/python_rest_api_client | ultra_rest_client/ultra_rest_client.py | RestApiClient.edit_sb_pool | python | def edit_sb_pool(self, zone_name, owner_name, ttl, pool_info, rdata_info, backup_record_list):
rrset = self._build_sb_rrset(backup_record_list, pool_info, rdata_info, ttl)
return self.rest_api_connection.put("/v1/zones/" + zone_name + "/rrsets/A/" + owner_name, json.dumps(rrset)) | Updates an existing SB Pool in the specified zone.
:param zone_name: The zone that contains the RRSet. The trailing dot is optional.
:param owner_name: The owner name for the RRSet.
If no trailing dot is supplied, the owner_name is assumed to be relative (foo).
... | train | https://github.com/ultradns/python_rest_api_client/blob/e4095f28f5cb5e258b768c06ef7cf8b1915aa5ec/ultra_rest_client/ultra_rest_client.py#L575-L592 | [
"def _build_sb_rrset(self, backup_record_list, pool_info, rdata_info, ttl):\n rdata = []\n rdata_info_list = []\n for rr in rdata_info:\n rdata.append(rr)\n rdata_info_list.append(rdata_info[rr])\n profile = {\"@context\": \"http://schemas.ultradns.com/SBPool.jsonschema\"}\n for p in po... | class RestApiClient:
def __init__(self, username, password, use_http=False, host="restapi.ultradns.com"):
"""Initialize a Rest API Client.
Arguments:
username -- The username of the user
password -- The password of the user
Keyword Arguments:
use_http -- For interna... |
ultradns/python_rest_api_client | ultra_rest_client/ultra_rest_client.py | RestApiClient.create_tc_pool | python | def create_tc_pool(self, zone_name, owner_name, ttl, pool_info, rdata_info, backup_record):
rrset = self._build_tc_rrset(backup_record, pool_info, rdata_info, ttl)
return self.rest_api_connection.post("/v1/zones/" + zone_name + "/rrsets/A/" + owner_name, json.dumps(rrset)) | Creates a new TC Pool.
Arguments:
zone_name -- The zone that contains the RRSet. The trailing dot is optional.
owner_name -- The owner name for the RRSet.
If no trailing dot is supplied, the owner_name is assumed to be relative (foo).
If a trailing d... | train | https://github.com/ultradns/python_rest_api_client/blob/e4095f28f5cb5e258b768c06ef7cf8b1915aa5ec/ultra_rest_client/ultra_rest_client.py#L661-L681 | [
"def _build_tc_rrset(self, backup_record, pool_info, rdata_info, ttl):\n rdata = []\n rdata_info_list = []\n for rr in rdata_info:\n rdata.append(rr)\n rdata_info_list.append(rdata_info[rr])\n profile = {\"@context\": \"http://schemas.ultradns.com/TCPool.jsonschema\"}\n for p in pool_in... | class RestApiClient:
def __init__(self, username, password, use_http=False, host="restapi.ultradns.com"):
"""Initialize a Rest API Client.
Arguments:
username -- The username of the user
password -- The password of the user
Keyword Arguments:
use_http -- For interna... |
ultradns/python_rest_api_client | ultra_rest_client/ultra_rest_client.py | RestApiClient.edit_tc_pool | python | def edit_tc_pool(self, zone_name, owner_name, ttl, pool_info, rdata_info, backup_record):
rrset = self._build_tc_rrset(backup_record, pool_info, rdata_info, ttl)
return self.rest_api_connection.put("/v1/zones/" + zone_name + "/rrsets/A/" + owner_name, json.dumps(rrset)) | Updates an existing TC Pool in the specified zone.
:param zone_name: The zone that contains the RRSet. The trailing dot is optional.
:param owner_name: The owner name for the RRSet.
If no trailing dot is supplied, the owner_name is assumed to be relative (foo).
... | train | https://github.com/ultradns/python_rest_api_client/blob/e4095f28f5cb5e258b768c06ef7cf8b1915aa5ec/ultra_rest_client/ultra_rest_client.py#L685-L702 | [
"def _build_tc_rrset(self, backup_record, pool_info, rdata_info, ttl):\n rdata = []\n rdata_info_list = []\n for rr in rdata_info:\n rdata.append(rr)\n rdata_info_list.append(rdata_info[rr])\n profile = {\"@context\": \"http://schemas.ultradns.com/TCPool.jsonschema\"}\n for p in pool_in... | class RestApiClient:
def __init__(self, username, password, use_http=False, host="restapi.ultradns.com"):
"""Initialize a Rest API Client.
Arguments:
username -- The username of the user
password -- The password of the user
Keyword Arguments:
use_http -- For interna... |
pudo/jsonmapping | jsonmapping/transforms.py | transliterate | python | def transliterate(text):
text = unidecode(six.text_type(text))
text = text.replace('@', 'a')
return text | Utility to properly transliterate text. | train | https://github.com/pudo/jsonmapping/blob/4cf0a20a393ba82e00651c6fd39522a67a0155de/jsonmapping/transforms.py#L11-L15 | null | import re
import six
from hashlib import sha1
from unidecode import unidecode
import normality
COLLAPSE = re.compile(r'\s+')
def coalesce(mapping, bind, values):
""" Given a list of values, return the first non-null value. """
for value in values:
if value is not None:
return [value]
... |
pudo/jsonmapping | jsonmapping/transforms.py | slugify | python | def slugify(mapping, bind, values):
for value in values:
if isinstance(value, six.string_types):
value = transliterate(value)
value = normality.slugify(value)
yield value | Transform all values into URL-capable slugs. | train | https://github.com/pudo/jsonmapping/blob/4cf0a20a393ba82e00651c6fd39522a67a0155de/jsonmapping/transforms.py#L26-L32 | [
"def transliterate(text):\n \"\"\" Utility to properly transliterate text. \"\"\"\n text = unidecode(six.text_type(text))\n text = text.replace('@', 'a')\n return text\n"
] | import re
import six
from hashlib import sha1
from unidecode import unidecode
import normality
COLLAPSE = re.compile(r'\s+')
def transliterate(text):
""" Utility to properly transliterate text. """
text = unidecode(six.text_type(text))
text = text.replace('@', 'a')
return text
def coalesce(mapping... |
pudo/jsonmapping | jsonmapping/transforms.py | latinize | python | def latinize(mapping, bind, values):
for v in values:
if isinstance(v, six.string_types):
v = transliterate(v)
yield v | Transliterate a given string into the latin alphabet. | train | https://github.com/pudo/jsonmapping/blob/4cf0a20a393ba82e00651c6fd39522a67a0155de/jsonmapping/transforms.py#L35-L40 | [
"def transliterate(text):\n \"\"\" Utility to properly transliterate text. \"\"\"\n text = unidecode(six.text_type(text))\n text = text.replace('@', 'a')\n return text\n"
] | import re
import six
from hashlib import sha1
from unidecode import unidecode
import normality
COLLAPSE = re.compile(r'\s+')
def transliterate(text):
""" Utility to properly transliterate text. """
text = unidecode(six.text_type(text))
text = text.replace('@', 'a')
return text
def coalesce(mapping... |
pudo/jsonmapping | jsonmapping/transforms.py | join | python | def join(mapping, bind, values):
return [' '.join([six.text_type(v) for v in values if v is not None])] | Merge all the strings. Put space between them. | train | https://github.com/pudo/jsonmapping/blob/4cf0a20a393ba82e00651c6fd39522a67a0155de/jsonmapping/transforms.py#L43-L45 | null | import re
import six
from hashlib import sha1
from unidecode import unidecode
import normality
COLLAPSE = re.compile(r'\s+')
def transliterate(text):
""" Utility to properly transliterate text. """
text = unidecode(six.text_type(text))
text = text.replace('@', 'a')
return text
def coalesce(mapping... |
pudo/jsonmapping | jsonmapping/transforms.py | str_func | python | def str_func(name):
def func(mapping, bind, values):
for v in values:
if isinstance(v, six.string_types):
v = getattr(v, name)()
yield v
return func | Apply functions like upper(), lower() and strip(). | train | https://github.com/pudo/jsonmapping/blob/4cf0a20a393ba82e00651c6fd39522a67a0155de/jsonmapping/transforms.py#L48-L55 | null | import re
import six
from hashlib import sha1
from unidecode import unidecode
import normality
COLLAPSE = re.compile(r'\s+')
def transliterate(text):
""" Utility to properly transliterate text. """
text = unidecode(six.text_type(text))
text = text.replace('@', 'a')
return text
def coalesce(mapping... |
pudo/jsonmapping | jsonmapping/transforms.py | hash | python | def hash(mapping, bind, values):
for v in values:
if v is None:
continue
if not isinstance(v, six.string_types):
v = six.text_type(v)
yield sha1(v.encode('utf-8')).hexdigest() | Generate a sha1 for each of the given values. | train | https://github.com/pudo/jsonmapping/blob/4cf0a20a393ba82e00651c6fd39522a67a0155de/jsonmapping/transforms.py#L58-L65 | null | import re
import six
from hashlib import sha1
from unidecode import unidecode
import normality
COLLAPSE = re.compile(r'\s+')
def transliterate(text):
""" Utility to properly transliterate text. """
text = unidecode(six.text_type(text))
text = text.replace('@', 'a')
return text
def coalesce(mapping... |
pudo/jsonmapping | jsonmapping/transforms.py | clean | python | def clean(mapping, bind, values):
categories = {'C': ' '}
for value in values:
if isinstance(value, six.string_types):
value = normality.normalize(value, lowercase=False, collapse=True,
decompose=False,
replace_c... | Perform several types of string cleaning for titles etc.. | train | https://github.com/pudo/jsonmapping/blob/4cf0a20a393ba82e00651c6fd39522a67a0155de/jsonmapping/transforms.py#L68-L76 | null | import re
import six
from hashlib import sha1
from unidecode import unidecode
import normality
COLLAPSE = re.compile(r'\s+')
def transliterate(text):
""" Utility to properly transliterate text. """
text = unidecode(six.text_type(text))
text = text.replace('@', 'a')
return text
def coalesce(mapping... |
pudo/jsonmapping | jsonmapping/value.py | extract_value | python | def extract_value(mapping, bind, data):
columns = mapping.get('columns', [mapping.get('column')])
values = [data.get(c) for c in columns]
for transform in mapping.get('transforms', []):
# any added transforms must also be added to the schema.
values = list(TRANSFORMS[transform](mapping, bin... | Given a mapping and JSON schema spec, extract a value from ``data``
and apply certain transformations to normalize the value. | train | https://github.com/pudo/jsonmapping/blob/4cf0a20a393ba82e00651c6fd39522a67a0155de/jsonmapping/value.py#L7-L25 | [
"def convert_value(bind, value):\n \"\"\" Type casting. \"\"\"\n type_name = get_type(bind)\n try:\n return typecast.cast(type_name, value)\n except typecast.ConverterError:\n return value\n",
"def is_empty(value):\n if value is None:\n return True\n if isinstance(value, six... | import six
import typecast
from jsonmapping.transforms import TRANSFORMS
def get_type(bind):
""" Detect the ideal type for the data, either using the explicit type
definition or the format (for date, date-time, not supported by JSON). """
types = bind.types + [bind.schema.get('format')]
for type_nam... |
pudo/jsonmapping | jsonmapping/value.py | get_type | python | def get_type(bind):
types = bind.types + [bind.schema.get('format')]
for type_name in ('date-time', 'date', 'decimal', 'integer', 'boolean',
'number', 'string'):
if type_name in types:
return type_name
return 'string' | Detect the ideal type for the data, either using the explicit type
definition or the format (for date, date-time, not supported by JSON). | train | https://github.com/pudo/jsonmapping/blob/4cf0a20a393ba82e00651c6fd39522a67a0155de/jsonmapping/value.py#L28-L36 | null | import six
import typecast
from jsonmapping.transforms import TRANSFORMS
def extract_value(mapping, bind, data):
""" Given a mapping and JSON schema spec, extract a value from ``data``
and apply certain transformations to normalize the value. """
columns = mapping.get('columns', [mapping.get('column')])
... |
pudo/jsonmapping | jsonmapping/value.py | convert_value | python | def convert_value(bind, value):
type_name = get_type(bind)
try:
return typecast.cast(type_name, value)
except typecast.ConverterError:
return value | Type casting. | train | https://github.com/pudo/jsonmapping/blob/4cf0a20a393ba82e00651c6fd39522a67a0155de/jsonmapping/value.py#L39-L45 | [
"def get_type(bind):\n \"\"\" Detect the ideal type for the data, either using the explicit type\n definition or the format (for date, date-time, not supported by JSON). \"\"\"\n types = bind.types + [bind.schema.get('format')]\n for type_name in ('date-time', 'date', 'decimal', 'integer', 'boolean',\n ... | import six
import typecast
from jsonmapping.transforms import TRANSFORMS
def extract_value(mapping, bind, data):
""" Given a mapping and JSON schema spec, extract a value from ``data``
and apply certain transformations to normalize the value. """
columns = mapping.get('columns', [mapping.get('column')])
... |
pudo/jsonmapping | jsonmapping/elastic.py | generate_schema_mapping | python | def generate_schema_mapping(resolver, schema_uri, depth=1):
visitor = SchemaVisitor({'$ref': schema_uri}, resolver)
return _generate_schema_mapping(visitor, set(), depth) | Try and recursively iterate a JSON schema and to generate an ES mapping
that encasulates it. | train | https://github.com/pudo/jsonmapping/blob/4cf0a20a393ba82e00651c6fd39522a67a0155de/jsonmapping/elastic.py#L6-L10 | [
"def _generate_schema_mapping(visitor, path, depth):\n if visitor.is_object:\n mapping = {\n 'type': 'nested',\n '_id': {'path': 'id'},\n 'properties': {\n '$schema': {'type': 'string', 'index': 'not_analyzed'},\n 'id': {'type': 'string', 'ind... | """ These are utility functions used by the OCCRP datamapper to generate a
matching ElasticSearch schema, given a JSON Schema descriptor. """
from jsonmapping.visitor import SchemaVisitor
def _generator_field_mapping(visitor):
type_name = 'string'
if 'number' in visitor.types:
type_name = 'float'
... |
pudo/jsonmapping | jsonmapping/util.py | validate_mapping | python | def validate_mapping(mapping):
file_path = os.path.join(os.path.dirname(__file__),
'schemas', 'mapping.json')
with open(file_path, 'r') as fh:
validator = Draft4Validator(json.load(fh))
validator.validate(mapping)
return mapping | Validate a mapping configuration file against the relevant schema. | train | https://github.com/pudo/jsonmapping/blob/4cf0a20a393ba82e00651c6fd39522a67a0155de/jsonmapping/util.py#L7-L14 | null | import os
import json
from jsonschema import Draft4Validator
|
pudo/jsonmapping | jsonmapping/mapper.py | Mapper.apply | python | def apply(self, data):
if self.visitor.is_object:
obj = {}
if self.visitor.parent is None:
obj['$schema'] = self.visitor.path
obj_empty = True
for child in self.children:
empty, value = child.apply(data)
if empty and... | Apply the given mapping to ``data``, recursively. The return type
is a tuple of a boolean and the resulting data element. The boolean
indicates whether any values were mapped in the child nodes of the
mapping. It is used to skip optional branches of the object graph. | train | https://github.com/pudo/jsonmapping/blob/4cf0a20a393ba82e00651c6fd39522a67a0155de/jsonmapping/mapper.py#L52-L79 | [
"def extract_value(mapping, bind, data):\n \"\"\" Given a mapping and JSON schema spec, extract a value from ``data``\n and apply certain transformations to normalize the value. \"\"\"\n columns = mapping.get('columns', [mapping.get('column')])\n values = [data.get(c) for c in columns]\n\n for transf... | class Mapper(object):
""" Given a JSON-specified mapping, this class will recursively transform
a flat data structure (e.g. a CSV file or database table) into a nested
JSON structure as specified by the JSON schema associated with the given
mapping. """
def __init__(self, mapping, resolver, visitor... |
pudo/jsonmapping | jsonmapping/mapper.py | Mapper.apply_iter | python | def apply_iter(cls, rows, mapping, resolver, scope=None):
mapper = cls(mapping, resolver, scope=scope)
for row in rows:
_, data = mapper.apply(row)
yield data | Given an iterable ``rows`` that yield data records, and a
``mapping`` which is to be applied to them, return a tuple of
``data`` (the generated object graph) and ``err``, a validation
exception if the resulting data did not match the expected schema. | train | https://github.com/pudo/jsonmapping/blob/4cf0a20a393ba82e00651c6fd39522a67a0155de/jsonmapping/mapper.py#L82-L90 | [
"def apply(self, data):\n \"\"\" Apply the given mapping to ``data``, recursively. The return type\n is a tuple of a boolean and the resulting data element. The boolean\n indicates whether any values were mapped in the child nodes of the\n mapping. It is used to skip optional branches of the object grap... | class Mapper(object):
""" Given a JSON-specified mapping, this class will recursively transform
a flat data structure (e.g. a CSV file or database table) into a nested
JSON structure as specified by the JSON schema associated with the given
mapping. """
def __init__(self, mapping, resolver, visitor... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.