text_prompt
stringlengths
157
13.1k
code_prompt
stringlengths
7
19.8k
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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'] server_port = self.options['port'] honeypot_id = self.options['honeypot_id'] session = self.create_session(server_host, server_port, honeypot_id) self.s...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _get_links(self, response): """ Parses the response text and returns all the links in it. :param response: The Response object. """
html_text = response.text.encode('utf-8') doc = document_fromstring(html_text) links = [] for e in doc.cssselect('a'): links.append(e.get('href'))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def bootstrap(server_workdir, drone_workdir): """Bootstraps localhost configurations for a Beeswarm server and a honeypot. :param server_workdir: Output director...
root_logger = logging.getLogger() root_logger.setLevel(logging.DEBUG) formatter = logging.Formatter('%(asctime)-15s (%(name)s) %(message)s') console_log = logging.StreamHandler() console_log.setLevel(logging.INFO) console_log.setFormatter(formatter) root_logger.addHandler(console_log) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def database_exists(url): """Check if a database exists. :param url: A SQLAlchemy engine URL. Performs backend-specific testing to quickly determine if a databas...
url = copy(make_url(url)) database = url.database if url.drivername.startswith('postgresql'): url.database = 'template1' else: url.database = None engine = sa.create_engine(url) if engine.dialect.name == 'postgresql': text = "SELECT 1 FROM pg_database WHERE datname='%...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 ...
public_keys_dir = os.path.join(work_dir, 'certificates', 'public_keys') secret_keys_dir = os.path.join(work_dir, 'certificates', 'private_keys') # start and configure auth worker auth = IOLoopAuthenticator() auth.start() auth.allow('127.0.0.1') auth.configure_cu...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def start(self): """ Starts the BeeSwarm server. """
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') cert_file = os.path.join(self.work_dir, 'server.crt')...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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_time
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def start(self): """ Launches a new Telnet client session on the server taken from the `self.options` dict. This session always fails. :param my_ip: IP of this C...
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_port, honeypot_id) self.sessions[session.id] = session logger...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create_session(self, server_host, server_port, honeypot_id): """ Creates a new session. :param server_host: IP address of the server :param server_port: Serv...
protocol = self.__class__.__name__.lower() session = BaitSession(protocol, server_host, server_port, honeypot_id) self.sessions[session.id] = session return session
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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'] server_port = self.options['port'] honeypot_id = self.options['honeypot_id'] command_limit = random.randint(6, 11) session = self.create_session(server_h...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sense(self): """ Launches a few "sensing" commands such as 'ls', or 'pwd' and updates the current bait state. """
cmd_name = random.choice(self.senses) command = getattr(self, cmd_name) self.state['last_command'] = cmd_name command()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def decide(self): """ Decides the next command to be launched based on the current state. :return: Tuple containing the next command name, and it's parameters. "...
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_command_name == 'cwd': param = random.choice(self.state['dir_list']) re...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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: command()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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_file)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cwd(self, newdir): """ Send the FTP CWD command :param newdir: Directory to change to """
logger.debug('Sending FTP cwd command. New Workding Directory: {}'.format(newdir)) self.client.cwd(newdir) self.state['current_dir'] = self.client.pwd()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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. :p...
res = list_line.split(' ', 8) if res[0].startswith('-'): self.state['file_list'].append(res[-1]) if res[0].startswith('d'): self.state['dir_list'].append(res[-1])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def start(self): """ Starts sending client bait to the configured Honeypot. """
logger.info('Starting client.') self.dispatcher_greenlets = [] for _, entry in self.config['baits'].items(): for b in clientbase.ClientBase.__subclasses__(): bait_name = b.__name__.lower() # if the bait has a entry in the config we consider the bait...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def start(self): """ Launches a new POP3 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'] server_port = self.options['port'] honeypot_id = self.options['honeypot_id'] session = self.create_session(server_host, server_port, honeypot_id) try: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 wit...
db_session = db_session min_datetime = session.timestamp - timedelta(seconds=timediff) max_datetime = session.timestamp + timedelta(seconds=timediff) # default return value match = None classification = db_session.query(Classification).filter( Classification....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _classify_malicious_sessions(self): """ Will classify all unclassified sessions as malicious activity. :param delay_seconds: no sessions newer than (now - de...
min_datetime = datetime.utcnow() - timedelta(seconds=self.delay_seconds) db_session = database_setup.get_session() # find and process bait sessions that did not get classified during # persistence. bait_sessions = db_session.query(BaitSession).options(joinedload(BaitSession.au...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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'] server_port = self.options['port'] honeypot_id = self.options['honeypot_id'] session = self.create_session(server_host, server_port, honeypot_id) self.s...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def connect_login(self): """ Try to login to the Remote SSH Server. :return: Response text on successful login :raise: `AuthenticationFailed` on unsuccessful log...
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) # Let the server take some time to get ready. while not self.comm_chan.recv_ready(...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def list2dict(list_of_options): """Transforms a list of 2 element tuples to a dictionary"""
d = {} for key, value in list_of_options: d[key] = value return d
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 characters from the # fullmode (defined above) and mode bits from the stat() system call. mode += ((st.st_mode >> (8 - i)) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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: logger.info('Drone has not been configured, awaiting configuration ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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'] server_port = self.options['port'] honeypot_id = self.options['honeypot_id'] session = self.create_session(server_host, server_port, honeypot_id) logge...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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] from_addr = mail.get_from() to_addr = mail['To'] mail_body = mail.get_payload() if not from_addr or not to_addr: continue ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def connect(self): """ Connect to the SMTP server. """
# TODO: local_hostname should be configurable self.client = smtplib.SMTP(self.options['server'], self.options['port'], local_hostname='local.domain', timeout=15)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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, dict): item = _asciify_dict(item) ret.a...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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 = _remove_accents(value) value = value.encode('utf-8') ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def write_human(self, buffer_): """ Emulates human typing speed """
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) self.sock.sendall(char) time.sleep(delta / 1000.0)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def start(self): """ Launches a new Telnet client session on the server taken from the `self.options` dict. :param my_ip: IP of this Client itself """
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.randint(6, 11) session = self.create_session(server_hos...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def connect(self): """ Open a new telnet session on the remote server. """
self.client = BaitTelnetClient(self.options['server'], self.options['port']) self.client.set_option_negotiation_callback(self.process_options)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def login(self, login, password): """ Login to the remote telnet server. :param login: Username to use for logging in :param password: Password to use for loggin...
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) if not current_data.endswith('$ '): raise InvalidLogin
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def logout(self): """ Logout from the remote server. """
self.client.write('exit\r\n') self.client.read_all() self.client.close()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sense(self): """ Launch a command in the 'senses' List, and update the current state."""
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 predefined ones opts = 'asnrvmpio' start = random.randint(0, len(o...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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: param = random.choice(self.state['dir_list']) except IndexError: next_command_name = 'ls' elif next_com...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def mutate_json_record(self, json_record): """Override it to convert fields of `json_record` to needed types. Default implementation converts `datetime` to strin...
for attr_name in json_record: attr = json_record[attr_name] if isinstance(attr, datetime): json_record[attr_name] = attr.isoformat() return json_record
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run(self): """ Listen to the stream and send events to the client. """
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.is_set(): try: if channel.exit_s...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def query(self, term): """ Run a query. :arg str term: The query term to run. :Returns: A list of results as :class:`pygerrit.models.Change` objects. :Raises: `V...
results = [] command = ["query", "--current-patch-set", "--all-approvals", "--format JSON", "--commit-message"] if not isinstance(term, basestring): raise ValueError("term must be a string") command.append(escape_string(term)) result = self._ssh_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def start_event_stream(self): """ Start streaming events from `gerrit stream-events`. """
if not self._stream: self._stream = GerritStream(self, ssh_client=self._ssh_client) self._stream.start()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def stop_event_stream(self): """ Stop streaming events from `gerrit stream-events`."""
if self._stream: self._stream.stop() self._stream.join() self._stream = None with self._events.mutex: self._events.queue.clear()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_event(self, block=True, timeout=None): """ Get the next event from the queue. :arg boolean block: Set to True to block if no event is available. :arg sec...
try: return self._events.get(block, timeout) except Empty: return None
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def put_event(self, data): """ Create event from `data` and add it to the queue. :arg json data: The JSON data from which to create the event. :Raises: :class:`p...
try: event = self._factory.create(data) self._events.put(event) except Full: raise GerritError("Unable to add event: queue is full")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _extract_version(version_string, pattern): """ Extract the version from `version_string` using `pattern`. Return the version as a string, with leading/traili...
if version_string: match = pattern.match(version_string.strip()) if match: return match.group(1) return ""
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _configure(self): """ Configure the ssh parameters from the config file. """
configfile = expanduser("~/.ssh/config") if not isfile(configfile): raise GerritError("ssh config file '%s' does not exist" % configfile) config = SSHConfig() config.parse(open(configfile)) data = config.lookup(self.hostname) if...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _do_connect(self): """ Connect to the remote. """
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, username=self.username, key_filename=self.ke...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _connect(self): """ Connect to the remote if not already connected. """
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(): self._do_connect() if self...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_remote_version(self): """ Return the version of the remote Gerrit server. """
if self.remote_version is None: result = self.run_gerrit_command("version") version_string = result.stdout.read() pattern = re.compile(r'^gerrit version (.*)$') self.remote_version = _extract_version(version_string, pattern) return self.remote_version
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def register(cls, name): """ Decorator to register the event identified by `name`. Return the decorated class. Raise GerritError if the event is already register...
def decorate(klazz): """ Decorator. """ if name in cls._events: raise GerritError("Duplicate event: %s" % name) cls._events[name] = [klazz.__module__, klazz.__name__] klazz.name = name return klazz return decorate
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def create(cls, data): """ Create a new event instance. Return an instance of the `GerritEvent` subclass after converting `data` to json. Raise GerritError if js...
try: json_data = json.loads(data) except ValueError as err: logging.debug("Failed to load json data: %s: [%s]", str(err), data) json_data = json.loads(ErrorEvent.error_json(err)) if "type" not in json_data: raise GerritError("`type` not in json_d...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def put(self, endpoint, **kwargs): """ Send HTTP PUT to the endpoint. :arg str endpoint: The endpoint to send to. :returns: JSON decoded result. :raises: request...
kwargs.update(self.kwargs.copy()) if "data" in kwargs: kwargs["headers"].update( {"Content-Type": "application/json;charset=UTF-8"}) response = requests.put(self.make_url(endpoint), **kwargs) return _decode_response(response)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def delete(self, endpoint, **kwargs): """ Send HTTP DELETE to the endpoint. :arg str endpoint: The endpoint to send to. :returns: JSON decoded result. :raises: r...
kwargs.update(self.kwargs.copy()) response = requests.delete(self.make_url(endpoint), **kwargs) return _decode_response(response)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def review(self, change_id, revision, review): """ Submit a review. :arg str change_id: The change ID. :arg str revision: The revision. :arg str review: The revi...
endpoint = "changes/%s/revisions/%s/review" % (change_id, revision) self.post(endpoint, data=str(review))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def add_comments(self, comments): """ Add inline comments. :arg dict comments: Comments to add. Usage:: add_comments([{'filename': 'Makefile', 'line': 10, 'messa...
for comment in comments: if 'filename' and 'message' in comment.keys(): msg = {} if 'range' in comment.keys(): msg = {"range": comment['range'], "message": comment['message']} elif 'line' in comment.keys(...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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._loop.run_until_complete( self._protoc...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: 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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _float_to_bits(value, lower=-90.0, middle=0.0, upper=90.0, length=15): """Convert a float to a list of GeoHash bits."""
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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _geohash_to_bits(value): """Convert a GeoHash to a list of GeoHash bits."""
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
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _bits_to_geohash(value): """Convert a list of GeoHash bits to a GeoHash."""
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 count,bit in enumerate(i[::-1])]) ret.append(BASE32MAPR[total]) # Joi...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def adjacent(geohash, direction): """Return the adjacent geohash for a given 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 geohash: %s"%geohash neighbor = { 'n': [ 'p0r21436x8zb9dcf5h7kjnmqesgutwvy', 'bc01fg45238967deuvhjy...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def neighbors(geohash): """Return all neighboring geohashes."""
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'), 'w'), 'w': adjacent(geohash, 'w'), 'nw': adjacent(adjace...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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) self._init_run_conf(run_conf)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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(self, func)): self._cancel_functions.append...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def handle_cancel(self, **kwargs): '''Cancelling a run. ''' for func in self._cancel_functions: f_args = getargspec(func)[0] f_kwargs = {key: kwargs[key] for key in f_args if key in kwargs} func(**f_kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
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...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def select_hits_from_cluster_info(input_file_hits, output_file_hits, cluster_size_condition, n_cluster_condition, chunk_size=4000000): ''' Takes a hit table and stores only selected hits into a new table. The selection is done on an event base and events are selected if they have a certain number of cluster or clus...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def histogram_cluster_table(analyzed_data_file, output_file, chunk_size=10000000): '''Reads in the cluster info table in chunks and histograms the seed pixels into one occupancy array. The 3rd dimension of the occupancy array is the number of different scan parameters used Parameters ---------- ana...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def analyze_hits_per_scan_parameter(analyze_data, scan_parameters=None, chunk_size=50000): '''Takes the hit table and analyzes the hits per scan parameter Parameters ---------- analyze_data : analysis.analyze_raw_data.AnalyzeRawData object with an opened hit file (AnalyzeRawData.out_file_h5) or a f...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def reset_bunch_counter(self): '''Resetting Bunch Counter ''' logging.info('Resetting Bunch Counter') commands = [] commands.extend(self.register.get_commands("RunMode")) commands.extend(self.register.get_commands("BCR")) self.send_commands(commands) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def generate_threshold_mask(hist): '''Masking array elements when equal 0.0 or greater than 10 times the median Parameters ---------- hist : array_like Input data. Returns ------- masked array Returns copy of the array with masked elements. ''' masked_array = np.ma....
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def get_ranges_from_array(arr, append_last=True): '''Takes an array and calculates ranges [start, stop[. The last range end is none to keep the same length. Parameters ---------- arr : array like append_last: bool If True, append item with a pair of last array item and None. Returns ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def in1d_sorted(ar1, ar2): """ Does the same than np.in1d but uses the fact that ar1 and ar2 are sorted. Is therefore much faster. """
if ar1.shape[0] == 0 or ar2.shape[0] == 0: # check for empty arrays to avoid crash return [] inds = ar2.searchsorted(ar1) inds[inds == len(ar2)] = 0 return ar2[inds] == ar1
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_parameter_value_from_file_names(files, parameters=None, unique=False, sort=True): """ Takes a list of files, searches for the parameter name in the file ...
# unique=False logging.debug('Get the parameter: ' + str(parameters) + ' values from the file names of ' + str(len(files)) + ' files') files_dict = collections.OrderedDict() if parameters is None: # special case, no parameter defined return files_dict if isinstance(parameters, basestring):...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_data_file_names_from_scan_base(scan_base, filter_str=['_analyzed.h5', '_interpreted.h5', '_cut.h5', '_result.h5', '_hists.h5'], sort_by_time=True, meta_da...
data_files = [] if scan_base is None: return data_files if isinstance(scan_base, basestring): scan_base = [scan_base] for scan_base_str in scan_base: if '.h5' == os.path.splitext(scan_base_str)[1]: data_files.append(scan_base_str) else: data_files...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def get_parameter_from_files(files, parameters=None, unique=False, sort=True): ''' Takes a list of files, searches for the parameter name in the file name and in the file. Returns a ordered dict with the file name in the first dimension and the corresponding parameter values in the second. If a scan paramet...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def check_parameter_similarity(files_dict): """ Checks if the parameter names of all files are similar. Takes the dictionary from get_parameter_from_files output...
try: parameter_names = files_dict.itervalues().next().keys() # get the parameter names of the first file, to check if these are the same in the other files except AttributeError: # if there is no parameter at all if any(i is not None for i in files_dict.itervalues()): # check if there is als...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def combine_meta_data(files_dict, meta_data_v2=True): """ Takes the dict of hdf5 files and combines their meta data tables into one new numpy record array. Param...
if len(files_dict) > 10: logging.info("Combine the meta data from %d files", len(files_dict)) # determine total length needed for the new combined array, thats the fastest way to combine arrays total_length = 0 # the total length of the new table for file_name in files_dict.iterkeys(): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reduce_sorted_to_intersect(ar1, ar2): """ Takes two sorted arrays and return the intersection ar1 in ar2, ar2 in ar1. Parameters ar1 : (M,) array_like Input ...
# Ravel both arrays, behavior for the first array could be different ar1 = np.asarray(ar1).ravel() ar2 = np.asarray(ar2).ravel() # get min max values of the arrays ar1_biggest_value = ar1[-1] ar1_smallest_value = ar1[0] ar2_biggest_value = ar2[-1] ar2_smallest_value = ar2[0] if ar...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def get_not_unique_values(array): '''Returns the values that appear at least twice in array. Parameters ---------- array : array like Returns ------- numpy.array ''' s = np.sort(array, axis=None) s = s[s[1:] == s[:-1]] return np.unique(s)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def get_meta_data_index_at_scan_parameter(meta_data_array, scan_parameter_name): '''Takes the analyzed meta_data table and returns the indices where the scan parameter changes Parameters ---------- meta_data_array : numpy.recordarray scan_parameter_name : string Returns ------- numpy.n...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def get_hits_in_events(hits_array, events, assume_sorted=True, condition=None): '''Selects the hits that occurred in events and optional selection criterion. If a event range can be defined use the get_data_in_event_range function. It is much faster. Parameters ---------- hits_array : numpy.arr...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def get_hits_of_scan_parameter(input_file_hits, scan_parameters=None, try_speedup=False, chunk_size=10000000): '''Takes the hit table of a hdf5 file and returns hits in chunks for each unique combination of scan_parameters. Yields the hits in chunks, since they usually do not fit into memory. Parameters ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def write_hits_in_events(hit_table_in, hit_table_out, events, start_hit_word=0, chunk_size=5000000, condition=None): '''Selects the hits that occurred in events and writes them to a pytable. This function reduces the in RAM operations and has to be used if the get_hits_in_events function raises a memory error. ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def write_hits_in_event_range(hit_table_in, hit_table_out, event_start=None, event_stop=None, start_hit_word=0, chunk_size=5000000, condition=None): '''Selects the hits that occurred in given event range [event_start, event_stop[ and write them to a pytable. This function reduces the in RAM operations and ha...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def get_events_with_n_cluster(event_number, condition='n_cluster==1'): '''Selects the events with a certain number of cluster. Parameters ---------- event_number : numpy.array Returns ------- numpy.array ''' logging.debug("Calculate events with clusters where " + condition) n_...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def get_events_with_cluster_size(event_number, cluster_size, condition='cluster_size==1'): '''Selects the events with cluster of a given cluster size. Parameters ---------- event_number : numpy.array cluster_size : numpy.array condition : string Returns ------- numpy.array ''' ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def get_events_with_error_code(event_number, event_status, select_mask=0b1111111111111111, condition=0b0000000000000000): '''Selects the events with a certain error code. Parameters ---------- event_number : numpy.array event_status : numpy.array select_mask : int The mask that selects ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def get_scan_parameter(meta_data_array, unique=True): '''Takes the numpy meta data array and returns the different scan parameter settings and the name aligned in a dictionary Parameters ---------- meta_data_array : numpy.ndarray unique: boolean If true only unique values for each scan para...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def get_unique_scan_parameter_combinations(meta_data_array, scan_parameters=None, scan_parameter_columns_only=False): '''Takes the numpy meta data array and returns the first rows with unique combinations of different scan parameter values for selected scan parameters. If selected columns only is true, the ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def select_good_pixel_region(hits, col_span, row_span, min_cut_threshold=0.2, max_cut_threshold=2.0): '''Takes the hit array and masks all pixels with a certain occupancy. Parameters ---------- hits : array like If dim > 2 the additional dimensions are summed up. min_cut_threshold : float ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def get_hit_rate_correction(gdacs, calibration_gdacs, cluster_size_histogram): '''Calculates a correction factor for single hit clusters at the given GDACs from the cluster_size_histogram via cubic interpolation. Parameters ---------- gdacs : array like The GDAC settings where the threshold sho...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def get_mean_threshold_from_calibration(gdac, mean_threshold_calibration): '''Calculates the mean threshold from the threshold calibration at the given gdac settings. If the given gdac value was not used during caluibration the value is determined by interpolation. Parameters ---------- gdacs : arr...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def get_pixel_thresholds_from_calibration_array(gdacs, calibration_gdacs, threshold_calibration_array, bounds_error=True): '''Calculates the threshold for all pixels in threshold_calibration_array at the given GDAC settings via linear interpolation. The GDAC settings used during calibration have to be given. P...