idx int64 0 63k | question stringlengths 53 5.28k | target stringlengths 5 805 |
|---|---|---|
51,800 | def _set_dict_translations ( instance , dict_translations ) : if not hasattr ( instance . _meta , "translatable_fields" ) : return False if site_is_monolingual ( ) : return False translatable_fields = instance . _meta . translatable_fields for field in translatable_fields : for lang in settings . LANGUAGES : lang = lang [ 0 ] if lang != settings . LANGUAGE_CODE : trans_field = trans_attr ( field , lang ) if dict_translations . has_key ( trans_field ) : setattr ( instance , trans_field , dict_translations [ trans_field ] ) trans_isfuzzy = trans_is_fuzzy_attr ( field , lang ) if dict_translations . has_key ( trans_isfuzzy ) : is_fuzzy_value = ( dict_translations [ trans_isfuzzy ] == "1" ) or ( dict_translations [ trans_isfuzzy ] == 1 ) setattr ( instance , trans_isfuzzy , is_fuzzy_value ) | Establece los atributos de traducciones a partir de una dict que contiene todas las traducciones . |
51,801 | def add_translation ( sender ) : signals . post_save . connect ( _save_translations , sender = sender ) sender . add_to_class ( "get_fieldtranslations" , _get_fieldtranslations ) sender . add_to_class ( "load_translations" , _load_translations ) sender . add_to_class ( "set_translation_fields" , _set_dict_translations ) sender . add_to_class ( "_" , _get_translated_field ) sender . add_to_class ( "get_trans_attr" , _get_translated_field ) sender . add_to_class ( "_t" , _get_translated_field ) | Adds the actions to a class . |
51,802 | def encrypt_file_inline ( filename , passphrase ) : key = key_generators . key_from_file ( filename , passphrase ) inline_transform ( filename , key ) return key | Encrypt file inline with an optional passphrase . |
51,803 | def inline_transform ( filename , key ) : pos = 0 for chunk , fp in iter_transform ( filename , key ) : fp . seek ( pos ) fp . write ( chunk ) fp . flush ( ) pos = fp . tell ( ) | Encrypt file inline . |
51,804 | def iter_transform ( filename , key ) : aes = AES . new ( key , AES . MODE_CTR , counter = Counter . new ( 128 ) ) with open ( filename , 'rb+' ) as f : for chunk in iter ( lambda : f . read ( CHUNK_SIZE ) , b'' ) : yield aes . encrypt ( chunk ) , f | Generate encrypted file with given key . |
51,805 | def signalbus ( self ) : try : signalbus = self . __signalbus except AttributeError : signalbus = self . __signalbus = SignalBus ( self , init_app = False ) return signalbus | The associated SignalBus object . |
51,806 | def get_signal_models ( self ) : base = self . db . Model return [ cls for cls in base . _decl_class_registry . values ( ) if ( isinstance ( cls , type ) and issubclass ( cls , base ) and hasattr ( cls , 'send_signalbus_message' ) ) ] | Return all signal types in a list . |
51,807 | def flush ( self , models = None , wait = 3.0 ) : models_to_flush = self . get_signal_models ( ) if models is None else models pks_to_flush = { } try : for model in models_to_flush : _raise_error_if_not_signal_model ( model ) m = inspect ( model ) pk_attrs = [ m . get_property_by_column ( c ) . class_attribute for c in m . primary_key ] pks_to_flush [ model ] = self . signal_session . query ( * pk_attrs ) . all ( ) self . signal_session . rollback ( ) time . sleep ( wait ) return sum ( self . _flush_signals_with_retry ( model , pk_values_set = set ( pks_to_flush [ model ] ) ) for model in models_to_flush ) finally : self . signal_session . remove ( ) | Send all pending signals over the message bus . |
51,808 | def get ( self , status_code ) : status_code = int ( status_code ) if status_code >= 400 : kwargs = { 'status_code' : status_code } if self . get_query_argument ( 'reason' , None ) : kwargs [ 'reason' ] = self . get_query_argument ( 'reason' ) if self . get_query_argument ( 'log_message' , None ) : kwargs [ 'log_message' ] = self . get_query_argument ( 'log_message' ) self . send_error ( ** kwargs ) else : self . set_status ( status_code ) | Returns the requested status . |
51,809 | def get_absolute_path ( self , path ) : if os . path . isabs ( path ) : return path else : return os . path . abspath ( os . path . join ( self . config . BASEDIR , path ) ) | Returns the absolute path of the path argument . |
51,810 | def get_roles ( self ) : roles = { } paths = self . get_roles_paths ( ) for path in paths : for entry in os . listdir ( path ) : rolepath = os . path . join ( path , entry ) if os . path . isdir ( rolepath ) : roles [ entry ] = rolepath return roles | Returns a key - value dict with a roles while the key is the role name and the value is the absolute role path . |
51,811 | def read_yaml ( self , filename ) : with open ( filename , 'r' ) as f : d = re . sub ( r'\{\{ *([^ ]+) *\}\}' , r'\1' , f . read ( ) ) y = yaml . safe_load ( d ) return y if y else { } | Reads and parses a YAML file and returns the content . |
51,812 | def get_yaml_items ( self , dir_path , param = None ) : result = [ ] if not os . path . isdir ( dir_path ) : return [ ] for filename in os . listdir ( dir_path ) : path = os . path . join ( dir_path , filename ) items = self . read_yaml ( path ) for item in items : if param : if param in item : item = item [ param ] if isinstance ( item , list ) : result . extend ( item ) else : result . append ( item ) else : result . append ( item ) return result | Loops through the dir_path and parses all YAML files inside the directory . |
51,813 | def clean_response ( response ) : response = re . sub ( "^['\"]" , "" , response ) response = re . sub ( "['\"]$" , "" , response ) return response | Cleans string quoting in response . |
51,814 | def retry_on_deadlock ( session , retries = 6 , min_wait = 0.1 , max_wait = 10.0 ) : def decorator ( action ) : @ wraps ( action ) def f ( * args , ** kwargs ) : num_failures = 0 while True : try : return action ( * args , ** kwargs ) except ( DBAPIError , DBSerializationError ) as e : num_failures += 1 is_serialization_error = ( isinstance ( e , DBSerializationError ) or get_db_error_code ( e . orig ) in DEADLOCK_ERROR_CODES ) if num_failures > retries or not is_serialization_error : raise session . rollback ( ) wait_seconds = min ( max_wait , min_wait * 2 ** ( num_failures - 1 ) ) time . sleep ( wait_seconds ) return f return decorator | Return function decorator that executes the function again in case of a deadlock . |
51,815 | def cached ( f ) : def memoized ( * args , ** kwargs ) : if hasattr ( memoized , '__cache__' ) : return memoized . __cache__ result = f ( * args , ** kwargs ) memoized . __cache__ = result return result return memoized | Decorator for functions evaluated only once . |
51,816 | def property_pickled ( f ) : def retrieve_from_cache ( self ) : if '__cache__' not in self . __dict__ : self . __cache__ = { } if f . __name__ in self . __cache__ : return self . __cache__ [ f . __name__ ] if 'cache_dir' in self . __dict__ : path = FilePath ( self . __dict__ [ 'cache_dir' ] + f . func_name + '.pickle' ) else : path = getattr ( self . p , f . func_name ) if path . exists : with open ( path ) as handle : result = pickle . load ( handle ) self . __cache__ [ f . __name__ ] = result return result result = f ( self ) with open ( path , 'w' ) as handle : pickle . dump ( result , handle ) self . __cache__ [ f . __name__ ] = result return result def overwrite_cache ( self , value ) : if 'cache_dir' in self . __dict__ : path = FilePath ( self . __dict__ [ 'cache_dir' ] + f . func_name + '.pickle' ) else : path = getattr ( self . p , f . func_name ) if value is None : path . remove ( ) else : raise Exception ( "You can't set a pickled property, you can only delete it" ) retrieve_from_cache . __doc__ = f . __doc__ return property ( retrieve_from_cache , overwrite_cache ) | Same thing as above but the result will be stored on disk The path of the pickle file will be determined by looking for the cache_dir attribute of the instance containing the cached property . If no cache_dir attribute exists the p attribute will be accessed with the name of the property being cached . |
51,817 | def smartformset_factory ( form , formset = BaseFormSet , extra = 1 , can_order = False , can_delete = False , min_num = None , max_num = None , validate_min = False , validate_max = False ) : if max_num is None : max_num = DEFAULT_MAX_NUM absolute_max = max_num + DEFAULT_MAX_NUM if min_num is None : min_num = 0 attrs = { 'form' : form , 'extra' : extra , 'can_order' : can_order , 'can_delete' : can_delete , 'min_num' : min_num , 'max_num' : max_num , 'absolute_max' : absolute_max , 'validate_min' : validate_min , 'validate_max' : validate_max } return type ( form . __name__ + str ( 'FormSet' ) , ( formset , ) , attrs ) | Return a FormSet for the given form class . |
51,818 | def save_form ( self , form , ** kwargs ) : obj = form . save ( commit = False ) change = obj . pk is not None self . save_obj ( obj , form , change ) if hasattr ( form , 'save_m2m' ) : form . save_m2m ( ) return obj | Contains formset save prepare obj for saving |
51,819 | def get_method_returning_field_value ( self , field_name ) : return ( super ( ) . get_method_returning_field_value ( field_name ) or self . core . get_method_returning_field_value ( field_name ) ) | Field values can be obtained from view or core . |
51,820 | def _get_perm_obj_or_404 ( self , pk = None ) : if pk : obj = get_object_or_none ( self . core . model , pk = pk ) else : try : obj = self . get_obj ( False ) except Http404 : obj = get_object_or_none ( self . core . model , ** self . get_obj_filters ( ) ) if not obj : raise Http404 return obj | If is send parameter pk is returned object according this pk else is returned object from get_obj method but it search only inside filtered values for current user finally if object is still None is returned according the input key from all objects . |
51,821 | def view_all ( request , language , filter = None ) : if request . method == "POST" : data = request . POST . dict ( ) if not data [ "search" ] or data [ "search" ] == "" : return HttpResponseRedirect ( reverse ( "modeltranslation:view_all_url" , args = ( data [ "language" ] , data [ "filter" ] ) ) ) return HttpResponseRedirect ( reverse ( "modeltranslation:view_all_url" , args = ( data [ "language" ] , data [ "filter" ] ) ) + "?search=" + data [ "search" ] ) LANGUAGES = dict ( lang for lang in settings . LANGUAGES ) if language not in LANGUAGES . keys ( ) : raise Http404 ( u"Language {0} does not exist" . format ( language ) ) if language == settings . LANGUAGE_CODE : raise Http404 ( u"El idioma {0} es el idioma por defecto" . format ( language ) ) trans_filter = { "lang" : language } if filter == "all" or filter is None : pass elif filter == "fuzzy" : trans_filter [ "is_fuzzy" ] = True elif filter == "completed" : trans_filter [ "is_fuzzy" ] = False search_query = "" if request . GET and "search" in request . GET and request . GET . get ( "search" ) != "" : search_query = request . GET . get ( "search" ) trans_filter [ "source_text__icontains" ] = search_query translations = FieldTranslation . objects . filter ( ** trans_filter ) active_translations = [ ] for translation in translations : source_model = translation . get_source_model ( ) if not translation . field in source_model . _meta . translatable_fields : translation . delete ( ) else : active_translations . append ( translation ) replacements = { "translations" : active_translations , "filter" : filter , "lang" : language , "language" : LANGUAGES [ language ] , "search_query" : search_query } return render_to_response ( 'modeltranslation/admin/list.html' , replacements , RequestContext ( request ) ) | View all translations that are in site . |
51,822 | def edit ( request , translation ) : translation = get_object_or_404 ( FieldTranslation , id = translation ) if request . method == 'POST' : if "cancel" in request . POST : return HttpResponseRedirect ( reverse ( "modeltranslation:view_all_url" , args = ( translation . lang , "all" ) ) ) elif "save" in request . POST : form = FieldTranslationForm ( request . POST , instance = translation ) valid_form = form . is_valid ( ) if valid_form : translation = form . save ( commit = False ) translation . context = u"Admin. Traducciones" translation . save ( ) return HttpResponseRedirect ( reverse ( "modeltranslation:view_all_url" , args = ( translation . lang , "all" ) ) ) else : form = FieldTranslationForm ( instance = translation ) else : form = FieldTranslationForm ( instance = translation ) LANGUAGES = dict ( lang for lang in settings . LANGUAGES ) language = LANGUAGES [ translation . lang ] return render_to_response ( 'modeltranslation/admin/edit_translation.html' , { "translation" : translation , "form" : form , "lang" : translation . lang , "language" : language } , RequestContext ( request ) ) | Edit a translation . |
51,823 | def export_translations ( request , language ) : FieldTranslation . delete_orphan_translations ( ) translations = FieldTranslation . objects . filter ( lang = language ) for trans in translations : trans . source_text = trans . source_text . replace ( "'" , "\'" ) . replace ( "\"" , "\\\"" ) trans . translation = trans . translation . replace ( "'" , "\'" ) . replace ( "\"" , "\\\"" ) replacements = { "translations" : translations , "lang" : language } if len ( settings . ADMINS ) > 0 : replacements [ "last_translator" ] = settings . ADMINS [ 0 ] [ 0 ] replacements [ "last_translator_email" ] = settings . ADMINS [ 0 ] [ 1 ] if settings . WEBSITE_NAME : replacements [ "website_name" ] = settings . WEBSITE_NAME response = render ( request = request , template_name = 'modeltranslation/admin/export_translations.po' , dictionary = replacements , context_instance = RequestContext ( request ) , content_type = "text/x-gettext-translation" ) response [ 'Content-Disposition' ] = 'attachment; filename="{0}.po"' . format ( language ) return response | Export translations view . |
51,824 | def client_get ( self , url , ** kwargs ) : response = requests . get ( self . make_url ( url ) , headers = self . headers ) if not response . ok : raise Exception ( '{status}: {reason}.\nCircleCI Status NOT OK' . format ( status = response . status_code , reason = response . reason ) ) return response . json ( ) | Send GET request with given url . |
51,825 | def client_post ( self , url , ** kwargs ) : response = requests . post ( self . make_url ( url ) , data = json . dumps ( kwargs ) , headers = self . headers ) if not response . ok : raise Exception ( '{status}: {reason}.\nCircleCI Status NOT OK' . format ( status = response . status_code , reason = response . reason ) ) return response . json ( ) | Send POST request with given url and keyword args . |
51,826 | def client_delete ( self , url , ** kwargs ) : response = requests . delete ( self . make_url ( url ) , headers = self . headers ) if not response . ok : raise Exception ( '{status}: {reason}.\nCircleCI Status NOT OK' . format ( status = response . status_code , reason = response . reason ) ) return response . json ( ) | Send POST request with given url . |
51,827 | def list_projects ( self ) : method = 'GET' url = '/projects?circle-token={token}' . format ( token = self . client . api_token ) json_data = self . client . request ( method , url ) return json_data | Return a list of all followed projects . |
51,828 | def trigger ( self , username , project , branch , ** build_params ) : method = 'POST' url = ( '/project/{username}/{project}/tree/{branch}?' 'circle-token={token}' . format ( username = username , project = project , branch = branch , token = self . client . api_token ) ) if build_params is not None : json_data = self . client . request ( method , url , build_parameters = build_params ) else : json_data = self . client . request ( method , url ) return json_data | Trigger new build and return a summary of the build . |
51,829 | def cancel ( self , username , project , build_num ) : method = 'POST' url = ( '/project/{username}/{project}/{build_num}/cancel?' 'circle-token={token}' . format ( username = username , project = project , build_num = build_num , token = self . client . api_token ) ) json_data = self . client . request ( method , url ) return json_data | Cancel the build and return its summary . |
51,830 | def recent_all_projects ( self , limit = 30 , offset = 0 ) : method = 'GET' url = ( '/recent-builds?circle-token={token}&limit={limit}&' 'offset={offset}' . format ( token = self . client . api_token , limit = limit , offset = offset ) ) json_data = self . client . request ( method , url ) return json_data | Return information about recent builds across all projects . |
51,831 | def recent ( self , username , project , limit = 1 , offset = 0 , branch = None , status_filter = "" ) : method = 'GET' if branch is not None : url = ( '/project/{username}/{project}/tree/{branch}?' 'circle-token={token}&limit={limit}&offset={offset}&filter={status_filter}' . format ( username = username , project = project , branch = branch , token = self . client . api_token , limit = limit , offset = offset , status_filter = status_filter ) ) else : url = ( '/project/{username}/{project}?' 'circle-token={token}&limit={limit}&offset={offset}&filter={status_filter}' . format ( username = username , project = project , token = self . client . api_token , limit = limit , offset = offset , status_filter = status_filter ) ) json_data = self . client . request ( method , url ) return json_data | Return status of recent builds for given project . |
51,832 | def clear ( self , username , project ) : method = 'DELETE' url = ( '/project/{username}/{project}/build-cache?' 'circle-token={token}' . format ( username = username , project = project , token = self . client . api_token ) ) json_data = self . client . request ( method , url ) return json_data | Clear the cache for given project . |
51,833 | def post ( self , request , format = None ) : data = request . data . copy ( ) try : ct = ChatType . objects . get ( pk = data . pop ( "chat_type" ) ) data [ "chat_type" ] = ct except ChatType . DoesNotExist : return typeNotFound404 if not self . is_path_unique ( None , data [ "publish_path" ] , ct . publish_path ) : return notUnique400 try : u = User . objects . get ( pk = data . pop ( "owner" ) ) data [ "owner" ] = u except User . DoesNotExist : return userNotFound404 c = Channel ( ** data ) c . save ( ) self . handle_webhook ( c ) return Response ( { "text" : "Channel saved." , "method" : "POST" , "saved" : ChannelCMSSerializer ( c ) . data , } , 200 , ) | Add a new Channel . |
51,834 | def patch ( self , request , format = None ) : data = request . data . copy ( ) try : ct = ChatType . objects . get ( id = data . pop ( "chat_type" ) ) data [ "chat_type" ] = ct except ChatType . DoesNotExist : return typeNotFound404 if not self . is_path_unique ( data [ "id" ] , data [ "publish_path" ] , ct . publish_path ) : return notUnique400 try : c = Channel . objects . get ( id = data . pop ( "id" ) ) except Channel . DoesNotExist : return channelNotFound404 for key , value in data . items ( ) : setattr ( c , key , value ) c . save ( ) self . handle_webhook ( c ) return Response ( { "text" : "Channel saved." , "method" : "PATCH" , "saved" : ChannelCMSSerializer ( c ) . data , } , 200 , ) | Update an existing Channel |
51,835 | def sha256_file ( path ) : h = hashlib . sha256 ( ) with open ( path , 'rb' ) as f : for chunk in iter ( lambda : f . read ( CHUNK_SIZE ) , b'' ) : h . update ( chunk ) return h . hexdigest ( ) | Calculate sha256 hex digest of a file . |
51,836 | def key_from_file ( filename , passphrase ) : hexdigest = sha256_file ( filename ) if passphrase is None : passphrase = DEFAULT_HMAC_PASSPHRASE return keyed_hash ( hexdigest , passphrase ) | Calculate convergent encryption key . |
51,837 | def find_child ( sexpr : Sexpr , * tags : str ) -> Optional [ Sexpr ] : _assert_valid_sexpr ( sexpr ) for child in sexpr [ 1 : ] : if _is_sexpr ( child ) and child [ 0 ] in tags : return child return None | Search for a tag among direct children of the s - expression . |
51,838 | def build_attrs ( self , * args , ** kwargs ) : "Helper function for building an attribute dictionary." self . attrs = self . widget . build_attrs ( * args , ** kwargs ) return self . attrs | Helper function for building an attribute dictionary . |
51,839 | def get_template_substitution_values ( self , value ) : return { 'initial' : os . path . basename ( conditional_escape ( value ) ) , 'initial_url' : conditional_escape ( value . url ) , } | Return value - related substitutions . |
51,840 | def is_restricted ( self ) : return ( not hasattr ( self . choices , 'queryset' ) or self . choices . queryset . count ( ) > settings . FOREIGN_KEY_MAX_SELECBOX_ENTRIES ) | Returns True or False according to number of objects in queryset . If queryset contains too much objects the widget will be restricted and won t be used select box with choices . |
51,841 | def city ( name = None ) : info = find_info ( name ) os . environ [ 'OPEN311_CITY_INFO' ] = dumps ( info ) return Three ( ** info ) | Store the city that will be queried against . |
51,842 | def dev ( endpoint , ** kwargs ) : kwargs [ 'endpoint' ] = endpoint os . environ [ 'OPEN311_CITY_INFO' ] = dumps ( kwargs ) return Three ( ** kwargs ) | Use an endpoint and any additional keyword arguments rather than one of the pre - defined cities . Similar to the city function but useful for development . |
51,843 | def display_object_data ( obj , field_name , request = None ) : from is_core . forms . utils import ReadonlyValue value , _ , _ = get_readonly_field_data ( field_name , obj ) return display_for_value ( value . humanized_value if isinstance ( value , ReadonlyValue ) else value , request = request ) | Returns humanized value of model object that can be rendered to HTML or returned as part of REST |
51,844 | def display_for_value ( value , request = None ) : from is_core . utils . compatibility import admin_display_for_value if request and isinstance ( value , Model ) : return render_model_object_with_link ( request , value ) else : return ( ( value and ugettext ( 'Yes' ) or ugettext ( 'No' ) ) if isinstance ( value , bool ) else admin_display_for_value ( value ) ) | Converts humanized value |
51,845 | def get_url_from_model_core ( request , obj ) : from is_core . site import get_model_core model_core = get_model_core ( obj . __class__ ) if model_core and hasattr ( model_core , 'ui_patterns' ) : edit_pattern = model_core . ui_patterns . get ( 'detail' ) return ( edit_pattern . get_url_string ( request , obj = obj ) if edit_pattern and edit_pattern . has_permission ( 'get' , request , obj = obj ) else None ) else : return None | Returns object URL from model core . |
51,846 | def get_obj_url ( request , obj ) : if ( is_callable ( getattr ( obj , 'get_absolute_url' , None ) ) and ( not hasattr ( obj , 'can_see_edit_link' ) or ( is_callable ( getattr ( obj , 'can_see_edit_link' , None ) ) and obj . can_see_edit_link ( request ) ) ) ) : return call_method_with_unknown_input ( obj . get_absolute_url , request = request ) else : return get_url_from_model_core ( request , obj ) | Returns object URL if current logged user has permissions to see the object |
51,847 | def get_link_or_none ( pattern_name , request , view_kwargs = None ) : from is_core . patterns import reverse_pattern pattern = reverse_pattern ( pattern_name ) assert pattern is not None , 'Invalid pattern name {}' . format ( pattern_name ) if pattern . has_permission ( 'get' , request , view_kwargs = view_kwargs ) : return pattern . get_url_string ( request , view_kwargs = view_kwargs ) else : return None | Helper that generate URL prom pattern name and kwargs and check if current request has permission to open the URL . If not None is returned . |
51,848 | def protect_api ( uuid = None , ** kwargs ) : bucket , version_id , key = uuid . split ( ':' , 2 ) g . obj = ObjectResource . get_object ( bucket , key , version_id ) return g . obj | Retrieve object and check permissions . |
51,849 | def image_opener ( key ) : if hasattr ( g , 'obj' ) : obj = g . obj else : obj = protect_api ( key ) fp = obj . file . storage ( ) . open ( 'rb' ) if HAS_IMAGEMAGICK and obj . mimetype in [ 'application/pdf' , 'text/plain' ] : first_page = Image ( Image ( fp ) . sequence [ 0 ] ) tempfile_ = tempfile . TemporaryFile ( ) with first_page . convert ( format = 'png' ) as converted : converted . save ( file = tempfile_ ) return tempfile_ return fp | Handler to locate file based on key . |
51,850 | def tables ( self ) : if os . name == "posix" : mdb_tables = sh . Command ( "mdb-tables" ) tables_list = mdb_tables ( '-1' , self . path ) . split ( '\n' ) condition = lambda t : t and not t . startswith ( 'MSys' ) return [ t . lower ( ) for t in tables_list if condition ( t ) ] return [ table [ 2 ] . lower ( ) for table in self . own_cursor . tables ( ) if not table [ 2 ] . startswith ( 'MSys' ) ] | The complete list of tables . |
51,851 | def table_as_df ( self , table_name ) : self . table_must_exist ( table_name ) query = "SELECT * FROM `%s`" % table_name . lower ( ) return pandas . read_sql ( query , self . own_conn ) | Return a table as a dataframe . |
51,852 | def count_rows ( self , table_name ) : self . table_must_exist ( table_name ) query = "SELECT COUNT (*) FROM `%s`" % table_name . lower ( ) self . own_cursor . execute ( query ) return int ( self . own_cursor . fetchone ( ) [ 0 ] ) | Return the number of entries in a table by counting them . |
51,853 | def tables_with_counts ( self ) : table_to_count = lambda t : self . count_rows ( t ) return zip ( self . tables , map ( table_to_count , self . tables ) ) | Return the number of entries in all table . |
51,854 | def convert_to_sqlite ( self , destination = None , method = "shell" , progress = False ) : if progress : progress = tqdm . tqdm else : progress = lambda x : x if destination is None : destination = self . replace_extension ( 'sqlite' ) destination . remove ( ) if method == 'shell' : return self . sqlite_by_shell ( destination ) if method == 'object' : return self . sqlite_by_object ( destination , progress ) if method == 'dataframe' : return self . sqlite_by_df ( destination , progress ) | Who wants to use Access when you can deal with SQLite databases instead? |
51,855 | def sqlite_by_shell ( self , destination ) : script_path = new_temp_path ( ) self . sqlite_dump_shell ( script_path ) shell_output ( 'sqlite3 -bail -init "%s" "%s" .quit' % ( script , destination ) ) script . remove ( ) | Method with shell and a temp file . This is hopefully fast . |
51,856 | def sqlite_by_object ( self , destination , progress ) : db = SQLiteDatabase ( destination ) db . create ( ) for script in self . sqlite_dump_string ( progress ) : db . cursor . executescript ( script ) db . close ( ) | This is probably not very fast . |
51,857 | def sqlite_by_df ( self , destination , progress ) : db = SQLiteDatabase ( destination ) db . create ( ) for table in progress ( self . real_tables ) : self [ table ] . to_sql ( table , con = db . connection ) db . close ( ) | Is this fast? |
51,858 | def sqlite_dump_string ( self , progress ) : mdb_schema = sh . Command ( "mdb-schema" ) yield mdb_schema ( self . path , "sqlite" ) . encode ( 'utf8' ) yield "BEGIN TRANSACTION;\n" mdb_export = sh . Command ( "mdb-export" ) for table in progress ( self . tables ) : yield mdb_export ( '-I' , 'sqlite' , self . path , table ) . encode ( 'utf8' ) yield "END TRANSACTION;\n" | Generate a text dump compatible with SQLite . By yielding every table one by one as a byte string . |
51,859 | def import_table ( self , source , table_name ) : wsl = sh . Command ( "wsl.exe" ) table_schema = wsl ( "-e" , "mdb-schema" , "-T" , table_name , source . wsl_style , "access" ) table_contents = wsl ( "-e" , "mdb-export" , "-I" , "access" , source . wsl_style , table_name ) table_schema = ' ' . join ( l for l in table_schema . split ( '\n' ) if not l . startswith ( "--" ) ) self . cursor . execute ( str ( table_schema ) ) self . cursor . execute ( str ( table_contents ) ) | Copy a table from another Access database to this one . Requires that you have mdbtools command line executables installed in a Windows Subsystem for Linux environment . |
51,860 | def create ( cls , destination ) : mdb_gz_b64 = pristine = StringIO ( ) pristine . write ( base64 . b64decode ( mdb_gz_b64 ) ) pristine . seek ( 0 ) pristine = gzip . GzipFile ( fileobj = pristine , mode = 'rb' ) with open ( destination , 'wb' ) as handle : shutil . copyfileobj ( pristine , handle ) return cls ( destination ) | Create a new empty MDB at destination . |
51,861 | def tables ( self ) : self . own_connection . row_factory = sqlite3 . Row self . own_cursor . execute ( 'SELECT name from sqlite_master where type="table";' ) result = [ x [ 0 ] . encode ( 'ascii' ) for x in self . own_cursor . fetchall ( ) ] self . own_connection . row_factory = self . factory return result | The complete list of SQL tables . |
51,862 | def new_connection ( self ) : if not self . prepared : self . prepare ( ) con = sqlite3 . connect ( self . path , isolation_level = self . isolation ) con . row_factory = self . factory if self . text_fact : con . text_factory = self . text_fact return con | Make a new connection . |
51,863 | def prepare ( self ) : if not os . path . exists ( self . path ) : if self . retrieve : print ( "Downloading SQLite3 database..." ) download_from_url ( self . retrieve , self . path , progress = True ) else : raise Exception ( "The file '" + self . path + "' does not exist." ) self . check_format ( ) if self . known_md5 : assert self . known_md5 == self . md5 self . prepared = True | Check that the file exists optionally downloads it . Checks that the file is indeed an SQLite3 database . Optionally check the MD5 . |
51,864 | def create ( self , columns = None , type_map = None , overwrite = False ) : if self . count_bytes > 0 : if overwrite : self . remove ( ) else : raise Exception ( "File exists already at '%s'" % self ) if columns is None : self . touch ( ) else : self . add_table ( self . main_table , columns = columns , type_map = type_map ) | Create a new database with a certain schema . |
51,865 | def get_columns_of_table ( self , table = None ) : if table is None : table = self . main_table if not table in self . tables : return [ ] self . own_cursor . execute ( 'SELECT * from "%s" LIMIT 1;' % table ) columns = [ x [ 0 ] for x in self . own_cursor . description ] self . cursor . fetchall ( ) return columns | Return the list of columns for a particular table by querying the SQL for the complete list of column names . |
51,866 | def count_entries ( self , table = None ) : if table is None : table = self . main_table self . own_cursor . execute ( 'SELECT COUNT(1) FROM "%s";' % table ) return int ( self . own_cursor . fetchone ( ) [ 0 ] ) | How many rows in a table . |
51,867 | def get_first ( self , table = None ) : if table is None : table = self . main_table query = 'SELECT * FROM "%s" LIMIT 1;' % table return self . own_cursor . execute ( query ) . fetchone ( ) | Just the first entry . |
51,868 | def get_last ( self , table = None ) : if table is None : table = self . main_table query = 'SELECT * FROM "%s" ORDER BY ROWID DESC LIMIT 1;' % table return self . own_cursor . execute ( query ) . fetchone ( ) | Just the last entry . |
51,869 | def get_number ( self , num , table = None ) : if table is None : table = self . main_table self . own_cursor . execute ( 'SELECT * from "%s" LIMIT 1 OFFSET %i;' % ( self . main_table , num ) ) return self . own_cursor . fetchone ( ) | Get a specific entry by its number . |
51,870 | def get_entry ( self , key , column = None , table = None ) : if table is None : table = self . main_table if column is None : column = "id" if isinstance ( key , basestring ) : key = key . replace ( "'" , "''" ) query = 'SELECT * from "%s" where "%s"=="%s" LIMIT 1;' query = query % ( table , column , key ) self . own_cursor . execute ( query ) return self . own_cursor . fetchone ( ) | Get a specific entry . |
51,871 | def get_and_order ( self , ids , column = None , table = None ) : command = ordered = ',' . join ( map ( str , ids ) ) rowids = '\n' . join ( "WHEN '%s' THEN %s" % ( row , i ) for i , row in enumerate ( ids ) ) command = command % ( ordered , rowids ) | Get specific entries and order them in the same way . |
51,872 | def import_table ( self , source , table_name ) : query = "SELECT * FROM `%s`" % table_name . lower ( ) df = pandas . read_sql ( query , source . connection ) df . to_sql ( table_name , con = self . own_connection ) | Copy a table from another SQLite database to this one . |
51,873 | def jsonify ( self , status_code = None , message = None , headers = None ) : if status_code is None : status_code = self . status_code if message is None : message = self . message if headers is None : headers = self . headers response = flask . jsonify ( { 'status_code' : status_code , 'error' : repr ( self ) , 'message' : message , } ) if status_code is not None : response . status_code = status_code if headers is not None : response . headers = headers return response | Returns a representation of the error in a jsonic form that is compatible with flask s error handling . |
51,874 | def humanized_model_to_dict ( instance , readonly_fields , fields = None , exclude = None ) : opts = instance . _meta data = { } for f in itertools . chain ( opts . concrete_fields , opts . private_fields , opts . many_to_many ) : if not getattr ( f , 'editable' , False ) : continue if fields and f . name not in fields : continue if f . name not in readonly_fields : continue if exclude and f . name in exclude : continue if f . humanized : data [ f . name ] = f . humanized ( getattr ( instance , f . name ) , instance ) return data | Returns a dict containing the humanized data in instance suitable for passing as a Form s initial keyword argument . |
51,875 | def find_info ( name = None ) : if not name : return list ( servers . keys ( ) ) name = name . lower ( ) if name in servers : info = servers [ name ] else : raise CityNotFound ( "Could not find the specified city: %s" % name ) return info | Find the needed city server information . |
51,876 | def process ( self , msg , kwargs ) : prefixed_dict = { } prefixed_dict [ 'repo_vcs' ] = self . bin_name prefixed_dict [ 'repo_name' ] = self . name kwargs [ "extra" ] = prefixed_dict return msg , kwargs | Add additional context information for loggers . |
51,877 | def branches ( self ) : result = self . git ( self . default + [ 'branch' , '-a' , '--no-color' ] ) return [ l . strip ( ' *\n' ) for l in result . split ( '\n' ) if l . strip ( ' *\n' ) ] | All branches in a list |
51,878 | def re_clone ( self , repo_dir ) : self . git ( 'clone' , self . remote_url , repo_dir ) return GitRepo ( repo_dir ) | Clone again somewhere else |
51,879 | def path ( self ) : yield self if not self . parent : return for node in self . parent . path : yield node | Iterate over all parent nodes and one - self . |
51,880 | def others ( self ) : if not self . parent : return yield self . parent for sibling in self . parent . children . values ( ) : if sibling . name == self . name : continue for node in sibling : yield node for node in self . parent . others : yield node | Iterate over all nodes of the tree excluding one self and one s children . |
51,881 | def get_level ( self , level = 2 ) : if level == 1 : for child in self . children . values ( ) : yield child else : for child in self . children . values ( ) : for node in child . get_level ( level - 1 ) : yield node | Get all nodes that are exactly this far away . |
51,882 | def mend ( self , length ) : if length == 0 : raise Exception ( "Can't mend the root !" ) if length == 1 : return self . children = OrderedDict ( ( node . name , node ) for node in self . get_level ( length ) ) for child in self . children . values ( ) : child . parent = self | Cut all branches from this node to its children and adopt all nodes at certain level . |
51,883 | def get_info ( self , apply_tag = None , info_dicts = False ) : raw_infos = self . fetcher . fetch ( * self . info_files ) raw_info = parse . merge_infos ( * raw_infos , info_dicts = info_dicts ) info = parse . parse_info ( raw_info , apply_tag = apply_tag ) return info | Get data from distroinfo instance . |
51,884 | def run ( create_application , settings = None , log_config = None ) : from . import runner app_settings = { } if settings is None else settings . copy ( ) debug_mode = bool ( app_settings . get ( 'debug' , int ( os . environ . get ( 'DEBUG' , 0 ) ) != 0 ) ) app_settings [ 'debug' ] = debug_mode logging . config . dictConfig ( _get_logging_config ( debug_mode ) if log_config is None else log_config ) port_number = int ( app_settings . pop ( 'port' , os . environ . get ( 'PORT' , 8000 ) ) ) num_procs = int ( app_settings . pop ( 'number_of_procs' , '0' ) ) server = runner . Runner ( create_application ( ** app_settings ) ) server . run ( port_number , num_procs ) | Run a Tornado create_application . |
51,885 | def obtain ( self ) : self . check_destination ( ) url = self . url cmd = [ 'clone' , '--progress' ] if self . git_shallow : cmd . extend ( [ '--depth' , '1' ] ) if self . tls_verify : cmd . extend ( [ '-c' , 'http.sslVerify=false' ] ) cmd . extend ( [ url , self . path ] ) self . info ( 'Cloning.' ) self . run ( cmd , log_in_real_time = True ) if self . remotes : for r in self . remotes : self . error ( 'Adding remote %s <%s>' % ( r [ 'remote_name' ] , r [ 'url' ] ) ) self . remote_set ( name = r [ 'remote_name' ] , url = r [ 'url' ] ) self . info ( 'Initializing submodules.' ) self . run ( [ 'submodule' , 'init' ] , log_in_real_time = True ) cmd = [ 'submodule' , 'update' , '--recursive' , '--init' ] cmd . extend ( self . git_submodules ) self . run ( cmd , log_in_real_time = True ) | Retrieve the repository clone if doesn t exist . |
51,886 | def remotes_get ( self ) : remotes = { } cmd = self . run ( [ 'remote' ] ) ret = filter ( None , cmd . split ( '\n' ) ) for remote_name in ret : remotes [ remote_name ] = self . remote_get ( remote_name ) return remotes | Return remotes like git remote - v . |
51,887 | def remote_get ( self , remote = 'origin' ) : try : ret = self . run ( [ 'remote' , 'show' , '-n' , remote ] ) lines = ret . split ( '\n' ) remote_fetch_url = lines [ 1 ] . replace ( 'Fetch URL: ' , '' ) . strip ( ) remote_push_url = lines [ 2 ] . replace ( 'Push URL: ' , '' ) . strip ( ) if remote_fetch_url != remote and remote_push_url != remote : res = ( remote_fetch_url , remote_push_url ) return res else : return None except exc . LibVCSException : return None | Get the fetch and push URL for a specified remote name . |
51,888 | def remote_set ( self , url , name = 'origin' ) : url = self . chomp_protocol ( url ) if self . remote_get ( name ) : self . run ( [ 'remote' , 'rm' , 'name' ] ) self . run ( [ 'remote' , 'add' , name , url ] ) return self . remote_get ( remote = name ) | Set remote with name and URL like git remote add . |
51,889 | def chomp_protocol ( url ) : if '+' in url : url = url . split ( '+' , 1 ) [ 1 ] scheme , netloc , path , query , frag = urlparse . urlsplit ( url ) rev = None if '@' in path : path , rev = path . rsplit ( '@' , 1 ) url = urlparse . urlunsplit ( ( scheme , netloc , path , query , '' ) ) if url . startswith ( 'ssh://git@github.com/' ) : url = url . replace ( 'ssh://' , 'git+ssh://' ) elif '://' not in url : assert 'file:' not in url url = url . replace ( 'git+' , 'git+ssh://' ) url = url . replace ( 'ssh://' , '' ) return url | Return clean VCS url from RFC - style url |
51,890 | def _log ( self , message , stream , color = None , newline = False ) : if color and self . color_term : colorend = Logger . COLOR_END else : color = colorend = '' stream . write ( '{color}{message}{colorend}\n' . format ( color = color , message = message , colorend = colorend ) ) if newline : sys . stdout . write ( '\n' ) stream . flush ( ) | Logs the message to the sys . stdout or sys . stderr stream . |
51,891 | def info ( self , message ) : return self . _log ( message = message . upper ( ) , stream = sys . stdout ) | Logs an informational message to stdout . |
51,892 | def passed ( self , message ) : return self . _log ( message = message . upper ( ) , stream = sys . stdout , color = Logger . COLOR_GREEN_BOLD , newline = True ) | Logs as whole test result as PASSED . |
51,893 | def failed ( self , message ) : return self . _log ( message = message . upper ( ) , stream = sys . stderr , color = Logger . COLOR_RED_BOLD , newline = True ) | Logs as whole test result as FAILED . |
51,894 | def logs ( self ) : if not self . parent . loaded : self . parent . load ( ) logs = self . parent . p . logs_dir . flat_directories logs . sort ( key = lambda x : x . mod_time ) return logs | Find the log directory and return all the logs sorted . |
51,895 | def run_locally ( self , steps = None , ** kwargs ) : self . slurm_job = LoggedJobSLURM ( self . command ( steps ) , base_dir = self . parent . p . logs_dir , modules = self . modules , ** kwargs ) self . slurm_job . run_locally ( ) | A convenience method to run the same result as a SLURM job but locally in a non - blocking way . |
51,896 | def run_slurm ( self , steps = None , ** kwargs ) : params = self . extra_slurm_params params . update ( kwargs ) if 'time' not in params : params [ 'time' ] = self . default_time if 'job_name' not in params : params [ 'job_name' ] = self . job_name if 'email' not in params : params [ 'email' ] = None if 'dependency' not in params : params [ 'dependency' ] = 'singleton' self . slurm_job = LoggedJobSLURM ( self . command ( steps ) , base_dir = self . parent . p . logs_dir , modules = self . modules , ** params ) return self . slurm_job . run ( ) | Run the steps via the SLURM queue . |
51,897 | def smart_generic_inlineformset_factory ( model , request , form = ModelForm , formset = BaseGenericInlineFormSet , ct_field = 'content_type' , fk_field = 'object_id' , fields = None , exclude = None , extra = 3 , can_order = False , can_delete = True , min_num = None , max_num = None , formfield_callback = None , widgets = None , validate_min = False , validate_max = False , localized_fields = None , labels = None , help_texts = None , error_messages = None , formreadonlyfield_callback = None , readonly_fields = None , for_concrete_model = True , readonly = False ) : opts = model . _meta ct_field = opts . get_field ( ct_field ) if not isinstance ( ct_field , models . ForeignKey ) or ct_field . related_model != ContentType : raise Exception ( "fk_name '%s' is not a ForeignKey to ContentType" % ct_field ) fk_field = opts . get_field ( fk_field ) if exclude is not None : exclude = list ( exclude ) exclude . extend ( [ ct_field . name , fk_field . name ] ) else : exclude = [ ct_field . name , fk_field . name ] kwargs = { 'form' : form , 'formfield_callback' : formfield_callback , 'formset' : formset , 'extra' : extra , 'can_delete' : can_delete , 'can_order' : can_order , 'fields' : fields , 'exclude' : exclude , 'max_num' : max_num , 'min_num' : min_num , 'widgets' : widgets , 'validate_min' : validate_min , 'validate_max' : validate_max , 'localized_fields' : localized_fields , 'formreadonlyfield_callback' : formreadonlyfield_callback , 'readonly_fields' : readonly_fields , 'readonly' : readonly , 'labels' : labels , 'help_texts' : help_texts , 'error_messages' : error_messages , } FormSet = smartmodelformset_factory ( model , request , ** kwargs ) FormSet . ct_field = ct_field FormSet . ct_fk_field = fk_field FormSet . for_concrete_model = for_concrete_model return FormSet | Returns a GenericInlineFormSet for the given kwargs . |
51,898 | def rename ( self , name ) : self . ec2 . create_tags ( Resources = [ self . instance_id ] , Tags = [ { 'Key' : 'Name' , 'Value' : name } ] ) self . refresh_info ( ) | Set the name of the machine . |
51,899 | def update_ssh_config ( self , path = "~/.ssh/config" ) : import sshconf config = sshconf . read_ssh_config ( os . path . expanduser ( path ) ) if not config . host ( self . instance_name ) : config . add ( self . instance_name ) config . set ( self . instance_name , Hostname = self . dns ) config . write ( os . path . expanduser ( path ) ) | Put the DNS into the ssh config file . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.