INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Check the token and raise an oauth. Error exception if invalid.
def validate_token(self, request, consumer, token): """ Check the token and raise an `oauth.Error` exception if invalid. """ oauth_server, oauth_request = oauth_provider.utils.initialize_server_request(request) oauth_server.verify_request(oauth_request, consumer, token)
Checks nonce of request and return True if valid.
def check_nonce(self, request, oauth_request): """ Checks nonce of request, and return True if valid. """ oauth_nonce = oauth_request['oauth_nonce'] oauth_timestamp = oauth_request['oauth_timestamp'] return check_nonce(request, oauth_request, oauth_nonce, oauth_timestamp)
Returns two - tuple of ( user token ) if authentication succeeds or None otherwise.
def authenticate(self, request): """ Returns two-tuple of (user, token) if authentication succeeds, or None otherwise. """ auth = get_authorization_header(request).split() if len(auth) == 1: msg = 'Invalid bearer header. No credentials provided.' raise exceptions.AuthenticationFailed(msg) elif len(auth) > 2: msg = 'Invalid bearer header. Token string should not contain spaces.' raise exceptions.AuthenticationFailed(msg) if auth and auth[0].lower() == b'bearer': access_token = auth[1] elif 'access_token' in request.POST: access_token = request.POST['access_token'] elif 'access_token' in request.GET and self.allow_query_params_token: access_token = request.GET['access_token'] else: return None return self.authenticate_credentials(request, access_token)
用SHA1算法生成安全签名
def getSHA1(self, token, timestamp, nonce, encrypt): """用SHA1算法生成安全签名 @param token: 票据 @param timestamp: 时间戳 @param encrypt: 密文 @param nonce: 随机字符串 @return: 安全签名 """ try: sortlist = [token, timestamp, nonce, encrypt] sortlist.sort() sha = hashlib.sha1() sha.update("".join(sortlist)) return WXBizMsgCrypt_OK, sha.hexdigest() except Exception: return WXBizMsgCrypt_ComputeSignature_Error, None
提取出xml数据包中的加密消息
def extract(self, xmltext): """提取出xml数据包中的加密消息 @param xmltext: 待提取的xml字符串 @return: 提取出的加密消息字符串 """ try: xml_tree = ET.fromstring(xmltext) encrypt = xml_tree.find("Encrypt") touser_name = xml_tree.find("ToUserName") if touser_name != None: touser_name = touser_name.text return WXBizMsgCrypt_OK, encrypt.text, touser_name except Exception: return WXBizMsgCrypt_ParseXml_Error, None, None
生成xml消息
def generate(self, encrypt, signature, timestamp, nonce): """生成xml消息 @param encrypt: 加密后的消息密文 @param signature: 安全签名 @param timestamp: 时间戳 @param nonce: 随机字符串 @return: 生成的xml字符串 """ resp_dict = { 'msg_encrypt': encrypt, 'msg_signaturet': signature, 'timestamp': timestamp, 'nonce': nonce, } resp_xml = self.AES_TEXT_RESPONSE_TEMPLATE % resp_dict return resp_xml
对需要加密的明文进行填充补位
def encode(self, text): """ 对需要加密的明文进行填充补位 @param text: 需要进行填充补位操作的明文 @return: 补齐明文字符串 """ text_length = len(text) # 计算需要填充的位数 amount_to_pad = self.block_size - (text_length % self.block_size) if amount_to_pad == 0: amount_to_pad = self.block_size # 获得补位所用的字符 pad = chr(amount_to_pad) return text + pad * amount_to_pad
删除解密后明文的补位字符
def decode(self, decrypted): """删除解密后明文的补位字符 @param decrypted: 解密后的明文 @return: 删除补位字符后的明文 """ pad = ord(decrypted[-1]) if pad < 1 or pad > 32: pad = 0 return decrypted[:-pad]
对明文进行加密
def encrypt(self, text, appid): """对明文进行加密 @param text: 需要加密的明文 @return: 加密得到的字符串 """ # 16位随机字符串添加到明文开头 text = self.get_random_str() + struct.pack( "I", socket.htonl(len(text))) + text + appid # 使用自定义的填充方式对明文进行补位填充 pkcs7 = PKCS7Encoder() text = pkcs7.encode(text) # 加密 cryptor = AES.new(self.key, self.mode, self.key[:16]) try: ciphertext = cryptor.encrypt(text) # 使用BASE64对加密后的字符串进行编码 return WXBizMsgCrypt_OK, base64.b64encode(ciphertext) except Exception: return WXBizMsgCrypt_EncryptAES_Error, None
对解密后的明文进行补位删除
def decrypt(self, text, appid): """对解密后的明文进行补位删除 @param text: 密文 @return: 删除填充补位后的明文 """ try: cryptor = AES.new(self.key, self.mode, self.key[:16]) # 使用BASE64对密文进行解码,然后AES-CBC解密 plain_text = cryptor.decrypt(base64.b64decode(text)) except Exception: return WXBizMsgCrypt_DecryptAES_Error, None try: pad = ord(plain_text[-1]) # 去掉补位字符串 #pkcs7 = PKCS7Encoder() #plain_text = pkcs7.encode(plain_text) # 去除16位随机字符串 content = plain_text[16:-pad] xml_len = socket.ntohl(struct.unpack("I", content[:4])[0]) xml_content = content[4:xml_len+4] from_appid = content[xml_len+4:] except Exception: return WXBizMsgCrypt_IllegalBuffer, None if from_appid != appid: return WXBizMsgCrypt_ValidateAppidOrCorpid_Error, None return 0, xml_content
随机生成16位字符串
def get_random_str(self): """ 随机生成16位字符串 @return: 16位字符串 """ rule = string.letters + string.digits str = random.sample(rule, 16) return "".join(str)
Get delivery log from Redis
def deliveries(self): """ Get delivery log from Redis""" key = make_key( event=self.object.event, owner_name=self.object.owner.username, identifier=self.object.identifier ) return redis.lrange(key, 0, 20)
Get the possible events from settings
def event_choices(events): """ Get the possible events from settings """ if events is None: msg = "Please add some events in settings.WEBHOOK_EVENTS." raise ImproperlyConfigured(msg) try: choices = [(x, x) for x in events] except TypeError: """ Not a valid iterator, so we raise an exception """ msg = "settings.WEBHOOK_EVENTS must be an iterable object." raise ImproperlyConfigured(msg) return choices
This is an asynchronous sender callable that uses the Django ORM to store webhooks. Redis is used to handle the message queue.
def worker(wrapped, dkwargs, hash_value=None, *args, **kwargs): """ This is an asynchronous sender callable that uses the Django ORM to store webhooks. Redis is used to handle the message queue. dkwargs argument requires the following key/values: :event: A string representing an event. kwargs argument requires the following key/values :owner: The user who created/owns the event """ if "event" not in dkwargs: msg = "djwebhooks.decorators.redis_hook requires an 'event' argument in the decorator." raise TypeError(msg) event = dkwargs['event'] if "owner" not in kwargs: msg = "djwebhooks.senders.redis_callable requires an 'owner' argument in the decorated function." raise TypeError(msg) owner = kwargs['owner'] if "identifier" not in kwargs: msg = "djwebhooks.senders.orm_callable requires an 'identifier' argument in the decorated function." raise TypeError(msg) identifier = kwargs['identifier'] senderobj = DjangoRQSenderable( wrapped, dkwargs, hash_value, WEBHOOK_ATTEMPTS, *args, **kwargs ) # Add the webhook object just so it's around # TODO - error handling if this can't be found senderobj.webhook_target = WebhookTarget.objects.get( event=event, owner=owner, identifier=identifier ) # Get the target url and add it senderobj.url = senderobj.webhook_target.target_url # Get the payload. This overides the senderobj.payload property. senderobj.payload = senderobj.get_payload() # Get the creator and add it to the payload. senderobj.payload['owner'] = getattr(kwargs['owner'], WEBHOOK_OWNER_FIELD) # get the event and add it to the payload senderobj.payload['event'] = dkwargs['event'] return senderobj.send()
TODO: Add code to lpush to redis stack rpop when stack hits size X
def notify(self, message): """ TODO: Add code to lpush to redis stack rpop when stack hits size 'X' """ data = dict( payload=self.payload, attempt=self.attempt, success=self.success, response_message=self.response_content, hash_value=self.hash_value, response_status=self.response.status_code, notification=message, created=timezone.now() ) value = json.dumps(data, cls=StandardJSONEncoder) key = make_key(self.event, self.owner.username, self.identifier) redis.lpush(key, value)
Encodes data to slip protocol and then sends over serial port
def send(self, msg): """Encodes data to slip protocol and then sends over serial port Uses the SlipLib module to convert the message data into SLIP format. The message is then sent over the serial port opened with the instance of the Faraday class used when invoking send(). Args: msg (bytes): Bytes format message to send over serial port. Returns: int: Number of bytes transmitted over the serial port. """ # Create a sliplib Driver slipDriver = sliplib.Driver() # Package data in slip format slipData = slipDriver.send(msg) # Send data over serial port res = self._serialPort.write(slipData) # Return number of bytes transmitted over serial port return res
Reads in data from a serial port ( length bytes ) decodes SLIP packets
def receive(self, length): """Reads in data from a serial port (length bytes), decodes SLIP packets A function which reads from the serial port and then uses the SlipLib module to decode the SLIP protocol packets. Each message received is added to a receive buffer in SlipLib which is then returned. Args: length (int): Length to receive with serialPort.read(length) Returns: bytes: An iterator of the receive buffer """ # Create a sliplib Driver slipDriver = sliplib.Driver() # Receive data from serial port ret = self._serialPort.read(length) # Decode data from slip format, stores msgs in sliplib.Driver.messages temp = slipDriver.receive(ret) return iter(temp)
Checks the TUN adapter for data and returns any that is found.
def checkTUN(self): """ Checks the TUN adapter for data and returns any that is found. Returns: packet: Data read from the TUN adapter """ packet = self._TUN._tun.read(self._TUN._tun.mtu) return(packet)
Monitors the TUN adapter and sends data over serial port.
def monitorTUN(self): """ Monitors the TUN adapter and sends data over serial port. Returns: ret: Number of bytes sent over serial port """ packet = self.checkTUN() if packet: try: # TODO Do I need to strip off [4:] before sending? ret = self._faraday.send(packet) return ret except AttributeError as error: # AttributeError was encounteredthreading.Event() print("AttributeError")
Check the serial port for data to write to the TUN adapter.
def checkSerial(self): """ Check the serial port for data to write to the TUN adapter. """ for item in self.rxSerial(self._TUN._tun.mtu): # print("about to send: {0}".format(item)) try: self._TUN._tun.write(item) except pytun.Error as error: print("pytun error writing: {0}".format(item)) print(error)
Wrapper function for TUN and serial port monitoring
def run(self): """ Wrapper function for TUN and serial port monitoring Wraps the necessary functions to loop over until self._isRunning threading.Event() is set(). This checks for data on the TUN/serial interfaces and then sends data over the appropriate interface. This function is automatically run when Threading.start() is called on the Monitor class. """ while self.isRunning.is_set(): try: try: # self.checkTUN() self.monitorTUN() except timeout_decorator.TimeoutError as error: # No data received so just move on pass self.checkSerial() except KeyboardInterrupt: break
Helper function to generate formsets for add/ change_view.
def _create_formsets(self, request, obj, change, index, is_template): "Helper function to generate formsets for add/change_view." formsets = [] inline_instances = [] prefixes = defaultdict(int) get_formsets_args = [request] if change: get_formsets_args.append(obj) base_prefix = self.get_formset(request).get_default_prefix() for FormSet, inline in self.get_formsets_with_inlines( *get_formsets_args): prefix = base_prefix + '-' + FormSet.get_default_prefix() if not is_template: prefix += '-%s' % index prefixes[prefix] += 1 if prefixes[prefix] != 1 or not prefix: prefix = "%s-%s" % (prefix, prefixes[prefix]) formset_params = { 'instance': obj, 'prefix': prefix, 'queryset': inline.get_queryset(request), } if request.method == 'POST': formset_params.update({ 'data': request.POST, 'files': request.FILES, 'save_as_new': '_saveasnew' in request.POST }) formset = FormSet(**formset_params) formset.has_parent = True formsets.append(formset) inline_instances.append(inline) return formsets, inline_instances
Get the field settings if the configured setting is a string try to get a profile from the global config.
def get_field_settings(self): """ Get the field settings, if the configured setting is a string try to get a 'profile' from the global config. """ field_settings = None if self.field_settings: if isinstance(self.field_settings, six.string_types): profiles = settings.CONFIG.get(self.PROFILE_KEY, {}) field_settings = profiles.get(self.field_settings) else: field_settings = self.field_settings return field_settings
Pass the submitted value through the sanitizer before returning it.
def value_from_datadict(self, *args, **kwargs): """ Pass the submitted value through the sanitizer before returning it. """ value = super(RichTextWidget, self).value_from_datadict( *args, **kwargs) if value is not None: value = self.get_sanitizer()(value) return value
Get the field sanitizer.
def get_sanitizer(self): """ Get the field sanitizer. The priority is the first defined in the following order: - A sanitizer provided to the widget. - Profile (field settings) specific sanitizer, if defined in settings. - Global sanitizer defined in settings. - Simple no-op sanitizer which just returns the provided value. """ sanitizer = self.sanitizer if not sanitizer: default_sanitizer = settings.CONFIG.get(self.SANITIZER_KEY) field_settings = getattr(self, 'field_settings', None) if isinstance(field_settings, six.string_types): profiles = settings.CONFIG.get(self.SANITIZER_PROFILES_KEY, {}) sanitizer = profiles.get(field_settings, default_sanitizer) else: sanitizer = default_sanitizer if isinstance(sanitizer, six.string_types): sanitizer = import_string(sanitizer) return sanitizer or noop
Maxheap version of a heappop.
def heappop_max(heap): """Maxheap version of a heappop.""" lastelt = heap.pop() # raises appropriate IndexError if heap is empty if heap: returnitem = heap[0] heap[0] = lastelt _siftup_max(heap, 0) return returnitem return lastelt
Maxheap version of a heappop followed by a heappush.
def heapreplace_max(heap, item): """Maxheap version of a heappop followed by a heappush.""" returnitem = heap[0] # raises appropriate IndexError if heap is empty heap[0] = item _siftup_max(heap, 0) return returnitem
Push item onto heap maintaining the heap invariant.
def heappush_max(heap, item): """Push item onto heap, maintaining the heap invariant.""" heap.append(item) _siftdown_max(heap, 0, len(heap) - 1)
Fast version of a heappush followed by a heappop.
def heappushpop_max(heap, item): """Fast version of a heappush followed by a heappop.""" if heap and heap[0] > item: # if item >= heap[0], it will be popped immediately after pushed item, heap[0] = heap[0], item _siftup_max(heap, 0) return item
Decorator to validate responses from QTM
def validate_response(expected_responses): """ Decorator to validate responses from QTM """ def internal_decorator(function): @wraps(function) async def wrapper(*args, **kwargs): response = await function(*args, **kwargs) for expected_response in expected_responses: if response.startswith(expected_response): return response raise QRTCommandException( "Expected %s but got %s" % (expected_responses, response) ) return wrapper return internal_decorator
Async function to connect to QTM
async def connect( host, port=22223, version="1.19", on_event=None, on_disconnect=None, timeout=5, loop=None, ) -> QRTConnection: """Async function to connect to QTM :param host: Address of the computer running QTM. :param port: Port number to connect to, should be the port configured for little endian. :param version: What version of the protocol to use, tested for 1.17 and above but could work with lower versions as well. :param on_disconnect: Function to be called when a disconnect from QTM occurs. :param on_event: Function to be called when there's an event from QTM. :param timeout: The default timeout time for calls to QTM. :param loop: Alternative event loop, will use asyncio default if None. :rtype: A :class:`.QRTConnection` """ loop = loop or asyncio.get_event_loop() try: _, protocol = await loop.create_connection( lambda: QTMProtocol( loop=loop, on_event=on_event, on_disconnect=on_disconnect ), host, port, ) except (ConnectionRefusedError, TimeoutError, OSError) as exception: LOG.error(exception) return None try: await protocol.set_version(version) except QRTCommandException as exception: LOG.error(Exception) return None except TypeError as exception: # TODO: fix test requiring this (test_connect_set_version) LOG.error(exception) return None return QRTConnection(protocol, timeout=timeout)
Get the QTM version.
async def qtm_version(self): """Get the QTM version. """ return await asyncio.wait_for( self._protocol.send_command("qtmversion"), timeout=self._timeout )
Get the byte order used when communicating ( should only ever be little endian using this library ).
async def byte_order(self): """Get the byte order used when communicating (should only ever be little endian using this library). """ return await asyncio.wait_for( self._protocol.send_command("byteorder"), timeout=self._timeout )
Get the latest state change of QTM. If the: func: ~qtm. connect on_event callback was set the callback will be called as well.
async def get_state(self): """Get the latest state change of QTM. If the :func:`~qtm.connect` on_event callback was set the callback will be called as well. :rtype: A :class:`qtm.QRTEvent` """ await self._protocol.send_command("getstate", callback=False) return await self._protocol.await_event()
Wait for an event from QTM.
async def await_event(self, event=None, timeout=30): """Wait for an event from QTM. :param event: A :class:`qtm.QRTEvent` to wait for a specific event. Otherwise wait for any event. :param timeout: Max time to wait for event. :rtype: A :class:`qtm.QRTEvent` """ return await self._protocol.await_event(event, timeout=timeout)
Get the settings for the requested component ( s ) of QTM in XML format.
async def get_parameters(self, parameters=None): """Get the settings for the requested component(s) of QTM in XML format. :param parameters: A list of parameters to request. Could be 'all' or any combination of 'general', '3d', '6d', 'analog', 'force', 'gazevector', 'image'. :rtype: An XML string containing the requested settings. See QTM RT Documentation for details. """ if parameters is None: parameters = ["all"] else: for parameter in parameters: if not parameter in [ "all", "general", "3d", "6d", "analog", "force", "gazevector", "image", "skeleton", "skeleton:global", ]: raise QRTCommandException("%s is not a valid parameter" % parameter) cmd = "getparameters %s" % " ".join(parameters) return await asyncio.wait_for( self._protocol.send_command(cmd), timeout=self._timeout )
Get measured values from QTM for a single frame.
async def get_current_frame(self, components=None) -> QRTPacket: """Get measured values from QTM for a single frame. :param components: A list of components to receive, could be 'all' or any combination of '2d', '2dlin', '3d', '3dres', '3dnolabels', '3dnolabelsres', 'force', 'forcesingle', '6d', '6dres', '6deuler', '6deulerres', 'gazevector', 'image', 'timecode', 'skeleton', 'skeleton:global' :rtype: A :class:`qtm.QRTPacket` containing requested components """ if components is None: components = ["all"] else: _validate_components(components) cmd = "getcurrentframe %s" % " ".join(components) return await asyncio.wait_for( self._protocol.send_command(cmd), timeout=self._timeout )
Stream measured frames from QTM until: func: ~qtm. QRTConnection. stream_frames_stop is called.
async def stream_frames(self, frames="allframes", components=None, on_packet=None): """Stream measured frames from QTM until :func:`~qtm.QRTConnection.stream_frames_stop` is called. :param frames: Which frames to receive, possible values are 'allframes', 'frequency:n' or 'frequencydivisor:n' where n should be desired value. :param components: A list of components to receive, could be 'all' or any combination of '2d', '2dlin', '3d', '3dres', '3dnolabels', '3dnolabelsres', 'force', 'forcesingle', '6d', '6dres', '6deuler', '6deulerres', 'gazevector', 'image', 'timecode', 'skeleton', 'skeleton:global' :rtype: The string 'Ok' if successful """ if components is None: components = ["all"] else: _validate_components(components) self._protocol.set_on_packet(on_packet) cmd = "streamframes %s %s" % (frames, " ".join(components)) return await asyncio.wait_for( self._protocol.send_command(cmd), timeout=self._timeout )
Stop streaming frames.
async def stream_frames_stop(self): """Stop streaming frames.""" self._protocol.set_on_packet(None) cmd = "streamframes stop" await self._protocol.send_command(cmd, callback=False)
Take control of QTM.
async def take_control(self, password): """Take control of QTM. :param password: Password as entered in QTM. """ cmd = "takecontrol %s" % password return await asyncio.wait_for( self._protocol.send_command(cmd), timeout=self._timeout )
Release control of QTM.
async def release_control(self): """Release control of QTM. """ cmd = "releasecontrol" return await asyncio.wait_for( self._protocol.send_command(cmd), timeout=self._timeout )
Start RT from file. You need to be in control of QTM to be able to do this.
async def start(self, rtfromfile=False): """Start RT from file. You need to be in control of QTM to be able to do this. """ cmd = "start" + (" rtfromfile" if rtfromfile else "") return await asyncio.wait_for( self._protocol.send_command(cmd), timeout=self._timeout )
Load a measurement.
async def load(self, filename): """Load a measurement. :param filename: Path to measurement you want to load. """ cmd = "load %s" % filename return await asyncio.wait_for( self._protocol.send_command(cmd), timeout=self._timeout )
Save a measurement.
async def save(self, filename, overwrite=False): """Save a measurement. :param filename: Filename you wish to save as. :param overwrite: If QTM should overwrite existing measurement. """ cmd = "save %s%s" % (filename, " overwrite" if overwrite else "") return await asyncio.wait_for( self._protocol.send_command(cmd), timeout=self._timeout )
Load a project.
async def load_project(self, project_path): """Load a project. :param project_path: Path to project you want to load. """ cmd = "loadproject %s" % project_path return await asyncio.wait_for( self._protocol.send_command(cmd), timeout=self._timeout )
Set event in QTM.
async def set_qtm_event(self, event=None): """Set event in QTM.""" cmd = "event%s" % ("" if event is None else " " + event) return await asyncio.wait_for( self._protocol.send_command(cmd), timeout=self._timeout )
Used to update QTM settings see QTM RT protocol for more information.
async def send_xml(self, xml): """Used to update QTM settings, see QTM RT protocol for more information. :param xml: XML document as a str. See QTM RT Documentation for details. """ return await asyncio.wait_for( self._protocol.send_command(xml, command_type=QRTPacketType.PacketXML), timeout=self._timeout, )
Received from QTM and route accordingly
def data_received(self, data): """ Received from QTM and route accordingly """ self._received_data += data h_size = RTheader.size data = self._received_data size, type_ = RTheader.unpack_from(data, 0) while len(data) >= size: self._parse_received(data[h_size:size], type_) data = data[size:] if len(data) < h_size: break size, type_ = RTheader.unpack_from(data, 0) self._received_data = data
Get analog data.
def get_analog(self, component_info=None, data=None, component_position=None): """Get analog data.""" components = [] append_components = components.append for _ in range(component_info.device_count): component_position, device = QRTPacket._get_exact( RTAnalogDevice, data, component_position ) if device.sample_count > 0: component_position, sample_number = QRTPacket._get_exact( RTSampleNumber, data, component_position ) RTAnalogChannel.format = struct.Struct( RTAnalogChannel.format_str % device.sample_count ) for _ in range(device.channel_count): component_position, channel = QRTPacket._get_tuple( RTAnalogChannel, data, component_position ) append_components((device, sample_number, channel)) return components
Get a single analog data channel.
def get_analog_single( self, component_info=None, data=None, component_position=None ): """Get a single analog data channel.""" components = [] append_components = components.append for _ in range(component_info.device_count): component_position, device = QRTPacket._get_exact( RTAnalogDeviceSingle, data, component_position ) RTAnalogDeviceSamples.format = struct.Struct( RTAnalogDeviceSamples.format_str % device.channel_count ) component_position, sample = QRTPacket._get_tuple( RTAnalogDeviceSamples, data, component_position ) append_components((device, sample)) return components
Get force data.
def get_force(self, component_info=None, data=None, component_position=None): """Get force data.""" components = [] append_components = components.append for _ in range(component_info.plate_count): component_position, plate = QRTPacket._get_exact( RTForcePlate, data, component_position ) force_list = [] for _ in range(plate.force_count): component_position, force = QRTPacket._get_exact( RTForce, data, component_position ) force_list.append(force) append_components((plate, force_list)) return components
Get a single force data channel.
def get_force_single(self, component_info=None, data=None, component_position=None): """Get a single force data channel.""" components = [] append_components = components.append for _ in range(component_info.plate_count): component_position, plate = QRTPacket._get_exact( RTForcePlateSingle, data, component_position ) component_position, force = QRTPacket._get_exact( RTForce, data, component_position ) append_components((plate, force)) return components
Get 6D data.
def get_6d(self, component_info=None, data=None, component_position=None): """Get 6D data.""" components = [] append_components = components.append for _ in range(component_info.body_count): component_position, position = QRTPacket._get_exact( RT6DBodyPosition, data, component_position ) component_position, matrix = QRTPacket._get_tuple( RT6DBodyRotation, data, component_position ) append_components((position, matrix)) return components
Get 6D data with euler rotations.
def get_6d_euler(self, component_info=None, data=None, component_position=None): """Get 6D data with euler rotations.""" components = [] append_components = components.append for _ in range(component_info.body_count): component_position, position = QRTPacket._get_exact( RT6DBodyPosition, data, component_position ) component_position, euler = QRTPacket._get_exact( RT6DBodyEuler, data, component_position ) append_components((position, euler)) return components
Get image.
def get_image(self, component_info=None, data=None, component_position=None): """Get image.""" components = [] append_components = components.append for _ in range(component_info.image_count): component_position, image_info = QRTPacket._get_exact( RTImage, data, component_position ) append_components((image_info, data[component_position:-1])) return components
Get 3D markers.
def get_3d_markers(self, component_info=None, data=None, component_position=None): """Get 3D markers.""" return self._get_3d_markers( RT3DMarkerPosition, component_info, data, component_position )
Get 3D markers with residual.
def get_3d_markers_residual( self, component_info=None, data=None, component_position=None ): """Get 3D markers with residual.""" return self._get_3d_markers( RT3DMarkerPositionResidual, component_info, data, component_position )
Get 3D markers without label.
def get_3d_markers_no_label( self, component_info=None, data=None, component_position=None ): """Get 3D markers without label.""" return self._get_3d_markers( RT3DMarkerPositionNoLabel, component_info, data, component_position )
Get 3D markers without label with residual.
def get_3d_markers_no_label_residual( self, component_info=None, data=None, component_position=None ): """Get 3D markers without label with residual.""" return self._get_3d_markers( RT3DMarkerPositionNoLabelResidual, component_info, data, component_position )
Get 2D markers.
def get_2d_markers( self, component_info=None, data=None, component_position=None, index=None ): """Get 2D markers. :param index: Specify which camera to get 2D from, will be returned as first entry in the returned array. """ return self._get_2d_markers( data, component_info, component_position, index=index )
Get 2D linearized markers.
def get_2d_markers_linearized( self, component_info=None, data=None, component_position=None, index=None ): """Get 2D linearized markers. :param index: Specify which camera to get 2D from, will be returned as first entry in the returned array. """ return self._get_2d_markers( data, component_info, component_position, index=index )
Get skeletons
def get_skeletons(self, component_info=None, data=None, component_position=None): """Get skeletons """ components = [] append_components = components.append for _ in range(component_info.skeleton_count): component_position, info = QRTPacket._get_exact( RTSegmentCount, data, component_position ) segments = [] for __ in range(info.segment_count): component_position, segment = QRTPacket._get_exact( RTSegmentId, data, component_position ) component_position, position = QRTPacket._get_exact( RTSegmentPosition, data, component_position ) component_position, rotation = QRTPacket._get_exact( RTSegmentRotation, data, component_position ) segments.append((segment.id, position, rotation)) append_components(segments) return components
Wait for any or specified event
async def await_event(self, event=None, timeout=None): """ Wait for any or specified event """ if self.event_future is not None: raise Exception("Can't wait on multiple events!") result = await asyncio.wait_for(self._wait_loop(event), timeout) return result
Sends commands to QTM
def send_command( self, command, callback=True, command_type=QRTPacketType.PacketCommand ): """ Sends commands to QTM """ if self.transport is not None: cmd_length = len(command) LOG.debug("S: %s", command) self.transport.write( struct.pack( RTCommand % cmd_length, RTheader.size + cmd_length + 1, command_type.value, command.encode(), b"\0", ) ) future = self.loop.create_future() if callback: self.request_queue.append(future) else: future.set_result(None) return future raise QRTCommandException("Not connected!")
async function to reboot QTM cameras
async def reboot(ip_address): """ async function to reboot QTM cameras """ _, protocol = await asyncio.get_event_loop().create_datagram_endpoint( QRebootProtocol, local_addr=(ip_address, 0), allow_broadcast=True, reuse_address=True, ) LOG.info("Sending reboot on %s", ip_address) protocol.send_reboot()
Callback function that is called everytime a data packet arrives from QTM
def on_packet(packet): """ Callback function that is called everytime a data packet arrives from QTM """ print("Framenumber: {}".format(packet.framenumber)) header, markers = packet.get_3d_markers() print("Component info: {}".format(header)) for marker in markers: print("\t", marker)
Main function
async def setup(): """ Main function """ connection = await qtm.connect("127.0.0.1") if connection is None: return await connection.stream_frames(components=["3d"], on_packet=on_packet)
On socket creation
def connection_made(self, transport): """ On socket creation """ self.transport = transport sock = transport.get_extra_info("socket") self.port = sock.getsockname()[1]
Parse response from QTM instances
def datagram_received(self, datagram, address): """ Parse response from QTM instances """ size, _ = RTheader.unpack_from(datagram, 0) info, = struct.unpack_from("{0}s".format(size - 3 - 8), datagram, RTheader.size) base_port, = QRTDiscoveryBasePort.unpack_from(datagram, size - 2) if self.receiver is not None: self.receiver(QRTDiscoveryResponse(info, address[0], base_port))
Send discovery packet for QTM to respond to
def send_discovery_packet(self): """ Send discovery packet for QTM to respond to """ if self.port is None: return self.transport.sendto( QRTDiscoveryP1.pack( QRTDiscoveryPacketSize, QRTPacketType.PacketDiscover.value ) + QRTDiscoveryP2.pack(self.port), ("<broadcast>", 22226), )
Asynchronous function that processes queue until None is posted in queue
async def packet_receiver(queue): """ Asynchronous function that processes queue until None is posted in queue """ LOG.info("Entering packet_receiver") while True: packet = await queue.get() if packet is None: break LOG.info("Framenumber %s", packet.framenumber) LOG.info("Exiting packet_receiver")
List running QTM instances asks for input and return chosen QTM
async def choose_qtm_instance(interface): """ List running QTM instances, asks for input and return chosen QTM """ instances = {} print("Available QTM instances:") async for i, qtm_instance in AsyncEnumerate(qtm.Discover(interface), start=1): instances[i] = qtm_instance print("{} - {}".format(i, qtm_instance.info)) try: choice = int(input("Connect to: ")) if choice not in instances: raise ValueError except ValueError: LOG.error("Invalid choice") return None return instances[choice].host
Main function
async def main(interface=None): """ Main function """ qtm_ip = await choose_qtm_instance(interface) if qtm_ip is None: return while True: connection = await qtm.connect(qtm_ip, 22223, version="1.18") if connection is None: return await connection.get_state() await connection.byte_order() async with qtm.TakeControl(connection, "password"): result = await connection.close() if result == b"Closing connection": await connection.await_event(qtm.QRTEvent.EventConnectionClosed) await connection.load(QTM_FILE) await connection.start(rtfromfile=True) (await connection.get_current_frame()).get_3d_markers() queue = asyncio.Queue() asyncio.ensure_future(packet_receiver(queue)) try: await connection.stream_frames( components=["incorrect"], on_packet=queue.put_nowait ) except qtm.QRTCommandException as exception: LOG.info("exception %s", exception) await connection.stream_frames( components=["3d"], on_packet=queue.put_nowait ) await asyncio.sleep(0.5) await connection.byte_order() await asyncio.sleep(0.5) await connection.stream_frames_stop() queue.put_nowait(None) await connection.get_parameters(parameters=["3d"]) await connection.stop() await connection.await_event() await connection.new() await connection.await_event(qtm.QRTEvent.EventConnected) await connection.start() await connection.await_event(qtm.QRTEvent.EventWaitingForTrigger) await connection.trig() await connection.await_event(qtm.QRTEvent.EventCaptureStarted) await asyncio.sleep(0.5) await connection.set_qtm_event() await asyncio.sleep(0.001) await connection.set_qtm_event("with_label") await asyncio.sleep(0.5) await connection.stop() await connection.await_event(qtm.QRTEvent.EventCaptureStopped) await connection.save(r"measurement.qtm") await asyncio.sleep(3) await connection.close() connection.disconnect()
Asynchronous function that processes queue until None is posted in queue
async def package_receiver(queue): """ Asynchronous function that processes queue until None is posted in queue """ LOG.info("Entering package_receiver") while True: packet = await queue.get() if packet is None: break LOG.info("Framenumber %s", packet.framenumber) header, cameras = packet.get_2d_markers() LOG.info("Component info: %s", header) for i, camera in enumerate(cameras, 1): LOG.info("Camera %d", i) for marker in camera: LOG.info("\t%s", marker) LOG.info("Exiting package_receiver")
main function
async def setup(): """ main function """ connection = await qtm.connect("127.0.0.1") if connection is None: return -1 async with qtm.TakeControl(connection, "password"): state = await connection.get_state() if state != qtm.QRTEvent.EventConnected: await connection.new() try: await connection.await_event(qtm.QRTEvent.EventConnected, timeout=10) except asyncio.TimeoutError: LOG.error("Failed to start new measurement") return -1 queue = asyncio.Queue() receiver_future = asyncio.ensure_future(package_receiver(queue)) await connection.stream_frames(components=["2d"], on_packet=queue.put_nowait) asyncio.ensure_future(shutdown(30, connection, receiver_future, queue))
Extract a name to index dictionary from 6dof settings xml
def create_body_index(xml_string): """ Extract a name to index dictionary from 6dof settings xml """ xml = ET.fromstring(xml_string) body_to_index = {} for index, body in enumerate(xml.findall("*/Body/Name")): body_to_index[body.text.strip()] = index return body_to_index
Try to find executable in the directories listed in path ( a string listing directories separated by os. pathsep ; defaults to os. environ [ PATH ] ).
def find_executable(executable, path=None): '''Try to find 'executable' in the directories listed in 'path' (a string listing directories separated by 'os.pathsep'; defaults to os.environ['PATH']).''' if path is None: path = os.environ['PATH'] paths = path.split(os.pathsep) extlist = [''] if os.name == 'os2': ext = os.path.splitext(executable) # executable files on OS/2 can have an arbitrary extension, but # .exe is automatically appended if no dot is present in the name if not ext: executable = executable + ".exe" elif sys.platform == 'win32': pathext = os.environ['PATHEXT'].lower().split(os.pathsep) ext = os.path.splitext(executable) if ext not in pathext: extlist = pathext for ext in extlist: execname = executable + ext if os.path.isfile(execname): return execname else: for pth in paths: fil = os.path.join(pth, execname) if os.path.isfile(fil): return fil break else: return None
Return true if substring is in string for files in specified path
def find_x(path1): '''Return true if substring is in string for files in specified path''' libs = os.listdir(path1) for lib_dir in libs: if "doublefann" in lib_dir: return True
Find doublefann library
def find_fann(): '''Find doublefann library''' # FANN possible libs directories (as $LD_LIBRARY_PATH), also includes # pkgsrc framework support. if sys.platform == "win32": dirs = sys.path for ver in dirs: if os.path.isdir(ver): if find_x(ver): return True raise Exception("Couldn't find FANN source libs!") else: dirs = ['/lib', '/usr/lib', '/usr/lib64', '/usr/local/lib', '/usr/pkg/lib'] for path in dirs: if os.path.isdir(path): if find_x(path): return True raise Exception("Couldn't find FANN source libs!")
Run SWIG with specified parameters
def build_swig(): '''Run SWIG with specified parameters''' print("Looking for FANN libs...") find_fann() print("running SWIG...") swig_bin = find_swig() swig_cmd = [swig_bin, '-c++', '-python', 'fann2/fann2.i'] subprocess.Popen(swig_cmd).wait()
Commands for experiments.
def experiment(ctx, project, experiment): # pylint:disable=redefined-outer-name """Commands for experiments.""" ctx.obj = ctx.obj or {} ctx.obj['project'] = project ctx.obj['experiment'] = experiment
Get experiment or experiment job.
def get(ctx, job): """Get experiment or experiment job. Uses [Caching](/references/polyaxon-cli/#caching) Examples for getting an experiment: \b ```bash $ polyaxon experiment get # if experiment is cached ``` \b ```bash $ polyaxon experiment --experiment=1 get ``` \b ```bash $ polyaxon experiment -xp 1 --project=cats-vs-dogs get ``` \b ```bash $ polyaxon experiment -xp 1 -p alain/cats-vs-dogs get ``` Examples for getting an experiment job: \b ```bash $ polyaxon experiment get -j 1 # if experiment is cached ``` \b ```bash $ polyaxon experiment --experiment=1 get --job=10 ``` \b ```bash $ polyaxon experiment -xp 1 --project=cats-vs-dogs get -j 2 ``` \b ```bash $ polyaxon experiment -xp 1 -p alain/cats-vs-dogs get -j 2 ``` """ def get_experiment(): try: response = PolyaxonClient().experiment.get_experiment(user, project_name, _experiment) cache.cache(config_manager=ExperimentManager, response=response) except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e: Printer.print_error('Could not load experiment `{}` info.'.format(_experiment)) Printer.print_error('Error message `{}`.'.format(e)) sys.exit(1) get_experiment_details(response) def get_experiment_job(): try: response = PolyaxonClient().experiment_job.get_job(user, project_name, _experiment, _job) cache.cache(config_manager=ExperimentJobManager, response=response) except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e: Printer.print_error('Could not get job `{}`.'.format(_job)) Printer.print_error('Error message `{}`.'.format(e)) sys.exit(1) if response.resources: get_resources(response.resources.to_dict(), header="Job resources:") response = Printer.add_status_color(response.to_light_dict( humanize_values=True, exclude_attrs=['uuid', 'definition', 'experiment', 'unique_name', 'resources'] )) Printer.print_header("Job info:") dict_tabulate(response) user, project_name, _experiment = get_project_experiment_or_local(ctx.obj.get('project'), ctx.obj.get('experiment')) if job: _job = get_experiment_job_or_local(job) get_experiment_job() else: get_experiment()
Delete experiment.
def delete(ctx): """Delete experiment. Uses [Caching](/references/polyaxon-cli/#caching) Example: \b ```bash $ polyaxon experiment delete ``` """ user, project_name, _experiment = get_project_experiment_or_local(ctx.obj.get('project'), ctx.obj.get('experiment')) if not click.confirm("Are sure you want to delete experiment `{}`".format(_experiment)): click.echo('Existing without deleting experiment.') sys.exit(1) try: response = PolyaxonClient().experiment.delete_experiment( user, project_name, _experiment) # Purge caching ExperimentManager.purge() except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e: Printer.print_error('Could not delete experiment `{}`.'.format(_experiment)) Printer.print_error('Error message `{}`.'.format(e)) sys.exit(1) if response.status_code == 204: Printer.print_success("Experiment `{}` was delete successfully".format(_experiment))
Update experiment.
def update(ctx, name, description, tags): """Update experiment. Uses [Caching](/references/polyaxon-cli/#caching) Examples: \b ```bash $ polyaxon experiment -xp 2 update --description="new description for my experiments" ``` \b ```bash $ polyaxon experiment -xp 2 update --tags="foo, bar" --name="unique-name" ``` """ user, project_name, _experiment = get_project_experiment_or_local(ctx.obj.get('project'), ctx.obj.get('experiment')) update_dict = {} if name: update_dict['name'] = name if description: update_dict['description'] = description tags = validate_tags(tags) if tags: update_dict['tags'] = tags if not update_dict: Printer.print_warning('No argument was provided to update the experiment.') sys.exit(0) try: response = PolyaxonClient().experiment.update_experiment( user, project_name, _experiment, update_dict) except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e: Printer.print_error('Could not update experiment `{}`.'.format(_experiment)) Printer.print_error('Error message `{}`.'.format(e)) sys.exit(1) Printer.print_success("Experiment updated.") get_experiment_details(response)
Stop experiment.
def stop(ctx, yes): """Stop experiment. Uses [Caching](/references/polyaxon-cli/#caching) Examples: \b ```bash $ polyaxon experiment stop ``` \b ```bash $ polyaxon experiment -xp 2 stop ``` """ user, project_name, _experiment = get_project_experiment_or_local(ctx.obj.get('project'), ctx.obj.get('experiment')) if not yes and not click.confirm("Are sure you want to stop " "experiment `{}`".format(_experiment)): click.echo('Existing without stopping experiment.') sys.exit(0) try: PolyaxonClient().experiment.stop(user, project_name, _experiment) except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e: Printer.print_error('Could not stop experiment `{}`.'.format(_experiment)) Printer.print_error('Error message `{}`.'.format(e)) sys.exit(1) Printer.print_success("Experiment is being stopped.")
Restart experiment.
def restart(ctx, copy, file, u): # pylint:disable=redefined-builtin """Restart experiment. Uses [Caching](/references/polyaxon-cli/#caching) Examples: \b ```bash $ polyaxon experiment --experiment=1 restart ``` """ config = None update_code = None if file: config = rhea.read(file) # Check if we need to upload if u: ctx.invoke(upload, sync=False) update_code = True user, project_name, _experiment = get_project_experiment_or_local(ctx.obj.get('project'), ctx.obj.get('experiment')) try: if copy: response = PolyaxonClient().experiment.copy( user, project_name, _experiment, config=config, update_code=update_code) Printer.print_success('Experiment was copied with id {}'.format(response.id)) else: response = PolyaxonClient().experiment.restart( user, project_name, _experiment, config=config, update_code=update_code) Printer.print_success('Experiment was restarted with id {}'.format(response.id)) except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e: Printer.print_error('Could not restart experiment `{}`.'.format(_experiment)) Printer.print_error('Error message `{}`.'.format(e)) sys.exit(1)
Get experiment or experiment job statuses.
def statuses(ctx, job, page): """Get experiment or experiment job statuses. Uses [Caching](/references/polyaxon-cli/#caching) Examples getting experiment statuses: \b ```bash $ polyaxon experiment statuses ``` \b ```bash $ polyaxon experiment -xp 1 statuses ``` Examples getting experiment job statuses: \b ```bash $ polyaxon experiment statuses -j 3 ``` \b ```bash $ polyaxon experiment -xp 1 statuses --job 1 ``` """ def get_experiment_statuses(): try: response = PolyaxonClient().experiment.get_statuses( user, project_name, _experiment, page=page) except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e: Printer.print_error('Could get status for experiment `{}`.'.format(_experiment)) Printer.print_error('Error message `{}`.'.format(e)) sys.exit(1) meta = get_meta_response(response) if meta: Printer.print_header('Statuses for experiment `{}`.'.format(_experiment)) Printer.print_header('Navigation:') dict_tabulate(meta) else: Printer.print_header('No statuses found for experiment `{}`.'.format(_experiment)) objects = list_dicts_to_tabulate( [Printer.add_status_color(o.to_light_dict(humanize_values=True), status_key='status') for o in response['results']]) if objects: Printer.print_header("Statuses:") objects.pop('experiment', None) dict_tabulate(objects, is_list_dict=True) def get_experiment_job_statuses(): try: response = PolyaxonClient().experiment_job.get_statuses(user, project_name, _experiment, _job, page=page) except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e: Printer.print_error('Could not get status for job `{}`.'.format(job)) Printer.print_error('Error message `{}`.'.format(e)) sys.exit(1) meta = get_meta_response(response) if meta: Printer.print_header('Statuses for Job `{}`.'.format(_job)) Printer.print_header('Navigation:') dict_tabulate(meta) else: Printer.print_header('No statuses found for job `{}`.'.format(_job)) objects = list_dicts_to_tabulate( [Printer.add_status_color(o.to_light_dict(humanize_values=True), status_key='status') for o in response['results']]) if objects: Printer.print_header("Statuses:") objects.pop('job', None) dict_tabulate(objects, is_list_dict=True) page = page or 1 user, project_name, _experiment = get_project_experiment_or_local(ctx.obj.get('project'), ctx.obj.get('experiment')) if job: _job = get_experiment_job_or_local(job) get_experiment_job_statuses() else: get_experiment_statuses()
Get experiment or experiment job resources.
def resources(ctx, job, gpu): """Get experiment or experiment job resources. Uses [Caching](/references/polyaxon-cli/#caching) Examples for getting experiment resources: \b ```bash $ polyaxon experiment -xp 19 resources ``` For GPU resources \b ```bash $ polyaxon experiment -xp 19 resources --gpu ``` Examples for getting experiment job resources: \b ```bash $ polyaxon experiment -xp 19 resources -j 1 ``` For GPU resources \b ```bash $ polyaxon experiment -xp 19 resources -j 1 --gpu ``` """ def get_experiment_resources(): try: message_handler = Printer.gpu_resources if gpu else Printer.resources PolyaxonClient().experiment.resources( user, project_name, _experiment, message_handler=message_handler) except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e: Printer.print_error('Could not get resources for experiment `{}`.'.format(_experiment)) Printer.print_error('Error message `{}`.'.format(e)) sys.exit(1) def get_experiment_job_resources(): try: message_handler = Printer.gpu_resources if gpu else Printer.resources PolyaxonClient().experiment_job.resources(user, project_name, _experiment, _job, message_handler=message_handler) except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e: Printer.print_error('Could not get resources for job `{}`.'.format(_job)) Printer.print_error('Error message `{}`.'.format(e)) sys.exit(1) user, project_name, _experiment = get_project_experiment_or_local(ctx.obj.get('project'), ctx.obj.get('experiment')) if job: _job = get_experiment_job_or_local(job) get_experiment_job_resources() else: get_experiment_resources()
Get experiment or experiment job logs.
def logs(ctx, job, past, follow, hide_time): """Get experiment or experiment job logs. Uses [Caching](/references/polyaxon-cli/#caching) Examples for getting experiment logs: \b ```bash $ polyaxon experiment logs ``` \b ```bash $ polyaxon experiment -xp 10 -p mnist logs ``` Examples for getting experiment job logs: \b ```bash $ polyaxon experiment -xp 1 -j 1 logs ``` """ def get_experiment_logs(): if past: try: response = PolyaxonClient().experiment.logs( user, project_name, _experiment, stream=False) get_logs_handler(handle_job_info=True, show_timestamp=not hide_time, stream=False)(response.content.decode().split('\n')) print() if not follow: return except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e: if not follow: Printer.print_error( 'Could not get logs for experiment `{}`.'.format(_experiment)) Printer.print_error( 'Error message `{}`.'.format(e)) sys.exit(1) try: PolyaxonClient().experiment.logs( user, project_name, _experiment, message_handler=get_logs_handler(handle_job_info=True, show_timestamp=not hide_time)) except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e: Printer.print_error('Could not get logs for experiment `{}`.'.format(_experiment)) Printer.print_error('Error message `{}`.'.format(e)) sys.exit(1) def get_experiment_job_logs(): if past: try: response = PolyaxonClient().experiment_job.logs( user, project_name, _experiment, _job, stream=False) get_logs_handler(handle_job_info=True, show_timestamp=not hide_time, stream=False)(response.content.decode().split('\n')) print() if not follow: return except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e: if not follow: Printer.print_error( 'Could not get logs for experiment `{}`.'.format(_experiment)) Printer.print_error( 'Error message `{}`.'.format(e)) sys.exit(1) try: PolyaxonClient().experiment_job.logs( user, project_name, _experiment, _job, message_handler=get_logs_handler(handle_job_info=True, show_timestamp=not hide_time)) except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e: Printer.print_error('Could not get logs for job `{}`.'.format(_job)) Printer.print_error('Error message `{}`.'.format(e)) sys.exit(1) user, project_name, _experiment = get_project_experiment_or_local(ctx.obj.get('project'), ctx.obj.get('experiment')) if job: _job = get_experiment_job_or_local(job) get_experiment_job_logs() else: get_experiment_logs()
Unbookmark experiment.
def unbookmark(ctx): """Unbookmark experiment. Uses [Caching](/references/polyaxon-cli/#caching) Examples: \b ```bash $ polyaxon experiment unbookmark ``` \b ```bash $ polyaxon experiment -xp 2 unbookmark ``` """ user, project_name, _experiment = get_project_experiment_or_local(ctx.obj.get('project'), ctx.obj.get('experiment')) try: PolyaxonClient().experiment.unbookmark(user, project_name, _experiment) except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e: Printer.print_error('Could not unbookmark experiment `{}`.'.format(_experiment)) Printer.print_error('Error message `{}`.'.format(e)) sys.exit(1) Printer.print_success("Experiment is unbookmarked.")
Upload code of the current directory while respecting the. polyaxonignore file.
def upload(sync=True): # pylint:disable=assign-to-new-keyword """Upload code of the current directory while respecting the .polyaxonignore file.""" project = ProjectManager.get_config_or_raise() files = IgnoreManager.get_unignored_file_paths() try: with create_tarfile(files, project.name) as file_path: with get_files_in_current_directory('repo', [file_path]) as (files, files_size): try: PolyaxonClient().project.upload_repo(project.user, project.name, files, files_size, sync=sync) except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e: Printer.print_error( 'Could not upload code for project `{}`.'.format(project.name)) Printer.print_error('Error message `{}`.'.format(e)) Printer.print_error( 'Check the project exists, ' 'and that you have access rights, ' 'this could happen as well when uploading large files.' 'If you are running a notebook and mounting the code to the notebook, ' 'you should stop it before uploading.') sys.exit(1) Printer.print_success('Files uploaded.') except Exception as e: Printer.print_error("Could not upload the file.") Printer.print_error('Error message `{}`.'.format(e)) sys.exit(1)
Get cluster and nodes info.
def cluster(node): """Get cluster and nodes info.""" cluster_client = PolyaxonClient().cluster if node: try: node_config = cluster_client.get_node(node) except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e: Printer.print_error('Could not load node `{}` info.'.format(node)) Printer.print_error('Error message `{}`.'.format(e)) sys.exit(1) get_node_info(node_config) else: try: cluster_config = cluster_client.get_cluster() except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e: Printer.print_error('Could not load cluster info.') Printer.print_error('Error message `{}`.'.format(e)) sys.exit(1) get_cluster_info(cluster_config)
Check a polyaxonfile.
def check(file, # pylint:disable=redefined-builtin version, definition): """Check a polyaxonfile.""" file = file or 'polyaxonfile.yaml' specification = check_polyaxonfile(file).specification if version: Printer.decorate_format_value('The version is: {}', specification.version, 'yellow') if definition: job_condition = (specification.is_job or specification.is_build or specification.is_notebook or specification.is_tensorboard) if specification.is_experiment: Printer.decorate_format_value('This polyaxon specification has {}', 'One experiment', 'yellow') if job_condition: Printer.decorate_format_value('This {} polyaxon specification is valid', specification.kind, 'yellow') if specification.is_group: experiments_def = specification.experiments_def click.echo( 'This polyaxon specification has experiment group with the following definition:') get_group_experiments_info(**experiments_def) return specification
Decorator for CLI with Sentry client handling.
def clean_outputs(fn): """Decorator for CLI with Sentry client handling. see https://github.com/getsentry/raven-python/issues/904 for more details. """ @wraps(fn) def clean_outputs_wrapper(*args, **kwargs): try: return fn(*args, **kwargs) except SystemExit as e: sys.stdout = StringIO() sys.exit(e.code) # make sure we still exit with the proper code except Exception as e: sys.stdout = StringIO() raise e return clean_outputs_wrapper
Commands for jobs.
def job(ctx, project, job): # pylint:disable=redefined-outer-name """Commands for jobs.""" ctx.obj = ctx.obj or {} ctx.obj['project'] = project ctx.obj['job'] = job
Get job.
def get(ctx): """Get job. Uses [Caching](/references/polyaxon-cli/#caching) Examples: \b ```bash $ polyaxon job --job=1 get ``` \b ```bash $ polyaxon job --job=1 --project=project_name get ``` """ user, project_name, _job = get_job_or_local(ctx.obj.get('project'), ctx.obj.get('job')) try: response = PolyaxonClient().job.get_job(user, project_name, _job) cache.cache(config_manager=JobManager, response=response) except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e: Printer.print_error('Could not get job `{}`.'.format(_job)) Printer.print_error('Error message `{}`.'.format(e)) sys.exit(1) get_job_details(response)
Delete job.
def delete(ctx): """Delete job. Uses [Caching](/references/polyaxon-cli/#caching) Example: \b ```bash $ polyaxon job delete ``` """ user, project_name, _job = get_job_or_local(ctx.obj.get('project'), ctx.obj.get('job')) if not click.confirm("Are sure you want to delete job `{}`".format(_job)): click.echo('Existing without deleting job.') sys.exit(1) try: response = PolyaxonClient().job.delete_job( user, project_name, _job) # Purge caching JobManager.purge() except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e: Printer.print_error('Could not delete job `{}`.'.format(_job)) Printer.print_error('Error message `{}`.'.format(e)) sys.exit(1) if response.status_code == 204: Printer.print_success("Job `{}` was delete successfully".format(_job))
Update job.
def update(ctx, name, description, tags): """Update job. Uses [Caching](/references/polyaxon-cli/#caching) Example: \b ```bash $ polyaxon job -j 2 update --description="new description for my job" ``` """ user, project_name, _job = get_job_or_local(ctx.obj.get('project'), ctx.obj.get('job')) update_dict = {} if name: update_dict['name'] = name if description: update_dict['description'] = description tags = validate_tags(tags) if tags: update_dict['tags'] = tags if not update_dict: Printer.print_warning('No argument was provided to update the job.') sys.exit(0) try: response = PolyaxonClient().job.update_job( user, project_name, _job, update_dict) except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e: Printer.print_error('Could not update job `{}`.'.format(_job)) Printer.print_error('Error message `{}`.'.format(e)) sys.exit(1) Printer.print_success("Job updated.") get_job_details(response)
Stop job.
def stop(ctx, yes): """Stop job. Uses [Caching](/references/polyaxon-cli/#caching) Examples: \b ```bash $ polyaxon job stop ``` \b ```bash $ polyaxon job -xp 2 stop ``` """ user, project_name, _job = get_job_or_local(ctx.obj.get('project'), ctx.obj.get('job')) if not yes and not click.confirm("Are sure you want to stop " "job `{}`".format(_job)): click.echo('Existing without stopping job.') sys.exit(0) try: PolyaxonClient().job.stop(user, project_name, _job) except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e: Printer.print_error('Could not stop job `{}`.'.format(_job)) Printer.print_error('Error message `{}`.'.format(e)) sys.exit(1) Printer.print_success("Job is being stopped.")
Restart job.
def restart(ctx, copy, file, u): # pylint:disable=redefined-builtin """Restart job. Uses [Caching](/references/polyaxon-cli/#caching) Examples: \b ```bash $ polyaxon job --job=1 restart ``` """ config = None update_code = None if file: config = rhea.read(file) # Check if we need to upload if u: ctx.invoke(upload, sync=False) update_code = True user, project_name, _job = get_job_or_local(ctx.obj.get('project'), ctx.obj.get('job')) try: if copy: response = PolyaxonClient().job.copy( user, project_name, _job, config=config, update_code=update_code) else: response = PolyaxonClient().job.restart( user, project_name, _job, config=config, update_code=update_code) except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e: Printer.print_error('Could not restart job `{}`.'.format(_job)) Printer.print_error('Error message `{}`.'.format(e)) sys.exit(1) get_job_details(response)