INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
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. Parameters ---------- khats : array Pareto tail indices. figsize : tuple Figure size. If None it will be defined automatically. textsize: float Text size scaling factor for labels, titles and lines. If None it will be autoscaled based on fig...
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. Plots are truncated at their 100*(1-alpha)% credible intervals. Plots are grouped per variable and colors assigned to models. Parameters ---------- data : Union[Object, Iterator[Object]] Any object that can be co...
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. Parameters ---------- vec : array 1D array from trace vname : str variable name color : str matplotlib color bw : float Bandwidth scaling factor. Should be larger than 0. The higher this number the smoother the KDE will be. D...
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. Parameters ---------- values : array-like Values to plot values2 : array-like, optional Values to plot. If present, a 2D KDE will be estimated cumulative : bool If true plot the estimated cumulative distribution func...
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). The code was adapted from https://github.com/mfouesneau/faststats Parameters ---------- x : Numpy array or list cumulative : bool If true, estimate the cdf instead of the pdf bw : float Bandwidth scaling facto...
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). The code was adapted from https://github.com/mfouesneau/faststats Parameters ---------- x : Numpy array or list y : Numpy array or list gridsize : tuple Number of points used to discretize data. Use powers of 2 for fft optimization ...
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. Parameters ---------- var_names: str, list, or None data : xarray.Dataset Posterior data in an xarray Returns ------- var_name: list or None
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. Notes ----- If called without arguments then return wrapped function. @conditional_jit def my_func(): return else called with arguments @conditional_jit(nopython=True) def my_func(): ret...
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. Parameters ---------- data : obj Any object that can be converted to an az.InferenceData object Refer to documentation of az.convert_to_dataset for details var_names : list of variable names Variables to be plotted, if N...
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. By default continuous variables are plotted using KDEs and discrete ones using histograms Parameters ---------- values : array-like Values to plot values2 : array-like, optional Values to plot. If present, a 2D KDE or a he...
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. Parameters ---------- data : az.InferenceData object InferenceData object containing the observed and posterior predictive data. kind : str Type of plot to display (density, cumulative, or scatter). Defaults to density. alpha : float ...
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. WARNING: Only idempotent in case `data` is InferenceData Parameters ---------- data : InferenceData, or any object accepted by `convert_to_inference_data` Object to be saved filename : str name or path of the file to load trace group : str (option...
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. WARNING: Only idempotent in case `data` is InferenceData Parameters ---------- data : InferenceData, or any object accepted by `convert_to_inference_data` Object to be saved filename : str name or path of the file to load trace group : str (option...
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. In case the array is already more than 2 dimensional, will ravel the dimensions after the first.
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. Parameters ---------- figsize : float or None Size of figure in inches textsize : float or None fontsize rows : int Number of rows cols : int Number of columns Returns ------- figsize : float or Non...
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. 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 Freedman-Diaconis estimators. ...
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. 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 number of columns, inclusive min_cols : int Minimum number of...
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. Parameters ---------- n_items : int Number of panels required rows : int Number of rows cols : int Number of columns Returns ------- fig : matplotlib figure ax : matplotlib axes
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. 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 "beside" the name of the variable Returns...
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. Parameters ---------- list_in: Iterable Returns ------- list List of first occurences in 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. Iterates over each var_name and all of its coordinates, returning the 1d data. Parameters ---------- data : xarray.Dataset Posterior data in an xarray var_names : iterator of strings (optional) Should be a subset of data.data_va...
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. Assumes that chain and draw are in coordinates Parameters ---------- data: xarray.DataSet Data in an xarray from an InferenceData object. Examples include posterior or sample_stats var_names: iter...
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. Raises ------ ValueError If coords name are not available in data KeyError If coords dims are not available in data Returns ------- data: xarray xarray.Dataset object
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. This function sends `obj` to the right conversion function. It is idempotent, in that it will return arviz.InferenceData objects unchanged. Parameters ---------- obj : dict, str, np.ndarray, xr.Dataset, pystan fit, pymc3 trace A su...
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. 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 DataInference object. See `convert_to_inference_data` for more details. Raise...
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. 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 mult: float Used to scale the number ...
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. 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 targeting the same posterior, we expect the ranks in each chain to be uniform, whereas if one chain has a ...
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. 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 customizations. Raises: GoogleAdsError: if no ExpandedTextAds ...
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. Args: client: an AdWordsClient instance. feed_name: the name for the new AdCustomizerFeed. Returns: The 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. Args: client: an AdWordsClient instance. feed_item: The feed item. adgroup_id: The ad group ID.
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. 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_feed: the AdCustomizerFeed we're associating the FeedItems with. ...
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. 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 for the price attribute of the FeedItem. date: the value for the date attr...
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. 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 the given yaml string does not contain the ...
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. 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 GoogleAdsValueError if the given yaml file does n...
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. 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. This defaults to what is currently the latest version. Thi...
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. This is a convenience method. It is functionally identical to calling BatchJobHelper(adwords_client, version). Args: [optional] version: A string identifying the AdWords version to connect to. This defaults to what is cur...
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. This is a convenience method. It is functionally identical to calling ReportDownloader(adwords_client, version, server). Args: [optional] version: A string identifying the AdWords version to connect to. This defaults to what is currently the ...
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. Args: create_method: The SOAP library specific method used to instantiate SOAP objects. Returns: A SOAP object containing the headers.
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. Returns: A dictionary containing the required headers.
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. Note that the given keyword arguments will override any settings configured from the googleads.yaml file. Args: **kwargs: Optional keyword arguments. Keyword Arguments: client_customer_id: A string containing a client_customer...
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. 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-specific logic for SOAP, if applic...
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. Args: file_input: a file-like object containing a serialized IncrementalUploadHelper. client: an AdWordsClient instance. If not specified, an AdWordsClient will be instantiated using the default configuration file. R...
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. Args: upload_url: a string url. current_content_length: an integer identifying the current content length of data uploaded to the Batch Job. Returns: An initialized string URL, or the provided string URL if the U...
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. 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.
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. 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: operations: one or more lists of operations as would be sen...
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. 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 containing the fields to be output 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. Args: field: the field to be added as an argument in the WHERE clause. Returns: The created WHERE builder.
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 "not equal to". Args: value: The value to be used in the WHERE condition. Returns: The query builder that this WHERE builder links 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 "equal to". Args: value: The value to be used in the WHERE condition. Returns: The query builder that this WHERE builder links 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 "greater than". Args: value: The value to be used in the WHERE condition. Returns: The query builder that this WHERE builder links to.
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". Args: value: The value to be used in the WHERE condition. Returns: The query builder that this WHERE builder links 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". Args: value: The value to be used in the WHERE condition. Returns: The query builder that this WHERE builder links to.
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. Args: value: The value to be used in the WHERE condition. Returns: The query builder that this WHERE builder links 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". Args: value: The value to be used in the WHERE condition. Returns: The query builder that this WHERE builder links to.
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". Args: value: The value to be used in the WHERE condition. Returns: The query builder that this WHERE builder links to.
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". Args: value: The value to be used in the WHERE condition. Returns: The query builder that this WHERE builder links to.
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". Args: value: The value to be used in the WHERE condition. Returns: The query builder that this WHERE builder links to.
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". Args: value: The value to be used in the WHERE condition. Returns: The query builder that this WHERE builder links to.
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". Args: value: The value to be used in the WHERE condition. Returns: The query builder that this WHERE builder links to.
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". Args: *values: The values to be used in the WHERE condition. Returns: The query builder that this WHERE builder links to.
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". Args: *values: The values to be used in the WHERE condition. Returns: The query builder that this WHERE builder links to.
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". Args: *values: The values to be used in the WHERE condition. Returns: The query builder that this WHERE builder links to.
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". Args: *values: The values to be used in the WHERE condition. Returns: The query builder that this WHERE builder links to.
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". Args: *values: The values to be used in the WHERE condition. Returns: The query builder that this WHERE builder links to.
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...
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_results. Args: page:...
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...
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/guides/bid-landscapes#paging_through_resu...
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...
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 query. Yields: A resulting...
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. Retrieve existing user credentials from datastore or add new user. Returns: AppUser instance of the 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. Args: client_id: str Client Id retrieved from the developer's console. client_secret: str Client Secret retrieved from the developer's console. refresh_token: str Refresh token generated with the above client id/secret. adwords_manager_cid: str...
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. Args: client: an AdWordsClient instance. ad_group_id: an integer ID for an ad group.
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. 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.
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. 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 value uniform to ReportService.
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. 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 user identifier, with a value hashed using SHA-256 if needed.
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. 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 fieldPathElements. Returns: An int index of the field ...
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. 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 _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. 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_compression
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. 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 envelope and headers.
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. 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 options dict for the SOAP binding. Returns: A tuple of the envelo...
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. Args: client: An AdWordsClient instance. feed_item: A FeedItem. location_id: The Id of the location to restrict to.
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. 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 Shopping campaign. Returns: A campaign ID.
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. Args: client: an AdWordsClient instance. campaign_id: the str ID of a Smart Shopping campaign. Returns: An ad group ID.
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. Args: client: an AdWordsClient instance. ad_group_id: an integer ID for an ad group.
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...
A simple convenience utility for adding months to a given start date. This increments the months by adding the number of days in the current month to the current month, for each month. Args: start_date: date The date months are being added to. months: int The number of months to add. Returns: A d...
def AddMonths(start_date, months): """A simple convenience utility for adding months to a given start date. This increments the months by adding the number of days in the current month to the current month, for each month. Args: start_date: date The date months are being added to. months: int The numb...
Displays mean average cpc, position, clicks, and total cost for estimate. Args: message: str message to display for the given estimate. min_estimate: sudsobject containing a minimum estimate from the TrafficEstimatorService response. max_estimate: sudsobject containing a maximum estimate from the ...
def DisplayEstimate(message, min_estimate, max_estimate): """Displays mean average cpc, position, clicks, and total cost for estimate. Args: message: str message to display for the given estimate. min_estimate: sudsobject containing a minimum estimate from the TrafficEstimatorService response. ma...
Builds a client config dictionary used in the OAuth 2.0 flow.
def Build(self): """Builds a client config dictionary used in the OAuth 2.0 flow.""" if all((self.client_type, self.client_id, self.client_secret, self.auth_uri, self.token_uri)): client_config = { self.client_type: { 'client_id': self.client_id, 'client_s...
Format a SOAP DateTime object for printing. Args: value: The DateTime object to format. Returns: A string representing the value.
def FormatSOAPDateTime(value): """Format a SOAP DateTime object for printing. Args: value: The DateTime object to format. Returns: A string representing the value. """ value_date = value['date'] return '%s-%s-%s %s:%s:%s (%s)' % ( value_date['year'], value_date['month'], value_date['day'], ...
Calculate forecast percentage stats. Args: matched: The number of matched impressions. available: The number of available impressions. possible: The optional number of possible impressions. Returns: The percentage of impressions that are available and possible.
def CalculateForecastStats(matched, available, possible=None): """Calculate forecast percentage stats. Args: matched: The number of matched impressions. available: The number of available impressions. possible: The optional number of possible impressions. Returns: The percentage of impressions t...
Creates a shopping campaign with the given budget and merchant IDs. 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 shopping campaign. Returns...
def CreateShoppingCampaign(client, budget_id, merchant_id): """Creates a shopping campaign with the given budget and merchant IDs. 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 acco...
Creates an AdGroup for the given shopping campaign ID. Args: client: an AdWordsClient instance. campaign_id: the str ID of a shopping campaign. Returns: The created AdGroup as a sudsobject.
def CreateAdGroup(client, campaign_id): """Creates an AdGroup for the given shopping campaign ID. Args: client: an AdWordsClient instance. campaign_id: the str ID of a shopping campaign. Returns: The created AdGroup as a sudsobject. """ ad_group_service = client.GetService('AdGroupService', 'v20...
Creates a showcase add for the given AdGroup with the given images. Args: client: an AdWordsClient instance. adgroup: a dict or suds object defining an AdGroup for a Shopping Campaign. expanded_image_filepath: a str filepath to a .jpg file that will be used as the Showcase Ad's expandedImage. c...
def CreateShowcaseAd(client, adgroup, expanded_image_filepath, collapsed_image_filepath): """Creates a showcase add for the given AdGroup with the given images. Args: client: an AdWordsClient instance. adgroup: a dict or suds object defining an AdGroup for a Shopping Campaign. expa...
Uploads a .jpg image with the given filepath via the AdWords MediaService. Args: client: an AdWordsClient instance. filepath: a str filepath to the .jpg file to be uploaded. Returns: The created Image as a sudsobject.
def UploadImage(client, filepath): """Uploads a .jpg image with the given filepath via the AdWords MediaService. Args: client: an AdWordsClient instance. filepath: a str filepath to the .jpg file to be uploaded. Returns: The created Image as a sudsobject. """ media_service = client.GetService('M...
Creates a ProductPartition tree for the given AdGroup ID. Args: client: an AdWordsClient instance. adgroup_id: a str AdGroup ID. Returns: The ProductPartition tree as a sudsobject.
def CreateProductPartition(client, adgroup_id): """Creates a ProductPartition tree for the given AdGroup ID. Args: client: an AdWordsClient instance. adgroup_id: a str AdGroup ID. Returns: The ProductPartition tree as a sudsobject. """ ad_group_criterion_service = client.GetService('AdGroupCrite...