INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
This method provides easier access to all writers inheriting Writer class
def get_concrete_class(cls, class_name): """This method provides easier access to all writers inheriting Writer class :param class_name: name of the parser (name of the parser class which should be used) :type class_name: str :return: Writer subclass specified by parser_name :rt...
Retrieve pupil data
def GetPupil(self): """Retrieve pupil data """ pupil_data = _co.namedtuple('pupil_data', ['ZemaxApertureType', 'ApertureValue', 'entrancePupilDiameter', 'entrancePupil...
Attempt to ping a list of hosts or networks ( can be a single host ): param targets: List - Name ( s ) or IP ( s ) of the host ( s ).: param filename: String - name of the file containing hosts to ping: param status: String - if one of [ alive dead noip ] then only return results that have that status. If this is not s...
def ping(self, targets=list(), filename=str(), status=str()): """ Attempt to ping a list of hosts or networks (can be a single host) :param targets: List - Name(s) or IP(s) of the host(s). :param filename: String - name of the file containing hosts to ping :param status: String -...
def get_results ( cmd: list ) - > str: return lines Get the ping results using fping.: param cmd: List - the fping command and its options: return: String - raw string output containing csv fping results including the newline characters
def get_results(cmd): """ def get_results(cmd: list) -> str: return lines Get the ping results using fping. :param cmd: List - the fping command and its options :return: String - raw string output containing csv fping results including the newline characters ...
Reads the lines of a file into a list and returns the list: param filename: String - path and name of the file: return: List - lines within the file
def read_file(filename): """ Reads the lines of a file into a list, and returns the list :param filename: String - path and name of the file :return: List - lines within the file """ lines = [] with open(filename) as f: for line in f: i...
Open a ROOT file with option RECREATE to create a new file ( the file will be overwritten if it already exists ) and using the ZLIB compression algorithm ( with compression level 1 ) for better compatibility with older ROOT versions ( see https:// root. cern. ch/ doc/ v614/ release - notes. html#important - notice ).
def _prepare_outputs(self, data_out, outputs): """ Open a ROOT file with option 'RECREATE' to create a new file (the file will be overwritten if it already exists), and using the ZLIB compression algorithm (with compression level 1) for better compatibility with older ROOT versions (see ...
: param data_in:: type data_in: hepconverter. parsers. ParsedData: param data_out: filelike object: type data_out: file: param args:: param kwargs:
def write(self, data_in, data_out, *args, **kwargs): """ :param data_in: :type data_in: hepconverter.parsers.ParsedData :param data_out: filelike object :type data_out: file :param args: :param kwargs: """ self._get_tables(data_in) self.fi...
itertools recipe s - > ( s0 s1 ) ( s1 s2 ) ( s2 s3 )...
def _pairwise(iterable): """ itertools recipe "s -> (s0,s1), (s1,s2), (s2, s3), ... """ a, b = itertools.tee(iterable) next(b, None) return zip(a, b)
Return an iterator of tuples for slicing in length chunks.
def _groups_of(length, total_length): """ Return an iterator of tuples for slicing, in 'length' chunks. Parameters ---------- length : int Length of each chunk. total_length : int Length of the object we are slicing Returns ------- iterable of tuples Values ...
Save the numeric results of each source into its corresponding target.
def save(sources, targets, masked=False): """ Save the numeric results of each source into its corresponding target. Parameters ---------- sources: list The list of source arrays for saving from; limited to length 1. targets: list The list of target arrays for saving to; limited...
Count the non - masked elements of the array along the given axis.
def count(a, axis=None): """ Count the non-masked elements of the array along the given axis. .. note:: Currently limited to operating on a single axis. :param axis: Axis or axes along which the operation is performed. The default (axis=None) is to perform the operation ...
Request the minimum of an Array over any number of axes.
def min(a, axis=None): """ Request the minimum of an Array over any number of axes. .. note:: Currently limited to operating on a single axis. Parameters ---------- a : Array object The object whose minimum is to be found. axis : None, or int, or iterable of ints Axis or ax...
Request the maximum of an Array over any number of axes.
def max(a, axis=None): """ Request the maximum of an Array over any number of axes. .. note:: Currently limited to operating on a single axis. Parameters ---------- a : Array object The object whose maximum is to be found. axis : None, or int, or iterable of ints Axis or ax...
Request the sum of an Array over any number of axes.
def sum(a, axis=None): """ Request the sum of an Array over any number of axes. .. note:: Currently limited to operating on a single axis. Parameters ---------- a : Array object The object whose summation is to be found. axis : None, or int, or iterable of ints Axis or axes...
Request the mean of an Array over any number of axes.
def mean(a, axis=None, mdtol=1): """ Request the mean of an Array over any number of axes. .. note:: Currently limited to operating on a single axis. :param axis: Axis or axes along which the operation is performed. The default (axis=None) is to perform the operation ...
Request the standard deviation of an Array over any number of axes.
def std(a, axis=None, ddof=0): """ Request the standard deviation of an Array over any number of axes. .. note:: Currently limited to operating on a single axis. :param axis: Axis or axes along which the operation is performed. The default (axis=None) is to perform the operation ...
Request the variance of an Array over any number of axes.
def var(a, axis=None, ddof=0): """ Request the variance of an Array over any number of axes. .. note:: Currently limited to operating on a single axis. :param axis: Axis or axes along which the operation is performed. The default (axis=None) is to perform the operation ...
A function to generate the top level biggus ufunc wrappers.
def _ufunc_wrapper(ufunc, name=None): """ A function to generate the top level biggus ufunc wrappers. """ if not isinstance(ufunc, np.ufunc): raise TypeError('{} is not a ufunc'.format(ufunc)) ufunc_name = ufunc.__name__ # Get hold of the masked array equivalent, if it exists. ma_u...
Returns the shape that results from slicing an array of the given shape by the given keys.
def _sliced_shape(shape, keys): """ Returns the shape that results from slicing an array of the given shape by the given keys. >>> _sliced_shape(shape=(52350, 70, 90, 180), ... keys=(np.newaxis, slice(None, 10), 3, ... slice(None), slice(2, 3))) (1, 10, 90,...
Given keys such as those passed to __getitem__ for an array of ndim return a fully expanded tuple of keys.
def _full_keys(keys, ndim): """ Given keys such as those passed to ``__getitem__`` for an array of ndim, return a fully expanded tuple of keys. In all instances, the result of this operation should follow: array[keys] == array[_full_keys(keys, array.ndim)] """ if not isinstance(keys, ...
Assert that the given array is an Array subclass ( or numpy array ).
def ensure_array(array): """ Assert that the given array is an Array subclass (or numpy array). If the given array is a numpy.ndarray an appropriate NumpyArrayAdapter instance is created, otherwise the passed array must be a subclass of :class:`Array` else a TypeError will be raised. """ i...
Return a human - readable description of the number of bytes required to store the data of the given array.
def size(array): """ Return a human-readable description of the number of bytes required to store the data of the given array. For example:: >>> array.nbytes 14000000 >> biggus.size(array) '13.35 MiB' Parameters ---------- array : array-like object ...
Dispatch the given Chunk onto all the registered output queues.
def output(self, chunk): """ Dispatch the given Chunk onto all the registered output queues. If the chunk is None, it is silently ignored. """ if chunk is not None: for queue in self.output_queues: queue.put(chunk)
Emit the Chunk instances which cover the underlying Array.
def run(self): """ Emit the Chunk instances which cover the underlying Array. The Array is divided into chunks with a size limit of MAX_CHUNK_SIZE which are emitted into all registered output queues. """ try: chunk_index = self.chunk_index_gen(self.a...
Set the given nodes as inputs for this node.
def add_input_nodes(self, input_nodes): """ Set the given nodes as inputs for this node. Creates a limited-size queue.Queue for each input node and registers each queue as an output of its corresponding node. """ self.input_queues = [queue.Queue(maxsize=3) for _ in inpu...
Process the input queues in lock - step and push any results to the registered output queues.
def run(self): """ Process the input queues in lock-step, and push any results to the registered output queues. """ try: while True: input_chunks = [input.get() for input in self.input_queues] for input in self.input_queues: ...
Store the incoming chunk at the corresponding position in the result array.
def process_chunks(self, chunks): """ Store the incoming chunk at the corresponding position in the result array. """ chunk, = chunks if chunk.keys: self.result[chunk.keys] = chunk.data else: self.result[...] = chunk.data
Return a key of type int slice or tuple that is guaranteed to be valid for the given dimension size.
def _cleanup_new_key(self, key, size, axis): """ Return a key of type int, slice, or tuple that is guaranteed to be valid for the given dimension size. Raises IndexError/TypeError for invalid keys. """ if _is_scalar(key): if key >= size or key < -size: ...
Return a key of type int slice or tuple that represents the combination of new_key with the given indices.
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): ...
Apply the transposition to the target iterable.
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...
Given input chunk keys compute what keys will be needed to put the result into the result array.
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 ...
Implements scalarmult ( B e ) more efficiently.
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
Not safe to use with secret keys or secret data.
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)
<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:
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: ...
<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:
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 ...
<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.
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. >>...
Cleanly deletes a file in n attempts ( if necessary )
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: statu...
Initiates link with OpticStudio DDE server
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("Z...
Close the DDE link with Zemax server
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(sel...
Set global timeout value in seconds for all DDE calls
def setTimeout(self, time): """Set global timeout value, in seconds, for all DDE calls""" self.conversation.SetDDETimeout(round(time)) return self.conversation.GetDDETimeout()
Send command to DDE client
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
Update the lens
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
Loads a zmx file into the DDE server
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: ...
Copy lens in the Zemax DDE server into LDE
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...
Saves the lens currently loaded in the server to a Zemax file
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()))
Turn on sync - with - ui
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
Push lens in ZOS COM server to UI
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)
Copy lens in UI to headless ZOS COM server
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)
Saves the current system to the specified file.
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. """ ...
Saves the current system
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()
Return surface data
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...
Sets surface data
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: ...
Sets the default merit function for Sequential Merit Function Editor
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, ...
<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.
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. >>> date...
<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. )
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(...
<Purpose > Return the base64 encoding of data with whitespace and = signs omitted.
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. <Sid...
<Purpose > Parse a base64 encoding with whitespace and = signs omitted.
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 enc...
<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 get escaped. The result is encoded in UTF - 8 and the resul...
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 q...
Process the error labels of a dependent variable value to ensure uniqueness.
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: ...
Returns a raw string representation of text
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
Retrieve a function from a library/ DLL and set the data types.
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 ...
Run the main windows message loop.
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 DispatchMessag...
Exceptional error is handled in zdde Init () method so the exception must be re - raised
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) # ...
Request DDE client timeout in seconds Note... handle the exception within this function.
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 time...
Request updates when DDE data changes.
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()) ...
Execute a DDE command.
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("Un...
Request data from DDE service.
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) hDd...
DdeCallback callback function for processing Dynamic Data Exchange ( DDE ) transactions sent by DDEML in response to DDE events
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...
: param data_in: path to submission. yaml: param args:: param kwargs:: raise ValueError:
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.p...
generate_ai_request
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...
get_ml_job
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( ...
Get a limited set of comments for a given object. Defaults to a limit of 5. Setting the limit to - 1 disables limiting. Set the amount of comments to
def get_molo_comments(parser, token): """ Get a limited set of comments for a given object. Defaults to a limit of 5. Setting the limit to -1 disables limiting. Set the amount of comments to usage: {% get_molo_comments for object as variable_name %} {% get_molo_comments for object ...
Get a limited set of comments for a given object. Defaults to a limit of 5. Setting the limit to - 1 disables limiting.
def get_comments_content_object(parser, token): """ Get a limited set of comments for a given object. Defaults to a limit of 5. Setting the limit to -1 disables limiting. usage: {% get_comments_content_object for form_object as variable_name %} """ keywords = token.contents.split() ...
Flags a comment on GET.
def report(request, comment_id): """ Flags a comment on GET. Redirects to whatever is provided in request.REQUEST['next']. """ comment = get_object_or_404( django_comments.get_model(), pk=comment_id, site__pk=settings.SITE_ID) if comment.parent is not None: messages.info(reques...
Allows for posting of a Molo Comment this allows comments to be set with the user_name as Anonymous
def post_molo_comment(request, next=None, using=None): """ Allows for posting of a Molo Comment, this allows comments to be set with the "user_name" as "Anonymous" """ data = request.POST.copy() if 'submit_anonymously' in data: data['name'] = 'Anonymous' # replace with our changed PO...
build_ai_client_from_env
def build_ai_client_from_env( verbose=ANTINEX_CLIENT_VERBOSE, debug=ANTINEX_CLIENT_DEBUG, ca_dir=None, cert_file=None, key_file=None): """build_ai_client_from_env Use environment variables to build a client :param verbose: verbose logging :param debug: debug int...
train_new_deep_neural_network
def train_new_deep_neural_network(): """train_new_deep_neural_network Train a new deep neural network and store the results as a new: ``MLJob`` and ``MLJobResult`` database records. """ parser = argparse.ArgumentParser( description=( "Python client to Train a Deep Neural Netwo...
prepare_new_dataset
def prepare_new_dataset(): """prepare_new_dataset Prepare a new ``MLPrepare`` record and dataset files on disk. """ parser = argparse.ArgumentParser( description=( "Python client to Prepare a dataset")) parser.add_argument( "-u", help="username", requir...
Convert a 2D feature to a 3D feature by sampling a raster
def drape(raster, feature): """Convert a 2D feature to a 3D feature by sampling a raster Parameters: raster (rasterio): raster to provide the z coordinate feature (dict): fiona feature record to convert Returns: result (Point or Linestring): shapely Point or LineString of xyz coord...
Sample a raster at given coordinates
def sample(raster, coords): """Sample a raster at given coordinates Given a list of coordinates, return a list of x,y,z triples with z coordinates sampled from an input raster Parameters: raster (rasterio): raster dataset to sample coords: array of tuples containing coordinate pairs (x,y) ...
setup_logging
def setup_logging( default_level=logging.INFO, default_path="{}/logging.json".format( os.getenv( "LOG_DIR", os.path.dirname(os.path.realpath(__file__)))), env_key="LOG_CFG", config_name=None): """setup_logging Setup logging configurati...
build_logger
def build_logger( name=os.getenv( "LOG_NAME", "client"), config="logging.json", log_level=logging.INFO, log_config_path="{}/logging.json".format( os.getenv( "LOG_CFG", os.path.dirname(os.path.realpath(__file__))))): """build_logger :param name: na...
build_colorized_logger
def build_colorized_logger( name=os.getenv( "LOG_NAME", "client"), config="colors-logging.json", log_level=logging.INFO, log_config_path="{}/logging.json".format( os.getenv( "LOG_CFG", os.path.dirname(os.path.realpath(__file__))))): """build_colorized_...
Your AuhtService should override this method for request authentication otherwise means no authentication.: param request: HttpRequest Django s HttpRequest object: param auth_route: str User s resqueted route: param actual_params: User s url parameters: return: bool
def authenticate(self, request: HttpRequest, auth_route: str, actual_params: dict) -> bool: """ Your AuhtService should override this method for request authentication, otherwise means no authentication. :param request: HttpRequest Django's HttpRequest object :param auth_route: str User'...
Converts 2D geometries to 3D using GEOS sample through fiona.
def cli(source_f, raster_f, output, verbose): """ Converts 2D geometries to 3D using GEOS sample through fiona. \b Example: drape point.shp elevation.tif -o point_z.shp """ with fiona.open(source_f, 'r') as source: source_driver = source.driver source_crs = source.crs ...
QuerySet for all comments for a particular model ( either an instance or a class ).
def for_model(self, model): """ QuerySet for all comments for a particular model (either an instance or a class). """ ct = ContentType.objects.get_for_model(model) qs = self.get_queryset().filter(content_type=ct) if isinstance(model, models.Model): qs ...
Blocking call returns the value of the execution in JS
def eval(self, command): 'Blocking call, returns the value of the execution in JS' event = threading.Event() # TODO: Add event to server #job_id = str(id(command)) import random job_id = str(random.random()) server.EVALUATIONS[job_id] = event message = '?...
Register a callback on server and on connected clients.
def register(self, callback, name): 'Register a callback on server and on connected clients.' server.CALLBACKS[name] = callback self.run(''' window.skink.%s = function(args=[]) { window.skink.call("%s", args); }''' % (name, name))
Launch a Python exception from an error that took place in the browser.
def launch_exception(message): """ Launch a Python exception from an error that took place in the browser. messsage format: - name: str - description: str """ error_name = message['name'] error_descr = message['description'] mapping = { 'ReferenceError': Name...
start_predictions
def start_predictions(): """start_predictions Using environment variables, create an AntiNex AI Client. You can also use command line args if you want. This can train a new deep neural network if it does not exist or it can use an existing pre-trained deep neural network within the AntiNex Cor...
login
def login( self): """login""" auth_url = self.api_urls["login"] if self.verbose: log.info(("log in user={} url={} ca_dir={} cert={}") .format( self.user, auth_url, self.ca_dir, ...
build_response
def build_response( self, status=NOT_SET, error="", data=None): """build_response :param status: status code :param error: error message :param data: dictionary to send back """ res_node = { "status": status, ...
retry_login
def retry_login( self): """retry_login""" if not self.user or not self.password: return self.build_response( status=ERROR, error="please set the user and password") retry = 0 not_done = True while not_done: if ...
get_prepare_by_id
def get_prepare_by_id( self, prepare_id=None): """get_prepare_by_id :param prepare_id: MLJob.id in the database """ if not prepare_id: log.error("missing prepare_id for get_prepare_by_id") return self.build_response( statu...
wait_for_job_to_finish
def wait_for_job_to_finish( self, job_id, sec_to_sleep=5.0, max_retries=100000): """wait_for_job_to_finish :param job_id: MLJob.id to wait on :param sec_to_sleep: seconds to sleep during polling :param max_retries: max retires until stoppi...
wait_for_prepare_to_finish
def wait_for_prepare_to_finish( self, prepare_id, sec_to_sleep=5.0, max_retries=100000): """wait_for_prepare_to_finish :param prepare_id: MLPrepare.id to wait on :param sec_to_sleep: seconds to sleep during polling :param max_retries: max ...
NB: Overridden to remove dupe comment check for admins ( necessary for canned responses )
def get_comment_object(self): """ NB: Overridden to remove dupe comment check for admins (necessary for canned responses) Return a new (unsaved) comment object based on the information in this form. Assumes that the form is already validated and will throw a ValueError i...
Start Rinzler App: param app_name: str Application s identifier: return: dict
def boot(app_name) -> Rinzler: """ Start Rinzler App :param app_name: str Application's identifier :return: dict """ app = Rinzler(app_name) app.log.info("App booted =)") return app
Maps a route namespace with the given params and point it s requests to the especified controller.: param route: str Namespace route to be mapped: param controller: callback Controller callable to map end - points: rtype: url
def mount(self, route: str, controller: callable) -> url: """ Maps a route namespace with the given params and point it's requests to the especified controller. :param route: str Namespace route to be mapped :param controller: callback Controller callable to map end-points :rtype...
Sets the authentication service: param auth_service: BaseAuthService Authentication service: raises: TypeError If the auth_service object is not a subclass of rinzler. auth. BaseAuthService: rtype: Rinzler
def set_auth_service(self, auth_service: BaseAuthService): """ Sets the authentication service :param auth_service: BaseAuthService Authentication service :raises: TypeError If the auth_service object is not a subclass of rinzler.auth.BaseAuthService :rtype: Rinzler """ ...