sentence1 stringlengths 52 3.87M | sentence2 stringlengths 1 47.2k | label stringclasses 1
value |
|---|---|---|
def get_expanded_schema(self, schema_name):
"""
Return a schema file with all $ref properties expanded
"""
if schema_name not in self.expanded_schemas:
fn = self.get_schema_file(schema_name)
schemas_folder = self.get_schemas_folder()
base_uri = self.ge... | Return a schema file with all $ref properties expanded | entailment |
def output(s):
"""
Parse, transform, and pretty print
the result
"""
p = Parser()
t = ExpressionsTransformer()
ast = p.parse(s)
logging.debug(ast.pretty())
print(ast.pretty())
d = t.transform(ast)
print(json.dumps(d, indent=4))
return d | Parse, transform, and pretty print
the result | entailment |
def comparison(self, t):
"""
<PropertyIsEqualTo>
<PropertyName>NAME</PropertyName>
<Literal>Sydney</Literal>
</PropertyIsEqualTo>
"""
assert(len(t) == 3)
d = {"PropertyIsEqualTo": [
t[0], t[1], t[2]
]}
#parts = [str(p.value) for p in t]
... | <PropertyIsEqualTo>
<PropertyName>NAME</PropertyName>
<Literal>Sydney</Literal>
</PropertyIsEqualTo> | entailment |
def main(ctx, verbose, quiet):
"""
Execute the main mappyfile command
"""
verbosity = verbose - quiet
configure_logging(verbosity)
ctx.obj = {}
ctx.obj['verbosity'] = verbosity | Execute the main mappyfile command | entailment |
def format(ctx, input_mapfile, output_mapfile, indent, spacer, quote, newlinechar, expand, comments):
"""
Format a the input-mapfile and save as output-mapfile. Note output-mapfile will be
overwritten if it already exists.
Example of formatting a single Mapfile:
mappyfile format C:/Temp/valid.... | Format a the input-mapfile and save as output-mapfile. Note output-mapfile will be
overwritten if it already exists.
Example of formatting a single Mapfile:
mappyfile format C:/Temp/valid.map C:/Temp/valid_formatted.map
Example of formatting a single Mapfile with single quotes and tabs for indent... | entailment |
def validate(ctx, mapfiles, expand):
"""
Validate Mapfile(s) against the Mapfile schema
The MAPFILES argument is a list of paths, either to individual Mapfiles, or a folders containing Mapfiles.
Wildcards are supported (natively on Linux, and up to one level deep on Windows).
Validation errors are ... | Validate Mapfile(s) against the Mapfile schema
The MAPFILES argument is a list of paths, either to individual Mapfiles, or a folders containing Mapfiles.
Wildcards are supported (natively on Linux, and up to one level deep on Windows).
Validation errors are reported to the console. The program returns the ... | entailment |
def get_keyword(text):
"""
Accept a string such as BACKGROUNDCOLOR [r] [g] [b]
and return backgroundcolor
"""
first_word = text.split(" ")[0]
if len(first_word) > 1 and first_word.isupper():
kwd = str(first_word.lower())
else:
kwd = None
return kwd | Accept a string such as BACKGROUNDCOLOR [r] [g] [b]
and return backgroundcolor | entailment |
def get_values(text):
"""
Accept a string such as BACKGROUNDCOLOR [r] [g] [b]
and return ['r', 'g', 'b']
"""
res = re.findall(r"\[(.*?)\]", text)
values = []
for r in res:
if "|" in r:
params = r.split("|")
for p in params:
values.append(p)
... | Accept a string such as BACKGROUNDCOLOR [r] [g] [b]
and return ['r', 'g', 'b'] | entailment |
def process_doc(text):
"""
The :ref: role is supported by Sphinx but not by plain docutils
"""
# remove :ref: directives
document = docutils.core.publish_doctree(text) # http://epydoc.sourceforge.net/docutils/private/docutils.nodes.document-class.html
visitor = RefVisitor(document)
document.... | The :ref: role is supported by Sphinx but not by plain docutils | entailment |
def open(fn, expand_includes=True, include_comments=False, include_position=False, **kwargs):
"""
Load a Mapfile from the supplied filename into a Python dictionary.
Parameters
----------
fn: string
The path to the Mapfile, or partial Mapfile
expand_includes: boolean
Load any `... | Load a Mapfile from the supplied filename into a Python dictionary.
Parameters
----------
fn: string
The path to the Mapfile, or partial Mapfile
expand_includes: boolean
Load any ``INCLUDE`` files in the MapFile
include_comments: boolean
Include or discard comment strings ... | entailment |
def load(fp, expand_includes=True, include_position=False, include_comments=False, **kwargs):
"""
Load a Mapfile from an open file or file-like object.
Parameters
----------
fp: file
A file-like object - as with all Mapfiles this should be encoded in "utf-8"
expand_includes: boolean
... | Load a Mapfile from an open file or file-like object.
Parameters
----------
fp: file
A file-like object - as with all Mapfiles this should be encoded in "utf-8"
expand_includes: boolean
Load any ``INCLUDE`` files in the MapFile
include_comments: boolean
Include or discard ... | entailment |
def loads(s, expand_includes=True, include_position=False, include_comments=False, **kwargs):
"""
Load a Mapfile from a string
Parameters
----------
s: string
The Mapfile, or partial Mapfile, text
expand_includes: boolean
Load any ``INCLUDE`` files in the MapFile
include_co... | Load a Mapfile from a string
Parameters
----------
s: string
The Mapfile, or partial Mapfile, text
expand_includes: boolean
Load any ``INCLUDE`` files in the MapFile
include_comments: boolean
Include or discard comment strings from the Mapfile - *experimental*
include_... | entailment |
def dump(d, fp, indent=4, spacer=" ", quote='"', newlinechar="\n", end_comment=False):
"""
Write d (the Mapfile dictionary) as a formatted stream to fp
Parameters
----------
d: dict
A Python dictionary based on the the mappyfile schema
fp: file
A file-like object
indent: in... | Write d (the Mapfile dictionary) as a formatted stream to fp
Parameters
----------
d: dict
A Python dictionary based on the the mappyfile schema
fp: file
A file-like object
indent: int
The number of ``spacer`` characters to indent structures in the Mapfile
spacer: strin... | entailment |
def save(d, output_file, indent=4, spacer=" ", quote='"', newlinechar="\n", end_comment=False, **kwargs):
"""
Write a dictionary to an output Mapfile on disk
Parameters
----------
d: dict
A Python dictionary based on the the mappyfile schema
output_file: string
The output filen... | Write a dictionary to an output Mapfile on disk
Parameters
----------
d: dict
A Python dictionary based on the the mappyfile schema
output_file: string
The output filename
indent: int
The number of ``spacer`` characters to indent structures in the Mapfile
spacer: string... | entailment |
def dumps(d, indent=4, spacer=" ", quote='"', newlinechar="\n", end_comment=False, **kwargs):
"""
Output a Mapfile dictionary as a string
Parameters
----------
d: dict
A Python dictionary based on the the mappyfile schema
indent: int
The number of ``spacer`` characters to inden... | Output a Mapfile dictionary as a string
Parameters
----------
d: dict
A Python dictionary based on the the mappyfile schema
indent: int
The number of ``spacer`` characters to indent structures in the Mapfile
spacer: string
The character to use for indenting structures in th... | entailment |
def find(lst, key, value):
"""
Find an item in a list of dicts using a key and a value
Parameters
----------
list: list
A list of composite dictionaries e.g. ``layers``, ``classes``
key: string
The key name to search each dictionary in the list
key: value
The value ... | Find an item in a list of dicts using a key and a value
Parameters
----------
list: list
A list of composite dictionaries e.g. ``layers``, ``classes``
key: string
The key name to search each dictionary in the list
key: value
The value to search for
Returns
-------
... | entailment |
def findall(lst, key, value):
"""
Find all items in lst where key matches value.
For example find all ``LAYER`` s in a ``MAP`` where ``GROUP`` equals ``VALUE``
Parameters
----------
list: list
A list of composite dictionaries e.g. ``layers``, ``classes``
key: string
The key... | Find all items in lst where key matches value.
For example find all ``LAYER`` s in a ``MAP`` where ``GROUP`` equals ``VALUE``
Parameters
----------
list: list
A list of composite dictionaries e.g. ``layers``, ``classes``
key: string
The key name to search each dictionary in the lis... | entailment |
def findunique(lst, key):
"""
Find all unique key values for items in lst.
Parameters
----------
lst: list
A list of composite dictionaries e.g. ``layers``, ``classes``
key: string
The key name to search each dictionary in the list
Returns
-------
list
A ... | Find all unique key values for items in lst.
Parameters
----------
lst: list
A list of composite dictionaries e.g. ``layers``, ``classes``
key: string
The key name to search each dictionary in the list
Returns
-------
list
A sorted Python list of unique keys in t... | entailment |
def findkey(d, *keys):
"""
Get a value from a dictionary based on a list of keys and/or list indexes.
Parameters
----------
d: dict
A Python dictionary
keys: list
A list of key names, or list indexes
Returns
-------
dict
The composite dictionary object at ... | Get a value from a dictionary based on a list of keys and/or list indexes.
Parameters
----------
d: dict
A Python dictionary
keys: list
A list of key names, or list indexes
Returns
-------
dict
The composite dictionary object at the path specified by the keys
... | entailment |
def update(d1, d2):
"""
Update dict d1 with properties from d2
Note
----
Allows deletion of objects with a special ``__delete__`` key
For any list of dicts new items can be added when updating
Parameters
----------
d1: dict
A Python dictionary
d2: dict
A Pytho... | Update dict d1 with properties from d2
Note
----
Allows deletion of objects with a special ``__delete__`` key
For any list of dicts new items can be added when updating
Parameters
----------
d1: dict
A Python dictionary
d2: dict
A Python dictionary that will be used t... | entailment |
def erosion(mapfile, dilated):
"""
We will continue to work with the modified Mapfile
If we wanted to start from scratch we could simply reread it
"""
ll = mappyfile.find(mapfile["layers"], "name", "line")
ll["status"] = "OFF"
pl = mappyfile.find(mapfile["layers"], "name", "polygon")
#... | We will continue to work with the modified Mapfile
If we wanted to start from scratch we could simply reread it | entailment |
def _decode_response(response):
"""Strip off Gerrit's magic prefix and decode a response.
:returns:
Decoded JSON content as a dict, or raw text if content could not be
decoded as JSON.
:raises:
requests.HTTPError if the response contains an HTTP error status code.
"""
cont... | Strip off Gerrit's magic prefix and decode a response.
:returns:
Decoded JSON content as a dict, or raw text if content could not be
decoded as JSON.
:raises:
requests.HTTPError if the response contains an HTTP error status code. | entailment |
def translate_kwargs(self, **kwargs):
"""Translate kwargs replacing `data` with `json` if necessary."""
local_kwargs = self.kwargs.copy()
local_kwargs.update(kwargs)
if "data" in local_kwargs and "json" in local_kwargs:
raise ValueError("Cannot use data and json together")
... | Translate kwargs replacing `data` with `json` if necessary. | entailment |
def post(self, endpoint, return_response=False, **kwargs):
"""Send HTTP POST to the endpoint.
:arg str endpoint: The endpoint to send to.
:returns:
JSON decoded result.
:raises:
requests.RequestException on timeout or connection error.
"""
args... | Send HTTP POST to the endpoint.
:arg str endpoint: The endpoint to send to.
:returns:
JSON decoded result.
:raises:
requests.RequestException on timeout or connection error. | entailment |
def escape_string(string):
"""Escape a string for use in Gerrit commands.
:arg str string: The string to escape.
:returns: The string with necessary escapes and surrounding double quotes
so that it can be passed to any of the Gerrit commands that require
double-quoted strings.
"""
... | Escape a string for use in Gerrit commands.
:arg str string: The string to escape.
:returns: The string with necessary escapes and surrounding double quotes
so that it can be passed to any of the Gerrit commands that require
double-quoted strings. | entailment |
def append(self, data):
"""Append the given `data` to the output.
:arg data: If a list, it is formatted as a bullet list with each
entry in the list being a separate bullet. Otherwise if it is a
string, the string is added as a paragraph.
:raises: ValueError if `data` ... | Append the given `data` to the output.
:arg data: If a list, it is formatted as a bullet list with each
entry in the list being a separate bullet. Otherwise if it is a
string, the string is added as a paragraph.
:raises: ValueError if `data` is not a list or a string. | entailment |
def format(self):
"""Format the message parts to a string.
:Returns: A string of all the message parts separated into paragraphs,
with header and footer paragraphs if they were specified in the
constructor.
"""
message = ""
if self.paragraphs:
... | Format the message parts to a string.
:Returns: A string of all the message parts separated into paragraphs,
with header and footer paragraphs if they were specified in the
constructor. | entailment |
def set_context_params(self, params):
""" Set header context parameters. Refer to the top of <Zimbra
Server-Root>/docs/soap.txt about specifics.
The <format>-Parameter cannot be changed, because it is set by the
implementing class.
Should be called by implementing method to ch... | Set header context parameters. Refer to the top of <Zimbra
Server-Root>/docs/soap.txt about specifics.
The <format>-Parameter cannot be changed, because it is set by the
implementing class.
Should be called by implementing method to check for valid context
params.
:par... | entailment |
def enable_batch(self, onerror="continue"):
""" Enables batch request gathering.
Do this first and then consecutively call "add_request" to add more
requests.
:param onerror: "continue" (default) if one request fails (and
response with soap Faults for the request) or "stop" ... | Enables batch request gathering.
Do this first and then consecutively call "add_request" to add more
requests.
:param onerror: "continue" (default) if one request fails (and
response with soap Faults for the request) or "stop" processing. | entailment |
def is_fault(self):
""" Checks, wether this response has at least one fault response (
supports both batch and single responses)
"""
if self.is_batch():
info = self.get_batch()
return info['hasFault']
else:
my_response = self.get_response... | Checks, wether this response has at least one fault response (
supports both batch and single responses) | entailment |
def _filter_response(self, response_dict):
""" Add additional filters to the response dictionary
Currently the response dictionary is filtered like this:
* If a list only has one item, the list is replaced by that item
* Namespace-Keys (_jsns and xmlns) are removed
:param... | Add additional filters to the response dictionary
Currently the response dictionary is filtered like this:
* If a list only has one item, the list is replaced by that item
* Namespace-Keys (_jsns and xmlns) are removed
:param response_dict: the pregenerated, but unfiltered respons... | entailment |
def create_preauth(byval, key, by='name', expires=0, timestamp=None):
""" Generates a zimbra preauth value
:param byval: The value of the targeted user (according to the
by-parameter). For example: The account name, if "by" is "name".
:param key: The domain preauth key (you can retrieve that using z... | Generates a zimbra preauth value
:param byval: The value of the targeted user (according to the
by-parameter). For example: The account name, if "by" is "name".
:param key: The domain preauth key (you can retrieve that using zmprov gd)
:param by: What type is the byval-parameter? Valid parameters are... | entailment |
def zimbra_to_python(zimbra_dict, key_attribute="n",
content_attribute="_content"):
"""
Converts single level Zimbra dicts to a standard python dict
:param zimbra_dict: The dictionary in Zimbra-Format
:return: A native python dict
"""
local_dict = {}
for item in zimb... | Converts single level Zimbra dicts to a standard python dict
:param zimbra_dict: The dictionary in Zimbra-Format
:return: A native python dict | entailment |
def get_value(haystack, needle, key_attribute="n",
content_attribute="_content"):
""" Fetch a value from a zimbra-like json dict (keys are "n", values are
"_content"
This function may be slightly faster than zimbra_to_python(haystack)[
needle], because it doesn't necessarily iterate over... | Fetch a value from a zimbra-like json dict (keys are "n", values are
"_content"
This function may be slightly faster than zimbra_to_python(haystack)[
needle], because it doesn't necessarily iterate over the complete list.
:param haystack: The list in zimbra-dict format
:param needle: the key to se... | entailment |
def convert_to_str(input_string):
""" Returns a string of the input compatible between py2 and py3
:param input_string:
:return:
"""
if sys.version < '3':
if isinstance(input_string, str) \
or isinstance(input_string, unicode): # pragma: no cover py3
return i... | Returns a string of the input compatible between py2 and py3
:param input_string:
:return: | entailment |
def dict_to_dom(root_node, xml_dict):
""" Create a DOM node and optionally several subnodes from a dictionary.
:param root_node: DOM-Node set the dictionary is applied upon
:type root_node: xml.dom.Element
:param xml_dict: The dictionary containing the nodes to process
:type xml_dict: dict
"""
... | Create a DOM node and optionally several subnodes from a dictionary.
:param root_node: DOM-Node set the dictionary is applied upon
:type root_node: xml.dom.Element
:param xml_dict: The dictionary containing the nodes to process
:type xml_dict: dict | entailment |
def dom_to_dict(root_node):
""" Serializes the given node to the dictionary
Serializes the given node to the documented dictionary format.
:param root_node: Node to serialize
:returns: The dictionary
:rtype: dict
"""
# Remove namespaces from tagname
tag = root_node.tagName
if "... | Serializes the given node to the dictionary
Serializes the given node to the documented dictionary format.
:param root_node: Node to serialize
:returns: The dictionary
:rtype: dict | entailment |
def connect(self):
"""Overrides HTTPSConnection.connect to specify TLS version"""
# Standard implementation from HTTPSConnection, which is not
# designed for extension, unfortunately
sock = socket.create_connection((self.host, self.port),
self.time... | Overrides HTTPSConnection.connect to specify TLS version | entailment |
def gen_request(self, request_type="json", token=None, set_batch=False,
batch_onerror=None):
""" Convenience method to quickly generate a token
:param request_type: Type of request (defaults to json)
:param token: Authentication token
:param set_batch: Also set this... | Convenience method to quickly generate a token
:param request_type: Type of request (defaults to json)
:param token: Authentication token
:param set_batch: Also set this request to batch mode?
:param batch_onerror: Onerror-parameter for batch mode
:return: The request | entailment |
def send_request(self, request, response=None):
""" Send the request.
Sends the request and retrieves the results, formats them and returns
them in a dict or a list (when it's a batchresponse). If something
goes wrong, raises a SoapFailure or a HTTPError on system-side
failu... | Send the request.
Sends the request and retrieves the results, formats them and returns
them in a dict or a list (when it's a batchresponse). If something
goes wrong, raises a SoapFailure or a HTTPError on system-side
failures. Note: AuthRequest raises an HTTPError on failed
... | entailment |
def authenticate(url, account, key, by='name', expires=0, timestamp=None,
timeout=None, request_type="xml", admin_auth=False,
use_password=False, raise_on_error=False):
""" Authenticate to the Zimbra server
:param url: URL of Zimbra SOAP service
:param account: The accoun... | Authenticate to the Zimbra server
:param url: URL of Zimbra SOAP service
:param account: The account to be authenticated against
:param key: The preauth key of the domain of the account or a password (if
admin_auth or use_password is True)
:param by: If the account is specified as a name, an ID o... | entailment |
def read_dbf(dbf_path, index = None, cols = False, incl_index = False):
"""
Read a dbf file as a pandas.DataFrame, optionally selecting the index
variable and which columns are to be loaded.
__author__ = "Dani Arribas-Bel <darribas@asu.edu> "
...
Arguments
---------
dbf_path : str
... | Read a dbf file as a pandas.DataFrame, optionally selecting the index
variable and which columns are to be loaded.
__author__ = "Dani Arribas-Bel <darribas@asu.edu> "
...
Arguments
---------
dbf_path : str
Path to the DBF file to be read
index : str
... | entailment |
def column_mask(self):
"""ndarray, True where column margin <= min_base_size, same shape as slice."""
margin = compress_pruned(
self._slice.margin(
axis=0,
weighted=False,
include_transforms_for_dims=self._hs_dims,
prune=self._p... | ndarray, True where column margin <= min_base_size, same shape as slice. | entailment |
def table_mask(self):
"""ndarray, True where table margin <= min_base_size, same shape as slice."""
margin = compress_pruned(
self._slice.margin(
axis=None,
weighted=False,
include_transforms_for_dims=self._hs_dims,
prune=self._... | ndarray, True where table margin <= min_base_size, same shape as slice. | entailment |
def values(self):
"""list of _ColumnPairwiseSignificance tests.
Result has as many elements as there are coliumns in the slice. Each
significance test contains `p_vals` and `t_stats` significance tests.
"""
# TODO: Figure out how to intersperse pairwise objects for columns
... | list of _ColumnPairwiseSignificance tests.
Result has as many elements as there are coliumns in the slice. Each
significance test contains `p_vals` and `t_stats` significance tests. | entailment |
def pairwise_indices(self):
"""ndarray containing tuples of pairwise indices."""
return np.array([sig.pairwise_indices for sig in self.values]).T | ndarray containing tuples of pairwise indices. | entailment |
def summary_pairwise_indices(self):
"""ndarray containing tuples of pairwise indices for the column summary."""
summary_pairwise_indices = np.empty(
self.values[0].t_stats.shape[1], dtype=object
)
summary_pairwise_indices[:] = [
sig.summary_pairwise_indices for si... | ndarray containing tuples of pairwise indices for the column summary. | entailment |
def score(self):
"""
Calculate and return a heuristic score for this Parser against the provided
script source and path. This is used to order the ArgumentParsers as "most likely to work"
against a given script/source file.
Each parser has a calculate_score() function that retur... | Calculate and return a heuristic score for this Parser against the provided
script source and path. This is used to order the ArgumentParsers as "most likely to work"
against a given script/source file.
Each parser has a calculate_score() function that returns a list of booleans representing
... | entailment |
def reset(self):
"""
Reset the calibration to it initial state
"""
simulation = self.survey_scenario.simulation
holder = simulation.get_holder(self.weight_name)
holder.array = numpy.array(self.initial_weight, dtype = holder.variable.dtype) | Reset the calibration to it initial state | entailment |
def _set_survey_scenario(self, survey_scenario):
"""
Set survey scenario
:param survey_scenario: the survey scenario
"""
self.survey_scenario = survey_scenario
# TODO deal with baseline if reform is present
if survey_scenario.simulation is None:
... | Set survey scenario
:param survey_scenario: the survey scenario | entailment |
def set_parameters(self, parameter, value):
"""
Set parameters value
:param parameter: the parameter to be set
:param value: the valeu used to set the parameter
"""
if parameter == 'lo':
self.parameters['lo'] = 1 / value
else:
... | Set parameters value
:param parameter: the parameter to be set
:param value: the valeu used to set the parameter | entailment |
def _build_calmar_data(self):
"""
Builds the data dictionnary used as calmar input argument
"""
# Select only filtered entities
assert self.initial_weight_name is not None
data = pd.DataFrame()
data[self.initial_weight_name] = self.initial_weight * self.filter... | Builds the data dictionnary used as calmar input argument | entailment |
def _update_weights(self, margins, parameters = {}):
"""
Run calmar, stores new weights and returns adjusted margins
"""
data = self._build_calmar_data()
assert self.initial_weight_name is not None
parameters['initial_weight'] = self.initial_weight_name
val_po... | Run calmar, stores new weights and returns adjusted margins | entailment |
def set_calibrated_weights(self):
"""
Modify the weights to use the calibrated weights
"""
period = self.period
survey_scenario = self.survey_scenario
assert survey_scenario.simulation is not None
for simulation in [survey_scenario.simulation, survey_scenario.... | Modify the weights to use the calibrated weights | entailment |
def get_parameter_action(action):
"""
To foster a general schema that can accomodate multiple parsers, the general behavior here is described
rather than the specific language of a given parser. For instance, the 'append' action of an argument
is collapsing each argument given to a single argument. It a... | To foster a general schema that can accomodate multiple parsers, the general behavior here is described
rather than the specific language of a given parser. For instance, the 'append' action of an argument
is collapsing each argument given to a single argument. It also returns a set of actions as well, since
... | entailment |
def nnd_hotdeck_using_feather(receiver = None, donor = None, matching_variables = None, z_variables = None):
"""
Not working
"""
import feather
assert receiver is not None and donor is not None
assert matching_variables is not None
temporary_directory_path = os.path.join(config_files_direc... | Not working | entailment |
def wishart_pfaffian(self):
"""ndarray of wishart pfaffian CDF, before normalization"""
return np.array(
[Pfaffian(self, val).value for i, val in np.ndenumerate(self._chisq)]
).reshape(self._chisq.shape) | ndarray of wishart pfaffian CDF, before normalization | entailment |
def other_ind(self):
"""last row or column of square A"""
return np.full(self.n_min, self.size - 1, dtype=np.int) | last row or column of square A | entailment |
def K(self):
"""Normalizing constant for wishart CDF."""
K1 = np.float_power(pi, 0.5 * self.n_min * self.n_min)
K1 /= (
np.float_power(2, 0.5 * self.n_min * self._n_max)
* self._mgamma(0.5 * self._n_max, self.n_min)
* self._mgamma(0.5 * self.n_min, self.n_min)... | Normalizing constant for wishart CDF. | entailment |
def value(self):
"""return float Cumulative Distribution Function.
The return value represents a floating point number of the CDF of the
largest eigenvalue of a Wishart(n, p) evaluated at chisq_val.
"""
wishart = self._wishart_cdf
# Prepare variables for integration alg... | return float Cumulative Distribution Function.
The return value represents a floating point number of the CDF of the
largest eigenvalue of a Wishart(n, p) evaluated at chisq_val. | entailment |
def A(self):
"""ndarray - a skew-symmetric matrix for integrating the target distribution"""
wishart = self._wishart_cdf
base = np.zeros([wishart.size, wishart.size])
if wishart.n_min % 2:
# If matrix has odd number of elements, we need to append a
# row and a co... | ndarray - a skew-symmetric matrix for integrating the target distribution | entailment |
def data(cls, cube, weighted, prune):
"""Return ndarray representing table index by margin."""
return cls()._data(cube, weighted, prune) | Return ndarray representing table index by margin. | entailment |
def _data(self, cube, weighted, prune):
"""ndarray representing table index by margin."""
result = []
for slice_ in cube.slices:
if cube.has_mr:
return self._mr_index(cube, weighted, prune)
num = slice_.margin(axis=0, weighted=weighted, prune=prune)
... | ndarray representing table index by margin. | entailment |
def gini(values, weights = None, bin_size = None):
"""
Gini coefficient (normalized to 1)
Using fastgini formula :
i=N j=i
SUM W_i*(SUM W_j*X_j - W_i*X_i/2)
i=1 j=1
G = 1 - 2* ----------------------------------
... | Gini coefficient (normalized to 1)
Using fastgini formula :
i=N j=i
SUM W_i*(SUM W_j*X_j - W_i*X_i/2)
i=1 j=1
G = 1 - 2* ----------------------------------
i=N i=N
... | entailment |
def kakwani(values, ineq_axis, weights = None):
"""
Computes the Kakwani index
"""
from scipy.integrate import simps
if weights is None:
weights = ones(len(values))
# sign = -1
# if tax == True:
# sign = -1
# else:
# sign = 1
PLCx, PLCy = pseudo_lorenz(values, i... | Computes the Kakwani index | entailment |
def lorenz(values, weights = None):
"""
Computes Lorenz Curve coordinates
"""
if weights is None:
weights = ones(len(values))
df = pd.DataFrame({'v': values, 'w': weights})
df = df.sort_values(by = 'v')
x = cumsum(df['w'])
x = x / float(x[-1:])
y = cumsum(df['v'] * df['w'])
... | Computes Lorenz Curve coordinates | entailment |
def pvals(cls, slice_, axis=0, weighted=True):
"""Wishart CDF values for slice columns as square ndarray.
Wishart CDF (Cumulative Distribution Function) is calculated to determine
statistical significance of slice columns, in relation to all other columns.
These values represent the ans... | Wishart CDF values for slice columns as square ndarray.
Wishart CDF (Cumulative Distribution Function) is calculated to determine
statistical significance of slice columns, in relation to all other columns.
These values represent the answer to the question "How much is a particular
colu... | entailment |
def _chi_squared(self, proportions, margin, observed):
"""return ndarray of chi-squared measures for proportions' columns.
*proportions* (ndarray): The basis of chi-squared calcualations
*margin* (ndarray): Column margin for proportions (See `def _margin`)
*observed* (ndarray): Row marg... | return ndarray of chi-squared measures for proportions' columns.
*proportions* (ndarray): The basis of chi-squared calcualations
*margin* (ndarray): Column margin for proportions (See `def _margin`)
*observed* (ndarray): Row margin proportions (See `def _observed`) | entailment |
def _pvals_from_chi_squared(self, pairwise_chisq):
"""return statistical significance for props' columns.
*pairwise_chisq* (ndarray) Matrix of chi-squared values (bases for Wishart CDF)
"""
return self._intersperse_insertion_rows_and_columns(
1.0 - WishartCDF(pairwise_chisq,... | return statistical significance for props' columns.
*pairwise_chisq* (ndarray) Matrix of chi-squared values (bases for Wishart CDF) | entailment |
def _factory(slice_, axis, weighted):
"""return subclass for PairwiseSignificance, based on slice dimension types."""
if slice_.dim_types[0] == DT.MR_SUBVAR:
return _MrXCatPairwiseSignificance(slice_, axis, weighted)
return _CatXCatPairwiseSignificance(slice_, axis, weighted) | return subclass for PairwiseSignificance, based on slice dimension types. | entailment |
def _intersperse_insertion_rows_and_columns(self, pairwise_pvals):
"""Return pvals matrix with inserted NaN rows and columns, as numpy.ndarray.
Each insertion (a header or a subtotal) creates an offset in the calculated
pvals. These need to be taken into account when converting each pval to a
... | Return pvals matrix with inserted NaN rows and columns, as numpy.ndarray.
Each insertion (a header or a subtotal) creates an offset in the calculated
pvals. These need to be taken into account when converting each pval to a
corresponding column letter. For this reason, we need to insert an all-... | entailment |
def _opposite_axis_margin(self):
"""ndarray representing margin along the axis opposite of self._axis
In the process of calculating p-values for the column significance testing we
need both the margin along the primary axis and the percentage margin along
the opposite axis.
"""
... | ndarray representing margin along the axis opposite of self._axis
In the process of calculating p-values for the column significance testing we
need both the margin along the primary axis and the percentage margin along
the opposite axis. | entailment |
def _proportions(self):
"""ndarray representing slice proportions along correct axis."""
return self._slice.proportions(
axis=self._axis, include_mr_cat=self._include_mr_cat
) | ndarray representing slice proportions along correct axis. | entailment |
def _pairwise_chisq(self):
"""Pairwise comparisons (Chi-Square) along axis, as numpy.ndarray.
Returns a square, symmetric matrix of test statistics for the null
hypothesis that each vector along *axis* is equal to each other.
"""
return self._chi_squared(self._proportions, self.... | Pairwise comparisons (Chi-Square) along axis, as numpy.ndarray.
Returns a square, symmetric matrix of test statistics for the null
hypothesis that each vector along *axis* is equal to each other. | entailment |
def _pairwise_chisq(self):
"""Pairwise comparisons (Chi-Square) along axis, as numpy.ndarray.
Returns a list of square and symmetric matrices of test statistics for the null
hypothesis that each vector along *axis* is equal to each other.
"""
return [
self._chi_squar... | Pairwise comparisons (Chi-Square) along axis, as numpy.ndarray.
Returns a list of square and symmetric matrices of test statistics for the null
hypothesis that each vector along *axis* is equal to each other. | entailment |
def process_parser(self):
"""
We can't use the exception catch trick for docopt because the module prevents access to
it's innards __all__ = ['docopt']. Instead call with --help enforced, catch sys.exit and
work up to the calling docopt function to pull out the elements. This is horrible... | We can't use the exception catch trick for docopt because the module prevents access to
it's innards __all__ = ['docopt']. Instead call with --help enforced, catch sys.exit and
work up to the calling docopt function to pull out the elements. This is horrible.
:return: | entailment |
def build_dummies_dict(data):
"""
Return a dict with unique values as keys and vectors as values
"""
unique_val_list = unique(data)
output = {}
for val in unique_val_list:
output[val] = (data == val)
return output | Return a dict with unique values as keys and vectors as values | entailment |
def calmar(data_in, margins, initial_weight = 'wprm_init', method = 'linear', lo = None, up = None, use_proportions = False,
xtol = 1.49012e-08, maxfev = 256):
"""
Calibrate weights to satisfy some margin constraints
:param dataframe data_in: The observations data
:param str initial... | Calibrate weights to satisfy some margin constraints
:param dataframe data_in: The observations data
:param str initial_weight: The initial weight variable name
:param dict margins: Margins is a dictionnary containing for each variable as key the following values
- a scalar for nume... | entailment |
def ca_main_axis(self):
"""For univariate CA, the main axis is the categorical axis"""
try:
ca_ind = self.dim_types.index(DT.CA_SUBVAR)
return 1 - ca_ind
except ValueError:
return None | For univariate CA, the main axis is the categorical axis | entailment |
def can_compare_pairwise(self):
"""Return bool indicating if slice can compute pairwise comparisons.
Currently, only the CAT x CAT slice can compute pairwise comparisons. This also
includes the categorical array categories dimnension (CA_CAT).
"""
if self.ndim != 2:
... | Return bool indicating if slice can compute pairwise comparisons.
Currently, only the CAT x CAT slice can compute pairwise comparisons. This also
includes the categorical array categories dimnension (CA_CAT). | entailment |
def get_shape(self, prune=False, hs_dims=None):
"""Tuple of array dimensions' lengths.
It returns a tuple of ints, each representing the length of a cube
dimension, in the order those dimensions appear in the cube.
Pruning is supported. Dimensions that get reduced to a single element
... | Tuple of array dimensions' lengths.
It returns a tuple of ints, each representing the length of a cube
dimension, in the order those dimensions appear in the cube.
Pruning is supported. Dimensions that get reduced to a single element
(e.g. due to pruning) are removed from the returning ... | entailment |
def index_table(self, axis=None, baseline=None, prune=False):
"""Return index percentages for a given axis and baseline.
The index values represent the difference of the percentages to the
corresponding baseline values. The baseline values are the univariate
percentages of the correspon... | Return index percentages for a given axis and baseline.
The index values represent the difference of the percentages to the
corresponding baseline values. The baseline values are the univariate
percentages of the corresponding variable. | entailment |
def labels(self, hs_dims=None, prune=False):
"""Get labels for the cube slice, and perform pruning by slice."""
if self.ca_as_0th:
labels = self._cube.labels(include_transforms_for_dims=hs_dims)[1:]
else:
labels = self._cube.labels(include_transforms_for_dims=hs_dims)[-2:... | Get labels for the cube slice, and perform pruning by slice. | entailment |
def margin(
self,
axis=None,
weighted=True,
include_missing=False,
include_transforms_for_dims=None,
prune=False,
include_mr_cat=False,
):
"""Return ndarray representing slice margin across selected axis.
A margin (or basis) can be calculated ... | Return ndarray representing slice margin across selected axis.
A margin (or basis) can be calculated for a contingency table, provided
that the dimensions of the desired directions are marginable. The
dimensions are marginable if they represent mutualy exclusive data,
such as true categ... | entailment |
def min_base_size_mask(self, size, hs_dims=None, prune=False):
"""Returns MinBaseSizeMask object with correct row, col and table masks.
The returned object stores the necessary information about the base size, as
well as about the base values. It can create corresponding masks in teh row,
... | Returns MinBaseSizeMask object with correct row, col and table masks.
The returned object stores the necessary information about the base size, as
well as about the base values. It can create corresponding masks in teh row,
column, and table directions, based on the corresponding base values
... | entailment |
def mr_dim_ind(self):
"""Get the correct index of the MR dimension in the cube slice."""
mr_dim_ind = self._cube.mr_dim_ind
if self._cube.ndim == 3:
if isinstance(mr_dim_ind, int):
if mr_dim_ind == 0:
# If only the 0th dimension of a 3D is an MR, t... | Get the correct index of the MR dimension in the cube slice. | entailment |
def scale_means(self, hs_dims=None, prune=False):
"""Return list of column and row scaled means for this slice.
If a row/col doesn't have numerical values, return None for the
corresponding dimension. If a slice only has 1D, return only the column
scaled mean (as numpy array). If both r... | Return list of column and row scaled means for this slice.
If a row/col doesn't have numerical values, return None for the
corresponding dimension. If a slice only has 1D, return only the column
scaled mean (as numpy array). If both row and col scaled means are
present, return them as t... | entailment |
def table_name(self):
"""Get slice name.
In case of 2D return cube name. In case of 3D, return the combination
of the cube name with the label of the corresponding slice
(nth label of the 0th dimension).
"""
if self._cube.ndim < 3 and not self.ca_as_0th:
retu... | Get slice name.
In case of 2D return cube name. In case of 3D, return the combination
of the cube name with the label of the corresponding slice
(nth label of the 0th dimension). | entailment |
def wishart_pairwise_pvals(self, axis=0):
"""Return square symmetric matrix of pairwise column-comparison p-values.
Square, symmetric matrix along *axis* of pairwise p-values for the
null hypothesis that col[i] = col[j] for each pair of columns.
*axis* (int): axis along which to perfor... | Return square symmetric matrix of pairwise column-comparison p-values.
Square, symmetric matrix along *axis* of pairwise p-values for the
null hypothesis that col[i] = col[j] for each pair of columns.
*axis* (int): axis along which to perform comparison. Only columns (0)
are implemente... | entailment |
def pvals(self, weighted=True, prune=False, hs_dims=None):
"""Return 2D ndarray with calculated P values
This function calculates statistically significant cells for
categorical contingency tables under the null hypothesis that the
row and column variables are independent (uncorrelated)... | Return 2D ndarray with calculated P values
This function calculates statistically significant cells for
categorical contingency tables under the null hypothesis that the
row and column variables are independent (uncorrelated).
The values are calculated for 2D tables only.
:para... | entailment |
def zscore(self, weighted=True, prune=False, hs_dims=None):
"""Return ndarray with slices's standardized residuals (Z-scores).
(Only applicable to a 2D contingency tables.) The Z-score or
standardized residual is the difference between observed and expected
cell counts if row and column... | Return ndarray with slices's standardized residuals (Z-scores).
(Only applicable to a 2D contingency tables.) The Z-score or
standardized residual is the difference between observed and expected
cell counts if row and column variables were independent divided
by the residual cell varian... | entailment |
def pairwise_indices(self, alpha=0.05, only_larger=True, hs_dims=None):
"""Indices of columns where p < alpha for column-comparison t-tests
Returns an array of tuples of columns that are significant at p<alpha,
from a series of pairwise t-tests.
Argument both_pairs returns indices stri... | Indices of columns where p < alpha for column-comparison t-tests
Returns an array of tuples of columns that are significant at p<alpha,
from a series of pairwise t-tests.
Argument both_pairs returns indices striclty on the test statistic. If
False, however, only the index of values *si... | entailment |
def _array_type_std_res(self, counts, total, colsum, rowsum):
"""Return ndarray containing standard residuals for array values.
The shape of the return value is the same as that of *counts*.
Array variables require special processing because of the
underlying math. Essentially, it boils... | Return ndarray containing standard residuals for array values.
The shape of the return value is the same as that of *counts*.
Array variables require special processing because of the
underlying math. Essentially, it boils down to the fact that the
variable dimensions are mutually indep... | entailment |
def _calculate_std_res(self, counts, total, colsum, rowsum):
"""Return ndarray containing standard residuals.
The shape of the return value is the same as that of *counts*.
"""
if set(self.dim_types) & DT.ARRAY_TYPES: # ---has-mr-or-ca---
return self._array_type_std_res(cou... | Return ndarray containing standard residuals.
The shape of the return value is the same as that of *counts*. | entailment |
def _calculate_correct_axis_for_cube(self, axis):
"""Return correct axis for cube, based on ndim.
If cube has 3 dimensions, increase axis by 1. This will translate the
default 0 (cols direction) and 1 (rows direction) to actual 1
(cols direction) and 2 (rows direction). This is needed b... | Return correct axis for cube, based on ndim.
If cube has 3 dimensions, increase axis by 1. This will translate the
default 0 (cols direction) and 1 (rows direction) to actual 1
(cols direction) and 2 (rows direction). This is needed because the
0th dimension of the 3D cube is only used ... | entailment |
def _scalar_type_std_res(self, counts, total, colsum, rowsum):
"""Return ndarray containing standard residuals for category values.
The shape of the return value is the same as that of *counts*.
"""
expected_counts = expected_freq(counts)
residuals = counts - expected_counts
... | Return ndarray containing standard residuals for category values.
The shape of the return value is the same as that of *counts*. | entailment |
def data(self):
"""list of mean numeric values of categorical responses."""
means = []
table = self._slice.as_array()
products = self._inner_prods(table, self.values)
for axis, product in enumerate(products):
if product is None:
means.append(product)
... | list of mean numeric values of categorical responses. | entailment |
def margin(self, axis):
"""Return marginal value of the current slice scaled means.
This value is the the same what you would get from a single variable
(constituting a 2D cube/slice), when the "non-missing" filter of the
opposite variable would be applied. This behavior is consistent w... | Return marginal value of the current slice scaled means.
This value is the the same what you would get from a single variable
(constituting a 2D cube/slice), when the "non-missing" filter of the
opposite variable would be applied. This behavior is consistent with
what is visible in the ... | entailment |
def values(self):
"""list of ndarray value-ids for each dimension in slice.
The values for each dimension appear as an ndarray. None appears
instead of the array for each dimension having only NaN values.
"""
return [
(
np.array(dim.numeric_values)
... | list of ndarray value-ids for each dimension in slice.
The values for each dimension appear as an ndarray. None appears
instead of the array for each dimension having only NaN values. | entailment |
def compress_pruned(table):
"""Compress table based on pruning mask.
Only the rows/cols in which all of the elements are masked need to be
pruned.
"""
if not isinstance(table, np.ma.core.MaskedArray):
return table
if table.ndim == 0:
return table.data
if table.ndim == 1:
... | Compress table based on pruning mask.
Only the rows/cols in which all of the elements are masked need to be
pruned. | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.