idx int64 0 63k | question stringlengths 53 5.28k | target stringlengths 5 805 |
|---|---|---|
29,300 | def _check_servers ( self ) : new_servers = [ ] def check_format ( server ) : if server . scheme not in [ "thrift" , "http" , "https" ] : raise RuntimeError ( "Unable to recognize protocol: \"%s\"" % _type ) if server . scheme == "thrift" : if not thrift_connect : raise RuntimeError ( "If you want to use thrift, please... | Check the servers variable and convert in a valid tuple form |
29,301 | def _init_connection ( self ) : if not self . servers : raise RuntimeError ( "No server defined" ) server = random . choice ( self . servers ) if server . scheme in [ "http" , "https" ] : self . connection = http_connect ( [ server for server in self . servers if server . scheme in [ "http" , "https" ] ] , timeout = se... | Create initial connection pool |
29,302 | def _discovery ( self ) : data = self . cluster_nodes ( ) self . cluster_name = data [ "cluster_name" ] for _ , nodedata in list ( data [ "nodes" ] . items ( ) ) : server = nodedata [ 'http_address' ] . replace ( "]" , "" ) . replace ( "inet[" , "http:/" ) if server not in self . servers : self . servers . append ( ser... | Find other servers asking nodes to given server |
29,303 | def _set_bulk_size ( self , bulk_size ) : self . _bulk_size = bulk_size self . bulker . bulk_size = bulk_size | Set the bulk size |
29,304 | def _set_raise_on_bulk_item_failure ( self , raise_on_bulk_item_failure ) : self . _raise_on_bulk_item_failure = raise_on_bulk_item_failure self . bulker . raise_on_bulk_item_failure = raise_on_bulk_item_failure | Set the raise_on_bulk_item_failure parameter |
29,305 | def _validate_indices ( self , indices = None ) : if indices is None : indices = self . default_indices if isinstance ( indices , six . string_types ) : indices = [ indices ] return indices | Return a valid list of indices . |
29,306 | def validate_types ( self , types = None ) : types = types or self . default_types if types is None : types = [ ] if isinstance ( types , six . string_types ) : types = [ types ] return types | Return a valid list of types . |
29,307 | def create_bulker ( self ) : return self . bulker_class ( self , bulk_size = self . bulk_size , raise_on_bulk_item_failure = self . raise_on_bulk_item_failure ) | Create a bulker object and return it to allow to manage custom bulk policies |
29,308 | def ensure_index ( self , index , mappings = None , settings = None , clear = False ) : mappings = mappings or [ ] if isinstance ( mappings , dict ) : mappings = [ mappings ] exists = self . indices . exists_index ( index ) if exists and not mappings and not clear : return if exists and clear : self . indices . delete_... | Ensure if an index with mapping exists |
29,309 | def collect_info ( self ) : try : info = { } res = self . _send_request ( 'GET' , "/" ) info [ 'server' ] = { } info [ 'server' ] [ 'name' ] = res [ 'name' ] info [ 'server' ] [ 'version' ] = res [ 'version' ] info [ 'allinfo' ] = res info [ 'status' ] = self . cluster . status ( ) info [ 'aliases' ] = self . indices .... | Collect info about the connection and fill the info dictionary . |
29,310 | def index_raw_bulk ( self , header , document ) : self . bulker . add ( "%s%s" % ( header , document ) ) return self . flush_bulk ( ) | Function helper for fast inserting |
29,311 | def index ( self , doc , index , doc_type , id = None , parent = None , force_insert = False , op_type = None , bulk = False , version = None , querystring_args = None , ttl = None ) : if querystring_args is None : querystring_args = { } if bulk : if op_type is None : op_type = "index" if force_insert : op_type = "crea... | Index a typed JSON document into a specific index and make it searchable . |
29,312 | def put_file ( self , filename , index , doc_type , id = None , name = None ) : if id is None : request_method = 'POST' else : request_method = 'PUT' path = make_path ( index , doc_type , id ) doc = file_to_attachment ( filename ) if name : doc [ "_name" ] = name return self . _send_request ( request_method , path , do... | Store a file in a index |
29,313 | def get_file ( self , index , doc_type , id = None ) : data = self . get ( index , doc_type , id ) return data [ '_name' ] , base64 . standard_b64decode ( data [ 'content' ] ) | Return the filename and memory data stream |
29,314 | def update_by_function ( self , extra_doc , index , doc_type , id , querystring_args = None , update_func = None , attempts = 2 ) : if querystring_args is None : querystring_args = { } if update_func is None : update_func = dict . update for attempt in range ( attempts - 1 , - 1 , - 1 ) : current_doc = self . get ( ind... | Update an already indexed typed JSON document . |
29,315 | def partial_update ( self , index , doc_type , id , doc = None , script = None , params = None , upsert = None , querystring_args = None ) : if querystring_args is None : querystring_args = { } if doc is None and script is None : raise InvalidQuery ( "script or doc can not both be None" ) if doc is None : cmd = { "scri... | Partially update a document with a script |
29,316 | def delete ( self , index , doc_type , id , bulk = False , ** query_params ) : if bulk : cmd = { "delete" : { "_index" : index , "_type" : doc_type , "_id" : id } } self . bulker . add ( json . dumps ( cmd , cls = self . encoder ) ) return self . flush_bulk ( ) path = make_path ( index , doc_type , id ) return self . _... | Delete a typed JSON document from a specific index based on its id . If bulk is True the delete operation is put in bulk mode . |
29,317 | def delete_by_query ( self , indices , doc_types , query , ** query_params ) : path = self . _make_path ( indices , doc_types , '_query' ) body = { "query" : query . serialize ( ) } return self . _send_request ( 'DELETE' , path , body , query_params ) | Delete documents from one or more indices and one or more types based on a query . |
29,318 | def exists ( self , index , doc_type , id , ** query_params ) : path = make_path ( index , doc_type , id ) return self . _send_request ( 'HEAD' , path , params = query_params ) | Return if a document exists |
29,319 | def get ( self , index , doc_type , id , fields = None , model = None , ** query_params ) : path = make_path ( index , doc_type , id ) if fields is not None : query_params [ "fields" ] = "," . join ( fields ) model = model or self . model return model ( self , self . _send_request ( 'GET' , path , params = query_params... | Get a typed JSON document from an index based on its id . |
29,320 | def factory_object ( self , index , doc_type , data = None , id = None ) : data = data or { } obj = self . model ( ) obj . _meta . index = index obj . _meta . type = doc_type obj . _meta . connection = self if id : obj . _meta . id = id if data : obj . update ( data ) return obj | Create a stub object to be manipulated |
29,321 | def mget ( self , ids , index = None , doc_type = None , ** query_params ) : if not ids : return [ ] body = [ ] for value in ids : if isinstance ( value , tuple ) : if len ( value ) == 3 : a , b , c = value body . append ( { "_index" : a , "_type" : b , "_id" : c } ) elif len ( value ) == 4 : a , b , c , d = value body... | Get multi JSON documents . |
29,322 | def search_raw ( self , query , indices = None , doc_types = None , headers = None , ** query_params ) : from . query import Search , Query if isinstance ( query , Query ) : query = query . search ( ) if isinstance ( query , Search ) : query = query . serialize ( ) body = self . _encode_query ( query ) path = self . _m... | Execute a search against one or more indices to get the search hits . |
29,323 | def search ( self , query , indices = None , doc_types = None , model = None , scan = False , headers = None , ** query_params ) : if isinstance ( query , Search ) : search = query elif isinstance ( query , ( Query , dict ) ) : search = Search ( query ) else : raise InvalidQuery ( "search() must be supplied with a Sear... | Execute a search against one or more indices to get the resultset . |
29,324 | def suggest ( self , name , text , field , type = 'term' , size = None , params = None , ** kwargs ) : from . query import Suggest suggest = Suggest ( ) suggest . add ( text , name , field , type = type , size = size , params = params ) return self . suggest_from_object ( suggest , ** kwargs ) | Execute suggester of given type . |
29,325 | def count ( self , query = None , indices = None , doc_types = None , ** query_params ) : from . query import MatchAllQuery if query is None : query = MatchAllQuery ( ) body = { "query" : query . serialize ( ) } path = self . _make_path ( indices , doc_types , "_count" ) return self . _send_request ( 'GET' , path , bod... | Execute a query against one or more indices and get hits count . |
29,326 | def create_river ( self , river , river_name = None ) : if isinstance ( river , River ) : body = river . serialize ( ) river_name = river . name else : body = river return self . _send_request ( 'PUT' , '/_river/%s/_meta' % river_name , body ) | Create a river |
29,327 | def delete_river ( self , river , river_name = None ) : if isinstance ( river , River ) : river_name = river . name return self . _send_request ( 'DELETE' , '/_river/%s/' % river_name ) | Delete a river |
29,328 | def morelikethis ( self , index , doc_type , id , fields , ** query_params ) : path = make_path ( index , doc_type , id , '_mlt' ) query_params [ 'mlt_fields' ] = ',' . join ( fields ) body = query_params [ "body" ] if "body" in query_params else None return self . _send_request ( 'GET' , path , body = body , params = ... | Execute a more like this search query against one or more fields and get back search hits . |
29,329 | def create_percolator ( self , index , name , query , ** kwargs ) : if isinstance ( query , Query ) : query = { "query" : query . serialize ( ) } if not isinstance ( query , dict ) : raise InvalidQuery ( "create_percolator() must be supplied with a Query object or dict" ) if kwargs : query . update ( kwargs ) path = ma... | Create a percolator document |
29,330 | def percolate ( self , index , doc_types , query ) : if doc_types is None : raise RuntimeError ( 'percolate() must be supplied with at least one doc_type' ) path = self . _make_path ( index , doc_types , '_percolate' ) body = self . _encode_query ( query ) return self . _send_request ( 'GET' , path , body ) | Match a query with a document |
29,331 | def fix_facets ( self ) : facets = self . facets for key in list ( facets . keys ( ) ) : _type = facets [ key ] . get ( "_type" , "unknown" ) if _type == "date_histogram" : for entry in facets [ key ] . get ( "entries" , [ ] ) : for k , v in list ( entry . items ( ) ) : if k in [ "count" , "max" , "min" , "total_count"... | This function convert date_histogram facets to datetime |
29,332 | def fix_aggs ( self ) : aggs = self . aggs for key in list ( aggs . keys ( ) ) : _type = aggs [ key ] . get ( "_type" , "unknown" ) if _type == "date_histogram" : for entry in aggs [ key ] . get ( "entries" , [ ] ) : for k , v in list ( entry . items ( ) ) : if k in [ "count" , "max" , "min" , "total_count" , "mean" , ... | This function convert date_histogram aggs to datetime |
29,333 | def fix_keys ( self ) : if not self . valid : return for hit in self . _results [ 'hits' ] [ 'hits' ] : for key , item in list ( hit . items ( ) ) : if key . startswith ( "_" ) : hit [ key [ 1 : ] ] = item del hit [ key ] | Remove the _ from the keys of the results |
29,334 | def clean_highlight ( self ) : if not self . valid : return for hit in self . _results [ 'hits' ] [ 'hits' ] : if 'highlight' in hit : hl = hit [ 'highlight' ] for key , item in list ( hl . items ( ) ) : if not item : del hl [ key ] | Remove the empty highlight |
29,335 | def add_field ( self , name , fragment_size = 150 , number_of_fragments = 3 , fragment_offset = None , order = "score" , type = None ) : data = { } if fragment_size : data [ 'fragment_size' ] = fragment_size if number_of_fragments is not None : data [ 'number_of_fragments' ] = number_of_fragments if fragment_offset is ... | Add a field to Highlinghter |
29,336 | def iterator ( self ) : if not self . _result_cache : len ( self ) for r in self . _result_cache : yield r | An iterator over the results from applying this QuerySet to the database . |
29,337 | def in_bulk ( self , id_list ) : if not id_list : return { } qs = self . _clone ( ) qs . add_filter ( ( 'pk__in' , id_list ) ) qs . _clear_ordering ( force_empty = True ) return dict ( [ ( obj . _get_pk_val ( ) , obj ) for obj in qs ] ) | Returns a dictionary mapping each of the given IDs to the object with that ID . |
29,338 | def complex_filter ( self , filter_obj ) : if isinstance ( filter_obj , Filter ) : clone = self . _clone ( ) clone . _filters . add ( filter_obj ) return clone return self . _filter_or_exclude ( None , ** filter_obj ) | Returns a new QuerySet instance with filter_obj added to the filters . |
29,339 | def reverse ( self ) : clone = self . _clone ( ) assert self . _ordering , "You need to set an ordering for reverse" ordering = [ ] for order in self . _ordering : for k , v in order . items ( ) : if v == "asc" : ordering . append ( { k : "desc" } ) else : ordering . append ( { k : "asc" } ) clone . _ordering = orderin... | Reverses the ordering of the QuerySet . |
29,340 | def only ( self , * fields ) : clone = self . _clone ( ) clone . _fields = fields return clone | Essentially the opposite of defer . Only the fields passed into this method and that are not already specified as deferred are loaded immediately when the queryset is evaluated . |
29,341 | def using ( self , alias ) : clone = self . _clone ( ) clone . _index = alias return clone | Selects which database this QuerySet should excecute its query against . |
29,342 | def from_qs ( cls , qs , ** kwargs ) : assert issubclass ( cls , QuerySet ) , "%s is not a QuerySet subclass" % cls assert isinstance ( qs , QuerySet ) , "qs has to be an instance of queryset" return qs . _clone ( klass = cls , ** kwargs ) | Creates a new queryset using class cls using qs data . |
29,343 | def add_mapping ( self , data , name = None ) : from . mappings import DocumentObjectField from . mappings import NestedObject from . mappings import ObjectField if isinstance ( data , ( DocumentObjectField , ObjectField , NestedObject ) ) : self . mappings [ data . name ] = data . as_dict ( ) return if name : self . m... | Add a new mapping |
29,344 | def get_field ( name , data , default = "object" , document_object_field = None , is_document = False ) : if isinstance ( data , AbstractField ) : return data data = keys_to_string ( data ) _type = data . get ( 'type' , default ) if _type == "string" : return StringField ( name = name , ** data ) elif _type == "binary"... | Return a valid Field by given data |
29,345 | def get_properties_by_type ( self , type , recursive = True , parent_path = "" ) : if parent_path : parent_path += "." if isinstance ( type , str ) : if type == "*" : type = set ( MAPPING_NAME_TYPE . keys ( ) ) - set ( [ "nested" , "multi_field" , "multifield" ] ) else : type = [ type ] properties = [ ] for prop in lis... | Returns a sorted list of fields that match the type . |
29,346 | def get_property_by_name ( self , name ) : if "." not in name and name in self . properties : return self . properties [ name ] tokens = name . split ( "." ) object = self for token in tokens : if isinstance ( object , ( DocumentObjectField , ObjectField , NestedObject ) ) : if token in object . properties : object = o... | Returns a mapped object . |
29,347 | def get_available_facets ( self ) : result = [ ] for k , v in list ( self . properties . items ( ) ) : if isinstance ( v , DateField ) : if not v . tokenize : result . append ( ( k , "date" ) ) elif isinstance ( v , NumericFieldAbstract ) : result . append ( ( k , "numeric" ) ) elif isinstance ( v , StringField ) : if ... | Returns Available facets for the document |
29,348 | def get_datetime_properties ( self , recursive = True ) : res = { } for name , field in self . properties . items ( ) : if isinstance ( field , DateField ) : res [ name ] = field elif recursive and isinstance ( field , ObjectField ) : for n , f in field . get_datetime_properties ( recursive = recursive ) : res [ name +... | Returns a dict of property . path and property . |
29,349 | def get_meta ( self , subtype = None ) : if subtype : return DotDict ( self . _meta . get ( subtype , { } ) ) return self . _meta | Return the meta data . |
29,350 | def _process ( self , data ) : indices = [ ] for indexname , indexdata in list ( data . items ( ) ) : idata = [ ] for docname , docdata in list ( indexdata . get ( "mappings" , { } ) . items ( ) ) : o = get_field ( docname , docdata , document_object_field = self . document_object_field , is_document = True ) o . conne... | Process indexer data |
29,351 | def get_doctypes ( self , index , edges = True ) : if index not in self . indices : self . get_all_indices ( ) return self . indices . get ( index , { } ) | Returns a list of doctypes given an index |
29,352 | def get_doctype ( self , index , name ) : if index not in self . indices : self . get_all_indices ( ) return self . indices . get ( index , { } ) . get ( name , None ) | Returns a doctype given an index and a name |
29,353 | def get_property ( self , index , doctype , name ) : return self . indices [ index ] [ doctype ] . properties [ name ] | Returns a property of a given type |
29,354 | def migrate ( self , mapping , index , doc_type ) : old_mapping = self . get_doctype ( index , doc_type ) if not old_mapping : self . connection . indices . put_mapping ( doc_type = doc_type , mapping = mapping , indices = index ) return mapping mapping_diff = old_mapping . get_diff ( mapping ) if not mapping_diff : re... | Migrate a ES mapping |
29,355 | def add_field ( self , name , script , lang = None , params = None , ignore_failure = False ) : data = { } if lang : data [ "lang" ] = lang if script : data [ 'script' ] = script else : raise ScriptFieldsError ( "Script is required for script_fields definition" ) if params : if isinstance ( params , dict ) : if len ( p... | Add a field to script_fields |
29,356 | def add_parameter ( self , field_name , param_name , param_value ) : try : self . fields [ field_name ] [ 'params' ] [ param_name ] = param_value except Exception as ex : raise ScriptFieldsError ( "Error adding parameter %s with value %s :%s" % ( param_name , param_value , ex ) ) return self | Add a parameter to a field into script_fields |
29,357 | def add ( self , text , name , field , type = 'term' , size = None , params = None ) : func = None if type == 'completion' : func = self . add_completion elif type == 'phrase' : func = self . add_phrase elif type == 'term' : func = self . add_term else : raise InvalidQuery ( 'Invalid type' ) func ( text = text , name =... | Set the suggester of given type . |
29,358 | def add_highlight ( self , field , fragment_size = None , number_of_fragments = None , fragment_offset = None , type = None ) : if self . _highlight is None : self . _highlight = HighLighter ( "<b>" , "</b>" ) self . _highlight . add_field ( field , fragment_size , number_of_fragments , fragment_offset , type = type ) ... | Add a highlight field . |
29,359 | def add_index_boost ( self , index , boost ) : if boost is None : if index in self . index_boost : del ( self . index_boost [ index ] ) else : self . index_boost [ index ] = boost return self | Add a boost on an index . |
29,360 | def add ( self , filter_or_query ) : if isinstance ( filter_or_query , Filter ) : if self . queries : raise QueryError ( "A Query is required" ) self . filters . append ( filter_or_query ) elif isinstance ( filter_or_query , Query ) : if self . filters : raise QueryError ( "A Filter is required" ) self . queries . appe... | Add a filter or a list of filters to the query . |
29,361 | def get_names ( ) : return [ n . strip ( ) for n in codecs . open ( os . path . join ( "data" , "names.txt" ) , "rb" , 'utf8' ) . readlines ( ) ] | Return a list of names . |
29,362 | def ext_process ( listname , hostname , url , filepath , msg ) : from pyes import ES from pyes . exceptions import ClusterBlockException , NoServerAvailable import datetime _ES_SERVERS = [ '127.0.0.1:9500' ] _indexname = "mailman" _doctype = "mail" date = datetime . datetime . today ( ) try : iconn = ES ( _ES_SERVERS )... | Here s where you put your code to deal with the just archived message . |
29,363 | def main ( ) : listname = sys . argv [ 2 ] hostname = sys . argv [ 1 ] mlist = MailList . MailList ( listname , lock = False ) f = StringIO ( sys . stdin . read ( ) ) msg = email . message_from_file ( f , Message . Message ) h = HyperArch . HyperArchive ( mlist ) sequence = h . sequence h . processUnixMailbox ( f ) f .... | This is the mainline . |
29,364 | def make_path ( * path_components ) : path_components = [ quote ( component ) for component in path_components if component ] path = '/' . join ( path_components ) if not path . startswith ( '/' ) : path = '/' + path return path | Smash together the path components . Empty components will be ignored . |
29,365 | def clean_string ( text ) : if isinstance ( text , six . string_types ) : return text . translate ( UNI_SPECIAL_CHARS ) . strip ( ) return text . translate ( None , STR_SPECIAL_CHARS ) . strip ( ) | Remove Lucene reserved characters from query string |
29,366 | def keys_to_string ( data ) : if isinstance ( data , dict ) : for key in list ( data . keys ( ) ) : if isinstance ( key , six . string_types ) : value = data [ key ] val = keys_to_string ( value ) del data [ key ] data [ key . encode ( "utf8" , "ignore" ) ] = val return data | Function to convert all the unicode keys in string keys |
29,367 | def negate ( self ) : self . from_value , self . to_value = self . to_value , self . from_value self . include_lower , self . include_upper = self . include_upper , self . include_lower | Reverse the range |
29,368 | def raise_if_error ( status , result , request = None ) : assert isinstance ( status , int ) if status < 400 : return if status == 404 and isinstance ( result , dict ) and 'error' not in result : raise exceptions . NotFoundException ( "Item not found" , status , result , request ) if not isinstance ( result , dict ) or... | Raise an appropriate exception if the result is an error . |
29,369 | def _django_to_es_field ( self , field ) : from django . db import models prefix = "" if field . startswith ( "-" ) : prefix = "-" field = field . lstrip ( "-" ) if field in [ "id" , "pk" ] : return "_id" , models . AutoField try : dj_field , _ , _ , _ = self . model . _meta . get_field_by_name ( field ) if isinstance ... | We use this function in value_list and ordering to get the correct fields name |
29,370 | def none ( self ) : return EmptyQuerySet ( model = self . model , using = self . _using , connection = self . _connection ) | Returns an empty QuerySet . |
29,371 | def rescorer ( self , rescorer ) : clone = self . _clone ( ) clone . _rescorer = rescorer return clone | Returns a new QuerySet with a set rescorer . |
29,372 | def _get_filter_modifier ( self , field ) : tokens = field . split ( FIELD_SEPARATOR ) if len ( tokens ) == 1 : return field , "" if tokens [ - 1 ] in self . FILTER_OPERATORS . keys ( ) : return u'.' . join ( tokens [ : - 1 ] ) , tokens [ - 1 ] return u'.' . join ( tokens ) , "" | Detect the filter modifier |
29,373 | def _prepare_value ( self , value , dj_field = None ) : from django . db import models if isinstance ( value , ( six . string_types , int , float ) ) : return value elif isinstance ( value , SimpleLazyObject ) : return value . pk elif isinstance ( value , models . Model ) : if dj_field : if isinstance ( dj_field , mode... | Cook the value |
29,374 | def order_by ( self , * field_names ) : obj = self . _clone ( ) obj . _clear_ordering ( ) self . _insert_ordering ( obj , * field_names ) return obj | Returns a new QuerySet instance with the ordering changed . We have a special field _random |
29,375 | def index ( self , alias ) : clone = self . _clone ( ) clone . _index = alias return clone | Selects which database this QuerySet should execute its query against . |
29,376 | def size ( self , size ) : clone = self . _clone ( ) clone . _size = size return clone | Set the query size of this QuerySet should execute its query against . |
29,377 | def refresh ( self ) : connection = self . model . _meta . dj_connection return connection . connection . indices . refresh ( indices = connection . database ) | Refresh an index |
29,378 | def create_index_if_missing ( self , index , settings = None ) : try : return self . create_index ( index , settings ) except IndexAlreadyExistsException as e : return e . result | Creates an index if it doesn t already exist . |
29,379 | def get_indices ( self , include_aliases = False ) : state = self . conn . cluster . state ( ) status = self . status ( ) result = { } indices_status = status [ 'indices' ] indices_metadata = state [ 'metadata' ] [ 'indices' ] for index in sorted ( indices_status . keys ( ) ) : info = indices_status [ index ] try : num... | Get a dict holding an entry for each index which exists . |
29,380 | def get_closed_indices ( self ) : state = self . conn . cluster . state ( ) status = self . status ( ) indices_metadata = set ( state [ 'metadata' ] [ 'indices' ] . keys ( ) ) indices_status = set ( status [ 'indices' ] . keys ( ) ) return indices_metadata . difference ( indices_status ) | Get all closed indices . |
29,381 | def analyze ( self , text , index = None , analyzer = None , tokenizer = None , filters = None , field = None ) : if filters is None : filters = [ ] argsets = 0 args = { } if analyzer : args [ 'analyzer' ] = analyzer argsets += 1 if tokenizer or filters : if tokenizer : args [ 'tokenizer' ] = tokenizer if filters : arg... | Performs the analysis process on a text and return the tokens breakdown of the text |
29,382 | def save ( self , bulk = False , id = None , parent = None , routing = None , force = False ) : meta = self . _meta conn = meta [ 'connection' ] id = id or meta . get ( "id" , None ) parent = parent or meta . get ( 'parent' , None ) routing = routing or meta . get ( 'routing' , None ) qargs = None if routing : qargs = ... | Save the object and returns id |
29,383 | def get_id ( self ) : _id = self . _meta . get ( "id" , None ) if _id is None : _id = self . save ( ) return _id | Force the object saveing to get an id |
29,384 | def get_bulk ( self , create = False ) : result = [ ] op_type = "index" if create : op_type = "create" meta = self . _meta cmd = { op_type : { "_index" : meta . index , "_type" : meta . type } } if meta . parent : cmd [ op_type ] [ '_parent' ] = meta . parent if meta . version : cmd [ op_type ] [ '_version' ] = meta . ... | Return bulk code |
29,385 | def insert ( self , index , key , value ) : if key in self . keyOrder : n = self . keyOrder . index ( key ) del self . keyOrder [ n ] if n < index : index -= 1 self . keyOrder . insert ( index , key ) super ( SortedDict , self ) . __setitem__ ( key , value ) | Inserts the key value pair before the item with the given index . |
29,386 | def connect ( servers = None , framed_transport = False , timeout = None , retry_time = 60 , recycle = None , round_robin = None , max_retries = 3 ) : if servers is None : servers = [ DEFAULT_SERVER ] return ThreadLocalConnection ( servers , framed_transport , timeout , retry_time , recycle , max_retries = max_retries ... | Constructs a single ElasticSearch connection . Connects to a randomly chosen server on the list . |
29,387 | def _ensure_connection ( self ) : conn = self . connect ( ) if conn . recycle and conn . recycle < time . time ( ) : logger . debug ( 'Client session expired after %is. Recycling.' , self . _recycle ) self . close ( ) conn = self . connect ( ) return conn | Make certain we have a valid connection and return it . |
29,388 | def connect ( self ) : if not getattr ( self . _local , 'conn' , None ) : try : server = self . _servers . get ( ) logger . debug ( 'Connecting to %s' , server ) self . _local . conn = ClientTransport ( server , self . _framed_transport , self . _timeout , self . _recycle ) except ( Thrift . TException , socket . timeo... | Create new connection unless we already have one . |
29,389 | def close ( self ) : if self . _local . conn : self . _local . conn . transport . close ( ) self . _local . conn = None | If a connection is open close its transport . |
29,390 | def execute ( self , request ) : url = request . uri if request . parameters : url += '?' + urlencode ( request . parameters ) if request . headers : headers = dict ( self . _headers , ** request . headers ) else : headers = self . _headers retry = 0 server = getattr ( self . _local , "server" , None ) while True : if ... | Execute a request and return a response |
29,391 | def list_dirs ( directory ) : return [ f for f in pathlib . Path ( directory ) . iterdir ( ) if f . is_dir ( ) ] | Returns all directories in a given directory |
29,392 | def list_files ( directory ) : return [ f for f in pathlib . Path ( directory ) . iterdir ( ) if f . is_file ( ) and not f . name . startswith ( '.' ) ] | Returns all files in a given directory |
29,393 | def setup_files ( class_dir , seed ) : random . seed ( seed ) files = list_files ( class_dir ) files . sort ( ) random . shuffle ( files ) return files | Returns shuffled files |
29,394 | def split_files ( files , split_train , split_val , use_test ) : files_train = files [ : split_train ] files_val = files [ split_train : split_val ] if use_test else files [ split_train : ] li = [ ( files_train , 'train' ) , ( files_val , 'val' ) ] if use_test : files_test = files [ split_val : ] li . append ( ( files_... | Splits the files along the provided indices |
29,395 | def copy_files ( files_type , class_dir , output ) : class_name = path . split ( class_dir ) [ 1 ] for ( files , folder_type ) in files_type : full_path = path . join ( output , folder_type , class_name ) pathlib . Path ( full_path ) . mkdir ( parents = True , exist_ok = True ) for f in files : shutil . copy2 ( f , ful... | Copies the files from the input folder to the output folder |
29,396 | def get_config ( self ) : config = { 'location' : self . location , 'language' : self . language , 'topic' : self . topic , } return config | function to get current configuration |
29,397 | def params_dict ( self ) : location_code = 'US' language_code = 'en' if len ( self . location ) : location_code = locationMap [ process . extractOne ( self . location , self . locations ) [ 0 ] ] if len ( self . language ) : language_code = langMap [ process . extractOne ( self . language , self . languages ) [ 0 ] ] p... | function to get params dict for HTTP request |
29,398 | def get_news ( self ) : if self . topic is None or self . topic is 'Top Stories' : resp = requests . get ( top_news_url , params = self . params_dict ) else : topic_code = topicMap [ process . extractOne ( self . topic , self . topics ) [ 0 ] ] resp = requests . get ( topic_url . format ( topic_code ) , params = self .... | function to get news articles |
29,399 | def parse_feed ( content ) : feed = feedparser . parse ( content ) articles = [ ] for entry in feed [ 'entries' ] : article = { 'title' : entry [ 'title' ] , 'link' : entry [ 'link' ] } try : article [ 'media' ] = entry [ 'media_content' ] [ 0 ] [ 'url' ] except KeyError : article [ 'media' ] = None articles . append (... | utility function to parse feed |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.