code stringlengths 1 18.2k |
|---|
slice): pass elif isinstance(key, np.ndarray) and key.dtype == np.dtype('bool'): if key.size > size: msg = 'too many boolean indices. Boolean index array ' \ 'of size {0} is greater than axis {1} with ' \ 'size {2}'.format(key.size, axis, size) raise IndexError(msg) elif isinstance(key, collections.Iterable) and \ not ... |
iterable, like a generator. key = tuple(key) for sub_key in key: if sub_key >= size or sub_key < -size: msg = 'index {0} is out of bounds for axis {1}' \ ' with size {2}'.format(sub_key, axis, size) raise IndexError(msg) else: raise TypeError('invalid key {!r}'.format(key)) return key |
def _remap_new_key(self, indices, new_key, axis): """ Return a key of type int, slice, or tuple that represents the combination of new_key with the given indices. Raises IndexError/TypeError for invalid keys. """ size = len(indices) if _is_scalar(new_key): if new_key >= size or new_key < -size: msg = 'index {0} is out ... |
result_key = indices[new_key] elif isinstance(new_key, slice): result_key = indices.__getitem__(new_key) elif isinstance(new_key, np.ndarray) and \ new_key.dtype == np.dtype('bool'): # Numpy boolean indexing. if new_key.size > size: msg = 'too many boolean indices. Boolean index array ' \ 'of size {0} is greater than a... |
# Make sure we capture the values in case we've # been given a one-shot iterable, like a generator. new_key = tuple(new_key) for sub_key in new_key: if sub_key >= size or sub_key < -size: msg = 'index {0} is out of bounds for axis {1}' \ ' with size {2}'.format(sub_key, axis, size) raise IndexError(msg) result_key = tu... |
key {!r}'.format(new_key)) return result_key |
def _apply_axes_mapping(self, target, inverse=False): """ Apply the transposition to the target iterable. Parameters ---------- target - iterable The iterable to transpose. This would be suitable for things such as a shape as well as a list of ``__getitem__`` keys. inverse - bool Whether to map old dimension to new dim... |
A tuple derived from target which has been ordered based on the new axes. """ if len(target) != self.ndim: raise ValueError('The target iterable is of length {}, but ' 'should be of length {}.'.format(len(target), self.ndim)) if inverse: axis_map = self._inverse_axes_map else: axis_map = self._forward_axes_map result =... |
def output_keys(self, source_keys): """ Given input chunk keys, compute what keys will be needed to put the result into the result array. As an example of where this gets used - when we aggregate on a particular axis, the source keys may be ``(0:2, None:None)``, but for an aggregation on axis 0, they would result in ta... |
be ``(None: None, )``. """ keys = list(source_keys) # Remove the aggregated axis from the keys. del keys[self.axis] return tuple(keys) |
def scalarmult_B(e): """ Implements scalarmult(B, e) more efficiently. """ # scalarmult(B, l) is the identity e = e % l P = ident for i in range(253): if e & 1: P = edwards_add(P, Bpow[i]) e = e // 2 assert e == 0, e return P |
def publickey_unsafe(sk): """ Not safe to use with secret keys or secret data. See module docstring. This function should be used for testing only. """ h = H(sk) a = 2 ** (b - 2) + sum(2 ** i * bit(h, i) for i in range(3, b - 2)) A = scalarmult_B(a) return encodepoint(A) |
def generate_public_and_private(): """ <Purpose> Generate a pair of ed25519 public and private keys with PyNaCl. The public and private keys returned conform to 'securesystemslib.formats.ED25519PULIC_SCHEMA' and 'securesystemslib.formats.ED25519SEED_SCHEMA', respectively, and have the form: '\xa2F\x99\xe0\x86\x80%\xc8\... |
PyNaCl ('nacl') module is unavailable. NotImplementedError, if a randomness source is not found by 'os.urandom'. <Side Effects> The ed25519 keys are generated by first creating a random 32-byte seed with os.urandom() and then calling PyNaCl's nacl.signing.SigningKey(). <Returns> A (public, private) tuple that conform t... |
suitable for cryptographic use and is OS-specific. # Raise 'NotImplementedError' if a randomness source is not found. # ed25519 seed keys are fixed at 32 bytes (256-bit keys). # http://blog.mozilla.org/warner/2011/11/29/ed25519-keys/ seed = os.urandom(32) public = None # Generate the public key. PyNaCl (i.e., 'nacl' mo... |
raise securesystemslib.exceptions.UnsupportedLibraryError('The PyNaCl' ' library and/or its dependencies unavailable.') return public, seed |
def create_signature(public_key, private_key, data, scheme): """ <Purpose> Return a (signature, scheme) tuple, where the signature scheme is 'ed25519' and is always generated by PyNaCl (i.e., 'nacl'). The signature returned conforms to 'securesystemslib.formats.ED25519SIGNATURE_SCHEMA', and has the form: '\xae\xd7\x9f\... |
'ed25519' >>> signature, scheme = \ create_signature(public, private, data, scheme) >>> securesystemslib.formats.ED25519SIGNATURE_SCHEMA.matches(signature) True >>> scheme == 'ed25519' True >>> signature, scheme = \ create_signature(public, private, data, scheme) >>> securesystemslib.formats.ED25519SIGNATURE_SCHEMA.mat... |
the signature. scheme: The signature scheme used to generate the signature. <Exceptions> securesystemslib.exceptions.FormatError, if the arguments are improperly formatted. securesystemslib.exceptions.CryptoError, if a signature cannot be created. <Side Effects> nacl.signing.SigningKey.sign() called to generate the act... |
format? # This check will ensure 'public_key' conforms to # 'securesystemslib.formats.ED25519PUBLIC_SCHEMA', which must have length 32 # bytes. Raise 'securesystemslib.exceptions.FormatError' if the check fails. securesystemslib.formats.ED25519PUBLIC_SCHEMA.check_match(public_key) # Is 'private_key' properly formatted?... |
if-clause is not strictly needed here, since 'ed25519' is the only # currently supported scheme. Nevertheless, include the conditional # statement to accommodate schemes that might be added in the future. if scheme == 'ed25519': try: nacl_key = nacl.signing.SigningKey(private) nacl_sig = nacl_key.sign(data) signature =... |
' library and/or its dependencies unavailable.') except (ValueError, TypeError, nacl.exceptions.CryptoError) as e: raise securesystemslib.exceptions.CryptoError('An "ed25519" signature' ' could not be created with PyNaCl.' + str(e)) # This is a defensive check for a valid 'scheme', which should have already # been vali... |
def verify_signature(public_key, scheme, signature, data, use_pynacl=False): """ <Purpose> Determine whether the private key corresponding to 'public_key' produced 'signature'. verify_signature() will use the public key, the 'scheme' and 'sig', and 'data' arguments to complete the verification. >>> public, private = ge... |
scheme) >>> verify_signature(public, scheme, signature, data, use_pynacl=False) True >>> verify_signature(public, scheme, signature, data, use_pynacl=True) True >>> bad_data = b'The sly brown fox jumps over the lazy dog' >>> bad_signature, scheme = \ create_signature(public, private, bad_data, scheme) >>> verify_signat... |
ed25519.py) or PyNacl (i.e., 'nacl'). signature: The signature is a 64-byte string. data: Data object used by securesystemslib.ed25519_keys.create_signature() to generate 'signature'. 'data' is needed here to verify the signature. use_pynacl: True, if the ed25519 signature should be verified by PyNaCl. False, if the si... |
not one supported by securesystemslib.ed25519_keys.create_signature(). securesystemslib.exceptions.FormatError. Raised if the arguments are improperly formatted. <Side Effects> securesystemslib._vendor.ed25519.ed25519.checkvalid() called to do the actual verification. nacl.signing.VerifyKey.verify() called if 'use_pyna... |
'securesystemslib.exceptions.FormatError' if the check fails. securesystemslib.formats.ED25519PUBLIC_SCHEMA.check_match(public_key) # Is 'scheme' properly formatted? securesystemslib.formats.ED25519_SIG_SCHEMA.check_match(scheme) # Is 'signature' properly formatted? securesystemslib.formats.ED25519SIGNATURE_SCHEMA.chec... |
use_pynacl: try: nacl_verify_key = nacl.signing.VerifyKey(public) nacl_message = nacl_verify_key.verify(data, signature) valid_signature = True # The unit tests expect PyNaCl to be installed. except NameError: # pragma: no cover raise securesystemslib.exceptions.UnsupportedLibraryError('The PyNaCl' ' library and/or its... |
'signature' is # invalid. except Exception as e: pass # This is a defensive check for a valid 'scheme', which should have already # been validated in the ED25519_SIG_SCHEMA.check_match(scheme) above. else: #pragma: no cover message = 'Unsupported ed25519 signature scheme: ' + repr(scheme) + '.\n' + \ 'Supported schemes... |
def _delete_file(fileName, n=10): """Cleanly deletes a file in `n` attempts (if necessary)""" status = False count = 0 while not status and count < n: try: _os.remove(fileName) except OSError: count += 1 _time.sleep(0.2) else: status = True return status |
def zDDEInit(self): """Initiates link with OpticStudio DDE server""" self.pyver = _get_python_version() # do this only one time or when there is no channel if _PyZDDE.liveCh==0: try: _PyZDDE.server = _dde.CreateServer() _PyZDDE.server.Create("ZCLIENT") except Exception as err: _sys.stderr.write("{}: DDE server may be i... |
_sys.stderr.write("{}.\nOpticStudio UI may not be running!\n".format(str(err))) # should close the DDE server if it exist self.zDDEClose() return -1 else: _PyZDDE.liveCh += 1 self.connection = True return 0 |
def zDDEClose(self): """Close the DDE link with Zemax server""" if _PyZDDE.server and not _PyZDDE.liveCh: _PyZDDE.server.Shutdown(self.conversation) _PyZDDE.server = 0 elif _PyZDDE.server and self.connection and _PyZDDE.liveCh == 1: _PyZDDE.server.Shutdown(self.conversation) self.connection = False self.appName = '' _P... |
def setTimeout(self, time): """Set global timeout value, in seconds, for all DDE calls""" self.conversation.SetDDETimeout(round(time)) return self.conversation.GetDDETimeout() |
def _sendDDEcommand(self, cmd, timeout=None): """Send command to DDE client""" reply = self.conversation.Request(cmd, timeout) if self.pyver > 2: reply = reply.decode('ascii').rstrip() return reply |
def zGetUpdate(self): """Update the lens""" status,ret = -998, None ret = self._sendDDEcommand("GetUpdate") if ret != None: status = int(ret) #Note: Zemax returns -1 if GetUpdate fails. return status |
def zLoadFile(self, fileName, append=None): """Loads a zmx file into the DDE server""" reply = None if append: cmd = "LoadFile,{},{}".format(fileName, append) else: cmd = "LoadFile,{}".format(fileName) reply = self._sendDDEcommand(cmd) if reply: return int(reply) #Note: Zemax returns -999 if update fails. else: return ... |
def zPushLens(self, update=None, timeout=None): """Copy lens in the Zemax DDE server into LDE""" reply = None if update == 1: reply = self._sendDDEcommand('PushLens,1', timeout) elif update == 0 or update is None: reply = self._sendDDEcommand('PushLens,0', timeout) else: raise ValueError('Invalid value for flag') if re... |
def zSaveFile(self, fileName): """Saves the lens currently loaded in the server to a Zemax file """ cmd = "SaveFile,{}".format(fileName) reply = self._sendDDEcommand(cmd) return int(float(reply.rstrip())) |
def zSyncWithUI(self): """Turn on sync-with-ui""" if not OpticalSystem._dde_link: OpticalSystem._dde_link = _get_new_dde_link() if not self._sync_ui_file: self._sync_ui_file = _get_sync_ui_filename() self._sync_ui = True |
def zPushLens(self, update=None): """Push lens in ZOS COM server to UI""" self.SaveAs(self._sync_ui_file) OpticalSystem._dde_link.zLoadFile(self._sync_ui_file) OpticalSystem._dde_link.zPushLens(update) |
def zGetRefresh(self): """Copy lens in UI to headless ZOS COM server""" OpticalSystem._dde_link.zGetRefresh() OpticalSystem._dde_link.zSaveFile(self._sync_ui_file) self._iopticalsystem.LoadFile (self._sync_ui_file, False) |
def SaveAs(self, filename): """Saves the current system to the specified file. @param filename: absolute path (string) @return: None @raise: ValueError if path (excluding the zemax file name) is not valid All future calls to `Save()` will use the same file. """ directory, zfile = _os.path.split(filename) if zfile.start... |
# store to use in Save() self._iopticalsystem.SaveAs(filename) |
def Save(self): """Saves the current system""" # This method is intercepted to allow ui_sync if self._file_to_save_on_Save: self._iopticalsystem.SaveAs(self._file_to_save_on_Save) else: self._iopticalsystem.Save() |
def zGetSurfaceData(self, surfNum): """Return surface data""" if self.pMode == 0: # Sequential mode surf_data = _co.namedtuple('surface_data', ['radius', 'thick', 'material', 'semidia', 'conic', 'comment']) surf = self.pLDE.GetSurfaceAt(surfNum) return surf_data(surf.pRadius, surf.pThickness, surf.pMaterial, surf.pSemi... |
def zSetSurfaceData(self, surfNum, radius=None, thick=None, material=None, semidia=None, conic=None, comment=None): """Sets surface data""" if self.pMode == 0: # Sequential mode surf = self.pLDE.GetSurfaceAt(surfNum) if radius is not None: surf.pRadius = radius if thick is not None: surf.pThickness = thick if material ... |
is not None: surf.pComment = comment else: raise NotImplementedError('Function not implemented for non-sequential mode') |
def zSetDefaultMeritFunctionSEQ(self, ofType=0, ofData=0, ofRef=0, pupilInteg=0, rings=0, arms=0, obscuration=0, grid=0, delVignetted=False, useGlass=False, glassMin=0, glassMax=1000, glassEdge=0, useAir=False, airMin=0, airMax=1000, airEdge=0, axialSymm=True, ignoreLatCol=False, addFavOper=False, startAt=1, relativeXW... |
pupilInteg : integer pupil integration method (0=Gaussian Quadrature, 1=Rectangular Array) rings : integer rings (0=1, 1=2, 2=3, 3=4, ...) arms : integer arms (0=6, 1=8, 2=10, 3=12) obscuration : real obscuration delVignetted : boolean delete vignetted ? useGlass : boolean whether to use Glass settings for thickness bo... |
edge thickness useAir : boolean whether to use Air settings for thickness boundary airMin : real air minimum thickness airMax : real air maximum thickness airEdge : real air edge thickness axialSymm : boolean assume axial symmetry ignoreLatCol : boolean ignore latent color addFavOper : boolean add favorite color config... |
X weight overallWgt : real overall weight """ mfe = self.pMFE wizard = mfe.pSEQOptimizationWizard wizard.pType = ofType wizard.pData = ofData wizard.pReference = ofRef wizard.pPupilIntegrationMethod = pupilInteg wizard.pRing = rings wizard.pArm = arms wizard.pObscuration = obscuration wizard.pGrid = grid wizard.pIsDele... |
airEdge wizard.pIsAssumeAxialSymmetryUsed = axialSymm wizard.pIsIgnoreLateralColorUsed = ignoreLatCol wizard.pConfiguration = configNum wizard.pIsAddFavoriteOperandsUsed = addFavOper wizard.pStartAt = startAt wizard.pRelativeXWeight = relativeXWgt wizard.pOverallWeight = overallWgt wizard.CommonSettings.OK() |
def datetime_to_unix_timestamp(datetime_object): """ <Purpose> Convert 'datetime_object' (in datetime.datetime()) format) to a Unix/POSIX timestamp. For example, Python's time.time() returns a Unix timestamp, and includes the number of microseconds. 'datetime_object' is converted to UTC. >>> datetime_object = datetime.... |
a datetime.datetime() object. <Side Effects> None. <Returns> A unix (posix) timestamp (e.g., 499137660). """ # Is 'datetime_object' a datetime.datetime() object? # Raise 'securesystemslib.exceptions.FormatError' if not. if not isinstance(datetime_object, datetime.datetime): message = repr(datetime_object) + ' is not a ... |
def unix_timestamp_to_datetime(unix_timestamp): """ <Purpose> Convert 'unix_timestamp' (i.e., POSIX time, in UNIX_TIMESTAMP_SCHEMA format) to a datetime.datetime() object. 'unix_timestamp' is the number of seconds since the epoch (January 1, 1970.) >>> datetime_object = unix_timestamp_to_datetime(1445455680) >>> dateti... |
object corresponding to 'unix_timestamp'. """ # Is 'unix_timestamp' properly formatted? # Raise 'securesystemslib.exceptions.FormatError' if there is a mismatch. securesystemslib.formats.UNIX_TIMESTAMP_SCHEMA.check_match(unix_timestamp) # Convert 'unix_timestamp' to a 'time.struct_time', in UTC. The Daylight # Savings ... |
# datetime object to be returned. datetime_object = datetime.datetime(*struct_time[:6]) return datetime_object |
def format_base64(data): """ <Purpose> Return the base64 encoding of 'data' with whitespace and '=' signs omitted. <Arguments> data: Binary or buffer of data to convert. <Exceptions> securesystemslib.exceptions.FormatError, if the base64 encoding fails or the argument is invalid. <Side Effects> None. <Returns> A base64... |
def parse_base64(base64_string): """ <Purpose> Parse a base64 encoding with whitespace and '=' signs omitted. <Arguments> base64_string: A string holding a base64 value. <Exceptions> securesystemslib.exceptions.FormatError, if 'base64_string' cannot be parsed due to an invalid base64 encoding. <Side Effects> None. <Ret... |
% 4 if extra: padding = '=' * (4 - extra) base64_string = base64_string + padding try: return binascii.a2b_base64(base64_string.encode('utf-8')) except (TypeError, binascii.Error) as e: raise securesystemslib.exceptions.FormatError('Invalid base64' ' encoding: ' + str(e)) |
def encode_canonical(object, output_function=None): """ <Purpose> Encode 'object' in canonical JSON form, as specified at http://wiki.laptop.org/go/Canonical_JSON . It's a restricted dialect of JSON in which keys are always lexically sorted, there is no whitespace, floats aren't allowed, and only quote and backslash ge... |
and returned. Note: This function should be called prior to computing the hash or signature of a JSON object in TUF. For example, generating a signature of a signing role object such as 'ROOT_SCHEMA' is required to ensure repeatable hashes are generated across different json module versions and platforms. Code elsewher... |
indentation and single quotes around object keys). These objects are only required to be in "canonical JSON" format when their hashes or signatures are needed. >>> encode_canonical("") '""' >>> encode_canonical([1, 2, 3]) '[1,2,3]' >>> encode_canonical([]) '[]' >>> encode_canonical({"A": [99]}) '{"A":[99]}' >>> encode_... |
'output_function' (e.g., output_function('result')). <Exceptions> securesystemslib.exceptions.FormatError, if 'object' cannot be encoded or 'output_function' is not callable. <Side Effects> The results are fed to 'output_function()' if 'output_function' is set. <Returns> A string representing the 'object' encoded in ca... |
result.append try: _encode_canonical(object, output_function) except (TypeError, securesystemslib.exceptions.FormatError) as e: message = 'Could not encode ' + repr(object) + ': ' + str(e) raise securesystemslib.exceptions.FormatError(message) # Return the encoded 'object' as a string. # Note: Implies 'output_function'... |
def process_error_labels(value): """ Process the error labels of a dependent variable 'value' to ensure uniqueness. """ observed_error_labels = {} for error in value.get('errors', []): label = error.get('label', 'error') if label not in observed_error_labels: observed_error_labels[label] = 0 observed_error_labels[label... |
2: for error1 in value.get('errors', []): error1_label = error1.get('label', 'error') if error1_label == label: error1['label'] = label + "_1" break |
def raw(text): """Returns a raw string representation of text""" new_string = '' for char in text: try: new_string += escape_dict[char] except KeyError: new_string += char return new_string |
def get_winfunc(libname, funcname, restype=None, argtypes=(), _libcache={}): """Retrieve a function from a library/DLL, and set the data types.""" if libname not in _libcache: _libcache[libname] = windll.LoadLibrary(libname) func = getattr(_libcache[libname], funcname) func.argtypes = argtypes func.restype = restype re... |
def WinMSGLoop(): """Run the main windows message loop.""" LPMSG = POINTER(MSG) LRESULT = c_ulong GetMessage = get_winfunc("user32", "GetMessageW", BOOL, (LPMSG, HWND, UINT, UINT)) TranslateMessage = get_winfunc("user32", "TranslateMessage", BOOL, (LPMSG,)) # restype = LRESULT DispatchMessage = get_winfunc("user32", "D... |
def ConnectTo(self, appName, data=None): """Exceptional error is handled in zdde Init() method, so the exception must be re-raised""" global number_of_apps_communicating self.ddeServerName = appName try: self.ddec = DDEClient(self.ddeServerName, self.ddeClientName) # establish conversation except DDEError: raise else: ... |
def Request(self, item, timeout=None): """Request DDE client timeout in seconds Note ... handle the exception within this function. """ if not timeout: timeout = self.ddetimeout try: reply = self.ddec.request(item, int(timeout*1000)) # convert timeout into milliseconds except DDEError: err_str = str(sys.exc_info()[1]) ... |
case of an error reply = b'-998' #Timeout error value else: reply = '-998' #Timeout error value return reply |
def advise(self, item, stop=False): """Request updates when DDE data changes.""" hszItem = DDE.CreateStringHandle(self._idInst, item, CP_WINUNICODE) hDdeData = DDE.ClientTransaction(LPBYTE(), 0, self._hConv, hszItem, CF_TEXT, XTYP_ADVSTOP if stop else XTYP_ADVSTART, TIMEOUT_ASYNC, LPDWORD()) DDE.FreeStringHandle(self._... |
def execute(self, command): """Execute a DDE command.""" pData = c_char_p(command) cbData = DWORD(len(command) + 1) hDdeData = DDE.ClientTransaction(pData, cbData, self._hConv, HSZ(), CF_TEXT, XTYP_EXECUTE, TIMEOUT_ASYNC, LPDWORD()) if not hDdeData: raise DDEError("Unable to send command", self._idInst) DDE.FreeDataHan... |
def request(self, item, timeout=5000): """Request data from DDE service.""" hszItem = DDE.CreateStringHandle(self._idInst, item, CP_WINUNICODE) #hDdeData = DDE.ClientTransaction(LPBYTE(), 0, self._hConv, hszItem, CF_TEXT, XTYP_REQUEST, timeout, LPDWORD()) pdwResult = DWORD(0) hDdeData = DDE.ClientTransaction(LPBYTE(), ... |
DDEError("Unable to access data in request function", self._idInst) DDE.UnaccessData(hDdeData) else: pData = None DDE.FreeDataHandle(hDdeData) return pData |
def _callback(self, wType, uFmt, hConv, hsz1, hsz2, hDdeData, dwData1, dwData2): """DdeCallback callback function for processing Dynamic Data Exchange (DDE) transactions sent by DDEML in response to DDE events Parameters ---------- wType : transaction type (UINT) uFmt : clipboard data format (UINT) hConv : handle to co... |
memory object (HDDEDATA) dwData1 : transaction-specific data (DWORD) dwData2 : transaction-specific data (DWORD) Returns ------- ret : specific to the type of transaction (HDDEDATA) """ if wType == XTYP_ADVDATA: # value of the data item has changed [hsz1 = topic; hsz2 = item; hDdeData = data] dwSize = DWORD(0) pData = ... |
CP_WINANSI) self.callback(pData, item.value) DDE.UnaccessData(hDdeData) return DDE_FACK else: print("Error: AccessData returned NULL! (err = %s)"% (hex(DDE.GetLastError(self._idInst)))) if wType == XTYP_DISCONNECT: print("Disconnect notification received from server") return 0 |
def parse(self, data_in, *args, **kwargs): """ :param data_in: path to submission.yaml :param args: :param kwargs: :raise ValueError: """ if not os.path.exists(data_in): raise ValueError("File / Directory does not exist: %s" % data_in) if os.path.isdir(data_in): submission_filepath = os.path.join(data_in, 'submission.y... |
open(data_in, 'r') as submission_file: submission_data = list(yaml.load_all(submission_file, Loader=Loader)) if len(submission_data) == 0: raise RuntimeError("Submission file (%s) is empty" % data_in) submission_file_validator = SubmissionFileValidator() if not submission_file_validator.validate(file_path=data_in, data... |
not submission_data[i]: # empty YAML document continue if 'data_file' not in submission_data[i]: metadata = submission_data[i] # information about whole submission continue table_filepath = os.path.join(os.path.dirname(data_in), submission_data[i]['data_file']) with open(table_filepath, 'r') as table_file: if not os.pa... |
data_file_validator.get_messages()))) index = index + 1 table = Table(index=index, metadata=submission_data[i], data=table_data) tables.append(table) return ParsedData(metadata, tables) |
def generate_ai_request( predict_rows, req_dict=None, req_file=ANTINEX_PUBLISH_REQUEST_FILE, features=ANTINEX_FEATURES_TO_PROCESS, ignore_features=ANTINEX_IGNORE_FEATURES, sort_values=ANTINEX_SORT_VALUES, ml_type=ANTINEX_ML_TYPE, use_model_name=ANTINEX_USE_MODEL_NAME, predict_feature=ANTINEX_PREDICT_FEATURE, seed=ANTIN... |
:param features: features to process in the data :param ignore_features: features to ignore in the data (non-numerics) :param sort_values: optional - order rows for scaler normalization :param ml_type: machine learning type - classification/regression :param use_model_name: use a pre-trained model by name :param predic... |
for processing :param epochs: test epochs :param num_splits: test splits for cross validation :param loss: loss function :param optimizer: optimizer :param metrics: metrics to apply :param histories: historical values to test :param filter_features_dict: dictionary of features to use :param filter_features: list of fea... |
this value to any columns that are missing :param version: version of the API request :param publish_to_core: want to publish it to the core or the worker :param debug: log debug messages """ status = NOT_SET err = "not-set" data = None if not ANTINEX_PUBLISH_ENABLED: log.info(("publish disabled ANTINEX_PUBLISH_ENABLED... |
# stop if not enabled try: err = "checking number of predict rows" if len(predict_rows) == 0: err = "please provide a list of predict_rows" log.error(err) status = FAILED res = { "status": status, "error": err, "data": None} return res # stop if there's no new rows body = None if not req_dict: if os.path.exists(req_fil... |
body = copy.deepcopy( req_dict) # end of loading body from requested if not body: err = ("failed to load request body " "req_dict={} req_file={}").format( req_dict, req_file) log.error(err) status = FAILED res = { "status": status, "error": err, "data": None} return res # if body is empty err = ("setting values rows={}... |
in predict_rows: new_row = {} for col in r: cur_value = r[col] if col in filter_features_dict: if not cur_value: cur_value = value_for_missing if ANTINEX_CONVERT_DATA: try: if convert_to_type == "float": new_row[col] = float(cur_value) elif convert_to_type == "int": new_row[col] = int(cur_value) except Exception as e: ... |
cur_value # if not converting data # if the column is in the filtered features # for all columns in the row dictionary for col in filter_features: if col not in new_row: new_row[col] = value_for_missing # make sure to fill in missing columns with a default if check_missing_predict_feature: if predict_feature not in new... |
and fileter err = ("converted rows={} to use_rows={}").format( len(predict_rows), len(use_predict_rows)) log.info(err) body["label"] = use_model_name body["predict_feature"] = predict_feature body["predict_rows"] = use_predict_rows body["publish_to_core"] = publish_to_core body["seed"] = seed body["test_size"] = test_s... |
ignore_features: body["ignore_features"] = ignore_features data = body if debug: log.info(("req={}") .format( ppj(data))) status = SUCCESS err = "" except Exception as e: log.error(("failed last_step='{}' with ex={}") .format( err, e)) status = ERROR # end of try/ex res = { "status": status, "error": err, "data": data}... |
def get_ml_job(): """get_ml_job Get an ``MLJob`` by database id. """ parser = argparse.ArgumentParser( description=("Python client get AI Job by ID")) parser.add_argument( "-u", help="username", required=False, dest="user") parser.add_argument( "-p", help="user password", required=False, dest="password") parser.add_arg... |
directory for " "client encryption over HTTP"), required=False, dest="ca_dir") parser.add_argument( "-c", help=( "optional - path to x509 certificate for " "client encryption over HTTP"), required=False, dest="cert_file") parser.add_argument( "-k", help=( "optional - path to x509 key file for " "client encryption over ... |
password = ev( "API_PASSWORD", "password-not-set") email = ev( "API_EMAIL", "email-not-set") url = ev( "API_URL", "http://localhost:8010") job_id = ev( "JOB_ID", "job_id-not-set") ca_dir = os.getenv( "API_CA_BUNDLE_DIR", None) cert_file = os.getenv( "API_CERT_FILE", None) key_file = os.getenv( "API_KEY_FILE", None) ver... |
if args.url: url = args.url if args.job_id: job_id = args.job_id if args.ca_dir: ca_dir = args.ca_dir if args.cert_file: cert_file = args.cert_file if args.key_file: key_file = args.key_file if args.silent: verbose = False if args.debug: debug = True usage = ( "Please run with " "-u <username> " "-p <password> " "-a <A... |
" "-c <optional - path to x509 ssl certificate file> " "-k <optional - path to x509 ssl key file>") valid = True if not user or user == "user-not-set": log.error("missing user") valid = False if not password or password == "password-not-set": log.error("missing password") valid = False if not job_id or job_id == "job_i... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.