_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q261500 | OPCN2.config | validation | def config(self):
"""Read the configuration variables and returns them as a dictionary
:rtype: dictionary
:Example:
>>> alpha.config()
{
'BPD 13': 1.6499,
'BPD 12': 1.6499,
'BPD 11': 1.6499,
'BPD 10': 1.6499,
'BPD 15': 1.6499,
'BPD 14': 1.6499,
'BSVW 15': 1.0,
...
}
"""
config = []
data = {}
# Send the command byte and sleep for 10 ms
self.cnxn.xfer([0x3C])
sleep(10e-3)
# Read the config variables by sending 256 empty bytes
for i in range(256):
resp = self.cnxn.xfer([0x00])[0]
config.append(resp)
# Add the bin bounds to the dictionary of data [bytes 0-29]
for i in range(0, 15):
data["Bin Boundary {0}".format(i)] = self._16bit_unsigned(config[2*i], config[2*i + 1])
# Add the Bin Particle Volumes (BPV) [bytes 32-95]
for i in range(0, 16):
data["BPV {0}".format(i)] = self._calculate_float(config[4*i + 32:4*i + 36])
# Add the Bin Particle Densities (BPD) [bytes 96-159]
for i in range(0, 16):
data["BPD {0}".format(i)] = self._calculate_float(config[4*i + 96:4*i + 100])
# Add the Bin Sample Volume Weight (BSVW) [bytes 160-223]
for i in range(0, 16):
data["BSVW {0}".format(i)] = self._calculate_float(config[4*i + 160: 4*i + 164])
# Add the Gain Scaling Coefficient (GSC) and sample flow rate (SFR)
data["GSC"] = self._calculate_float(config[224:228])
data["SFR"] = self._calculate_float(config[228:232])
# Add laser dac (LDAC) and Fan dac (FanDAC)
data["LaserDAC"] = config[232]
data["FanDAC"] = config[233]
# If past firmware 15, add other things
if self.firmware['major'] > 15.:
data['TOF_SFR'] = config[234]
sleep(0.1)
return data | python | {
"resource": ""
} |
q261501 | OPCN2.config2 | validation | def config2(self):
"""Read the second set of configuration variables and return as a dictionary.
**NOTE: This method is supported by firmware v18+.**
:rtype: dictionary
:Example:
>>> a.config2()
{
'AMFanOnIdle': 0,
'AMIdleIntervalCount': 0,
'AMMaxDataArraysInFile': 61798,
'AMSamplingInterval': 1,
'AMOnlySavePMData': 0,
'AMLaserOnIdle': 0
}
"""
config = []
data = {}
# Send the command byte and sleep for 10 ms
self.cnxn.xfer([0x3D])
sleep(10e-3)
# Read the config variables by sending 256 empty bytes
for i in range(9):
resp = self.cnxn.xfer([0x00])[0]
config.append(resp)
data["AMSamplingInterval"] = self._16bit_unsigned(config[0], config[1])
data["AMIdleIntervalCount"] = self._16bit_unsigned(config[2], config[3])
data['AMFanOnIdle'] = config[4]
data['AMLaserOnIdle'] = config[5]
data['AMMaxDataArraysInFile'] = self._16bit_unsigned(config[6], config[7])
data['AMOnlySavePMData'] = config[8]
sleep(0.1)
return data | python | {
"resource": ""
} |
q261502 | OPCN2.set_fan_power | validation | def set_fan_power(self, power):
"""Set only the Fan power.
:param power: Fan power value as an integer between 0-255.
:type power: int
:rtype: boolean
:Example:
>>> alpha.set_fan_power(255)
True
"""
# Check to make sure the value is a single byte
if power > 255:
raise ValueError("The fan power should be a single byte (0-255).")
# Send the command byte and wait 10 ms
a = self.cnxn.xfer([0x42])[0]
sleep(10e-3)
# Send the next two bytes
b = self.cnxn.xfer([0x00])[0]
c = self.cnxn.xfer([power])[0]
sleep(0.1)
return True if a == 0xF3 and b == 0x42 and c == 0x00 else False | python | {
"resource": ""
} |
q261503 | OPCN2.toggle_laser | validation | def toggle_laser(self, state):
"""Toggle the power state of the laser.
:param state: Boolean state of the laser
:type state: boolean
:rtype: boolean
:Example:
>>> alpha.toggle_laser(True)
True
"""
# Send the command byte and wait 10 ms
a = self.cnxn.xfer([0x03])[0]
sleep(10e-3)
# If state is true, turn the laser ON, else OFF
if state:
b = self.cnxn.xfer([0x02])[0]
else:
b = self.cnxn.xfer([0x03])[0]
sleep(0.1)
return True if a == 0xF3 and b == 0x03 else False | python | {
"resource": ""
} |
q261504 | OPCN2.sn | validation | def sn(self):
"""Read the Serial Number string. This method is only available on OPC-N2
firmware versions 18+.
:rtype: string
:Example:
>>> alpha.sn()
'OPC-N2 123456789'
"""
string = []
# Send the command byte and sleep for 9 ms
self.cnxn.xfer([0x10])
sleep(9e-3)
# Read the info string by sending 60 empty bytes
for i in range(60):
resp = self.cnxn.xfer([0x00])[0]
string.append(chr(resp))
sleep(0.1)
return ''.join(string) | python | {
"resource": ""
} |
q261505 | OPCN2.read_firmware | validation | def read_firmware(self):
"""Read the firmware version of the OPC-N2. Firmware v18+ only.
:rtype: dict
:Example:
>>> alpha.read_firmware()
{
'major': 18,
'minor': 2,
'version': 18.2
}
"""
# Send the command byte and sleep for 9 ms
self.cnxn.xfer([0x12])
sleep(10e-3)
self.firmware['major'] = self.cnxn.xfer([0x00])[0]
self.firmware['minor'] = self.cnxn.xfer([0x00])[0]
# Build the firmware version
self.firmware['version'] = float('{}.{}'.format(self.firmware['major'], self.firmware['minor']))
sleep(0.1)
return self.firmware | python | {
"resource": ""
} |
q261506 | OPCN2.pm | validation | def pm(self):
"""Read the PM data and reset the histogram
**NOTE: This method is supported by firmware v18+.**
:rtype: dictionary
:Example:
>>> alpha.pm()
{
'PM1': 0.12,
'PM2.5': 0.24,
'PM10': 1.42
}
"""
resp = []
data = {}
# Send the command byte
self.cnxn.xfer([0x32])
# Wait 10 ms
sleep(10e-3)
# read the histogram
for i in range(12):
r = self.cnxn.xfer([0x00])[0]
resp.append(r)
# convert to real things and store in dictionary!
data['PM1'] = self._calculate_float(resp[0:4])
data['PM2.5'] = self._calculate_float(resp[4:8])
data['PM10'] = self._calculate_float(resp[8:])
sleep(0.1)
return data | python | {
"resource": ""
} |
q261507 | OPCN1.read_gsc_sfr | validation | def read_gsc_sfr(self):
"""Read the gain-scaling-coefficient and sample flow rate.
:returns: dictionary containing GSC and SFR
"""
config = []
data = {}
# Send the command byte and sleep for 10 ms
self.cnxn.xfer([0x33])
sleep(10e-3)
# Read the config variables by sending 256 empty bytes
for i in range(8):
resp = self.cnxn.xfer([0x00])[0]
config.append(resp)
data["GSC"] = self._calculate_float(config[0:4])
data["SFR"] = self._calculate_float(config[4:])
return data | python | {
"resource": ""
} |
q261508 | OPCN1.read_bin_boundaries | validation | def read_bin_boundaries(self):
"""Return the bin boundaries.
:returns: dictionary with 17 bin boundaries.
"""
config = []
data = {}
# Send the command byte and sleep for 10 ms
self.cnxn.xfer([0x33])
sleep(10e-3)
# Read the config variables by sending 256 empty bytes
for i in range(30):
resp = self.cnxn.xfer([0x00])[0]
config.append(resp)
# Add the bin bounds to the dictionary of data [bytes 0-29]
for i in range(0, 14):
data["Bin Boundary {0}".format(i)] = self._16bit_unsigned(config[2*i], config[2*i + 1])
return data | python | {
"resource": ""
} |
q261509 | OPCN1.read_bin_particle_density | validation | def read_bin_particle_density(self):
"""Read the bin particle density
:returns: float
"""
config = []
# Send the command byte and sleep for 10 ms
self.cnxn.xfer([0x33])
sleep(10e-3)
# Read the config variables by sending 256 empty bytes
for i in range(4):
resp = self.cnxn.xfer([0x00])[0]
config.append(resp)
bpd = self._calculate_float(config)
return bpd | python | {
"resource": ""
} |
q261510 | HDLController.start | validation | def start(self):
"""
Starts HDLC controller's threads.
"""
self.receiver = self.Receiver(
self.read,
self.write,
self.send_lock,
self.senders,
self.frames_received,
callback=self.receive_callback,
fcs_nack=self.fcs_nack,
)
self.receiver.start() | python | {
"resource": ""
} |
q261511 | HDLController.stop | validation | def stop(self):
"""
Stops HDLC controller's threads.
"""
if self.receiver != None:
self.receiver.join()
for s in self.senders.values():
s.join() | python | {
"resource": ""
} |
q261512 | HDLController.send | validation | def send(self, data):
"""
Sends a new data frame.
This method will block until a new room is available for
a new sender. This limit is determined by the size of the window.
"""
while len(self.senders) >= self.window:
pass
self.senders[self.new_seq_no] = self.Sender(
self.write,
self.send_lock,
data,
self.new_seq_no,
timeout=self.sending_timeout,
callback=self.send_callback,
)
self.senders[self.new_seq_no].start()
self.new_seq_no = (self.new_seq_no + 1) % HDLController.MAX_SEQ_NO | python | {
"resource": ""
} |
q261513 | Range.cut | validation | def cut(self, by, from_start=True):
""" Cuts this object from_start to the number requestd
returns new instance
"""
s, e = copy(self.start), copy(self.end)
if from_start:
e = s + by
else:
s = e - by
return Range(s, e) | python | {
"resource": ""
} |
q261514 | Date.replace | validation | def replace(self, **k):
"""Note returns a new Date obj"""
if self.date != 'infinity':
return Date(self.date.replace(**k))
else:
return Date('infinity') | python | {
"resource": ""
} |
q261515 | findall | validation | def findall(text):
"""Find all the timestrings within a block of text.
>>> timestring.findall("once upon a time, about 3 weeks ago, there was a boy whom was born on august 15th at 7:20 am. epic.")
[
('3 weeks ago,', <timestring.Date 2014-02-09 00:00:00 4483019280>),
('august 15th at 7:20 am', <timestring.Date 2014-08-15 07:20:00 4483019344>)
]
"""
results = TIMESTRING_RE.findall(text)
dates = []
for date in results:
if re.compile('((next|last)\s(\d+|couple(\sof))\s(weeks|months|quarters|years))|(between|from)', re.I).match(date[0]):
dates.append((date[0].strip(), Range(date[0])))
else:
dates.append((date[0].strip(), Date(date[0])))
return dates | python | {
"resource": ""
} |
q261516 | OAuthAuthentication.validate_token | validation | 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) | python | {
"resource": ""
} |
q261517 | OAuthAuthentication.check_nonce | validation | 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) | python | {
"resource": ""
} |
q261518 | WebhookTargetRedisDetailView.deliveries | validation | 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) | python | {
"resource": ""
} |
q261519 | event_choices | validation | 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 | python | {
"resource": ""
} |
q261520 | worker | validation | 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() | python | {
"resource": ""
} |
q261521 | Faraday.send | validation | 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 | python | {
"resource": ""
} |
q261522 | Monitor.checkTUN | validation | 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) | python | {
"resource": ""
} |
q261523 | Monitor.monitorTUN | validation | 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") | python | {
"resource": ""
} |
q261524 | Monitor.checkSerial | validation | 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) | python | {
"resource": ""
} |
q261525 | Monitor.run | validation | 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 | python | {
"resource": ""
} |
q261526 | RichTextWidget.get_field_settings | validation | 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 | python | {
"resource": ""
} |
q261527 | RichTextWidget.value_from_datadict | validation | 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 | python | {
"resource": ""
} |
q261528 | SanitizerMixin.get_sanitizer | validation | 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 | python | {
"resource": ""
} |
q261529 | heappop_max | validation | 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 | python | {
"resource": ""
} |
q261530 | heapreplace_max | validation | 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 | python | {
"resource": ""
} |
q261531 | heappush_max | validation | def heappush_max(heap, item):
"""Push item onto heap, maintaining the heap invariant."""
heap.append(item)
_siftdown_max(heap, 0, len(heap) - 1) | python | {
"resource": ""
} |
q261532 | heappushpop_max | validation | 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 | python | {
"resource": ""
} |
q261533 | validate_response | validation | 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 | python | {
"resource": ""
} |
q261534 | connect | validation | 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) | python | {
"resource": ""
} |
q261535 | QRTConnection.qtm_version | validation | async def qtm_version(self):
"""Get the QTM version.
"""
return await asyncio.wait_for(
self._protocol.send_command("qtmversion"), timeout=self._timeout
) | python | {
"resource": ""
} |
q261536 | QRTConnection.await_event | validation | 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) | python | {
"resource": ""
} |
q261537 | QRTConnection.get_current_frame | validation | 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
) | python | {
"resource": ""
} |
q261538 | QRTConnection.stream_frames_stop | validation | 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) | python | {
"resource": ""
} |
q261539 | QRTConnection.take_control | validation | 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
) | python | {
"resource": ""
} |
q261540 | QRTConnection.release_control | validation | async def release_control(self):
"""Release control of QTM.
"""
cmd = "releasecontrol"
return await asyncio.wait_for(
self._protocol.send_command(cmd), timeout=self._timeout
) | python | {
"resource": ""
} |
q261541 | QRTConnection.start | validation | 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
) | python | {
"resource": ""
} |
q261542 | QRTConnection.load | validation | 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
) | python | {
"resource": ""
} |
q261543 | QRTConnection.save | validation | 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
) | python | {
"resource": ""
} |
q261544 | QRTConnection.load_project | validation | 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
) | python | {
"resource": ""
} |
q261545 | QRTConnection.set_qtm_event | validation | 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
) | python | {
"resource": ""
} |
q261546 | QRTConnection.send_xml | validation | 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,
) | python | {
"resource": ""
} |
q261547 | Receiver.data_received | validation | 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 | python | {
"resource": ""
} |
q261548 | QRTPacket.get_analog | validation | 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 | python | {
"resource": ""
} |
q261549 | QRTPacket.get_analog_single | validation | 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 | python | {
"resource": ""
} |
q261550 | QRTPacket.get_force | validation | 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 | python | {
"resource": ""
} |
q261551 | QRTPacket.get_force_single | validation | 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 | python | {
"resource": ""
} |
q261552 | QRTPacket.get_6d | validation | 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 | python | {
"resource": ""
} |
q261553 | QRTPacket.get_6d_euler | validation | 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 | python | {
"resource": ""
} |
q261554 | QRTPacket.get_image | validation | 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 | python | {
"resource": ""
} |
q261555 | QRTPacket.get_3d_markers | validation | 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
) | python | {
"resource": ""
} |
q261556 | QRTPacket.get_3d_markers_residual | validation | 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
) | python | {
"resource": ""
} |
q261557 | QRTPacket.get_3d_markers_no_label | validation | 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
) | python | {
"resource": ""
} |
q261558 | QRTPacket.get_3d_markers_no_label_residual | validation | 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
) | python | {
"resource": ""
} |
q261559 | QRTPacket.get_2d_markers | validation | 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
) | python | {
"resource": ""
} |
q261560 | QRTPacket.get_2d_markers_linearized | validation | 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
) | python | {
"resource": ""
} |
q261561 | QTMProtocol.await_event | validation | 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 | python | {
"resource": ""
} |
q261562 | QTMProtocol.send_command | validation | 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!") | python | {
"resource": ""
} |
q261563 | reboot | validation | 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() | python | {
"resource": ""
} |
q261564 | on_packet | validation | 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) | python | {
"resource": ""
} |
q261565 | QRTDiscoveryProtocol.connection_made | validation | def connection_made(self, transport):
""" On socket creation """
self.transport = transport
sock = transport.get_extra_info("socket")
self.port = sock.getsockname()[1] | python | {
"resource": ""
} |
q261566 | QRTDiscoveryProtocol.datagram_received | validation | 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)) | python | {
"resource": ""
} |
q261567 | QRTDiscoveryProtocol.send_discovery_packet | validation | 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),
) | python | {
"resource": ""
} |
q261568 | choose_qtm_instance | validation | 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 | python | {
"resource": ""
} |
q261569 | create_body_index | validation | 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 | python | {
"resource": ""
} |
q261570 | find_x | validation | 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 | python | {
"resource": ""
} |
q261571 | find_fann | validation | 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!") | python | {
"resource": ""
} |
q261572 | build_swig | validation | 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() | python | {
"resource": ""
} |
q261573 | experiment | validation | 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 | python | {
"resource": ""
} |
q261574 | get | validation | 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() | python | {
"resource": ""
} |
q261575 | delete | validation | 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)) | python | {
"resource": ""
} |
q261576 | update | validation | 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) | python | {
"resource": ""
} |
q261577 | stop | validation | 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.") | python | {
"resource": ""
} |
q261578 | restart | validation | 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) | python | {
"resource": ""
} |
q261579 | statuses | validation | 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() | python | {
"resource": ""
} |
q261580 | resources | validation | 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() | python | {
"resource": ""
} |
q261581 | logs | validation | 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() | python | {
"resource": ""
} |
q261582 | unbookmark | validation | 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.") | python | {
"resource": ""
} |
q261583 | upload | validation | 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) | python | {
"resource": ""
} |
q261584 | cluster | validation | 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) | python | {
"resource": ""
} |
q261585 | check | validation | 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 | python | {
"resource": ""
} |
q261586 | clean_outputs | validation | 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 | python | {
"resource": ""
} |
q261587 | job | validation | 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 | python | {
"resource": ""
} |
q261588 | get | validation | 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) | python | {
"resource": ""
} |
q261589 | delete | validation | 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)) | python | {
"resource": ""
} |
q261590 | update | validation | 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) | python | {
"resource": ""
} |
q261591 | stop | validation | 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.") | python | {
"resource": ""
} |
q261592 | restart | validation | 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) | python | {
"resource": ""
} |
q261593 | statuses | validation | def statuses(ctx, page):
"""Get job statuses.
Uses [Caching](/references/polyaxon-cli/#caching)
Examples:
\b
```bash
$ polyaxon job -j 2 statuses
```
"""
user, project_name, _job = get_job_or_local(ctx.obj.get('project'), ctx.obj.get('job'))
page = page or 1
try:
response = PolyaxonClient().job.get_statuses(user, project_name, _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) | python | {
"resource": ""
} |
q261594 | resources | validation | def resources(ctx, gpu):
"""Get job resources.
Uses [Caching](/references/polyaxon-cli/#caching)
Examples:
\b
```bash
$ polyaxon job -j 2 resources
```
For GPU resources
\b
```bash
$ polyaxon job -j 2 resources --gpu
```
"""
user, project_name, _job = get_job_or_local(ctx.obj.get('project'), ctx.obj.get('job'))
try:
message_handler = Printer.gpu_resources if gpu else Printer.resources
PolyaxonClient().job.resources(user,
project_name,
_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) | python | {
"resource": ""
} |
q261595 | logs | validation | def logs(ctx, past, follow, hide_time):
"""Get job logs.
Uses [Caching](/references/polyaxon-cli/#caching)
Examples:
\b
```bash
$ polyaxon job -j 2 logs
```
\b
```bash
$ polyaxon job logs
```
"""
user, project_name, _job = get_job_or_local(ctx.obj.get('project'), ctx.obj.get('job'))
if past:
try:
response = PolyaxonClient().job.logs(
user, project_name, _job, stream=False)
get_logs_handler(handle_job_info=False,
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 job `{}`.'.format(_job))
Printer.print_error('Error message `{}`.'.format(e))
sys.exit(1)
try:
PolyaxonClient().job.logs(
user,
project_name,
_job,
message_handler=get_logs_handler(handle_job_info=False, 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) | python | {
"resource": ""
} |
q261596 | outputs | validation | def outputs(ctx):
"""Download outputs for job.
Uses [Caching](/references/polyaxon-cli/#caching)
Examples:
\b
```bash
$ polyaxon job -j 1 outputs
```
"""
user, project_name, _job = get_job_or_local(ctx.obj.get('project'), ctx.obj.get('job'))
try:
PolyaxonClient().job.download_outputs(user, project_name, _job)
except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:
Printer.print_error('Could not download outputs for job `{}`.'.format(_job))
Printer.print_error('Error message `{}`.'.format(e))
sys.exit(1)
Printer.print_success('Files downloaded.') | python | {
"resource": ""
} |
q261597 | pprint | validation | def pprint(value):
"""Prints as formatted JSON"""
click.echo(
json.dumps(value,
sort_keys=True,
indent=4,
separators=(',', ': '))) | python | {
"resource": ""
} |
q261598 | login | validation | def login(token, username, password):
"""Login to Polyaxon."""
auth_client = PolyaxonClient().auth
if username:
# Use username / password login
if not password:
password = click.prompt('Please enter your password', type=str, hide_input=True)
password = password.strip()
if not password:
logger.info('You entered an empty string. '
'Please make sure you enter your password correctly.')
sys.exit(1)
credentials = CredentialsConfig(username=username, password=password)
try:
access_code = auth_client.login(credentials=credentials)
except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:
Printer.print_error('Could not login.')
Printer.print_error('Error Message `{}`.'.format(e))
sys.exit(1)
if not access_code:
Printer.print_error("Failed to login")
return
else:
if not token:
token_url = "{}/app/token".format(auth_client.config.http_host)
click.confirm('Authentication token page will now open in your browser. Continue?',
abort=True, default=True)
click.launch(token_url)
logger.info("Please copy and paste the authentication token.")
token = click.prompt('This is an invisible field. Paste token and press ENTER',
type=str, hide_input=True)
if not token:
logger.info("Empty token received. "
"Make sure your shell is handling the token appropriately.")
logger.info("See docs for help: http://docs.polyaxon.com/polyaxon_cli/commands/auth")
return
access_code = token.strip(" ")
# Set user
try:
AuthConfigManager.purge()
user = PolyaxonClient().auth.get_user(token=access_code)
except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:
Printer.print_error('Could not load user info.')
Printer.print_error('Error message `{}`.'.format(e))
sys.exit(1)
access_token = AccessTokenConfig(username=user.username, token=access_code)
AuthConfigManager.set_config(access_token)
Printer.print_success("Login successful")
# Reset current cli
server_version = get_server_version()
current_version = get_current_version()
log_handler = get_log_handler()
CliConfigManager.reset(check_count=0,
current_version=current_version,
min_version=server_version.min_version,
log_handler=log_handler) | python | {
"resource": ""
} |
q261599 | whoami | validation | def whoami():
"""Show current logged Polyaxon user."""
try:
user = PolyaxonClient().auth.get_user()
except (PolyaxonHTTPError, PolyaxonShouldExitError, PolyaxonClientException) as e:
Printer.print_error('Could not load user info.')
Printer.print_error('Error message `{}`.'.format(e))
sys.exit(1)
click.echo("\nUsername: {username}, Email: {email}\n".format(**user.to_dict())) | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.