idx
int64
0
251k
question
stringlengths
53
3.53k
target
stringlengths
5
1.23k
len_question
int64
20
893
len_target
int64
3
238
249,000
def push_async_callback ( self , callback , * args , * * kwds ) : _exit_wrapper = self . _create_async_cb_wrapper ( callback , * args , * * kwds ) # We changed the signature, so using @wraps is not appropriate, but # setting __wrapped__ may still help with introspection. _exit_wrapper . __wrapped__ = callback self . _push_exit_callback ( _exit_wrapper , False ) return callback
Registers an arbitrary coroutine function and arguments . Cannot suppress exceptions .
108
14
249,001
async def Runtime ( args , env ) : r = _Runtime ( args , env ) await r . _init_cache ( ) return r
This is the async constructor for the _Runtime class .
30
11
249,002
def find_project_file ( start_dir , basename ) : prefix = os . path . abspath ( start_dir ) while True : candidate = os . path . join ( prefix , basename ) if os . path . isfile ( candidate ) : return candidate if os . path . exists ( candidate ) : raise PrintableError ( "Found {}, but it's not a file." . format ( candidate ) ) if os . path . dirname ( prefix ) == prefix : # We've walked all the way to the top. Bail. raise PrintableError ( "Can't find " + basename ) # Not found at this level. We must go...shallower. prefix = os . path . dirname ( prefix )
Walk up the directory tree until we find a file of the given name .
155
15
249,003
def delete_if_error ( path ) : try : yield except Exception : if os . path . exists ( path ) : os . remove ( path ) raise
If any exception is raised inside the context delete the file at the given path and allow the exception to continue .
33
22
249,004
def _format_file_lines ( files ) : LINES_TO_SHOW = 10 if len ( files ) <= LINES_TO_SHOW : lines = '\n' . join ( files ) else : lines = ( '\n' . join ( files [ : LINES_TO_SHOW - 1 ] ) + '\n...{} total' . format ( len ( files ) ) ) return lines
Given a list of filenames that we re about to print limit it to a reasonable number of lines .
91
22
249,005
def git_env ( self ) : env = dict ( os . environ ) for var in [ "HOME" , "XDG_CONFIG_HOME" ] : env . pop ( var , None ) env [ "GIT_CONFIG_NOSYSTEM" ] = "true" # Weirdly, GIT_INDEX_FILE is interpreted relative to the work tree. As # a workaround, we absoluteify the path. env [ "GIT_INDEX_FILE" ] = os . path . abspath ( self . index_file ) return env
Set the index file and prevent git from reading global configs .
122
13
249,006
def load_states ( ) : from pkg_resources import resource_stream # load state data from pickle file with resource_stream ( __name__ , 'states.pkl' ) as pklfile : for s in pickle . load ( pklfile ) : state = State ( * * s ) # create state object # create separate lists for obsolete, states, and territories if state . is_obsolete : OBSOLETE . append ( state ) elif state . is_territory : TERRITORIES . append ( state ) else : STATES . append ( state ) if state . is_contiguous : STATES_CONTIGUOUS . append ( state ) if state . is_continental : STATES_CONTINENTAL . append ( state ) # also create list of all states and territories STATES_AND_TERRITORIES . append ( state ) # provide package-level abbreviation access: us.states.MD globals ( ) [ state . abbr ] = state
Load state data from pickle file distributed with this package .
215
12
249,007
def lookup ( val , field = None , use_cache = True ) : import jellyfish if field is None : if FIPS_RE . match ( val ) : field = 'fips' elif ABBR_RE . match ( val ) : val = val . upper ( ) field = 'abbr' else : val = jellyfish . metaphone ( val ) field = 'name_metaphone' # see if result is in cache cache_key = "%s:%s" % ( field , val ) if use_cache and cache_key in _lookup_cache : return _lookup_cache [ cache_key ] for state in STATES_AND_TERRITORIES : if val == getattr ( state , field ) : _lookup_cache [ cache_key ] = state return state
Semi - fuzzy state lookup . This method will make a best effort attempt at finding the state based on the lookup value provided .
174
26
249,008
def query ( searchstr , outformat = FORMAT_BIBTEX , allresults = False ) : logger . debug ( "Query: {sstring}" . format ( sstring = searchstr ) ) searchstr = '/scholar?q=' + quote ( searchstr ) url = GOOGLE_SCHOLAR_URL + searchstr header = HEADERS header [ 'Cookie' ] = "GSP=CF=%d" % outformat request = Request ( url , headers = header ) response = urlopen ( request ) html = response . read ( ) html = html . decode ( 'utf8' ) # grab the links tmp = get_links ( html , outformat ) # follow the bibtex links to get the bibtex entries result = list ( ) if not allresults : tmp = tmp [ : 1 ] for link in tmp : url = GOOGLE_SCHOLAR_URL + link request = Request ( url , headers = header ) response = urlopen ( request ) bib = response . read ( ) bib = bib . decode ( 'utf8' ) result . append ( bib ) return result
Query google scholar .
246
4
249,009
def get_links ( html , outformat ) : if outformat == FORMAT_BIBTEX : refre = re . compile ( r'<a href="https://scholar.googleusercontent.com(/scholar\.bib\?[^"]*)' ) elif outformat == FORMAT_ENDNOTE : refre = re . compile ( r'<a href="https://scholar.googleusercontent.com(/scholar\.enw\?[^"]*)"' ) elif outformat == FORMAT_REFMAN : refre = re . compile ( r'<a href="https://scholar.googleusercontent.com(/scholar\.ris\?[^"]*)"' ) elif outformat == FORMAT_WENXIANWANG : refre = re . compile ( r'<a href="https://scholar.googleusercontent.com(/scholar\.ral\?[^"]*)"' ) reflist = refre . findall ( html ) # escape html entities reflist = [ re . sub ( '&(%s);' % '|' . join ( name2codepoint ) , lambda m : chr ( name2codepoint [ m . group ( 1 ) ] ) , s ) for s in reflist ] return reflist
Return a list of reference links from the html .
284
10
249,010
def convert_pdf_to_txt ( pdf , startpage = None ) : if startpage is not None : startpageargs = [ '-f' , str ( startpage ) ] else : startpageargs = [ ] stdout = subprocess . Popen ( [ "pdftotext" , "-q" ] + startpageargs + [ pdf , "-" ] , stdout = subprocess . PIPE ) . communicate ( ) [ 0 ] # python2 and 3 if not isinstance ( stdout , str ) : stdout = stdout . decode ( ) return stdout
Convert a pdf file to text and return the text .
132
12
249,011
def pdflookup ( pdf , allresults , outformat , startpage = None ) : txt = convert_pdf_to_txt ( pdf , startpage ) # remove all non alphanumeric characters txt = re . sub ( "\W" , " " , txt ) words = txt . strip ( ) . split ( ) [ : 20 ] gsquery = " " . join ( words ) bibtexlist = query ( gsquery , outformat , allresults ) return bibtexlist
Look a pdf up on google scholar and return bibtex items .
111
14
249,012
def _get_bib_element ( bibitem , element ) : lst = [ i . strip ( ) for i in bibitem . split ( "\n" ) ] for i in lst : if i . startswith ( element ) : value = i . split ( "=" , 1 ) [ - 1 ] value = value . strip ( ) while value . endswith ( ',' ) : value = value [ : - 1 ] while value . startswith ( '{' ) or value . startswith ( '"' ) : value = value [ 1 : - 1 ] return value return None
Return element from bibitem or None .
131
9
249,013
def rename_file ( pdf , bibitem ) : year = _get_bib_element ( bibitem , "year" ) author = _get_bib_element ( bibitem , "author" ) if author : author = author . split ( "," ) [ 0 ] title = _get_bib_element ( bibitem , "title" ) l = [ i for i in ( year , author , title ) if i ] filename = "-" . join ( l ) + ".pdf" newfile = pdf . replace ( os . path . basename ( pdf ) , filename ) logger . info ( 'Renaming {in_} to {out}' . format ( in_ = pdf , out = newfile ) ) os . rename ( pdf , newfile )
Attempt to rename pdf according to bibitem .
169
10
249,014
def soup_maker ( fh ) : try : from bs4 import BeautifulSoup soup = BeautifulSoup ( fh , "lxml" ) for tag in soup . find_all ( ) : tag . name = tag . name . lower ( ) except ImportError : from BeautifulSoup import BeautifulStoneSoup soup = BeautifulStoneSoup ( fh ) return soup
Takes a file handler returns BeautifulSoup
80
9
249,015
def parse ( self , file_handle ) : xbrl_obj = XBRL ( ) # if no file handle was given create our own if not hasattr ( file_handle , 'read' ) : file_handler = open ( file_handle ) else : file_handler = file_handle # Store the headers xbrl_file = XBRLPreprocessedFile ( file_handler ) xbrl = soup_maker ( xbrl_file . fh ) file_handler . close ( ) xbrl_base = xbrl . find ( name = re . compile ( "xbrl*:*" ) ) if xbrl . find ( 'xbrl' ) is None and xbrl_base is None : raise XBRLParserException ( 'The xbrl file is empty!' ) # lookahead to see if we need a custom leading element lookahead = xbrl . find ( name = re . compile ( "context" , re . IGNORECASE | re . MULTILINE ) ) . name if ":" in lookahead : self . xbrl_base = lookahead . split ( ":" ) [ 0 ] + ":" else : self . xbrl_base = "" return xbrl
parse is the main entry point for an XBRLParser . It takes a file handle .
270
19
249,016
def parseDEI ( self , xbrl , ignore_errors = 0 ) : dei_obj = DEI ( ) if ignore_errors == 2 : logging . basicConfig ( filename = '/tmp/xbrl.log' , level = logging . ERROR , format = '%(asctime)s %(levelname)s %(name)s %(message)s' ) logger = logging . getLogger ( __name__ ) else : logger = None trading_symbol = xbrl . find_all ( name = re . compile ( "(dei:tradingsymbol)" , re . IGNORECASE | re . MULTILINE ) ) dei_obj . trading_symbol = self . data_processing ( trading_symbol , xbrl , ignore_errors , logger , options = { 'type' : 'String' , 'no_context' : True } ) company_name = xbrl . find_all ( name = re . compile ( "(dei:entityregistrantname)" , re . IGNORECASE | re . MULTILINE ) ) dei_obj . company_name = self . data_processing ( company_name , xbrl , ignore_errors , logger , options = { 'type' : 'String' , 'no_context' : True } ) shares_outstanding = xbrl . find_all ( name = re . compile ( "(dei:entitycommonstocksharesoutstanding)" , re . IGNORECASE | re . MULTILINE ) ) dei_obj . shares_outstanding = self . data_processing ( shares_outstanding , xbrl , ignore_errors , logger , options = { 'type' : 'Number' , 'no_context' : True } ) public_float = xbrl . find_all ( name = re . compile ( "(dei:entitypublicfloat)" , re . IGNORECASE | re . MULTILINE ) ) dei_obj . public_float = self . data_processing ( public_float , xbrl , ignore_errors , logger , options = { 'type' : 'Number' , 'no_context' : True } ) return dei_obj
Parse DEI from our XBRL soup and return a DEI object .
485
17
249,017
def parseCustom ( self , xbrl , ignore_errors = 0 ) : custom_obj = Custom ( ) custom_data = xbrl . find_all ( re . compile ( '^((?!(us-gaap|dei|xbrll|xbrldi)).)*:\s*' , re . IGNORECASE | re . MULTILINE ) ) elements = { } for data in custom_data : if XBRLParser ( ) . is_number ( data . text ) : setattr ( custom_obj , data . name . split ( ':' ) [ 1 ] , data . text ) return custom_obj
Parse company custom entities from XBRL and return an Custom object .
139
15
249,018
def trim_decimals ( s , precision = - 3 ) : encoded = s . encode ( 'ascii' , 'ignore' ) str_val = "" if six . PY3 : str_val = str ( encoded , encoding = 'ascii' , errors = 'ignore' ) [ : precision ] else : # If precision is 0, this must be handled seperately if precision == 0 : str_val = str ( encoded ) else : str_val = str ( encoded ) [ : precision ] if len ( str_val ) > 0 : return float ( str_val ) else : return 0
Convert from scientific notation using precision
132
7
249,019
def data_processing ( self , elements , xbrl , ignore_errors , logger , context_ids = [ ] , * * kwargs ) : options = kwargs . get ( 'options' , { 'type' : 'Number' , 'no_context' : False } ) if options [ 'type' ] == 'String' : if len ( elements ) > 0 : return elements [ 0 ] . text if options [ 'no_context' ] == True : if len ( elements ) > 0 and XBRLParser ( ) . is_number ( elements [ 0 ] . text ) : return elements [ 0 ] . text try : # Extract the correct values by context correct_elements = [ ] for element in elements : std = element . attrs [ 'contextref' ] if std in context_ids : correct_elements . append ( element ) elements = correct_elements if len ( elements ) > 0 and XBRLParser ( ) . is_number ( elements [ 0 ] . text ) : decimals = elements [ 0 ] . attrs [ 'decimals' ] if decimals is not None : attr_precision = decimals if xbrl . precision != 0 and xbrl . precison != attr_precision : xbrl . precision = attr_precision if elements : return XBRLParser ( ) . trim_decimals ( elements [ 0 ] . text , int ( xbrl . precision ) ) else : return 0 else : return 0 except Exception as e : if ignore_errors == 0 : raise XBRLParserException ( 'value extraction error' ) elif ignore_errors == 1 : return 0 elif ignore_errors == 2 : logger . error ( str ( e ) + " error at " + '' . join ( elements [ 0 ] . text ) )
Process a XBRL tag object and extract the correct value as stated by the context .
396
18
249,020
def by_name ( self ) : return { key . split ( preferences_settings . SECTION_KEY_SEPARATOR ) [ - 1 ] : value for key , value in self . all ( ) . items ( ) }
Return a dictionary with preferences identifiers and values but without the section name in the identifier
47
16
249,021
def get_cache_key ( self , section , name ) : if not self . instance : return 'dynamic_preferences_{0}_{1}_{2}' . format ( self . model . __name__ , section , name ) return 'dynamic_preferences_{0}_{1}_{2}_{3}' . format ( self . model . __name__ , self . instance . pk , section , name , self . instance . pk )
Return the cache key corresponding to a given preference
103
9
249,022
def from_cache ( self , section , name ) : cached_value = self . cache . get ( self . get_cache_key ( section , name ) , CachedValueNotFound ) if cached_value is CachedValueNotFound : raise CachedValueNotFound if cached_value == preferences_settings . CACHE_NONE_VALUE : cached_value = None return self . registry . get ( section = section , name = name ) . serializer . deserialize ( cached_value )
Return a preference raw_value from cache
108
8
249,023
def many_from_cache ( self , preferences ) : keys = { p : self . get_cache_key ( p . section . name , p . name ) for p in preferences } cached = self . cache . get_many ( list ( keys . values ( ) ) ) for k , v in cached . items ( ) : # we replace dummy cached values by None here, if needed if v == preferences_settings . CACHE_NONE_VALUE : cached [ k ] = None # we have to remap returned value since the underlying cached keys # are not usable for an end user return { p . identifier ( ) : p . serializer . deserialize ( cached [ k ] ) for p , k in keys . items ( ) if k in cached }
Return cached value for given preferences missing preferences will be skipped
162
11
249,024
def all ( self ) : if not preferences_settings . ENABLE_CACHE : return self . load_from_db ( ) preferences = self . registry . preferences ( ) # first we hit the cache once for all existing preferences a = self . many_from_cache ( preferences ) if len ( a ) == len ( preferences ) : return a # avoid database hit if not necessary # then we fill those that miss, but exist in the database # (just hit the database for all of them, filtering is complicated, and # in most cases you'd need to grab the majority of them anyway) a . update ( self . load_from_db ( cache = True ) ) return a
Return a dictionary containing all preferences by section Loaded from cache or from db in case of cold cache
145
19
249,025
def load_from_db ( self , cache = False ) : a = { } db_prefs = { p . preference . identifier ( ) : p for p in self . queryset } for preference in self . registry . preferences ( ) : try : db_pref = db_prefs [ preference . identifier ( ) ] except KeyError : db_pref = self . create_db_pref ( section = preference . section . name , name = preference . name , value = preference . get ( 'default' ) ) else : # cache if create_db_pref() hasn't already done so if cache : self . to_cache ( db_pref ) a [ preference . identifier ( ) ] = db_pref . value return a
Return a dictionary of preferences by section directly from DB
162
10
249,026
def validate_value ( self , value ) : field = self . instance . preference . setup_field ( ) value = field . to_python ( value ) field . validate ( value ) field . run_validators ( value ) return value
We call validation from the underlying form field
50
8
249,027
def to_python ( cls , value , * * kwargs ) : if not value : return '' try : return str ( value ) except : pass try : return value . encode ( 'utf-8' ) except : pass raise cls . exception ( "Cannot deserialize value {0} tostring" . format ( value ) )
String deserialisation just return the value as a string
74
11
249,028
def get_by_instance ( self , instance ) : # we iterate throught registered preference models in order to get the instance class # and check if instance is and instance of this class for model , registry in self . items ( ) : try : instance_class = model . _meta . get_field ( 'instance' ) . remote_field . model if isinstance ( instance , instance_class ) : return registry except FieldDoesNotExist : # global preferences pass return None
Return a preference registry using a model instance
101
8
249,029
def register ( self , preference_class ) : preference = preference_class ( registry = self ) self . section_objects [ preference . section . name ] = preference . section try : self [ preference . section . name ] [ preference . name ] = preference except KeyError : self [ preference . section . name ] = collections . OrderedDict ( ) self [ preference . section . name ] [ preference . name ] = preference return preference_class
Store the given preference class in the registry .
93
9
249,030
def get ( self , name , section = None , fallback = False ) : # try dotted notation try : _section , name = name . split ( preferences_settings . SECTION_KEY_SEPARATOR ) return self [ _section ] [ name ] except ValueError : pass # use standard params try : return self [ section ] [ name ] except KeyError : if fallback : return self . _fallback ( section_name = section , pref_name = name ) raise NotFoundInRegistry ( "No such preference in {0} with section={1} and name={2}" . format ( self . __class__ . __name__ , section , name ) )
Returns a previously registered preference
142
5
249,031
def manager ( self , * * kwargs ) : return PreferencesManager ( registry = self , model = self . preference_model , * * kwargs )
Return a preference manager that can be used to retrieve preference values
34
12
249,032
def preferences ( self , section = None ) : if section is None : return [ self [ section ] [ name ] for section in self for name in self [ section ] ] else : return [ self [ section ] [ name ] for name in self [ section ] ]
Return a list of all registered preferences or a list of preferences registered for a given section
55
17
249,033
def get_queryset ( self ) : self . init_preferences ( ) queryset = super ( PreferenceViewSet , self ) . get_queryset ( ) section = self . request . query_params . get ( 'section' ) if section : queryset = queryset . filter ( section = section ) return queryset
We just ensure preferences are actually populated before fetching from db
77
12
249,034
def bulk ( self , request , * args , * * kwargs ) : manager = self . get_manager ( ) errors = { } preferences = [ ] payload = request . data # first, we check updated preferences actually exists in the registry try : for identifier , value in payload . items ( ) : try : preferences . append ( self . queryset . model . registry . get ( identifier ) ) except exceptions . NotFoundInRegistry : errors [ identifier ] = 'invalid preference' except ( TypeError , AttributeError ) : return Response ( 'invalid payload' , status = 400 ) if errors : return Response ( errors , status = 400 ) # now, we generate an optimized Q objects to retrieve all matching # preferences at once from database queries = [ Q ( section = p . section . name , name = p . name ) for p in preferences ] query = queries [ 0 ] for q in queries [ 1 : ] : query |= q preferences_qs = self . get_queryset ( ) . filter ( query ) # next, we generate a serializer for each database preference serializer_objects = [ ] for p in preferences_qs : s = self . get_serializer_class ( ) ( p , data = { 'value' : payload [ p . preference . identifier ( ) ] } ) serializer_objects . append ( s ) validation_errors = { } # we check if any serializer is invalid for s in serializer_objects : if s . is_valid ( ) : continue validation_errors [ s . instance . preference . identifier ( ) ] = s . errors if validation_errors : return Response ( validation_errors , status = 400 ) for s in serializer_objects : s . save ( ) return Response ( [ s . data for s in serializer_objects ] , status = 200 , )
Update multiple preferences at once
389
5
249,035
def set_value ( self , value ) : self . raw_value = self . preference . serializer . serialize ( value )
Save serialized self . value to self . raw_value
28
12
249,036
def delete_preferences ( queryset ) : deleted = [ ] # Iterate through preferences. If an error is raised when accessing preference object, just delete it for p in queryset : try : pref = p . registry . get ( section = p . section , name = p . name , fallback = False ) except NotFoundInRegistry : p . delete ( ) deleted . append ( p ) return deleted
Delete preferences objects if they are not present in registry . Return a list of deleted objects
89
17
249,037
def create_deletion_handler ( preference ) : def delete_related_preferences ( sender , instance , * args , * * kwargs ) : queryset = preference . registry . preference_model . objects . filter ( name = preference . name , section = preference . section ) related_preferences = queryset . filter ( raw_value = preference . serializer . serialize ( instance ) ) related_preferences . delete ( ) return delete_related_preferences
Will generate a dynamic handler to purge related preference on instance deletion
107
12
249,038
def get_field_kwargs ( self ) : kwargs = self . field_kwargs . copy ( ) kwargs . setdefault ( 'label' , self . get ( 'verbose_name' ) ) kwargs . setdefault ( 'help_text' , self . get ( 'help_text' ) ) kwargs . setdefault ( 'widget' , self . get ( 'widget' ) ) kwargs . setdefault ( 'required' , self . get ( 'required' ) ) kwargs . setdefault ( 'initial' , self . initial ) kwargs . setdefault ( 'validators' , [ ] ) kwargs [ 'validators' ] . append ( self . validate ) return kwargs
Return a dict of arguments to use as parameters for the field class instianciation .
162
17
249,039
def get_api_field_data ( self ) : field = self . setup_field ( ) d = { 'class' : field . __class__ . __name__ , 'widget' : { 'class' : field . widget . __class__ . __name__ } } try : d [ 'input_type' ] = field . widget . input_type except AttributeError : # some widgets, such as Select do not have an input type # in django < 1.11 d [ 'input_type' ] = None return d
Field data to serialize for use on front - end side for example will include choices available for a choice field
116
22
249,040
def commiter_factory ( config : dict ) -> BaseCommitizen : name : str = config [ "name" ] try : _cz = registry [ name ] ( config ) except KeyError : msg_error = ( "The commiter has not been found in the system.\n\n" f"Try running 'pip install {name}'\n" ) out . error ( msg_error ) raise SystemExit ( NO_COMMITIZEN_FOUND ) else : return _cz
Return the correct commitizen existing in the registry .
107
10
249,041
def generate_version ( current_version : str , increment : str , prerelease : Optional [ str ] = None ) -> Version : pre_version = prerelease_generator ( current_version , prerelease = prerelease ) semver = semver_generator ( current_version , increment = increment ) # TODO: post version # TODO: dev version return Version ( f"{semver}{pre_version}" )
Based on the given increment a proper semver will be generated .
91
13
249,042
def update_version_in_files ( current_version : str , new_version : str , files : list ) : for filepath in files : # Read in the file with open ( filepath , "r" ) as file : filedata = file . read ( ) # Replace the target string filedata = filedata . replace ( current_version , new_version ) # Write the file out again with open ( filepath , "w" ) as file : file . write ( filedata )
Change old version to the new one in every file given .
105
12
249,043
def create_tag ( version : Union [ Version , str ] , tag_format : Optional [ str ] = None ) : if isinstance ( version , str ) : version = Version ( version ) if not tag_format : return version . public major , minor , patch = version . release prerelease = "" if version . is_prerelease : prerelease = f"{version.pre[0]}{version.pre[1]}" t = Template ( tag_format ) return t . safe_substitute ( version = version , major = major , minor = minor , patch = patch , prerelease = prerelease )
The tag and the software version might be different .
131
10
249,044
def read_pyproject_conf ( data : str ) -> dict : doc = parse ( data ) try : return doc [ "tool" ] [ "commitizen" ] except exceptions . NonExistentKey : return { }
We expect to have a section in pyproject looking like
47
11
249,045
def read_raw_parser_conf ( data : str ) -> dict : config = configparser . ConfigParser ( allow_no_value = True ) config . read_string ( data ) try : _data : dict = dict ( config [ "commitizen" ] ) if "files" in _data : files = _data [ "files" ] _f = json . loads ( files ) _data . update ( { "files" : _f } ) return _data except KeyError : return { }
We expect to have a section like this
107
8
249,046
def set_key ( key : str , value : str ) -> dict : if not _conf . path : return { } if "toml" in _conf . path : with open ( _conf . path , "r" ) as f : parser = parse ( f . read ( ) ) parser [ "tool" ] [ "commitizen" ] [ key ] = value with open ( _conf . path , "w" ) as f : f . write ( parser . as_string ( ) ) else : parser = configparser . ConfigParser ( ) parser . read ( _conf . path ) parser [ "commitizen" ] [ key ] = value with open ( _conf . path , "w" ) as f : parser . write ( f ) return _conf . config
Set or update a key in the conf .
164
9
249,047
def close ( self ) : if self . fp : self . fp . close ( ) self . fp = None if self . fp_extra : self . fp_extra . close ( ) self . fp_extra = None self . ctype = None
Close a file pointer .
58
5
249,048
def get_compression_type ( self , file_name ) : ext = os . path . splitext ( file_name ) [ 1 ] if ext == '.gz' : self . ctype = 'gzip' elif ext == '.bz2' : self . ctype = 'bzip2' elif ext in ( '.xz' , '.lzma' ) : self . ctype = 'lzma' else : self . ctype = None
Determine compression type for a given file using its extension .
103
13
249,049
def do ( to_install ) : for solver in to_install : print ( 'preparing {0}' . format ( solver ) ) download_archive ( sources [ solver ] ) extract_archive ( sources [ solver ] [ - 1 ] , solver ) adapt_files ( solver ) patch_solver ( solver ) compile_solver ( solver )
Prepare all solvers specified in the command line .
82
11
249,050
def adapt_files ( solver ) : print ( "adapting {0}'s files" . format ( solver ) ) root = os . path . join ( 'solvers' , solver ) for arch in to_extract [ solver ] : arch = os . path . join ( root , arch ) extract_archive ( arch , solver , put_inside = True ) for fnames in to_move [ solver ] : old = os . path . join ( root , fnames [ 0 ] ) new = os . path . join ( root , fnames [ 1 ] ) os . rename ( old , new ) for f in to_remove [ solver ] : f = os . path . join ( root , f ) if os . path . isdir ( f ) : shutil . rmtree ( f ) else : os . remove ( f )
Rename and remove files whenever necessary .
186
8
249,051
def _map_extlit ( self , l ) : v = abs ( l ) if v in self . vmap . e2i : return int ( copysign ( self . vmap . e2i [ v ] , l ) ) else : self . topv += 1 self . vmap . e2i [ v ] = self . topv self . vmap . i2e [ self . topv ] = v return int ( copysign ( self . topv , l ) )
Map an external variable to an internal one if necessary .
107
11
249,052
def init ( self , bootstrap_with ) : # formula encoding the sets to hit formula = WCNF ( ) # hard clauses for to_hit in bootstrap_with : to_hit = list ( map ( lambda obj : self . idpool . id ( obj ) , to_hit ) ) formula . append ( to_hit ) # soft clauses for obj_id in six . iterkeys ( self . idpool . id2obj ) : formula . append ( [ - obj_id ] , weight = 1 ) if self . htype == 'rc2' : # using the RC2-A options from MaxSAT evaluation 2018 self . oracle = RC2 ( formula , solver = self . solver , adapt = False , exhaust = True , trim = 5 ) elif self . htype == 'lbx' : self . oracle = LBX ( formula , solver_name = self . solver , use_cld = True ) else : self . oracle = MCSls ( formula , solver_name = self . solver , use_cld = True )
This method serves for initializing the hitting set solver with a given list of sets to hit . Concretely the hitting set problem is encoded into partial MaxSAT as outlined above which is then fed either to a MaxSAT solver or an MCS enumerator .
233
56
249,053
def get ( self ) : model = self . oracle . compute ( ) if model : if self . htype == 'rc2' : # extracting a hitting set self . hset = filter ( lambda v : v > 0 , model ) else : self . hset = model return list ( map ( lambda vid : self . idpool . id2obj [ vid ] , self . hset ) )
This method computes and returns a hitting set . The hitting set is obtained using the underlying oracle operating the MaxSAT problem formulation . The computed solution is mapped back to objects of the problem domain .
87
41
249,054
def hit ( self , to_hit ) : # translating objects to variables to_hit = list ( map ( lambda obj : self . idpool . id ( obj ) , to_hit ) ) # a soft clause should be added for each new object new_obj = list ( filter ( lambda vid : vid not in self . oracle . vmap . e2i , to_hit ) ) # new hard clause self . oracle . add_clause ( to_hit ) # new soft clauses for vid in new_obj : self . oracle . add_clause ( [ - vid ] , 1 )
This method adds a new set to hit to the hitting set solver . This is done by translating the input iterable of objects into a list of Boolean variables in the MaxSAT problem formulation .
133
40
249,055
def block ( self , to_block ) : # translating objects to variables to_block = list ( map ( lambda obj : self . idpool . id ( obj ) , to_block ) ) # a soft clause should be added for each new object new_obj = list ( filter ( lambda vid : vid not in self . oracle . vmap . e2i , to_block ) ) # new hard clause self . oracle . add_clause ( [ - vid for vid in to_block ] ) # new soft clauses for vid in new_obj : self . oracle . add_clause ( [ - vid ] , 1 )
The method serves for imposing a constraint forbidding the hitting set solver to compute a given hitting set . Each set to block is encoded as a hard clause in the MaxSAT problem formulation which is then added to the underlying oracle .
142
48
249,056
def _compute ( self , approx ) : i = 0 while i < len ( approx ) : to_test = approx [ : i ] + approx [ ( i + 1 ) : ] sel , clid = approx [ i ] , self . vmap [ approx [ i ] ] if self . verbose > 1 : print ( 'c testing clid: {0}' . format ( clid ) , end = '' ) if self . oracle . solve ( assumptions = to_test ) : if self . verbose > 1 : print ( ' -> sat (keeping {0})' . format ( clid ) ) i += 1 else : if self . verbose > 1 : print ( ' -> unsat (removing {0})' . format ( clid ) ) approx = to_test
Deletion - based MUS extraction . Given an over - approximation of an MUS i . e . an unsatisfiable core previously returned by a SAT oracle the method represents a loop which at each iteration removes a clause from the core and checks whether the remaining clauses of the approximation are unsatisfiable together with the hard clauses .
171
64
249,057
def run ( self ) : # download and compile solvers prepare . do ( to_install ) # now, do standard build distutils . command . build . build . run ( self )
Download patch and compile SAT solvers before building .
39
10
249,058
def add_clause ( self , clause , no_return = True ) : if self . solver : res = self . solver . add_clause ( clause , no_return ) if not no_return : return res
This method is used to add a single clause to the solver . An optional argument no_return controls whether or not to check the formula s satisfiability after adding the new clause .
49
37
249,059
def append_formula ( self , formula , no_return = True ) : if self . solver : res = self . solver . append_formula ( formula , no_return ) if not no_return : return res
This method can be used to add a given list of clauses into the solver .
49
17
249,060
def enum_models ( self , assumptions = [ ] ) : if self . glucose : done = False while not done : if self . use_timer : start_time = time . clock ( ) self . status = pysolvers . glucose41_solve ( self . glucose , assumptions ) if self . use_timer : self . call_time = time . clock ( ) - start_time self . accu_time += self . call_time model = self . get_model ( ) if model : self . add_clause ( [ - l for l in model ] ) # blocking model yield model else : done = True
Iterate over models of the internal formula .
134
9
249,061
def propagate ( self , assumptions = [ ] , phase_saving = 0 ) : if self . maplesat : if self . use_timer : start_time = time . clock ( ) # saving default SIGINT handler def_sigint_handler = signal . signal ( signal . SIGINT , signal . SIG_DFL ) st , props = pysolvers . maplechrono_propagate ( self . maplesat , assumptions , phase_saving ) # recovering default SIGINT handler def_sigint_handler = signal . signal ( signal . SIGINT , def_sigint_handler ) if self . use_timer : self . call_time = time . clock ( ) - start_time self . accu_time += self . call_time return bool ( st ) , props if props != None else [ ]
Propagate a given set of assumption literals .
177
10
249,062
def get_proof ( self ) : if self . maplesat and self . prfile : self . prfile . seek ( 0 ) return [ line . rstrip ( ) for line in self . prfile . readlines ( ) ]
Get a proof produced while deciding the formula .
50
9
249,063
def add_atmost ( self , lits , k , no_return = True ) : if self . minicard : res = pysolvers . minicard_add_am ( self . minicard , lits , k ) if res == False : self . status = False if not no_return : return res
Add a new atmost constraint to solver s internal formula .
71
13
249,064
def id ( self , obj ) : vid = self . obj2id [ obj ] if vid not in self . id2obj : self . id2obj [ vid ] = obj return vid
The method is to be used to assign an integer variable ID for a given new object . If the object already has an ID no new ID is created and the old one is returned instead .
44
38
249,065
def _next ( self ) : self . top += 1 while self . _occupied and self . top >= self . _occupied [ 0 ] [ 0 ] : if self . top <= self . _occupied [ 0 ] [ 1 ] : self . top = self . _occupied [ 0 ] [ 1 ] + 1 self . _occupied . pop ( 0 ) return self . top
Get next variable ID . Skip occupied intervals if any .
78
11
249,066
def from_file ( self , fname , comment_lead = [ 'c' ] , compressed_with = 'use_ext' ) : with FileObject ( fname , mode = 'r' , compression = compressed_with ) as fobj : self . from_fp ( fobj . fp , comment_lead )
Read a CNF formula from a file in the DIMACS format . A file name is expected as an argument . A default argument is comment_lead for parsing comment lines . A given file can be compressed by either gzip bzip2 or lzma .
70
55
249,067
def from_fp ( self , file_pointer , comment_lead = [ 'c' ] ) : self . nv = 0 self . clauses = [ ] self . comments = [ ] comment_lead = tuple ( 'p' ) + tuple ( comment_lead ) for line in file_pointer : line = line . strip ( ) if line : if line [ 0 ] not in comment_lead : cl = [ int ( l ) for l in line . split ( ) [ : - 1 ] ] self . nv = max ( [ abs ( l ) for l in cl ] + [ self . nv ] ) self . clauses . append ( cl ) elif not line . startswith ( 'p cnf ' ) : self . comments . append ( line )
Read a CNF formula from a file pointer . A file pointer should be specified as an argument . The only default argument is comment_lead which can be used for parsing specific comment lines .
164
38
249,068
def from_clauses ( self , clauses ) : self . clauses = copy . deepcopy ( clauses ) for cl in self . clauses : self . nv = max ( [ abs ( l ) for l in cl ] + [ self . nv ] )
This methods copies a list of clauses into a CNF object .
55
13
249,069
def to_fp ( self , file_pointer , comments = None ) : # saving formula's internal comments for c in self . comments : print ( c , file = file_pointer ) # saving externally specified comments if comments : for c in comments : print ( c , file = file_pointer ) print ( 'p cnf' , self . nv , len ( self . clauses ) , file = file_pointer ) for cl in self . clauses : print ( ' ' . join ( str ( l ) for l in cl ) , '0' , file = file_pointer )
The method can be used to save a CNF formula into a file pointer . The file pointer is expected as an argument . Additionally supplementary comment lines can be specified in the comments parameter .
123
37
249,070
def append ( self , clause ) : self . nv = max ( [ abs ( l ) for l in clause ] + [ self . nv ] ) self . clauses . append ( clause )
Add one more clause to CNF formula . This method additionally updates the number of variables i . e . variable self . nv used in the formula .
41
31
249,071
def from_fp ( self , file_pointer , comment_lead = [ 'c' ] ) : self . nv = 0 self . hard = [ ] self . soft = [ ] self . wght = [ ] self . topw = 0 self . comments = [ ] comment_lead = tuple ( 'p' ) + tuple ( comment_lead ) for line in file_pointer : line = line . strip ( ) if line : if line [ 0 ] not in comment_lead : cl = [ int ( l ) for l in line . split ( ) [ : - 1 ] ] w = cl . pop ( 0 ) self . nv = max ( [ abs ( l ) for l in cl ] + [ self . nv ] ) if w >= self . topw : self . hard . append ( cl ) else : self . soft . append ( cl ) self . wght . append ( w ) elif not line . startswith ( 'p wcnf ' ) : self . comments . append ( line ) else : # expecting the preamble self . topw = int ( line . rsplit ( ' ' , 1 ) [ 1 ] )
Read a WCNF formula from a file pointer . A file pointer should be specified as an argument . The only default argument is comment_lead which can be used for parsing specific comment lines .
249
38
249,072
def to_fp ( self , file_pointer , comments = None ) : # saving formula's internal comments for c in self . comments : print ( c , file = file_pointer ) # saving externally specified comments if comments : for c in comments : print ( c , file = file_pointer ) print ( 'p wcnf' , self . nv , len ( self . hard ) + len ( self . soft ) , self . topw , file = file_pointer ) # soft clauses are dumped first because # some tools (e.g. LBX) cannot count them properly for i , cl in enumerate ( self . soft ) : print ( self . wght [ i ] , ' ' . join ( str ( l ) for l in cl ) , '0' , file = file_pointer ) for cl in self . hard : print ( self . topw , ' ' . join ( str ( l ) for l in cl ) , '0' , file = file_pointer )
The method can be used to save a WCNF formula into a file pointer . The file pointer is expected as an argument . Additionally supplementary comment lines can be specified in the comments parameter .
211
37
249,073
def append ( self , clause , weight = None ) : self . nv = max ( [ abs ( l ) for l in clause ] + [ self . nv ] ) if weight : self . soft . append ( clause ) self . wght . append ( weight ) else : self . hard . append ( clause )
Add one more clause to WCNF formula . This method additionally updates the number of variables i . e . variable self . nv used in the formula .
68
31
249,074
def from_fp ( self , file_pointer , comment_lead = [ 'c' ] ) : self . nv = 0 self . clauses = [ ] self . atmosts = [ ] self . comments = [ ] comment_lead = tuple ( 'p' ) + tuple ( comment_lead ) for line in file_pointer : line = line . strip ( ) if line : if line [ 0 ] not in comment_lead : if line [ - 1 ] == '0' : # normal clause cl = [ int ( l ) for l in line . split ( ) [ : - 1 ] ] self . nv = max ( [ abs ( l ) for l in cl ] + [ self . nv ] ) self . clauses . append ( cl ) else : # atmost/atleast constraint items = [ i for i in line . split ( ) ] lits = [ int ( l ) for l in items [ : - 2 ] ] rhs = int ( items [ - 1 ] ) self . nv = max ( [ abs ( l ) for l in lits ] + [ self . nv ] ) if items [ - 2 ] [ 0 ] == '>' : lits = list ( map ( lambda l : - l , lits ) ) rhs = len ( lits ) - rhs self . atmosts . append ( [ lits , rhs ] ) elif not line . startswith ( 'p cnf+ ' ) : self . comments . append ( line )
Read a CNF + formula from a file pointer . A file pointer should be specified as an argument . The only default argument is comment_lead which can be used for parsing specific comment lines .
323
39
249,075
def to_fp ( self , file_pointer , comments = None ) : # saving formula's internal comments for c in self . comments : print ( c , file = file_pointer ) # saving externally specified comments if comments : for c in comments : print ( c , file = file_pointer ) ftype = 'cnf+' if self . atmosts else 'cnf' print ( 'p' , ftype , self . nv , len ( self . clauses ) + len ( self . atmosts ) , file = file_pointer ) for cl in self . clauses : print ( ' ' . join ( str ( l ) for l in cl ) , '0' , file = file_pointer ) for am in self . atmosts : print ( ' ' . join ( str ( l ) for l in am [ 0 ] ) , '<=' , am [ 1 ] , file = file_pointer )
The method can be used to save a CNF + formula into a file pointer . The file pointer is expected as an argument . Additionally supplementary comment lines can be specified in the comments parameter .
195
38
249,076
def append ( self , clause , is_atmost = False ) : if not is_atmost : self . nv = max ( [ abs ( l ) for l in clause ] + [ self . nv ] ) self . clauses . append ( clause ) else : self . nv = max ( [ abs ( l ) for l in clause [ 0 ] ] + [ self . nv ] ) self . atmosts . append ( clause )
Add a single clause or a single AtMostK constraint to CNF + formula . This method additionally updates the number of variables i . e . variable self . nv used in the formula .
95
39
249,077
def from_fp ( self , file_pointer , comment_lead = [ 'c' ] ) : self . nv = 0 self . hard = [ ] self . atms = [ ] self . soft = [ ] self . wght = [ ] self . topw = 0 self . comments = [ ] comment_lead = tuple ( 'p' ) + tuple ( comment_lead ) for line in file_pointer : line = line . strip ( ) if line : if line [ 0 ] not in comment_lead : if line [ - 1 ] == '0' : # normal clause cl = [ int ( l ) for l in line . split ( ) [ : - 1 ] ] w = cl . pop ( 0 ) self . nv = max ( [ abs ( l ) for l in cl ] + [ self . nv ] ) if w >= self . topw : self . hard . append ( cl ) else : self . soft . append ( cl ) self . wght . append ( w ) else : # atmost/atleast constraint items = [ i for i in line . split ( ) ] lits = [ int ( l ) for l in items [ 1 : - 2 ] ] rhs = int ( items [ - 1 ] ) self . nv = max ( [ abs ( l ) for l in lits ] + [ self . nv ] ) if items [ - 2 ] [ 0 ] == '>' : lits = list ( map ( lambda l : - l , lits ) ) rhs = len ( lits ) - rhs self . atms . append ( [ lits , rhs ] ) elif not line . startswith ( 'p wcnf+ ' ) : self . comments . append ( line ) else : # expecting the preamble self . topw = int ( line . rsplit ( ' ' , 1 ) [ 1 ] )
Read a WCNF + formula from a file pointer . A file pointer should be specified as an argument . The only default argument is comment_lead which can be used for parsing specific comment lines .
407
39
249,078
def append ( self , clause , weight = None , is_atmost = False ) : if not is_atmost : self . nv = max ( [ abs ( l ) for l in clause ] + [ self . nv ] ) if weight : self . soft . append ( clause ) self . wght . append ( weight ) else : self . hard . append ( clause ) else : self . nv = max ( [ abs ( l ) for l in clause [ 0 ] ] + [ self . nv ] ) self . atms . append ( clause )
Add a single clause or a single AtMostK constraint to WCNF + formula . This method additionally updates the number of variables i . e . variable self . nv used in the formula .
121
39
249,079
def delete ( self ) : if self . oracle : self . time += self . oracle . time_accum ( ) # keep SAT solving time self . oracle . delete ( ) self . oracle = None
Explicit destructor of the internal SAT oracle .
46
11
249,080
def split_core ( self , minw ) : for clid in self . core : sel = self . sels [ clid ] if self . wght [ clid ] > minw : self . topv += 1 cl_new = [ ] for l in self . soft [ clid ] : if l != - sel : cl_new . append ( l ) else : cl_new . append ( - self . topv ) self . sels . append ( self . topv ) self . vmap [ self . topv ] = len ( self . soft ) self . soft . append ( cl_new ) self . wght . append ( self . wght [ clid ] - minw ) self . wght [ clid ] = minw self . scpy . append ( True )
Split clauses in the core whenever necessary .
177
8
249,081
def relax_core ( self ) : if len ( self . core ) > 1 : # relaxing rels = [ ] for clid in self . core : self . topv += 1 rels . append ( self . topv ) self . soft [ clid ] . append ( self . topv ) # creating a new cardinality constraint am1 = CardEnc . atmost ( lits = rels , top_id = self . topv , encoding = self . cenc ) for cl in am1 . clauses : self . hard . append ( cl ) # only if minicard # (for other solvers am1.atmosts should be empty) for am in am1 . atmosts : self . atm1 . append ( am ) self . topv = am1 . nv elif len ( self . core ) == 1 : # unit core => simply negate the clause self . remove_unit_core ( )
Relax and bound the core .
198
7
249,082
def parse_options ( ) : try : opts , args = getopt . getopt ( sys . argv [ 1 : ] , 'hms:v' , [ 'help' , 'model' , 'solver=' , 'verbose' ] ) except getopt . GetoptError as err : sys . stderr . write ( str ( err ) . capitalize ( ) ) print_usage ( ) sys . exit ( 1 ) solver = 'g4' verbose = 1 print_model = False for opt , arg in opts : if opt in ( '-h' , '--help' ) : print_usage ( ) sys . exit ( 0 ) elif opt in ( '-m' , '--model' ) : print_model = True elif opt in ( '-s' , '--solver' ) : solver = str ( arg ) elif opt in ( '-v' , '--verbose' ) : verbose += 1 else : assert False , 'Unhandled option: {0} {1}' . format ( opt , arg ) return print_model , solver , verbose , args
Parses command - line options .
246
8
249,083
def parse_formula ( fml_file ) : if re . search ( '\.wcnf(\.(gz|bz2|lzma|xz))?$' , fml_file ) : fml = WCNF ( from_file = fml_file ) else : # expecting '*.cnf' fml = CNF ( from_file = fml_file ) . weighted ( ) return fml
Parse and return MaxSAT formula .
93
9
249,084
def _init ( self , formula ) : self . oracle = Solver ( name = self . solver , bootstrap_with = formula . hard , incr = True , use_timer = True ) for i , cl in enumerate ( formula . soft ) : # TODO: if clause is unit, use its literal as selector # (ITotalizer must be extended to support PB constraints first) self . topv += 1 selv = self . topv cl . append ( self . topv ) self . oracle . add_clause ( cl ) self . sels . append ( selv ) if self . verbose > 1 : print ( 'c formula: {0} vars, {1} hard, {2} soft' . format ( formula . nv , len ( formula . hard ) , len ( formula . soft ) ) )
SAT oracle initialization . The method creates a new SAT oracle and feeds it with the formula s hard clauses . Afterwards all soft clauses of the formula are augmented with selector literals and also added to the solver . The list of all introduced selectors is stored in variable self . sels .
182
61
249,085
def _get_model_cost ( self , formula , model ) : model_set = set ( model ) cost = 0 for i , cl in enumerate ( formula . soft ) : cost += formula . wght [ i ] if all ( l not in model_set for l in filter ( lambda l : abs ( l ) <= self . formula . nv , cl ) ) else 0 return cost
Given a WCNF formula and a model the method computes the MaxSAT cost of the model i . e . the sum of weights of soft clauses that are unsatisfied by the model .
85
39
249,086
def parse_options ( ) : try : opts , args = getopt . getopt ( sys . argv [ 1 : ] , 'ac:e:hilms:t:vx' , [ 'adapt' , 'comp=' , 'enum=' , 'exhaust' , 'help' , 'incr' , 'blo' , 'minimize' , 'solver=' , 'trim=' , 'verbose' ] ) except getopt . GetoptError as err : sys . stderr . write ( str ( err ) . capitalize ( ) ) usage ( ) sys . exit ( 1 ) adapt = False exhaust = False cmode = None to_enum = 1 incr = False blo = False minz = False solver = 'g3' trim = 0 verbose = 1 for opt , arg in opts : if opt in ( '-a' , '--adapt' ) : adapt = True elif opt in ( '-c' , '--comp' ) : cmode = str ( arg ) elif opt in ( '-e' , '--enum' ) : to_enum = str ( arg ) if to_enum != 'all' : to_enum = int ( to_enum ) else : to_enum = 0 elif opt in ( '-h' , '--help' ) : usage ( ) sys . exit ( 0 ) elif opt in ( '-i' , '--incr' ) : incr = True elif opt in ( '-l' , '--blo' ) : blo = True elif opt in ( '-m' , '--minimize' ) : minz = True elif opt in ( '-s' , '--solver' ) : solver = str ( arg ) elif opt in ( '-t' , '--trim' ) : trim = int ( arg ) elif opt in ( '-v' , '--verbose' ) : verbose += 1 elif opt in ( '-x' , '--exhaust' ) : exhaust = True else : assert False , 'Unhandled option: {0} {1}' . format ( opt , arg ) return adapt , blo , cmode , to_enum , exhaust , incr , minz , solver , trim , verbose , args
Parses command - line option
500
7
249,087
def delete ( self ) : if self . oracle : self . oracle . delete ( ) self . oracle = None if self . solver != 'mc' : # for minicard, there is nothing to free for t in six . itervalues ( self . tobj ) : t . delete ( )
Explicit destructor of the internal SAT oracle and all the totalizer objects creating during the solving process .
68
22
249,088
def trim_core ( self ) : for i in range ( self . trim ) : # call solver with core assumption only # it must return 'unsatisfiable' self . oracle . solve ( assumptions = self . core ) # extract a new core new_core = self . oracle . get_core ( ) if len ( new_core ) == len ( self . core ) : # stop if new core is not better than the previous one break # otherwise, update core self . core = new_core
This method trims a previously extracted unsatisfiable core at most a given number of times . If a fixed point is reached before that the method returns .
107
30
249,089
def minimize_core ( self ) : if self . minz and len ( self . core ) > 1 : self . core = sorted ( self . core , key = lambda l : self . wght [ l ] ) self . oracle . conf_budget ( 1000 ) i = 0 while i < len ( self . core ) : to_test = self . core [ : i ] + self . core [ ( i + 1 ) : ] if self . oracle . solve_limited ( assumptions = to_test ) == False : self . core = to_test else : i += 1
Reduce a previously extracted core and compute an over - approximation of an MUS . This is done using the simple deletion - based MUS extraction algorithm .
125
29
249,090
def update_sum ( self , assump ) : # getting a totalizer object corresponding to assumption t = self . tobj [ assump ] # increment the current bound b = self . bnds [ assump ] + 1 if self . solver != 'mc' : # the case of standard totalizer encoding # increasing its bound t . increase ( ubound = b , top_id = self . topv ) # updating top variable id self . topv = t . top_id # adding its clauses to oracle if t . nof_new : for cl in t . cnf . clauses [ - t . nof_new : ] : self . oracle . add_clause ( cl ) else : # the case of cardinality constraints represented natively # right-hand side is always equal to the number of input literals rhs = len ( t . lits ) if b < rhs : # creating an additional bound if not t . rhs [ b ] : self . topv += 1 t . rhs [ b ] = self . topv # a new at-most-b constraint amb = [ [ - t . rhs [ b ] ] * ( rhs - b ) + t . lits , rhs ] self . oracle . add_atmost ( * amb ) return t , b
The method is used to increase the bound for a given totalizer sum . The totalizer object is identified by the input parameter assump which is an assumption literal associated with the totalizer object .
282
39
249,091
def set_bound ( self , tobj , rhs ) : # saving the sum and its weight in a mapping self . tobj [ - tobj . rhs [ rhs ] ] = tobj self . bnds [ - tobj . rhs [ rhs ] ] = rhs self . wght [ - tobj . rhs [ rhs ] ] = self . minw # adding a new assumption to force the sum to be at most rhs self . sums . append ( - tobj . rhs [ rhs ] )
Given a totalizer sum and its right - hand side to be enforced the method creates a new sum assumption literal which will be used in the following SAT oracle calls .
117
34
249,092
def filter_assumps ( self ) : self . sels = list ( filter ( lambda x : x not in self . garbage , self . sels ) ) self . sums = list ( filter ( lambda x : x not in self . garbage , self . sums ) ) self . bnds = { l : b for l , b in six . iteritems ( self . bnds ) if l not in self . garbage } self . wght = { l : w for l , w in six . iteritems ( self . wght ) if l not in self . garbage } self . garbage . clear ( )
Filter out unnecessary selectors and sums from the list of assumption literals . The corresponding values are also removed from the dictionaries of bounds and weights .
132
30
249,093
def __get_path_to_mecab_config ( self ) : if six . PY2 : path_mecab_config_dir = subprocess . check_output ( [ 'which' , 'mecab-config' ] ) path_mecab_config_dir = path_mecab_config_dir . strip ( ) . replace ( '/mecab-config' , '' ) else : path_mecab_config_dir = subprocess . check_output ( [ 'which' , 'mecab-config' ] ) . decode ( self . string_encoding ) path_mecab_config_dir = path_mecab_config_dir . strip ( ) . replace ( '/mecab-config' , '' ) logger . info ( msg = 'mecab-config is detected at {}' . format ( path_mecab_config_dir ) ) return path_mecab_config_dir
You get path into mecab - config
211
9
249,094
def __result_parser ( self , analyzed_line , is_feature , is_surface ) : # type: (text_type,bool,bool)->TokenizedResult assert isinstance ( analyzed_line , str ) assert isinstance ( is_feature , bool ) assert isinstance ( is_surface , bool ) surface , features = analyzed_line . split ( '\t' , 1 ) tuple_pos , word_stem = self . __feature_parser ( features , surface ) tokenized_obj = TokenizedResult ( node_obj = None , analyzed_line = analyzed_line , tuple_pos = tuple_pos , word_stem = word_stem , word_surface = surface , is_feature = is_feature , is_surface = is_surface ) return tokenized_obj
Extract surface word and feature from analyzed line . Extracted elements are returned with TokenizedResult class
169
20
249,095
def __is_valid_pos ( pos_tuple , valid_pos ) : # type: (Tuple[text_type,...],List[Tuple[text_type,...]])->bool def is_valid_pos ( valid_pos_tuple ) : # type: (Tuple[text_type,...])->bool length_valid_pos_tuple = len ( valid_pos_tuple ) if valid_pos_tuple == pos_tuple [ : length_valid_pos_tuple ] : return True else : return False seq_bool_flags = [ is_valid_pos ( valid_pos_tuple ) for valid_pos_tuple in valid_pos ] if True in set ( seq_bool_flags ) : return True else : return False
This function checks token s pos is with in POS set that user specified . If token meets all conditions Return True ; else return False
170
26
249,096
def filter_words ( tokenized_obj , valid_pos , stopwords , check_field_name = 'stem' ) : # type: (TokenizedSenetence, List[Tuple[text_type,...]], List[text_type],text_type) -> FilteredObject assert isinstance ( tokenized_obj , TokenizedSenetence ) assert isinstance ( valid_pos , list ) assert isinstance ( stopwords , list ) filtered_tokens = [ ] for token_obj in tokenized_obj . tokenized_objects : assert isinstance ( token_obj , TokenizedResult ) if check_field_name == 'stem' : res_stopwords = __is_sotpwords ( token_obj . word_stem , stopwords ) else : res_stopwords = __is_sotpwords ( token_obj . word_surface , stopwords ) res_pos_condition = __is_valid_pos ( token_obj . tuple_pos , valid_pos ) # case1: only pos filtering is ON if valid_pos != [ ] and stopwords == [ ] : if res_pos_condition : filtered_tokens . append ( token_obj ) # case2: only stopwords filtering is ON if valid_pos == [ ] and stopwords != [ ] : if res_stopwords is False : filtered_tokens . append ( token_obj ) # case3: both condition is ON if valid_pos != [ ] and stopwords != [ ] : if res_stopwords is False and res_pos_condition : filtered_tokens . append ( token_obj ) filtered_object = FilteredObject ( sentence = tokenized_obj . sentence , tokenized_objects = filtered_tokens , pos_condition = valid_pos , stopwords = stopwords ) return filtered_object
This function filter token that user don t want to take . Condition is stopword and pos .
398
19
249,097
def __extend_token_object ( self , token_object , is_denormalize = True , func_denormalizer = denormalize_text ) : # type: (TokenizedResult,bool,Callable[[str],str])->Tuple assert isinstance ( token_object , TokenizedResult ) if is_denormalize : if token_object . is_feature == True : if token_object . is_surface == True : token = ( func_denormalizer ( token_object . word_surface ) , token_object . tuple_pos ) else : token = ( func_denormalizer ( token_object . word_stem ) , token_object . tuple_pos ) else : if token_object . is_surface == True : token = func_denormalizer ( token_object . word_surface ) else : token = func_denormalizer ( token_object . word_stem ) else : if token_object . is_feature == True : if token_object . is_surface == True : token = ( token_object . word_surface , token_object . tuple_pos ) else : token = ( token_object . word_stem , token_object . tuple_pos ) else : if token_object . is_surface == True : token = token_object . word_surface else : token = token_object . word_stem return token
This method creates dict object from token object .
297
9
249,098
def notify ( notification , value = None , unset_environment = False ) : if not isinstance ( notification , Notification ) : raise TypeError ( "state must be an instance of Notification" ) state = notification . value if state . constant is not None and value : raise ValueError ( "State %s should contain only constant value %r" % ( state . name , state . constant ) , state . name , state . constant ) line = "%s=%s" % ( state . name , state . constant if state . constant is not None else state . type ( value ) ) log . debug ( "Send %r into systemd" , line ) try : return sd_notify ( line , unset_environment ) except Exception as e : log . error ( "%s" , e )
Send notification to systemd daemon
167
5
249,099
def expand_source_paths ( paths ) : for src_path in paths : # only track the source path if we can find it to avoid double-reloads # when the source and the compiled path change because on some # platforms they are not changed at the same time if src_path . endswith ( ( '.pyc' , '.pyo' ) ) : py_path = get_py_path ( src_path ) if os . path . exists ( py_path ) : src_path = py_path yield src_path
Convert pyc files into their source equivalents .
116
10