text_prompt stringlengths 157 13.1k | code_prompt stringlengths 7 19.8k ⌀ |
|---|---|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def reload(self):
""" Reloads the space. """ |
result = self._client._get(
self.__class__.base_url(
self.sys['id']
)
)
self._update_from_resource(result)
return self |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def delete(self):
""" Deletes the space """ |
return self._client._delete(
self.__class__.base_url(
self.sys['id']
)
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def to_json(self):
""" Returns the JSON representation of the space. """ |
result = super(Space, self).to_json()
result.update({'name': self.name})
return result |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def all(self, query=None, **kwargs):
""" Gets all spaces. """ |
return super(SpacesProxy, self).all(query=query) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def find(self, space_id, query=None, **kwargs):
""" Gets a space by ID. """ |
try:
self.space_id = space_id
return super(SpacesProxy, self).find(space_id, query=query)
finally:
self.space_id = None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create(self, attributes=None, **kwargs):
""" Creates a space with given attributes. """ |
if attributes is None:
attributes = {}
if 'default_locale' not in attributes:
attributes['default_locale'] = self.client.default_locale
return super(SpacesProxy, self).create(resource_id=None, attributes=attributes) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def delete(self, space_id):
""" Deletes a space by ID. """ |
try:
self.space_id = space_id
return super(SpacesProxy, self).delete(space_id)
finally:
self.space_id = None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def editor_interfaces(self, space_id, environment_id, content_type_id):
""" Provides access to editor interfaces management methods. API reference: https://www.c... |
return EditorInterfacesProxy(self, space_id, environment_id, content_type_id) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def snapshots(self, space_id, environment_id, resource_id, resource_kind='entries'):
""" Provides access to snapshot management methods. API reference: https://w... |
return SnapshotsProxy(self, space_id, environment_id, resource_id, resource_kind) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def entry_snapshots(self, space_id, environment_id, entry_id):
""" Provides access to entry snapshot management methods. API reference: https://www.contentful.co... |
return SnapshotsProxy(self, space_id, environment_id, entry_id, 'entries') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def content_type_snapshots(self, space_id, environment_id, content_type_id):
""" Provides access to content type snapshot management methods. API reference: http... |
return SnapshotsProxy(self, space_id, environment_id, content_type_id, 'content_types') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _validate_configuration(self):
""" Validates that required parameters are present. """ |
if not self.access_token:
raise ConfigurationException(
'You will need to initialize a client with an Access Token'
)
if not self.api_url:
raise ConfigurationException(
'The client configuration needs to contain an API URL'
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _contentful_user_agent(self):
""" Sets the X-Contentful-User-Agent header. """ |
header = {}
from . import __version__
header['sdk'] = {
'name': 'contentful-management.py',
'version': __version__
}
header['app'] = {
'name': self.application_name,
'version': self.application_version
}
header['int... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _url(self, url, file_upload=False):
""" Creates the request URL. """ |
host = self.api_url
if file_upload:
host = self.uploads_api_url
protocol = 'https' if self.https else 'http'
if url.endswith('/'):
url = url[:-1]
return '{0}://{1}/{2}'.format(
protocol,
host,
url
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _http_request(self, method, url, request_kwargs=None):
""" Performs the requested HTTP request. """ |
kwargs = request_kwargs if request_kwargs is not None else {}
headers = self._request_headers()
headers.update(self.additional_headers)
if 'headers' in kwargs:
headers.update(kwargs['headers'])
kwargs['headers'] = headers
if self._has_proxy():
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _http_get(self, url, query, **kwargs):
""" Performs the HTTP GET request. """ |
self._normalize_query(query)
kwargs.update({'params': query})
return self._http_request('get', url, kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _http_post(self, url, data, **kwargs):
""" Performs the HTTP POST request. """ |
if not kwargs.get('file_upload', False):
data = json.dumps(data)
kwargs.update({'data': data})
return self._http_request('post', url, kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _http_put(self, url, data, **kwargs):
""" Performs the HTTP PUT request. """ |
kwargs.update({'data': json.dumps(data)})
return self._http_request('put', url, kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _request(self, method, url, query_or_data=None, **kwargs):
""" Wrapper for the HTTP requests, rate limit backoff is handled here, responses are processed wit... |
if query_or_data is None:
query_or_data = {}
request_method = getattr(self, '_http_{0}'.format(method))
response = retry_request(self)(request_method)(url, query_or_data, **kwargs)
if self.raw_mode:
return response
if response.status_code >= 300:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get(self, url, query=None, **kwargs):
""" Wrapper for the HTTP GET request. """ |
return self._request('get', url, query, **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _post(self, url, attributes=None, **kwargs):
""" Wrapper for the HTTP POST request. """ |
return self._request('post', url, attributes, **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _put(self, url, attributes=None, **kwargs):
""" Wrapper for the HTTP PUT request. """ |
return self._request('put', url, attributes, **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _delete(self, url, **kwargs):
""" Wrapper for the HTTP DELETE request. """ |
response = retry_request(self)(self._http_delete)(url, **kwargs)
if self.raw_mode:
return response
if response.status_code >= 300:
error = get_error(response)
if self.raise_errors:
raise error
return error
return respon... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def to_json(self):
""" Returns the JSON representation of the locale. """ |
result = super(Locale, self).to_json()
result.update({
'code': self.code,
'name': self.name,
'fallbackCode': self.fallback_code,
'optional': self.optional,
'contentDeliveryApi': self.content_delivery_api,
'contentManagementApi': s... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def all(self, query=None, **kwargs):
""" Gets all assets of a space. """ |
if query is None:
query = {}
normalize_select(query)
return super(AssetsProxy, self).all(query, **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def find(self, asset_id, query=None, **kwargs):
""" Gets a single asset by ID. """ |
if query is None:
query = {}
normalize_select(query)
return super(AssetsProxy, self).find(asset_id, query=query, **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def snapshots(self):
""" Provides access to snapshot management methods for the given entry. API reference: https://www.contentful.com/developers/docs/references... |
return EntrySnapshotsProxy(self._client, self.sys['space'].id, self._environment_id, self.sys['id']) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def all(self, query=None):
""" Gets resource collection for _resource_class. """ |
if query is None:
query = {}
return self.client._get(
self._url(),
query
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def delete(self, resource_id, **kwargs):
""" Deletes a resource by ID. """ |
return self.client._delete(self._url(resource_id), **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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.policies
})
return result |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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', False):
raise Exception("A file or path to a file is required for this operation.")
try:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def find(self, upload_id, **kwargs):
""" Finds an upload by ID. """ |
return super(UploadsProxy, self).find(upload_id, file_upload=True) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def delete(self, upload_id):
""" Deletes an upload by ID. """ |
return super(UploadsProxy, self).delete(upload_id, file_upload=True) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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,
'required': self.required,
'disabled': self.disabled,
'validations': [v.to_json() for v ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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')))
} |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) if environment_id is not None else '',
resource_url,
parent_resource_id,
resource_id if resource_id is not None else ''
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def all(self, *args, **kwargs):
""" Gets all usage periods. """ |
return self.client._get(
self._url(),
{},
headers={
'x-contentful-enable-alpha-feature': 'usage-insights'
}
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 this operation.")
return result |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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_username,
'headers': self.headers
})
if self.filters:
result.... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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_id is not None else '',
content_type_id
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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.host:
try:
return function(self, host, **kwargs)
except SolrError as e:
self.logger.except... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def start_virtual_display(self, width=1440, height=900, colordepth=24, **kwargs):
"""Starts virtual display which will be destroyed after test execution will be ... |
if self._display is None:
logger.info("Using virtual display: '{0}x{1}x{2}'".format(
width, height, colordepth))
self._display = Xvfb(int(width), int(height),
int(colordepth), **kwargs)
self._display.start()
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 repl... |
res = self.cluster_status_raw()
cluster = res['cluster']['collections']
out = {}
try:
for collection in cluster:
out[collection] = {}
for shard in cluster[collection]['shards']:
out[collection][shard] = {}
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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['base_url'], log=self.logger)
try:
return self.solr_clients['base_url'].query(core_data['core'],
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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'] = "{... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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),
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| 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 ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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 ... |
self.completion_event = threading.Event()
self._send_kex_init()
while True:
self.completion_event.wait(0.1)
if not self.active:
e = self.get_exception()
if e is not None:
raise e
raise SSHException('Nego... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
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(DEBUG, 'Dropping user packet because connection is dead.')
return
self.clear_to_send_lock.acquire()
if self.clear_to_send.isSet():
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def _generate_prime(bits, rng):
"primtive attempt at prime generation"
hbyte_mask = pow(2, bits % 8) - 1
while True:
# loop catches the case where we increment n into a higher bit-range
x = rng.read((bits+7) // 8)
if hbyte_mask > 0:
x = chr(ord(x[0]) & hbyte_mask) + x[1:]... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_string(self, s):
""" Add a string to the stream. @param s: string to add @type s: str """ |
self.add_int(len(s))
self.packet.write(s)
return self |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def agent_auth(transport, username):
""" Attempt to authenticate to the given transport using any of the private keys available from an SSH agent. """ |
agent = ssh.Agent()
agent_keys = agent.get_keys()
if len(agent_keys) == 0:
return
for key in agent_keys:
print 'Trying ssh-agent key %s' % hexlify(key.get_fingerprint()),
try:
transport.auth_publickey(username, key)
print '... success!'
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _read_prefetch(self, size):
""" read data out of the prefetch buffer, if possible. if the data isn't in the buffer, return None. otherwise, behaves like a no... |
# while not closed, and haven't fetched past the current position, and haven't reached EOF...
while True:
offset = self._data_in_prefetch_buffers(self._realpos)
if offset is not None:
break
if self._prefetch_done or self._closed:
break... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _set_mode(self, mode='r', bufsize=-1):
""" Subclasses call this method to initialize the BufferedFile. """ |
# set bufsize in any event, because it's used for readline().
self._bufsize = self._DEFAULT_BUFSIZE
if bufsize < 0:
# do no buffering by default, because otherwise writes will get
# buffered in a way that will probably confuse people.
bufsize = 0
if b... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _request(self, method, path, data=None, reestablish_session=True):
"""Perform HTTP request for REST API.""" |
if path.startswith("http"):
url = path # For cases where URL of different form is needed.
else:
url = self._format_path(path)
headers = {"Content-Type": "application/json"}
if self._user_agent:
headers['User-Agent'] = self._user_agent
body ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _check_rest_version(self, version):
"""Validate a REST API version is supported by the library and target array.""" |
version = str(version)
if version not in self.supported_rest_versions:
msg = "Library is incompatible with REST API version {0}"
raise ValueError(msg.format(version))
array_rest_versions = self._list_available_rest_versions()
if version not in array_rest_versio... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _choose_rest_version(self):
"""Return the newest REST API version supported by target array.""" |
versions = self._list_available_rest_versions()
versions = [LooseVersion(x) for x in versions if x in self.supported_rest_versions]
if versions:
return max(versions)
else:
raise PureError(
"Library is incompatible with all REST API versions suppor... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _list_available_rest_versions(self):
"""Return a list of the REST API versions supported by the array""" |
url = "https://{0}/api/api_version".format(self._target)
data = self._request("GET", url, reestablish_session=False)
return data["version"] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _obtain_api_token(self, username, password):
"""Use username and password to obtain and return an API token.""" |
data = self._request("POST", "auth/apitoken",
{"username": username, "password": password},
reestablish_session=False)
return data["api_token"] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create_snapshots(self, volumes, **kwargs):
"""Create snapshots of the listed volumes. :param volumes: List of names of the volumes to snapshot. :type volumes... |
data = {"source": volumes, "snap": True}
data.update(kwargs)
return self._request("POST", "volume", data) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create_volume(self, volume, size, **kwargs):
"""Create a volume and return a dictionary describing it. :param volume: Name of the volume to be created. :type... |
data = {"size": size}
data.update(kwargs)
return self._request("POST", "volume/{0}".format(volume), data) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def extend_volume(self, volume, size):
"""Extend a volume to a new, larger size. :param volume: Name of the volume to be extended. :type volume: str :type size: ... |
return self.set_volume(volume, size=size, truncate=False) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def truncate_volume(self, volume, size):
"""Truncate a volume to a new, smaller size. :param volume: Name of the volume to truncate. :type volume: str :param siz... |
return self.set_volume(volume, size=size, truncate=True) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def connect_host(self, host, volume, **kwargs):
"""Create a connection between a host and a volume. :param host: Name of host to connect to volume. :type host: s... |
return self._request(
"POST", "host/{0}/volume/{1}".format(host, volume), kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def connect_hgroup(self, hgroup, volume, **kwargs):
"""Create a shared connection between a host group and a volume. :param hgroup: Name of hgroup to connect to ... |
return self._request(
"POST", "hgroup/{0}/volume/{1}".format(hgroup, volume), kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_offload(self, name, **kwargs):
"""Return a dictionary describing the connected offload target. :param offload: Name of offload target to get information ... |
# Unbox if a list to accommodate a bug in REST 1.14
result = self._request("GET", "offload/{0}".format(name), kwargs)
if isinstance(result, list):
headers = result.headers
result = ResponseDict(result[0])
result.headers = headers
return result |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create_subnet(self, subnet, prefix, **kwargs):
"""Create a subnet. :param subnet: Name of subnet to be created. :type subnet: str :param prefix: Routing pref... |
data = {"prefix": prefix}
data.update(kwargs)
return self._request("POST", "subnet/{0}".format(subnet), data) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create_vlan_interface(self, interface, subnet, **kwargs):
"""Create a vlan interface :param interface: Name of interface to be created. :type interface: str ... |
data = {"subnet": subnet}
data.update(kwargs)
return self._request("POST", "network/vif/{0}".format(interface), data) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_password(self, admin, new_password, old_password):
"""Set an admin's password. :param admin: Name of admin whose password is to be set. :type admin: str ... |
return self.set_admin(admin, password=new_password,
old_password=old_password) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.