sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
def update(self, attributes=None): """ Updates the entry with attributes. """ if attributes is None: attributes = {} attributes['content_type_id'] = self.sys['content_type'].id return super(Entry, self).update(attributes)
Updates the entry with attributes.
entailment
def all(self, query=None): """ Gets resource collection for _resource_class. """ if query is None: query = {} return self.client._get( self._url(), query )
Gets resource collection for _resource_class.
entailment
def find(self, resource_id, query=None, **kwargs): """Gets a single resource.""" if query is None: query = {} return self.client._get( self._url(resource_id), query, **kwargs )
Gets a single resource.
entailment
def create(self, resource_id=None, attributes=None): """ Creates a resource with the given ID (optional) and attributes. """ if attributes is None: attributes = {} result = None if not resource_id: result = self.client._post( self...
Creates a resource with the given ID (optional) and attributes.
entailment
def delete(self, resource_id, **kwargs): """ Deletes a resource by ID. """ return self.client._delete(self._url(resource_id), **kwargs)
Deletes a resource by ID.
entailment
def to_json(self): """ Returns the JSON representation of the role. """ result = super(Role, self).to_json() result.update({ 'name': self.name, 'description': self.description, 'permissions': self.permissions, 'policies': self.poli...
Returns the JSON representation of the role.
entailment
def to_json(self): """ Returns the JSON representation of the space membership. """ result = super(SpaceMembership, self).to_json() result.update({ 'admin': self.admin, 'roles': self.roles }) return result
Returns the JSON representation of the space membership.
entailment
def create(self, file_or_path, **kwargs): """ Creates an upload for the given file or path. """ opened = False if isinstance(file_or_path, str_type()): file_or_path = open(file_or_path, 'rb') opened = True elif not getattr(file_or_path, 'read', Fa...
Creates an upload for the given file or path.
entailment
def find(self, upload_id, **kwargs): """ Finds an upload by ID. """ return super(UploadsProxy, self).find(upload_id, file_upload=True)
Finds an upload by ID.
entailment
def delete(self, upload_id): """ Deletes an upload by ID. """ return super(UploadsProxy, self).delete(upload_id, file_upload=True)
Deletes an upload by ID.
entailment
def to_json(self): """ Returns the JSON Representation of the content type field. """ result = { 'name': self.name, 'id': self._real_id(), 'type': self.type, 'localized': self.localized, 'omitted': self.omitted, 're...
Returns the JSON Representation of the content type field.
entailment
def coerce(self, value): """ Coerces value to location hash. """ return { 'lat': float(value.get('lat', value.get('latitude'))), 'lon': float(value.get('lon', value.get('longitude'))) }
Coerces value to location hash.
entailment
def base_url(klass, space_id, parent_resource_id, resource_url='entries', resource_id=None, environment_id=None): """ Returns the URI for the snapshot. """ return "spaces/{0}{1}/{2}/{3}/snapshots/{4}".format( space_id, '/environments/{0}'.format(environment_id) i...
Returns the URI for the snapshot.
entailment
def to_json(self): """ Returns the JSON representation of the snapshot. """ result = super(Snapshot, self).to_json() result.update({ 'snapshot': self.snapshot.to_json(), }) return result
Returns the JSON representation of the snapshot.
entailment
def all(self, *args, **kwargs): """ Gets all usage periods. """ return self.client._get( self._url(), {}, headers={ 'x-contentful-enable-alpha-feature': 'usage-insights' } )
Gets all usage periods.
entailment
def create_attributes(klass, attributes, previous_object=None): """ Attributes for webhook creation. """ result = super(Webhook, klass).create_attributes(attributes, previous_object) if 'topics' not in result: raise Exception("Topics ('topics') must be provided for ...
Attributes for webhook creation.
entailment
def calls(self): """ Provides access to call overview for the given webhook. API reference: https://www.contentful.com/developers/docs/references/content-management-api/#/reference/webhook-calls :return: :class:`WebhookWebhooksCallProxy <contentful_management.webhook_webhooks_call_prox...
Provides access to call overview for the given webhook. API reference: https://www.contentful.com/developers/docs/references/content-management-api/#/reference/webhook-calls :return: :class:`WebhookWebhooksCallProxy <contentful_management.webhook_webhooks_call_proxy.WebhookWebhooksCallProxy>` object. ...
entailment
def health(self): """ Provides access to health overview for the given webhook. API reference: https://www.contentful.com/developers/docs/references/content-management-api/#/reference/webhook-calls/webhook-health :return: :class:`WebhookWebhooksHealthProxy <contentful_management.webhoo...
Provides access to health overview for the given webhook. API reference: https://www.contentful.com/developers/docs/references/content-management-api/#/reference/webhook-calls/webhook-health :return: :class:`WebhookWebhooksHealthProxy <contentful_management.webhook_webhooks_health_proxy.WebhookWebhook...
entailment
def to_json(self): """ Returns the JSON representation of the webhook. """ result = super(Webhook, self).to_json() result.update({ 'name': self.name, 'url': self.url, 'topics': self.topics, 'httpBasicUsername': self.http_basic_user...
Returns the JSON representation of the webhook.
entailment
def base_url(self, space_id, content_type_id, environment_id=None, **kwargs): """ Returns the URI for the editor interface. """ return "spaces/{0}{1}/content_types/{2}/editor_interface".format( space_id, '/environments/{0}'.format(environment_id) if environment_i...
Returns the URI for the editor interface.
entailment
def to_json(self): """ Returns the JSON representation of the editor interface. """ result = super(EditorInterface, self).to_json() result.update({'controls': self.controls}) return result
Returns the JSON representation of the editor interface.
entailment
def to_json(self): """ Returns the JSON Representation of the content type field validation. """ result = {} for k, v in self._data.items(): result[camel_case(k)] = v return result
Returns the JSON Representation of the content type field validation.
entailment
def build(self): """ Creates the objects from the JSON response. """ if self.json['sys']['type'] == 'Array': return self._build_array() return self._build_item(self.json)
Creates the objects from the JSON response.
entailment
def create(self, resource_id=None, attributes=None): """ Creates a resource with a given ID (optional) and attributes for the current content type. """ return self.proxy.create(resource_id=resource_id, attributes=attributes)
Creates a resource with a given ID (optional) and attributes for the current content type.
entailment
def find(self, resource_id, query=None): """ Finds a single resource by ID related to the current space. """ return self.proxy.find(resource_id, query=query)
Finds a single resource by ID related to the current space.
entailment
def get_ngroups(self, field=None): ''' Returns ngroups count if it was specified in the query, otherwise ValueError. If grouping on more than one field, provide the field argument to specify which count you are looking for. ''' field = field if field else self._determine_group_f...
Returns ngroups count if it was specified in the query, otherwise ValueError. If grouping on more than one field, provide the field argument to specify which count you are looking for.
entailment
def get_groups_count(self, field=None): ''' Returns 'matches' from group response. If grouping on more than one field, provide the field argument to specify which count you are looking for. ''' field = field if field else self._determine_group_field(field) if 'ma...
Returns 'matches' from group response. If grouping on more than one field, provide the field argument to specify which count you are looking for.
entailment
def get_flat_groups(self, field=None): ''' Flattens the group response and just returns a list of documents. ''' field = field if field else self._determine_group_field(field) temp_groups = self.data['grouped'][field]['groups'] return [y for x in temp_groups for y in x['d...
Flattens the group response and just returns a list of documents.
entailment
def get_facets(self): ''' Returns a dictionary of facets:: >>> res = solr.query('SolrClient_unittest',{ 'q':'product_name:Lorem', 'facet':True, 'facet.field':'facet_test', })... ... ... ... >>> res.get_resul...
Returns a dictionary of facets:: >>> res = solr.query('SolrClient_unittest',{ 'q':'product_name:Lorem', 'facet':True, 'facet.field':'facet_test', })... ... ... ... >>> res.get_results_count() 4 >>> r...
entailment
def get_facets_ranges(self): ''' Returns query facet ranges :: >>> res = solr.query('SolrClient_unittest',{ 'q':'*:*', 'facet':True, 'facet.range':'price', 'facet.range.start':0, 'facet.range.end':100, ...
Returns query facet ranges :: >>> res = solr.query('SolrClient_unittest',{ 'q':'*:*', 'facet':True, 'facet.range':'price', 'facet.range.start':0, 'facet.range.end':100, 'facet.range.gap':10 }) ...
entailment
def get_facet_pivot(self): ''' Parses facet pivot response. Example:: >>> res = solr.query('SolrClient_unittest',{ 'q':'*:*', 'fq':'price:[50 TO *]', 'facet':True, 'facet.pivot':'facet_test,price' #Note how there is no space between fields. The...
Parses facet pivot response. Example:: >>> res = solr.query('SolrClient_unittest',{ 'q':'*:*', 'fq':'price:[50 TO *]', 'facet':True, 'facet.pivot':'facet_test,price' #Note how there is no space between fields. They are just separated by commas }) ...
entailment
def get_field_values_as_list(self,field): ''' :param str field: The name of the field for which to pull in values. Will parse the query results (must be ungrouped) and return all values of 'field' as a list. Note that these are not unique values. Example:: >>> r.get_field_values_as...
:param str field: The name of the field for which to pull in values. Will parse the query results (must be ungrouped) and return all values of 'field' as a list. Note that these are not unique values. Example:: >>> r.get_field_values_as_list('product_name_exact') ['Mauris risus risus l...
entailment
def get_first_field_values_as_list(self, field): ''' :param str field: The name of the field for lookup. Goes through all documents returned looking for specified field. At first encounter will return the field's value. ''' for doc in self.docs: if field in doc.keys(...
:param str field: The name of the field for lookup. Goes through all documents returned looking for specified field. At first encounter will return the field's value.
entailment
def get_facet_values_as_list(self, field): ''' :param str field: Name of facet field to retrieve values from. Returns facet values as list for a given field. Example:: >>> res = solr.query('SolrClient_unittest',{ 'q':'*:*', 'facet':'true', ...
:param str field: Name of facet field to retrieve values from. Returns facet values as list for a given field. Example:: >>> res = solr.query('SolrClient_unittest',{ 'q':'*:*', 'facet':'true', 'facet.field':'facet_test', }) >>...
entailment
def get_facet_keys_as_list(self,field): ''' :param str field: Name of facet field to retrieve keys from. Similar to get_facet_values_as_list but returns the list of keys as a list instead. Example:: >>> r.get_facet_keys_as_list('facet_test') ['Lorem', 'ipsum', '...
:param str field: Name of facet field to retrieve keys from. Similar to get_facet_values_as_list but returns the list of keys as a list instead. Example:: >>> r.get_facet_keys_as_list('facet_test') ['Lorem', 'ipsum', 'amet,', 'dolor', 'sit']
entailment
def json_facet(self, field=None): ''' EXPERIMENTAL Tried to kick back the json.fact output. ''' facets = self.data['facets'] if field is None: temp_fields = [x for x in facets.keys() if x != 'count'] if len(temp_fields) != 1: raise...
EXPERIMENTAL Tried to kick back the json.fact output.
entailment
def get_jsonfacet_counts_as_dict(self, field, data=None): ''' EXPERIMENTAL Takes facets and returns then as a dictionary that is easier to work with, for example, if you are getting something this:: {'facets': {'count': 50, 'test': {'buckets': [{'count': 10, ...
EXPERIMENTAL Takes facets and returns then as a dictionary that is easier to work with, for example, if you are getting something this:: {'facets': {'count': 50, 'test': {'buckets': [{'count': 10, 'pr': {'buckets': [{'count': 2, 'unique': 1, 'val': 79}, ...
entailment
def _gen_file_name(self): ''' Generates a random file name based on self._output_filename_pattern for the output to do file. ''' date = datetime.datetime.now() dt = "{}-{}-{}-{}-{}-{}-{}".format(str(date.year),str(date.month),str(date.day),str(date.hour),str(date.minute),str(date...
Generates a random file name based on self._output_filename_pattern for the output to do file.
entailment
def add(self, item=None, finalize=False, callback=None): ''' Takes a string, dictionary or list of items for adding to queue. To help troubleshoot it will output the updated buffer size, however when the content gets written it will output the file path of the new file. Generally this can be safely disc...
Takes a string, dictionary or list of items for adding to queue. To help troubleshoot it will output the updated buffer size, however when the content gets written it will output the file path of the new file. Generally this can be safely discarded. :param <dict,list> item: Item to add to the queue. If dict wi...
entailment
def _lock(self): ''' Locks, or returns False if already locked ''' if not self._is_locked(): with open(self._lck,'w') as fh: if self._devel: self.logger.debug("Locking") fh.write(str(os.getpid())) return True else: ...
Locks, or returns False if already locked
entailment
def _is_locked(self): ''' Checks to see if we are already pulling items from the queue ''' if os.path.isfile(self._lck): try: import psutil except ImportError: return True #Lock file exists and no psutil #If psutil is im...
Checks to see if we are already pulling items from the queue
entailment
def _unlock(self): ''' Unlocks the index ''' if self._devel: self.logger.debug("Unlocking Index") if self._is_locked(): os.remove(self._lck) return True else: return True
Unlocks the index
entailment
def get_all_as_list(self, dir='_todo_dir'): ''' Returns a list of the the full path to all items currently in the todo directory. The items will be listed in ascending order based on filesystem time. This will re-scan the directory on each execution. Do not use this to process items, th...
Returns a list of the the full path to all items currently in the todo directory. The items will be listed in ascending order based on filesystem time. This will re-scan the directory on each execution. Do not use this to process items, this method should only be used for troubleshooting or something a...
entailment
def get_todo_items(self, **kwargs): ''' Returns an iterator that will provide each item in the todo queue. Note that to complete each item you have to run complete method with the output of this iterator. That will move the item to the done directory and prevent it from being retrieved in the f...
Returns an iterator that will provide each item in the todo queue. Note that to complete each item you have to run complete method with the output of this iterator. That will move the item to the done directory and prevent it from being retrieved in the future.
entailment
def complete(self, filepath): ''' Marks the item as complete by moving it to the done directory and optionally gzipping it. ''' if not os.path.exists(filepath): raise FileNotFoundError("Can't Complete {}, it doesn't exist".format(filepath)) if self._devel: self.logger...
Marks the item as complete by moving it to the done directory and optionally gzipping it.
entailment
def index(self, solr, collection, threads=1, send_method='stream_file', **kwargs): ''' Will index the queue into a specified solr instance and collection. Specify multiple threads to make this faster, however keep in mind that if you specify multiple threads the items may not be in order. Exampl...
Will index the queue into a specified solr instance and collection. Specify multiple threads to make this faster, however keep in mind that if you specify multiple threads the items may not be in order. Example:: solr = SolrClient('http://localhost:8983/solr/') for doc in self.docs: ...
entailment
def get_all_json_from_indexq(self): ''' Gets all data from the todo files in indexq and returns one huge list of all data. ''' files = self.get_all_as_list() out = [] for efile in files: out.extend(self._open_file(efile)) return out
Gets all data from the todo files in indexq and returns one huge list of all data.
entailment
def get_multi_q(self, sentinel='STOP'): ''' This helps indexq operate in multiprocessing environment without each process having to have it's own IndexQ. It also is a handy way to deal with thread / process safety. This method will create and return a JoinableQueue object. Additionally, it will...
This helps indexq operate in multiprocessing environment without each process having to have it's own IndexQ. It also is a handy way to deal with thread / process safety. This method will create and return a JoinableQueue object. Additionally, it will kick off a back end process that will monitor the queue, de...
entailment
def _retry(function): """ Internal mechanism to try to send data to multiple Solr Hosts if the query fails on the first one. """ def inner(self, **kwargs): last_exception = None #for host in self.router.get_hosts(**kwargs): for host in self.ho...
Internal mechanism to try to send data to multiple Solr Hosts if the query fails on the first one.
entailment
def commit(self, collection, openSearcher=False, softCommit=False, waitSearcher=True, commit=True, **kwargs): """ :param str collection: The name of the collection for the request :param bool openSearcher: If new searcher is to be opened :param bool softCommit: SoftCommit ...
:param str collection: The name of the collection for the request :param bool openSearcher: If new searcher is to be opened :param bool softCommit: SoftCommit :param bool waitServer: Blocks until the new searcher is opened :param bool commit: Commit Sends a commit to a Solr coll...
entailment
def query_raw(self, collection, query, request_handler='select', **kwargs): """ :param str collection: The name of the collection for the request :param str request_handler: Request handler, default is 'select' :param dict query: Python dictionary of Solr query parameters. Sends...
:param str collection: The name of the collection for the request :param str request_handler: Request handler, default is 'select' :param dict query: Python dictionary of Solr query parameters. Sends a query to Solr, returns a dict. `query` should be a dictionary of solr request handler argumen...
entailment
def query(self, collection, query, request_handler='select', **kwargs): """ :param str collection: The name of the collection for the request :param str request_handler: Request handler, default is 'select' :param dict query: Python dictonary of Solr query parameters. Sends a qu...
:param str collection: The name of the collection for the request :param str request_handler: Request handler, default is 'select' :param dict query: Python dictonary of Solr query parameters. Sends a query to Solr, returns a SolrResults Object. `query` should be a dictionary of solr request ha...
entailment
def index(self, collection, docs, params=None, min_rf=None, **kwargs): """ :param str collection: The name of the collection for the request. :param docs list docs: List of dicts. ex: [{"title": "testing solr indexing", "id": "test1"}] :param min_rf int min_rf: Required number of replica...
:param str collection: The name of the collection for the request. :param docs list docs: List of dicts. ex: [{"title": "testing solr indexing", "id": "test1"}] :param min_rf int min_rf: Required number of replicas to write to' Sends supplied list of dicts to solr for indexing. :: ...
entailment
def index_json(self, collection, data, params=None, min_rf=None, **kwargs): """ :param str collection: The name of the collection for the request. :param data str data: Valid Solr JSON as a string. ex: '[{"title": "testing solr indexing", "id": "test1"}]' :param min_rf int min_rf: Requir...
:param str collection: The name of the collection for the request. :param data str data: Valid Solr JSON as a string. ex: '[{"title": "testing solr indexing", "id": "test1"}]' :param min_rf int min_rf: Required number of replicas to write to' Sends supplied json to solr for indexing, supplied J...
entailment
def get(self, collection, doc_id, **kwargs): """ :param str collection: The name of the collection for the request :param str doc_id: ID of the document to be retrieved. Retrieve document from Solr based on the ID. :: >>> solr.get('SolrClient_unittest','changeme') "...
:param str collection: The name of the collection for the request :param str doc_id: ID of the document to be retrieved. Retrieve document from Solr based on the ID. :: >>> solr.get('SolrClient_unittest','changeme')
entailment
def mget(self, collection, doc_ids, **kwargs): """ :param str collection: The name of the collection for the request :param tuple doc_ids: ID of the document to be retrieved. Retrieve documents from Solr based on the ID. :: >>> solr.get('SolrClient_unittest','changeme') ...
:param str collection: The name of the collection for the request :param tuple doc_ids: ID of the document to be retrieved. Retrieve documents from Solr based on the ID. :: >>> solr.get('SolrClient_unittest','changeme')
entailment
def delete_doc_by_id(self, collection, doc_id, **kwargs): """ :param str collection: The name of the collection for the request :param str id: ID of the document to be deleted. Can specify '*' to delete everything. Deletes items from Solr based on the ID. :: >>> solr.delete...
:param str collection: The name of the collection for the request :param str id: ID of the document to be deleted. Can specify '*' to delete everything. Deletes items from Solr based on the ID. :: >>> solr.delete_doc_by_id('SolrClient_unittest','changeme')
entailment
def delete_doc_by_query(self, collection, query, **kwargs): """ :param str collection: The name of the collection for the request :param str query: Query selecting documents to be deleted. Deletes items from Solr based on a given query. :: >>> solr.delete_doc_by_query('Solr...
:param str collection: The name of the collection for the request :param str query: Query selecting documents to be deleted. Deletes items from Solr based on a given query. :: >>> solr.delete_doc_by_query('SolrClient_unittest','*:*')
entailment
def local_index(self, collection, filename, **kwargs): """ :param str collection: The name of the collection for the request :param str filename: String file path of the file to index. Will index specified file into Solr. The `file` must be local to the server, this is faster than other...
:param str collection: The name of the collection for the request :param str filename: String file path of the file to index. Will index specified file into Solr. The `file` must be local to the server, this is faster than other indexing options. If the files are already on the servers I sugges...
entailment
def paging_query(self, collection, query, rows=1000, start=0, max_start=200000): """ :param str collection: The name of the collection for the request. :param dict query: Dictionary of solr args. :param int rows: Number of rows to return in each batch. Default is 1000. :param int...
:param str collection: The name of the collection for the request. :param dict query: Dictionary of solr args. :param int rows: Number of rows to return in each batch. Default is 1000. :param int start: What position to start with. Default is 0. :param int max_start: Once the start will ...
entailment
def cursor_query(self, collection, query): """ :param str collection: The name of the collection for the request. :param dict query: Dictionary of solr args. Will page through the result set in increments using cursorMark until it has all items. Sort is required for cursorMark \ ...
:param str collection: The name of the collection for the request. :param dict query: Dictionary of solr args. Will page through the result set in increments using cursorMark until it has all items. Sort is required for cursorMark \ queries, if you don't specify it, the default is 'id desc'. ...
entailment
def get_shard_map(self, force_refresh=False): """ You can change this function to get the shard-map from somewhere/somehow place else in conjuction with save_shard_map(). """ now = datetime.utcnow() if force_refresh is True or \ self.shard_map is ...
You can change this function to get the shard-map from somewhere/somehow place else in conjuction with save_shard_map().
entailment
def check_zk(self): ''' Will attempt to telnet to each zookeeper that is used by SolrClient and issue 'mntr' command. Response is parsed to check to see if the zookeeper node is a leader or a follower and returned as a dict. If the telnet collection fails or the proper response is not...
Will attempt to telnet to each zookeeper that is used by SolrClient and issue 'mntr' command. Response is parsed to check to see if the zookeeper node is a leader or a follower and returned as a dict. If the telnet collection fails or the proper response is not parsed, the zk node will be listed as '...
entailment
def copy_config(self, original, new): ''' Copies collection configs into a new folder. Can be used to create new collections based on existing configs. Basically, copies all nodes under /configs/original to /configs/new. :param original str: ZK name of original config :param n...
Copies collection configs into a new folder. Can be used to create new collections based on existing configs. Basically, copies all nodes under /configs/original to /configs/new. :param original str: ZK name of original config :param new str: New name of the ZK config.
entailment
def download_collection_configs(self, collection, fs_path): ''' Downloads ZK Directory to the FileSystem. :param collection str: Name of the collection (zk config name) :param fs_path str: Destination filesystem path. ''' if not self.kz.exists('/configs/{}'.for...
Downloads ZK Directory to the FileSystem. :param collection str: Name of the collection (zk config name) :param fs_path str: Destination filesystem path.
entailment
def upload_collection_configs(self, collection, fs_path): ''' Uploads collection configurations from a specified directory to zookeeper. ''' coll_path = fs_path if not os.path.isdir(coll_path): raise ValueError("{} Doesn't Exist".format(coll_path)) s...
Uploads collection configurations from a specified directory to zookeeper.
entailment
def create_field(self, collection, field_dict): ''' Creates a new field in managed schema, will raise ValueError if the field already exists. field_dict should look like this:: { "name":"sell-by", "type":"tdate", "stored":True ...
Creates a new field in managed schema, will raise ValueError if the field already exists. field_dict should look like this:: { "name":"sell-by", "type":"tdate", "stored":True } Reference: https://cwiki.apache.org/confluence/display/so...
entailment
def delete_field(self,collection,field_name): ''' Deletes a field from the Solr Collection. Will raise ValueError if the field doesn't exist. :param string collection: Name of the collection for the action :param string field_name: String name of the field. ''' if not se...
Deletes a field from the Solr Collection. Will raise ValueError if the field doesn't exist. :param string collection: Name of the collection for the action :param string field_name: String name of the field.
entailment
def does_field_exist(self,collection,field_name): ''' Checks if the field exists will return a boolean True (exists) or False(doesn't exist). :param string collection: Name of the collection for the action :param string field_name: String name of the field. ''' schema = ...
Checks if the field exists will return a boolean True (exists) or False(doesn't exist). :param string collection: Name of the collection for the action :param string field_name: String name of the field.
entailment
def create_copy_field(self,collection,copy_dict): ''' Creates a copy field. copy_dict should look like :: {'source':'source_field_name','dest':'destination_field_name'} :param string collection: Name of the collection for the action :param dict copy_field: Dictiona...
Creates a copy field. copy_dict should look like :: {'source':'source_field_name','dest':'destination_field_name'} :param string collection: Name of the collection for the action :param dict copy_field: Dictionary of field info Reference: https://cwiki.apache.org/confluen...
entailment
def delete_copy_field(self, collection, copy_dict): ''' Deletes a copy field. copy_dict should look like :: {'source':'source_field_name','dest':'destination_field_name'} :param string collection: Name of the collection for the action :param dict copy_field: Dictio...
Deletes a copy field. copy_dict should look like :: {'source':'source_field_name','dest':'destination_field_name'} :param string collection: Name of the collection for the action :param dict copy_field: Dictionary of field info
entailment
def shuffle_hosts(self): """ Shuffle hosts so we don't always query the first one. Example: using in a webapp with X processes in Y servers, the hosts contacted will be more random. The user can also call this function to reshuffle every 'x' seconds or before every request. :retu...
Shuffle hosts so we don't always query the first one. Example: using in a webapp with X processes in Y servers, the hosts contacted will be more random. The user can also call this function to reshuffle every 'x' seconds or before every request. :return:
entailment
def start_virtual_display(self, width=1440, height=900, colordepth=24, **kwargs): """Starts virtual display which will be destroyed after test execution will be end *Arguments:* - width: a width to be set in pixels - height: a height to be set in p...
Starts virtual display which will be destroyed after test execution will be end *Arguments:* - width: a width to be set in pixels - height: a height to be set in pixels - color_depth: a color depth to be used - kwargs: extra parameters *Example:* | Sta...
entailment
def api(self, action, args=None): """ Sends a request to Solr Collections API. Documentation is here: https://cwiki.apache.org/confluence/display/solr/Collections+API :param string action: Name of the collection for the action :param dict args: Dictionary of specific parameters ...
Sends a request to Solr Collections API. Documentation is here: https://cwiki.apache.org/confluence/display/solr/Collections+API :param string action: Name of the collection for the action :param dict args: Dictionary of specific parameters for action
entailment
def clusterstatus(self): """ Returns a slightly slimmed down version of the clusterstatus api command. It also gets count of documents in each shard on each replica and returns it as doc_count key for each replica. """ res = self.cluster_status_raw() cluster = res['clu...
Returns a slightly slimmed down version of the clusterstatus api command. It also gets count of documents in each shard on each replica and returns it as doc_count key for each replica.
entailment
def create(self, name, numShards, params=None): """ Create a new collection. """ if params is None: params = {} params.update( name=name, numShards=numShards ) return self.api('CREATE', params)
Create a new collection.
entailment
def _get_collection_counts(self, core_data): """ Queries each core to get individual counts for each core for each shard. """ if core_data['base_url'] not in self.solr_clients: from SolrClient import SolrClient self.solr_clients['base_url'] = SolrClient(core_data[...
Queries each core to get individual counts for each core for each shard.
entailment
def check_status(self, ignore=(), status=None): """ Checks status of each collection and shard to make sure that: a) Cluster state is active b) Number of docs matches across replicas for a given shard. Returns a dict of results for custom alerting. """ self.SH...
Checks status of each collection and shard to make sure that: a) Cluster state is active b) Number of docs matches across replicas for a given shard. Returns a dict of results for custom alerting.
entailment
def reindex(self, fq= [], **kwargs): ''' Starts Reindexing Process. All parameter arguments will be passed down to the getter function. :param string fq: FilterQuery to pass to source Solr to retrieve items. This can be used to limit the results. ''' for items in self._gette...
Starts Reindexing Process. All parameter arguments will be passed down to the getter function. :param string fq: FilterQuery to pass to source Solr to retrieve items. This can be used to limit the results.
entailment
def _from_solr(self, fq=[], report_frequency = 25): ''' Method for retrieving batch data from Solr. ''' cursor = '*' stime = datetime.now() query_count = 0 while True: #Get data with starting cursorMark query = self._get_query(curs...
Method for retrieving batch data from Solr.
entailment
def _trim_fields(self, docs): ''' Removes ignore fields from the data that we got from Solr. ''' for doc in docs: for field in self._ignore_fields: if field in doc: del(doc[field]) return docs
Removes ignore fields from the data that we got from Solr.
entailment
def _get_query(self, cursor): ''' Query tempalte for source Solr, sorts by id by default. ''' query = {'q':'*:*', 'sort':'id desc', 'rows':self._rows, 'cursorMark':cursor} if self._date_field: query['sort'] = "{...
Query tempalte for source Solr, sorts by id by default.
entailment
def _to_solr(self, data): ''' Sends data to a Solr instance. ''' return self._dest.index_json(self._dest_coll, json.dumps(data,sort_keys=True))
Sends data to a Solr instance.
entailment
def _get_date_range_query(self, start_date, end_date, timespan= 'DAY', date_field= None): ''' Gets counts of items per specified date range. :param collection: Solr Collection to use. :param timespan: Solr Date Math compliant value for faceting ex HOUR, MONTH, DAY ''' ...
Gets counts of items per specified date range. :param collection: Solr Collection to use. :param timespan: Solr Date Math compliant value for faceting ex HOUR, MONTH, DAY
entailment
def _get_edge_date(self, date_field, sort): ''' This method is used to get start and end dates for the collection. ''' return self._source.query(self._source_coll, { 'q':'*:*', 'rows':1, 'fq':'+{}:*'.format(date_field), ...
This method is used to get start and end dates for the collection.
entailment
def _get_date_facet_counts(self, timespan, date_field, start_date=None, end_date=None): ''' Returns Range Facet counts based on ''' if 'DAY' not in timespan: raise ValueError("At this time, only DAY date range increment is supported. Aborting..... ") #Need to ...
Returns Range Facet counts based on
entailment
def resume(self, start_date=None, end_date=None, timespan='DAY', check= False): ''' This method may help if the original run was interrupted for some reason. It will only work under the following conditions * You have a date field that you can facet on * Indexing was stopped for the ...
This method may help if the original run was interrupted for some reason. It will only work under the following conditions * You have a date field that you can facet on * Indexing was stopped for the duration of the copy The way this tries to resume re-indexing is by running a date range fa...
entailment
def start_client(self, event=None): """ Negotiate a new SSH2 session as a client. This is the first step after creating a new L{Transport}. A separate thread is created for protocol negotiation. If an event is passed in, this method returns immediately. When negotiati...
Negotiate a new SSH2 session as a client. This is the first step after creating a new L{Transport}. A separate thread is created for protocol negotiation. If an event is passed in, this method returns immediately. When negotiation is done (successful or not), the given C{Event} will ...
entailment
def start_server(self, event=None, server=None): """ Negotiate a new SSH2 session as a server. This is the first step after creating a new L{Transport} and setting up your server host key(s). A separate thread is created for protocol negotiation. If an event is passed in, this...
Negotiate a new SSH2 session as a server. This is the first step after creating a new L{Transport} and setting up your server host key(s). A separate thread is created for protocol negotiation. If an event is passed in, this method returns immediately. When negotiation is done (succe...
entailment
def close(self): """ Close this session, and any open channels that are tied to it. """ if not self.active: return self.active = False self.packetizer.close() self.join() for chan in self._channels.values(): chan._unlink()
Close this session, and any open channels that are tied to it.
entailment
def open_forwarded_tcpip_channel(self, (src_addr, src_port), (dest_addr, dest_port)): """ Request a new channel back to the client, of type C{"forwarded-tcpip"}. This is used after a client has requested port forwarding, for sending incoming connections back to the client. @para...
Request a new channel back to the client, of type C{"forwarded-tcpip"}. This is used after a client has requested port forwarding, for sending incoming connections back to the client. @param src_addr: originator's address @param src_port: originator's port @param dest_addr: loca...
entailment
def request_port_forward(self, address, port, handler=None): """ Ask the server to forward TCP connections from a listening port on the server, across this SSH session. If a handler is given, that handler is called from a different thread whenever a forwarded connection arrives....
Ask the server to forward TCP connections from a listening port on the server, across this SSH session. If a handler is given, that handler is called from a different thread whenever a forwarded connection arrives. The handler parameters are:: handler(channel, (origin_addr, origin...
entailment
def send_ignore(self, bytes=None): """ Send a junk packet across the encrypted link. This is sometimes used to add "noise" to a connection to confuse would-be attackers. It can also be used as a keep-alive for long lived connections traversing firewalls. @param bytes: ...
Send a junk packet across the encrypted link. This is sometimes used to add "noise" to a connection to confuse would-be attackers. It can also be used as a keep-alive for long lived connections traversing firewalls. @param bytes: the number of random bytes to send in the payload of th...
entailment
def renegotiate_keys(self): """ Force this session to switch to new keys. Normally this is done automatically after the session hits a certain number of packets or bytes sent or received, but this method gives you the option of forcing new keys whenever you want. Negotiating ne...
Force this session to switch to new keys. Normally this is done automatically after the session hits a certain number of packets or bytes sent or received, but this method gives you the option of forcing new keys whenever you want. Negotiating new keys causes a pause in traffic both wa...
entailment
def set_keepalive(self, interval): """ Turn on/off keepalive packets (default is off). If this is set, after C{interval} seconds without sending any data over the connection, a "keepalive" packet will be sent (and ignored by the remote host). This can be useful to keep connecti...
Turn on/off keepalive packets (default is off). If this is set, after C{interval} seconds without sending any data over the connection, a "keepalive" packet will be sent (and ignored by the remote host). This can be useful to keep connections alive over a NAT, for example. @param inte...
entailment
def connect(self, hostkey=None, username='', password=None, pkey=None): """ Negotiate an SSH2 session, and optionally verify the server's host key and authenticate using a password or private key. This is a shortcut for L{start_client}, L{get_remote_server_key}, and L{Transport....
Negotiate an SSH2 session, and optionally verify the server's host key and authenticate using a password or private key. This is a shortcut for L{start_client}, L{get_remote_server_key}, and L{Transport.auth_password} or L{Transport.auth_publickey}. Use those methods if you want more c...
entailment
def auth_none(self, username): """ Try to authenticate to the server using no authentication at all. This will almost always fail. It may be useful for determining the list of authentication types supported by the server, by catching the L{BadAuthenticationType} exception raised...
Try to authenticate to the server using no authentication at all. This will almost always fail. It may be useful for determining the list of authentication types supported by the server, by catching the L{BadAuthenticationType} exception raised. @param username: the username to authent...
entailment
def _send_user_message(self, data): """ send a message, but block if we're in key negotiation. this is used for user-initiated requests. """ start = time.time() while True: self.clear_to_send.wait(0.1) if not self.active: self._log...
send a message, but block if we're in key negotiation. this is used for user-initiated requests.
entailment
def _set_K_H(self, k, h): "used by a kex object to set the K (root key) and H (exchange hash)" self.K = k self.H = h if self.session_id == None: self.session_id = h
used by a kex object to set the K (root key) and H (exchange hash)
entailment
def _compute_key(self, id, nbytes): "id is 'A' - 'F' for the various keys used by ssh" m = Message() m.add_mpint(self.K) m.add_bytes(self.H) m.add_byte(id) m.add_bytes(self.session_id) out = sofar = SHA.new(str(m)).digest() while len(out) < nbytes: ...
id is 'A' - 'F' for the various keys used by ssh
entailment