idx int64 0 251k | question stringlengths 53 3.53k | target stringlengths 5 1.23k | len_question int64 20 893 | len_target int64 3 238 |
|---|---|---|---|---|
4,200 | 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 | 54 | 5 |
4,201 | def _get_number_from_fmt ( fmt ) : if '%' in fmt : # its datetime return len ( ( "{0:" + fmt + "}" ) . format ( dt . datetime . now ( ) ) ) else : # its something 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 . | 91 | 14 |
4,202 | def get_convert_dict ( fmt ) : convdef = { } for literal_text , field_name , format_spec , conversion in formatter . parse ( fmt ) : if field_name is None : continue # XXX: Do I need to include 'conversion'? convdef [ field_name ] = format_spec return convdef | Retrieve parse definition from the format string fmt . | 73 | 10 |
4,203 | def _generate_data_for_format ( fmt ) : # finally try some data, create some random data for the fmt. data = { } # keep track of how many "free_size" (wildcard) parameters we have # if we get two in a row then we know the pattern is invalid, meaning # we'll never be able to match the second wildcard field free_size_sta... | Generate a fake data dictionary to fill in the provided format string . | 470 | 14 |
4,204 | def is_one2one ( fmt ) : data = _generate_data_for_format ( fmt ) if data is None : return False # run data forward once and back to data stri = compose ( fmt , data ) data2 = parse ( fmt , stri ) # check if data2 equal to original data if len ( data ) != len ( data2 ) : return False for key in data : if key not in dat... | 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 . | 119 | 62 |
4,205 | 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' ] : # default conversion ('r', 's') return super ( StringFormatter , self ) . convert_field ( value , conversion ) if conversion in [ 'h... | Apply conversions mentioned above . | 136 | 5 |
4,206 | 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 . | 38 | 8 |
4,207 | def format_spec_to_regex ( field_name , format_spec ) : # NOTE: remove escaped backslashes so regex matches 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 . ... | Make an attempt at converting a format spec to a regular expression . | 421 | 13 |
4,208 | def feed_parser ( self , data ) : assert isinstance ( data , bytes ) self . parser . feed ( data ) | Feed parser with new data | 26 | 5 |
4,209 | def scan ( self , callback = None ) : def scan_finished ( ) : """ Callback when scan is 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 ( ) ... | Scan the bus and call the callback when a new module is discovered | 161 | 13 |
4,210 | 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 | 49 | 12 |
4,211 | 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 | 296 | 29 |
4,212 | 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 . | 154 | 14 |
4,213 | 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 . | 154 | 13 |
4,214 | 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 . | 289 | 12 |
4,215 | 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 . | 43 | 10 |
4,216 | 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 . | 291 | 11 |
4,217 | 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 . | 58 | 6 |
4,218 | def save_token ( self , user , token ) : self . config . set ( 'auth' , 'user' , user ) self . config . set ( 'auth' , 'token' , token ) # allow_no_value=True is used to keep the comments on the config file. new_config = ConfigParser ( allow_no_value = True ) # Parse the config file. If no config file was found, then c... | Save the token on the config file . | 208 | 8 |
4,219 | def clear_token ( self ) : # allow_no_value=True is used to keep the comments on the config file. new_config = ConfigParser ( allow_no_value = True ) # Parse the config file. If no config file was found, then create some # default sections on the config variable. new_config . read ( self . config_file ) self . check_se... | Clear Token information on config file . | 172 | 7 |
4,220 | 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 . | 834 | 8 |
4,221 | def relocate_instance ( part , target_parent , name = None , include_children = True ) : # First, if the user doesn't provide the name, then just use the default "Clone - ..." name if not name : name = "CLONE - {}" . format ( part . name ) # Initially the model of the part needs to be recreated under the model of the t... | Move the Part instance to target parent . | 278 | 8 |
4,222 | def move_part_instance ( part_instance , target_parent , part_model , name = None , include_children = True ) : # If no specific name has been required, then call in as Clone of the part_instance. if not name : name = part_instance . name # Retrieve the model of the future part to be created moved_model = get_mapping_d... | Move the Part instance to target parent and updates the properties based on the original part instance . | 693 | 18 |
4,223 | def update_part_with_properties ( part_instance , moved_instance , name = None ) : # Instantiate and empty dictionary later used to map {property.id: property.value} in order to update the part # in one go properties_id_dict = dict ( ) for prop_instance in part_instance . properties : # Do different magic if there is a... | Update the newly created part and its properties based on the original one . | 463 | 14 |
4,224 | def map_property_instances ( original_part , new_part ) : # Map the original part with the new one get_mapping_dictionary ( ) [ original_part . id ] = new_part # Do the same for each Property of original part instance, using the 'model' id and the get_mapping_dictionary for prop_original in original_part . properties :... | Map the id of the original part with the Part object of the newly created one . | 160 | 17 |
4,225 | 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 . | 201 | 9 |
4,226 | 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 . | 146 | 6 |
4,227 | 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 . | 50 | 9 |
4,228 | def delete ( self ) : # type () -> () r = self . _client . _request ( 'DELETE' , self . _client . _build_url ( 'property' , property_id = self . id ) ) if r . status_code != requests . codes . no_content : # pragma: no cover raise APIError ( "Could not delete property: {} with id {}" . format ( self . name , self . id ... | Delete this property . | 98 | 4 |
4,229 | def create ( cls , json , * * kwargs ) : # type: (dict, **Any) -> Property 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... | Create a property based on the json data . | 205 | 9 |
4,230 | 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 . | 68 | 12 |
4,231 | 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 . | 179 | 18 |
4,232 | def is_valid ( self ) : # type: () -> Union[bool, None] 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 . | 82 | 12 |
4,233 | 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 . | 80 | 46 |
4,234 | 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 | 113 | 13 |
4,235 | 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 | 129 | 17 |
4,236 | 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 | 77 | 9 |
4,237 | def _detects_peaks ( ecg_integrated , sample_rate ) : # Minimum RR interval = 200 ms min_rr = ( sample_rate / 1000 ) * 200 # Computes all possible peaks and their amplitudes possible_peaks = [ i for i in range ( 0 , len ( ecg_integrated ) - 1 ) if ecg_integrated [ i - 1 ] < ecg_integrated [ i ] and ecg_integrated [ i ]... | Detects peaks from local maximum | 336 | 6 |
4,238 | 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 ] # accept if larger than threshold and slope in raw signal # is +-30% of previous slop... | Check each peak according to thresholds | 420 | 6 |
4,239 | 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 # spk1 is the running estimate of the signal peak if len ( definitive_peaks_out ) > 1 : rr_buffer . pop (... | Private function intended to insert a new RR interval in the buffer . | 157 | 13 |
4,240 | def tachogram ( data , sample_rate , signal = False , in_seconds = False , out_seconds = False ) : if signal is False : # data is a list of R peaks position. data_copy = data time_axis = numpy . array ( data ) #.cumsum() if out_seconds is True and in_seconds is False : time_axis = time_axis / sample_rate else : # data ... | Function for generation of ECG Tachogram . | 201 | 10 |
4,241 | 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 . | 67 | 4 |
4,242 | def feed_parser ( self , data ) : assert isinstance ( data , bytes ) self . controller . feed_parser ( data ) | Parse received message . | 28 | 5 |
4,243 | def send ( self , message , callback = None ) : assert isinstance ( message , velbus . Message ) self . _write_queue . put_nowait ( ( message , callback ) ) | Add message to write queue . | 41 | 6 |
4,244 | 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 . | 114 | 3 |
4,245 | 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 . | 134 | 10 |
4,246 | def set_napp ( self , user , napp , version = None ) : self . user = user self . napp = napp self . version = version or 'latest' | Set info about NApp . | 39 | 6 |
4,247 | 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 . | 61 | 11 |
4,248 | 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 . | 125 | 10 |
4,249 | 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 . | 45 | 9 |
4,250 | 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 . | 45 | 9 |
4,251 | 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 . | 55 | 10 |
4,252 | 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 . | 69 | 11 |
4,253 | def search ( pattern ) : def match ( napp ) : """Whether a NApp metadata matches the pattern.""" # WARNING: This will change for future versions, when 'author' will # be removed. username = napp . get ( 'username' , napp . get ( 'author' ) ) strings = [ '{}/{}' . format ( username , napp . get ( 'name' ) ) , napp . get... | Search all server NApps matching pattern . | 156 | 8 |
4,254 | 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 . | 54 | 14 |
4,255 | 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 ) # WARNING: T... | Return local NApp root folder . | 188 | 7 |
4,256 | 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 . | 152 | 7 |
4,257 | 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 . | 92 | 7 |
4,258 | 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 . | 95 | 8 |
4,259 | 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 . | 661 | 15 |
4,260 | 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 . | 176 | 7 |
4,261 | 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 . | 253 | 15 |
4,262 | def create_metadata ( * args , * * kwargs ) : # pylint: disable=unused-argument 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 ( j... | Generate the metadata to send the napp package . | 279 | 11 |
4,263 | 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 . | 72 | 10 |
4,264 | 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 . | 88 | 13 |
4,265 | def reload ( self , napps = None ) : client = NAppsClient ( self . _config ) client . reload_napps ( napps ) | Reload a NApp or all NApps . | 32 | 10 |
4,266 | 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 | 52 | 8 |
4,267 | def from_env ( cls , env_filename = None ) : # type: (Optional[str]) -> Client 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... | Create a client from environment variable settings . | 210 | 8 |
4,268 | def _build_url ( self , resource , * * kwargs ) : # type: (str, **str) -> str return urljoin ( self . api_root , API_PATH [ resource ] . format ( * * kwargs ) ) | Build the correct API url . | 54 | 6 |
4,269 | 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 . | 49 | 9 |
4,270 | def _request ( self , method , url , * * kwargs ) : # type: (str, str, **Any) -> requests.Response 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... | Perform the request on the API . | 149 | 8 |
4,271 | 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 . | 173 | 13 |
4,272 | 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 . | 271 | 9 |
4,273 | def reload ( self , obj , extra_params = None ) : if not obj . _json_data . get ( 'url' ) : # pragma: no cover 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... | Reload an object from server . This method is immutable and will return a new object . | 162 | 18 |
4,274 | def scope ( self , * args , * * kwargs ) : # type: (*Any, **Any) -> Scope _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 . | 96 | 10 |
4,275 | def activities ( self , name = None , pk = None , scope = None , * * kwargs ) : # type: (Optional[str], Optional[str], Optional[str], **Any) -> List[Activity] request_params = { 'id' : pk , 'name' : name , 'scope' : scope } # update the fields query params # for 'kechain.core.wim >= 2.0.0' add additional API params if ... | Search for activities with optional name pk and scope filter . | 358 | 12 |
4,276 | def activity ( self , * args , * * kwargs ) : # type: (*Any, **Any) -> Activity _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 _... | Search for a single activity . | 94 | 6 |
4,277 | def parts ( self , name = None , # type: Optional[str] pk = None , # type: Optional[str] model = None , # type: Optional[Part] category = Category . INSTANCE , # type: Optional[str] bucket = None , # type: Optional[str] parent = None , # type: Optional[str] activity = None , # type: Optional[str] limit = None , # type:... | Retrieve multiple KE - chain parts . | 411 | 8 |
4,278 | def part ( self , * args , * * kwargs ) : # type: (*Any, **Any) -> Part _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 . | 90 | 8 |
4,279 | def model ( self , * args , * * kwargs ) : # type: (*Any, **Any) -> Part 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" ) r... | Retrieve single KE - chain part model . | 103 | 9 |
4,280 | def property ( self , * args , * * kwargs ) : # type: (*Any, **Any) -> Property _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 _... | Retrieve single KE - chain Property . | 90 | 8 |
4,281 | def properties ( self , name = None , pk = None , category = Category . INSTANCE , * * kwargs ) : # type: (Optional[str], Optional[str], Optional[str], **Any) -> List[Property] request_params = { 'name' : name , 'id' : pk , 'category' : category } if kwargs : request_params . update ( * * kwargs ) response = self . _re... | Retrieve properties . | 182 | 4 |
4,282 | 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 !=... | Retrieve Services . | 153 | 4 |
4,283 | 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 cri... | Retrieve single KE - chain Service . | 100 | 8 |
4,284 | 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' ) , pa... | Retrieve Service Executions . | 178 | 6 |
4,285 | 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 criter... | Retrieve single KE - chain ServiceExecution . | 128 | 10 |
4,286 | 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 : # pragma: no c... | Users of KE - chain . | 158 | 6 |
4,287 | def user ( self , username = None , pk = None , * * kwargs ) : _users = self . users ( username = username , pk = pk , * * kwargs ) if len ( _users ) == 0 : raise NotFoundError ( "No user criteria matches" ) if len ( _users ) != 1 : raise MultipleFoundError ( "Multiple users fit criteria" ) return _users [ 0 ] | User of KE - chain . | 92 | 6 |
4,288 | def team ( self , name = None , id = None , is_hidden = False , * * kwargs ) : _teams = self . teams ( name = name , id = id , * * kwargs ) if len ( _teams ) == 0 : raise NotFoundError ( "No team criteria matches" ) if len ( _teams ) != 1 : raise MultipleFoundError ( "Multiple teams fit criteria" ) return _teams [ 0 ] | Team of KE - chain . | 99 | 6 |
4,289 | def teams ( self , name = None , id = None , is_hidden = False , * * kwargs ) : request_params = { 'name' : name , 'id' : id , 'is_hidden' : is_hidden } if kwargs : request_params . update ( * * kwargs ) r = self . _request ( 'GET' , self . _build_url ( 'teams' ) , params = request_params ) if r . status_code != reques... | Teams of KE - chain . | 171 | 7 |
4,290 | def _create_part ( self , action , data , * * kwargs ) : # suppress_kevents should be in the data (not the query_params) if 'suppress_kevents' in kwargs : data [ 'suppress_kevents' ] = kwargs . pop ( 'suppress_kevents' ) # prepare url query parameters query_params = kwargs query_params [ 'select_action' ] = action resp... | Create a part internal core function . | 204 | 7 |
4,291 | def create_part ( self , parent , model , name = None , * * kwargs ) : if parent . category != Category . INSTANCE : raise IllegalArgumentError ( "The parent should be an category 'INSTANCE'" ) if model . category != Category . MODEL : raise IllegalArgumentError ( "The models should be of category 'MODEL'" ) if not nam... | Create a new part instance from a given model under a given parent . | 138 | 14 |
4,292 | def create_model ( self , parent , name , multiplicity = 'ZERO_MANY' , * * kwargs ) : if parent . category != Category . MODEL : raise IllegalArgumentError ( "The parent should be of category 'MODEL'" ) data = { "name" : name , "parent" : parent . id , "multiplicity" : multiplicity } return self . _create_part ( action... | Create a new child model under a given parent . | 110 | 10 |
4,293 | def _create_clone ( self , parent , part , * * kwargs ) : if part . category == Category . MODEL : select_action = 'clone_model' else : select_action = 'clone_instance' data = { "part" : part . id , "parent" : parent . id , "suppress_kevents" : kwargs . pop ( 'suppress_kevents' , None ) } # prepare url query parameters... | Create a new Part clone under the Parent . | 215 | 9 |
4,294 | def create_property ( self , model , name , description = None , property_type = PropertyType . CHAR_VALUE , default_value = None , unit = None , options = None ) : if model . category != Category . MODEL : raise IllegalArgumentError ( "The model should be of category MODEL" ) if not property_type . endswith ( '_VALUE'... | Create a new property model under a given model . | 475 | 10 |
4,295 | def create_service ( self , name , scope , description = None , version = None , service_type = ServiceType . PYTHON_SCRIPT , environment_version = ServiceEnvironmentVersion . PYTHON_3_5 , pkg_path = None ) : if service_type not in ServiceType . values ( ) : raise IllegalArgumentError ( "The type should be of one of {}... | Create a Service . | 320 | 4 |
4,296 | def delete_scope ( self , scope ) : assert isinstance ( scope , Scope ) , 'Scope "{}" is not a scope!' . format ( scope . name ) response = self . _request ( 'DELETE' , self . _build_url ( 'scope' , scope_id = str ( scope . id ) ) ) if response . status_code != requests . codes . no_content : # pragma: no cover raise A... | Delete a scope . | 119 | 4 |
4,297 | def set_sort ( self , request ) : # Look for 'sort' in get request. If not available use default. sort_request = request . GET . get ( self . sort_parameter , self . default_sort ) if sort_request . startswith ( '-' ) : sort_order = '-' sort_field = sort_request . split ( '-' ) [ 1 ] else : sort_order = '' sort_field =... | Take the sort parameter from the get parameters and split it into the field and the prefix | 151 | 17 |
4,298 | def get_next_sort_string ( self , field ) : # self.sort_field is the currect sort field if field == self . sort_field : next_sort = self . toggle_sort_order ( ) + field else : default_order_for_field = self . _allowed_sort_fields [ field ] [ 'default_direction' ] next_sort = default_order_for_field + field return self ... | If we re already sorted by the field then the sort query returned reverses the sort order . | 104 | 19 |
4,299 | def get_sort_indicator ( self , field ) : indicator = '' if field == self . sort_field : indicator = 'sort-asc' if self . sort_order == '-' : indicator = 'sort-desc' return indicator | Returns a sort class for the active sort only . That is if field is not sort_field then nothing will be returned becaues the sort is not active . | 51 | 33 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.