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 generate_shapes(shapes): """ Generate the shapes for the topology :param dict shapes: A dict of converted shapes from the old topology :return: dict containi...
new_shapes = {'ellipse': [], 'rectangle': []} for shape in shapes: tmp_shape = {} for shape_item in shapes[shape]: if shape_item != 'type': tmp_shape[shape_item] = shapes[shape][shape_item] new_shapes[shapes[shape]['type']].appen...
<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_notes(notes): """ Generate the notes list :param dict notes: A dict of converted notes from the old topology :return: List of notes for the the topo...
new_notes = [] for note in notes: tmp_note = {} for note_item in notes[note]: tmp_note[note_item] = notes[note][note_item] new_notes.append(tmp_note) return new_notes
<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_images(self, pixmaps): """ Generate the images list and store the images to copy :param dict pixmaps: A dict of converted pixmaps from the old topol...
new_images = [] for image in pixmaps: tmp_image = {} for img_item in pixmaps[image]: if img_item == 'path': path = os.path.join('images', os.path.basename( pi...
<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_qemu_path(self, instance): """ Add the qemu path to the hypervisor conf data :param instance: Hypervisor instance """
tmp_conf = {'qemu_path': self.old_top[instance]['qemupath']} if len(self.topology['conf']) == 0: self.topology['conf'].append(tmp_conf) else: self.topology['conf'][self.hv_id].update(tmp_conf)
<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_conf_item(self, instance, item): """ Add a hypervisor configuration item :param instance: Hypervisor instance :param item: Item to add """
tmp_conf = {} if item not in EXTRA_CONF: tmp_conf['model'] = MODEL_TRANSFORM[item] for s_item in sorted(self.old_top[instance][item]): if self.old_top[instance][item][s_item] is not None: tmp_conf[s_item] = self.old_top[instance][item][s_item] ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def device_typename(item): """ Convert the old names to new-style names and types :param str item: A device in the form of 'TYPE NAME' :return: tuple containing ...
dev_type = {'ROUTER': {'from': 'ROUTER', 'desc': 'Router', 'type': 'Router', 'label_x': 19.5}, 'QEMU': {'from': 'QEMU', 'desc': 'QEMU VM', ...
<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_topology(self): """ Get the converted topology ready for JSON encoding :return: converted topology assembled into a single dict :rtype: dict """
topology = {'name': self._name, 'resources_type': 'local', 'topology': {}, 'type': 'topology', 'version': '1.0'} if self._links: topology['topology']['links'] = self._links if self._nodes: t...
<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_vboxes(self): """ Get the maximum ID of the VBoxes :return: Maximum VBox ID :rtype: int """
vbox_list = [] vbox_max = None for node in self.nodes: if node['type'] == 'VirtualBoxVM': vbox_list.append(node['vbox_id']) if len(vbox_list) > 0: vbox_max = max(vbox_list) return vbox_max
<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_qemus(self): """ Get the maximum ID of the Qemu VMs :return: Maximum Qemu VM ID :rtype: int """
qemu_vm_list = [] qemu_vm_max = None for node in self.nodes: if node['type'] == 'QemuVM': qemu_vm_list.append(node['qemu_id']) if len(qemu_vm_list) > 0: qemu_vm_max = max(qemu_vm_list) return qemu_vm_max
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def getElements(self,name=''): 'Get a list of child elements' #If no tag name is specified, return the all children if not name: return self.children else: # else return only those children with a matching tag name elements = [] for element in self.children: if element.name == name: element...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def StartElement(self,name,attributes): 'SAX start element even handler' # Instantiate an Element object element = Element(name.encode(),attributes) # Push element onto the stack and make it a child of parent if len(self.nodeStack) > 0: parent = self.nodeStack[-1] parent.AddChild(element) 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 CharacterData(self,data): 'SAX character data event handler' ## HACK: to preserve the newlines #if string.strip(data): data = data.encode("utf-8") element = self.nodeStack[-1] element.cdata += data return
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def doShow(self, xml=0): """Shows the contents of our resultset."""
if xml == 0: print 'Errorcode:', self.errorcode print print 'Product information:' for key in self.product.keys(): print ' ', key.encode('UTF-8'), print '->', self.product[key].encode('UTF-8') print print 'Database information:' for key in self.database.keys(): print ' ',...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _setSkipRecords(self, skipRec): """Specifies how many records to skip in the found set"""
if type(skipRec) == int or (type(skipRec) == str and skipRec.isdigit()): self._skipRecords = skipRec else: raise FMError, 'Unsupported -skip value (not a number).'
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _setLogicalOperator(self, lop): """Sets the way the find fields should be combined together."""
if not lop.lower() in ['and', 'or']: raise FMError, 'Unsupported logical operator (not one of "and" or "or").' self._lop = lop.lower()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _setComparasionOperator(self, field, oper): """Sets correct operator for given string representation"""
if oper != '': validOperators = { 'eq':'eq', 'equals':'eq', '=':'eq', '==':'eq', 'cn':'cn', 'contains':'cn', '%%':'cn', '%':'cn', '*':'cn', 'bw':'bw', 'begins with':'bw', '^':'bw', 'ew':'ew', 'ends with':'ew', '$':'ew', 'gt':'gt', 'greater than'...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _addDBParam(self, name, value): """Adds a database parameter"""
if name[-4:] == '__OP': return self._setComparasionOperator(name[:-4], value) if name[-3:] == '.op': return self._setComparasionOperator(name[:-3], value) if name.find('__') != -1: import re name = name.replace('__','::') elif name.find('.') != -1: name = name.replace('.','::') self._dbParam...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getFile(self, file_xml_uri): """ This will execute cmd to fetch file data from FMServer """
find = re.match('/fmi/xml/cnt/([\w\d.-]+)\.([\w]+)?-*', file_xml_uri) file_name = find.group(1) file_extension = find.group(2) file_binary = self._doRequest(is_file=True, file_xml_uri=file_xml_uri) return (file_name, file_extension, file_binary)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def doScript(self, script_name, params=None, return_all=False): """This function executes the script for given layout for the current db."""
request = [ uu({'-db': self._db }), uu({'-lay': self._layout }), uu({'-script': script_name}) ] if params: request.append(uu({'-script.param': params })) request.append(uu({'-findall': '' })) result = self._doRequest(request) result = FMResultset.FMResultset(result) try: # Try to retur...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def doScriptAfter(self, func, func_kwargs={}, script_name='', params=None): """ This function will execute extra script after passed function """
request = [ uu({'-script': script_name}) ] if params: request.append(uu({'-script.param': params })) self._extra_script = request return func(**func_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 getDbNames(self): """This function returns the list of open databases"""
request = [] request.append(uu({'-dbnames': '' })) result = self._doRequest(request) result = FMResultset.FMResultset(result) dbNames = [] for dbName in result.resultset: dbNames.append(string.lower(dbName['DATABASE_NAME'])) return dbNames
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def doFind(self, WHAT={}, SORT=[], SKIP=None, MAX=None, LOP='AND', **params): """This function will perform the command -find."""
self._preFind(WHAT, SORT, SKIP, MAX, LOP) for key in params: self._addDBParam(key, params[key]) try: return self._doAction('-find') except FMServerError as e: if e.args[0] in [401, 8]: return []
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def doFindAll(self, WHAT={}, SORT=[], SKIP=None, MAX=None): """This function will perform the command -findall."""
self._preFind(WHAT, SORT, SKIP, MAX) return self._doAction('-findall')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def doFindAny(self, WHAT={}, SORT=[], SKIP=None, MAX=None, LOP='AND', **params): """This function will perform the command -findany."""
self._preFind(WHAT, SORT, SKIP, MAX, LOP) for key in params: self._addDBParam(key, params[key]) return self._doAction('-findany')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def doDelete(self, WHAT={}): """This function will perform the command -delete."""
if hasattr(WHAT, '_modified'): self._addDBParam('RECORDID', WHAT.RECORDID) self._addDBParam('MODID', WHAT.MODID) elif type(WHAT) == dict and WHAT.has_key('RECORDID'): self._addDBParam('RECORDID', WHAT['RECORDID']) else: raise FMError, 'Python Runtime: Object type (%s) given to function doDelete as a...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def doNew(self, WHAT={}, **params): """This function will perform the command -new."""
if hasattr(WHAT, '_modified'): for key in WHAT: if key not in ['RECORDID','MODID']: if WHAT.__new2old__.has_key(key): self._addDBParam(WHAT.__new2old__[key].encode('utf-8'), WHAT[key]) else: self._addDBParam(key, WHAT[key]) elif type(WHAT)==dict: for key in WHAT: self._addDBPar...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def doDup(self, WHAT={}, **params): """This function will perform the command -dup."""
if hasattr(WHAT, '_modified'): for key, value in WHAT._modified(): if WHAT.__new2old__.has_key(key): self._addDBParam(WHAT.__new2old__[key].encode('utf-8'), value) else: self._addDBParam(key, value) self._addDBParam('RECORDID', WHAT.RECORDID) self._addDBParam('MODID', WHAT.MODID) elif t...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _buildUrl(self): """Builds url for normal FM requests."""
return '%(protocol)s://%(host)s:%(port)s%(address)s'%{ 'protocol': self._protocol, 'host': self._host, 'port': self._port, 'address': self._address, }
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _buildFileUrl(self, xml_req): """Builds url for fetching the files from FM."""
return '%(protocol)s://%(host)s:%(port)s%(xml_req)s'%{ 'protocol': self._protocol, 'host': self._host, 'port': self._port, 'xml_req': xml_req, }
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _doRequest(self, request=None, is_file=False, file_xml_uri=''): """This function will perform the specified request on the FileMaker server, and it will ...
if request is None: request = [] if is_file and file_xml_uri: url = self._buildFileUrl(file_xml_uri) else: request = '&'.join(request) url = "%s?%s" % (self._buildUrl(), request) if self._debug: print '[PyFileMaker DEBUG] ', url resp = requests.get( url = url, auth = (self._login, sel...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def FMErrorByNum( num ): """This function raises an error based on the specified error code."""
if not num in FMErrorNum.keys(): raise FMServerError, (num, FMErrorNum[-1]) elif num == 102: raise FMFieldError, (num, FMErrorNum[num]) else: raise FMServerError, (num, FMErrorNum[num])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def doParseXMLData( self ): """This function parses the XML output of FileMaker."""
parser = xml2obj.Xml2Obj() # Not valid document comming from FMServer if self.data[-6:] == '</COL>': self.data += '</ROW></RESULTSET></FMPXMLRESULT>' xobj = parser.ParseString( self.data ) try: el = xobj.getElements( 'ERRORCODE') if el: self.errorcode = int( el[0].getData() ) else: 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 fill(metrics_headers=()): """Add the metrics headers known to GAX. Return an OrderedDict with all of the metrics headers provided to this function, as well a...
# Create an ordered dictionary with the Python version, which # should go first. answer = collections.OrderedDict(( ('gl-python', platform.python_version()), )) # Add anything that already appears in the passed metrics headers, # in order. for key, value in collections.OrderedDict(...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def stringify(metrics_headers=()): """Convert the provided metrics headers to a string. Iterate over the metrics headers (a dictionary, usually ordered) and retu...
metrics_headers = collections.OrderedDict(metrics_headers) return ' '.join(['%s/%s' % (k, v) for k, v in metrics_headers.items()])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _str_dotted_getattr(obj, name): """Expands extends getattr to allow dots in x to indicate nested objects. Args: obj (object): an object. name (str): a name...
for part in name.split('.'): obj = getattr(obj, part) return str(obj) if obj else 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 request_bytesize(self): """The size of in bytes of the bundled field elements."""
return sum(len(str(e)) for elts in self._in_deque for e in elts)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def run(self): """Call the task's func. The task's func will be called with the bundling requests func """
if not self._in_deque: return req = self._bundling_request del getattr(req, self.bundled_field)[:] getattr(req, self.bundled_field).extend( [e for elts in self._in_deque for e in elts]) subresponse_field = self.subresponse_field if subresponse_fi...
<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(self, elts): """Adds elts to the tasks. Args: elts (Sequence): a iterable of elements that can be appended to the task's bundle_field. Returns: Event...
# Use a copy, not a reference, as it is later necessary to mutate # the proto field from which elts are drawn in order to construct # the bundled request. elts = elts[:] self._in_deque.append(elts) event = self._event_for(elts) self._event_deque.append(event) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _event_for(self, elts): """Creates an Event that is set when the bundle with elts is sent."""
event = Event() event.canceller = self._canceller_for(elts, event) return event
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _canceller_for(self, elts, event): """Obtains a cancellation function that removes elts. The returned cancellation function returns ``True`` if all elements ...
def canceller(): """Cancels submission of ``elts`` as part of this bundle. Returns: bool: ``False`` if any of elements had already been sent, otherwise ``True``. """ try: self._event_deque.remove(event) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def schedule(self, api_call, bundle_id, bundle_desc, bundling_request, kwargs=None): """Schedules bundle_desc of bundling_request as part of bundle_id. The retur...
kwargs = kwargs or dict() bundle = self._bundle_for(api_call, bundle_id, bundle_desc, bundling_request, kwargs) elts = getattr(bundling_request, bundle_desc.bundled_field) event = bundle.extend(elts) # Run the bundle if the count threshold was ...
<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_stub(generated_create_stub, channel=None, service_path=None, service_port=None, credentials=None, scopes=None, ssl_credentials=None): """Creates a gRP...
if channel is None: target = '{}:{}'.format(service_path, service_port) if credentials is None: credentials = _grpc_google_auth.get_default_credentials(scopes) channel = _grpc_google_auth.secure_authorized_channel( credentials, target, ssl_credentials=ssl_credentia...
<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_default_credentials(scopes): """Gets the Application Default Credentials."""
credentials, _ = google.auth.default(scopes=scopes) return credentials
<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_timeout_arg(a_func, timeout, **kwargs): """Updates a_func so that it gets called with the timeout as its final arg. This converts a callable, a_func, int...
def inner(*args): """Updates args with the timeout.""" updated_args = args + (timeout,) return a_func(*updated_args, **kwargs) return inner
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def retryable(a_func, retry_options, **kwargs): """Creates a function equivalent to a_func, but that retries on certain exceptions. Args: a_func (callable): A c...
delay_mult = retry_options.backoff_settings.retry_delay_multiplier max_delay_millis = retry_options.backoff_settings.max_retry_delay_millis has_timeout_settings = _has_timeout_settings(retry_options.backoff_settings) if has_timeout_settings: timeout_mult = retry_options.backoff_settings.rpc_ti...
<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_error(msg, cause=None): """Creates a ``GaxError`` or subclass. Attributes: msg (string): describes the error that occurred. cause (Exception, optiona...
status_code = config.exc_to_code(cause) status_name = config.NAME_STATUS_CODES.get(status_code) if status_name == 'INVALID_ARGUMENT': return InvalidArgumentError(msg, cause=cause) else: return GaxError(msg, cause=cause)
<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_operation(self, name, options=None): """ Gets the latest state of a long-running operation. Clients can use this method to poll the operation result at i...
# Create the request object. request = operations_pb2.GetOperationRequest(name=name) return self._get_operation(request, options)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cancel_operation(self, name, options=None): """ Starts asynchronous cancellation on a long-running operation. The server makes a best effort to cancel the op...
# Create the request object. request = operations_pb2.CancelOperationRequest(name=name) self._cancel_operation(request, options)
<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_operation(self, name, options=None): """ Deletes a long-running operation. This method indicates that the client is no longer interested in the operat...
# Create the request object. request = operations_pb2.DeleteOperationRequest(name=name) self._delete_operation(request, options)
<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_oneof(**kwargs): """Raise ValueError if more than one keyword argument is not none. Args: kwargs (dict): The keyword arguments sent to the function. R...
# Sanity check: If no keyword arguments were sent, this is fine. if not kwargs: return None not_nones = [val for val in kwargs.values() if val is not None] if len(not_nones) > 1: raise ValueError('Only one of {fields} should be set.'.format( fields=', '.join(sorted(kwargs.k...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _bundleable(desc): """Creates a function that transforms an API call into a bundling call. It transform a_func from an API call that receives the requests an...
def inner(a_func, settings, request, **kwargs): """Schedules execution of a bundling task.""" if not settings.bundler: return a_func(request, **kwargs) the_id = bundling.compute_bundle_id( request, desc.request_discriminator_fields) return settings.bundler.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 _page_streamable(page_descriptor): """Creates a function that yields an iterable to performs page-streaming. Args: page_descriptor (:class:`PageDescriptor`):...
def inner(a_func, settings, request, **kwargs): """Actual page-streaming based on the settings.""" page_iterator = gax.PageIterator( a_func, page_descriptor, settings.page_token, request, **kwargs) if settings.flatten_pages: return gax.ResourceIterator(page_iterator...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def construct_settings( service_name, client_config, config_override, retry_names, bundle_descriptors=None, page_descriptors=None, metrics_headers=(), kwargs=None...
# pylint: disable=too-many-locals # pylint: disable=protected-access defaults = {} bundle_descriptors = bundle_descriptors or {} page_descriptors = page_descriptors or {} kwargs = kwargs or {} # Sanity check: It is possible that we got this far but some headers # were specified with an...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _catch_errors(a_func, to_catch): """Updates a_func to wrap exceptions with GaxError Args: a_func (callable): A callable. to_catch (list[Exception]): Config...
def inner(*args, **kwargs): """Wraps specified exceptions""" try: return a_func(*args, **kwargs) # pylint: disable=catching-non-exception except tuple(to_catch) as exception: utils.raise_with_traceback( gax.errors.create_error('RPC failed', ca...
<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_api_call(func, settings): """Converts an rpc call into an API call governed by the settings. In typical usage, ``func`` will be a callable used to mak...
def base_caller(api_call, _, *args): """Simply call api_call and ignore settings.""" return api_call(*args) def inner(request, options=None): """Invoke with the actual settings.""" this_options = _merge_options_metadata(options, settings) this_settings = settings.merge(...
<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(pb_or_dict, key, default=_SENTINEL): """Retrieve the given key off of the object. If a default is specified, return it if the key is not found, otherwise...
# We may need to get a nested key. Resolve this. key, subkey = _resolve_subkeys(key) # Attempt to get the value from the two types of objects we know baout. # If we get something else, complain. if isinstance(pb_or_dict, Message): answer = getattr(pb_or_dict, key, default) elif isinsta...
<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(pb_or_dict, key, value): """Set the given key on the object. Args: pb_or_dict (Union[~google.protobuf.message.Message, Mapping]): the object. key (str):...
# pylint: disable=redefined-builtin,too-many-branches # redefined-builtin: We want 'set' to be part of the public interface. # too-many-branches: This method is inherently complex. # Sanity check: Is our target object valid? if not isinstance(pb_or_dict, (collections.MutableMapping, Message)): ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def setdefault(pb_or_dict, key, value): """Set the key on the object to the value if the current value is falsy. Because protobuf Messages do not distinguish bet...
if not get(pb_or_dict, key, default=None): set(pb_or_dict, key, value)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _resolve_subkeys(key, separator='.'): """Given a key which may actually be a nested key, return the top level key and any nested subkeys as separate values. ...
subkey = None if separator in key: index = key.index(separator) subkey = key[index + 1:] key = key[:index] return key, subkey
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def merge(self, options): """Returns new _CallSettings merged from this and a CallOptions object. Note that passing if the CallOptions instance specifies a page_...
if not options: return _CallSettings( timeout=self.timeout, retry=self.retry, page_descriptor=self.page_descriptor, page_token=self.page_token, bundler=self.bundler, bundle_descriptor=self.bundle_descriptor, kwargs=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 cancel(self): """If last Operation's value of `done` is true, returns false; otherwise, issues OperationsClient.cancel_operation and returns true. """
if self.done(): return False self._client.cancel_operation(self._operation.name) 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 result(self, timeout=None): """Enters polling loop on OperationsClient.get_operation, and once Operation.done is true, then returns Operation.response if suc...
# Check exceptional case: raise if no response if not self._poll(timeout).HasField('response'): raise GaxError(self._operation.error.message) # Return expected result return _from_any(self._result_type, self._operation.response)
<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_done_callback(self, fn): # pylint: disable=invalid-name """Enters a polling loop on OperationsClient.get_operation, and once the operation is done or can...
if self._operation.done: _try_callback(self, fn) else: self._queue.put(dill.dumps(fn)) if self._process is None: self._process = mp.Process(target=self._execute_tasks) self._process.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 get_sql(self): """ Generates the JOIN sql for the join tables and join condition :rtype: str :return: the JOIN sql for the join tables and join condition """
return '{0} {1} ON {2}'.format(self.join_type, self.right_table.get_sql(), self.get_condition())
<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_left_table(self, left_table=None): """ Sets the left table for this join clause. If no table is specified, the first table in the query will be used :typ...
if left_table: self.left_table = TableFactory( table=left_table, owner=self.owner, ) else: self.left_table = self.get_left_table()
<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_left_table(self): """ Returns the left table if one was specified, otherwise the first table in the query is returned :rtype: :class:`Table <querybuilder...
if self.left_table: return self.left_table if len(self.owner.tables): return self.owner.tables[0]
<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_related_objects(self, table): """ Fix for django 1.10 to replace deprecated code. Keep support for django 1.7 """
# Django 1.7 method if hasattr(table.model._meta, 'get_all_related_objects'): return table.model._meta.get_all_related_objects() else: # Django > 1.7 return [ f for f in table.model._meta.get_fields() if (f.one_to_many or f.one...
<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_right_table(self, table): """ Sets the right table for this join clause and try to automatically set the condition if one isn't specified """
self.right_table = table if self.left_table is None: return # find table prefix if type(self.left_table) is ModelTable and type(self.right_table) is ModelTable: # loop through fields to find the field for this model # check if this join type is 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 get_condition(self): """ Determines the condition to be used in the condition part of the join sql. :return: The condition for the join clause :rtype: str or...
if self.condition: return self.condition if type(self.right_table) is ModelTable and type(self.right_table) is ModelTable: # loop through fields to find the field for this model # check if this join type is for a related field for field in self.get_all_...
<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_sql(self): """ Builds and returns the WHERE portion of the sql :return: the WHERE portion of the sql :rtype: str """
# reset arg index and args self.arg_index = 0 self.args = {} # build the WHERE sql portion if needed if len(self.wheres): where = self.build_where_part(self.wheres) return 'WHERE {0} '.format(where) return ''
<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_condition_value(self, operator, value): """ Gets the condition value based on the operator and value :param operator: the condition operator name :type o...
if operator in ('contains', 'icontains'): value = '%{0}%'.format(value) elif operator == 'startswith': value = '{0}%'.format(value) return value
<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_arg(self, value): """ Set the query param in self.args based on the prefix and arg index and auto increment the arg_index :return: the string placeholder...
named_arg = '{0}A{1}'.format(self.arg_prefix, self.arg_index) self.args[named_arg] = value self.arg_index += 1 return named_arg
<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_name(self, use_alias=True): """ Gets the name to reference the sorted field :return: the name to reference the sorted field :rtype: str """
if self.desc: direction = 'DESC' else: direction = 'ASC' if use_alias: return '{0} {1}'.format(self.field.get_identifier(), direction) return '{0} {1}'.format(self.field.get_select_sql(), direction)
<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_sql(self): """ Generates the sql used for the limit clause of a Query :return: the sql for the limit clause of a Query :rtype: str """
sql = '' if self.limit and self.limit > 0: sql += 'LIMIT {0} '.format(self.limit) if self.offset and self.offset > 0: sql += 'OFFSET {0} '.format(self.offset) return sql
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def init_defaults(self): """ Sets the default values for this instance """
self.sql = '' self.tables = [] self.joins = [] self._where = Where() self.groups = [] self.sorters = [] self._limit = None self.table_prefix = '' self.is_inner = False self.with_tables = [] self._distinct = False self.disti...
<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_table(self, table=None, fields='*', schema=None, **kwargs): """ Adds a ``Table`` and any optional fields to the list of tables this query is selecting f...
# self.mark_dirty() self.tables.append(TableFactory( table=table, fields=fields, schema=schema, owner=self, **kwargs )) 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 insert_into(self, table=None, field_names=None, values=None, **kwargs): """ Bulk inserts a list of values into a table :type table: str or dict or :class:`Ta...
table = TableFactory( table=table, **kwargs ) self.tables.append(table) self.field_names = field_names self.values = values 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 update_table(self, table=None, field_names=None, values=None, pk=None, **kwargs): """ Bulk updates rows in a table :type table: str or dict or :class:`Table ...
table = TableFactory( table=table, **kwargs ) self.tables.append(table) self.field_names = field_names self.values = values self.field_names_pk = pk
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def join(self, right_table=None, fields=None, condition=None, join_type='JOIN', schema=None, left_table=None, extract_fields=True, prefix_fields=False, field_pref...
# self.mark_dirty() # TODO: fix bug when joining from simple table to model table with no condition # it assumes left_table.model # if there is no left table, assume the query's first table # TODO: add test for auto left table to replace old auto left table # if left_ta...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def join_left(self, right_table=None, fields=None, condition=None, join_type='LEFT JOIN', schema=None, left_table=None, extract_fields=True, prefix_fields=False, ...
return self.join( right_table=right_table, fields=fields, condition=condition, join_type=join_type, schema=schema, left_table=left_table, extract_fields=extract_fields, prefix_fields=prefix_fields, 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 where(self, q=None, where_type='AND', **kwargs): """ Adds a where condition as a Q object to the query's ``Where`` instance. :type q: :class:`Q <django:djang...
# self.mark_dirty() if q is not None: self._where.wheres.add(q, where_type) if len(kwargs): for key, value in kwargs.items(): q = Q(**{ key: value }) self._where.wheres.add(q, where_type) return ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def group_by(self, field=None, table=None, allow_duplicates=False): """ Adds a group by clause to the query by adding a ``Group`` instance to the query's groups ...
new_group_item = Group( field=field, table=table, ) if allow_duplicates is False: for group_item in self.groups: if group_item.field.get_identifier() == new_group_item.field.get_identifier(): return self self.grou...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def order_by(self, field=None, table=None, desc=False): """ Adds an order by clause to the query by adding a ``Sorter`` instance to the query's sorters list :typ...
self.sorters.append(Sorter( field=field, table=table, desc=desc )) 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 check_name_collisions(self): """ Checks if there are any tables referenced by the same identifier and updated the auto_alias accordingly. This is called when...
table_index = 0 table_names = {} for table in self.tables + self.with_tables: table_prefix = 'T{0}'.format(table_index) auto_alias = '{0}{1}'.format(self.table_prefix, table_prefix) identifier = table.get_identifier() if identifier is None or ide...
<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_sql(self, debug=False, use_cache=True): """ Generates the sql for this query and returns the sql as a string. :type debug: bool :param debug: If True, th...
# TODO: enable caching # if self.sql and use_cache and not debug: # return self.sql # auto alias any naming collisions self.check_name_collisions() # if debugging, return the debug formatted sql if debug: return self.format_sql() # buil...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def format_sql(self): """ Builds the sql in a format that is easy for humans to read and debug :return: The formatted sql for this query :rtype: str """
# TODO: finish adding the other parts of the sql generation sql = '' # build SELECT select_segment = self.build_select_fields() select_segment = select_segment.replace('SELECT ', '', 1) fields = [field.strip() for field in select_segment.split(',')] sql += 'SELE...
<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_select_fields(self): """ Generates the sql for the SELECT portion of the query :return: the SELECT portion of the query :rtype: str """
field_sql = [] # get the field sql for each table for table in self.tables: field_sql += table.get_field_sql() # get the field sql for each join table for join_item in self.joins: field_sql += join_item.right_table.get_field_sql() # combine all...
<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_from_table(self): """ Generates the sql for the FROM portion of the query :return: the FROM portion of the query :rtype: str """
table_parts = [] # get the table sql for each table for table in self.tables: sql = table.get_sql() if len(sql): table_parts.append(sql) # combine all table sql separated by a comma sql = 'FROM {0} '.format(', '.join(table_parts)) ...
<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_joins(self): """ Generates the sql for the JOIN portion of the query :return: the JOIN portion of the query :rtype: str """
join_parts = [] # get the sql for each join object for join_item in self.joins: join_parts.append(join_item.get_sql()) # if there are any joins, combine them if len(join_parts): combined_joins = ' '.join(join_parts) return '{0} '.format(comb...
<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_groups(self): """ Generates the sql for the GROUP BY portion of the query :return: the GROUP BY portion of the query :rtype: str """
# check if there are any groupings if len(self.groups): groups = [] # get the group sql for each grouping for group in self.groups: groups.append(group.get_name()) return 'GROUP BY {0} '.format(', '.join(groups)) return ''
<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_order_by(self, use_alias=True): """ Generates the sql for the ORDER BY portion of the query :type use_alias: bool :param use_alias: If True, the alias ...
# check if there are any sorters if len(self.sorters): sorters = [] # get the sql for each sorter for sorter in self.sorters: sorters.append(sorter.get_name(use_alias=use_alias)) return 'ORDER BY {0} '.format(', '.join(sorters)) r...
<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_table(self, table): """ Finds a table by name or alias. The FROM tables and JOIN tables are included in the search. :type table: str or :class:`ModelBas...
table = TableFactory(table) identifier = table.get_identifier() join_tables = [join_item.right_table for join_item in self.joins] for table in (self.tables + join_tables): if table.get_identifier() == identifier: return table return 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 wrap(self, alias=None): """ Wraps the query by selecting all fields from itself :rtype: :class:`Query <querybuilder.query.Query>` :return: The wrapped query ...
field_names = self.get_field_names() query = Query(self.connection).from_table(deepcopy(self), alias=alias) self.__dict__.update(query.__dict__) # set explicit field names self.tables[0].set_fields(field_names) field_names = self.get_field_names() 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 copy(self): """ Deeply copies everything in the query object except the connection object is shared """
connection = self.connection del self.connection copied_query = deepcopy(self) copied_query.connection = connection self.connection = connection return copied_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_args(self): """ Gets the args for the query which will be escaped when being executed by the db. All inner queries are inspected and their args are combi...
for table in self.tables + self.with_tables: if type(table) is QueryTable: self._where.args.update(table.query.get_args()) return self._where.args
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def explain(self, sql=None, sql_args=None): """ Runs EXPLAIN on this query :type sql: str or None :param sql: The sql to run EXPLAIN on. If None is specified, th...
cursor = self.get_cursor() if sql is None: sql = self.get_sql() sql_args = self.get_args() elif sql_args is None: sql_args = {} cursor.execute('EXPLAIN {0}'.format(sql), sql_args) rows = self._fetch_all_as_dict(cursor) return rows
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def select(self, return_models=False, nest=False, bypass_safe_limit=False, sql=None, sql_args=None): """ Executes the SELECT statement and returns the rows as a ...
# Check if we need to set a safe limit if bypass_safe_limit is False: if Query.enable_safe_limit: if self.count() > Query.safe_limit: self.limit(Query.safe_limit) # determine which sql to use if sql is None: sql = self.get_sql...
<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, rows): """ Updates records in the db """
if len(rows) == 0: return sql, sql_args = self.get_update_sql(rows) # get the cursor to execute the query cursor = self.get_cursor() # execute the query cursor.execute(sql, sql_args)
<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_auto_field_name(self, model_class): """ If one of the unique_fields is the model's AutoField, return the field name, otherwise return None """
# Get auto field name (a model can only have one AutoField) for field in model_class._meta.fields: if isinstance(field, AutoField): return field.column return 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 upsert(self, rows, unique_fields, update_fields, return_rows=False, return_models=False): """ Performs an upsert with the set of models defined in rows. If t...
if len(rows) == 0: return ModelClass = self.tables[0].model rows_with_null_auto_field_value = [] # Get auto field name (a model can only have one AutoField) auto_field_name = self.get_auto_field_name(ModelClass) # Check if unique fields list contains an a...