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 _get_socket(self, sid): """Return the socket object for a given session."""
try: s = self.sockets[sid] except KeyError: raise KeyError('Session not found') if s.closed: del self.sockets[sid] raise KeyError('Session is disconnected') return 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 _ok(self, packets=None, headers=None, b64=False): """Generate a successful HTTP response."""
if packets is not None: if headers is None: headers = [] if b64: headers += [('Content-Type', 'text/plain; charset=UTF-8')] else: headers += [('Content-Type', 'application/octet-stream')] return {'status': '200 OK', 'headers': headers, 'response': payload.Payload(packets=packets).encode(b64)} else: return {'status': '200 OK', 'headers': [('Content-Type', 'text/plain')], 'response': b'OK'}
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _cors_headers(self, environ): """Return the cross-origin-resource-sharing headers."""
if isinstance(self.cors_allowed_origins, six.string_types): if self.cors_allowed_origins == '*': allowed_origins = None else: allowed_origins = [self.cors_allowed_origins] else: allowed_origins = self.cors_allowed_origins if allowed_origins is not None and \ environ.get('HTTP_ORIGIN', '') not in allowed_origins: return [] if 'HTTP_ORIGIN' in environ: headers = [('Access-Control-Allow-Origin', environ['HTTP_ORIGIN'])] else: headers = [('Access-Control-Allow-Origin', '*')] if environ['REQUEST_METHOD'] == 'OPTIONS': headers += [('Access-Control-Allow-Methods', 'OPTIONS, GET, POST')] if 'HTTP_ACCESS_CONTROL_REQUEST_HEADERS' in environ: headers += [('Access-Control-Allow-Headers', environ['HTTP_ACCESS_CONTROL_REQUEST_HEADERS'])] if self.cors_credentials: headers += [('Access-Control-Allow-Credentials', 'true')] return headers
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _gzip(self, response): """Apply gzip compression to a response."""
bytesio = six.BytesIO() with gzip.GzipFile(fileobj=bytesio, mode='w') as gz: gz.write(response) return bytesio.getvalue()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def close(self): """Disconnects uWSGI from the client."""
uwsgi.disconnect() if self._req_ctx is None: # better kill it here in case wait() is not called again self._select_greenlet.kill() self._event.set()
<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(self, msg): """Transmits message either in binary or UTF-8 text mode, depending on its type."""
if isinstance(msg, six.binary_type): method = uwsgi.websocket_send_binary else: method = uwsgi.websocket_send if self._req_ctx is not None: method(msg, request_context=self._req_ctx) else: method(msg)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _decode_received(self, msg): """Returns either bytes or str, depending on message type."""
if not isinstance(msg, six.binary_type): # already decoded - do nothing return msg # only decode from utf-8 if message is not binary data type = six.byte2int(msg[0:1]) if type >= 48: # no binary return msg.decode('utf-8') # binary message, don't try to decode return msg
<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(self, msg): """Queues a message for sending. Real transmission is done in wait method. Sends directly if uWSGI version is new enough."""
if self._req_ctx is not None: self._send(msg) else: self._send_queue.put(msg) self._event.set()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def attach(self, app, engineio_path='engine.io'): """Attach the Engine.IO server to an application."""
engineio_path = engineio_path.strip('/') self._async['create_route'](app, self, '/{}/'.format(engineio_path))
<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_get_request(self, environ, start_response): """Handle a long-polling GET request from the client."""
connections = [ s.strip() for s in environ.get('HTTP_CONNECTION', '').lower().split(',')] transport = environ.get('HTTP_UPGRADE', '').lower() if 'upgrade' in connections and transport in self.upgrade_protocols: self.server.logger.info('%s: Received request to upgrade to %s', self.sid, transport) return getattr(self, '_upgrade_' + transport)(environ, start_response) try: packets = self.poll() except exceptions.QueueEmpty: exc = sys.exc_info() self.close(wait=False) six.reraise(*exc) return packets
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def close(self, wait=True, abort=False): """Close the socket connection."""
if not self.closed and not self.closing: self.closing = True self.server._trigger_event('disconnect', self.sid, run_async=False) if not abort: self.send(packet.Packet(packet.CLOSE)) self.closed = True self.queue.put(None) if wait: self.queue.join()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: async def connect(self, url, headers={}, transports=None, engineio_path='engine.io'): """Connect to an Engine.IO server. :param url: The URL of the Engine.IO server. It can include custom query string parameters if required by the server. :param headers: A dictionary with custom headers to send with the connection request. :param transports: The list of allowed transports. Valid transports are ``'polling'`` and ``'websocket'``. If not given, the polling transport is connected first, then an upgrade to websocket is attempted. :param engineio_path: The endpoint where the Engine.IO server is installed. The default value is appropriate for most cases. Note: this method is a coroutine. Example usage:: eio = engineio.Client() await eio.connect('http://localhost:5000') """
if self.state != 'disconnected': raise ValueError('Client is not in a disconnected state') valid_transports = ['polling', 'websocket'] if transports is not None: if isinstance(transports, six.text_type): transports = [transports] transports = [transport for transport in transports if transport in valid_transports] if not transports: raise ValueError('No valid transports provided') self.transports = transports or valid_transports self.queue = self.create_queue() return await getattr(self, '_connect_' + self.transports[0])( url, headers, engineio_path)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: async def _connect_polling(self, url, headers, engineio_path): """Establish a long-polling connection to the Engine.IO server."""
if aiohttp is None: # pragma: no cover self.logger.error('aiohttp not installed -- cannot make HTTP ' 'requests!') return self.base_url = self._get_engineio_url(url, engineio_path, 'polling') self.logger.info('Attempting polling connection to ' + self.base_url) r = await self._send_request( 'GET', self.base_url + self._get_url_timestamp(), headers=headers) if r is None: self._reset() raise exceptions.ConnectionError( 'Connection refused by the server') if r.status != 200: raise exceptions.ConnectionError( 'Unexpected status code {} in server response'.format( r.status)) try: p = payload.Payload(encoded_payload=await r.read()) except ValueError: six.raise_from(exceptions.ConnectionError( 'Unexpected response from server'), None) open_packet = p.packets[0] if open_packet.packet_type != packet.OPEN: raise exceptions.ConnectionError( 'OPEN packet not returned by server') self.logger.info( 'Polling connection accepted with ' + str(open_packet.data)) self.sid = open_packet.data['sid'] self.upgrades = open_packet.data['upgrades'] self.ping_interval = open_packet.data['pingInterval'] / 1000.0 self.ping_timeout = open_packet.data['pingTimeout'] / 1000.0 self.current_transport = 'polling' self.base_url += '&sid=' + self.sid self.state = 'connected' client.connected_clients.append(self) await self._trigger_event('connect', run_async=False) for pkt in p.packets[1:]: await self._receive_packet(pkt) if 'websocket' in self.upgrades and 'websocket' in self.transports: # attempt to upgrade to websocket if await self._connect_websocket(url, headers, engineio_path): # upgrade to websocket succeeded, we're done here return self.ping_loop_task = self.start_background_task(self._ping_loop) self.write_loop_task = self.start_background_task(self._write_loop) self.read_loop_task = self.start_background_task( self._read_loop_polling)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: async def _receive_packet(self, pkt): """Handle incoming packets from the server."""
packet_name = packet.packet_names[pkt.packet_type] \ if pkt.packet_type < len(packet.packet_names) else 'UNKNOWN' self.logger.info( 'Received packet %s data %s', packet_name, pkt.data if not isinstance(pkt.data, bytes) else '<binary>') if pkt.packet_type == packet.MESSAGE: await self._trigger_event('message', pkt.data, run_async=True) elif pkt.packet_type == packet.PONG: self.pong_received = True elif pkt.packet_type == packet.NOOP: pass else: self.logger.error('Received unexpected packet of type %s', pkt.packet_type)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: async def _send_packet(self, pkt): """Queue a packet to be sent to the server."""
if self.state != 'connected': return await self.queue.put(pkt) self.logger.info( 'Sending packet %s data %s', packet.packet_names[pkt.packet_type], pkt.data if not isinstance(pkt.data, bytes) else '<binary>')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def encode(self, b64=False): """Encode the payload for transmission."""
encoded_payload = b'' for pkt in self.packets: encoded_packet = pkt.encode(b64=b64) packet_len = len(encoded_packet) if b64: encoded_payload += str(packet_len).encode('utf-8') + b':' + \ encoded_packet else: binary_len = b'' while packet_len != 0: binary_len = six.int2byte(packet_len % 10) + binary_len packet_len = int(packet_len / 10) if not pkt.binary: encoded_payload += b'\0' else: encoded_payload += b'\1' encoded_payload += binary_len + b'\xff' + encoded_packet return encoded_payload
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def decode(self, encoded_payload): """Decode a transmitted payload."""
self.packets = [] while encoded_payload: if six.byte2int(encoded_payload[0:1]) <= 1: packet_len = 0 i = 1 while six.byte2int(encoded_payload[i:i + 1]) != 255: packet_len = packet_len * 10 + six.byte2int( encoded_payload[i:i + 1]) i += 1 self.packets.append(packet.Packet( encoded_packet=encoded_payload[i + 1:i + 1 + packet_len])) else: i = encoded_payload.find(b':') if i == -1: raise ValueError('invalid payload') # extracting the packet out of the payload is extremely # inefficient, because the payload needs to be treated as # binary, but the non-binary packets have to be parsed as # unicode. Luckily this complication only applies to long # polling, as the websocket transport sends packets # individually wrapped. packet_len = int(encoded_payload[0:i]) pkt = encoded_payload.decode('utf-8', errors='ignore')[ i + 1: i + 1 + packet_len].encode('utf-8') self.packets.append(packet.Packet(encoded_packet=pkt)) # the engine.io protocol sends the packet length in # utf-8 characters, but we need it in bytes to be able to # jump to the next packet in the payload packet_len = len(pkt) encoded_payload = encoded_payload[i + 1 + packet_len:]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: async def receive(self, pkt): """Receive packet from the client."""
self.server.logger.info('%s: Received packet %s data %s', self.sid, packet.packet_names[pkt.packet_type], pkt.data if not isinstance(pkt.data, bytes) else '<binary>') if pkt.packet_type == packet.PING: self.last_ping = time.time() await self.send(packet.Packet(packet.PONG, pkt.data)) elif pkt.packet_type == packet.MESSAGE: await self.server._trigger_event( 'message', self.sid, pkt.data, run_async=self.server.async_handlers) elif pkt.packet_type == packet.UPGRADE: await self.send(packet.Packet(packet.NOOP)) elif pkt.packet_type == packet.CLOSE: await self.close(wait=False, abort=True) else: raise exceptions.UnknownPacketError()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: async def check_ping_timeout(self): """Make sure the client is still sending pings. This helps detect disconnections for long-polling clients. """
if self.closed: raise exceptions.SocketIsClosedError() if time.time() - self.last_ping > self.server.ping_interval + 5: self.server.logger.info('%s: Client is gone, closing socket', self.sid) # Passing abort=False here will cause close() to write a # CLOSE packet. This has the effect of updating half-open sockets # to their correct state of disconnected await self.close(wait=False, abort=False) return False return True
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: async def send(self, pkt): """Send a packet to the client."""
if not await self.check_ping_timeout(): return if self.upgrading: self.packet_backlog.append(pkt) else: await self.queue.put(pkt) self.server.logger.info('%s: Sending packet %s data %s', self.sid, packet.packet_names[pkt.packet_type], pkt.data if not isinstance(pkt.data, bytes) else '<binary>')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: async def handle_post_request(self, environ): """Handle a long-polling POST request from the client."""
length = int(environ.get('CONTENT_LENGTH', '0')) if length > self.server.max_http_buffer_size: raise exceptions.ContentTooLongError() else: body = await environ['wsgi.input'].read(length) p = payload.Payload(encoded_payload=body) for pkt in p.packets: await self.receive(pkt)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: async def _upgrade_websocket(self, environ): """Upgrade the connection from polling to websocket."""
if self.upgraded: raise IOError('Socket has been upgraded already') if self.server._async['websocket'] is None: # the selected async mode does not support websocket return self.server._bad_request() ws = self.server._async['websocket'](self._websocket_handler) return await ws(environ)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def decodeRPCErrorMsg(e): """ Helper function to decode the raised Exception and give it a python Exception class """
found = re.search( ( "(10 assert_exception: Assert Exception\n|" "3030000 tx_missing_posting_auth)" ".*: (.*)\n" ), str(e), flags=re.M, ) if found: return found.group(2).strip() else: return str(e)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def transfer(self, to, amount, asset, memo="", account=None, **kwargs): """ Transfer an asset to another account. :param str to: Recipient :param float amount: Amount to transfer :param str asset: Asset to transfer :param str memo: (optional) Memo, may begin with `#` for encrypted messaging :param str account: (optional) the source account for the transfer if not ``default_account`` """
from .memo import Memo if not account: if "default_account" in self.config: account = self.config["default_account"] if not account: raise ValueError("You need to provide an account") account = Account(account, blockchain_instance=self) amount = Amount(amount, asset, blockchain_instance=self) to = Account(to, blockchain_instance=self) memoObj = Memo(from_account=account, to_account=to, blockchain_instance=self) op = operations.Transfer( **{ "fee": {"amount": 0, "asset_id": "1.3.0"}, "from": account["id"], "to": to["id"], "amount": {"amount": int(amount), "asset_id": amount.asset["id"]}, "memo": memoObj.encrypt(memo), "prefix": self.prefix, } ) return self.finalizeOp(op, account, "active", **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 upgrade_account(self, account=None, **kwargs): """ Upgrade an account to Lifetime membership :param str account: (optional) the account to allow access to (defaults to ``default_account``) """
if not account: if "default_account" in self.config: account = self.config["default_account"] if not account: raise ValueError("You need to provide an account") account = Account(account, blockchain_instance=self) op = operations.Account_upgrade( **{ "fee": {"amount": 0, "asset_id": "1.3.0"}, "account_to_upgrade": account["id"], "upgrade_to_lifetime_member": True, "prefix": self.prefix, } ) return self.finalizeOp(op, account["name"], "active", **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 allow( self, foreign, weight=None, permission="active", account=None, threshold=None, **kwargs ): """ Give additional access to an account by some other public key or account. :param str foreign: The foreign account that will obtain access :param int weight: (optional) The weight to use. If not define, the threshold will be used. If the weight is smaller than the threshold, additional signatures will be required. (defaults to threshold) :param str permission: (optional) The actual permission to modify (defaults to ``active``) :param str account: (optional) the account to allow access to (defaults to ``default_account``) :param int threshold: The threshold that needs to be reached by signatures to be able to interact """
from copy import deepcopy if not account: if "default_account" in self.config: account = self.config["default_account"] if not account: raise ValueError("You need to provide an account") if permission not in ["owner", "active"]: raise ValueError("Permission needs to be either 'owner', or 'active") account = Account(account, blockchain_instance=self) if not weight: weight = account[permission]["weight_threshold"] authority = deepcopy(account[permission]) try: pubkey = PublicKey(foreign, prefix=self.prefix) authority["key_auths"].append([str(pubkey), weight]) except Exception: try: foreign_account = Account(foreign, blockchain_instance=self) authority["account_auths"].append([foreign_account["id"], weight]) except Exception: raise ValueError("Unknown foreign account or invalid public key") if threshold: authority["weight_threshold"] = threshold self._test_weights_treshold(authority) op = operations.Account_update( **{ "fee": {"amount": 0, "asset_id": "1.3.0"}, "account": account["id"], permission: authority, "extensions": {}, "prefix": self.prefix, } ) if permission == "owner": return self.finalizeOp(op, account["name"], "owner", **kwargs) else: return self.finalizeOp(op, account["name"], "active", **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 update_memo_key(self, key, account=None, **kwargs): """ Update an account's memo public key This method does **not** add any private keys to your wallet but merely changes the memo public key. :param str key: New memo public key :param str account: (optional) the account to allow access to (defaults to ``default_account``) """
if not account: if "default_account" in self.config: account = self.config["default_account"] if not account: raise ValueError("You need to provide an account") PublicKey(key, prefix=self.prefix) account = Account(account, blockchain_instance=self) account["options"]["memo_key"] = key op = operations.Account_update( **{ "fee": {"amount": 0, "asset_id": "1.3.0"}, "account": account["id"], "new_options": account["options"], "extensions": {}, "prefix": self.prefix, } ) return self.finalizeOp(op, account["name"], "active", **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 approveworker(self, workers, account=None, **kwargs): """ Approve a worker :param list workers: list of worker member name or id :param str account: (optional) the account to allow access to (defaults to ``default_account``) """
if not account: if "default_account" in self.config: account = self.config["default_account"] if not account: raise ValueError("You need to provide an account") account = Account(account, blockchain_instance=self) options = account["options"] if not isinstance(workers, (list, set, tuple)): workers = {workers} for worker in workers: worker = Worker(worker, blockchain_instance=self) options["votes"].append(worker["vote_for"]) options["votes"] = list(set(options["votes"])) options["voting_account"] = "1.2.5" # Account("proxy-to-self")["id"] op = operations.Account_update( **{ "fee": {"amount": 0, "asset_id": "1.3.0"}, "account": account["id"], "new_options": options, "extensions": {}, "prefix": self.prefix, } ) return self.finalizeOp(op, account["name"], "active", **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 set_proxy(self, proxy_account, account=None, **kwargs): """ Set a specific proxy for account :param bitshares.account.Account proxy_account: Account to be proxied :param str account: (optional) the account to allow access to (defaults to ``default_account``) """
if not account: if "default_account" in self.config: account = self.config["default_account"] if not account: raise ValueError("You need to provide an account") account = Account(account, blockchain_instance=self) proxy = Account(proxy_account, blockchain_instance=self) options = account["options"] options["voting_account"] = proxy["id"] op = operations.Account_update( **{ "fee": {"amount": 0, "asset_id": "1.3.0"}, "account": account["id"], "new_options": options, "extensions": {}, "prefix": self.prefix, } ) return self.finalizeOp(op, account["name"], "active", **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 cancel(self, orderNumbers, account=None, **kwargs): """ Cancels an order you have placed in a given market. Requires only the "orderNumbers". An order number takes the form ``1.7.xxx``. :param str orderNumbers: The Order Object ide of the form ``1.7.xxxx`` """
if not account: if "default_account" in self.config: account = self.config["default_account"] if not account: raise ValueError("You need to provide an account") account = Account(account, full=False, blockchain_instance=self) if not isinstance(orderNumbers, (list, set, tuple)): orderNumbers = {orderNumbers} op = [] for order in orderNumbers: op.append( operations.Limit_order_cancel( **{ "fee": {"amount": 0, "asset_id": "1.3.0"}, "fee_paying_account": account["id"], "order": order, "extensions": [], "prefix": self.prefix, } ) ) return self.finalizeOp(op, account["name"], "active", **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 vesting_balance_withdraw(self, vesting_id, amount=None, account=None, **kwargs): """ Withdraw vesting balance :param str vesting_id: Id of the vesting object :param bitshares.amount.Amount Amount: to withdraw ("all" if not provided") :param str account: (optional) the account to allow access to (defaults to ``default_account``) """
if not account: if "default_account" in self.config: account = self.config["default_account"] if not account: raise ValueError("You need to provide an account") account = Account(account, blockchain_instance=self) if not amount: obj = Vesting(vesting_id, blockchain_instance=self) amount = obj.claimable op = operations.Vesting_balance_withdraw( **{ "fee": {"amount": 0, "asset_id": "1.3.0"}, "vesting_balance": vesting_id, "owner": account["id"], "amount": {"amount": int(amount), "asset_id": amount["asset"]["id"]}, "prefix": self.prefix, } ) return self.finalizeOp(op, account["name"], "active")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def publish_price_feed( self, symbol, settlement_price, cer=None, mssr=110, mcr=200, account=None ): """ Publish a price feed for a market-pegged asset :param str symbol: Symbol of the asset to publish feed for :param bitshares.price.Price settlement_price: Price for settlement :param bitshares.price.Price cer: Core exchange Rate (default ``settlement_price + 5%``) :param float mssr: Percentage for max short squeeze ratio (default: 110%) :param float mcr: Percentage for maintenance collateral ratio (default: 200%) :param str account: (optional) the account to allow access to (defaults to ``default_account``) .. note:: The ``account`` needs to be allowed to produce a price feed for ``symbol``. For witness produced feeds this means ``account`` is a witness account! """
assert mcr > 100 assert mssr > 100 assert isinstance( settlement_price, Price ), "settlement_price needs to be instance of `bitshares.price.Price`!" assert cer is None or isinstance( cer, Price ), "cer needs to be instance of `bitshares.price.Price`!" if not account: if "default_account" in self.config: account = self.config["default_account"] if not account: raise ValueError("You need to provide an account") account = Account(account, blockchain_instance=self) asset = Asset(symbol, blockchain_instance=self, full=True) backing_asset = asset["bitasset_data"]["options"]["short_backing_asset"] assert ( asset["id"] == settlement_price["base"]["asset"]["id"] or asset["id"] == settlement_price["quote"]["asset"]["id"] ), "Price needs to contain the asset of the symbol you'd like to produce a feed for!" assert asset.is_bitasset, "Symbol needs to be a bitasset!" assert ( settlement_price["base"]["asset"]["id"] == backing_asset or settlement_price["quote"]["asset"]["id"] == backing_asset ), "The Price needs to be relative to the backing collateral!" settlement_price = settlement_price.as_base(symbol) if cer: cer = cer.as_base(symbol) if cer["quote"]["asset"]["id"] != "1.3.0": raise ValueError("CER must be defined against core asset '1.3.0'") else: if settlement_price["quote"]["asset"]["id"] != "1.3.0": raise ValueError( "CER must be manually provided because it relates to core asset '1.3.0'" ) cer = settlement_price.as_quote(symbol) * 0.95 op = operations.Asset_publish_feed( **{ "fee": {"amount": 0, "asset_id": "1.3.0"}, "publisher": account["id"], "asset_id": asset["id"], "feed": { "settlement_price": settlement_price.as_base(symbol).json(), "core_exchange_rate": cer.as_base(symbol).json(), "maximum_short_squeeze_ratio": int(mssr * 10), "maintenance_collateral_ratio": int(mcr * 10), }, "prefix": self.prefix, } ) return self.finalizeOp(op, account["name"], "active")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def update_witness(self, witness_identifier, url=None, key=None, **kwargs): """ Upgrade a witness account :param str witness_identifier: Identifier for the witness :param str url: New URL for the witness :param str key: Public Key for the signing """
witness = Witness(witness_identifier) account = witness.account op = operations.Witness_update( **{ "fee": {"amount": 0, "asset_id": "1.3.0"}, "prefix": self.prefix, "witness": witness["id"], "witness_account": account["id"], "new_url": url, "new_signing_key": key, } ) return self.finalizeOp(op, account["name"], "active", **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 create_worker( self, name, daily_pay, end, url="", begin=None, payment_type="vesting", pay_vesting_period_days=0, account=None, **kwargs ): """ Create a worker This removes the shares from the supply **Required** :param str name: Name of the worke :param bitshares.amount.Amount daily_pay: The amount to be paid daily :param datetime end: Date/time of end of the worker **Optional** :param str url: URL to read more about the worker :param datetime begin: Date/time of begin of the worker :param string payment_type: ["burn", "refund", "vesting"] (default: "vesting") :param int pay_vesting_period_days: Days of vesting (default: 0) :param str account: (optional) the account to allow access to (defaults to ``default_account``) """
from bitsharesbase.transactions import timeformat assert isinstance(daily_pay, Amount) assert daily_pay["asset"]["id"] == "1.3.0" if not begin: begin = datetime.utcnow() + timedelta(seconds=30) if not account: if "default_account" in self.config: account = self.config["default_account"] if not account: raise ValueError("You need to provide an account") account = Account(account, blockchain_instance=self) if payment_type == "refund": initializer = [0, {}] elif payment_type == "vesting": initializer = [1, {"pay_vesting_period_days": pay_vesting_period_days}] elif payment_type == "burn": initializer = [2, {}] else: raise ValueError('payment_type not in ["burn", "refund", "vesting"]') op = operations.Worker_create( **{ "fee": {"amount": 0, "asset_id": "1.3.0"}, "owner": account["id"], "work_begin_date": begin.strftime(timeformat), "work_end_date": end.strftime(timeformat), "daily_pay": int(daily_pay), "name": name, "url": url, "initializer": initializer, } ) return self.finalizeOp(op, account, "active", **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 create_committee_member(self, url="", account=None, **kwargs): """ Create a committee member :param str url: URL to read more about the worker :param str account: (optional) the account to allow access to (defaults to ``default_account``) """
if not account: if "default_account" in self.config: account = self.config["default_account"] if not account: raise ValueError("You need to provide an account") account = Account(account, blockchain_instance=self) op = operations.Committee_member_create( **{ "fee": {"amount": 0, "asset_id": "1.3.0"}, "committee_member_account": account["id"], "url": url, } ) return self.finalizeOp(op, account, "active", **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 reset_subscriptions(self, accounts=[], markets=[], objects=[]): """Change the subscriptions of a running Notify instance """
self.websocket.reset_subscriptions( accounts, self.get_market_ids(markets), objects )
<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_market(self, data): """ This method is used for post processing of market notifications. It will return instances of either * :class:`bitshares.price.Order` or * :class:`bitshares.price.FilledOrder` or * :class:`bitshares.price.UpdateCallOrder` Also possible are limit order updates (margin calls) """
for d in data: if not d: continue if isinstance(d, str): # Single order has been placed log.debug("Calling on_market with Order()") self.on_market(Order(d, blockchain_instance=self.blockchain)) continue elif isinstance(d, dict): d = [d] # Orders have been matched for p in d: if not isinstance(p, list): p = [p] for i in p: if isinstance(i, dict): if "pays" in i and "receives" in i: self.on_market( FilledOrder(i, blockchain_instance=self.blockchain) ) elif "for_sale" in i and "sell_price" in i: self.on_market( Order(i, blockchain_instance=self.blockchain) ) elif "collateral" in i and "call_price" in i: self.on_market( UpdateCallOrder(i, blockchain_instance=self.blockchain) ) else: if i: log.error("Unknown market update type: %s" % 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 returnFees(self): """ Returns a dictionary of all fees that apply through the network Example output: .. code-block:: js {'proposal_create': {'fee': 400000.0}, 'asset_publish_feed': {'fee': 1000.0}, 'account_create': {'basic_fee': 950000.0, 'price_per_kbyte': 20000.0, 'premium_fee': 40000000.0}, 'custom': {'fee': 20000.0}, 'asset_fund_fee_pool': {'fee': 20000.0}, 'override_transfer': {'fee': 400000.0}, 'fill_order': {}, 'asset_update': {'price_per_kbyte': 20000.0, 'fee': 200000.0}, 'asset_update_feed_producers': {'fee': 10000000.0}, 'assert': {'fee': 20000.0}, 'committee_member_create': {'fee': 100000000.0}} """
from bitsharesbase.operations import operations r = {} obj, base = self.blockchain.rpc.get_objects(["2.0.0", "1.3.0"]) fees = obj["parameters"]["current_fees"]["parameters"] scale = float(obj["parameters"]["current_fees"]["scale"]) for f in fees: op_name = "unknown %d" % f[0] for name in operations: if operations[name] == f[0]: op_name = name fs = f[1] for _type in fs: fs[_type] = float(fs[_type]) * scale / 1e4 / 10 ** base["precision"] r[op_name] = fs return r
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def close_debt_position(self, symbol, account=None): """ Close a debt position and reclaim the collateral :param str symbol: Symbol to close debt position for :raises ValueError: if symbol has no open call position """
if not account: if "default_account" in self.blockchain.config: account = self.blockchain.config["default_account"] if not account: raise ValueError("You need to provide an account") account = Account(account, full=True, blockchain_instance=self.blockchain) debts = self.list_debt_positions(account) if symbol not in debts: raise ValueError("No call position open for %s" % symbol) debt = debts[symbol] asset = debt["debt"]["asset"] collateral_asset = debt["collateral"]["asset"] op = operations.Call_order_update( **{ "fee": {"amount": 0, "asset_id": "1.3.0"}, "delta_debt": { "amount": int(-float(debt["debt"]) * 10 ** asset["precision"]), "asset_id": asset["id"], }, "delta_collateral": { "amount": int( -float(debt["collateral"]) * 10 ** collateral_asset["precision"] ), "asset_id": collateral_asset["id"], }, "funding_account": account["id"], "extensions": [], } ) return self.blockchain.finalizeOp(op, account["name"], "active")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def adjust_debt( self, delta, new_collateral_ratio=None, account=None, target_collateral_ratio=None, ): """ Adjust the amount of debt for an asset :param Amount delta: Delta amount of the debt (-10 means reduce debt by 10, +10 means borrow another 10) :param float new_collateral_ratio: collateral ratio to maintain (optional, by default tries to maintain old ratio) :param float target_collateral_ratio: Tag the call order so that in case of margin call, only enough debt is covered to get back to this ratio :raises ValueError: if symbol is not a bitasset :raises ValueError: if collateral ratio is smaller than maintenance collateral ratio :raises ValueError: if required amounts of collateral are not available """
if not account: if "default_account" in self.blockchain.config: account = self.blockchain.config["default_account"] if not account: raise ValueError("You need to provide an account") account = Account(account, full=True, blockchain_instance=self.blockchain) # We sell quote and pay with base symbol = delta["symbol"] asset = Asset(symbol, full=True, blockchain_instance=self.blockchain) if not asset.is_bitasset: raise ValueError("%s is not a bitasset!" % symbol) bitasset = asset["bitasset_data"] # Check minimum collateral ratio backing_asset_id = bitasset["options"]["short_backing_asset"] current_debts = self.list_debt_positions(account) if not new_collateral_ratio and symbol not in current_debts: new_collateral_ratio = ( bitasset["current_feed"]["maintenance_collateral_ratio"] / 1000 ) elif not new_collateral_ratio and symbol in current_debts: new_collateral_ratio = current_debts[symbol]["ratio"] # Derive Amount of Collateral collateral_asset = Asset(backing_asset_id, blockchain_instance=self.blockchain) settlement_price = Price( bitasset["current_feed"]["settlement_price"], blockchain_instance=self.blockchain, ) if symbol in current_debts: amount_of_collateral = ( (float(current_debts[symbol]["debt"]) + float(delta["amount"])) * new_collateral_ratio / float(settlement_price) ) amount_of_collateral -= float(current_debts[symbol]["collateral"]) else: amount_of_collateral = ( float(delta["amount"]) * new_collateral_ratio / float(settlement_price) ) # Verify that enough funds are available fundsNeeded = amount_of_collateral + float( self.returnFees()["call_order_update"]["fee"] ) fundsHave = account.balance(collateral_asset["symbol"]) or 0 if fundsHave <= fundsNeeded: raise ValueError( "Not enough funds available. Need %f %s, but only %f %s are available" % ( fundsNeeded, collateral_asset["symbol"], fundsHave, collateral_asset["symbol"], ) ) payload = { "fee": {"amount": 0, "asset_id": "1.3.0"}, "delta_debt": { "amount": int(float(delta) * 10 ** asset["precision"]), "asset_id": asset["id"], }, "delta_collateral": { "amount": int( float(amount_of_collateral) * 10 ** collateral_asset["precision"] ), "asset_id": collateral_asset["id"], }, "funding_account": account["id"], "extensions": {}, } # Extension if target_collateral_ratio: payload["extensions"].update( dict(target_collateral_ratio=int(target_collateral_ratio * 100)) ) op = operations.Call_order_update(**payload) return self.blockchain.finalizeOp(op, account["name"], "active")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def adjust_collateral_ratio( self, symbol, new_collateral_ratio, account=None, target_collateral_ratio=None ): """ Adjust the collataral ratio of a debt position :param Asset amount: Amount to borrow (denoted in 'asset') :param float new_collateral_ratio: desired collateral ratio :param float target_collateral_ratio: Tag the call order so that in case of margin call, only enough debt is covered to get back to this ratio :raises ValueError: if symbol is not a bitasset :raises ValueError: if collateral ratio is smaller than maintenance collateral ratio :raises ValueError: if required amounts of collateral are not available """
if not account: if "default_account" in self.blockchain.config: account = self.blockchain.config["default_account"] if not account: raise ValueError("You need to provide an account") account = Account(account, full=True, blockchain_instance=self.blockchain) current_debts = self.list_debt_positions(account) if symbol not in current_debts: raise ValueError( "No Call position available to adjust! Please borrow first!" ) return self.adjust_debt( Amount(0, symbol), new_collateral_ratio, account, target_collateral_ratio=target_collateral_ratio, )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getOperationNameForId(i): """ Convert an operation id into the corresponding string """
for key in operations: if int(operations[key]) is int(i): return key return "Unknown Operation ID %d" % 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 getOperationName(id: str): """ This method returns the name representation of an operation given its value as used in the API """
if isinstance(id, str): # Some graphene chains (e.g. steem) do not encode the # operation_type as id but in its string form assert id in operations.keys(), "Unknown operation {}".format(id) return id elif isinstance(id, int): return getOperationNameForId(id) else: raise ValueError
<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_account(self, name, **kwargs): """ Get full account details from account name or id :param str name: Account name or account id """
if len(name.split(".")) == 3: return self.get_objects([name])[0] else: return self.get_account_by_name(name, **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 get_asset(self, name, **kwargs): """ Get full asset from name of id :param str name: Symbol name or asset id (e.g. 1.3.0) """
if len(name.split(".")) == 3: return self.get_objects([name], **kwargs)[0] else: return self.lookup_asset_symbols([name], **kwargs)[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 process_notice(self, notice): """ This method is called on notices that need processing. Here, we call ``on_object`` and ``on_account`` slots. """
id = notice["id"] _a, _b, _ = id.split(".") if id in self.subscription_objects: self.on_object(notice) elif ".".join([_a, _b, "x"]) in self.subscription_objects: self.on_object(notice) elif id[:4] == "2.6.": # Treat account updates separately self.on_account(notice)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def close(self, *args, **kwargs): """ Closes the websocket connection and waits for the ping thread to close """
self.run_event.set() self.ws.close() if self.keepalive and self.keepalive.is_alive(): self.keepalive.join()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rpcexec(self, payload): """ Execute a call by sending the payload :param dict payload: Payload data :raises ValueError: if the server does not respond in proper JSON format :raises RPCError: if the server returns an error """
log.debug(json.dumps(payload)) self.ws.send(json.dumps(payload, ensure_ascii=False).encode("utf8"))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def text2html_table(items): "Put the texts in `items` in an HTML table." html_code = f"""<table border="1" class="dataframe">\n"""
html_code += f""" <thead>\n <tr style="text-align: left;">\n""" for i in items[0]: html_code += f" <th>{i}</th>\n" html_code += f" </tr>\n </thead>\n <tbody>\n" for line in items[1:]: html_code += " <tr>\n" for i in line: html_code += f" <td>{i}</td>\n" html_code += " </tr>\n" html_code += " </tbody>\n</table><p>" return html_code
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def log_value(self, name, value, step=None): """Log new value for given name on given step. Args: name (str): name of the variable (it will be converted to a valid tensorflow summary name). value (float): this is a real number to be logged as a scalar. step (int): non-negative integer used for visualization: you can log several different variables on one step, but should not log different values of the same variable on the same step (this is not checked). """
if isinstance(value, six.string_types): raise TypeError('"value" should be a number, got {}' .format(type(value))) value = float(value) self._check_step(step) tf_name = self._ensure_tf_name(name) summary = self._scalar_summary(tf_name, value, step) self._log_summary(tf_name, summary, value, step=step)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def log_histogram(self, name, value, step=None): """Log a histogram for given name on given step. Args: name (str): name of the variable (it will be converted to a valid tensorflow summary name). value (tuple or list): either list of numbers to be summarized as a histogram, or a tuple of bin_edges and bincounts that directly define a histogram. step (int): non-negative integer used for visualization """
if isinstance(value, six.string_types): raise TypeError('"value" should be a number, got {}' .format(type(value))) self._check_step(step) tf_name = self._ensure_tf_name(name) summary = self._histogram_summary(tf_name, value, step=step) self._log_summary(tf_name, summary, value, step=step)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def log_images(self, name, images, step=None): """Log new images for given name on given step. Args: name (str): name of the variable (it will be converted to a valid tensorflow summary name). images (list): list of images to visualize step (int): non-negative integer used for visualization """
if isinstance(images, six.string_types): raise TypeError('"images" should be a list of ndarrays, got {}' .format(type(images))) self._check_step(step) tf_name = self._ensure_tf_name(name) summary = self._image_summary(tf_name, images, step=step) self._log_summary(tf_name, summary, images, step=step)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _image_summary(self, tf_name, images, step=None): """ Log a list of images. References: https://github.com/yunjey/pytorch-tutorial/blob/master/tutorials/04-utils/tensorboard/logger.py#L22 Example: """
img_summaries = [] for i, img in enumerate(images): # Write the image to a string try: s = StringIO() except: s = BytesIO() scipy.misc.toimage(img).save(s, format="png") # Create an Image object img_sum = summary_pb2.Summary.Image( encoded_image_string=s.getvalue(), height=img.shape[0], width=img.shape[1] ) # Create a Summary value img_value = summary_pb2.Summary.Value(tag='{}/{}'.format(tf_name, i), image=img_sum) img_summaries.append(img_value) summary = summary_pb2.Summary() summary.value.add(tag=tf_name, image=img_sum) summary = summary_pb2.Summary(value=img_summaries) return summary
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def jinja_filter_param_value_str(value, str_quote_style="", bool_is_str=False): """ Convert a parameter value to string suitable to be passed to an EDA tool Rules: - Booleans are represented as 0/1 or "true"/"false" depending on the bool_is_str argument - Strings are either passed through or enclosed in the characters specified in str_quote_style (e.g. '"' or '\\"') - Everything else (including int, float, etc.) are converted using the str() function. """
if (type(value) == bool) and not bool_is_str: if (value) == True: return '1' else: return '0' elif type(value) == str or ((type(value) == bool) and bool_is_str): return str_quote_style + str(value) + str_quote_style else: return str(value)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def render_template(self, template_file, target_file, template_vars = {}): """ Render a Jinja2 template for the backend The template file is expected in the directory templates/BACKEND_NAME. """
template_dir = str(self.__class__.__name__).lower() template = self.jinja_env.get_template(os.path.join(template_dir, template_file)) file_path = os.path.join(self.work_root, target_file) with open(file_path, 'w') as f: f.write(template.render(template_vars))
<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_target_count(self, target): """Return the target count"""
reply = NVCtrlQueryTargetCountReplyRequest(display=self.display, opcode=self.display.get_extension_major(extname), target_type=target.type()) return int(reply._data.get('count'))
<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_int_attribute(self, target, display_mask, attr): """Return the value of an integer attribute"""
reply = NVCtrlQueryAttributeReplyRequest(display=self.display, opcode=self.display.get_extension_major(extname), target_id=target.id(), target_type=target.type(), display_mask=display_mask, attr=attr) if not reply._data.get('flags'): return None return int(reply._data.get('value'))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_int_attribute(self, target, display_mask, attr, value): """Set the value of an integer attribute"""
reply = NVCtrlSetAttributeAndGetStatusReplyRequest(display=self.display, opcode=self.display.get_extension_major(extname), target_id=target.id(), target_type=target.type(), display_mask=display_mask, attr=attr, value=value) return reply._data.get('flags') != 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 query_string_attribute(self, target, display_mask, attr): """Return the value of a string attribute"""
reply = NVCtrlQueryStringAttributeReplyRequest(display=self.display, opcode=self.display.get_extension_major(extname), target_id=target.id(), target_type=target.type(), display_mask=display_mask, attr=attr) if not reply._data.get('flags'): return None return str(reply._data.get('string')).strip('\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 query_binary_data(self, target, display_mask, attr): """Return binary data"""
reply = NVCtrlQueryBinaryDataReplyRequest(display=self.display, opcode=self.display.get_extension_major(extname), target_id=target.id(), target_type=target.type(), display_mask=display_mask, attr=attr) if not reply._data.get('flags'): return None return reply._data.get('data')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _displaystr2num(st): """Return a display number from a string"""
num = None for s, n in [('DFP-', 16), ('TV-', 8), ('CRT-', 0)]: if st.startswith(s): try: curnum = int(st[len(s):]) if 0 <= curnum <= 7: num = n + curnum break except Exception: pass if num is not None: return num else: raise ValueError('Unrecognised display name: ' + st)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def keycode_to_keysym(self, keycode, index): """Convert a keycode to a keysym, looking in entry index. Normally index 0 is unshifted, 1 is shifted, 2 is alt grid, and 3 is shift+alt grid. If that key entry is not bound, X.NoSymbol is returned."""
try: return self._keymap_codes[keycode][index] except IndexError: return X.NoSymbol
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def refresh_keyboard_mapping(self, evt): """This method should be called once when a MappingNotify event is received, to update the keymap cache. evt should be the event object."""
if isinstance(evt, event.MappingNotify): if evt.request == X.MappingKeyboard: self._update_keymap(evt.first_keycode, evt.count) else: raise TypeError('expected a MappingNotify event')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _update_keymap(self, first_keycode, count): """Internal function, called to refresh the keymap cache. """
# Delete all sym->code maps for the changed codes lastcode = first_keycode + count for keysym, codes in self._keymap_syms.items(): i = 0 while i < len(codes): code = codes[i][1] if code >= first_keycode and code < lastcode: del codes[i] else: i = i + 1 # Get the new keyboard mapping keysyms = self.get_keyboard_mapping(first_keycode, count) # Replace code->sym map with the new map self._keymap_codes[first_keycode:lastcode] = keysyms # Update sym->code map code = first_keycode for syms in keysyms: index = 0 for sym in syms: if sym != X.NoSymbol: if sym in self._keymap_syms: symcodes = self._keymap_syms[sym] symcodes.append((index, code)) symcodes.sort() else: self._keymap_syms[sym] = [(index, code)] index = index + 1 code = code + 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 lookup_string(self, keysym): """Return a string corresponding to KEYSYM, or None if no reasonable translation is found. """
s = self.keysym_translations.get(keysym) if s is not None: return s import Xlib.XK return Xlib.XK.keysym_to_string(keysym)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def rebind_string(self, keysym, newstring): """Change the translation of KEYSYM to NEWSTRING. If NEWSTRING is None, remove old translation if any. """
if newstring is None: try: del self.keysym_translations[keysym] except KeyError: pass else: self.keysym_translations[keysym] = newstring
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def intern_atom(self, name, only_if_exists = 0): """Intern the string name, returning its atom number. If only_if_exists is true and the atom does not already exist, it will not be created and X.NONE is returned."""
r = request.InternAtom(display = self.display, name = name, only_if_exists = only_if_exists) return r.atom
<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_atom_name(self, atom): """Look up the name of atom, returning it as a string. Will raise BadAtom if atom does not exist."""
r = request.GetAtomName(display = self.display, atom = atom) return r.name
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def allow_events(self, mode, time, onerror = None): """Release some queued events. mode should be one of X.AsyncPointer, X.SyncPointer, X.AsyncKeyboard, X.SyncKeyboard, X.ReplayPointer, X.ReplayKeyboard, X.AsyncBoth, or X.SyncBoth. time should be a timestamp or X.CurrentTime."""
request.AllowEvents(display = self.display, onerror = onerror, mode = mode, time = 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 grab_server(self, onerror = None): """Disable processing of requests on all other client connections until the server is ungrabbed. Server grabbing should be avoided as much as possible."""
request.GrabServer(display = self.display, onerror = onerror)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ungrab_server(self, onerror = None): """Release the server if it was previously grabbed by this client."""
request.UngrabServer(display = self.display, onerror = onerror)
<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_keymap(self): """Return a bit vector for the logical state of the keyboard, where each bit set to 1 indicates that the corresponding key is currently pressed down. The vector is represented as a list of 32 integers. List item N contains the bits for keys 8N to 8N + 7 with the least significant bit in the byte representing key 8N."""
r = request.QueryKeymap(display = self.display) return r.map
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def open_font(self, name): """Open the font identifed by the pattern name and return its font object. If name does not match any font, None is returned."""
fid = self.display.allocate_resource_id() ec = error.CatchError(error.BadName) request.OpenFont(display = self.display, onerror = ec, fid = fid, name = name) self.sync() if ec.get_error(): self.display.free_resource_id(fid) return None else: cls = self.display.get_resource_class('font', fontable.Font) return cls(self.display, fid, owner = 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 list_fonts(self, pattern, max_names): """Return a list of font names matching pattern. No more than max_names will be returned."""
r = request.ListFonts(display = self.display, max_names = max_names, pattern = pattern) return r.fonts
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_font_path(self, path, onerror = None): """Set the font path to path, which should be a list of strings. If path is empty, the default font path of the server will be restored."""
request.SetFontPath(display = self.display, onerror = onerror, path = path)
<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_font_path(self): """Return the current font path as a list of strings."""
r = request.GetFontPath(display = self.display) return r.paths
<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_extensions(self): """Return a list of all the extensions provided by the server."""
r = request.ListExtensions(display = self.display) return r.names
<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_keyboard_mapping(self, first_keycode, count): """Return the current keyboard mapping as a list of tuples, starting at first_keycount and no more than count."""
r = request.GetKeyboardMapping(display = self.display, first_keycode = first_keycode, count = count) return r.keysyms
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def change_hosts(self, mode, host_family, host, onerror = None): """mode is either X.HostInsert or X.HostDelete. host_family is one of X.FamilyInternet, X.FamilyDECnet or X.FamilyChaos. host is a list of bytes. For the Internet family, it should be the four bytes of an IPv4 address."""
request.ChangeHosts(display = self.display, onerror = onerror, mode = mode, host_family = host_family, host = host)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_access_control(self, mode, onerror = None): """Enable use of access control lists at connection setup if mode is X.EnableAccess, disable if it is X.DisableAccess."""
request.SetAccessControl(display = self.display, onerror = onerror, mode = mode)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_close_down_mode(self, mode, onerror = None): """Control what will happen with the client's resources at connection close. The default is X.DestroyAll, the other values are X.RetainPermanent and X.RetainTemporary."""
request.SetCloseDownMode(display = self.display, onerror = onerror, mode = mode)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def force_screen_saver(self, mode, onerror = None): """If mode is X.ScreenSaverActive the screen saver is activated. If it is X.ScreenSaverReset, the screen saver is deactivated as if device input had been received."""
request.ForceScreenSaver(display = self.display, onerror = onerror, mode = mode)
<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_pointer_mapping(self): """Return a list of the pointer button mappings. Entry N in the list sets the logical button number for the physical button N+1."""
r = request.GetPointerMapping(display = self.display) return r.map
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def set_modifier_mapping(self, keycodes): """Set the keycodes for the eight modifiers X.Shift, X.Lock, X.Control, X.Mod1, X.Mod2, X.Mod3, X.Mod4 and X.Mod5. keycodes should be a eight-element list where each entry is a list of the keycodes that should be bound to that modifier. If any changed key is logically in the down state, X.MappingBusy is returned and the mapping is not changed. If the mapping violates some server restriction, X.MappingFailed is returned. Otherwise the mapping is changed and X.MappingSuccess is returned."""
r = request.SetModifierMapping(display = self.display, keycodes = keycodes) return r.status
<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_modifier_mapping(self): """Return a list of eight lists, one for each modifier. The list can be indexed using X.ShiftMapIndex, X.Mod1MapIndex, and so on. The sublists list the keycodes bound to that modifier."""
r = request.GetModifierMapping(display = self.display) return r.keycodes
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def no_operation(self, onerror = None): """Do nothing but send a request to the server."""
request.NoOperation(display = self.display, onerror = onerror)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse_connection_setup(self): """Internal function used to parse connection setup response. """
# Only the ConnectionSetupRequest has been sent so far r = self.sent_requests[0] while 1: # print 'data_send:', repr(self.data_send) # print 'data_recv:', repr(self.data_recv) if r._data: alen = r._data['additional_length'] * 4 # The full response haven't arrived yet if len(self.data_recv) < alen: return 0 # Connection failed or further authentication is needed. # Set reason to the reason string if r._data['status'] != 1: r._data['reason'] = self.data_recv[:r._data['reason_length']] # Else connection succeeded, parse the reply else: x, d = r._success_reply.parse_binary(self.data_recv[:alen], self, rawdict = 1) r._data.update(x) del self.sent_requests[0] self.data_recv = self.data_recv[alen:] return 1 else: # The base reply is 8 bytes long if len(self.data_recv) < 8: return 0 r._data, d = r._reply.parse_binary(self.data_recv[:8], self, rawdict = 1) self.data_recv = self.data_recv[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 redirect_subwindows(self, update, onerror = None): """Redirect the hierarchies starting at all current and future children to this window to off-screen storage. """
RedirectSubwindows(display = self.display, onerror = onerror, opcode = self.display.get_extension_major(extname), window = self, update = update, )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def unredirect_window(self, update, onerror = None): """Stop redirecting this window hierarchy. """
UnredirectWindow(display = self.display, onerror = onerror, opcode = self.display.get_extension_major(extname), window = self, update = update, )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def unredirect_subwindows(self, update, onerror = None): """Stop redirecting the hierarchies of children to this window. """
RedirectWindow(display = self.display, onerror = onerror, opcode = self.display.get_extension_major(extname), window = self, update = update, )
<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_region_from_border_clip(self, onerror = None): """Create a region of the border clip of the window, i.e. the area that is not clipped by the parent and any sibling windows. """
rid = self.display.allocate_resource_id() CreateRegionFromBorderClip( display = self.display, onerror = onerror, opcode = self.display.get_extension_major(extname), region = rid, window = self, ) # FIXME: create Region object and return it return rid
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def name_window_pixmap(self, onerror = None): """Create a new pixmap that refers to the off-screen storage of the window, including its border. This pixmap will remain allocated until freed whatever happens with the window. However, the window will get a new off-screen pixmap every time it is mapped or resized, so to keep track of the contents you must listen for these events and get a new pixmap after them. """
pid = self.display.allocate_resource_id() NameWindowPixmap(display = self.display, onerror = onerror, opcode = self.display.get_extension_major(extname), window = self, pixmap = pid, ) cls = self.display.get_resource_class('pixmap', drawable.Pixmap) return cls(self.display, pid, owner = 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 get_overlay_window(self): """Return the overlay window of the root window. """
return GetOverlayWindow(display = self.display, opcode = self.display.get_extension_major(extname), window = 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 pack_value(self, val): """Convert 8-byte string into 16-byte list"""
if isinstance(val, bytes): val = list(iterbytes(val)) slen = len(val) if self.pad: pad = b'\0\0' * (slen % 2) else: pad = b'' return struct.pack('>' + 'H' * slen, *val) + pad, slen, 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 pack_value(self, value): """ This function allows Struct objects to be used in List and Object fields. Each item represents the arguments to pass to to_binary, either a tuple, a dictionary or a DictWrapper. """
if type(value) is tuple: return self.to_binary(*value) elif isinstance(value, dict): return self.to_binary(**value) elif isinstance(value, DictWrapper): return self.to_binary(**value._data) else: raise BadDataError('%s is not a tuple or a list' % (value))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def parse_value(self, val, display, rawdict = 0): """This function is used by List and Object fields to convert Struct objects with no var_fields into Python values. """
ret = {} vno = 0 for f in self.static_fields: # Fields without names should be ignored, and there should # not be any length or format fields if this function # ever gets called. (If there were such fields, there should # be a matching field in var_fields and then parse_binary # would have been called instead. if not f.name: pass elif isinstance(f, LengthField): pass elif isinstance(f, FormatField): pass # Value fields else: # If this field has a parse_value method, call it, otherwise # use the unpacked value as is. if f.structvalues == 1: field_val = val[vno] else: field_val = val[vno:vno+f.structvalues] if f.parse_value is not None: field_val = f.parse_value(field_val, display, rawdict=rawdict) ret[f.name] = field_val vno = vno + f.structvalues if not rawdict: return DictWrapper(ret) 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 get_best_auth(self, family, address, dispno, types = ( b"MIT-MAGIC-COOKIE-1", )): """Find an authentication entry matching FAMILY, ADDRESS and DISPNO. The name of the auth scheme must match one of the names in TYPES. If several entries match, the first scheme in TYPES will be choosen. If an entry is found, the tuple (name, data) is returned, otherwise XNoAuthError is raised. """
num = str(dispno).encode() matches = {} for efam, eaddr, enum, ename, edata in self.entries: if efam == family and eaddr == address and num == enum: matches[ename] = edata for t in types: try: return (t, matches[t]) except KeyError: pass raise error.XNoAuthError((family, address, dispno))
<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_example(path): """ Returns returncode of example """
cmd = "{0} {1}".format(sys.executable, path) proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) res = proc.communicate() if proc.returncode: print(res[1].decode()) return proc.returncode
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def load_keysym_group(group): '''Load all the keysyms in group. Given a group name such as 'latin1' or 'katakana' load the keysyms defined in module 'Xlib.keysymdef.group-name' into this XK module.''' if '.' in group: raise ValueError('invalid keysym group name: %s' % group) G = globals() #Get a reference to XK.__dict__ a.k.a. globals #Import just the keysyms module. mod = __import__('Xlib.keysymdef.%s' % group, G, locals(), [group]) #Extract names of just the keysyms. keysyms = [n for n in dir(mod) if n.startswith('XK_')] #Copy the named keysyms into XK.__dict__ for keysym in keysyms: ## k = mod.__dict__[keysym]; assert k == int(k) #probably too much. G[keysym] = mod.__dict__[keysym] #And get rid of the keysym module. del mod
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _1_0set_screen_config(self, size_id, rotation, config_timestamp, timestamp=X.CurrentTime): """Sets the screen to the specified size and rotation. """
return _1_0SetScreenConfig( display=self.display, opcode=self.display.get_extension_major(extname), drawable=self, timestamp=timestamp, config_timestamp=config_timestamp, size_id=size_id, rotation=rotation, )