idx int64 0 63k | question stringlengths 61 4.03k | target stringlengths 6 1.23k |
|---|---|---|
17,200 | def groups_add_moderator ( self , room_id , user_id , ** kwargs ) : return self . __call_api_post ( 'groups.addModerator' , roomId = room_id , userId = user_id , kwargs = kwargs ) | Gives the role of moderator for a user in the current groups . |
17,201 | def groups_remove_moderator ( self , room_id , user_id , ** kwargs ) : return self . __call_api_post ( 'groups.removeModerator' , roomId = room_id , userId = user_id , kwargs = kwargs ) | Removes the role of moderator from a user in the current groups . |
17,202 | def groups_moderators ( self , room_id = None , group = None , ** kwargs ) : if room_id : return self . __call_api_get ( 'groups.moderators' , roomId = room_id , kwargs = kwargs ) elif group : return self . __call_api_get ( 'groups.moderators' , roomName = group , kwargs = kwargs ) else : raise RocketMissingParamException ( 'roomId or group required' ) | Lists all moderators of a group . |
17,203 | def groups_add_owner ( self , room_id , user_id , ** kwargs ) : return self . __call_api_post ( 'groups.addOwner' , roomId = room_id , userId = user_id , kwargs = kwargs ) | Gives the role of owner for a user in the current Group . |
17,204 | def groups_remove_owner ( self , room_id , user_id , ** kwargs ) : return self . __call_api_post ( 'groups.removeOwner' , roomId = room_id , userId = user_id , kwargs = kwargs ) | Removes the role of owner from a user in the current Group . |
17,205 | def groups_unarchive ( self , room_id , ** kwargs ) : return self . __call_api_post ( 'groups.unarchive' , roomId = room_id , kwargs = kwargs ) | Unarchives a private group . |
17,206 | def groups_get_integrations ( self , room_id , ** kwargs ) : return self . __call_api_get ( 'groups.getIntegrations' , roomId = room_id , kwargs = kwargs ) | Retrieves the integrations which the group has |
17,207 | def groups_invite ( self , room_id , user_id , ** kwargs ) : return self . __call_api_post ( 'groups.invite' , roomId = room_id , userId = user_id , kwargs = kwargs ) | Adds a user to the private group . |
17,208 | def groups_kick ( self , room_id , user_id , ** kwargs ) : return self . __call_api_post ( 'groups.kick' , roomId = room_id , userId = user_id , kwargs = kwargs ) | Removes a user from the private group . |
17,209 | def groups_rename ( self , room_id , name , ** kwargs ) : return self . __call_api_post ( 'groups.rename' , roomId = room_id , name = name , kwargs = kwargs ) | Changes the name of the private group . |
17,210 | def groups_set_description ( self , room_id , description , ** kwargs ) : return self . __call_api_post ( 'groups.setDescription' , roomId = room_id , description = description , kwargs = kwargs ) | Sets the description for the private group . |
17,211 | def groups_set_read_only ( self , room_id , read_only , ** kwargs ) : return self . __call_api_post ( 'groups.setReadOnly' , roomId = room_id , readOnly = bool ( read_only ) , kwargs = kwargs ) | Sets whether the group is read only or not . |
17,212 | def groups_set_topic ( self , room_id , topic , ** kwargs ) : return self . __call_api_post ( 'groups.setTopic' , roomId = room_id , topic = topic , kwargs = kwargs ) | Sets the topic for the private group . |
17,213 | def groups_set_type ( self , room_id , a_type , ** kwargs ) : return self . __call_api_post ( 'groups.setType' , roomId = room_id , type = a_type , kwargs = kwargs ) | Sets the type of room this group should be . The type of room this channel should be either c or p . |
17,214 | def groups_delete ( self , room_id = None , group = None , ** kwargs ) : if room_id : return self . __call_api_post ( 'groups.delete' , roomId = room_id , kwargs = kwargs ) elif group : return self . __call_api_post ( 'groups.delete' , roomName = group , kwargs = kwargs ) else : raise RocketMissingParamException ( 'roomId or group required' ) | Delete a private group . |
17,215 | def im_history ( self , room_id , ** kwargs ) : return self . __call_api_get ( 'im.history' , roomId = room_id , kwargs = kwargs ) | Retrieves the history for a private im chat |
17,216 | def im_create ( self , username , ** kwargs ) : return self . __call_api_post ( 'im.create' , username = username , kwargs = kwargs ) | Create a direct message session with another user . |
17,217 | def im_messages_others ( self , room_id , ** kwargs ) : return self . __call_api_get ( 'im.messages.others' , roomId = room_id , kwargs = kwargs ) | Retrieves the messages from any direct message in the server |
17,218 | def im_set_topic ( self , room_id , topic , ** kwargs ) : return self . __call_api_post ( 'im.setTopic' , roomId = room_id , topic = topic , kwargs = kwargs ) | Sets the topic for the direct message |
17,219 | def im_files ( self , room_id = None , user_name = None , ** kwargs ) : if room_id : return self . __call_api_get ( 'im.files' , roomId = room_id , kwargs = kwargs ) elif user_name : return self . __call_api_get ( 'im.files' , username = user_name , kwargs = kwargs ) else : raise RocketMissingParamException ( 'roomId or username required' ) | Retrieves the files from a direct message . |
17,220 | def rooms_upload ( self , rid , file , ** kwargs ) : files = { 'file' : ( os . path . basename ( file ) , open ( file , 'rb' ) , mimetypes . guess_type ( file ) [ 0 ] ) , } return self . __call_api_post ( 'rooms.upload/' + rid , kwargs = kwargs , use_json = False , files = files ) | Post a message with attached file to a dedicated room . |
17,221 | def rooms_clean_history ( self , room_id , latest , oldest , ** kwargs ) : return self . __call_api_post ( 'rooms.cleanHistory' , roomId = room_id , latest = latest , oldest = oldest , kwargs = kwargs ) | Cleans up a room removing messages from the provided time range . |
17,222 | def rooms_favorite ( self , room_id = None , room_name = None , favorite = True ) : if room_id is not None : return self . __call_api_post ( 'rooms.favorite' , roomId = room_id , favorite = favorite ) elif room_name is not None : return self . __call_api_post ( 'rooms.favorite' , roomName = room_name , favorite = favorite ) else : raise RocketMissingParamException ( 'roomId or roomName required' ) | Favorite or unfavorite room . |
17,223 | def rooms_info ( self , room_id = None , room_name = None ) : if room_id is not None : return self . __call_api_get ( 'rooms.info' , roomId = room_id ) elif room_name is not None : return self . __call_api_get ( 'rooms.info' , roomName = room_name ) else : raise RocketMissingParamException ( 'roomId or roomName required' ) | Retrieves the information about the room . |
17,224 | def subscriptions_get_one ( self , room_id , ** kwargs ) : return self . __call_api_get ( 'subscriptions.getOne' , roomId = room_id , kwargs = kwargs ) | Get the subscription by room id . |
17,225 | def subscriptions_unread ( self , room_id , ** kwargs ) : return self . __call_api_post ( 'subscriptions.unread' , roomId = room_id , kwargs = kwargs ) | Mark messages as unread by roomId or from a message |
17,226 | def subscriptions_read ( self , rid , ** kwargs ) : return self . __call_api_post ( 'subscriptions.read' , rid = rid , kwargs = kwargs ) | Mark room as read |
17,227 | def assets_set_asset ( self , asset_name , file , ** kwargs ) : content_type = mimetypes . MimeTypes ( ) . guess_type ( file ) files = { asset_name : ( file , open ( file , 'rb' ) , content_type [ 0 ] , { 'Expires' : '0' } ) , } return self . __call_api_post ( 'assets.setAsset' , kwargs = kwargs , use_json = False , files = files ) | Set an asset image by name . |
17,228 | def find_callback ( args , kw = None ) : 'Return callback whether passed as a last argument or as a keyword' if args and callable ( args [ - 1 ] ) : return args [ - 1 ] , args [ : - 1 ] try : return kw [ 'callback' ] , args except ( KeyError , TypeError ) : return None , args | Return callback whether passed as a last argument or as a keyword |
17,229 | def once ( self , event , callback ) : 'Define a callback to handle the first event emitted by the server' self . _once_events . add ( event ) self . on ( event , callback ) | Define a callback to handle the first event emitted by the server |
17,230 | def off ( self , event ) : 'Remove an event handler' try : self . _once_events . remove ( event ) except KeyError : pass self . _callback_by_event . pop ( event , None ) | Remove an event handler |
17,231 | def wait ( self , seconds = None , ** kw ) : 'Wait in a loop and react to events as defined in the namespaces' self . _heartbeat_thread . hurry ( ) self . _transport . set_timeout ( seconds = 1 ) warning_screen = self . _yield_warning_screen ( seconds ) for elapsed_time in warning_screen : if self . _should_stop_waiting ( ** kw ) : break try : try : self . _process_packets ( ) except TimeoutError : pass except KeyboardInterrupt : self . _close ( ) raise except ConnectionError as e : self . _opened = False try : warning = Exception ( '[connection error] %s' % e ) warning_screen . throw ( warning ) except StopIteration : self . _warn ( warning ) try : namespace = self . get_namespace ( ) namespace . _find_packet_callback ( 'disconnect' ) ( ) except PacketError : pass self . _heartbeat_thread . relax ( ) self . _transport . set_timeout ( ) | Wait in a loop and react to events as defined in the namespaces |
17,232 | def _prepare_to_send_ack ( self , path , ack_id ) : 'Return function that acknowledges the server' return lambda * args : self . _ack ( path , ack_id , * args ) | Return function that acknowledges the server |
17,233 | def rotateX ( self , angle ) : rad = angle * math . pi / 180 cosa = math . cos ( rad ) sina = math . sin ( rad ) y = self . y * cosa - self . z * sina z = self . y * sina + self . z * cosa return Point3D ( self . x , y , z ) | Rotates the point around the X axis by the given angle in degrees . |
17,234 | def animate ( canvas , fn , delay = 1. / 24 , * args , ** kwargs ) : if not IS_PY3 : import locale locale . setlocale ( locale . LC_ALL , "" ) def animation ( stdscr ) : for frame in fn ( * args , ** kwargs ) : for x , y in frame : canvas . set ( x , y ) f = canvas . frame ( ) stdscr . addstr ( 0 , 0 , '{0}\n' . format ( f ) ) stdscr . refresh ( ) if delay : sleep ( delay ) canvas . clear ( ) curses . wrapper ( animation ) | Animation automation function |
17,235 | def set_text ( self , x , y , text ) : col , row = get_pos ( x , y ) for i , c in enumerate ( text ) : self . chars [ row ] [ col + i ] = c | Set text to the given coords . |
17,236 | def get ( self , x , y ) : x = normalize ( x ) y = normalize ( y ) dot_index = pixel_map [ y % 4 ] [ x % 2 ] col , row = get_pos ( x , y ) char = self . chars . get ( row , { } ) . get ( col ) if not char : return False if type ( char ) != int : return True return bool ( char & dot_index ) | Get the state of a pixel . Returns bool . |
17,237 | def forward ( self , step ) : x = self . pos_x + math . cos ( math . radians ( self . rotation ) ) * step y = self . pos_y + math . sin ( math . radians ( self . rotation ) ) * step prev_brush_state = self . brush_on self . brush_on = True self . move ( x , y ) self . brush_on = prev_brush_state | Move the turtle forward . |
17,238 | def move ( self , x , y ) : if self . brush_on : for lx , ly in line ( self . pos_x , self . pos_y , x , y ) : self . set ( lx , ly ) self . pos_x = x self . pos_y = y | Move the turtle to a coordinate . |
17,239 | def URL ( base , path , segments = None , defaults = None ) : url_class = type ( Segments . __name__ , Segments . __bases__ , dict ( Segments . __dict__ ) ) segments = [ ] if segments is None else segments defaults = [ ] if defaults is None else defaults for segment in segments : setattr ( url_class , segment , url_class . _segment ( segment ) ) return url_class ( base , path , segments , defaults ) | URL segment handler capable of getting and setting segments by name . The URL is constructed by joining base path and segments . |
17,240 | def _segment ( cls , segment ) : return property ( fget = lambda x : cls . _get_segment ( x , segment ) , fset = lambda x , v : cls . _set_segment ( x , segment , v ) , ) | Returns a property capable of setting and getting a segment . |
17,241 | def self_if_parameters ( func ) : @ wraps ( func ) def wrapper ( self , * args , ** kwargs ) : result = func ( self , * args , ** kwargs ) if args or kwargs : return self else : return result return wrapper | If any parameter is given the method s binded object is returned after executing the function . Else the function s result is returned . |
17,242 | def items ( self ) : request = get ( str ( self . url ) , headers = { 'User-Agent' : "Magic Browser" , "origin_req_host" : "thepiratebay.se" } ) root = html . fromstring ( request . text ) items = [ self . _build_torrent ( row ) for row in self . _get_torrent_rows ( root ) ] for item in items : yield item | Request URL and parse response . Yield a Torrent for every torrent on page . |
17,243 | def _build_torrent ( self , row ) : cols = row . findall ( './/td' ) [ category , sub_category ] = [ c . text for c in cols [ 0 ] . findall ( './/a' ) ] links = cols [ 1 ] . findall ( './/a' ) title = unicode ( links [ 0 ] . text ) url = self . url . build ( ) . path ( links [ 0 ] . get ( 'href' ) ) magnet_link = links [ 1 ] . get ( 'href' ) try : torrent_link = links [ 2 ] . get ( 'href' ) if not torrent_link . endswith ( '.torrent' ) : torrent_link = None except IndexError : torrent_link = None comments = 0 has_cover = 'No' images = cols [ 1 ] . findall ( './/img' ) for image in images : image_title = image . get ( 'title' ) if image_title is None : continue if "comments" in image_title : comments = int ( image_title . split ( " " ) [ 3 ] ) if "cover" in image_title : has_cover = 'Yes' user_status = "MEMBER" if links [ - 2 ] . get ( 'href' ) . startswith ( "/user/" ) : user_status = links [ - 2 ] . find ( './/img' ) . get ( 'title' ) meta_col = cols [ 1 ] . find ( './/font' ) . text_content ( ) match = self . _meta . match ( meta_col ) created = match . groups ( ) [ 0 ] . replace ( '\xa0' , ' ' ) size = match . groups ( ) [ 1 ] . replace ( '\xa0' , ' ' ) user = match . groups ( ) [ 2 ] seeders = int ( cols [ 2 ] . text ) leechers = int ( cols [ 3 ] . text ) t = Torrent ( title , url , category , sub_category , magnet_link , torrent_link , comments , has_cover , user_status , created , size , user , seeders , leechers ) return t | Builds and returns a Torrent object for the given parsed row . |
17,244 | def items ( self ) : if self . _multipage : while True : items = super ( Paginated , self ) . items ( ) first = next ( items , None ) if first is None : raise StopIteration ( ) else : yield first for item in items : yield item self . next ( ) else : for item in super ( Paginated , self ) . items ( ) : yield item | Request URL and parse response . Yield a Torrent for every torrent on page . If in multipage mode Torrents from next pages are automatically chained . |
17,245 | def page ( self , number = None ) : if number is None : return int ( self . url . page ) self . url . page = str ( number ) | If page is given modify the URL correspondingly return the current page otherwise . |
17,246 | def query ( self , query = None ) : if query is None : return self . url . query self . url . query = query | If query is given modify the URL correspondingly return the current query otherwise . |
17,247 | def order ( self , order = None ) : if order is None : return int ( self . url . order ) self . url . order = str ( order ) | If order is given modify the URL correspondingly return the current order otherwise . |
17,248 | def category ( self , category = None ) : if category is None : return int ( self . url . category ) self . url . category = str ( category ) | If category is given modify the URL correspondingly return the current category otherwise . |
17,249 | def search ( self , query , page = 0 , order = 7 , category = 0 , multipage = False ) : search = Search ( self . base_url , query , page , order , category ) if multipage : search . multipage ( ) return search | Searches TPB for query and returns a list of paginated Torrents capable of changing query categories and orders . |
17,250 | def created ( self ) : timestamp , current = self . _created if timestamp . endswith ( 'ago' ) : quantity , kind , ago = timestamp . split ( ) quantity = int ( quantity ) if 'sec' in kind : current -= quantity elif 'min' in kind : current -= quantity * 60 elif 'hour' in kind : current -= quantity * 60 * 60 return datetime . datetime . fromtimestamp ( current ) current = datetime . datetime . fromtimestamp ( current ) timestamp = timestamp . replace ( 'Y-day' , str ( current . date ( ) - datetime . timedelta ( days = 1 ) ) ) timestamp = timestamp . replace ( 'Today' , current . date ( ) . isoformat ( ) ) try : return dateutil . parser . parse ( timestamp ) except : return current | Attempt to parse the human readable torrent creation datetime . |
17,251 | def print_torrent ( self ) : print ( 'Title: %s' % self . title ) print ( 'URL: %s' % self . url ) print ( 'Category: %s' % self . category ) print ( 'Sub-Category: %s' % self . sub_category ) print ( 'Magnet Link: %s' % self . magnet_link ) print ( 'Torrent Link: %s' % self . torrent_link ) print ( 'Uploaded: %s' % self . created ) print ( 'Comments: %d' % self . comments ) print ( 'Has Cover Image: %s' % self . has_cover ) print ( 'User Status: %s' % self . user_status ) print ( 'Size: %s' % self . size ) print ( 'User: %s' % self . user ) print ( 'Seeders: %d' % self . seeders ) print ( 'Leechers: %d' % self . leechers ) | Print the details of a torrent |
17,252 | def foreground ( color , content , readline = False ) : return encode ( color , readline = readline ) + content + encode ( DEFAULT , readline = readline ) | Color the text of the content |
17,253 | def get_or_create ( cls , ** kwargs ) : session = Session ( ) instance = session . query ( cls ) . filter_by ( ** kwargs ) . first ( ) session . close ( ) if not instance : self = cls ( ** kwargs ) self . save ( ) else : self = instance return self | Creates an object or returns the object if exists credit to Kevin |
17,254 | def calling_logger ( height = 1 ) : stack = inspect . stack ( ) height = min ( len ( stack ) - 1 , height ) caller = stack [ height ] scope = caller [ 0 ] . f_globals path = scope [ '__name__' ] if path == '__main__' : path = scope [ '__package__' ] or os . path . basename ( sys . argv [ 0 ] ) return logging . getLogger ( path ) | Obtain a logger for the calling module . |
17,255 | def fillna ( self , series , addition = 0 ) : if series . dtype == numpy . object : return series return series . fillna ( self . missing_value + addition ) . astype ( self . dtype ) | Fills with encoder specific default values . |
17,256 | def hyper_parameter_search ( self , param_distributions , n_iter = 10 , scoring = None , fit_params = { } , n_jobs = 1 , iid = True , refit = True , cv = None , verbose = 0 , pre_dispatch = '2*njobs' , random_state = None , error_score = 'raise' , return_train_score = True , test = True , score = True , save = True , custom_data = None ) : params = locals ( ) params . pop ( 'self' ) self . fitting = lore . metadata . Fitting . create ( model = self . name , custom_data = custom_data , snapshot = lore . metadata . Snapshot ( pipeline = self . pipeline . name , head = str ( self . pipeline . training_data . head ( 2 ) ) , tail = str ( self . pipeline . training_data . tail ( 2 ) ) ) ) result = RandomizedSearchCV ( self . estimator , param_distributions , n_iter = n_iter , scoring = scoring , n_jobs = n_jobs , iid = iid , refit = refit , cv = cv , verbose = verbose , pre_dispatch = pre_dispatch , random_state = random_state , error_score = error_score , return_train_score = return_train_score ) . fit ( self . pipeline . encoded_training_data . x , y = self . pipeline . encoded_training_data . y , validation_x = self . pipeline . encoded_validation_data . x , validation_y = self . pipeline . encoded_validation_data . y , ** fit_params ) self . estimator = result . best_estimator_ self . stats = { } self . estimator_kwargs = self . estimator . __getstate__ ( ) if test : self . stats [ 'test' ] = self . evaluate ( self . pipeline . test_data ) if score : self . stats [ 'score' ] = self . score ( self . pipeline . test_data ) self . complete_fitting ( ) if save : self . save ( ) return result | Random search hyper params |
17,257 | def require ( packages ) : global INSTALLED_PACKAGES , _new_requirements if _new_requirements : INSTALLED_PACKAGES = None set_installed_packages ( ) if not INSTALLED_PACKAGES : return if not isinstance ( packages , list ) : packages = [ packages ] missing = [ ] for package in packages : name = re . split ( r'[!<>=]' , package ) [ 0 ] . lower ( ) if name not in INSTALLED_PACKAGES : print ( ansi . info ( ) + ' %s is required.' % package ) missing += [ package ] if missing : mode = 'a' if os . path . exists ( REQUIREMENTS ) else 'w' with open ( REQUIREMENTS , mode ) as requirements : requirements . write ( '\n' + '\n' . join ( missing ) + '\n' ) print ( ansi . info ( ) + ' Dependencies added to requirements.txt. Rebooting.' ) _new_requirements = True import lore . __main__ lore . __main__ . install ( None , None ) reboot ( '--env-checked' ) | Ensures that a pypi package has been installed into the App s python environment . If not the package will be installed and your env will be rebooted . |
17,258 | def launched ( ) : if not PREFIX : return False return os . path . realpath ( sys . prefix ) == os . path . realpath ( PREFIX ) | Test whether the current python environment is the correct lore env . |
17,259 | def validate ( ) : if not os . path . exists ( os . path . join ( ROOT , APP , '__init__.py' ) ) : message = ansi . error ( ) + ' Python module not found.' if os . environ . get ( 'LORE_APP' ) is None : message += ' $LORE_APP is not set. Should it be different than "%s"?' % APP else : message += ' $LORE_APP is set to "%s". Should it be different?' % APP sys . exit ( message ) if exists ( ) : return if len ( sys . argv ) > 1 : command = sys . argv [ 1 ] else : command = 'lore' sys . exit ( ansi . error ( ) + ' %s is only available in lore ' 'app directories (missing %s)' % ( ansi . bold ( command ) , ansi . underline ( VERSION_PATH ) ) ) | Display error messages and exit if no lore environment can be found . |
17,260 | def launch ( ) : if launched ( ) : check_version ( ) os . chdir ( ROOT ) return if not os . path . exists ( BIN_LORE ) : missing = ' %s virtualenv is missing.' % APP if '--launched' in sys . argv : sys . exit ( ansi . error ( ) + missing + ' Please check for errors during:\n $ lore install\n' ) else : print ( ansi . warning ( ) + missing ) import lore . __main__ lore . __main__ . install ( None , None ) reboot ( '--env-launched' ) | Ensure that python is running from the Lore virtualenv past this point . |
17,261 | def reboot ( * args ) : args = list ( sys . argv ) + list ( args ) if args [ 0 ] == 'python' or not args [ 0 ] : args [ 0 ] = BIN_PYTHON elif os . path . basename ( sys . argv [ 0 ] ) in [ 'lore' , 'lore.exe' ] : args [ 0 ] = BIN_LORE try : os . execv ( args [ 0 ] , args ) except Exception as e : if args [ 0 ] == BIN_LORE and args [ 1 ] == 'console' and JUPYTER_KERNEL_PATH : print ( ansi . error ( ) + ' Your jupyter kernel may be corrupt. Please remove it so lore can reinstall:\n $ rm ' + JUPYTER_KERNEL_PATH ) raise e | Reboot python in the Lore virtualenv |
17,262 | def check_version ( ) : if sys . version_info [ 0 : 3 ] == PYTHON_VERSION_INFO [ 0 : 3 ] : return sys . exit ( ansi . error ( ) + ' your virtual env points to the wrong python version. ' 'This is likely because you used a python installer that clobbered ' 'the system installation, which breaks virtualenv creation. ' 'To fix, check this symlink, and delete the installation of python ' 'that it is brokenly pointing to, then delete the virtual env itself ' 'and rerun lore install: ' + os . linesep + os . linesep + BIN_PYTHON + os . linesep ) | Sanity check version information for corrupt virtualenv symlinks |
17,263 | def check_requirements ( ) : if not os . path . exists ( REQUIREMENTS ) : sys . exit ( ansi . error ( ) + ' %s is missing. Please check it in.' % ansi . underline ( REQUIREMENTS ) ) with open ( REQUIREMENTS , 'r' , encoding = 'utf-8' ) as f : dependencies = f . readlines ( ) vcs = [ d for d in dependencies if re . match ( r'^(-e )?(git|svn|hg|bzr).*' , d ) ] dependencies = list ( set ( dependencies ) - set ( vcs ) ) missing = [ ] try : pkg_resources . require ( dependencies ) except ( pkg_resources . ContextualVersionConflict , pkg_resources . DistributionNotFound , pkg_resources . VersionConflict ) as error : missing . append ( str ( error ) ) except pkg_resources . RequirementParseError : pass if missing : missing = ' missing requirement:\n ' + os . linesep . join ( missing ) if '--env-checked' in sys . argv : sys . exit ( ansi . error ( ) + missing + '\nRequirement installation failure, please check for errors in:\n $ lore install\n' ) else : print ( ansi . warning ( ) + missing ) import lore . __main__ lore . __main__ . install_requirements ( None ) reboot ( '--env-checked' ) | Make sure all listed packages from requirements . txt have been installed into the virtualenv at boot . |
17,264 | def get_config ( path ) : if configparser is None : return None if os . path . exists ( os . path . join ( ROOT , 'config' , NAME , path ) ) : path = os . path . join ( ROOT , 'config' , NAME , path ) else : path = os . path . join ( ROOT , 'config' , path ) if not os . path . isfile ( path ) : return None conf = open ( path , 'rt' ) . read ( ) conf = os . path . expandvars ( conf ) config = configparser . SafeConfigParser ( ) if sys . version_info [ 0 ] == 2 : from io import StringIO config . readfp ( StringIO ( unicode ( conf ) ) ) else : config . read_string ( conf ) return config | Load a config from disk |
17,265 | def read_version ( path ) : version = None if os . path . exists ( path ) : version = open ( path , 'r' , encoding = 'utf-8' ) . read ( ) . strip ( ) if version : return re . sub ( r'^python-' , '' , version ) return version | Attempts to read a python version string from a runtime . txt file |
17,266 | def set_installed_packages ( ) : global INSTALLED_PACKAGES , REQUIRED_VERSION if INSTALLED_PACKAGES : return if os . path . exists ( BIN_PYTHON ) : pip = subprocess . Popen ( ( BIN_PYTHON , '-m' , 'pip' , 'freeze' ) , stdout = subprocess . PIPE , stderr = subprocess . PIPE ) ( stdout , stderr ) = pip . communicate ( ) pip . wait ( ) INSTALLED_PACKAGES = [ r . decode ( ) . split ( '==' ) [ 0 ] . lower ( ) for r in stdout . split ( ) ] REQUIRED_VERSION = next ( ( package for package in INSTALLED_PACKAGES if re . match ( r'^lore[!<>=]' , package ) ) , None ) if REQUIRED_VERSION : REQUIRED_VERSION = re . split ( r'[!<>=]' , REQUIRED_VERSION ) [ - 1 ] | Idempotently caches the list of packages installed in the virtualenv . Can be run safely before the virtualenv is created and will be rerun afterwards . |
17,267 | def _force_https ( self ) : if self . session_cookie_secure : if not self . app . debug : self . app . config [ 'SESSION_COOKIE_SECURE' ] = True criteria = [ self . app . debug , flask . request . is_secure , flask . request . headers . get ( 'X-Forwarded-Proto' , 'http' ) == 'https' , ] local_options = self . _get_local_options ( ) if local_options [ 'force_https' ] and not any ( criteria ) : if flask . request . url . startswith ( 'http://' ) : url = flask . request . url . replace ( 'http://' , 'https://' , 1 ) code = 302 if self . force_https_permanent : code = 301 r = flask . redirect ( url , code = code ) return r | Redirect any non - https requests to https . |
17,268 | def _set_response_headers ( self , response ) : options = self . _get_local_options ( ) self . _set_feature_headers ( response . headers , options ) self . _set_frame_options_headers ( response . headers , options ) self . _set_content_security_policy_headers ( response . headers , options ) self . _set_hsts_headers ( response . headers ) self . _set_referrer_policy_headers ( response . headers ) return response | Applies all configured headers to the given response . |
17,269 | def init_weapon_list ( ) : twohand = [ ] for item in TWOHANDED_WEAPONS : twohand . append ( [ item ] ) onehand = [ ] for item in ONEHANDED_WEAPONS : onehand . append ( [ item ] ) shield = SHIELDS dualwield_variations = [ ] weapon_shield_variations = [ ] for item in ONEHANDED_WEAPONS : for i in ONEHANDED_WEAPONS : dualwield_variations . append ( [ item , i ] ) for j in shield : weapon_shield_variations . append ( [ j , item ] ) return twohand + onehand + dualwield_variations + weapon_shield_variations | Initialize the possible weapon combinations . |
17,270 | def split_sequence ( seq , n ) : tokens = [ ] while seq : tokens . append ( seq [ : n ] ) seq = seq [ n : ] return tokens | Generates tokens of length n from a sequence . The last token may be of smaller length . |
17,271 | def grind_hash_for_weapon ( hashcode ) : weaponlist = init_weapon_list ( ) weapon_control = hashcode [ ASPECT_CONTROL_LEN : ( ASPECT_CONTROL_LEN * 2 ) ] hash_dec_value = int ( weapon_control , HEX_BASE ) decision = map_decision ( MAX_DECISION_VALUE , len ( weaponlist ) , hash_dec_value ) return choose_weapon ( decision , weaponlist ) | Grinds the given hashcode for a weapon to draw on the pixelmap . Utilizes the second six characters from the hashcode . |
17,272 | def choose_weapon ( decision , weapons ) : choice = [ ] for i in range ( len ( weapons ) ) : if ( i < decision ) : choice = weapons [ i ] return choice | Chooses a weapon from a given list based on the decision . |
17,273 | def choose_aspect ( decision ) : choice = [ ] for i in range ( len ( ASPECTSTYLES ) ) : if ( i < decision ) : choice = ASPECTSTYLES [ i ] return choice | Chooses a style from ASPECTSTYLES based on the decision . |
17,274 | def hex2rgb ( hexvalue ) : if ( '#' in hexvalue ) : hexcolor = hexvalue . replace ( '#' , '' ) else : hexcolor = hexvalue if ( len ( hexcolor ) != 6 ) : print ( "Unexpected length of hex color value.\nSix characters excluding \'#\' expected." ) return 0 r = int ( hexcolor [ 0 : 2 ] , HEX_BASE ) g = int ( hexcolor [ 2 : 4 ] , HEX_BASE ) b = int ( hexcolor [ 4 : 6 ] , HEX_BASE ) return r , g , b | Converts a given hex color to its respective rgb color . |
17,275 | def index ( ) : default = [ "pagan" , "python" , "avatar" , "github" ] slogan = request . forms . get ( "slogan" ) if not slogan : if request . get_cookie ( "hist1" ) : slogan = request . get_cookie ( "hist1" ) else : slogan = "pagan" if not request . get_cookie ( "hist1" ) : hist1 , hist2 , hist3 , hist4 = default [ : ] else : hist1 = request . get_cookie ( "hist1" ) hist2 = request . get_cookie ( "hist2" ) hist3 = request . get_cookie ( "hist3" ) hist4 = request . get_cookie ( "hist4" ) if slogan in ( hist1 , hist2 , hist3 , hist4 ) : history = [ hist1 , hist2 , hist3 , hist4 ] history . remove ( slogan ) hist1 , hist2 , hist3 = history [ 0 ] , history [ 1 ] , history [ 2 ] response . set_cookie ( "hist1" , slogan , max_age = 60 * 60 * 24 * 30 , httponly = True ) response . set_cookie ( "hist2" , hist1 , max_age = 60 * 60 * 24 * 30 , httponly = True ) response . set_cookie ( "hist3" , hist2 , max_age = 60 * 60 * 24 * 30 , httponly = True ) response . set_cookie ( "hist4" , hist3 , max_age = 60 * 60 * 24 * 30 , httponly = True ) md5 = hashlib . md5 ( ) md5 . update ( slogan ) slogan_hash = md5 . hexdigest ( ) md5 . update ( hist1 ) hist1_hash = md5 . hexdigest ( ) md5 . update ( hist2 ) hist2_hash = md5 . hexdigest ( ) md5 . update ( hist3 ) hist3_hash = md5 . hexdigest ( ) return template ( TEMPLATEINDEX , slogan = slogan , hist1 = hist1 , hist2 = hist2 , hist3 = hist3 , sloganHash = slogan_hash , hist1Hash = hist1_hash , hist2Hash = hist2_hash , hist3Hash = hist3_hash ) | main functionality of webserver |
17,276 | def __create_image ( self , inpt , hashfun ) : if hashfun not in generator . HASHES . keys ( ) : print ( "Unknown or unsupported hash function. Using default: %s" % self . DEFAULT_HASHFUN ) algo = self . DEFAULT_HASHFUN else : algo = hashfun return generator . generate ( inpt , algo ) | Creates the avatar based on the input and the chosen hash function . |
17,277 | def change ( self , inpt , hashfun = DEFAULT_HASHFUN ) : self . img = self . __create_image ( inpt , hashfun ) | Change the avatar by providing a new input . Uses the standard hash function if no one is given . |
17,278 | def create_shield_deco_layer ( weapons , ip ) : layer = [ ] if weapons [ 0 ] in hashgrinder . SHIELDS : layer = pgnreader . parse_pagan_file ( FILE_SHIELD_DECO , ip , invert = False , sym = False ) return layer | Reads the SHIELD_DECO . pgn file and creates the shield decal layer . |
17,279 | def create_hair_layer ( aspect , ip ) : layer = [ ] if 'HAIR' in aspect : layer = pgnreader . parse_pagan_file ( FILE_HAIR , ip , invert = False , sym = True ) return layer | Reads the HAIR . pgn file and creates the hair layer . |
17,280 | def create_torso_layer ( aspect , ip ) : layer = [ ] if 'TOP' in aspect : layer = pgnreader . parse_pagan_file ( FILE_TORSO , ip , invert = False , sym = True ) return layer | Reads the TORSO . pgn file and creates the torso layer . |
17,281 | def create_subfield_layer ( aspect , ip ) : layer = [ ] if 'PANTS' in aspect : layer = pgnreader . parse_pagan_file ( FILE_SUBFIELD , ip , invert = False , sym = True ) else : layer = pgnreader . parse_pagan_file ( FILE_MIN_SUBFIELD , ip , invert = False , sym = True ) return layer | Reads the SUBFIELD . pgn file and creates the subfield layer . |
17,282 | def create_boots_layer ( aspect , ip ) : layer = [ ] if 'BOOTS' in aspect : layer = pgnreader . parse_pagan_file ( FILE_BOOTS , ip , invert = False , sym = True ) return layer | Reads the BOOTS . pgn file and creates the boots layer . |
17,283 | def create_shield_layer ( shield , hashcode ) : return pgnreader . parse_pagan_file ( ( '%s%spgn%s' % ( PACKAGE_DIR , os . sep , os . sep ) ) + shield + '.pgn' , hashcode , sym = False , invert = False ) | Creates the layer for shields . |
17,284 | def create_weapon_layer ( weapon , hashcode , isSecond = False ) : return pgnreader . parse_pagan_file ( ( '%s%spgn%s' % ( PACKAGE_DIR , os . sep , os . sep ) ) + weapon + '.pgn' , hashcode , sym = False , invert = isSecond ) | Creates the layer for weapons . |
17,285 | def scale_pixels ( color , layer ) : pixelmap = [ ] for pix_x in range ( MAX_X + 1 ) : for pix_y in range ( MAX_Y + 1 ) : y1 = pix_y * dotsize [ 0 ] x1 = pix_x * dotsize [ 1 ] y2 = pix_y * dotsize [ 0 ] + ( dotsize [ 0 ] - 1 ) x2 = pix_x * dotsize [ 1 ] + ( dotsize [ 1 ] - 1 ) if ( y1 <= MAX_Y ) and ( y2 <= MAX_Y ) : if ( x1 <= MAX_X ) and ( x2 <= MAX_X ) : if ( pix_x , pix_y ) in layer : pixelmap . append ( [ ( y1 , x1 ) , ( y2 , x2 ) , color ] ) return pixelmap | Scales the pixel to the virtual pixelmap . |
17,286 | def draw_image ( pixelmap , img ) : for item in pixelmap : color = item [ 2 ] pixelbox = ( item [ 0 ] [ 0 ] , item [ 0 ] [ 1 ] , item [ 1 ] [ 0 ] , item [ 1 ] [ 1 ] ) draw = ImageDraw . Draw ( img ) draw . rectangle ( pixelbox , fill = color ) | Draws the image based on the given pixelmap . |
17,287 | def setup_pixelmap ( hashcode ) : colors = hashgrinder . grind_hash_for_colors ( hashcode ) color_body = colors [ 0 ] color_subfield = colors [ 1 ] color_weapon_a = colors [ 2 ] color_weapon_b = colors [ 3 ] color_shield_deco = colors [ 4 ] color_boots = colors [ 5 ] color_hair = colors [ 6 ] color_top = colors [ 7 ] aspect = hashgrinder . grind_hash_for_aspect ( hashcode ) weapons = hashgrinder . grind_hash_for_weapon ( hashcode ) if DEBUG : print ( "Current aspect: %r" % aspect ) print ( "Current weapons: %r" % weapons ) layer_body = pgnreader . parse_pagan_file ( FILE_BODY , hashcode , invert = False , sym = True ) layer_hair = create_hair_layer ( aspect , hashcode ) layer_boots = create_boots_layer ( aspect , hashcode ) layer_torso = create_torso_layer ( aspect , hashcode ) has_shield = ( weapons [ 0 ] in hashgrinder . SHIELDS ) if has_shield : layer_weapon_a = create_shield_layer ( weapons [ 0 ] , hashcode ) layer_weapon_b = create_weapon_layer ( weapons [ 1 ] , hashcode ) else : layer_weapon_a = create_weapon_layer ( weapons [ 0 ] , hashcode ) if ( len ( weapons ) == 2 ) : layer_weapon_b = create_weapon_layer ( weapons [ 1 ] , hashcode , True ) layer_subfield = create_subfield_layer ( aspect , hashcode ) layer_deco = create_shield_deco_layer ( weapons , hashcode ) pixelmap = scale_pixels ( color_body , layer_body ) pixelmap += scale_pixels ( color_top , layer_torso ) pixelmap += scale_pixels ( color_hair , layer_hair ) pixelmap += scale_pixels ( color_subfield , layer_subfield ) pixelmap += scale_pixels ( color_boots , layer_boots ) pixelmap += scale_pixels ( color_weapon_a , layer_weapon_a ) if ( len ( weapons ) == 2 ) : pixelmap += scale_pixels ( color_weapon_b , layer_weapon_b ) pixelmap += scale_pixels ( color_shield_deco , layer_deco ) return pixelmap | Creates and combines all required layers to build a pixelmap for creating the virtual pixels . |
17,288 | def generate ( str , alg ) : img = Image . new ( IMAGE_MODE , IMAGE_SIZE , BACKGROUND_COLOR ) hashcode = hash_input ( str , alg ) pixelmap = setup_pixelmap ( hashcode ) draw_image ( pixelmap , img ) return img | Generates an PIL image avatar based on the given input String . Acts as the main accessor to pagan . |
17,289 | def generate_by_hash ( hashcode ) : img = Image . new ( IMAGE_MODE , IMAGE_SIZE , BACKGROUND_COLOR ) if len ( hashcode ) < 32 : print ( "hashcode must have lenght >= 32, %s" % hashcode ) raise FalseHashError allowed = "0123456789abcdef" hashcheck = [ c in allowed for c in hashcode ] if False in hashcheck : print ( "hashcode has not allowed structure %s" % hashcode ) raise FalseHashError pixelmap = setup_pixelmap ( hashcode ) draw_image ( pixelmap , img ) return img | Generates an PIL image avatar based on the given hash String . Acts as the main accessor to pagan . |
17,290 | def enforce_vertical_symmetry ( pixmap ) : mirror = [ ] for item in pixmap : y = item [ 0 ] x = item [ 1 ] if x <= IMAGE_APEX : diff_x = diff ( x , IMAGE_APEX ) mirror . append ( ( y , x + ( 2 * diff_x ) - 1 ) ) if x > IMAGE_APEX : diff_x = diff ( x , IMAGE_APEX ) mirror . append ( ( y , x - ( 2 * diff_x ) - 1 ) ) return mirror + pixmap | Enforces vertical symmetry of the pixelmap . Returns a pixelmap with all pixels mirrored in the middle . The initial ones still remain . |
17,291 | def replace_types ( text ) : if not hasattr ( replace_types , '_replacer' ) : replace_types . _replacer = build_replacer ( ) return replace_types . _replacer ( text ) | Chomp down company types to a more convention form . |
17,292 | def clean_strict ( text , boundary = WS ) : text = ascii_text ( text ) text = CHARACTERS_REMOVE_RE . sub ( '' , text ) text = category_replace ( text ) text = '' . join ( ( boundary , collapse_spaces ( text ) , boundary ) ) return text | Super - hardcore string scrubbing . |
17,293 | def selfcheck ( tools ) : msg = [ ] for tool_name , check_cli in collections . OrderedDict ( tools ) . items ( ) : try : subprocess . check_output ( check_cli , shell = True , stderr = subprocess . STDOUT ) except subprocess . CalledProcessError : msg . append ( '%r not found or not usable.' % tool_name ) return '\n' . join ( msg ) if msg else 'Your system is ready.' | Audit the system for issues . |
17,294 | def seed ( cache_dir = CACHE_DIR , product = DEFAULT_PRODUCT , bounds = None , max_download_tiles = 9 , ** kwargs ) : datasource_root , spec = ensure_setup ( cache_dir , product ) ensure_tiles_names = list ( spec [ 'tile_names' ] ( * bounds ) ) if len ( ensure_tiles_names ) > max_download_tiles : raise RuntimeError ( "Too many tiles: %d. Please consult the providers' websites " "for how to bulk download tiles." % len ( ensure_tiles_names ) ) with util . lock_tiles ( datasource_root , ensure_tiles_names ) : ensure_tiles ( datasource_root , ensure_tiles_names , ** kwargs ) with util . lock_vrt ( datasource_root , product ) : util . check_call_make ( datasource_root , targets = [ 'all' ] ) return datasource_root | Seed the DEM to given bounds . |
17,295 | def clip ( bounds , output = DEFAULT_OUTPUT , margin = MARGIN , ** kwargs ) : bounds = build_bounds ( bounds , margin = margin ) datasource_root = seed ( bounds = bounds , ** kwargs ) do_clip ( datasource_root , bounds , output , ** kwargs ) | Clip the DEM to given bounds . |
17,296 | def info ( cache_dir = CACHE_DIR , product = DEFAULT_PRODUCT ) : datasource_root , _ = ensure_setup ( cache_dir , product ) util . check_call_make ( datasource_root , targets = [ 'info' ] ) | Show info about the product cache . |
17,297 | def new_oauth ( yaml_path ) : print ( 'Retrieve consumer key and consumer secret from http://www.tumblr.com/oauth/apps' ) consumer_key = input ( 'Paste the consumer key here: ' ) . strip ( ) consumer_secret = input ( 'Paste the consumer secret here: ' ) . strip ( ) request_token_url = 'http://www.tumblr.com/oauth/request_token' authorize_url = 'http://www.tumblr.com/oauth/authorize' access_token_url = 'http://www.tumblr.com/oauth/access_token' oauth_session = OAuth1Session ( consumer_key , client_secret = consumer_secret ) fetch_response = oauth_session . fetch_request_token ( request_token_url ) resource_owner_key = fetch_response . get ( 'oauth_token' ) resource_owner_secret = fetch_response . get ( 'oauth_token_secret' ) full_authorize_url = oauth_session . authorization_url ( authorize_url ) print ( '\nPlease go here and authorize:\n{}' . format ( full_authorize_url ) ) redirect_response = input ( 'Allow then paste the full redirect URL here:\n' ) . strip ( ) oauth_response = oauth_session . parse_authorization_response ( redirect_response ) verifier = oauth_response . get ( 'oauth_verifier' ) oauth_session = OAuth1Session ( consumer_key , client_secret = consumer_secret , resource_owner_key = resource_owner_key , resource_owner_secret = resource_owner_secret , verifier = verifier ) oauth_tokens = oauth_session . fetch_access_token ( access_token_url ) tokens = { 'consumer_key' : consumer_key , 'consumer_secret' : consumer_secret , 'oauth_token' : oauth_tokens . get ( 'oauth_token' ) , 'oauth_token_secret' : oauth_tokens . get ( 'oauth_token_secret' ) } yaml_file = open ( yaml_path , 'w+' ) yaml . dump ( tokens , yaml_file , indent = 2 ) yaml_file . close ( ) return tokens | Return the consumer and oauth tokens with three - legged OAuth process and save in a yaml file in the user s home directory . |
17,298 | def validate_params ( valid_options , params ) : if not params : return data_filter = [ 'data' , 'source' , 'external_url' , 'embed' ] multiple_data = [ key for key in params . keys ( ) if key in data_filter ] if len ( multiple_data ) > 1 : raise Exception ( "You can't mix and match data parameters" ) disallowed_fields = [ key for key in params . keys ( ) if key not in valid_options ] if disallowed_fields : field_strings = "," . join ( disallowed_fields ) raise Exception ( "{} are not allowed fields" . format ( field_strings ) ) | Helps us validate the parameters for the request |
17,299 | def get ( self , url , params ) : url = self . host + url if params : url = url + "?" + urllib . parse . urlencode ( params ) try : resp = requests . get ( url , allow_redirects = False , headers = self . headers , auth = self . oauth ) except TooManyRedirects as e : resp = e . response return self . json_parse ( resp ) | Issues a GET request against the API properly formatting the params |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.