idx int64 0 63k | question stringlengths 53 5.28k | target stringlengths 5 805 |
|---|---|---|
14,900 | def run ( self ) : input = self . _consume ( ) put_item = self . _que_out . put try : if input is None : res = self . _callable ( * self . _args , ** self . _kwargs ) else : res = self . _callable ( input , * self . _args , ** self . _kwargs ) if res != None : for item in res : put_item ( item ) except Exception as e :... | Execute the task on all the input and send the needed number of EXIT at the end |
14,901 | def setup ( self , workers = 1 , qsize = 0 ) : if workers <= 0 : raise ValueError ( "workers have to be greater then zero" ) if qsize < 0 : raise ValueError ( "qsize have to be greater or equal zero" ) self . qsize = qsize self . workers = workers return self | Setup the pool parameters like number of workers and output queue size |
14,902 | def processes ( self ) : if self . _processes is None : self . _processes = [ ] for p in range ( self . workers ) : t = Task ( self . _target , self . _args , self . _kwargs ) t . name = "%s-%d" % ( self . target_name , p ) self . _processes . append ( t ) return self . _processes | Initialise and return the list of processes associated with this pool |
14,903 | def results ( self ) : tt = None for i , tf in enumerate ( self [ : - 1 ] ) : tt = self [ i + 1 ] q = Queue ( tf . qsize ) tf . set_out ( q , tt . workers ) tt . set_in ( q , tf . workers ) if tt is None : tt = self [ 0 ] q = Queue ( tt . qsize ) err_q = Queue ( ) tt . set_out ( q , 1 ) for t in self : t . set_err ( er... | Start all the tasks and return data on an iterator |
14,904 | def office_content ( self , election_day , office ) : from electionnight . models import PageType office_type = ContentType . objects . get_for_model ( office ) page_type = PageType . objects . get ( model_type = office_type , election_day = election_day , division_level = office . division . level , ) page_content = s... | Return serialized content for an office page . |
14,905 | def body_content ( self , election_day , body , division = None ) : from electionnight . models import PageType body_type = ContentType . objects . get_for_model ( body ) page_type = PageType . objects . get ( model_type = body_type , election_day = election_day , body = body , jurisdiction = body . jurisdiction , divi... | Return serialized content for a body page . |
14,906 | def division_content ( self , election_day , division , special = False ) : from electionnight . models import PageType division_type = ContentType . objects . get_for_model ( division ) page_type = PageType . objects . get ( model_type = division_type , election_day = election_day , division_level = division . level ,... | Return serialized content for a division page . |
14,907 | def site_content ( self , election_day ) : from electionnight . models import PageType page_type = PageType . objects . get ( model_type = ContentType . objects . get ( app_label = "election" , model = "electionday" ) , election_day = election_day , ) site_content = self . get ( content_type = ContentType . objects . g... | Site content represents content for the entire site on a given election day . |
14,908 | def get_interesting_members ( base_class , cls ) : base_members = dir ( base_class ) predicate = inspect . ismethod if _py2 else inspect . isfunction all_members = inspect . getmembers ( cls , predicate = predicate ) return [ member for member in all_members if not member [ 0 ] in base_members and ( ( hasattr ( member ... | Returns a list of methods that can be routed to |
14,909 | def initialize ( self , value = ( ) ) : if value == ( ) : try : return self . default ( ) except TypeError : return self . default else : return self . clean ( value ) | \ initialize returns a cleaned value or the default raising ValueErrors as necessary . |
14,910 | def clean ( self , value ) : if not isinstance ( value , self . t ) : value = self . t ( value ) if not self . allow_negative and value < 0 : raise ValueError ( 'value was negative' ) if not self . allow_positive and value > 0 : raise ValueError ( 'values was positive' ) return value | clean a value converting and performing bounds checking |
14,911 | def r12_serial_port ( port ) : return serial . Serial ( port , baudrate = BAUD_RATE , parity = PARITY , stopbits = STOP_BITS , bytesize = BYTE_SIZE ) | Create a serial connect to the arm . |
14,912 | def search_for_port ( port_glob , req , expected_res ) : if usb . core . find ( idVendor = 0x0403 , idProduct = 0x6001 ) is None : return None ports = glob . glob ( port_glob ) if len ( ports ) == 0 : return None for port in ports : with r12_serial_port ( port ) as ser : if not ser . isOpen ( ) : ser . open ( ) if sys ... | Find the serial port the arm is connected to . |
14,913 | def connect ( self , port = None ) : if port is None : self . port = search_for_port ( '/dev/ttyUSB*' , 'ROBOFORTH\r\n' , 'ROBOFORTH' ) else : self . port = port if self . port is None : raise ArmException ( 'ST Robotics connection not found.' ) self . ser = r12_serial_port ( port ) if not self . ser . isOpen ( ) : sel... | Open a serial connection to the arm . |
14,914 | def write ( self , text ) : if sys . version_info [ 0 ] == 2 : text_bytes = str ( text . upper ( ) + '\r\n' ) . encode ( 'utf-8' ) else : text_bytes = bytes ( text . upper ( ) + '\r\n' , 'utf-8' ) self . ser . write ( text_bytes ) | Write text out to the arm . |
14,915 | def read ( self , timeout = READ_TIMEOUT , raw = False ) : time . sleep ( READ_SLEEP_TIME ) raw_out = self . ser . read ( self . ser . in_waiting ) out = raw_out . decode ( OUTPUT_ENCODING ) time_waiting = 0 while len ( out ) == 0 or ending_in ( out . strip ( OUTPUT_STRIP_CHARS ) , RESPONSE_END_WORDS ) is None : time .... | Read data from the arm . Data is returned as a latin_1 encoded string or raw bytes if raw is True . |
14,916 | def dump ( self , raw = False ) : raw_out = self . ser . read ( self . ser . in_waiting ) if raw : return raw_out return raw_out . decode ( OUTPUT_ENCODING ) | Dump all output currently in the arm s output queue . |
14,917 | def get_info ( self ) : return { 'Connected' : self . is_connected ( ) , 'Port' : self . port , 'Bytes Waiting' : self . ser . in_waiting if self . ser else 0 } | Returns status of the robot arm . |
14,918 | async def get_data ( self ) : try : async with async_timeout . timeout ( 5 , loop = self . _loop ) : response = await self . _session . get ( self . base_url ) _LOGGER . info ( "Response from OpenSenseMap API: %s" , response . status ) self . data = await response . json ( ) _LOGGER . debug ( self . data ) except ( asy... | Get details of OpenSenseMap station . |
14,919 | def get_value ( self , key ) : for title in _TITLES . get ( key , ( ) ) + ( key , ) : try : value = [ entry [ 'lastMeasurement' ] [ 'value' ] for entry in self . data [ 'sensors' ] if entry [ 'title' ] == title ] [ 0 ] return value except IndexError : pass return None | Extract a value for a given key . |
14,920 | def cmd ( send , msg , args ) : if not args [ 'config' ] [ 'feature' ] . getboolean ( 'hooks' ) : send ( "Hooks are disabled, and this command depends on hooks. Please contact the bot admin(s)." ) return if args [ 'type' ] == 'privmsg' : send ( "Note-passing should be done in public." ) return try : nick , note = msg .... | Leaves a note for a user or users . |
14,921 | def from_frame ( klass , frame , connection ) : event = frame . headers [ 'new' ] data = json . loads ( frame . body ) info = data [ 'info' ] build = Build . fromDict ( info ) build . connection = connection return klass ( build , event ) | Create a new BuildStateChange event from a Stompest Frame . |
14,922 | def from_frame ( klass , frame , connection ) : event = frame . headers [ 'new' ] data = json . loads ( frame . body ) info = data [ 'info' ] task = Task . fromDict ( info ) task . connection = connection return klass ( task , event ) | Create a new TaskStateChange event from a Stompest Frame . |
14,923 | def cmd ( send , msg , args ) : if not msg : send ( "Ping what?" ) return channel = args [ 'target' ] if args [ 'target' ] != 'private' else args [ 'nick' ] if "." not in msg and ":" not in msg : targets = set ( msg . split ( ) ) if len ( targets ) > 3 : send ( "Please specify three or fewer people to ping." ) return f... | Ping something . |
14,924 | def execution_duration ( self ) : duration = None if self . execution_start and self . execution_end : delta = self . execution_end - self . execution_start duration = delta . total_seconds ( ) return duration | Returns total BMDS execution time in seconds . |
14,925 | def get_exe_path ( cls ) : return os . path . abspath ( os . path . join ( ROOT , cls . bmds_version_dir , cls . exe + ".exe" ) ) | Return the full path to the executable . |
14,926 | def plot ( self ) : fig = self . dataset . plot ( ) ax = fig . gca ( ) ax . set_title ( "{}\n{}, {}" . format ( self . dataset . _get_dataset_name ( ) , self . name , self . get_bmr_text ( ) ) ) if self . has_successfully_executed : self . _set_x_range ( ax ) ax . plot ( self . _xs , self . get_ys ( self . _xs ) , labe... | After model execution print the dataset curve - fit BMD and BMDL . |
14,927 | def write_dfile ( self ) : f_in = self . tempfiles . get_tempfile ( prefix = "bmds-" , suffix = ".(d)" ) with open ( f_in , "w" ) as f : f . write ( self . as_dfile ( ) ) return f_in | Write the generated d_file to a temporary file . |
14,928 | def to_dict ( self , model_index ) : return dict ( name = self . name , model_index = model_index , model_name = self . model_name , model_version = self . version , has_output = self . output_created , dfile = self . as_dfile ( ) , execution_halted = self . execution_halted , stdout = self . stdout , stderr = self . s... | Return a summary of the model in a dictionary format for serialization . |
14,929 | def merge_config ( d1 , d2 ) : result = deepcopy ( d1 ) elements = deque ( ) elements . append ( ( result , d2 ) ) while elements : old , new = elements . popleft ( ) new = OrderedDict ( [ ( k . lower ( ) , ( k , v ) ) for k , v in new . items ( ) ] ) visited_keys = [ ] for k , old_value in old . items ( ) : klow = k .... | Merges to config dicts . Key values are case insensitive for merging but the value of d1 is remembered . |
14,930 | def set_if_none ( user_config , config , key , value ) : keys = key . split ( '.' ) for k in keys [ : - 1 ] : try : user_config = user_config [ k ] except KeyError : user_config = { } config = config [ k ] key = keys [ - 1 ] if key not in user_config and not config [ key ] : config [ key ] = value | If the value of the key in is None and doesn t exist on the user config set it to a different value |
14,931 | def set_admin ( msg , handler ) : if handler . config [ 'feature' ] [ 'servicestype' ] == "ircservices" : match = re . match ( "STATUS (.*) ([0-3])" , msg ) elif handler . config [ 'feature' ] [ 'servicestype' ] == "atheme" : match = re . match ( "(.*) ACC ([0-3])" , msg ) if match : status = int ( match . group ( 2 ) ... | Handle admin verification responses from NickServ . |
14,932 | def is_tuple ( obj , len_ = None ) : if not isinstance ( obj , tuple ) : return False if len_ is None : return True if not isinstance ( len_ , Integral ) : raise TypeError ( "length must be a number (got %s instead)" % type ( len_ ) . __name__ ) if len_ < 0 : raise ValueError ( "length must be positive (got %s instead)... | Checks whether given object is a tuple . |
14,933 | def select ( indices , from_ , strict = False ) : ensure_iterable ( indices ) ensure_sequence ( from_ ) if strict : return from_ . __class__ ( from_ [ index ] for index in indices ) else : len_ = len ( from_ ) return from_ . __class__ ( from_ [ index ] for index in indices if 0 <= index < len_ ) | Selects a subsequence of given tuple including only specified indices . |
14,934 | def omit ( indices , from_ , strict = False ) : from taipan . collections . sets import remove_subset ensure_iterable ( indices ) ensure_sequence ( from_ ) if strict : remaining_indices = set ( xrange ( len ( from_ ) ) ) try : remove_subset ( remaining_indices , indices ) except KeyError as e : raise IndexError ( int (... | Returns a subsequence from given tuple omitting specified indices . |
14,935 | def _describe_type ( arg ) : if isinstance ( arg , tuple ) : return "tuple of length %s" % len ( arg ) else : return type ( arg ) . __name__ | Describe given argument including length if it s a tuple . |
14,936 | def _create_image_url ( self , file_path , type_ , target_size ) : if self . image_config is None : logger . warning ( 'no image configuration available' ) return return '' . join ( [ self . image_config [ 'secure_base_url' ] , self . _image_size ( self . image_config , type_ , target_size ) , file_path , ] ) | The the closest available size for specified image type . |
14,937 | def from_json ( cls , json , image_config = None ) : cls . image_config = image_config return cls ( ** { attr : json . get ( attr if key is None else key ) for attr , key in cls . JSON_MAPPING . items ( ) } ) | Create a model instance |
14,938 | def _image_size ( image_config , type_ , target_size ) : return min ( image_config [ '{}_sizes' . format ( type_ ) ] , key = lambda size : ( abs ( target_size - int ( size [ 1 : ] ) ) if size . startswith ( 'w' ) or size . startswith ( 'h' ) else 999 ) , ) | Find the closest available size for specified image type . |
14,939 | def getallgroups ( arr , k = - 1 ) : if k < 0 : k = len ( arr ) return itertools . chain . from_iterable ( itertools . combinations ( set ( arr ) , j ) for j in range ( 1 , k + 1 ) ) | returns all the subset of |
14,940 | def open_get_line ( filename , limit = - 1 , ** kwargs ) : allowed_keys_for_get_line = { 'sep' , 'pw_filter' , 'errors' } for k in list ( kwargs . keys ( ) ) : if k not in allowed_keys_for_get_line : del kwargs [ k ] print ( "After filtering: {}" . format ( kwargs ) ) with open_ ( filename , 'rt' ) as f : for w , c in ... | Opens the password file named |
14,941 | def stop_workers ( self , clean ) : with executor_lock : self . executor . shutdown ( clean ) del self . executor with self . worker_lock : if clean : self . pool . close ( ) else : self . pool . terminate ( ) self . pool . join ( ) del self . pool for x in self . events . values ( ) : x . event . cancel ( ) self . eve... | Stop workers and deferred events . |
14,942 | def extract_translations ( self , string ) : tree = ast . parse ( string ) visitor = TransVisitor ( self . tranz_functions , self . tranzchoice_functions ) visitor . visit ( tree ) return visitor . translations | Extract messages from Python string . |
14,943 | def cmd ( send , msg , args ) : if not msg : send ( "What are you trying to get to?" ) return nick = args [ 'nick' ] isup = get ( "http://isup.me/%s" % msg ) . text if "looks down from here" in isup : send ( "%s: %s is down" % ( nick , msg ) ) elif "like a site on the interwho" in isup : send ( "%s: %s is not a valid u... | Checks if a website is up . |
14,944 | def create_required_directories ( self ) : required = ( self . CACHE_DIR , self . LOG_DIR , self . OUTPUT_DIR , self . ENGINEER . JINJA_CACHE_DIR , ) for folder in required : ensure_exists ( folder , assume_dirs = True ) | Creates any directories required for Engineer to function if they don t already exist . |
14,945 | def cmd ( send , msg , args ) : if 'livedoc' in args [ 'name' ] : url = 'http://livedoc.tjhsst.edu/w' name = 'livedoc' else : url = 'http://en.wikipedia.org/w' name = 'wikipedia' if not msg : msg = get_rand ( url ) params = { 'format' : 'json' , 'action' : 'query' , 'list' : 'search' , 'srlimit' : '1' , 'srsearch' : ms... | Returns the first wikipedia result for the argument . |
14,946 | def parse_devices ( self ) : devices = [ ] for device in self . _channel_dict [ "devices" ] : devices . append ( Device ( device , self . _is_sixteen_bit , self . _ignore_list ) ) return devices | Creates an array of Device objects from the channel |
14,947 | def update ( self ) : for device in self . devices : device . update ( ) for i in range ( len ( self . _channel_dict [ "devices" ] ) ) : device_dict = self . _channel_dict [ "devices" ] [ i ] for device in self . _devices : if device . name == device_dict [ "common.ALLTYPES_NAME" ] : self . _channel_dict [ "devices" ] ... | Updates the dictionary of the channel |
14,948 | def open_config ( self , type = "shared" ) : try : output = self . dev . rpc ( "<open-configuration><{0}/></open-configuration>" . format ( type ) ) except Exception as err : print err | Opens the configuration of the currently connected device |
14,949 | def close_config ( self ) : try : self . dev . rpc . close_configuration ( ) except Exception as err : print err | Closes the exiting opened configuration |
14,950 | def commit_config ( self ) : try : self . dev . rpc . commit_configuration ( ) except Exception as err : print err | Commits exiting configuration |
14,951 | def commit_and_quit ( self ) : try : self . dev . rpc . commit_configuration ( ) self . close_config ( ) except Exception as err : print err | Commits and closes the currently open configration . Saves a step by not needing to manually close the config . |
14,952 | def load_local_plugin ( name ) : try : module_name = '.' . join ( name . split ( '.' ) [ : - 1 ] ) module_obj = importlib . import_module ( name = module_name ) obj = getattr ( module_obj , name . split ( '.' ) [ - 1 ] ) return obj except ( ImportError , AttributeError , ValueError ) as e : raise PluginNotFoundError ( ... | Import a local plugin accessible through Python path . |
14,953 | def load_installed_plugins ( ) : providers = { } checkers = { } for entry_point in pkg_resources . iter_entry_points ( group = 'archan' ) : obj = entry_point . load ( ) if issubclass ( obj , Provider ) : providers [ entry_point . name ] = obj elif issubclass ( obj , Checker ) : checkers [ entry_point . name ] = obj ret... | Search and load every installed plugin through entry points . |
14,954 | def from_file ( path ) : with open ( path ) as stream : obj = yaml . safe_load ( stream ) Config . lint ( obj ) return Config ( config_dict = obj ) | Return a Config instance by reading a configuration file . |
14,955 | def find ( ) : names = ( 'archan.yml' , 'archan.yaml' , '.archan.yml' , '.archan.yaml' ) current_dir = os . getcwd ( ) configconfig_file = os . path . join ( current_dir , '.configconfig' ) default_config_dir = os . path . join ( current_dir , 'config' ) if os . path . isfile ( configconfig_file ) : logger . debug ( 'R... | Find the configuration file if any . |
14,956 | def inflate_nd_checker ( identifier , definition ) : if isinstance ( definition , bool ) : return Checker ( name = identifier , passes = definition ) elif isinstance ( definition , dict ) : return Checker ( definition . pop ( 'name' , identifier ) , ** definition ) else : raise ValueError ( '%s type is not supported fo... | Inflate a no - data checker from a basic definition . |
14,957 | def get_plugin ( self , identifier , cls = None ) : if ( ( cls is None or cls == 'provider' ) and identifier in self . available_providers ) : return self . available_providers [ identifier ] elif ( ( cls is None or cls == 'checker' ) and identifier in self . available_checkers ) : return self . available_checkers [ id... | Return the plugin corresponding to the given identifier and type . |
14,958 | def provider_from_dict ( self , dct ) : provider_identifier = list ( dct . keys ( ) ) [ 0 ] provider_class = self . get_provider ( provider_identifier ) if provider_class : return provider_class ( ** dct [ provider_identifier ] ) return None | Return a provider instance from a dict object . |
14,959 | def checker_from_dict ( self , dct ) : checker_identifier = list ( dct . keys ( ) ) [ 0 ] checker_class = self . get_checker ( checker_identifier ) if checker_class : return checker_class ( ** dct [ checker_identifier ] ) return None | Return a checker instance from a dict object . |
14,960 | def inflate_plugin ( self , identifier , definition = None , cls = None ) : cls = self . get_plugin ( identifier , cls ) return cls ( ** definition or { } ) | Inflate a plugin thanks to it s identifier definition and class . |
14,961 | def inflate_analysis_group ( self , identifier , definition ) : providers_definition = definition . pop ( 'providers' , None ) checkers_definition = definition . pop ( 'checkers' , None ) analysis_group = AnalysisGroup ( ) try : first_plugin = self . inflate_plugin ( identifier , definition ) if isinstance ( first_plug... | Inflate a whole analysis group . |
14,962 | def print_plugins ( self ) : width = console_width ( ) line = Style . BRIGHT + '=' * width + '\n' middle = int ( width / 2 ) if self . available_providers : print ( line + ' ' * middle + 'PROVIDERS' ) for provider in sorted ( self . available_providers . values ( ) , key = lambda x : x . identifier ) : provider ( ) . p... | Print the available plugins . |
14,963 | def cmd ( send , msg , args ) : match = re . match ( r'--(.+?)\b' , msg ) randtype = 'hex' if match : if match . group ( 1 ) == 'int' : randtype = 'int' else : send ( "Invalid Flag." ) return if randtype == 'hex' : send ( hex ( getrandbits ( 50 ) ) ) else : maxlen = 1000000000 msg = msg . split ( ) if len ( msg ) == 2 ... | For when you don t have enough randomness in your life . |
14,964 | def split ( X , Y , question ) : true_X , false_X = [ ] , [ ] true_Y , false_Y = [ ] , [ ] for x , y in zip ( X , Y ) : if question . match ( x ) : true_X . append ( x ) true_Y . append ( y ) else : false_X . append ( x ) false_Y . append ( y ) return ( np . array ( true_X ) , np . array ( false_X ) , np . array ( true... | Partitions a dataset . |
14,965 | def build_tree ( X , y , criterion , max_depth , current_depth = 1 ) : if max_depth >= 0 and current_depth >= max_depth : return Leaf ( y ) gain , question = find_best_question ( X , y , criterion ) if gain == 0 : return Leaf ( y ) true_X , false_X , true_y , false_y = split ( X , y , question ) true_branch = build_tre... | Builds the decision tree . |
14,966 | def print_tree ( root , space = ' ' ) : if isinstance ( root , Leaf ) : print ( space + "Prediction: " + str ( root . most_frequent ) ) return print ( space + str ( root . question ) ) print ( space + " ) print_tree ( root . true_branch , space + ' ' ) print ( space + " ) print_tree ( root . false_branch , space + ' ... | Prints the Decision Tree in a pretty way . |
14,967 | def find_element ( driver , elem_path , by = CSS , timeout = TIMEOUT , poll_frequency = 0.5 ) : wait = WebDriverWait ( driver , timeout , poll_frequency ) return wait . until ( EC . presence_of_element_located ( ( by , elem_path ) ) ) | Find and return an element once located |
14,968 | def find_elements ( driver , elem_path , by = CSS , timeout = TIMEOUT , poll_frequency = 0.5 ) : wait = WebDriverWait ( driver , timeout , poll_frequency ) return wait . until ( EC . presence_of_all_elements_located ( ( by , elem_path ) ) ) | Find and return all elements once located |
14,969 | def find_write ( driver , elem_path , write_str , clear_first = True , send_enter = False , by = CSS , timeout = TIMEOUT , poll_frequency = 0.5 ) : elem = find_element ( driver , elem_path = elem_path , by = by , timeout = timeout , poll_frequency = poll_frequency ) if clear_first : elem . clear ( ) elem . send_keys ( ... | Find a writable element and write to it |
14,970 | def cmd ( send , msg , args ) : if not msg : msg = gen_word ( ) send ( gen_intensify ( msg ) ) | Intensifies text . |
14,971 | def fetch_states ( self , elections ) : states = [ ] for election in elections : if election . division . level . name == DivisionLevel . DISTRICT : division = election . division . parent else : division = election . division states . append ( division ) return sorted ( list ( set ( states ) ) , key = lambda s : s . l... | Returns the unique divisions for all elections on an election day . |
14,972 | def get_name ( self , type_ , id_ ) : cachefile = self . filename ( type_ , id_ ) try : with open ( cachefile , 'r' ) as f : return f . read ( ) except ( OSError , IOError ) as e : if e . errno != errno . ENOENT : raise | Read a cached name if available . |
14,973 | def put_name ( self , type_ , id_ , name ) : cachefile = self . filename ( type_ , id_ ) dirname = os . path . dirname ( cachefile ) try : os . makedirs ( dirname ) except OSError as e : if e . errno != errno . EEXIST : raise with open ( cachefile , 'w' ) as f : f . write ( name ) | Write a cached name to disk . |
14,974 | def get_or_load_name ( self , type_ , id_ , method ) : name = self . get_name ( type_ , id_ ) if name is not None : defer . returnValue ( name ) instance = yield method ( id_ ) if instance is None : defer . returnValue ( None ) self . put_name ( type_ , id_ , instance . name ) defer . returnValue ( instance . name ) | read - through cache for a type of object s name . |
14,975 | def call ( self , name , * args , ** kwargs ) : if name in ( 'getTaskInfo' , 'getTaskDescendants' ) : kwargs [ 'request' ] = True if kwargs : kwargs [ '__starstar' ] = True args = args + ( kwargs , ) payload = { 'methodName' : name , 'params' : args } self . calls . append ( payload ) | Add a new call to the list that we will submit to the server . |
14,976 | def _multicall_callback ( self , values , calls ) : result = KojiMultiCallIterator ( values ) result . connection = self . connection result . calls = calls return result | Fires when we get information back from the XML - RPC server . |
14,977 | def time_ago ( dt ) : now = datetime . datetime . now ( ) return humanize . naturaltime ( now - dt ) | Return the current time ago |
14,978 | def cmd ( send , msg , args ) : if not msg : user = choice ( get_users ( args ) ) else : user = msg send ( gen_insult ( user ) ) | Insults a user . |
14,979 | def needed ( name , required ) : return [ relative_field ( r , name ) if r and startswith_field ( r , name ) else None for r in required ] | RETURN SUBSET IF name IN REQUIRED |
14,980 | def _match_data_to_parameter ( cls , data ) : in_value = data [ "in" ] for cls in [ QueryParameter , HeaderParameter , FormDataParameter , PathParameter , BodyParameter ] : if in_value == cls . IN : return cls return None | find the appropriate parameter for a parameter field |
14,981 | def cmd ( send , msg , args ) : if not msg : result = subprocess . run ( [ 'eix' , '-c' ] , env = { 'EIX_LIMIT' : '0' , 'HOME' : os . environ [ 'HOME' ] } , stdout = subprocess . PIPE , universal_newlines = True ) if result . returncode : send ( "eix what?" ) return send ( choice ( result . stdout . splitlines ( ) ) ) ... | Runs eix with the given arguments . |
14,982 | def to_str ( number ) : states = globals ( ) for name , value in states . items ( ) : if number == value and name . isalpha ( ) and name . isupper ( ) : return name return '(unknown state %d)' % number | Convert a task state ID number to a string . |
14,983 | def to_json ( self , filename , indent = 2 ) : d = self . to_dicts ( ) if hasattr ( filename , "write" ) : json . dump ( d , filename , indent = indent ) elif isinstance ( filename , string_types ) : with open ( os . path . expanduser ( filename ) , "w" ) as f : json . dump ( d , f , indent = indent ) else : raise Valu... | Return a JSON string of all model inputs and outputs . |
14,984 | def to_df ( self , recommended_only = False , include_io = True ) : od = BMDS . _df_ordered_dict ( include_io ) [ session . _add_to_to_ordered_dict ( od , i , recommended_only ) for i , session in enumerate ( self ) ] return pd . DataFrame ( od ) | Return a pandas DataFrame for each model and dataset . |
14,985 | def to_csv ( self , filename , delimiter = "," , recommended_only = False , include_io = True ) : df = self . to_df ( recommended_only , include_io ) df . to_csv ( filename , index = False , sep = delimiter ) | Return a CSV for each model and dataset . |
14,986 | def to_excel ( self , filename , recommended_only = False , include_io = True ) : df = self . to_df ( recommended_only , include_io ) if isinstance ( filename , string_types ) : filename = os . path . expanduser ( filename ) df . to_excel ( filename , index = False ) | Return an Excel file for each model and dataset . |
14,987 | def to_docx ( self , filename = None , input_dataset = True , summary_table = True , recommendation_details = True , recommended_model = True , all_models = False , ) : rep = Reporter ( ) for model in self : rep . add_session ( model , input_dataset , summary_table , recommendation_details , recommended_model , all_mod... | Write batch sessions to a Word file . |
14,988 | def save_plots ( self , directory , format = "png" , recommended_only = False ) : for i , session in enumerate ( self ) : session . save_plots ( directory , prefix = str ( i ) , format = format , recommended_only = recommended_only ) | Save images of dose - response curve - fits for each model . |
14,989 | def load_messages ( self , directory , catalogue ) : if not os . path . isdir ( directory ) : raise ValueError ( "{0} is not a directory" . format ( directory ) ) for format , loader in list ( self . loaders . items ( ) ) : extension = "{0}.{1}" . format ( catalogue . locale , format ) files = find_files ( directory , ... | Loads translation found in a directory . |
14,990 | def disable_backup ( self ) : for dumper in list ( self . dumpers . values ( ) ) : dumper . set_backup ( False ) | Disables dumper backup . |
14,991 | def write_translations ( self , catalogue , format , options = { } ) : if format not in self . dumpers : raise ValueError ( 'There is no dumper associated with format "{0}"' . format ( format ) ) dumper = self . dumpers [ format ] if "path" in options and not os . path . isdir ( options [ 'path' ] ) : os . mkdir ( opti... | Writes translation from the catalogue according to the selected format . |
14,992 | def main ( ) : s = rawdata . content . DataFiles ( ) all_ingredients = list ( s . get_collist_by_name ( data_files [ 1 ] [ 'file' ] , data_files [ 1 ] [ 'col' ] ) [ 0 ] ) best_ingred , worst_ingred = find_best_ingredients ( all_ingredients , dinner_guests ) print ( 'best ingred = ' , best_ingred ) print ( 'worst ingre... | script to find a list of recipes for a group of people with specific likes and dislikes . Output of script |
14,993 | def batch ( iterable , n , fillvalue = None ) : ensure_iterable ( iterable ) if not isinstance ( n , Integral ) : raise TypeError ( "invalid number of elements in a batch" ) if not ( n > 0 ) : raise ValueError ( "number of elements in a batch must be positive" ) if fillvalue is None : fillvalue = object ( ) trimmer = l... | Batches the elements of given iterable . |
14,994 | def intertwine ( * iterables ) : iterables = tuple ( imap ( ensure_iterable , iterables ) ) empty = object ( ) return ( item for iterable in izip_longest ( * iterables , fillvalue = empty ) for item in iterable if item is not empty ) | Constructs an iterable which intertwines given iterables . |
14,995 | def iterate ( iterator , n = None ) : ensure_iterable ( iterator ) if n is None : deque ( iterator , maxlen = 0 ) else : next ( islice ( iterator , n , n ) , None ) | Efficiently advances the iterator N times ; by default goes to its end . |
14,996 | def unique ( iterable , key = None ) : ensure_iterable ( iterable ) key = hash if key is None else ensure_callable ( key ) def generator ( ) : seen = set ( ) for elem in iterable : k = key ( elem ) if k not in seen : seen . add ( k ) yield elem return generator ( ) | Removes duplicates from given iterable using given key as criterion . |
14,997 | def breadth_first ( start , expand ) : ensure_callable ( expand ) def generator ( ) : queue = deque ( [ start ] ) while queue : node = queue . popleft ( ) yield node queue . extend ( expand ( node ) ) return generator ( ) | Performs a breadth - first search of a graph - like structure . |
14,998 | def depth_first ( start , descend ) : ensure_callable ( descend ) def generator ( ) : stack = [ start ] while stack : node = stack . pop ( ) yield node stack . extend ( descend ( node ) ) return generator ( ) | Performs a depth - first search of a graph - like structure . |
14,999 | def regex ( regex ) : if not hasattr ( regex , 'pattern' ) : regex = re . compile ( regex ) pattern = regex . pattern flags = regex . flags codes = sre . parse ( pattern ) return _strategy ( codes , Context ( flags = flags ) ) . filter ( regex . match ) | Return strategy that generates strings that match given regex . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.