output stringlengths 1 928k | instruction stringlengths 7 928k | system stringlengths 0 104k |
|---|---|---|
Sets up the database schema and adds defaults. | Can you generate the documentation for the following Python 3 function
def setup_db(connection_string):
global DB_Session, engine
new_database = False
if connection_string == 'sqlite://' or not database_exists(connection_string):
new_database = True
engine = create_engine(connection_string, conn... | You are a Python code generator, capable of creating scripts from specifications. |
def start_pty_request(self, channel, term, modes):
"""Start a PTY - intended to run it a (green)thread."""
request = self.dummy_request()
request._sock = channel
request.modes = modes
request.term = term
request.username = self.username
# This should block until ... | How would you implement a function in Python 3 that
starts a PTY - intended to run it a ( green ) thread. | As a Python code analyst, you investigate and solve complex coding mysteries |
Check if our Honeypot time is consistent and not too far off
. | Explain what the following Python 3 code does
def check_time(self):
poll = self.config['timecheck']['poll']
ntp_poll = self.config['timecheck']['ntp_pool']
while True:
clnt = ntplib.NTPClient()
try:
response = clnt.request(ntp_poll, version=3)
... | As a Python code analyst, you investigate and solve complex coding mysteries |
Stops all services and greenlets | Can you generate the documentation for the following Python 3 function
def stop(self):
for s in self._servers:
s.stop()
for g in self._server_greenlets:
g.kill()
logger.info('All workers stopped.') | As a Python code composer, you craft elegant and concise scripts. |
def prepare_environment(work_dir):
"""
Performs a few maintenance tasks before the Honeypot is run. Copies the data directory,
and the config file to the cwd. The config file copied here is overwritten if
the __init__ method is called with a configuration URL.
:param... | Can you write a function in Python 3 where it
prepares the environment for the Honeypot. | You are a Python code generator, capable of creating scripts from specifications. |
def start(self):
"""
Launches a new HTTP client session on the server taken from the `self.options` dict.
:param my_ip: IP of this Client itself
"""
username = self.options['username']
password = self.options['password']
server_host = self.options['server']
... | Create a Python 3 function for
launching a new HTTP client session on the server taken from the self. options dict. | You are a Python code generator, capable of creating scripts from specifications. |
Parses the response text and returns all the links in it. | Here you have a function in Python 3, explain what it does
def _get_links(self, response):
html_text = response.text.encode('utf-8')
doc = document_fromstring(html_text)
links = []
for e in doc.cssselect('a'):
links.append(e.get('href')) | You are a Python code architect, reviewing and designing scalable and efficient code |
def bootstrap(server_workdir, drone_workdir):
"""Bootstraps localhost configurations for a Beeswarm server and a honeypot.
:param server_workdir: Output directory for the server configuration file.
:param drone_workdir: Output directory for the drone configuration file.
"""
root_logger = logging.ge... | Create a Python 3 function to
bootstrap the server and a honeypot. | As a Python code analyst, you investigate and solve complex coding mysteries |
def database_exists(url):
"""Check if a database exists.
:param url: A SQLAlchemy engine URL.
Performs backend-specific testing to quickly determine if a database
exists on the server. ::
database_exists('postgres://postgres@localhost/name') #=> False
create_database('postgres://post... | Implement a Python 3 function for
checking if a database exists on the server. | You are a Python code analyst, evaluating scripts for potential improvements. |
def message_proxy(self, work_dir):
"""
drone_data_inboud is for data comming from drones
drone_data_outbound is for commands to the drones, topic must either be a drone ID or all for sending
a broadcast message to all drones
"""
public_keys_dir = os.... | Can you create a Python 3 function that
creates a socket that connects to the drones and connects it to the messages. | You are a Python code analyst, evaluating scripts for potential improvements. |
Starts the BeeSwarm server. | Make a summary of the following Python 3 code
def start(self):
self.started = True
if self.app:
web_port = self.config['network']['web_port']
logger.info('Starting server listening on port {0}'.format(web_port))
key_file = os.path.join(self.work_dir, 'server.key')
... | You are a Python code architect, reviewing and designing scalable and efficient code |
def get_config(self, configfile):
"""
Loads the configuration from the JSON file, and returns it.
:param configfile: Path to the configuration file
"""
with open(configfile) as config_file:
config = json.load(config_file)
return config | Write a Python 3 script to
load the configuration from the JSON file and returns it. | You are a Python code analyst, evaluating scripts for potential improvements. |
def time_in_range(self):
"""Return true if current time is in the active range"""
curr = datetime.datetime.now().time()
if self.start_time <= self.end_time:
return self.start_time <= curr <= self.end_time
else:
return self.start_time <= curr or curr <= self.end_ti... | Write a Python 3 script to
return true if current time is in the active range | As a Python code composer, you craft elegant and concise scripts. |
Launches a new Telnet client session on the server taken from the self. options dict. | Here you have a function in Python 3, explain what it does
def start(self):
password = self.options['password']
server_host = self.options['server']
server_port = self.options['port']
honeypot_id = self.options['honeypot_id']
session = self.create_session(server_host, server_por... | As a Python code analyst, you investigate and solve complex coding mysteries |
Creates a new session. | Make a summary of the following Python 3 code
def create_session(self, server_host, server_port, honeypot_id):
protocol = self.__class__.__name__.lower()
session = BaitSession(protocol, server_host, server_port, honeypot_id)
self.sessions[session.id] = session
return session | As a Python code composer, you craft elegant and concise scripts. |
def start(self):
"""
Launches a new FTP client session on the server taken from the `self.options` dict.
:param my_ip: IP of this Client itself
"""
username = self.options['username']
password = self.options['password']
server_host = self.options['server']
... | Write a Python 3 function for
launching a new FTP client session on the server taken from the self. options dict. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Launches a few sensing commands such as ls or pwd. | Explain what the following Python 3 code does
def sense(self):
cmd_name = random.choice(self.senses)
command = getattr(self, cmd_name)
self.state['last_command'] = cmd_name
command() | As a python code expert, you are capable of creating scripts from specifications. |
Decides the next command to be launched based on the current state. | Can you generate the documentation for the following Python 3 function
def decide(self):
next_command_name = random.choice(self.COMMAND_MAP[self.state['last_command']])
param = ''
if next_command_name == 'retrieve':
param = random.choice(self.state['file_list'])
elif next_com... | You are a Python code generator, capable of creating scripts from specifications. |
def act(self, cmd_name, param):
"""
Run the command with the parameters.
:param cmd_name: The name of command to run
:param param: Params for the command
"""
command = getattr(self, cmd_name)
if param:
command(param)
else:
comm... | Implement a function in Python 3 to
run the command with the parameters. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def list(self):
"""
Run the FTP LIST command, and update the state.
"""
logger.debug('Sending FTP list command.')
self.state['file_list'] = []
self.state['dir_list'] = []
self.client.retrlines('LIST', self._process_list) | Write a Python 3 function for
sending the LIST command to the server. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def retrieve(self, filename):
"""
Run the FTP RETR command, and download the file
:param filename: Name of the file to download
"""
logger.debug('Sending FTP retr command. Filename: {}'.format(filename))
self.client.retrbinary('RETR {}'.format(filename), self._save_f... | Write a Python 3 script to
run the FTP RETR command and download the file | As a Python code translator, you convert algorithms and pseudocode into Python. |
Send the FTP CWD command to change the current working directory | Can you generate a brief explanation for the following Python 3 code
def cwd(self, newdir):
logger.debug('Sending FTP cwd command. New Workding Directory: {}'.format(newdir))
self.client.cwd(newdir)
self.state['current_dir'] = self.client.pwd() | You are a Python code generator, capable of creating scripts from specifications. |
Processes a line of ls - l output and updates state accordingly. | Here you have a function in Python 3, explain what it does
def _process_list(self, list_line):
# -rw-r--r-- 1 ftp ftp 68 May 09 19:37 testftp.txt
"""
Processes a line of 'ls -l' output, and updates state accordingly.
:param list_line: Line to process
"""
res = list_... | You are a Python code generator, capable of creating scripts from specifications. |
Make sure the form data is in the correct format and the start time is less than end time. | How would you explain what the following Python 3 function does
def validate_time_range(form, field):
string = field.data
try:
begin, end = string.split('-')
begin = begin.strip()
end = end.strip()
begin_hours, begin_min = begin.split(':')
end_hours, end_min = end.split(... | You are a Python code architect, reviewing and designing scalable and efficient code |
Starts sending bait to the configured Honeypot. | Can you generate a brief explanation for the following Python 3 code
def start(self):
logger.info('Starting client.')
self.dispatcher_greenlets = []
for _, entry in self.config['baits'].items():
for b in clientbase.ClientBase.__subclasses__():
bait_name = b.__name__... | As a Python code analyst, you investigate and solve complex coding mysteries |
Launches a new POP3 client session on the server taken from the self. options dict. | Given the following Python 3 function, write the documentation
def start(self):
username = self.options['username']
password = self.options['password']
server_host = self.options['server']
server_port = self.options['port']
honeypot_id = self.options['honeypot_id']
sess... | As a Python code analyst, you investigate and solve complex coding mysteries |
def get_matching_session(self, session, db_session, timediff=5):
"""
Tries to match a session with it's counterpart. For bait session it will try to match it with honeypot sessions
and the other way around.
:param session: session object which will be used as base for query.
:pa... | Write a Python 3 function for
trying to match a session with it s counterpart. | As a Python code analyst, you investigate and solve complex coding mysteries |
def _classify_malicious_sessions(self):
"""
Will classify all unclassified sessions as malicious activity.
:param delay_seconds: no sessions newer than (now - delay_seconds) will be processed.
"""
min_datetime = datetime.utcnow() - timedelta(seconds=self.delay_seconds)
... | Can you implement a function in Python 3 that
classifies all unclassified sessions as malicious activity. | As a Python code composer, you craft elegant and concise scripts. |
def start(self):
"""
Launches a new SSH client session on the server taken from the `self.options` dict.
:param my_ip: IP of this Client itself
"""
username = self.options['username']
password = self.options['password']
server_host = self.options['server']
... | Create a Python 3 function for
launching a new SSH client session on the server taken from the self. options dict. | As a Python code analyst, you investigate and solve complex coding mysteries |
def send_command(self, cmd):
"""
Send a command to the remote SSH server.
:param cmd: The command to send
"""
logger.debug('Sending {0} command.'.format(cmd))
self.comm_chan.sendall(cmd + '\n') | Can you write a function in Python 3 where it
sends a command to the remote SSH server. | You are a Python code architect, reviewing and designing scalable and efficient code |
def get_response(self):
"""
Get the response from the server. *This may not return the full response*
:return: Response data
"""
while not self.comm_chan.recv_ready():
time.sleep(0.5)
return self.comm_chan.recv(2048) | Create a Python 3 function for
getting the response from the server. | As a Python code analyst, you investigate and solve complex coding mysteries |
Connect to the Remote SSH Server and login to the Remote SSH Server. | Given the following Python 3 function, write the documentation
def connect_login(self):
self.client.connect(self.options['server'], self.options['port'], self.options['username'],
self.options['password'])
self.comm_chan = self.client.invoke_shell()
time.sleep(1) # L... | As a Python code composer, you craft elegant and concise scripts. |
Transforms a list of 2 element tuples to a dictionary | Explain what the following Python 3 code does
def list2dict(list_of_options):
d = {}
for key, value in list_of_options:
d[key] = value
return d | As a Python code translator, you convert algorithms and pseudocode into Python. |
def path_to_ls(fn):
""" Converts an absolute path to an entry resembling the output of
the ls command on most UNIX systems."""
st = os.stat(fn)
full_mode = 'rwxrwxrwx'
mode = ''
file_time = ''
d = ''
for i in range(9):
# Incrementally builds up the 9 character string, using c... | Write a Python 3 function for
converting an absolute path to an entry resembling the output of the ls command on most UNIX systems. | As a Python code translator, you convert algorithms and pseudocode into Python. |
def _start_drone(self):
"""
Restarts the drone
"""
with open(self.config_file, 'r') as config_file:
self.config = json.load(config_file, object_hook=asciify)
mode = None
if self.config['general']['mode'] == '' or self.config['general']['mode'] is None:
... | How would you implement a function in Python 3 that
restarts the drone and starts it | As a python code expert, you are capable of creating scripts from specifications. |
Stops the drone and kills the drone_greenlet. | Given the following Python 3 function, write the documentation
def stop(self):
logging.debug('Stopping drone, hang on.')
if self.drone is not None:
self.drone_greenlet.unlink(self.on_exception)
self.drone.stop()
self.drone_greenlet.kill()
self.drone = None... | As a python code expert, you are capable of creating scripts from specifications. |
def start(self):
"""
Launches a new SMTP client session on the server taken from the `self.options` dict.
:param my_ip: IP of this Client itself
"""
username = self.options['username']
password = self.options['password']
server_host = self.options['server']
... | Write a Python 3 function for
launching a new SMTP client session on the server taken from the self. options dict. | As a Python code analyst, you investigate and solve complex coding mysteries |
def get_one_mail(self):
"""
Choose and return a random email from the mail archive.
:return: Tuple containing From Address, To Address and the mail body.
"""
while True:
mail_key = random.choice(self.mailbox.keys())
mail = self.mailbox[mail_key]
... | Write a Python 3 function that can
choose and return a random email from the mail archive. | You are a Python code architect, reviewing and designing scalable and efficient code |
Connect to the SMTP server. | Can you generate the documentation for the following Python 3 function
def connect(self):
# TODO: local_hostname should be configurable
self.client = smtplib.SMTP(self.options['server'], self.options['port'],
local_hostname='local.domain', timeout=15) | You are a Python code generator, capable of creating scripts from specifications. |
The actual service to which the user has connected. | Can you tell what is the following Python 3 function doing
def handle(self):
"The actual service to which the user has connected."
if not self.authentication_ok():
return
if self.DOECHO:
self.writeline(self.WELCOME)
self.session_start()
while self.RUNSHELL... | You are a Python code analyst, evaluating scripts for potential improvements. |
def _asciify_list(data):
""" Ascii-fies list values """
ret = []
for item in data:
if isinstance(item, unicode):
item = _remove_accents(item)
item = item.encode('utf-8')
elif isinstance(item, list):
item = _asciify_list(item)
elif isinstance(item, ... | How would you code a function in Python 3 to
convert list items into Ascii - fies list values | As a Python code translator, you convert algorithms and pseudocode into Python. |
def _asciify_dict(data):
""" Ascii-fies dict keys and values """
ret = {}
for key, value in data.iteritems():
if isinstance(key, unicode):
key = _remove_accents(key)
key = key.encode('utf-8')
# # note new if
if isinstance(value, unicode):
value... | Can you implement a function in Python 3 that
converts dict keys and values into Ascii - fies dict keys and values | As a python code expert, you are capable of creating scripts from specifications. |
Emulates human typing speed | Can you generate the documentation for the following Python 3 function
def write_human(self, buffer_):
if self.IAC in buffer_:
buffer_ = buffer_.replace(self.IAC, self.IAC + self.IAC)
self.msg("send %r", buffer_)
for char in buffer_:
delta = random.gauss(80, 20)
... | As a Python code analyst, you investigate and solve complex coding mysteries |
Launches a new Telnet client session on the server taken from the self. options dict. | Explain what the following Python 3 code does
def start(self):
login = self.options['username']
password = self.options['password']
server_host = self.options['server']
server_port = self.options['port']
honeypot_id = self.options['honeypot_id']
command_limit = random.ra... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Open a new telnet session on the remote server. | Can you generate a brief explanation for the following Python 3 code
def connect(self):
self.client = BaitTelnetClient(self.options['server'], self.options['port'])
self.client.set_option_negotiation_callback(self.process_options) | As a Python code composer, you craft elegant and concise scripts. |
Log in to the remote telnet server. | Explain what the following Python 3 code does
def login(self, login, password):
self.client.read_until('Username: ')
self.client.write(login + '\r\n')
self.client.read_until('Password: ')
self.client.write(password + '\r\n')
current_data = self.client.read_until('$ ', 10)
... | You are a Python code architect, reviewing and designing scalable and efficient code |
def add_auth_attempt(self, auth_type, successful, **kwargs):
"""
:param username:
:param password:
:param auth_type: possible values:
plain: plaintext username/password
:return:
"""
entry = {'timestamp': datetime.utcnow(),
... | Write a Python 3 script to
add an auth attempt to the log. | You are a Python code architect, reviewing and designing scalable and efficient code |
Launch a command in the sense list and update the current state. | Can you generate a brief explanation for the following Python 3 code
def sense(self):
cmd_name = random.choice(self.senses)
param = ''
if cmd_name == 'ls':
if random.randint(0, 1):
param = '-l'
elif cmd_name == 'uname':
# Choose options from prede... | You are a Python code architect, reviewing and designing scalable and efficient code |
def decide(self):
""" Choose the next command to execute, and its parameters, based on the current
state.
"""
next_command_name = random.choice(self.COMMAND_MAP[self.state['last_command']])
param = ''
if next_command_name == 'cd':
try:
par... | How would you code a function in Python 3 to
choose the next command to execute and its parameters based on the current state. | As a Python code composer, you craft elegant and concise scripts. |
def act(self, cmd_name, params=None):
""" Run the specified command with its parameters."""
command = getattr(self, cmd_name)
if params:
command(params)
else:
command() | How would you code a function in Python 3 to
run the specified command with its parameters. | As a Python code analyst, you investigate and solve complex coding mysteries |
def json_record(self, message, extra, record):
"""Prepares a JSON payload which will be logged.
Override this method to change JSON log format.
:param message: Log message, e.g., `logger.info(msg='Sign up')`.
:param extra: Dictionary that was passed as `extra` param
`logger... | Can you implement a function in Python 3 that
prepares a JSON payload which will be logged. | As a Python code analyst, you investigate and solve complex coding mysteries |
def mutate_json_record(self, json_record):
"""Override it to convert fields of `json_record` to needed types.
Default implementation converts `datetime` to string in ISO8601 format.
"""
for attr_name in json_record:
attr = json_record[attr_name]
if isinstance(at... | How would you implement a function in Python 3 that
overrides it to convert fields of json_record to needed types. | As a Python code composer, you craft elegant and concise scripts. |
Listen to the stream and send events to the client. | Explain what the following Python 3 code does
def run(self):
channel = self._ssh_client.get_transport().open_session()
self._channel = channel
channel.exec_command("gerrit stream-events")
stdout = channel.makefile()
stderr = channel.makefile_stderr()
while not self._stop.... | You are a Python code analyst, evaluating scripts for potential improvements. |
Run a command.
:arg str command: The command to run.
:Return: The result as a string.
:Raises: `ValueError` if `command` is not a string. | How would you explain what the following Python 3 function does
def run_command(self, command):
if not isinstance(command, basestring):
raise ValueError("command must be a string")
return self._ssh_client.run_gerrit_command(command) | As a Python code composer, you craft elegant and concise scripts. |
Run a query on the current patch set. | Can you generate a brief explanation for the following Python 3 code
def query(self, term):
results = []
command = ["query", "--current-patch-set", "--all-approvals",
"--format JSON", "--commit-message"]
if not isinstance(term, basestring):
raise ValueError("term ... | You are a Python code architect, reviewing and designing scalable and efficient code |
Start streaming events from gerrit stream - events. | Can you tell what is the following Python 3 function doing
def start_event_stream(self):
if not self._stream:
self._stream = GerritStream(self, ssh_client=self._ssh_client)
self._stream.start() | You are a Python code generator, capable of creating scripts from specifications. |
Stop streaming events from gerrit stream - events. | Here you have a function in Python 3, explain what it does
def stop_event_stream(self):
if self._stream:
self._stream.stop()
self._stream.join()
self._stream = None
with self._events.mutex:
self._events.queue.clear() | As a Python code composer, you craft elegant and concise scripts. |
Get the next event from the queue. | Explain what the following Python 3 code does
def get_event(self, block=True, timeout=None):
try:
return self._events.get(block, timeout)
except Empty:
return None | As a Python code analyst, you investigate and solve complex coding mysteries |
Add an event to the queue. | Given the following Python 3 function, write the documentation
def put_event(self, data):
try:
event = self._factory.create(data)
self._events.put(event)
except Full:
raise GerritError("Unable to add event: queue is full") | You are a Python code architect, reviewing and designing scalable and efficient code |
Extract the version from version_string using pattern. | Can you tell what is the following Python 3 function doing
def _extract_version(version_string, pattern):
if version_string:
match = pattern.match(version_string.strip())
if match:
return match.group(1)
return "" | As a python code expert, you are capable of creating scripts from specifications. |
Configure the ssh parameters from the config file. | Can you generate the documentation for the following Python 3 function
def _configure(self):
configfile = expanduser("~/.ssh/config")
if not isfile(configfile):
raise GerritError("ssh config file '%s' does not exist" %
configfile)
config = SSHConfig()
... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Connect to the remote server. | Can you generate the documentation for the following Python 3 function
def _do_connect(self):
self.load_system_host_keys()
if self.username is None or self.port is None:
self._configure()
try:
self.connect(hostname=self.hostname,
port=self.port,
... | As a python code expert, you are capable of creating scripts from specifications. |
Connect to the remote if not already connected. | Explain what the following Python 3 code does
def _connect(self):
if not self.connected.is_set():
try:
self.lock.acquire()
# Another thread may have connected while we were
# waiting to acquire the lock
if not self.connected.is_set():
... | As a Python code analyst, you investigate and solve complex coding mysteries |
Return the version of the remote Gerrit server. | How would you explain what the following Python 3 function does
def get_remote_version(self):
if self.remote_version is None:
result = self.run_gerrit_command("version")
version_string = result.stdout.read()
pattern = re.compile(r'^gerrit version (.*)$')
self.remo... | As a python code expert, you are capable of creating scripts from specifications. |
Run a gerrit command and return the output as a GerritSSHCommandResult. | How would you explain what the following Python 3 function does
def run_gerrit_command(self, command):
if not isinstance(command, basestring):
raise ValueError("command must be a string")
gerrit_command = "gerrit " + command
# are we sending non-ascii data?
try:
... | You are a Python code analyst, evaluating scripts for potential improvements. |
Decorator to register an event identified by name. | Can you generate the documentation for the following Python 3 function
def register(cls, name):
def decorate(klazz):
""" Decorator. """
if name in cls._events:
raise GerritError("Duplicate event: %s" % name)
cls._events[name] = [klazz.__module__, klazz.__name... | As a Python code composer, you craft elegant and concise scripts. |
def create(cls, data):
""" Create a new event instance.
Return an instance of the `GerritEvent` subclass after converting
`data` to json.
Raise GerritError if json parsed from `data` does not contain a `type`
key.
"""
try:
json_data = json.loads(dat... | How would you code a function in Python 3 to
create a new event instance. | As a python code expert, you are capable of creating scripts from specifications. |
def _decode_response(response):
""" Strip off Gerrit's magic prefix and decode a response.
:returns:
Decoded JSON content as a dict, or raw text if content could not be
decoded as JSON.
:raises:
requests.HTTPError if the response contains an HTTP error status code.
"""
con... | Write a Python 3 function for
stripping off Gerrit s magic prefix and decode a response. | As a Python code analyst, you investigate and solve complex coding mysteries |
def put(self, endpoint, **kwargs):
""" Send HTTP PUT to the endpoint.
:arg str endpoint: The endpoint to send to.
:returns:
JSON decoded result.
:raises:
requests.RequestException on timeout or connection error.
"""
kwargs.update(self.kwargs.co... | Write a Python 3 function that can
send HTTP PUT to the endpoint. | You are a Python code generator, capable of creating scripts from specifications. |
Send HTTP DELETE to the endpoint. | Can you tell what is the following Python 3 function doing
def delete(self, endpoint, **kwargs):
kwargs.update(self.kwargs.copy())
response = requests.delete(self.make_url(endpoint), **kwargs)
return _decode_response(response) | As a Python code analyst, you investigate and solve complex coding mysteries |
Submit a review.
:arg str change_id: The change ID.
:arg str revision: The revision.
:arg str review: The review details as a :class:`GerritReview`.
:returns:
JSON decoded result.
:raises:
requests.RequestException on timeout or connection error. | Given the following Python 3 function, write the documentation
def review(self, change_id, revision, review):
endpoint = "changes/%s/revisions/%s/review" % (change_id, revision)
self.post(endpoint, data=str(review)) | As a Python code composer, you craft elegant and concise scripts. |
def add_comments(self, comments):
""" Add inline comments.
:arg dict comments: Comments to add.
Usage::
add_comments([{'filename': 'Makefile',
'line': 10,
'message': 'inline message'}])
add_comments([{'filename': '... | Write a Python 3 function for
adding inline comments to the comments list. | As a Python code translator, you convert algorithms and pseudocode into Python. |
Called by asyncio when a connection is made. | Can you tell what is the following Python 3 function doing
def connection_made(self, transport):
'''
override asyncio.Protocol
'''
self._connected = True
self.transport = transport
self.remote_ip, self.port = transport.get_extra_info('peername')[:2]
logging.deb... | You are a Python code architect, reviewing and designing scalable and efficient code |
Called when the connection is lost. | Can you generate a brief explanation for the following Python 3 code
def connection_lost(self, exc):
'''
override asyncio.Protocol
'''
self._connected = False
logging.debug(
'Connection lost (address: {} port: {})'
.format(self.remote_ip, self.port))
... | You are a Python code generator, capable of creating scripts from specifications. |
This method is called when data is received from the server. | Can you generate the documentation for the following Python 3 function
def data_received(self, data):
'''
override asyncio.Protocol
'''
self._buffered_data.extend(data)
while self._buffered_data:
size = len(self._buffered_data)
if self._data_package is Non... | As a Python code translator, you convert algorithms and pseudocode into Python. |
Register a new SiriDB Server. | Explain what the following Python 3 code does
def _register_server(self, server, timeout=30):
'''Register a new SiriDB Server.
This method is used by the SiriDB manage tool and should not be used
otherwise. Full access rights are required for this request.
'''
result = self._loo... | As a python code expert, you are capable of creating scripts from specifications. |
def _get_file(self, fn, timeout=30):
'''Request a SiriDB configuration file.
This method is used by the SiriDB manage tool and should not be used
otherwise. Full access rights are required for this request.
'''
msg = FILE_MAP.get(fn, None)
if msg is None:
rai... | Can you implement a function in Python 3 that
requests a SiriDB configuration file. | You are a Python code generator, capable of creating scripts from specifications. |
def _bits_to_float(bits, lower=-90.0, middle=0.0, upper=90.0):
"""Convert GeoHash bits to a float."""
for i in bits:
if i:
lower = middle
else:
upper = middle
middle = (upper + lower) / 2
return middle | Write a Python 3 function that can
convert GeoHash bits to a float. | As a python code expert, you are capable of creating scripts from specifications. |
Convert a float to a list of GeoHash bits. | Explain what the following Python 3 code does
def _float_to_bits(value, lower=-90.0, middle=0.0, upper=90.0, length=15):
ret = []
for i in range(length):
if value >= middle:
lower = middle
ret.append(1)
else:
upper = middle
ret.append(0)
middle = (upper + lower) / 2
return ret | You are a Python code generator, capable of creating scripts from specifications. |
Convert a GeoHash to a list of GeoHash bits. | Here you have a function in Python 3, explain what it does
def _geohash_to_bits(value):
b = map(BASE32MAP.get, value)
ret = []
for i in b:
out = []
for z in range(5):
out.append(i & 0b1)
i = i >> 1
ret += out[::-1]
return ret | As a python code expert, you are capable of creating scripts from specifications. |
Convert a list of GeoHash bits to a GeoHash. | Make a summary of the following Python 3 code
def _bits_to_geohash(value):
ret = []
# Get 5 bits at a time
for i in (value[i:i+5] for i in xrange(0, len(value), 5)):
# Convert binary to integer
# Note: reverse here, the slice above doesn't work quite right in reverse.
total = sum([(bit*2**count) for c... | You are a Python code generator, capable of creating scripts from specifications. |
Decode a geohash. Returns a ( lon lat ) pair. | Explain what the following Python 3 code does
def decode(value):
assert value, "Invalid geohash: %s"%value
# Get the GeoHash bits
bits = _geohash_to_bits(value)
# Unzip the GeoHash bits.
lon = bits[0::2]
lat = bits[1::2]
# Convert to lat/lon
return (
_bits_to_float(lon, lower=-180.0, upper=180.0),
... | You are a Python code architect, reviewing and designing scalable and efficient code |
Encode a ( lon lat ) pair to a GeoHash. | Given the following Python 3 function, write the documentation
def encode(lonlat, length=12):
assert len(lonlat) == 2, "Invalid lon/lat: %s"%lonlat
# Half the length for each component.
length /= 2
lon = _float_to_bits(lonlat[0], lower=-180.0, upper=180.0, length=length*5)
lat = _float_to_bits(lonlat[1], lowe... | As a python code expert, you are capable of creating scripts from specifications. |
Return the adjacent geohash for a given direction. | Can you generate the documentation for the following Python 3 function
def adjacent(geohash, direction):
# Based on an MIT licensed implementation by Chris Veness from:
# http://www.movable-type.co.uk/scripts/geohash.html
assert direction in 'nsew', "Invalid direction: %s"%direction
assert geohash, "Invalid g... | As a Python code analyst, you investigate and solve complex coding mysteries |
Return all neighboring geohashes. | Explain what the following Python 3 code does
def neighbors(geohash):
return {
'n': adjacent(geohash, 'n'),
'ne': adjacent(adjacent(geohash, 'n'), 'e'),
'e': adjacent(geohash, 'e'),
'se': adjacent(adjacent(geohash, 's'), 'e'),
's': adjacent(geohash, 's'),
'sw': adjacent(adjacent(geohash, 's... | You are a Python code generator, capable of creating scripts from specifications. |
A decorator which returns a function immediately return a function of no args which will be processed in another thread. | Can you generate a brief explanation for the following Python 3 code
def thunkify(thread_name=None, daemon=True, default_func=None):
'''Make a function immediately return a function of no args which, when called,
waits for the result, which will start being processed in another thread.
Taken from https://wi... | You are a Python code generator, capable of creating scripts from specifications. |
Decorator function that sets Threading. Event when keyboard interrupt was raised. | Can you generate a brief explanation for the following Python 3 code
def set_event_when_keyboard_interrupt(_lambda):
'''Decorator function that sets Threading.Event() when keyboard interrupt (Ctrl+C) was raised
Parameters
----------
_lambda : function
Lambda function that points to Threading.Ev... | As a python code expert, you are capable of creating scripts from specifications. |
Run name without whitespace
| How would you explain what the following Python 3 function does
def run_id(self):
'''Run name without whitespace
'''
s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', self.__class__.__name__)
return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower() | As a Python code translator, you convert algorithms and pseudocode into Python. |
Return a named tuple containing the current configuration. | Can you generate the documentation for the following Python 3 function
def conf(self):
'''Configuration (namedtuple)
'''
conf = namedtuple('conf', field_names=self._conf.keys())
return conf(**self._conf) | As a python code expert, you are capable of creating scripts from specifications. |
def run_conf(self):
'''Run configuration (namedtuple)
'''
run_conf = namedtuple('run_conf', field_names=self._run_conf.keys())
return run_conf(**self._run_conf) | Write a Python 3 function that can
run configuration of the current session | As a Python code translator, you convert algorithms and pseudocode into Python. |
def default_run_conf(self):
'''Default run configuration (namedtuple)
'''
default_run_conf = namedtuple('default_run_conf', field_names=self._default_run_conf.keys())
return default_run_conf(**self._default_run_conf) | Write a Python 3 script to
default run configuration (namedtuple) | As a Python code composer, you craft elegant and concise scripts. |
Initialize before a new run. | Can you generate a brief explanation for the following Python 3 code
def _init(self, run_conf, run_number=None):
'''Initialization before a new run.
'''
self.stop_run.clear()
self.abort_run.clear()
self._run_status = run_status.running
self._write_run_number(run_number)
... | As a Python code analyst, you investigate and solve complex coding mysteries |
Connect given functions when a run is cancelled. | Here you have a function in Python 3, explain what it does
def connect_cancel(self, functions):
'''Run given functions when a run is cancelled.
'''
self._cancel_functions = []
for func in functions:
if isinstance(func, basestring) and hasattr(self, func) and callable(getattr(... | As a Python code translator, you convert algorithms and pseudocode into Python. |
def stop(self, msg=None):
'''Stopping a run. Control for loops. Gentle stop/abort.
This event should provide a more gentle abort. The run should stop ASAP but the run is still considered complete.
'''
if not self.stop_run.is_set():
if msg:
logging.info('%s%s ... | Write a Python 3 script to
stop a run. Control for loops. Gentle stop and abort. | As a python code expert, you are capable of creating scripts from specifications. |
def abort(self, msg=None):
'''Aborting a run. Control for loops. Immediate stop/abort.
The implementation should stop a run ASAP when this event is set. The run is considered incomplete.
'''
if not self.abort_run.is_set():
if msg:
logging.error('%s%s Aborting... | Can you write a function in Python 3 where it
aborts a run. Control for loops. Immediate stop and abort. | You are a Python code analyst, evaluating scripts for potential improvements. |
def run_run(self, run, conf=None, run_conf=None, use_thread=False, catch_exception=True):
'''Runs a run in another thread. Non-blocking.
Parameters
----------
run : class, object
Run class or object.
run_conf : str, dict, file
Specific configuration for t... | Write a Python 3 script for
running a run in another thread. Non - blocking. | You are a Python code analyst, evaluating scripts for potential improvements. |
def run_primlist(self, primlist, skip_remaining=False):
'''Runs runs from a primlist.
Parameters
----------
primlist : string
Filename of primlist.
skip_remaining : bool
If True, skip remaining runs, if a run does not exit with status FINISHED.
N... | Can you write a function in Python 3 where it
runs runs from a primlist. | As a Python code composer, you craft elegant and concise scripts. |
Analyzes the mean x and y of a beam spot. | Here you have a function in Python 3, explain what it does
def analyze_beam_spot(scan_base, combine_n_readouts=1000, chunk_size=10000000, plot_occupancy_hists=False, output_pdf=None, output_file=None):
''' Determines the mean x and y beam spot position as a function of time. Therefore the data of a fixed number of ... | As a Python code analyst, you investigate and solve complex coding mysteries |
def analyze_event_rate(scan_base, combine_n_readouts=1000, time_line_absolute=True, output_pdf=None, output_file=None):
''' Determines the number of events as a function of time. Therefore the data of a fixed number of read outs are combined ('combine_n_readouts'). The number of events is taken from the meta data i... | Create a Python 3 function for
analyzing the number of events as a function of time. | You are a Python code generator, capable of creating scripts from specifications. |
Analyse the number of cluster per event. | Given the following Python 3 function, write the documentation
def analyse_n_cluster_per_event(scan_base, include_no_cluster=False, time_line_absolute=True, combine_n_readouts=1000, chunk_size=10000000, plot_n_cluster_hists=False, output_pdf=None, output_file=None):
''' Determines the number of cluster per event as... | You are a Python code analyst, evaluating scripts for potential improvements. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.