idx
int64
0
251k
question
stringlengths
53
3.53k
target
stringlengths
5
1.23k
len_question
int64
20
893
len_target
int64
3
238
7,400
def lookup ( ctx , path ) : regions = parse_intervals ( path , as_context = ctx . obj [ 'semantic' ] ) _report_from_regions ( regions , ctx . obj )
Determine which tests intersect a source interval .
48
10
7,401
def diff ( ctx , branch ) : diff = GitDiffReporter ( branch ) regions = diff . changed_intervals ( ) _report_from_regions ( regions , ctx . obj , file_factory = diff . old_file )
Determine which tests intersect a git diff .
54
10
7,402
def combine ( ctx , src , dst ) : c = coverage . Coverage ( config_file = ctx . obj [ 'rcfile' ] ) result = Smother ( c ) for infile in src : result |= Smother . load ( infile ) result . write ( dst )
Combine several smother reports .
62
7
7,403
def convert_to_relative_paths ( src , dst ) : result = Smother . convert_to_relative_paths ( Smother . load ( src ) ) result . write ( dst )
Converts all file paths in a smother report to relative paths relative to the current directory .
43
19
7,404
def csv ( ctx , dst ) : sm = Smother . load ( ctx . obj [ 'report' ] ) semantic = ctx . obj [ 'semantic' ] writer = _csv . writer ( dst , lineterminator = '\n' ) dst . write ( "source_context, test_context\n" ) writer . writerows ( sm . iter_records ( semantic = semantic ) )
Flatten a coverage file into a CSV of source_context testname
90
14
7,405
def erase ( ctx ) : if os . path . exists ( ctx . obj [ 'report' ] ) : os . remove ( ctx . obj [ 'report' ] )
Erase the existing smother report .
39
8
7,406
def to_coverage ( ctx ) : sm = Smother . load ( ctx . obj [ 'report' ] ) sm . coverage = coverage . coverage ( ) sm . write_coverage ( )
Produce a . coverage file from a smother file
44
11
7,407
def fill_missing_fields ( self , data , columns ) : for column in columns : if column not in data . columns : data [ column ] = scipy . zeros ( len ( data ) ) return data
This method fills with 0 s missing fields
46
8
7,408
def update_field_names ( self , data , matching ) : for key in matching . keys ( ) : if key in data . columns : data . rename ( columns = { key : matching [ key ] } ) return data
This method updates the names of the fields according to matching
47
11
7,409
def format_dates ( self , data , columns ) : for column in columns : if column in data . columns : data [ column ] = pandas . to_datetime ( data [ column ] ) return data
This method translates columns values into datetime objects
44
9
7,410
def remove_columns ( self , data , columns ) : for column in columns : if column in data . columns : data = data . drop ( column , axis = 1 ) return data
This method removes columns in data
39
6
7,411
def tange_grun ( v , v0 , gamma0 , a , b ) : x = v / v0 return gamma0 * ( 1. + a * ( np . power ( x , b ) - 1. ) )
calculate Gruneisen parameter for the Tange equation
50
12
7,412
def tange_debyetemp ( v , v0 , gamma0 , a , b , theta0 ) : x = v / v0 gamma = tange_grun ( v , v0 , gamma0 , a , b ) if isuncertainties ( [ v , v0 , gamma0 , a , b , theta0 ] ) : theta = theta0 * np . power ( x , ( - 1. * ( 1. - a ) * gamma0 ) ) * unp . exp ( ( gamma0 - gamma ) / b ) else : theta = theta0 * np . power ( x , ( - 1. * ( 1. - a ) * gamma0 ) ) * np . exp ( ( gamma0 - gamma ) / b ) return theta
calculate Debye temperature for the Tange equation
168
11
7,413
def tange_pth ( v , temp , v0 , gamma0 , a , b , theta0 , n , z , t_ref = 300. , three_r = 3. * constants . R ) : v_mol = vol_uc2mol ( v , z ) gamma = tange_grun ( v , v0 , gamma0 , a , b ) theta = tange_debyetemp ( v , v0 , gamma0 , a , b , theta0 ) xx = theta / temp debye = debye_E ( xx ) if t_ref == 0. : debye0 = 0. else : xx0 = theta / t_ref debye0 = debye_E ( xx0 ) Eth0 = three_r * n * t_ref * debye0 Eth = three_r * n * temp * debye delEth = Eth - Eth0 p_th = ( gamma / v_mol * delEth ) * 1.e-9 return p_th
calculate thermal pressure for the Tange equation
221
10
7,414
def _make_passage_kwargs ( urn , reference ) : kwargs = { } if urn is not None : if reference is not None : kwargs [ "urn" ] = URN ( "{}:{}" . format ( urn . upTo ( URN . VERSION ) , reference ) ) else : kwargs [ "urn" ] = urn return kwargs
Little helper used by CapitainsCtsPassage here to comply with parents args
87
17
7,415
def getTextualNode ( self , subreference = None , simple = False ) : if subreference is None : return self . _getSimplePassage ( ) if not isinstance ( subreference , CtsReference ) : if isinstance ( subreference , str ) : subreference = CtsReference ( subreference ) elif isinstance ( subreference , list ) : subreference = CtsReference ( "." . join ( subreference ) ) if len ( subreference . start ) > self . citation . root . depth : raise CitationDepthError ( "URN is deeper than citation scheme" ) if simple is True : return self . _getSimplePassage ( subreference ) if not subreference . is_range ( ) : start = end = subreference . start . list else : start , end = subreference . start . list , subreference . end . list citation_start = self . citation . root [ len ( start ) - 1 ] citation_end = self . citation . root [ len ( end ) - 1 ] start , end = citation_start . fill ( passage = start ) , citation_end . fill ( passage = end ) start , end = normalizeXpath ( start . split ( "/" ) [ 2 : ] ) , normalizeXpath ( end . split ( "/" ) [ 2 : ] ) xml = self . textObject . xml if isinstance ( xml , etree . _Element ) : root = copyNode ( xml ) else : root = copyNode ( xml . getroot ( ) ) root = passageLoop ( xml , root , start , end ) if self . urn : urn = URN ( "{}:{}" . format ( self . urn , subreference ) ) else : urn = None return CapitainsCtsPassage ( urn = urn , resource = root , text = self , citation = citation_start , reference = subreference )
Finds a passage in the current text
403
8
7,416
def _getSimplePassage ( self , reference = None ) : if reference is None : return _SimplePassage ( resource = self . resource , reference = None , urn = self . urn , citation = self . citation . root , text = self ) subcitation = self . citation . root [ reference . depth - 1 ] resource = self . resource . xpath ( subcitation . fill ( reference ) , namespaces = XPATH_NAMESPACES ) if len ( resource ) != 1 : raise InvalidURN return _SimplePassage ( resource [ 0 ] , reference = reference , urn = self . urn , citation = subcitation , text = self . textObject )
Retrieve a single node representing the passage .
147
9
7,417
def getReffs ( self , level : int = 1 , subreference : CtsReference = None ) -> CtsReferenceSet : if not subreference and hasattr ( self , "reference" ) : subreference = self . reference elif subreference and not isinstance ( subreference , CtsReference ) : subreference = CtsReference ( subreference ) return self . getValidReff ( level = level , reference = subreference )
CtsReference available at a given level
94
8
7,418
def xpath ( self , * args , * * kwargs ) : if "smart_strings" not in kwargs : kwargs [ "smart_strings" ] = False return self . resource . xpath ( * args , * * kwargs )
Perform XPath on the passage XML
57
8
7,419
def tostring ( self , * args , * * kwargs ) : return etree . tostring ( self . resource , * args , * * kwargs )
Transform the CapitainsCtsPassage in XML string
36
12
7,420
def childIds ( self ) : if self . depth >= len ( self . citation . root ) : return [ ] elif self . _children is not None : return self . _children else : self . _children = self . getReffs ( ) return self . _children
Children of the passage
60
4
7,421
def location ( hexgrid_type , coord ) : if hexgrid_type == TILE : return str ( coord ) elif hexgrid_type == NODE : tile_id = nearest_tile_to_node ( coord ) dirn = tile_node_offset_to_direction ( coord - tile_id_to_coord ( tile_id ) ) return '({} {})' . format ( tile_id , dirn ) elif hexgrid_type == EDGE : tile_id = nearest_tile_to_edge ( coord ) dirn = tile_edge_offset_to_direction ( coord - tile_id_to_coord ( tile_id ) ) return '({} {})' . format ( tile_id , dirn ) else : logging . warning ( 'unsupported hexgrid_type={}' . format ( hexgrid_type ) ) return None
Returns a formatted string representing the coordinate . The format depends on the coordinate type .
188
16
7,422
def coastal_edges ( tile_id ) : edges = list ( ) tile_coord = tile_id_to_coord ( tile_id ) for edge_coord in edges_touching_tile ( tile_id ) : dirn = tile_edge_offset_to_direction ( edge_coord - tile_coord ) if tile_id_in_direction ( tile_id , dirn ) is None : edges . append ( edge_coord ) return edges
Returns a list of coastal edge coordinate .
99
8
7,423
def tile_id_in_direction ( from_tile_id , direction ) : coord_from = tile_id_to_coord ( from_tile_id ) for offset , dirn in _tile_tile_offsets . items ( ) : if dirn == direction : coord_to = coord_from + offset if coord_to in legal_tile_coords ( ) : return tile_id_from_coord ( coord_to ) return None
Variant on direction_to_tile . Returns None if there s no tile there .
98
18
7,424
def direction_to_tile ( from_tile_id , to_tile_id ) : coord_from = tile_id_to_coord ( from_tile_id ) coord_to = tile_id_to_coord ( to_tile_id ) direction = tile_tile_offset_to_direction ( coord_to - coord_from ) # logging.debug('Tile direction: {}->{} is {}'.format( # from_tile.tile_id, # to_tile.tile_id, # direction # )) return direction
Convenience method wrapping tile_tile_offset_to_direction . Used to get the direction of the offset between two tiles . The tiles must be adjacent .
117
33
7,425
def edge_coord_in_direction ( tile_id , direction ) : tile_coord = tile_id_to_coord ( tile_id ) for edge_coord in edges_touching_tile ( tile_id ) : if tile_edge_offset_to_direction ( edge_coord - tile_coord ) == direction : return edge_coord raise ValueError ( 'No edge found in direction={} at tile_id={}' . format ( direction , tile_id ) )
Returns the edge coordinate in the given direction at the given tile identifier .
104
14
7,426
def node_coord_in_direction ( tile_id , direction ) : tile_coord = tile_id_to_coord ( tile_id ) for node_coord in nodes_touching_tile ( tile_id ) : if tile_node_offset_to_direction ( node_coord - tile_coord ) == direction : return node_coord raise ValueError ( 'No node found in direction={} at tile_id={}' . format ( direction , tile_id ) )
Returns the node coordinate in the given direction at the given tile identifier .
104
14
7,427
def tile_id_from_coord ( coord ) : for i , c in _tile_id_to_coord . items ( ) : if c == coord : return i raise Exception ( 'Tile id lookup failed, coord={} not found in map' . format ( hex ( coord ) ) )
Convert a tile coordinate to its corresponding tile identifier .
63
11
7,428
def nearest_tile_to_edge_using_tiles ( tile_ids , edge_coord ) : for tile_id in tile_ids : if edge_coord - tile_id_to_coord ( tile_id ) in _tile_edge_offsets . keys ( ) : return tile_id logging . critical ( 'Did not find a tile touching edge={}' . format ( edge_coord ) )
Get the first tile found adjacent to the given edge . Returns a tile identifier .
89
16
7,429
def nearest_tile_to_node_using_tiles ( tile_ids , node_coord ) : for tile_id in tile_ids : if node_coord - tile_id_to_coord ( tile_id ) in _tile_node_offsets . keys ( ) : return tile_id logging . critical ( 'Did not find a tile touching node={}' . format ( node_coord ) )
Get the first tile found adjacent to the given node . Returns a tile identifier .
89
16
7,430
def edges_touching_tile ( tile_id ) : coord = tile_id_to_coord ( tile_id ) edges = [ ] for offset in _tile_edge_offsets . keys ( ) : edges . append ( coord + offset ) # logging.debug('tile_id={}, edges touching={}'.format(tile_id, edges)) return edges
Get a list of edge coordinates touching the given tile .
79
11
7,431
def nodes_touching_tile ( tile_id ) : coord = tile_id_to_coord ( tile_id ) nodes = [ ] for offset in _tile_node_offsets . keys ( ) : nodes . append ( coord + offset ) # logging.debug('tile_id={}, nodes touching={}'.format(tile_id, nodes)) return nodes
Get a list of node coordinates touching the given tile .
79
11
7,432
def nodes_touching_edge ( edge_coord ) : a , b = hex_digit ( edge_coord , 1 ) , hex_digit ( edge_coord , 2 ) if a % 2 == 0 and b % 2 == 0 : return [ coord_from_hex_digits ( a , b + 1 ) , coord_from_hex_digits ( a + 1 , b ) ] else : return [ coord_from_hex_digits ( a , b ) , coord_from_hex_digits ( a + 1 , b + 1 ) ]
Returns the two node coordinates which are on the given edge coordinate .
121
13
7,433
def legal_edge_coords ( ) : edges = set ( ) for tile_id in legal_tile_ids ( ) : for edge in edges_touching_tile ( tile_id ) : edges . add ( edge ) logging . debug ( 'Legal edge coords({})={}' . format ( len ( edges ) , edges ) ) return edges
Return all legal edge coordinates on the grid .
76
9
7,434
def legal_node_coords ( ) : nodes = set ( ) for tile_id in legal_tile_ids ( ) : for node in nodes_touching_tile ( tile_id ) : nodes . add ( node ) logging . debug ( 'Legal node coords({})={}' . format ( len ( nodes ) , nodes ) ) return nodes
Return all legal node coordinates on the grid
76
8
7,435
def make ( parser ) : s = parser . add_subparsers ( title = 'commands' , metavar = 'COMMAND' , help = 'description' , ) def create_manila_db_f ( args ) : create_manila_db ( args ) create_manila_db_parser = create_manila_db_subparser ( s ) create_manila_db_parser . set_defaults ( func = create_manila_db_f ) def create_service_credentials_f ( args ) : create_service_credentials ( args ) create_service_credentials_parser = create_service_credentials_subparser ( s ) create_service_credentials_parser . set_defaults ( func = create_service_credentials_f ) def install_f ( args ) : install ( args ) install_parser = install_subparser ( s ) install_parser . set_defaults ( func = install_f )
provison Manila with HA
221
5
7,436
def assoc ( self , index , value ) : newnode = LookupTreeNode ( index , value ) newtree = LookupTree ( ) newtree . root = _assoc_down ( self . root , newnode , 0 ) return newtree
Return a new tree with value associated at index .
54
10
7,437
def remove ( self , index ) : newtree = LookupTree ( ) newtree . root = _remove_down ( self . root , index , 0 ) return newtree
Return new tree with index removed .
37
7
7,438
def insert ( self , index , value ) : newnode = LookupTreeNode ( index , value ) level = 0 node = self . root while True : ind = _getbits ( newnode . index , level ) level += 1 child = node . children [ ind ] if child is None or child . index == newnode . index : if child : assert child . value == newnode . value node . children [ ind ] = newnode break elif child . index == _root_index : # This is a branch node = child else : branch = LookupTreeNode ( ) nind = _getbits ( newnode . index , level ) cind = _getbits ( child . index , level ) node . children [ ind ] = branch # Life gets tricky when... if nind == cind : branch . children [ cind ] = child # recurse node = branch else : branch . children [ nind ] = newnode branch . children [ cind ] = child break
Insert a node in - place . It is highly suggested that you do not use this method . Use assoc instead
207
23
7,439
def reset ( cls ) : cls . _codecs = { } c = cls . _codec for ( name , encode , decode ) in cls . _common_codec_data : cls . _codecs [ name ] = c ( encode , decode )
Reset the registry to the standard codecs .
62
10
7,440
def register ( cls , name , encode , decode ) : cls . _codecs [ name ] = cls . _codec ( encode , decode )
Add a codec to the registry .
35
7
7,441
def default_formatter ( handler , item , value ) : if hasattr ( value , '__unicode__' ) : value = value . __unicode__ ( ) return escape ( str ( value ) )
Default formatter . Convert value to string .
45
9
7,442
def list_formatter ( handler , item , value ) : return u', ' . join ( str ( v ) for v in value )
Format list .
29
3
7,443
def format_value ( handler , item , column ) : value = getattr ( item , column , None ) formatter = FORMATTERS . get ( type ( value ) , default_formatter ) return formatter ( handler , item , value )
Format value .
52
3
7,444
def make_regex ( string ) : if string and string [ 0 ] in '+-' : sign , name = string [ 0 ] , string [ 1 : ] if not name or '+' in name or '-' in name : raise ValueError ( 'inappropriate feature name: %r' % string ) tmpl = r'([+]?%s)' if sign == '+' else r'(-%s)' return tmpl % name if not string or '+' in string or '-' in string : raise ValueError ( 'inappropriate feature name: %r' % string ) return r'(%s)' % string
Regex string for optionally signed binary or privative feature .
138
12
7,445
def substring_names ( features ) : names = tools . uniqued ( map ( remove_sign , features ) ) for l , r in permutations ( names , 2 ) : if l in r : yield ( l , r )
Yield all feature name pairs in substring relation .
50
11
7,446
def join ( self , featuresets ) : concepts = ( f . concept for f in featuresets ) join = self . lattice . join ( concepts ) return self . _featuresets [ join . index ]
Return the nearest featureset that subsumes all given ones .
43
12
7,447
def meet ( self , featuresets ) : concepts = ( f . concept for f in featuresets ) meet = self . lattice . meet ( concepts ) return self . _featuresets [ meet . index ]
Return the nearest featureset that implies all given ones .
43
11
7,448
def upset_union ( self , featuresets ) : concepts = ( f . concept for f in featuresets ) indexes = ( c . index for c in self . lattice . upset_union ( concepts ) ) return map ( self . _featuresets . __getitem__ , indexes )
Yield all featuresets that subsume any of the given ones .
60
14
7,449
def graphviz ( self , highlight = None , maximal_label = None , topdown = None , filename = None , directory = None , render = False , view = False ) : return visualize . featuresystem ( self , highlight , maximal_label , topdown , filename , directory , render , view )
Return the system lattice visualization as graphviz source .
64
12
7,450
def soap_action ( self , service , action , payloadbody ) : payload = self . soapenvelope . format ( body = payloadbody ) . encode ( 'utf-8' ) headers = { "Host" : self . url , "Content-Type" : "text/xml; charset=UTF-8" , "Cache-Control" : "no-cache" , "Content-Length" : str ( len ( payload ) ) , "SOAPAction" : action } try : self . last_exception = None response = requests . post ( url = self . url + service , headers = headers , data = payload , cookies = self . cookies ) except requests . exceptions . RequestException as exp : self . last_exception = exp return False if response . status_code != 200 : self . last_response = response return False self . cookies = response . cookies try : xdoc = xml . etree . ElementTree . fromstring ( response . text ) except xml . etree . ElementTree . ParseError as exp : self . last_exception = exp self . last_response = response return False return xdoc
Do a soap request .
242
5
7,451
def getValidReff ( self , level = 1 , reference = None ) : if reference : urn = "{0}:{1}" . format ( self . urn , reference ) else : urn = str ( self . urn ) if level == - 1 : level = len ( self . citation ) xml = self . retriever . getValidReff ( level = level , urn = urn ) xml = xmlparser ( xml ) self . _parse_request ( xml . xpath ( "//ti:request" , namespaces = XPATH_NAMESPACES ) [ 0 ] ) return [ ref . split ( ":" ) [ - 1 ] for ref in xml . xpath ( "//ti:reply//ti:urn/text()" , namespaces = XPATH_NAMESPACES ) ]
Given a resource CtsText will compute valid reffs
175
12
7,452
def getTextualNode ( self , subreference = None ) : if isinstance ( subreference , URN ) : urn = str ( subreference ) elif isinstance ( subreference , CtsReference ) : urn = "{0}:{1}" . format ( self . urn , str ( subreference ) ) elif isinstance ( subreference , str ) : if ":" in subreference : urn = subreference else : urn = "{0}:{1}" . format ( self . urn . upTo ( URN . NO_PASSAGE ) , subreference ) elif isinstance ( subreference , list ) : urn = "{0}:{1}" . format ( self . urn , "." . join ( subreference ) ) else : urn = str ( self . urn ) response = xmlparser ( self . retriever . getPassage ( urn = urn ) ) self . _parse_request ( response . xpath ( "//ti:request" , namespaces = XPATH_NAMESPACES ) [ 0 ] ) return CtsPassage ( urn = urn , resource = response , retriever = self . retriever )
Retrieve a passage and store it in the object
256
10
7,453
def getPassagePlus ( self , reference = None ) : if reference : urn = "{0}:{1}" . format ( self . urn , reference ) else : urn = str ( self . urn ) response = xmlparser ( self . retriever . getPassagePlus ( urn = urn ) ) passage = CtsPassage ( urn = urn , resource = response , retriever = self . retriever ) passage . _parse_request ( response . xpath ( "//ti:reply/ti:label" , namespaces = XPATH_NAMESPACES ) [ 0 ] ) self . citation = passage . citation return passage
Retrieve a passage and informations around it and store it in the object
141
15
7,454
def _parse_request ( self , xml ) : for node in xml . xpath ( ".//ti:groupname" , namespaces = XPATH_NAMESPACES ) : lang = node . get ( "xml:lang" ) or CtsText . DEFAULT_LANG self . metadata . add ( RDF_NAMESPACES . CTS . groupname , lang = lang , value = node . text ) self . set_creator ( node . text , lang ) for node in xml . xpath ( ".//ti:title" , namespaces = XPATH_NAMESPACES ) : lang = node . get ( "xml:lang" ) or CtsText . DEFAULT_LANG self . metadata . add ( RDF_NAMESPACES . CTS . title , lang = lang , value = node . text ) self . set_title ( node . text , lang ) for node in xml . xpath ( ".//ti:label" , namespaces = XPATH_NAMESPACES ) : lang = node . get ( "xml:lang" ) or CtsText . DEFAULT_LANG self . metadata . add ( RDF_NAMESPACES . CTS . label , lang = lang , value = node . text ) self . set_subject ( node . text , lang ) for node in xml . xpath ( ".//ti:description" , namespaces = XPATH_NAMESPACES ) : lang = node . get ( "xml:lang" ) or CtsText . DEFAULT_LANG self . metadata . add ( RDF_NAMESPACES . CTS . description , lang = lang , value = node . text ) self . set_description ( node . text , lang ) # Need to code that p if not self . citation . is_set ( ) and xml . xpath ( "//ti:citation" , namespaces = XPATH_NAMESPACES ) : self . citation = CtsCollection . XmlCtsCitation . ingest ( xml , xpath = ".//ti:citation[not(ancestor::ti:citation)]" )
Parse a request with metadata information
458
7
7,455
def getLabel ( self ) : response = xmlparser ( self . retriever . getLabel ( urn = str ( self . urn ) ) ) self . _parse_request ( response . xpath ( "//ti:reply/ti:label" , namespaces = XPATH_NAMESPACES ) [ 0 ] ) return self . metadata
Retrieve metadata about the text
74
6
7,456
def getPrevNextUrn ( self , reference ) : _prev , _next = _SharedMethod . prevnext ( self . retriever . getPrevNextUrn ( urn = "{}:{}" . format ( str ( URN ( str ( self . urn ) ) . upTo ( URN . NO_PASSAGE ) ) , str ( reference ) ) ) ) return _prev , _next
Get the previous URN of a reference of the text
89
11
7,457
def getFirstUrn ( self , reference = None ) : if reference is not None : if ":" in reference : urn = reference else : urn = "{}:{}" . format ( str ( URN ( str ( self . urn ) ) . upTo ( URN . NO_PASSAGE ) ) , str ( reference ) ) else : urn = str ( self . urn ) _first = _SharedMethod . firstUrn ( self . retriever . getFirstUrn ( urn ) ) return _first
Get the first children URN for a given resource
116
10
7,458
def firstUrn ( resource ) : resource = xmlparser ( resource ) urn = resource . xpath ( "//ti:reply/ti:urn/text()" , namespaces = XPATH_NAMESPACES , magic_string = True ) if len ( urn ) > 0 : urn = str ( urn [ 0 ] ) return urn . split ( ":" ) [ - 1 ]
Parse a resource to get the first URN
87
10
7,459
def prevnext ( resource ) : _prev , _next = False , False resource = xmlparser ( resource ) prevnext = resource . xpath ( "//ti:prevnext" , namespaces = XPATH_NAMESPACES ) if len ( prevnext ) > 0 : _next , _prev = None , None prevnext = prevnext [ 0 ] _next_xpath = prevnext . xpath ( "ti:next/ti:urn/text()" , namespaces = XPATH_NAMESPACES , smart_strings = False ) _prev_xpath = prevnext . xpath ( "ti:prev/ti:urn/text()" , namespaces = XPATH_NAMESPACES , smart_strings = False ) if len ( _next_xpath ) : _next = _next_xpath [ 0 ] . split ( ":" ) [ - 1 ] if len ( _prev_xpath ) : _prev = _prev_xpath [ 0 ] . split ( ":" ) [ - 1 ] return _prev , _next
Parse a resource to get the prev and next urn
228
12
7,460
def prevId ( self ) : if self . _prev_id is False : # Request the next urn self . _prev_id , self . _next_id = self . getPrevNextUrn ( reference = self . urn . reference ) return self . _prev_id
Previous passage Identifier
61
4
7,461
def nextId ( self ) : if self . _next_id is False : # Request the next urn self . _prev_id , self . _next_id = self . getPrevNextUrn ( reference = self . urn . reference ) return self . _next_id
Shortcut for getting the following passage identifier
61
8
7,462
def siblingsId ( self ) : if self . _next_id is False or self . _prev_id is False : self . _prev_id , self . _next_id = self . getPrevNextUrn ( reference = self . urn . reference ) return self . _prev_id , self . _next_id
Shortcut for getting the previous and next passage identifier
71
10
7,463
def _parse ( self ) : self . response = self . resource self . resource = self . resource . xpath ( "//ti:passage/tei:TEI" , namespaces = XPATH_NAMESPACES ) [ 0 ] self . _prev_id , self . _next_id = _SharedMethod . prevnext ( self . response ) if not self . citation . is_set ( ) and len ( self . resource . xpath ( "//ti:citation" , namespaces = XPATH_NAMESPACES ) ) : self . citation = CtsCollection . XmlCtsCitation . ingest ( self . response , xpath = ".//ti:citation[not(ancestor::ti:citation)]" )
Given self . resource split information from the CTS API
165
11
7,464
def get_user_token ( self ) : headers = { 'User-Agent' : self . user_agent ( ) , 'Host' : self . domain ( ) , 'Accept' : '*/*' , } headers . update ( self . headers ( ) ) r = requests . get ( self . portals_url ( ) + '/users/_this/token' , headers = headers , auth = self . auth ( ) ) if HTTP_STATUS . OK == r . status_code : return r . text else : print ( "get_user_token: Something went wrong: <{0}>: {1}" . format ( r . status_code , r . reason ) ) r . raise_for_status ( )
Gets a authorization token for session reuse .
155
9
7,465
def add_device ( self , model , serial ) : device = { 'model' : model , 'vendor' : self . vendor ( ) , 'sn' : serial , 'type' : 'vendor' } headers = { 'User-Agent' : self . user_agent ( ) , } headers . update ( self . headers ( ) ) r = requests . post ( self . portals_url ( ) + '/portals/' + self . portal_id ( ) + '/devices' , data = json . dumps ( device ) , headers = headers , auth = self . auth ( ) ) if HTTP_STATUS . ADDED == r . status_code : # fix the 'meta' to be dictionary instead of string device_obj = r . json ( ) return dictify_device_meta ( device_obj ) else : print ( "add_device: Something went wrong: <{0}>: {1}" . format ( r . status_code , r . reason ) ) r . raise_for_status ( )
Returns device object of newly created device .
220
8
7,466
def update_portal ( self , portal_obj ) : headers = { 'User-Agent' : self . user_agent ( ) , } headers . update ( self . headers ( ) ) r = requests . put ( self . portals_url ( ) + '/portals/' + self . portal_id ( ) , data = json . dumps ( portal_obj ) , headers = headers , auth = self . auth ( ) ) if HTTP_STATUS . OK == r . status_code : return r . json ( ) else : print ( "update_portal: Something went wrong: <{0}>: {1}" . format ( r . status_code , r . reason ) ) r . raise_for_status ( )
Implements the Update device Portals API .
157
10
7,467
def get_device ( self , rid ) : headers = { 'User-Agent' : self . user_agent ( ) , 'Content-Type' : self . content_type ( ) } headers . update ( self . headers ( ) ) url = self . portals_url ( ) + '/devices/' + rid # print("URL: {0}".format(url)) r = requests . get ( url , headers = headers , auth = self . auth ( ) ) if HTTP_STATUS . OK == r . status_code : # fix the 'meta' to be dictionary instead of string device_obj = r . json ( ) # device_obj['info']['description']['meta'] = \ # json.loads(device_obj['info']['description']['meta']) return device_obj else : print ( "get_device: Something went wrong: <{0}>: {1}" . format ( r . status_code , r . reason ) ) r . raise_for_status ( )
Retrieve the device object for a given RID .
220
11
7,468
def get_multiple_devices ( self , rids ) : headers = { 'User-Agent' : self . user_agent ( ) , 'Content-Type' : self . content_type ( ) } headers . update ( self . headers ( ) ) url = self . portals_url ( ) + '/users/_this/devices/' + str ( rids ) . replace ( "'" , "" ) . replace ( ' ' , '' ) # print("URL: {0}".format(url)) r = requests . get ( url , headers = headers , auth = self . auth ( ) ) if HTTP_STATUS . OK == r . status_code : # TODO: loop through all rids and fix 'meta' to be dict like add_device and get_device do return r . json ( ) else : print ( "get_multiple_devices: Something went wrong: <{0}>: {1}" . format ( r . status_code , r . reason ) ) r . raise_for_status ( )
Implements the Get Multiple Devices API .
219
9
7,469
def dorogokupets2015_pth ( v , temp , v0 , gamma0 , gamma_inf , beta , theta01 , m1 , theta02 , m2 , n , z , t_ref = 300. , three_r = 3. * constants . R ) : # x = v / v0 # a = a0 * np.power(x, m) v_mol = vol_uc2mol ( v , z ) gamma = altshuler_grun ( v , v0 , gamma0 , gamma_inf , beta ) theta1 = altshuler_debyetemp ( v , v0 , gamma0 , gamma_inf , beta , theta01 ) theta2 = altshuler_debyetemp ( v , v0 , gamma0 , gamma_inf , beta , theta02 ) if isuncertainties ( [ v , temp , v0 , gamma0 , gamma_inf , beta , theta01 , m1 , theta02 , m2 ] ) : term_h1 = m1 / ( m1 + m2 ) * three_r * n * gamma / v_mol * ( theta1 / ( unp . exp ( theta1 / temp ) - 1. ) ) term_h2 = m2 / ( m1 + m2 ) * three_r * n * gamma / v_mol * ( theta2 / ( unp . exp ( theta2 / temp ) - 1. ) ) term_h1_ref = m1 / ( m1 + m2 ) * three_r * n * gamma / v_mol * ( theta1 / ( unp . exp ( theta1 / t_ref ) - 1. ) ) term_h2_ref = m2 / ( m1 + m2 ) * three_r * n * gamma / v_mol * ( theta2 / ( unp . exp ( theta2 / t_ref ) - 1. ) ) else : term_h1 = m1 / ( m1 + m2 ) * three_r * n * gamma / v_mol * ( theta1 / ( np . exp ( theta1 / temp ) - 1. ) ) term_h2 = m2 / ( m1 + m2 ) * three_r * n * gamma / v_mol * ( theta2 / ( np . exp ( theta2 / temp ) - 1. ) ) term_h1_ref = m1 / ( m1 + m2 ) * three_r * n * gamma / v_mol * ( theta1 / ( np . exp ( theta1 / t_ref ) - 1. ) ) term_h2_ref = m2 / ( m1 + m2 ) * three_r * n * gamma / v_mol * ( theta2 / ( np . exp ( theta2 / t_ref ) - 1. ) ) p_th = term_h1 * 1.e-9 + term_h2 * 1.e-9 p_th_ref = term_h1_ref * 1.e-9 + term_h2_ref * 1.e-9 return ( p_th - p_th_ref )
calculate thermal pressure for Dorogokupets 2015 EOS
705
14
7,470
def routes ( self ) : if self . _routes : return self . _routes request = requests . get ( self . endpoint ) request . raise_for_status ( ) data = request . json ( ) self . _routes = { "collections" : parse_uri ( data [ "collections" ] , self . endpoint ) , "documents" : parse_uri ( data [ "documents" ] , self . endpoint ) , "navigation" : parse_uri ( data [ "navigation" ] , self . endpoint ) } return self . _routes
Retrieves the main routes of the DTS Collection
128
11
7,471
def get_collection ( self , collection_id = None , nav = "children" , page = None ) : return self . call ( "collections" , { "id" : collection_id , "nav" : nav , "page" : page } , defaults = { "id" : None , "nav" : "children" , "page" : 1 } )
Makes a call on the Collection API
80
8
7,472
def _create_glance_db ( self , root_db_pass , glance_db_pass ) : print red ( env . host_string + ' | Create glance database' ) sudo ( "mysql -uroot -p{0} -e \"CREATE DATABASE glance;\"" . format ( root_db_pass ) , shell = False ) sudo ( "mysql -uroot -p{0} -e \"GRANT ALL PRIVILEGES ON glance.* TO 'glance'@'localhost' IDENTIFIED BY '{1}';\"" . format ( root_db_pass , glance_db_pass ) , shell = False ) sudo ( "mysql -uroot -p{0} -e \"GRANT ALL PRIVILEGES ON glance.* TO 'glance'@'%' IDENTIFIED BY '{1}';\"" . format ( root_db_pass , glance_db_pass ) , shell = False )
Create the glance database
212
4
7,473
def chain ( self , token : 'CancelToken' ) -> 'CancelToken' : if self . loop != token . _loop : raise EventLoopMismatch ( "Chained CancelToken objects must be on the same event loop" ) chain_name = ":" . join ( [ self . name , token . name ] ) chain = CancelToken ( chain_name , loop = self . loop ) chain . _chain . extend ( [ self , token ] ) return chain
Return a new CancelToken chaining this and the given token .
101
13
7,474
def triggered_token ( self ) -> 'CancelToken' : if self . _triggered . is_set ( ) : return self for token in self . _chain : if token . triggered : # Use token.triggered_token here to make the lookup recursive as self._chain may # contain other chains. return token . triggered_token return None
Return the token which was triggered .
76
7
7,475
def triggered ( self ) -> bool : if self . _triggered . is_set ( ) : return True return any ( token . triggered for token in self . _chain )
Return True or False whether this token has been triggered .
38
11
7,476
async def wait ( self ) -> None : if self . triggered_token is not None : return futures = [ asyncio . ensure_future ( self . _triggered . wait ( ) , loop = self . loop ) ] for token in self . _chain : futures . append ( asyncio . ensure_future ( token . wait ( ) , loop = self . loop ) ) def cancel_not_done ( fut : 'asyncio.Future[None]' ) -> None : for future in futures : if not future . done ( ) : future . cancel ( ) async def _wait_for_first ( futures : Sequence [ Awaitable [ Any ] ] ) -> None : for future in asyncio . as_completed ( futures ) : # We don't need to catch CancelledError here (and cancel not done futures) # because our callback (above) takes care of that. await cast ( Awaitable [ Any ] , future ) return fut = asyncio . ensure_future ( _wait_for_first ( futures ) , loop = self . loop ) fut . add_done_callback ( cancel_not_done ) await fut
Coroutine which returns when this token has been triggered
243
10
7,477
async def cancellable_wait ( self , * awaitables : Awaitable [ _R ] , timeout : float = None ) -> _R : futures = [ asyncio . ensure_future ( a , loop = self . loop ) for a in awaitables + ( self . wait ( ) , ) ] try : done , pending = await asyncio . wait ( futures , timeout = timeout , return_when = asyncio . FIRST_COMPLETED , loop = self . loop , ) except asyncio . futures . CancelledError : # Since we use return_when=asyncio.FIRST_COMPLETED above, we can be sure none of our # futures will be done here, so we don't need to check if any is done before cancelling. for future in futures : future . cancel ( ) raise for task in pending : task . cancel ( ) if not done : raise TimeoutError ( ) if self . triggered_token is not None : # We've been asked to cancel so we don't care about our future, but we must # consume its exception or else asyncio will emit warnings. for task in done : task . exception ( ) raise OperationCancelled ( "Cancellation requested by {} token" . format ( self . triggered_token ) ) return done . pop ( ) . result ( )
Wait for the first awaitable to complete unless we timeout or the token is triggered .
278
17
7,478
def parent ( self ) -> Optional [ 'CtsReference' ] : if self . start . depth == 1 and ( self . end is None or self . end . depth <= 1 ) : return None else : if self . start . depth > 1 and ( self . end is None or self . end . depth == 0 ) : return CtsReference ( "{0}{1}" . format ( "." . join ( self . start . list [ : - 1 ] ) , self . start . subreference or "" ) ) elif self . start . depth > 1 and self . end is not None and self . end . depth > 1 : _start = self . start . list [ 0 : - 1 ] _end = self . end . list [ 0 : - 1 ] if _start == _end and self . start . subreference is None and self . end . subreference is None : return CtsReference ( "." . join ( _start ) ) else : return CtsReference ( "{0}{1}-{2}{3}" . format ( "." . join ( _start ) , self . start . subreference or "" , "." . join ( _end ) , self . end . subreference or "" ) )
Parent of the actual URN for example 1 . 1 for 1 . 1 . 1
259
17
7,479
def highest ( self ) -> CtsSinglePassageId : if not self . end : return self . start elif len ( self . start ) < len ( self . end ) and len ( self . start ) : return self . start elif len ( self . start ) > len ( self . end ) and len ( self . end ) : return self . end elif len ( self . start ) : return self . start
Return highest reference level
90
4
7,480
def upTo ( self , key ) : middle = [ component for component in [ self . __parsed [ "textgroup" ] , self . __parsed [ "work" ] , self . __parsed [ "version" ] ] if component is not None ] if key == URN . COMPLETE : return self . __str__ ( ) elif key == URN . NAMESPACE : return ":" . join ( [ "urn" , self . __parsed [ "urn_namespace" ] , self . __parsed [ "cts_namespace" ] ] ) elif key == URN . TEXTGROUP and self . __parsed [ "textgroup" ] : return ":" . join ( [ "urn" , self . __parsed [ "urn_namespace" ] , self . __parsed [ "cts_namespace" ] , self . __parsed [ "textgroup" ] ] ) elif key == URN . WORK and self . __parsed [ "work" ] : return ":" . join ( [ "urn" , self . __parsed [ "urn_namespace" ] , self . __parsed [ "cts_namespace" ] , "." . join ( [ self . __parsed [ "textgroup" ] , self . __parsed [ "work" ] ] ) ] ) elif key == URN . VERSION and self . __parsed [ "version" ] : return ":" . join ( [ "urn" , self . __parsed [ "urn_namespace" ] , self . __parsed [ "cts_namespace" ] , "." . join ( middle ) ] ) elif key == URN . NO_PASSAGE and self . __parsed [ "work" ] : return ":" . join ( [ "urn" , self . __parsed [ "urn_namespace" ] , self . __parsed [ "cts_namespace" ] , "." . join ( middle ) ] ) elif key == URN . PASSAGE and self . __parsed [ "reference" ] : return ":" . join ( [ "urn" , self . __parsed [ "urn_namespace" ] , self . __parsed [ "cts_namespace" ] , "." . join ( middle ) , str ( self . reference ) ] ) elif key == URN . PASSAGE_START and self . __parsed [ "reference" ] : return ":" . join ( [ "urn" , self . __parsed [ "urn_namespace" ] , self . __parsed [ "cts_namespace" ] , "." . join ( middle ) , str ( self . reference . start ) ] ) elif key == URN . PASSAGE_END and self . __parsed [ "reference" ] and self . reference . end is not None : return ":" . join ( [ "urn" , self . __parsed [ "urn_namespace" ] , self . __parsed [ "cts_namespace" ] , "." . join ( middle ) , str ( self . reference . end ) ] ) else : raise KeyError ( "Provided key is not recognized." )
Returns the urn up to given level using URN Constants
737
13
7,481
def attribute ( self ) : refs = re . findall ( "\@([a-zA-Z:]+)=\\\?[\'\"]\$" + str ( self . refsDecl . count ( "$" ) ) + "\\\?[\'\"]" , self . refsDecl ) return refs [ - 1 ]
Attribute that serves as a reference getter
74
8
7,482
def match ( self , passageId ) : if not isinstance ( passageId , CtsReference ) : passageId = CtsReference ( passageId ) if self . is_root ( ) : return self [ passageId . depth - 1 ] return self . root . match ( passageId )
Given a passageId matches a citation level
61
8
7,483
def fill ( self , passage = None , xpath = None ) : if xpath is True : # Then passage is a string or None xpath = self . xpath replacement = r"\1" if isinstance ( passage , str ) : replacement = r"\1\2'" + passage + "'" return REFERENCE_REPLACER . sub ( replacement , xpath ) else : if isinstance ( passage , CtsReference ) : passage = passage . start . list elif passage is None : return REFERENCE_REPLACER . sub ( r"\1" , self . refsDecl ) passage = iter ( passage ) return REFERENCE_REPLACER . sub ( lambda m : _ref_replacer ( m , passage ) , self . refsDecl )
Fill the xpath with given informations
171
8
7,484
def ingest ( resource , xpath = ".//tei:cRefPattern" ) : if len ( resource ) == 0 and isinstance ( resource , list ) : return None elif isinstance ( resource , list ) : resource = resource [ 0 ] elif not isinstance ( resource , _Element ) : return None resource = resource . xpath ( xpath , namespaces = XPATH_NAMESPACES ) citations = [ ] for x in range ( 0 , len ( resource ) ) : citations . append ( Citation ( name = resource [ x ] . get ( "n" ) , refsDecl = resource [ x ] . get ( "replacementPattern" ) [ 7 : - 1 ] , child = _child_or_none ( citations ) ) ) if len ( citations ) > 1 : for citation in citations [ : - 1 ] : citation . root = citations [ - 1 ] return citations [ - 1 ]
Ingest a resource and store data in its instance
195
10
7,485
def get_tweets_count_times ( twitter , count , query = None ) : # get id to start from oldest_id , newest_id = _get_oldest_id ( query = query ) newest_id = newest_id or oldest_id all_tweets = [ ] i = 0 while i < count : i += 1 # use search api to request 100 tweets. Twitter returns the most recent (max_id) first if oldest_id <= newest_id : tweets = get_tweets ( query = query , max_id = oldest_id - 1 , count = TWEETS_PER_SEARCH , twitter = twitter ) else : tweets = get_tweets ( query = query , max_id = oldest_id - 1 , since_id = newest_id , count = TWEETS_PER_SEARCH , twitter = twitter ) rate_limit_remaining = twitter . get_lastfunction_header ( 'x-rate-limit-remaining' ) rate_limit_reset = twitter . get_lastfunction_header ( 'x-rate-limit-reset' ) if not len ( tweets ) : # not rate limitted, just no tweets returned by query oldest_id = oldest_id + ( ( newest_id or oldest_id ) - oldest_id + 1 ) * 10000 break elif isinstance ( tweets , dict ) : # rate limit hit, or other twython response error print ( tweets ) break all_tweets . extend ( tweets ) # determine new oldest id tweet_ids = { t [ 'id' ] for t in tweets } if oldest_id : tweet_ids . add ( oldest_id ) oldest_id , newest_id = min ( tweet_ids ) , max ( tweet_ids ) if rate_limit_remaining == 1 : time . sleep ( rate_limit_reset - time . time ( ) ) save_tweets ( all_tweets , query = query ) # set id to start from for next time _set_oldest_id ( oldest_id , newest_id , query = query ) if len ( all_tweets ) == 0 : os . remove ( make_oldest_id_path ( query ) ) return len ( all_tweets ) , twitter . get_lastfunction_header ( 'x-rate-limit-remaining' )
r hits the twitter api count times and grabs tweets for the indicated query
510
14
7,486
def parse ( self , * * kwargs ) : try : output_folder = self . retrieved except exceptions . NotExistent : return self . exit_codes . ERROR_NO_RETRIEVED_FOLDER filename_stdout = self . node . get_attribute ( 'output_filename' ) filename_stderr = self . node . get_attribute ( 'error_filename' ) try : with output_folder . open ( filename_stderr , 'r' ) as handle : exit_code = self . parse_stderr ( handle ) except ( OSError , IOError ) : self . logger . exception ( 'Failed to read the stderr file\n%s' , traceback . format_exc ( ) ) return self . exit_codes . ERROR_READING_ERROR_FILE if exit_code : return exit_code try : with output_folder . open ( filename_stdout , 'r' ) as handle : handle . seek ( 0 ) exit_code = self . parse_stdout ( handle ) except ( OSError , IOError ) : self . logger . exception ( 'Failed to read the stdout file\n%s' , traceback . format_exc ( ) ) return self . exit_codes . ERROR_READING_OUTPUT_FILE if exit_code : return exit_code
Parse the contents of the output files retrieved in the FolderData .
296
14
7,487
def parse_stdout ( self , filelike ) : from CifFile import StarError if not filelike . read ( ) . strip ( ) : return self . exit_codes . ERROR_EMPTY_OUTPUT_FILE try : filelike . seek ( 0 ) cif = CifData ( file = filelike ) except StarError : self . logger . exception ( 'Failed to parse a `CifData` from the stdout file\n%s' , traceback . format_exc ( ) ) return self . exit_codes . ERROR_PARSING_CIF_DATA else : self . out ( 'cif' , cif ) return
Parse the content written by the script to standard out into a CifData object .
143
18
7,488
def parse_stderr ( self , filelike ) : marker_error = 'ERROR,' marker_warning = 'WARNING,' messages = { 'errors' : [ ] , 'warnings' : [ ] } for line in filelike . readlines ( ) : if marker_error in line : messages [ 'errors' ] . append ( line . split ( marker_error ) [ - 1 ] . strip ( ) ) if marker_warning in line : messages [ 'warnings' ] . append ( line . split ( marker_warning ) [ - 1 ] . strip ( ) ) if self . node . get_option ( 'attach_messages' ) : self . out ( 'messages' , Dict ( dict = messages ) ) for error in messages [ 'errors' ] : if 'unknown option' in error : return self . exit_codes . ERROR_INVALID_COMMAND_LINE_OPTION return
Parse the content written by the script to standard err .
197
12
7,489
def reset ( cls ) : # Maps function names (hyphens or underscores) to registered functions. cls . _func_from_name = { } # Maps hashlib names to registered functions. cls . _func_from_hash = { } # Hashlib compatibility data by function. cls . _func_hash = { } register = cls . _do_register for ( func , hash_name , hash_new ) in cls . _std_func_data : register ( func , func . name , hash_name , hash_new ) assert set ( cls . _func_hash ) == set ( Func )
Reset the registry to the standard multihash functions .
137
12
7,490
def get ( cls , func_hint ) : # Different possibilities of `func_hint`, most to least probable. try : # `Func` member (or its value) return Func ( func_hint ) except ValueError : pass if func_hint in cls . _func_from_name : # `Func` member name, extended return cls . _func_from_name [ func_hint ] if func_hint in cls . _func_hash : # registered app-specific code return func_hint raise KeyError ( "unknown hash function" , func_hint )
Return a registered hash function matching the given hint .
135
10
7,491
def _do_register ( cls , code , name , hash_name = None , hash_new = None ) : cls . _func_from_name [ name . replace ( '-' , '_' ) ] = code cls . _func_from_name [ name . replace ( '_' , '-' ) ] = code if hash_name : cls . _func_from_hash [ hash_name ] = code cls . _func_hash [ code ] = cls . _hash ( hash_name , hash_new )
Add hash function data to the registry without checks .
120
10
7,492
def register ( cls , code , name , hash_name = None , hash_new = None ) : if not _is_app_specific_func ( code ) : raise ValueError ( "only application-specific functions can be registered" ) # Check already registered name in different mappings. name_mapping_data = [ # (mapping, name in mapping, error if existing) ( cls . _func_from_name , name , "function name is already registered for a different function" ) , ( cls . _func_from_hash , hash_name , "hashlib name is already registered for a different function" ) ] for ( mapping , nameinmap , errmsg ) in name_mapping_data : existing_func = mapping . get ( nameinmap , code ) if existing_func != code : raise ValueError ( errmsg , existing_func ) # Unregister if existing to ensure no orphan entries. if code in cls . _func_hash : cls . unregister ( code ) # Proceed to registration. cls . _do_register ( code , name , hash_name , hash_new )
Add an application - specific function to the registry .
244
10
7,493
def unregister ( cls , code ) : if code in Func : raise ValueError ( "only application-specific functions can be unregistered" ) # Remove mapping to function by name. func_names = { n for ( n , f ) in cls . _func_from_name . items ( ) if f == code } for func_name in func_names : del cls . _func_from_name [ func_name ] # Remove hashlib data and mapping to hash. hash = cls . _func_hash . pop ( code ) if hash . name : del cls . _func_from_hash [ hash . name ]
Remove an application - specific function from the registry .
139
10
7,494
def hash_from_func ( cls , func ) : new = cls . _func_hash [ func ] . new return new ( ) if new else None
Return a hashlib - compatible object for the multihash func .
35
14
7,495
def thermal_data ( data , figsize = ( 12 , 4 ) , ms_data = 50 , v_label = 'Unit-cell volume $(\mathrm{\AA}^3)$' , pdf_filen = None , title = 'P-V-T data' ) : # basic figure setup f , ax = plt . subplots ( 1 , 2 , figsize = figsize , sharex = True ) # read data to plot if isuncertainties ( [ data [ 'p' ] , data [ 'v' ] , data [ 'temp' ] ] ) : p = unp . nominal_values ( data [ 'p' ] ) v = unp . nominal_values ( data [ 'v' ] ) temp = unp . nominal_values ( data [ 'temp' ] ) sp = unp . std_devs ( data [ 'p' ] ) sv = unp . std_devs ( data [ 'v' ] ) stemp = unp . std_devs ( data [ 'temp' ] ) ax [ 0 ] . errorbar ( p , v , xerr = sp , yerr = sv , marker = ' ' , c = 'k' , ms = 0 , mew = 0 , linestyle = 'None' , capsize = 0 , lw = 0.5 , zorder = 1 ) ax [ 1 ] . errorbar ( p , temp , xerr = sp , yerr = stemp , marker = ' ' , c = 'k' , ms = 0 , mew = 0 , linestyle = 'None' , capsize = 0 , lw = 0.5 , zorder = 1 ) else : p = data [ 'p' ] v = data [ 'v' ] temp = data [ 'temp' ] points = ax [ 0 ] . scatter ( p , v , marker = 'o' , s = ms_data , c = temp , cmap = c_map , vmin = 300. , vmax = temp . max ( ) , zorder = 2 ) points = ax [ 1 ] . scatter ( p , temp , marker = 'o' , s = ms_data , c = temp , cmap = c_map , vmin = 300. , vmax = temp . max ( ) , zorder = 2 ) ax [ 0 ] . set_xlabel ( 'Pressure (GPa)' ) ax [ 1 ] . set_xlabel ( 'Pressure (GPa)' ) ax [ 0 ] . set_ylabel ( v_label ) ax [ 1 ] . set_ylabel ( 'Temperature (K)' ) f . suptitle ( title ) # the parameters are the specified position you set position = f . add_axes ( [ 0.92 , 0.11 , .01 , 0.75 ] ) f . colorbar ( points , orientation = "vertical" , cax = position ) # position.text(150., 0.5, 'Temperature (K)', fontsize=10, # rotation=270, va='center') if pdf_filen is not None : f . savefig ( pdf_filen )
plot P - V - T data before fitting
671
9
7,496
def _do_digest ( data , func ) : func = FuncReg . get ( func ) hash = FuncReg . hash_from_func ( func ) if not hash : raise ValueError ( "no available hash function for hash" , func ) hash . update ( data ) return bytes ( hash . digest ( ) )
Return the binary digest of data with the given func .
70
11
7,497
def digest ( data , func ) : digest = _do_digest ( data , func ) return Multihash ( func , digest )
Hash the given data into a new Multihash .
29
11
7,498
def decode ( mhash , encoding = None ) : mhash = bytes ( mhash ) if encoding : mhash = CodecReg . get_decoder ( encoding ) ( mhash ) try : func = mhash [ 0 ] length = mhash [ 1 ] digest = mhash [ 2 : ] except IndexError as ie : raise ValueError ( "multihash is too short" ) from ie if length != len ( digest ) : raise ValueError ( "multihash length field does not match digest field length" ) return Multihash ( func , digest )
r Decode a multihash - encoded digest into a Multihash .
119
16
7,499
def from_hash ( self , hash ) : try : func = FuncReg . func_from_hash ( hash ) except KeyError as ke : raise ValueError ( "no matching multihash function" , hash . name ) from ke digest = hash . digest ( ) return Multihash ( func , digest )
Create a Multihash from a hashlib - compatible hash object .
67
14