idx int64 0 63k | question stringlengths 53 5.28k | target stringlengths 5 805 |
|---|---|---|
54,900 | def _erf ( x ) : T = [ 9.60497373987051638749E0 , 9.00260197203842689217E1 , 2.23200534594684319226E3 , 7.00332514112805075473E3 , 5.55923013010394962768E4 , ] U = [ 3.35617141647503099647E1 , 5.21357949780152679795E2 , 4.59432382970980127987E3 , 2.26290000613890934246E4 , 4.92673942608635921086E4 , ] if x == 0 : retur... | Port of cephes ndtr . c erf function . |
54,901 | def _erfc ( a ) : P = [ 2.46196981473530512524E-10 , 5.64189564831068821977E-1 , 7.46321056442269912687E0 , 4.86371970985681366614E1 , 1.96520832956077098242E2 , 5.26445194995477358631E2 , 9.34528527171957607540E2 , 1.02755188689515710272E3 , 5.57535335369399327526E2 , ] Q = [ 1.32281951154744992508E1 , 8.6707214088598... | Port of cephes ndtr . c erfc function . |
54,902 | def erfinv ( z ) : if abs ( z ) > 1 : raise ValueError ( "`z` must be between -1 and 1 inclusive" ) if z == 0 : return 0 if z == 1 : return inf if z == - 1 : return - inf return _ndtri ( ( z + 1 ) / 2.0 ) / math . sqrt ( 2 ) | Calculate the inverse error function at point z . |
54,903 | def get_cmap ( name , lut = None ) : if name in rcParams [ 'colors.cmaps' ] : colors = rcParams [ 'colors.cmaps' ] [ name ] lut = lut or len ( colors ) return FixedColorMap . from_list ( name = name , colors = colors , N = lut ) elif name in _cmapnames : colors = _cmapnames [ name ] lut = lut or len ( colors ) return F... | Returns the specified colormap . |
54,904 | def _get_cmaps ( names ) : import matplotlib . pyplot as plt available_cmaps = list ( chain ( plt . cm . cmap_d , _cmapnames , rcParams [ 'colors.cmaps' ] ) ) names = list ( names ) wrongs = [ ] for arg in ( arg for arg in names if ( not isinstance ( arg , Colormap ) and arg not in available_cmaps ) ) : if isinstance (... | Filter the given names for colormaps |
54,905 | def show_colormaps ( names = [ ] , N = 10 , show = True , use_qt = None ) : names = safe_list ( names ) if use_qt or ( use_qt is None and psyplot . with_gui ) : from psy_simple . widgets . colors import ColormapDialog from psyplot_gui . main import mainwindow return ColormapDialog . show_colormap ( names , N , show , p... | Function to show standard colormaps from pyplot |
54,906 | def _create_stdout_logger ( logging_level ) : out_hdlr = logging . StreamHandler ( sys . stdout ) out_hdlr . setFormatter ( logging . Formatter ( '[%(asctime)s] %(message)s' , "%H:%M:%S" ) ) out_hdlr . setLevel ( logging_level ) for name in LOGGING_NAMES : log = logging . getLogger ( name ) log . addHandler ( out_hdlr ... | create a logger to stdout . This creates logger for a series of module we would like to log information on . |
54,907 | def main ( ) : docraptor = DocRaptor ( ) print ( "Create PDF" ) resp = docraptor . create ( { "document_content" : "<h1>python-docraptor</h1><p>Async Test</p>" , "test" : True , "async" : True , } ) print ( "Status ID: {status_id}" . format ( status_id = resp [ "status_id" ] ) ) status_id = resp [ "status_id" ] resp = ... | Generate a PDF using the async method . |
54,908 | def get_alternate_types_resolving_forwardref_union_and_typevar ( typ , _memo : List [ Any ] = None ) -> Tuple [ Any , ... ] : _memo = _memo or [ ] if typ in _memo : return tuple ( ) _memo . append ( typ ) if is_typevar ( typ ) : if hasattr ( typ , '__bound__' ) and typ . __bound__ is not None : if hasattr ( typ , '__co... | Returns a tuple of all alternate types allowed by the typ type annotation . |
54,909 | def robust_isinstance ( inst , typ ) -> bool : if typ is Any : return True if is_typevar ( typ ) : if hasattr ( typ , '__constraints__' ) and typ . __constraints__ is not None : typs = get_args ( typ , evaluate = True ) return any ( robust_isinstance ( inst , t ) for t in typs ) elif hasattr ( typ , '__bound__' ) and t... | Similar to isinstance but if typ is a parametrized generic Type it is first transformed into its base generic class so that the instance check works . It is also robust to Union and Any . |
54,910 | def eval_forward_ref ( typ : _ForwardRef ) : for frame in stack ( ) : m = getmodule ( frame [ 0 ] ) m_name = m . __name__ if m is not None else '<unknown>' if m_name . startswith ( 'parsyfiles.tests' ) or not m_name . startswith ( 'parsyfiles' ) : try : return typ . _eval_type ( frame [ 0 ] . f_globals , frame [ 0 ] . ... | Climbs the current stack until the given Forward reference has been resolved or raises an InvalidForwardRefError |
54,911 | def is_valid_pep484_type_hint ( typ_hint , allow_forward_refs : bool = False ) : try : if isinstance ( typ_hint , type ) : return True except : pass try : if allow_forward_refs and is_forward_ref ( typ_hint ) : return True except : pass try : return is_union_type ( typ_hint ) or is_typevar ( typ_hint ) except : return ... | Returns True if the provided type is a valid PEP484 type hint False otherwise . |
54,912 | def is_pep484_nonable ( typ ) : if typ is type ( None ) : return True elif is_typevar ( typ ) or is_union_type ( typ ) : return any ( is_pep484_nonable ( tt ) for tt in get_alternate_types_resolving_forwardref_union_and_typevar ( typ ) ) else : return False | Checks if a given type is nonable meaning that it explicitly or implicitly declares a Union with NoneType . Nested TypeVars and Unions are supported . |
54,913 | def create_for_collection_items ( item_type , hint ) : return TypeInformationRequiredError ( "Cannot parse object of type {t} as a collection: this type has no valid " "PEP484 type hint about its contents: found {h}. Please use a standard " "PEP484 declaration such as Dict[str, Foo] or List[Foo]" "" . format ( t = str ... | Helper method for collection items |
54,914 | def create_for_object_attributes ( item_type , faulty_attribute_name : str , hint ) : return TypeInformationRequiredError ( "Cannot create instances of type {t}: constructor attribute '{a}' has an" " invalid PEP484 type hint: {h}." . format ( t = str ( item_type ) , a = faulty_attribute_name , h = hint ) ) | Helper method for constructor attributes |
54,915 | def exception_class ( self , exception ) : cls = type ( exception ) if cls . __module__ == 'exceptions' : return cls . __name__ return "%s.%s" % ( cls . __module__ , cls . __name__ ) | Return a name representing the class of an exception . |
54,916 | def request_info ( self , request ) : view , args , kwargs = resolve ( request . path ) for i , arg in enumerate ( args ) : kwargs [ i ] = arg parameters = { } parameters . update ( kwargs ) parameters . update ( request . POST . items ( ) ) environ = request . META return { "session" : dict ( request . session ) , 'co... | Return a dictionary of information for a given request . |
54,917 | def _save ( self , hdf5 , model , positives , negatives ) : hdf5 . set ( "PositiveIndices" , sorted ( list ( positives ) ) ) hdf5 . set ( "NegativeIndices" , sorted ( list ( negatives ) ) ) hdf5 . create_group ( "Model" ) hdf5 . cd ( "Model" ) model . save ( hdf5 ) del hdf5 | Saves the given intermediate state of the bootstrapping to file . |
54,918 | def _load ( self , hdf5 ) : positives = set ( hdf5 . get ( "PositiveIndices" ) ) negatives = set ( hdf5 . get ( "NegativeIndices" ) ) hdf5 . cd ( "Model" ) model = bob . learn . boosting . BoostedMachine ( hdf5 ) return model , positives , negatives | Loads the intermediate state of the bootstrapping from file . |
54,919 | def undelay ( self ) : i = 0 while i < len ( self ) : op = self [ i ] i += 1 if hasattr ( op , 'arg1' ) : if isinstance ( op . arg1 , DelayedArg ) : op . arg1 = op . arg1 . resolve ( ) if isinstance ( op . arg1 , CodeBlock ) : op . arg1 . undelay ( ) | resolves all delayed arguments |
54,920 | def get_directorship_heads ( self , val ) : __ldap_group_ou__ = "cn=groups,cn=accounts,dc=csh,dc=rit,dc=edu" res = self . __con__ . search_s ( __ldap_group_ou__ , ldap . SCOPE_SUBTREE , "(cn=eboard-%s)" % val , [ 'member' ] ) ret = [ ] for member in res [ 0 ] [ 1 ] [ 'member' ] : try : ret . append ( member . decode ( ... | Get the head of a directorship |
54,921 | def enqueue_mod ( self , dn , mod ) : if dn not in self . __pending_mod_dn__ : self . __pending_mod_dn__ . append ( dn ) self . __mod_queue__ [ dn ] = [ ] self . __mod_queue__ [ dn ] . append ( mod ) | Enqueue a LDAP modification . |
54,922 | def flush_mod ( self ) : for dn in self . __pending_mod_dn__ : try : if self . __ro__ : for mod in self . __mod_queue__ [ dn ] : if mod [ 0 ] == ldap . MOD_DELETE : mod_str = "DELETE" elif mod [ 0 ] == ldap . MOD_ADD : mod_str = "ADD" else : mod_str = "REPLACE" print ( "{} VALUE {} = {} FOR {}" . format ( mod_str , mod... | Flush all pending LDAP modifications . |
54,923 | def detect_encoding ( value ) : if six . PY2 : null_pattern = tuple ( bool ( ord ( char ) ) for char in value [ : 4 ] ) else : null_pattern = tuple ( bool ( char ) for char in value [ : 4 ] ) encodings = { ( 0 , 0 , 0 , 1 ) : 'utf-32-be' , ( 0 , 1 , 0 , 1 ) : 'utf-16-be' , ( 1 , 0 , 0 , 0 ) : 'utf-32-le' , ( 1 , 0 , 1 ... | Returns the character encoding for a JSON string . |
54,924 | def _merge_params ( url , params ) : if isinstance ( params , dict ) : params = list ( params . items ( ) ) scheme , netloc , path , query , fragment = urllib . parse . urlsplit ( url ) url_params = urllib . parse . parse_qsl ( query , keep_blank_values = True ) url_params . extend ( params ) query = _encode_data ( url... | Merge and encode query parameters with an URL . |
54,925 | def json ( self , ** kwargs ) : encoding = detect_encoding ( self . content [ : 4 ] ) value = self . content . decode ( encoding ) return simplejson . loads ( value , ** kwargs ) | Decodes response as JSON . |
54,926 | def raise_for_status ( self ) : if 400 <= self . status_code < 600 : message = 'Error %s for %s' % ( self . status_code , self . url ) raise HTTPError ( message ) | Raises HTTPError if the request got an error . |
54,927 | def metric ( cls , name , count , elapsed ) : if name is None : warnings . warn ( "Ignoring unnamed metric" , stacklevel = 3 ) return with cls . lock : if cls . dump_atexit and not cls . instances : atexit . register ( cls . dump ) try : self = cls . instances [ name ] except KeyError : self = cls . instances [ name ] ... | A metric function that buffers through numpy |
54,928 | def _dump ( self ) : try : self . temp . seek ( 0 ) arr = np . fromfile ( self . temp , self . dtype ) self . count_arr = arr [ 'count' ] self . elapsed_arr = arr [ 'elapsed' ] if self . calc_stats : self . count_mean = np . mean ( self . count_arr ) self . count_std = np . std ( self . count_arr ) self . elapsed_mean ... | dump data for an individual metric . For internal use only . |
54,929 | def list ( self , host_rec = None , service_rec = None , hostfilter = None ) : return self . send . vuln_list ( host_rec , service_rec , hostfilter ) | Returns a list of vulnerabilities based on t_hosts . id or t_services . id . If neither are set then statistical results are added |
54,930 | def ip_info ( self , vuln_name = None , vuln_id = None , ip_list_only = True , hostfilter = None ) : return self . send . vuln_ip_info ( vuln_name , vuln_id , ip_list_only , hostfilter ) | List of all IP Addresses with a vulnerability |
54,931 | def service_list ( self , vuln_name = None , vuln_id = None , hostfilter = None ) : return self . send . vuln_service_list ( vuln_name , vuln_id , hostfilter ) | Returns a dictionary of vulns with services and IP Addresses |
54,932 | def import_name ( mod_name ) : try : mod_obj_old = sys . modules [ mod_name ] except KeyError : mod_obj_old = None if mod_obj_old is not None : return mod_obj_old __import__ ( mod_name ) mod_obj = sys . modules [ mod_name ] return mod_obj | Import a module by module name . |
54,933 | def import_path ( mod_path , mod_name ) : mod_code = open ( mod_path ) . read ( ) mod_obj = import_code ( mod_code = mod_code , mod_name = mod_name , ) if not hasattr ( mod_obj , '__file__' ) : mod_obj . __file__ = mod_path return mod_obj | Import a module by module file path . |
54,934 | def import_obj ( uri , mod_name = None , mod_attr_sep = '::' , attr_chain_sep = '.' , retn_mod = False , ) : if mod_attr_sep is None : mod_attr_sep = '::' uri_parts = split_uri ( uri = uri , mod_attr_sep = mod_attr_sep ) protocol , mod_uri , attr_chain = uri_parts if protocol == 'py' : mod_obj = import_name ( mod_uri )... | Load an object from a module . |
54,935 | def add_to_sys_modules ( mod_name , mod_obj = None ) : mod_snames = mod_name . split ( '.' ) parent_mod_name = '' parent_mod_obj = None for mod_sname in mod_snames : if parent_mod_name == '' : current_mod_name = mod_sname else : current_mod_name = parent_mod_name + '.' + mod_sname if current_mod_name == mod_name : curr... | Add a module object to sys . modules . |
54,936 | def get_host ( environ ) : scheme = environ . get ( 'wsgi.url_scheme' ) if 'HTTP_X_FORWARDED_HOST' in environ : result = environ [ 'HTTP_X_FORWARDED_HOST' ] elif 'HTTP_HOST' in environ : result = environ [ 'HTTP_HOST' ] else : result = environ [ 'SERVER_NAME' ] if ( scheme , str ( environ [ 'SERVER_PORT' ] ) ) not in (... | Return the real host for the given WSGI environment . This takes care of the X - Forwarded - Host header . |
54,937 | def _raw ( cls , vertices , edges , out_edges , in_edges , head , tail ) : self = object . __new__ ( cls ) self . _out_edges = out_edges self . _in_edges = in_edges self . _head = head self . _tail = tail self . _vertices = vertices self . _edges = edges return self | Private constructor for direct construction of an ObjectGraph from its attributes . |
54,938 | def annotated ( self ) : edge_annotations = { } for edge in self . edges : if edge not in edge_annotations : referrer = self . _tail [ edge ] known_refs = annotated_references ( referrer ) for out_edge in self . _out_edges [ referrer ] : referent = self . _head [ out_edge ] if known_refs [ referent ] : annotation = kno... | Annotate this graph returning an AnnotatedGraph object with the same structure . |
54,939 | def owned_objects ( self ) : return ( [ self , self . __dict__ , self . _head , self . _tail , self . _out_edges , self . _out_edges . _keys , self . _out_edges . _values , self . _in_edges , self . _in_edges . _keys , self . _in_edges . _values , self . _vertices , self . _vertices . _elements , self . _edges , ] + li... | List of gc - tracked objects owned by this ObjectGraph instance . |
54,940 | def find_by_typename ( self , typename ) : return self . find_by ( lambda obj : type ( obj ) . __name__ == typename ) | List of all objects whose type has the given name . |
54,941 | def get_unset_inputs ( self ) : return set ( [ k for k , v in self . _inputs . items ( ) if v . is_empty ( False ) ] ) | Return a set of unset inputs |
54,942 | def prompt_unset_inputs ( self , force = False ) : for k , v in self . _inputs . items ( ) : if force or v . is_empty ( False ) : self . get_input ( k , force = force ) | Prompt for unset input values |
54,943 | def values ( self , with_defaults = True ) : return dict ( ( ( k , str ( v ) ) for k , v in self . _inputs . items ( ) if not v . is_empty ( with_defaults ) ) ) | Return the values dictionary defaulting to default values |
54,944 | def write_values ( self ) : return dict ( ( ( k , v . value ) for k , v in self . _inputs . items ( ) if not v . is_secret and not v . is_empty ( False ) ) ) | Return the dictionary with which to write values |
54,945 | def _parse_param_line ( self , line ) : value = line . strip ( '\n \t' ) if len ( value ) > 0 : i = Input ( ) if value . find ( '#' ) != - 1 : value , extra_attributes = value . split ( '#' ) try : extra_attributes = eval ( extra_attributes ) except SyntaxError : raise InputException ( "Incorrectly formatted input for ... | Parse a single param line . |
54,946 | def download ( self , overwrite = True ) : if overwrite or not os . path . exists ( self . file_path ) : _ , f = tempfile . mkstemp ( ) try : urlretrieve ( self . DOWNLOAD_URL , f ) extract_csv ( f , self . file_path ) finally : os . remove ( f ) | Download the zipcodes CSV file . If overwrite is set to False the file won t be downloaded if it already exists . |
54,947 | def get_zipcodes_for_canton ( self , canton ) : zipcodes = [ zipcode for zipcode , location in self . get_locations ( ) . items ( ) if location . canton == canton ] return zipcodes | Return the list of zipcodes for the given canton code . |
54,948 | def get_cantons ( self ) : return sorted ( list ( set ( [ location . canton for location in self . get_locations ( ) . values ( ) ] ) ) ) | Return the list of unique cantons sorted by name . |
54,949 | def get_municipalities ( self ) : return sorted ( list ( set ( [ location . municipality for location in self . get_locations ( ) . values ( ) ] ) ) ) | Return the list of unique municipalities sorted by name . |
54,950 | def _get_formula_class ( self , formula ) : from sprinter . formula . base import FormulaBase if formula in LEGACY_MAPPINGS : formula = LEGACY_MAPPINGS [ formula ] formula_class , formula_url = formula , None if ':' in formula : formula_class , formula_url = formula . split ( ":" , 1 ) if formula_class not in self . _f... | get a formula class object if it exists else create one add it to the dict and pass return it . |
54,951 | def is_backup_class ( cls ) : return True if ( isclass ( cls ) and issubclass ( cls , Storable ) and get_mapping ( cls , no_mapping_ok = True ) ) else False | Return true if given class supports back up . Currently this means a gludb . data . Storable - derived class that has a mapping as defined in gludb . config |
54,952 | def process ( hw_num : int , problems_to_do : Optional [ Iterable [ int ] ] = None , prefix : Optional [ Path ] = None , by_hand : Optional [ Iterable [ int ] ] = None , ) -> None : if prefix is None : prefix = Path ( "." ) problems : Iterable [ Path ] if problems_to_do is None : problems = list ( prefix . glob ( f"hom... | Process the homework problems in prefix folder . |
54,953 | def main ( argv : Optional [ Sequence [ str ] ] = None ) -> None : parser = ArgumentParser ( description = "Convert Jupyter Notebook assignments to PDFs" ) parser . add_argument ( "--hw" , type = int , required = True , help = "Homework number to convert" , dest = "hw_num" , ) parser . add_argument ( "-p" , "--problems... | Parse arguments and process the homework assignment . |
54,954 | def get_vm_by_name ( content , name , regex = False ) : return get_object_by_name ( content , vim . VirtualMachine , name , regex ) | Get a VM by its name |
54,955 | def get_datacenter ( content , obj ) : datacenters = content . rootFolder . childEntity for d in datacenters : dch = get_all ( content , d , type ( obj ) ) if dch is not None and obj in dch : return d | Get the datacenter to whom an object belongs |
54,956 | def get_all_vswitches ( content ) : vswitches = [ ] hosts = get_all_hosts ( content ) for h in hosts : for s in h . config . network . vswitch : vswitches . append ( s ) return vswitches | Get all the virtual switches |
54,957 | def print_vm_info ( vm ) : summary = vm . summary print ( 'Name : ' , summary . config . name ) print ( 'Path : ' , summary . config . vmPathName ) print ( 'Guest : ' , summary . config . guestFullName ) annotation = summary . config . annotation if annotation is not None and annotation != '' : print ( 'Annotation : ... | Print information for a particular virtual machine |
54,958 | def module_import ( module_path ) : try : module = __import__ ( module_path ) components = module_path . split ( '.' ) for component in components [ 1 : ] : module = getattr ( module , component ) return module except ImportError : raise BadModulePathError ( 'Unable to find module "%s".' % ( module_path , ) ) | Imports the module indicated in name |
54,959 | def find_contour_yaml ( config_file = __file__ , names = None ) : checked = set ( ) contour_yaml = _find_countour_yaml ( os . path . dirname ( config_file ) , checked , names = names ) if not contour_yaml : contour_yaml = _find_countour_yaml ( os . getcwd ( ) , checked , names = names ) return contour_yaml | Traverse directory trees to find a contour . yaml file |
54,960 | def _find_countour_yaml ( start , checked , names = None ) : extensions = [ ] if names : for name in names : if not os . path . splitext ( name ) [ 1 ] : extensions . append ( name + ".yaml" ) extensions . append ( name + ".yml" ) yaml_names = ( names or [ ] ) + CONTOUR_YAML_NAMES + extensions directory = start while d... | Traverse the directory tree identified by start until a directory already in checked is encountered or the path of countour . yaml is found . |
54,961 | def _guess_type_from_validator ( validator ) : if isinstance ( validator , _OptionalValidator ) : return _guess_type_from_validator ( validator . validator ) elif isinstance ( validator , _AndValidator ) : for v in validator . validators : typ = _guess_type_from_validator ( v ) if typ is not None : return typ return No... | Utility method to return the declared type of an attribute or None . It handles _OptionalValidator and _AndValidator in order to unpack the validators . |
54,962 | def is_optional ( attr ) : return isinstance ( attr . validator , _OptionalValidator ) or ( attr . default is not None and attr . default is not NOTHING ) | Helper method to find if an attribute is mandatory |
54,963 | def preprocess ( self , nb : "NotebookNode" , resources : dict ) -> Tuple [ "NotebookNode" , dict ] : if not resources . get ( "global_content_filter" , { } ) . get ( "include_raw" , False ) : keep_cells = [ ] for cell in nb . cells : if cell . cell_type != "raw" : keep_cells . append ( cell ) nb . cells = keep_cells r... | Remove any raw cells from the Notebook . |
54,964 | def preprocess ( self , nb : "NotebookNode" , resources : dict ) -> Tuple [ "NotebookNode" , dict ] : if "remove_solution" not in resources : raise KeyError ( "The resources dictionary must have a remove_solution key." ) if resources [ "remove_solution" ] : keep_cells_idx = [ ] for index , cell in enumerate ( nb . cell... | Preprocess the entire notebook . |
54,965 | def parse_from_dict ( json_dict ) : order_columns = json_dict [ 'columns' ] order_list = MarketOrderList ( upload_keys = json_dict [ 'uploadKeys' ] , order_generator = json_dict [ 'generator' ] , ) for rowset in json_dict [ 'rowsets' ] : generated_at = parse_datetime ( rowset [ 'generatedAt' ] ) region_id = rowset [ 'r... | Given a Unified Uploader message parse the contents and return a MarketOrderList . |
54,966 | def encode_to_json ( order_list ) : rowsets = [ ] for items_in_region_list in order_list . _orders . values ( ) : region_id = items_in_region_list . region_id type_id = items_in_region_list . type_id generated_at = gen_iso_datetime_str ( items_in_region_list . generated_at ) rows = [ ] for order in items_in_region_list... | Encodes this list of MarketOrder instances to a JSON string . |
54,967 | def decode ( f ) : decoder = mqtt_io . FileDecoder ( f ) ( byte_0 , ) = decoder . unpack ( mqtt_io . FIELD_U8 ) packet_type_u4 = ( byte_0 >> 4 ) flags = byte_0 & 0x0f try : packet_type = MqttControlPacketType ( packet_type_u4 ) except ValueError : raise DecodeError ( 'Unknown packet type 0x{:02x}.' . format ( packet_ty... | Extract a MqttFixedHeader from f . |
54,968 | def decode_body ( cls , header , f ) : assert header . packet_type == MqttControlPacketType . subscribe decoder = mqtt_io . FileDecoder ( mqtt_io . LimitReader ( f , header . remaining_len ) ) packet_id , = decoder . unpack ( mqtt_io . FIELD_PACKET_ID ) topics = [ ] while header . remaining_len > decoder . num_bytes_co... | Generates a MqttSubscribe packet given a MqttFixedHeader . This method asserts that header . packet_type is subscribe . |
54,969 | def decode_body ( cls , header , f ) : assert header . packet_type == MqttControlPacketType . suback decoder = mqtt_io . FileDecoder ( mqtt_io . LimitReader ( f , header . remaining_len ) ) packet_id , = decoder . unpack ( mqtt_io . FIELD_PACKET_ID ) results = [ ] while header . remaining_len > decoder . num_bytes_cons... | Generates a MqttSuback packet given a MqttFixedHeader . This method asserts that header . packet_type is suback . |
54,970 | def decode_body ( cls , header , f ) : assert header . packet_type == MqttControlPacketType . publish dupe = bool ( header . flags & 0x08 ) retain = bool ( header . flags & 0x01 ) qos = ( ( header . flags & 0x06 ) >> 1 ) if qos == 0 and dupe : raise DecodeError ( "Unexpected dupe=True for qos==0 message [MQTT-3.3.1-2].... | Generates a MqttPublish packet given a MqttFixedHeader . This method asserts that header . packet_type is publish . |
54,971 | def decode_body ( cls , header , f ) : assert header . packet_type == MqttControlPacketType . pubrel decoder = mqtt_io . FileDecoder ( mqtt_io . LimitReader ( f , header . remaining_len ) ) packet_id , = decoder . unpack ( mqtt_io . FIELD_U16 ) if header . remaining_len != decoder . num_bytes_consumed : raise DecodeErr... | Generates a MqttPubrel packet given a MqttFixedHeader . This method asserts that header . packet_type is pubrel . |
54,972 | def decode_body ( cls , header , f ) : assert header . packet_type == MqttControlPacketType . unsubscribe decoder = mqtt_io . FileDecoder ( mqtt_io . LimitReader ( f , header . remaining_len ) ) packet_id , = decoder . unpack ( mqtt_io . FIELD_PACKET_ID ) topics = [ ] while header . remaining_len > decoder . num_bytes_... | Generates a MqttUnsubscribe packet given a MqttFixedHeader . This method asserts that header . packet_type is unsubscribe . |
54,973 | def decode_body ( cls , header , f ) : assert header . packet_type == MqttControlPacketType . unsuback decoder = mqtt_io . FileDecoder ( mqtt_io . LimitReader ( f , header . remaining_len ) ) packet_id , = decoder . unpack ( mqtt_io . FIELD_PACKET_ID ) if header . remaining_len != decoder . num_bytes_consumed : raise D... | Generates a MqttUnsuback packet given a MqttFixedHeader . This method asserts that header . packet_type is unsuback . |
54,974 | def decode_body ( cls , header , f ) : assert header . packet_type == MqttControlPacketType . pingreq if header . remaining_len != 0 : raise DecodeError ( 'Extra bytes at end of packet.' ) return 0 , MqttPingreq ( ) | Generates a MqttPingreq packet given a MqttFixedHeader . This method asserts that header . packet_type is pingreq . |
54,975 | def decode_body ( cls , header , f ) : assert header . packet_type == MqttControlPacketType . pingresp if header . remaining_len != 0 : raise DecodeError ( 'Extra bytes at end of packet.' ) return 0 , MqttPingresp ( ) | Generates a MqttPingresp packet given a MqttFixedHeader . This method asserts that header . packet_type is pingresp . |
54,976 | def connect ( self ) : if self . token : self . phab_session = { 'token' : self . token } return req = self . req_session . post ( '%s/api/conduit.connect' % self . host , data = { 'params' : json . dumps ( self . connect_params ) , 'output' : 'json' , '__conduit__' : True , } ) result = req . json ( ) [ 'result' ] sel... | Sets up your Phabricator session it s not necessary to call this directly |
54,977 | def install ( force = False ) : ret , git_dir , _ = run ( "git rev-parse --show-toplevel" ) if ret != 0 : click . echo ( "ERROR: Please run from within a GIT repository." , file = sys . stderr ) raise click . Abort git_dir = git_dir [ 0 ] hooks_dir = os . path . join ( git_dir , HOOK_PATH ) for hook in HOOKS : hook_pat... | Install git hooks . |
54,978 | def uninstall ( ) : ret , git_dir , _ = run ( "git rev-parse --show-toplevel" ) if ret != 0 : click . echo ( "ERROR: Please run from within a GIT repository." , file = sys . stderr ) raise click . Abort git_dir = git_dir [ 0 ] hooks_dir = os . path . join ( git_dir , HOOK_PATH ) for hook in HOOKS : hook_path = os . pat... | Uninstall git hooks . |
54,979 | def setup_logger ( ) : logger = logging . getLogger ( 'dockerstache' ) logger . setLevel ( logging . INFO ) handler = logging . StreamHandler ( stream = sys . stdout ) handler . setLevel ( logging . INFO ) logger . addHandler ( handler ) return logger | setup basic logger |
54,980 | def named_any ( name ) : assert name , 'Empty module name' names = name . split ( '.' ) topLevelPackage = None moduleNames = names [ : ] while not topLevelPackage : if moduleNames : trialname = '.' . join ( moduleNames ) try : topLevelPackage = __import__ ( trialname ) except Exception , ex : moduleNames . pop ( ) else... | Retrieve a Python object by its fully qualified name from the global Python module namespace . The first part of the name that describes a module will be discovered and imported . Each subsequent part of the name is treated as the name of an attribute of the object specified by all of the name which came before it . |
54,981 | def for_name ( modpath , classname ) : module = __import__ ( modpath , fromlist = [ classname ] ) classobj = getattr ( module , classname ) return classobj ( ) | Returns a class of classname from module modname . |
54,982 | def _convert ( self , val ) : if isinstance ( val , dict ) and not isinstance ( val , DotDict ) : return DotDict ( val ) , True elif isinstance ( val , list ) and not isinstance ( val , DotList ) : return DotList ( val ) , True return val , False | Convert the type if necessary and return if a conversion happened . |
54,983 | def to_json ( self ) : obj = { "vertices" : [ { "id" : vertex . id , "annotation" : vertex . annotation , } for vertex in self . vertices ] , "edges" : [ { "id" : edge . id , "annotation" : edge . annotation , "head" : edge . head , "tail" : edge . tail , } for edge in self . _edges ] , } return six . text_type ( json ... | Convert to a JSON string . |
54,984 | def from_json ( cls , json_graph ) : obj = json . loads ( json_graph ) vertices = [ AnnotatedVertex ( id = vertex [ "id" ] , annotation = vertex [ "annotation" ] , ) for vertex in obj [ "vertices" ] ] edges = [ AnnotatedEdge ( id = edge [ "id" ] , annotation = edge [ "annotation" ] , head = edge [ "head" ] , tail = edg... | Reconstruct the graph from a graph exported to JSON . |
54,985 | def export_json ( self , filename ) : json_graph = self . to_json ( ) with open ( filename , 'wb' ) as f : f . write ( json_graph . encode ( 'utf-8' ) ) | Export graph in JSON form to the given file . |
54,986 | def import_json ( cls , filename ) : with open ( filename , 'rb' ) as f : json_graph = f . read ( ) . decode ( 'utf-8' ) return cls . from_json ( json_graph ) | Import graph from the given file . The file is expected to contain UTF - 8 encoded JSON data . |
54,987 | def to_dot ( self ) : edge_labels = { edge . id : edge . annotation for edge in self . _edges } edges = [ self . _format_edge ( edge_labels , edge ) for edge in self . _edges ] vertices = [ DOT_VERTEX_TEMPLATE . format ( vertex = vertex . id , label = dot_quote ( vertex . annotation ) , ) for vertex in self . vertices ... | Produce a graph in DOT format . |
54,988 | def install_brew ( target_path ) : if not os . path . exists ( target_path ) : try : os . makedirs ( target_path ) except OSError : logger . warn ( "Unable to create directory %s for brew." % target_path ) logger . warn ( "Skipping..." ) return extract_targz ( HOMEBREW_URL , target_path , remove_common_prefix = True ) | Install brew to the target path |
54,989 | def pass_service ( * names ) : def decorator ( f ) : @ functools . wraps ( f ) def wrapper ( * args , ** kwargs ) : for name in names : kwargs [ name ] = service_proxy ( name ) return f ( * args , ** kwargs ) return wrapper return decorator | Injects a service instance into the kwargs |
54,990 | def get_conn ( ) : if os . environ . get ( 'DEBUG' , False ) or os . environ . get ( 'travis' , False ) : conn = DynamoDBConnection ( host = 'localhost' , port = 8000 , aws_access_key_id = 'TEST' , aws_secret_access_key = 'TEST' , is_secure = False ) else : conn = DynamoDBConnection ( ) return conn | Return a connection to DynamoDB . |
54,991 | def table_schema_call ( self , target , cls ) : index_defs = [ ] for name in cls . index_names ( ) or [ ] : index_defs . append ( GlobalIncludeIndex ( gsi_name ( name ) , parts = [ HashKey ( name ) ] , includes = [ 'value' ] ) ) return target ( cls . get_table_name ( ) , connection = get_conn ( ) , schema = [ HashKey (... | Perform a table schema call . |
54,992 | def thread ( self ) : log . info ( '@{}.thread starting' . format ( self . __class__ . __name__ ) ) thread = threading . Thread ( target = thread_wrapper ( self . consume ) , args = ( ) ) thread . daemon = True thread . start ( ) | Start a thread for this consumer . |
54,993 | def _parse_multifile ( self , desired_type : Type [ T ] , obj : PersistedObject , parsing_plan_for_children : Dict [ str , ParsingPlan ] , logger : Logger , options : Dict [ str , Dict [ str , Any ] ] ) -> T : pass | First parse all children from the parsing plan then calls _build_object_from_parsed_children |
54,994 | def execute ( self , logger : Logger , options : Dict [ str , Dict [ str , Any ] ] ) -> T : in_root_call = False if logger is not None : if not hasattr ( _BaseParsingPlan . thrd_locals , 'flag_exec' ) or _BaseParsingPlan . thrd_locals . flag_exec == 0 : logger . debug ( 'Executing Parsing Plan for [{location}]' '' . fo... | Overrides the parent method to add log messages . |
54,995 | def _execute ( self , logger : Logger , options : Dict [ str , Dict [ str , Any ] ] ) -> T : if isinstance ( self . parser , _BaseParser ) : if ( not self . is_singlefile ) and self . parser . supports_multifile ( ) : return self . parser . _parse_multifile ( self . obj_type , self . obj_on_fs_to_parse , self . _get_ch... | Implementation of the parent class method . Checks that self . parser is a _BaseParser and calls the appropriate parsing method . |
54,996 | def create_parsing_plan ( self , desired_type : Type [ T ] , filesystem_object : PersistedObject , logger : Logger , _main_call : bool = True ) : in_root_call = False if _main_call and ( not hasattr ( AnyParser . thrd_locals , 'flag_init' ) or AnyParser . thrd_locals . flag_init == 0 ) : logger . debug ( 'Building a pa... | Implements the abstract parent method by using the recursive parsing plan impl . Subclasses wishing to produce their own parsing plans should rather override _create_parsing_plan in order to benefit from this same log msg . |
54,997 | def _create_parsing_plan ( self , desired_type : Type [ T ] , filesystem_object : PersistedObject , logger : Logger , log_only_last : bool = False ) : logger . debug ( '(B) ' + get_parsing_plan_log_str ( filesystem_object , desired_type , log_only_last = log_only_last , parser = self ) ) return AnyParser . _RecursivePa... | Adds a log message and creates a recursive parsing plan . |
54,998 | def _get_parsing_plan_for_multifile_children ( self , obj_on_fs : PersistedObject , desired_type : Type [ T ] , logger : Logger ) -> Dict [ str , ParsingPlan [ T ] ] : pass | This method is called by the _RecursiveParsingPlan when created . Implementing classes should return a dictionary containing a ParsingPlan for each child they plan to parse using this framework . Note that for the files that will be parsed using a parsing library it is not necessary to return a ParsingPlan . |
54,999 | def _parse_singlefile ( self , desired_type : Type [ T ] , file_path : str , encoding : str , logger : Logger , options : Dict [ str , Dict [ str , Any ] ] ) -> T : opts = get_options_for_id ( options , self . get_id_for_options ( ) ) if self . _streaming_mode : file_stream = None try : file_stream = open ( file_path ,... | Relies on the inner parsing function to parse the file . If _streaming_mode is True the file will be opened and closed by this method . Otherwise the parsing function will be responsible to open and close . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.