idx
int64
0
252k
question
stringlengths
48
5.28k
target
stringlengths
5
1.23k
4,200
def parse_datetime ( value ) : if value is None : return None def _get_fixed_timezone ( offset ) : if isinstance ( offset , timedelta ) : offset = offset . seconds // 60 sign = '-' if offset < 0 else '+' hhmm = '%02d%02d' % divmod ( abs ( offset ) , 60 ) name = sign + hhmm return pytz . FixedOffset ( offset , name ) DA...
Convert datetime string to datetime object .
4,201
def _save_customization ( self , widgets ) : if len ( widgets ) > 0 : customization = self . activity . _json_data . get ( 'customization' , dict ( ) ) if customization : customization [ 'ext' ] = dict ( widgets = widgets ) else : customization = dict ( ext = dict ( widgets = widgets ) ) else : customization = None if ...
Save the complete customization to the activity .
4,202
def _add_widget ( self , widget ) : widgets = self . widgets ( ) widgets += [ widget ] self . _save_customization ( widgets )
Add a widget to the customization .
4,203
def widgets ( self ) : customization = self . activity . _json_data . get ( 'customization' ) if customization and "ext" in customization . keys ( ) : return customization [ 'ext' ] [ 'widgets' ] else : return [ ]
Get the Ext JS specific customization from the activity .
4,204
def delete_widget ( self , index ) : widgets = self . widgets ( ) if len ( widgets ) == 0 : raise ValueError ( "This customization has no widgets" ) widgets . pop ( index ) self . _save_customization ( widgets )
Delete widgets by index .
4,205
def add_json_widget ( self , config ) : validate ( config , component_jsonwidget_schema ) self . _add_widget ( dict ( config = config , name = WidgetNames . JSONWIDGET ) )
Add an Ext Json Widget to the customization .
4,206
def add_property_grid_widget ( self , part_instance , max_height = None , custom_title = False , show_headers = True , show_columns = None ) : height = max_height if isinstance ( part_instance , Part ) : part_instance_id = part_instance . id elif isinstance ( part_instance , text_type ) and is_uuid ( part_instance ) : ...
Add a KE - chain Property Grid widget to the customization .
4,207
def add_text_widget ( self , text = None , custom_title = None , collapsible = True , collapsed = False ) : config = { "xtype" : ComponentXType . HTMLPANEL , "filter" : { "activity_id" : str ( self . activity . id ) , } } if text : config [ 'html' ] = text if custom_title : show_title_value = "Custom title" title = cus...
Add a KE - chain Text widget to the customization .
4,208
def enable_mp_crash_reporting ( ) : global mp_crash_reporting_enabled multiprocessing . Process = multiprocessing . process . Process = CrashReportingProcess mp_crash_reporting_enabled = True
Monkey - patch the multiprocessing . Process class with our own CrashReportingProcess . Any subsequent imports of multiprocessing . Process will reference CrashReportingProcess instead .
4,209
def feed ( self , data ) : self . buffer += data while len ( self . buffer ) >= 6 : self . next_packet ( )
Add new incoming data to buffer and try to process
4,210
def valid_header_waiting ( self ) : if len ( self . buffer ) < 4 : self . logger . debug ( "Buffer does not yet contain full header" ) result = False else : result = True result = result and self . buffer [ 0 ] == velbus . START_BYTE if not result : self . logger . warning ( "Start byte not recognized" ) result = resul...
Check if a valid header is waiting in buffer
4,211
def valid_body_waiting ( self ) : packet_size = velbus . MINIMUM_MESSAGE_SIZE + ( self . buffer [ 3 ] & 0x0F ) if len ( self . buffer ) < packet_size : self . logger . debug ( "Buffer does not yet contain full message" ) result = False else : result = True result = result and self . buffer [ packet_size - 1 ] == velbus...
Check if a valid body is waiting in buffer
4,212
def next_packet ( self ) : try : start_byte_index = self . buffer . index ( velbus . START_BYTE ) except ValueError : self . buffer = bytes ( [ ] ) return if start_byte_index >= 0 : self . buffer = self . buffer [ start_byte_index : ] if self . valid_header_waiting ( ) and self . valid_body_waiting ( ) : next_packet = ...
Process next packet if present
4,213
def extract_packet ( self ) : packet_size = velbus . MINIMUM_MESSAGE_SIZE + ( self . buffer [ 3 ] & 0x0F ) packet = self . buffer [ 0 : packet_size ] return packet
Extract packet from buffer
4,214
def _get_number_from_fmt ( fmt ) : if '%' in fmt : return len ( ( "{0:" + fmt + "}" ) . format ( dt . datetime . now ( ) ) ) else : fmt = fmt . lstrip ( '0' ) return int ( re . search ( '[0-9]+' , fmt ) . group ( 0 ) )
Helper function for extract_values figures out string length from format string .
4,215
def get_convert_dict ( fmt ) : convdef = { } for literal_text , field_name , format_spec , conversion in formatter . parse ( fmt ) : if field_name is None : continue convdef [ field_name ] = format_spec return convdef
Retrieve parse definition from the format string fmt .
4,216
def _generate_data_for_format ( fmt ) : data = { } free_size_start = False for literal_text , field_name , format_spec , conversion in formatter . parse ( fmt ) : if literal_text : free_size_start = False if not field_name : free_size_start = False continue if not format_spec or format_spec == "s" or format_spec == "d"...
Generate a fake data dictionary to fill in the provided format string .
4,217
def is_one2one ( fmt ) : data = _generate_data_for_format ( fmt ) if data is None : return False stri = compose ( fmt , data ) data2 = parse ( fmt , stri ) if len ( data ) != len ( data2 ) : return False for key in data : if key not in data2 : return False if data2 [ key ] != data [ key ] : return False return True
Runs a check to evaluate if the format string has a one to one correspondence . I . e . that successive composing and parsing opperations will result in the original data . In other words that input data maps to a string which then maps back to the original data without any change or loss in information .
4,218
def convert_field ( self , value , conversion ) : func = self . CONV_FUNCS . get ( conversion ) if func is not None : value = getattr ( value , func ) ( ) elif conversion not in [ 'R' ] : return super ( StringFormatter , self ) . convert_field ( value , conversion ) if conversion in [ 'h' , 'H' , 'R' ] : value = value ...
Apply conversions mentioned above .
4,219
def _escape ( self , s ) : for ch , r_ch in self . ESCAPE_SETS : s = s . replace ( ch , r_ch ) return s
Escape bad characters for regular expressions .
4,220
def format_spec_to_regex ( field_name , format_spec ) : regex_match = fmt_spec_regex . match ( format_spec . replace ( '\\' , '' ) ) if regex_match is None : raise ValueError ( "Invalid format specification: '{}'" . format ( format_spec ) ) regex_dict = regex_match . groupdict ( ) fill = regex_dict [ 'fill' ] ftype = r...
Make an attempt at converting a format spec to a regular expression .
4,221
def feed_parser ( self , data ) : assert isinstance ( data , bytes ) self . parser . feed ( data )
Feed parser with new data
4,222
def scan ( self , callback = None ) : def scan_finished ( ) : time . sleep ( 3 ) logging . info ( 'Scan finished' ) self . _nb_of_modules_loaded = 0 def module_loaded ( ) : self . _nb_of_modules_loaded += 1 if self . _nb_of_modules_loaded >= len ( self . _modules ) : callback ( ) for module in self . _modules : self . ...
Scan the bus and call the callback when a new module is discovered
4,223
def sync_clock ( self ) : self . send ( velbus . SetRealtimeClock ( ) ) self . send ( velbus . SetDate ( ) ) self . send ( velbus . SetDaylightSaving ( ) )
This will send all the needed messages to sync the cloc
4,224
def string_variable_lookup ( tb , s ) : refs = [ ] dot_refs = s . split ( '.' ) DOT_LOOKUP = 0 DICT_LOOKUP = 1 for ii , ref in enumerate ( dot_refs ) : dict_refs = dict_lookup_regex . findall ( ref ) if dict_refs : bracket = ref . index ( '[' ) refs . append ( ( DOT_LOOKUP , ref [ : bracket ] ) ) refs . extend ( [ ( DI...
Look up the value of an object in a traceback by a dot - lookup string . ie . self . crashreporter . application_name
4,225
def get_object_references ( tb , source , max_string_length = 1000 ) : global obj_ref_regex referenced_attr = set ( ) for line in source . split ( '\n' ) : referenced_attr . update ( set ( re . findall ( obj_ref_regex , line ) ) ) referenced_attr = sorted ( referenced_attr ) info = [ ] for attr in referenced_attr : v =...
Find the values of referenced attributes of objects within the traceback scope .
4,226
def get_local_references ( tb , max_string_length = 1000 ) : if 'self' in tb . tb_frame . f_locals : _locals = [ ( 'self' , repr ( tb . tb_frame . f_locals [ 'self' ] ) ) ] else : _locals = [ ] for k , v in tb . tb_frame . f_locals . iteritems ( ) : if k == 'self' : continue try : vstr = format_reference ( v , max_stri...
Find the values of the local variables within the traceback scope .
4,227
def analyze_traceback ( tb , inspection_level = None , limit = None ) : info = [ ] tb_level = tb extracted_tb = traceback . extract_tb ( tb , limit = limit ) for ii , ( filepath , line , module , code ) in enumerate ( extracted_tb ) : func_source , func_lineno = inspect . getsourcelines ( tb_level . tb_frame ) d = { "F...
Extract trace back information into a list of dictionaries .
4,228
def log_configs ( self ) : for sec in self . config . sections ( ) : LOG . debug ( ' %s: %s' , sec , self . config . options ( sec ) )
Log the read configs if debug is enabled .
4,229
def set_env_or_defaults ( self ) : option = namedtuple ( 'Option' , [ 'section' , 'name' , 'env_var' , 'default_value' ] ) options = [ option ( 'auth' , 'user' , 'NAPPS_USER' , None ) , option ( 'auth' , 'token' , 'NAPPS_TOKEN' , None ) , option ( 'napps' , 'api' , 'NAPPS_API_URI' , 'https://napps.kytos.io/api/' ) , op...
Read some environment variables and set them on the config .
4,230
def check_sections ( config ) : default_sections = [ 'global' , 'auth' , 'napps' , 'kytos' ] for section in default_sections : if not config . has_section ( section ) : config . add_section ( section )
Create a empty config file .
4,231
def save_token ( self , user , token ) : self . config . set ( 'auth' , 'user' , user ) self . config . set ( 'auth' , 'token' , token ) new_config = ConfigParser ( allow_no_value = True ) new_config . read ( self . config_file ) self . check_sections ( new_config ) new_config . set ( 'auth' , 'user' , user ) new_confi...
Save the token on the config file .
4,232
def clear_token ( self ) : new_config = ConfigParser ( allow_no_value = True ) new_config . read ( self . config_file ) self . check_sections ( new_config ) new_config . remove_option ( 'auth' , 'user' ) new_config . remove_option ( 'auth' , 'token' ) filename = os . path . expanduser ( self . config_file ) with open (...
Clear Token information on config file .
4,233
def relocate_model ( part , target_parent , name = None , include_children = True ) : if target_parent . id in get_illegal_targets ( part , include = { part . id } ) : raise IllegalArgumentError ( 'cannot relocate part "{}" under target parent "{}", because the target is part of ' 'its descendants' . format ( part . na...
Move the Part model to target parent .
4,234
def relocate_instance ( part , target_parent , name = None , include_children = True ) : if not name : name = "CLONE - {}" . format ( part . name ) part_model = part . model ( ) target_parent_model = target_parent . model ( ) relocate_model ( part = part_model , target_parent = target_parent_model , name = part_model ....
Move the Part instance to target parent .
4,235
def move_part_instance ( part_instance , target_parent , part_model , name = None , include_children = True ) : if not name : name = part_instance . name moved_model = get_mapping_dictionary ( ) [ part_model . id ] if moved_model . multiplicity == Multiplicity . ONE : moved_instance = moved_model . instances ( parent_i...
Move the Part instance to target parent and updates the properties based on the original part instance .
4,236
def update_part_with_properties ( part_instance , moved_instance , name = None ) : properties_id_dict = dict ( ) for prop_instance in part_instance . properties : if prop_instance . _json_data [ 'property_type' ] == PropertyType . ATTACHMENT_VALUE : moved_prop = get_mapping_dictionary ( ) [ prop_instance . id ] if prop...
Update the newly created part and its properties based on the original one .
4,237
def map_property_instances ( original_part , new_part ) : get_mapping_dictionary ( ) [ original_part . id ] = new_part for prop_original in original_part . properties : get_mapping_dictionary ( ) [ prop_original . id ] = [ prop_new for prop_new in new_part . properties if get_mapping_dictionary ( ) [ prop_original . _j...
Map the id of the original part with the Part object of the newly created one .
4,238
def ask_question ( self , field_name , pattern = NAME_PATTERN , is_required = False , password = False ) : input_value = "" question = ( "Insert the field using the pattern below:" "\n{}\n{}: " . format ( pattern [ 0 ] , field_name ) ) while not input_value : input_value = getpass ( question ) if password else input ( ...
Ask a question and get the input values .
4,239
def cli ( action , config_file , debug , verbose ) : if verbose is True : log_level = 'DEBUG' elif verbose is False : log_level = 'WARNING' else : assert verbose is None log_level = 'INFO' setup_logging ( log_level ) try : grab = Grab ( config_file , debug = debug ) if action in { 'download' , None } : grab . download ...
Static asset management in python .
4,240
def part ( self ) : part_id = self . _json_data [ 'part' ] return self . _client . part ( pk = part_id , category = self . _json_data [ 'category' ] )
Retrieve the part that holds this Property .
4,241
def delete ( self ) : r = self . _client . _request ( 'DELETE' , self . _client . _build_url ( 'property' , property_id = self . id ) ) if r . status_code != requests . codes . no_content : raise APIError ( "Could not delete property: {} with id {}" . format ( self . name , self . id ) )
Delete this property .
4,242
def create ( cls , json , ** kwargs ) : property_type = json . get ( 'property_type' ) if property_type == PropertyType . ATTACHMENT_VALUE : from . property_attachment import AttachmentProperty return AttachmentProperty ( json , ** kwargs ) elif property_type == PropertyType . SINGLE_SELECT_VALUE : from . property_sele...
Create a property based on the json data .
4,243
def __parse_validators ( self ) : self . _validators = [ ] validators_json = self . _options . get ( 'validators' ) for validator_json in validators_json : self . _validators . append ( PropertyValidator . parse ( json = validator_json ) )
Parse the validator in the options to validators .
4,244
def __dump_validators ( self ) : if hasattr ( self , '_validators' ) : validators_json = [ ] for validator in self . _validators : if isinstance ( validator , PropertyValidator ) : validators_json . append ( validator . as_json ( ) ) else : raise APIError ( "validator is not a PropertyValidator: '{}'" . format ( valida...
Dump the validators as json inside the _options dictionary with the key validators .
4,245
def is_valid ( self ) : if not hasattr ( self , '_validators' ) : return None else : self . validate ( reason = False ) if all ( [ vr is None for vr in self . _validation_results ] ) : return None else : return all ( self . _validation_results )
Determine if the value in the property is valid .
4,246
def get_ini_config ( config = os . path . join ( os . path . expanduser ( '~' ) , '.zdeskcfg' ) , default_section = None , section = None ) : plac_ini . call ( __placeholder__ , config = config , default_section = default_section ) return __placeholder__ . getconfig ( section )
This is a convenience function for getting the zdesk configuration from an ini file without the need to decorate and call your own function . Handy when using zdesk and zdeskcfg from the interactive prompt .
4,247
def _ecg_band_pass_filter ( data , sample_rate ) : nyquist_sample_rate = sample_rate / 2. normalized_cut_offs = [ 5 / nyquist_sample_rate , 15 / nyquist_sample_rate ] b_coeff , a_coeff = butter ( 2 , normalized_cut_offs , btype = 'bandpass' ) [ : 2 ] return filtfilt ( b_coeff , a_coeff , data , padlen = 150 )
Bandpass filter with a bandpass setting of 5 to 15 Hz
4,248
def _integration ( data , sample_rate ) : wind_size = int ( 0.080 * sample_rate ) int_ecg = numpy . zeros_like ( data ) cum_sum = data . cumsum ( ) int_ecg [ wind_size : ] = ( cum_sum [ wind_size : ] - cum_sum [ : - wind_size ] ) / wind_size int_ecg [ : wind_size ] = cum_sum [ : wind_size ] / numpy . arange ( 1 , wind_...
Moving window integration . N is the number of samples in the width of the integration window
4,249
def _buffer_ini ( data , sample_rate ) : rr_buffer = [ 1 ] * 8 spk1 = max ( data [ sample_rate : 2 * sample_rate ] ) npk1 = 0 threshold = _buffer_update ( npk1 , spk1 ) return rr_buffer , spk1 , npk1 , threshold
Initializes the buffer with eight 1s intervals
4,250
def _detects_peaks ( ecg_integrated , sample_rate ) : min_rr = ( sample_rate / 1000 ) * 200 possible_peaks = [ i for i in range ( 0 , len ( ecg_integrated ) - 1 ) if ecg_integrated [ i - 1 ] < ecg_integrated [ i ] and ecg_integrated [ i ] > ecg_integrated [ i + 1 ] ] possible_amplitudes = [ ecg_integrated [ k ] for k i...
Detects peaks from local maximum
4,251
def _checkup ( peaks , ecg_integrated , sample_rate , rr_buffer , spk1 , npk1 , threshold ) : peaks_amp = [ ecg_integrated [ peak ] for peak in peaks ] definitive_peaks = [ ] for i , peak in enumerate ( peaks ) : amp = peaks_amp [ i ] if amp > threshold : definitive_peaks , spk1 , rr_buffer = _acceptpeak ( peak , amp ,...
Check each peak according to thresholds
4,252
def _acceptpeak ( peak , amp , definitive_peaks , spk1 , rr_buffer ) : definitive_peaks_out = definitive_peaks definitive_peaks_out = numpy . append ( definitive_peaks_out , peak ) spk1 = 0.125 * amp + 0.875 * spk1 if len ( definitive_peaks_out ) > 1 : rr_buffer . pop ( 0 ) rr_buffer += [ definitive_peaks_out [ - 1 ] -...
Private function intended to insert a new RR interval in the buffer .
4,253
def tachogram ( data , sample_rate , signal = False , in_seconds = False , out_seconds = False ) : if signal is False : data_copy = data time_axis = numpy . array ( data ) if out_seconds is True and in_seconds is False : time_axis = time_axis / sample_rate else : data_copy = detect_r_peaks ( data , sample_rate , time_u...
Function for generation of ECG Tachogram .
4,254
def stop ( self ) : self . logger . warning ( "Stop executed" ) try : self . _reader . close ( ) except serial . serialutil . SerialException : self . logger . error ( "Error while closing device" ) raise VelbusException ( "Error while closing device" ) time . sleep ( 1 )
Close serial port .
4,255
def feed_parser ( self , data ) : assert isinstance ( data , bytes ) self . controller . feed_parser ( data )
Parse received message .
4,256
def send ( self , message , callback = None ) : assert isinstance ( message , velbus . Message ) self . _write_queue . put_nowait ( ( message , callback ) )
Add message to write queue .
4,257
def write_daemon ( self ) : while True : ( message , callback ) = self . _write_queue . get ( block = True ) self . logger . info ( "Sending message on USB bus: %s" , str ( message ) ) self . logger . debug ( "Sending binary message: %s" , str ( message . to_binary ( ) ) ) self . _reader . write ( message . to_binary ...
Write thread .
4,258
def __require_kytos_config ( self ) : if self . __enabled is None : uri = self . _kytos_api + 'api/kytos/core/config/' try : options = json . loads ( urllib . request . urlopen ( uri ) . read ( ) ) except urllib . error . URLError : print ( 'Kytos is not running.' ) sys . exit ( ) self . __enabled = Path ( options . ge...
Set path locations from kytosd API .
4,259
def set_napp ( self , user , napp , version = None ) : self . user = user self . napp = napp self . version = version or 'latest'
Set info about NApp .
4,260
def dependencies ( self , user = None , napp = None ) : napps = self . _get_napp_key ( 'napp_dependencies' , user , napp ) return [ tuple ( napp . split ( '/' ) ) for napp in napps ]
Get napp_dependencies from install NApp .
4,261
def _get_napp_key ( self , key , user = None , napp = None ) : if user is None : user = self . user if napp is None : napp = self . napp kytos_json = self . _installed / user / napp / 'kytos.json' try : with kytos_json . open ( ) as file_descriptor : meta = json . load ( file_descriptor ) return meta [ key ] except ( F...
Return a value from kytos . json .
4,262
def disable ( self ) : core_napps_manager = CoreNAppsManager ( base_path = self . _enabled ) core_napps_manager . disable ( self . user , self . napp )
Disable a NApp if it is enabled .
4,263
def enable ( self ) : core_napps_manager = CoreNAppsManager ( base_path = self . _enabled ) core_napps_manager . enable ( self . user , self . napp )
Enable a NApp if not already enabled .
4,264
def uninstall ( self ) : if self . is_installed ( ) : installed = self . installed_dir ( ) if installed . is_symlink ( ) : installed . unlink ( ) else : shutil . rmtree ( str ( installed ) )
Delete code inside NApp directory if existent .
4,265
def render_template ( templates_path , template_filename , context ) : template_env = Environment ( autoescape = False , trim_blocks = False , loader = FileSystemLoader ( str ( templates_path ) ) ) return template_env . get_template ( str ( template_filename ) ) . render ( context )
Render Jinja2 template for a NApp structure .
4,266
def search ( pattern ) : def match ( napp ) : username = napp . get ( 'username' , napp . get ( 'author' ) ) strings = [ '{}/{}' . format ( username , napp . get ( 'name' ) ) , napp . get ( 'description' ) ] + napp . get ( 'tags' ) return any ( pattern . match ( string ) for string in strings ) napps = NAppsClient ( ) ...
Search all server NApps matching pattern .
4,267
def install_local ( self ) : folder = self . _get_local_folder ( ) installed = self . installed_dir ( ) self . _check_module ( installed . parent ) installed . symlink_to ( folder . resolve ( ) )
Make a symlink in install folder to a local NApp .
4,268
def _get_local_folder ( self , root = None ) : if root is None : root = Path ( ) for folders in [ '.' ] , [ self . user , self . napp ] : kytos_json = root / Path ( * folders ) / 'kytos.json' if kytos_json . exists ( ) : with kytos_json . open ( ) as file_descriptor : meta = json . load ( file_descriptor ) username = m...
Return local NApp root folder .
4,269
def install_remote ( self ) : package , pkg_folder = None , None try : package = self . _download ( ) pkg_folder = self . _extract ( package ) napp_folder = self . _get_local_folder ( pkg_folder ) dst = self . _installed / self . user / self . napp self . _check_module ( dst . parent ) shutil . move ( str ( napp_folder...
Download extract and install NApp .
4,270
def _download ( self ) : repo = self . _config . get ( 'napps' , 'repo' ) napp_id = '{}/{}-{}.napp' . format ( self . user , self . napp , self . version ) uri = os . path . join ( repo , napp_id ) return urllib . request . urlretrieve ( uri ) [ 0 ]
Download NApp package from server .
4,271
def _extract ( filename ) : random_string = '{:0d}' . format ( randint ( 0 , 10 ** 6 ) ) tmp = '/tmp/kytos-napp-' + Path ( filename ) . stem + '-' + random_string os . mkdir ( tmp ) with tarfile . open ( filename , 'r:xz' ) as tar : tar . extractall ( tmp ) return Path ( tmp )
Extract package to a temporary folder .
4,272
def create_napp ( cls , meta_package = False ) : templates_path = SKEL_PATH / 'napp-structure/username/napp' ui_templates_path = os . path . join ( templates_path , 'ui' ) username = None napp_name = None print ( '--------------------------------------------------------------' ) print ( 'Welcome to the bootstrap proces...
Bootstrap a basic NApp structure for you to develop your NApp .
4,273
def create_ui_structure ( cls , username , napp_name , ui_templates_path , context ) : for section in [ 'k-info-panel' , 'k-toolbar' , 'k-action-menu' ] : os . makedirs ( os . path . join ( username , napp_name , 'ui' , section ) ) templates = os . listdir ( ui_templates_path ) for tmp in templates : fname = os . path ...
Create the ui directory structure .
4,274
def build_napp_package ( napp_name ) : ignored_extensions = [ '.swp' , '.pyc' , '.napp' ] ignored_dirs = [ '__pycache__' , '.git' , '.tox' ] files = os . listdir ( ) for filename in files : if os . path . isfile ( filename ) and '.' in filename and filename . rsplit ( '.' , 1 ) [ 1 ] in ignored_extensions : files . rem...
Build the . napp file to be sent to the napps server .
4,275
def create_metadata ( * args , ** kwargs ) : json_filename = kwargs . get ( 'json_filename' , 'kytos.json' ) readme_filename = kwargs . get ( 'readme_filename' , 'README.rst' ) ignore_json = kwargs . get ( 'ignore_json' , False ) metadata = { } if not ignore_json : try : with open ( json_filename ) as json_file : metad...
Generate the metadata to send the napp package .
4,276
def upload ( self , * args , ** kwargs ) : self . prepare ( ) metadata = self . create_metadata ( * args , ** kwargs ) package = self . build_napp_package ( metadata . get ( 'name' ) ) NAppsClient ( ) . upload_napp ( metadata , package )
Create package and upload it to NApps Server .
4,277
def prepare ( cls ) : if cls . _ask_openapi ( ) : napp_path = Path ( ) tpl_path = SKEL_PATH / 'napp-structure/username/napp' OpenAPI ( napp_path , tpl_path ) . render_template ( ) print ( 'Please, update your openapi.yml file.' ) sys . exit ( )
Prepare NApp to be uploaded by creating openAPI skeleton .
4,278
def reload ( self , napps = None ) : client = NAppsClient ( self . _config ) client . reload_napps ( napps )
Reload a NApp or all NApps .
4,279
def _get_thumbnail_url ( image ) : lhs , rhs = splitext ( image . url ) lhs += THUMB_EXT thumb_url = f'{lhs}{rhs}' return thumb_url
Given a large image return the thumbnail url
4,280
def from_env ( cls , env_filename = None ) : with warnings . catch_warnings ( ) : warnings . simplefilter ( "ignore" , UserWarning ) env . read_envfile ( env_filename ) client = cls ( url = env ( KechainEnv . KECHAIN_URL ) ) if env ( KechainEnv . KECHAIN_TOKEN , None ) : client . login ( token = env ( KechainEnv . KECH...
Create a client from environment variable settings .
4,281
def _build_url ( self , resource , ** kwargs ) : return urljoin ( self . api_root , API_PATH [ resource ] . format ( ** kwargs ) )
Build the correct API url .
4,282
def _retrieve_users ( self ) : users_url = self . _build_url ( 'users' ) response = self . _request ( 'GET' , users_url ) users = response . json ( ) return users
Retrieve user objects of the entire administration .
4,283
def _request ( self , method , url , ** kwargs ) : self . last_request = None self . last_response = self . session . request ( method , url , auth = self . auth , headers = self . headers , ** kwargs ) self . last_request = self . last_response . request self . last_url = self . last_response . url if self . last_resp...
Perform the request on the API .
4,284
def app_versions ( self ) : if not self . _app_versions : app_versions_url = self . _build_url ( 'versions' ) response = self . _request ( 'GET' , app_versions_url ) if response . status_code == requests . codes . not_found : self . _app_versions = [ ] elif response . status_code == requests . codes . forbidden : raise...
List of the versions of the internal KE - chain app modules .
4,285
def match_app_version ( self , app = None , label = None , version = None , default = False ) : if not app or not label and not ( app and label ) : target_app = [ a for a in self . app_versions if a . get ( 'app' ) == app or a . get ( 'label' ) == label ] if not target_app and not isinstance ( default , bool ) : raise ...
Match app version against a semantic version string .
4,286
def reload ( self , obj , extra_params = None ) : if not obj . _json_data . get ( 'url' ) : raise NotFoundError ( "Could not reload object, there is no url for object '{}' configured" . format ( obj ) ) response = self . _request ( 'GET' , obj . _json_data . get ( 'url' ) , params = extra_params ) if response . status_...
Reload an object from server . This method is immutable and will return a new object .
4,287
def scope ( self , * args , ** kwargs ) : _scopes = self . scopes ( * args , ** kwargs ) if len ( _scopes ) == 0 : raise NotFoundError ( "No scope fits criteria" ) if len ( _scopes ) != 1 : raise MultipleFoundError ( "Multiple scopes fit criteria" ) return _scopes [ 0 ]
Return a single scope based on the provided name .
4,288
def activities ( self , name = None , pk = None , scope = None , ** kwargs ) : request_params = { 'id' : pk , 'name' : name , 'scope' : scope } if self . match_app_version ( label = 'wim' , version = '>=2.0.0' , default = False ) : request_params . update ( API_EXTRA_PARAMS [ 'activity' ] ) if kwargs : request_params ....
Search for activities with optional name pk and scope filter .
4,289
def activity ( self , * args , ** kwargs ) : _activities = self . activities ( * args , ** kwargs ) if len ( _activities ) == 0 : raise NotFoundError ( "No activity fits criteria" ) if len ( _activities ) != 1 : raise MultipleFoundError ( "Multiple activities fit criteria" ) return _activities [ 0 ]
Search for a single activity .
4,290
def parts ( self , name = None , pk = None , model = None , category = Category . INSTANCE , bucket = None , parent = None , activity = None , limit = None , batch = 100 , ** kwargs ) : if limit and limit < batch : batch = limit request_params = { 'id' : pk , 'name' : name , 'model' : model . id if model else None , 'c...
Retrieve multiple KE - chain parts .
4,291
def part ( self , * args , ** kwargs ) : _parts = self . parts ( * args , ** kwargs ) if len ( _parts ) == 0 : raise NotFoundError ( "No part fits criteria" ) if len ( _parts ) != 1 : raise MultipleFoundError ( "Multiple parts fit criteria" ) return _parts [ 0 ]
Retrieve single KE - chain part .
4,292
def model ( self , * args , ** kwargs ) : kwargs [ 'category' ] = Category . MODEL _parts = self . parts ( * args , ** kwargs ) if len ( _parts ) == 0 : raise NotFoundError ( "No model fits criteria" ) if len ( _parts ) != 1 : raise MultipleFoundError ( "Multiple models fit criteria" ) return _parts [ 0 ]
Retrieve single KE - chain part model .
4,293
def property ( self , * args , ** kwargs ) : _properties = self . properties ( * args , ** kwargs ) if len ( _properties ) == 0 : raise NotFoundError ( "No property fits criteria" ) if len ( _properties ) != 1 : raise MultipleFoundError ( "Multiple properties fit criteria" ) return _properties [ 0 ]
Retrieve single KE - chain Property .
4,294
def properties ( self , name = None , pk = None , category = Category . INSTANCE , ** kwargs ) : request_params = { 'name' : name , 'id' : pk , 'category' : category } if kwargs : request_params . update ( ** kwargs ) response = self . _request ( 'GET' , self . _build_url ( 'properties' ) , params = request_params ) if...
Retrieve properties .
4,295
def services ( self , name = None , pk = None , scope = None , ** kwargs ) : request_params = { 'name' : name , 'id' : pk , 'scope' : scope } if kwargs : request_params . update ( ** kwargs ) response = self . _request ( 'GET' , self . _build_url ( 'services' ) , params = request_params ) if response . status_code != r...
Retrieve Services .
4,296
def service ( self , name = None , pk = None , scope = None , ** kwargs ) : _services = self . services ( name = name , pk = pk , scope = scope , ** kwargs ) if len ( _services ) == 0 : raise NotFoundError ( "No service fits criteria" ) if len ( _services ) != 1 : raise MultipleFoundError ( "Multiple services fit crite...
Retrieve single KE - chain Service .
4,297
def service_executions ( self , name = None , pk = None , scope = None , service = None , ** kwargs ) : request_params = { 'name' : name , 'id' : pk , 'service' : service , 'scope' : scope } if kwargs : request_params . update ( ** kwargs ) r = self . _request ( 'GET' , self . _build_url ( 'service_executions' ) , para...
Retrieve Service Executions .
4,298
def service_execution ( self , name = None , pk = None , scope = None , service = None , ** kwargs ) : _service_executions = self . service_executions ( name = name , pk = pk , scope = scope , service = service , ** kwargs ) if len ( _service_executions ) == 0 : raise NotFoundError ( "No service execution fits criteria...
Retrieve single KE - chain ServiceExecution .
4,299
def users ( self , username = None , pk = None , ** kwargs ) : request_params = { 'username' : username , 'pk' : pk , } if kwargs : request_params . update ( ** kwargs ) r = self . _request ( 'GET' , self . _build_url ( 'users' ) , params = request_params ) if r . status_code != requests . codes . ok : raise NotFoundEr...
Users of KE - chain .