INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Draw ridgeplot for each plotter.
def ridgeplot(self, mult, linewidth, alpha, ax): """Draw ridgeplot for each plotter. Parameters ---------- mult : float How much to multiply height by. Set this to greater than 1 to have some overlap. linewidth : float Width of line on border of ridges ...
Draw forestplot for each plotter.
def forestplot( self, credible_interval, quartiles, xt_labelsize, titlesize, linewidth, markersize, ax, rope ): """Draw forestplot for each plotter. Parameters ---------- credible_interval : float How wide each line should be quartiles : bool ...
Draw effective n for each plotter.
def plot_neff(self, ax, xt_labelsize, titlesize, markersize): """Draw effective n for each plotter.""" for plotter in self.plotters.values(): for y, ess, color in plotter.ess(): if ess is not None: ax.plot( ess, ...
Draw r - hat for each plotter.
def plot_rhat(self, ax, xt_labelsize, titlesize, markersize): """Draw r-hat for each plotter.""" for plotter in self.plotters.values(): for y, r_hat, color in plotter.r_hat(): if r_hat is not None: ax.plot(r_hat, y, "o", color=color, markersize=markersize,...
Draw shaded horizontal bands for each plotter.
def make_bands(self, ax): """Draw shaded horizontal bands for each plotter.""" y_vals, y_prev, is_zero = [0], None, False prev_color_index = 0 for plotter in self.plotters.values(): for y, *_, color in plotter.iterator(): if self.colors.index(color) < prev_col...
Figure out the height of this plot.
def fig_height(self): """Figure out the height of this plot.""" # hand-tuned return ( 4 + len(self.data) * len(self.var_names) - 1 + 0.1 * sum(1 for j in self.plotters.values() for _ in j.iterator()) )
Iterate over models and chains for each variable.
def iterator(self): """Iterate over models and chains for each variable.""" if self.combined: grouped_data = [[(0, datum)] for datum in self.data] skip_dims = {"chain"} else: grouped_data = [datum.groupby("chain") for datum in self.data] skip_dims ...
Get labels ticks values and colors for the variable.
def labels_ticks_and_vals(self): """Get labels, ticks, values, and colors for the variable.""" y_ticks = defaultdict(list) for y, label, _, vals, color in self.iterator(): y_ticks[label].append((y, vals, color)) labels, ticks, vals, colors = [], [], [], [] for label, ...
Get data for each treeplot for the variable.
def treeplot(self, qlist, credible_interval): """Get data for each treeplot for the variable.""" for y, _, label, values, color in self.iterator(): ntiles = np.percentile(values.flatten(), qlist) ntiles[0], ntiles[-1] = hpd(values.flatten(), credible_interval) yield y...
Get data for each ridgeplot for the variable.
def ridgeplot(self, mult): """Get data for each ridgeplot for the variable.""" xvals, yvals, pdfs, colors = [], [], [], [] for y, *_, values, color in self.iterator(): yvals.append(y) colors.append(color) values = values.flatten() density, lower, u...
Get effective n data for the variable.
def ess(self): """Get effective n data for the variable.""" _, y_vals, values, colors = self.labels_ticks_and_vals() for y, value, color in zip(y_vals, values, colors): if value.ndim != 2 or value.shape[0] < 2: yield y, None, color else: yi...
Get rhat data for the variable.
def r_hat(self): """Get rhat data for the variable.""" _, y_vals, values, colors = self.labels_ticks_and_vals() for y, value, color in zip(y_vals, values, colors): if value.ndim != 2 or value.shape[0] < 2: yield y, None, color else: yield y...
Get max y value for the variable.
def y_max(self): """Get max y value for the variable.""" end_y = max(y for y, *_ in self.iterator()) if self.combined: end_y += self.group_offset return end_y + 2 * self.group_offset
Plot Pareto tail indices.
def plot_khat( khats, figsize=None, textsize=None, markersize=None, ax=None, hlines_kwargs=None, **kwargs ): """ Plot Pareto tail indices. Parameters ---------- khats : array Pareto tail indices. figsize : tuple Figure size. If None it will be defined automatically. text...
Generate KDE plots for continuous variables and histograms for discrete ones.
def plot_density( data, group="posterior", data_labels=None, var_names=None, credible_interval=0.94, point_estimate="mean", colors="cycle", outline=True, hpd_markers="", shade=0.0, bw=4.5, figsize=None, textsize=None, ): """Generate KDE plots for continuous variab...
Plot an individual dimension.
def _d_helper( vec, vname, color, bw, titlesize, xt_labelsize, linewidth, markersize, credible_interval, point_estimate, hpd_markers, outline, shade, ax, ): """Plot an individual dimension. Parameters ---------- vec : array 1D array from t...
1D or 2D KDE plot taking into account boundary conditions.
def plot_kde( values, values2=None, cumulative=False, rug=False, label=None, bw=4.5, quantiles=None, rotated=False, contour=True, fill_last=True, textsize=None, plot_kwargs=None, fill_kwargs=None, rug_kwargs=None, contour_kwargs=None, contourf_kwargs=None,...
Fast Fourier transform - based Gaussian kernel density estimate ( KDE ).
def _fast_kde(x, cumulative=False, bw=4.5, xmin=None, xmax=None): """Fast Fourier transform-based Gaussian kernel density estimate (KDE). The code was adapted from https://github.com/mfouesneau/faststats Parameters ---------- x : Numpy array or list cumulative : bool If true, estimate ...
2D fft - based Gaussian kernel density estimate ( KDE ).
def _fast_kde_2d(x, y, gridsize=(128, 128), circular=False): """ 2D fft-based Gaussian kernel density estimate (KDE). The code was adapted from https://github.com/mfouesneau/faststats Parameters ---------- x : Numpy array or list y : Numpy array or list gridsize : tuple Number ...
Handle var_names input across arviz.
def _var_names(var_names, data): """Handle var_names input across arviz. Parameters ---------- var_names: str, list, or None data : xarray.Dataset Posterior data in an xarray Returns ------- var_name: list or None """ if var_names is not None: if isinstance(var_...
Use numba s jit decorator if numba is installed.
def conditional_jit(function=None, **kwargs): # noqa: D202 """Use numba's jit decorator if numba is installed. Notes ----- If called without arguments then return wrapped function. @conditional_jit def my_func(): return else called with arguments @co...
Plot a scatter or hexbin matrix of the sampled parameters.
def plot_pair( data, var_names=None, coords=None, figsize=None, textsize=None, kind="scatter", gridsize="auto", contour=True, fill_last=True, divergences=False, colorbar=False, ax=None, divergences_kwargs=None, plot_kwargs=None, ): """ Plot a scatter or he...
Extract a module - level docstring
def extract_docstring(self): """ Extract a module-level docstring """ lines = open(self.filename).readlines() start_row = 0 if lines[0].startswith('#!'): lines.pop(0) start_row = 1 docstring = '' first_par = '' line_iter = lines.__...
Plot distribution as histogram or kernel density estimates.
def plot_dist( values, values2=None, color="C0", kind="auto", cumulative=False, label=None, rotated=False, rug=False, bw=4.5, quantiles=None, contour=True, fill_last=True, textsize=None, plot_kwargs=None, fill_kwargs=None, rug_kwargs=None, contour_kwar...
Add a histogram for the data to the axes.
def _histplot_op(values, values2, rotated, ax, hist_kwargs): """Add a histogram for the data to the axes.""" if values2 is not None: raise NotImplementedError("Insert hexbin plot here") bins = hist_kwargs.pop("bins") if bins is None: bins = get_bins(values) ax.hist(values, bins=bins...
Plot for posterior predictive checks.
def plot_ppc( data, kind="density", alpha=None, mean=True, figsize=None, textsize=None, data_pairs=None, var_names=None, coords=None, flatten=None, flatten_pp=None, num_pp_samples=None, random_seed=None, jitter=None, animated=False, animation_kwargs=None, ...
Save dataset as a netcdf file.
def to_netcdf(data, filename, *, group="posterior", coords=None, dims=None): """Save dataset as a netcdf file. WARNING: Only idempotent in case `data` is InferenceData Parameters ---------- data : InferenceData, or any object accepted by `convert_to_inference_data` Object to be saved f...
Save dataset as a netcdf file.
def save_data(data, filename, *, group="posterior", coords=None, dims=None): """Save dataset as a netcdf file. WARNING: Only idempotent in case `data` is InferenceData Parameters ---------- data : InferenceData, or any object accepted by `convert_to_inference_data` Object to be saved f...
Convert any array into a 2d numpy array.
def make_2d(ary): """Convert any array into a 2d numpy array. In case the array is already more than 2 dimensional, will ravel the dimensions after the first. """ dim_0, *_ = np.atleast_1d(ary).shape return ary.reshape(dim_0, -1, order="F")
Scale figure properties according to rows and cols.
def _scale_fig_size(figsize, textsize, rows=1, cols=1): """Scale figure properties according to rows and cols. Parameters ---------- figsize : float or None Size of figure in inches textsize : float or None fontsize rows : int Number of rows cols : int Number...
Automatically compute the number of bins for discrete variables.
def get_bins(values): """ Automatically compute the number of bins for discrete variables. Parameters ---------- values = numpy array values Returns ------- array with the bins Notes ----- Computes the width of the bins by taking the maximun of the Sturges and the ...
Make a grid for subplots.
def default_grid(n_items, max_cols=4, min_cols=3): # noqa: D202 """Make a grid for subplots. Tries to get as close to sqrt(n_items) x sqrt(n_items) as it can, but allows for custom logic Parameters ---------- n_items : int Number of panels required max_cols : int Maximum n...
Create figure and axes for grids with multiple plots.
def _create_axes_grid(length_plotters, rows, cols, **kwargs): """Create figure and axes for grids with multiple plots. Parameters ---------- n_items : int Number of panels required rows : int Number of rows cols : int Number of columns Returns ------- fig : ...
Consistent labelling for plots.
def make_label(var_name, selection, position="below"): """Consistent labelling for plots. Parameters ---------- var_name : str Name of the variable selection : dict[Any] -> Any Coordinates of the variable position : whether to position the coordinates' label "below" (default) or...
Remove duplicates from list while preserving order.
def purge_duplicates(list_in): """Remove duplicates from list while preserving order. Parameters ---------- list_in: Iterable Returns ------- list List of first occurences in order """ _list = [] for item in list_in: if item not in _list: _list.appen...
Convert xarray data to an iterator over vectors.
def xarray_var_iter(data, var_names=None, combined=False, skip_dims=None, reverse_selections=False): """Convert xarray data to an iterator over vectors. Iterates over each var_name and all of its coordinates, returning the 1d data. Parameters ---------- data : xarray.Dataset Posterior ...
Take xarray data and unpacks into variables and data into list and numpy array respectively.
def xarray_to_ndarray(data, *, var_names=None, combined=True): """Take xarray data and unpacks into variables and data into list and numpy array respectively. Assumes that chain and draw are in coordinates Parameters ---------- data: xarray.DataSet Data in an xarray from an InferenceData o...
Subselects xarray dataset object to provided coords. Raises exception if fails.
def get_coords(data, coords): """Subselects xarray dataset object to provided coords. Raises exception if fails. Raises ------ ValueError If coords name are not available in data KeyError If coords dims are not available in data Returns ------- data: xarray xar...
r Convert a supported object to an InferenceData object.
def convert_to_inference_data(obj, *, group="posterior", coords=None, dims=None, **kwargs): r"""Convert a supported object to an InferenceData object. This function sends `obj` to the right conversion function. It is idempotent, in that it will return arviz.InferenceData objects unchanged. Parameters ...
Convert a supported object to an xarray dataset.
def convert_to_dataset(obj, *, group="posterior", coords=None, dims=None): """Convert a supported object to an xarray dataset. This function is idempotent, in that it will return xarray.Dataset functions unchanged. Raises `ValueError` if the desired group can not be extracted. Note this goes through a...
Use Sturges formula to determine number of bins.
def _sturges_formula(dataset, mult=1): """Use Sturges' formula to determine number of bins. See https://en.wikipedia.org/wiki/Histogram#Sturges'_formula or https://doi.org/10.1080%2F01621459.1926.10502161 Parameters ---------- dataset: xarray.DataSet Must have the `draw` dimension ...
Plot rank order statistics of chains.
def plot_rank(data, var_names=None, coords=None, bins=None, ref_line=True, figsize=None, axes=None): """Plot rank order statistics of chains. From the paper: Rank plots are histograms of the ranked posterior draws (ranked over all chains) plotted separately for each chain. If all of the chains are targ...
Creates ExpandedTextAds that use ad customizations for specified AdGroups.
def CreateAdsWithCustomizations(client, adgroup_ids, feed_name): """Creates ExpandedTextAds that use ad customizations for specified AdGroups. Args: client: an AdWordsClient instance. adgroup_ids: a list containing the AdGroup ids to add ExpandedTextAds to. feed_name: the name of the feed used to apply...
Creates a new AdCustomizerFeed.
def CreateCustomizerFeed(client, feed_name): """Creates a new AdCustomizerFeed. Args: client: an AdWordsClient instance. feed_name: the name for the new AdCustomizerFeed. Returns: The new AdCustomizerFeed. """ # Get the AdCustomizerFeedService ad_customizer_feed_service = client.GetService('Ad...
Restricts the feed item to an ad group.
def RestrictFeedItemToAdGroup(client, feed_item, adgroup_id): """Restricts the feed item to an ad group. Args: client: an AdWordsClient instance. feed_item: The feed item. adgroup_id: The ad group ID. """ # Get the FeedItemTargetService feed_item_target_service = client.GetService( 'FeedIte...
Creates FeedItems for the specified AdGroups.
def CreateCustomizerFeedItems(client, adgroup_ids, ad_customizer_feed): """Creates FeedItems for the specified AdGroups. These FeedItems contain values to use in ad customizations for the AdGroups. Args: client: an AdWordsClient instance. adgroup_ids: a list containing two AdGroup Ids. ad_customizer...
Creates a FeedItemOperation.
def CreateFeedItemAddOperation(name, price, date, ad_customizer_feed): """Creates a FeedItemOperation. The generated FeedItemOperation will create a FeedItem with the specified values when sent to FeedItemService.mutate. Args: name: the value for the name attribute of the FeedItem. price: the value fo...
Creates an AdWordsClient with information stored in a yaml string.
def LoadFromString(cls, yaml_doc): """Creates an AdWordsClient with information stored in a yaml string. Args: yaml_doc: The yaml string containing the cached AdWords data. Returns: An AdWordsClient initialized with the values cached in the string. Raises: A GoogleAdsValueError if t...
Creates an AdWordsClient with information stored in a yaml file.
def LoadFromStorage(cls, path=None): """Creates an AdWordsClient with information stored in a yaml file. Args: [optional] path: The path string to the file containing cached AdWords data. Returns: An AdWordsClient initialized with the values cached in the file. Raises: A Googl...
Creates a service client for the given service.
def GetService(self, service_name, version=None, server=None): """Creates a service client for the given service. Args: service_name: A string identifying which AdWords service to create a service client for. [optional] version: A string identifying the AdWords version to connect to...
Returns a BatchJobHelper to work with the BatchJobService.
def GetBatchJobHelper(self, version=sorted(_SERVICE_MAP.keys())[-1], server=None): """Returns a BatchJobHelper to work with the BatchJobService. This is a convenience method. It is functionally identical to calling BatchJobHelper(adwords_client, version). Args: [optio...
Creates a downloader for AdWords reports.
def GetReportDownloader(self, version=sorted(_SERVICE_MAP.keys())[-1], server=None): """Creates a downloader for AdWords reports. This is a convenience method. It is functionally identical to calling ReportDownloader(adwords_client, version, server). Args: [optional] ...
Returns the SOAP headers required for request authorization.
def GetSOAPHeaders(self, create_method): """Returns the SOAP headers required for request authorization. Args: create_method: The SOAP library specific method used to instantiate SOAP objects. Returns: A SOAP object containing the headers. """ header = create_method(self._SOAP_HE...
Returns the HTTP headers required for request authorization.
def GetHTTPHeaders(self): """Returns the HTTP headers required for request authorization. Returns: A dictionary containing the required headers. """ http_headers = self._adwords_client.oauth2_client.CreateHttpHeader() if self.enable_compression: http_headers['accept-encoding'] = 'gzip' ...
Returns a dictionary of headers for a report download request.
def GetReportDownloadHeaders(self, **kwargs): """Returns a dictionary of headers for a report download request. Note that the given keyword arguments will override any settings configured from the googleads.yaml file. Args: **kwargs: Optional keyword arguments. Keyword Arguments: clie...
Pack the given object using AdWords - specific logic.
def Pack(cls, obj, version): """Pack the given object using AdWords-specific logic. Args: obj: an object to be packed for SOAP using AdWords-specific logic, if applicable. version: the version of the current API, e.g. 'v201809' Returns: The given object packed with AdWords-spec...
Loads an IncrementalUploadHelper from the given file - like object.
def Load(cls, file_input, client=None): """Loads an IncrementalUploadHelper from the given file-like object. Args: file_input: a file-like object containing a serialized IncrementalUploadHelper. client: an AdWordsClient instance. If not specified, an AdWordsClient will be instantiat...
Ensures that the URL used to upload operations is properly initialized.
def _InitializeURL(self, upload_url, current_content_length): """Ensures that the URL used to upload operations is properly initialized. Args: upload_url: a string url. current_content_length: an integer identifying the current content length of data uploaded to the Batch Job. Returns:...
Serialize the IncrementalUploadHelper and store in file - like object.
def Dump(self, output): """Serialize the IncrementalUploadHelper and store in file-like object. Args: output: a file-like object where the status of the IncrementalUploadHelper will be written. Raises: GoogleAdsError: If a YAMLError occurs while writing to the file. """ data = ...
Uploads operations to the given uploadUrl in incremental steps.
def UploadOperations(self, operations, is_last=False): """Uploads operations to the given uploadUrl in incremental steps. Note: Each list of operations is expected to contain operations of the same type, similar to how one would normally send operations in an AdWords API Service request. Args: ...
Extract fields used in the summary logs.
def _ExtractRequestSummaryFields(self, request, error=None): """Extract fields used in the summary logs. Args: request: a urllib2.Request instance configured to make the request. [optional] error: a urllib2.HttpError instance used to retrieve error details. Returns: A dict contain...
Creates a WHERE builder using a provided field.
def Where(self, field): """Creates a WHERE builder using a provided field. Args: field: the field to be added as an argument in the WHERE clause. Returns: The created WHERE builder. """ where_builder = _WhereBuilder(self, field) self.where_builders.append(where_builder) return ...
Sets the type of the WHERE clause as equal to.
def EqualTo(self, value): """Sets the type of the WHERE clause as "equal to". Args: value: The value to be used in the WHERE condition. Returns: The query builder that this WHERE builder links to. """ self._awql = self._CreateSingleValueCondition(value, '=') return self._query_buil...
Sets the type of the WHERE clause as not equal to.
def NotEqualTo(self, value): """Sets the type of the WHERE clause as "not equal to". Args: value: The value to be used in the WHERE condition. Returns: The query builder that this WHERE builder links to. """ self._awql = self._CreateSingleValueCondition(value, '!=') return self._qu...
Sets the type of the WHERE clause as greater than.
def GreaterThan(self, value): """Sets the type of the WHERE clause as "greater than". Args: value: The value to be used in the WHERE condition. Returns: The query builder that this WHERE builder links to. """ self._awql = self._CreateSingleValueCondition(value, '>') return self._qu...
Sets the type of the WHERE clause as greater than or equal to.
def GreaterThanOrEqualTo(self, value): """Sets the type of the WHERE clause as "greater than or equal to". Args: value: The value to be used in the WHERE condition. Returns: The query builder that this WHERE builder links to. """ self._awql = self._CreateSingleValueCondition(value, '>=...
Sets the type of the WHERE clause as less than.
def LessThan(self, value): """Sets the type of the WHERE clause as "less than". Args: value: The value to be used in the WHERE condition. Returns: The query builder that this WHERE builder links to. """ self._awql = self._CreateSingleValueCondition(value, '<') return self._query_bu...
Sets the type of the WHERE clause as less than or equal to.
def LessThanOrEqualTo(self, value): """Sets the type of the WHERE clause as "less than or equal to. Args: value: The value to be used in the WHERE condition. Returns: The query builder that this WHERE builder links to. """ self._awql = self._CreateSingleValueCondition(value, '<=') ...
Sets the type of the WHERE clause as starts with.
def StartsWith(self, value): """Sets the type of the WHERE clause as "starts with". Args: value: The value to be used in the WHERE condition. Returns: The query builder that this WHERE builder links to. """ self._awql = self._CreateSingleValueCondition(value, 'STARTS_WITH') return ...
Sets the type of the WHERE clause as starts with ignore case.
def StartsWithIgnoreCase(self, value): """Sets the type of the WHERE clause as "starts with ignore case". Args: value: The value to be used in the WHERE condition. Returns: The query builder that this WHERE builder links to. """ self._awql = self._CreateSingleValueCondition(value, ...
Sets the type of the WHERE clause as contains.
def Contains(self, value): """Sets the type of the WHERE clause as "contains". Args: value: The value to be used in the WHERE condition. Returns: The query builder that this WHERE builder links to. """ self._awql = self._CreateSingleValueCondition(value, 'CONTAINS') return self._qu...
Sets the type of the WHERE clause as contains ignore case.
def ContainsIgnoreCase(self, value): """Sets the type of the WHERE clause as "contains ignore case". Args: value: The value to be used in the WHERE condition. Returns: The query builder that this WHERE builder links to. """ self._awql = self._CreateSingleValueCondition(value, 'CONTAINS...
Sets the type of the WHERE clause as does not contain.
def DoesNotContain(self, value): """Sets the type of the WHERE clause as "does not contain". Args: value: The value to be used in the WHERE condition. Returns: The query builder that this WHERE builder links to. """ self._awql = self._CreateSingleValueCondition(value, 'DOES_NOT_CONTAIN...
Sets the type of the WHERE clause as doesn not contain ignore case.
def DoesNotContainIgnoreCase(self, value): """Sets the type of the WHERE clause as "doesn not contain ignore case". Args: value: The value to be used in the WHERE condition. Returns: The query builder that this WHERE builder links to. """ self._awql = self._CreateSingleValueCondition( ...
Sets the type of the WHERE clause as in.
def In(self, *values): """Sets the type of the WHERE clause as "in". Args: *values: The values to be used in the WHERE condition. Returns: The query builder that this WHERE builder links to. """ self._awql = self._CreateMultipleValuesCondition(values, 'IN') return self._query_build...
Sets the type of the WHERE clause as in.
def NotIn(self, *values): """Sets the type of the WHERE clause as "in". Args: *values: The values to be used in the WHERE condition. Returns: The query builder that this WHERE builder links to. """ self._awql = self._CreateMultipleValuesCondition(values, 'NOT_IN') return self._quer...
Sets the type of the WHERE clause as contains any.
def ContainsAny(self, *values): """Sets the type of the WHERE clause as "contains any". Args: *values: The values to be used in the WHERE condition. Returns: The query builder that this WHERE builder links to. """ self._awql = self._CreateMultipleValuesCondition(values, 'CONTAINS_ANY')...
Sets the type of the WHERE clause as contains none.
def ContainsNone(self, *values): """Sets the type of the WHERE clause as "contains none". Args: *values: The values to be used in the WHERE condition. Returns: The query builder that this WHERE builder links to. """ self._awql = self._CreateMultipleValuesCondition(values, 'CONTAINS_NON...
Sets the type of the WHERE clause as contains all.
def ContainsAll(self, *values): """Sets the type of the WHERE clause as "contains all". Args: *values: The values to be used in the WHERE condition. Returns: The query builder that this WHERE builder links to. """ self._awql = self._CreateMultipleValuesCondition(values, 'CONTAINS_ALL')...
Creates a single - value condition with the provided value and operator.
def _CreateSingleValueCondition(self, value, operator): """Creates a single-value condition with the provided value and operator.""" if isinstance(value, str) or isinstance(value, unicode): value = '"%s"' % value return '%s %s %s' % (self._field, operator, value)
Creates a condition with the provided list of values and operator.
def _CreateMultipleValuesCondition(self, values, operator): """Creates a condition with the provided list of values and operator.""" values = ['"%s"' % value if isinstance(value, str) or isinstance(value, unicode) else str(value) for value in values] return '%s %s [%s]' % (self._field, operato...
Sets the LIMIT clause of the AWQL to the next page.
def NextPage(self, page=None): """Sets the LIMIT clause of the AWQL to the next page. This method is meant to be used with HasNext(). When using DataService, page is needed, as its paging mechanism is different from other services. For details, see https://developers.google.com/adwords/api/docs/gui...
Checks if there is still a page left to query.
def HasNext(self, page): """Checks if there is still a page left to query. This method is meant to be used with NextPage(). When using DataService, the paging mechanism is different from other services. For details, see https://developers.google.com/adwords/api/docs/guides/bid-landscapes#paging_through...
A page generator for this service query and the provided service.
def Pager(self, service): """A page generator for this service query and the provided service. This generates a page as a result from using the provided service's query() method until there are no more results to fetch. Args: service: The service object for making a query using this service quer...
Initialize application user.
def InitUser(): """Initialize application user. Retrieve existing user credentials from datastore or add new user. Returns: AppUser instance of the application user. """ result = AppUser.query(AppUser.user == users.get_current_user()).fetch() if result: app_user = result[0] else: app_user =...
Update the credentials associated with application user.
def UpdateUserCredentials(client_id, client_secret, refresh_token, adwords_manager_cid, developer_token): """Update the credentials associated with application user. Args: client_id: str Client Id retrieved from the developer's console. client_secret: str Client Secret retrieved f...
Creates a default partition.
def CreateDefaultPartition(client, ad_group_id): """Creates a default partition. Args: client: an AdWordsClient instance. ad_group_id: an integer ID for an ad group. """ ad_group_criterion_service = client.GetService('AdGroupCriterionService', version='v...
Sanitizes a field value from a Value object to a CSV suitable format.
def ConvertValueForCsv(pql_value): """Sanitizes a field value from a Value object to a CSV suitable format. Args: pql_value: dict a dictionary containing the data for a single field of an entity. Returns: str a CSV writer friendly value formatted by Value.Type. """ if 'value' in pql...
Converts the PQL formatted response for a dateTime object.
def ConvertDateTimeToOffset(date_time_value): """Converts the PQL formatted response for a dateTime object. Output conforms to ISO 8061 format, e.g. 'YYYY-MM-DDTHH:MM:SSz.' Args: date_time_value: dict The date time value from the PQL response. Returns: str: A string representation of the date time va...
Creates a user identifier from the specified type and value.
def _CreateUserIdentifier(identifier_type=None, value=None): """Creates a user identifier from the specified type and value. Args: identifier_type: a str specifying the type of user identifier. value: a str value of the identifier; to be hashed using SHA-256 if needed. Returns: A dict specifying a u...
Retrieve the index of a given field in the api_error s fieldPathElements.
def _GetFieldPathElementIndex(api_error, field): """Retrieve the index of a given field in the api_error's fieldPathElements. Args: api_error: a dict containing a partialFailureError returned from the AdWords API. field: a str field for which this determines the index in the api_error's fieldPa...
Handle post request.
def post(self): """Handle post request.""" client_customer_id = self.request.get('clientCustomerId') budget_id = self.request.get('budgetId') if not client_customer_id or not budget_id: self.redirect('/') else: self.redirect('/showBudget?clientCustomerId=%s&budgetId=%s' ...
Appends a Monkey Patch to the suds. mx. appender module.
def _ApplySudsJurkoAppenderPatch(self): """Appends a Monkey Patch to the suds.mx.appender module. This resolves an issue where empty objects are ignored and stripped from the request output. More details can be found on the suds-jurko issue tracker: https://goo.gl/uyYw0C """ def PatchedAppend(s...
Appends a Monkey Patch to the suds. transport. http module.
def _ApplySudsJurkoSendPatch(self): """Appends a Monkey Patch to the suds.transport.http module. This allows the suds library to decompress the SOAP body when compression is enabled. For more details on SOAP Compression, see: https://developers.google.com/adwords/api/docs/guides/bestpractices?hl=en#use...
Overrides the ingress function for response logging.
def ingress(self, envelope, http_headers, operation): """Overrides the ingress function for response logging. Args: envelope: An Element with the SOAP request data. http_headers: A dict of the current http headers. operation: The SoapOperation instance. Returns: A tuple of the enve...
Overrides the egress function ror request logging.
def egress(self, envelope, http_headers, operation, binding_options): """Overrides the egress function ror request logging. Args: envelope: An Element with the SOAP request data. http_headers: A dict of the current http headers. operation: The SoapOperation instance. binding_options: An...
Restrict a feed item to a geo target location.
def RestrictFeedItemToGeoTarget(client, feed_item, location_id): """Restrict a feed item to a geo target location. Args: client: An AdWordsClient instance. feed_item: A FeedItem. location_id: The Id of the location to restrict to. """ # Retrieve the FeedItemTargetService feed_item_target_service ...
Adds a new Smart Shopping campaign.
def CreateSmartCampaign(client, budget_id, merchant_id): """Adds a new Smart Shopping campaign. Args: client: an AdWordsClient instance. budget_id: the str ID of the budget to be associated with the Shopping campaign. merchant_id: the str ID of the merchant account to be associated with the ...
Adds a new Smart Shopping ad group.
def CreateSmartShoppingAdGroup(client, campaign_id): """Adds a new Smart Shopping ad group. Args: client: an AdWordsClient instance. campaign_id: the str ID of a Smart Shopping campaign. Returns: An ad group ID. """ ad_group_service = client.GetService('AdGroupService', version='v201809') # Cre...
Adds a new Smart Shopping ad.
def CreateSmartShoppingAd(client, ad_group_id): """Adds a new Smart Shopping ad. Args: client: an AdWordsClient instance. ad_group_id: an integer ID for an ad group. """ ad_group_ad_service = client.GetService('AdGroupAdService', version='v201809') # Create an AdGroup Ad. adgroup_ad = { 'adGr...