idx
int64
0
251k
question
stringlengths
53
3.53k
target
stringlengths
5
1.23k
len_question
int64
20
893
len_target
int64
3
238
3,900
def rebin_scale ( a , scale = 1 ) : newshape = tuple ( ( side * scale ) for side in a . shape ) return rebin ( a , newshape )
Scale an array to a new shape .
39
8
3,901
def rebin ( a , newshape ) : slices = [ slice ( 0 , old , float ( old ) / new ) for old , new in zip ( a . shape , newshape ) ] coordinates = numpy . mgrid [ slices ] # choose the biggest smaller integer index indices = coordinates . astype ( 'i' ) return a [ tuple ( indices ) ]
Rebin an array to a new shape .
77
9
3,902
def fixpix ( data , mask , kind = 'linear' ) : if data . shape != mask . shape : raise ValueError if not numpy . any ( mask ) : return data x = numpy . arange ( 0 , data . shape [ 0 ] ) for row , mrow in zip ( data , mask ) : if numpy . any ( mrow ) : # Interpolate if there's some pixel missing valid = ( mrow == numpy ...
Interpolate 2D array data in rows
164
9
3,903
def fixpix2 ( data , mask , iterations = 3 , out = None ) : out = out if out is not None else data . copy ( ) # A binary mask, regions are ones binry = mask != 0 # Label regions in the binary mask lblarr , labl = ndimage . label ( binry ) # Structure for dilation is 8-way stct = ndimage . generate_binary_structure ( 2 ...
Substitute pixels in mask by a bilinear least square fitting .
336
15
3,904
def numberarray ( x , shape ) : try : iter ( x ) except TypeError : return numpy . ones ( shape ) * x else : return x
Return x if it is an array or create an array and fill it with x .
33
17
3,905
def get_token ( request ) : if ( not request . META . get ( header_name_to_django ( auth_token_settings . HEADER_NAME ) ) and config . CHAMBER_MULTIDOMAINS_OVERTAKER_AUTH_COOKIE_NAME ) : ovetaker_auth_token = request . COOKIES . get ( config . CHAMBER_MULTIDOMAINS_OVERTAKER_AUTH_COOKIE_NAME ) token = get_object_or_none...
Returns the token model instance associated with the given request token key . If no user is retrieved AnonymousToken is returned .
171
23
3,906
def process_request ( self , request ) : request . token = get_token ( request ) request . user = SimpleLazyObject ( lambda : get_user ( request ) ) request . _dont_enforce_csrf_checks = dont_enforce_csrf_checks ( request )
Lazy set user and token
64
6
3,907
def ximplotxy_jupyter ( x , y , fmt = None , * * args ) : using_jupyter = True if fmt is None : return ximplotxy ( x , y , using_jupyter = using_jupyter , * * args ) else : return ximplotxy ( x , y , fmt , using_jupyter = using_jupyter , * * args )
Auxiliary function to call ximplotxy from a jupyter notebook .
97
18
3,908
def atomic ( func ) : try : from reversion . revisions import create_revision return transaction . atomic ( create_revision ( ) ( func ) ) except ImportError : return transaction . atomic ( func )
Decorator helper that overrides django atomic decorator and automatically adds create revision .
44
18
3,909
def atomic_with_signals ( func ) : try : from reversion . revisions import create_revision return transaction . atomic ( create_revision ( ) ( transaction_signals ( func ) ) ) except ImportError : return transaction . atomic ( transaction_signals ( func ) )
Atomic decorator with transaction signals .
61
8
3,910
def parse_from_file ( root_processor , # type: RootProcessor xml_file_path , # type: Text encoding = 'utf-8' # type: Text ) : # type: (...) -> Any with open ( xml_file_path , 'r' , encoding = encoding ) as xml_file : xml_string = xml_file . read ( ) parsed_value = parse_from_string ( root_processor , xml_string ) retur...
Parse the XML file using the processor starting from the root of the document .
102
16
3,911
def parse_from_string ( root_processor , # type: RootProcessor xml_string # type: Text ) : # type: (...) -> Any if not _is_valid_root_processor ( root_processor ) : raise InvalidRootProcessor ( 'Invalid root processor' ) parseable_xml_string = xml_string # type: Union[Text, bytes] if _PY2 and isinstance ( xml_string , ...
Parse the XML string using the processor starting from the root of the document .
176
16
3,912
def serialize_to_file ( root_processor , # type: RootProcessor value , # type: Any xml_file_path , # type: Text encoding = 'utf-8' , # type: Text indent = None # type: Optional[Text] ) : # type: (...) -> None serialized_value = serialize_to_string ( root_processor , value , indent ) with open ( xml_file_path , 'w' , en...
Serialize the value to an XML file using the root processor .
118
13
3,913
def serialize_to_string ( root_processor , # type: RootProcessor value , # type: Any indent = None # type: Optional[Text] ) : # type: (...) -> Text if not _is_valid_root_processor ( root_processor ) : raise InvalidRootProcessor ( 'Invalid root processor' ) state = _ProcessorState ( ) state . push_location ( root_proces...
Serialize the value to an XML string using the root processor .
243
13
3,914
def array ( item_processor , # type: Processor alias = None , # type: Optional[Text] nested = None , # type: Optional[Text] omit_empty = False , # type: bool hooks = None # type: Optional[Hooks] ) : # type: (...) -> RootProcessor processor = _Array ( item_processor , alias , nested , omit_empty ) return _processor_wrap...
Create an array processor that can be used to parse and serialize array data .
97
16
3,915
def boolean ( element_name , # type: Text attribute = None , # type: Optional[Text] required = True , # type: bool alias = None , # type: Optional[Text] default = False , # type: Optional[bool] omit_empty = False , # type: bool hooks = None # type: Optional[Hooks] ) : # type: (...) -> Processor return _PrimitiveValue (...
Create a processor for boolean values .
112
7
3,916
def dictionary ( element_name , # type: Text children , # type: List[Processor] required = True , # type: bool alias = None , # type: Optional[Text] hooks = None # type: Optional[Hooks] ) : # type: (...) -> RootProcessor processor = _Dictionary ( element_name , children , required , alias ) return _processor_wrap_if_ho...
Create a processor for dictionary values .
93
7
3,917
def floating_point ( element_name , # type: Text attribute = None , # type: Optional[Text] required = True , # type: bool alias = None , # type: Optional[Text] default = 0.0 , # type: Optional[float] omit_empty = False , # type: bool hooks = None # type: Optional[Hooks] ) : # type: (...) -> Processor value_parser = _nu...
Create a processor for floating point values .
125
8
3,918
def integer ( element_name , # type: Text attribute = None , # type: Optional[Text] required = True , # type: bool alias = None , # type: Optional[Text] default = 0 , # type: Optional[int] omit_empty = False , # type: bool hooks = None # type: Optional[Hooks] ) : # type: (...) -> Processor value_parser = _number_parser...
Create a processor for integer values .
121
7
3,919
def named_tuple ( element_name , # type: Text tuple_type , # type: Type[Tuple] child_processors , # type: List[Processor] required = True , # type: bool alias = None , # type: Optional[Text] hooks = None # type: Optional[Hooks] ) : # type: (...) -> RootProcessor converter = _named_tuple_converter ( tuple_type ) process...
Create a processor for namedtuple values .
132
9
3,920
def string ( element_name , # type: Text attribute = None , # type: Optional[Text] required = True , # type: bool alias = None , # type: Optional[Text] default = '' , # type: Optional[Text] omit_empty = False , # type: bool strip_whitespace = True , # type: bool hooks = None # type: Optional[Hooks] ) : # type: (...) ->...
Create a processor for string values .
137
7
3,921
def user_object ( element_name , # type: Text cls , # type: Type[Any] child_processors , # type: List[Processor] required = True , # type: bool alias = None , # type: Optional[Text] hooks = None # type: Optional[Hooks] ) : # type: (...) -> RootProcessor converter = _user_object_converter ( cls ) processor = _Aggregate ...
Create a processor for user objects .
127
7
3,922
def _element_append_path ( start_element , # type: ET.Element element_names # type: Iterable[Text] ) : # type: (...) -> ET.Element end_element = start_element for element_name in element_names : new_element = ET . Element ( element_name ) end_element . append ( new_element ) end_element = new_element return end_element
Append the list of element names as a path to the provided start element .
89
16
3,923
def _element_find_from_root ( root , # type: ET.Element element_path # type: Text ) : # type: (...) -> Optional[ET.Element] element = None element_names = element_path . split ( '/' ) if element_names [ 0 ] == root . tag : if len ( element_names ) > 1 : element = root . find ( '/' . join ( element_names [ 1 : ] ) ) els...
Find the element specified by the given path starting from the root element of the document .
104
17
3,924
def _element_get_or_add_from_parent ( parent , # type: ET.Element element_path # type: Text ) : # type: (...) -> ET.Element element_names = element_path . split ( '/' ) # Starting from the parent, walk the element path until we find the first element in the path # that does not exist. Create that element and all the el...
Ensure all elements specified in the given path relative to the provided parent element exist .
206
17
3,925
def _element_path_create_new ( element_path ) : # type: (Text) -> Tuple[ET.Element, ET.Element] element_names = element_path . split ( '/' ) start_element = ET . Element ( element_names [ 0 ] ) end_element = _element_append_path ( start_element , element_names [ 1 : ] ) return start_element , end_element
Create an entirely new element path .
92
7
3,926
def _hooks_apply_after_parse ( hooks , # type: Optional[Hooks] state , # type: _ProcessorState value # type: Any ) : # type: (...) -> Any if hooks and hooks . after_parse : return hooks . after_parse ( ProcessorStateView ( state ) , value ) return value
Apply the after parse hook .
71
6
3,927
def _hooks_apply_before_serialize ( hooks , # type: Optional[Hooks] state , # type: _ProcessorState value # type: Any ) : # type: (...) -> Any if hooks and hooks . before_serialize : return hooks . before_serialize ( ProcessorStateView ( state ) , value ) return value
Apply the before serialize hook .
74
7
3,928
def _named_tuple_converter ( tuple_type ) : # type: (Type[Tuple]) -> _AggregateConverter def _from_dict ( dict_value ) : if dict_value : return tuple_type ( * * dict_value ) # Cannot construct a namedtuple value from an empty dictionary return None def _to_dict ( value ) : if value : return value . _asdict ( ) return {...
Return an _AggregateConverter for named tuples of the given type .
125
17
3,929
def _number_parser ( str_to_number_func ) : def _parse_number_value ( element_text , state ) : value = None try : value = str_to_number_func ( element_text ) except ( ValueError , TypeError ) : state . raise_error ( InvalidPrimitiveValue , 'Invalid numeric value "{}"' . format ( element_text ) ) return value return _pa...
Return a function to parse numbers .
93
7
3,930
def _parse_boolean ( element_text , state ) : value = None lowered_text = element_text . lower ( ) if lowered_text == 'true' : value = True elif lowered_text == 'false' : value = False else : state . raise_error ( InvalidPrimitiveValue , 'Invalid boolean value "{}"' . format ( element_text ) ) return value
Parse the raw XML string as a boolean value .
83
11
3,931
def _string_parser ( strip_whitespace ) : def _parse_string_value ( element_text , _state ) : if element_text is None : value = '' elif strip_whitespace : value = element_text . strip ( ) else : value = element_text return value return _parse_string_value
Return a parser function for parsing string values .
72
9
3,932
def _user_object_converter ( cls ) : # type: (Type[Any]) -> _AggregateConverter def _from_dict ( dict_value ) : try : object_value = cls ( * * dict_value ) except TypeError : # Constructor does not support keyword arguments, try setting each # field individually. object_value = cls ( ) for field_name , field_value in d...
Return an _AggregateConverter for a user object of the given class .
166
17
3,933
def _xml_namespace_strip ( root ) : # type: (ET.Element) -> None if '}' not in root . tag : return # Nothing to do, no namespace present for element in root . iter ( ) : if '}' in element . tag : element . tag = element . tag . split ( '}' ) [ 1 ] else : # pragma: no cover # We should never get here. If there is a name...
Strip the XML namespace prefix from all element tags under the given root Element .
109
16
3,934
def parse_at_element ( self , element , # type: ET.Element state # type: _ProcessorState ) : # type: (...) -> Any parsed_dict = self . _dictionary . parse_at_element ( element , state ) return self . _converter . from_dict ( parsed_dict )
Parse the provided element as an aggregate .
70
9
3,935
def parse_at_root ( self , root , # type: ET.Element state # type: _ProcessorState ) : # type: (...) -> Any parsed_dict = self . _dictionary . parse_at_root ( root , state ) return self . _converter . from_dict ( parsed_dict )
Parse the root XML element as an aggregate .
70
10
3,936
def parse_from_parent ( self , parent , # type: ET.Element state # type: _ProcessorState ) : # type: (...) -> Any parsed_dict = self . _dictionary . parse_from_parent ( parent , state ) return self . _converter . from_dict ( parsed_dict )
Parse the aggregate from the provided parent XML element .
70
11
3,937
def serialize ( self , value , # type: Any state # type: _ProcessorState ) : # type: (...) -> ET.Element dict_value = self . _converter . to_dict ( value ) return self . _dictionary . serialize ( dict_value , state )
Serialize the value to a new element and returns the element .
64
13
3,938
def serialize_on_parent ( self , parent , # type: ET.Element value , # type: Any state # type: _ProcessorState ) : # type: (...) -> None dict_value = self . _converter . to_dict ( value ) self . _dictionary . serialize_on_parent ( parent , dict_value , state )
Serialize the value and adds it to the parent .
79
11
3,939
def parse_at_element ( self , element , # type: ET.Element state # type: _ProcessorState ) : # type: (...) -> Any item_iter = element . findall ( self . _item_processor . element_path ) return self . _parse ( item_iter , state )
Parse the provided element as an array .
66
9
3,940
def parse_at_root ( self , root , # type: ET.Element state # type: _ProcessorState ) : # type: (...) -> Any if not self . _nested : raise InvalidRootProcessor ( 'Non-nested array "{}" cannot be root element' . format ( self . alias ) ) parsed_array = [ ] # type: List array_element = _element_find_from_root ( root , sel...
Parse the root XML element as an array .
160
10
3,941
def parse_from_parent ( self , parent , # type: ET.Element state # type: _ProcessorState ) : # type: (...) -> Any item_iter = parent . findall ( self . _item_path ) return self . _parse ( item_iter , state )
Parse the array data from the provided parent XML element .
62
12
3,942
def serialize ( self , value , # type: Any state # type: _ProcessorState ) : # type: (...) -> ET.Element if self . _nested is None : state . raise_error ( InvalidRootProcessor , 'Cannot directly serialize a non-nested array "{}"' . format ( self . alias ) ) if not value and self . required : state . raise_error ( Missi...
Serialize the value into a new Element object and return it .
148
13
3,943
def serialize_on_parent ( self , parent , # type: ET.Element value , # type: Any state # type: _ProcessorState ) : # type: (...) -> None if not value and self . required : state . raise_error ( MissingValue , 'Missing required array: "{}"' . format ( self . alias ) ) if not value and self . omit_empty : return # Do not...
Serialize the value and append it to the parent element .
158
12
3,944
def _parse ( self , item_iter , # type: Iterable[ET.Element] state # type: _ProcessorState ) : # type: (...) -> List parsed_array = [ ] for i , item in enumerate ( item_iter ) : state . push_location ( self . _item_processor . element_path , i ) parsed_array . append ( self . _item_processor . parse_at_element ( item ,...
Parse the array data using the provided iterator of XML elements .
144
13
3,945
def _serialize ( self , array_parent , # type: ET.Element value , # type: List state # type: _ProcessorState ) : # type: (...) -> None if not value : # Nothing to do. Avoid attempting to iterate over a possibly # None value. return for i , item_value in enumerate ( value ) : state . push_location ( self . _item_process...
Serialize the array value and add it to the array parent element .
131
14
3,946
def parse_at_element ( self , element , # type: ET.Element state # type: _ProcessorState ) : # type: (...) -> Any parsed_dict = { } for child in self . _child_processors : state . push_location ( child . element_path ) parsed_dict [ child . alias ] = child . parse_from_parent ( element , state ) state . pop_location ( ...
Parse the provided element as a dictionary .
95
9
3,947
def parse_at_root ( self , root , # type: ET.Element state # type: _ProcessorState ) : # type: (...) -> Any parsed_dict = { } # type: Dict dict_element = _element_find_from_root ( root , self . element_path ) if dict_element is not None : parsed_dict = self . parse_at_element ( dict_element , state ) elif self . requir...
Parse the root XML element as a dictionary .
124
10
3,948
def serialize ( self , value , # type: Any state # type: _ProcessorState ) : # type: (...) -> ET.Element if not value and self . required : state . raise_error ( MissingValue , 'Missing required aggregate "{}"' . format ( self . element_path ) ) start_element , end_element = _element_path_create_new ( self . element_pa...
Serialize the value to a new element and return the element .
106
13
3,949
def _serialize ( self , element , # type: ET.Element value , # type: Dict state # type: _ProcessorState ) : # type: (...) -> None for child in self . _child_processors : state . push_location ( child . element_path ) child_value = value . get ( child . alias ) child . serialize_on_parent ( element , child_value , state...
Serialize the dictionary and append all serialized children to the element .
98
14
3,950
def parse_at_element ( self , element , # type: ET.Element state # type: _ProcessorState ) : # type: (...) -> Any xml_value = self . _processor . parse_at_element ( element , state ) return _hooks_apply_after_parse ( self . _hooks , state , xml_value )
Parse the given element .
76
6
3,951
def parse_at_root ( self , root , # type: ET.Element state # type: _ProcessorState ) : # type: (...) -> Any xml_value = self . _processor . parse_at_root ( root , state ) return _hooks_apply_after_parse ( self . _hooks , state , xml_value )
Parse the given element as the root of the document .
76
12
3,952
def parse_from_parent ( self , parent , # type: ET.Element state # type: _ProcessorState ) : # type: (...) -> Any xml_value = self . _processor . parse_from_parent ( parent , state ) return _hooks_apply_after_parse ( self . _hooks , state , xml_value )
Parse the element from the given parent element .
76
10
3,953
def serialize ( self , value , # type: Any state # type: _ProcessorState ) : # type: (...) -> ET.Element xml_value = _hooks_apply_before_serialize ( self . _hooks , state , value ) return self . _processor . serialize ( xml_value , state )
Serialize the value and returns it .
71
8
3,954
def serialize_on_parent ( self , parent , # type: ET.Element value , # type: Any state # type: _ProcessorState ) : # type: (...) -> None xml_value = _hooks_apply_before_serialize ( self . _hooks , state , value ) self . _processor . serialize_on_parent ( parent , xml_value , state )
Serialize the value directory on the parent .
86
9
3,955
def parse_at_element ( self , element , # type: ET.Element state # type: _ProcessorState ) : # type: (...) -> Any if self . _attribute : parsed_value = self . _parse_attribute ( element , self . _attribute , state ) else : parsed_value = self . _parser_func ( element . text , state ) return _hooks_apply_after_parse ( s...
Parse the primitive value at the XML element .
102
10
3,956
def parse_from_parent ( self , parent , # type: ET.Element state # type: _ProcessorState ) : # type: (...) -> Any element = parent . find ( self . element_path ) if element is None and self . required : state . raise_error ( MissingValue , 'Missing required element "{}"' . format ( self . element_path ) ) elif element ...
Parse the primitive value under the parent XML element .
125
11
3,957
def serialize ( self , value , # type: Any state # type: _ProcessorState ) : # type: (...) -> ET.Element # For primitive values, this is only called when the value is part of an array, # in which case we do not need to check for missing or omitted values. start_element , end_element = _element_path_create_new ( self . ...
Serialize the value into a new element object and return the element .
106
14
3,958
def serialize_on_parent ( self , parent , # type: ET.Element value , # type: Any state # type: _ProcessorState ) : # type: (...) -> None # Note that falsey values are not treated as missing, but they may be omitted. if value is None and self . required : state . raise_error ( MissingValue , self . _missing_value_messag...
Serialize the value and add it to the parent element .
138
12
3,959
def _missing_value_message ( self , parent ) : # type: (ET.Element) -> Text if self . _attribute is None : message = 'Missing required value for element "{}"' . format ( self . element_path ) else : if self . element_path == '.' : parent_name = parent . tag else : parent_name = self . element_path message = 'Missing re...
Return the message to report that the value needed for serialization is missing .
110
15
3,960
def _parse_attribute ( self , element , # type: ET.Element attribute , # type: Text state # type: _ProcessorState ) : # type: (...) -> Any parsed_value = self . _default attribute_value = element . get ( attribute , None ) if attribute_value is not None : parsed_value = self . _parser_func ( attribute_value , state ) e...
Parse the primitive value within the XML element s attribute .
127
12
3,961
def _serialize ( self , element , # type: ET.Element value , # type: Any state # type: _ProcessorState ) : # type: (...) -> None xml_value = _hooks_apply_before_serialize ( self . _hooks , state , value ) # A value is only considered missing, and hence eligible to be replaced by its # default only if it is None. Falsey...
Serialize the value to the element .
184
8
3,962
def push_location ( self , element_path , # type: Text array_index = None # type: Optional[int] ) : # type: (...) -> None location = ProcessorLocation ( element_path = element_path , array_index = array_index ) self . _locations . append ( location )
Push an item onto the state s stack of locations .
67
11
3,963
def raise_error ( self , exception_type , # type: Type[Exception] message # type: Text ) : # type: (...) -> NoReturn error_message = '{} at {}' . format ( message , repr ( self ) ) raise exception_type ( error_message )
Raise an exception with the current parser state information and error message .
62
14
3,964
def export_partlist_to_file ( input , output , timeout = 20 , showgui = False ) : input = norm_path ( input ) output = norm_path ( output ) commands = export_command ( output = output , output_type = 'partlist' ) command_eagle ( input = input , timeout = timeout , commands = commands , showgui = showgui )
call eagle and export sch or brd to partlist text file
82
13
3,965
def parse_partlist ( str ) : lines = str . strip ( ) . splitlines ( ) lines = filter ( len , lines ) hind = header_index ( lines ) if hind is None : log . debug ( 'empty partlist found' ) return ( [ ] , [ ] ) header_line = lines [ hind ] header = header_line . split ( ' ' ) header = filter ( len , header ) positions = ...
parse partlist text delivered by eagle .
223
8
3,966
def raw_partlist ( input , timeout = 20 , showgui = False ) : output = tempfile . NamedTemporaryFile ( prefix = 'eagexp_' , suffix = '.partlist' , delete = 0 ) . name export_partlist_to_file ( input = input , output = output , timeout = timeout , showgui = showgui ) s = Path ( output ) . text ( encoding = 'latin1' ) os...
export partlist by eagle then return it
102
8
3,967
def structured_partlist ( input , timeout = 20 , showgui = False ) : s = raw_partlist ( input = input , timeout = timeout , showgui = showgui ) return parse_partlist ( s )
export partlist by eagle then parse it
47
8
3,968
def print_partlist ( input , timeout = 20 , showgui = False ) : print raw_partlist ( input = input , timeout = timeout , showgui = showgui )
print partlist text delivered by eagle
38
7
3,969
def bitset ( bs , member_label = None , filename = None , directory = None , format = None , render = False , view = False ) : if member_label is None : member_label = MEMBER_LABEL if filename is None : kind = 'members' if member_label else 'bits' filename = FILENAME % ( bs . __name__ , kind ) dot = graphviz . Digraph ...
Graphviz source for the Hasse diagram of the domains Boolean algebra .
277
15
3,970
def _get_field_method ( self , tp ) : method = self . field_constructor . get ( tp ) if method and hasattr ( self , method . __name__ ) : return getattr ( self , method . __name__ ) return method
Returns a reference to the form element s constructor method .
57
11
3,971
def _create_plain_field ( self , attr , options ) : method = self . _get_field_method ( attr . py_type ) or self . _create_other_field klass , options = method ( attr , options ) if attr . is_unique : options [ 'validators' ] . append ( validators . UniqueEntityValidator ( attr . entity ) ) return klass , options
Creates the form element .
92
6
3,972
def _create_relational_field ( self , attr , options ) : options [ 'entity_class' ] = attr . py_type options [ 'allow_empty' ] = not attr . is_required return EntityField , options
Creates the form element for working with entity relationships .
53
11
3,973
def add ( self , attr , field_class = None , * * options ) : # print(attr.name, attr.py_type, getattr(attr, 'set', None)) # print(dir(attr)) # print(attr, attr.is_relation, attr.is_collection) # print(attr.is_pk, attr.auto, attr.is_unique, attr.is_part_of_unique_index, attr.composite_keys) def add ( klass , options ) :...
Adds an element to the form based on the entity attribute .
366
12
3,974
def add_button ( self , name , button_class = wtf_fields . SubmitField , * * options ) : self . _buttons [ name ] = button_class ( * * options )
Adds a button to the form .
43
7
3,975
def field_uuid ( self , attr , options ) : options [ 'validators' ] . append ( validators . UUIDValidator ( attr . entity ) ) return wtf_fields . StringField , options
Creates a form element for the UUID type .
48
11
3,976
def runm ( ) : signal . signal ( signal . SIGINT , signal_handler ) count = int ( sys . argv . pop ( 1 ) ) processes = [ Process ( target = run , args = ( ) ) for x in range ( count ) ] try : for p in processes : p . start ( ) except KeyError : # Not sure why we see a keyerror here. Weird. pass finally : for p in proce...
This is super minimal and pretty hacky but it counts as a first pass .
97
16
3,977
def identify ( self , request ) : token = self . get_jwt ( request ) if token is None : return NO_IDENTITY try : claims_set = self . decode_jwt ( token ) except ( DecodeError , ExpiredSignatureError ) : return NO_IDENTITY userid = self . get_userid ( claims_set ) if userid is None : return NO_IDENTITY extra_claims = se...
Establish what identity this user claims to have from request .
141
12
3,978
def remember ( self , response , request , identity ) : claims = identity . as_dict ( ) userid = claims . pop ( 'userid' ) claims_set = self . create_claims_set ( request , userid , claims ) token = self . encode_jwt ( claims_set ) response . headers [ 'Authorization' ] = '%s %s' % ( self . auth_header_prefix , token )
Remember identity on response .
94
5
3,979
def decode_jwt ( self , token , verify_expiration = True ) : options = { 'verify_exp' : verify_expiration , } return jwt . decode ( token , self . public_key , algorithms = [ self . algorithm ] , options = options , leeway = self . leeway , issuer = self . issuer )
Decode a JWTAuth token into its claims set .
74
13
3,980
def create_claims_set ( self , request , userid , extra_claims = None ) : claims_set = { self . userid_claim : userid } now = timegm ( datetime . utcnow ( ) . utctimetuple ( ) ) if self . expiration_delta is not None : claims_set [ 'exp' ] = now + self . expiration_delta if self . issuer is not None : claims_set [ 'iss...
Create the claims set based on the userid of the claimed identity the settings and the extra_claims dictionary .
207
23
3,981
def encode_jwt ( self , claims_set ) : token = jwt . encode ( claims_set , self . private_key , self . algorithm ) if PY3 : token = token . decode ( encoding = 'UTF-8' ) return token
Encode a JWT token based on the claims_set and the settings .
55
16
3,982
def get_extra_claims ( self , claims_set ) : reserved_claims = ( self . userid_claim , "iss" , "aud" , "exp" , "nbf" , "iat" , "jti" , "refresh_until" , "nonce" ) extra_claims = { } for claim in claims_set : if claim not in reserved_claims : extra_claims [ claim ] = claims_set [ claim ] if not extra_claims : return Non...
Get claims holding extra identity info from the claims set .
117
11
3,983
def get_jwt ( self , request ) : try : authorization = request . authorization except ValueError : return None if authorization is None : return None authtype , token = authorization if authtype . lower ( ) != self . auth_header_prefix . lower ( ) : return None return token
Extract the JWT token from the authorisation header of the request .
61
15
3,984
def verify_refresh ( self , request ) : if not self . allow_refresh : raise InvalidTokenError ( 'Token refresh is disabled' ) token = self . get_jwt ( request ) if token is None : raise InvalidTokenError ( 'Token not found' ) try : claims_set = self . decode_jwt ( token , self . verify_expiration_on_refresh ) # reraise...
Verify if the request to refresh the token is valid . If valid it returns the userid which can be used to create an updated identity with remember_identity . Otherwise it raises an exception based on InvalidTokenError .
353
45
3,985
def fit_theil_sen ( x , y ) : xx = numpy . asarray ( x ) y1 = numpy . asarray ( y ) n = len ( xx ) if n < 5 : raise ValueError ( 'Number of points < 5' ) if xx . ndim != 1 : raise ValueError ( 'Input arrays have unexpected dimensions' ) if y1 . ndim == 1 : if len ( y1 ) != n : raise ValueError ( 'X and Y arrays have di...
Compute a robust linear fit using the Theil - Sen method .
334
14
3,986
def process_unknown_arguments ( unknowns ) : result = argparse . Namespace ( ) result . extra_control = { } # It would be interesting to use argparse internal # machinery for this for unknown in unknowns : # Check prefixes prefix = '--parameter-' if unknown . startswith ( prefix ) : # process '=' values = unknown . spl...
Process arguments unknown to the parser
125
6
3,987
def get_fd ( file_or_fd , default = None ) : fd = file_or_fd if fd is None : fd = default if hasattr ( fd , "fileno" ) : fd = fd . fileno ( ) return fd
Helper function for getting a file descriptor .
60
8
3,988
def forkexec_pty ( argv , env = None , size = None ) : child_pid , child_fd = pty . fork ( ) if child_pid == 0 : os . closerange ( 3 , MAXFD ) environ = os . environ . copy ( ) if env is not None : environ . update ( env ) os . execve ( argv [ 0 ] , argv , environ ) if size is None : try : size = get_terminal_size ( 1 ...
Fork a child process attached to a pty .
141
11
3,989
def get_ancestor_processes ( ) : if not _ANCESTOR_PROCESSES and psutil is not None : proc = psutil . Process ( os . getpid ( ) ) while proc . parent ( ) is not None : try : _ANCESTOR_PROCESSES . append ( proc . parent ( ) . exe ( ) ) proc = proc . parent ( ) except psutil . Error : break return _ANCESTOR_PROCESSES
Get a list of the executables of all ancestor processes .
103
12
3,990
def get_default_shell ( environ = None , fallback = _UNSPECIFIED ) : if environ is None : environ = os . environ # If the option is specified in the environment, respect it. if "PIAS_OPT_SHELL" in environ : return environ [ "PIAS_OPT_SHELL" ] # Find all candiate shell programs. shells = [ ] for filename in ( environ . ...
Get the user s default shell program .
232
8
3,991
def get_default_terminal ( environ = None , fallback = _UNSPECIFIED ) : if environ is None : environ = os . environ # If the option is specified in the environment, respect it. if "PIAS_OPT_TERMINAL" in environ : return environ [ "PIAS_OPT_TERMINAL" ] # Find all candiate terminal programs. terminals = [ ] colorterm = e...
Get the user s default terminal program .
252
8
3,992
def get_pias_script ( environ = None ) : if os . path . basename ( sys . argv [ 0 ] ) == "pias" : return sys . argv [ 0 ] filepath = find_executable ( "pias" , environ ) if filepath is not None : return filepath filepath = os . path . join ( os . path . dirname ( __file__ ) , "__main__.py" ) # XXX TODO: check if execut...
Get the path to the playitagainsam command - line script .
135
15
3,993
def airwires ( board , showgui = 0 ) : board = Path ( board ) . expand ( ) . abspath ( ) file_out = tempfile . NamedTemporaryFile ( suffix = '.txt' , delete = 0 ) file_out . close ( ) ulp = ulp_templ . replace ( 'FILE_NAME' , file_out . name ) file_ulp = tempfile . NamedTemporaryFile ( suffix = '.ulp' , delete = 0 ) fi...
search for airwires in eagle board
205
8
3,994
def _initialize ( self , con ) : if self . initialized : return SQLite3Database ( ) . _initialize ( con ) # ASE db initialization cur = con . execute ( 'SELECT COUNT(*) FROM sqlite_master WHERE name="reaction"' ) if cur . fetchone ( ) [ 0 ] == 0 : # no reaction table for init_command in init_commands : con . execute ( ...
Set up tables in SQL
106
5
3,995
def write_publication ( self , values ) : con = self . connection or self . _connect ( ) self . _initialize ( con ) cur = con . cursor ( ) values = ( values [ 'pub_id' ] , values [ 'title' ] , json . dumps ( values [ 'authors' ] ) , values [ 'journal' ] , values [ 'volume' ] , values [ 'number' ] , values [ 'pages' ] ,...
Write publication info to db
216
5
3,996
def write ( self , values , data = None ) : con = self . connection or self . _connect ( ) self . _initialize ( con ) cur = con . cursor ( ) pub_id = values [ 'pub_id' ] ase_ids = values [ 'ase_ids' ] energy_corrections = values [ 'energy_corrections' ] if ase_ids is not None : check_ase_ids ( values , ase_ids ) else :...
Write reaction info to db file
494
6
3,997
def update ( self , id , values , key_names = 'all' ) : con = self . connection or self . _connect ( ) self . _initialize ( con ) cur = con . cursor ( ) pub_id = values [ 'pub_id' ] ase_ids = values [ 'ase_ids' ] energy_corrections = values [ 'energy_corrections' ] if ase_ids is not None : check_ase_ids ( values , ase_...
Update reaction info for a selected row
420
7
3,998
def get_last_id ( self , cur , table = 'reaction' ) : cur . execute ( "SELECT seq FROM sqlite_sequence WHERE name='{0}'" . format ( table ) ) result = cur . fetchone ( ) if result is not None : id = result [ 0 ] else : id = 0 return id
Get the id of the last written row in table
71
10
3,999
def read_wv_master_from_array ( master_table , lines = 'brightest' , debugplot = 0 ) : # protection if lines not in [ 'brightest' , 'all' ] : raise ValueError ( 'Unexpected lines=' + str ( lines ) ) # determine wavelengths according to the number of columns if master_table . ndim == 1 : wv_master = master_table else : ...
read arc line wavelengths from numpy array
284
8