filename
stringlengths 13
19
| text
stringlengths 134
1.04M
|
---|---|
the-stack_106_26556 | # -*- coding: utf-8 -*-
__author__ = "Gian Gamberi, Gui Reis, Rone FIlho, Marcelo Takayama"
__copyright__ = "GadosComp"
__version__ = "2.0"
__status__ = "Production"
__license__ = """
MIT License
Copyright (c) 2021 GadosComp
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
## Bibliotecas necessárias
# Arquivos globais
from discord import Intents, Client, Game, Message # Configurações do dircord
from os import getenv # Pega o token do bot
# Arquivos locais
from Gados import Gados
if __name__ == "__main__":
intents = Intents.default()
intents.members = True
client = Client(intents=intents)
cmds = Gados(client)
@client.event # Regstra um evento
async def on_ready(): # Quando o bot estiver pronto
print(f"Bot ativado com o nome {client.user}")
await client.change_presence(activity=Game(name="~help for commands"))
@client.event # Próximo evento, se bot receber uma mensagem
async def on_message(message:Message):
cmds.setMsg(message)
msg = cmds.getMsg()
await cmds.padrao()
# Comandos nativos do bot
if msg.startswith("~floodPV"): await cmds.spamPv()
elif msg.startswith("~flood"): await cmds.spam()
elif msg.startswith("~erase"): await cmds.erase()
elif msg.startswith("~mensagem"): await cmds.mensagem()
elif msg.startswith("~status"): await cmds.status()
elif msg.startswith("~yall"): await cmds.alerta()
elif msg.startswith("~purge"): await cmds.purge()
elif msg.startswith("~erradicate"): await cmds.erradicate()
elif msg.startswith("~shake"): await cmds.shake()
elif msg.startswith("~earthquake"): await cmds.milkshake()
elif msg.startswith("~copypasta"): await cmds.copypasta()
elif msg.startswith("~roullete"): await cmds.roll()
elif msg.startswith("~ban"): await cmds.ban()
elif msg.startswith("~deafen"): await cmds.headFone(True)
elif msg.startswith("~undeafen"): await cmds.headFone(False)
elif msg.startswith("~silence"): await cmds.silence(True)
elif msg.startswith("~unsilence"): await cmds.silence(False)
elif msg.startswith("~help"): await cmds.listCommands()
elif msg.startswith("~shout"): await cmds.playSound()
elif msg.startswith("~magnetize"): await cmds.magnetize()
elif msg.startswith("~barricade"): await cmds.barricade(True)
elif msg.startswith("~unbarricade"): await cmds.barricade(False)
# Comandos para os gados
elif msg.startswith("~silence patrick"): await cmds.patrick()
elif msg.startswith("#CassioVitima"): await cmds.cassio()
elif msg.startswith("obliterate TryRak"): await cmds.BFG(True)
client.run(getenv('TOKEN')) |
the-stack_106_26557 | import os
from typing import List
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
if __name__ == '__main__':
data_path: str = os.path.join('.', 'datawarehouse', 'memory_comparison')
file: str = os.path.join(data_path, 'mem_time.csv')
df: pd.DataFrame = pd.read_csv(file, header=0)
fig, ax = plt.subplots(figsize=(10,10))
memory_types = df['memory_type'].drop_duplicates()
colors: List[str] = ['#ffa15a', '#636efa']
index = np.arange(start=1, stop=len(memory_types)+1, step=1)
bar_width: float = 0.35
acc_width: float = 0
for i, memory_type in enumerate(memory_types):
v = df[df['memory_type'] == memory_type]
plt.bar(
x=index + acc_width,
height=v['time'].tolist(),
color=colors[i],
label=memory_type,
width=bar_width,
)
acc_width += bar_width
plt.legend(loc='upper left', ncol=2, prop={"size":18})
plt.grid(linestyle='-', color='#B0BEC5', axis='y')
plt.ylabel('Seconds', fontsize=20)
plt.xlabel('')
plt.xticks(index + (bar_width/2), df['device'].drop_duplicates().to_list(), fontsize=20)
ax.tick_params(axis='both', which='major', labelsize=18)
y_limit = 14
ax.set_ylim(0, y_limit)
plt.yticks(np.arange(0, y_limit, 1))
# time text
ax.text(0.93, 6.1, '5.9s', fontsize=16)
ax.text(1.28, 7.6, '7.4s', fontsize=16)
ax.text(1.92, 11.5, '11.3s', fontsize=16)
ax.text(2.28, 12.4, '12.2s', fontsize=16)
out: str = os.path.join(data_path, 'mem_comparison.eps')
plt.savefig(out, format='eps', bbox_inches='tight') |
the-stack_106_26559 | from pylab import *
from synapseConstants import *
figure()
title("NMDA synapse - Mg dependence")
Vrange = arange(-80e-3,0e-3,1e-3)
eta = 1.0 / mitral_granule_NMDA_KMg_A
gamma = 1.0 / mitral_granule_NMDA_KMg_B
Vdep = [ 1.0/(1+eta*MG_CONC*exp(-gamma*V)) for V in Vrange]
plot(Vrange,Vdep,'r,-')
show()
|
the-stack_106_26561 | import numpy as np
from .shape import Shape
from .._shapes_utils import (
triangulate_edge,
triangulate_ellipse,
center_radii_to_corners,
rectangle_to_box,
)
class Ellipse(Shape):
"""Class for a single ellipse
Parameters
----------
data : (4, D) array or (2, 2) array.
Either a (2, 2) array specifying the center and radii of an axis
aligned ellipse, or a (4, D) array specifying the four corners of a
boudning box that contains the ellipse. These need not be axis aligned.
edge_width : float
thickness of lines and edges.
edge_color : str | tuple
If string can be any color name recognized by vispy or hex value if
starting with `#`. If array-like must be 1-dimensional array with 3 or
4 elements.
face_color : str | tuple
If string can be any color name recognized by vispy or hex value if
starting with `#`. If array-like must be 1-dimensional array with 3 or
4 elements.
opacity : float
Opacity of the shape, must be between 0 and 1.
z_index : int
Specifier of z order priority. Shapes with higher z order are displayed
ontop of others.
dims_order : (D,) list
Order that the dimensions are to be rendered in.
"""
def __init__(
self,
data,
*,
edge_width=1,
edge_color='black',
face_color='white',
opacity=1,
z_index=0,
dims_order=None,
ndisplay=2,
):
super().__init__(
edge_width=edge_width,
edge_color=edge_color,
face_color=face_color,
opacity=opacity,
z_index=z_index,
dims_order=dims_order,
ndisplay=ndisplay,
)
self._closed = True
self._use_face_vertices = True
self.data = data
self.name = 'ellipse'
@property
def data(self):
"""(4, D) array: ellipse vertices.
"""
return self._data
@data.setter
def data(self, data):
data = np.array(data).astype(float)
if len(self.dims_order) != data.shape[1]:
self._dims_order = list(range(data.shape[1]))
if len(data) == 2 and data.shape[1] == 2:
data = center_radii_to_corners(data[0], data[1])
if len(data) != 4:
raise ValueError(
f"""Data shape does not match a ellipse.
Ellipse expects four corner vertices,
{len(data)} provided."""
)
self._data = data
self._update_displayed_data()
def _update_displayed_data(self):
"""Update the data that is to be displayed."""
# Build boundary vertices with num_segments
vertices, triangles = triangulate_ellipse(self.data_displayed)
self._set_meshes(vertices[1:-1], face=False)
self._face_vertices = vertices
self._face_triangles = triangles
self._box = rectangle_to_box(self.data_displayed)
data_not_displayed = self.data[:, self.dims_not_displayed]
self.slice_key = np.round(
[
np.min(data_not_displayed, axis=0),
np.max(data_not_displayed, axis=0),
]
).astype('int')
def transform(self, transform):
"""Performs a linear transform on the shape
Parameters
----------
transform : np.ndarray
2x2 array specifying linear transform.
"""
self._box = self._box @ transform.T
self._data[:, self.dims_displayed] = (
self._data[:, self.dims_displayed] @ transform.T
)
self._face_vertices = self._face_vertices @ transform.T
points = self._face_vertices[1:-1]
centers, offsets, triangles = triangulate_edge(
points, closed=self._closed
)
self._edge_vertices = centers
self._edge_offsets = offsets
self._edge_triangles = triangles
|
the-stack_106_26564 | '''
Description:
The Hamming distance between two integers is the number of positions at which the corresponding bits are different.
Given two integers x and y, calculate the Hamming distance.
Note:
0 ≤ x, y < 231.
Example:
Input: x = 1, y = 4
Output: 2
Explanation:
1 (0 0 0 1)
4 (0 1 0 0)
↑ ↑
The above arrows point to positions where the corresponding bits are different.
'''
class Solution:
def hammingDistance(self, x: int, y: int) -> int:
xor_result = x ^ y
hamming_dist = 0
for bit_shift in range(32):
if xor_result & 1:
hamming_dist += 1
xor_result >>= 1
return hamming_dist
## Time Complexity: O( 1 )
#
# The overhead in time is the cost of xor and loop, which is of O(32) = O( 1 )
## Space Complexity: O( 1 )
#
# The overhead in space is the storage for loop index and temporary variable, which is of O( 1 )
import unittest
class Testing( unittest.TestCase ):
def test_case_1(self):
result = Solution().hammingDistance(1, 4)
self.assertEqual(result, 2)
if __name__ == '__main__':
unittest.main()
|
the-stack_106_26565 | #!/usr/bin/env python
# Copyright (c) 2014 Wladimir J. van der Laan
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
'''
Run this script from the root of the repository to update all translations from
transifex.
It will do the following automatically:
- fetch all translations using the tx tool
- post-process them into valid and committable format
- remove invalid control characters
- remove location tags (makes diffs less noisy)
TODO:
- auto-add new translations to the build system according to the translation process
'''
from __future__ import division, print_function
import subprocess
import re
import sys
import os
import io
import xml.etree.ElementTree as ET
# Name of transifex tool
TX = 'tx'
# Name of source language file
SOURCE_LANG = 'cc_en.ts'
# Directory with locale files
LOCALE_DIR = 'src/qt/locale'
# Minimum number of messages for translation to be considered at all
MIN_NUM_MESSAGES = 10
def check_at_repository_root():
if not os.path.exists('.git'):
print('No .git directory found')
print('Execute this script at the root of the repository', file=sys.stderr)
exit(1)
def fetch_all_translations():
if subprocess.call([TX, 'pull', '-f', '-a']):
print('Error while fetching translations', file=sys.stderr)
exit(1)
def find_format_specifiers(s):
'''Find all format specifiers in a string.'''
pos = 0
specifiers = []
while True:
percent = s.find('%', pos)
if percent < 0:
break
specifiers.append(s[percent+1])
pos = percent+2
return specifiers
def split_format_specifiers(specifiers):
'''Split format specifiers between numeric (Qt) and others (strprintf)'''
numeric = []
other = []
for s in specifiers:
if s in {'1','2','3','4','5','6','7','8','9'}:
numeric.append(s)
else:
other.append(s)
# If both numeric format specifiers and "others" are used, assume we're dealing
# with a Qt-formatted message. In the case of Qt formatting (see https://doc.qt.io/qt-5/qstring.html#arg)
# only numeric formats are replaced at all. This means "(percentage: %1%)" is valid, without needing
# any kind of escaping that would be necessary for strprintf. Without this, this function
# would wrongly detect '%)' as a printf format specifier.
if numeric:
other = []
# numeric (Qt) can be present in any order, others (strprintf) must be in specified order
return set(numeric),other
def sanitize_string(s):
'''Sanitize string for printing'''
return s.replace('\n',' ')
def check_format_specifiers(source, translation, errors, numerus):
source_f = split_format_specifiers(find_format_specifiers(source))
# assert that no source messages contain both Qt and strprintf format specifiers
# if this fails, go change the source as this is hacky and confusing!
assert(not(source_f[0] and source_f[1]))
try:
translation_f = split_format_specifiers(find_format_specifiers(translation))
except IndexError:
errors.append("Parse error in translation for '%s': '%s'" % (sanitize_string(source), sanitize_string(translation)))
return False
else:
if source_f != translation_f:
if numerus and source_f == (set(), ['n']) and translation_f == (set(), []) and translation.find('%') == -1:
# Allow numerus translations to omit %n specifier (usually when it only has one possible value)
return True
errors.append("Mismatch between '%s' and '%s'" % (sanitize_string(source), sanitize_string(translation)))
return False
return True
def all_ts_files(suffix=''):
for filename in os.listdir(LOCALE_DIR):
# process only language files, and do not process source language
if not filename.endswith('.ts'+suffix) or filename == SOURCE_LANG+suffix:
continue
if suffix: # remove provided suffix
filename = filename[0:-len(suffix)]
filepath = os.path.join(LOCALE_DIR, filename)
yield(filename, filepath)
FIX_RE = re.compile(b'[\x00-\x09\x0b\x0c\x0e-\x1f]')
def remove_invalid_characters(s):
'''Remove invalid characters from translation string'''
return FIX_RE.sub(b'', s)
# Override cdata escape function to make our output match Qt's (optional, just for cleaner diffs for
# comparison, disable by default)
_orig_escape_cdata = None
def escape_cdata(text):
text = _orig_escape_cdata(text)
text = text.replace("'", ''')
text = text.replace('"', '"')
return text
def postprocess_translations(reduce_diff_hacks=False):
print('Checking and postprocessing...')
if reduce_diff_hacks:
global _orig_escape_cdata
_orig_escape_cdata = ET._escape_cdata
ET._escape_cdata = escape_cdata
for (filename,filepath) in all_ts_files():
os.rename(filepath, filepath+'.orig')
have_errors = False
for (filename,filepath) in all_ts_files('.orig'):
# pre-fixups to cope with transifex output
parser = ET.XMLParser(encoding='utf-8') # need to override encoding because 'utf8' is not understood only 'utf-8'
with open(filepath + '.orig', 'rb') as f:
data = f.read()
# remove control characters; this must be done over the entire file otherwise the XML parser will fail
data = remove_invalid_characters(data)
tree = ET.parse(io.BytesIO(data), parser=parser)
# iterate over all messages in file
root = tree.getroot()
for context in root.findall('context'):
for message in context.findall('message'):
numerus = message.get('numerus') == 'yes'
source = message.find('source').text
translation_node = message.find('translation')
# pick all numerusforms
if numerus:
translations = [i.text for i in translation_node.findall('numerusform')]
else:
translations = [translation_node.text]
for translation in translations:
if translation is None:
continue
errors = []
valid = check_format_specifiers(source, translation, errors, numerus)
for error in errors:
print('%s: %s' % (filename, error))
if not valid: # set type to unfinished and clear string if invalid
translation_node.clear()
translation_node.set('type', 'unfinished')
have_errors = True
# Remove location tags
for location in message.findall('location'):
message.remove(location)
# Remove entire message if it is an unfinished translation
if translation_node.get('type') == 'unfinished':
context.remove(message)
# check if document is (virtually) empty, and remove it if so
num_messages = 0
for context in root.findall('context'):
for message in context.findall('message'):
num_messages += 1
if num_messages < MIN_NUM_MESSAGES:
print('Removing %s, as it contains only %i messages' % (filepath, num_messages))
continue
# write fixed-up tree
# if diff reduction requested, replace some XML to 'sanitize' to qt formatting
if reduce_diff_hacks:
out = io.BytesIO()
tree.write(out, encoding='utf-8')
out = out.getvalue()
out = out.replace(b' />', b'/>')
with open(filepath, 'wb') as f:
f.write(out)
else:
tree.write(filepath, encoding='utf-8')
return have_errors
if __name__ == '__main__':
check_at_repository_root()
fetch_all_translations()
postprocess_translations()
|
the-stack_106_26566 | import numpy as np
__author__ = 'Otilia Stretcu'
def normalize(data, axis, offset=None, scale=None, return_offset=False):
"""
Normalizes the data along the provided axis.
If offset and scale are provided, we compute (data-offset) / scale,
otherwise the offset is the mean, and the scale is the std (i.e. we z-score).
Args:
data(np.ndarray or list of embedded lists): Array-like data.
axis(int): Axis along which to normalize.
offset(np.ndarray or list of embedded lists): It matches the
shape of the data along the provided axis.
scale(np.ndarray or list of embedded lists): It matches the
shape of the data along the provided axis.
Returns:
Normalized data, and optionally the offset and scale.
"""
if offset is None:
offset = np.expand_dims(data.mean(axis=axis), axis=axis)
if scale is None:
scale = np.expand_dims(data.std(axis=axis), axis=axis)
scale[scale == 0.0] = 1.0
if return_offset:
return (data - offset) / scale, offset, scale
return (data - offset) / scale
|
the-stack_106_26567 | """Store configuration options as a singleton."""
import os
import re
import subprocess
import sys
from argparse import Namespace
from functools import lru_cache
from typing import Any, Dict, List, Optional, Tuple
from packaging.version import Version
from ansiblelint.constants import ANSIBLE_MISSING_RC
DEFAULT_KINDS = [
# Do not sort this list, order matters.
{"jinja2": "**/*.j2"}, # jinja2 templates are not always parsable as something else
{"jinja2": "**/*.j2.*"},
{"requirements": "**/meta/requirements.yml"}, # v1 only
# https://docs.ansible.com/ansible/latest/dev_guide/collections_galaxy_meta.html
{"galaxy": "**/galaxy.yml"}, # Galaxy collection meta
{"reno": "**/releasenotes/*/*.{yaml,yml}"}, # reno release notes
{"playbook": "**/playbooks/*.{yml,yaml}"},
{"playbook": "**/*playbook*.{yml,yaml}"},
{"role": "**/roles/*/"},
{"tasks": "**/tasks/**/*.{yaml,yml}"},
{"handlers": "**/handlers/*.{yaml,yml}"},
{"vars": "**/{host_vars,group_vars,vars,defaults}/**/*.{yaml,yml}"},
{"meta": "**/meta/main.{yaml,yml}"},
{"yaml": ".config/molecule/config.{yaml,yml}"}, # molecule global config
{
"requirements": "**/molecule/*/{collections,requirements}.{yaml,yml}"
}, # molecule old collection requirements (v1), ansible 2.8 only
{"yaml": "**/molecule/*/{base,molecule}.{yaml,yml}"}, # molecule config
{"requirements": "**/requirements.yml"}, # v2 and v1
{"playbook": "**/molecule/*/*.{yaml,yml}"}, # molecule playbooks
{"yaml": "**/{.ansible-lint,.yamllint}"},
{"yaml": "**/*.{yaml,yml}"},
{"yaml": "**/.*.{yaml,yml}"},
]
BASE_KINDS = [
# These assignations are only for internal use and are only inspired by
# MIME/IANA model. Their purpose is to be able to process a file based on
# it type, including generic processing of text files using the prefix.
{
"text/jinja2": "**/*.j2"
}, # jinja2 templates are not always parsable as something else
{"text/jinja2": "**/*.j2.*"},
{"text": "**/templates/**/*.*"}, # templates are likely not validable
{"text/json": "**/*.json"}, # standardized
{"text/markdown": "**/*.md"}, # https://tools.ietf.org/html/rfc7763
{"text/rst": "**/*.rst"}, # https://en.wikipedia.org/wiki/ReStructuredText
{"text/ini": "**/*.ini"},
# YAML has no official IANA assignation
{"text/yaml": "**/{.ansible-lint,.yamllint}"},
{"text/yaml": "**/*.{yaml,yml}"},
{"text/yaml": "**/.*.{yaml,yml}"},
]
options = Namespace(
colored=True,
configured=False,
cwd=".",
display_relative_path=True,
exclude_paths=[],
lintables=[],
listrules=False,
listtags=False,
parseable=False,
parseable_severity=False,
quiet=False,
rulesdirs=[],
skip_list=[],
tags=[],
verbosity=False,
warn_list=[],
kinds=DEFAULT_KINDS,
mock_modules=[],
mock_roles=[],
loop_var_prefix=None,
offline=False,
project_dir=".", # default should be valid folder (do not use None here)
extra_vars=None,
enable_list=[],
skip_action_validation=True,
rules=dict(), # Placeholder to set and keep configurations for each rule.
)
# Used to store detected tag deprecations
used_old_tags: Dict[str, str] = {}
# Used to store collection list paths (with mock paths if needed)
collection_list: List[str] = []
def get_rule_config(rule_id: str) -> Dict[str, Any]:
"""Get configurations for the rule ``rule_id``."""
return options.rules.get(rule_id, dict())
@lru_cache()
def ansible_collections_path() -> str:
"""Return collection path variable for current version of Ansible."""
# respect Ansible behavior, which is to load old name if present
for env_var in ["ANSIBLE_COLLECTIONS_PATHS", "ANSIBLE_COLLECTIONS_PATH"]:
if env_var in os.environ:
return env_var
# https://github.com/ansible/ansible/pull/70007
if ansible_version() >= ansible_version("2.10.0.dev0"):
return "ANSIBLE_COLLECTIONS_PATH"
return "ANSIBLE_COLLECTIONS_PATHS"
def parse_ansible_version(stdout: str) -> Tuple[str, Optional[str]]:
"""Parse output of 'ansible --version'."""
# ansible-core 2.11+: 'ansible [core 2.11.3]'
match = re.match(r"^ansible \[(?:core|base) ([^\]]+)\]", stdout)
if match:
return match.group(1), None
# ansible-base 2.10 and Ansible 2.9: 'ansible 2.x.y'
match = re.match(r"^ansible ([^\s]+)", stdout)
if match:
return match.group(1), None
return "", "FATAL: Unable parse ansible cli version: %s" % stdout
@lru_cache()
def ansible_version(version: str = "") -> Version:
"""Return current Version object for Ansible.
If version is not mentioned, it returns current version as detected.
When version argument is mentioned, it return converts the version string
to Version object in order to make it usable in comparisons.
"""
if not version:
proc = subprocess.run(
["ansible", "--version"],
universal_newlines=True,
check=False,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
if proc.returncode == 0:
version, error = parse_ansible_version(proc.stdout)
if error is not None:
print(error)
sys.exit(ANSIBLE_MISSING_RC)
else:
print(
"Unable to find a working copy of ansible executable.",
proc,
)
sys.exit(ANSIBLE_MISSING_RC)
return Version(version)
if ansible_collections_path() in os.environ:
collection_list = os.environ[ansible_collections_path()].split(':')
|
the-stack_106_26569 | import os, sys
# We allow a two-level project structure where your root folder contains
# project-specific apps and the "common" subfolder contains common apps.
COMMON_DIR = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
PROJECT_DIR = os.path.dirname(COMMON_DIR)
if os.path.basename(COMMON_DIR) == 'common-apps':
MAIN_DIRS = (PROJECT_DIR, COMMON_DIR)
print >>sys.stderr, '!!!!!!!!!!!!!!!!!!!!!!!!!!\n' \
'Deprecation warning: the "common-apps" folder ' \
'is deprecated. Please move all modules from ' \
'there into the main project folder and remove ' \
'the "common-apps" folder.\n' \
'!!!!!!!!!!!!!!!!!!!!!!!!!!\n'
else:
PROJECT_DIR = COMMON_DIR
MAIN_DIRS = (PROJECT_DIR,)
# Overrides for os.environ
env_ext = {}
if 'DJANGO_SETTINGS_MODULE' not in os.environ:
env_ext['DJANGO_SETTINGS_MODULE'] = 'settings'
def setup_env():
"""Configures app engine environment for command-line apps."""
# Try to import the appengine code from the system path.
try:
from google.appengine.api import apiproxy_stub_map
except ImportError:
for k in [k for k in sys.modules if k.startswith('google')]:
del sys.modules[k]
# Not on the system path. Build a list of alternative paths where it
# may be. First look within the project for a local copy, then look for
# where the Mac OS SDK installs it.
paths = [os.path.join(PROJECT_DIR, '.google_appengine'),
os.path.join(COMMON_DIR, '.google_appengine'),
'/usr/local/google_appengine',
'/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine']
for path in os.environ.get('PATH', '').split(os.pathsep):
path = path.rstrip(os.sep)
if path.endswith('google_appengine'):
paths.append(path)
if os.name in ('nt', 'dos'):
path = r'%(PROGRAMFILES)s\Google\google_appengine' % os.environ
paths.append(path)
# Loop through all possible paths and look for the SDK dir.
SDK_PATH = None
for sdk_path in paths:
sdk_path = os.path.realpath(sdk_path)
if os.path.exists(sdk_path):
SDK_PATH = sdk_path
break
if SDK_PATH is None:
# The SDK could not be found in any known location.
sys.stderr.write('The Google App Engine SDK could not be found!\n'
"Make sure it's accessible via your PATH "
"environment and called google_appengine.")
sys.exit(1)
# Add the SDK and the libraries within it to the system path.
EXTRA_PATHS = [SDK_PATH]
lib = os.path.join(SDK_PATH, 'lib')
# Automatically add all packages in the SDK's lib folder:
for dir in os.listdir(lib):
path = os.path.join(lib, dir)
# Package can be under 'lib/<pkg>/<pkg>/' or 'lib/<pkg>/lib/<pkg>/'
detect = (os.path.join(path, dir), os.path.join(path, 'lib', dir))
for path in detect:
if os.path.isdir(path) and not dir == 'django':
EXTRA_PATHS.append(os.path.dirname(path))
break
sys.path = EXTRA_PATHS + sys.path
from google.appengine.api import apiproxy_stub_map
setup_project()
setup_logging()
# Patch Django to support loading management commands from zip files
from django.core import management
management.find_commands = find_commands
def find_commands(management_dir):
"""
Given a path to a management directory, returns a list of all the command
names that are available.
This version works for django deployments which are file based or
contained in a ZIP (in sys.path).
Returns an empty list if no commands are defined.
"""
import pkgutil
return [modname for importer, modname, ispkg in pkgutil.iter_modules(
[os.path.join(management_dir, 'commands')]) if not ispkg]
def setup_threading():
# XXX: GAE's threading.local doesn't work correctly with subclassing
try:
from django.utils._threading_local import local
import threading
threading.local = local
except ImportError:
pass
def setup_logging():
import logging
# Fix Python 2.6 logging module
logging.logMultiprocessing = 0
# Enable logging
from django.conf import settings
if settings.DEBUG:
logging.getLogger().setLevel(logging.DEBUG)
else:
logging.getLogger().setLevel(logging.INFO)
def setup_project():
from .utils import have_appserver, on_production_server
if have_appserver:
# This fixes a pwd import bug for os.path.expanduser()
global env_ext
env_ext['HOME'] = PROJECT_DIR
# Get the subprocess module into the dev_appserver sandbox.
# This module is just too important for development.
# The second part of this hack is in runserver.py which adds
# important environment variables like PATH etc.
if not on_production_server:
try:
from google.appengine.api.mail_stub import subprocess
sys.modules['subprocess'] = subprocess
except ImportError:
import logging
logging.warn('Could not add the subprocess module to the sandbox.')
os.environ.update(env_ext)
EXTRA_PATHS = list(MAIN_DIRS)
EXTRA_PATHS.append(os.path.dirname(PROJECT_DIR))
EXTRA_PATHS.append(os.path.join(os.path.dirname(__file__), 'lib'))
ZIP_PACKAGES_DIRS = tuple(os.path.join(dir, 'zip-packages')
for dir in MAIN_DIRS)
# We support zipped packages in the common and project folders.
for packages_dir in ZIP_PACKAGES_DIRS:
if os.path.isdir(packages_dir):
for zip_package in os.listdir(packages_dir):
EXTRA_PATHS.append(os.path.join(packages_dir, zip_package))
# App Engine causes main.py to be reloaded if an exception gets raised
# on the first request of a main.py instance, so don't call setup_project()
# multiple times. We ensure this indirectly by checking if we've already
# modified sys.path.
if len(sys.path) < len(EXTRA_PATHS) or \
sys.path[:len(EXTRA_PATHS)] != EXTRA_PATHS:
sys.path = EXTRA_PATHS + sys.path
|
the-stack_106_26571 | import pygame
from map import game_map
from gameSettings import *
'''def ray_casting(screen, position, angle):
half_angle = angle - h_fov #Angle of the first ray of scope
xc, yc = position #Position of the player/camera //Starting position of all rays
for ray in range(no_of_rays):
sinA = math.sin(half_angle)
cosA = math.cos(half_angle)
for depth in range(fov_length):
x0 = xc + depth * cosA
y0 = yc + depth * sinA
#pygame.draw.line(screen, gray, position, (x0, y0), 2)
if (x0 // tile * tile, y0 // tile * tile) in game_map: #If an object/sprite falls inside our Scope or FOV
depth = depth * math.cos(angle - half_angle) #To remove fish-eye effect, removes distorted edges of rectangles in map
obj_height = Est_Coeff / depth #Calculating height of the object/sprite that falls in our scope
brightness = 255 / (1 + depth * depth * 0.00002) #Used to give a contrast/saturation effect, the further our object is, it will become darker
colour = (brightness, brightness // 2, brightness//2) #Applying the effect here, can be used later give the illusion
pygame.draw.rect(screen, colour, (ray * scale, h_height - obj_height // 2, scale, obj_height)) #Draw a rectangle for the each object in the scope
break
half_angle = half_angle + ray_angle'''
def mapping(x, y):
return (x // tile) * tile, (y // tile) * tile
def ray_casting(screen, position, angle): #Implementing the Bresenham's line algorithm along with ray tracing here
Px, Py = position #player model's co-ordinates
Xm, Ym = mapping(Px, Py) #co-ordinates of the upper left corner of current grid in the map
half_angle = angle - h_fov
for ray in range(no_of_rays):
sinA = math.sin(half_angle)
cosA = math.cos(half_angle)
#For vertical line on the grid map (mentioned in notes)
if cosA >= 0: #if it is positive (y-axis // vertical axis)
x = Xm + tile
dx = 1 #used to store the next location on the vertical axis
else: #if it is negative (y-axis // vertical axis)
x = Xm
dx = -1 #used to store the next location on the vertical axis
for i in range (0, width, tile):
depthV = (x - Px) / cosA #depth of ray (length)
y = Py + (depthV * sinA) #y-co-ordinate of collision with vertical or y-axis
if mapping(x + dx, y) in game_map: #checking for walls/object
break #break if a wall is encountered
x = x + (dx * tile)
#For horizontal line on the grid map (mentioned in notes)
if sinA >= 0: #if it is positive (x-axis // horizontal axis)
y = Ym + tile
dy = 1
else: #for negative
y = Ym
dy = -1
for i in range (0, height, tile):
depthH = (y - Py) / sinA
x = Px + (depthH * cosA)
if mapping(x, y + dy) in game_map: #checking for wall/object
break #break if a wall is encountered
y = y + (dy * tile)
#Projection
if depthV < depthH: #picking the shorter distance
depth = depthV
else:
depth = depthH
depth = depth * math.cos(angle - half_angle) # To remove fish-eye effect, removes distorted edges of rectangles in map
obj_height = Est_Coeff / depth # Calculating height of the object/sprite that falls in our scope
brightness = 255 / (1 + depth * depth * 0.00001) # Used to give a contrast/saturation effect, the further our object is, it will become darker
colour = (brightness, brightness // 3, brightness // 4) # Applying the effect here, can be used later give the illusion
pygame.draw.rect(screen, colour, (ray * scale, h_height - obj_height // 2, scale, obj_height)) # Draw a rectangle for the each object in the scope
half_angle = half_angle + ray_angle
|
the-stack_106_26572 | #!/usr/bin/env python
#
# Copyright (c) 2009 Google Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""Does google-lint on c++ files.
The goal of this script is to identify places in the code that *may*
be in non-compliance with google style. It does not attempt to fix
up these problems -- the point is to educate. It does also not
attempt to find all problems, or to ensure that everything it does
find is legitimately a problem.
In particular, we can get very confused by /* and // inside strings!
We do a small hack, which is to ignore //'s with "'s after them on the
same line, but it is far from perfect (in either direction).
"""
import codecs
import copy
import getopt
import math # for log
import os
import re
import sre_compile
import string
import sys
import unicodedata
_USAGE = """
Syntax: cpplint.py [--verbose=#] [--output=vs7] [--filter=-x,+y,...]
[--counting=total|toplevel|detailed] [--root=subdir]
[--linelength=digits] [--headers=x,y,...]
<file> [file] ...
The style guidelines this tries to follow are those in
https://google-styleguide.googlecode.com/svn/trunk/cppguide.xml
Every problem is given a confidence score from 1-5, with 5 meaning we are
certain of the problem, and 1 meaning it could be a legitimate construct.
This will miss some errors, and is not a substitute for a code review.
To suppress false-positive errors of a certain category, add a
'NOLINT(category)' comment to the line. NOLINT or NOLINT(*)
suppresses errors of all categories on that line.
The files passed in will be linted; at least one file must be provided.
Default linted extensions are .cc, .cpp, .cu, .cuh and .h. Change the
extensions with the --extensions flag.
Flags:
output=vs7
By default, the output is formatted to ease emacs parsing. Visual Studio
compatible output (vs7) may also be used. Other formats are unsupported.
verbose=#
Specify a number 0-5 to restrict errors to certain verbosity levels.
filter=-x,+y,...
Specify a comma-separated list of category-filters to apply: only
error messages whose category names pass the filters will be printed.
(Category names are printed with the message and look like
"[whitespace/indent]".) Filters are evaluated left to right.
"-FOO" and "FOO" means "do not print categories that start with FOO".
"+FOO" means "do print categories that start with FOO".
Examples: --filter=-whitespace,+whitespace/braces
--filter=whitespace,runtime/printf,+runtime/printf_format
--filter=-,+build/include_what_you_use
To see a list of all the categories used in cpplint, pass no arg:
--filter=
counting=total|toplevel|detailed
The total number of errors found is always printed. If
'toplevel' is provided, then the count of errors in each of
the top-level categories like 'build' and 'whitespace' will
also be printed. If 'detailed' is provided, then a count
is provided for each category like 'build/class'.
root=subdir
The root directory used for deriving header guard CPP variable.
By default, the header guard CPP variable is calculated as the relative
path to the directory that contains .git, .hg, or .svn. When this flag
is specified, the relative path is calculated from the specified
directory. If the specified directory does not exist, this flag is
ignored.
Examples:
Assuming that src/.git exists, the header guard CPP variables for
src/chrome/browser/ui/browser.h are:
No flag => CHROME_BROWSER_UI_BROWSER_H_
--root=chrome => BROWSER_UI_BROWSER_H_
--root=chrome/browser => UI_BROWSER_H_
linelength=digits
This is the allowed line length for the project. The default value is
80 characters.
Examples:
--linelength=120
extensions=extension,extension,...
The allowed file extensions that cpplint will check
Examples:
--extensions=hpp,cpp
headers=x,y,...
The header extensions that cpplint will treat as .h in checks. Values are
automatically added to --extensions list.
Examples:
--headers=hpp,hxx
--headers=hpp
cpplint.py supports per-directory configurations specified in CPPLINT.cfg
files. CPPLINT.cfg file can contain a number of key=value pairs.
Currently the following options are supported:
set noparent
filter=+filter1,-filter2,...
exclude_files=regex
linelength=80
root=subdir
headers=x,y,...
"set noparent" option prevents cpplint from traversing directory tree
upwards looking for more .cfg files in parent directories. This option
is usually placed in the top-level project directory.
The "filter" option is similar in function to --filter flag. It specifies
message filters in addition to the |_DEFAULT_FILTERS| and those specified
through --filter command-line flag.
"exclude_files" allows to specify a regular expression to be matched against
a file name. If the expression matches, the file is skipped and not run
through liner.
"linelength" allows to specify the allowed line length for the project.
The "root" option is similar in function to the --root flag (see example
above).
The "headers" option is similar in function to the --headers flag
(see example above).
CPPLINT.cfg has an effect on files in the same directory and all
sub-directories, unless overridden by a nested configuration file.
Example file:
filter=-build/include_order,+build/include_alpha
exclude_files=.*\.cc
The above example disables build/include_order warning and enables
build/include_alpha as well as excludes all .cc from being
processed by linter, in the current directory (where the .cfg
file is located) and all sub-directories.
"""
# We categorize each error message we print. Here are the categories.
# We want an explicit list so we can list them all in cpplint --filter=.
# If you add a new error message with a new category, add it to the list
# here! cpplint_unittest.py should tell you if you forget to do this.
_ERROR_CATEGORIES = [
'build/class',
'build/c++11',
'build/c++14',
'build/c++tr1',
'build/deprecated',
'build/endif_comment',
'build/explicit_make_pair',
'build/forward_decl',
'build/header_guard',
'build/include',
'build/include_alpha',
'build/include_order',
'build/include_what_you_use',
'build/namespaces',
'build/printf_format',
'build/storage_class',
'legal/copyright',
'readability/alt_tokens',
'readability/braces',
'readability/casting',
'readability/check',
'readability/constructors',
'readability/fn_size',
'readability/inheritance',
'readability/multiline_comment',
'readability/multiline_string',
'readability/namespace',
'readability/nolint',
'readability/nul',
'readability/strings',
'readability/todo',
'readability/utf8',
'runtime/arrays',
'runtime/casting',
'runtime/explicit',
'runtime/int',
'runtime/init',
'runtime/invalid_increment',
'runtime/member_string_references',
'runtime/memset',
'runtime/indentation_namespace',
'runtime/operator',
'runtime/printf',
'runtime/printf_format',
'runtime/references',
'runtime/string',
'runtime/threadsafe_fn',
'runtime/vlog',
'whitespace/blank_line',
'whitespace/braces',
'whitespace/comma',
'whitespace/comments',
'whitespace/empty_conditional_body',
'whitespace/empty_if_body',
'whitespace/empty_loop_body',
'whitespace/end_of_line',
'whitespace/ending_newline',
'whitespace/forcolon',
'whitespace/indent',
'whitespace/line_length',
'whitespace/newline',
'whitespace/operators',
'whitespace/parens',
'whitespace/semicolon',
'whitespace/tab',
'whitespace/todo',
]
# These error categories are no longer enforced by cpplint, but for backwards-
# compatibility they may still appear in NOLINT comments.
_LEGACY_ERROR_CATEGORIES = [
'readability/streams',
'readability/function',
]
# The default state of the category filter. This is overridden by the --filter=
# flag. By default all errors are on, so only add here categories that should be
# off by default (i.e., categories that must be enabled by the --filter= flags).
# All entries here should start with a '-' or '+', as in the --filter= flag.
_DEFAULT_FILTERS = ['-build/include_alpha']
# The default list of categories suppressed for C (not C++) files.
_DEFAULT_C_SUPPRESSED_CATEGORIES = [
'readability/casting',
]
# The default list of categories suppressed for Linux Kernel files.
_DEFAULT_KERNEL_SUPPRESSED_CATEGORIES = [
'whitespace/tab',
]
# We used to check for high-bit characters, but after much discussion we
# decided those were OK, as long as they were in UTF-8 and didn't represent
# hard-coded international strings, which belong in a separate i18n file.
# C++ headers
_CPP_HEADERS = frozenset([
# Legacy
'algobase.h',
'algo.h',
'alloc.h',
'builtinbuf.h',
'bvector.h',
'complex.h',
'defalloc.h',
'deque.h',
'editbuf.h',
'fstream.h',
'function.h',
'hash_map',
'hash_map.h',
'hash_set',
'hash_set.h',
'hashtable.h',
'heap.h',
'indstream.h',
'iomanip.h',
'iostream.h',
'istream.h',
'iterator.h',
'list.h',
'map.h',
'multimap.h',
'multiset.h',
'ostream.h',
'pair.h',
'parsestream.h',
'pfstream.h',
'procbuf.h',
'pthread_alloc',
'pthread_alloc.h',
'rope',
'rope.h',
'ropeimpl.h',
'set.h',
'slist',
'slist.h',
'stack.h',
'stdiostream.h',
'stl_alloc.h',
'stl_relops.h',
'streambuf.h',
'stream.h',
'strfile.h',
'strstream.h',
'tempbuf.h',
'tree.h',
'type_traits.h',
'vector.h',
# 17.6.1.2 C++ library headers
'algorithm',
'array',
'atomic',
'bitset',
'chrono',
'codecvt',
'complex',
'condition_variable',
'deque',
'exception',
'forward_list',
'fstream',
'functional',
'future',
'initializer_list',
'iomanip',
'ios',
'iosfwd',
'iostream',
'istream',
'iterator',
'limits',
'list',
'locale',
'map',
'memory',
'mutex',
'new',
'numeric',
'ostream',
'queue',
'random',
'ratio',
'regex',
'scoped_allocator',
'set',
'sstream',
'stack',
'stdexcept',
'streambuf',
'string',
'strstream',
'system_error',
'thread',
'tuple',
'typeindex',
'typeinfo',
'type_traits',
'unordered_map',
'unordered_set',
'utility',
'valarray',
'vector',
# 17.6.1.2 C++ headers for C library facilities
'cassert',
'ccomplex',
'cctype',
'cerrno',
'cfenv',
'cfloat',
'cinttypes',
'ciso646',
'climits',
'clocale',
'cmath',
'csetjmp',
'csignal',
'cstdalign',
'cstdarg',
'cstdbool',
'cstddef',
'cstdint',
'cstdio',
'cstdlib',
'cstring',
'ctgmath',
'ctime',
'cuchar',
'cwchar',
'cwctype',
])
# Type names
_TYPES = re.compile(
r'^(?:'
# [dcl.type.simple]
r'(char(16_t|32_t)?)|wchar_t|'
r'bool|short|int|long|signed|unsigned|float|double|'
# [support.types]
r'(ptrdiff_t|size_t|max_align_t|nullptr_t)|'
# [cstdint.syn]
r'(u?int(_fast|_least)?(8|16|32|64)_t)|'
r'(u?int(max|ptr)_t)|'
r')$')
# These headers are excluded from [build/include] and [build/include_order]
# checks:
# - Anything not following google file name conventions (containing an
# uppercase character, such as Python.h or nsStringAPI.h, for example).
# - Lua headers.
_THIRD_PARTY_HEADERS_PATTERN = re.compile(
r'^(?:[^/]*[A-Z][^/]*\.h|lua\.h|lauxlib\.h|lualib\.h)$')
# Pattern for matching FileInfo.BaseName() against test file name
_TEST_FILE_SUFFIX = r'(_test|_unittest|_regtest)$'
# Pattern that matches only complete whitespace, possibly across multiple lines.
_EMPTY_CONDITIONAL_BODY_PATTERN = re.compile(r'^\s*$', re.DOTALL)
# Assertion macros. These are defined in base/logging.h and
# testing/base/public/gunit.h.
_CHECK_MACROS = [
'DCHECK', 'CHECK',
'EXPECT_TRUE', 'ASSERT_TRUE',
'EXPECT_FALSE', 'ASSERT_FALSE',
]
# Replacement macros for CHECK/DCHECK/EXPECT_TRUE/EXPECT_FALSE
_CHECK_REPLACEMENT = dict([(m, {}) for m in _CHECK_MACROS])
for op, replacement in [('==', 'EQ'), ('!=', 'NE'),
('>=', 'GE'), ('>', 'GT'),
('<=', 'LE'), ('<', 'LT')]:
_CHECK_REPLACEMENT['DCHECK'][op] = 'DCHECK_%s' % replacement
_CHECK_REPLACEMENT['CHECK'][op] = 'CHECK_%s' % replacement
_CHECK_REPLACEMENT['EXPECT_TRUE'][op] = 'EXPECT_%s' % replacement
_CHECK_REPLACEMENT['ASSERT_TRUE'][op] = 'ASSERT_%s' % replacement
for op, inv_replacement in [('==', 'NE'), ('!=', 'EQ'),
('>=', 'LT'), ('>', 'LE'),
('<=', 'GT'), ('<', 'GE')]:
_CHECK_REPLACEMENT['EXPECT_FALSE'][op] = 'EXPECT_%s' % inv_replacement
_CHECK_REPLACEMENT['ASSERT_FALSE'][op] = 'ASSERT_%s' % inv_replacement
# Alternative tokens and their replacements. For full list, see section 2.5
# Alternative tokens [lex.digraph] in the C++ standard.
#
# Digraphs (such as '%:') are not included here since it's a mess to
# match those on a word boundary.
_ALT_TOKEN_REPLACEMENT = {
'and': '&&',
'bitor': '|',
'or': '||',
'xor': '^',
'compl': '~',
'bitand': '&',
'and_eq': '&=',
'or_eq': '|=',
'xor_eq': '^=',
'not': '!',
'not_eq': '!='
}
# Compile regular expression that matches all the above keywords. The "[ =()]"
# bit is meant to avoid matching these keywords outside of boolean expressions.
#
# False positives include C-style multi-line comments and multi-line strings
# but those have always been troublesome for cpplint.
_ALT_TOKEN_REPLACEMENT_PATTERN = re.compile(
r'[ =()](' + ('|'.join(_ALT_TOKEN_REPLACEMENT.keys())) + r')(?=[ (]|$)')
# These constants define types of headers for use with
# _IncludeState.CheckNextIncludeOrder().
_C_SYS_HEADER = 1
_CPP_SYS_HEADER = 2
_LIKELY_MY_HEADER = 3
_POSSIBLE_MY_HEADER = 4
_OTHER_HEADER = 5
# These constants define the current inline assembly state
_NO_ASM = 0 # Outside of inline assembly block
_INSIDE_ASM = 1 # Inside inline assembly block
_END_ASM = 2 # Last line of inline assembly block
_BLOCK_ASM = 3 # The whole block is an inline assembly block
# Match start of assembly blocks
_MATCH_ASM = re.compile(r'^\s*(?:asm|_asm|__asm|__asm__)'
r'(?:\s+(volatile|__volatile__))?'
r'\s*[{(]')
# Match strings that indicate we're working on a C (not C++) file.
_SEARCH_C_FILE = re.compile(r'\b(?:LINT_C_FILE|'
r'vim?:\s*.*(\s*|:)filetype=c(\s*|:|$))')
# Match string that indicates we're working on a Linux Kernel file.
_SEARCH_KERNEL_FILE = re.compile(r'\b(?:LINT_KERNEL_FILE)')
_regexp_compile_cache = {}
# {str, set(int)}: a map from error categories to sets of linenumbers
# on which those errors are expected and should be suppressed.
_error_suppressions = {}
# The root directory used for deriving header guard CPP variable.
# This is set by --root flag.
_root = None
# The allowed line length of files.
# This is set by --linelength flag.
_line_length = 80
# The allowed extensions for file names
# This is set by --extensions flag.
_valid_extensions = set(['c', 'cc', 'h', 'cpp', 'cu', 'cuh'])
# Treat all headers starting with 'h' equally: .h, .hpp, .hxx etc.
# This is set by --headers flag.
_hpp_headers = set(['h'])
# {str, bool}: a map from error categories to booleans which indicate if the
# category should be suppressed for every line.
_global_error_suppressions = {}
def ProcessHppHeadersOption(val):
global _hpp_headers
try:
_hpp_headers = set(val.split(','))
# Automatically append to extensions list so it does not have to be set 2 times
_valid_extensions.update(_hpp_headers)
except ValueError:
PrintUsage('Header extensions must be comma seperated list.')
def IsHeaderExtension(file_extension):
return file_extension in _hpp_headers
def ParseNolintSuppressions(filename, raw_line, linenum, error):
"""Updates the global list of line error-suppressions.
Parses any NOLINT comments on the current line, updating the global
error_suppressions store. Reports an error if the NOLINT comment
was malformed.
Args:
filename: str, the name of the input file.
raw_line: str, the line of input text, with comments.
linenum: int, the number of the current line.
error: function, an error handler.
"""
matched = Search(r'\bNOLINT(NEXTLINE)?\b(\([^)]+\))?', raw_line)
if matched:
if matched.group(1):
suppressed_line = linenum + 1
else:
suppressed_line = linenum
category = matched.group(2)
if category in (None, '(*)'): # => "suppress all"
_error_suppressions.setdefault(None, set()).add(suppressed_line)
else:
if category.startswith('(') and category.endswith(')'):
category = category[1:-1]
if category in _ERROR_CATEGORIES:
_error_suppressions.setdefault(category, set()).add(suppressed_line)
elif category not in _LEGACY_ERROR_CATEGORIES:
error(filename, linenum, 'readability/nolint', 5,
'Unknown NOLINT error category: %s' % category)
def ProcessGlobalSuppresions(lines):
"""Updates the list of global error suppressions.
Parses any lint directives in the file that have global effect.
Args:
lines: An array of strings, each representing a line of the file, with the
last element being empty if the file is terminated with a newline.
"""
for line in lines:
if _SEARCH_C_FILE.search(line):
for category in _DEFAULT_C_SUPPRESSED_CATEGORIES:
_global_error_suppressions[category] = True
if _SEARCH_KERNEL_FILE.search(line):
for category in _DEFAULT_KERNEL_SUPPRESSED_CATEGORIES:
_global_error_suppressions[category] = True
def ResetNolintSuppressions():
"""Resets the set of NOLINT suppressions to empty."""
_error_suppressions.clear()
_global_error_suppressions.clear()
def IsErrorSuppressedByNolint(category, linenum):
"""Returns true if the specified error category is suppressed on this line.
Consults the global error_suppressions map populated by
ParseNolintSuppressions/ProcessGlobalSuppresions/ResetNolintSuppressions.
Args:
category: str, the category of the error.
linenum: int, the current line number.
Returns:
bool, True iff the error should be suppressed due to a NOLINT comment or
global suppression.
"""
return (_global_error_suppressions.get(category, False) or
linenum in _error_suppressions.get(category, set()) or
linenum in _error_suppressions.get(None, set()))
def Match(pattern, s):
"""Matches the string with the pattern, caching the compiled regexp."""
# The regexp compilation caching is inlined in both Match and Search for
# performance reasons; factoring it out into a separate function turns out
# to be noticeably expensive.
if pattern not in _regexp_compile_cache:
_regexp_compile_cache[pattern] = sre_compile.compile(pattern)
return _regexp_compile_cache[pattern].match(s)
def ReplaceAll(pattern, rep, s):
"""Replaces instances of pattern in a string with a replacement.
The compiled regex is kept in a cache shared by Match and Search.
Args:
pattern: regex pattern
rep: replacement text
s: search string
Returns:
string with replacements made (or original string if no replacements)
"""
if pattern not in _regexp_compile_cache:
_regexp_compile_cache[pattern] = sre_compile.compile(pattern)
return _regexp_compile_cache[pattern].sub(rep, s)
def Search(pattern, s):
"""Searches the string for the pattern, caching the compiled regexp."""
if pattern not in _regexp_compile_cache:
_regexp_compile_cache[pattern] = sre_compile.compile(pattern)
return _regexp_compile_cache[pattern].search(s)
def _IsSourceExtension(s):
"""File extension (excluding dot) matches a source file extension."""
return s in ('c', 'cc', 'cpp', 'cxx')
class _IncludeState(object):
"""Tracks line numbers for includes, and the order in which includes appear.
include_list contains list of lists of (header, line number) pairs.
It's a lists of lists rather than just one flat list to make it
easier to update across preprocessor boundaries.
Call CheckNextIncludeOrder() once for each header in the file, passing
in the type constants defined above. Calls in an illegal order will
raise an _IncludeError with an appropriate error message.
"""
# self._section will move monotonically through this set. If it ever
# needs to move backwards, CheckNextIncludeOrder will raise an error.
_INITIAL_SECTION = 0
_MY_H_SECTION = 1
_C_SECTION = 2
_CPP_SECTION = 3
_OTHER_H_SECTION = 4
_TYPE_NAMES = {
_C_SYS_HEADER: 'C system header',
_CPP_SYS_HEADER: 'C++ system header',
_LIKELY_MY_HEADER: 'header this file implements',
_POSSIBLE_MY_HEADER: 'header this file may implement',
_OTHER_HEADER: 'other header',
}
_SECTION_NAMES = {
_INITIAL_SECTION: "... nothing. (This can't be an error.)",
_MY_H_SECTION: 'a header this file implements',
_C_SECTION: 'C system header',
_CPP_SECTION: 'C++ system header',
_OTHER_H_SECTION: 'other header',
}
def __init__(self):
self.include_list = [[]]
self.ResetSection('')
def FindHeader(self, header):
"""Check if a header has already been included.
Args:
header: header to check.
Returns:
Line number of previous occurrence, or -1 if the header has not
been seen before.
"""
for section_list in self.include_list:
for f in section_list:
if f[0] == header:
return f[1]
return -1
def ResetSection(self, directive):
"""Reset section checking for preprocessor directive.
Args:
directive: preprocessor directive (e.g. "if", "else").
"""
# The name of the current section.
self._section = self._INITIAL_SECTION
# The path of last found header.
self._last_header = ''
# Update list of includes. Note that we never pop from the
# include list.
if directive in ('if', 'ifdef', 'ifndef'):
self.include_list.append([])
elif directive in ('else', 'elif'):
self.include_list[-1] = []
def SetLastHeader(self, header_path):
self._last_header = header_path
def CanonicalizeAlphabeticalOrder(self, header_path):
"""Returns a path canonicalized for alphabetical comparison.
- replaces "-" with "_" so they both cmp the same.
- removes '-inl' since we don't require them to be after the main header.
- lowercase everything, just in case.
Args:
header_path: Path to be canonicalized.
Returns:
Canonicalized path.
"""
return header_path.replace('-inl.h', '.h').replace('-', '_').lower()
def IsInAlphabeticalOrder(self, clean_lines, linenum, header_path):
"""Check if a header is in alphabetical order with the previous header.
Args:
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
header_path: Canonicalized header to be checked.
Returns:
Returns true if the header is in alphabetical order.
"""
# If previous section is different from current section, _last_header will
# be reset to empty string, so it's always less than current header.
#
# If previous line was a blank line, assume that the headers are
# intentionally sorted the way they are.
if (self._last_header > header_path and
Match(r'^\s*#\s*include\b', clean_lines.elided[linenum - 1])):
return False
return True
def CheckNextIncludeOrder(self, header_type):
"""Returns a non-empty error message if the next header is out of order.
This function also updates the internal state to be ready to check
the next include.
Args:
header_type: One of the _XXX_HEADER constants defined above.
Returns:
The empty string if the header is in the right order, or an
error message describing what's wrong.
"""
error_message = ('Found %s after %s' %
(self._TYPE_NAMES[header_type],
self._SECTION_NAMES[self._section]))
last_section = self._section
if header_type == _C_SYS_HEADER:
if self._section <= self._C_SECTION:
self._section = self._C_SECTION
else:
self._last_header = ''
return error_message
elif header_type == _CPP_SYS_HEADER:
if self._section <= self._CPP_SECTION:
self._section = self._CPP_SECTION
else:
self._last_header = ''
return error_message
elif header_type == _LIKELY_MY_HEADER:
if self._section <= self._MY_H_SECTION:
self._section = self._MY_H_SECTION
else:
self._section = self._OTHER_H_SECTION
elif header_type == _POSSIBLE_MY_HEADER:
if self._section <= self._MY_H_SECTION:
self._section = self._MY_H_SECTION
else:
# This will always be the fallback because we're not sure
# enough that the header is associated with this file.
self._section = self._OTHER_H_SECTION
else:
assert header_type == _OTHER_HEADER
self._section = self._OTHER_H_SECTION
if last_section != self._section:
self._last_header = ''
return ''
class _CppLintState(object):
"""Maintains module-wide state.."""
def __init__(self):
self.verbose_level = 1 # global setting.
self.error_count = 0 # global count of reported errors
# filters to apply when emitting error messages
self.filters = _DEFAULT_FILTERS[:]
# backup of filter list. Used to restore the state after each file.
self._filters_backup = self.filters[:]
self.counting = 'total' # In what way are we counting errors?
self.errors_by_category = {} # string to int dict storing error counts
# output format:
# "emacs" - format that emacs can parse (default)
# "vs7" - format that Microsoft Visual Studio 7 can parse
self.output_format = 'emacs'
def SetOutputFormat(self, output_format):
"""Sets the output format for errors."""
self.output_format = output_format
def SetVerboseLevel(self, level):
"""Sets the module's verbosity, and returns the previous setting."""
last_verbose_level = self.verbose_level
self.verbose_level = level
return last_verbose_level
def SetCountingStyle(self, counting_style):
"""Sets the module's counting options."""
self.counting = counting_style
def SetFilters(self, filters):
"""Sets the error-message filters.
These filters are applied when deciding whether to emit a given
error message.
Args:
filters: A string of comma-separated filters (eg "+whitespace/indent").
Each filter should start with + or -; else we die.
Raises:
ValueError: The comma-separated filters did not all start with '+' or '-'.
E.g. "-,+whitespace,-whitespace/indent,whitespace/badfilter"
"""
# Default filters always have less priority than the flag ones.
self.filters = _DEFAULT_FILTERS[:]
self.AddFilters(filters)
def AddFilters(self, filters):
""" Adds more filters to the existing list of error-message filters. """
for filt in filters.split(','):
clean_filt = filt.strip()
if clean_filt:
self.filters.append(clean_filt)
for filt in self.filters:
if not (filt.startswith('+') or filt.startswith('-')):
raise ValueError('Every filter in --filters must start with + or -'
' (%s does not)' % filt)
def BackupFilters(self):
""" Saves the current filter list to backup storage."""
self._filters_backup = self.filters[:]
def RestoreFilters(self):
""" Restores filters previously backed up."""
self.filters = self._filters_backup[:]
def ResetErrorCounts(self):
"""Sets the module's error statistic back to zero."""
self.error_count = 0
self.errors_by_category = {}
def IncrementErrorCount(self, category):
"""Bumps the module's error statistic."""
self.error_count += 1
if self.counting in ('toplevel', 'detailed'):
if self.counting != 'detailed':
category = category.split('/')[0]
if category not in self.errors_by_category:
self.errors_by_category[category] = 0
self.errors_by_category[category] += 1
def PrintErrorCounts(self):
"""Print a summary of errors by category, and the total."""
for category, count in self.errors_by_category.iteritems():
sys.stderr.write('Category \'%s\' errors found: %d\n' %
(category, count))
sys.stdout.write('Total errors found: %d\n' % self.error_count)
_cpplint_state = _CppLintState()
def _OutputFormat():
"""Gets the module's output format."""
return _cpplint_state.output_format
def _SetOutputFormat(output_format):
"""Sets the module's output format."""
_cpplint_state.SetOutputFormat(output_format)
def _VerboseLevel():
"""Returns the module's verbosity setting."""
return _cpplint_state.verbose_level
def _SetVerboseLevel(level):
"""Sets the module's verbosity, and returns the previous setting."""
return _cpplint_state.SetVerboseLevel(level)
def _SetCountingStyle(level):
"""Sets the module's counting options."""
_cpplint_state.SetCountingStyle(level)
def _Filters():
"""Returns the module's list of output filters, as a list."""
return _cpplint_state.filters
def _SetFilters(filters):
"""Sets the module's error-message filters.
These filters are applied when deciding whether to emit a given
error message.
Args:
filters: A string of comma-separated filters (eg "whitespace/indent").
Each filter should start with + or -; else we die.
"""
_cpplint_state.SetFilters(filters)
def _AddFilters(filters):
"""Adds more filter overrides.
Unlike _SetFilters, this function does not reset the current list of filters
available.
Args:
filters: A string of comma-separated filters (eg "whitespace/indent").
Each filter should start with + or -; else we die.
"""
_cpplint_state.AddFilters(filters)
def _BackupFilters():
""" Saves the current filter list to backup storage."""
_cpplint_state.BackupFilters()
def _RestoreFilters():
""" Restores filters previously backed up."""
_cpplint_state.RestoreFilters()
class _FunctionState(object):
"""Tracks current function name and the number of lines in its body."""
_NORMAL_TRIGGER = 250 # for --v=0, 500 for --v=1, etc.
_TEST_TRIGGER = 400 # about 50% more than _NORMAL_TRIGGER.
def __init__(self):
self.in_a_function = False
self.lines_in_function = 0
self.current_function = ''
def Begin(self, function_name):
"""Start analyzing function body.
Args:
function_name: The name of the function being tracked.
"""
self.in_a_function = True
self.lines_in_function = 0
self.current_function = function_name
def Count(self):
"""Count line in current function body."""
if self.in_a_function:
self.lines_in_function += 1
def Check(self, error, filename, linenum):
"""Report if too many lines in function body.
Args:
error: The function to call with any errors found.
filename: The name of the current file.
linenum: The number of the line to check.
"""
if not self.in_a_function:
return
if Match(r'T(EST|est)', self.current_function):
base_trigger = self._TEST_TRIGGER
else:
base_trigger = self._NORMAL_TRIGGER
trigger = base_trigger * 2**_VerboseLevel()
if self.lines_in_function > trigger:
error_level = int(math.log(self.lines_in_function / base_trigger, 2))
# 50 => 0, 100 => 1, 200 => 2, 400 => 3, 800 => 4, 1600 => 5, ...
if error_level > 5:
error_level = 5
error(filename, linenum, 'readability/fn_size', error_level,
'Small and focused functions are preferred:'
' %s has %d non-comment lines'
' (error triggered by exceeding %d lines).' % (
self.current_function, self.lines_in_function, trigger))
def End(self):
"""Stop analyzing function body."""
self.in_a_function = False
class _IncludeError(Exception):
"""Indicates a problem with the include order in a file."""
pass
class FileInfo(object):
"""Provides utility functions for filenames.
FileInfo provides easy access to the components of a file's path
relative to the project root.
"""
def __init__(self, filename):
self._filename = filename
def FullName(self):
"""Make Windows paths like Unix."""
return os.path.abspath(self._filename).replace('\\', '/')
def RepositoryName(self):
"""FullName after removing the local path to the repository.
If we have a real absolute path name here we can try to do something smart:
detecting the root of the checkout and truncating /path/to/checkout from
the name so that we get header guards that don't include things like
"C:\Documents and Settings\..." or "/home/username/..." in them and thus
people on different computers who have checked the source out to different
locations won't see bogus errors.
"""
fullname = self.FullName()
if os.path.exists(fullname):
project_dir = os.path.dirname(fullname)
if os.path.exists(os.path.join(project_dir, ".svn")):
# If there's a .svn file in the current directory, we recursively look
# up the directory tree for the top of the SVN checkout
root_dir = project_dir
one_up_dir = os.path.dirname(root_dir)
while os.path.exists(os.path.join(one_up_dir, ".svn")):
root_dir = os.path.dirname(root_dir)
one_up_dir = os.path.dirname(one_up_dir)
prefix = os.path.commonprefix([root_dir, project_dir])
return fullname[len(prefix) + 1:]
# Not SVN <= 1.6? Try to find a git, hg, or svn top level directory by
# searching up from the current path.
root_dir = current_dir = os.path.dirname(fullname)
while current_dir != os.path.dirname(current_dir):
if (os.path.exists(os.path.join(current_dir, ".git")) or
os.path.exists(os.path.join(current_dir, ".hg")) or
os.path.exists(os.path.join(current_dir, ".svn"))):
root_dir = current_dir
current_dir = os.path.dirname(current_dir)
if (os.path.exists(os.path.join(root_dir, ".git")) or
os.path.exists(os.path.join(root_dir, ".hg")) or
os.path.exists(os.path.join(root_dir, ".svn"))):
prefix = os.path.commonprefix([root_dir, project_dir])
return fullname[len(prefix) + 1:]
# Don't know what to do; header guard warnings may be wrong...
return fullname
def Split(self):
"""Splits the file into the directory, basename, and extension.
For 'chrome/browser/browser.cc', Split() would
return ('chrome/browser', 'browser', '.cc')
Returns:
A tuple of (directory, basename, extension).
"""
googlename = self.RepositoryName()
project, rest = os.path.split(googlename)
return (project,) + os.path.splitext(rest)
def BaseName(self):
"""File base name - text after the final slash, before the final period."""
return self.Split()[1]
def Extension(self):
"""File extension - text following the final period."""
return self.Split()[2]
def NoExtension(self):
"""File has no source file extension."""
return '/'.join(self.Split()[0:2])
def IsSource(self):
"""File has a source file extension."""
return _IsSourceExtension(self.Extension()[1:])
def _ShouldPrintError(category, confidence, linenum):
"""If confidence >= verbose, category passes filter and is not suppressed."""
# There are three ways we might decide not to print an error message:
# a "NOLINT(category)" comment appears in the source,
# the verbosity level isn't high enough, or the filters filter it out.
if IsErrorSuppressedByNolint(category, linenum):
return False
if confidence < _cpplint_state.verbose_level:
return False
is_filtered = False
for one_filter in _Filters():
if one_filter.startswith('-'):
if category.startswith(one_filter[1:]):
is_filtered = True
elif one_filter.startswith('+'):
if category.startswith(one_filter[1:]):
is_filtered = False
else:
assert False # should have been checked for in SetFilter.
if is_filtered:
return False
return True
def Error(filename, linenum, category, confidence, message):
"""Logs the fact we've found a lint error.
We log where the error was found, and also our confidence in the error,
that is, how certain we are this is a legitimate style regression, and
not a misidentification or a use that's sometimes justified.
False positives can be suppressed by the use of
"cpplint(category)" comments on the offending line. These are
parsed into _error_suppressions.
Args:
filename: The name of the file containing the error.
linenum: The number of the line containing the error.
category: A string used to describe the "category" this bug
falls under: "whitespace", say, or "runtime". Categories
may have a hierarchy separated by slashes: "whitespace/indent".
confidence: A number from 1-5 representing a confidence score for
the error, with 5 meaning that we are certain of the problem,
and 1 meaning that it could be a legitimate construct.
message: The error message.
"""
if _ShouldPrintError(category, confidence, linenum):
_cpplint_state.IncrementErrorCount(category)
if _cpplint_state.output_format == 'vs7':
sys.stderr.write('%s(%s): %s [%s] [%d]\n' % (
filename, linenum, message, category, confidence))
elif _cpplint_state.output_format == 'eclipse':
sys.stderr.write('%s:%s: warning: %s [%s] [%d]\n' % (
filename, linenum, message, category, confidence))
else:
sys.stderr.write('%s:%s: %s [%s] [%d]\n' % (
filename, linenum, message, category, confidence))
# Matches standard C++ escape sequences per 2.13.2.3 of the C++ standard.
_RE_PATTERN_CLEANSE_LINE_ESCAPES = re.compile(
r'\\([abfnrtv?"\\\']|\d+|x[0-9a-fA-F]+)')
# Match a single C style comment on the same line.
_RE_PATTERN_C_COMMENTS = r'/\*(?:[^*]|\*(?!/))*\*/'
# Matches multi-line C style comments.
# This RE is a little bit more complicated than one might expect, because we
# have to take care of space removals tools so we can handle comments inside
# statements better.
# The current rule is: We only clear spaces from both sides when we're at the
# end of the line. Otherwise, we try to remove spaces from the right side,
# if this doesn't work we try on left side but only if there's a non-character
# on the right.
_RE_PATTERN_CLEANSE_LINE_C_COMMENTS = re.compile(
r'(\s*' + _RE_PATTERN_C_COMMENTS + r'\s*$|' +
_RE_PATTERN_C_COMMENTS + r'\s+|' +
r'\s+' + _RE_PATTERN_C_COMMENTS + r'(?=\W)|' +
_RE_PATTERN_C_COMMENTS + r')')
def IsCppString(line):
"""Does line terminate so, that the next symbol is in string constant.
This function does not consider single-line nor multi-line comments.
Args:
line: is a partial line of code starting from the 0..n.
Returns:
True, if next character appended to 'line' is inside a
string constant.
"""
line = line.replace(r'\\', 'XX') # after this, \\" does not match to \"
return ((line.count('"') - line.count(r'\"') - line.count("'\"'")) & 1) == 1
def CleanseRawStrings(raw_lines):
"""Removes C++11 raw strings from lines.
Before:
static const char kData[] = R"(
multi-line string
)";
After:
static const char kData[] = ""
(replaced by blank line)
"";
Args:
raw_lines: list of raw lines.
Returns:
list of lines with C++11 raw strings replaced by empty strings.
"""
delimiter = None
lines_without_raw_strings = []
for line in raw_lines:
if delimiter:
# Inside a raw string, look for the end
end = line.find(delimiter)
if end >= 0:
# Found the end of the string, match leading space for this
# line and resume copying the original lines, and also insert
# a "" on the last line.
leading_space = Match(r'^(\s*)\S', line)
line = leading_space.group(1) + '""' + line[end + len(delimiter):]
delimiter = None
else:
# Haven't found the end yet, append a blank line.
line = '""'
# Look for beginning of a raw string, and replace them with
# empty strings. This is done in a loop to handle multiple raw
# strings on the same line.
while delimiter is None:
# Look for beginning of a raw string.
# See 2.14.15 [lex.string] for syntax.
#
# Once we have matched a raw string, we check the prefix of the
# line to make sure that the line is not part of a single line
# comment. It's done this way because we remove raw strings
# before removing comments as opposed to removing comments
# before removing raw strings. This is because there are some
# cpplint checks that requires the comments to be preserved, but
# we don't want to check comments that are inside raw strings.
matched = Match(r'^(.*?)\b(?:R|u8R|uR|UR|LR)"([^\s\\()]*)\((.*)$', line)
if (matched and
not Match(r'^([^\'"]|\'(\\.|[^\'])*\'|"(\\.|[^"])*")*//',
matched.group(1))):
delimiter = ')' + matched.group(2) + '"'
end = matched.group(3).find(delimiter)
if end >= 0:
# Raw string ended on same line
line = (matched.group(1) + '""' +
matched.group(3)[end + len(delimiter):])
delimiter = None
else:
# Start of a multi-line raw string
line = matched.group(1) + '""'
else:
break
lines_without_raw_strings.append(line)
# TODO(unknown): if delimiter is not None here, we might want to
# emit a warning for unterminated string.
return lines_without_raw_strings
def FindNextMultiLineCommentStart(lines, lineix):
"""Find the beginning marker for a multiline comment."""
while lineix < len(lines):
if lines[lineix].strip().startswith('/*'):
# Only return this marker if the comment goes beyond this line
if lines[lineix].strip().find('*/', 2) < 0:
return lineix
lineix += 1
return len(lines)
def FindNextMultiLineCommentEnd(lines, lineix):
"""We are inside a comment, find the end marker."""
while lineix < len(lines):
if lines[lineix].strip().endswith('*/'):
return lineix
lineix += 1
return len(lines)
def RemoveMultiLineCommentsFromRange(lines, begin, end):
"""Clears a range of lines for multi-line comments."""
# Having // dummy comments makes the lines non-empty, so we will not get
# unnecessary blank line warnings later in the code.
for i in range(begin, end):
lines[i] = '/**/'
def RemoveMultiLineComments(filename, lines, error):
"""Removes multiline (c-style) comments from lines."""
lineix = 0
while lineix < len(lines):
lineix_begin = FindNextMultiLineCommentStart(lines, lineix)
if lineix_begin >= len(lines):
return
lineix_end = FindNextMultiLineCommentEnd(lines, lineix_begin)
if lineix_end >= len(lines):
error(filename, lineix_begin + 1, 'readability/multiline_comment', 5,
'Could not find end of multi-line comment')
return
RemoveMultiLineCommentsFromRange(lines, lineix_begin, lineix_end + 1)
lineix = lineix_end + 1
def CleanseComments(line):
"""Removes //-comments and single-line C-style /* */ comments.
Args:
line: A line of C++ source.
Returns:
The line with single-line comments removed.
"""
commentpos = line.find('//')
if commentpos != -1 and not IsCppString(line[:commentpos]):
line = line[:commentpos].rstrip()
# get rid of /* ... */
return _RE_PATTERN_CLEANSE_LINE_C_COMMENTS.sub('', line)
class CleansedLines(object):
"""Holds 4 copies of all lines with different preprocessing applied to them.
1) elided member contains lines without strings and comments.
2) lines member contains lines without comments.
3) raw_lines member contains all the lines without processing.
4) lines_without_raw_strings member is same as raw_lines, but with C++11 raw
strings removed.
All these members are of <type 'list'>, and of the same length.
"""
def __init__(self, lines):
self.elided = []
self.lines = []
self.raw_lines = lines
self.num_lines = len(lines)
self.lines_without_raw_strings = CleanseRawStrings(lines)
for linenum in range(len(self.lines_without_raw_strings)):
self.lines.append(CleanseComments(
self.lines_without_raw_strings[linenum]))
elided = self._CollapseStrings(self.lines_without_raw_strings[linenum])
self.elided.append(CleanseComments(elided))
def NumLines(self):
"""Returns the number of lines represented."""
return self.num_lines
@staticmethod
def _CollapseStrings(elided):
"""Collapses strings and chars on a line to simple "" or '' blocks.
We nix strings first so we're not fooled by text like '"http://"'
Args:
elided: The line being processed.
Returns:
The line with collapsed strings.
"""
if _RE_PATTERN_INCLUDE.match(elided):
return elided
# Remove escaped characters first to make quote/single quote collapsing
# basic. Things that look like escaped characters shouldn't occur
# outside of strings and chars.
elided = _RE_PATTERN_CLEANSE_LINE_ESCAPES.sub('', elided)
# Replace quoted strings and digit separators. Both single quotes
# and double quotes are processed in the same loop, otherwise
# nested quotes wouldn't work.
collapsed = ''
while True:
# Find the first quote character
match = Match(r'^([^\'"]*)([\'"])(.*)$', elided)
if not match:
collapsed += elided
break
head, quote, tail = match.groups()
if quote == '"':
# Collapse double quoted strings
second_quote = tail.find('"')
if second_quote >= 0:
collapsed += head + '""'
elided = tail[second_quote + 1:]
else:
# Unmatched double quote, don't bother processing the rest
# of the line since this is probably a multiline string.
collapsed += elided
break
else:
# Found single quote, check nearby text to eliminate digit separators.
#
# There is no special handling for floating point here, because
# the integer/fractional/exponent parts would all be parsed
# correctly as long as there are digits on both sides of the
# separator. So we are fine as long as we don't see something
# like "0.'3" (gcc 4.9.0 will not allow this literal).
if Search(r'\b(?:0[bBxX]?|[1-9])[0-9a-fA-F]*$', head):
match_literal = Match(r'^((?:\'?[0-9a-zA-Z_])*)(.*)$', "'" + tail)
collapsed += head + match_literal.group(1).replace("'", '')
elided = match_literal.group(2)
else:
second_quote = tail.find('\'')
if second_quote >= 0:
collapsed += head + "''"
elided = tail[second_quote + 1:]
else:
# Unmatched single quote
collapsed += elided
break
return collapsed
def FindEndOfExpressionInLine(line, startpos, stack):
"""Find the position just after the end of current parenthesized expression.
Args:
line: a CleansedLines line.
startpos: start searching at this position.
stack: nesting stack at startpos.
Returns:
On finding matching end: (index just after matching end, None)
On finding an unclosed expression: (-1, None)
Otherwise: (-1, new stack at end of this line)
"""
for i in xrange(startpos, len(line)):
char = line[i]
if char in '([{':
# Found start of parenthesized expression, push to expression stack
stack.append(char)
elif char == '<':
# Found potential start of template argument list
if i > 0 and line[i - 1] == '<':
# Left shift operator
if stack and stack[-1] == '<':
stack.pop()
if not stack:
return (-1, None)
elif i > 0 and Search(r'\boperator\s*$', line[0:i]):
# operator<, don't add to stack
continue
else:
# Tentative start of template argument list
stack.append('<')
elif char in ')]}':
# Found end of parenthesized expression.
#
# If we are currently expecting a matching '>', the pending '<'
# must have been an operator. Remove them from expression stack.
while stack and stack[-1] == '<':
stack.pop()
if not stack:
return (-1, None)
if ((stack[-1] == '(' and char == ')') or
(stack[-1] == '[' and char == ']') or
(stack[-1] == '{' and char == '}')):
stack.pop()
if not stack:
return (i + 1, None)
else:
# Mismatched parentheses
return (-1, None)
elif char == '>':
# Found potential end of template argument list.
# Ignore "->" and operator functions
if (i > 0 and
(line[i - 1] == '-' or Search(r'\boperator\s*$', line[0:i - 1]))):
continue
# Pop the stack if there is a matching '<'. Otherwise, ignore
# this '>' since it must be an operator.
if stack:
if stack[-1] == '<':
stack.pop()
if not stack:
return (i + 1, None)
elif char == ';':
# Found something that look like end of statements. If we are currently
# expecting a '>', the matching '<' must have been an operator, since
# template argument list should not contain statements.
while stack and stack[-1] == '<':
stack.pop()
if not stack:
return (-1, None)
# Did not find end of expression or unbalanced parentheses on this line
return (-1, stack)
def CloseExpression(clean_lines, linenum, pos):
"""If input points to ( or { or [ or <, finds the position that closes it.
If lines[linenum][pos] points to a '(' or '{' or '[' or '<', finds the
linenum/pos that correspond to the closing of the expression.
TODO(unknown): cpplint spends a fair bit of time matching parentheses.
Ideally we would want to index all opening and closing parentheses once
and have CloseExpression be just a simple lookup, but due to preprocessor
tricks, this is not so easy.
Args:
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
pos: A position on the line.
Returns:
A tuple (line, linenum, pos) pointer *past* the closing brace, or
(line, len(lines), -1) if we never find a close. Note we ignore
strings and comments when matching; and the line we return is the
'cleansed' line at linenum.
"""
line = clean_lines.elided[linenum]
if (line[pos] not in '({[<') or Match(r'<[<=]', line[pos:]):
return (line, clean_lines.NumLines(), -1)
# Check first line
(end_pos, stack) = FindEndOfExpressionInLine(line, pos, [])
if end_pos > -1:
return (line, linenum, end_pos)
# Continue scanning forward
while stack and linenum < clean_lines.NumLines() - 1:
linenum += 1
line = clean_lines.elided[linenum]
(end_pos, stack) = FindEndOfExpressionInLine(line, 0, stack)
if end_pos > -1:
return (line, linenum, end_pos)
# Did not find end of expression before end of file, give up
return (line, clean_lines.NumLines(), -1)
def FindStartOfExpressionInLine(line, endpos, stack):
"""Find position at the matching start of current expression.
This is almost the reverse of FindEndOfExpressionInLine, but note
that the input position and returned position differs by 1.
Args:
line: a CleansedLines line.
endpos: start searching at this position.
stack: nesting stack at endpos.
Returns:
On finding matching start: (index at matching start, None)
On finding an unclosed expression: (-1, None)
Otherwise: (-1, new stack at beginning of this line)
"""
i = endpos
while i >= 0:
char = line[i]
if char in ')]}':
# Found end of expression, push to expression stack
stack.append(char)
elif char == '>':
# Found potential end of template argument list.
#
# Ignore it if it's a "->" or ">=" or "operator>"
if (i > 0 and
(line[i - 1] == '-' or
Match(r'\s>=\s', line[i - 1:]) or
Search(r'\boperator\s*$', line[0:i]))):
i -= 1
else:
stack.append('>')
elif char == '<':
# Found potential start of template argument list
if i > 0 and line[i - 1] == '<':
# Left shift operator
i -= 1
else:
# If there is a matching '>', we can pop the expression stack.
# Otherwise, ignore this '<' since it must be an operator.
if stack and stack[-1] == '>':
stack.pop()
if not stack:
return (i, None)
elif char in '([{':
# Found start of expression.
#
# If there are any unmatched '>' on the stack, they must be
# operators. Remove those.
while stack and stack[-1] == '>':
stack.pop()
if not stack:
return (-1, None)
if ((char == '(' and stack[-1] == ')') or
(char == '[' and stack[-1] == ']') or
(char == '{' and stack[-1] == '}')):
stack.pop()
if not stack:
return (i, None)
else:
# Mismatched parentheses
return (-1, None)
elif char == ';':
# Found something that look like end of statements. If we are currently
# expecting a '<', the matching '>' must have been an operator, since
# template argument list should not contain statements.
while stack and stack[-1] == '>':
stack.pop()
if not stack:
return (-1, None)
i -= 1
return (-1, stack)
def ReverseCloseExpression(clean_lines, linenum, pos):
"""If input points to ) or } or ] or >, finds the position that opens it.
If lines[linenum][pos] points to a ')' or '}' or ']' or '>', finds the
linenum/pos that correspond to the opening of the expression.
Args:
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
pos: A position on the line.
Returns:
A tuple (line, linenum, pos) pointer *at* the opening brace, or
(line, 0, -1) if we never find the matching opening brace. Note
we ignore strings and comments when matching; and the line we
return is the 'cleansed' line at linenum.
"""
line = clean_lines.elided[linenum]
if line[pos] not in ')}]>':
return (line, 0, -1)
# Check last line
(start_pos, stack) = FindStartOfExpressionInLine(line, pos, [])
if start_pos > -1:
return (line, linenum, start_pos)
# Continue scanning backward
while stack and linenum > 0:
linenum -= 1
line = clean_lines.elided[linenum]
(start_pos, stack) = FindStartOfExpressionInLine(line, len(line) - 1, stack)
if start_pos > -1:
return (line, linenum, start_pos)
# Did not find start of expression before beginning of file, give up
return (line, 0, -1)
def CheckForCopyright(filename, lines, error):
"""Logs an error if no Copyright message appears at the top of the file."""
# We'll say it should occur by line 10. Don't forget there's a
# dummy line at the front.
for line in xrange(1, min(len(lines), 11)):
if re.search(r'Copyright', lines[line], re.I): break
else: # means no copyright line was found
error(filename, 0, 'legal/copyright', 5,
'No copyright message found. '
'You should have a line: "Copyright [year] <Copyright Owner>"')
def GetIndentLevel(line):
"""Return the number of leading spaces in line.
Args:
line: A string to check.
Returns:
An integer count of leading spaces, possibly zero.
"""
indent = Match(r'^( *)\S', line)
if indent:
return len(indent.group(1))
else:
return 0
def GetHeaderGuardCPPVariable(filename):
"""Returns the CPP variable that should be used as a header guard.
Args:
filename: The name of a C++ header file.
Returns:
The CPP variable that should be used as a header guard in the
named file.
"""
# Restores original filename in case that cpplint is invoked from Emacs's
# flymake.
filename = re.sub(r'_flymake\.h$', '.h', filename)
filename = re.sub(r'/\.flymake/([^/]*)$', r'/\1', filename)
# Replace 'c++' with 'cpp'.
filename = filename.replace('C++', 'cpp').replace('c++', 'cpp')
fileinfo = FileInfo(filename)
file_path_from_root = fileinfo.RepositoryName()
if _root:
suffix = os.sep
# On Windows using directory separator will leave us with
# "bogus escape error" unless we properly escape regex.
if suffix == '\\':
suffix += '\\'
file_path_from_root = re.sub('^' + _root + suffix, '', file_path_from_root)
return re.sub(r'[^a-zA-Z0-9]', '_', file_path_from_root).upper() + '_'
def CheckForHeaderGuard(filename, clean_lines, error):
"""Checks that the file contains a header guard.
Logs an error if no #ifndef header guard is present. For other
headers, checks that the full pathname is used.
Args:
filename: The name of the C++ header file.
clean_lines: A CleansedLines instance containing the file.
error: The function to call with any errors found.
"""
# Don't check for header guards if there are error suppression
# comments somewhere in this file.
#
# Because this is silencing a warning for a nonexistent line, we
# only support the very specific NOLINT(build/header_guard) syntax,
# and not the general NOLINT or NOLINT(*) syntax.
raw_lines = clean_lines.lines_without_raw_strings
for i in raw_lines:
if Search(r'//\s*NOLINT\(build/header_guard\)', i):
return
cppvar = GetHeaderGuardCPPVariable(filename)
ifndef = ''
ifndef_linenum = 0
define = ''
endif = ''
endif_linenum = 0
for linenum, line in enumerate(raw_lines):
linesplit = line.split()
if len(linesplit) >= 2:
# find the first occurrence of #ifndef and #define, save arg
if not ifndef and linesplit[0] == '#ifndef':
# set ifndef to the header guard presented on the #ifndef line.
ifndef = linesplit[1]
ifndef_linenum = linenum
if not define and linesplit[0] == '#define':
define = linesplit[1]
# find the last occurrence of #endif, save entire line
if line.startswith('#endif'):
endif = line
endif_linenum = linenum
if not ifndef or not define or ifndef != define:
error(filename, 0, 'build/header_guard', 5,
'No #ifndef header guard found, suggested CPP variable is: %s' %
cppvar)
return
# The guard should be PATH_FILE_H_, but we also allow PATH_FILE_H__
# for backward compatibility.
if ifndef != cppvar:
error_level = 0
if ifndef != cppvar + '_':
error_level = 5
ParseNolintSuppressions(filename, raw_lines[ifndef_linenum], ifndef_linenum,
error)
error(filename, ifndef_linenum, 'build/header_guard', error_level,
'#ifndef header guard has wrong style, please use: %s' % cppvar)
# Check for "//" comments on endif line.
ParseNolintSuppressions(filename, raw_lines[endif_linenum], endif_linenum,
error)
match = Match(r'#endif\s*//\s*' + cppvar + r'(_)?\b', endif)
if match:
if match.group(1) == '_':
# Issue low severity warning for deprecated double trailing underscore
error(filename, endif_linenum, 'build/header_guard', 0,
'#endif line should be "#endif // %s"' % cppvar)
return
# Didn't find the corresponding "//" comment. If this file does not
# contain any "//" comments at all, it could be that the compiler
# only wants "/**/" comments, look for those instead.
no_single_line_comments = True
for i in xrange(1, len(raw_lines) - 1):
line = raw_lines[i]
if Match(r'^(?:(?:\'(?:\.|[^\'])*\')|(?:"(?:\.|[^"])*")|[^\'"])*//', line):
no_single_line_comments = False
break
if no_single_line_comments:
match = Match(r'#endif\s*/\*\s*' + cppvar + r'(_)?\s*\*/', endif)
if match:
if match.group(1) == '_':
# Low severity warning for double trailing underscore
error(filename, endif_linenum, 'build/header_guard', 0,
'#endif line should be "#endif /* %s */"' % cppvar)
return
# Didn't find anything
error(filename, endif_linenum, 'build/header_guard', 5,
'#endif line should be "#endif // %s"' % cppvar)
def CheckHeaderFileIncluded(filename, include_state, error):
"""Logs an error if a .cc file does not include its header."""
# Do not check test files
fileinfo = FileInfo(filename)
if Search(_TEST_FILE_SUFFIX, fileinfo.BaseName()):
return
headerfile = filename[0:len(filename) - len(fileinfo.Extension())] + '.h'
if not os.path.exists(headerfile):
return
headername = FileInfo(headerfile).RepositoryName()
first_include = 0
for section_list in include_state.include_list:
for f in section_list:
if headername in f[0] or f[0] in headername:
return
if not first_include:
first_include = f[1]
error(filename, first_include, 'build/include', 5,
'%s should include its header file %s' % (fileinfo.RepositoryName(),
headername))
def CheckForBadCharacters(filename, lines, error):
"""Logs an error for each line containing bad characters.
Two kinds of bad characters:
1. Unicode replacement characters: These indicate that either the file
contained invalid UTF-8 (likely) or Unicode replacement characters (which
it shouldn't). Note that it's possible for this to throw off line
numbering if the invalid UTF-8 occurred adjacent to a newline.
2. NUL bytes. These are problematic for some tools.
Args:
filename: The name of the current file.
lines: An array of strings, each representing a line of the file.
error: The function to call with any errors found.
"""
for linenum, line in enumerate(lines):
if u'\ufffd' in line:
error(filename, linenum, 'readability/utf8', 5,
'Line contains invalid UTF-8 (or Unicode replacement character).')
if '\0' in line:
error(filename, linenum, 'readability/nul', 5, 'Line contains NUL byte.')
def CheckForNewlineAtEOF(filename, lines, error):
"""Logs an error if there is no newline char at the end of the file.
Args:
filename: The name of the current file.
lines: An array of strings, each representing a line of the file.
error: The function to call with any errors found.
"""
# The array lines() was created by adding two newlines to the
# original file (go figure), then splitting on \n.
# To verify that the file ends in \n, we just have to make sure the
# last-but-two element of lines() exists and is empty.
if len(lines) < 3 or lines[-2]:
error(filename, len(lines) - 2, 'whitespace/ending_newline', 5,
'Could not find a newline character at the end of the file.')
def CheckForMultilineCommentsAndStrings(filename, clean_lines, linenum, error):
"""Logs an error if we see /* ... */ or "..." that extend past one line.
/* ... */ comments are legit inside macros, for one line.
Otherwise, we prefer // comments, so it's ok to warn about the
other. Likewise, it's ok for strings to extend across multiple
lines, as long as a line continuation character (backslash)
terminates each line. Although not currently prohibited by the C++
style guide, it's ugly and unnecessary. We don't do well with either
in this lint program, so we warn about both.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found.
"""
line = clean_lines.elided[linenum]
# Remove all \\ (escaped backslashes) from the line. They are OK, and the
# second (escaped) slash may trigger later \" detection erroneously.
line = line.replace('\\\\', '')
if line.count('/*') > line.count('*/'):
error(filename, linenum, 'readability/multiline_comment', 5,
'Complex multi-line /*...*/-style comment found. '
'Lint may give bogus warnings. '
'Consider replacing these with //-style comments, '
'with #if 0...#endif, '
'or with more clearly structured multi-line comments.')
if (line.count('"') - line.count('\\"')) % 2:
error(filename, linenum, 'readability/multiline_string', 5,
'Multi-line string ("...") found. This lint script doesn\'t '
'do well with such strings, and may give bogus warnings. '
'Use C++11 raw strings or concatenation instead.')
# (non-threadsafe name, thread-safe alternative, validation pattern)
#
# The validation pattern is used to eliminate false positives such as:
# _rand(); // false positive due to substring match.
# ->rand(); // some member function rand().
# ACMRandom rand(seed); // some variable named rand.
# ISAACRandom rand(); // another variable named rand.
#
# Basically we require the return value of these functions to be used
# in some expression context on the same line by matching on some
# operator before the function name. This eliminates constructors and
# member function calls.
_UNSAFE_FUNC_PREFIX = r'(?:[-+*/=%^&|(<]\s*|>\s+)'
_THREADING_LIST = (
('asctime(', 'asctime_r(', _UNSAFE_FUNC_PREFIX + r'asctime\([^)]+\)'),
('ctime(', 'ctime_r(', _UNSAFE_FUNC_PREFIX + r'ctime\([^)]+\)'),
('getgrgid(', 'getgrgid_r(', _UNSAFE_FUNC_PREFIX + r'getgrgid\([^)]+\)'),
('getgrnam(', 'getgrnam_r(', _UNSAFE_FUNC_PREFIX + r'getgrnam\([^)]+\)'),
('getlogin(', 'getlogin_r(', _UNSAFE_FUNC_PREFIX + r'getlogin\(\)'),
('getpwnam(', 'getpwnam_r(', _UNSAFE_FUNC_PREFIX + r'getpwnam\([^)]+\)'),
('getpwuid(', 'getpwuid_r(', _UNSAFE_FUNC_PREFIX + r'getpwuid\([^)]+\)'),
('gmtime(', 'gmtime_r(', _UNSAFE_FUNC_PREFIX + r'gmtime\([^)]+\)'),
('localtime(', 'localtime_r(', _UNSAFE_FUNC_PREFIX + r'localtime\([^)]+\)'),
('rand(', 'rand_r(', _UNSAFE_FUNC_PREFIX + r'rand\(\)'),
('strtok(', 'strtok_r(',
_UNSAFE_FUNC_PREFIX + r'strtok\([^)]+\)'),
('ttyname(', 'ttyname_r(', _UNSAFE_FUNC_PREFIX + r'ttyname\([^)]+\)'),
)
def CheckPosixThreading(filename, clean_lines, linenum, error):
"""Checks for calls to thread-unsafe functions.
Much code has been originally written without consideration of
multi-threading. Also, engineers are relying on their old experience;
they have learned posix before threading extensions were added. These
tests guide the engineers to use thread-safe functions (when using
posix directly).
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found.
"""
line = clean_lines.elided[linenum]
for single_thread_func, multithread_safe_func, pattern in _THREADING_LIST:
# Additional pattern matching check to confirm that this is the
# function we are looking for
if Search(pattern, line):
error(filename, linenum, 'runtime/threadsafe_fn', 2,
'Consider using ' + multithread_safe_func +
'...) instead of ' + single_thread_func +
'...) for improved thread safety.')
def CheckVlogArguments(filename, clean_lines, linenum, error):
"""Checks that VLOG() is only used for defining a logging level.
For example, VLOG(2) is correct. VLOG(INFO), VLOG(WARNING), VLOG(ERROR), and
VLOG(FATAL) are not.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found.
"""
line = clean_lines.elided[linenum]
if Search(r'\bVLOG\((INFO|ERROR|WARNING|DFATAL|FATAL)\)', line):
error(filename, linenum, 'runtime/vlog', 5,
'VLOG() should be used with numeric verbosity level. '
'Use LOG() if you want symbolic severity levels.')
# Matches invalid increment: *count++, which moves pointer instead of
# incrementing a value.
_RE_PATTERN_INVALID_INCREMENT = re.compile(
r'^\s*\*\w+(\+\+|--);')
def CheckInvalidIncrement(filename, clean_lines, linenum, error):
"""Checks for invalid increment *count++.
For example following function:
void increment_counter(int* count) {
*count++;
}
is invalid, because it effectively does count++, moving pointer, and should
be replaced with ++*count, (*count)++ or *count += 1.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found.
"""
line = clean_lines.elided[linenum]
if _RE_PATTERN_INVALID_INCREMENT.match(line):
error(filename, linenum, 'runtime/invalid_increment', 5,
'Changing pointer instead of value (or unused value of operator*).')
def IsMacroDefinition(clean_lines, linenum):
if Search(r'^#define', clean_lines[linenum]):
return True
if linenum > 0 and Search(r'\\$', clean_lines[linenum - 1]):
return True
return False
def IsForwardClassDeclaration(clean_lines, linenum):
return Match(r'^\s*(\btemplate\b)*.*class\s+\w+;\s*$', clean_lines[linenum])
class _BlockInfo(object):
"""Stores information about a generic block of code."""
def __init__(self, linenum, seen_open_brace):
self.starting_linenum = linenum
self.seen_open_brace = seen_open_brace
self.open_parentheses = 0
self.inline_asm = _NO_ASM
self.check_namespace_indentation = False
def CheckBegin(self, filename, clean_lines, linenum, error):
"""Run checks that applies to text up to the opening brace.
This is mostly for checking the text after the class identifier
and the "{", usually where the base class is specified. For other
blocks, there isn't much to check, so we always pass.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found.
"""
pass
def CheckEnd(self, filename, clean_lines, linenum, error):
"""Run checks that applies to text after the closing brace.
This is mostly used for checking end of namespace comments.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found.
"""
pass
def IsBlockInfo(self):
"""Returns true if this block is a _BlockInfo.
This is convenient for verifying that an object is an instance of
a _BlockInfo, but not an instance of any of the derived classes.
Returns:
True for this class, False for derived classes.
"""
return self.__class__ == _BlockInfo
class _ExternCInfo(_BlockInfo):
"""Stores information about an 'extern "C"' block."""
def __init__(self, linenum):
_BlockInfo.__init__(self, linenum, True)
class _ClassInfo(_BlockInfo):
"""Stores information about a class."""
def __init__(self, name, class_or_struct, clean_lines, linenum):
_BlockInfo.__init__(self, linenum, False)
self.name = name
self.is_derived = False
self.check_namespace_indentation = True
if class_or_struct == 'struct':
self.access = 'public'
self.is_struct = True
else:
self.access = 'private'
self.is_struct = False
# Remember initial indentation level for this class. Using raw_lines here
# instead of elided to account for leading comments.
self.class_indent = GetIndentLevel(clean_lines.raw_lines[linenum])
# Try to find the end of the class. This will be confused by things like:
# class A {
# } *x = { ...
#
# But it's still good enough for CheckSectionSpacing.
self.last_line = 0
depth = 0
for i in range(linenum, clean_lines.NumLines()):
line = clean_lines.elided[i]
depth += line.count('{') - line.count('}')
if not depth:
self.last_line = i
break
def CheckBegin(self, filename, clean_lines, linenum, error):
# Look for a bare ':'
if Search('(^|[^:]):($|[^:])', clean_lines.elided[linenum]):
self.is_derived = True
def CheckEnd(self, filename, clean_lines, linenum, error):
# If there is a DISALLOW macro, it should appear near the end of
# the class.
seen_last_thing_in_class = False
for i in xrange(linenum - 1, self.starting_linenum, -1):
match = Search(
r'\b(DISALLOW_COPY_AND_ASSIGN|DISALLOW_IMPLICIT_CONSTRUCTORS)\(' +
self.name + r'\)',
clean_lines.elided[i])
if match:
if seen_last_thing_in_class:
error(filename, i, 'readability/constructors', 3,
match.group(1) + ' should be the last thing in the class')
break
if not Match(r'^\s*$', clean_lines.elided[i]):
seen_last_thing_in_class = True
# Check that closing brace is aligned with beginning of the class.
# Only do this if the closing brace is indented by only whitespaces.
# This means we will not check single-line class definitions.
indent = Match(r'^( *)\}', clean_lines.elided[linenum])
if indent and len(indent.group(1)) != self.class_indent:
if self.is_struct:
parent = 'struct ' + self.name
else:
parent = 'class ' + self.name
error(filename, linenum, 'whitespace/indent', 3,
'Closing brace should be aligned with beginning of %s' % parent)
class _NamespaceInfo(_BlockInfo):
"""Stores information about a namespace."""
def __init__(self, name, linenum):
_BlockInfo.__init__(self, linenum, False)
self.name = name or ''
self.check_namespace_indentation = True
def CheckEnd(self, filename, clean_lines, linenum, error):
"""Check end of namespace comments."""
line = clean_lines.raw_lines[linenum]
# Check how many lines is enclosed in this namespace. Don't issue
# warning for missing namespace comments if there aren't enough
# lines. However, do apply checks if there is already an end of
# namespace comment and it's incorrect.
#
# TODO(unknown): We always want to check end of namespace comments
# if a namespace is large, but sometimes we also want to apply the
# check if a short namespace contained nontrivial things (something
# other than forward declarations). There is currently no logic on
# deciding what these nontrivial things are, so this check is
# triggered by namespace size only, which works most of the time.
if (linenum - self.starting_linenum < 10
and not Match(r'^\s*};*\s*(//|/\*).*\bnamespace\b', line)):
return
# Look for matching comment at end of namespace.
#
# Note that we accept C style "/* */" comments for terminating
# namespaces, so that code that terminate namespaces inside
# preprocessor macros can be cpplint clean.
#
# We also accept stuff like "// end of namespace <name>." with the
# period at the end.
#
# Besides these, we don't accept anything else, otherwise we might
# get false negatives when existing comment is a substring of the
# expected namespace.
if self.name:
# Named namespace
if not Match((r'^\s*};*\s*(//|/\*).*\bnamespace\s+' +
re.escape(self.name) + r'[\*/\.\\\s]*$'),
line):
error(filename, linenum, 'readability/namespace', 5,
'Namespace should be terminated with "// namespace %s"' %
self.name)
else:
# Anonymous namespace
if not Match(r'^\s*};*\s*(//|/\*).*\bnamespace[\*/\.\\\s]*$', line):
# If "// namespace anonymous" or "// anonymous namespace (more text)",
# mention "// anonymous namespace" as an acceptable form
if Match(r'^\s*}.*\b(namespace anonymous|anonymous namespace)\b', line):
error(filename, linenum, 'readability/namespace', 5,
'Anonymous namespace should be terminated with "// namespace"'
' or "// anonymous namespace"')
else:
error(filename, linenum, 'readability/namespace', 5,
'Anonymous namespace should be terminated with "// namespace"')
class _PreprocessorInfo(object):
"""Stores checkpoints of nesting stacks when #if/#else is seen."""
def __init__(self, stack_before_if):
# The entire nesting stack before #if
self.stack_before_if = stack_before_if
# The entire nesting stack up to #else
self.stack_before_else = []
# Whether we have already seen #else or #elif
self.seen_else = False
class NestingState(object):
"""Holds states related to parsing braces."""
def __init__(self):
# Stack for tracking all braces. An object is pushed whenever we
# see a "{", and popped when we see a "}". Only 3 types of
# objects are possible:
# - _ClassInfo: a class or struct.
# - _NamespaceInfo: a namespace.
# - _BlockInfo: some other type of block.
self.stack = []
# Top of the previous stack before each Update().
#
# Because the nesting_stack is updated at the end of each line, we
# had to do some convoluted checks to find out what is the current
# scope at the beginning of the line. This check is simplified by
# saving the previous top of nesting stack.
#
# We could save the full stack, but we only need the top. Copying
# the full nesting stack would slow down cpplint by ~10%.
self.previous_stack_top = []
# Stack of _PreprocessorInfo objects.
self.pp_stack = []
def SeenOpenBrace(self):
"""Check if we have seen the opening brace for the innermost block.
Returns:
True if we have seen the opening brace, False if the innermost
block is still expecting an opening brace.
"""
return (not self.stack) or self.stack[-1].seen_open_brace
def InNamespaceBody(self):
"""Check if we are currently one level inside a namespace body.
Returns:
True if top of the stack is a namespace block, False otherwise.
"""
return self.stack and isinstance(self.stack[-1], _NamespaceInfo)
def InExternC(self):
"""Check if we are currently one level inside an 'extern "C"' block.
Returns:
True if top of the stack is an extern block, False otherwise.
"""
return self.stack and isinstance(self.stack[-1], _ExternCInfo)
def InClassDeclaration(self):
"""Check if we are currently one level inside a class or struct declaration.
Returns:
True if top of the stack is a class/struct, False otherwise.
"""
return self.stack and isinstance(self.stack[-1], _ClassInfo)
def InAsmBlock(self):
"""Check if we are currently one level inside an inline ASM block.
Returns:
True if the top of the stack is a block containing inline ASM.
"""
return self.stack and self.stack[-1].inline_asm != _NO_ASM
def InTemplateArgumentList(self, clean_lines, linenum, pos):
"""Check if current position is inside template argument list.
Args:
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
pos: position just after the suspected template argument.
Returns:
True if (linenum, pos) is inside template arguments.
"""
while linenum < clean_lines.NumLines():
# Find the earliest character that might indicate a template argument
line = clean_lines.elided[linenum]
match = Match(r'^[^{};=\[\]\.<>]*(.)', line[pos:])
if not match:
linenum += 1
pos = 0
continue
token = match.group(1)
pos += len(match.group(0))
# These things do not look like template argument list:
# class Suspect {
# class Suspect x; }
if token in ('{', '}', ';'): return False
# These things look like template argument list:
# template <class Suspect>
# template <class Suspect = default_value>
# template <class Suspect[]>
# template <class Suspect...>
if token in ('>', '=', '[', ']', '.'): return True
# Check if token is an unmatched '<'.
# If not, move on to the next character.
if token != '<':
pos += 1
if pos >= len(line):
linenum += 1
pos = 0
continue
# We can't be sure if we just find a single '<', and need to
# find the matching '>'.
(_, end_line, end_pos) = CloseExpression(clean_lines, linenum, pos - 1)
if end_pos < 0:
# Not sure if template argument list or syntax error in file
return False
linenum = end_line
pos = end_pos
return False
def UpdatePreprocessor(self, line):
"""Update preprocessor stack.
We need to handle preprocessors due to classes like this:
#ifdef SWIG
struct ResultDetailsPageElementExtensionPoint {
#else
struct ResultDetailsPageElementExtensionPoint : public Extension {
#endif
We make the following assumptions (good enough for most files):
- Preprocessor condition evaluates to true from #if up to first
#else/#elif/#endif.
- Preprocessor condition evaluates to false from #else/#elif up
to #endif. We still perform lint checks on these lines, but
these do not affect nesting stack.
Args:
line: current line to check.
"""
if Match(r'^\s*#\s*(if|ifdef|ifndef)\b', line):
# Beginning of #if block, save the nesting stack here. The saved
# stack will allow us to restore the parsing state in the #else case.
self.pp_stack.append(_PreprocessorInfo(copy.deepcopy(self.stack)))
elif Match(r'^\s*#\s*(else|elif)\b', line):
# Beginning of #else block
if self.pp_stack:
if not self.pp_stack[-1].seen_else:
# This is the first #else or #elif block. Remember the
# whole nesting stack up to this point. This is what we
# keep after the #endif.
self.pp_stack[-1].seen_else = True
self.pp_stack[-1].stack_before_else = copy.deepcopy(self.stack)
# Restore the stack to how it was before the #if
self.stack = copy.deepcopy(self.pp_stack[-1].stack_before_if)
else:
# TODO(unknown): unexpected #else, issue warning?
pass
elif Match(r'^\s*#\s*endif\b', line):
# End of #if or #else blocks.
if self.pp_stack:
# If we saw an #else, we will need to restore the nesting
# stack to its former state before the #else, otherwise we
# will just continue from where we left off.
if self.pp_stack[-1].seen_else:
# Here we can just use a shallow copy since we are the last
# reference to it.
self.stack = self.pp_stack[-1].stack_before_else
# Drop the corresponding #if
self.pp_stack.pop()
else:
# TODO(unknown): unexpected #endif, issue warning?
pass
# TODO(unknown): Update() is too long, but we will refactor later.
def Update(self, filename, clean_lines, linenum, error):
"""Update nesting state with current line.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found.
"""
line = clean_lines.elided[linenum]
# Remember top of the previous nesting stack.
#
# The stack is always pushed/popped and not modified in place, so
# we can just do a shallow copy instead of copy.deepcopy. Using
# deepcopy would slow down cpplint by ~28%.
if self.stack:
self.previous_stack_top = self.stack[-1]
else:
self.previous_stack_top = None
# Update pp_stack
self.UpdatePreprocessor(line)
# Count parentheses. This is to avoid adding struct arguments to
# the nesting stack.
if self.stack:
inner_block = self.stack[-1]
depth_change = line.count('(') - line.count(')')
inner_block.open_parentheses += depth_change
# Also check if we are starting or ending an inline assembly block.
if inner_block.inline_asm in (_NO_ASM, _END_ASM):
if (depth_change != 0 and
inner_block.open_parentheses == 1 and
_MATCH_ASM.match(line)):
# Enter assembly block
inner_block.inline_asm = _INSIDE_ASM
else:
# Not entering assembly block. If previous line was _END_ASM,
# we will now shift to _NO_ASM state.
inner_block.inline_asm = _NO_ASM
elif (inner_block.inline_asm == _INSIDE_ASM and
inner_block.open_parentheses == 0):
# Exit assembly block
inner_block.inline_asm = _END_ASM
# Consume namespace declaration at the beginning of the line. Do
# this in a loop so that we catch same line declarations like this:
# namespace proto2 { namespace bridge { class MessageSet; } }
while True:
# Match start of namespace. The "\b\s*" below catches namespace
# declarations even if it weren't followed by a whitespace, this
# is so that we don't confuse our namespace checker. The
# missing spaces will be flagged by CheckSpacing.
namespace_decl_match = Match(r'^\s*namespace\b\s*([:\w]+)?(.*)$', line)
if not namespace_decl_match:
break
new_namespace = _NamespaceInfo(namespace_decl_match.group(1), linenum)
self.stack.append(new_namespace)
line = namespace_decl_match.group(2)
if line.find('{') != -1:
new_namespace.seen_open_brace = True
line = line[line.find('{') + 1:]
# Look for a class declaration in whatever is left of the line
# after parsing namespaces. The regexp accounts for decorated classes
# such as in:
# class LOCKABLE API Object {
# };
class_decl_match = Match(
r'^(\s*(?:template\s*<[\w\s<>,:]*>\s*)?'
r'(class|struct)\s+(?:[A-Z_]+\s+)*(\w+(?:::\w+)*))'
r'(.*)$', line)
if (class_decl_match and
(not self.stack or self.stack[-1].open_parentheses == 0)):
# We do not want to accept classes that are actually template arguments:
# template <class Ignore1,
# class Ignore2 = Default<Args>,
# template <Args> class Ignore3>
# void Function() {};
#
# To avoid template argument cases, we scan forward and look for
# an unmatched '>'. If we see one, assume we are inside a
# template argument list.
end_declaration = len(class_decl_match.group(1))
if not self.InTemplateArgumentList(clean_lines, linenum, end_declaration):
self.stack.append(_ClassInfo(
class_decl_match.group(3), class_decl_match.group(2),
clean_lines, linenum))
line = class_decl_match.group(4)
# If we have not yet seen the opening brace for the innermost block,
# run checks here.
if not self.SeenOpenBrace():
self.stack[-1].CheckBegin(filename, clean_lines, linenum, error)
# Update access control if we are inside a class/struct
if self.stack and isinstance(self.stack[-1], _ClassInfo):
classinfo = self.stack[-1]
access_match = Match(
r'^(.*)\b(public|private|protected|signals)(\s+(?:slots\s*)?)?'
r':(?:[^:]|$)',
line)
if access_match:
classinfo.access = access_match.group(2)
# Check that access keywords are indented +1 space. Skip this
# check if the keywords are not preceded by whitespaces.
indent = access_match.group(1)
if (len(indent) != classinfo.class_indent + 1 and
Match(r'^\s*$', indent)):
if classinfo.is_struct:
parent = 'struct ' + classinfo.name
else:
parent = 'class ' + classinfo.name
slots = ''
if access_match.group(3):
slots = access_match.group(3)
error(filename, linenum, 'whitespace/indent', 3,
'%s%s: should be indented +1 space inside %s' % (
access_match.group(2), slots, parent))
# Consume braces or semicolons from what's left of the line
while True:
# Match first brace, semicolon, or closed parenthesis.
matched = Match(r'^[^{;)}]*([{;)}])(.*)$', line)
if not matched:
break
token = matched.group(1)
if token == '{':
# If namespace or class hasn't seen a opening brace yet, mark
# namespace/class head as complete. Push a new block onto the
# stack otherwise.
if not self.SeenOpenBrace():
self.stack[-1].seen_open_brace = True
elif Match(r'^extern\s*"[^"]*"\s*\{', line):
self.stack.append(_ExternCInfo(linenum))
else:
self.stack.append(_BlockInfo(linenum, True))
if _MATCH_ASM.match(line):
self.stack[-1].inline_asm = _BLOCK_ASM
elif token == ';' or token == ')':
# If we haven't seen an opening brace yet, but we already saw
# a semicolon, this is probably a forward declaration. Pop
# the stack for these.
#
# Similarly, if we haven't seen an opening brace yet, but we
# already saw a closing parenthesis, then these are probably
# function arguments with extra "class" or "struct" keywords.
# Also pop these stack for these.
if not self.SeenOpenBrace():
self.stack.pop()
else: # token == '}'
# Perform end of block checks and pop the stack.
if self.stack:
self.stack[-1].CheckEnd(filename, clean_lines, linenum, error)
self.stack.pop()
line = matched.group(2)
def InnermostClass(self):
"""Get class info on the top of the stack.
Returns:
A _ClassInfo object if we are inside a class, or None otherwise.
"""
for i in range(len(self.stack), 0, -1):
classinfo = self.stack[i - 1]
if isinstance(classinfo, _ClassInfo):
return classinfo
return None
def CheckCompletedBlocks(self, filename, error):
"""Checks that all classes and namespaces have been completely parsed.
Call this when all lines in a file have been processed.
Args:
filename: The name of the current file.
error: The function to call with any errors found.
"""
# Note: This test can result in false positives if #ifdef constructs
# get in the way of brace matching. See the testBuildClass test in
# cpplint_unittest.py for an example of this.
for obj in self.stack:
if isinstance(obj, _ClassInfo):
error(filename, obj.starting_linenum, 'build/class', 5,
'Failed to find complete declaration of class %s' %
obj.name)
elif isinstance(obj, _NamespaceInfo):
error(filename, obj.starting_linenum, 'build/namespaces', 5,
'Failed to find complete declaration of namespace %s' %
obj.name)
def CheckForNonStandardConstructs(filename, clean_lines, linenum,
nesting_state, error):
r"""Logs an error if we see certain non-ANSI constructs ignored by gcc-2.
Complain about several constructs which gcc-2 accepts, but which are
not standard C++. Warning about these in lint is one way to ease the
transition to new compilers.
- put storage class first (e.g. "static const" instead of "const static").
- "%lld" instead of %qd" in printf-type functions.
- "%1$d" is non-standard in printf-type functions.
- "\%" is an undefined character escape sequence.
- text after #endif is not allowed.
- invalid inner-style forward declaration.
- >? and <? operators, and their >?= and <?= cousins.
Additionally, check for constructor/destructor style violations and reference
members, as it is very convenient to do so while checking for
gcc-2 compliance.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
nesting_state: A NestingState instance which maintains information about
the current stack of nested blocks being parsed.
error: A callable to which errors are reported, which takes 4 arguments:
filename, line number, error level, and message
"""
# Remove comments from the line, but leave in strings for now.
line = clean_lines.lines[linenum]
if Search(r'printf\s*\(.*".*%[-+ ]?\d*q', line):
error(filename, linenum, 'runtime/printf_format', 3,
'%q in format strings is deprecated. Use %ll instead.')
if Search(r'printf\s*\(.*".*%\d+\$', line):
error(filename, linenum, 'runtime/printf_format', 2,
'%N$ formats are unconventional. Try rewriting to avoid them.')
# Remove escaped backslashes before looking for undefined escapes.
line = line.replace('\\\\', '')
if Search(r'("|\').*\\(%|\[|\(|{)', line):
error(filename, linenum, 'build/printf_format', 3,
'%, [, (, and { are undefined character escapes. Unescape them.')
# For the rest, work with both comments and strings removed.
line = clean_lines.elided[linenum]
if Search(r'\b(const|volatile|void|char|short|int|long'
r'|float|double|signed|unsigned'
r'|schar|u?int8|u?int16|u?int32|u?int64)'
r'\s+(register|static|extern|typedef)\b',
line):
error(filename, linenum, 'build/storage_class', 5,
'Storage-class specifier (static, extern, typedef, etc) should be '
'at the beginning of the declaration.')
if Match(r'\s*#\s*endif\s*[^/\s]+', line):
error(filename, linenum, 'build/endif_comment', 5,
'Uncommented text after #endif is non-standard. Use a comment.')
if Match(r'\s*class\s+(\w+\s*::\s*)+\w+\s*;', line):
error(filename, linenum, 'build/forward_decl', 5,
'Inner-style forward declarations are invalid. Remove this line.')
if Search(r'(\w+|[+-]?\d+(\.\d*)?)\s*(<|>)\?=?\s*(\w+|[+-]?\d+)(\.\d*)?',
line):
error(filename, linenum, 'build/deprecated', 3,
'>? and <? (max and min) operators are non-standard and deprecated.')
if Search(r'^\s*const\s*string\s*&\s*\w+\s*;', line):
# TODO(unknown): Could it be expanded safely to arbitrary references,
# without triggering too many false positives? The first
# attempt triggered 5 warnings for mostly benign code in the regtest, hence
# the restriction.
# Here's the original regexp, for the reference:
# type_name = r'\w+((\s*::\s*\w+)|(\s*<\s*\w+?\s*>))?'
# r'\s*const\s*' + type_name + '\s*&\s*\w+\s*;'
error(filename, linenum, 'runtime/member_string_references', 2,
'const string& members are dangerous. It is much better to use '
'alternatives, such as pointers or simple constants.')
# Everything else in this function operates on class declarations.
# Return early if the top of the nesting stack is not a class, or if
# the class head is not completed yet.
classinfo = nesting_state.InnermostClass()
if not classinfo or not classinfo.seen_open_brace:
return
# The class may have been declared with namespace or classname qualifiers.
# The constructor and destructor will not have those qualifiers.
base_classname = classinfo.name.split('::')[-1]
# Look for single-argument constructors that aren't marked explicit.
# Technically a valid construct, but against style.
explicit_constructor_match = Match(
r'\s+(?:inline\s+)?(explicit\s+)?(?:inline\s+)?%s\s*'
r'\(((?:[^()]|\([^()]*\))*)\)'
% re.escape(base_classname),
line)
if explicit_constructor_match:
is_marked_explicit = explicit_constructor_match.group(1)
if not explicit_constructor_match.group(2):
constructor_args = []
else:
constructor_args = explicit_constructor_match.group(2).split(',')
# collapse arguments so that commas in template parameter lists and function
# argument parameter lists don't split arguments in two
i = 0
while i < len(constructor_args):
constructor_arg = constructor_args[i]
while (constructor_arg.count('<') > constructor_arg.count('>') or
constructor_arg.count('(') > constructor_arg.count(')')):
constructor_arg += ',' + constructor_args[i + 1]
del constructor_args[i + 1]
constructor_args[i] = constructor_arg
i += 1
defaulted_args = [arg for arg in constructor_args if '=' in arg]
noarg_constructor = (not constructor_args or # empty arg list
# 'void' arg specifier
(len(constructor_args) == 1 and
constructor_args[0].strip() == 'void'))
onearg_constructor = ((len(constructor_args) == 1 and # exactly one arg
not noarg_constructor) or
# all but at most one arg defaulted
(len(constructor_args) >= 1 and
not noarg_constructor and
len(defaulted_args) >= len(constructor_args) - 1))
initializer_list_constructor = bool(
onearg_constructor and
Search(r'\bstd\s*::\s*initializer_list\b', constructor_args[0]))
copy_constructor = bool(
onearg_constructor and
Match(r'(const\s+)?%s(\s*<[^>]*>)?(\s+const)?\s*(?:<\w+>\s*)?&'
% re.escape(base_classname), constructor_args[0].strip()))
if (not is_marked_explicit and
onearg_constructor and
not initializer_list_constructor and
not copy_constructor):
if defaulted_args:
error(filename, linenum, 'runtime/explicit', 5,
'Constructors callable with one argument '
'should be marked explicit.')
else:
error(filename, linenum, 'runtime/explicit', 5,
'Single-parameter constructors should be marked explicit.')
elif is_marked_explicit and not onearg_constructor:
if noarg_constructor:
error(filename, linenum, 'runtime/explicit', 5,
'Zero-parameter constructors should not be marked explicit.')
def CheckSpacingForFunctionCall(filename, clean_lines, linenum, error):
"""Checks for the correctness of various spacing around function calls.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found.
"""
line = clean_lines.elided[linenum]
# Since function calls often occur inside if/for/while/switch
# expressions - which have their own, more liberal conventions - we
# first see if we should be looking inside such an expression for a
# function call, to which we can apply more strict standards.
fncall = line # if there's no control flow construct, look at whole line
for pattern in (r'\bif\s*\((.*)\)\s*{',
r'\bfor\s*\((.*)\)\s*{',
r'\bwhile\s*\((.*)\)\s*[{;]',
r'\bswitch\s*\((.*)\)\s*{'):
match = Search(pattern, line)
if match:
fncall = match.group(1) # look inside the parens for function calls
break
# Except in if/for/while/switch, there should never be space
# immediately inside parens (eg "f( 3, 4 )"). We make an exception
# for nested parens ( (a+b) + c ). Likewise, there should never be
# a space before a ( when it's a function argument. I assume it's a
# function argument when the char before the whitespace is legal in
# a function name (alnum + _) and we're not starting a macro. Also ignore
# pointers and references to arrays and functions coz they're too tricky:
# we use a very simple way to recognize these:
# " (something)(maybe-something)" or
# " (something)(maybe-something," or
# " (something)[something]"
# Note that we assume the contents of [] to be short enough that
# they'll never need to wrap.
if ( # Ignore control structures.
not Search(r'\b(if|for|while|switch|return|new|delete|catch|sizeof)\b',
fncall) and
# Ignore pointers/references to functions.
not Search(r' \([^)]+\)\([^)]*(\)|,$)', fncall) and
# Ignore pointers/references to arrays.
not Search(r' \([^)]+\)\[[^\]]+\]', fncall)):
if Search(r'\w\s*\(\s(?!\s*\\$)', fncall): # a ( used for a fn call
error(filename, linenum, 'whitespace/parens', 4,
'Extra space after ( in function call')
elif Search(r'\(\s+(?!(\s*\\)|\()', fncall):
error(filename, linenum, 'whitespace/parens', 2,
'Extra space after (')
if (Search(r'\w\s+\(', fncall) and
not Search(r'_{0,2}asm_{0,2}\s+_{0,2}volatile_{0,2}\s+\(', fncall) and
not Search(r'#\s*define|typedef|using\s+\w+\s*=', fncall) and
not Search(r'\w\s+\((\w+::)*\*\w+\)\(', fncall) and
not Search(r'\bcase\s+\(', fncall)):
# TODO(unknown): Space after an operator function seem to be a common
# error, silence those for now by restricting them to highest verbosity.
if Search(r'\boperator_*\b', line):
error(filename, linenum, 'whitespace/parens', 0,
'Extra space before ( in function call')
else:
error(filename, linenum, 'whitespace/parens', 4,
'Extra space before ( in function call')
# If the ) is followed only by a newline or a { + newline, assume it's
# part of a control statement (if/while/etc), and don't complain
if Search(r'[^)]\s+\)\s*[^{\s]', fncall):
# If the closing parenthesis is preceded by only whitespaces,
# try to give a more descriptive error message.
if Search(r'^\s+\)', fncall):
error(filename, linenum, 'whitespace/parens', 2,
'Closing ) should be moved to the previous line')
else:
error(filename, linenum, 'whitespace/parens', 2,
'Extra space before )')
def IsBlankLine(line):
"""Returns true if the given line is blank.
We consider a line to be blank if the line is empty or consists of
only white spaces.
Args:
line: A line of a string.
Returns:
True, if the given line is blank.
"""
return not line or line.isspace()
def CheckForNamespaceIndentation(filename, nesting_state, clean_lines, line,
error):
is_namespace_indent_item = (
len(nesting_state.stack) > 1 and
nesting_state.stack[-1].check_namespace_indentation and
isinstance(nesting_state.previous_stack_top, _NamespaceInfo) and
nesting_state.previous_stack_top == nesting_state.stack[-2])
if ShouldCheckNamespaceIndentation(nesting_state, is_namespace_indent_item,
clean_lines.elided, line):
CheckItemIndentationInNamespace(filename, clean_lines.elided,
line, error)
def CheckForFunctionLengths(filename, clean_lines, linenum,
function_state, error):
"""Reports for long function bodies.
For an overview why this is done, see:
https://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Write_Short_Functions
Uses a simplistic algorithm assuming other style guidelines
(especially spacing) are followed.
Only checks unindented functions, so class members are unchecked.
Trivial bodies are unchecked, so constructors with huge initializer lists
may be missed.
Blank/comment lines are not counted so as to avoid encouraging the removal
of vertical space and comments just to get through a lint check.
NOLINT *on the last line of a function* disables this check.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
function_state: Current function name and lines in body so far.
error: The function to call with any errors found.
"""
lines = clean_lines.lines
line = lines[linenum]
joined_line = ''
starting_func = False
regexp = r'(\w(\w|::|\*|\&|\s)*)\(' # decls * & space::name( ...
match_result = Match(regexp, line)
if match_result:
# If the name is all caps and underscores, figure it's a macro and
# ignore it, unless it's TEST or TEST_F.
function_name = match_result.group(1).split()[-1]
if function_name == 'TEST' or function_name == 'TEST_F' or (
not Match(r'[A-Z_]+$', function_name)):
starting_func = True
if starting_func:
body_found = False
for start_linenum in xrange(linenum, clean_lines.NumLines()):
start_line = lines[start_linenum]
joined_line += ' ' + start_line.lstrip()
if Search(r'(;|})', start_line): # Declarations and trivial functions
body_found = True
break # ... ignore
elif Search(r'{', start_line):
body_found = True
function = Search(r'((\w|:)*)\(', line).group(1)
if Match(r'TEST', function): # Handle TEST... macros
parameter_regexp = Search(r'(\(.*\))', joined_line)
if parameter_regexp: # Ignore bad syntax
function += parameter_regexp.group(1)
else:
function += '()'
function_state.Begin(function)
break
if not body_found:
# No body for the function (or evidence of a non-function) was found.
error(filename, linenum, 'readability/fn_size', 5,
'Lint failed to find start of function body.')
elif Match(r'^\}\s*$', line): # function end
function_state.Check(error, filename, linenum)
function_state.End()
elif not Match(r'^\s*$', line):
function_state.Count() # Count non-blank/non-comment lines.
_RE_PATTERN_TODO = re.compile(r'^//(\s*)TODO(\(.+?\))?:?(\s|$)?')
def CheckComment(line, filename, linenum, next_line_start, error):
"""Checks for common mistakes in comments.
Args:
line: The line in question.
filename: The name of the current file.
linenum: The number of the line to check.
next_line_start: The first non-whitespace column of the next line.
error: The function to call with any errors found.
"""
commentpos = line.find('//')
if commentpos != -1:
# Check if the // may be in quotes. If so, ignore it
if re.sub(r'\\.', '', line[0:commentpos]).count('"') % 2 == 0:
# Allow one space for new scopes, two spaces otherwise:
if (not (Match(r'^.*{ *//', line) and next_line_start == commentpos) and
((commentpos >= 1 and
line[commentpos-1] not in string.whitespace) or
(commentpos >= 2 and
line[commentpos-2] not in string.whitespace))):
error(filename, linenum, 'whitespace/comments', 2,
'At least two spaces is best between code and comments')
# Checks for common mistakes in TODO comments.
comment = line[commentpos:]
match = _RE_PATTERN_TODO.match(comment)
if match:
# One whitespace is correct; zero whitespace is handled elsewhere.
leading_whitespace = match.group(1)
if len(leading_whitespace) > 1:
error(filename, linenum, 'whitespace/todo', 2,
'Too many spaces before TODO')
username = match.group(2)
if not username:
error(filename, linenum, 'readability/todo', 2,
'Missing username in TODO; it should look like '
'"// TODO(my_username): Stuff."')
middle_whitespace = match.group(3)
# Comparisons made explicit for correctness -- pylint: disable=g-explicit-bool-comparison
if middle_whitespace != ' ' and middle_whitespace != '':
error(filename, linenum, 'whitespace/todo', 2,
'TODO(my_username) should be followed by a space')
# If the comment contains an alphanumeric character, there
# should be a space somewhere between it and the // unless
# it's a /// or //! Doxygen comment.
if (Match(r'//[^ ]*\w', comment) and
not Match(r'(///|//\!)(\s+|$)', comment)):
error(filename, linenum, 'whitespace/comments', 4,
'Should have a space between // and comment')
def CheckAccess(filename, clean_lines, linenum, nesting_state, error):
"""Checks for improper use of DISALLOW* macros.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
nesting_state: A NestingState instance which maintains information about
the current stack of nested blocks being parsed.
error: The function to call with any errors found.
"""
line = clean_lines.elided[linenum] # get rid of comments and strings
matched = Match((r'\s*(DISALLOW_COPY_AND_ASSIGN|'
r'DISALLOW_IMPLICIT_CONSTRUCTORS)'), line)
if not matched:
return
if nesting_state.stack and isinstance(nesting_state.stack[-1], _ClassInfo):
if nesting_state.stack[-1].access != 'private':
error(filename, linenum, 'readability/constructors', 3,
'%s must be in the private: section' % matched.group(1))
else:
# Found DISALLOW* macro outside a class declaration, or perhaps it
# was used inside a function when it should have been part of the
# class declaration. We could issue a warning here, but it
# probably resulted in a compiler error already.
pass
def CheckSpacing(filename, clean_lines, linenum, nesting_state, error):
"""Checks for the correctness of various spacing issues in the code.
Things we check for: spaces around operators, spaces after
if/for/while/switch, no spaces around parens in function calls, two
spaces between code and comment, don't start a block with a blank
line, don't end a function with a blank line, don't add a blank line
after public/protected/private, don't have too many blank lines in a row.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
nesting_state: A NestingState instance which maintains information about
the current stack of nested blocks being parsed.
error: The function to call with any errors found.
"""
# Don't use "elided" lines here, otherwise we can't check commented lines.
# Don't want to use "raw" either, because we don't want to check inside C++11
# raw strings,
raw = clean_lines.lines_without_raw_strings
line = raw[linenum]
# Before nixing comments, check if the line is blank for no good
# reason. This includes the first line after a block is opened, and
# blank lines at the end of a function (ie, right before a line like '}'
#
# Skip all the blank line checks if we are immediately inside a
# namespace body. In other words, don't issue blank line warnings
# for this block:
# namespace {
#
# }
#
# A warning about missing end of namespace comments will be issued instead.
#
# Also skip blank line checks for 'extern "C"' blocks, which are formatted
# like namespaces.
if (IsBlankLine(line) and
not nesting_state.InNamespaceBody() and
not nesting_state.InExternC()):
elided = clean_lines.elided
prev_line = elided[linenum - 1]
prevbrace = prev_line.rfind('{')
# TODO(unknown): Don't complain if line before blank line, and line after,
# both start with alnums and are indented the same amount.
# This ignores whitespace at the start of a namespace block
# because those are not usually indented.
if prevbrace != -1 and prev_line[prevbrace:].find('}') == -1:
# OK, we have a blank line at the start of a code block. Before we
# complain, we check if it is an exception to the rule: The previous
# non-empty line has the parameters of a function header that are indented
# 4 spaces (because they did not fit in a 80 column line when placed on
# the same line as the function name). We also check for the case where
# the previous line is indented 6 spaces, which may happen when the
# initializers of a constructor do not fit into a 80 column line.
exception = False
if Match(r' {6}\w', prev_line): # Initializer list?
# We are looking for the opening column of initializer list, which
# should be indented 4 spaces to cause 6 space indentation afterwards.
search_position = linenum-2
while (search_position >= 0
and Match(r' {6}\w', elided[search_position])):
search_position -= 1
exception = (search_position >= 0
and elided[search_position][:5] == ' :')
else:
# Search for the function arguments or an initializer list. We use a
# simple heuristic here: If the line is indented 4 spaces; and we have a
# closing paren, without the opening paren, followed by an opening brace
# or colon (for initializer lists) we assume that it is the last line of
# a function header. If we have a colon indented 4 spaces, it is an
# initializer list.
exception = (Match(r' {4}\w[^\(]*\)\s*(const\s*)?(\{\s*$|:)',
prev_line)
or Match(r' {4}:', prev_line))
if not exception:
error(filename, linenum, 'whitespace/blank_line', 2,
'Redundant blank line at the start of a code block '
'should be deleted.')
# Ignore blank lines at the end of a block in a long if-else
# chain, like this:
# if (condition1) {
# // Something followed by a blank line
#
# } else if (condition2) {
# // Something else
# }
if linenum + 1 < clean_lines.NumLines():
next_line = raw[linenum + 1]
if (next_line
and Match(r'\s*}', next_line)
and next_line.find('} else ') == -1):
error(filename, linenum, 'whitespace/blank_line', 3,
'Redundant blank line at the end of a code block '
'should be deleted.')
matched = Match(r'\s*(public|protected|private):', prev_line)
if matched:
error(filename, linenum, 'whitespace/blank_line', 3,
'Do not leave a blank line after "%s:"' % matched.group(1))
# Next, check comments
next_line_start = 0
if linenum + 1 < clean_lines.NumLines():
next_line = raw[linenum + 1]
next_line_start = len(next_line) - len(next_line.lstrip())
CheckComment(line, filename, linenum, next_line_start, error)
# get rid of comments and strings
line = clean_lines.elided[linenum]
# You shouldn't have spaces before your brackets, except maybe after
# 'delete []' or 'return []() {};'
if Search(r'\w\s+\[', line) and not Search(r'(?:delete|return)\s+\[', line):
error(filename, linenum, 'whitespace/braces', 5,
'Extra space before [')
# In range-based for, we wanted spaces before and after the colon, but
# not around "::" tokens that might appear.
if (Search(r'for *\(.*[^:]:[^: ]', line) or
Search(r'for *\(.*[^: ]:[^:]', line)):
error(filename, linenum, 'whitespace/forcolon', 2,
'Missing space around colon in range-based for loop')
def CheckOperatorSpacing(filename, clean_lines, linenum, error):
"""Checks for horizontal spacing around operators.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found.
"""
line = clean_lines.elided[linenum]
# Don't try to do spacing checks for operator methods. Do this by
# replacing the troublesome characters with something else,
# preserving column position for all other characters.
#
# The replacement is done repeatedly to avoid false positives from
# operators that call operators.
while True:
match = Match(r'^(.*\boperator\b)(\S+)(\s*\(.*)$', line)
if match:
line = match.group(1) + ('_' * len(match.group(2))) + match.group(3)
else:
break
# We allow no-spaces around = within an if: "if ( (a=Foo()) == 0 )".
# Otherwise not. Note we only check for non-spaces on *both* sides;
# sometimes people put non-spaces on one side when aligning ='s among
# many lines (not that this is behavior that I approve of...)
if ((Search(r'[\w.]=', line) or
Search(r'=[\w.]', line))
and not Search(r'\b(if|while|for) ', line)
# Operators taken from [lex.operators] in C++11 standard.
and not Search(r'(>=|<=|==|!=|&=|\^=|\|=|\+=|\*=|\/=|\%=)', line)
and not Search(r'operator=', line)):
error(filename, linenum, 'whitespace/operators', 4,
'Missing spaces around =')
# It's ok not to have spaces around binary operators like + - * /, but if
# there's too little whitespace, we get concerned. It's hard to tell,
# though, so we punt on this one for now. TODO.
# You should always have whitespace around binary operators.
#
# Check <= and >= first to avoid false positives with < and >, then
# check non-include lines for spacing around < and >.
#
# If the operator is followed by a comma, assume it's be used in a
# macro context and don't do any checks. This avoids false
# positives.
#
# Note that && is not included here. This is because there are too
# many false positives due to RValue references.
match = Search(r'[^<>=!\s](==|!=|<=|>=|\|\|)[^<>=!\s,;\)]', line)
if match:
error(filename, linenum, 'whitespace/operators', 3,
'Missing spaces around %s' % match.group(1))
elif not Match(r'#.*include', line):
# Look for < that is not surrounded by spaces. This is only
# triggered if both sides are missing spaces, even though
# technically should should flag if at least one side is missing a
# space. This is done to avoid some false positives with shifts.
match = Match(r'^(.*[^\s<])<[^\s=<,]', line)
if match:
(_, _, end_pos) = CloseExpression(
clean_lines, linenum, len(match.group(1)))
if end_pos <= -1:
error(filename, linenum, 'whitespace/operators', 3,
'Missing spaces around <')
# Look for > that is not surrounded by spaces. Similar to the
# above, we only trigger if both sides are missing spaces to avoid
# false positives with shifts.
match = Match(r'^(.*[^-\s>])>[^\s=>,]', line)
if match:
(_, _, start_pos) = ReverseCloseExpression(
clean_lines, linenum, len(match.group(1)))
if start_pos <= -1:
error(filename, linenum, 'whitespace/operators', 3,
'Missing spaces around >')
# We allow no-spaces around << when used like this: 10<<20, but
# not otherwise (particularly, not when used as streams)
#
# We also allow operators following an opening parenthesis, since
# those tend to be macros that deal with operators.
match = Search(r'(operator|[^\s(<])(?:L|UL|LL|ULL|l|ul|ll|ull)?<<([^\s,=<])', line)
if (match and not (match.group(1).isdigit() and match.group(2).isdigit()) and
not (match.group(1) == 'operator' and match.group(2) == ';')):
error(filename, linenum, 'whitespace/operators', 3,
'Missing spaces around <<')
# We allow no-spaces around >> for almost anything. This is because
# C++11 allows ">>" to close nested templates, which accounts for
# most cases when ">>" is not followed by a space.
#
# We still warn on ">>" followed by alpha character, because that is
# likely due to ">>" being used for right shifts, e.g.:
# value >> alpha
#
# When ">>" is used to close templates, the alphanumeric letter that
# follows would be part of an identifier, and there should still be
# a space separating the template type and the identifier.
# type<type<type>> alpha
match = Search(r'>>[a-zA-Z_]', line)
if match:
error(filename, linenum, 'whitespace/operators', 3,
'Missing spaces around >>')
# There shouldn't be space around unary operators
match = Search(r'(!\s|~\s|[\s]--[\s;]|[\s]\+\+[\s;])', line)
if match:
error(filename, linenum, 'whitespace/operators', 4,
'Extra space for operator %s' % match.group(1))
def CheckParenthesisSpacing(filename, clean_lines, linenum, error):
"""Checks for horizontal spacing around parentheses.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found.
"""
line = clean_lines.elided[linenum]
# No spaces after an if, while, switch, or for
match = Search(r' (if\(|for\(|while\(|switch\()', line)
if match:
error(filename, linenum, 'whitespace/parens', 5,
'Missing space before ( in %s' % match.group(1))
# For if/for/while/switch, the left and right parens should be
# consistent about how many spaces are inside the parens, and
# there should either be zero or one spaces inside the parens.
# We don't want: "if ( foo)" or "if ( foo )".
# Exception: "for ( ; foo; bar)" and "for (foo; bar; )" are allowed.
match = Search(r'\b(if|for|while|switch)\s*'
r'\(([ ]*)(.).*[^ ]+([ ]*)\)\s*{\s*$',
line)
if match:
if len(match.group(2)) != len(match.group(4)):
if not (match.group(3) == ';' and
len(match.group(2)) == 1 + len(match.group(4)) or
not match.group(2) and Search(r'\bfor\s*\(.*; \)', line)):
error(filename, linenum, 'whitespace/parens', 5,
'Mismatching spaces inside () in %s' % match.group(1))
if len(match.group(2)) not in [0, 1]:
error(filename, linenum, 'whitespace/parens', 5,
'Should have zero or one spaces inside ( and ) in %s' %
match.group(1))
def CheckCommaSpacing(filename, clean_lines, linenum, error):
"""Checks for horizontal spacing near commas and semicolons.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found.
"""
raw = clean_lines.lines_without_raw_strings
line = clean_lines.elided[linenum]
# You should always have a space after a comma (either as fn arg or operator)
#
# This does not apply when the non-space character following the
# comma is another comma, since the only time when that happens is
# for empty macro arguments.
#
# We run this check in two passes: first pass on elided lines to
# verify that lines contain missing whitespaces, second pass on raw
# lines to confirm that those missing whitespaces are not due to
# elided comments.
if (Search(r',[^,\s]', ReplaceAll(r'\boperator\s*,\s*\(', 'F(', line)) and
Search(r',[^,\s]', raw[linenum])):
error(filename, linenum, 'whitespace/comma', 3,
'Missing space after ,')
# You should always have a space after a semicolon
# except for few corner cases
# TODO(unknown): clarify if 'if (1) { return 1;}' is requires one more
# space after ;
if Search(r';[^\s};\\)/]', line):
error(filename, linenum, 'whitespace/semicolon', 3,
'Missing space after ;')
def _IsType(clean_lines, nesting_state, expr):
"""Check if expression looks like a type name, returns true if so.
Args:
clean_lines: A CleansedLines instance containing the file.
nesting_state: A NestingState instance which maintains information about
the current stack of nested blocks being parsed.
expr: The expression to check.
Returns:
True, if token looks like a type.
"""
# Keep only the last token in the expression
last_word = Match(r'^.*(\b\S+)$', expr)
if last_word:
token = last_word.group(1)
else:
token = expr
# Match native types and stdint types
if _TYPES.match(token):
return True
# Try a bit harder to match templated types. Walk up the nesting
# stack until we find something that resembles a typename
# declaration for what we are looking for.
typename_pattern = (r'\b(?:typename|class|struct)\s+' + re.escape(token) +
r'\b')
block_index = len(nesting_state.stack) - 1
while block_index >= 0:
if isinstance(nesting_state.stack[block_index], _NamespaceInfo):
return False
# Found where the opening brace is. We want to scan from this
# line up to the beginning of the function, minus a few lines.
# template <typename Type1, // stop scanning here
# ...>
# class C
# : public ... { // start scanning here
last_line = nesting_state.stack[block_index].starting_linenum
next_block_start = 0
if block_index > 0:
next_block_start = nesting_state.stack[block_index - 1].starting_linenum
first_line = last_line
while first_line >= next_block_start:
if clean_lines.elided[first_line].find('template') >= 0:
break
first_line -= 1
if first_line < next_block_start:
# Didn't find any "template" keyword before reaching the next block,
# there are probably no template things to check for this block
block_index -= 1
continue
# Look for typename in the specified range
for i in xrange(first_line, last_line + 1, 1):
if Search(typename_pattern, clean_lines.elided[i]):
return True
block_index -= 1
return False
def CheckBracesSpacing(filename, clean_lines, linenum, nesting_state, error):
"""Checks for horizontal spacing near commas.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
nesting_state: A NestingState instance which maintains information about
the current stack of nested blocks being parsed.
error: The function to call with any errors found.
"""
line = clean_lines.elided[linenum]
# Except after an opening paren, or after another opening brace (in case of
# an initializer list, for instance), you should have spaces before your
# braces when they are delimiting blocks, classes, namespaces etc.
# And since you should never have braces at the beginning of a line,
# this is an easy test. Except that braces used for initialization don't
# follow the same rule; we often don't want spaces before those.
match = Match(r'^(.*[^ ({>]){', line)
if match:
# Try a bit harder to check for brace initialization. This
# happens in one of the following forms:
# Constructor() : initializer_list_{} { ... }
# Constructor{}.MemberFunction()
# Type variable{};
# FunctionCall(type{}, ...);
# LastArgument(..., type{});
# LOG(INFO) << type{} << " ...";
# map_of_type[{...}] = ...;
# ternary = expr ? new type{} : nullptr;
# OuterTemplate<InnerTemplateConstructor<Type>{}>
#
# We check for the character following the closing brace, and
# silence the warning if it's one of those listed above, i.e.
# "{.;,)<>]:".
#
# To account for nested initializer list, we allow any number of
# closing braces up to "{;,)<". We can't simply silence the
# warning on first sight of closing brace, because that would
# cause false negatives for things that are not initializer lists.
# Silence this: But not this:
# Outer{ if (...) {
# Inner{...} if (...){ // Missing space before {
# }; }
#
# There is a false negative with this approach if people inserted
# spurious semicolons, e.g. "if (cond){};", but we will catch the
# spurious semicolon with a separate check.
leading_text = match.group(1)
(endline, endlinenum, endpos) = CloseExpression(
clean_lines, linenum, len(match.group(1)))
trailing_text = ''
if endpos > -1:
trailing_text = endline[endpos:]
for offset in xrange(endlinenum + 1,
min(endlinenum + 3, clean_lines.NumLines() - 1)):
trailing_text += clean_lines.elided[offset]
# We also suppress warnings for `uint64_t{expression}` etc., as the style
# guide recommends brace initialization for integral types to avoid
# overflow/truncation.
# if (not Match(r'^[\s}]*[{.;,)<>\]:]', trailing_text)
# and not _IsType(clean_lines, nesting_state, leading_text)):
# error(filename, linenum, 'whitespace/braces', 5,
# 'Missing space before {')
# Make sure '} else {' has spaces.
if Search(r'}else', line):
error(filename, linenum, 'whitespace/braces', 5,
'Missing space before else')
# You shouldn't have a space before a semicolon at the end of the line.
# There's a special case for "for" since the style guide allows space before
# the semicolon there.
if Search(r':\s*;\s*$', line):
error(filename, linenum, 'whitespace/semicolon', 5,
'Semicolon defining empty statement. Use {} instead.')
elif Search(r'^\s*;\s*$', line):
error(filename, linenum, 'whitespace/semicolon', 5,
'Line contains only semicolon. If this should be an empty statement, '
'use {} instead.')
elif (Search(r'\s+;\s*$', line) and
not Search(r'\bfor\b', line)):
error(filename, linenum, 'whitespace/semicolon', 5,
'Extra space before last semicolon. If this should be an empty '
'statement, use {} instead.')
def IsDecltype(clean_lines, linenum, column):
"""Check if the token ending on (linenum, column) is decltype().
Args:
clean_lines: A CleansedLines instance containing the file.
linenum: the number of the line to check.
column: end column of the token to check.
Returns:
True if this token is decltype() expression, False otherwise.
"""
(text, _, start_col) = ReverseCloseExpression(clean_lines, linenum, column)
if start_col < 0:
return False
if Search(r'\bdecltype\s*$', text[0:start_col]):
return True
return False
def CheckSectionSpacing(filename, clean_lines, class_info, linenum, error):
"""Checks for additional blank line issues related to sections.
Currently the only thing checked here is blank line before protected/private.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
class_info: A _ClassInfo objects.
linenum: The number of the line to check.
error: The function to call with any errors found.
"""
# Skip checks if the class is small, where small means 25 lines or less.
# 25 lines seems like a good cutoff since that's the usual height of
# terminals, and any class that can't fit in one screen can't really
# be considered "small".
#
# Also skip checks if we are on the first line. This accounts for
# classes that look like
# class Foo { public: ... };
#
# If we didn't find the end of the class, last_line would be zero,
# and the check will be skipped by the first condition.
if (class_info.last_line - class_info.starting_linenum <= 24 or
linenum <= class_info.starting_linenum):
return
matched = Match(r'\s*(public|protected|private):', clean_lines.lines[linenum])
if matched:
# Issue warning if the line before public/protected/private was
# not a blank line, but don't do this if the previous line contains
# "class" or "struct". This can happen two ways:
# - We are at the beginning of the class.
# - We are forward-declaring an inner class that is semantically
# private, but needed to be public for implementation reasons.
# Also ignores cases where the previous line ends with a backslash as can be
# common when defining classes in C macros.
prev_line = clean_lines.lines[linenum - 1]
if (not IsBlankLine(prev_line) and
not Search(r'\b(class|struct)\b', prev_line) and
not Search(r'\\$', prev_line)):
# Try a bit harder to find the beginning of the class. This is to
# account for multi-line base-specifier lists, e.g.:
# class Derived
# : public Base {
end_class_head = class_info.starting_linenum
for i in range(class_info.starting_linenum, linenum):
if Search(r'\{\s*$', clean_lines.lines[i]):
end_class_head = i
break
if end_class_head < linenum - 1:
error(filename, linenum, 'whitespace/blank_line', 3,
'"%s:" should be preceded by a blank line' % matched.group(1))
def GetPreviousNonBlankLine(clean_lines, linenum):
"""Return the most recent non-blank line and its line number.
Args:
clean_lines: A CleansedLines instance containing the file contents.
linenum: The number of the line to check.
Returns:
A tuple with two elements. The first element is the contents of the last
non-blank line before the current line, or the empty string if this is the
first non-blank line. The second is the line number of that line, or -1
if this is the first non-blank line.
"""
prevlinenum = linenum - 1
while prevlinenum >= 0:
prevline = clean_lines.elided[prevlinenum]
if not IsBlankLine(prevline): # if not a blank line...
return (prevline, prevlinenum)
prevlinenum -= 1
return ('', -1)
def CheckBraces(filename, clean_lines, linenum, error):
"""Looks for misplaced braces (e.g. at the end of line).
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found.
"""
line = clean_lines.elided[linenum] # get rid of comments and strings
if Match(r'\s*{\s*$', line):
# We allow an open brace to start a line in the case where someone is using
# braces in a block to explicitly create a new scope, which is commonly used
# to control the lifetime of stack-allocated variables. Braces are also
# used for brace initializers inside function calls. We don't detect this
# perfectly: we just don't complain if the last non-whitespace character on
# the previous non-blank line is ',', ';', ':', '(', '{', or '}', or if the
# previous line starts a preprocessor block. We also allow a brace on the
# following line if it is part of an array initialization and would not fit
# within the 80 character limit of the preceding line.
prevline = GetPreviousNonBlankLine(clean_lines, linenum)[0]
# if (not Search(r'[,;:}{(]\s*$', prevline) and
# not Match(r'\s*#', prevline) and
# not (GetLineWidth(prevline) > _line_length - 2 and '[]' in prevline)):
# error(filename, linenum, 'whitespace/braces', 4,
# '{ should almost always be at the end of the previous line')
# An else clause should be on the same line as the preceding closing brace.
# if Match(r'\s*else\b\s*(?:if\b|\{|$)', line):
# prevline = GetPreviousNonBlankLine(clean_lines, linenum)[0]
# if Match(r'\s*}\s*$', prevline):
# error(filename, linenum, 'whitespace/newline', 4,
# 'An else should appear on the same line as the preceding }')
# If braces come on one side of an else, they should be on both.
# However, we have to worry about "else if" that spans multiple lines!
if Search(r'else if\s*\(', line): # could be multi-line if
brace_on_left = bool(Search(r'}\s*else if\s*\(', line))
# find the ( after the if
pos = line.find('else if')
pos = line.find('(', pos)
if pos > 0:
(endline, _, endpos) = CloseExpression(clean_lines, linenum, pos)
brace_on_right = endline[endpos:].find('{') != -1
if brace_on_left != brace_on_right: # must be brace after if
error(filename, linenum, 'readability/braces', 5,
'If an else has a brace on one side, it should have it on both')
elif Search(r'}\s*else[^{]*$', line) or Match(r'[^}]*else\s*{', line):
error(filename, linenum, 'readability/braces', 5,
'If an else has a brace on one side, it should have it on both')
# Likewise, an else should never have the else clause on the same line
if Search(r'\belse [^\s{]', line) and not Search(r'\belse if\b', line):
error(filename, linenum, 'whitespace/newline', 4,
'Else clause should never be on same line as else (use 2 lines)')
# In the same way, a do/while should never be on one line
if Match(r'\s*do [^\s{]', line):
error(filename, linenum, 'whitespace/newline', 4,
'do/while clauses should not be on a single line')
# Check single-line if/else bodies. The style guide says 'curly braces are not
# required for single-line statements'. We additionally allow multi-line,
# single statements, but we reject anything with more than one semicolon in
# it. This means that the first semicolon after the if should be at the end of
# its line, and the line after that should have an indent level equal to or
# lower than the if. We also check for ambiguous if/else nesting without
# braces.
if_else_match = Search(r'\b(if\s*\(|else\b)', line)
if if_else_match and not Match(r'\s*#', line):
if_indent = GetIndentLevel(line)
endline, endlinenum, endpos = line, linenum, if_else_match.end()
if_match = Search(r'\bif\s*\(', line)
if if_match:
# This could be a multiline if condition, so find the end first.
pos = if_match.end() - 1
(endline, endlinenum, endpos) = CloseExpression(clean_lines, linenum, pos)
# Check for an opening brace, either directly after the if or on the next
# line. If found, this isn't a single-statement conditional.
if (not Match(r'\s*{', endline[endpos:])
and not (Match(r'\s*$', endline[endpos:])
and endlinenum < (len(clean_lines.elided) - 1)
and Match(r'\s*{', clean_lines.elided[endlinenum + 1]))):
while (endlinenum < len(clean_lines.elided)
and ';' not in clean_lines.elided[endlinenum][endpos:]):
endlinenum += 1
endpos = 0
if endlinenum < len(clean_lines.elided):
endline = clean_lines.elided[endlinenum]
# We allow a mix of whitespace and closing braces (e.g. for one-liner
# methods) and a single \ after the semicolon (for macros)
endpos = endline.find(';')
if not Match(r';[\s}]*(\\?)$', endline[endpos:]):
# Semicolon isn't the last character, there's something trailing.
# Output a warning if the semicolon is not contained inside
# a lambda expression.
if not Match(r'^[^{};]*\[[^\[\]]*\][^{}]*\{[^{}]*\}\s*\)*[;,]\s*$',
endline):
error(filename, linenum, 'readability/braces', 4,
'If/else bodies with multiple statements require braces')
elif endlinenum < len(clean_lines.elided) - 1:
# Make sure the next line is dedented
next_line = clean_lines.elided[endlinenum + 1]
next_indent = GetIndentLevel(next_line)
# With ambiguous nested if statements, this will error out on the
# if that *doesn't* match the else, regardless of whether it's the
# inner one or outer one.
if (if_match and Match(r'\s*else\b', next_line)
and next_indent != if_indent):
error(filename, linenum, 'readability/braces', 4,
'Else clause should be indented at the same level as if. '
'Ambiguous nested if/else chains require braces.')
elif next_indent > if_indent:
error(filename, linenum, 'readability/braces', 4,
'If/else bodies with multiple statements require braces')
def CheckTrailingSemicolon(filename, clean_lines, linenum, error):
"""Looks for redundant trailing semicolon.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found.
"""
line = clean_lines.elided[linenum]
# Block bodies should not be followed by a semicolon. Due to C++11
# brace initialization, there are more places where semicolons are
# required than not, so we use a whitelist approach to check these
# rather than a blacklist. These are the places where "};" should
# be replaced by just "}":
# 1. Some flavor of block following closing parenthesis:
# for (;;) {};
# while (...) {};
# switch (...) {};
# Function(...) {};
# if (...) {};
# if (...) else if (...) {};
#
# 2. else block:
# if (...) else {};
#
# 3. const member function:
# Function(...) const {};
#
# 4. Block following some statement:
# x = 42;
# {};
#
# 5. Block at the beginning of a function:
# Function(...) {
# {};
# }
#
# Note that naively checking for the preceding "{" will also match
# braces inside multi-dimensional arrays, but this is fine since
# that expression will not contain semicolons.
#
# 6. Block following another block:
# while (true) {}
# {};
#
# 7. End of namespaces:
# namespace {};
#
# These semicolons seems far more common than other kinds of
# redundant semicolons, possibly due to people converting classes
# to namespaces. For now we do not warn for this case.
#
# Try matching case 1 first.
match = Match(r'^(.*\)\s*)\{', line)
if match:
# Matched closing parenthesis (case 1). Check the token before the
# matching opening parenthesis, and don't warn if it looks like a
# macro. This avoids these false positives:
# - macro that defines a base class
# - multi-line macro that defines a base class
# - macro that defines the whole class-head
#
# But we still issue warnings for macros that we know are safe to
# warn, specifically:
# - TEST, TEST_F, TEST_P, MATCHER, MATCHER_P
# - TYPED_TEST
# - INTERFACE_DEF
# - EXCLUSIVE_LOCKS_REQUIRED, SHARED_LOCKS_REQUIRED, LOCKS_EXCLUDED:
#
# We implement a whitelist of safe macros instead of a blacklist of
# unsafe macros, even though the latter appears less frequently in
# google code and would have been easier to implement. This is because
# the downside for getting the whitelist wrong means some extra
# semicolons, while the downside for getting the blacklist wrong
# would result in compile errors.
#
# In addition to macros, we also don't want to warn on
# - Compound literals
# - Lambdas
# - alignas specifier with anonymous structs
# - decltype
closing_brace_pos = match.group(1).rfind(')')
opening_parenthesis = ReverseCloseExpression(
clean_lines, linenum, closing_brace_pos)
if opening_parenthesis[2] > -1:
line_prefix = opening_parenthesis[0][0:opening_parenthesis[2]]
macro = Search(r'\b([A-Z_][A-Z0-9_]*)\s*$', line_prefix)
func = Match(r'^(.*\])\s*$', line_prefix)
if ((macro and
macro.group(1) not in (
'TEST', 'TEST_F', 'MATCHER', 'MATCHER_P', 'TYPED_TEST',
'EXCLUSIVE_LOCKS_REQUIRED', 'SHARED_LOCKS_REQUIRED',
'LOCKS_EXCLUDED', 'INTERFACE_DEF')) or
(func and not Search(r'\boperator\s*\[\s*\]', func.group(1))) or
Search(r'\b(?:struct|union)\s+alignas\s*$', line_prefix) or
Search(r'\bdecltype$', line_prefix) or
Search(r'\s+=\s*$', line_prefix)):
match = None
if (match and
opening_parenthesis[1] > 1 and
Search(r'\]\s*$', clean_lines.elided[opening_parenthesis[1] - 1])):
# Multi-line lambda-expression
match = None
else:
# Try matching cases 2-3.
match = Match(r'^(.*(?:else|\)\s*const)\s*)\{', line)
if not match:
# Try matching cases 4-6. These are always matched on separate lines.
#
# Note that we can't simply concatenate the previous line to the
# current line and do a single match, otherwise we may output
# duplicate warnings for the blank line case:
# if (cond) {
# // blank line
# }
prevline = GetPreviousNonBlankLine(clean_lines, linenum)[0]
if prevline and Search(r'[;{}]\s*$', prevline):
match = Match(r'^(\s*)\{', line)
# Check matching closing brace
if match:
(endline, endlinenum, endpos) = CloseExpression(
clean_lines, linenum, len(match.group(1)))
if endpos > -1 and Match(r'^\s*;', endline[endpos:]):
# Current {} pair is eligible for semicolon check, and we have found
# the redundant semicolon, output warning here.
#
# Note: because we are scanning forward for opening braces, and
# outputting warnings for the matching closing brace, if there are
# nested blocks with trailing semicolons, we will get the error
# messages in reversed order.
# We need to check the line forward for NOLINT
raw_lines = clean_lines.raw_lines
ParseNolintSuppressions(filename, raw_lines[endlinenum-1], endlinenum-1,
error)
ParseNolintSuppressions(filename, raw_lines[endlinenum], endlinenum,
error)
error(filename, endlinenum, 'readability/braces', 4,
"You don't need a ; after a }")
def CheckEmptyBlockBody(filename, clean_lines, linenum, error):
"""Look for empty loop/conditional body with only a single semicolon.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found.
"""
# Search for loop keywords at the beginning of the line. Because only
# whitespaces are allowed before the keywords, this will also ignore most
# do-while-loops, since those lines should start with closing brace.
#
# We also check "if" blocks here, since an empty conditional block
# is likely an error.
line = clean_lines.elided[linenum]
matched = Match(r'\s*(for|while|if)\s*\(', line)
if matched:
# Find the end of the conditional expression.
(end_line, end_linenum, end_pos) = CloseExpression(
clean_lines, linenum, line.find('('))
# Output warning if what follows the condition expression is a semicolon.
# No warning for all other cases, including whitespace or newline, since we
# have a separate check for semicolons preceded by whitespace.
if end_pos >= 0 and Match(r';', end_line[end_pos:]):
if matched.group(1) == 'if':
error(filename, end_linenum, 'whitespace/empty_conditional_body', 5,
'Empty conditional bodies should use {}')
else:
error(filename, end_linenum, 'whitespace/empty_loop_body', 5,
'Empty loop bodies should use {} or continue')
# Check for if statements that have completely empty bodies (no comments)
# and no else clauses.
if end_pos >= 0 and matched.group(1) == 'if':
# Find the position of the opening { for the if statement.
# Return without logging an error if it has no brackets.
opening_linenum = end_linenum
opening_line_fragment = end_line[end_pos:]
# Loop until EOF or find anything that's not whitespace or opening {.
while not Search(r'^\s*\{', opening_line_fragment):
if Search(r'^(?!\s*$)', opening_line_fragment):
# Conditional has no brackets.
return
opening_linenum += 1
if opening_linenum == len(clean_lines.elided):
# Couldn't find conditional's opening { or any code before EOF.
return
opening_line_fragment = clean_lines.elided[opening_linenum]
# Set opening_line (opening_line_fragment may not be entire opening line).
opening_line = clean_lines.elided[opening_linenum]
# Find the position of the closing }.
opening_pos = opening_line_fragment.find('{')
if opening_linenum == end_linenum:
# We need to make opening_pos relative to the start of the entire line.
opening_pos += end_pos
(closing_line, closing_linenum, closing_pos) = CloseExpression(
clean_lines, opening_linenum, opening_pos)
if closing_pos < 0:
return
# Now construct the body of the conditional. This consists of the portion
# of the opening line after the {, all lines until the closing line,
# and the portion of the closing line before the }.
if (clean_lines.raw_lines[opening_linenum] !=
CleanseComments(clean_lines.raw_lines[opening_linenum])):
# Opening line ends with a comment, so conditional isn't empty.
return
if closing_linenum > opening_linenum:
# Opening line after the {. Ignore comments here since we checked above.
body = list(opening_line[opening_pos+1:])
# All lines until closing line, excluding closing line, with comments.
body.extend(clean_lines.raw_lines[opening_linenum+1:closing_linenum])
# Closing line before the }. Won't (and can't) have comments.
body.append(clean_lines.elided[closing_linenum][:closing_pos-1])
body = '\n'.join(body)
else:
# If statement has brackets and fits on a single line.
body = opening_line[opening_pos+1:closing_pos-1]
# Check if the body is empty
if not _EMPTY_CONDITIONAL_BODY_PATTERN.search(body):
return
# The body is empty. Now make sure there's not an else clause.
current_linenum = closing_linenum
current_line_fragment = closing_line[closing_pos:]
# Loop until EOF or find anything that's not whitespace or else clause.
while Search(r'^\s*$|^(?=\s*else)', current_line_fragment):
if Search(r'^(?=\s*else)', current_line_fragment):
# Found an else clause, so don't log an error.
return
current_linenum += 1
if current_linenum == len(clean_lines.elided):
break
current_line_fragment = clean_lines.elided[current_linenum]
# The body is empty and there's no else clause until EOF or other code.
error(filename, end_linenum, 'whitespace/empty_if_body', 4,
('If statement had no body and no else clause'))
def FindCheckMacro(line):
"""Find a replaceable CHECK-like macro.
Args:
line: line to search on.
Returns:
(macro name, start position), or (None, -1) if no replaceable
macro is found.
"""
for macro in _CHECK_MACROS:
i = line.find(macro)
if i >= 0:
# Find opening parenthesis. Do a regular expression match here
# to make sure that we are matching the expected CHECK macro, as
# opposed to some other macro that happens to contain the CHECK
# substring.
matched = Match(r'^(.*\b' + macro + r'\s*)\(', line)
if not matched:
continue
return (macro, len(matched.group(1)))
return (None, -1)
def CheckCheck(filename, clean_lines, linenum, error):
"""Checks the use of CHECK and EXPECT macros.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found.
"""
# Decide the set of replacement macros that should be suggested
lines = clean_lines.elided
(check_macro, start_pos) = FindCheckMacro(lines[linenum])
if not check_macro:
return
# Find end of the boolean expression by matching parentheses
(last_line, end_line, end_pos) = CloseExpression(
clean_lines, linenum, start_pos)
if end_pos < 0:
return
# If the check macro is followed by something other than a
# semicolon, assume users will log their own custom error messages
# and don't suggest any replacements.
if not Match(r'\s*;', last_line[end_pos:]):
return
if linenum == end_line:
expression = lines[linenum][start_pos + 1:end_pos - 1]
else:
expression = lines[linenum][start_pos + 1:]
for i in xrange(linenum + 1, end_line):
expression += lines[i]
expression += last_line[0:end_pos - 1]
# Parse expression so that we can take parentheses into account.
# This avoids false positives for inputs like "CHECK((a < 4) == b)",
# which is not replaceable by CHECK_LE.
lhs = ''
rhs = ''
operator = None
while expression:
matched = Match(r'^\s*(<<|<<=|>>|>>=|->\*|->|&&|\|\||'
r'==|!=|>=|>|<=|<|\()(.*)$', expression)
if matched:
token = matched.group(1)
if token == '(':
# Parenthesized operand
expression = matched.group(2)
(end, _) = FindEndOfExpressionInLine(expression, 0, ['('])
if end < 0:
return # Unmatched parenthesis
lhs += '(' + expression[0:end]
expression = expression[end:]
elif token in ('&&', '||'):
# Logical and/or operators. This means the expression
# contains more than one term, for example:
# CHECK(42 < a && a < b);
#
# These are not replaceable with CHECK_LE, so bail out early.
return
elif token in ('<<', '<<=', '>>', '>>=', '->*', '->'):
# Non-relational operator
lhs += token
expression = matched.group(2)
else:
# Relational operator
operator = token
rhs = matched.group(2)
break
else:
# Unparenthesized operand. Instead of appending to lhs one character
# at a time, we do another regular expression match to consume several
# characters at once if possible. Trivial benchmark shows that this
# is more efficient when the operands are longer than a single
# character, which is generally the case.
matched = Match(r'^([^-=!<>()&|]+)(.*)$', expression)
if not matched:
matched = Match(r'^(\s*\S)(.*)$', expression)
if not matched:
break
lhs += matched.group(1)
expression = matched.group(2)
# Only apply checks if we got all parts of the boolean expression
if not (lhs and operator and rhs):
return
# Check that rhs do not contain logical operators. We already know
# that lhs is fine since the loop above parses out && and ||.
if rhs.find('&&') > -1 or rhs.find('||') > -1:
return
# At least one of the operands must be a constant literal. This is
# to avoid suggesting replacements for unprintable things like
# CHECK(variable != iterator)
#
# The following pattern matches decimal, hex integers, strings, and
# characters (in that order).
lhs = lhs.strip()
rhs = rhs.strip()
match_constant = r'^([-+]?(\d+|0[xX][0-9a-fA-F]+)[lLuU]{0,3}|".*"|\'.*\')$'
if Match(match_constant, lhs) or Match(match_constant, rhs):
# Note: since we know both lhs and rhs, we can provide a more
# descriptive error message like:
# Consider using CHECK_EQ(x, 42) instead of CHECK(x == 42)
# Instead of:
# Consider using CHECK_EQ instead of CHECK(a == b)
#
# We are still keeping the less descriptive message because if lhs
# or rhs gets long, the error message might become unreadable.
error(filename, linenum, 'readability/check', 2,
'Consider using %s instead of %s(a %s b)' % (
_CHECK_REPLACEMENT[check_macro][operator],
check_macro, operator))
def CheckAltTokens(filename, clean_lines, linenum, error):
"""Check alternative keywords being used in boolean expressions.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found.
"""
line = clean_lines.elided[linenum]
# Avoid preprocessor lines
if Match(r'^\s*#', line):
return
# Last ditch effort to avoid multi-line comments. This will not help
# if the comment started before the current line or ended after the
# current line, but it catches most of the false positives. At least,
# it provides a way to workaround this warning for people who use
# multi-line comments in preprocessor macros.
#
# TODO(unknown): remove this once cpplint has better support for
# multi-line comments.
if line.find('/*') >= 0 or line.find('*/') >= 0:
return
for match in _ALT_TOKEN_REPLACEMENT_PATTERN.finditer(line):
error(filename, linenum, 'readability/alt_tokens', 2,
'Use operator %s instead of %s' % (
_ALT_TOKEN_REPLACEMENT[match.group(1)], match.group(1)))
def GetLineWidth(line):
"""Determines the width of the line in column positions.
Args:
line: A string, which may be a Unicode string.
Returns:
The width of the line in column positions, accounting for Unicode
combining characters and wide characters.
"""
if isinstance(line, unicode):
width = 0
for uc in unicodedata.normalize('NFC', line):
if unicodedata.east_asian_width(uc) in ('W', 'F'):
width += 2
elif not unicodedata.combining(uc):
width += 1
return width
else:
return len(line)
def CheckStyle(filename, clean_lines, linenum, file_extension, nesting_state,
error):
"""Checks rules from the 'C++ style rules' section of cppguide.html.
Most of these rules are hard to test (naming, comment style), but we
do what we can. In particular we check for 2-space indents, line lengths,
tab usage, spaces inside code, etc.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
file_extension: The extension (without the dot) of the filename.
nesting_state: A NestingState instance which maintains information about
the current stack of nested blocks being parsed.
error: The function to call with any errors found.
"""
# Don't use "elided" lines here, otherwise we can't check commented lines.
# Don't want to use "raw" either, because we don't want to check inside C++11
# raw strings,
raw_lines = clean_lines.lines_without_raw_strings
line = raw_lines[linenum]
prev = raw_lines[linenum - 1] if linenum > 0 else ''
# if line.find('\t') != -1:
# error(filename, linenum, 'whitespace/tab', 1,
# 'Tab found; better to use spaces')
# One or three blank spaces at the beginning of the line is weird; it's
# hard to reconcile that with 2-space indents.
# NOTE: here are the conditions rob pike used for his tests. Mine aren't
# as sophisticated, but it may be worth becoming so: RLENGTH==initial_spaces
# if(RLENGTH > 20) complain = 0;
# if(match($0, " +(error|private|public|protected):")) complain = 0;
# if(match(prev, "&& *$")) complain = 0;
# if(match(prev, "\\|\\| *$")) complain = 0;
# if(match(prev, "[\",=><] *$")) complain = 0;
# if(match($0, " <<")) complain = 0;
# if(match(prev, " +for \\(")) complain = 0;
# if(prevodd && match(prevprev, " +for \\(")) complain = 0;
scope_or_label_pattern = r'\s*\w+\s*:\s*\\?$'
classinfo = nesting_state.InnermostClass()
initial_spaces = 0
cleansed_line = clean_lines.elided[linenum]
while initial_spaces < len(line) and line[initial_spaces] == ' ':
initial_spaces += 1
# There are certain situations we allow one space, notably for
# section labels, and also lines containing multi-line raw strings.
# We also don't check for lines that look like continuation lines
# (of lines ending in double quotes, commas, equals, or angle brackets)
# because the rules for how to indent those are non-trivial.
if (not Search(r'[",=><] *$', prev) and
(initial_spaces == 1 or initial_spaces == 3) and
not Match(scope_or_label_pattern, cleansed_line) and
not (clean_lines.raw_lines[linenum] != line and
Match(r'^\s*""', line))):
error(filename, linenum, 'whitespace/indent', 3,
'Weird number of spaces at line-start. '
'Are you using a 2-space indent?')
if line and line[-1].isspace():
error(filename, linenum, 'whitespace/end_of_line', 4,
'Line ends in whitespace. Consider deleting these extra spaces.')
# Check if the line is a header guard.
is_header_guard = False
if IsHeaderExtension(file_extension):
cppvar = GetHeaderGuardCPPVariable(filename)
if (line.startswith('#ifndef %s' % cppvar) or
line.startswith('#define %s' % cppvar) or
line.startswith('#endif // %s' % cppvar)):
is_header_guard = True
# #include lines and header guards can be long, since there's no clean way to
# split them.
#
# URLs can be long too. It's possible to split these, but it makes them
# harder to cut&paste.
#
# The "$Id:...$" comment may also get very long without it being the
# developers fault.
if (not line.startswith('#include') and not is_header_guard and
not Match(r'^\s*//.*http(s?)://\S*$', line) and
not Match(r'^\s*//\s*[^\s]*$', line) and
not Match(r'^// \$Id:.*#[0-9]+ \$$', line)):
line_width = GetLineWidth(line)
if line_width > _line_length:
error(filename, linenum, 'whitespace/line_length', 2,
'Lines should be <= %i characters long' % _line_length)
if (cleansed_line.count(';') > 1 and
# for loops are allowed two ;'s (and may run over two lines).
cleansed_line.find('for') == -1 and
(GetPreviousNonBlankLine(clean_lines, linenum)[0].find('for') == -1 or
GetPreviousNonBlankLine(clean_lines, linenum)[0].find(';') != -1) and
# It's ok to have many commands in a switch case that fits in 1 line
not ((cleansed_line.find('case ') != -1 or
cleansed_line.find('default:') != -1) and
cleansed_line.find('break;') != -1)):
error(filename, linenum, 'whitespace/newline', 0,
'More than one command on the same line')
# Some more style checks
CheckBraces(filename, clean_lines, linenum, error)
CheckTrailingSemicolon(filename, clean_lines, linenum, error)
CheckEmptyBlockBody(filename, clean_lines, linenum, error)
CheckAccess(filename, clean_lines, linenum, nesting_state, error)
CheckSpacing(filename, clean_lines, linenum, nesting_state, error)
CheckOperatorSpacing(filename, clean_lines, linenum, error)
CheckParenthesisSpacing(filename, clean_lines, linenum, error)
CheckCommaSpacing(filename, clean_lines, linenum, error)
CheckBracesSpacing(filename, clean_lines, linenum, nesting_state, error)
CheckSpacingForFunctionCall(filename, clean_lines, linenum, error)
CheckCheck(filename, clean_lines, linenum, error)
CheckAltTokens(filename, clean_lines, linenum, error)
classinfo = nesting_state.InnermostClass()
if classinfo:
CheckSectionSpacing(filename, clean_lines, classinfo, linenum, error)
_RE_PATTERN_INCLUDE = re.compile(r'^\s*#\s*include\s*([<"])([^>"]*)[>"].*$')
# Matches the first component of a filename delimited by -s and _s. That is:
# _RE_FIRST_COMPONENT.match('foo').group(0) == 'foo'
# _RE_FIRST_COMPONENT.match('foo.cc').group(0) == 'foo'
# _RE_FIRST_COMPONENT.match('foo-bar_baz.cc').group(0) == 'foo'
# _RE_FIRST_COMPONENT.match('foo_bar-baz.cc').group(0) == 'foo'
_RE_FIRST_COMPONENT = re.compile(r'^[^-_.]+')
def _DropCommonSuffixes(filename):
"""Drops common suffixes like _test.cc or -inl.h from filename.
For example:
>>> _DropCommonSuffixes('foo/foo-inl.h')
'foo/foo'
>>> _DropCommonSuffixes('foo/bar/foo.cc')
'foo/bar/foo'
>>> _DropCommonSuffixes('foo/foo_internal.h')
'foo/foo'
>>> _DropCommonSuffixes('foo/foo_unusualinternal.h')
'foo/foo_unusualinternal'
Args:
filename: The input filename.
Returns:
The filename with the common suffix removed.
"""
for suffix in ('test.cc', 'regtest.cc', 'unittest.cc',
'inl.h', 'impl.h', 'internal.h'):
if (filename.endswith(suffix) and len(filename) > len(suffix) and
filename[-len(suffix) - 1] in ('-', '_')):
return filename[:-len(suffix) - 1]
return os.path.splitext(filename)[0]
def _ClassifyInclude(fileinfo, include, is_system):
"""Figures out what kind of header 'include' is.
Args:
fileinfo: The current file cpplint is running over. A FileInfo instance.
include: The path to a #included file.
is_system: True if the #include used <> rather than "".
Returns:
One of the _XXX_HEADER constants.
For example:
>>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'stdio.h', True)
_C_SYS_HEADER
>>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'string', True)
_CPP_SYS_HEADER
>>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'foo/foo.h', False)
_LIKELY_MY_HEADER
>>> _ClassifyInclude(FileInfo('foo/foo_unknown_extension.cc'),
... 'bar/foo_other_ext.h', False)
_POSSIBLE_MY_HEADER
>>> _ClassifyInclude(FileInfo('foo/foo.cc'), 'foo/bar.h', False)
_OTHER_HEADER
"""
# This is a list of all standard c++ header files, except
# those already checked for above.
is_cpp_h = include in _CPP_HEADERS
if is_system:
if is_cpp_h:
return _CPP_SYS_HEADER
else:
return _C_SYS_HEADER
# If the target file and the include we're checking share a
# basename when we drop common extensions, and the include
# lives in . , then it's likely to be owned by the target file.
target_dir, target_base = (
os.path.split(_DropCommonSuffixes(fileinfo.RepositoryName())))
include_dir, include_base = os.path.split(_DropCommonSuffixes(include))
if target_base == include_base and (
include_dir == target_dir or
include_dir == os.path.normpath(target_dir + '/../public')):
return _LIKELY_MY_HEADER
# If the target and include share some initial basename
# component, it's possible the target is implementing the
# include, so it's allowed to be first, but we'll never
# complain if it's not there.
target_first_component = _RE_FIRST_COMPONENT.match(target_base)
include_first_component = _RE_FIRST_COMPONENT.match(include_base)
if (target_first_component and include_first_component and
target_first_component.group(0) ==
include_first_component.group(0)):
return _POSSIBLE_MY_HEADER
return _OTHER_HEADER
def CheckIncludeLine(filename, clean_lines, linenum, include_state, error):
"""Check rules that are applicable to #include lines.
Strings on #include lines are NOT removed from elided line, to make
certain tasks easier. However, to prevent false positives, checks
applicable to #include lines in CheckLanguage must be put here.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
include_state: An _IncludeState instance in which the headers are inserted.
error: The function to call with any errors found.
"""
fileinfo = FileInfo(filename)
line = clean_lines.lines[linenum]
# "include" should use the new style "foo/bar.h" instead of just "bar.h"
# Only do this check if the included header follows google naming
# conventions. If not, assume that it's a 3rd party API that
# requires special include conventions.
#
# We also make an exception for Lua headers, which follow google
# naming convention but not the include convention.
match = Match(r'#include\s*"([^/]+\.h)"', line)
if match and not _THIRD_PARTY_HEADERS_PATTERN.match(match.group(1)):
error(filename, linenum, 'build/include', 4,
'Include the directory when naming .h files')
# we shouldn't include a file more than once. actually, there are a
# handful of instances where doing so is okay, but in general it's
# not.
match = _RE_PATTERN_INCLUDE.search(line)
if match:
include = match.group(2)
is_system = (match.group(1) == '<')
duplicate_line = include_state.FindHeader(include)
if duplicate_line >= 0:
error(filename, linenum, 'build/include', 4,
'"%s" already included at %s:%s' %
(include, filename, duplicate_line))
elif (include.endswith('.cc') and
os.path.dirname(fileinfo.RepositoryName()) != os.path.dirname(include)):
error(filename, linenum, 'build/include', 4,
'Do not include .cc files from other packages')
elif not _THIRD_PARTY_HEADERS_PATTERN.match(include):
include_state.include_list[-1].append((include, linenum))
# We want to ensure that headers appear in the right order:
# 1) for foo.cc, foo.h (preferred location)
# 2) c system files
# 3) cpp system files
# 4) for foo.cc, foo.h (deprecated location)
# 5) other google headers
#
# We classify each include statement as one of those 5 types
# using a number of techniques. The include_state object keeps
# track of the highest type seen, and complains if we see a
# lower type after that.
error_message = include_state.CheckNextIncludeOrder(
_ClassifyInclude(fileinfo, include, is_system))
if error_message:
error(filename, linenum, 'build/include_order', 4,
'%s. Should be: %s.h, c system, c++ system, other.' %
(error_message, fileinfo.BaseName()))
canonical_include = include_state.CanonicalizeAlphabeticalOrder(include)
if not include_state.IsInAlphabeticalOrder(
clean_lines, linenum, canonical_include):
error(filename, linenum, 'build/include_alpha', 4,
'Include "%s" not in alphabetical order' % include)
include_state.SetLastHeader(canonical_include)
def _GetTextInside(text, start_pattern):
r"""Retrieves all the text between matching open and close parentheses.
Given a string of lines and a regular expression string, retrieve all the text
following the expression and between opening punctuation symbols like
(, [, or {, and the matching close-punctuation symbol. This properly nested
occurrences of the punctuations, so for the text like
printf(a(), b(c()));
a call to _GetTextInside(text, r'printf\(') will return 'a(), b(c())'.
start_pattern must match string having an open punctuation symbol at the end.
Args:
text: The lines to extract text. Its comments and strings must be elided.
It can be single line and can span multiple lines.
start_pattern: The regexp string indicating where to start extracting
the text.
Returns:
The extracted text.
None if either the opening string or ending punctuation could not be found.
"""
# TODO(unknown): Audit cpplint.py to see what places could be profitably
# rewritten to use _GetTextInside (and use inferior regexp matching today).
# Give opening punctuations to get the matching close-punctuations.
matching_punctuation = {'(': ')', '{': '}', '[': ']'}
closing_punctuation = set(matching_punctuation.itervalues())
# Find the position to start extracting text.
match = re.search(start_pattern, text, re.M)
if not match: # start_pattern not found in text.
return None
start_position = match.end(0)
assert start_position > 0, (
'start_pattern must ends with an opening punctuation.')
assert text[start_position - 1] in matching_punctuation, (
'start_pattern must ends with an opening punctuation.')
# Stack of closing punctuations we expect to have in text after position.
punctuation_stack = [matching_punctuation[text[start_position - 1]]]
position = start_position
while punctuation_stack and position < len(text):
if text[position] == punctuation_stack[-1]:
punctuation_stack.pop()
elif text[position] in closing_punctuation:
# A closing punctuation without matching opening punctuations.
return None
elif text[position] in matching_punctuation:
punctuation_stack.append(matching_punctuation[text[position]])
position += 1
if punctuation_stack:
# Opening punctuations left without matching close-punctuations.
return None
# punctuations match.
return text[start_position:position - 1]
# Patterns for matching call-by-reference parameters.
#
# Supports nested templates up to 2 levels deep using this messy pattern:
# < (?: < (?: < [^<>]*
# >
# | [^<>] )*
# >
# | [^<>] )*
# >
_RE_PATTERN_IDENT = r'[_a-zA-Z]\w*' # =~ [[:alpha:]][[:alnum:]]*
_RE_PATTERN_TYPE = (
r'(?:const\s+)?(?:typename\s+|class\s+|struct\s+|union\s+|enum\s+)?'
r'(?:\w|'
r'\s*<(?:<(?:<[^<>]*>|[^<>])*>|[^<>])*>|'
r'::)+')
# A call-by-reference parameter ends with '& identifier'.
_RE_PATTERN_REF_PARAM = re.compile(
r'(' + _RE_PATTERN_TYPE + r'(?:\s*(?:\bconst\b|[*]))*\s*'
r'&\s*' + _RE_PATTERN_IDENT + r')\s*(?:=[^,()]+)?[,)]')
# A call-by-const-reference parameter either ends with 'const& identifier'
# or looks like 'const type& identifier' when 'type' is atomic.
_RE_PATTERN_CONST_REF_PARAM = (
r'(?:.*\s*\bconst\s*&\s*' + _RE_PATTERN_IDENT +
r'|const\s+' + _RE_PATTERN_TYPE + r'\s*&\s*' + _RE_PATTERN_IDENT + r')')
# Stream types.
_RE_PATTERN_REF_STREAM_PARAM = (
r'(?:.*stream\s*&\s*' + _RE_PATTERN_IDENT + r')')
def CheckLanguage(filename, clean_lines, linenum, file_extension,
include_state, nesting_state, error):
"""Checks rules from the 'C++ language rules' section of cppguide.html.
Some of these rules are hard to test (function overloading, using
uint32 inappropriately), but we do the best we can.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
file_extension: The extension (without the dot) of the filename.
include_state: An _IncludeState instance in which the headers are inserted.
nesting_state: A NestingState instance which maintains information about
the current stack of nested blocks being parsed.
error: The function to call with any errors found.
"""
# If the line is empty or consists of entirely a comment, no need to
# check it.
line = clean_lines.elided[linenum]
if not line:
return
match = _RE_PATTERN_INCLUDE.search(line)
if match:
CheckIncludeLine(filename, clean_lines, linenum, include_state, error)
return
# Reset include state across preprocessor directives. This is meant
# to silence warnings for conditional includes.
match = Match(r'^\s*#\s*(if|ifdef|ifndef|elif|else|endif)\b', line)
if match:
include_state.ResetSection(match.group(1))
# Make Windows paths like Unix.
fullname = os.path.abspath(filename).replace('\\', '/')
# Perform other checks now that we are sure that this is not an include line
CheckCasts(filename, clean_lines, linenum, error)
CheckGlobalStatic(filename, clean_lines, linenum, error)
CheckPrintf(filename, clean_lines, linenum, error)
if IsHeaderExtension(file_extension):
# TODO(unknown): check that 1-arg constructors are explicit.
# How to tell it's a constructor?
# (handled in CheckForNonStandardConstructs for now)
# TODO(unknown): check that classes declare or disable copy/assign
# (level 1 error)
pass
# Check if people are using the verboten C basic types. The only exception
# we regularly allow is "unsigned short port" for port.
if Search(r'\bshort port\b', line):
if not Search(r'\bunsigned short port\b', line):
error(filename, linenum, 'runtime/int', 4,
'Use "unsigned short" for ports, not "short"')
else:
match = Search(r'\b(short|long(?! +double)|long long)\b', line)
if match:
error(filename, linenum, 'runtime/int', 4,
'Use int16/int64/etc, rather than the C type %s' % match.group(1))
# Check if some verboten operator overloading is going on
# TODO(unknown): catch out-of-line unary operator&:
# class X {};
# int operator&(const X& x) { return 42; } // unary operator&
# The trick is it's hard to tell apart from binary operator&:
# class Y { int operator&(const Y& x) { return 23; } }; // binary operator&
if Search(r'\boperator\s*&\s*\(\s*\)', line):
error(filename, linenum, 'runtime/operator', 4,
'Unary operator& is dangerous. Do not use it.')
# Check for suspicious usage of "if" like
# } if (a == b) {
if Search(r'\}\s*if\s*\(', line):
error(filename, linenum, 'readability/braces', 4,
'Did you mean "else if"? If not, start a new line for "if".')
# Check for potential format string bugs like printf(foo).
# We constrain the pattern not to pick things like DocidForPrintf(foo).
# Not perfect but it can catch printf(foo.c_str()) and printf(foo->c_str())
# TODO(unknown): Catch the following case. Need to change the calling
# convention of the whole function to process multiple line to handle it.
# printf(
# boy_this_is_a_really_long_variable_that_cannot_fit_on_the_prev_line);
printf_args = _GetTextInside(line, r'(?i)\b(string)?printf\s*\(')
if printf_args:
match = Match(r'([\w.\->()]+)$', printf_args)
if match and match.group(1) != '__VA_ARGS__':
function_name = re.search(r'\b((?:string)?printf)\s*\(',
line, re.I).group(1)
error(filename, linenum, 'runtime/printf', 4,
'Potential format string bug. Do %s("%%s", %s) instead.'
% (function_name, match.group(1)))
# Check for potential memset bugs like memset(buf, sizeof(buf), 0).
match = Search(r'memset\s*\(([^,]*),\s*([^,]*),\s*0\s*\)', line)
if match and not Match(r"^''|-?[0-9]+|0x[0-9A-Fa-f]$", match.group(2)):
error(filename, linenum, 'runtime/memset', 4,
'Did you mean "memset(%s, 0, %s)"?'
% (match.group(1), match.group(2)))
if Search(r'\busing namespace\b', line):
error(filename, linenum, 'build/namespaces', 5,
'Do not use namespace using-directives. '
'Use using-declarations instead.')
# Detect variable-length arrays.
match = Match(r'\s*(.+::)?(\w+) [a-z]\w*\[(.+)];', line)
if (match and match.group(2) != 'return' and match.group(2) != 'delete' and
match.group(3).find(']') == -1):
# Split the size using space and arithmetic operators as delimiters.
# If any of the resulting tokens are not compile time constants then
# report the error.
tokens = re.split(r'\s|\+|\-|\*|\/|<<|>>]', match.group(3))
is_const = True
skip_next = False
for tok in tokens:
if skip_next:
skip_next = False
continue
if Search(r'sizeof\(.+\)', tok): continue
if Search(r'arraysize\(\w+\)', tok): continue
tok = tok.lstrip('(')
tok = tok.rstrip(')')
if not tok: continue
if Match(r'\d+', tok): continue
if Match(r'0[xX][0-9a-fA-F]+', tok): continue
if Match(r'k[A-Z0-9]\w*', tok): continue
if Match(r'(.+::)?k[A-Z0-9]\w*', tok): continue
if Match(r'(.+::)?[A-Z][A-Z0-9_]*', tok): continue
# A catch all for tricky sizeof cases, including 'sizeof expression',
# 'sizeof(*type)', 'sizeof(const type)', 'sizeof(struct StructName)'
# requires skipping the next token because we split on ' ' and '*'.
if tok.startswith('sizeof'):
skip_next = True
continue
is_const = False
break
if not is_const:
error(filename, linenum, 'runtime/arrays', 1,
'Do not use variable-length arrays. Use an appropriately named '
"('k' followed by CamelCase) compile-time constant for the size.")
# Check for use of unnamed namespaces in header files. Registration
# macros are typically OK, so we allow use of "namespace {" on lines
# that end with backslashes.
if (IsHeaderExtension(file_extension)
and Search(r'\bnamespace\s*{', line)
and line[-1] != '\\'):
error(filename, linenum, 'build/namespaces', 4,
'Do not use unnamed namespaces in header files. See '
'https://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Namespaces'
' for more information.')
def CheckGlobalStatic(filename, clean_lines, linenum, error):
"""Check for unsafe global or static objects.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found.
"""
line = clean_lines.elided[linenum]
# Match two lines at a time to support multiline declarations
if linenum + 1 < clean_lines.NumLines() and not Search(r'[;({]', line):
line += clean_lines.elided[linenum + 1].strip()
# Check for people declaring static/global STL strings at the top level.
# This is dangerous because the C++ language does not guarantee that
# globals with constructors are initialized before the first access, and
# also because globals can be destroyed when some threads are still running.
# TODO(unknown): Generalize this to also find static unique_ptr instances.
# TODO(unknown): File bugs for clang-tidy to find these.
match = Match(
r'((?:|static +)(?:|const +))(?::*std::)?string( +const)? +'
r'([a-zA-Z0-9_:]+)\b(.*)',
line)
# Remove false positives:
# - String pointers (as opposed to values).
# string *pointer
# const string *pointer
# string const *pointer
# string *const pointer
#
# - Functions and template specializations.
# string Function<Type>(...
# string Class<Type>::Method(...
#
# - Operators. These are matched separately because operator names
# cross non-word boundaries, and trying to match both operators
# and functions at the same time would decrease accuracy of
# matching identifiers.
# string Class::operator*()
if (match and
not Search(r'\bstring\b(\s+const)?\s*[\*\&]\s*(const\s+)?\w', line) and
not Search(r'\boperator\W', line) and
not Match(r'\s*(<.*>)?(::[a-zA-Z0-9_]+)*\s*\(([^"]|$)', match.group(4))):
if Search(r'\bconst\b', line):
error(filename, linenum, 'runtime/string', 4,
'For a static/global string constant, use a C style string '
'instead: "%schar%s %s[]".' %
(match.group(1), match.group(2) or '', match.group(3)))
else:
error(filename, linenum, 'runtime/string', 4,
'Static/global string variables are not permitted.')
if (Search(r'\b([A-Za-z0-9_]*_)\(\1\)', line) or
Search(r'\b([A-Za-z0-9_]*_)\(CHECK_NOTNULL\(\1\)\)', line)):
error(filename, linenum, 'runtime/init', 4,
'You seem to be initializing a member variable with itself.')
def CheckPrintf(filename, clean_lines, linenum, error):
"""Check for printf related issues.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found.
"""
line = clean_lines.elided[linenum]
# When snprintf is used, the second argument shouldn't be a literal.
match = Search(r'snprintf\s*\(([^,]*),\s*([0-9]*)\s*,', line)
if match and match.group(2) != '0':
# If 2nd arg is zero, snprintf is used to calculate size.
error(filename, linenum, 'runtime/printf', 3,
'If you can, use sizeof(%s) instead of %s as the 2nd arg '
'to snprintf.' % (match.group(1), match.group(2)))
# Check if some verboten C functions are being used.
if Search(r'\bsprintf\s*\(', line):
error(filename, linenum, 'runtime/printf', 5,
'Never use sprintf. Use snprintf instead.')
match = Search(r'\b(strcpy|strcat)\s*\(', line)
if match:
error(filename, linenum, 'runtime/printf', 4,
'Almost always, snprintf is better than %s' % match.group(1))
def IsDerivedFunction(clean_lines, linenum):
"""Check if current line contains an inherited function.
Args:
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
Returns:
True if current line contains a function with "override"
virt-specifier.
"""
# Scan back a few lines for start of current function
for i in xrange(linenum, max(-1, linenum - 10), -1):
match = Match(r'^([^()]*\w+)\(', clean_lines.elided[i])
if match:
# Look for "override" after the matching closing parenthesis
line, _, closing_paren = CloseExpression(
clean_lines, i, len(match.group(1)))
return (closing_paren >= 0 and
Search(r'\boverride\b', line[closing_paren:]))
return False
def IsOutOfLineMethodDefinition(clean_lines, linenum):
"""Check if current line contains an out-of-line method definition.
Args:
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
Returns:
True if current line contains an out-of-line method definition.
"""
# Scan back a few lines for start of current function
for i in xrange(linenum, max(-1, linenum - 10), -1):
if Match(r'^([^()]*\w+)\(', clean_lines.elided[i]):
return Match(r'^[^()]*\w+::\w+\(', clean_lines.elided[i]) is not None
return False
def IsInitializerList(clean_lines, linenum):
"""Check if current line is inside constructor initializer list.
Args:
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
Returns:
True if current line appears to be inside constructor initializer
list, False otherwise.
"""
for i in xrange(linenum, 1, -1):
line = clean_lines.elided[i]
if i == linenum:
remove_function_body = Match(r'^(.*)\{\s*$', line)
if remove_function_body:
line = remove_function_body.group(1)
if Search(r'\s:\s*\w+[({]', line):
# A lone colon tend to indicate the start of a constructor
# initializer list. It could also be a ternary operator, which
# also tend to appear in constructor initializer lists as
# opposed to parameter lists.
return True
if Search(r'\}\s*,\s*$', line):
# A closing brace followed by a comma is probably the end of a
# brace-initialized member in constructor initializer list.
return True
if Search(r'[{};]\s*$', line):
# Found one of the following:
# - A closing brace or semicolon, probably the end of the previous
# function.
# - An opening brace, probably the start of current class or namespace.
#
# Current line is probably not inside an initializer list since
# we saw one of those things without seeing the starting colon.
return False
# Got to the beginning of the file without seeing the start of
# constructor initializer list.
return False
def CheckForNonConstReference(filename, clean_lines, linenum,
nesting_state, error):
"""Check for non-const references.
Separate from CheckLanguage since it scans backwards from current
line, instead of scanning forward.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
nesting_state: A NestingState instance which maintains information about
the current stack of nested blocks being parsed.
error: The function to call with any errors found.
"""
# Do nothing if there is no '&' on current line.
line = clean_lines.elided[linenum]
if '&' not in line:
return
# If a function is inherited, current function doesn't have much of
# a choice, so any non-const references should not be blamed on
# derived function.
if IsDerivedFunction(clean_lines, linenum):
return
# Don't warn on out-of-line method definitions, as we would warn on the
# in-line declaration, if it isn't marked with 'override'.
if IsOutOfLineMethodDefinition(clean_lines, linenum):
return
# Long type names may be broken across multiple lines, usually in one
# of these forms:
# LongType
# ::LongTypeContinued &identifier
# LongType::
# LongTypeContinued &identifier
# LongType<
# ...>::LongTypeContinued &identifier
#
# If we detected a type split across two lines, join the previous
# line to current line so that we can match const references
# accordingly.
#
# Note that this only scans back one line, since scanning back
# arbitrary number of lines would be expensive. If you have a type
# that spans more than 2 lines, please use a typedef.
if linenum > 1:
previous = None
if Match(r'\s*::(?:[\w<>]|::)+\s*&\s*\S', line):
# previous_line\n + ::current_line
previous = Search(r'\b((?:const\s*)?(?:[\w<>]|::)+[\w<>])\s*$',
clean_lines.elided[linenum - 1])
elif Match(r'\s*[a-zA-Z_]([\w<>]|::)+\s*&\s*\S', line):
# previous_line::\n + current_line
previous = Search(r'\b((?:const\s*)?(?:[\w<>]|::)+::)\s*$',
clean_lines.elided[linenum - 1])
if previous:
line = previous.group(1) + line.lstrip()
else:
# Check for templated parameter that is split across multiple lines
endpos = line.rfind('>')
if endpos > -1:
(_, startline, startpos) = ReverseCloseExpression(
clean_lines, linenum, endpos)
if startpos > -1 and startline < linenum:
# Found the matching < on an earlier line, collect all
# pieces up to current line.
line = ''
for i in xrange(startline, linenum + 1):
line += clean_lines.elided[i].strip()
# Check for non-const references in function parameters. A single '&' may
# found in the following places:
# inside expression: binary & for bitwise AND
# inside expression: unary & for taking the address of something
# inside declarators: reference parameter
# We will exclude the first two cases by checking that we are not inside a
# function body, including one that was just introduced by a trailing '{'.
# TODO(unknown): Doesn't account for 'catch(Exception& e)' [rare].
if (nesting_state.previous_stack_top and
not (isinstance(nesting_state.previous_stack_top, _ClassInfo) or
isinstance(nesting_state.previous_stack_top, _NamespaceInfo))):
# Not at toplevel, not within a class, and not within a namespace
return
# Avoid initializer lists. We only need to scan back from the
# current line for something that starts with ':'.
#
# We don't need to check the current line, since the '&' would
# appear inside the second set of parentheses on the current line as
# opposed to the first set.
if linenum > 0:
for i in xrange(linenum - 1, max(0, linenum - 10), -1):
previous_line = clean_lines.elided[i]
if not Search(r'[),]\s*$', previous_line):
break
if Match(r'^\s*:\s+\S', previous_line):
return
# Avoid preprocessors
if Search(r'\\\s*$', line):
return
# Avoid constructor initializer lists
if IsInitializerList(clean_lines, linenum):
return
# We allow non-const references in a few standard places, like functions
# called "swap()" or iostream operators like "<<" or ">>". Do not check
# those function parameters.
#
# We also accept & in static_assert, which looks like a function but
# it's actually a declaration expression.
whitelisted_functions = (r'(?:[sS]wap(?:<\w:+>)?|'
r'operator\s*[<>][<>]|'
r'static_assert|COMPILE_ASSERT'
r')\s*\(')
if Search(whitelisted_functions, line):
return
elif not Search(r'\S+\([^)]*$', line):
# Don't see a whitelisted function on this line. Actually we
# didn't see any function name on this line, so this is likely a
# multi-line parameter list. Try a bit harder to catch this case.
for i in xrange(2):
if (linenum > i and
Search(whitelisted_functions, clean_lines.elided[linenum - i - 1])):
return
# decls = ReplaceAll(r'{[^}]*}', ' ', line) # exclude function body
# for parameter in re.findall(_RE_PATTERN_REF_PARAM, decls):
# if (not Match(_RE_PATTERN_CONST_REF_PARAM, parameter) and
# not Match(_RE_PATTERN_REF_STREAM_PARAM, parameter)):
# error(filename, linenum, 'runtime/references', 2,
# 'Is this a non-const reference? '
# 'If so, make const or use a pointer: ' +
# ReplaceAll(' *<', '<', parameter))
def CheckCasts(filename, clean_lines, linenum, error):
"""Various cast related checks.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found.
"""
line = clean_lines.elided[linenum]
# Check to see if they're using an conversion function cast.
# I just try to capture the most common basic types, though there are more.
# Parameterless conversion functions, such as bool(), are allowed as they are
# probably a member operator declaration or default constructor.
match = Search(
r'(\bnew\s+(?:const\s+)?|\S<\s*(?:const\s+)?)?\b'
r'(int|float|double|bool|char|int32|uint32|int64|uint64)'
r'(\([^)].*)', line)
expecting_function = ExpectingFunctionArgs(clean_lines, linenum)
if match and not expecting_function:
matched_type = match.group(2)
# matched_new_or_template is used to silence two false positives:
# - New operators
# - Template arguments with function types
#
# For template arguments, we match on types immediately following
# an opening bracket without any spaces. This is a fast way to
# silence the common case where the function type is the first
# template argument. False negative with less-than comparison is
# avoided because those operators are usually followed by a space.
#
# function<double(double)> // bracket + no space = false positive
# value < double(42) // bracket + space = true positive
matched_new_or_template = match.group(1)
# Avoid arrays by looking for brackets that come after the closing
# parenthesis.
if Match(r'\([^()]+\)\s*\[', match.group(3)):
return
# Other things to ignore:
# - Function pointers
# - Casts to pointer types
# - Placement new
# - Alias declarations
matched_funcptr = match.group(3)
if (matched_new_or_template is None and
not (matched_funcptr and
(Match(r'\((?:[^() ]+::\s*\*\s*)?[^() ]+\)\s*\(',
matched_funcptr) or
matched_funcptr.startswith('(*)'))) and
not Match(r'\s*using\s+\S+\s*=\s*' + matched_type, line) and
not Search(r'new\(\S+\)\s*' + matched_type, line)):
error(filename, linenum, 'readability/casting', 4,
'Using deprecated casting style. '
'Use static_cast<%s>(...) instead' %
matched_type)
if not expecting_function:
CheckCStyleCast(filename, clean_lines, linenum, 'static_cast',
r'\((int|float|double|bool|char|u?int(16|32|64))\)', error)
# This doesn't catch all cases. Consider (const char * const)"hello".
#
# (char *) "foo" should always be a const_cast (reinterpret_cast won't
# compile).
if CheckCStyleCast(filename, clean_lines, linenum, 'const_cast',
r'\((char\s?\*+\s?)\)\s*"', error):
pass
else:
# Check pointer casts for other than string constants
CheckCStyleCast(filename, clean_lines, linenum, 'reinterpret_cast',
r'\((\w+\s?\*+\s?)\)', error)
# In addition, we look for people taking the address of a cast. This
# is dangerous -- casts can assign to temporaries, so the pointer doesn't
# point where you think.
#
# Some non-identifier character is required before the '&' for the
# expression to be recognized as a cast. These are casts:
# expression = &static_cast<int*>(temporary());
# function(&(int*)(temporary()));
#
# This is not a cast:
# reference_type&(int* function_param);
match = Search(
r'(?:[^\w]&\(([^)*][^)]*)\)[\w(])|'
r'(?:[^\w]&(static|dynamic|down|reinterpret)_cast\b)', line)
if match:
# Try a better error message when the & is bound to something
# dereferenced by the casted pointer, as opposed to the casted
# pointer itself.
parenthesis_error = False
match = Match(r'^(.*&(?:static|dynamic|down|reinterpret)_cast\b)<', line)
if match:
_, y1, x1 = CloseExpression(clean_lines, linenum, len(match.group(1)))
if x1 >= 0 and clean_lines.elided[y1][x1] == '(':
_, y2, x2 = CloseExpression(clean_lines, y1, x1)
if x2 >= 0:
extended_line = clean_lines.elided[y2][x2:]
if y2 < clean_lines.NumLines() - 1:
extended_line += clean_lines.elided[y2 + 1]
if Match(r'\s*(?:->|\[)', extended_line):
parenthesis_error = True
if parenthesis_error:
error(filename, linenum, 'readability/casting', 4,
('Are you taking an address of something dereferenced '
'from a cast? Wrapping the dereferenced expression in '
'parentheses will make the binding more obvious'))
else:
error(filename, linenum, 'runtime/casting', 4,
('Are you taking an address of a cast? '
'This is dangerous: could be a temp var. '
'Take the address before doing the cast, rather than after'))
def CheckCStyleCast(filename, clean_lines, linenum, cast_type, pattern, error):
"""Checks for a C-style cast by looking for the pattern.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
cast_type: The string for the C++ cast to recommend. This is either
reinterpret_cast, static_cast, or const_cast, depending.
pattern: The regular expression used to find C-style casts.
error: The function to call with any errors found.
Returns:
True if an error was emitted.
False otherwise.
"""
line = clean_lines.elided[linenum]
match = Search(pattern, line)
if not match:
return False
# Exclude lines with keywords that tend to look like casts
context = line[0:match.start(1) - 1]
if Match(r'.*\b(?:sizeof|alignof|alignas|[_A-Z][_A-Z0-9]*)\s*$', context):
return False
# Try expanding current context to see if we one level of
# parentheses inside a macro.
if linenum > 0:
for i in xrange(linenum - 1, max(0, linenum - 5), -1):
context = clean_lines.elided[i] + context
if Match(r'.*\b[_A-Z][_A-Z0-9]*\s*\((?:\([^()]*\)|[^()])*$', context):
return False
# operator++(int) and operator--(int)
if context.endswith(' operator++') or context.endswith(' operator--'):
return False
# A single unnamed argument for a function tends to look like old style cast.
# If we see those, don't issue warnings for deprecated casts.
remainder = line[match.end(0):]
if Match(r'^\s*(?:;|const\b|throw\b|final\b|override\b|[=>{),]|->)',
remainder):
return False
# At this point, all that should be left is actual casts.
# error(filename, linenum, 'readability/casting', 4,
# 'Using C-style cast. Use %s<%s>(...) instead' %
# (cast_type, match.group(1)))
return True
def ExpectingFunctionArgs(clean_lines, linenum):
"""Checks whether where function type arguments are expected.
Args:
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
Returns:
True if the line at 'linenum' is inside something that expects arguments
of function types.
"""
line = clean_lines.elided[linenum]
return (Match(r'^\s*MOCK_(CONST_)?METHOD\d+(_T)?\(', line) or
(linenum >= 2 and
(Match(r'^\s*MOCK_(?:CONST_)?METHOD\d+(?:_T)?\((?:\S+,)?\s*$',
clean_lines.elided[linenum - 1]) or
Match(r'^\s*MOCK_(?:CONST_)?METHOD\d+(?:_T)?\(\s*$',
clean_lines.elided[linenum - 2]) or
Search(r'\bstd::m?function\s*\<\s*$',
clean_lines.elided[linenum - 1]))))
_HEADERS_CONTAINING_TEMPLATES = (
('<deque>', ('deque',)),
('<functional>', ('unary_function', 'binary_function',
'plus', 'minus', 'multiplies', 'divides', 'modulus',
'negate',
'equal_to', 'not_equal_to', 'greater', 'less',
'greater_equal', 'less_equal',
'logical_and', 'logical_or', 'logical_not',
'unary_negate', 'not1', 'binary_negate', 'not2',
'bind1st', 'bind2nd',
'pointer_to_unary_function',
'pointer_to_binary_function',
'ptr_fun',
'mem_fun_t', 'mem_fun', 'mem_fun1_t', 'mem_fun1_ref_t',
'mem_fun_ref_t',
'const_mem_fun_t', 'const_mem_fun1_t',
'const_mem_fun_ref_t', 'const_mem_fun1_ref_t',
'mem_fun_ref',
)),
('<limits>', ('numeric_limits',)),
('<list>', ('list',)),
('<map>', ('map', 'multimap',)),
('<memory>', ('allocator', 'make_shared', 'make_unique', 'shared_ptr',
'unique_ptr', 'weak_ptr')),
('<queue>', ('queue', 'priority_queue',)),
('<set>', ('set', 'multiset',)),
('<stack>', ('stack',)),
('<string>', ('char_traits', 'basic_string',)),
('<tuple>', ('tuple',)),
('<unordered_map>', ('unordered_map', 'unordered_multimap')),
('<unordered_set>', ('unordered_set', 'unordered_multiset')),
('<utility>', ('pair',)),
('<vector>', ('vector',)),
# gcc extensions.
# Note: std::hash is their hash, ::hash is our hash
('<hash_map>', ('hash_map', 'hash_multimap',)),
('<hash_set>', ('hash_set', 'hash_multiset',)),
('<slist>', ('slist',)),
)
_HEADERS_MAYBE_TEMPLATES = (
('<algorithm>', ('copy', 'max', 'min', 'min_element', 'sort',
'transform',
)),
('<utility>', ('forward', 'make_pair', 'move', 'swap')),
)
_RE_PATTERN_STRING = re.compile(r'\bstring\b')
_re_pattern_headers_maybe_templates = []
for _header, _templates in _HEADERS_MAYBE_TEMPLATES:
for _template in _templates:
# Match max<type>(..., ...), max(..., ...), but not foo->max, foo.max or
# type::max().
_re_pattern_headers_maybe_templates.append(
(re.compile(r'[^>.]\b' + _template + r'(<.*?>)?\([^\)]'),
_template,
_header))
# Other scripts may reach in and modify this pattern.
_re_pattern_templates = []
for _header, _templates in _HEADERS_CONTAINING_TEMPLATES:
for _template in _templates:
_re_pattern_templates.append(
(re.compile(r'(\<|\b)' + _template + r'\s*\<'),
_template + '<>',
_header))
def FilesBelongToSameModule(filename_cc, filename_h):
"""Check if these two filenames belong to the same module.
The concept of a 'module' here is a as follows:
foo.h, foo-inl.h, foo.cc, foo_test.cc and foo_unittest.cc belong to the
same 'module' if they are in the same directory.
some/path/public/xyzzy and some/path/internal/xyzzy are also considered
to belong to the same module here.
If the filename_cc contains a longer path than the filename_h, for example,
'/absolute/path/to/base/sysinfo.cc', and this file would include
'base/sysinfo.h', this function also produces the prefix needed to open the
header. This is used by the caller of this function to more robustly open the
header file. We don't have access to the real include paths in this context,
so we need this guesswork here.
Known bugs: tools/base/bar.cc and base/bar.h belong to the same module
according to this implementation. Because of this, this function gives
some false positives. This should be sufficiently rare in practice.
Args:
filename_cc: is the path for the .cc file
filename_h: is the path for the header path
Returns:
Tuple with a bool and a string:
bool: True if filename_cc and filename_h belong to the same module.
string: the additional prefix needed to open the header file.
"""
fileinfo = FileInfo(filename_cc)
if not fileinfo.IsSource():
return (False, '')
filename_cc = filename_cc[:-len(fileinfo.Extension())]
matched_test_suffix = Search(_TEST_FILE_SUFFIX, fileinfo.BaseName())
if matched_test_suffix:
filename_cc = filename_cc[:-len(matched_test_suffix.group(1))]
filename_cc = filename_cc.replace('/public/', '/')
filename_cc = filename_cc.replace('/internal/', '/')
if not filename_h.endswith('.h'):
return (False, '')
filename_h = filename_h[:-len('.h')]
if filename_h.endswith('-inl'):
filename_h = filename_h[:-len('-inl')]
filename_h = filename_h.replace('/public/', '/')
filename_h = filename_h.replace('/internal/', '/')
files_belong_to_same_module = filename_cc.endswith(filename_h)
common_path = ''
if files_belong_to_same_module:
common_path = filename_cc[:-len(filename_h)]
return files_belong_to_same_module, common_path
def UpdateIncludeState(filename, include_dict, io=codecs):
"""Fill up the include_dict with new includes found from the file.
Args:
filename: the name of the header to read.
include_dict: a dictionary in which the headers are inserted.
io: The io factory to use to read the file. Provided for testability.
Returns:
True if a header was successfully added. False otherwise.
"""
headerfile = None
try:
headerfile = io.open(filename, 'r', 'utf8', 'replace')
except IOError:
return False
linenum = 0
for line in headerfile:
linenum += 1
clean_line = CleanseComments(line)
match = _RE_PATTERN_INCLUDE.search(clean_line)
if match:
include = match.group(2)
include_dict.setdefault(include, linenum)
return True
def CheckForIncludeWhatYouUse(filename, clean_lines, include_state, error,
io=codecs):
"""Reports for missing stl includes.
This function will output warnings to make sure you are including the headers
necessary for the stl containers and functions that you use. We only give one
reason to include a header. For example, if you use both equal_to<> and
less<> in a .h file, only one (the latter in the file) of these will be
reported as a reason to include the <functional>.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
include_state: An _IncludeState instance.
error: The function to call with any errors found.
io: The IO factory to use to read the header file. Provided for unittest
injection.
"""
required = {} # A map of header name to linenumber and the template entity.
# Example of required: { '<functional>': (1219, 'less<>') }
for linenum in xrange(clean_lines.NumLines()):
line = clean_lines.elided[linenum]
if not line or line[0] == '#':
continue
# String is special -- it is a non-templatized type in STL.
matched = _RE_PATTERN_STRING.search(line)
if matched:
# Don't warn about strings in non-STL namespaces:
# (We check only the first match per line; good enough.)
prefix = line[:matched.start()]
if prefix.endswith('std::') or not prefix.endswith('::'):
required['<string>'] = (linenum, 'string')
for pattern, template, header in _re_pattern_headers_maybe_templates:
if pattern.search(line):
required[header] = (linenum, template)
# The following function is just a speed up, no semantics are changed.
if not '<' in line: # Reduces the cpu time usage by skipping lines.
continue
for pattern, template, header in _re_pattern_templates:
matched = pattern.search(line)
if matched:
# Don't warn about IWYU in non-STL namespaces:
# (We check only the first match per line; good enough.)
prefix = line[:matched.start()]
if prefix.endswith('std::') or not prefix.endswith('::'):
required[header] = (linenum, template)
# The policy is that if you #include something in foo.h you don't need to
# include it again in foo.cc. Here, we will look at possible includes.
# Let's flatten the include_state include_list and copy it into a dictionary.
include_dict = dict([item for sublist in include_state.include_list
for item in sublist])
# Did we find the header for this file (if any) and successfully load it?
header_found = False
# Use the absolute path so that matching works properly.
abs_filename = FileInfo(filename).FullName()
# For Emacs's flymake.
# If cpplint is invoked from Emacs's flymake, a temporary file is generated
# by flymake and that file name might end with '_flymake.cc'. In that case,
# restore original file name here so that the corresponding header file can be
# found.
# e.g. If the file name is 'foo_flymake.cc', we should search for 'foo.h'
# instead of 'foo_flymake.h'
abs_filename = re.sub(r'_flymake\.cc$', '.cc', abs_filename)
# include_dict is modified during iteration, so we iterate over a copy of
# the keys.
header_keys = include_dict.keys()
for header in header_keys:
(same_module, common_path) = FilesBelongToSameModule(abs_filename, header)
fullpath = common_path + header
if same_module and UpdateIncludeState(fullpath, include_dict, io):
header_found = True
# If we can't find the header file for a .cc, assume it's because we don't
# know where to look. In that case we'll give up as we're not sure they
# didn't include it in the .h file.
# TODO(unknown): Do a better job of finding .h files so we are confident that
# not having the .h file means there isn't one.
if filename.endswith('.cc') and not header_found:
return
# All the lines have been processed, report the errors found.
for required_header_unstripped in required:
template = required[required_header_unstripped][1]
if required_header_unstripped.strip('<>"') not in include_dict:
error(filename, required[required_header_unstripped][0],
'build/include_what_you_use', 4,
'Add #include ' + required_header_unstripped + ' for ' + template)
_RE_PATTERN_EXPLICIT_MAKEPAIR = re.compile(r'\bmake_pair\s*<')
def CheckMakePairUsesDeduction(filename, clean_lines, linenum, error):
"""Check that make_pair's template arguments are deduced.
G++ 4.6 in C++11 mode fails badly if make_pair's template arguments are
specified explicitly, and such use isn't intended in any case.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found.
"""
line = clean_lines.elided[linenum]
match = _RE_PATTERN_EXPLICIT_MAKEPAIR.search(line)
if match:
error(filename, linenum, 'build/explicit_make_pair',
4, # 4 = high confidence
'For C++11-compatibility, omit template arguments from make_pair'
' OR use pair directly OR if appropriate, construct a pair directly')
def CheckRedundantVirtual(filename, clean_lines, linenum, error):
"""Check if line contains a redundant "virtual" function-specifier.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found.
"""
# Look for "virtual" on current line.
line = clean_lines.elided[linenum]
virtual = Match(r'^(.*)(\bvirtual\b)(.*)$', line)
if not virtual: return
# Ignore "virtual" keywords that are near access-specifiers. These
# are only used in class base-specifier and do not apply to member
# functions.
if (Search(r'\b(public|protected|private)\s+$', virtual.group(1)) or
Match(r'^\s+(public|protected|private)\b', virtual.group(3))):
return
# Ignore the "virtual" keyword from virtual base classes. Usually
# there is a column on the same line in these cases (virtual base
# classes are rare in google3 because multiple inheritance is rare).
if Match(r'^.*[^:]:[^:].*$', line): return
# Look for the next opening parenthesis. This is the start of the
# parameter list (possibly on the next line shortly after virtual).
# TODO(unknown): doesn't work if there are virtual functions with
# decltype() or other things that use parentheses, but csearch suggests
# that this is rare.
end_col = -1
end_line = -1
start_col = len(virtual.group(2))
for start_line in xrange(linenum, min(linenum + 3, clean_lines.NumLines())):
line = clean_lines.elided[start_line][start_col:]
parameter_list = Match(r'^([^(]*)\(', line)
if parameter_list:
# Match parentheses to find the end of the parameter list
(_, end_line, end_col) = CloseExpression(
clean_lines, start_line, start_col + len(parameter_list.group(1)))
break
start_col = 0
if end_col < 0:
return # Couldn't find end of parameter list, give up
# Look for "override" or "final" after the parameter list
# (possibly on the next few lines).
for i in xrange(end_line, min(end_line + 3, clean_lines.NumLines())):
line = clean_lines.elided[i][end_col:]
match = Search(r'\b(override|final)\b', line)
if match:
error(filename, linenum, 'readability/inheritance', 4,
('"virtual" is redundant since function is '
'already declared as "%s"' % match.group(1)))
# Set end_col to check whole lines after we are done with the
# first line.
end_col = 0
if Search(r'[^\w]\s*$', line):
break
def CheckRedundantOverrideOrFinal(filename, clean_lines, linenum, error):
"""Check if line contains a redundant "override" or "final" virt-specifier.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found.
"""
# Look for closing parenthesis nearby. We need one to confirm where
# the declarator ends and where the virt-specifier starts to avoid
# false positives.
line = clean_lines.elided[linenum]
declarator_end = line.rfind(')')
if declarator_end >= 0:
fragment = line[declarator_end:]
else:
if linenum > 1 and clean_lines.elided[linenum - 1].rfind(')') >= 0:
fragment = line
else:
return
# Check that at most one of "override" or "final" is present, not both
if Search(r'\boverride\b', fragment) and Search(r'\bfinal\b', fragment):
error(filename, linenum, 'readability/inheritance', 4,
('"override" is redundant since function is '
'already declared as "final"'))
# Returns true if we are at a new block, and it is directly
# inside of a namespace.
def IsBlockInNameSpace(nesting_state, is_forward_declaration):
"""Checks that the new block is directly in a namespace.
Args:
nesting_state: The _NestingState object that contains info about our state.
is_forward_declaration: If the class is a forward declared class.
Returns:
Whether or not the new block is directly in a namespace.
"""
if is_forward_declaration:
if len(nesting_state.stack) >= 1 and (
isinstance(nesting_state.stack[-1], _NamespaceInfo)):
return True
else:
return False
return (len(nesting_state.stack) > 1 and
nesting_state.stack[-1].check_namespace_indentation and
isinstance(nesting_state.stack[-2], _NamespaceInfo))
def ShouldCheckNamespaceIndentation(nesting_state, is_namespace_indent_item,
raw_lines_no_comments, linenum):
"""This method determines if we should apply our namespace indentation check.
Args:
nesting_state: The current nesting state.
is_namespace_indent_item: If we just put a new class on the stack, True.
If the top of the stack is not a class, or we did not recently
add the class, False.
raw_lines_no_comments: The lines without the comments.
linenum: The current line number we are processing.
Returns:
True if we should apply our namespace indentation check. Currently, it
only works for classes and namespaces inside of a namespace.
"""
is_forward_declaration = IsForwardClassDeclaration(raw_lines_no_comments,
linenum)
if not (is_namespace_indent_item or is_forward_declaration):
return False
# If we are in a macro, we do not want to check the namespace indentation.
if IsMacroDefinition(raw_lines_no_comments, linenum):
return False
return IsBlockInNameSpace(nesting_state, is_forward_declaration)
# Call this method if the line is directly inside of a namespace.
# If the line above is blank (excluding comments) or the start of
# an inner namespace, it cannot be indented.
def CheckItemIndentationInNamespace(filename, raw_lines_no_comments, linenum,
error):
line = raw_lines_no_comments[linenum]
if Match(r'^\s+', line):
error(filename, linenum, 'runtime/indentation_namespace', 4,
'Do not indent within a namespace')
def ProcessLine(filename, file_extension, clean_lines, line,
include_state, function_state, nesting_state, error,
extra_check_functions=[]):
"""Processes a single line in the file.
Args:
filename: Filename of the file that is being processed.
file_extension: The extension (dot not included) of the file.
clean_lines: An array of strings, each representing a line of the file,
with comments stripped.
line: Number of line being processed.
include_state: An _IncludeState instance in which the headers are inserted.
function_state: A _FunctionState instance which counts function lines, etc.
nesting_state: A NestingState instance which maintains information about
the current stack of nested blocks being parsed.
error: A callable to which errors are reported, which takes 4 arguments:
filename, line number, error level, and message
extra_check_functions: An array of additional check functions that will be
run on each source line. Each function takes 4
arguments: filename, clean_lines, line, error
"""
raw_lines = clean_lines.raw_lines
ParseNolintSuppressions(filename, raw_lines[line], line, error)
nesting_state.Update(filename, clean_lines, line, error)
CheckForNamespaceIndentation(filename, nesting_state, clean_lines, line,
error)
if nesting_state.InAsmBlock(): return
CheckForFunctionLengths(filename, clean_lines, line, function_state, error)
CheckForMultilineCommentsAndStrings(filename, clean_lines, line, error)
CheckStyle(filename, clean_lines, line, file_extension, nesting_state, error)
CheckLanguage(filename, clean_lines, line, file_extension, include_state,
nesting_state, error)
CheckForNonConstReference(filename, clean_lines, line, nesting_state, error)
CheckForNonStandardConstructs(filename, clean_lines, line,
nesting_state, error)
CheckVlogArguments(filename, clean_lines, line, error)
CheckPosixThreading(filename, clean_lines, line, error)
CheckInvalidIncrement(filename, clean_lines, line, error)
CheckMakePairUsesDeduction(filename, clean_lines, line, error)
CheckRedundantVirtual(filename, clean_lines, line, error)
CheckRedundantOverrideOrFinal(filename, clean_lines, line, error)
for check_fn in extra_check_functions:
check_fn(filename, clean_lines, line, error)
def FlagCxx11Features(filename, clean_lines, linenum, error):
"""Flag those c++11 features that we only allow in certain places.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found.
"""
line = clean_lines.elided[linenum]
include = Match(r'\s*#\s*include\s+[<"]([^<"]+)[">]', line)
# Flag unapproved C++ TR1 headers.
if include and include.group(1).startswith('tr1/'):
error(filename, linenum, 'build/c++tr1', 5,
('C++ TR1 headers such as <%s> are unapproved.') % include.group(1))
# Flag unapproved C++11 headers.
if include and include.group(1) in ('cfenv',
'condition_variable',
'fenv.h',
'future',
'mutex',
'thread',
'chrono',
'ratio',
'regex',
'system_error',
):
error(filename, linenum, 'build/c++11', 5,
('<%s> is an unapproved C++11 header.') % include.group(1))
# The only place where we need to worry about C++11 keywords and library
# features in preprocessor directives is in macro definitions.
if Match(r'\s*#', line) and not Match(r'\s*#\s*define\b', line): return
# These are classes and free functions. The classes are always
# mentioned as std::*, but we only catch the free functions if
# they're not found by ADL. They're alphabetical by header.
for top_name in (
# type_traits
'alignment_of',
'aligned_union',
):
if Search(r'\bstd::%s\b' % top_name, line):
error(filename, linenum, 'build/c++11', 5,
('std::%s is an unapproved C++11 class or function. Send c-style '
'an example of where it would make your code more readable, and '
'they may let you use it.') % top_name)
def FlagCxx14Features(filename, clean_lines, linenum, error):
"""Flag those C++14 features that we restrict.
Args:
filename: The name of the current file.
clean_lines: A CleansedLines instance containing the file.
linenum: The number of the line to check.
error: The function to call with any errors found.
"""
line = clean_lines.elided[linenum]
include = Match(r'\s*#\s*include\s+[<"]([^<"]+)[">]', line)
# Flag unapproved C++14 headers.
if include and include.group(1) in ('scoped_allocator', 'shared_mutex'):
error(filename, linenum, 'build/c++14', 5,
('<%s> is an unapproved C++14 header.') % include.group(1))
def ProcessFileData(filename, file_extension, lines, error,
extra_check_functions=[]):
"""Performs lint checks and reports any errors to the given error function.
Args:
filename: Filename of the file that is being processed.
file_extension: The extension (dot not included) of the file.
lines: An array of strings, each representing a line of the file, with the
last element being empty if the file is terminated with a newline.
error: A callable to which errors are reported, which takes 4 arguments:
filename, line number, error level, and message
extra_check_functions: An array of additional check functions that will be
run on each source line. Each function takes 4
arguments: filename, clean_lines, line, error
"""
lines = (['// marker so line numbers and indices both start at 1'] + lines +
['// marker so line numbers end in a known way'])
include_state = _IncludeState()
function_state = _FunctionState()
nesting_state = NestingState()
ResetNolintSuppressions()
CheckForCopyright(filename, lines, error)
ProcessGlobalSuppresions(lines)
RemoveMultiLineComments(filename, lines, error)
clean_lines = CleansedLines(lines)
if IsHeaderExtension(file_extension):
CheckForHeaderGuard(filename, clean_lines, error)
for line in xrange(clean_lines.NumLines()):
ProcessLine(filename, file_extension, clean_lines, line,
include_state, function_state, nesting_state, error,
extra_check_functions)
FlagCxx11Features(filename, clean_lines, line, error)
nesting_state.CheckCompletedBlocks(filename, error)
CheckForIncludeWhatYouUse(filename, clean_lines, include_state, error)
# Check that the .cc file has included its header if it exists.
if _IsSourceExtension(file_extension):
CheckHeaderFileIncluded(filename, include_state, error)
# We check here rather than inside ProcessLine so that we see raw
# lines rather than "cleaned" lines.
CheckForBadCharacters(filename, lines, error)
CheckForNewlineAtEOF(filename, lines, error)
def ProcessConfigOverrides(filename):
""" Loads the configuration files and processes the config overrides.
Args:
filename: The name of the file being processed by the linter.
Returns:
False if the current |filename| should not be processed further.
"""
abs_filename = os.path.abspath(filename)
cfg_filters = []
keep_looking = True
while keep_looking:
abs_path, base_name = os.path.split(abs_filename)
if not base_name:
break # Reached the root directory.
cfg_file = os.path.join(abs_path, "CPPLINT.cfg")
abs_filename = abs_path
if not os.path.isfile(cfg_file):
continue
try:
with open(cfg_file) as file_handle:
for line in file_handle:
line, _, _ = line.partition('#') # Remove comments.
if not line.strip():
continue
name, _, val = line.partition('=')
name = name.strip()
val = val.strip()
if name == 'set noparent':
keep_looking = False
elif name == 'filter':
cfg_filters.append(val)
elif name == 'exclude_files':
# When matching exclude_files pattern, use the base_name of
# the current file name or the directory name we are processing.
# For example, if we are checking for lint errors in /foo/bar/baz.cc
# and we found the .cfg file at /foo/CPPLINT.cfg, then the config
# file's "exclude_files" filter is meant to be checked against "bar"
# and not "baz" nor "bar/baz.cc".
if base_name:
pattern = re.compile(val)
if pattern.match(base_name):
sys.stderr.write('Ignoring "%s": file excluded by "%s". '
'File path component "%s" matches '
'pattern "%s"\n' %
(filename, cfg_file, base_name, val))
return False
elif name == 'linelength':
global _line_length
try:
_line_length = int(val)
except ValueError:
sys.stderr.write('Line length must be numeric.')
elif name == 'root':
global _root
_root = val
elif name == 'headers':
ProcessHppHeadersOption(val)
else:
sys.stderr.write(
'Invalid configuration option (%s) in file %s\n' %
(name, cfg_file))
except IOError:
sys.stderr.write(
"Skipping config file '%s': Can't open for reading\n" % cfg_file)
keep_looking = False
# Apply all the accumulated filters in reverse order (top-level directory
# config options having the least priority).
for filter in reversed(cfg_filters):
_AddFilters(filter)
return True
def ProcessFile(filename, vlevel, extra_check_functions=[]):
"""Does google-lint on a single file.
Args:
filename: The name of the file to parse.
vlevel: The level of errors to report. Every error of confidence
>= verbose_level will be reported. 0 is a good default.
extra_check_functions: An array of additional check functions that will be
run on each source line. Each function takes 4
arguments: filename, clean_lines, line, error
"""
_SetVerboseLevel(vlevel)
_BackupFilters()
if not ProcessConfigOverrides(filename):
_RestoreFilters()
return
lf_lines = []
crlf_lines = []
try:
# Support the UNIX convention of using "-" for stdin. Note that
# we are not opening the file with universal newline support
# (which codecs doesn't support anyway), so the resulting lines do
# contain trailing '\r' characters if we are reading a file that
# has CRLF endings.
# If after the split a trailing '\r' is present, it is removed
# below.
if filename == '-':
lines = codecs.StreamReaderWriter(sys.stdin,
codecs.getreader('utf8'),
codecs.getwriter('utf8'),
'replace').read().split('\n')
else:
lines = codecs.open(filename, 'r', 'utf8', 'replace').read().split('\n')
# Remove trailing '\r'.
# The -1 accounts for the extra trailing blank line we get from split()
for linenum in range(len(lines) - 1):
if lines[linenum].endswith('\r'):
lines[linenum] = lines[linenum].rstrip('\r')
crlf_lines.append(linenum + 1)
else:
lf_lines.append(linenum + 1)
except IOError:
sys.stderr.write(
"Skipping input '%s': Can't open for reading\n" % filename)
_RestoreFilters()
return
# Note, if no dot is found, this will give the entire filename as the ext.
file_extension = filename[filename.rfind('.') + 1:]
# When reading from stdin, the extension is unknown, so no cpplint tests
# should rely on the extension.
if filename != '-' and file_extension not in _valid_extensions:
sys.stderr.write('Ignoring %s; not a valid file name '
'(%s)\n' % (filename, ', '.join(_valid_extensions)))
else:
ProcessFileData(filename, file_extension, lines, Error,
extra_check_functions)
# If end-of-line sequences are a mix of LF and CR-LF, issue
# warnings on the lines with CR.
#
# Don't issue any warnings if all lines are uniformly LF or CR-LF,
# since critique can handle these just fine, and the style guide
# doesn't dictate a particular end of line sequence.
#
# We can't depend on os.linesep to determine what the desired
# end-of-line sequence should be, since that will return the
# server-side end-of-line sequence.
if lf_lines and crlf_lines:
# Warn on every line with CR. An alternative approach might be to
# check whether the file is mostly CRLF or just LF, and warn on the
# minority, we bias toward LF here since most tools prefer LF.
for linenum in crlf_lines:
Error(filename, linenum, 'whitespace/newline', 1,
'Unexpected \\r (^M) found; better to use only \\n')
sys.stdout.write('Done processing %s\n' % filename)
_RestoreFilters()
def PrintUsage(message):
"""Prints a brief usage string and exits, optionally with an error message.
Args:
message: The optional error message.
"""
sys.stderr.write(_USAGE)
if message:
sys.exit('\nFATAL ERROR: ' + message)
else:
sys.exit(1)
def PrintCategories():
"""Prints a list of all the error-categories used by error messages.
These are the categories used to filter messages via --filter.
"""
sys.stderr.write(''.join(' %s\n' % cat for cat in _ERROR_CATEGORIES))
sys.exit(0)
def ParseArguments(args):
"""Parses the command line arguments.
This may set the output format and verbosity level as side-effects.
Args:
args: The command line arguments:
Returns:
The list of filenames to lint.
"""
try:
(opts, filenames) = getopt.getopt(args, '', ['help', 'output=', 'verbose=',
'counting=',
'filter=',
'root=',
'linelength=',
'extensions=',
'headers='])
except getopt.GetoptError:
PrintUsage('Invalid arguments.')
verbosity = _VerboseLevel()
output_format = _OutputFormat()
filters = ''
counting_style = ''
for (opt, val) in opts:
if opt == '--help':
PrintUsage(None)
elif opt == '--output':
if val not in ('emacs', 'vs7', 'eclipse'):
PrintUsage('The only allowed output formats are emacs, vs7 and eclipse.')
output_format = val
elif opt == '--verbose':
verbosity = int(val)
elif opt == '--filter':
filters = val
if not filters:
PrintCategories()
elif opt == '--counting':
if val not in ('total', 'toplevel', 'detailed'):
PrintUsage('Valid counting options are total, toplevel, and detailed')
counting_style = val
elif opt == '--root':
global _root
_root = val
elif opt == '--linelength':
global _line_length
try:
_line_length = int(val)
except ValueError:
PrintUsage('Line length must be digits.')
elif opt == '--extensions':
global _valid_extensions
try:
_valid_extensions = set(val.split(','))
except ValueError:
PrintUsage('Extensions must be comma seperated list.')
elif opt == '--headers':
ProcessHppHeadersOption(val)
if not filenames:
PrintUsage('No files were specified.')
_SetOutputFormat(output_format)
_SetVerboseLevel(verbosity)
_SetFilters(filters)
_SetCountingStyle(counting_style)
return filenames
def main():
filenames = ParseArguments(sys.argv[1:])
# Change stderr to write with replacement characters so we don't die
# if we try to print something containing non-ASCII characters.
sys.stderr = codecs.StreamReaderWriter(sys.stderr,
codecs.getreader('utf8'),
codecs.getwriter('utf8'),
'replace')
_cpplint_state.ResetErrorCounts()
for filename in filenames:
ProcessFile(filename, _cpplint_state.verbose_level)
_cpplint_state.PrintErrorCounts()
sys.exit(_cpplint_state.error_count > 0)
if __name__ == '__main__':
main()
|
the-stack_106_26573 | """packer_builder/__main__.py"""
import os
from packer_builder.cli import cli_args
from packer_builder.build import Build
from packer_builder.distros import Distros
from packer_builder.templates import Templates
from packer_builder.logger import setup_logger
def build(args):
"""Build images."""
# Get dictionary of distros
distros = Distros(args).get()
# Build all distros
Build(args, distros)
def list_distros(args):
"""Get distros and display as JSON."""
# Get dictionary of distros
distros = Distros(args)
# List all distros as JSON output
distros.list_()
def generate_templates(args):
"""Generate templates without building."""
# Get dictionary of distros
distros = Distros(args).get()
# Generate all templates without building
templates = Templates(args, distros)
templates.generate()
def main():
"""Packer builder main execution."""
# Setup root logger
setup_logger()
# Capture CLI arguments
args = cli_args()
# Ensure output dir exists if defined
if args.outputdir is not None:
if not os.path.isdir:
os.makedirs(args.outputdir)
# Map actions to respective functions
action_map = {'build': build, 'generate-templates': generate_templates,
'list-distros': list_distros}
# Lookup action from map
action = action_map[args.action]
# Execute action
action(args)
if __name__ == '__main__':
main()
|
the-stack_106_26574 | import os
from abc import ABC, abstractmethod
from typing import Dict, List
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from superai.data_program import DataProgram
from superai import Client
from ..workflow import Workflow
from superai.log import logger
log = logger.get_logger(__name__)
class Router(ABC):
def __init__(
self,
name: str = "router", # Can't get overriden for now
dataprorgam: "DataProgram" = None,
client: Client = None,
**kwargs,
):
"""
:param workflows:
:param metrics:
:param prefix:
:param name:
"""
if name != "router":
raise AttributeError("Router name is constraint to 'router'")
self.name = name
self.client = client
self.dataprogram = dataprorgam
self.kkwargs = kwargs
@abstractmethod
def subscribe_wf(self):
pass
|
the-stack_106_26576 | #!/usr/bin/env python3
#
# Copyright (c) 2017, Piotr Przymus
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
"""
Command-line tool to expose qtile.command functionality to shell.
This can be used standalone or in other shell scripts.
"""
from __future__ import annotations
import argparse
import itertools
import pprint
import sys
import textwrap
from libqtile.command.base import CommandError, CommandException, SelectError
from libqtile.command.client import CommandClient
from libqtile.command.graph import CommandGraphRoot
from libqtile.command.interface import IPCCommandInterface
from libqtile.ipc import Client, find_sockfile
def get_formated_info(obj: CommandClient, cmd: str, args=True, short=True) -> str:
"""Get documentation for command/function and format it.
Returns:
* args=True, short=True - '*' if arguments are present and a summary line.
* args=True, short=False - (function args) and a summary line.
* args=False - a summary line.
If 'doc' function is not present in object or there is no doc string for
given cmd it returns empty string. The arguments are extracted from doc[0]
line, the summary is constructed from doc[1] line.
"""
doc = obj.call("doc", cmd).splitlines()
tdoc = doc[0]
doc_args = tdoc[tdoc.find("(") : tdoc.find(")") + 1].strip()
short_description = doc[1] if len(doc) > 1 else ""
if not args:
doc_args = ""
elif short:
doc_args = " " if doc_args == "()" else "*"
return (doc_args + " " + short_description).rstrip()
def print_commands(prefix: str, obj: CommandClient) -> None:
"""Print available commands for given object."""
prefix += " -f "
cmds = obj.call("commands")
output = []
for cmd in cmds:
doc_args = get_formated_info(obj, cmd)
pcmd = prefix + cmd
output.append([pcmd, doc_args])
max_cmd = max(len(pcmd) for pcmd, _ in output)
# Print formatted output
formatting = "{:<%d}\t{}" % (max_cmd + 1)
for line in output:
print(formatting.format(line[0], line[1]))
def get_object(client: CommandClient, argv: list[str]) -> CommandClient:
"""
Constructs a path to object and returns given object (if it exists).
"""
if argv[0] == "cmd":
argv = argv[1:]
# flag noting if we have consumed arg1 as the selector, eg screen[0]
parsed_next = False
for arg0, arg1 in itertools.zip_longest(argv, argv[1:]):
# previous argument was an item, skip here
if parsed_next:
parsed_next = False
continue
# check if it is an item
try:
client = client.navigate(arg0, arg1)
parsed_next = True
continue
except SelectError:
pass
# check if it is an attr
try:
client = client.navigate(arg0, None)
continue
except SelectError:
pass
print("Specified object does not exist: " + " ".join(argv))
sys.exit(1)
return client
def run_function(client: CommandClient, funcname: str, args: list[str]) -> str:
"Run command with specified args on given object."
try:
ret = client.call(funcname, *args)
except SelectError:
print("error: Sorry no function ", funcname)
sys.exit(1)
except CommandError as e:
print("error: Command '{}' returned error: {}".format(funcname, str(e)))
sys.exit(1)
except CommandException as e:
print(
"error: Sorry cannot run function '{}' with arguments {}: {}".format(
funcname, args, str(e)
)
)
sys.exit(1)
return ret
def print_base_objects() -> None:
"""Prints access objects of Client, use cmd for commands."""
root = CommandGraphRoot()
actions = ["-o cmd"] + [f"-o {key}" for key in root.children]
print("Specify an object on which to execute command")
print("\n".join(actions))
def cmd_obj(args) -> None:
"Runs tool according to specified arguments."
if args.obj_spec:
sock_file = args.socket or find_sockfile()
ipc_client = Client(sock_file)
cmd_object = IPCCommandInterface(ipc_client)
cmd_client = CommandClient(cmd_object)
obj = get_object(cmd_client, args.obj_spec)
if args.function == "help":
try:
print_commands("-o " + " ".join(args.obj_spec), obj)
except CommandError:
if len(args.obj_spec) == 1:
print(
f"{args.obj_spec} object needs a specified identifier e.g. '-o bar top'."
)
sys.exit(1)
else:
raise
elif args.info:
print(args.function + get_formated_info(obj, args.function, args=True, short=False))
else:
ret = run_function(obj, args.function, args.args)
if ret is not None:
pprint.pprint(ret)
else:
print_base_objects()
sys.exit(1)
def add_subcommand(subparsers, parents):
epilog = textwrap.dedent(
"""\
Examples:
qtile cmd-obj
qtile cmd-obj -o cmd
qtile cmd-obj -o cmd -f prev_layout -i
qtile cmd-obj -o cmd -f prev_layout -a 3 # prev_layout on group 3
qtile cmd-obj -o group 3 -f focus_back
qtile cmd-obj -o cmd -f restart # restart qtile
"""
)
description = "qtile.command functionality exposed to the shell."
parser = subparsers.add_parser(
"cmd-obj",
help=description,
parents=parents,
epilog=epilog,
formatter_class=argparse.RawDescriptionHelpFormatter,
)
parser.add_argument(
"--object",
"-o",
dest="obj_spec",
nargs="+",
help="Specify path to object (space separated). "
"If no --function flag display available commands. "
"Use `cmd` to specify root command.",
)
parser.add_argument("--function", "-f", default="help", help="Select function to execute.")
parser.add_argument(
"--args", "-a", nargs="+", default=[], help="Set arguments supplied to function."
)
parser.add_argument(
"--info",
"-i",
action="store_true",
help="With both --object and --function args prints documentation for function.",
)
parser.add_argument("--socket", "-s", help="Path of the Qtile IPC socket.")
parser.set_defaults(func=cmd_obj)
|
the-stack_106_26580 | from random import randint
from time import sleep
from operator import itemgetter
jogo = dict()
quant = int(input('\nInforme o número de jogadores: '))
# Definindo o dicionário jogo:
for c in range(quant):
jogo[f'jogador{c+1}'] = randint(1, 6)
# Exibindo o dicionário jogo:
print('\nValores sorteados:\n')
for k, v in jogo.items():
print(f'O {k} tirou {v} no dado.')
sleep(0.75)
print()
print('\033[1;34m*=\033[m'*24)
print(f"\033[1;34m{'== RANKING DOS JOGADORES ==':^48}\033[m")
print('\033[1;34m*=\033[m'*24)
# para ordenar o dicionário foi usado a função "itemgetter()", obtida da biblioteca "operator"
ranking = sorted(jogo.items(), key=itemgetter(1), reverse=True)
sleep(0.75)
for i, v in enumerate(ranking):
print(f'{i+1:>8}º lugar: {v[0]} com {v[1]} pontos')
print('\033[1;34m*=\033[m'*24)
|
the-stack_106_26582 | """Ray constants used in the Python code."""
import logging
import math
import os
logger = logging.getLogger(__name__)
def env_integer(key, default):
if key in os.environ:
return int(os.environ[key])
return default
def env_bool(key, default):
if key in os.environ:
return True if os.environ[key].lower() == "true" else False
return default
ID_SIZE = 28
# The default maximum number of bytes to allocate to the object store unless
# overridden by the user.
DEFAULT_OBJECT_STORE_MAX_MEMORY_BYTES = 200 * 10**9
# The default proportion of available memory allocated to the object store
DEFAULT_OBJECT_STORE_MEMORY_PROPORTION = 0.3
# The smallest cap on the memory used by the object store that we allow.
# This must be greater than MEMORY_RESOURCE_UNIT_BYTES * 0.7
OBJECT_STORE_MINIMUM_MEMORY_BYTES = 75 * 1024 * 1024
# The default maximum number of bytes that the non-primary Redis shards are
# allowed to use unless overridden by the user.
DEFAULT_REDIS_MAX_MEMORY_BYTES = 10**10
# The smallest cap on the memory used by Redis that we allow.
REDIS_MINIMUM_MEMORY_BYTES = 10**7
# If a user does not specify a port for the primary Ray service,
# we attempt to start the service running at this port.
DEFAULT_PORT = 6379
DEFAULT_DASHBOARD_IP = "127.0.0.1"
DEFAULT_DASHBOARD_PORT = 8265
PROMETHEUS_SERVICE_DISCOVERY_FILE = "prom_metrics_service_discovery.json"
# Default resource requirements for actors when no resource requirements are
# specified.
DEFAULT_ACTOR_METHOD_CPU_SIMPLE = 1
DEFAULT_ACTOR_CREATION_CPU_SIMPLE = 0
# Default resource requirements for actors when some resource requirements are
# specified in .
DEFAULT_ACTOR_METHOD_CPU_SPECIFIED = 0
DEFAULT_ACTOR_CREATION_CPU_SPECIFIED = 1
# Default number of return values for each actor method.
DEFAULT_ACTOR_METHOD_NUM_RETURN_VALS = 1
# If a remote function or actor (or some other export) has serialized size
# greater than this quantity, print an warning.
PICKLE_OBJECT_WARNING_SIZE = 10**7
# If remote functions with the same source are imported this many times, then
# print a warning.
DUPLICATE_REMOTE_FUNCTION_THRESHOLD = 100
# The maximum resource quantity that is allowed. TODO(rkn): This could be
# relaxed, but the current implementation of the node manager will be slower
# for large resource quantities due to bookkeeping of specific resource IDs.
MAX_RESOURCE_QUANTITY = 100000
# Each memory "resource" counts as this many bytes of memory.
MEMORY_RESOURCE_UNIT_BYTES = 50 * 1024 * 1024
# Number of units 1 resource can be subdivided into.
MIN_RESOURCE_GRANULARITY = 0.0001
# Fraction of plasma memory that can be reserved. It is actually 70% but this
# is set to 69% to leave some headroom.
PLASMA_RESERVABLE_MEMORY_FRACTION = 0.69
def round_to_memory_units(memory_bytes, round_up):
"""Round bytes to the nearest memory unit."""
return from_memory_units(to_memory_units(memory_bytes, round_up))
def from_memory_units(memory_units):
"""Convert from memory units -> bytes."""
return memory_units * MEMORY_RESOURCE_UNIT_BYTES
def to_memory_units(memory_bytes, round_up):
"""Convert from bytes -> memory units."""
value = memory_bytes / MEMORY_RESOURCE_UNIT_BYTES
if value < 1:
raise ValueError(
"The minimum amount of memory that can be requested is {} bytes, "
"however {} bytes was asked.".format(MEMORY_RESOURCE_UNIT_BYTES,
memory_bytes))
if isinstance(value, float) and not value.is_integer():
# TODO(ekl) Ray currently does not support fractional resources when
# the quantity is greater than one. We should fix memory resources to
# be allocated in units of bytes and not 100MB.
if round_up:
value = int(math.ceil(value))
else:
value = int(math.floor(value))
return int(value)
# Different types of Ray errors that can be pushed to the driver.
# TODO(rkn): These should be defined in flatbuffers and must be synced with
# the existing C++ definitions.
WAIT_FOR_CLASS_PUSH_ERROR = "wait_for_class"
PICKLING_LARGE_OBJECT_PUSH_ERROR = "pickling_large_object"
WAIT_FOR_FUNCTION_PUSH_ERROR = "wait_for_function"
TASK_PUSH_ERROR = "task"
REGISTER_REMOTE_FUNCTION_PUSH_ERROR = "register_remote_function"
FUNCTION_TO_RUN_PUSH_ERROR = "function_to_run"
VERSION_MISMATCH_PUSH_ERROR = "version_mismatch"
CHECKPOINT_PUSH_ERROR = "checkpoint"
REGISTER_ACTOR_PUSH_ERROR = "register_actor"
WORKER_CRASH_PUSH_ERROR = "worker_crash"
WORKER_DIED_PUSH_ERROR = "worker_died"
WORKER_POOL_LARGE_ERROR = "worker_pool_large"
PUT_RECONSTRUCTION_PUSH_ERROR = "put_reconstruction"
INFEASIBLE_TASK_ERROR = "infeasible_task"
RESOURCE_DEADLOCK_ERROR = "resource_deadlock"
REMOVED_NODE_ERROR = "node_removed"
MONITOR_DIED_ERROR = "monitor_died"
LOG_MONITOR_DIED_ERROR = "log_monitor_died"
REPORTER_DIED_ERROR = "reporter_died"
DASHBOARD_AGENT_DIED_ERROR = "dashboard_agent_died"
DASHBOARD_DIED_ERROR = "dashboard_died"
RAYLET_CONNECTION_ERROR = "raylet_connection_error"
# Used in gpu detection
RESOURCE_CONSTRAINT_PREFIX = "accelerator_type:"
RESOURCES_ENVIRONMENT_VARIABLE = "RAY_OVERRIDE_RESOURCES"
# The reporter will report its statistics this often (milliseconds).
REPORTER_UPDATE_INTERVAL_MS = env_integer("REPORTER_UPDATE_INTERVAL_MS", 2500)
# Number of attempts to ping the Redis server. See
# `services.py:wait_for_redis_to_start`.
START_REDIS_WAIT_RETRIES = env_integer("RAY_START_REDIS_WAIT_RETRIES", 12)
LOGGER_FORMAT = (
"%(asctime)s\t%(levelname)s %(filename)s:%(lineno)s -- %(message)s")
LOGGER_FORMAT_HELP = f"The logging format. default='{LOGGER_FORMAT}'"
LOGGER_LEVEL = "info"
LOGGER_LEVEL_CHOICES = ["debug", "info", "warning", "error", "critical"]
LOGGER_LEVEL_HELP = ("The logging level threshold, choices=['debug', 'info',"
" 'warning', 'error', 'critical'], default='info'")
LOGGING_ROTATE_BYTES = 512 * 1024 * 1024 # 512MB.
LOGGING_ROTATE_BACKUP_COUNT = 5 # 5 Backup files at max.
# Constants used to define the different process types.
PROCESS_TYPE_REAPER = "reaper"
PROCESS_TYPE_MONITOR = "monitor"
PROCESS_TYPE_RAY_CLIENT_SERVER = "ray_client_server"
PROCESS_TYPE_LOG_MONITOR = "log_monitor"
# TODO(sang): Delete it.
PROCESS_TYPE_REPORTER = "reporter"
PROCESS_TYPE_DASHBOARD = "dashboard"
PROCESS_TYPE_DASHBOARD_AGENT = "dashboard_agent"
PROCESS_TYPE_WORKER = "worker"
PROCESS_TYPE_RAYLET = "raylet"
PROCESS_TYPE_PLASMA_STORE = "plasma_store"
PROCESS_TYPE_REDIS_SERVER = "redis_server"
PROCESS_TYPE_WEB_UI = "web_ui"
PROCESS_TYPE_GCS_SERVER = "gcs_server"
PROCESS_TYPE_PYTHON_CORE_WORKER_DRIVER = "python-core-driver"
PROCESS_TYPE_PYTHON_CORE_WORKER = "python-core-worker"
# Log file names
MONITOR_LOG_FILE_NAME = f"{PROCESS_TYPE_MONITOR}.log"
LOG_MONITOR_LOG_FILE_NAME = f"{PROCESS_TYPE_LOG_MONITOR}.log"
WORKER_PROCESS_TYPE_IDLE_WORKER = "ray::IDLE"
WORKER_PROCESS_TYPE_SPILL_WORKER_NAME = "SpillWorker"
WORKER_PROCESS_TYPE_RESTORE_WORKER_NAME = "RestoreWorker"
WORKER_PROCESS_TYPE_SPILL_WORKER_IDLE = (
f"ray::IDLE_{WORKER_PROCESS_TYPE_SPILL_WORKER_NAME}")
WORKER_PROCESS_TYPE_RESTORE_WORKER_IDLE = (
f"ray::IDLE_{WORKER_PROCESS_TYPE_RESTORE_WORKER_NAME}")
WORKER_PROCESS_TYPE_SPILL_WORKER = (
f"ray::SPILL_{WORKER_PROCESS_TYPE_SPILL_WORKER_NAME}")
WORKER_PROCESS_TYPE_RESTORE_WORKER = (
f"ray::RESTORE_{WORKER_PROCESS_TYPE_RESTORE_WORKER_NAME}")
WORKER_PROCESS_TYPE_SPILL_WORKER_DELETE = (
f"ray::DELETE_{WORKER_PROCESS_TYPE_SPILL_WORKER_NAME}")
WORKER_PROCESS_TYPE_RESTORE_WORKER_DELETE = (
f"ray::DELETE_{WORKER_PROCESS_TYPE_RESTORE_WORKER_NAME}")
LOG_MONITOR_MAX_OPEN_FILES = 200
# The object metadata field uses the following format: It is a comma
# separated list of fields. The first field is mandatory and is the
# type of the object (see types below) or an integer, which is interpreted
# as an error value. The second part is optional and if present has the
# form DEBUG:<breakpoint_id>, it is used for implementing the debugger.
# A constant used as object metadata to indicate the object is cross language.
OBJECT_METADATA_TYPE_CROSS_LANGUAGE = b"XLANG"
# A constant used as object metadata to indicate the object is python specific.
OBJECT_METADATA_TYPE_PYTHON = b"PYTHON"
# A constant used as object metadata to indicate the object is raw bytes.
OBJECT_METADATA_TYPE_RAW = b"RAW"
# A constant used as object metadata to indicate the object is an actor handle.
# This value should be synchronized with the Java definition in
# ObjectSerializer.java
# TODO(fyrestone): Serialize the ActorHandle via the custom type feature
# of XLANG.
OBJECT_METADATA_TYPE_ACTOR_HANDLE = b"ACTOR_HANDLE"
# A constant indicating the debugging part of the metadata (see above).
OBJECT_METADATA_DEBUG_PREFIX = b"DEBUG:"
AUTOSCALER_RESOURCE_REQUEST_CHANNEL = b"autoscaler_resource_request"
# The default password to prevent redis port scanning attack.
# Hex for ray.
REDIS_DEFAULT_PASSWORD = "5241590000000000"
# The default ip address to bind to.
NODE_DEFAULT_IP = "127.0.0.1"
# The Mach kernel page size in bytes.
MACH_PAGE_SIZE_BYTES = 4096
# Max 64 bit integer value, which is needed to ensure against overflow
# in C++ when passing integer values cross-language.
MAX_INT64_VALUE = 9223372036854775807
# Object Spilling related constants
DEFAULT_OBJECT_PREFIX = "ray_spilled_object"
|
the-stack_106_26584 | # coding: utf-8
import pprint
import re
import six
class ThreadCollection(object):
"""
Attributes:
swagger_types (dict): The key is attribute name and the value is attribute type.
attribute_map (dict): The key is attribute name and the value is json key in definition.
"""
swagger_types = {
'threads': 'list[Thread]'
}
attribute_map = {
'threads': 'threads'
}
def __init__(self, threads=None):
"""ThreadCollection"""
self._threads = None
self.discriminator = None
self.threads = threads
@property
def threads(self):
"""Gets the threads of this ThreadCollection.
:return: The threads of this ThreadCollection.
:rtype: list[ResourcePermission]
"""
return self._threads
@threads.setter
def threads(self, threads):
"""Sets the threads of this ThreadCollection.
:param threads: The threads of this ThreadCollection.
:type: ResourcePermission
"""
if threads is None:
raise ValueError("Invalid value for `threads`, must not be `None`")
self._threads = threads
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
if issubclass(ThreadCollection, dict):
for key, value in self.items():
result[key] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, ThreadCollection):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""Returns true if both objects are not equal"""
return not self == other
|
the-stack_106_26585 | # coding: utf-8
# Copyright (c) 2016, 2022, Oracle and/or its affiliates. All rights reserved.
# This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
from .document_feature import DocumentFeature
from oci.util import formatted_flat_dict, NONE_SENTINEL, value_allowed_none_or_none_sentinel # noqa: F401
from oci.decorators import init_model_state_from_kwargs
@init_model_state_from_kwargs
class DocumentTextDetectionFeature(DocumentFeature):
"""
Text recognition
"""
def __init__(self, **kwargs):
"""
Initializes a new DocumentTextDetectionFeature object with values from keyword arguments. The default value of the :py:attr:`~oci.ai_vision.models.DocumentTextDetectionFeature.feature_type` attribute
of this class is ``TEXT_DETECTION`` and it should not be changed.
The following keyword arguments are supported (corresponding to the getters/setters of this class):
:param feature_type:
The value to assign to the feature_type property of this DocumentTextDetectionFeature.
Allowed values for this property are: "LANGUAGE_CLASSIFICATION", "TEXT_DETECTION", "TABLE_DETECTION", "KEY_VALUE_DETECTION", "DOCUMENT_CLASSIFICATION"
:type feature_type: str
:param generate_searchable_pdf:
The value to assign to the generate_searchable_pdf property of this DocumentTextDetectionFeature.
:type generate_searchable_pdf: bool
"""
self.swagger_types = {
'feature_type': 'str',
'generate_searchable_pdf': 'bool'
}
self.attribute_map = {
'feature_type': 'featureType',
'generate_searchable_pdf': 'generateSearchablePdf'
}
self._feature_type = None
self._generate_searchable_pdf = None
self._feature_type = 'TEXT_DETECTION'
@property
def generate_searchable_pdf(self):
"""
Gets the generate_searchable_pdf of this DocumentTextDetectionFeature.
Whether or not to generate a searchable PDF file.
:return: The generate_searchable_pdf of this DocumentTextDetectionFeature.
:rtype: bool
"""
return self._generate_searchable_pdf
@generate_searchable_pdf.setter
def generate_searchable_pdf(self, generate_searchable_pdf):
"""
Sets the generate_searchable_pdf of this DocumentTextDetectionFeature.
Whether or not to generate a searchable PDF file.
:param generate_searchable_pdf: The generate_searchable_pdf of this DocumentTextDetectionFeature.
:type: bool
"""
self._generate_searchable_pdf = generate_searchable_pdf
def __repr__(self):
return formatted_flat_dict(self)
def __eq__(self, other):
if other is None:
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not self == other
|
the-stack_106_26586 | # Copyright 2020 The StackStorm Authors.
# Copyright 2019 Extreme Networks, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import absolute_import
import unittest2
from st2common.models.system.common import ResourceReference
from st2common.models.system.common import InvalidResourceReferenceError
class ResourceReferenceTestCase(unittest2.TestCase):
def test_resource_reference_success(self):
value = 'pack1.name1'
ref = ResourceReference.from_string_reference(ref=value)
self.assertEqual(ref.pack, 'pack1')
self.assertEqual(ref.name, 'name1')
self.assertEqual(ref.ref, value)
ref = ResourceReference(pack='pack1', name='name1')
self.assertEqual(ref.ref, 'pack1.name1')
ref = ResourceReference(pack='pack1', name='name1.name2')
self.assertEqual(ref.ref, 'pack1.name1.name2')
def test_resource_reference_failure(self):
self.assertRaises(InvalidResourceReferenceError,
ResourceReference.from_string_reference,
ref='blah')
self.assertRaises(InvalidResourceReferenceError,
ResourceReference.from_string_reference,
ref=None)
def test_to_string_reference(self):
ref = ResourceReference.to_string_reference(pack='mapack', name='moname')
self.assertEqual(ref, 'mapack.moname')
expected_msg = r'Pack name should not contain "\."'
self.assertRaisesRegexp(ValueError, expected_msg, ResourceReference.to_string_reference,
pack='pack.invalid', name='bar')
expected_msg = 'Both pack and name needed for building'
self.assertRaisesRegexp(ValueError, expected_msg, ResourceReference.to_string_reference,
pack='pack', name=None)
expected_msg = 'Both pack and name needed for building'
self.assertRaisesRegexp(ValueError, expected_msg, ResourceReference.to_string_reference,
pack=None, name='name')
def test_is_resource_reference(self):
self.assertTrue(ResourceReference.is_resource_reference('foo.bar'))
self.assertTrue(ResourceReference.is_resource_reference('foo.bar.ponies'))
self.assertFalse(ResourceReference.is_resource_reference('foo'))
|
the-stack_106_26587 | # Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import os
import torch
from torch.utils.data import Dataset
import numpy as np
import jsonlines
import json
from pytorch_transformers.tokenization_bert import BertTokenizer
from ._image_features_reader import ImageFeaturesH5Reader
import _pickle as cPickle
def iou(anchors, gt_boxes):
"""
anchors: (N, 4) ndarray of float
gt_boxes: (K, 4) ndarray of float
overlaps: (N, K) ndarray of overlap between boxes and query_boxes
"""
N = anchors.size(0)
K = gt_boxes.size(0)
gt_boxes_area = (
(gt_boxes[:, 2] - gt_boxes[:, 0] + 1) * (gt_boxes[:, 3] - gt_boxes[:, 1] + 1)
).view(1, K)
anchors_area = (
(anchors[:, 2] - anchors[:, 0] + 1) * (anchors[:, 3] - anchors[:, 1] + 1)
).view(N, 1)
boxes = anchors.view(N, 1, 4).expand(N, K, 4)
query_boxes = gt_boxes.view(1, K, 4).expand(N, K, 4)
iw = (
torch.min(boxes[:, :, 2], query_boxes[:, :, 2])
- torch.max(boxes[:, :, 0], query_boxes[:, :, 0])
+ 1
)
iw[iw < 0] = 0
ih = (
torch.min(boxes[:, :, 3], query_boxes[:, :, 3])
- torch.max(boxes[:, :, 1], query_boxes[:, :, 1])
+ 1
)
ih[ih < 0] = 0
ua = anchors_area + gt_boxes_area - (iw * ih)
overlaps = iw * ih / ua
return overlaps
def assert_eq(real, expected):
assert real == expected, "%s (true) vs %s (expected)" % (real, expected)
class GuessWhatPointingDataset(Dataset):
def __init__(
self,
task: str,
dataroot: str,
annotations_jsonpath: str,
split: str,
image_features_reader: ImageFeaturesH5Reader,
gt_image_features_reader: ImageFeaturesH5Reader,
tokenizer: BertTokenizer,
bert_model,
clean_datasets,
padding_index: int = 0,
max_seq_length: int = 20,
max_region_num: int = 60,
):
self.split = split
self.num_labels = 1
self._image_features_reader = image_features_reader
self._gt_image_features_reader = gt_image_features_reader
self._tokenizer = tokenizer
self._padding_index = padding_index
self._max_seq_length = max_seq_length
self.dataroot = dataroot
self.entries = self._load_annotations(clean_datasets)
self.max_region_num = max_region_num
clean_train = "_cleaned" if clean_datasets else ""
if "roberta" in bert_model:
cache_path = os.path.join(
dataroot,
"cache",
task
+ "_"
+ split
+ "_"
+ "roberta"
+ "_"
+ str(max_seq_length)
+ "_"
+ str(max_region_num)
+ clean_train
+ ".pkl",
)
else:
cache_path = os.path.join(
dataroot,
"cache",
task
+ "_"
+ split
+ "_"
+ str(max_seq_length)
+ "_"
+ str(max_region_num)
+ clean_train
+ ".pkl",
)
if not os.path.exists(cache_path):
self.tokenize()
self.tensorize()
cPickle.dump(self.entries, open(cache_path, "wb"))
else:
print("loading entries from %s" % (cache_path))
self.entries = cPickle.load(open(cache_path, "rb"))
def _load_annotations(self, clean_datasets):
# Build an index which maps image id with a list of caption annotations.
entries = []
remove_ids = []
if clean_datasets or self.split == "mteval":
remove_ids = np.load(
os.path.join(self.dataroot, "cache", "coco_test_ids.npy")
)
remove_ids = [int(x) for x in remove_ids]
all_images = cPickle.load(
open(os.path.join(self.dataroot, "cache", "image_bbox_list.pkl"), "rb")
)
boxes_dict = cPickle.load(
open(os.path.join(self.dataroot, "cache", "bboxes_dict.pkl"), "rb")
)
if self.split == "mteval":
annotations_path = os.path.join(
self.dataroot, "guesswhat.%s.jsonl" % "train"
)
else:
annotations_path = os.path.join(
self.dataroot, "guesswhat.%s.jsonl" % self.split
)
with jsonlines.open(annotations_path) as reader:
# Build an index which maps image id with a list of qa annotations.
for annotation in reader:
if (
self.split == "train"
and int(annotation["image"]["id"]) in remove_ids
):
continue
elif (
self.split == "mteval"
and int(annotation["image"]["id"]) not in remove_ids
):
continue
questions = []
answers = []
bboxes = []
for q in annotation["qas"]:
questions.append(q["question"])
answers.append(q["answer"])
for o in annotation["objects"]:
bboxes.append(o["id"])
total_bboxes = list(
set(all_images[annotation["image"]["id"]]["bboxes"])
)
total_bboxes = sorted(total_bboxes)
bbox_idx = []
for a in sorted(bboxes):
bbox_idx.append(total_bboxes.index(a))
entries.append(
{
"questions": questions,
"answers": answers,
"dialog_id": annotation["id"],
"image_id": annotation["image"]["id"],
"refBox": boxes_dict[annotation["object_id"]],
"ref_id": annotation["object_id"],
"mc_idx": bbox_idx,
}
)
return entries
def tokenize(self):
"""Tokenizes the questions.
This will add question_tokens in each entry of the dataset.
-1 represents nil, and should be treated as padding_idx in embedding.
"""
for entry in self.entries:
sentence = ""
for sent, ans in zip(entry["questions"], entry["answers"]):
sentence += "start " + sent + " answer " + ans + " stop "
tokens = self._tokenizer.encode(sentence)
tokens = tokens[: self._max_seq_length - 2]
tokens = self._tokenizer.add_special_tokens_single_sentence(tokens)
segment_ids = [0] * len(tokens)
input_mask = [1] * len(tokens)
if len(tokens) < self._max_seq_length:
# Note here we pad in front of the sentence
padding = [self._padding_index] * (self._max_seq_length - len(tokens))
tokens = tokens + padding
input_mask += padding
segment_ids += padding
assert_eq(len(tokens), self._max_seq_length)
entry["token"] = tokens
entry["input_mask"] = input_mask
entry["segment_ids"] = segment_ids
def tensorize(self):
for entry in self.entries:
token = torch.from_numpy(np.array(entry["token"]))
entry["token"] = token
input_mask = torch.from_numpy(np.array(entry["input_mask"]))
entry["input_mask"] = input_mask
segment_ids = torch.from_numpy(np.array(entry["segment_ids"]))
entry["segment_ids"] = segment_ids
def __getitem__(self, index):
entry = self.entries[index]
image_id = entry["image_id"]
ref_box = entry["refBox"]
mc_indexes = entry["mc_idx"] + [204] * 204
multiple_choice_idx = torch.from_numpy(np.array(mc_indexes[:204]))
features, num_boxes, boxes, boxes_ori = self._image_features_reader[image_id]
boxes_ori = boxes_ori[:num_boxes]
boxes = boxes[:num_boxes]
features = features[:num_boxes]
gt_features, gt_num_boxes, gt_boxes, gt_boxes_ori = self._gt_image_features_reader[
image_id
]
# merge two boxes, and assign the labels.
gt_boxes_ori = gt_boxes_ori[1:gt_num_boxes]
gt_boxes = gt_boxes[1:gt_num_boxes]
gt_features = gt_features[1:gt_num_boxes]
# concatenate the boxes
mix_boxes_ori = np.concatenate((boxes_ori, gt_boxes_ori), axis=0)
mix_boxes = np.concatenate((boxes, gt_boxes), axis=0)
mix_features = np.concatenate((features, gt_features), axis=0)
mix_num_boxes = min(int(num_boxes + int(gt_num_boxes) - 1), self.max_region_num)
# given the mix boxes, and ref_box, calculate the overlap.
mix_target = iou(
torch.tensor(mix_boxes_ori[:, :4]).float(), torch.tensor([ref_box]).float()
)
mix_target[mix_target < 0.5] = 0
image_mask = [1] * (mix_num_boxes)
while len(image_mask) < self.max_region_num:
image_mask.append(0)
mix_boxes_pad = np.zeros((self.max_region_num, 5))
mix_features_pad = np.zeros((self.max_region_num, 2048))
mix_boxes_pad[:mix_num_boxes] = mix_boxes[:mix_num_boxes]
mix_features_pad[:mix_num_boxes] = mix_features[:mix_num_boxes]
# appending the target feature.
features = torch.tensor(mix_features_pad).float()
image_mask = torch.tensor(image_mask).long()
spatials = torch.tensor(mix_boxes_pad).float()
spatials_ori = torch.tensor(mix_boxes_ori).float()
co_attention_mask = torch.zeros((self.max_region_num, self._max_seq_length))
# Only require the multiple choice bbox targets for calculating loss
target = torch.zeros((self.max_region_num, 1)).float()
target[:mix_num_boxes] = mix_target[:mix_num_boxes]
target = target[101:]
target = target[multiple_choice_idx]
caption = entry["token"]
input_mask = entry["input_mask"]
segment_ids = entry["segment_ids"]
return (
features,
spatials,
image_mask,
caption,
target,
input_mask,
segment_ids,
multiple_choice_idx,
co_attention_mask,
image_id,
)
def __len__(self):
return len(self.entries)
|
the-stack_106_26588 | from setuptools import setup
with open("README.md", "r") as fh:
long_description = fh.read()
setup(
author='Pelle Drijver',
author_email='[email protected]',
url='https://github.com/pelledrijver/twitch-highlights',
name='twitch-highlights',
version='1.1.1',
long_description=long_description,
long_description_content_type="text/markdown",
description="An OS-independent and easy-to-use module for creating highlight videos from trending Twitch clips. "
"Twitch highlight videos can be created by either specifying a category or a list of streamer "
"names.",
keywords="twitch, twitch highlights, twitch clips, twitch compilation",
install_requires=[
'requests',
'datetime',
'moviepy>=1.0.3',
'python-slugify>=4.0'
],
package_dir={'': 'src'},
packages=['twitch_highlights'],
license='Apache License 2.0',
classifiers=[
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
'License :: OSI Approved :: Apache Software License',
'Operating System :: OS Independent'
]
)
|
the-stack_106_26589 | # -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making BK-LOG 蓝鲸日志平台 available.
Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved.
BK-LOG 蓝鲸日志平台 is licensed under the MIT License.
License for BK-LOG 蓝鲸日志平台:
--------------------------------------------------------------------
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial
portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""
from apps.utils import ChoicesEnum
from django.utils.translation import ugettext_lazy as _
CONTENT_PATTERN_INDEX = 1
LATEST_PUBLISH_STATUS = "latest"
PATTERN_SIGNATURE_INDEX = 5
PATTERN_INDEX = 2
HOUR_MINUTES = 60
PERCENTAGE_RATE = 100
MIN_COUNT = 0
DOUBLE_PERCENTAGE = 100
EX_MAX_SIZE = 10000
IS_NEW_PATTERN_PREFIX = "is_new_class"
AGGS_FIELD_PREFIX = "__dist"
NEW_CLASS_FIELD_PREFIX = "dist"
NEW_CLASS_SENSITIVITY_FIELD = "sensitivity"
NEW_CLASS_QUERY_FIELDS = ["signature"]
NEW_CLASS_QUERY_TIME_RANGE = "1d"
CLUSTERING_CONFIG_EXCLUDE = ["sample_set_id", "model_id"]
CLUSTERING_CONFIG_DEFAULT = "default_clustering_config"
DEFAULT_CLUSTERING_FIELDS = "log"
DEFAULT_IS_CASE_SENSITIVE = 0
SAMPLE_SET_SLEEP_TIMER = 15 * 60
class YearOnYearEnum(ChoicesEnum):
NOT = 0
ONE_HOUR = 1
TWO_HOUR = 2
THREE_HOUR = 3
SIX_HOUR = 6
HALF_DAY = 12
ONE_DAY = 24
_choices_labels = (
(NOT, _("不比对")),
(ONE_HOUR, _("1小时前")),
(TWO_HOUR, _("2小时前")),
(THREE_HOUR, _("3小时前")),
(SIX_HOUR, _("6小时前")),
(HALF_DAY, _("12小时前")),
(ONE_DAY, _("24小时前")),
)
class PatternEnum(ChoicesEnum):
LEVEL_01 = "01"
LEVEL_03 = "03"
LEVEL_05 = "05"
LEVEL_07 = "07"
LEVEL_09 = "09"
@classmethod
def get_choices(cls) -> tuple:
return (
cls.LEVEL_09.value,
cls.LEVEL_07.value,
cls.LEVEL_05.value,
cls.LEVEL_03.value,
cls.LEVEL_01.value,
)
|
the-stack_106_26591 | #!/usr/bin/env python
# coding: utf-8
# This notebook was prepared by [Donne Martin](https://github.com/donnemartin). Source and license info is on [GitHub](https://github.com/donnemartin/interactive-coding-challenges).
# # Solution Notebook
# ## Problem: Format license keys.
#
# See the [LeetCode](https://leetcode.com/problems/license-key-formatting/) problem page.
#
# <pre>
# Now you are given a string S, which represents a software license key which we would like to format. The string S is composed of alphanumerical characters and dashes. The dashes split the alphanumerical characters within the string into groups. (i.e. if there are M dashes, the string is split into M+1 groups). The dashes in the given string are possibly misplaced.
#
# We want each group of characters to be of length K (except for possibly the first group, which could be shorter, but still must contain at least one character). To satisfy this requirement, we will reinsert dashes. Additionally, all the lower case letters in the string must be converted to upper case.
#
# So, you are given a non-empty string S, representing a license key to format, and an integer K. And you need to return the license key formatted according to the description above.
#
# Example 1:
# Input: S = "2-4A0r7-4k", K = 4
#
# Output: "24A0-R74K"
#
# Explanation: The string S has been split into two parts, each part has 4 characters.
# Example 2:
# Input: S = "2-4A0r7-4k", K = 3
#
# Output: "24-A0R-74K"
#
# Explanation: The string S has been split into three parts, each part has 3 characters except the first part as it could be shorter as said above.
#
# Note:
# The length of string S will not exceed 12,000, and K is a positive integer.
# String S consists only of alphanumerical characters (a-z and/or A-Z and/or 0-9) and dashes(-).
# String S is non-empty.
# </pre>
#
# * [Constraints](#Constraints)
# * [Test Cases](#Test-Cases)
# * [Algorithm](#Algorithm)
# * [Code](#Code)
# * [Unit Test](#Unit-Test)
# ## Constraints
#
# * Is the output a string?
# * Yes
# * Can we change the input string?
# * No, you can't modify the input string
# * Can we assume the inputs are valid?
# * No
# * Can we assume this fits memory?
# * Yes
# ## Test Cases
#
# * None -> TypeError
# * '---', k=3 -> ''
# * '2-4A0r7-4k', k=3 -> '24-A0R-74K'
# * '2-4A0r7-4k', k=4 -> '24A0-R74K'
# ## Algorithm
#
# * Loop through each character in the license key backwards, keeping a count of the number of chars we've reached so far, while inserting each character into a result list (convert to upper case)
# * If we reach a '-', skip it
# * Whenever we reach a char count of k, append a '-' character to the result list, reset the char count
# * Careful that we don't have a leading '-', which we might hit with test case: '2-4A0r7-4k', k=4 -> '24A0-R74K'
# * Reverse the result list and return it
#
# Complexity:
# * Time: O(n)
# * Space: O(n)
# ## Code
# In[1]:
class Solution(object):
def format_license_key(self, license_key, k):
if license_key is None:
raise TypeError('license_key must be a str')
if not license_key:
raise ValueError('license_key must not be empty')
formatted_license_key = []
num_chars = 0
for char in license_key[::-1]:
if char == '-':
continue
num_chars += 1
formatted_license_key.append(char.upper())
if num_chars >= k:
formatted_license_key.append('-')
num_chars = 0
if formatted_license_key and formatted_license_key[-1] == '-':
formatted_license_key.pop(-1)
return ''.join(formatted_license_key[::-1])
# ## Unit Test
# In[2]:
get_ipython().run_cell_magic('writefile', 'test_format_license_key.py', "import unittest\n\n\nclass TestSolution(unittest.TestCase):\n\n def test_format_license_key(self):\n solution = Solution()\n self.assertRaises(TypeError, solution.format_license_key, None, None)\n license_key = '---'\n k = 3\n expected = ''\n self.assertEqual(solution.format_license_key(license_key, k), expected)\n license_key = '2-4A0r7-4k'\n k = 3\n expected = '24-A0R-74K'\n self.assertEqual(solution.format_license_key(license_key, k), expected)\n license_key = '2-4A0r7-4k'\n k = 4\n expected = '24A0-R74K'\n self.assertEqual(solution.format_license_key(license_key, k), expected)\n print('Success: test_format_license_key')\n\ndef main():\n test = TestSolution()\n test.test_format_license_key()\n\n\nif __name__ == '__main__':\n main()")
# In[3]:
get_ipython().run_line_magic('run', '-i test_format_license_key.py')
|
the-stack_106_26593 | from .base import *
# Django Debug Toolbar
# https://django-debug-toolbar.readthedocs.io/en/latest/
INSTALLED_APPS += [
'debug_toolbar',
]
MIDDLEWARE += [
'debug_toolbar.middleware.DebugToolbarMiddleware',
]
INTERNAL_IPS = [
'127.0.0.1',
]
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.2/howto/static-files/
STATIC_URL = '/static/'
MEDIA_ROOT = os.path.join(PROJECT_ROOT, 'media')
MEDIA_URL = '/media/'
# Email
# https://docs.djangoproject.com/en/2.2/topics/email/#email-backends
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = config('EMAIL_HOST')
EMAIL_PORT = config('EMAIL_PORT')
BROKER_URL = config('CELERY_REDIS_LOCATION')
BROKER_TRANSPORT_OPTIONS = {
'polling_interval': 10,
'visibility_timeout': 3600
}
|
the-stack_106_26595 | import numpy as np
import pandas as pd
from data_generation import *
from calibration_functions import *
from calibration_function_derivates import *
from dataframe_helpers import *
from binnings import *
from os.path import join
def create_CV_trick_rows(df):
data_rows = []
selection = df[(df["n_folds"] == 5) | (df["n_folds"] == 10)]
for idx, row in selection.iterrows():
optimal = row["n_bins"]
pos_new = row["n_bins"]
min_bin_score = np.min(row["bin_scores"])
assert min_bin_score == row["bin_scores"][optimal]
for pos in range(optimal-1, 0, -1):
max_diff = min_bin_score*0.001
new_min_cand = row["bin_scores"][pos]
if new_min_cand <= min_bin_score + max_diff:
pos_new = pos
s1 = df[(df["seed"] == row["seed"])]
s2 = s1[(s1["expected_calibration_error"] == row["expected_calibration_error"])]
s3 = s2[(s2["binning"] == row["binning"])]
s4 = s3[(s3["n_bins"] == pos_new)]
found = s4[(s4["n_folds"] == 0)].copy()
found["n_folds"] = str(row["n_folds"]) + "_trick"
found["old_n_bins"] = optimal
data_rows.append(found.iloc[0])
return pd.DataFrame(data_rows)
def construct_data_row(binning, seed, n_folds, calibration_fun_name, n_data,
true_calibration_error_abs, true_calibration_error_square, expected_calibration_error,
bin_scores=None, all_cv_scores=None):
return {
"seed": seed,
"calibration_function": calibration_fun_name,
"n_data": n_data,
"n_folds": n_folds,
"binning": binning.binning_name,
"n_bins": binning.n_bins,
"ECE_abs": binning.ECE_abs,
"ECE_abs_debiased": binning.ECE_abs_debiased,
"true_calibration_error_abs": true_calibration_error_abs,
"ECE_square": binning.ECE_square,
"ECE_square_debiased": binning.ECE_square_debiased,
"true_calibration_error_square": true_calibration_error_square,
"flat_abs_c_hat_dist_c":np.mean(np.abs(binning.eval_flat(binning.p) - binning.c)),
"flat_square_c_hat_dist_c":np.mean(np.square(binning.eval_flat(binning.p) - binning.c)),
"slope_abs_c_hat_dist_c":np.mean(np.abs(binning.eval_slope_1(binning.p) - binning.c)),
"slope_square_c_hat_dist_c":np.mean(np.square(binning.eval_slope_1(binning.p) - binning.c)),
"expected_calibration_error": expected_calibration_error,
"bin_scores": bin_scores,
"all_cv_scores": all_cv_scores
}
def run_ece_tests(p, y, c, cal_method, data_name, n_data, seed, all_n_bins, data_path, data_part = -1):
"""
all_n_data = [100, 300, ..]
all_derivate_functions = find_all_derivates_for_calibration_functions(..)
seeds = [0,1,2,3,..]
beta_distribution = [1,1] # uniform
[1.1, 0.1] # beta1
all_n_bins = [1,2,3,4,5,..]
file_identifier = "uniform" # v6i m6ni muu s6na t2histamaks salvestatavat jaotust
"""
data_rows = []
expected_calibration_error = -1
error_fun = np.abs
true_calibration_error_abs = np.mean(np.abs(p - c))
true_calibration_error_square = np.mean(np.square(p - c))
cv_ECEs = {}
# Cross-validation
for use_eq_width in [True, False]:
for n_splits in [5, 10]:
bin_scores, all_cv_scores = binning_n_bins_with_crossvalidation(p, y, use_eq_width, n_splits)
n_bins_cv = np.argmin(bin_scores)
if use_eq_width:
binning = EqualWidthBinning(p, y, c, n_bins_cv)
else:
binning = EqualSizeBinning(p, y, c, n_bins_cv)
data_rows.append(construct_data_row(binning, seed, n_splits, cal_method, n_data,
true_calibration_error_abs, true_calibration_error_square, expected_calibration_error,
bin_scores, all_cv_scores))
# No cross-validation
for n_bins in all_n_bins:
# Eq width
binning = EqualWidthBinning(p, y, c, n_bins)
data_rows.append(construct_data_row(binning, seed, 0, cal_method, n_data,
true_calibration_error_abs, true_calibration_error_square, expected_calibration_error))
# Eq size
binning = EqualSizeBinning(p, y, c, n_bins)
data_rows.append(construct_data_row(binning, seed, 0, cal_method, n_data,
true_calibration_error_abs, true_calibration_error_square, expected_calibration_error))
# Monotonic eq size
binning = MonotonicEqualSizeBinning(p, y, c)
n_bins = binning.n_bins
data_rows.append(construct_data_row(binning, seed, 0, cal_method, n_data,
true_calibration_error_abs, true_calibration_error_square, expected_calibration_error))
df = pd.DataFrame(data_rows)
df_CV_trick = create_CV_trick_rows(df)
df_all = pd.concat([df,df_CV_trick])
df_all.to_pickle(join(data_path, f"binning_CV_seed_{seed}_{n_data}_{cal_method}_{data_name}_dp_{data_part}.pkl"), protocol = 4)
return df_all |
the-stack_106_26597 | # https://www.hackerrank.com/challenges/re-sub-regex-substitution/problem
import re
PATTERN = r"(?<= )(&&|\|\|)(?= )"
N = int(input())
for _ in range(N):
func = lambda x: "and" if x.group() == "&&" else "or"
result = re.sub(PATTERN, func, input())
print(result)
|
the-stack_106_26599 | # -*- python -*-
# Copyright (C) 2009-2014 Free Software Foundation, Inc.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import sys
import gdb
import os
import os.path
pythondir = '/home/tcwg-buildslave/workspace/tcwg-make-release/label/docker-trusty-amd64-tcwg-build/target/arm-eabi/_build/builds/destdir/x86_64-unknown-linux-gnu/share/gcc-4.9.4/python'
libdir = '/home/tcwg-buildslave/workspace/tcwg-make-release/label/docker-trusty-amd64-tcwg-build/target/arm-eabi/_build/builds/destdir/x86_64-unknown-linux-gnu/arm-eabi/lib/thumb/v7-a/fpv3/hard'
# This file might be loaded when there is no current objfile. This
# can happen if the user loads it manually. In this case we don't
# update sys.path; instead we just hope the user managed to do that
# beforehand.
if gdb.current_objfile () is not None:
# Update module path. We want to find the relative path from libdir
# to pythondir, and then we want to apply that relative path to the
# directory holding the objfile with which this file is associated.
# This preserves relocatability of the gcc tree.
# Do a simple normalization that removes duplicate separators.
pythondir = os.path.normpath (pythondir)
libdir = os.path.normpath (libdir)
prefix = os.path.commonprefix ([libdir, pythondir])
# In some bizarre configuration we might have found a match in the
# middle of a directory name.
if prefix[-1] != '/':
prefix = os.path.dirname (prefix) + '/'
# Strip off the prefix.
pythondir = pythondir[len (prefix):]
libdir = libdir[len (prefix):]
# Compute the ".."s needed to get from libdir to the prefix.
dotdots = ('..' + os.sep) * len (libdir.split (os.sep))
objfile = gdb.current_objfile ().filename
dir_ = os.path.join (os.path.dirname (objfile), dotdots, pythondir)
if not dir_ in sys.path:
sys.path.insert(0, dir_)
# Load the pretty-printers.
from libstdcxx.v6.printers import register_libstdcxx_printers
register_libstdcxx_printers (gdb.current_objfile ())
|
the-stack_106_26600 | #!/usr/bin/env python
import random
def getAnswer(number):
if number == 1:
return 'Hmm.. Good!!'
elif number == 3:
return 'Not good!'
else:
return 'Hmm.. Dunno!'
ans = getAnswer(random.randint(0, 3))
print(ans)
|
the-stack_106_26601 | """Unit tests for the Hypersphere."""
import scipy.special
import geomstats.backend as gs
import geomstats.tests
from geomstats.geometry.hypersphere import Hypersphere, HypersphereMetric
from geomstats.learning.frechet_mean import FrechetMean
from tests.conftest import Parametrizer
from tests.data.hypersphere_data import HypersphereMetricTestData, HypersphereTestData
from tests.geometry_test_cases import LevelSetTestCase, RiemannianMetricTestCase
MEAN_ESTIMATION_TOL = 1e-1
KAPPA_ESTIMATION_TOL = 1e-1
ONLINE_KMEANS_TOL = 1e-1
class TestHypersphere(LevelSetTestCase, metaclass=Parametrizer):
space = Hypersphere
testing_data = HypersphereTestData()
def test_replace_values(self, dim, points, new_points, indcs, expected):
space = self.space(dim)
result = space._replace_values(
gs.array(points), gs.array(new_points), gs.array(indcs)
)
self.assertAllClose(result, expected)
def test_angle_to_extrinsic(self, dim, point, expected):
space = self.space(dim)
result = space.angle_to_extrinsic(point)
self.assertAllClose(result, expected)
def test_extrinsic_to_angle(self, dim, point, expected):
space = self.space(dim)
result = space.extrinsic_to_angle(point)
self.assertAllClose(result, expected)
def test_spherical_to_extrinsic(self, dim, point, expected):
space = self.space(dim)
result = space.spherical_to_extrinsic(point)
self.assertAllClose(result, expected)
def test_extrinsic_to_spherical(self, dim, point, expected):
space = self.space(dim)
result = space.extrinsic_to_spherical(point)
self.assertAllClose(result, expected)
def test_random_von_mises_fisher_belongs(self, dim, n_samples):
space = self.space(dim)
result = space.belongs(space.random_von_mises_fisher(n_samples=n_samples))
self.assertTrue(gs.all(result))
def test_random_von_mises_fisher_mean(self, dim, kappa, n_samples, expected):
space = self.space(dim)
points = space.random_von_mises_fisher(kappa=kappa, n_samples=n_samples)
sum_points = gs.sum(points, axis=0)
result = sum_points / gs.linalg.norm(sum_points)
self.assertAllClose(result, expected, atol=KAPPA_ESTIMATION_TOL)
def test_tangent_spherical_to_extrinsic(
self, dim, tangent_vec_spherical, base_point_spherical, expected
):
space = self.space(dim)
result = space.tangent_spherical_to_extrinsic(
tangent_vec_spherical, base_point_spherical
)
self.assertAllClose(result, expected)
def test_tangent_extrinsic_to_spherical(
self, dim, tangent_vec, base_point, base_point_spherical, expected
):
space = self.space(dim)
result = space.tangent_extrinsic_to_spherical(
tangent_vec, base_point, base_point_spherical
)
self.assertAllClose(result, expected)
def test_tangent_extrinsic_to_spherical_raises(
self, dim, tangent_vec, base_point, base_point_spherical, expected
):
space = self.space(dim)
with expected:
space.tangent_extrinsic_to_spherical(
tangent_vec, base_point, base_point_spherical
)
@geomstats.tests.np_autograd_and_torch_only
def test_riemannian_normal_frechet_mean(self, dim):
space = self.space(dim)
mean = space.random_uniform()
precision = gs.eye(space.dim) * 10
sample = space.random_riemannian_normal(mean, precision, 30000)
estimator = FrechetMean(space.metric, method="adaptive")
estimator.fit(sample)
estimate = estimator.estimate_
self.assertAllClose(estimate, mean, atol=1e-1)
@geomstats.tests.np_autograd_and_torch_only
def test_riemannian_normal_and_belongs(self, dim, n_points):
space = self.space(dim)
mean = space.random_uniform()
cov = gs.eye(dim)
sample = space.random_riemannian_normal(mean, cov, n_points)
result = space.belongs(sample)
self.assertTrue(gs.all(result))
def test_sample_von_mises_fisher_mean(self, dim, mean, kappa, n_points):
"""
Check that the maximum likelihood estimates of the mean and
concentration parameter are close to the real values. A first
estimation of the concentration parameter is obtained by a
closed-form expression and improved through the Newton method.
"""
space = self.space(dim)
points = space.random_von_mises_fisher(mu=mean, kappa=kappa, n_samples=n_points)
sum_points = gs.sum(points, axis=0)
result = sum_points / gs.linalg.norm(sum_points)
expected = mean
self.assertAllClose(result, expected, atol=MEAN_ESTIMATION_TOL)
def test_sample_random_von_mises_fisher_kappa(self, dim, kappa, n_points):
# check concentration parameter for dispersed distribution
sphere = Hypersphere(dim)
points = sphere.random_von_mises_fisher(kappa=kappa, n_samples=n_points)
sum_points = gs.sum(points, axis=0)
mean_norm = gs.linalg.norm(sum_points) / n_points
kappa_estimate = (
mean_norm * (dim + 1.0 - mean_norm**2) / (1.0 - mean_norm**2)
)
kappa_estimate = gs.cast(kappa_estimate, gs.float64)
p = dim + 1
n_steps = 100
for _ in range(n_steps):
bessel_func_1 = scipy.special.iv(p / 2.0, kappa_estimate)
bessel_func_2 = scipy.special.iv(p / 2.0 - 1.0, kappa_estimate)
ratio = bessel_func_1 / bessel_func_2
denominator = 1.0 - ratio**2 - (p - 1.0) * ratio / kappa_estimate
mean_norm = gs.cast(mean_norm, gs.float64)
kappa_estimate = kappa_estimate - (ratio - mean_norm) / denominator
result = kappa_estimate
expected = kappa
self.assertAllClose(result, expected, atol=KAPPA_ESTIMATION_TOL)
class HypersphereMetricTestCase(RiemannianMetricTestCase):
def test_inner_product(
self, dim, tangent_vec_a, tangent_vec_b, base_point, expected
):
metric = self.metric(dim)
result = metric.inner_product(
gs.array(tangent_vec_a), gs.array(tangent_vec_b), gs.array(base_point)
)
self.assertAllClose(result, expected)
def test_dist(self, dim, point_a, point_b, expected):
metric = self.metric(dim)
result = metric.dist(gs.array(point_a), gs.array(point_b))
self.assertAllClose(result, gs.array(expected))
def test_dist_pairwise(self, dim, point, expected, rtol):
metric = self.metric(dim)
result = metric.dist_pairwise(gs.array(point))
self.assertAllClose(result, gs.array(expected), rtol=rtol)
def test_diameter(self, dim, points, expected):
metric = self.metric(dim)
result = metric.diameter(gs.array(points))
self.assertAllClose(result, gs.array(expected))
def test_christoffels_shape(self, dim, point, expected):
metric = self.metric(dim)
result = metric.christoffels(point)
self.assertAllClose(gs.shape(result), expected)
def test_sectional_curvature(
self, dim, tangent_vec_a, tangent_vec_b, base_point, expected
):
metric = self.metric(dim)
result = metric.sectional_curvature(tangent_vec_a, tangent_vec_b, base_point)
self.assertAllClose(result, expected, atol=1e-2)
def test_exp_and_dist_and_projection_to_tangent_space(
self, dim, vector, base_point
):
metric = self.metric(dim)
tangent_vec = Hypersphere(dim).to_tangent(vector=vector, base_point=base_point)
exp = metric.exp(tangent_vec=tangent_vec, base_point=base_point)
result = metric.dist(base_point, exp)
expected = gs.linalg.norm(tangent_vec) % (2 * gs.pi)
self.assertAllClose(result, expected)
class TestHypersphereMetric(HypersphereMetricTestCase, metaclass=Parametrizer):
metric = connection = HypersphereMetric
skip_test_exp_geodesic_ivp = True
skip_test_dist_point_to_itself_is_zero = True
testing_data = HypersphereMetricTestData()
|
the-stack_106_26602 | from torch.utils.data import Dataset
from torch.utils.data import DataLoader, WeightedRandomSampler
import torch
import numpy as np
import scipy
class TorchDataset(Dataset):
"""
Format for numpy array
Parameters
----------
X: 2D array
The input matrix
y: 2D array
The one-hot encoded target
"""
def __init__(self, x, y):
self.x = x
self.y = y
def __len__(self):
return len(self.x)
def __getitem__(self, index):
x, y = self.x[index], self.y[index]
return x, y
class PredictDataset(Dataset):
"""
Format for numpy array
Parameters
----------
X: 2D array
The input matrix
"""
def __init__(self, x):
self.x = x
def __len__(self):
return len(self.x)
def __getitem__(self, index):
x = self.x[index]
return x
def create_dataloaders(X_train, y_train, X_valid, y_valid, weights,
batch_size, num_workers, drop_last, sample_class=None):
"""
Create dataloaders with or wihtout subsampling depending on weights and balanced.
Parameters
----------
X_train: np.ndarray
Training data
y_train: np.array
Mapped Training targets
X_valid: np.ndarray
Validation data
y_valid: np.array
Mapped Validation targets
weights : either 0, 1, dict or iterable
if 0 (default) : no weights will be applied
if 1 : classification only, will balanced class with inverse frequency
if dict : keys are corresponding class values are sample weights
if iterable : list or np array must be of length equal to nb elements
in the training set
Returns
-------
train_dataloader, valid_dataloader : torch.DataLoader, torch.DataLoader
Training and validation dataloaders
"""
train_ds = TorchDataset(X_train, y_train)
valid_ds = TorchDataset(X_valid, y_valid)
if sample_class is not None:
need_shuffle = False
sampler = sample_class(train_ds)
else:
if isinstance(weights, int):
if weights == 0:
need_shuffle = True
sampler = None
elif weights == 1:
need_shuffle = False
class_sample_count = np.array(
[len(np.where(y_train == t)[0]) for t in np.unique(y_train)])
weights = 1. / class_sample_count
samples_weight = np.array([weights[t] for t in y_train])
samples_weight = torch.from_numpy(samples_weight)
samples_weight = samples_weight.double()
sampler = WeightedRandomSampler(samples_weight, len(samples_weight))
else:
raise ValueError('Weights should be either 0, 1, dictionnary or list.')
elif isinstance(weights, dict):
# custom weights per class
need_shuffle = False
samples_weight = np.array([weights[t] for t in y_train])
sampler = WeightedRandomSampler(samples_weight, len(samples_weight))
else:
# custom weights
if len(weights) != len(y_train):
raise ValueError('Custom weights should match number of train samples.')
need_shuffle = False
samples_weight = np.array(weights)
sampler = WeightedRandomSampler(samples_weight, len(samples_weight))
train_dataloader = DataLoader(train_ds,
batch_size=batch_size,
sampler=sampler,
shuffle=need_shuffle,
num_workers=num_workers,
drop_last=drop_last)
valid_dataloader = DataLoader(valid_ds,
batch_size=batch_size,
shuffle=False,
num_workers=num_workers)
return train_dataloader, valid_dataloader
def create_explain_matrix(input_dim, cat_emb_dim, cat_idxs, post_embed_dim):
"""
This is a computational trick.
In order to rapidly sum importances from same embeddings
to the initial index.
Parameters
----------
input_dim: int
Initial input dim
cat_emb_dim : int or list of int
if int : size of embedding for all categorical feature
if list of int : size of embedding for each categorical feature
cat_idxs : list of int
Initial position of categorical features
post_embed_dim : int
Post embedding inputs dimension
Returns
-------
reducing_matrix : np.array
Matrix of dim (post_embed_dim, input_dim) to performe reduce
"""
if isinstance(cat_emb_dim, int):
all_emb_impact = [cat_emb_dim-1]*len(cat_idxs)
else:
all_emb_impact = [emb_dim-1 for emb_dim in cat_emb_dim]
acc_emb = 0
nb_emb = 0
indices_trick = []
for i in range(input_dim):
if i not in cat_idxs:
indices_trick.append([i+acc_emb])
else:
indices_trick.append(range(i+acc_emb, i+acc_emb+all_emb_impact[nb_emb]+1))
acc_emb += all_emb_impact[nb_emb]
nb_emb += 1
reducing_matrix = np.zeros((post_embed_dim, input_dim))
for i, cols in enumerate(indices_trick):
reducing_matrix[cols, i] = 1
return scipy.sparse.csc_matrix(reducing_matrix)
|
the-stack_106_26603 | from __future__ import division, print_function
import argparse
import os
import random
import time
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
import factorial_crf_tagger
import unit
import utils
parser = argparse.ArgumentParser()
parser.add_argument(
"--treebank_path",
type=str,
default="/projects/tir2/users/cmalaviy/ud_exp/ud-treebanks-v2.1/",
)
parser.add_argument(
"--optim", type=str, default="adam", choices=["sgd", "adam", "adagrad"]
)
parser.add_argument("--lr", type=float, default=0.1)
parser.add_argument("--emb_dim", type=int, default=128)
parser.add_argument("--hidden_dim", type=int, default=256)
parser.add_argument("--mlp_dim", type=int, default=128)
parser.add_argument("--n_layers", type=int, default=2)
parser.add_argument("--dropout", type=float, default=0.2)
parser.add_argument("--epochs", type=int, default=10)
parser.add_argument("--batch_size", type=int, default=16)
parser.add_argument(
"--langs",
type=str,
default="uk",
help="Languages separated by delimiter '/' with last language being target language",
)
parser.add_argument(
"--tgt_size",
type=int,
default=None,
help="Number of training sentences for target language",
)
parser.add_argument("--model_name", type=str, default="model_dcrf")
parser.add_argument("--no_transitions", action="store_true")
parser.add_argument("--no_pairwise", action="store_true")
parser.add_argument("--continue_train", action="store_true")
parser.add_argument(
"--model_type",
type=str,
default="baseline",
choices=["universal", "joint", "mono", "specific", "baseline"],
)
parser.add_argument("--sum_word_char", action="store_true")
parser.add_argument("--sent_attn", action="store_true")
parser.add_argument("--patience", type=int, default=3)
parser.add_argument("--test", action="store_true")
parser.add_argument("--visualize", action="store_true")
parser.add_argument("--gpu", action="store_true")
parser.add_argument("--unit_test", action="store_true")
parser.add_argument("--unit_test_args", type=str, default="2,2,2")
parser.add_argument("--seed", type=int, default=42)
args = parser.parse_args()
print(args)
# Set seeds
torch.manual_seed(args.seed)
random.seed(args.seed)
langs = args.langs.split("/")
lang_to_code, code_to_lang = utils.get_lang_code_dicts()
# Set model name
args.model_name += "_" + args.model_type + "".join(["_" + l for l in langs])
# if args.sum_word_char:
# args.model_name += "-wc_sum"
if args.sent_attn:
args.model_name += "-sent_attn"
if args.tgt_size:
args.model_name += "-" + str(args.tgt_size)
if args.no_transitions:
args.model_name += "-no_transitions"
if args.no_pairwise:
args.model_name += "-no_pairwise"
# Get training data
print("Loading training data...")
training_data_langwise, train_tgt_labels = utils.read_conll(
args.treebank_path,
langs,
code_to_lang,
tgt_size=args.tgt_size,
train_or_dev="train",
)
training_data = []
train_lang_ids = []
# labels_to_ix = train_tgt_labels
unique_tags = utils.find_unique_tags(train_tgt_labels, null_label=True)
print("Number of unique tags: %d" % unique_tags.size())
# unique_tags.printTags()
# Oversample target language data
if args.tgt_size == 100 and args.model_type != "mono":
training_data_langwise[langs[-1]] = training_data_langwise[langs[-1]] * 10
# Add null labels to tag sets in training data
training_data_langwise = utils.addNullLabels(training_data_langwise, langs, unique_tags)
# Create batches for training
train_order = []
train_lang_ids = []
startIdx = 0
for l in langs:
training_data_langwise[l], lang_ids = utils.sortbylength(
training_data_langwise[l], [l] * len(training_data_langwise[l])
)
if args.batch_size != 1:
train_order += utils.get_train_order(
training_data_langwise[l], args.batch_size, startIdx=startIdx
)
training_data += training_data_langwise[l]
train_lang_ids += [l] * len(training_data_langwise[l])
startIdx = len(training_data)
print("%d sentences in training set" % len(training_data))
if args.unit_test:
training_data = []
no_tags, no_labels, no_timesteps = [
int(arg) for arg in args.unit_test_args.strip().split(",")
]
training_data, train_tgt_labels = unit.create_sample_data(
int(no_tags), [int(no_labels)] * int(no_tags), int(no_timesteps)
)
# training_data, train_tgt_labels = unit.create_sample_data(int(no_tags), [2,3], int(no_timesteps))
training_data = [training_data]
dev_data_langwise, dev_tgt_labels = utils.read_conll(
args.treebank_path, [langs[-1]], code_to_lang, train_or_dev="dev"
)
# Add null labels to tag sets in dev data
dev_data_langwise = utils.addNullLabels(dev_data_langwise, [langs[-1]], unique_tags)
dev_data = dev_data_langwise[langs[-1]]
dev_lang_ids = [langs[-1]] * len(dev_data)
## Sort train/valid set before minibatching
dev_data, dev_lang_ids = utils.sortbylength(dev_data, dev_lang_ids)
if args.test:
test_lang = langs[-1]
test_data_langwise, test_tgt_labels = utils.read_conll(
args.treebank_path, [test_lang], code_to_lang, train_or_dev="test", test=True
)
test_data_langwise = utils.addNullLabels(
test_data_langwise, [test_lang], unique_tags
)
test_data = test_data_langwise[test_lang]
test_data, test_lang_ids = utils.sortbylength(
test_data, [langs[-1]] * len(test_data)
)
# Store starting index of each minibatch
if args.batch_size != 1:
print("Training Set: %d batches" % len(train_order))
dev_order = utils.get_train_order(dev_data, args.batch_size)
print("Dev Set: %d batches" % len(dev_order))
if args.test:
test_order = utils.get_train_order(test_data, args.batch_size)
print("Test Set: %d batches" % len(test_order))
else:
train_order = [(i, i) for i in range(len(training_data))]
dev_order = [(i, i) for i in range(len(dev_data))]
if args.test:
test_order = [(i, i) for i in range(len(test_data))]
# Build word and character dictionaries
word_to_ix = {}
char_to_ix = {}
word_freq = {}
for sent, _ in training_data:
for word in sent:
if word not in word_to_ix:
word_to_ix[word] = len(word_to_ix)
if word_to_ix[word] not in word_freq:
word_freq[word_to_ix[word]] = 1
else:
word_freq[word_to_ix[word]] += 1
for char in word:
if char not in char_to_ix:
char_to_ix[char] = len(char_to_ix)
word_to_ix["UNK"] = len(word_to_ix)
char_to_ix["UNK"] = len(char_to_ix)
def main():
if not os.path.isfile(args.model_name) or args.continue_train:
if args.continue_train:
print("Loading tagger model from " + args.model_name + "...")
tagger_model = torch.load(
args.model_name, map_location=lambda storage, loc: storage
)
if args.gpu:
tagger_model = tagger_model.cuda()
else:
print("Creating new model...")
tagger_model = factorial_crf_tagger.DynamicCRF(
args, word_freq, langs, len(char_to_ix), len(word_to_ix), unique_tags
)
if args.gpu:
tagger_model = tagger_model.cuda()
if args.unit_test:
tests = unit.TestBP()
labelSum = sum([tag.size() for tag in tagger_model.uniqueTags])
# Create dummy LSTM features
lstm_feats = utils.get_var(
torch.Tensor(torch.randn(len(training_data[0][0]), labelSum)), args.gpu
)
tests.setUp(
tagger_model, training_data[0][1], len(training_data[0][0]), lstm_feats
)
loss_function = nn.NLLLoss()
# Provide (N,C) log probability values as input
# loss_function = nn.CrossEntropyLoss()
if args.optim == "sgd":
optimizer = optim.SGD(tagger_model.parameters(), lr=1.0)
elif args.optim == "adam":
optimizer = optim.Adam(tagger_model.parameters())
elif args.optim == "adagrad":
optimizer = optim.Adagrad(tagger_model.parameters())
print("Training FCRF-LSTM model...")
patience_counter = 0
prev_avg_tok_accuracy = 0
for epoch in range(args.epochs):
accuracies = []
sent = 0
batch_idx = 0
tokens = 0
cum_loss = 0
correct = 0
random.shuffle(train_order)
print("Starting epoch %d .." % epoch)
start_time = time.time()
for start_idx, end_idx in train_order:
train_data = training_data[start_idx : end_idx + 1]
train_sents = [elem[0] for elem in train_data]
morph_sents = [elem[1] for elem in train_data]
lang_ids = train_lang_ids[start_idx : end_idx + 1]
sent += end_idx - start_idx + 1
tokens += sum([len(sentence) for sentence in train_sents])
batch_idx += 1
if batch_idx % 5 == 0:
print(
"[Epoch %d] \
Sentence %d/%d, \
Tokens %d \
Cum_Loss: %f \
Time: %f \
Tokens/Sec: %d"
# Average Accuracy: %f"
% (
epoch,
sent,
len(training_data),
tokens,
cum_loss / tokens,
time.time() - start_time,
tokens / (time.time() - start_time),
)
)
# , correct/tokens))
tagger_model.zero_grad()
sents_in = []
for i, sentence in enumerate(train_sents):
sent_in = []
lang_id = []
if args.model_type == "universal":
lang_id = [lang_ids[i]]
for word in sentence:
s_appended_word = lang_id + [c for c in word] + lang_id
word_in = utils.prepare_sequence(
s_appended_word, char_to_ix, args.gpu
)
# targets = utils.prepare_sequence(s_appended_word[1:], char_to_ix, args.gpu)
sent_in.append(word_in)
sents_in.append(sent_in)
# sents_in = torch.stack(sent_in)
tagger_model.char_hidden = tagger_model.init_hidden()
tagger_model.hidden = tagger_model.init_hidden()
if args.sum_word_char:
all_word_seq = []
for sentence in train_sents:
word_seq = utils.prepare_sequence(
sentence, word_to_ix, args.gpu
)
all_word_seq.append(word_seq)
else:
all_word_seq = None
if args.model_type == "specific" or args.model_type == "joint":
lstm_feat_sents, graph, maxVal = tagger_model(
sents_in, morph_sents, word_idxs=all_word_seq, langs=lang_ids
)
else:
lstm_feat_sents, graph, maxVal = tagger_model(
sents_in, morph_sents, word_idxs=all_word_seq
)
# Skip parameter updates if marginals are not within a threshold
if maxVal > 10.00:
print("Skipping parameter updates...")
continue
# Compute the loss, gradients, and update the parameters
all_factors_batch = []
for k in range(len(train_sents)):
all_factors = tagger_model.get_scores(
graph, morph_sents[k], lstm_feat_sents[k], k
)
all_factors_batch.append(all_factors)
loss = tagger_model.compute_loss(all_factors_batch, loss_function)
# print("Loss:", loss)
cum_loss += loss.cpu().item()
loss.backward()
# tagger_model.gradient_check(all_factors_batch[0])
optimizer.step()
print("Loss: %f" % loss.cpu().numpy())
print("Saving model..")
torch.save(tagger_model, args.model_name)
if (epoch + 1) % 4 == 0:
print("Evaluating on dev set...")
avg_tok_accuracy, f1_score = eval_on_dev(tagger_model, curEpoch=epoch)
# Early Stopping
if avg_tok_accuracy <= prev_avg_tok_accuracy:
patience_counter += 1
if patience_counter == args.patience:
print(
"Model hasn't improved on dev set for %d epochs. Stopping Training."
% patience_counter
)
break
prev_avg_tok_accuracy = avg_tok_accuracy
else:
print("Loading tagger model from " + args.model_name + "...")
tagger_model = torch.load(
args.model_name, map_location=lambda storage, loc: storage
)
if args.gpu:
tagger_model = tagger_model.cuda()
else:
tagger_model.gpu = False
if args.visualize:
print("[Visualization Mode]")
utils.plot_heatmap(unique_tags, tagger_model.pairwise_weights, "pair")
# utils.plot_heatmap(unique_tags, tagger_model.transition_weights, "trans")
# utils.plot_heatmap(unique_tags, tagger_model.lang_pairwise_weights, "pair", lang_idx=1)
print("Stored plots in figures/ directory!")
if args.test:
avg_tok_accuracy, f1_score = eval_on_dev(tagger_model, dev_or_test="test")
def eval_on_dev(tagger_model, curEpoch=None, dev_or_test="dev"):
correct = 0
toks = 0
all_out_tags = np.array([])
all_targets = np.array([])
eval_order = dev_order if dev_or_test == "dev" else test_order
eval_data = dev_data if dev_or_test == "dev" else test_data
print(
"Starting evaluation on %s set... (%d sentences)"
% (dev_or_test, len(eval_data))
)
lang_id = []
if args.model_type == "universal":
lang_id = [langs[-1]]
for start_idx, end_idx in eval_order:
cur_eval_data = eval_data[start_idx : end_idx + 1]
eval_sents = [elem[0] for elem in cur_eval_data]
morph_sents = [elem[1] for elem in cur_eval_data]
sents_in = []
for i, sentence in enumerate(eval_sents):
sent_in = []
for word in sentence:
s_appended_word = lang_id + [c for c in word] + lang_id
word_in = utils.prepare_sequence(s_appended_word, char_to_ix, args.gpu)
# targets = utils.prepare_sequence(s_appended_word[1:], char_to_ix, args.gpu)
sent_in.append(word_in)
sents_in.append(sent_in)
tagger_model.zero_grad()
tagger_model.char_hidden = tagger_model.init_hidden()
tagger_model.hidden = tagger_model.init_hidden()
all_word_seq = []
for sentence in eval_sents:
word_seq = utils.prepare_sequence(sentence, word_to_ix, args.gpu)
all_word_seq.append(word_seq)
if args.model_type == "specific" or args.model_type == "joint":
lstm_feats, graph, maxVal = tagger_model(
sents_in,
morph_sents,
word_idxs=all_word_seq,
langs=[langs[-1]] * len(sents_in),
test=True,
)
else:
lstm_feats, graph, maxVal = tagger_model(
sents_in, morph_sents, word_idxs=all_word_seq, test=True
)
for k in range(len(eval_sents)):
hypSeq = tagger_model.getBestSequence(graph, k)
targets = [utils.unfreeze_dict(tags) for tags in morph_sents[k]]
correct += utils.getCorrectCount(targets, hypSeq)
toks += len(eval_sents[k])
all_out_tags = np.append(all_out_tags, hypSeq)
all_targets = np.append(all_targets, targets)
avg_tok_accuracy = correct / toks
prefix = args.model_name
prefix += "_" + dev_or_test
if args.sent_attn:
prefix += "sent_attn"
if args.tgt_size:
prefix += "_" + str(args.tgt_size)
write = True if dev_or_test == "test" else False
f1_score, f1_micro_score = utils.computeF1(
all_out_tags, all_targets, prefix, write_results=write
)
print("Test Set Accuracy: %f" % avg_tok_accuracy)
print("Test Set Avg F1 Score (Macro): %f" % f1_score)
print("Test Set Avg F1 Score (Micro): %f" % f1_micro_score)
if write:
with open(prefix + "_results_f1.txt", "ab") as file:
file.write("\nAccuracy: " + str(avg_tok_accuracy) + "\n")
for target, hyp in zip(all_targets, all_out_tags):
file.write(str(target) + "\n")
file.write(str(hyp) + "\n")
return avg_tok_accuracy, f1_score
# def eval_on_test(tagger_model):
# correct = 0
# toks = 0
# all_out_tags = np.array([])
# all_targets = np.array([])
# print("Starting evaluation on test set... (%d sentences)" % (len(test_data)))
# lang_id = []
# if args.model_type=="universal":
# lang_id = [lang]
# for sentence, morph in test_data:
# tagger_model.zero_grad()
# tagger_model.char_hidden = tagger_model.init_hidden()
# tagger_model.hidden = tagger_model.init_hidden()
# sent_in = []
# for word in sentence:
# s_appended_word = lang_id + [c for c in word] + lang_id
# word_in = utils.prepare_sequence(s_appended_word, char_to_ix, args.gpu)
# sent_in.append(word_in)
# # sentence_in = utils.prepare_sequence(sentence, word_to_ix, args.gpu)
# # targets = utils.prepare_sequence(morph, labels_to_ix, args.gpu)
# # if args.sum_word_char:
# word_seq = [utils.prepare_sequence(sentence, word_to_ix, args.gpu)]
# # else:
# # word_seq = None
# if args.model_type=="specific" or args.model_type=="joint":
# lstm_feats, graph, maxVal = tagger_model([sent_in], [morph], word_idxs=word_seq, lang=langs[-1], test=True)
# else:
# lstm_feats, graph, maxVal = tagger_model([sent_in], [morph], word_idxs=word_seq, test=True)
# hypSeq = tagger_model.getBestSequence(graph, 0)
# targets = [utils.unfreeze_dict(tags) for tags in morph]
# # correct += np.count_nonzero(out_tags==targets)
# correct += utils.getCorrectCount(targets, hypSeq)
# toks += len(sentence)
# all_out_tags = np.append(all_out_tags, hypSeq)
# all_targets = np.append(all_targets, targets)
# avg_tok_accuracy = correct / toks
# prefix = args.model_type + "_"
# if args.sum_word_char:
# prefix = "wc-sum-hf_" + prefix
# prefix += "-".join([l for l in langs]) + "_test"
# if args.sent_attn:
# prefix += "sent_attn"
# if args.tgt_size:
# prefix += "_" + str(args.tgt_size)
# f1_score, f1_micro_score = utils.computeF1(all_out_tags, all_targets, prefix, write_results=True)
# print("Test Set Accuracy: %f" % avg_tok_accuracy)
# print("Test Set Avg F1 Score (Macro): %f" % f1_score)
# print("Test Set Avg F1 Score (Micro): %f" % f1_micro_score)
# with open(prefix + '_results_f1.txt', 'a') as file:
# file.write("\nAccuracy: " + str(avg_tok_accuracy) + "\n")
# return avg_tok_accuracy, f1_score
if __name__ == "__main__":
main()
|
the-stack_106_26605 | import zmq
import argparse
import logging
from logging import StreamHandler, Formatter
from logging.handlers import SysLogHandler
logger = logging.getLogger("") # setup the root logger
def setup_logger(debug=False):
if debug:
level = logging.DEBUG
else:
level = logging.INFO
logger.setLevel(logging.DEBUG)
formatter = Formatter('%(asctime)s %(name)-12s%(levelname)-8s %(message)s', datefmt='%m-%d %H:%M')
consoleh = StreamHandler()
consoleh.setLevel(level)
consoleh.setFormatter(formatter)
# syslogh = SysLogHandler()
# syslogh.setLevel(level)
# syslogh.setFormatter(formatter)
logger.addHandler(consoleh)
# logger.addHandler(syslogh)
_ctx = zmq.Context()
_socket = _ctx.socket(zmq.SUB)
def main():
setup_logger()
parser = argparse.ArgumentParser()
parser.add_argument("endpoint", help="ZeroMQ PUB endpoint to subscribe to")
args = parser.parse_args()
_socket.connect(args.endpoint)
_socket.setsockopt(zmq.SUBSCRIBE, "")
while(True):
msg = _socket.recv_multipart()
logger.info(msg)
if __name__ == "__main__":
main()
|
the-stack_106_26606 | #
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
from datetime import datetime, timedelta
import hashlib
import os
import random
import sys
import tempfile
import time
from glob import glob
from py4j.protocol import Py4JJavaError
from pyspark import shuffle, RDD
from pyspark.resource import ExecutorResourceRequests, ResourceProfile, ResourceProfileBuilder,\
TaskResourceRequests
from pyspark.serializers import CloudPickleSerializer, BatchedSerializer, PickleSerializer,\
MarshalSerializer, UTF8Deserializer, NoOpSerializer
from pyspark.testing.utils import ReusedPySparkTestCase, SPARK_HOME, QuietTest
if sys.version_info[0] >= 3:
xrange = range
global_func = lambda: "Hi"
class RDDTests(ReusedPySparkTestCase):
def test_range(self):
self.assertEqual(self.sc.range(1, 1).count(), 0)
self.assertEqual(self.sc.range(1, 0, -1).count(), 1)
self.assertEqual(self.sc.range(0, 1 << 40, 1 << 39).count(), 2)
def test_id(self):
rdd = self.sc.parallelize(range(10))
id = rdd.id()
self.assertEqual(id, rdd.id())
rdd2 = rdd.map(str).filter(bool)
id2 = rdd2.id()
self.assertEqual(id + 1, id2)
self.assertEqual(id2, rdd2.id())
def test_empty_rdd(self):
rdd = self.sc.emptyRDD()
self.assertTrue(rdd.isEmpty())
def test_sum(self):
self.assertEqual(0, self.sc.emptyRDD().sum())
self.assertEqual(6, self.sc.parallelize([1, 2, 3]).sum())
def test_to_localiterator(self):
rdd = self.sc.parallelize([1, 2, 3])
it = rdd.toLocalIterator()
self.assertEqual([1, 2, 3], sorted(it))
rdd2 = rdd.repartition(1000)
it2 = rdd2.toLocalIterator()
self.assertEqual([1, 2, 3], sorted(it2))
def test_to_localiterator_prefetch(self):
# Test that we fetch the next partition in parallel
# We do this by returning the current time and:
# reading the first elem, waiting, and reading the second elem
# If not in parallel then these would be at different times
# But since they are being computed in parallel we see the time
# is "close enough" to the same.
rdd = self.sc.parallelize(range(2), 2)
times1 = rdd.map(lambda x: datetime.now())
times2 = rdd.map(lambda x: datetime.now())
times_iter_prefetch = times1.toLocalIterator(prefetchPartitions=True)
times_iter = times2.toLocalIterator(prefetchPartitions=False)
times_prefetch_head = next(times_iter_prefetch)
times_head = next(times_iter)
time.sleep(2)
times_next = next(times_iter)
times_prefetch_next = next(times_iter_prefetch)
self.assertTrue(times_next - times_head >= timedelta(seconds=2))
self.assertTrue(times_prefetch_next - times_prefetch_head < timedelta(seconds=1))
def test_save_as_textfile_with_unicode(self):
# Regression test for SPARK-970
x = u"\u00A1Hola, mundo!"
data = self.sc.parallelize([x])
tempFile = tempfile.NamedTemporaryFile(delete=True)
tempFile.close()
data.saveAsTextFile(tempFile.name)
raw_contents = b''.join(open(p, 'rb').read()
for p in glob(tempFile.name + "/part-0000*"))
self.assertEqual(x, raw_contents.strip().decode("utf-8"))
def test_save_as_textfile_with_utf8(self):
x = u"\u00A1Hola, mundo!"
data = self.sc.parallelize([x.encode("utf-8")])
tempFile = tempfile.NamedTemporaryFile(delete=True)
tempFile.close()
data.saveAsTextFile(tempFile.name)
raw_contents = b''.join(open(p, 'rb').read()
for p in glob(tempFile.name + "/part-0000*"))
self.assertEqual(x, raw_contents.strip().decode('utf8'))
def test_transforming_cartesian_result(self):
# Regression test for SPARK-1034
rdd1 = self.sc.parallelize([1, 2])
rdd2 = self.sc.parallelize([3, 4])
cart = rdd1.cartesian(rdd2)
result = cart.map(lambda x_y3: x_y3[0] + x_y3[1]).collect()
def test_transforming_pickle_file(self):
# Regression test for SPARK-2601
data = self.sc.parallelize([u"Hello", u"World!"])
tempFile = tempfile.NamedTemporaryFile(delete=True)
tempFile.close()
data.saveAsPickleFile(tempFile.name)
pickled_file = self.sc.pickleFile(tempFile.name)
pickled_file.map(lambda x: x).collect()
def test_cartesian_on_textfile(self):
# Regression test for
path = os.path.join(SPARK_HOME, "python/test_support/hello/hello.txt")
a = self.sc.textFile(path)
result = a.cartesian(a).collect()
(x, y) = result[0]
self.assertEqual(u"Hello World!", x.strip())
self.assertEqual(u"Hello World!", y.strip())
def test_cartesian_chaining(self):
# Tests for SPARK-16589
rdd = self.sc.parallelize(range(10), 2)
self.assertSetEqual(
set(rdd.cartesian(rdd).cartesian(rdd).collect()),
set([((x, y), z) for x in range(10) for y in range(10) for z in range(10)])
)
self.assertSetEqual(
set(rdd.cartesian(rdd.cartesian(rdd)).collect()),
set([(x, (y, z)) for x in range(10) for y in range(10) for z in range(10)])
)
self.assertSetEqual(
set(rdd.cartesian(rdd.zip(rdd)).collect()),
set([(x, (y, y)) for x in range(10) for y in range(10)])
)
def test_zip_chaining(self):
# Tests for SPARK-21985
rdd = self.sc.parallelize('abc', 2)
self.assertSetEqual(
set(rdd.zip(rdd).zip(rdd).collect()),
set([((x, x), x) for x in 'abc'])
)
self.assertSetEqual(
set(rdd.zip(rdd.zip(rdd)).collect()),
set([(x, (x, x)) for x in 'abc'])
)
def test_union_pair_rdd(self):
# Regression test for SPARK-31788
rdd = self.sc.parallelize([1, 2])
pair_rdd = rdd.zip(rdd)
self.assertEqual(
self.sc.union([pair_rdd, pair_rdd]).collect(),
[((1, 1), (2, 2)), ((1, 1), (2, 2))]
)
def test_deleting_input_files(self):
# Regression test for SPARK-1025
tempFile = tempfile.NamedTemporaryFile(delete=False)
tempFile.write(b"Hello World!")
tempFile.close()
data = self.sc.textFile(tempFile.name)
filtered_data = data.filter(lambda x: True)
self.assertEqual(1, filtered_data.count())
os.unlink(tempFile.name)
with QuietTest(self.sc):
self.assertRaises(Exception, lambda: filtered_data.count())
def test_sampling_default_seed(self):
# Test for SPARK-3995 (default seed setting)
data = self.sc.parallelize(xrange(1000), 1)
subset = data.takeSample(False, 10)
self.assertEqual(len(subset), 10)
def test_aggregate_mutable_zero_value(self):
# Test for SPARK-9021; uses aggregate and treeAggregate to build dict
# representing a counter of ints
# NOTE: dict is used instead of collections.Counter for Python 2.6
# compatibility
from collections import defaultdict
# Show that single or multiple partitions work
data1 = self.sc.range(10, numSlices=1)
data2 = self.sc.range(10, numSlices=2)
def seqOp(x, y):
x[y] += 1
return x
def comboOp(x, y):
for key, val in y.items():
x[key] += val
return x
counts1 = data1.aggregate(defaultdict(int), seqOp, comboOp)
counts2 = data2.aggregate(defaultdict(int), seqOp, comboOp)
counts3 = data1.treeAggregate(defaultdict(int), seqOp, comboOp, 2)
counts4 = data2.treeAggregate(defaultdict(int), seqOp, comboOp, 2)
ground_truth = defaultdict(int, dict((i, 1) for i in range(10)))
self.assertEqual(counts1, ground_truth)
self.assertEqual(counts2, ground_truth)
self.assertEqual(counts3, ground_truth)
self.assertEqual(counts4, ground_truth)
def test_aggregate_by_key_mutable_zero_value(self):
# Test for SPARK-9021; uses aggregateByKey to make a pair RDD that
# contains lists of all values for each key in the original RDD
# list(range(...)) for Python 3.x compatibility (can't use * operator
# on a range object)
# list(zip(...)) for Python 3.x compatibility (want to parallelize a
# collection, not a zip object)
tuples = list(zip(list(range(10))*2, [1]*20))
# Show that single or multiple partitions work
data1 = self.sc.parallelize(tuples, 1)
data2 = self.sc.parallelize(tuples, 2)
def seqOp(x, y):
x.append(y)
return x
def comboOp(x, y):
x.extend(y)
return x
values1 = data1.aggregateByKey([], seqOp, comboOp).collect()
values2 = data2.aggregateByKey([], seqOp, comboOp).collect()
# Sort lists to ensure clean comparison with ground_truth
values1.sort()
values2.sort()
ground_truth = [(i, [1]*2) for i in range(10)]
self.assertEqual(values1, ground_truth)
self.assertEqual(values2, ground_truth)
def test_fold_mutable_zero_value(self):
# Test for SPARK-9021; uses fold to merge an RDD of dict counters into
# a single dict
# NOTE: dict is used instead of collections.Counter for Python 2.6
# compatibility
from collections import defaultdict
counts1 = defaultdict(int, dict((i, 1) for i in range(10)))
counts2 = defaultdict(int, dict((i, 1) for i in range(3, 8)))
counts3 = defaultdict(int, dict((i, 1) for i in range(4, 7)))
counts4 = defaultdict(int, dict((i, 1) for i in range(5, 6)))
all_counts = [counts1, counts2, counts3, counts4]
# Show that single or multiple partitions work
data1 = self.sc.parallelize(all_counts, 1)
data2 = self.sc.parallelize(all_counts, 2)
def comboOp(x, y):
for key, val in y.items():
x[key] += val
return x
fold1 = data1.fold(defaultdict(int), comboOp)
fold2 = data2.fold(defaultdict(int), comboOp)
ground_truth = defaultdict(int)
for counts in all_counts:
for key, val in counts.items():
ground_truth[key] += val
self.assertEqual(fold1, ground_truth)
self.assertEqual(fold2, ground_truth)
def test_fold_by_key_mutable_zero_value(self):
# Test for SPARK-9021; uses foldByKey to make a pair RDD that contains
# lists of all values for each key in the original RDD
tuples = [(i, range(i)) for i in range(10)]*2
# Show that single or multiple partitions work
data1 = self.sc.parallelize(tuples, 1)
data2 = self.sc.parallelize(tuples, 2)
def comboOp(x, y):
x.extend(y)
return x
values1 = data1.foldByKey([], comboOp).collect()
values2 = data2.foldByKey([], comboOp).collect()
# Sort lists to ensure clean comparison with ground_truth
values1.sort()
values2.sort()
# list(range(...)) for Python 3.x compatibility
ground_truth = [(i, list(range(i))*2) for i in range(10)]
self.assertEqual(values1, ground_truth)
self.assertEqual(values2, ground_truth)
def test_aggregate_by_key(self):
data = self.sc.parallelize([(1, 1), (1, 1), (3, 2), (5, 1), (5, 3)], 2)
def seqOp(x, y):
x.add(y)
return x
def combOp(x, y):
x |= y
return x
sets = dict(data.aggregateByKey(set(), seqOp, combOp).collect())
self.assertEqual(3, len(sets))
self.assertEqual(set([1]), sets[1])
self.assertEqual(set([2]), sets[3])
self.assertEqual(set([1, 3]), sets[5])
def test_itemgetter(self):
rdd = self.sc.parallelize([range(10)])
from operator import itemgetter
self.assertEqual([1], rdd.map(itemgetter(1)).collect())
self.assertEqual([(2, 3)], rdd.map(itemgetter(2, 3)).collect())
def test_namedtuple_in_rdd(self):
from collections import namedtuple
Person = namedtuple("Person", "id firstName lastName")
jon = Person(1, "Jon", "Doe")
jane = Person(2, "Jane", "Doe")
theDoes = self.sc.parallelize([jon, jane])
self.assertEqual([jon, jane], theDoes.collect())
def test_large_broadcast(self):
N = 10000
data = [[float(i) for i in range(300)] for i in range(N)]
bdata = self.sc.broadcast(data) # 27MB
m = self.sc.parallelize(range(1), 1).map(lambda x: len(bdata.value)).sum()
self.assertEqual(N, m)
def test_unpersist(self):
N = 1000
data = [[float(i) for i in range(300)] for i in range(N)]
bdata = self.sc.broadcast(data) # 3MB
bdata.unpersist()
m = self.sc.parallelize(range(1), 1).map(lambda x: len(bdata.value)).sum()
self.assertEqual(N, m)
bdata.destroy(blocking=True)
try:
self.sc.parallelize(range(1), 1).map(lambda x: len(bdata.value)).sum()
except Exception as e:
pass
else:
raise Exception("job should fail after destroy the broadcast")
def test_multiple_broadcasts(self):
N = 1 << 21
b1 = self.sc.broadcast(set(range(N))) # multiple blocks in JVM
r = list(range(1 << 15))
random.shuffle(r)
s = str(r).encode()
checksum = hashlib.md5(s).hexdigest()
b2 = self.sc.broadcast(s)
r = list(set(self.sc.parallelize(range(10), 10).map(
lambda x: (len(b1.value), hashlib.md5(b2.value).hexdigest())).collect()))
self.assertEqual(1, len(r))
size, csum = r[0]
self.assertEqual(N, size)
self.assertEqual(checksum, csum)
random.shuffle(r)
s = str(r).encode()
checksum = hashlib.md5(s).hexdigest()
b2 = self.sc.broadcast(s)
r = list(set(self.sc.parallelize(range(10), 10).map(
lambda x: (len(b1.value), hashlib.md5(b2.value).hexdigest())).collect()))
self.assertEqual(1, len(r))
size, csum = r[0]
self.assertEqual(N, size)
self.assertEqual(checksum, csum)
def test_multithread_broadcast_pickle(self):
import threading
b1 = self.sc.broadcast(list(range(3)))
b2 = self.sc.broadcast(list(range(3)))
def f1():
return b1.value
def f2():
return b2.value
funcs_num_pickled = {f1: None, f2: None}
def do_pickle(f, sc):
command = (f, None, sc.serializer, sc.serializer)
ser = CloudPickleSerializer()
ser.dumps(command)
def process_vars(sc):
broadcast_vars = list(sc._pickled_broadcast_vars)
num_pickled = len(broadcast_vars)
sc._pickled_broadcast_vars.clear()
return num_pickled
def run(f, sc):
do_pickle(f, sc)
funcs_num_pickled[f] = process_vars(sc)
# pickle f1, adds b1 to sc._pickled_broadcast_vars in main thread local storage
do_pickle(f1, self.sc)
# run all for f2, should only add/count/clear b2 from worker thread local storage
t = threading.Thread(target=run, args=(f2, self.sc))
t.start()
t.join()
# count number of vars pickled in main thread, only b1 should be counted and cleared
funcs_num_pickled[f1] = process_vars(self.sc)
self.assertEqual(funcs_num_pickled[f1], 1)
self.assertEqual(funcs_num_pickled[f2], 1)
self.assertEqual(len(list(self.sc._pickled_broadcast_vars)), 0)
def test_large_closure(self):
N = 200000
data = [float(i) for i in xrange(N)]
rdd = self.sc.parallelize(range(1), 1).map(lambda x: len(data))
self.assertEqual(N, rdd.first())
# regression test for SPARK-6886
self.assertEqual(1, rdd.map(lambda x: (x, 1)).groupByKey().count())
def test_zip_with_different_serializers(self):
a = self.sc.parallelize(range(5))
b = self.sc.parallelize(range(100, 105))
self.assertEqual(a.zip(b).collect(), [(0, 100), (1, 101), (2, 102), (3, 103), (4, 104)])
a = a._reserialize(BatchedSerializer(PickleSerializer(), 2))
b = b._reserialize(MarshalSerializer())
self.assertEqual(a.zip(b).collect(), [(0, 100), (1, 101), (2, 102), (3, 103), (4, 104)])
# regression test for SPARK-4841
path = os.path.join(SPARK_HOME, "python/test_support/hello/hello.txt")
t = self.sc.textFile(path)
cnt = t.count()
self.assertEqual(cnt, t.zip(t).count())
rdd = t.map(str)
self.assertEqual(cnt, t.zip(rdd).count())
# regression test for bug in _reserializer()
self.assertEqual(cnt, t.zip(rdd).count())
def test_zip_with_different_object_sizes(self):
# regress test for SPARK-5973
a = self.sc.parallelize(xrange(10000)).map(lambda i: '*' * i)
b = self.sc.parallelize(xrange(10000, 20000)).map(lambda i: '*' * i)
self.assertEqual(10000, a.zip(b).count())
def test_zip_with_different_number_of_items(self):
a = self.sc.parallelize(range(5), 2)
# different number of partitions
b = self.sc.parallelize(range(100, 106), 3)
self.assertRaises(ValueError, lambda: a.zip(b))
with QuietTest(self.sc):
# different number of batched items in JVM
b = self.sc.parallelize(range(100, 104), 2)
self.assertRaises(Exception, lambda: a.zip(b).count())
# different number of items in one pair
b = self.sc.parallelize(range(100, 106), 2)
self.assertRaises(Exception, lambda: a.zip(b).count())
# same total number of items, but different distributions
a = self.sc.parallelize([2, 3], 2).flatMap(range)
b = self.sc.parallelize([3, 2], 2).flatMap(range)
self.assertEqual(a.count(), b.count())
self.assertRaises(Exception, lambda: a.zip(b).count())
def test_count_approx_distinct(self):
rdd = self.sc.parallelize(xrange(1000))
self.assertTrue(950 < rdd.countApproxDistinct(0.03) < 1050)
self.assertTrue(950 < rdd.map(float).countApproxDistinct(0.03) < 1050)
self.assertTrue(950 < rdd.map(str).countApproxDistinct(0.03) < 1050)
self.assertTrue(950 < rdd.map(lambda x: (x, -x)).countApproxDistinct(0.03) < 1050)
rdd = self.sc.parallelize([i % 20 for i in range(1000)], 7)
self.assertTrue(18 < rdd.countApproxDistinct() < 22)
self.assertTrue(18 < rdd.map(float).countApproxDistinct() < 22)
self.assertTrue(18 < rdd.map(str).countApproxDistinct() < 22)
self.assertTrue(18 < rdd.map(lambda x: (x, -x)).countApproxDistinct() < 22)
self.assertRaises(ValueError, lambda: rdd.countApproxDistinct(0.00000001))
def test_histogram(self):
# empty
rdd = self.sc.parallelize([])
self.assertEqual([0], rdd.histogram([0, 10])[1])
self.assertEqual([0, 0], rdd.histogram([0, 4, 10])[1])
self.assertRaises(ValueError, lambda: rdd.histogram(1))
# out of range
rdd = self.sc.parallelize([10.01, -0.01])
self.assertEqual([0], rdd.histogram([0, 10])[1])
self.assertEqual([0, 0], rdd.histogram((0, 4, 10))[1])
# in range with one bucket
rdd = self.sc.parallelize(range(1, 5))
self.assertEqual([4], rdd.histogram([0, 10])[1])
self.assertEqual([3, 1], rdd.histogram([0, 4, 10])[1])
# in range with one bucket exact match
self.assertEqual([4], rdd.histogram([1, 4])[1])
# out of range with two buckets
rdd = self.sc.parallelize([10.01, -0.01])
self.assertEqual([0, 0], rdd.histogram([0, 5, 10])[1])
# out of range with two uneven buckets
rdd = self.sc.parallelize([10.01, -0.01])
self.assertEqual([0, 0], rdd.histogram([0, 4, 10])[1])
# in range with two buckets
rdd = self.sc.parallelize([1, 2, 3, 5, 6])
self.assertEqual([3, 2], rdd.histogram([0, 5, 10])[1])
# in range with two bucket and None
rdd = self.sc.parallelize([1, 2, 3, 5, 6, None, float('nan')])
self.assertEqual([3, 2], rdd.histogram([0, 5, 10])[1])
# in range with two uneven buckets
rdd = self.sc.parallelize([1, 2, 3, 5, 6])
self.assertEqual([3, 2], rdd.histogram([0, 5, 11])[1])
# mixed range with two uneven buckets
rdd = self.sc.parallelize([-0.01, 0.0, 1, 2, 3, 5, 6, 11.0, 11.01])
self.assertEqual([4, 3], rdd.histogram([0, 5, 11])[1])
# mixed range with four uneven buckets
rdd = self.sc.parallelize([-0.01, 0.0, 1, 2, 3, 5, 6, 11.01, 12.0, 199.0, 200.0, 200.1])
self.assertEqual([4, 2, 1, 3], rdd.histogram([0.0, 5.0, 11.0, 12.0, 200.0])[1])
# mixed range with uneven buckets and NaN
rdd = self.sc.parallelize([-0.01, 0.0, 1, 2, 3, 5, 6, 11.01, 12.0,
199.0, 200.0, 200.1, None, float('nan')])
self.assertEqual([4, 2, 1, 3], rdd.histogram([0.0, 5.0, 11.0, 12.0, 200.0])[1])
# out of range with infinite buckets
rdd = self.sc.parallelize([10.01, -0.01, float('nan'), float("inf")])
self.assertEqual([1, 2], rdd.histogram([float('-inf'), 0, float('inf')])[1])
# invalid buckets
self.assertRaises(ValueError, lambda: rdd.histogram([]))
self.assertRaises(ValueError, lambda: rdd.histogram([1]))
self.assertRaises(ValueError, lambda: rdd.histogram(0))
self.assertRaises(TypeError, lambda: rdd.histogram({}))
# without buckets
rdd = self.sc.parallelize(range(1, 5))
self.assertEqual(([1, 4], [4]), rdd.histogram(1))
# without buckets single element
rdd = self.sc.parallelize([1])
self.assertEqual(([1, 1], [1]), rdd.histogram(1))
# without bucket no range
rdd = self.sc.parallelize([1] * 4)
self.assertEqual(([1, 1], [4]), rdd.histogram(1))
# without buckets basic two
rdd = self.sc.parallelize(range(1, 5))
self.assertEqual(([1, 2.5, 4], [2, 2]), rdd.histogram(2))
# without buckets with more requested than elements
rdd = self.sc.parallelize([1, 2])
buckets = [1 + 0.2 * i for i in range(6)]
hist = [1, 0, 0, 0, 1]
self.assertEqual((buckets, hist), rdd.histogram(5))
# invalid RDDs
rdd = self.sc.parallelize([1, float('inf')])
self.assertRaises(ValueError, lambda: rdd.histogram(2))
rdd = self.sc.parallelize([float('nan')])
self.assertRaises(ValueError, lambda: rdd.histogram(2))
# string
rdd = self.sc.parallelize(["ab", "ac", "b", "bd", "ef"], 2)
self.assertEqual([2, 2], rdd.histogram(["a", "b", "c"])[1])
self.assertEqual((["ab", "ef"], [5]), rdd.histogram(1))
self.assertRaises(TypeError, lambda: rdd.histogram(2))
def test_repartitionAndSortWithinPartitions_asc(self):
rdd = self.sc.parallelize([(0, 5), (3, 8), (2, 6), (0, 8), (3, 8), (1, 3)], 2)
repartitioned = rdd.repartitionAndSortWithinPartitions(2, lambda key: key % 2, True)
partitions = repartitioned.glom().collect()
self.assertEqual(partitions[0], [(0, 5), (0, 8), (2, 6)])
self.assertEqual(partitions[1], [(1, 3), (3, 8), (3, 8)])
def test_repartitionAndSortWithinPartitions_desc(self):
rdd = self.sc.parallelize([(0, 5), (3, 8), (2, 6), (0, 8), (3, 8), (1, 3)], 2)
repartitioned = rdd.repartitionAndSortWithinPartitions(2, lambda key: key % 2, False)
partitions = repartitioned.glom().collect()
self.assertEqual(partitions[0], [(2, 6), (0, 5), (0, 8)])
self.assertEqual(partitions[1], [(3, 8), (3, 8), (1, 3)])
def test_repartition_no_skewed(self):
num_partitions = 20
a = self.sc.parallelize(range(int(1000)), 2)
l = a.repartition(num_partitions).glom().map(len).collect()
zeros = len([x for x in l if x == 0])
self.assertTrue(zeros == 0)
l = a.coalesce(num_partitions, True).glom().map(len).collect()
zeros = len([x for x in l if x == 0])
self.assertTrue(zeros == 0)
def test_repartition_on_textfile(self):
path = os.path.join(SPARK_HOME, "python/test_support/hello/hello.txt")
rdd = self.sc.textFile(path)
result = rdd.repartition(1).collect()
self.assertEqual(u"Hello World!", result[0])
def test_distinct(self):
rdd = self.sc.parallelize((1, 2, 3)*10, 10)
self.assertEqual(rdd.getNumPartitions(), 10)
self.assertEqual(rdd.distinct().count(), 3)
result = rdd.distinct(5)
self.assertEqual(result.getNumPartitions(), 5)
self.assertEqual(result.count(), 3)
def test_external_group_by_key(self):
self.sc._conf.set("spark.python.worker.memory", "1m")
N = 2000001
kv = self.sc.parallelize(xrange(N)).map(lambda x: (x % 3, x))
gkv = kv.groupByKey().cache()
self.assertEqual(3, gkv.count())
filtered = gkv.filter(lambda kv: kv[0] == 1)
self.assertEqual(1, filtered.count())
self.assertEqual([(1, N // 3)], filtered.mapValues(len).collect())
self.assertEqual([(N // 3, N // 3)],
filtered.values().map(lambda x: (len(x), len(list(x)))).collect())
result = filtered.collect()[0][1]
self.assertEqual(N // 3, len(result))
self.assertTrue(isinstance(result.data, shuffle.ExternalListOfList))
def test_sort_on_empty_rdd(self):
self.assertEqual([], self.sc.parallelize(zip([], [])).sortByKey().collect())
def test_sample(self):
rdd = self.sc.parallelize(range(0, 100), 4)
wo = rdd.sample(False, 0.1, 2).collect()
wo_dup = rdd.sample(False, 0.1, 2).collect()
self.assertSetEqual(set(wo), set(wo_dup))
wr = rdd.sample(True, 0.2, 5).collect()
wr_dup = rdd.sample(True, 0.2, 5).collect()
self.assertSetEqual(set(wr), set(wr_dup))
wo_s10 = rdd.sample(False, 0.3, 10).collect()
wo_s20 = rdd.sample(False, 0.3, 20).collect()
self.assertNotEqual(set(wo_s10), set(wo_s20))
wr_s11 = rdd.sample(True, 0.4, 11).collect()
wr_s21 = rdd.sample(True, 0.4, 21).collect()
self.assertNotEqual(set(wr_s11), set(wr_s21))
def test_null_in_rdd(self):
jrdd = self.sc._jvm.PythonUtils.generateRDDWithNull(self.sc._jsc)
rdd = RDD(jrdd, self.sc, UTF8Deserializer())
self.assertEqual([u"a", None, u"b"], rdd.collect())
rdd = RDD(jrdd, self.sc, NoOpSerializer())
self.assertEqual([b"a", None, b"b"], rdd.collect())
def test_multiple_python_java_RDD_conversions(self):
# Regression test for SPARK-5361
data = [
(u'1', {u'director': u'David Lean'}),
(u'2', {u'director': u'Andrew Dominik'})
]
data_rdd = self.sc.parallelize(data)
data_java_rdd = data_rdd._to_java_object_rdd()
data_python_rdd = self.sc._jvm.SerDeUtil.javaToPython(data_java_rdd)
converted_rdd = RDD(data_python_rdd, self.sc)
self.assertEqual(2, converted_rdd.count())
# conversion between python and java RDD threw exceptions
data_java_rdd = converted_rdd._to_java_object_rdd()
data_python_rdd = self.sc._jvm.SerDeUtil.javaToPython(data_java_rdd)
converted_rdd = RDD(data_python_rdd, self.sc)
self.assertEqual(2, converted_rdd.count())
# Regression test for SPARK-6294
def test_take_on_jrdd(self):
rdd = self.sc.parallelize(xrange(1 << 20)).map(lambda x: str(x))
rdd._jrdd.first()
def test_sortByKey_uses_all_partitions_not_only_first_and_last(self):
# Regression test for SPARK-5969
seq = [(i * 59 % 101, i) for i in range(101)] # unsorted sequence
rdd = self.sc.parallelize(seq)
for ascending in [True, False]:
sort = rdd.sortByKey(ascending=ascending, numPartitions=5)
self.assertEqual(sort.collect(), sorted(seq, reverse=not ascending))
sizes = sort.glom().map(len).collect()
for size in sizes:
self.assertGreater(size, 0)
def test_pipe_functions(self):
data = ['1', '2', '3']
rdd = self.sc.parallelize(data)
with QuietTest(self.sc):
self.assertEqual([], rdd.pipe('java').collect())
self.assertRaises(Py4JJavaError, rdd.pipe('java', checkCode=True).collect)
result = rdd.pipe('cat').collect()
result.sort()
for x, y in zip(data, result):
self.assertEqual(x, y)
self.assertRaises(Py4JJavaError, rdd.pipe('grep 4', checkCode=True).collect)
self.assertEqual([], rdd.pipe('grep 4').collect())
def test_pipe_unicode(self):
# Regression test for SPARK-20947
data = [u'\u6d4b\u8bd5', '1']
rdd = self.sc.parallelize(data)
result = rdd.pipe('cat').collect()
self.assertEqual(data, result)
def test_stopiteration_in_user_code(self):
def stopit(*x):
raise StopIteration()
seq_rdd = self.sc.parallelize(range(10))
keyed_rdd = self.sc.parallelize((x % 2, x) for x in range(10))
msg = "Caught StopIteration thrown from user's code; failing the task"
self.assertRaisesRegexp(Py4JJavaError, msg, seq_rdd.map(stopit).collect)
self.assertRaisesRegexp(Py4JJavaError, msg, seq_rdd.filter(stopit).collect)
self.assertRaisesRegexp(Py4JJavaError, msg, seq_rdd.foreach, stopit)
self.assertRaisesRegexp(Py4JJavaError, msg, seq_rdd.reduce, stopit)
self.assertRaisesRegexp(Py4JJavaError, msg, seq_rdd.fold, 0, stopit)
self.assertRaisesRegexp(Py4JJavaError, msg, seq_rdd.foreach, stopit)
self.assertRaisesRegexp(Py4JJavaError, msg,
seq_rdd.cartesian(seq_rdd).flatMap(stopit).collect)
# these methods call the user function both in the driver and in the executor
# the exception raised is different according to where the StopIteration happens
# RuntimeError is raised if in the driver
# Py4JJavaError is raised if in the executor (wraps the RuntimeError raised in the worker)
self.assertRaisesRegexp((Py4JJavaError, RuntimeError), msg,
keyed_rdd.reduceByKeyLocally, stopit)
self.assertRaisesRegexp((Py4JJavaError, RuntimeError), msg,
seq_rdd.aggregate, 0, stopit, lambda *x: 1)
self.assertRaisesRegexp((Py4JJavaError, RuntimeError), msg,
seq_rdd.aggregate, 0, lambda *x: 1, stopit)
def test_overwritten_global_func(self):
# Regression test for SPARK-27000
global global_func
self.assertEqual(self.sc.parallelize([1]).map(lambda _: global_func()).first(), "Hi")
global_func = lambda: "Yeah"
self.assertEqual(self.sc.parallelize([1]).map(lambda _: global_func()).first(), "Yeah")
def test_to_local_iterator_failure(self):
# SPARK-27548 toLocalIterator task failure not propagated to Python driver
def fail(_):
raise RuntimeError("local iterator error")
rdd = self.sc.range(10).map(fail)
with self.assertRaisesRegexp(Exception, "local iterator error"):
for _ in rdd.toLocalIterator():
pass
def test_to_local_iterator_collects_single_partition(self):
# Test that partitions are not computed until requested by iteration
def fail_last(x):
if x == 9:
raise RuntimeError("This should not be hit")
return x
rdd = self.sc.range(12, numSlices=4).map(fail_last)
it = rdd.toLocalIterator()
# Only consume first 4 elements from partitions 1 and 2, this should not collect the last
# partition which would trigger the error
for i in range(4):
self.assertEqual(i, next(it))
def test_resourceprofile(self):
rp_builder = ResourceProfileBuilder()
ereqs = ExecutorResourceRequests().cores(2).memory("6g").memoryOverhead("1g")
ereqs.pysparkMemory("2g").resource("gpu", 2, "testGpus", "nvidia.com")
treqs = TaskResourceRequests().cpus(2).resource("gpu", 2)
def assert_request_contents(exec_reqs, task_reqs):
self.assertEqual(len(exec_reqs), 5)
self.assertEqual(exec_reqs["cores"].amount, 2)
self.assertEqual(exec_reqs["memory"].amount, 6144)
self.assertEqual(exec_reqs["memoryOverhead"].amount, 1024)
self.assertEqual(exec_reqs["pyspark.memory"].amount, 2048)
self.assertEqual(exec_reqs["gpu"].amount, 2)
self.assertEqual(exec_reqs["gpu"].discoveryScript, "testGpus")
self.assertEqual(exec_reqs["gpu"].resourceName, "gpu")
self.assertEqual(exec_reqs["gpu"].vendor, "nvidia.com")
self.assertEqual(len(task_reqs), 2)
self.assertEqual(task_reqs["cpus"].amount, 2.0)
self.assertEqual(task_reqs["gpu"].amount, 2.0)
assert_request_contents(ereqs.requests, treqs.requests)
rp = rp_builder.require(ereqs).require(treqs).build
assert_request_contents(rp.executorResources, rp.taskResources)
rdd = self.sc.parallelize(range(10)).withResources(rp)
return_rp = rdd.getResourceProfile()
assert_request_contents(return_rp.executorResources, return_rp.taskResources)
rddWithoutRp = self.sc.parallelize(range(10))
self.assertEqual(rddWithoutRp.getResourceProfile(), None)
def test_multiple_group_jobs(self):
import threading
group_a = "job_ids_to_cancel"
group_b = "job_ids_to_run"
threads = []
thread_ids = range(4)
thread_ids_to_cancel = [i for i in thread_ids if i % 2 == 0]
thread_ids_to_run = [i for i in thread_ids if i % 2 != 0]
# A list which records whether job is cancelled.
# The index of the array is the thread index which job run in.
is_job_cancelled = [False for _ in thread_ids]
def run_job(job_group, index):
"""
Executes a job with the group ``job_group``. Each job waits for 3 seconds
and then exits.
"""
try:
self.sc.parallelize([15]).map(lambda x: time.sleep(x)) \
.collectWithJobGroup(job_group, "test rdd collect with setting job group")
is_job_cancelled[index] = False
except Exception:
# Assume that exception means job cancellation.
is_job_cancelled[index] = True
# Test if job succeeded when not cancelled.
run_job(group_a, 0)
self.assertFalse(is_job_cancelled[0])
# Run jobs
for i in thread_ids_to_cancel:
t = threading.Thread(target=run_job, args=(group_a, i))
t.start()
threads.append(t)
for i in thread_ids_to_run:
t = threading.Thread(target=run_job, args=(group_b, i))
t.start()
threads.append(t)
# Wait to make sure all jobs are executed.
time.sleep(3)
# And then, cancel one job group.
self.sc.cancelJobGroup(group_a)
# Wait until all threads launching jobs are finished.
for t in threads:
t.join()
for i in thread_ids_to_cancel:
self.assertTrue(
is_job_cancelled[i],
"Thread {i}: Job in group A was not cancelled.".format(i=i))
for i in thread_ids_to_run:
self.assertFalse(
is_job_cancelled[i],
"Thread {i}: Job in group B did not succeeded.".format(i=i))
if __name__ == "__main__":
import unittest
from pyspark.tests.test_rdd import *
try:
import xmlrunner
testRunner = xmlrunner.XMLTestRunner(output='target/test-reports', verbosity=2)
except ImportError:
testRunner = None
unittest.main(testRunner=testRunner, verbosity=2)
|
the-stack_106_26608 | import json
import logging
from django.contrib.auth.models import ContentType, Permission
from django.contrib.contenttypes.models import ContentType
from django.http import (
HttpResponse,
HttpResponseBadRequest,
HttpResponseServerError,
HttpResponseNotFound,
)
from django.views.decorators.csrf import csrf_exempt
from integrations.metagov.models import MetagovProcess, MetagovPlatformAction, MetagovUser
from policyengine.models import Community, CommunityPlatform, CommunityRole
from integrations.slack.models import SlackCommunity
logger = logging.getLogger(__name__)
# INTERNAL ENDPOINT, no auth
@csrf_exempt
def internal_receive_outcome(request, id):
if request.method != "POST" or not request.body:
return HttpResponseBadRequest()
try:
body = json.loads(request.body)
except ValueError:
return HttpResponseBadRequest("unable to decode body")
logger.info(f"Received external process outcome: {body}")
# Special case for Slack voting mechanism
if body["name"] == "slack.emoji-vote":
community = SlackCommunity.objects.get(community__metagov_slug=body["community"])
community.handle_metagov_process(body)
return HttpResponse()
try:
process = MetagovProcess.objects.get(pk=id)
except MetagovProcess.DoesNotExist:
return HttpResponseNotFound()
process.json_data = json.dumps(body)
process.save()
return HttpResponse()
# INTERNAL ENDPOINT, no auth
@csrf_exempt
def internal_receive_action(request):
"""
Receive event from Metagov
"""
if request.method != "POST" or not request.body:
return HttpResponseBadRequest()
try:
body = json.loads(request.body)
except ValueError:
return HttpResponseBadRequest("unable to decode body")
logger.info(f"Received metagov action: {body}")
metagov_community_slug = body.get("community")
try:
community = Community.objects.get(metagov_slug=metagov_community_slug)
except Community.DoesNotExist:
logger.error(f"Received event for community {metagov_community_slug} which doesn't exist in PolicyKit")
return HttpResponseBadRequest("Community does not exist")
# Special cases for receiving events from "governable platforms" that have fully featured integrations
if body.get("source") == "slack":
# Route Slack event to the correct SlackCommunity handler
slack_community = SlackCommunity.objects.filter(community=community).first()
if slack_community is None:
return HttpResponseBadRequest(f"no slack community exists for {metagov_community_slug}")
slack_community.handle_metagov_event(body)
return HttpResponse()
# For all other sources, create generic MetagovPlatformActions.
platform_community = CommunityPlatform.objects.filter(community=community).first()
if platform_community is None:
logger.error(f"No platforms exist for community '{community}'")
return HttpResponse()
# Get or create a MetagovUser that's tied to the PlatformCommunity, and give them permission to propose MetagovPlatformActions
# Hack so MetagovUser username doesn't clash with usernames from other communities (django User requires unique username).
# TODO(#299): make the CommunityUser model unique on community+username, not just username.
initiator = body["initiator"]
prefixed_username = f"{initiator['provider']}.{initiator['user_id']}"
metagov_user, _ = MetagovUser.objects.get_or_create(
username=prefixed_username, provider=initiator["provider"], community=platform_community
)
# Give this user permission to propose any MetagovPlatformAction
user_group, usergroup_created = CommunityRole.objects.get_or_create(
role_name="Base User", name=f"Metagov: {metagov_community_slug}: Base User"
)
if usergroup_created:
user_group.community = platform_community
content_type = ContentType.objects.get_for_model(MetagovPlatformAction)
permission, _ = Permission.objects.get_or_create(
codename="add_metagovaction",
name="Can add metagov action",
content_type=content_type,
)
user_group.permissions.add(permission)
user_group.save()
user_group.user_set.add(metagov_user)
# Create MetagovPlatformAction
new_api_action = MetagovPlatformAction()
new_api_action.community = platform_community
new_api_action.initiator = metagov_user
new_api_action.event_type = f"{body['source']}.{body['event_type']}"
new_api_action.json_data = json.dumps(body["data"])
# Save to create Proposal and trigger policy evaluations
new_api_action.save()
if not new_api_action.pk:
return HttpResponseServerError()
logger.info(f"Created new MetagovPlatformAction with pk {new_api_action.pk}")
return HttpResponse()
|
the-stack_106_26612 | #
# Jasy - Web Tooling Framework
# Copyright 2010-2012 Zynga Inc.
# Copyright 2013-2014 Sebastian Werner
#
import jasy.core.Console as Console
import jasy.item.Abstract as AbstractItem
class ResolverError(Exception):
"""Error which is throws when resolving items could be be finished because of items which could not be found or are
of an unexpected type."""
pass
class Resolver():
"""
Resolves dependencies between items.
This class is not type depended e.g. is used for both scripts and styles.
"""
def __init__(self, profile):
# Keep profile reference
self.profile = profile
# Keep permutation reference
self.permutation = profile.getCurrentPermutation()
# Collecting all available items
self.items = {}
# Required classes by the user
self.__required = []
# Hard excluded classes (used for filtering previously included classes etc.)
self.__excluded = []
# Included classes after dependency calculation
self.__included = []
def add(self, nameOrItem, prepend=False):
"""Adds an item by its name or via the item instance."""
if isinstance(nameOrItem, str):
if not nameOrItem in self.items:
raise ResolverError("Unknown item: %s" % nameOrItem)
# Replace variable with item instance
nameOrItem = self.items[nameOrItem]
elif not isinstance(nameOrItem, AbstractItem.AbstractItem):
raise ResolverError("Invalid item: %s" % nameOrItem)
if prepend:
self.__required.insert(0, nameOrItem)
else:
self.__required.append(nameOrItem)
# Invalidate included list
self.__included = None
return self
def remove(self, nameOrItem):
"""Removes an item via its name or via the item instance."""
for item in self.__required:
if item is nameOrItem or item.getId() == nameOrItem:
self.__required.remove(item)
if self.__included:
self.__included = []
return True
return False
def exclude(self, items):
"""
Excludes the given items (just a hard-exclude which is
applied after calculating the current dependencies)
"""
self.__excluded.extend(items)
# Invalidate included list
self.__included = None
return self
def getRequired(self):
""" Returns the user added classes - the so-called required classes. """
return self.__required
def getIncluded(self):
"""Returns a final set of classes after resolving dependencies."""
if self.__included:
return self.__included
collection = set()
for item in self.__required:
self.__resolveDependencies(item, collection)
# Filter excluded classes
for item in self.__excluded:
if item in collection:
collection.remove(item)
self.__included = collection
return self.__included
def __resolveDependencies(self, item, collection):
"""Internal resolver engine which works recursively through all dependencies."""
collection.add(item)
dependencies = self.getItemDependencies(item)
for depObj in dependencies:
if depObj not in collection:
self.__resolveDependencies(depObj, collection)
|
the-stack_106_26619 | import sqlalchemy as sa
from sqlalchemy import event
from sqlalchemy import exc
from sqlalchemy import func
from sqlalchemy import Integer
from sqlalchemy import MetaData
from sqlalchemy import select
from sqlalchemy import String
from sqlalchemy import testing
from sqlalchemy.ext.declarative import comparable_using
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import AttributeExtension
from sqlalchemy.orm import attributes
from sqlalchemy.orm import collections
from sqlalchemy.orm import column_property
from sqlalchemy.orm import comparable_property
from sqlalchemy.orm import composite
from sqlalchemy.orm import configure_mappers
from sqlalchemy.orm import create_session
from sqlalchemy.orm import defer
from sqlalchemy.orm import deferred
from sqlalchemy.orm import EXT_CONTINUE
from sqlalchemy.orm import identity
from sqlalchemy.orm import instrumentation
from sqlalchemy.orm import joinedload
from sqlalchemy.orm import joinedload_all
from sqlalchemy.orm import mapper
from sqlalchemy.orm import MapperExtension
from sqlalchemy.orm import PropComparator
from sqlalchemy.orm import relationship
from sqlalchemy.orm import Session
from sqlalchemy.orm import SessionExtension
from sqlalchemy.orm import sessionmaker
from sqlalchemy.orm import synonym
from sqlalchemy.orm import undefer
from sqlalchemy.orm.collections import collection
from sqlalchemy.testing import assert_raises
from sqlalchemy.testing import assert_raises_message
from sqlalchemy.testing import assertions
from sqlalchemy.testing import AssertsCompiledSQL
from sqlalchemy.testing import engines
from sqlalchemy.testing import eq_
from sqlalchemy.testing import fixtures
from sqlalchemy.testing import is_
from sqlalchemy.testing.schema import Column
from sqlalchemy.testing.schema import Table
from sqlalchemy.testing.util import gc_collect
from sqlalchemy.util.compat import pypy
from . import _fixtures
from .test_options import PathTest as OptionsPathTest
from .test_transaction import _LocalFixture
class DeprecationWarningsTest(fixtures.DeclarativeMappedTest):
run_setup_classes = "each"
run_setup_mappers = "each"
run_define_tables = "each"
run_create_tables = None
def test_attribute_extension(self):
class SomeExtension(AttributeExtension):
def append(self, obj, value, initiator):
pass
def remove(self, obj, value, initiator):
pass
def set(self, obj, value, oldvalue, initiator):
pass
with assertions.expect_deprecated(
".*The column_property.extension parameter will be removed in a "
"future release."
):
class Foo(self.DeclarativeBasic):
__tablename__ = "foo"
id = Column(Integer, primary_key=True)
foo = column_property(
Column("q", Integer), extension=SomeExtension()
)
with assertions.expect_deprecated(
"AttributeExtension.append is deprecated. The "
"AttributeExtension class will be removed in a future release.",
"AttributeExtension.remove is deprecated. The "
"AttributeExtension class will be removed in a future release.",
"AttributeExtension.set is deprecated. The "
"AttributeExtension class will be removed in a future release.",
):
configure_mappers()
def test_attribute_extension_parameter(self):
class SomeExtension(AttributeExtension):
def append(self, obj, value, initiator):
pass
with assertions.expect_deprecated(
".*The relationship.extension parameter will be removed in a "
"future release."
):
relationship("Bar", extension=SomeExtension)
with assertions.expect_deprecated(
".*The column_property.extension parameter will be removed in a "
"future release."
):
column_property(Column("q", Integer), extension=SomeExtension)
with assertions.expect_deprecated(
".*The composite.extension parameter will be removed in a "
"future release."
):
composite("foo", extension=SomeExtension)
def test_session_extension(self):
class SomeExtension(SessionExtension):
def after_commit(self, session):
pass
def after_rollback(self, session):
pass
def before_flush(self, session, flush_context, instances):
pass
with assertions.expect_deprecated(
".*The Session.extension parameter will be removed",
"SessionExtension.after_commit is deprecated. "
"The SessionExtension class",
"SessionExtension.before_flush is deprecated. "
"The SessionExtension class",
"SessionExtension.after_rollback is deprecated. "
"The SessionExtension class",
):
Session(extension=SomeExtension())
def test_mapper_extension(self):
class SomeExtension(MapperExtension):
def init_instance(
self, mapper, class_, oldinit, instance, args, kwargs
):
pass
def init_failed(
self, mapper, class_, oldinit, instance, args, kwargs
):
pass
with assertions.expect_deprecated(
"MapperExtension.init_instance is deprecated. "
"The MapperExtension class",
"MapperExtension.init_failed is deprecated. "
"The MapperExtension class",
".*The mapper.extension parameter will be removed",
):
class Foo(self.DeclarativeBasic):
__tablename__ = "foo"
id = Column(Integer, primary_key=True)
__mapper_args__ = {"extension": SomeExtension()}
def test_session_weak_identity_map(self):
with testing.expect_deprecated(
".*Session.weak_identity_map parameter as well as the"
):
s = Session(weak_identity_map=True)
is_(s._identity_cls, identity.WeakInstanceDict)
with assertions.expect_deprecated(
"The Session.weak_identity_map parameter as well as"
):
s = Session(weak_identity_map=False)
is_(s._identity_cls, identity.StrongInstanceDict)
s = Session()
is_(s._identity_cls, identity.WeakInstanceDict)
def test_session_prune(self):
s = Session()
with assertions.expect_deprecated(
r"The Session.prune\(\) method is deprecated along with "
"Session.weak_identity_map"
):
s.prune()
def test_session_enable_transaction_accounting(self):
with assertions.expect_deprecated(
"the Session._enable_transaction_accounting parameter is "
"deprecated"
):
s = Session(_enable_transaction_accounting=False)
def test_session_is_modified(self):
class Foo(self.DeclarativeBasic):
__tablename__ = "foo"
id = Column(Integer, primary_key=True)
f1 = Foo()
s = Session()
with assertions.expect_deprecated(
"The Session.is_modified.passive flag is deprecated"
):
# this flag was for a long time documented as requiring
# that it be set to True, so we've changed the default here
# so that the warning emits
s.is_modified(f1, passive=True)
class DeprecatedAccountingFlagsTest(_LocalFixture):
def test_rollback_no_accounting(self):
User, users = self.classes.User, self.tables.users
with testing.expect_deprecated(
"The Session._enable_transaction_accounting parameter"
):
sess = sessionmaker(_enable_transaction_accounting=False)()
u1 = User(name="ed")
sess.add(u1)
sess.commit()
u1.name = "edwardo"
sess.rollback()
testing.db.execute(
users.update(users.c.name == "ed").values(name="edward")
)
assert u1.name == "edwardo"
sess.expire_all()
assert u1.name == "edward"
def test_commit_no_accounting(self):
User, users = self.classes.User, self.tables.users
with testing.expect_deprecated(
"The Session._enable_transaction_accounting parameter"
):
sess = sessionmaker(_enable_transaction_accounting=False)()
u1 = User(name="ed")
sess.add(u1)
sess.commit()
u1.name = "edwardo"
sess.rollback()
testing.db.execute(
users.update(users.c.name == "ed").values(name="edward")
)
assert u1.name == "edwardo"
sess.commit()
assert testing.db.execute(select([users.c.name])).fetchall() == [
("edwardo",)
]
assert u1.name == "edwardo"
sess.delete(u1)
sess.commit()
def test_preflush_no_accounting(self):
User, users = self.classes.User, self.tables.users
with testing.expect_deprecated(
"The Session._enable_transaction_accounting parameter"
):
sess = Session(
_enable_transaction_accounting=False,
autocommit=True,
autoflush=False,
)
u1 = User(name="ed")
sess.add(u1)
sess.flush()
sess.begin()
u1.name = "edwardo"
u2 = User(name="some other user")
sess.add(u2)
sess.rollback()
sess.begin()
assert testing.db.execute(select([users.c.name])).fetchall() == [
("ed",)
]
class TLTransactionTest(fixtures.MappedTest):
run_dispose_bind = "once"
__backend__ = True
@classmethod
def setup_bind(cls):
with testing.expect_deprecated(
".*'threadlocal' engine strategy is deprecated"
):
return engines.testing_engine(options=dict(strategy="threadlocal"))
@classmethod
def define_tables(cls, metadata):
Table(
"users",
metadata,
Column(
"id", Integer, primary_key=True, test_needs_autoincrement=True
),
Column("name", String(20)),
test_needs_acid=True,
)
@classmethod
def setup_classes(cls):
class User(cls.Basic):
pass
@classmethod
def setup_mappers(cls):
users, User = cls.tables.users, cls.classes.User
mapper(User, users)
@testing.exclude("mysql", "<", (5, 0, 3), "FIXME: unknown")
def test_session_nesting(self):
User = self.classes.User
sess = create_session(bind=self.bind)
self.bind.begin()
u = User(name="ed")
sess.add(u)
sess.flush()
self.bind.commit()
class DeprecatedSessionFeatureTest(_fixtures.FixtureTest):
run_inserts = None
def test_fast_discard_race(self):
# test issue #4068
users, User = self.tables.users, self.classes.User
mapper(User, users)
with testing.expect_deprecated(".*identity map are deprecated"):
sess = Session(weak_identity_map=False)
u1 = User(name="u1")
sess.add(u1)
sess.commit()
u1_state = u1._sa_instance_state
sess.identity_map._dict.pop(u1_state.key)
ref = u1_state.obj
u1_state.obj = lambda: None
u2 = sess.query(User).first()
u1_state._cleanup(ref)
u3 = sess.query(User).first()
is_(u2, u3)
u2_state = u2._sa_instance_state
assert sess.identity_map.contains_state(u2._sa_instance_state)
ref = u2_state.obj
u2_state.obj = lambda: None
u2_state._cleanup(ref)
assert not sess.identity_map.contains_state(u2._sa_instance_state)
def test_is_modified_passive_on(self):
User, Address = self.classes.User, self.classes.Address
users, addresses = self.tables.users, self.tables.addresses
mapper(User, users, properties={"addresses": relationship(Address)})
mapper(Address, addresses)
s = Session()
u = User(name="fred", addresses=[Address(email_address="foo")])
s.add(u)
s.commit()
u.id
def go():
assert not s.is_modified(u, passive=True)
with testing.expect_deprecated(
".*Session.is_modified.passive flag is deprecated "
):
self.assert_sql_count(testing.db, go, 0)
u.name = "newname"
def go():
assert s.is_modified(u, passive=True)
with testing.expect_deprecated(
".*Session.is_modified.passive flag is deprecated "
):
self.assert_sql_count(testing.db, go, 0)
class StrongIdentityMapTest(_fixtures.FixtureTest):
run_inserts = None
def _strong_ident_fixture(self):
with testing.expect_deprecated(
".*Session.weak_identity_map parameter as well as the"
):
sess = create_session(weak_identity_map=False)
def prune():
with testing.expect_deprecated(".*Session.prune"):
return sess.prune()
return sess, prune
def _event_fixture(self):
session = create_session()
@event.listens_for(session, "pending_to_persistent")
@event.listens_for(session, "deleted_to_persistent")
@event.listens_for(session, "detached_to_persistent")
@event.listens_for(session, "loaded_as_persistent")
def strong_ref_object(sess, instance):
if "refs" not in sess.info:
sess.info["refs"] = refs = set()
else:
refs = sess.info["refs"]
refs.add(instance)
@event.listens_for(session, "persistent_to_detached")
@event.listens_for(session, "persistent_to_deleted")
@event.listens_for(session, "persistent_to_transient")
def deref_object(sess, instance):
sess.info["refs"].discard(instance)
def prune():
if "refs" not in session.info:
return 0
sess_size = len(session.identity_map)
session.info["refs"].clear()
gc_collect()
session.info["refs"] = set(
s.obj() for s in session.identity_map.all_states()
)
return sess_size - len(session.identity_map)
return session, prune
def test_strong_ref_imap(self):
self._test_strong_ref(self._strong_ident_fixture)
def test_strong_ref_events(self):
self._test_strong_ref(self._event_fixture)
def _test_strong_ref(self, fixture):
s, prune = fixture()
users, User = self.tables.users, self.classes.User
mapper(User, users)
# save user
s.add(User(name="u1"))
s.flush()
user = s.query(User).one()
user = None
print(s.identity_map)
gc_collect()
assert len(s.identity_map) == 1
user = s.query(User).one()
assert not s.identity_map._modified
user.name = "u2"
assert s.identity_map._modified
s.flush()
eq_(users.select().execute().fetchall(), [(user.id, "u2")])
def test_prune_imap(self):
self._test_prune(self._strong_ident_fixture)
def test_prune_events(self):
self._test_prune(self._event_fixture)
@testing.fails_if(lambda: pypy, "pypy has a real GC")
@testing.fails_on("+zxjdbc", "http://www.sqlalchemy.org/trac/ticket/1473")
def _test_prune(self, fixture):
s, prune = fixture()
users, User = self.tables.users, self.classes.User
mapper(User, users)
for o in [User(name="u%s" % x) for x in range(10)]:
s.add(o)
# o is still live after this loop...
self.assert_(len(s.identity_map) == 0)
eq_(prune(), 0)
s.flush()
gc_collect()
eq_(prune(), 9)
# o is still in local scope here, so still present
self.assert_(len(s.identity_map) == 1)
id_ = o.id
del o
eq_(prune(), 1)
self.assert_(len(s.identity_map) == 0)
u = s.query(User).get(id_)
eq_(prune(), 0)
self.assert_(len(s.identity_map) == 1)
u.name = "squiznart"
del u
eq_(prune(), 0)
self.assert_(len(s.identity_map) == 1)
s.flush()
eq_(prune(), 1)
self.assert_(len(s.identity_map) == 0)
s.add(User(name="x"))
eq_(prune(), 0)
self.assert_(len(s.identity_map) == 0)
s.flush()
self.assert_(len(s.identity_map) == 1)
eq_(prune(), 1)
self.assert_(len(s.identity_map) == 0)
u = s.query(User).get(id_)
s.delete(u)
del u
eq_(prune(), 0)
self.assert_(len(s.identity_map) == 1)
s.flush()
eq_(prune(), 0)
self.assert_(len(s.identity_map) == 0)
class DeprecatedMapperTest(_fixtures.FixtureTest, AssertsCompiledSQL):
__dialect__ = "default"
def test_cancel_order_by(self):
users, User = self.tables.users, self.classes.User
with testing.expect_deprecated(
"The Mapper.order_by parameter is deprecated, and will be "
"removed in a future release."
):
mapper(User, users, order_by=users.c.name.desc())
assert (
"order by users.name desc"
in str(create_session().query(User).statement).lower()
)
assert (
"order by"
not in str(
create_session().query(User).order_by(None).statement
).lower()
)
assert (
"order by users.name asc"
in str(
create_session()
.query(User)
.order_by(User.name.asc())
.statement
).lower()
)
eq_(
create_session().query(User).all(),
[
User(id=7, name="jack"),
User(id=9, name="fred"),
User(id=8, name="ed"),
User(id=10, name="chuck"),
],
)
eq_(
create_session().query(User).order_by(User.name).all(),
[
User(id=10, name="chuck"),
User(id=8, name="ed"),
User(id=9, name="fred"),
User(id=7, name="jack"),
],
)
def test_comparable(self):
users = self.tables.users
class extendedproperty(property):
attribute = 123
def method1(self):
return "method1"
from sqlalchemy.orm.properties import ColumnProperty
class UCComparator(ColumnProperty.Comparator):
__hash__ = None
def method1(self):
return "uccmethod1"
def method2(self, other):
return "method2"
def __eq__(self, other):
cls = self.prop.parent.class_
col = getattr(cls, "name")
if other is None:
return col is None
else:
return sa.func.upper(col) == sa.func.upper(other)
def map_(with_explicit_property):
class User(object):
@extendedproperty
def uc_name(self):
if self.name is None:
return None
return self.name.upper()
if with_explicit_property:
args = (UCComparator, User.uc_name)
else:
args = (UCComparator,)
with assertions.expect_deprecated(
r"comparable_property\(\) is deprecated and will be "
"removed in a future release."
):
mapper(
User,
users,
properties=dict(uc_name=sa.orm.comparable_property(*args)),
)
return User
for User in (map_(True), map_(False)):
sess = create_session()
sess.begin()
q = sess.query(User)
assert hasattr(User, "name")
assert hasattr(User, "uc_name")
eq_(User.uc_name.method1(), "method1")
eq_(User.uc_name.method2("x"), "method2")
assert_raises_message(
AttributeError,
"Neither 'extendedproperty' object nor 'UCComparator' "
"object associated with User.uc_name has an attribute "
"'nonexistent'",
getattr,
User.uc_name,
"nonexistent",
)
# test compile
assert not isinstance(User.uc_name == "jack", bool)
u = q.filter(User.uc_name == "JACK").one()
assert u.uc_name == "JACK"
assert u not in sess.dirty
u.name = "some user name"
eq_(u.name, "some user name")
assert u in sess.dirty
eq_(u.uc_name, "SOME USER NAME")
sess.flush()
sess.expunge_all()
q = sess.query(User)
u2 = q.filter(User.name == "some user name").one()
u3 = q.filter(User.uc_name == "SOME USER NAME").one()
assert u2 is u3
eq_(User.uc_name.attribute, 123)
sess.rollback()
def test_comparable_column(self):
users, User = self.tables.users, self.classes.User
class MyComparator(sa.orm.properties.ColumnProperty.Comparator):
__hash__ = None
def __eq__(self, other):
# lower case comparison
return func.lower(self.__clause_element__()) == func.lower(
other
)
def intersects(self, other):
# non-standard comparator
return self.__clause_element__().op("&=")(other)
mapper(
User,
users,
properties={
"name": sa.orm.column_property(
users.c.name, comparator_factory=MyComparator
)
},
)
assert_raises_message(
AttributeError,
"Neither 'InstrumentedAttribute' object nor "
"'MyComparator' object associated with User.name has "
"an attribute 'nonexistent'",
getattr,
User.name,
"nonexistent",
)
eq_(
str(
(User.name == "ed").compile(
dialect=sa.engine.default.DefaultDialect()
)
),
"lower(users.name) = lower(:lower_1)",
)
eq_(
str(
(User.name.intersects("ed")).compile(
dialect=sa.engine.default.DefaultDialect()
)
),
"users.name &= :name_1",
)
def test_info(self):
users = self.tables.users
Address = self.classes.Address
class MyComposite(object):
pass
with assertions.expect_deprecated(
r"comparable_property\(\) is deprecated and will be "
"removed in a future release."
):
for constructor, args in [(comparable_property, "foo")]:
obj = constructor(info={"x": "y"}, *args)
eq_(obj.info, {"x": "y"})
obj.info["q"] = "p"
eq_(obj.info, {"x": "y", "q": "p"})
obj = constructor(*args)
eq_(obj.info, {})
obj.info["q"] = "p"
eq_(obj.info, {"q": "p"})
def test_add_property(self):
users = self.tables.users
assert_col = []
class User(fixtures.ComparableEntity):
def _get_name(self):
assert_col.append(("get", self._name))
return self._name
def _set_name(self, name):
assert_col.append(("set", name))
self._name = name
name = property(_get_name, _set_name)
def _uc_name(self):
if self._name is None:
return None
return self._name.upper()
uc_name = property(_uc_name)
uc_name2 = property(_uc_name)
m = mapper(User, users)
class UCComparator(PropComparator):
__hash__ = None
def __eq__(self, other):
cls = self.prop.parent.class_
col = getattr(cls, "name")
if other is None:
return col is None
else:
return func.upper(col) == func.upper(other)
m.add_property("_name", deferred(users.c.name))
m.add_property("name", synonym("_name"))
with assertions.expect_deprecated(
r"comparable_property\(\) is deprecated and will be "
"removed in a future release."
):
m.add_property("uc_name", comparable_property(UCComparator))
m.add_property(
"uc_name2", comparable_property(UCComparator, User.uc_name2)
)
sess = create_session(autocommit=False)
assert sess.query(User).get(7)
u = sess.query(User).filter_by(name="jack").one()
def go():
eq_(u.name, "jack")
eq_(u.uc_name, "JACK")
eq_(u.uc_name2, "JACK")
eq_(assert_col, [("get", "jack")], str(assert_col))
self.sql_count_(1, go)
def test_kwarg_accepted(self):
users, Address = self.tables.users, self.classes.Address
class DummyComposite(object):
def __init__(self, x, y):
pass
class MyFactory(PropComparator):
pass
with assertions.expect_deprecated(
r"comparable_property\(\) is deprecated and will be "
"removed in a future release."
):
for args in ((comparable_property,),):
fn = args[0]
args = args[1:]
fn(comparator_factory=MyFactory, *args)
def test_merge_synonym_comparable(self):
users = self.tables.users
class User(object):
class Comparator(PropComparator):
pass
def _getValue(self):
return self._value
def _setValue(self, value):
setattr(self, "_value", value)
value = property(_getValue, _setValue)
with assertions.expect_deprecated(
r"comparable_property\(\) is deprecated and will be "
"removed in a future release."
):
mapper(
User,
users,
properties={
"uid": synonym("id"),
"foobar": comparable_property(User.Comparator, User.value),
},
)
sess = create_session()
u = User()
u.name = "ed"
sess.add(u)
sess.flush()
sess.expunge(u)
sess.merge(u)
class DeprecatedDeclTest(fixtures.TestBase):
@testing.provide_metadata
def test_comparable_using(self):
class NameComparator(sa.orm.PropComparator):
@property
def upperself(self):
cls = self.prop.parent.class_
col = getattr(cls, "name")
return sa.func.upper(col)
def operate(self, op, other, **kw):
return op(self.upperself, other, **kw)
Base = declarative_base(metadata=self.metadata)
with testing.expect_deprecated(
r"comparable_property\(\) is deprecated and will be "
"removed in a future release."
):
class User(Base, fixtures.ComparableEntity):
__tablename__ = "users"
id = Column(
"id",
Integer,
primary_key=True,
test_needs_autoincrement=True,
)
name = Column("name", String(50))
@comparable_using(NameComparator)
@property
def uc_name(self):
return self.name is not None and self.name.upper() or None
Base.metadata.create_all()
sess = create_session()
u1 = User(name="someuser")
eq_(u1.name, "someuser", u1.name)
eq_(u1.uc_name, "SOMEUSER", u1.uc_name)
sess.add(u1)
sess.flush()
sess.expunge_all()
rt = sess.query(User).filter(User.uc_name == "SOMEUSER").one()
eq_(rt, u1)
sess.expunge_all()
rt = sess.query(User).filter(User.uc_name.startswith("SOMEUSE")).one()
eq_(rt, u1)
class DeprecatedMapperExtensionTest(_fixtures.FixtureTest):
"""Superseded by MapperEventsTest - test backwards
compatibility of MapperExtension."""
run_inserts = None
def extension(self):
methods = []
class Ext(MapperExtension):
def instrument_class(self, mapper, cls):
methods.append("instrument_class")
return EXT_CONTINUE
def init_instance(
self, mapper, class_, oldinit, instance, args, kwargs
):
methods.append("init_instance")
return EXT_CONTINUE
def init_failed(
self, mapper, class_, oldinit, instance, args, kwargs
):
methods.append("init_failed")
return EXT_CONTINUE
def reconstruct_instance(self, mapper, instance):
methods.append("reconstruct_instance")
return EXT_CONTINUE
def before_insert(self, mapper, connection, instance):
methods.append("before_insert")
return EXT_CONTINUE
def after_insert(self, mapper, connection, instance):
methods.append("after_insert")
return EXT_CONTINUE
def before_update(self, mapper, connection, instance):
methods.append("before_update")
return EXT_CONTINUE
def after_update(self, mapper, connection, instance):
methods.append("after_update")
return EXT_CONTINUE
def before_delete(self, mapper, connection, instance):
methods.append("before_delete")
return EXT_CONTINUE
def after_delete(self, mapper, connection, instance):
methods.append("after_delete")
return EXT_CONTINUE
return Ext, methods
def test_basic(self):
"""test that common user-defined methods get called."""
User, users = self.classes.User, self.tables.users
Ext, methods = self.extension()
with testing.expect_deprecated(
"MapperExtension is deprecated in favor of the MapperEvents",
"MapperExtension.before_insert is deprecated",
"MapperExtension.instrument_class is deprecated",
"MapperExtension.init_instance is deprecated",
"MapperExtension.after_insert is deprecated",
"MapperExtension.reconstruct_instance is deprecated",
"MapperExtension.before_delete is deprecated",
"MapperExtension.after_delete is deprecated",
"MapperExtension.before_update is deprecated",
"MapperExtension.after_update is deprecated",
"MapperExtension.init_failed is deprecated",
):
mapper(User, users, extension=Ext())
sess = create_session()
u = User(name="u1")
sess.add(u)
sess.flush()
u = sess.query(User).populate_existing().get(u.id)
sess.expunge_all()
u = sess.query(User).get(u.id)
u.name = "u1 changed"
sess.flush()
sess.delete(u)
sess.flush()
eq_(
methods,
[
"instrument_class",
"init_instance",
"before_insert",
"after_insert",
"reconstruct_instance",
"before_update",
"after_update",
"before_delete",
"after_delete",
],
)
def test_inheritance(self):
users, addresses, User = (
self.tables.users,
self.tables.addresses,
self.classes.User,
)
Ext, methods = self.extension()
class AdminUser(User):
pass
with testing.expect_deprecated(
"MapperExtension is deprecated in favor of the MapperEvents",
"MapperExtension.before_insert is deprecated",
"MapperExtension.instrument_class is deprecated",
"MapperExtension.init_instance is deprecated",
"MapperExtension.after_insert is deprecated",
"MapperExtension.reconstruct_instance is deprecated",
"MapperExtension.before_delete is deprecated",
"MapperExtension.after_delete is deprecated",
"MapperExtension.before_update is deprecated",
"MapperExtension.after_update is deprecated",
"MapperExtension.init_failed is deprecated",
):
mapper(User, users, extension=Ext())
mapper(
AdminUser,
addresses,
inherits=User,
properties={"address_id": addresses.c.id},
)
sess = create_session()
am = AdminUser(name="au1", email_address="au1@e1")
sess.add(am)
sess.flush()
am = sess.query(AdminUser).populate_existing().get(am.id)
sess.expunge_all()
am = sess.query(AdminUser).get(am.id)
am.name = "au1 changed"
sess.flush()
sess.delete(am)
sess.flush()
eq_(
methods,
[
"instrument_class",
"instrument_class",
"init_instance",
"before_insert",
"after_insert",
"reconstruct_instance",
"before_update",
"after_update",
"before_delete",
"after_delete",
],
)
def test_before_after_only_collection(self):
"""before_update is called on parent for collection modifications,
after_update is called even if no columns were updated.
"""
keywords, items, item_keywords, Keyword, Item = (
self.tables.keywords,
self.tables.items,
self.tables.item_keywords,
self.classes.Keyword,
self.classes.Item,
)
Ext1, methods1 = self.extension()
Ext2, methods2 = self.extension()
with testing.expect_deprecated(
"MapperExtension is deprecated in favor of the MapperEvents",
"MapperExtension.before_insert is deprecated",
"MapperExtension.instrument_class is deprecated",
"MapperExtension.init_instance is deprecated",
"MapperExtension.after_insert is deprecated",
"MapperExtension.reconstruct_instance is deprecated",
"MapperExtension.before_delete is deprecated",
"MapperExtension.after_delete is deprecated",
"MapperExtension.before_update is deprecated",
"MapperExtension.after_update is deprecated",
"MapperExtension.init_failed is deprecated",
):
mapper(
Item,
items,
extension=Ext1(),
properties={
"keywords": relationship(Keyword, secondary=item_keywords)
},
)
with testing.expect_deprecated(
"MapperExtension is deprecated in favor of the MapperEvents",
"MapperExtension.before_insert is deprecated",
"MapperExtension.instrument_class is deprecated",
"MapperExtension.init_instance is deprecated",
"MapperExtension.after_insert is deprecated",
"MapperExtension.reconstruct_instance is deprecated",
"MapperExtension.before_delete is deprecated",
"MapperExtension.after_delete is deprecated",
"MapperExtension.before_update is deprecated",
"MapperExtension.after_update is deprecated",
"MapperExtension.init_failed is deprecated",
):
mapper(Keyword, keywords, extension=Ext2())
sess = create_session()
i1 = Item(description="i1")
k1 = Keyword(name="k1")
sess.add(i1)
sess.add(k1)
sess.flush()
eq_(
methods1,
[
"instrument_class",
"init_instance",
"before_insert",
"after_insert",
],
)
eq_(
methods2,
[
"instrument_class",
"init_instance",
"before_insert",
"after_insert",
],
)
del methods1[:]
del methods2[:]
i1.keywords.append(k1)
sess.flush()
eq_(methods1, ["before_update", "after_update"])
eq_(methods2, [])
def test_inheritance_with_dupes(self):
"""Inheritance with the same extension instance on both mappers."""
users, addresses, User = (
self.tables.users,
self.tables.addresses,
self.classes.User,
)
Ext, methods = self.extension()
class AdminUser(User):
pass
ext = Ext()
with testing.expect_deprecated(
"MapperExtension is deprecated in favor of the MapperEvents",
"MapperExtension.before_insert is deprecated",
"MapperExtension.instrument_class is deprecated",
"MapperExtension.init_instance is deprecated",
"MapperExtension.after_insert is deprecated",
"MapperExtension.reconstruct_instance is deprecated",
"MapperExtension.before_delete is deprecated",
"MapperExtension.after_delete is deprecated",
"MapperExtension.before_update is deprecated",
"MapperExtension.after_update is deprecated",
"MapperExtension.init_failed is deprecated",
):
mapper(User, users, extension=ext)
with testing.expect_deprecated(
"MapperExtension is deprecated in favor of the MapperEvents"
):
mapper(
AdminUser,
addresses,
inherits=User,
extension=ext,
properties={"address_id": addresses.c.id},
)
sess = create_session()
am = AdminUser(name="au1", email_address="au1@e1")
sess.add(am)
sess.flush()
am = sess.query(AdminUser).populate_existing().get(am.id)
sess.expunge_all()
am = sess.query(AdminUser).get(am.id)
am.name = "au1 changed"
sess.flush()
sess.delete(am)
sess.flush()
eq_(
methods,
[
"instrument_class",
"instrument_class",
"init_instance",
"before_insert",
"after_insert",
"reconstruct_instance",
"before_update",
"after_update",
"before_delete",
"after_delete",
],
)
def test_unnecessary_methods_not_evented(self):
users = self.tables.users
class MyExtension(MapperExtension):
def before_insert(self, mapper, connection, instance):
pass
class Foo(object):
pass
with testing.expect_deprecated(
"MapperExtension is deprecated in favor of the MapperEvents",
"MapperExtension.before_insert is deprecated",
):
m = mapper(Foo, users, extension=MyExtension())
assert not m.class_manager.dispatch.load
assert not m.dispatch.before_update
assert len(m.dispatch.before_insert) == 1
class DeprecatedSessionExtensionTest(_fixtures.FixtureTest):
run_inserts = None
def test_extension(self):
User, users = self.classes.User, self.tables.users
mapper(User, users)
log = []
class MyExt(SessionExtension):
def before_commit(self, session):
log.append("before_commit")
def after_commit(self, session):
log.append("after_commit")
def after_rollback(self, session):
log.append("after_rollback")
def before_flush(self, session, flush_context, objects):
log.append("before_flush")
def after_flush(self, session, flush_context):
log.append("after_flush")
def after_flush_postexec(self, session, flush_context):
log.append("after_flush_postexec")
def after_begin(self, session, transaction, connection):
log.append("after_begin")
def after_attach(self, session, instance):
log.append("after_attach")
def after_bulk_update(self, session, query, query_context, result):
log.append("after_bulk_update")
def after_bulk_delete(self, session, query, query_context, result):
log.append("after_bulk_delete")
with testing.expect_deprecated(
"SessionExtension is deprecated in favor of " "the SessionEvents",
"SessionExtension.before_commit is deprecated",
"SessionExtension.after_commit is deprecated",
"SessionExtension.after_begin is deprecated",
"SessionExtension.after_attach is deprecated",
"SessionExtension.before_flush is deprecated",
"SessionExtension.after_flush is deprecated",
"SessionExtension.after_flush_postexec is deprecated",
"SessionExtension.after_rollback is deprecated",
"SessionExtension.after_bulk_update is deprecated",
"SessionExtension.after_bulk_delete is deprecated",
):
sess = create_session(extension=MyExt())
u = User(name="u1")
sess.add(u)
sess.flush()
assert log == [
"after_attach",
"before_flush",
"after_begin",
"after_flush",
"after_flush_postexec",
"before_commit",
"after_commit",
]
log = []
with testing.expect_deprecated(
"SessionExtension is deprecated in favor of " "the SessionEvents",
"SessionExtension.before_commit is deprecated",
"SessionExtension.after_commit is deprecated",
"SessionExtension.after_begin is deprecated",
"SessionExtension.after_attach is deprecated",
"SessionExtension.before_flush is deprecated",
"SessionExtension.after_flush is deprecated",
"SessionExtension.after_flush_postexec is deprecated",
"SessionExtension.after_rollback is deprecated",
"SessionExtension.after_bulk_update is deprecated",
"SessionExtension.after_bulk_delete is deprecated",
):
sess = create_session(autocommit=False, extension=MyExt())
u = User(name="u1")
sess.add(u)
sess.flush()
assert log == [
"after_attach",
"before_flush",
"after_begin",
"after_flush",
"after_flush_postexec",
]
log = []
u.name = "ed"
sess.commit()
assert log == [
"before_commit",
"before_flush",
"after_flush",
"after_flush_postexec",
"after_commit",
]
log = []
sess.commit()
assert log == ["before_commit", "after_commit"]
log = []
sess.query(User).delete()
assert log == ["after_begin", "after_bulk_delete"]
log = []
sess.query(User).update({"name": "foo"})
assert log == ["after_bulk_update"]
log = []
with testing.expect_deprecated(
"SessionExtension is deprecated in favor of " "the SessionEvents",
"SessionExtension.before_commit is deprecated",
"SessionExtension.after_commit is deprecated",
"SessionExtension.after_begin is deprecated",
"SessionExtension.after_attach is deprecated",
"SessionExtension.before_flush is deprecated",
"SessionExtension.after_flush is deprecated",
"SessionExtension.after_flush_postexec is deprecated",
"SessionExtension.after_rollback is deprecated",
"SessionExtension.after_bulk_update is deprecated",
"SessionExtension.after_bulk_delete is deprecated",
):
sess = create_session(
autocommit=False, extension=MyExt(), bind=testing.db
)
sess.connection()
assert log == ["after_begin"]
sess.close()
def test_multiple_extensions(self):
User, users = self.classes.User, self.tables.users
log = []
class MyExt1(SessionExtension):
def before_commit(self, session):
log.append("before_commit_one")
class MyExt2(SessionExtension):
def before_commit(self, session):
log.append("before_commit_two")
mapper(User, users)
with testing.expect_deprecated(
"SessionExtension is deprecated in favor of " "the SessionEvents",
"SessionExtension.before_commit is deprecated",
):
sess = create_session(extension=[MyExt1(), MyExt2()])
u = User(name="u1")
sess.add(u)
sess.flush()
assert log == ["before_commit_one", "before_commit_two"]
def test_unnecessary_methods_not_evented(self):
class MyExtension(SessionExtension):
def before_commit(self, session):
pass
with testing.expect_deprecated(
"SessionExtension is deprecated in favor of " "the SessionEvents",
"SessionExtension.before_commit is deprecated.",
):
s = Session(extension=MyExtension())
assert not s.dispatch.after_commit
assert len(s.dispatch.before_commit) == 1
class DeprecatedAttributeExtensionTest1(fixtures.ORMTest):
def test_extension_commit_attr(self):
"""test that an extension which commits attribute history
maintains the end-result history.
This won't work in conjunction with some unitofwork extensions.
"""
class Foo(fixtures.BasicEntity):
pass
class Bar(fixtures.BasicEntity):
pass
class ReceiveEvents(AttributeExtension):
def __init__(self, key):
self.key = key
def append(self, state, child, initiator):
if commit:
state._commit_all(state.dict)
return child
def remove(self, state, child, initiator):
if commit:
state._commit_all(state.dict)
return child
def set(self, state, child, oldchild, initiator):
if commit:
state._commit_all(state.dict)
return child
instrumentation.register_class(Foo)
instrumentation.register_class(Bar)
b1, b2, b3, b4 = Bar(id="b1"), Bar(id="b2"), Bar(id="b3"), Bar(id="b4")
def loadcollection(state, passive):
if passive is attributes.PASSIVE_NO_FETCH:
return attributes.PASSIVE_NO_RESULT
return [b1, b2]
def loadscalar(state, passive):
if passive is attributes.PASSIVE_NO_FETCH:
return attributes.PASSIVE_NO_RESULT
return b2
with testing.expect_deprecated(
"AttributeExtension.append is deprecated.",
"AttributeExtension.remove is deprecated.",
"AttributeExtension.set is deprecated.",
):
attributes.register_attribute(
Foo,
"bars",
uselist=True,
useobject=True,
callable_=loadcollection,
extension=[ReceiveEvents("bars")],
)
with testing.expect_deprecated(
"AttributeExtension.append is deprecated.",
"AttributeExtension.remove is deprecated.",
"AttributeExtension.set is deprecated.",
):
attributes.register_attribute(
Foo,
"bar",
uselist=False,
useobject=True,
callable_=loadscalar,
extension=[ReceiveEvents("bar")],
)
with testing.expect_deprecated(
"AttributeExtension.append is deprecated.",
"AttributeExtension.remove is deprecated.",
"AttributeExtension.set is deprecated.",
):
attributes.register_attribute(
Foo,
"scalar",
uselist=False,
useobject=False,
extension=[ReceiveEvents("scalar")],
)
def create_hist():
def hist(key, fn, *arg):
attributes.instance_state(f1)._commit_all(
attributes.instance_dict(f1)
)
fn(*arg)
histories.append(attributes.get_history(f1, key))
f1 = Foo()
hist("bars", f1.bars.append, b3)
hist("bars", f1.bars.append, b4)
hist("bars", f1.bars.remove, b2)
hist("bar", setattr, f1, "bar", b3)
hist("bar", setattr, f1, "bar", None)
hist("bar", setattr, f1, "bar", b4)
hist("scalar", setattr, f1, "scalar", 5)
hist("scalar", setattr, f1, "scalar", None)
hist("scalar", setattr, f1, "scalar", 4)
histories = []
commit = False
create_hist()
without_commit = list(histories)
histories[:] = []
commit = True
create_hist()
with_commit = histories
for without, with_ in zip(without_commit, with_commit):
woc = without
wic = with_
eq_(woc, wic)
def test_extension_lazyload_assertion(self):
class Foo(fixtures.BasicEntity):
pass
class Bar(fixtures.BasicEntity):
pass
class ReceiveEvents(AttributeExtension):
def append(self, state, child, initiator):
state.obj().bars
return child
def remove(self, state, child, initiator):
state.obj().bars
return child
def set(self, state, child, oldchild, initiator):
return child
instrumentation.register_class(Foo)
instrumentation.register_class(Bar)
bar1, bar2, bar3 = [Bar(id=1), Bar(id=2), Bar(id=3)]
def func1(state, passive):
if passive is attributes.PASSIVE_NO_FETCH:
return attributes.PASSIVE_NO_RESULT
return [bar1, bar2, bar3]
with testing.expect_deprecated(
"AttributeExtension.append is deprecated.",
"AttributeExtension.remove is deprecated.",
"AttributeExtension.set is deprecated.",
):
attributes.register_attribute(
Foo,
"bars",
uselist=True,
callable_=func1,
useobject=True,
extension=[ReceiveEvents()],
)
attributes.register_attribute(
Bar, "foos", uselist=True, useobject=True, backref="bars"
)
x = Foo()
assert_raises(AssertionError, Bar(id=4).foos.append, x)
x.bars
b = Bar(id=4)
b.foos.append(x)
attributes.instance_state(x)._expire_attributes(
attributes.instance_dict(x), ["bars"]
)
assert_raises(AssertionError, b.foos.remove, x)
def test_scalar_listener(self):
# listeners on ScalarAttributeImpl aren't used normally. test that
# they work for the benefit of user extensions
class Foo(object):
pass
results = []
class ReceiveEvents(AttributeExtension):
def append(self, state, child, initiator):
assert False
def remove(self, state, child, initiator):
results.append(("remove", state.obj(), child))
def set(self, state, child, oldchild, initiator):
results.append(("set", state.obj(), child, oldchild))
return child
instrumentation.register_class(Foo)
with testing.expect_deprecated(
"AttributeExtension.append is deprecated.",
"AttributeExtension.remove is deprecated.",
"AttributeExtension.set is deprecated.",
):
attributes.register_attribute(
Foo,
"x",
uselist=False,
useobject=False,
extension=ReceiveEvents(),
)
f = Foo()
f.x = 5
f.x = 17
del f.x
eq_(
results,
[
("set", f, 5, attributes.NEVER_SET),
("set", f, 17, 5),
("remove", f, 17),
],
)
def test_cascading_extensions(self):
t1 = Table(
"t1",
MetaData(),
Column("id", Integer, primary_key=True),
Column("type", String(40)),
Column("data", String(50)),
)
ext_msg = []
class Ex1(AttributeExtension):
def set(self, state, value, oldvalue, initiator):
ext_msg.append("Ex1 %r" % value)
return "ex1" + value
class Ex2(AttributeExtension):
def set(self, state, value, oldvalue, initiator):
ext_msg.append("Ex2 %r" % value)
return "ex2" + value
class A(fixtures.BasicEntity):
pass
class B(A):
pass
class C(B):
pass
with testing.expect_deprecated(
"AttributeExtension is deprecated in favor of the "
"AttributeEvents listener interface. "
"The column_property.extension parameter"
):
mapper(
A,
t1,
polymorphic_on=t1.c.type,
polymorphic_identity="a",
properties={
"data": column_property(t1.c.data, extension=Ex1())
},
)
mapper(B, polymorphic_identity="b", inherits=A)
with testing.expect_deprecated(
"AttributeExtension is deprecated in favor of the "
"AttributeEvents listener interface. "
"The column_property.extension parameter"
):
mapper(
C,
polymorphic_identity="c",
inherits=B,
properties={
"data": column_property(t1.c.data, extension=Ex2())
},
)
with testing.expect_deprecated(
"AttributeExtension.set is deprecated. "
):
configure_mappers()
a1 = A(data="a1")
b1 = B(data="b1")
c1 = C(data="c1")
eq_(a1.data, "ex1a1")
eq_(b1.data, "ex1b1")
eq_(c1.data, "ex2c1")
a1.data = "a2"
b1.data = "b2"
c1.data = "c2"
eq_(a1.data, "ex1a2")
eq_(b1.data, "ex1b2")
eq_(c1.data, "ex2c2")
eq_(
ext_msg,
[
"Ex1 'a1'",
"Ex1 'b1'",
"Ex2 'c1'",
"Ex1 'a2'",
"Ex1 'b2'",
"Ex2 'c2'",
],
)
class DeprecatedOptionAllTest(OptionsPathTest, _fixtures.FixtureTest):
run_inserts = "once"
run_deletes = None
def _mapper_fixture_one(self):
users, User, addresses, Address, orders, Order = (
self.tables.users,
self.classes.User,
self.tables.addresses,
self.classes.Address,
self.tables.orders,
self.classes.Order,
)
keywords, items, item_keywords, Keyword, Item = (
self.tables.keywords,
self.tables.items,
self.tables.item_keywords,
self.classes.Keyword,
self.classes.Item,
)
mapper(
User,
users,
properties={
"addresses": relationship(Address),
"orders": relationship(Order),
},
)
mapper(Address, addresses)
mapper(
Order,
orders,
properties={
"items": relationship(Item, secondary=self.tables.order_items)
},
)
mapper(
Keyword,
keywords,
properties={
"keywords": column_property(keywords.c.name + "some keyword")
},
)
mapper(
Item,
items,
properties=dict(
keywords=relationship(Keyword, secondary=item_keywords)
),
)
def _assert_eager_with_entity_exception(
self, entity_list, options, message
):
assert_raises_message(
sa.exc.ArgumentError,
message,
create_session().query(*entity_list).options,
*options
)
def test_option_against_nonexistent_twolevel_all(self):
self._mapper_fixture_one()
Item = self.classes.Item
with testing.expect_deprecated(
r"The joinedload_all\(\) function is deprecated, and "
"will be removed in a future release. "
r"Please use method chaining with joinedload\(\)"
):
self._assert_eager_with_entity_exception(
[Item],
(joinedload_all("keywords.foo"),),
r"Can't find property named 'foo' on the mapped entity "
r"Mapper\|Keyword\|keywords in this Query.",
)
def test_all_path_vs_chained(self):
self._mapper_fixture_one()
User = self.classes.User
Order = self.classes.Order
Item = self.classes.Item
with testing.expect_deprecated(
r"The joinedload_all\(\) function is deprecated, and "
"will be removed in a future release. "
r"Please use method chaining with joinedload\(\)"
):
l1 = joinedload_all("orders.items.keywords")
sess = Session()
q = sess.query(User)
self._assert_path_result(
l1,
q,
[
(User, "orders"),
(User, "orders", Order, "items"),
(User, "orders", Order, "items", Item, "keywords"),
],
)
l2 = joinedload("orders").joinedload("items").joinedload("keywords")
self._assert_path_result(
l2,
q,
[
(User, "orders"),
(User, "orders", Order, "items"),
(User, "orders", Order, "items", Item, "keywords"),
],
)
def test_subqueryload_mapper_order_by(self):
users, User, Address, addresses = (
self.tables.users,
self.classes.User,
self.classes.Address,
self.tables.addresses,
)
mapper(Address, addresses)
with testing.expect_deprecated(
".*Mapper.order_by parameter is deprecated"
):
mapper(
User,
users,
properties={
"addresses": relationship(
Address, lazy="subquery", order_by=addresses.c.id
)
},
order_by=users.c.id.desc(),
)
sess = create_session()
q = sess.query(User)
result = q.limit(2).all()
eq_(result, list(reversed(self.static.user_address_result[2:4])))
def test_selectinload_mapper_order_by(self):
users, User, Address, addresses = (
self.tables.users,
self.classes.User,
self.classes.Address,
self.tables.addresses,
)
mapper(Address, addresses)
with testing.expect_deprecated(
".*Mapper.order_by parameter is deprecated"
):
mapper(
User,
users,
properties={
"addresses": relationship(
Address, lazy="selectin", order_by=addresses.c.id
)
},
order_by=users.c.id.desc(),
)
sess = create_session()
q = sess.query(User)
result = q.limit(2).all()
eq_(result, list(reversed(self.static.user_address_result[2:4])))
def test_join_mapper_order_by(self):
"""test that mapper-level order_by is adapted to a selectable."""
User, users = self.classes.User, self.tables.users
with testing.expect_deprecated(
".*Mapper.order_by parameter is deprecated"
):
mapper(User, users, order_by=users.c.id)
sel = users.select(users.c.id.in_([7, 8]))
sess = create_session()
eq_(
sess.query(User).select_entity_from(sel).all(),
[User(name="jack", id=7), User(name="ed", id=8)],
)
def test_defer_addtl_attrs(self):
users, User, Address, addresses = (
self.tables.users,
self.classes.User,
self.classes.Address,
self.tables.addresses,
)
mapper(Address, addresses)
mapper(
User,
users,
properties={
"addresses": relationship(
Address, lazy="selectin", order_by=addresses.c.id
)
},
)
sess = create_session()
with testing.expect_deprecated(
r"The \*addl_attrs on orm.defer is deprecated. "
"Please use method chaining"
):
sess.query(User).options(defer("addresses", "email_address"))
with testing.expect_deprecated(
r"The \*addl_attrs on orm.undefer is deprecated. "
"Please use method chaining"
):
sess.query(User).options(undefer("addresses", "email_address"))
class LegacyLockModeTest(_fixtures.FixtureTest):
run_inserts = None
@classmethod
def setup_mappers(cls):
User, users = cls.classes.User, cls.tables.users
mapper(User, users)
def _assert_legacy(self, arg, read=False, nowait=False):
User = self.classes.User
s = Session()
with testing.expect_deprecated(
r"The Query.with_lockmode\(\) method is deprecated"
):
q = s.query(User).with_lockmode(arg)
sel = q._compile_context().statement
if arg is None:
assert q._for_update_arg is None
assert sel._for_update_arg is None
return
assert q._for_update_arg.read is read
assert q._for_update_arg.nowait is nowait
assert sel._for_update_arg.read is read
assert sel._for_update_arg.nowait is nowait
def test_false_legacy(self):
self._assert_legacy(None)
def test_plain_legacy(self):
self._assert_legacy("update")
def test_nowait_legacy(self):
self._assert_legacy("update_nowait", nowait=True)
def test_read_legacy(self):
self._assert_legacy("read", read=True)
def test_unknown_legacy_lock_mode(self):
User = self.classes.User
sess = Session()
with testing.expect_deprecated(
r"The Query.with_lockmode\(\) method is deprecated"
):
assert_raises_message(
exc.ArgumentError,
"Unknown with_lockmode argument: 'unknown_mode'",
sess.query(User.id).with_lockmode,
"unknown_mode",
)
class InstrumentationTest(fixtures.ORMTest):
def test_dict_subclass4(self):
# tests #2654
with testing.expect_deprecated(
r"The collection.converter\(\) handler is deprecated and will "
"be removed in a future release. Please refer to the "
"AttributeEvents"
):
class MyDict(collections.MappedCollection):
def __init__(self):
super(MyDict, self).__init__(lambda value: "k%d" % value)
@collection.converter
def _convert(self, dictlike):
for key, value in dictlike.items():
yield value + 5
class Foo(object):
pass
instrumentation.register_class(Foo)
d = attributes.register_attribute(
Foo, "attr", uselist=True, typecallable=MyDict, useobject=True
)
f = Foo()
f.attr = {"k1": 1, "k2": 2}
eq_(f.attr, {"k7": 7, "k6": 6})
def test_name_setup(self):
with testing.expect_deprecated(
r"The collection.converter\(\) handler is deprecated and will "
"be removed in a future release. Please refer to the "
"AttributeEvents"
):
class Base(object):
@collection.iterator
def base_iterate(self, x):
return "base_iterate"
@collection.appender
def base_append(self, x):
return "base_append"
@collection.converter
def base_convert(self, x):
return "base_convert"
@collection.remover
def base_remove(self, x):
return "base_remove"
from sqlalchemy.orm.collections import _instrument_class
_instrument_class(Base)
eq_(Base._sa_remover(Base(), 5), "base_remove")
eq_(Base._sa_appender(Base(), 5), "base_append")
eq_(Base._sa_iterator(Base(), 5), "base_iterate")
eq_(Base._sa_converter(Base(), 5), "base_convert")
with testing.expect_deprecated(
r"The collection.converter\(\) handler is deprecated and will "
"be removed in a future release. Please refer to the "
"AttributeEvents"
):
class Sub(Base):
@collection.converter
def base_convert(self, x):
return "sub_convert"
@collection.remover
def sub_remove(self, x):
return "sub_remove"
_instrument_class(Sub)
eq_(Sub._sa_appender(Sub(), 5), "base_append")
eq_(Sub._sa_remover(Sub(), 5), "sub_remove")
eq_(Sub._sa_iterator(Sub(), 5), "base_iterate")
eq_(Sub._sa_converter(Sub(), 5), "sub_convert")
def test_link_event(self):
canary = []
with testing.expect_deprecated(
r"The collection.linker\(\) handler is deprecated and will "
"be removed in a future release. Please refer to the "
"AttributeEvents"
):
class Collection(list):
@collection.linker
def _on_link(self, obj):
canary.append(obj)
class Foo(object):
pass
instrumentation.register_class(Foo)
attributes.register_attribute(
Foo, "attr", uselist=True, typecallable=Collection, useobject=True
)
f1 = Foo()
f1.attr.append(3)
eq_(canary, [f1.attr._sa_adapter])
adapter_1 = f1.attr._sa_adapter
l2 = Collection()
f1.attr = l2
eq_(canary, [adapter_1, f1.attr._sa_adapter, None])
|
the-stack_106_26621 | import logging
from typing import Dict, List, Optional, Tuple
import aiosqlite
from mint.consensus.block_record import BlockRecord
from mint.types.blockchain_format.sized_bytes import bytes32
from mint.types.blockchain_format.sub_epoch_summary import SubEpochSummary
from mint.types.full_block import FullBlock
from mint.types.weight_proof import SubEpochChallengeSegment, SubEpochSegments
from mint.util.db_wrapper import DBWrapper
from mint.util.ints import uint32
from mint.util.lru_cache import LRUCache
log = logging.getLogger(__name__)
class BlockStore:
db: aiosqlite.Connection
block_cache: LRUCache
db_wrapper: DBWrapper
ses_challenge_cache: LRUCache
@classmethod
async def create(cls, db_wrapper: DBWrapper):
self = cls()
# All full blocks which have been added to the blockchain. Header_hash -> block
self.db_wrapper = db_wrapper
self.db = db_wrapper.db
await self.db.execute(
"CREATE TABLE IF NOT EXISTS full_blocks(header_hash text PRIMARY KEY, height bigint,"
" is_block tinyint, is_fully_compactified tinyint, block blob)"
)
# Block records
await self.db.execute(
"CREATE TABLE IF NOT EXISTS block_records(header_hash "
"text PRIMARY KEY, prev_hash text, height bigint,"
"block blob, sub_epoch_summary blob, is_peak tinyint, is_block tinyint)"
)
# todo remove in v1.2
await self.db.execute("DROP TABLE IF EXISTS sub_epoch_segments_v2")
# Sub epoch segments for weight proofs
await self.db.execute(
"CREATE TABLE IF NOT EXISTS sub_epoch_segments_v3(ses_block_hash text PRIMARY KEY, challenge_segments blob)"
)
# Height index so we can look up in order of height for sync purposes
await self.db.execute("CREATE INDEX IF NOT EXISTS full_block_height on full_blocks(height)")
# this index is not used by any queries, don't create it for new
# installs, and remove it from existing installs in the future
# await self.db.execute("DROP INDEX IF EXISTS is_block on full_blocks(is_block)")
await self.db.execute("CREATE INDEX IF NOT EXISTS is_fully_compactified on full_blocks(is_fully_compactified)")
await self.db.execute("CREATE INDEX IF NOT EXISTS height on block_records(height)")
await self.db.execute("CREATE INDEX IF NOT EXISTS hh on block_records(header_hash)")
await self.db.execute("CREATE INDEX IF NOT EXISTS peak on block_records(is_peak)")
# this index is not used by any queries, don't create it for new
# installs, and remove it from existing installs in the future
# await self.db.execute("DROP INDEX IF EXISTS is_block on block_records(is_block)")
await self.db.commit()
self.block_cache = LRUCache(1000)
self.ses_challenge_cache = LRUCache(50)
return self
async def add_full_block(self, header_hash: bytes32, block: FullBlock, block_record: BlockRecord) -> None:
self.block_cache.put(header_hash, block)
cursor_1 = await self.db.execute(
"INSERT OR REPLACE INTO full_blocks VALUES(?, ?, ?, ?, ?)",
(
header_hash.hex(),
block.height,
int(block.is_transaction_block()),
int(block.is_fully_compactified()),
bytes(block),
),
)
await cursor_1.close()
cursor_2 = await self.db.execute(
"INSERT OR REPLACE INTO block_records VALUES(?, ?, ?, ?,?, ?, ?)",
(
header_hash.hex(),
block.prev_header_hash.hex(),
block.height,
bytes(block_record),
None
if block_record.sub_epoch_summary_included is None
else bytes(block_record.sub_epoch_summary_included),
False,
block.is_transaction_block(),
),
)
await cursor_2.close()
async def persist_sub_epoch_challenge_segments(
self, ses_block_hash: bytes32, segments: List[SubEpochChallengeSegment]
) -> None:
async with self.db_wrapper.lock:
cursor_1 = await self.db.execute(
"INSERT OR REPLACE INTO sub_epoch_segments_v3 VALUES(?, ?)",
(ses_block_hash.hex(), bytes(SubEpochSegments(segments))),
)
await cursor_1.close()
await self.db.commit()
async def get_sub_epoch_challenge_segments(
self,
ses_block_hash: bytes32,
) -> Optional[List[SubEpochChallengeSegment]]:
cached = self.ses_challenge_cache.get(ses_block_hash)
if cached is not None:
return cached
cursor = await self.db.execute(
"SELECT challenge_segments from sub_epoch_segments_v3 WHERE ses_block_hash=?", (ses_block_hash.hex(),)
)
row = await cursor.fetchone()
await cursor.close()
if row is not None:
challenge_segments = SubEpochSegments.from_bytes(row[0]).challenge_segments
self.ses_challenge_cache.put(ses_block_hash, challenge_segments)
return challenge_segments
return None
def rollback_cache_block(self, header_hash: bytes32):
try:
self.block_cache.remove(header_hash)
except KeyError:
# this is best effort. When rolling back, we may not have added the
# block to the cache yet
pass
async def get_full_block(self, header_hash: bytes32) -> Optional[FullBlock]:
cached = self.block_cache.get(header_hash)
if cached is not None:
log.debug(f"cache hit for block {header_hash.hex()}")
return cached
log.debug(f"cache miss for block {header_hash.hex()}")
cursor = await self.db.execute("SELECT block from full_blocks WHERE header_hash=?", (header_hash.hex(),))
row = await cursor.fetchone()
await cursor.close()
if row is not None:
block = FullBlock.from_bytes(row[0])
self.block_cache.put(header_hash, block)
return block
return None
async def get_full_block_bytes(self, header_hash: bytes32) -> Optional[bytes]:
cached = self.block_cache.get(header_hash)
if cached is not None:
log.debug(f"cache hit for block {header_hash.hex()}")
return bytes(cached)
log.debug(f"cache miss for block {header_hash.hex()}")
cursor = await self.db.execute("SELECT block from full_blocks WHERE header_hash=?", (header_hash.hex(),))
row = await cursor.fetchone()
await cursor.close()
if row is not None:
return row[0]
return None
async def get_full_blocks_at(self, heights: List[uint32]) -> List[FullBlock]:
if len(heights) == 0:
return []
heights_db = tuple(heights)
formatted_str = f'SELECT block from full_blocks WHERE height in ({"?," * (len(heights_db) - 1)}?)'
cursor = await self.db.execute(formatted_str, heights_db)
rows = await cursor.fetchall()
await cursor.close()
return [FullBlock.from_bytes(row[0]) for row in rows]
async def get_block_records_by_hash(self, header_hashes: List[bytes32]):
"""
Returns a list of Block Records, ordered by the same order in which header_hashes are passed in.
Throws an exception if the blocks are not present
"""
if len(header_hashes) == 0:
return []
header_hashes_db = tuple([hh.hex() for hh in header_hashes])
formatted_str = f'SELECT block from block_records WHERE header_hash in ({"?," * (len(header_hashes_db) - 1)}?)'
cursor = await self.db.execute(formatted_str, header_hashes_db)
rows = await cursor.fetchall()
await cursor.close()
all_blocks: Dict[bytes32, BlockRecord] = {}
for row in rows:
block_rec: BlockRecord = BlockRecord.from_bytes(row[0])
all_blocks[block_rec.header_hash] = block_rec
ret: List[BlockRecord] = []
for hh in header_hashes:
if hh not in all_blocks:
raise ValueError(f"Header hash {hh} not in the blockchain")
ret.append(all_blocks[hh])
return ret
async def get_blocks_by_hash(self, header_hashes: List[bytes32]) -> List[FullBlock]:
"""
Returns a list of Full Blocks blocks, ordered by the same order in which header_hashes are passed in.
Throws an exception if the blocks are not present
"""
if len(header_hashes) == 0:
return []
header_hashes_db = tuple([hh.hex() for hh in header_hashes])
formatted_str = (
f'SELECT header_hash, block from full_blocks WHERE header_hash in ({"?," * (len(header_hashes_db) - 1)}?)'
)
cursor = await self.db.execute(formatted_str, header_hashes_db)
rows = await cursor.fetchall()
await cursor.close()
all_blocks: Dict[bytes32, FullBlock] = {}
for row in rows:
header_hash = bytes.fromhex(row[0])
full_block: FullBlock = FullBlock.from_bytes(row[1])
all_blocks[header_hash] = full_block
self.block_cache.put(header_hash, full_block)
ret: List[FullBlock] = []
for hh in header_hashes:
if hh not in all_blocks:
raise ValueError(f"Header hash {hh} not in the blockchain")
ret.append(all_blocks[hh])
return ret
async def get_block_record(self, header_hash: bytes32) -> Optional[BlockRecord]:
cursor = await self.db.execute(
"SELECT block from block_records WHERE header_hash=?",
(header_hash.hex(),),
)
row = await cursor.fetchone()
await cursor.close()
if row is not None:
return BlockRecord.from_bytes(row[0])
return None
async def get_block_records_in_range(
self,
start: int,
stop: int,
) -> Dict[bytes32, BlockRecord]:
"""
Returns a dictionary with all blocks in range between start and stop
if present.
"""
formatted_str = f"SELECT header_hash, block from block_records WHERE height >= {start} and height <= {stop}"
cursor = await self.db.execute(formatted_str)
rows = await cursor.fetchall()
await cursor.close()
ret: Dict[bytes32, BlockRecord] = {}
for row in rows:
header_hash = bytes.fromhex(row[0])
ret[header_hash] = BlockRecord.from_bytes(row[1])
return ret
async def get_block_records_close_to_peak(
self, blocks_n: int
) -> Tuple[Dict[bytes32, BlockRecord], Optional[bytes32]]:
"""
Returns a dictionary with all blocks that have height >= peak height - blocks_n, as well as the
peak header hash.
"""
res = await self.db.execute("SELECT * from block_records WHERE is_peak = 1")
peak_row = await res.fetchone()
await res.close()
if peak_row is None:
return {}, None
formatted_str = f"SELECT header_hash, block from block_records WHERE height >= {peak_row[2] - blocks_n}"
cursor = await self.db.execute(formatted_str)
rows = await cursor.fetchall()
await cursor.close()
ret: Dict[bytes32, BlockRecord] = {}
for row in rows:
header_hash = bytes.fromhex(row[0])
ret[header_hash] = BlockRecord.from_bytes(row[1])
return ret, bytes.fromhex(peak_row[0])
async def get_peak_height_dicts(self) -> Tuple[Dict[uint32, bytes32], Dict[uint32, SubEpochSummary]]:
"""
Returns a dictionary with all blocks, as well as the header hash of the peak,
if present.
"""
res = await self.db.execute("SELECT * from block_records WHERE is_peak = 1")
row = await res.fetchone()
await res.close()
if row is None:
return {}, {}
peak: bytes32 = bytes.fromhex(row[0])
cursor = await self.db.execute("SELECT header_hash,prev_hash,height,sub_epoch_summary from block_records")
rows = await cursor.fetchall()
await cursor.close()
hash_to_prev_hash: Dict[bytes32, bytes32] = {}
hash_to_height: Dict[bytes32, uint32] = {}
hash_to_summary: Dict[bytes32, SubEpochSummary] = {}
for row in rows:
hash_to_prev_hash[bytes.fromhex(row[0])] = bytes.fromhex(row[1])
hash_to_height[bytes.fromhex(row[0])] = row[2]
if row[3] is not None:
hash_to_summary[bytes.fromhex(row[0])] = SubEpochSummary.from_bytes(row[3])
height_to_hash: Dict[uint32, bytes32] = {}
sub_epoch_summaries: Dict[uint32, SubEpochSummary] = {}
curr_header_hash = peak
curr_height = hash_to_height[curr_header_hash]
while True:
height_to_hash[curr_height] = curr_header_hash
if curr_header_hash in hash_to_summary:
sub_epoch_summaries[curr_height] = hash_to_summary[curr_header_hash]
if curr_height == 0:
break
curr_header_hash = hash_to_prev_hash[curr_header_hash]
curr_height = hash_to_height[curr_header_hash]
return height_to_hash, sub_epoch_summaries
async def set_peak(self, header_hash: bytes32) -> None:
# We need to be in a sqlite transaction here.
# Note: we do not commit this to the database yet, as we need to also change the coin store
cursor_1 = await self.db.execute("UPDATE block_records SET is_peak=0 WHERE is_peak=1")
await cursor_1.close()
cursor_2 = await self.db.execute(
"UPDATE block_records SET is_peak=1 WHERE header_hash=?",
(header_hash.hex(),),
)
await cursor_2.close()
async def is_fully_compactified(self, header_hash: bytes32) -> Optional[bool]:
cursor = await self.db.execute(
"SELECT is_fully_compactified from full_blocks WHERE header_hash=?", (header_hash.hex(),)
)
row = await cursor.fetchone()
await cursor.close()
if row is None:
return None
return bool(row[0])
async def get_random_not_compactified(self, number: int) -> List[int]:
# Since orphan blocks do not get compactified, we need to check whether all blocks with a
# certain height are not compact. And if we do have compact orphan blocks, then all that
# happens is that the occasional chain block stays uncompact - not ideal, but harmless.
cursor = await self.db.execute(
f"SELECT height FROM full_blocks GROUP BY height HAVING sum(is_fully_compactified)=0 "
f"ORDER BY RANDOM() LIMIT {number}"
)
rows = await cursor.fetchall()
await cursor.close()
heights = []
for row in rows:
heights.append(int(row[0]))
return heights
|
the-stack_106_26624 | import cv2
import time
import mediapipe as mp
import autopy
import numpy as np
import math
#####################################
width_cam, height_cam = 640, 480
frame_reduction = 100
smoothen = 3
#####################################
p_time = 0
p_loca_x, p_loca_y = 0, 0
cap = cv2.VideoCapture(0)
cap.set(3, height_cam)
cap.set(4, width_cam)
mp_hand = mp.solutions.hands
hand = mp_hand.Hands(max_num_hands=1)
mp_draw = mp.solutions.drawing_utils
width_screen, height_screen = autopy.screen.size()
while True:
# Draw Hand Landmarks
success, img = cap.read()
img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
result = hand.process(img_rgb)
if result.multi_hand_landmarks:
lm_list = []
x_list = []
y_list = []
for hand_lm in result.multi_hand_landmarks:
for id, lm in enumerate(hand_lm.landmark):
height, width, channel = img.shape
x, y = int(lm.x * width), int(lm.y * height)
x_list.append(x)
y_list.append(y)
lm_list.append([id, x, y])
mp_draw.draw_landmarks(img, hand_lm, mp_hand.HAND_CONNECTIONS)
x_min, x_max = min(x_list), max(x_list)
y_min, y_max = min(y_list), max(y_list)
cv2.rectangle(
img, (x_min - 20, y_min - 20),
(x_max + 20, y_max + 20),
(0, 255, 0), 2
)
# print(lm_list)
if len(lm_list) > 15:
x1, y1 = lm_list[8][1:]
x2, y2 = lm_list[12][1:]
# Frame Reduction
cv2.rectangle(img, (frame_reduction, frame_reduction),
(width_cam - frame_reduction, height_cam - frame_reduction),
(255, 255, 0), 3)
# Moving Mode - Index finger Up
if y1 < lm_list[6][2] and y2 > lm_list[10][2]:
# print("Index Finger Up")
# Convert Coordinates into mouse Coordinates
x3 = np.interp(x1, (frame_reduction, width_cam - frame_reduction), (0, width_screen))
y3 = np.interp(y1, (frame_reduction, height_cam - frame_reduction), (0, height_screen))
# Smoothening
c_loca_x = p_loca_x + (x3 - p_loca_x) / smoothen
c_loca_y = p_loca_y + (y3 - p_loca_y) / smoothen
# Move Mouse
autopy.mouse.move(width_screen - c_loca_x, c_loca_y)
cv2.circle(
img, (x1, y1), 10,
(255, 0, 255), cv2.FILLED
)
p_loca_x, p_loca_y = c_loca_x, c_loca_y
# Selection Mode - Index and Middle fingers are Up
elif y1 < lm_list[6][2] and y2 < lm_list[10][2]:
# print("Index and Middle fingers are Up")
# Find Length between Index and middle finger
length = math.hypot(x2 - x1, y2 - y1)
# print(length)
# If length < 32 - Mouse Click
if length < 32:
cv2.circle(
img, (x1, y1), 10,
(0, 255, 0), cv2.FILLED
)
autopy.mouse.click()
# Frame Per Sec
c_time = time.time()
fps = 1 / (c_time - p_time)
p_time = c_time
cv2.putText(
img, f'FPS: {int(fps)}', (10, 50),
cv2.FONT_HERSHEY_PLAIN, 2,
(255, 0, 0), 2
)
cv2.imshow("Image", img)
cv2.waitKey(1) |
the-stack_106_26626 | """Use the EPA crosswalk to connect EPA units to EIA generators and other data.
A major use case for this dataset is to identify subplants within plant_ids,
which are the smallest coherent units for aggregation.
Despite the name, plant_id refers to a legal entity that often contains
multiple distinct power plants, even of different technology or fuel types.
EPA CEMS data combines information from several parts of a power plant:
* emissions from smokestacks
* fuel use from combustors
* electricty production from generators
But smokestacks, combustors, and generators can be connected in
complex, many-to-many relationships. This complexity makes attribution difficult for,
as an example, allocating pollution to energy producers.
Furthermore, heterogeneity within plant_ids make aggregation
to the parent entity difficult or inappropriate.
But by analyzing the relationships between combustors and generators,
as provided in the EPA/EIA crosswalk, we can identify distinct power plants.
These are the smallest coherent units of aggregation.
In graph analysis terminology, the crosswalk is a list of edges between nodes
(combustors and generators) in a bipartite graph. The networkx python package provides
functions to analyze this edge list and extract disjoint subgraphs (groups of combustors
and generators that are connected to each other). These are the distinct power plants.
To avoid a name collision with plant_id, we term these collections 'subplants', and
identify them with a subplant_id that is unique within each plant_id. Subplants are thus
identified with the composite key (plant_id, subplant_id).
Through this analysis, we found that 56% of plant_ids contain multiple distinct
subplants, and 11% contain subplants with different technology types, such as a gas
boiler and gas turbine (not in a combined cycle).
Usage Example:
epacems = pudl.output.epacems.epacems(states=['ID']) # small subset for quick test
epa_crosswalk_df = pudl.output.epacems.epa_crosswalk()
filtered_crosswalk = filter_crosswalk(epa_crosswalk_df, epacems)
crosswalk_with_subplant_ids = make_subplant_ids(filtered_crosswalk)
"""
from typing import Union
import dask.dataframe as dd
import networkx as nx
import pandas as pd
def _get_unique_keys(epacems: Union[pd.DataFrame, dd.DataFrame]) -> pd.DataFrame:
"""Get unique unit IDs from CEMS data.
Args:
epacems (Union[pd.DataFrame, dd.DataFrame]): epacems dataset from pudl.output.epacems.epacems
Returns:
pd.DataFrame: unique keys from the epacems dataset
"""
# The purpose of this function is mostly to resolve the
# ambiguity between dask and pandas dataframes
ids = epacems[["plant_id_eia", "unitid", "unit_id_epa"]].drop_duplicates()
if isinstance(epacems, dd.DataFrame):
ids = ids.compute()
return ids
def filter_crosswalk_by_epacems(
crosswalk: pd.DataFrame, epacems: Union[pd.DataFrame, dd.DataFrame]
) -> pd.DataFrame:
"""Inner join unique CEMS units with the EPA crosswalk.
This is essentially an empirical filter on EPA units. Instead of filtering by
construction/retirement dates in the crosswalk (thus assuming they are accurate),
use the presence/absence of CEMS data to filter the units.
Args:
crosswalk: the EPA crosswalk, as from pudl.output.epacems.epa_crosswalk()
unique_epacems_ids (pd.DataFrame): unique ids from _get_unique_keys
Returns:
The inner join of the EPA crosswalk and unique epacems units. Adds
the global ID column unit_id_epa.
"""
unique_epacems_ids = _get_unique_keys(epacems)
key_map = unique_epacems_ids.merge(
crosswalk,
left_on=["plant_id_eia", "unitid"],
right_on=["CAMD_PLANT_ID", "CAMD_UNIT_ID"],
how="inner",
)
return key_map
def filter_out_unmatched(crosswalk: pd.DataFrame) -> pd.DataFrame:
"""Remove unmatched or excluded (non-exporting) units.
Unmatched rows are limitations of the completeness of the EPA crosswalk itself, not of PUDL.
Args:
crosswalk (pd.DataFrame): the EPA crosswalk, as from pudl.output.epacems.epa_crosswalk()
Returns:
pd.DataFrame: the EPA crosswalk with unmatched units removed
"""
bad = crosswalk["MATCH_TYPE_GEN"].isin({"CAMD Unmatched", "Manual CAMD Excluded"})
return crosswalk.loc[~bad].copy()
def filter_out_boiler_rows(crosswalk: pd.DataFrame) -> pd.DataFrame:
"""Remove rows that represent graph edges between generators and boilers.
Args:
crosswalk (pd.DataFrame): the EPA crosswalk, as from pudl.output.epacems.epa_crosswalk()
Returns:
pd.DataFrame: the EPA crosswalk with boiler rows (many/one-to-many) removed
"""
crosswalk = crosswalk.drop_duplicates(
subset=["CAMD_PLANT_ID", "CAMD_UNIT_ID", "EIA_GENERATOR_ID"]
)
return crosswalk
def _prep_for_networkx(crosswalk: pd.DataFrame) -> pd.DataFrame:
"""Make surrogate keys for combustors and generators.
Args:
crosswalk (pd.DataFrame): EPA crosswalk, as from pudl.output.epacems.epa_crosswalk()
Returns:
pd.DataFrame: copy of EPA crosswalk with new surrogate ID columns 'combustor_id' and 'generator_id'
"""
prepped = crosswalk.copy()
# networkx can't handle composite keys, so make surrogates
prepped["combustor_id"] = prepped.groupby(
by=["CAMD_PLANT_ID", "CAMD_UNIT_ID"]
).ngroup()
# node IDs can't overlap so add (max + 1)
prepped["generator_id"] = (
prepped.groupby(by=["CAMD_PLANT_ID", "EIA_GENERATOR_ID"]).ngroup()
+ prepped["combustor_id"].max()
+ 1
)
return prepped
def _subplant_ids_from_prepped_crosswalk(prepped: pd.DataFrame) -> pd.DataFrame:
"""Use networkx graph analysis to create global subplant IDs from a preprocessed crosswalk edge list.
Args:
prepped (pd.DataFrame): an EPA crosswalk that has passed through _prep_for_networkx()
Returns:
pd.DataFrame: copy of EPA crosswalk plus new column 'global_subplant_id'
"""
graph = nx.from_pandas_edgelist(
prepped,
source="combustor_id",
target="generator_id",
edge_attr=True,
)
for i, node_set in enumerate(nx.connected_components(graph)):
subgraph = graph.subgraph(node_set)
assert nx.algorithms.bipartite.is_bipartite(
subgraph
), f"non-bipartite: i={i}, node_set={node_set}"
nx.set_edge_attributes(subgraph, name="global_subplant_id", values=i)
return nx.to_pandas_edgelist(graph)
def _convert_global_id_to_composite_id(
crosswalk_with_ids: pd.DataFrame,
) -> pd.DataFrame:
"""Convert global_subplant_id to an equivalent composite key (CAMD_PLANT_ID, subplant_id).
The composite key will be much more stable (though not fully stable!) in time.
The global ID changes if ANY unit or generator changes, whereas the
compound key only changes if units/generators change within that specific plant.
A global ID could also tempt users into using it as a crutch, even though it isn't stable.
A compound key should discourage that behavior.
Args:
crosswalk_with_ids (pd.DataFrame): crosswalk with global_subplant_id, as from _subplant_ids_from_prepped_crosswalk()
Raises:
ValueError: if crosswalk_with_ids has a MultiIndex
Returns:
pd.DataFrame: copy of crosswalk_with_ids with an added column: 'subplant_id'
"""
if isinstance(crosswalk_with_ids.index, pd.MultiIndex):
raise ValueError(
f"Input crosswalk must have single level index. Given levels: {crosswalk_with_ids.index.names}"
)
reindexed = crosswalk_with_ids.reset_index() # copy
idx_name = crosswalk_with_ids.index.name
if idx_name is None:
# Indices with no name (None) are set to a pandas default name ('index'), which
# could (though probably won't) change.
idx_col = reindexed.columns.symmetric_difference(crosswalk_with_ids.columns)[
0
] # get index name
else:
idx_col = idx_name
composite_key: pd.Series = reindexed.groupby("CAMD_PLANT_ID", as_index=False).apply(
lambda x: x.groupby("global_subplant_id").ngroup()
)
# Recombine. Could use index join but I chose to reindex, sort and assign.
# Errors like mismatched length will raise exceptions, which is good.
# drop the outer group, leave the reindexed row index
composite_key.reset_index(level=0, drop=True, inplace=True)
composite_key.sort_index(inplace=True) # put back in same order as reindexed
reindexed["subplant_id"] = composite_key
# restore original index
reindexed.set_index(idx_col, inplace=True) # restore values
reindexed.index.rename(idx_name, inplace=True) # restore original name
return reindexed
def filter_crosswalk(
crosswalk: pd.DataFrame, epacems: Union[pd.DataFrame, dd.DataFrame]
) -> pd.DataFrame:
"""Remove crosswalk rows that do not correspond to an EIA facility or are duplicated due to many-to-many boiler relationships.
Args:
crosswalk (pd.DataFrame): The EPA/EIA crosswalk, as from pudl.output.epacems.epa_crosswalk()
epacems (Union[pd.DataFrame, dd.DataFrame]): Emissions data. Must contain columns named ["plant_id_eia", "unitid", "unit_id_epa"]
Returns:
pd.DataFrame: A filtered copy of EPA crosswalk
"""
filtered_crosswalk = filter_out_unmatched(crosswalk)
filtered_crosswalk = filter_out_boiler_rows(filtered_crosswalk)
key_map = filter_crosswalk_by_epacems(filtered_crosswalk, epacems)
return key_map
def make_subplant_ids(crosswalk: pd.DataFrame) -> pd.DataFrame:
"""Identify sub-plants in the EPA/EIA crosswalk graph. Any row filtering should be done before this step.
Usage Example:
epacems = pudl.output.epacems.epacems(states=['ID']) # small subset for quick test
epa_crosswalk_df = pudl.output.epacems.epa_crosswalk()
filtered_crosswalk = filter_crosswalk(epa_crosswalk_df, epacems)
crosswalk_with_subplant_ids = make_subplant_ids(filtered_crosswalk)
Args:
crosswalk (pd.DataFrame): The EPA/EIA crosswalk, as from pudl.output.epacems.epa_crosswalk()
Returns:
pd.DataFrame: An edge list connecting EPA units to EIA generators, with connected pieces issued a subplant_id
"""
edge_list = _prep_for_networkx(crosswalk)
edge_list = _subplant_ids_from_prepped_crosswalk(edge_list)
edge_list = _convert_global_id_to_composite_id(edge_list)
column_order = ["subplant_id"] + list(crosswalk.columns)
return edge_list[column_order] # reorder and drop global_subplant_id
|
the-stack_106_26627 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Name : FedAvg_tutorial.py
# Time : 2020/3/3 13:55
# Author : Fu Yao
# Mail : [email protected]
"""
This file is to show how to use this framework in general ML scenarios.
Because this model (Linear Regression) is super simple, multi-process FL
is slower then single process.
Multi-process FL, however, is useful in complex model,
when client's updates cost more time than creating process.
Though we implemented the multi-process FL, due to the dumplication of dataset,
it's still impractical to use multi-process when the number of clients is to large.
Because of the concurrent execution, the result of multi-process FL may vary.
"""
from torch import nn, optim
import torch.multiprocessing as mp
from torch.utils.data import DataLoader, TensorDataset
import numpy as np
import time
from sklearn.datasets import load_boston
from tests.models import BostonLR
from tests.settings import device, args
from FLsim.federated_learning import SerialFedAvg, ParallelFedAvg
from tests.utils import *
def single_process(train_data, test_loader):
# Fix random seed then the result should be same
torch.manual_seed(args.seed)
np.random.seed(args.seed)
# Construct the SERIAL federated model
FL = SerialFedAvg(BostonLR, device, args.client_count, optim.SGD, nn.MSELoss)
"""
A list of client id, whose length equals to training data count,
should be given, which means the owner of each data.
If you want to test your algorithm on Non-IID dataset,
you need to change the clients below into any distribution.
"""
# IID dataset
clients = [i % args.client_count for i in range(len(train_data))]
# Construct the federated dataset
FL.federated_data(train_data, clients, args.batch_size)
# Single process FL
start = time.time()
record_loss = []
model = BostonLR().to(device)
state = model.state_dict().copy()
for epoch in range(args.epochs):
state, loss = FL.global_update(state, lr=args.lr, E=args.E)
print("Epoch {}\tLoss: {}".format(epoch, loss))
record_loss.append(loss)
# Evaluate the trained model
model.load_state_dict(state.copy())
print("Traing time: {}".format(time.time() - start))
criterion = nn.MSELoss(reduction="sum")
loss = eval(device, model, test_loader, criterion)
print("Loss on the test dataset: {}".format(loss))
def multi_process(train_data, test_loader):
# Test multi-process FL
torch.manual_seed(args.seed)
np.random.seed(args.seed)
"""manager is required"""
manager = mp.Manager()
FL = ParallelFedAvg(BostonLR, device, args.client_count, optim.SGD, nn.MSELoss, manager)
"""
A list of client id, whose length equals to training data count,
should be given, which means the owner of each data.
If you want to test your algorithm on Non-IID dataset,
you need to change the clients below into any distribution.
"""
# IID dataset
clients = [i % args.client_count for i in range(len(train_data))]
FL.federated_data(train_data, clients, args.batch_size)
# Start
start = time.time()
model = BostonLR().to(device)
state = model.state_dict().copy()
for epoch in range(args.epochs):
state, loss = FL.global_update(state, args.lr, args.E)
print("Epoch {}\tLoss: {}".format(epoch, loss))
# Evaluate the trained model
model.load_state_dict(state.copy())
print("Traing time: {}".format(time.time() - start))
criterion = nn.MSELoss(reduction="sum")
loss = eval(device, model, test_loader, criterion)
print("Loss on the test dataset: {}".format(loss))
if __name__ == '__main__':
"""Load any dataset"""
# Load Boston dataset
X, y = load_boston(return_X_y=True)
# Normalize
X = (X - X.mean(axis=0, keepdims=True)) / X.std(axis=0, keepdims=True)
# Convert Numpy array to Torch tensor
X = torch.from_numpy(X).type(torch.float).to(device)
y = torch.from_numpy(y).type(torch.float).to(device)
training_data_count = 500
"""You need to construct a dataset whose type is torch.utils.data.Dataset"""
train_data = TensorDataset(X[:training_data_count], y[:training_data_count])
test_loader = DataLoader(TensorDataset(X[training_data_count:], y[training_data_count:]),
batch_size=args.batch_size, shuffle=True)
# Compare single and multi process FL
single_process(train_data, test_loader)
multi_process(train_data, test_loader)
|
the-stack_106_26628 | """
Module difflib -- helpers for computing deltas between objects.
Function get_close_matches(word, possibilities, n=3, cutoff=0.6):
Use SequenceMatcher to return list of the best "good enough" matches.
Function context_diff(a, b):
For two lists of strings, return a delta in context diff format.
Function ndiff(a, b):
Return a delta: the difference between `a` and `b` (lists of strings).
Function restore(delta, which):
Return one of the two sequences that generated an ndiff delta.
Function unified_diff(a, b):
For two lists of strings, return a delta in unified diff format.
Class SequenceMatcher:
A flexible class for comparing pairs of sequences of any type.
Class Differ:
For producing human-readable deltas from sequences of lines of text.
Class HtmlDiff:
For producing HTML side by side comparison with change highlights.
"""
__all__ = ['get_close_matches', 'ndiff', 'restore', 'SequenceMatcher',
'Differ','IS_CHARACTER_JUNK', 'IS_LINE_JUNK', 'context_diff',
'unified_diff', 'HtmlDiff', 'Match']
import heapq
# from collections import namedtuple as _namedtuple
# from functools import reduce
import functools
from functools import reduce
reduce = functools.reduce
import operator
_itemgetter = operator.itemgetter
_property = property
_tuple = tuple
def setdefault(d, k, default=None):
if k not in d:
d[k] = default
return d[k]
# Match = _namedtuple('Match', 'a b size')
class Match(tuple):
'Match(a, b, size)'
__slots__ = ()
_fields = ('a', 'b', 'size')
def __new__(_cls, a, b, size):
'Create new instance of Match(a, b, size)'
return _tuple.__new__(_cls, (a, b, size))
# @classmethod
def _make(cls, iterable, new=tuple.__new__, len=len):
'Make a new Match object from a sequence or iterable'
result = new(cls, iterable)
if len(result) != 3:
raise TypeError('Expected 3 arguments, got %d' % len(result))
return result
_make = classmethod(_make)
def __repr__(self):
'Return a nicely formatted representation string'
return 'Match(a=%r, b=%r, size=%r)' % self
def _asdict(self):
'Return a new OrderedDict which maps field names to their values'
return OrderedDict(list(zip(self._fields, self)))
def _replace(_self, **kwds):
'Return a new Match object replacing specified fields with new values'
result = _self._make(list(map(kwds.pop, ('a', 'b', 'size'), _self)))
if kwds:
raise ValueError('Got unexpected field names: %r' % list(kwds.keys()))
return result
def __getnewargs__(self):
'Return self as a plain tuple. Used by copy and pickle.'
return tuple(self)
__dict__ = _property(_asdict)
def __getstate__(self):
'Exclude the OrderedDict from pickling'
pass
a = _property(_itemgetter(0), doc='Alias for field number 0')
b = _property(_itemgetter(1), doc='Alias for field number 1')
size = _property(_itemgetter(2), doc='Alias for field number 2')
def _calculate_ratio(matches, length):
if length:
return 2.0 * matches / length
return 1.0
class SequenceMatcher(object):
"""
SequenceMatcher is a flexible class for comparing pairs of sequences of
any type, so long as the sequence elements are hashable. The basic
algorithm predates, and is a little fancier than, an algorithm
published in the late 1980's by Ratcliff and Obershelp under the
hyperbolic name "gestalt pattern matching". The basic idea is to find
the longest contiguous matching subsequence that contains no "junk"
elements (R-O doesn't address junk). The same idea is then applied
recursively to the pieces of the sequences to the left and to the right
of the matching subsequence. This does not yield minimal edit
sequences, but does tend to yield matches that "look right" to people.
SequenceMatcher tries to compute a "human-friendly diff" between two
sequences. Unlike e.g. UNIX(tm) diff, the fundamental notion is the
longest *contiguous* & junk-free matching subsequence. That's what
catches peoples' eyes. The Windows(tm) windiff has another interesting
notion, pairing up elements that appear uniquely in each sequence.
That, and the method here, appear to yield more intuitive difference
reports than does diff. This method appears to be the least vulnerable
to synching up on blocks of "junk lines", though (like blank lines in
ordinary text files, or maybe "<P>" lines in HTML files). That may be
because this is the only method of the 3 that has a *concept* of
"junk" <wink>.
Example, comparing two strings, and considering blanks to be "junk":
>>> s = SequenceMatcher(lambda x: x == " ",
... "private Thread currentThread;",
... "private volatile Thread currentThread;")
>>>
.ratio() returns a float in [0, 1], measuring the "similarity" of the
sequences. As a rule of thumb, a .ratio() value over 0.6 means the
sequences are close matches:
>>> print round(s.ratio(), 3)
0.866
>>>
If you're only interested in where the sequences match,
.get_matching_blocks() is handy:
>>> for block in s.get_matching_blocks():
... print "a[%d] and b[%d] match for %d elements" % block
a[0] and b[0] match for 8 elements
a[8] and b[17] match for 21 elements
a[29] and b[38] match for 0 elements
Note that the last tuple returned by .get_matching_blocks() is always a
dummy, (len(a), len(b), 0), and this is the only case in which the last
tuple element (number of elements matched) is 0.
If you want to know how to change the first sequence into the second,
use .get_opcodes():
>>> for opcode in s.get_opcodes():
... print "%6s a[%d:%d] b[%d:%d]" % opcode
equal a[0:8] b[0:8]
insert a[8:8] b[8:17]
equal a[8:29] b[17:38]
See the Differ class for a fancy human-friendly file differencer, which
uses SequenceMatcher both to compare sequences of lines, and to compare
sequences of characters within similar (near-matching) lines.
See also function get_close_matches() in this module, which shows how
simple code building on SequenceMatcher can be used to do useful work.
Timing: Basic R-O is cubic time worst case and quadratic time expected
case. SequenceMatcher is quadratic time for the worst case and has
expected-case behavior dependent in a complicated way on how many
elements the sequences have in common; best case time is linear.
Methods:
__init__(isjunk=None, a='', b='')
Construct a SequenceMatcher.
set_seqs(a, b)
Set the two sequences to be compared.
set_seq1(a)
Set the first sequence to be compared.
set_seq2(b)
Set the second sequence to be compared.
find_longest_match(alo, ahi, blo, bhi)
Find longest matching block in a[alo:ahi] and b[blo:bhi].
get_matching_blocks()
Return list of triples describing matching subsequences.
get_opcodes()
Return list of 5-tuples describing how to turn a into b.
ratio()
Return a measure of the sequences' similarity (float in [0,1]).
quick_ratio()
Return an upper bound on .ratio() relatively quickly.
real_quick_ratio()
Return an upper bound on ratio() very quickly.
"""
def __init__(self, isjunk=None, a='', b='', autojunk=True):
"""Construct a SequenceMatcher.
Optional arg isjunk is None (the default), or a one-argument
function that takes a sequence element and returns true iff the
element is junk. None is equivalent to passing "lambda x: 0", i.e.
no elements are considered to be junk. For example, pass
lambda x: x in " \\t"
if you're comparing lines as sequences of characters, and don't
want to synch up on blanks or hard tabs.
Optional arg a is the first of two sequences to be compared. By
default, an empty string. The elements of a must be hashable. See
also .set_seqs() and .set_seq1().
Optional arg b is the second of two sequences to be compared. By
default, an empty string. The elements of b must be hashable. See
also .set_seqs() and .set_seq2().
Optional arg autojunk should be set to False to disable the
"automatic junk heuristic" that treats popular elements as junk
(see module documentation for more information).
"""
# Members:
# a
# first sequence
# b
# second sequence; differences are computed as "what do
# we need to do to 'a' to change it into 'b'?"
# b2j
# for x in b, b2j[x] is a list of the indices (into b)
# at which x appears; junk elements do not appear
# fullbcount
# for x in b, fullbcount[x] == the number of times x
# appears in b; only materialized if really needed (used
# only for computing quick_ratio())
# matching_blocks
# a list of (i, j, k) triples, where a[i:i+k] == b[j:j+k];
# ascending & non-overlapping in i and in j; terminated by
# a dummy (len(a), len(b), 0) sentinel
# opcodes
# a list of (tag, i1, i2, j1, j2) tuples, where tag is
# one of
# 'replace' a[i1:i2] should be replaced by b[j1:j2]
# 'delete' a[i1:i2] should be deleted
# 'insert' b[j1:j2] should be inserted
# 'equal' a[i1:i2] == b[j1:j2]
# isjunk
# a user-supplied function taking a sequence element and
# returning true iff the element is "junk" -- this has
# subtle but helpful effects on the algorithm, which I'll
# get around to writing up someday <0.9 wink>.
# DON'T USE! Only __chain_b uses this. Use isbjunk.
# isbjunk
# for x in b, isbjunk(x) == isjunk(x) but much faster;
# it's really the __contains__ method of a hidden dict.
# DOES NOT WORK for x in a!
# isbpopular
# for x in b, isbpopular(x) is true iff b is reasonably long
# (at least 200 elements) and x accounts for more than 1 + 1% of
# its elements (when autojunk is enabled).
# DOES NOT WORK for x in a!
self.isjunk = isjunk
self.a = self.b = None
self.autojunk = autojunk
self.set_seqs(a, b)
def set_seqs(self, a, b):
"""Set the two sequences to be compared.
>>> s = SequenceMatcher()
>>> s.set_seqs("abcd", "bcde")
>>> s.ratio()
0.75
"""
self.set_seq1(a)
self.set_seq2(b)
def set_seq1(self, a):
"""Set the first sequence to be compared.
The second sequence to be compared is not changed.
>>> s = SequenceMatcher(None, "abcd", "bcde")
>>> s.ratio()
0.75
>>> s.set_seq1("bcde")
>>> s.ratio()
1.0
>>>
SequenceMatcher computes and caches detailed information about the
second sequence, so if you want to compare one sequence S against
many sequences, use .set_seq2(S) once and call .set_seq1(x)
repeatedly for each of the other sequences.
See also set_seqs() and set_seq2().
"""
if a is self.a:
return
self.a = a
self.matching_blocks = self.opcodes = None
def set_seq2(self, b):
"""Set the second sequence to be compared.
The first sequence to be compared is not changed.
>>> s = SequenceMatcher(None, "abcd", "bcde")
>>> s.ratio()
0.75
>>> s.set_seq2("abcd")
>>> s.ratio()
1.0
>>>
SequenceMatcher computes and caches detailed information about the
second sequence, so if you want to compare one sequence S against
many sequences, use .set_seq2(S) once and call .set_seq1(x)
repeatedly for each of the other sequences.
See also set_seqs() and set_seq1().
"""
if b is self.b:
return
self.b = b
self.matching_blocks = self.opcodes = None
self.fullbcount = None
self.__chain_b()
# For each element x in b, set b2j[x] to a list of the indices in
# b where x appears; the indices are in increasing order; note that
# the number of times x appears in b is len(b2j[x]) ...
# when self.isjunk is defined, junk elements don't show up in this
# map at all, which stops the central find_longest_match method
# from starting any matching block at a junk element ...
# also creates the fast isbjunk function ...
# b2j also does not contain entries for "popular" elements, meaning
# elements that account for more than 1 + 1% of the total elements, and
# when the sequence is reasonably large (>= 200 elements); this can
# be viewed as an adaptive notion of semi-junk, and yields an enormous
# speedup when, e.g., comparing program files with hundreds of
# instances of "return NULL;" ...
# note that this is only called when b changes; so for cross-product
# kinds of matches, it's best to call set_seq2 once, then set_seq1
# repeatedly
def __chain_b(self):
# Because isjunk is a user-defined (not C) function, and we test
# for junk a LOT, it's important to minimize the number of calls.
# Before the tricks described here, __chain_b was by far the most
# time-consuming routine in the whole module! If anyone sees
# Jim Roskind, thank him again for profile.py -- I never would
# have guessed that.
# The first trick is to build b2j ignoring the possibility
# of junk. I.e., we don't call isjunk at all yet. Throwing
# out the junk later is much cheaper than building b2j "right"
# from the start.
b = self.b
self.b2j = b2j = {}
for i, elt in enumerate(b):
indices = setdefault(b2j, elt, [])
# indices = b2j.setdefault(elt, [])
indices.append(i)
# Purge junk elements
junk = set()
isjunk = self.isjunk
if isjunk:
for elt in list(b2j.keys()): # using list() since b2j is modified
if isjunk(elt):
junk.add(elt)
del b2j[elt]
# Purge popular elements that are not junk
popular = set()
n = len(b)
if self.autojunk and n >= 200:
ntest = n // 100 + 1
for elt, idxs in list(b2j.items()):
if len(idxs) > ntest:
popular.add(elt)
del b2j[elt]
# Now for x in b, isjunk(x) == x in junk, but the latter is much faster.
# Sicne the number of *unique* junk elements is probably small, the
# memory burden of keeping this set alive is likely trivial compared to
# the size of b2j.
self.isbjunk = junk.__contains__
self.isbpopular = popular.__contains__
def find_longest_match(self, alo, ahi, blo, bhi):
"""Find longest matching block in a[alo:ahi] and b[blo:bhi].
If isjunk is not defined:
Return (i,j,k) such that a[i:i+k] is equal to b[j:j+k], where
alo <= i <= i+k <= ahi
blo <= j <= j+k <= bhi
and for all (i',j',k') meeting those conditions,
k >= k'
i <= i'
and if i == i', j <= j'
In other words, of all maximal matching blocks, return one that
starts earliest in a, and of all those maximal matching blocks that
start earliest in a, return the one that starts earliest in b.
>>> s = SequenceMatcher(None, " abcd", "abcd abcd")
>>> s.find_longest_match(0, 5, 0, 9)
Match(a=0, b=4, size=5)
If isjunk is defined, first the longest matching block is
determined as above, but with the additional restriction that no
junk element appears in the block. Then that block is extended as
far as possible by matching (only) junk elements on both sides. So
the resulting block never matches on junk except as identical junk
happens to be adjacent to an "interesting" match.
Here's the same example as before, but considering blanks to be
junk. That prevents " abcd" from matching the " abcd" at the tail
end of the second sequence directly. Instead only the "abcd" can
match, and matches the leftmost "abcd" in the second sequence:
>>> s = SequenceMatcher(lambda x: x==" ", " abcd", "abcd abcd")
>>> s.find_longest_match(0, 5, 0, 9)
Match(a=1, b=0, size=4)
If no blocks match, return (alo, blo, 0).
>>> s = SequenceMatcher(None, "ab", "c")
>>> s.find_longest_match(0, 2, 0, 1)
Match(a=0, b=0, size=0)
"""
# CAUTION: stripping common prefix or suffix would be incorrect.
# E.g.,
# ab
# acab
# Longest matching block is "ab", but if common prefix is
# stripped, it's "a" (tied with "b"). UNIX(tm) diff does so
# strip, so ends up claiming that ab is changed to acab by
# inserting "ca" in the middle. That's minimal but unintuitive:
# "it's obvious" that someone inserted "ac" at the front.
# Windiff ends up at the same place as diff, but by pairing up
# the unique 'b's and then matching the first two 'a's.
a, b, b2j, isbjunk = self.a, self.b, self.b2j, self.isbjunk
besti, bestj, bestsize = alo, blo, 0
# find longest junk-free match
# during an iteration of the loop, j2len[j] = length of longest
# junk-free match ending with a[i-1] and b[j]
j2len = {}
nothing = []
for i in range(alo, ahi):
# look at all instances of a[i] in b; note that because
# b2j has no junk keys, the loop is skipped if a[i] is junk
j2lenget = j2len.get
newj2len = {}
for j in b2j.get(a[i], nothing):
# a[i] matches b[j]
if j < blo:
continue
if j >= bhi:
break
k = newj2len[j] = j2lenget(j-1, 0) + 1
if k > bestsize:
besti, bestj, bestsize = i-k+1, j-k+1, k
j2len = newj2len
# Extend the best by non-junk elements on each end. In particular,
# "popular" non-junk elements aren't in b2j, which greatly speeds
# the inner loop above, but also means "the best" match so far
# doesn't contain any junk *or* popular non-junk elements.
while besti > alo and bestj > blo and \
not isbjunk(b[bestj-1]) and \
a[besti-1] == b[bestj-1]:
besti, bestj, bestsize = besti-1, bestj-1, bestsize+1
while besti+bestsize < ahi and bestj+bestsize < bhi and \
not isbjunk(b[bestj+bestsize]) and \
a[besti+bestsize] == b[bestj+bestsize]:
bestsize += 1
# Now that we have a wholly interesting match (albeit possibly
# empty!), we may as well suck up the matching junk on each
# side of it too. Can't think of a good reason not to, and it
# saves post-processing the (possibly considerable) expense of
# figuring out what to do with it. In the case of an empty
# interesting match, this is clearly the right thing to do,
# because no other kind of match is possible in the regions.
while besti > alo and bestj > blo and \
isbjunk(b[bestj-1]) and \
a[besti-1] == b[bestj-1]:
besti, bestj, bestsize = besti-1, bestj-1, bestsize+1
while besti+bestsize < ahi and bestj+bestsize < bhi and \
isbjunk(b[bestj+bestsize]) and \
a[besti+bestsize] == b[bestj+bestsize]:
bestsize = bestsize + 1
return Match(besti, bestj, bestsize)
def get_matching_blocks(self):
"""Return list of triples describing matching subsequences.
Each triple is of the form (i, j, n), and means that
a[i:i+n] == b[j:j+n]. The triples are monotonically increasing in
i and in j. New in Python 2.5, it's also guaranteed that if
(i, j, n) and (i', j', n') are adjacent triples in the list, and
the second is not the last triple in the list, then i+n != i' or
j+n != j'. IOW, adjacent triples never describe adjacent equal
blocks.
The last triple is a dummy, (len(a), len(b), 0), and is the only
triple with n==0.
>>> s = SequenceMatcher(None, "abxcd", "abcd")
>>> s.get_matching_blocks()
[Match(a=0, b=0, size=2), Match(a=3, b=2, size=2), Match(a=5, b=4, size=0)]
"""
if self.matching_blocks is not None:
return self.matching_blocks
la, lb = len(self.a), len(self.b)
# This is most naturally expressed as a recursive algorithm, but
# at least one user bumped into extreme use cases that exceeded
# the recursion limit on their box. So, now we maintain a list
# ('queue`) of blocks we still need to look at, and append partial
# results to `matching_blocks` in a loop; the matches are sorted
# at the end.
queue = [(0, la, 0, lb)]
matching_blocks = []
while queue:
alo, ahi, blo, bhi = queue.pop()
i, j, k = x = self.find_longest_match(alo, ahi, blo, bhi)
# a[alo:i] vs b[blo:j] unknown
# a[i:i+k] same as b[j:j+k]
# a[i+k:ahi] vs b[j+k:bhi] unknown
if k: # if k is 0, there was no matching block
matching_blocks.append(x)
if alo < i and blo < j:
queue.append((alo, i, blo, j))
if i+k < ahi and j+k < bhi:
queue.append((i+k, ahi, j+k, bhi))
matching_blocks.sort()
# It's possible that we have adjacent equal blocks in the
# matching_blocks list now. Starting with 2.5, this code was added
# to collapse them.
i1 = j1 = k1 = 0
non_adjacent = []
for i2, j2, k2 in matching_blocks:
# Is this block adjacent to i1, j1, k1?
if i1 + k1 == i2 and j1 + k1 == j2:
# Yes, so collapse them -- this just increases the length of
# the first block by the length of the second, and the first
# block so lengthened remains the block to compare against.
k1 += k2
else:
# Not adjacent. Remember the first block (k1==0 means it's
# the dummy we started with), and make the second block the
# new block to compare against.
if k1:
non_adjacent.append((i1, j1, k1))
i1, j1, k1 = i2, j2, k2
if k1:
non_adjacent.append((i1, j1, k1))
non_adjacent.append( (la, lb, 0) )
self.matching_blocks = list(map(Match._make, non_adjacent))
return self.matching_blocks
def get_opcodes(self):
"""Return list of 5-tuples describing how to turn a into b.
Each tuple is of the form (tag, i1, i2, j1, j2). The first tuple
has i1 == j1 == 0, and remaining tuples have i1 == the i2 from the
tuple preceding it, and likewise for j1 == the previous j2.
The tags are strings, with these meanings:
'replace': a[i1:i2] should be replaced by b[j1:j2]
'delete': a[i1:i2] should be deleted.
Note that j1==j2 in this case.
'insert': b[j1:j2] should be inserted at a[i1:i1].
Note that i1==i2 in this case.
'equal': a[i1:i2] == b[j1:j2]
>>> a = "qabxcd"
>>> b = "abycdf"
>>> s = SequenceMatcher(None, a, b)
>>> for tag, i1, i2, j1, j2 in s.get_opcodes():
... print ("%7s a[%d:%d] (%s) b[%d:%d] (%s)" %
... (tag, i1, i2, a[i1:i2], j1, j2, b[j1:j2]))
delete a[0:1] (q) b[0:0] ()
equal a[1:3] (ab) b[0:2] (ab)
replace a[3:4] (x) b[2:3] (y)
equal a[4:6] (cd) b[3:5] (cd)
insert a[6:6] () b[5:6] (f)
"""
if self.opcodes is not None:
return self.opcodes
i = j = 0
self.opcodes = answer = []
for ai, bj, size in self.get_matching_blocks():
# invariant: we've pumped out correct diffs to change
# a[:i] into b[:j], and the next matching block is
# a[ai:ai+size] == b[bj:bj+size]. So we need to pump
# out a diff to change a[i:ai] into b[j:bj], pump out
# the matching block, and move (i,j) beyond the match
tag = ''
if i < ai and j < bj:
tag = 'replace'
elif i < ai:
tag = 'delete'
elif j < bj:
tag = 'insert'
if tag:
answer.append( (tag, i, ai, j, bj) )
i, j = ai+size, bj+size
# the list of matching blocks is terminated by a
# sentinel with size 0
if size:
answer.append( ('equal', ai, i, bj, j) )
return answer
def get_grouped_opcodes(self, n=3):
""" Isolate change clusters by eliminating ranges with no changes.
Return a generator of groups with up to n lines of context.
Each group is in the same format as returned by get_opcodes().
>>> from pprint import pprint
>>> a = map(str, range(1,40))
>>> b = a[:]
>>> b[8:8] = ['i'] # Make an insertion
>>> b[20] += 'x' # Make a replacement
>>> b[23:28] = [] # Make a deletion
>>> b[30] += 'y' # Make another replacement
>>> pprint(list(SequenceMatcher(None,a,b).get_grouped_opcodes()))
[[('equal', 5, 8, 5, 8), ('insert', 8, 8, 8, 9), ('equal', 8, 11, 9, 12)],
[('equal', 16, 19, 17, 20),
('replace', 19, 20, 20, 21),
('equal', 20, 22, 21, 23),
('delete', 22, 27, 23, 23),
('equal', 27, 30, 23, 26)],
[('equal', 31, 34, 27, 30),
('replace', 34, 35, 30, 31),
('equal', 35, 38, 31, 34)]]
"""
codes = self.get_opcodes()
if not codes:
codes = [("equal", 0, 1, 0, 1)]
# Fixup leading and trailing groups if they show no changes.
if codes[0][0] == 'equal':
tag, i1, i2, j1, j2 = codes[0]
codes[0] = tag, max(i1, i2-n), i2, max(j1, j2-n), j2
if codes[-1][0] == 'equal':
tag, i1, i2, j1, j2 = codes[-1]
codes[-1] = tag, i1, min(i2, i1+n), j1, min(j2, j1+n)
nn = n + n
group = []
for tag, i1, i2, j1, j2 in codes:
# End the current group and start a new one whenever
# there is a large range with no changes.
if tag == 'equal' and i2-i1 > nn:
group.append((tag, i1, min(i2, i1+n), j1, min(j2, j1+n)))
yield group
group = []
i1, j1 = max(i1, i2-n), max(j1, j2-n)
group.append((tag, i1, i2, j1 ,j2))
if group and not (len(group)==1 and group[0][0] == 'equal'):
yield group
def ratio(self):
"""Return a measure of the sequences' similarity (float in [0,1]).
Where T is the total number of elements in both sequences, and
M is the number of matches, this is 2.0*M / T.
Note that this is 1 if the sequences are identical, and 0 if
they have nothing in common.
.ratio() is expensive to compute if you haven't already computed
.get_matching_blocks() or .get_opcodes(), in which case you may
want to try .quick_ratio() or .real_quick_ratio() first to get an
upper bound.
>>> s = SequenceMatcher(None, "abcd", "bcde")
>>> s.ratio()
0.75
>>> s.quick_ratio()
0.75
>>> s.real_quick_ratio()
1.0
"""
matches = reduce(lambda sum, triple: sum + triple[-1],
self.get_matching_blocks(), 0)
return _calculate_ratio(matches, len(self.a) + len(self.b))
def quick_ratio(self):
"""Return an upper bound on ratio() relatively quickly.
This isn't defined beyond that it is an upper bound on .ratio(), and
is faster to compute.
"""
# viewing a and b as multisets, set matches to the cardinality
# of their intersection; this counts the number of matches
# without regard to order, so is clearly an upper bound
if self.fullbcount is None:
self.fullbcount = fullbcount = {}
for elt in self.b:
fullbcount[elt] = fullbcount.get(elt, 0) + 1
fullbcount = self.fullbcount
# avail[x] is the number of times x appears in 'b' less the
# number of times we've seen it in 'a' so far ... kinda
avail = {}
availhas, matches = avail.__contains__, 0
for elt in self.a:
if availhas(elt):
numb = avail[elt]
else:
numb = fullbcount.get(elt, 0)
avail[elt] = numb - 1
if numb > 0:
matches = matches + 1
return _calculate_ratio(matches, len(self.a) + len(self.b))
def real_quick_ratio(self):
"""Return an upper bound on ratio() very quickly.
This isn't defined beyond that it is an upper bound on .ratio(), and
is faster to compute than either .ratio() or .quick_ratio().
"""
la, lb = len(self.a), len(self.b)
# can't have more matches than the number of elements in the
# shorter sequence
return _calculate_ratio(min(la, lb), la + lb)
def get_close_matches(word, possibilities, n=3, cutoff=0.6):
"""Use SequenceMatcher to return list of the best "good enough" matches.
word is a sequence for which close matches are desired (typically a
string).
possibilities is a list of sequences against which to match word
(typically a list of strings).
Optional arg n (default 3) is the maximum number of close matches to
return. n must be > 0.
Optional arg cutoff (default 0.6) is a float in [0, 1]. Possibilities
that don't score at least that similar to word are ignored.
The best (no more than n) matches among the possibilities are returned
in a list, sorted by similarity score, most similar first.
>>> get_close_matches("appel", ["ape", "apple", "peach", "puppy"])
['apple', 'ape']
>>> import keyword as _keyword
>>> get_close_matches("wheel", _keyword.kwlist)
['while']
>>> get_close_matches("apple", _keyword.kwlist)
[]
>>> get_close_matches("accept", _keyword.kwlist)
['except']
"""
if not n > 0:
raise ValueError("n must be > 0: %r" % (n,))
if not 0.0 <= cutoff <= 1.0:
raise ValueError("cutoff must be in [0.0, 1.0]: %r" % (cutoff,))
result = []
s = SequenceMatcher()
s.set_seq2(word)
for x in possibilities:
s.set_seq1(x)
if s.real_quick_ratio() >= cutoff and \
s.quick_ratio() >= cutoff and \
s.ratio() >= cutoff:
result.append((s.ratio(), x))
# Move the best scorers to head of list
result = heapq.nlargest(n, result)
# Strip scores for the best n matches
return [x for score, x in result]
def _count_leading(line, ch):
"""
Return number of `ch` characters at the start of `line`.
Example:
>>> _count_leading(' abc', ' ')
3
"""
i, n = 0, len(line)
while i < n and line[i] == ch:
i += 1
return i
class Differ(object):
r"""
Differ is a class for comparing sequences of lines of text, and
producing human-readable differences or deltas. Differ uses
SequenceMatcher both to compare sequences of lines, and to compare
sequences of characters within similar (near-matching) lines.
Each line of a Differ delta begins with a two-letter code:
'- ' line unique to sequence 1
'+ ' line unique to sequence 2
' ' line common to both sequences
'? ' line not present in either input sequence
Lines beginning with '? ' attempt to guide the eye to intraline
differences, and were not present in either input sequence. These lines
can be confusing if the sequences contain tab characters.
Note that Differ makes no claim to produce a *minimal* diff. To the
contrary, minimal diffs are often counter-intuitive, because they synch
up anywhere possible, sometimes accidental matches 100 pages apart.
Restricting synch points to contiguous matches preserves some notion of
locality, at the occasional cost of producing a longer diff.
Example: Comparing two texts.
First we set up the texts, sequences of individual single-line strings
ending with newlines (such sequences can also be obtained from the
`readlines()` method of file-like objects):
>>> text1 = ''' 1. Beautiful is better than ugly.
... 2. Explicit is better than implicit.
... 3. Simple is better than complex.
... 4. Complex is better than complicated.
... '''.splitlines(1)
>>> len(text1)
4
>>> text1[0][-1]
'\n'
>>> text2 = ''' 1. Beautiful is better than ugly.
... 3. Simple is better than complex.
... 4. Complicated is better than complex.
... 5. Flat is better than nested.
... '''.splitlines(1)
Next we instantiate a Differ object:
>>> d = Differ()
Note that when instantiating a Differ object we may pass functions to
filter out line and character 'junk'. See Differ.__init__ for details.
Finally, we compare the two:
>>> result = list(d.compare(text1, text2))
'result' is a list of strings, so let's pretty-print it:
>>> from pprint import pprint as _pprint
>>> _pprint(result)
[' 1. Beautiful is better than ugly.\n',
'- 2. Explicit is better than implicit.\n',
'- 3. Simple is better than complex.\n',
'+ 3. Simple is better than complex.\n',
'? ++\n',
'- 4. Complex is better than complicated.\n',
'? ^ ---- ^\n',
'+ 4. Complicated is better than complex.\n',
'? ++++ ^ ^\n',
'+ 5. Flat is better than nested.\n']
As a single multi-line string it looks like this:
>>> print ''.join(result),
1. Beautiful is better than ugly.
- 2. Explicit is better than implicit.
- 3. Simple is better than complex.
+ 3. Simple is better than complex.
? ++
- 4. Complex is better than complicated.
? ^ ---- ^
+ 4. Complicated is better than complex.
? ++++ ^ ^
+ 5. Flat is better than nested.
Methods:
__init__(linejunk=None, charjunk=None)
Construct a text differencer, with optional filters.
compare(a, b)
Compare two sequences of lines; generate the resulting delta.
"""
def __init__(self, linejunk=None, charjunk=None):
"""
Construct a text differencer, with optional filters.
The two optional keyword parameters are for filter functions:
- `linejunk`: A function that should accept a single string argument,
and return true iff the string is junk. The module-level function
`IS_LINE_JUNK` may be used to filter out lines without visible
characters, except for at most one splat ('#'). It is recommended
to leave linejunk None; as of Python 2.3, the underlying
SequenceMatcher class has grown an adaptive notion of "noise" lines
that's better than any static definition the author has ever been
able to craft.
- `charjunk`: A function that should accept a string of length 1. The
module-level function `IS_CHARACTER_JUNK` may be used to filter out
whitespace characters (a blank or tab; **note**: bad idea to include
newline in this!). Use of IS_CHARACTER_JUNK is recommended.
"""
self.linejunk = linejunk
self.charjunk = charjunk
def compare(self, a, b):
r"""
Compare two sequences of lines; generate the resulting delta.
Each sequence must contain individual single-line strings ending with
newlines. Such sequences can be obtained from the `readlines()` method
of file-like objects. The delta generated also consists of newline-
terminated strings, ready to be printed as-is via the writeline()
method of a file-like object.
Example:
>>> print ''.join(Differ().compare('one\ntwo\nthree\n'.splitlines(1),
... 'ore\ntree\nemu\n'.splitlines(1))),
- one
? ^
+ ore
? ^
- two
- three
? -
+ tree
+ emu
"""
cruncher = SequenceMatcher(self.linejunk, a, b)
for tag, alo, ahi, blo, bhi in cruncher.get_opcodes():
if tag == 'replace':
g = self._fancy_replace(a, alo, ahi, b, blo, bhi)
elif tag == 'delete':
g = self._dump('-', a, alo, ahi)
elif tag == 'insert':
g = self._dump('+', b, blo, bhi)
elif tag == 'equal':
g = self._dump(' ', a, alo, ahi)
else:
raise ValueError('unknown tag %r' % (tag,))
for line in g:
yield line
def _dump(self, tag, x, lo, hi):
"""Generate comparison results for a same-tagged range."""
for i in range(lo, hi):
yield '%s %s' % (tag, x[i])
def _plain_replace(self, a, alo, ahi, b, blo, bhi):
assert alo < ahi and blo < bhi
# dump the shorter block first -- reduces the burden on short-term
# memory if the blocks are of very different sizes
if bhi - blo < ahi - alo:
first = self._dump('+', b, blo, bhi)
second = self._dump('-', a, alo, ahi)
else:
first = self._dump('-', a, alo, ahi)
second = self._dump('+', b, blo, bhi)
for g in first, second:
for line in g:
yield line
def _fancy_replace(self, a, alo, ahi, b, blo, bhi):
r"""
When replacing one block of lines with another, search the blocks
for *similar* lines; the best-matching pair (if any) is used as a
synch point, and intraline difference marking is done on the
similar pair. Lots of work, but often worth it.
Example:
>>> d = Differ()
>>> results = d._fancy_replace(['abcDefghiJkl\n'], 0, 1,
... ['abcdefGhijkl\n'], 0, 1)
>>> print ''.join(results),
- abcDefghiJkl
? ^ ^ ^
+ abcdefGhijkl
? ^ ^ ^
"""
# don't synch up unless the lines have a similarity score of at
# least cutoff; best_ratio tracks the best score seen so far
best_ratio, cutoff = 0.74, 0.75
cruncher = SequenceMatcher(self.charjunk)
eqi, eqj = None, None # 1st indices of equal lines (if any)
# search for the pair that matches best without being identical
# (identical lines must be junk lines, & we don't want to synch up
# on junk -- unless we have to)
for j in range(blo, bhi):
bj = b[j]
cruncher.set_seq2(bj)
for i in range(alo, ahi):
ai = a[i]
if ai == bj:
if eqi is None:
eqi, eqj = i, j
continue
cruncher.set_seq1(ai)
# computing similarity is expensive, so use the quick
# upper bounds first -- have seen this speed up messy
# compares by a factor of 3.
# note that ratio() is only expensive to compute the first
# time it's called on a sequence pair; the expensive part
# of the computation is cached by cruncher
if cruncher.real_quick_ratio() > best_ratio and \
cruncher.quick_ratio() > best_ratio and \
cruncher.ratio() > best_ratio:
best_ratio, best_i, best_j = cruncher.ratio(), i, j
if best_ratio < cutoff:
# no non-identical "pretty close" pair
if eqi is None:
# no identical pair either -- treat it as a straight replace
for line in self._plain_replace(a, alo, ahi, b, blo, bhi):
yield line
return
# no close pair, but an identical pair -- synch up on that
best_i, best_j, best_ratio = eqi, eqj, 1.0
else:
# there's a close pair, so forget the identical pair (if any)
eqi = None
# a[best_i] very similar to b[best_j]; eqi is None iff they're not
# identical
# pump out diffs from before the synch point
for line in self._fancy_helper(a, alo, best_i, b, blo, best_j):
yield line
# do intraline marking on the synch pair
aelt, belt = a[best_i], b[best_j]
if eqi is None:
# pump out a '-', '?', '+', '?' quad for the synched lines
atags = btags = ""
cruncher.set_seqs(aelt, belt)
for tag, ai1, ai2, bj1, bj2 in cruncher.get_opcodes():
la, lb = ai2 - ai1, bj2 - bj1
if tag == 'replace':
atags += '^' * la
btags += '^' * lb
elif tag == 'delete':
atags += '-' * la
elif tag == 'insert':
btags += '+' * lb
elif tag == 'equal':
atags += ' ' * la
btags += ' ' * lb
else:
raise ValueError('unknown tag %r' % (tag,))
for line in self._qformat(aelt, belt, atags, btags):
yield line
else:
# the synch pair is identical
yield ' ' + aelt
# pump out diffs from after the synch point
for line in self._fancy_helper(a, best_i+1, ahi, b, best_j+1, bhi):
yield line
def _fancy_helper(self, a, alo, ahi, b, blo, bhi):
g = []
if alo < ahi:
if blo < bhi:
g = self._fancy_replace(a, alo, ahi, b, blo, bhi)
else:
g = self._dump('-', a, alo, ahi)
elif blo < bhi:
g = self._dump('+', b, blo, bhi)
for line in g:
yield line
def _qformat(self, aline, bline, atags, btags):
r"""
Format "?" output and deal with leading tabs.
Example:
>>> d = Differ()
>>> results = d._qformat('\tabcDefghiJkl\n', '\tabcdefGhijkl\n',
... ' ^ ^ ^ ', ' ^ ^ ^ ')
>>> for line in results: print repr(line)
...
'- \tabcDefghiJkl\n'
'? \t ^ ^ ^\n'
'+ \tabcdefGhijkl\n'
'? \t ^ ^ ^\n'
"""
# Can hurt, but will probably help most of the time.
common = min(_count_leading(aline, "\t"),
_count_leading(bline, "\t"))
common = min(common, _count_leading(atags[:common], " "))
common = min(common, _count_leading(btags[:common], " "))
atags = atags[common:].rstrip()
btags = btags[common:].rstrip()
yield "- " + aline
if atags:
yield "? %s%s\n" % ("\t" * common, atags)
yield "+ " + bline
if btags:
yield "? %s%s\n" % ("\t" * common, btags)
# With respect to junk, an earlier version of ndiff simply refused to
# *start* a match with a junk element. The result was cases like this:
# before: private Thread currentThread;
# after: private volatile Thread currentThread;
# If you consider whitespace to be junk, the longest contiguous match
# not starting with junk is "e Thread currentThread". So ndiff reported
# that "e volatil" was inserted between the 't' and the 'e' in "private".
# While an accurate view, to people that's absurd. The current version
# looks for matching blocks that are entirely junk-free, then extends the
# longest one of those as far as possible but only with matching junk.
# So now "currentThread" is matched, then extended to suck up the
# preceding blank; then "private" is matched, and extended to suck up the
# following blank; then "Thread" is matched; and finally ndiff reports
# that "volatile " was inserted before "Thread". The only quibble
# remaining is that perhaps it was really the case that " volatile"
# was inserted after "private". I can live with that <wink>.
import re
def IS_LINE_JUNK(line, pat=re.compile(r"\s*#?\s*$").match):
r"""
Return 1 for ignorable line: iff `line` is blank or contains a single '#'.
Examples:
>>> IS_LINE_JUNK('\n')
True
>>> IS_LINE_JUNK(' # \n')
True
>>> IS_LINE_JUNK('hello\n')
False
"""
return pat(line) is not None
def IS_CHARACTER_JUNK(ch, ws=" \t"):
r"""
Return 1 for ignorable character: iff `ch` is a space or tab.
Examples:
>>> IS_CHARACTER_JUNK(' ')
True
>>> IS_CHARACTER_JUNK('\t')
True
>>> IS_CHARACTER_JUNK('\n')
False
>>> IS_CHARACTER_JUNK('x')
False
"""
return ch in ws
########################################################################
### Unified Diff
########################################################################
def _format_range_unified(start, stop):
'Convert range to the "ed" format'
# Per the diff spec at http://www.unix.org/single_unix_specification/
beginning = start + 1 # lines start numbering with one
length = stop - start
if length == 1:
# return '{}'.format(beginning)
return '%s' % (beginning)
if not length:
beginning -= 1 # empty ranges begin at line just before the range
return '%s,%s' % (beginning, length)
def unified_diff(a, b, fromfile='', tofile='', fromfiledate='',
tofiledate='', n=3, lineterm='\n'):
r"""
Compare two sequences of lines; generate the delta as a unified diff.
Unified diffs are a compact way of showing line changes and a few
lines of context. The number of context lines is set by 'n' which
defaults to three.
By default, the diff control lines (those with ---, +++, or @@) are
created with a trailing newline. This is helpful so that inputs
created from file.readlines() result in diffs that are suitable for
file.writelines() since both the inputs and outputs have trailing
newlines.
For inputs that do not have trailing newlines, set the lineterm
argument to "" so that the output will be uniformly newline free.
The unidiff format normally has a header for filenames and modification
times. Any or all of these may be specified using strings for
'fromfile', 'tofile', 'fromfiledate', and 'tofiledate'.
The modification times are normally expressed in the ISO 8601 format.
Example:
>>> for line in unified_diff('one two three four'.split(),
... 'zero one tree four'.split(), 'Original', 'Current',
... '2005-01-26 23:30:50', '2010-04-02 10:20:52',
... lineterm=''):
... print line # doctest: +NORMALIZE_WHITESPACE
--- Original 2005-01-26 23:30:50
+++ Current 2010-04-02 10:20:52
@@ -1,4 +1,4 @@
+zero
one
-two
-three
+tree
four
"""
started = False
for group in SequenceMatcher(None,a,b).get_grouped_opcodes(n):
if not started:
started = True
# fromdate = '\t{}'.format(fromfiledate) if fromfiledate else ''
fromdate = '\t%s' % (fromfiledate) if fromfiledate else ''
# todate = '\t{}'.format(tofiledate) if tofiledate else ''
todate = '\t%s' % (tofiledate) if tofiledate else ''
# yield '--- {}{}{}'.format(fromfile, fromdate, lineterm)
yield '--- %s%s%s' % (fromfile, fromdate, lineterm)
# yield '+++ {}{}{}'.format(tofile, todate, lineterm)
yield '+++ %s%s%s' % (tofile, todate, lineterm)
first, last = group[0], group[-1]
file1_range = _format_range_unified(first[1], last[2])
file2_range = _format_range_unified(first[3], last[4])
# yield '@@ -{} +{} @@{}'.format(file1_range, file2_range, lineterm)
yield '@@ -%s +%s @@%s' % (file1_range, file2_range, lineterm)
for tag, i1, i2, j1, j2 in group:
if tag == 'equal':
for line in a[i1:i2]:
yield ' ' + line
continue
if tag in ('replace', 'delete'):
for line in a[i1:i2]:
yield '-' + line
if tag in ('replace', 'insert'):
for line in b[j1:j2]:
yield '+' + line
########################################################################
### Context Diff
########################################################################
def _format_range_context(start, stop):
'Convert range to the "ed" format'
# Per the diff spec at http://www.unix.org/single_unix_specification/
beginning = start + 1 # lines start numbering with one
length = stop - start
if not length:
beginning -= 1 # empty ranges begin at line just before the range
if length <= 1:
# return '{}'.format(beginning)
return '%s' % (beginning)
# return '{},{}'.format(beginning, beginning + length - 1)
return '%s,%s' % (beginning, beginning + length - 1)
# See http://www.unix.org/single_unix_specification/
def context_diff(a, b, fromfile='', tofile='',
fromfiledate='', tofiledate='', n=3, lineterm='\n'):
r"""
Compare two sequences of lines; generate the delta as a context diff.
Context diffs are a compact way of showing line changes and a few
lines of context. The number of context lines is set by 'n' which
defaults to three.
By default, the diff control lines (those with *** or ---) are
created with a trailing newline. This is helpful so that inputs
created from file.readlines() result in diffs that are suitable for
file.writelines() since both the inputs and outputs have trailing
newlines.
For inputs that do not have trailing newlines, set the lineterm
argument to "" so that the output will be uniformly newline free.
The context diff format normally has a header for filenames and
modification times. Any or all of these may be specified using
strings for 'fromfile', 'tofile', 'fromfiledate', and 'tofiledate'.
The modification times are normally expressed in the ISO 8601 format.
If not specified, the strings default to blanks.
Example:
>>> print ''.join(context_diff('one\ntwo\nthree\nfour\n'.splitlines(1),
... 'zero\none\ntree\nfour\n'.splitlines(1), 'Original', 'Current')),
*** Original
--- Current
***************
*** 1,4 ****
one
! two
! three
four
--- 1,4 ----
+ zero
one
! tree
four
"""
prefix = dict(insert='+ ', delete='- ', replace='! ', equal=' ')
started = False
for group in SequenceMatcher(None,a,b).get_grouped_opcodes(n):
if not started:
started = True
# fromdate = '\t{}'.format(fromfiledate) if fromfiledate else ''
fromdate = '\t%s' % (fromfiledate) if fromfiledate else ''
# todate = '\t{}'.format(tofiledate) if tofiledate else ''
todate = '\t%s' % (tofiledate) if tofiledate else ''
# yield '*** {}{}{}'.format(fromfile, fromdate, lineterm)
yield '*** %s%s%s' % (fromfile, fromdate, lineterm)
# yield '--- {}{}{}'.format(tofile, todate, lineterm)
yield '--- %s%s%s' % (tofile, todate, lineterm)
first, last = group[0], group[-1]
yield '***************' + lineterm
file1_range = _format_range_context(first[1], last[2])
# yield '*** {} ****{}'.format(file1_range, lineterm)
yield '*** %s ****%s' % (file1_range, lineterm)
if any(tag in ('replace', 'delete') for tag, _, _, _, _ in group):
for tag, i1, i2, _, _ in group:
if tag != 'insert':
for line in a[i1:i2]:
yield prefix[tag] + line
file2_range = _format_range_context(first[3], last[4])
# yield '--- {} ----{}'.format(file2_range, lineterm)
yield '--- %s ----%s' % (file2_range, lineterm)
if any(tag in ('replace', 'insert') for tag, _, _, _, _ in group):
for tag, _, _, j1, j2 in group:
if tag != 'delete':
for line in b[j1:j2]:
yield prefix[tag] + line
def ndiff(a, b, linejunk=None, charjunk=IS_CHARACTER_JUNK):
r"""
Compare `a` and `b` (lists of strings); return a `Differ`-style delta.
Optional keyword parameters `linejunk` and `charjunk` are for filter
functions (or None):
- linejunk: A function that should accept a single string argument, and
return true iff the string is junk. The default is None, and is
recommended; as of Python 2.3, an adaptive notion of "noise" lines is
used that does a good job on its own.
- charjunk: A function that should accept a string of length 1. The
default is module-level function IS_CHARACTER_JUNK, which filters out
whitespace characters (a blank or tab; note: bad idea to include newline
in this!).
Tools/scripts/ndiff.py is a command-line front-end to this function.
Example:
>>> diff = ndiff('one\ntwo\nthree\n'.splitlines(1),
... 'ore\ntree\nemu\n'.splitlines(1))
>>> print ''.join(diff),
- one
? ^
+ ore
? ^
- two
- three
? -
+ tree
+ emu
"""
return Differ(linejunk, charjunk).compare(a, b)
def _mdiff(fromlines, tolines, context=None, linejunk=None,
charjunk=IS_CHARACTER_JUNK):
r"""Returns generator yielding marked up from/to side by side differences.
Arguments:
fromlines -- list of text lines to compared to tolines
tolines -- list of text lines to be compared to fromlines
context -- number of context lines to display on each side of difference,
if None, all from/to text lines will be generated.
linejunk -- passed on to ndiff (see ndiff documentation)
charjunk -- passed on to ndiff (see ndiff documentation)
This function returns an iterator which returns a tuple:
(from line tuple, to line tuple, boolean flag)
from/to line tuple -- (line num, line text)
line num -- integer or None (to indicate a context separation)
line text -- original line text with following markers inserted:
'\0+' -- marks start of added text
'\0-' -- marks start of deleted text
'\0^' -- marks start of changed text
'\1' -- marks end of added/deleted/changed text
boolean flag -- None indicates context separation, True indicates
either "from" or "to" line contains a change, otherwise False.
This function/iterator was originally developed to generate side by side
file difference for making HTML pages (see HtmlDiff class for example
usage).
Note, this function utilizes the ndiff function to generate the side by
side difference markup. Optional ndiff arguments may be passed to this
function and they in turn will be passed to ndiff.
"""
import re
# regular expression for finding intraline change indices
change_re = re.compile('(\++|\-+|\^+)')
# create the difference iterator to generate the differences
diff_lines_iterator = ndiff(fromlines,tolines,linejunk,charjunk)
def _make_line(lines, format_key, side, num_lines=[0,0]):
"""Returns line of text with user's change markup and line formatting.
lines -- list of lines from the ndiff generator to produce a line of
text from. When producing the line of text to return, the
lines used are removed from this list.
format_key -- '+' return first line in list with "add" markup around
the entire line.
'-' return first line in list with "delete" markup around
the entire line.
'?' return first line in list with add/delete/change
intraline markup (indices obtained from second line)
None return first line in list with no markup
side -- indice into the num_lines list (0=from,1=to)
num_lines -- from/to current line number. This is NOT intended to be a
passed parameter. It is present as a keyword argument to
maintain memory of the current line numbers between calls
of this function.
Note, this function is purposefully not defined at the module scope so
that data it needs from its parent function (within whose context it
is defined) does not need to be of module scope.
"""
num_lines[side] += 1
# Handle case where no user markup is to be added, just return line of
# text with user's line format to allow for usage of the line number.
if format_key is None:
return (num_lines[side],lines.pop(0)[2:])
# Handle case of intraline changes
if format_key == '?':
text, markers = lines.pop(0), lines.pop(0)
# find intraline changes (store change type and indices in tuples)
sub_info = []
def record_sub_info(match_object,sub_info=sub_info):
sub_info.append([match_object.group(1)[0],match_object.span()])
return match_object.group(1)
change_re.sub(record_sub_info,markers)
# process each tuple inserting our special marks that won't be
# noticed by an xml/html escaper.
for key,(begin,end) in sub_info[::-1]:
text = text[0:begin]+'\0'+key+text[begin:end]+'\1'+text[end:]
text = text[2:]
# Handle case of add/delete entire line
else:
text = lines.pop(0)[2:]
# if line of text is just a newline, insert a space so there is
# something for the user to highlight and see.
if not text:
text = ' '
# insert marks that won't be noticed by an xml/html escaper.
text = '\0' + format_key + text + '\1'
# Return line of text, first allow user's line formatter to do its
# thing (such as adding the line number) then replace the special
# marks with what the user's change markup.
return (num_lines[side],text)
def _line_iterator():
"""Yields from/to lines of text with a change indication.
This function is an iterator. It itself pulls lines from a
differencing iterator, processes them and yields them. When it can
it yields both a "from" and a "to" line, otherwise it will yield one
or the other. In addition to yielding the lines of from/to text, a
boolean flag is yielded to indicate if the text line(s) have
differences in them.
Note, this function is purposefully not defined at the module scope so
that data it needs from its parent function (within whose context it
is defined) does not need to be of module scope.
"""
lines = []
num_blanks_pending, num_blanks_to_yield = 0, 0
while True:
# Load up next 4 lines so we can look ahead, create strings which
# are a concatenation of the first character of each of the 4 lines
# so we can do some very readable comparisons.
while len(lines) < 4:
try:
lines.append(next(diff_lines_iterator))
except StopIteration:
lines.append('X')
s = ''.join([line[0] for line in lines])
if s.startswith('X'):
# When no more lines, pump out any remaining blank lines so the
# corresponding add/delete lines get a matching blank line so
# all line pairs get yielded at the next level.
num_blanks_to_yield = num_blanks_pending
elif s.startswith('-?+?'):
# simple intraline change
yield _make_line(lines,'?',0), _make_line(lines,'?',1), True
continue
elif s.startswith('--++'):
# in delete block, add block coming: we do NOT want to get
# caught up on blank lines yet, just process the delete line
num_blanks_pending -= 1
yield _make_line(lines,'-',0), None, True
continue
elif s.startswith(('--?+', '--+', '- ')):
# in delete block and see an intraline change or unchanged line
# coming: yield the delete line and then blanks
from_line,to_line = _make_line(lines,'-',0), None
num_blanks_to_yield,num_blanks_pending = num_blanks_pending-1,0
elif s.startswith('-+?'):
# intraline change
yield _make_line(lines,None,0), _make_line(lines,'?',1), True
continue
elif s.startswith('-?+'):
# intraline change
yield _make_line(lines,'?',0), _make_line(lines,None,1), True
continue
elif s.startswith('-'):
# delete FROM line
num_blanks_pending -= 1
yield _make_line(lines,'-',0), None, True
continue
elif s.startswith('+--'):
# in add block, delete block coming: we do NOT want to get
# caught up on blank lines yet, just process the add line
num_blanks_pending += 1
yield None, _make_line(lines,'+',1), True
continue
elif s.startswith(('+ ', '+-')):
# will be leaving an add block: yield blanks then add line
from_line, to_line = None, _make_line(lines,'+',1)
num_blanks_to_yield,num_blanks_pending = num_blanks_pending+1,0
elif s.startswith('+'):
# inside an add block, yield the add line
num_blanks_pending += 1
yield None, _make_line(lines,'+',1), True
continue
elif s.startswith(' '):
# unchanged text, yield it to both sides
yield _make_line(lines[:],None,0),_make_line(lines,None,1),False
continue
# Catch up on the blank lines so when we yield the next from/to
# pair, they are lined up.
while(num_blanks_to_yield < 0):
num_blanks_to_yield += 1
yield None,('','\n'),True
while(num_blanks_to_yield > 0):
num_blanks_to_yield -= 1
yield ('','\n'),None,True
if s.startswith('X'):
raise StopIteration
else:
yield from_line,to_line,True
def _line_pair_iterator():
"""Yields from/to lines of text with a change indication.
This function is an iterator. It itself pulls lines from the line
iterator. Its difference from that iterator is that this function
always yields a pair of from/to text lines (with the change
indication). If necessary it will collect single from/to lines
until it has a matching pair from/to pair to yield.
Note, this function is purposefully not defined at the module scope so
that data it needs from its parent function (within whose context it
is defined) does not need to be of module scope.
"""
line_iterator = _line_iterator()
fromlines,tolines=[],[]
while True:
# Collecting lines of text until we have a from/to pair
while (len(fromlines)==0 or len(tolines)==0):
from_line, to_line, found_diff =next(line_iterator)
if from_line is not None:
fromlines.append((from_line,found_diff))
if to_line is not None:
tolines.append((to_line,found_diff))
# Once we have a pair, remove them from the collection and yield it
from_line, fromDiff = fromlines.pop(0)
to_line, to_diff = tolines.pop(0)
yield (from_line,to_line,fromDiff or to_diff)
# Handle case where user does not want context differencing, just yield
# them up without doing anything else with them.
line_pair_iterator = _line_pair_iterator()
if context is None:
while True:
yield next(line_pair_iterator)
# Handle case where user wants context differencing. We must do some
# storage of lines until we know for sure that they are to be yielded.
else:
context += 1
lines_to_write = 0
while True:
# Store lines up until we find a difference, note use of a
# circular queue because we only need to keep around what
# we need for context.
index, contextLines = 0, [None]*(context)
found_diff = False
while(found_diff is False):
from_line, to_line, found_diff = next(line_pair_iterator)
i = index % context
contextLines[i] = (from_line, to_line, found_diff)
index += 1
# Yield lines that we have collected so far, but first yield
# the user's separator.
if index > context:
yield None, None, None
lines_to_write = context
else:
lines_to_write = index
index = 0
while(lines_to_write):
i = index % context
index += 1
yield contextLines[i]
lines_to_write -= 1
# Now yield the context lines after the change
lines_to_write = context-1
while(lines_to_write):
from_line, to_line, found_diff = next(line_pair_iterator)
# If another change within the context, extend the context
if found_diff:
lines_to_write = context-1
else:
lines_to_write -= 1
yield from_line, to_line, found_diff
_file_template = """
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<meta http-equiv="Content-Type"
content="text/html; charset=ISO-8859-1" />
<title></title>
<style type="text/css">%(styles)s
</style>
</head>
<body>
%(table)s%(legend)s
</body>
</html>"""
_styles = """
table.diff {font-family:Courier; border:medium;}
.diff_header {background-color:#e0e0e0}
td.diff_header {text-align:right}
.diff_next {background-color:#c0c0c0}
.diff_add {background-color:#aaffaa}
.diff_chg {background-color:#ffff77}
.diff_sub {background-color:#ffaaaa}"""
_table_template = """
<table class="diff" id="difflib_chg_%(prefix)s_top"
cellspacing="0" cellpadding="0" rules="groups" >
<colgroup></colgroup> <colgroup></colgroup> <colgroup></colgroup>
<colgroup></colgroup> <colgroup></colgroup> <colgroup></colgroup>
%(header_row)s
<tbody>
%(data_rows)s </tbody>
</table>"""
_legend = """
<table class="diff" summary="Legends">
<tr> <th colspan="2"> Legends </th> </tr>
<tr> <td> <table border="" summary="Colors">
<tr><th> Colors </th> </tr>
<tr><td class="diff_add"> Added </td></tr>
<tr><td class="diff_chg">Changed</td> </tr>
<tr><td class="diff_sub">Deleted</td> </tr>
</table></td>
<td> <table border="" summary="Links">
<tr><th colspan="2"> Links </th> </tr>
<tr><td>(f)irst change</td> </tr>
<tr><td>(n)ext change</td> </tr>
<tr><td>(t)op</td> </tr>
</table></td> </tr>
</table>"""
class HtmlDiff(object):
"""For producing HTML side by side comparison with change highlights.
This class can be used to create an HTML table (or a complete HTML file
containing the table) showing a side by side, line by line comparison
of text with inter-line and intra-line change highlights. The table can
be generated in either full or contextual difference mode.
The following methods are provided for HTML generation:
make_table -- generates HTML for a single side by side table
make_file -- generates complete HTML file with a single side by side table
See tools/scripts/diff.py for an example usage of this class.
"""
_file_template = _file_template
_styles = _styles
_table_template = _table_template
_legend = _legend
_default_prefix = 0
def __init__(self,tabsize=8,wrapcolumn=None,linejunk=None,
charjunk=IS_CHARACTER_JUNK):
"""HtmlDiff instance initializer
Arguments:
tabsize -- tab stop spacing, defaults to 8.
wrapcolumn -- column number where lines are broken and wrapped,
defaults to None where lines are not wrapped.
linejunk,charjunk -- keyword arguments passed into ndiff() (used to by
HtmlDiff() to generate the side by side HTML differences). See
ndiff() documentation for argument default values and descriptions.
"""
self._tabsize = tabsize
self._wrapcolumn = wrapcolumn
self._linejunk = linejunk
self._charjunk = charjunk
def make_file(self,fromlines,tolines,fromdesc='',todesc='',context=False,
numlines=5):
"""Returns HTML file of side by side comparison with change highlights
Arguments:
fromlines -- list of "from" lines
tolines -- list of "to" lines
fromdesc -- "from" file column header string
todesc -- "to" file column header string
context -- set to True for contextual differences (defaults to False
which shows full differences).
numlines -- number of context lines. When context is set True,
controls number of lines displayed before and after the change.
When context is False, controls the number of lines to place
the "next" link anchors before the next change (so click of
"next" link jumps to just before the change).
"""
return self._file_template % dict(
styles = self._styles,
legend = self._legend,
table = self.make_table(fromlines,tolines,fromdesc,todesc,
context=context,numlines=numlines))
def _tab_newline_replace(self,fromlines,tolines):
"""Returns from/to line lists with tabs expanded and newlines removed.
Instead of tab characters being replaced by the number of spaces
needed to fill in to the next tab stop, this function will fill
the space with tab characters. This is done so that the difference
algorithms can identify changes in a file when tabs are replaced by
spaces and vice versa. At the end of the HTML generation, the tab
characters will be replaced with a nonbreakable space.
"""
def expand_tabs(line):
# hide real spaces
line = line.replace(' ','\0')
# expand tabs into spaces
line = line.expandtabs(self._tabsize)
# replace spaces from expanded tabs back into tab characters
# (we'll replace them with markup after we do differencing)
line = line.replace(' ','\t')
return line.replace('\0',' ').rstrip('\n')
fromlines = [expand_tabs(line) for line in fromlines]
tolines = [expand_tabs(line) for line in tolines]
return fromlines,tolines
def _split_line(self,data_list,line_num,text):
"""Builds list of text lines by splitting text lines at wrap point
This function will determine if the input text line needs to be
wrapped (split) into separate lines. If so, the first wrap point
will be determined and the first line appended to the output
text line list. This function is used recursively to handle
the second part of the split line to further split it.
"""
# if blank line or context separator, just add it to the output list
if not line_num:
data_list.append((line_num,text))
return
# if line text doesn't need wrapping, just add it to the output list
size = len(text)
max = self._wrapcolumn
if (size <= max) or ((size -(text.count('\0')*3)) <= max):
data_list.append((line_num,text))
return
# scan text looking for the wrap point, keeping track if the wrap
# point is inside markers
i = 0
n = 0
mark = ''
while n < max and i < size:
if text[i] == '\0':
i += 1
mark = text[i]
i += 1
elif text[i] == '\1':
i += 1
mark = ''
else:
i += 1
n += 1
# wrap point is inside text, break it up into separate lines
line1 = text[:i]
line2 = text[i:]
# if wrap point is inside markers, place end marker at end of first
# line and start marker at beginning of second line because each
# line will have its own table tag markup around it.
if mark:
line1 = line1 + '\1'
line2 = '\0' + mark + line2
# tack on first line onto the output list
data_list.append((line_num,line1))
# use this routine again to wrap the remaining text
self._split_line(data_list,'>',line2)
def _line_wrapper(self,diffs):
"""Returns iterator that splits (wraps) mdiff text lines"""
# pull from/to data and flags from mdiff iterator
for fromdata,todata,flag in diffs:
# check for context separators and pass them through
if flag is None:
yield fromdata,todata,flag
continue
(fromline,fromtext),(toline,totext) = fromdata,todata
# for each from/to line split it at the wrap column to form
# list of text lines.
fromlist,tolist = [],[]
self._split_line(fromlist,fromline,fromtext)
self._split_line(tolist,toline,totext)
# yield from/to line in pairs inserting blank lines as
# necessary when one side has more wrapped lines
while fromlist or tolist:
if fromlist:
fromdata = fromlist.pop(0)
else:
fromdata = ('',' ')
if tolist:
todata = tolist.pop(0)
else:
todata = ('',' ')
yield fromdata,todata,flag
def _collect_lines(self,diffs):
"""Collects mdiff output into separate lists
Before storing the mdiff from/to data into a list, it is converted
into a single line of text with HTML markup.
"""
fromlist,tolist,flaglist = [],[],[]
# pull from/to data and flags from mdiff style iterator
for fromdata,todata,flag in diffs:
try:
# store HTML markup of the lines into the lists
fromlist.append(self._format_line(0,flag,*fromdata))
tolist.append(self._format_line(1,flag,*todata))
except TypeError:
# exceptions occur for lines where context separators go
fromlist.append(None)
tolist.append(None)
flaglist.append(flag)
return fromlist,tolist,flaglist
def _format_line(self,side,flag,linenum,text):
"""Returns HTML markup of "from" / "to" text lines
side -- 0 or 1 indicating "from" or "to" text
flag -- indicates if difference on line
linenum -- line number (used for line number column)
text -- line text to be marked up
"""
try:
linenum = '%d' % linenum
id = ' id="%s%s"' % (self._prefix[side],linenum)
except TypeError:
# handle blank lines where linenum is '>' or ''
id = ''
# replace those things that would get confused with HTML symbols
text=text.replace("&","&").replace(">",">").replace("<","<")
# make space non-breakable so they don't get compressed or line wrapped
text = text.replace(' ',' ').rstrip()
return '<td class="diff_header"%s>%s</td><td nowrap="nowrap">%s</td>' \
% (id,linenum,text)
def _make_prefix(self):
"""Create unique anchor prefixes"""
# Generate a unique anchor prefix so multiple tables
# can exist on the same HTML page without conflicts.
fromprefix = "from%d_" % HtmlDiff._default_prefix
toprefix = "to%d_" % HtmlDiff._default_prefix
HtmlDiff._default_prefix += 1
# store prefixes so line format method has access
self._prefix = [fromprefix,toprefix]
def _convert_flags(self,fromlist,tolist,flaglist,context,numlines):
"""Makes list of "next" links"""
# all anchor names will be generated using the unique "to" prefix
toprefix = self._prefix[1]
# process change flags, generating middle column of next anchors/links
next_id = ['']*len(flaglist)
next_href = ['']*len(flaglist)
num_chg, in_change = 0, False
last = 0
for i,flag in enumerate(flaglist):
if flag:
if not in_change:
in_change = True
last = i
# at the beginning of a change, drop an anchor a few lines
# (the context lines) before the change for the previous
# link
i = max([0,i-numlines])
next_id[i] = ' id="difflib_chg_%s_%d"' % (toprefix,num_chg)
# at the beginning of a change, drop a link to the next
# change
num_chg += 1
next_href[last] = '<a href="#difflib_chg_%s_%d">n</a>' % (
toprefix,num_chg)
else:
in_change = False
# check for cases where there is no content to avoid exceptions
if not flaglist:
flaglist = [False]
next_id = ['']
next_href = ['']
last = 0
if context:
fromlist = ['<td></td><td> No Differences Found </td>']
tolist = fromlist
else:
fromlist = tolist = ['<td></td><td> Empty File </td>']
# if not a change on first line, drop a link
if not flaglist[0]:
next_href[0] = '<a href="#difflib_chg_%s_0">f</a>' % toprefix
# redo the last link to link to the top
next_href[last] = '<a href="#difflib_chg_%s_top">t</a>' % (toprefix)
return fromlist,tolist,flaglist,next_href,next_id
def make_table(self,fromlines,tolines,fromdesc='',todesc='',context=False,
numlines=5):
"""Returns HTML table of side by side comparison with change highlights
Arguments:
fromlines -- list of "from" lines
tolines -- list of "to" lines
fromdesc -- "from" file column header string
todesc -- "to" file column header string
context -- set to True for contextual differences (defaults to False
which shows full differences).
numlines -- number of context lines. When context is set True,
controls number of lines displayed before and after the change.
When context is False, controls the number of lines to place
the "next" link anchors before the next change (so click of
"next" link jumps to just before the change).
"""
# make unique anchor prefixes so that multiple tables may exist
# on the same page without conflict.
self._make_prefix()
# change tabs to spaces before it gets more difficult after we insert
# markup
fromlines,tolines = self._tab_newline_replace(fromlines,tolines)
# create diffs iterator which generates side by side from/to data
if context:
context_lines = numlines
else:
context_lines = None
diffs = _mdiff(fromlines,tolines,context_lines,linejunk=self._linejunk,
charjunk=self._charjunk)
# set up iterator to wrap lines that exceed desired width
if self._wrapcolumn:
diffs = self._line_wrapper(diffs)
# collect up from/to lines and flags into lists (also format the lines)
fromlist,tolist,flaglist = self._collect_lines(diffs)
# process change flags, generating middle column of next anchors/links
fromlist,tolist,flaglist,next_href,next_id = self._convert_flags(
fromlist,tolist,flaglist,context,numlines)
s = []
fmt = ' <tr><td class="diff_next"%s>%s</td>%s' + \
'<td class="diff_next">%s</td>%s</tr>\n'
for i in range(len(flaglist)):
if flaglist[i] is None:
# mdiff yields None on separator lines skip the bogus ones
# generated for the first line
if i > 0:
s.append(' </tbody> \n <tbody>\n')
else:
s.append( fmt % (next_id[i],next_href[i],fromlist[i],
next_href[i],tolist[i]))
if fromdesc or todesc:
header_row = '<thead><tr>%s%s%s%s</tr></thead>' % (
'<th class="diff_next"><br /></th>',
'<th colspan="2" class="diff_header">%s</th>' % fromdesc,
'<th class="diff_next"><br /></th>',
'<th colspan="2" class="diff_header">%s</th>' % todesc)
else:
header_row = ''
table = self._table_template % dict(
data_rows=''.join(s),
header_row=header_row,
prefix=self._prefix[1])
return table.replace('\0+','<span class="diff_add">'). \
replace('\0-','<span class="diff_sub">'). \
replace('\0^','<span class="diff_chg">'). \
replace('\1','</span>'). \
replace('\t',' ')
del re
def restore(delta, which):
r"""
Generate one of the two sequences that generated a delta.
Given a `delta` produced by `Differ.compare()` or `ndiff()`, extract
lines originating from file 1 or 2 (parameter `which`), stripping off line
prefixes.
Examples:
>>> diff = ndiff('one\ntwo\nthree\n'.splitlines(1),
... 'ore\ntree\nemu\n'.splitlines(1))
>>> diff = list(diff)
>>> print ''.join(restore(diff, 1)),
one
two
three
>>> print ''.join(restore(diff, 2)),
ore
tree
emu
"""
try:
tag = {1: "- ", 2: "+ "}[int(which)]
except KeyError:
raise ValueError('unknown delta choice (must be 1 or 2): %r'
% which)
prefixes = (" ", tag)
for line in delta:
if line[:2] in prefixes:
yield line[2:]
# def _test():
# import doctest, difflib
# return doctest.testmod(difflib)
# if __name__ == "__main__":
# _test()
|
the-stack_106_26629 | import os
os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
os.environ["CUDA_VISIBLE_DEVICES"] = "-1"
import numpy as np
import pandas as pd
import tensorflow as tf
from tqdm import tqdm
import matplotlib.pyplot as plt
import random
from Utils.DataProcessing import *
import scipy
import sys
seed = 2605
l = 9
r = 50
epsilon = float(sys.argv[1])
numbit_whole = 0
numbit_frac = 9
num_file_per_batch = 1000
random.seed(seed)
np.random.seed(seed)
tf.random.set_seed(seed)
eps = epsilon/r
print(epsilon, eps)
duchi_mech = lambda x: duchi_mechanism(x, eps)
duchi_vec = np.vectorize(duchi_mech)
hybrid_mech = lambda x: hybrid_mechanism(x, eps)
hybrid_vec = np.vectorize(hybrid_mech)
piece_mech = lambda x: piecewise_mechanism(x, eps)
piece_vec = np.vectorize(piece_mech)
threeoutput_mech = lambda x: three_output_mechanism(x, eps)
threeoutput_vec = np.vectorize(threeoutput_mech)
PM_mech = lambda x: PM_SUB(x, eps)
PM_vec = np.vectorize(PM_mech)
float_bin = lambda x: float_to_binary(x, numbit_whole, numbit_frac)
float_to_binary_vec = np.vectorize(float_bin)
bin_float = lambda x: binary_to_float(x, numbit_whole, numbit_frac)
binary_to_float_vec = np.vectorize(bin_float)
save_path = '../Datasets/PPI/feat/'
file_path = '../Datasets/PPI/feat/'
files = [
'ppi_0_feat_val.npy',
'ppi_1_feat_val.npy',
'ppi_0_feat_test.npy',
'ppi_1_feat_test.npy',
'ppi_0_feat.npy',
'ppi_1_feat.npy',
'ppi_2_feat.npy',
'ppi_3_feat.npy',
'ppi_4_feat.npy',
'ppi_5_feat.npy',
'ppi_6_feat.npy',
'ppi_7_feat.npy',
'ppi_8_feat.npy',
'ppi_9_feat.npy',
'ppi_10_feat.npy',
'ppi_11_feat.npy',
'ppi_12_feat.npy',
'ppi_13_feat.npy',
'ppi_14_feat.npy',
'ppi_15_feat.npy',
'ppi_16_feat.npy',
'ppi_17_feat.npy',
'ppi_18_feat.npy',
'ppi_19_feat.npy',
]
# upper_limit = 0
# for i in range(1, numbit_frac+1):
# upper_limit += (0.5)**i
# print("Upper value for {} number of fractional bit is: {}".format(numbit_frac, upper_limit))
for f in tqdm(files):
name = f.split('.')[0]
feat_matrix = np.load(file_path+f)
print("Size of feature matrix:", feat_matrix.shape)
max_by_row = np.max(feat_matrix, axis=1)
min_by_row = np.min(feat_matrix, axis=1)
range_by_row = np.max(feat_matrix, axis=1) - np.min(feat_matrix, axis=1)
min_by_row = np.expand_dims(min_by_row, axis=-1)
range_by_row = np.expand_dims(range_by_row, axis=-1)
min_by_row = np.tile(min_by_row, (1, r))
range_by_row = np.tile(range_by_row, (1, r))
feat_matrix = (feat_matrix - min_by_row)/range_by_row
del(range_by_row)
del(min_by_row)
num_sample = feat_matrix.shape[0]
perturbed_feat_duchi = duchi_vec(feat_matrix)
np.save(save_path+'duchi_{}_eps_{}.npy'.format(name, epsilon),perturbed_feat_duchi)
# piecewise
perturbed_feat_piecewise = piece_vec(feat_matrix)
np.save(save_path+'piecewise_{}_eps_{}.npy'.format(name, epsilon),perturbed_feat_piecewise)
# hybrid
perturbed_feat_hybrid = hybrid_vec(feat_matrix)
np.save(save_path+'hybrid_{}_eps_{}.npy'.format(name, epsilon),perturbed_feat_hybrid)
# threeoutput
perturbed_feat_threeoutput = threeoutput_vec(feat_matrix)
np.save(save_path+'threeoutput_{}_eps_{}.npy'.format(name, epsilon),perturbed_feat_threeoutput)
#PM-SUB
perturbed_feat_PM = PM_vec(feat_matrix)
np.save(save_path+'PM_{}_eps_{}.npy'.format(name, epsilon),perturbed_feat_PM)
del(perturbed_feat_duchi)
del(perturbed_feat_piecewise)
del(perturbed_feat_hybrid)
del(perturbed_feat_threeoutput)
del(perturbed_feat_PM)
print("==============Process is Done===============")
|
the-stack_106_26631 | #!/usr/bin/env python
from __future__ import absolute_import, print_function, unicode_literals
import os
from optparse import OptionParser
from django.core.management import ManagementUtility
def create_project(parser, options, args):
# Validate args
if len(args) < 2:
parser.error("Please specify a name for your Tuiuiu installation")
elif len(args) > 3:
parser.error("Too many arguments")
project_name = args[1]
try:
dest_dir = args[2]
except IndexError:
dest_dir = None
# Make sure given name is not already in use by another python package/module.
try:
__import__(project_name)
except ImportError:
pass
else:
parser.error("'%s' conflicts with the name of an existing "
"Python module and cannot be used as a project "
"name. Please try another name." % project_name)
print("Creating a Tuiuiu project called %(project_name)s" % {'project_name': project_name}) # noqa
# Create the project from the Tuiuiu template using startapp
# First find the path to Tuiuiu
import tuiuiu
tuiuiu_path = os.path.dirname(tuiuiu.__file__)
template_path = os.path.join(tuiuiu_path, 'project_template')
# Call django-admin startproject
utility_args = ['django-admin.py',
'startproject',
'--template=' + template_path,
'--ext=html,rst',
project_name]
if dest_dir:
utility_args.append(dest_dir)
utility = ManagementUtility(utility_args)
utility.execute()
print("Success! %(project_name)s has been created" % {'project_name': project_name}) # noqa
COMMANDS = {
'start': create_project,
}
def main():
# Parse options
parser = OptionParser(usage="Usage: %prog start project_name [directory]")
(options, args) = parser.parse_args()
# Find command
try:
command = args[0]
except IndexError:
parser.print_help()
return
if command in COMMANDS:
COMMANDS[command](parser, options, args)
else:
parser.error("Unrecognised command: " + command)
if __name__ == "__main__":
main()
|
the-stack_106_26632 | '''
Comparison of basis data against authoritative sources
'''
from ..api import get_basis
from ..misc import compact_elements
from ..sort import sort_shells, sort_potentials
from ..lut import element_sym_from_Z
from .. import manip
from ..readers import read_formatted_basis_file
from .compare import _reldiff
def _print_list(lst):
'''
Prints a list from a comparison
'''
a = compact_elements(lst)
if a is not None:
return a
else:
return ""
def shells_difference(s1, s2):
"""
Computes and prints the differences between two lists of shells
If the shells contain a different number primitives,
or the lists are of different length, inf is returned.
Otherwise, the maximum relative difference is returned.
"""
max_rdiff = 0.0
nsh = len(s1)
if len(s2) != nsh:
print("Different number of shells: {} vs {}".format(len(s1), len(s2)))
return float('inf')
shells1 = sort_shells(s1)
shells2 = sort_shells(s2)
for n in range(nsh):
sh1 = shells1[n]
sh2 = shells2[n]
if sh1['angular_momentum'] != sh2['angular_momentum']:
print("Different angular momentum for shell {}".format(n))
return float('inf')
nprim = len(sh1['exponents'])
if len(sh2['exponents']) != nprim:
print("Different number of primitives for shell {}: {} vs {}".format(n, nprim, len(sh2['exponents'])))
return float('inf')
ngen = len(sh1['coefficients'])
if len(sh2['coefficients']) != ngen:
print("Different number of general contractions for shell {}: {} vs {}".format(
n, ngen, len(sh2['coefficients'])))
return float('inf')
for p in range(nprim):
e1 = sh1['exponents'][p]
e2 = sh2['exponents'][p]
r = _reldiff(e1, e2)
if r > 0.0:
print(" Exponent {:3}: {:20} {:20} -> {:16.8e}".format(p, e1, e2, r))
max_rdiff = max(max_rdiff, r)
for g in range(ngen):
c1 = sh1['coefficients'][g][p]
c2 = sh2['coefficients'][g][p]
r = _reldiff(c1, c2)
if r > 0.0:
print("Coefficient ({:3},{:3}): {:20} {:20} -> {:16.8e}".format(g, p, c1, c2, r))
max_rdiff = max(max_rdiff, r)
print()
print("Max relative difference for these shells: {}".format(max_rdiff))
return max_rdiff
def potentials_difference(p1, p2):
"""
Computes and prints the differences between two lists of potentials
If the shells contain a different number primitives,
or the lists are of different length, inf is returned.
Otherwise, the maximum relative difference is returned.
"""
max_rdiff = 0.0
np = len(p1)
if len(p2) != np:
print("Different number of potentials")
return float('inf')
pots1 = sort_potentials(p1)
pots2 = sort_potentials(p2)
for n in range(np):
pot1 = pots1[n]
pot2 = pots2[n]
if pot1['angular_momentum'] != pot2['angular_momentum']:
print("Different angular momentum for potential {}".format(n))
return float('inf')
nprim = len(pot1['gaussian_exponents'])
if len(pot2['gaussian_exponents']) != nprim:
print("Different number of primitives for potential {}".format(n))
return float('inf')
ngen = len(pot1['coefficients'])
if len(pot2['coefficients']) != ngen:
print("Different number of general contractions for potential {}".format(n))
return float('inf')
for p in range(nprim):
e1 = pot1['gaussian_exponents'][p]
e2 = pot2['gaussian_exponents'][p]
r = _reldiff(e1, e2)
if r > 0.0:
print(" Gaussian Exponent {:3}: {:20} {:20} -> {:16.8e}".format(p, e1, e2, r))
max_rdiff = max(max_rdiff, r)
e1 = pot1['r_exponents'][p]
e2 = pot2['r_exponents'][p]
r = _reldiff(e1, e2)
if r > 0.0:
print(" R Exponent {:3}: {:20} {:20} -> {:16.8e}".format(p, e1, e2, r))
max_rdiff = max(max_rdiff, r)
for g in range(ngen):
c1 = pot1['coefficients'][g][p]
c2 = pot2['coefficients'][g][p]
r = _reldiff(c1, c2)
if r > 0.0:
print(" Coefficient ({:3},{:3}): {:20} {:20} -> {:16.8e}".format(g, p, c1, c2, r))
max_rdiff = max(max_rdiff, r)
print()
print("Max relative difference for these potentials: {}".format(max_rdiff))
return max_rdiff
def basis_comparison_report(bs1, bs2, uncontract_general=False):
'''
Compares two basis set dictionaries and prints a report about their differences
'''
all_bs1 = list(bs1['elements'].keys())
if uncontract_general:
bs1 = manip.uncontract_general(bs1)
bs2 = manip.uncontract_general(bs2)
not_in_bs1 = [] # Found in bs2, not in bs1
not_in_bs2 = all_bs1.copy() # Found in bs1, not in bs2
no_diff = [] # Elements for which there is no difference
some_diff = [] # Elements that are different
big_diff = [] # Elements that are substantially different
for k, v in bs2['elements'].items():
if k not in all_bs1:
not_in_bs1.append(k)
continue
print()
print("-------------------------------------")
print(" Element {}: {}".format(k, element_sym_from_Z(k, True)))
bs1_el = bs1['elements'][k]
max_rdiff_el = 0.0
max_rdiff_ecp = 0.0
# Check to make sure that neither or both have ecp/electron shells
if 'electron_shells' in v and 'electron_shells' not in bs1_el:
print("bs2 has electron_shells, but bs1 does not")
max_rdiff_el = float('inf')
if 'electron_shells' in bs1_el and 'electron_shells' not in v:
print("bs1 has electron_shells, but bs2 does not")
max_rdiff_el = float('inf')
if 'ecp_potentials' in v and 'ecp_potentials' not in bs1_el:
print("bs2 has ecp_potentials, but bs1 does not")
max_rdiff_ecp = float('inf')
if 'ecp_potentials' in bs1_el and 'ecp_potentials' not in v:
print("bs1 has ecp_potentials, but bs2 does not")
max_rdiff_ecp = float('inf')
if 'electron_shells' in v and 'electron_shells' in bs1_el:
max_rdiff_el = max(max_rdiff_el, shells_difference(v['electron_shells'], bs1_el['electron_shells']))
if 'ecp_potentials' in v and 'ecp_potentials' in bs1_el:
nel1 = v['ecp_electrons']
nel2 = bs1_el['ecp_electrons']
if int(nel1) != int(nel2):
print('Different number of electrons replaced by ECP ({} vs {})'.format(nel1, nel2))
max_rdiff_ecp = float('inf')
else:
max_rdiff_ecp = max(max_rdiff_ecp, potentials_difference(v['ecp_potentials'],
bs1_el['ecp_potentials']))
max_rdiff = max(max_rdiff_el, max_rdiff_ecp)
# Handle some differences
if max_rdiff == float('inf'):
big_diff.append(k)
elif max_rdiff == 0.0:
no_diff.append(k)
else:
some_diff.append(k)
not_in_bs2.remove(k)
print()
print(" Not in bs1: ", _print_list(not_in_bs1))
print(" Not in bs2: ", _print_list(not_in_bs2))
print(" No difference: ", _print_list(no_diff))
print("Some difference: ", _print_list(some_diff))
print(" BIG difference: ", _print_list(big_diff))
print()
return (not not_in_bs1 and not not_in_bs2 and not some_diff and not big_diff)
def compare_basis_against_file(basis_name,
src_filepath,
file_type=None,
version=None,
uncontract_general=False,
data_dir=None):
'''Compare a basis set in the BSE against a reference file'''
bse_data = get_basis(basis_name, version=version, data_dir=data_dir)
src_data = read_formatted_basis_file(src_filepath, file_type)
return basis_comparison_report(bse_data, src_data, uncontract_general=uncontract_general)
def compare_basis_files(file_path_1, file_path_2, file_type_1=None, file_type_2=None, uncontract_general=False):
'''Compare two files containing formatted basis sets'''
bs1 = read_formatted_basis_file(file_path_1, file_type_1)
bs2 = read_formatted_basis_file(file_path_2, file_type_2)
return basis_comparison_report(bs1, bs2, uncontract_general)
def compare_basis_sets(basis_name_1,
basis_name_2,
version_1=None,
version_2=None,
uncontract_general=False,
data_dir_1=None,
data_dir_2=None):
'''Compare two files containing formatted basis sets'''
bs1 = get_basis(basis_name_1, version=version_1, data_dir=data_dir_1)
bs2 = get_basis(basis_name_2, version=version_2, data_dir=data_dir_2)
return basis_comparison_report(bs1, bs2, uncontract_general)
|
the-stack_106_26633 | # coding: utf-8
"""
Pure Storage FlashBlade REST 1.3 Python SDK
Pure Storage FlashBlade REST 1.3 Python SDK, developed by [Pure Storage, Inc](http://www.purestorage.com/). Documentations can be found at [purity-fb.readthedocs.io](http://purity-fb.readthedocs.io/).
OpenAPI spec version: 1.3
Contact: [email protected]
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re # noqa: F401
import six
class Blade(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
#BEGIN_CUSTOM
# IR-51527: Prevent Pytest from attempting to collect this class based on name.
__test__ = False
#END_CUSTOM
"""
Attributes:
swagger_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
swagger_types = {
'name': 'str',
'details': 'str',
'raw_capacity': 'int',
'target': 'str',
'progress': 'float',
'status': 'str'
}
attribute_map = {
'name': 'name',
'details': 'details',
'raw_capacity': 'raw_capacity',
'target': 'target',
'progress': 'progress',
'status': 'status'
}
def __init__(self, name=None, details=None, raw_capacity=None, target=None, progress=None, status=None): # noqa: E501
"""Blade - a model defined in Swagger""" # noqa: E501
self._name = None
self._details = None
self._raw_capacity = None
self._target = None
self._progress = None
self._status = None
self.discriminator = None
if name is not None:
self.name = name
if details is not None:
self.details = details
if raw_capacity is not None:
self.raw_capacity = raw_capacity
if target is not None:
self.target = target
if progress is not None:
self.progress = progress
if status is not None:
self.status = status
@property
def name(self):
"""Gets the name of this Blade. # noqa: E501
blade name # noqa: E501
:return: The name of this Blade. # noqa: E501
:rtype: str
"""
return self._name
@name.setter
def name(self, name):
"""Sets the name of this Blade.
blade name # noqa: E501
:param name: The name of this Blade. # noqa: E501
:type: str
"""
self._name = name
@property
def details(self):
"""Gets the details of this Blade. # noqa: E501
blade details # noqa: E501
:return: The details of this Blade. # noqa: E501
:rtype: str
"""
return self._details
@details.setter
def details(self, details):
"""Sets the details of this Blade.
blade details # noqa: E501
:param details: The details of this Blade. # noqa: E501
:type: str
"""
self._details = details
@property
def raw_capacity(self):
"""Gets the raw_capacity of this Blade. # noqa: E501
blade capacity in bytes # noqa: E501
:return: The raw_capacity of this Blade. # noqa: E501
:rtype: int
"""
return self._raw_capacity
@raw_capacity.setter
def raw_capacity(self, raw_capacity):
"""Sets the raw_capacity of this Blade.
blade capacity in bytes # noqa: E501
:param raw_capacity: The raw_capacity of this Blade. # noqa: E501
:type: int
"""
self._raw_capacity = raw_capacity
@property
def target(self):
"""Gets the target of this Blade. # noqa: E501
evacuation target # noqa: E501
:return: The target of this Blade. # noqa: E501
:rtype: str
"""
return self._target
@target.setter
def target(self, target):
"""Sets the target of this Blade.
evacuation target # noqa: E501
:param target: The target of this Blade. # noqa: E501
:type: str
"""
self._target = target
@property
def progress(self):
"""Gets the progress of this Blade. # noqa: E501
current operation progress # noqa: E501
:return: The progress of this Blade. # noqa: E501
:rtype: float
"""
return self._progress
@progress.setter
def progress(self, progress):
"""Sets the progress of this Blade.
current operation progress # noqa: E501
:param progress: The progress of this Blade. # noqa: E501
:type: float
"""
self._progress = progress
@property
def status(self):
"""Gets the status of this Blade. # noqa: E501
blade status # noqa: E501
:return: The status of this Blade. # noqa: E501
:rtype: str
"""
return self._status
@status.setter
def status(self, status):
"""Sets the status of this Blade.
blade status # noqa: E501
:param status: The status of this Blade. # noqa: E501
:type: str
"""
self._status = status
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
if issubclass(Blade, dict):
for key, value in self.items():
result[key] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, Blade):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""Returns true if both objects are not equal"""
return not self == other
|
the-stack_106_26635 | # flake8: noqa
import copy
from typing import List, Tuple, Union
from django import forms
from django.conf import settings
from django.forms import BaseForm, BaseInlineFormSet, BaseModelForm, BaseModelFormSet
from django.forms.forms import DeclarativeFieldsMetaclass
from django.forms.models import ModelFormMetaclass
from django.forms.widgets import Input
from django.utils.safestring import mark_safe
from .strings import LazyI18nString
class TextInput(Input):
input_type = "text"
template_name = "i18n/widgets/input.html"
def __init__(self, language, *args, **kwargs):
super().__init__(*args, **kwargs)
self.language = language
def get_context(self, *args, **kwargs):
context = super().get_context(*args, **kwargs)
context["language"] = self.language
return context
class TextArea(TextInput):
template_name = "i18n/widgets/textarea.html"
def __init__(self, language, *args, **kwargs):
attrs = kwargs.get("attrs", {})
default_attrs = {"cols": "40", "rows": "10"}
if attrs:
default_attrs.update(attrs)
kwargs["attrs"] = default_attrs
super().__init__(language, *args, **kwargs)
class I18nWidget(forms.MultiWidget):
"""
The default form widget for I18nCharField and I18nTextField. It makes
use of Django's MultiWidget mechanism and does some magic to save you
time.
"""
widget = TextInput
def __init__(self, locales: List[Tuple[str, str]], field: forms.Field, attrs=None):
widgets = []
self.locales = locales
self.enabled_locales = locales
self.field = field
for code, language in self.locales:
a = copy.copy(attrs) or {}
a["lang"] = code
widgets.append(self.widget(language=language, attrs=a))
super().__init__(widgets, attrs)
def decompress(self, value) -> List[Union[str, None]]:
data = []
first_enabled = None
any_enabled_filled = False
if not isinstance(value, LazyI18nString):
value = LazyI18nString(value)
for i, locale in enumerate(self.locales):
lng = locale[0]
dataline = (
value.data[lng]
if value is not None
and (
isinstance(value.data, dict)
or isinstance(value.data, LazyI18nString.LazyGettextProxy)
)
and lng in value.data
else None
)
if locale in self.enabled_locales:
if not first_enabled:
first_enabled = i
if dataline:
any_enabled_filled = True
data.append(dataline)
if (
value
and not isinstance(value.data, dict)
and not isinstance(value.data, LazyI18nString.LazyGettextProxy)
):
data[first_enabled] = value.data
elif value and not any_enabled_filled:
data[first_enabled] = value.localize(self.enabled_locales[0][0])
return data
def render(self, name: str, value, attrs=None, renderer=None) -> str:
if self.is_localized:
for widget in self.widgets:
widget.is_localized = self.is_localized
# value is a list of values, each corresponding to a widget
# in self.widgets.
if not isinstance(value, list):
value = self.decompress(value)
output = []
final_attrs = self.build_attrs(attrs or dict())
id_ = final_attrs.get("id", None)
for i, widget in enumerate(self.widgets):
locale = self.locales[i]
lang = locale[0]
if locale not in self.enabled_locales:
continue
try:
widget_value = value[i]
except IndexError:
widget_value = None
if id_:
final_attrs = dict(final_attrs, id="%s_%s" % (id_, i), title=lang)
output.append(
widget.render(
name + "_%s" % i, widget_value, final_attrs, renderer=renderer
)
)
return mark_safe(self.format_output(output))
def format_output(self, rendered_widgets) -> str:
return '<div class="i18n-form-group">%s</div>' % "".join(rendered_widgets)
class I18nTextInput(I18nWidget):
"""
The default form widget for I18nCharField. It makes use of Django's MultiWidget
mechanism and does some magic to save you time.
"""
widget = TextInput
class I18nTextarea(I18nWidget):
"""
The default form widget for I18nTextField. It makes use of Django's MultiWidget
mechanism and does some magic to save you time.
"""
widget = TextArea
class I18nFormField(forms.MultiValueField):
"""
The form field that is used by I18nCharField and I18nTextField. It makes use
of Django's MultiValueField mechanism to create one sub-field per available
language.
It contains special treatment to make sure that a field marked as "required" is validated
as "filled out correctly" if *at least one* translation is filled it. It is never required
to fill in all of them. This has the drawback that the HTML property ``required`` is set on
none of the fields as this would lead to irritating behaviour.
:param locales: An iterable of locale codes that the widget should render a field for. If
omitted, fields will be rendered for all languages configured in
``settings.LANGUAGES``.
:param require_all_fields: A boolean, if set to True field requires all translations to be given.
"""
def compress(self, data_list) -> LazyI18nString:
locales = self.locales
data = {}
for i, value in enumerate(data_list):
data[locales[i][0]] = value
return LazyI18nString(data)
def clean(self, value) -> LazyI18nString:
# if isinstance(value, LazyI18nString):
# # This happens e.g. if the field is disabled
# return value
found = False
found_all = True
clean_data = []
errors: List[str] = []
for i, field in enumerate(self.fields):
try:
field_value = value[i]
except (IndexError, TypeError):
field_value = None
if field_value not in self.empty_values:
found = True
elif field.locale in self.widget.enabled_locales:
found_all = False
try:
clean_data.append(field.clean(field_value))
except forms.ValidationError as e:
# Collect all validation errors in a single list, which we'll
# raise at the end of clean(), rather than raising a single
# exception for the first error we encounter. Skip duplicates.
errors.extend(m for m in e.error_list if m not in errors)
if errors:
raise forms.ValidationError(errors)
if self.one_required and not found:
raise forms.ValidationError(
self.error_messages["required"], code="required"
)
if self.require_all_fields and not found_all:
raise forms.ValidationError(
self.error_messages["incomplete"], code="incomplete"
)
out = self.compress(clean_data)
self.validate(out)
self.run_validators(out)
import json
return json.dumps(out.data)
def __init__(self, *args, **kwargs):
fields = []
defaults = {"widget": self.widget, "max_length": kwargs.pop("max_length", None)}
self.locales = kwargs.pop("locales", settings.LANGUAGES)
self.one_required = kwargs.get("required", True)
require_all_fields = kwargs.pop("require_all_fields", False)
kwargs["required"] = False
kwargs["widget"] = kwargs["widget"](
locales=self.locales, field=self, **kwargs.pop("widget_kwargs", {})
)
# encoder and decoder are defaults for JSONField, not for CharField!
kwargs.pop("encoder", "")
kwargs.pop("decoder", "")
defaults.update(**kwargs)
for lngcode, _ in self.locales:
defaults["label"] = "%s (%s)" % (defaults.get("label"), lngcode)
field = forms.CharField(**defaults)
field.locale = lngcode
fields.append(field)
super().__init__(fields=fields, require_all_fields=False, *args, **kwargs)
self.require_all_fields = require_all_fields
class I18nFormMixin:
def __init__(self, *args, **kwargs):
locales = kwargs.pop("locales", None)
super().__init__(*args, **kwargs)
if locales:
for k, field in self.fields.items():
if isinstance(field, I18nFormField):
field.widget.enabled_locales = locales
class BaseI18nModelForm(I18nFormMixin, BaseModelForm):
"""
This is a helperclass to construct an I18nModelForm.
"""
pass
class BaseI18nForm(I18nFormMixin, BaseForm):
"""
This is a helperclass to construct an I18nForm.
"""
pass
class I18nForm(BaseI18nForm, metaclass=DeclarativeFieldsMetaclass):
"""
This is a modified version of Django's Form which differs from Form in
only one way: The constructor takes one additional optional argument ``locales``
expecting a list of language codes. If given, this instance is used to select
the visible languages in all I18nFormFields of the form. If not given, all languages
from ``settings.LANGUAGES`` will be displayed.
:param locales: A list of locales that should be displayed.
"""
pass
class I18nModelForm(BaseI18nModelForm, metaclass=ModelFormMetaclass):
"""
This is a modified version of Django's ModelForm which differs from ModelForm in
only one way: The constructor takes one additional optional argument ``locales``
expecting a list of language codes. If given, this instance is used to select
the visible languages in all I18nFormFields of the form. If not given, all languages
from ``settings.LANGUAGES`` will be displayed.
:param locales: A list of locales that should be displayed.
"""
pass
class I18nFormSetMixin:
def __init__(self, *args, **kwargs):
self.locales = kwargs.pop("locales", None)
super().__init__(*args, **kwargs)
def _construct_form(self, i, **kwargs):
kwargs["locales"] = self.locales
return super()._construct_form(i, **kwargs)
@property
def empty_form(self):
form = self.form(
auto_id=self.auto_id,
prefix=self.add_prefix("__prefix__"),
empty_permitted=True,
use_required_attribute=False,
locales=self.locales,
)
self.add_fields(form, None)
return form
class I18nModelFormSet(I18nFormSetMixin, BaseModelFormSet):
"""
This is equivalent to a normal BaseModelFormset, but cares for the special needs
of I18nForms (see there for more information).
:param locales: A list of locales that should be displayed.
"""
pass
class I18nInlineFormSet(I18nFormSetMixin, BaseInlineFormSet):
"""
This is equivalent to a normal BaseInlineFormset, but cares for the special needs
of I18nForms (see there for more information).
:param locales: A list of locales that should be displayed.
"""
pass
|
the-stack_106_26636 | import json
import logging
import subprocess
import re
import sys
import unicodedata
from HTMLParser import HTMLParser
# Input text must be pre-processed for fastText to use
class MLStripper(HTMLParser):
def __init__(self):
self.reset()
self.fed = []
def handle_data(self, d):
self.fed.append(d)
def get_data(self):
return ''.join(self.fed)
def strip_html_tags(html):
s = MLStripper()
s.feed(html)
return s.get_data()
punctuation_table = dict.fromkeys(i for i in xrange(sys.maxunicode)
if unicodedata.category(unichr(i)).startswith('P'))
def preprocess_text(input):
s = input
s = strip_html_tags(s)
s = s.lower()
s = s.translate(punctuation_table) # Remove punctuation
return s
# Find existing hashtags so we do not recomment them again
def find_hashtags(text):
HASHTAG_REGEXP = r'\B(#[\w-]{3,})\b(?![#\-\w])'
return re.findall(HASHTAG_REGEXP, text)
# API endpoint returns recommendations and existing hashtags
def endpoint(event, context):
data = json.loads(event['body'])
if 'text' not in data:
logging.error("Validation Failed")
raise Exception("Couldn't read any provided text.")
return
raw_text = data['text']
clean_text = preprocess_text(raw_text)
p = subprocess.Popen(
['./fasttext', 'predict-prob', 'trained_models/model_standard.bin', '-', '5'],
stdout=subprocess.PIPE,
stdin=subprocess.PIPE,
stderr=subprocess.PIPE
)
stdout_recommendations = p.communicate(input=clean_text)
body = {
"hashtags_recommended": str(stdout_recommendations),
"hashtags_already_used": str(" ".join(find_hashtags(raw_text)))
}
response = {
"statusCode": 200,
"headers": {
"Access-Control-Allow-Origin" : "*", # Required for CORS support to work
"Access-Control-Allow-Credentials" : "true"
},
"body": json.dumps(body)
}
return response
|
the-stack_106_26637 | import pytest
import time
from esclient import TextfileDocument
@pytest.fixture
def textfile_document(request):
textfile_document = TextfileDocument()
textfile_document.delete_index()
textfile_document.put_index()
textfile_document.put_mapping()
def clean_up():
textfile_document.delete_index()
request.addfinalizer(clean_up)
return textfile_document
@pytest.fixture
def s3_tuple_list():
return [
("bucket", "key", 1024),
("bucket", "key2", 1028)
]
@pytest.fixture
def example_textfile_data_list(s3_tuple_list):
data_list = [
{
"title" : "test title",
"extension" : "pdf",
"s3_tuple" : s3_tuple_list[0],
"content" : "this is a pdf document"
},
{
"title" : "test title 2",
"extension" : "docx",
"s3_tuple" : s3_tuple_list[1],
"content" : "this is a docx file"
}
]
return data_list
def test_create_document(textfile_document, s3_tuple_list, example_textfile_data_list):
tx = textfile_document
for s3_tuple, example_textfile in zip(s3_tuple_list, example_textfile_data_list):
pid = tx.create_pid(s3_tuple)
document = tx.create_doc_entry(**example_textfile)
response = tx.put_document(pid, document)
response = tx.get_document(pid)
assert example_textfile["title"] == response.json()["_source"]["title"]
assert example_textfile["content"] == response.json()["_source"]["content"]
# Wait for eventual consistency
time.sleep(1)
response = tx.query_all()
assert len(example_textfile_data_list) == response.json()["hits"]["total"]
def test_create_document_bulk(textfile_document, s3_tuple_list, example_textfile_data_list):
tx = textfile_document
pid_list = [tx.create_pid(s3_tuple) for s3_tuple in s3_tuple_list]
document_list = [tx.create_doc_entry(**example_textfile) for example_textfile in example_textfile_data_list]
response = tx.put_document_bulk(pid_list, document_list)
# Wait for eventual consistency
time.sleep(1)
response = tx.query_all()
assert len(example_textfile_data_list) == response.json()["hits"]["total"]
|
the-stack_106_26639 | #!/usr/bin/env python
import sys
import tensorflow as tf
import numpy as np
if len(sys.argv) == 2:
ckpt_fpath = sys.argv[1]
else:
print('Usage: python count_ckpt_param.py path-to-ckpt')
sys.exit(1)
# Open TensorFlow ckpt and count the number of trainable parameters in the model
reader = tf.train.NewCheckpointReader(ckpt_fpath)
print('\nCount the number of parameters in ckpt file(%s)' % ckpt_fpath)
param_map = reader.get_variable_to_shape_map()
total_count = 0
for k, v in param_map.items():
#if 'Momentum' not in k and 'global_step' not in k:
temp = np.prod(v)
total_count += temp
print('%s: %s => %d' % (k, str(v), temp))
print('Total Param Count: %d' % total_count)
|
the-stack_106_26640 | import os
import re
import mock
import requests
import shutil
import subprocess
import _test_helpers as helpers
def make_r_side_effect(recognized = True):
'''
Make a mock of mocks subprocess.check_output() for R CMD BATCH commands
The executable_recognized argument determines whether "R"
is a recognized executable on the mock platform.
'''
def side_effect(*args, **kwargs):
'''
This side effect mocks the behaviour of a subprocess.check_output()
call on a machine with R set up for command-line use.
'''
# Get and parse the command passed to os.system()
command = args[0]
if re.search('R', command, flags = re.I) and not recognized:
raise subprocess.CalledProcessError(1, command)
match = helpers.command_match(command, 'R')
executable = match.group('executable')
log = match.group('log')
append = match.group('append')
if log is None:
# If no log path is specified, create one by using the
# R script's path after replacing .R (if present) with .log.
source = match.group('source')
log = '%s.log' % re.sub('\.R', '', source)
if executable == 'Rscript' and log and append == '2>&1':
with open(log.replace('>', '').strip(), 'wb') as log_file:
log_file.write('Test log\n')
with open('./test_output.txt', 'wb') as target:
target.write('Test target')
return side_effect
def python_side_effect(*args, **kwargs):
''' Mock subprocess.check_output for testing build_python()'''
command = args[0]
match = helpers.command_match(command, 'python')
if match.group('log'):
log_path = re.sub('(\s|>)', '', match.group('log'))
with open(log_path, 'wb') as log_file:
log_file.write('Test log')
with open('./test_output.txt', 'wb') as target:
target.write('Test target')
def make_matlab_side_effect(recognized = True):
'''
Make a mock of subprocess.check_output() for Matlab commands
The recognized argument determines whether "matlab"
is a recognized executable on the mock platform.
'''
def side_effect(*args, **kwargs):
try:
command = kwargs['command']
except KeyError:
command = args[0]
if re.search('^matlab', command, flags = re.I) and not recognized:
raise subprocess.CalledProcessError(1, command)
log_match = re.search('> (?P<log>[-\.\w\/]+)', command)
if log_match:
log_path = log_match.group('log')
with open(log_path, 'wb') as log_file:
log_file.write('Test log')
with open('./test_output.txt', 'wb') as target:
target.write('Test target')
return None
return side_effect
def matlab_copy_effect(*args, **kwargs):
'''Mock copy so that it creates a file with the destination's path'''
open(args[1], 'wb').write('test')
def make_stata_side_effect(recognized = True):
'''
Make a side effect mocking the behaviour of
subprocess.check_output() when `recognized` is
the only recognised system command.
'''
def stata_side_effect(*args, **kwargs):
command = args[0]
match = helpers.command_match(command, 'stata')
if match.group('executable') == recognized:
# Find the Stata script's name
script_name = match.group('source')
stata_log = os.path.basename(script_name).replace('.do', '.log')
# Write a log
with open(stata_log, 'wb') as logfile:
logfile.write('Test Stata log.\n')
with open('./test_output.txt', 'wb') as target:
target.write('Test target')
else:
# Raise an error if the executable is not recognised.
raise subprocess.CalledProcessError(1, command)
return stata_side_effect
def make_stata_path_effect(executable):
'''
Return a side effect for misc.is_in_path() that returns
True iff the function's argument equals `executable`.
'''
def side_effect(*args, **kwargs):
return (args[0] == executable)
return side_effect
def lyx_side_effect(*args, **kwargs):
'''
This side effect mocks the behaviour of a subprocess.check_output call.
The mocked machine has lyx set up as a command-line executable
and can export .lyx files to .pdf files only using
the "-e pdf2" option.
'''
# Get and parse the command passed to os.system()
command = args[0]
match = helpers.command_match(command, 'lyx')
executable = match.group('executable')
option = match.group('option')
source = match.group('source')
log_redirect = match.group('log_redirect')
option_type = re.findall('^(-\w+)', option)[0]
option_setting = re.findall('\s(\w+)$', option)[0]
is_lyx = bool(re.search('^lyx$', executable, flags = re.I))
# As long as output is redirected, create a log
if log_redirect:
log_path = re.sub('>\s*', '', log_redirect)
with open(log_path, 'wb') as log_file:
log_file.write('Test log\n')
# If LyX is the executable, the options are correctly specified,
# and the source exists, produce a .pdf file with the same base
# name as the source file.
# Mock a list of the files that LyX sees as existing
# source_exists should be True only if the source script
# specified in the system command belongs to existing_files.
existing_files = ['test_script.lyx', './input/lyx_test_file.lyx']
source_exists = os.path.abspath(source) in \
map(os.path.abspath, existing_files)
if is_lyx and option_type == '-e' and option_setting == 'pdf2' \
and source_exists:
out_path = re.sub('lyx$', 'pdf', source, flags = re.I)
with open(out_path, 'wb') as out_file:
out_file.write('Mock .pdf output')
def latex_side_effect(*args, **kwargs):
'''
This side effect mocks the behaviour of a subprocess.check_output call.
The mocked machine has pdflatex set up as a command-line executable
and can export .tex files to .pdf files only using the "-jobname" option.
'''
# Get and parse the command passed to os.system()
command = args[0]
match = helpers.command_match(command, 'pdflatex')
executable = match.group('executable')
option1 = match.group('option1')
option2 = match.group('option2')
source = match.group('source')
log_redirect = match.group('log_redirect')
option1_type = re.findall('^(-\w+)', option1)[0]
interaction = re.findall('\s(\S+)', option1)[0]
option2_type = re.findall('^(-\w+)', option2)[0]
target_file = re.findall('\s(\S+)', option2)[0]
is_pdflatex = bool(re.search('^pdflatex$', executable, flags = re.I))
# As long as output is redirected, create a log
if log_redirect:
log_path = re.sub('>\s*', '', log_redirect)
with open(log_path, 'wb') as log_file:
log_file.write('Test log\n')
# If pdflatex is the executable, the options are correctly specified,
# and the source exists, produce a .pdf file with the name specified in
# the -jobname option.
# Mock a list of the files that pdflatex sees as existing
# source_exists should be True only if the source script
# specified in the system command belongs to existing_files.
existing_files = ['test_script.tex', './input/latex_test_file.tex']
source_exists = os.path.abspath(source) in \
map(os.path.abspath, existing_files)
if is_pdflatex and source_exists and option1_type == '-interaction' and option2_type == '-jobname':
with open('%s.pdf' % target_file, 'wb') as out_file:
out_file.write('Mock .pdf output')
with open('%s.log' % target_file, 'wb') as out_file:
out_file.write('Mock .log output')
def make_call_side_effect(text):
'''
Intended for mocking the subprocess.call() in testing
_release_tools.up_to_date(). Return a side effect that
prints text to mocked function's stdout argument.
'''
def side_effect(*args, **kwargs):
log = kwargs['stdout']
log.write(text)
return side_effect
def upload_asset_side_effect(*args, **kwargs):
'''
This side effect, intended for mocking
_release_tools.upload_asset() in testing release(),
copies an asset so it can be checked by tests.
'''
assets_path = kwargs['file_name']
shutil.copyfile(assets_path, 'assets_listing.txt')
def post_side_effect(*args, **kwargs):
'''
Intended for mocking requests.session.post in testing release().
This side effect returns a MagicMock that raises an error
when its raise_for_status() method is called unless
a specific release_path is specified.
'''
# The release path is specified by the first positional argument.
mock_output = mock.MagicMock(raise_for_status = mock.MagicMock())
release_path = args[0]
real_path = "https://test_token:@api.github.com/repos/org/repo/releases"
def raise_http_error():
raise requests.exceptions.HTTPError('404 Client Error')
if release_path != real_path:
mock_output.raise_for_status.side_effect = raise_http_error
return mock_output
def dot_git_open_side_effect(repo = 'repo',
org = 'org',
branch = 'branch',
url = True):
'''
This function produces a side effect mocking the behaviour of
open() when used to read the lines of the 'config' or 'HEAD' file
of a GitHub repository's '.git' directory.
'''
def open_side_effect(*args, **kwargs):
path = args[0]
if path not in ['.git/config', '.git/HEAD']:
raise Exception('Cannot open %s' % path)
# If specified by the url argument, include the url of the origin
# in the mock .git file, as is standard.
github_url = '\turl = https://github.com/%s/%s\n' % (org, repo)
github_url = ['', github_url][int(url)]
if path == '.git/config':
# These are the mocked contents of a .git/config file
lines = ['[core]\n',
'\trepositoryformatversion = 0\n',
'\tfilemode = true\n',
'\tbare = false\n',
'\tlogallrefupdates = true\n',
'\tignorecase = true\n',
'\tprecomposeunicode = true\n',
'[remote "origin"]\n',
github_url,
'\tfetch = +refs/heads/*:refs/remotes/origin/*\n',
'[branch "master"]\n',
'\tremote = origin\n',
'\tmerge = refs/heads/master\n']
elif path == '.git/HEAD':
# These are the mocked contents of a .git/HEAD file
lines = ['ref: refs/heads/%s\n' % branch]
# Ultimately return a mock whose readlines() method
# just returns a list of lines from our mocked-up file.
file_object = mock.MagicMock(readlines = lambda: lines)
return file_object
return open_side_effect
|
the-stack_106_26641 | import os
import sys
import logging
import subprocess
from typing import List, NoReturn, Union, Any
from . import __pyright_version__, node
from .utils import env_to_bool
__all__ = (
'run',
'main',
)
log: logging.Logger = logging.getLogger(__name__)
def main(args: List[str], **kwargs: Any) -> int:
return run(*args, **kwargs).returncode
def run(
*args: str, **kwargs: Any
) -> Union['subprocess.CompletedProcess[bytes]', 'subprocess.CompletedProcess[str]']:
version = os.environ.get('PYRIGHT_PYTHON_FORCE_VERSION', __pyright_version__)
if version == 'latest':
version = node.latest('pyright')
npx = node.version('npx')
if npx[0] >= 7:
pre_args = ['--yes']
if not env_to_bool('PYRIGHT_PYTHON_VERBOSE', default=False):
pre_args.insert(0, '--silent')
else:
pre_args = []
if args and pre_args:
pre_args = (*pre_args, '--')
return node.run('npx', *pre_args, f'pyright@{version}', *args, **kwargs)
def entrypoint() -> NoReturn:
sys.exit(main(sys.argv[1:]))
|
the-stack_106_26642 | #!/usr/bin/env python3
"""
NAPALM using nxos_ssh has the following data structure in one of its unit tests (the below data is in JSON format).
{
"Ethernet2/1": {
"ipv4": {
"1.1.1.1": {
"prefix_length": 24
}
}
},
"Ethernet2/2": {
"ipv4": {
"2.2.2.2": {
"prefix_length": 27
},
"3.3.3.3": {
"prefix_length": 25
}
}
},
"Ethernet2/3": {
"ipv4": {
"4.4.4.4": {
"prefix_length": 16
}
},
"ipv6": {
"fe80::2ec2:60ff:fe4f:feb2": {
"prefix_length": 64
},
"2001:db8::1": {
"prefix_length": 10
}
}
},
"Ethernet2/4": {
"ipv6": {
"fe80::2ec2:60ff:fe4f:feb2": {
"prefix_length": 64
},
"2001:11:2233::a1": {
"prefix_length": 24
},
"2001:cc11:22bb:0:2ec2:60ff:fe4f:feb2": {
"prefix_length": 64
}
}
}
}
Read this JSON data in from a file.
From this data structure extract all of the IPv4 and IPv6 addresses that are used on this NXOS device.
From this data create two lists: 'ipv4_list' and 'ipv6_list'.
The 'ipv4_list' should be a list of all of the IPv4 addresses including prefixes;
the 'ipv6_list' should be a list of all of the IPv6 addresses including prefixes.
"""
import json
ipv4_list = []
ipv6_list = []
filename = "nxosinterfaces.json"
with open(filename, 'r') as f:
ip_data = json.load(f)
for key1, ip_item1 in ip_data.items():
for key2, ip_item2 in ip_item1.items():
for key3, ip_item3 in ip_item2.items():
new_ip = ""
new_ip = str(key3) + "/" + str(ip_item3['prefix_length'])
if key2 == 'ipv4':
ipv4_list.append(new_ip)
else:
ipv6_list.append(new_ip)
print(ipv4_list)
print(ipv6_list)
|
the-stack_106_26643 | import argparse
import os
import pathlib
import random
import typing
import pycspr
from pycspr.client import NodeClient
from pycspr.client import NodeConnectionInfo
from pycspr.types import Deploy
from pycspr.types import PrivateKey
from pycspr.types import PublicKey
from pycspr.types import UnforgeableReference
# CLI argument parser.
_ARGS = argparse.ArgumentParser("Demo illustrating how to execute native transfers with pycspr.")
# CLI argument: path to cp2 account key - defaults to NCTL user 2.
_ARGS.add_argument(
"--account-key-path",
default=pathlib.Path(os.getenv("NCTL")) / "assets" / "net-1" / "users" / "user-1" / "public_key_hex",
dest="path_to_account_key",
help="Path to a test user's public_key_hex file.",
type=str,
)
# CLI argument: host address of target node - defaults to NCTL node 1.
_ARGS.add_argument(
"--node-host",
default="localhost",
dest="node_host",
help="Host address of target node.",
type=str,
)
# CLI argument: Node API REST port - defaults to 14101 @ NCTL node 1.
_ARGS.add_argument(
"--node-port-rest",
default=14101,
dest="node_port_rest",
help="Node API REST port. Typically 8888 on most nodes.",
type=int,
)
# CLI argument: Node API JSON-RPC port - defaults to 11101 @ NCTL node 1.
_ARGS.add_argument(
"--node-port-rpc",
default=11101,
dest="node_port_rpc",
help="Node API JSON-RPC port. Typically 7777 on most nodes.",
type=int,
)
# CLI argument: Node API SSE port - defaults to 18101 @ NCTL node 1.
_ARGS.add_argument(
"--node-port-sse",
default=18101,
dest="node_port_sse",
help="Node API SSE port. Typically 9999 on most nodes.",
type=int,
)
def _main(args: argparse.Namespace):
"""Main entry point.
:param args: Parsed command line arguments.
"""
# Set client.
client = _get_client(args)
# Set account key of test user.
user_public_key = pycspr.factory.parse_public_key(args.path_to_account_key)
# Query 0.1: get_rpc_schema.
rpc_schema: typing.List[dict] = client.queries.get_rpc_schema()
assert isinstance(rpc_schema, dict)
print("SUCCESS :: Query 0.1: get_rpc_schema")
# Query 0.2: get_rpc_endpoints.
rpc_endpoints: typing.List[str] = client.queries.get_rpc_endpoints()
assert isinstance(rpc_endpoints, list)
print("SUCCESS :: Query 0.2: get_rpc_endpoints")
# Query 0.3: get_rpc_endpoint.
rpc_endpoint: dict = client.queries.get_rpc_endpoint("account_put_deploy")
assert isinstance(rpc_endpoint, dict)
print("SUCCESS :: Query 0.3: get_rpc_endpoint")
# Query 1.1: get_node_metrics.
node_metrics: typing.List[str] = client.queries.get_node_metrics()
assert isinstance(node_metrics, list)
print("SUCCESS :: Query 1.1: get_node_metrics")
# Query 1.2: get_node_metric.
node_metric: typing.List[str] = client.queries.get_node_metric("mem_deploy_gossiper")
assert isinstance(node_metrics, list)
print("SUCCESS :: Query 1.2: get_node_metric")
# Query 1.3: get_node_peers.
node_peers: typing.List[dict] = client.queries.get_node_peers()
assert isinstance(node_peers, list)
print("SUCCESS :: Query 1.3: get_node_peers")
# Query 1.4: get_node_status.
node_status: typing.List[dict] = client.queries.get_node_status()
assert isinstance(node_status, dict)
print("SUCCESS :: Query 1.4: get_node_status")
# Query 2.1: get_state_root_hash - required for global state related queries.
state_root_hash: bytes = client.queries.get_state_root_hash()
assert isinstance(state_root_hash, bytes)
print("SUCCESS :: Query 2.1: get_state_root_hash")
# Query 2.2: get_account_info.
account_info = client.queries.get_account_info(user_public_key.account_key)
assert isinstance(account_info, dict)
print("SUCCESS :: Query 2.2: get_account_info")
# Query 2.3: get_account_main_purse_uref.
account_main_purse = client.queries.get_account_main_purse_uref(user_public_key.account_key)
assert isinstance(account_main_purse, UnforgeableReference)
print("SUCCESS :: Query 2.3: get_account_main_purse_uref")
# Query 2.4: get_account_balance.
account_balance = client.queries.get_account_balance(account_main_purse, state_root_hash)
assert isinstance(account_balance, int)
print("SUCCESS :: Query 2.4: get_account_balance")
# Query 3.1: get_block_at_era_switch - will poll until switch block.
print("POLLING :: Query 3.1: get_block_at_era_switch - may take some time")
block: dict = client.queries.get_block_at_era_switch()
assert isinstance(block, dict)
print("SUCCESS :: Query 3.1: get_block_at_era_switch")
# Query 3.2: get_block - by hash & by height.
assert client.queries.get_block(block["hash"]) == \
client.queries.get_block(block["header"]["height"])
print("SUCCESS :: Query 3.2: get_block - by hash & by height")
# Query 3.3: get_block_transfers - by hash & by height.
block_transfers = client.queries.get_block_transfers(block["hash"])
assert isinstance(block_transfers, tuple)
assert isinstance(block_transfers[0], str) # black hash
assert isinstance(block_transfers[1], list) # set of transfers
assert block_transfers == client.queries.get_block_transfers(block["header"]["height"])
print("SUCCESS :: Query 3.3: get_block_transfers - by hash & by height")
# Query 4.1: get_auction_info.
auction_info = client.queries.get_auction_info()
assert isinstance(auction_info, dict)
print("SUCCESS :: Query 4.1: get_auction_info")
# Query 4.2: get_era_info - by switch block hash.
era_info = client.queries.get_era_info(block["hash"])
assert isinstance(era_info, dict)
print("SUCCESS :: Query 4.2: get_era_info - by switch block hash")
# Query 4.3: get_era_info - by switch block height.
assert client.queries.get_era_info(block["hash"]) == \
client.queries.get_era_info(block["header"]["height"])
print("SUCCESS :: Query 4.3: get_era_info - by switch block height")
def _get_client(args: argparse.Namespace) -> NodeClient:
"""Returns a pycspr client instance.
"""
connection = NodeConnectionInfo(
host=args.node_host,
port_rest=args.node_port_rest,
port_rpc=args.node_port_rpc,
port_sse=args.node_port_sse
)
return NodeClient(connection)
def _get_counter_parties(args: argparse.Namespace) -> PublicKey:
"""Returns the 2 counter-parties participating in the transfer.
"""
return pycspr.factory.parse_public_key(
args.path_to_cp2_account_key
)
return cp1, cp2
# Entry point.
if __name__ == '__main__':
_main(_ARGS.parse_args())
|
the-stack_106_26647 | #
# This file is part of BDC Core.
# Copyright (C) 2019-2020 INPE.
#
# BDC Core is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
#
"""Authentication decorators such scope validator and token require."""
from functools import wraps
import os
import jwt
from flask import request
from werkzeug.exceptions import Forbidden, HTTPException, Unauthorized
def get_token() -> str:
"""Retrieves token from request intercept."""
try:
bearer, authorization = request.headers['Authorization'].split()
if 'bearer' not in bearer.lower():
raise Forbidden('Invalid token. Please login!')
return authorization
except Exception:
raise Forbidden('Token is required. Please login!')
def validate_scope(scope_required, scope_token):
"""Validates user token scope.
Args:
scope_required (str) - OAuth scope required
scope_token (dict) - Token object
Exceptions:
Unauthorized when scope is not allowed
"""
if scope_required:
service, function, actions = scope_required.split(':')
if (service != scope_token['type'] and scope_token['type'] != '*') or \
(function != scope_token['name'] and scope_token['name'] != '*') or \
(actions not in scope_token['actions'] and '*' not in scope_token['actions']):
raise Unauthorized('Scope not allowed!')
def require_oauth_scopes(scope):
"""Flask decorator to require OAuth scope in request intercept.
Make sure to export the following variables:
- `CLIENT_SECRET_KEY` OAuth client secret
- `CLIENT_AUDIENCE` OAuth client audience control
Example:
>>> from flask import Flask
>>> from bdc_core.decorators.auth import require_oauth_scopes
>>>
>>> app = Flask('')
>>> @app.route('/edit/<int:thing_id>')
... @require_oauth_scopes('app:thing:edit')
... def edit_something(thing_id):
... # put logic here
... return dict()
Args:
scope (str) - Required scope to match
Returns:
Wrapped function which performs request validation
"""
def jwt_required(func):
@wraps(func)
def wrapper(*args, **kwargs):
if not os.environ.get('CLIENT_SECRET_KEY'):
raise HTTPException('Set CLIENT_SECRET_KEY in environment variable')
if not os.environ.get('CLIENT_AUDIENCE'):
raise HTTPException('Set CLIENT_AUDIENCE in environment variable')
try:
token = get_token()
payload = jwt.decode(
token,
os.environ.get('CLIENT_SECRET_KEY'),
verify=True,
algorithms=['HS512'],
audience=os.environ.get('CLIENT_AUDIENCE')
)
if payload.get('user_id'):
request.user_id = payload['user_id']
validate_scope(scope, payload['access'][0])
return func(*args, **kwargs)
raise Forbidden('Incomplete token. Please login!')
except jwt.ExpiredSignatureError:
raise Forbidden('This token has expired. Please login!')
except jwt.InvalidTokenError:
raise Forbidden('Invalid token. Please login!')
return wrapper
return jwt_required
|
the-stack_106_26651 | import matplotlib.pyplot as plt
import numpy as np
lines = open('log.txt').readlines()
scores = []
# print(len(lines))
for line in lines:
score = line.split(' ')[5]
score = score.split('\n')
if len(score) > 1:
scores.append(float(score[0]))
plt.plot(scores)
plt.show() |
the-stack_106_26653 | # -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# Generated code. DO NOT EDIT!
#
# Snippet for ListTensorboardTimeSeries
# NOTE: This snippet has been automatically generated for illustrative purposes only.
# It may require modifications to work in your environment.
# To install the latest published package dependency, execute the following:
# python3 -m pip install google-cloud-aiplatform
# [START aiplatform_generated_aiplatform_v1beta1_TensorboardService_ListTensorboardTimeSeries_async]
from google.cloud import aiplatform_v1beta1
async def sample_list_tensorboard_time_series():
"""Snippet for list_tensorboard_time_series"""
# Create a client
client = aiplatform_v1beta1.TensorboardServiceAsyncClient()
# Initialize request argument(s)
request = aiplatform_v1beta1.ListTensorboardTimeSeriesRequest(
parent="projects/{project}/locations/{location}/tensorboards/{tensorboard}/experiments/{experiment}/runs/{run}/timeSeries/{time_series}",
)
# Make the request
page_result = client.list_tensorboard_time_series(request=request)
async for response in page_result:
print(response)
# [END aiplatform_generated_aiplatform_v1beta1_TensorboardService_ListTensorboardTimeSeries_async]
|
the-stack_106_26655 | # encoding: latin2
"""Transport Layer geometry
"""
__author__ = "Juan C. Duque, Alejandro Betancourt"
__credits__ = "Copyright (c) 2009-10 Juan C. Duque"
__license__ = "New BSD License"
__version__ = "1.0.0"
__maintainer__ = "RiSE Group"
__email__ = "[email protected]"
__all__ = ['getBbox']
# transportLayer
def getBbox(layer):
"""
Finds the layer's bounding box
:param layer: object layer
:type layer: Layer
This is how you can ask for a bounding box of a layer
>>> layer.bbox
**Example**
>>> import clusterpy
>>> clusterpy.importArcData("../data_examples/china")
>>> china.bbox
"""
xmin = xmax = layer.areas[0][0][0][0]
ymin = ymax = layer.areas[0][0][0][1]
for area in layer.areas:
for ring in area:
for point in ring:
if point[0] < xmin:
xmin = point[0]
if point[0] > xmax:
xmax = point[0]
if point[1] < ymin:
ymin = point[1]
if point[1] > ymax:
ymax = point[1]
return xmin, ymin, xmax, ymax
|
the-stack_106_26656 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from math import exp, pi
import os
import random
import torch
import unittest
import gpytorch
from torch import optim
from gpytorch.kernels import RBFKernel, ScaleKernel
from gpytorch.likelihoods import BernoulliLikelihood
from gpytorch.means import ConstantMean
from gpytorch.priors import SmoothedBoxPrior
from gpytorch.distributions import MultivariateNormal
train_x = torch.linspace(0, 1, 10)
train_y = torch.sign(torch.cos(train_x * (16 * pi)))
class GPClassificationModel(gpytorch.models.GridInducingVariationalGP):
def __init__(self):
super(GPClassificationModel, self).__init__(grid_size=32, grid_bounds=[(0, 1)])
self.mean_module = ConstantMean(prior=SmoothedBoxPrior(-5, 5))
self.covar_module = ScaleKernel(
RBFKernel(log_lengthscale_prior=SmoothedBoxPrior(exp(-5), exp(6), sigma=0.1, log_transform=True)),
log_outputscale_prior=SmoothedBoxPrior(exp(-5), exp(6), sigma=0.1, log_transform=True),
)
def forward(self, x):
mean_x = self.mean_module(x)
covar_x = self.covar_module(x)
latent_pred = MultivariateNormal(mean_x, covar_x)
return latent_pred
class TestKISSGPClassification(unittest.TestCase):
def setUp(self):
if os.getenv("UNLOCK_SEED") is None or os.getenv("UNLOCK_SEED").lower() == "false":
self.rng_state = torch.get_rng_state()
torch.manual_seed(0)
if torch.cuda.is_available():
torch.cuda.manual_seed_all(0)
random.seed(0)
def tearDown(self):
if hasattr(self, "rng_state"):
torch.set_rng_state(self.rng_state)
def test_kissgp_classification_error(self):
model = GPClassificationModel()
likelihood = BernoulliLikelihood()
mll = gpytorch.mlls.VariationalMarginalLogLikelihood(likelihood, model, num_data=len(train_y))
# Find optimal model hyperparameters
model.train()
likelihood.train()
optimizer = optim.SGD(model.parameters(), lr=0.01)
optimizer.n_iter = 0
for _ in range(200):
optimizer.zero_grad()
output = model(train_x)
loss = -mll(output, train_y)
loss.backward()
optimizer.n_iter += 1
optimizer.step()
for _, param in model.named_parameters():
self.assertTrue(param.grad is not None)
self.assertGreater(param.grad.norm().item(), 0)
for param in likelihood.parameters():
self.assertTrue(param.grad is not None)
self.assertGreater(param.grad.norm().item(), 0)
# Set back to eval mode
model.eval()
likelihood.eval()
test_preds = likelihood(model(train_x)).mean.ge(0.5).float().mul(2).sub(1).squeeze()
mean_abs_error = torch.mean(torch.abs(train_y - test_preds) / 2)
self.assertLess(mean_abs_error.squeeze().item(), 1e-5)
if __name__ == "__main__":
unittest.main()
|
the-stack_106_26657 | import time
import board
import busio
import adafruit_bno055
import numpy as np
np.set_printoptions(linewidth=np.inf, precision=6, suppress=True)
i2c = busio.I2C(board.SCL, board.SDA)
sensor = adafruit_bno055.BNO055_I2C(i2c)
sensor.mode = adafruit_bno055.IMUPLUS_MODE
tt = None
for i in range(1000000):
t0 = time.clock()
g = sensor.gyro
t1 = time.clock()
t = (t1-t0)
if tt is None:
tt = t
else:
if t > tt:
tt = t
print(tt, t)
# print(np.array(sensor._euler))
# time.sleep(1.0/50.0)
|
the-stack_106_26658 | import json
from snet.snet_cli.utils.utils import get_address_from_private, get_contract_object, normalize_private_key
DEFAULT_GAS = 300000
TRANSACTION_TIMEOUT = 500
class TransactionError(Exception):
"""Raised when an Ethereum transaction receipt has a status of 0. Can provide a custom message. Optionally includes receipt"""
def __init__(self, message, receipt=None):
super().__init__(message)
self.message = message
self.receipt = receipt
def __str__(self):
return self.message
class Account:
def __init__(self, w3, config, mpe_contract):
self.config = config
self.web3 = w3
self.mpe_contract = mpe_contract
_token_contract_address = self.config.get("token_contract_address", None)
if _token_contract_address is None:
self.token_contract = get_contract_object(
self.web3, "SingularityNetToken.json")
else:
self.token_contract = get_contract_object(
self.web3, "SingularityNetToken.json", _token_contract_address)
private_key = config.get("private_key", None)
signer_private_key = config.get("signer_private_key", None)
if private_key is not None:
self.private_key = normalize_private_key(config["private_key"])
if signer_private_key is not None:
self.signer_private_key = normalize_private_key(
config["signer_private_key"])
else:
self.signer_private_key = self.private_key
self.address = get_address_from_private(self.private_key)
self.signer_address = get_address_from_private(self.signer_private_key)
self.nonce = 0
def _get_nonce(self):
nonce = self.web3.eth.getTransactionCount(self.address)
if self.nonce >= nonce:
nonce = self.nonce + 1
self.nonce = nonce
return nonce
def _get_gas_price(self):
return int(self.web3.eth.generateGasPrice())
def _send_signed_transaction(self, contract_fn, *args):
transaction = contract_fn(*args).buildTransaction({
"chainId": int(self.web3.version.network),
"gas": DEFAULT_GAS,
"gasPrice": self._get_gas_price(),
"nonce": self._get_nonce()
})
signed_txn = self.web3.eth.account.signTransaction(
transaction, private_key=self.private_key)
return self.web3.toHex(self.web3.eth.sendRawTransaction(signed_txn.rawTransaction))
def send_transaction(self, contract_fn, *args):
txn_hash = self._send_signed_transaction(contract_fn, *args)
return self.web3.eth.waitForTransactionReceipt(txn_hash, TRANSACTION_TIMEOUT)
def _parse_receipt(self, receipt, event, encoder=json.JSONEncoder):
if receipt.status == 0:
raise TransactionError("Transaction failed", receipt)
else:
return json.dumps(dict(event().processReceipt(receipt)[0]["args"]), cls=encoder)
def escrow_balance(self):
return self.mpe_contract.balance(self.address)
def deposit_to_escrow_account(self, amount_in_cogs):
already_approved = self.allowance()
if amount_in_cogs > already_approved:
self.approve_transfer(amount_in_cogs)
return self.mpe_contract.deposit(self, amount_in_cogs)
def approve_transfer(self, amount_in_cogs):
return self.send_transaction(self.token_contract.functions.approve,self.mpe_contract.contract.address, amount_in_cogs)
def allowance(self):
return self.token_contract.functions.allowance(self.address, self.mpe_contract.contract.address).call()
|
the-stack_106_26660 | import base64
import os
import re
import shutil
import subprocess
import tempfile
import urllib
from contextlib import contextmanager
from datetime import timedelta
from typing import (
Any,
Callable,
Collection,
Dict,
Iterable,
Iterator,
List,
Mapping,
Optional,
Sequence,
Set,
Tuple,
Union,
)
from unittest import TestResult, mock
import lxml.html
import orjson
from django.apps import apps
from django.conf import settings
from django.core.mail import EmailMessage
from django.db import connection
from django.db.migrations.executor import MigrationExecutor
from django.db.migrations.state import StateApps
from django.db.utils import IntegrityError
from django.http import HttpRequest, HttpResponse
from django.test import TestCase
from django.test.client import BOUNDARY, MULTIPART_CONTENT, encode_multipart
from django.test.testcases import SerializeMixin
from django.urls import resolve
from django.utils import translation
from django.utils.timezone import now as timezone_now
from fakeldap import MockLDAP
from two_factor.models import PhoneDevice
from corporate.models import Customer, CustomerPlan, LicenseLedger
from zerver.decorator import do_two_factor_login
from zerver.lib.actions import (
bulk_add_subscriptions,
bulk_remove_subscriptions,
check_send_message,
check_send_stream_message,
do_set_realm_property,
gather_subscriptions,
)
from zerver.lib.cache import bounce_key_prefix_for_testing
from zerver.lib.initial_password import initial_password
from zerver.lib.notification_data import UserMessageNotificationsData
from zerver.lib.rate_limiter import bounce_redis_key_prefix_for_testing
from zerver.lib.sessions import get_session_dict_user
from zerver.lib.stream_subscription import get_stream_subscriptions_for_user
from zerver.lib.streams import (
create_stream_if_needed,
get_default_value_for_history_public_to_subscribers,
)
from zerver.lib.test_console_output import (
ExtraConsoleOutputFinder,
ExtraConsoleOutputInTestException,
TeeStderrAndFindExtraConsoleOutput,
TeeStdoutAndFindExtraConsoleOutput,
)
from zerver.lib.test_helpers import find_key_by_email, instrument_url
from zerver.lib.users import get_api_key
from zerver.lib.validator import check_string
from zerver.lib.webhooks.common import get_fixture_http_headers, standardize_headers
from zerver.models import (
Client,
Message,
Realm,
Recipient,
Stream,
Subscription,
UserProfile,
clear_supported_auth_backends_cache,
flush_per_request_caches,
get_client,
get_display_recipient,
get_realm,
get_realm_stream,
get_stream,
get_system_bot,
get_user,
get_user_by_delivery_email,
)
from zerver.openapi.openapi import validate_against_openapi_schema, validate_request
from zerver.tornado import django_api as django_tornado_api
from zerver.tornado.event_queue import clear_client_event_queues_for_testing
if settings.ZILENCER_ENABLED:
from zilencer.models import get_remote_server_by_uuid
class UploadSerializeMixin(SerializeMixin):
"""
We cannot use override_settings to change upload directory because
because settings.LOCAL_UPLOADS_DIR is used in URL pattern and URLs
are compiled only once. Otherwise using a different upload directory
for conflicting test cases would have provided better performance
while providing the required isolation.
"""
lockfile = "var/upload_lock"
@classmethod
def setUpClass(cls: Any, *args: Any, **kwargs: Any) -> None:
if not os.path.exists(cls.lockfile):
with open(cls.lockfile, "w"): # nocoverage - rare locking case
pass
super().setUpClass(*args, **kwargs)
class ZulipTestCase(TestCase):
# Ensure that the test system just shows us diffs
maxDiff: Optional[int] = None
def setUp(self) -> None:
super().setUp()
self.API_KEYS: Dict[str, str] = {}
test_name = self.id()
bounce_key_prefix_for_testing(test_name)
bounce_redis_key_prefix_for_testing(test_name)
def tearDown(self) -> None:
super().tearDown()
# Important: we need to clear event queues to avoid leaking data to future tests.
clear_client_event_queues_for_testing()
clear_supported_auth_backends_cache()
flush_per_request_caches()
translation.activate(settings.LANGUAGE_CODE)
# Clean up after using fakeldap in LDAP tests:
if hasattr(self, "mock_ldap") and hasattr(self, "mock_initialize"):
if self.mock_ldap is not None:
self.mock_ldap.reset()
self.mock_initialize.stop()
def run(self, result: Optional[TestResult] = None) -> Optional[TestResult]: # nocoverage
if not settings.BAN_CONSOLE_OUTPUT:
return super().run(result)
extra_output_finder = ExtraConsoleOutputFinder()
with TeeStderrAndFindExtraConsoleOutput(
extra_output_finder
), TeeStdoutAndFindExtraConsoleOutput(extra_output_finder):
test_result = super().run(result)
if extra_output_finder.full_extra_output:
exception_message = f"""
---- UNEXPECTED CONSOLE OUTPUT DETECTED ----
To ensure that we never miss important error output/warnings,
we require test-backend to have clean console output.
This message usually is triggered by forgotten debugging print()
statements or new logging statements. For the latter, you can
use `with self.assertLogs()` to capture and verify the log output;
use `git grep assertLogs` to see dozens of correct examples.
You should be able to quickly reproduce this failure with:
test-backend --ban-console-output {self.id()}
Output:
{extra_output_finder.full_extra_output}
--------------------------------------------
"""
raise ExtraConsoleOutputInTestException(exception_message)
return test_result
"""
WRAPPER_COMMENT:
We wrap calls to self.client.{patch,put,get,post,delete} for various
reasons. Some of this has to do with fixing encodings before calling
into the Django code. Some of this has to do with providing a future
path for instrumentation. Some of it's just consistency.
The linter will prevent direct calls to self.client.foo, so the wrapper
functions have to fake out the linter by using a local variable called
django_client to fool the regext.
"""
DEFAULT_SUBDOMAIN = "zulip"
TOKENIZED_NOREPLY_REGEX = settings.TOKENIZED_NOREPLY_EMAIL_ADDRESS.format(token="[a-z0-9_]{24}")
def set_http_headers(self, kwargs: Dict[str, Any]) -> None:
if "subdomain" in kwargs:
kwargs["HTTP_HOST"] = Realm.host_for_subdomain(kwargs["subdomain"])
del kwargs["subdomain"]
elif "HTTP_HOST" not in kwargs:
kwargs["HTTP_HOST"] = Realm.host_for_subdomain(self.DEFAULT_SUBDOMAIN)
# set User-Agent
if "HTTP_AUTHORIZATION" in kwargs:
# An API request; use mobile as the default user agent
default_user_agent = "ZulipMobile/26.22.145 (iOS 10.3.1)"
else:
# A web app request; use a browser User-Agent string.
default_user_agent = (
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
+ "AppleWebKit/537.36 (KHTML, like Gecko) "
+ "Chrome/79.0.3945.130 Safari/537.36"
)
if kwargs.get("skip_user_agent"):
# Provide a way to disable setting User-Agent if desired.
assert "HTTP_USER_AGENT" not in kwargs
del kwargs["skip_user_agent"]
elif "HTTP_USER_AGENT" not in kwargs:
kwargs["HTTP_USER_AGENT"] = default_user_agent
def extract_api_suffix_url(self, url: str) -> Tuple[str, Dict[str, Any]]:
"""
Function that extracts the URL after `/api/v1` or `/json` and also
returns the query data in the URL, if there is any.
"""
url_split = url.split("?")
data: Dict[str, Any] = {}
if len(url_split) == 2:
data = urllib.parse.parse_qs(url_split[1])
url = url_split[0]
url = url.replace("/json/", "/").replace("/api/v1/", "/")
return (url, data)
def validate_api_response_openapi(
self,
url: str,
method: str,
result: HttpResponse,
data: Union[str, bytes, Dict[str, Any]],
http_headers: Dict[str, Any],
intentionally_undocumented: bool = False,
) -> None:
"""
Validates all API responses received by this test against Zulip's API documentation,
declared in zerver/openapi/zulip.yaml. This powerful test lets us use Zulip's
extensive test coverage of corner cases in the API to ensure that we've properly
documented those corner cases.
"""
if not (url.startswith("/json") or url.startswith("/api/v1")):
return
try:
content = orjson.loads(result.content)
except orjson.JSONDecodeError:
return
json_url = False
if url.startswith("/json"):
json_url = True
url, query_data = self.extract_api_suffix_url(url)
if len(query_data) != 0:
# In some cases the query parameters are defined in the URL itself. In such cases
# The `data` argument of our function is not used. Hence get `data` argument
# from url.
data = query_data
response_validated = validate_against_openapi_schema(
content, url, method, str(result.status_code)
)
if response_validated:
validate_request(
url,
method,
data,
http_headers,
json_url,
str(result.status_code),
intentionally_undocumented=intentionally_undocumented,
)
@instrument_url
def client_patch(
self,
url: str,
info: Dict[str, Any] = {},
intentionally_undocumented: bool = False,
**kwargs: Any,
) -> HttpResponse:
"""
We need to urlencode, since Django's function won't do it for us.
"""
encoded = urllib.parse.urlencode(info)
django_client = self.client # see WRAPPER_COMMENT
self.set_http_headers(kwargs)
result = django_client.patch(url, encoded, **kwargs)
self.validate_api_response_openapi(
url,
"patch",
result,
info,
kwargs,
intentionally_undocumented=intentionally_undocumented,
)
return result
@instrument_url
def client_patch_multipart(
self, url: str, info: Dict[str, Any] = {}, **kwargs: Any
) -> HttpResponse:
"""
Use this for patch requests that have file uploads or
that need some sort of multi-part content. In the future
Django's test client may become a bit more flexible,
so we can hopefully eliminate this. (When you post
with the Django test client, it deals with MULTIPART_CONTENT
automatically, but not patch.)
"""
encoded = encode_multipart(BOUNDARY, info)
django_client = self.client # see WRAPPER_COMMENT
self.set_http_headers(kwargs)
result = django_client.patch(url, encoded, content_type=MULTIPART_CONTENT, **kwargs)
self.validate_api_response_openapi(url, "patch", result, info, kwargs)
return result
@instrument_url
def client_put(self, url: str, info: Dict[str, Any] = {}, **kwargs: Any) -> HttpResponse:
encoded = urllib.parse.urlencode(info)
django_client = self.client # see WRAPPER_COMMENT
self.set_http_headers(kwargs)
return django_client.put(url, encoded, **kwargs)
@instrument_url
def client_delete(self, url: str, info: Dict[str, Any] = {}, **kwargs: Any) -> HttpResponse:
encoded = urllib.parse.urlencode(info)
django_client = self.client # see WRAPPER_COMMENT
self.set_http_headers(kwargs)
result = django_client.delete(url, encoded, **kwargs)
self.validate_api_response_openapi(url, "delete", result, info, kwargs)
return result
@instrument_url
def client_options(self, url: str, info: Dict[str, Any] = {}, **kwargs: Any) -> HttpResponse:
encoded = urllib.parse.urlencode(info)
django_client = self.client # see WRAPPER_COMMENT
self.set_http_headers(kwargs)
return django_client.options(url, encoded, **kwargs)
@instrument_url
def client_head(self, url: str, info: Dict[str, Any] = {}, **kwargs: Any) -> HttpResponse:
encoded = urllib.parse.urlencode(info)
django_client = self.client # see WRAPPER_COMMENT
self.set_http_headers(kwargs)
return django_client.head(url, encoded, **kwargs)
@instrument_url
def client_post(
self,
url: str,
info: Union[str, bytes, Dict[str, Any]] = {},
**kwargs: Any,
) -> HttpResponse:
intentionally_undocumented: bool = kwargs.pop("intentionally_undocumented", False)
django_client = self.client # see WRAPPER_COMMENT
self.set_http_headers(kwargs)
result = django_client.post(url, info, **kwargs)
self.validate_api_response_openapi(
url, "post", result, info, kwargs, intentionally_undocumented=intentionally_undocumented
)
return result
@instrument_url
def client_post_request(self, url: str, req: Any) -> HttpResponse:
"""
We simulate hitting an endpoint here, although we
actually resolve the URL manually and hit the view
directly. We have this helper method to allow our
instrumentation to work for /notify_tornado and
future similar methods that require doing funny
things to a request object.
"""
match = resolve(url)
return match.func(req)
@instrument_url
def client_get(self, url: str, info: Dict[str, Any] = {}, **kwargs: Any) -> HttpResponse:
intentionally_undocumented: bool = kwargs.pop("intentionally_undocumented", False)
django_client = self.client # see WRAPPER_COMMENT
self.set_http_headers(kwargs)
result = django_client.get(url, info, **kwargs)
self.validate_api_response_openapi(
url, "get", result, info, kwargs, intentionally_undocumented=intentionally_undocumented
)
return result
example_user_map = dict(
hamlet="[email protected]",
cordelia="[email protected]",
iago="[email protected]",
prospero="[email protected]",
othello="[email protected]",
AARON="[email protected]",
aaron="[email protected]",
ZOE="[email protected]",
polonius="[email protected]",
desdemona="[email protected]",
shiva="[email protected]",
webhook_bot="[email protected]",
welcome_bot="[email protected]",
outgoing_webhook_bot="[email protected]",
default_bot="[email protected]",
)
mit_user_map = dict(
sipbtest="[email protected]",
starnine="[email protected]",
espuser="[email protected]",
)
lear_user_map = dict(
cordelia="[email protected]",
king="[email protected]",
)
# Non-registered test users
nonreg_user_map = dict(
test="[email protected]",
test1="[email protected]",
alice="[email protected]",
newuser="[email protected]",
bob="[email protected]",
cordelia="[email protected]",
newguy="[email protected]",
me="[email protected]",
)
example_user_ldap_username_map = dict(
hamlet="hamlet",
cordelia="cordelia",
# aaron's uid in our test directory is "letham".
aaron="letham",
)
def nonreg_user(self, name: str) -> UserProfile:
email = self.nonreg_user_map[name]
return get_user_by_delivery_email(email, get_realm("zulip"))
def example_user(self, name: str) -> UserProfile:
email = self.example_user_map[name]
return get_user_by_delivery_email(email, get_realm("zulip"))
def mit_user(self, name: str) -> UserProfile:
email = self.mit_user_map[name]
return get_user(email, get_realm("zephyr"))
def lear_user(self, name: str) -> UserProfile:
email = self.lear_user_map[name]
return get_user(email, get_realm("lear"))
def nonreg_email(self, name: str) -> str:
return self.nonreg_user_map[name]
def example_email(self, name: str) -> str:
return self.example_user_map[name]
def mit_email(self, name: str) -> str:
return self.mit_user_map[name]
def notification_bot(self) -> UserProfile:
return get_system_bot(settings.NOTIFICATION_BOT)
def create_test_bot(
self, short_name: str, user_profile: UserProfile, full_name: str = "Foo Bot", **extras: Any
) -> UserProfile:
self.login_user(user_profile)
bot_info = {
"short_name": short_name,
"full_name": full_name,
}
bot_info.update(extras)
result = self.client_post("/json/bots", bot_info)
self.assert_json_success(result)
bot_email = f"{short_name}[email protected]"
bot_profile = get_user(bot_email, user_profile.realm)
return bot_profile
def fail_to_create_test_bot(
self,
short_name: str,
user_profile: UserProfile,
full_name: str = "Foo Bot",
*,
assert_json_error_msg: str,
**extras: Any,
) -> None:
self.login_user(user_profile)
bot_info = {
"short_name": short_name,
"full_name": full_name,
}
bot_info.update(extras)
result = self.client_post("/json/bots", bot_info)
self.assert_json_error(result, assert_json_error_msg)
def _get_page_params(self, result: HttpResponse) -> Dict[str, Any]:
"""Helper for parsing page_params after fetching the web app's home view."""
doc = lxml.html.document_fromstring(result.content)
[div] = doc.xpath("//div[@id='page-params']")
page_params_json = div.get("data-params")
page_params = orjson.loads(page_params_json)
return page_params
def check_rendered_logged_in_app(self, result: HttpResponse) -> None:
"""Verifies that a visit of / was a 200 that rendered page_params
and not for a (logged-out) spectator."""
self.assertEqual(result.status_code, 200)
page_params = self._get_page_params(result)
# It is important to check `is_spectator` to verify
# that we treated this request as a normal logged-in session,
# not as a spectator.
self.assertEqual(page_params["is_spectator"], False)
def check_rendered_spectator(self, result: HttpResponse) -> None:
"""Verifies that a visit of / was a 200 that rendered page_params
for a (logged-out) spectator."""
self.assertEqual(result.status_code, 200)
page_params = self._get_page_params(result)
# It is important to check `is_spectator` to verify
# that we treated this request to render for a `spectator`
self.assertEqual(page_params["is_spectator"], True)
def login_with_return(
self, email: str, password: Optional[str] = None, **kwargs: Any
) -> HttpResponse:
if password is None:
password = initial_password(email)
result = self.client_post(
"/accounts/login/", {"username": email, "password": password}, **kwargs
)
self.assertNotEqual(result.status_code, 500)
return result
def login(self, name: str) -> None:
"""
Use this for really simple tests where you just need
to be logged in as some user, but don't need the actual
user object for anything else. Try to use 'hamlet' for
non-admins and 'iago' for admins:
self.login('hamlet')
Try to use 'cordelia' or 'othello' as "other" users.
"""
assert "@" not in name, "use login_by_email for email logins"
user = self.example_user(name)
self.login_user(user)
def login_by_email(self, email: str, password: str) -> None:
realm = get_realm("zulip")
request = HttpRequest()
request.session = self.client.session
self.assertTrue(
self.client.login(
request=request,
username=email,
password=password,
realm=realm,
),
)
def assert_login_failure(self, email: str, password: str) -> None:
realm = get_realm("zulip")
self.assertFalse(
self.client.login(
username=email,
password=password,
realm=realm,
),
)
def login_user(self, user_profile: UserProfile) -> None:
email = user_profile.delivery_email
realm = user_profile.realm
password = initial_password(email)
request = HttpRequest()
request.session = self.client.session
self.assertTrue(
self.client.login(request=request, username=email, password=password, realm=realm)
)
def login_2fa(self, user_profile: UserProfile) -> None:
"""
We need this function to call request.session.save().
do_two_factor_login doesn't save session; in normal request-response
cycle this doesn't matter because middleware will save the session
when it finds it dirty; however,in tests we will have to do that
explicitly.
"""
request = HttpRequest()
request.session = self.client.session
request.user = user_profile
do_two_factor_login(request, user_profile)
request.session.save()
def logout(self) -> None:
self.client.logout()
def register(self, email: str, password: str, **kwargs: Any) -> HttpResponse:
self.client_post("/accounts/home/", {"email": email}, **kwargs)
return self.submit_reg_form_for_user(email, password, **kwargs)
def submit_reg_form_for_user(
self,
email: str,
password: Optional[str],
realm_name: str = "Zulip Test",
realm_subdomain: str = "zuliptest",
from_confirmation: str = "",
full_name: Optional[str] = None,
timezone: str = "",
realm_in_root_domain: Optional[str] = None,
default_stream_groups: Sequence[str] = [],
source_realm_id: str = "",
key: Optional[str] = None,
**kwargs: Any,
) -> HttpResponse:
"""
Stage two of the two-step registration process.
If things are working correctly the account should be fully
registered after this call.
You can pass the HTTP_HOST variable for subdomains via kwargs.
"""
if full_name is None:
full_name = email.replace("@", "_")
payload = {
"full_name": full_name,
"realm_name": realm_name,
"realm_subdomain": realm_subdomain,
"key": key if key is not None else find_key_by_email(email),
"timezone": timezone,
"terms": True,
"from_confirmation": from_confirmation,
"default_stream_group": default_stream_groups,
"source_realm_id": source_realm_id,
}
if password is not None:
payload["password"] = password
if realm_in_root_domain is not None:
payload["realm_in_root_domain"] = realm_in_root_domain
return self.client_post("/accounts/register/", payload, **kwargs)
def get_confirmation_url_from_outbox(
self,
email_address: str,
*,
url_pattern: Optional[str] = None,
email_subject_contains: Optional[str] = None,
email_body_contains: Optional[str] = None,
) -> str:
from django.core.mail import outbox
if url_pattern is None:
# This is a bit of a crude heuristic, but good enough for most tests.
url_pattern = settings.EXTERNAL_HOST + r"(\S+)>"
for message in reversed(outbox):
if any(
addr == email_address or addr.endswith(f" <{email_address}>") for addr in message.to
):
match = re.search(url_pattern, message.body)
assert match is not None
if email_subject_contains:
self.assertIn(email_subject_contains, message.subject)
if email_body_contains:
self.assertIn(email_body_contains, message.body)
[confirmation_url] = match.groups()
return confirmation_url
else:
raise AssertionError("Couldn't find a confirmation email.")
def encode_uuid(self, uuid: str) -> str:
"""
identifier: Can be an email or a remote server uuid.
"""
if uuid in self.API_KEYS:
api_key = self.API_KEYS[uuid]
else:
api_key = get_remote_server_by_uuid(uuid).api_key
self.API_KEYS[uuid] = api_key
return self.encode_credentials(uuid, api_key)
def encode_user(self, user: UserProfile) -> str:
email = user.delivery_email
api_key = user.api_key
return self.encode_credentials(email, api_key)
def encode_email(self, email: str, realm: str = "zulip") -> str:
# TODO: use encode_user where possible
assert "@" in email
user = get_user_by_delivery_email(email, get_realm(realm))
api_key = get_api_key(user)
return self.encode_credentials(email, api_key)
def encode_credentials(self, identifier: str, api_key: str) -> str:
"""
identifier: Can be an email or a remote server uuid.
"""
credentials = f"{identifier}:{api_key}"
return "Basic " + base64.b64encode(credentials.encode("utf-8")).decode("utf-8")
def uuid_get(self, identifier: str, *args: Any, **kwargs: Any) -> HttpResponse:
kwargs["HTTP_AUTHORIZATION"] = self.encode_uuid(identifier)
return self.client_get(*args, **kwargs)
def uuid_post(self, identifier: str, *args: Any, **kwargs: Any) -> HttpResponse:
kwargs["HTTP_AUTHORIZATION"] = self.encode_uuid(identifier)
return self.client_post(*args, **kwargs)
def api_get(self, user: UserProfile, *args: Any, **kwargs: Any) -> HttpResponse:
kwargs["HTTP_AUTHORIZATION"] = self.encode_user(user)
return self.client_get(*args, **kwargs)
def api_post(
self, user: UserProfile, *args: Any, intentionally_undocumented: bool = False, **kwargs: Any
) -> HttpResponse:
kwargs["HTTP_AUTHORIZATION"] = self.encode_user(user)
return self.client_post(
*args, intentionally_undocumented=intentionally_undocumented, **kwargs
)
def api_patch(self, user: UserProfile, *args: Any, **kwargs: Any) -> HttpResponse:
kwargs["HTTP_AUTHORIZATION"] = self.encode_user(user)
return self.client_patch(*args, **kwargs)
def api_delete(self, user: UserProfile, *args: Any, **kwargs: Any) -> HttpResponse:
kwargs["HTTP_AUTHORIZATION"] = self.encode_user(user)
return self.client_delete(*args, **kwargs)
def get_streams(self, user_profile: UserProfile) -> List[str]:
"""
Helper function to get the stream names for a user
"""
subs = get_stream_subscriptions_for_user(user_profile).filter(
active=True,
)
return [check_string("recipient", get_display_recipient(sub.recipient)) for sub in subs]
def send_personal_message(
self,
from_user: UserProfile,
to_user: UserProfile,
content: str = "test content",
sending_client_name: str = "test suite",
) -> int:
recipient_list = [to_user.id]
(sending_client, _) = Client.objects.get_or_create(name=sending_client_name)
return check_send_message(
from_user,
sending_client,
"private",
recipient_list,
None,
content,
)
def send_huddle_message(
self,
from_user: UserProfile,
to_users: List[UserProfile],
content: str = "test content",
sending_client_name: str = "test suite",
) -> int:
to_user_ids = [u.id for u in to_users]
assert len(to_user_ids) >= 2
(sending_client, _) = Client.objects.get_or_create(name=sending_client_name)
return check_send_message(
from_user,
sending_client,
"private",
to_user_ids,
None,
content,
)
def send_stream_message(
self,
sender: UserProfile,
stream_name: str,
content: str = "test content",
topic_name: str = "test",
recipient_realm: Optional[Realm] = None,
sending_client_name: str = "test suite",
) -> int:
(sending_client, _) = Client.objects.get_or_create(name=sending_client_name)
return check_send_stream_message(
sender=sender,
client=sending_client,
stream_name=stream_name,
topic=topic_name,
body=content,
realm=recipient_realm,
)
def get_messages_response(
self,
anchor: Union[int, str] = 1,
num_before: int = 100,
num_after: int = 100,
use_first_unread_anchor: bool = False,
) -> Dict[str, List[Dict[str, Any]]]:
post_params = {
"anchor": anchor,
"num_before": num_before,
"num_after": num_after,
"use_first_unread_anchor": orjson.dumps(use_first_unread_anchor).decode(),
}
result = self.client_get("/json/messages", dict(post_params))
data = result.json()
return data
def get_messages(
self,
anchor: Union[str, int] = 1,
num_before: int = 100,
num_after: int = 100,
use_first_unread_anchor: bool = False,
) -> List[Dict[str, Any]]:
data = self.get_messages_response(anchor, num_before, num_after, use_first_unread_anchor)
return data["messages"]
def users_subscribed_to_stream(self, stream_name: str, realm: Realm) -> List[UserProfile]:
stream = Stream.objects.get(name=stream_name, realm=realm)
recipient = Recipient.objects.get(type_id=stream.id, type=Recipient.STREAM)
subscriptions = Subscription.objects.filter(recipient=recipient, active=True)
return [subscription.user_profile for subscription in subscriptions]
def assert_url_serves_contents_of_file(self, url: str, result: bytes) -> None:
response = self.client_get(url)
data = b"".join(response.streaming_content)
self.assertEqual(result, data)
def assert_json_success(self, result: HttpResponse) -> Dict[str, Any]:
"""
Successful POSTs return a 200 and JSON of the form {"result": "success",
"msg": ""}.
"""
try:
json = orjson.loads(result.content)
except orjson.JSONDecodeError: # nocoverage
json = {"msg": "Error parsing JSON in response!"}
self.assertEqual(result.status_code, 200, json["msg"])
self.assertEqual(json.get("result"), "success")
# We have a msg key for consistency with errors, but it typically has an
# empty value.
self.assertIn("msg", json)
self.assertNotEqual(json["msg"], "Error parsing JSON in response!")
return json
def get_json_error(self, result: HttpResponse, status_code: int = 400) -> str:
try:
json = orjson.loads(result.content)
except orjson.JSONDecodeError: # nocoverage
json = {"msg": "Error parsing JSON in response!"}
self.assertEqual(result.status_code, status_code, msg=json.get("msg"))
self.assertEqual(json.get("result"), "error")
return json["msg"]
def assert_json_error(self, result: HttpResponse, msg: str, status_code: int = 400) -> None:
"""
Invalid POSTs return an error status code and JSON of the form
{"result": "error", "msg": "reason"}.
"""
self.assertEqual(self.get_json_error(result, status_code=status_code), msg)
def assert_length(self, items: Collection[Any], count: int) -> None:
actual_count = len(items)
if actual_count != count: # nocoverage
print("\nITEMS:\n")
for item in items:
print(item)
print(f"\nexpected length: {count}\nactual length: {actual_count}")
raise AssertionError(f"{str(type(items))} is of unexpected size!")
def assert_json_error_contains(
self, result: HttpResponse, msg_substring: str, status_code: int = 400
) -> None:
self.assertIn(msg_substring, self.get_json_error(result, status_code=status_code))
def assert_in_response(self, substring: str, response: HttpResponse) -> None:
self.assertIn(substring, response.content.decode("utf-8"))
def assert_in_success_response(self, substrings: List[str], response: HttpResponse) -> None:
self.assertEqual(response.status_code, 200)
decoded = response.content.decode("utf-8")
for substring in substrings:
self.assertIn(substring, decoded)
def assert_not_in_success_response(self, substrings: List[str], response: HttpResponse) -> None:
self.assertEqual(response.status_code, 200)
decoded = response.content.decode("utf-8")
for substring in substrings:
self.assertNotIn(substring, decoded)
def assert_logged_in_user_id(self, user_id: Optional[int]) -> None:
"""
Verifies the user currently logged in for the test client has the provided user_id.
Pass None to verify no user is logged in.
"""
self.assertEqual(get_session_dict_user(self.client.session), user_id)
def webhook_fixture_data(self, type: str, action: str, file_type: str = "json") -> str:
fn = os.path.join(
os.path.dirname(__file__),
f"../webhooks/{type}/fixtures/{action}.{file_type}",
)
with open(fn) as f:
return f.read()
def fixture_file_name(self, file_name: str, type: str = "") -> str:
return os.path.join(
os.path.dirname(__file__),
f"../tests/fixtures/{type}/{file_name}",
)
def fixture_data(self, file_name: str, type: str = "") -> str:
fn = self.fixture_file_name(file_name, type)
with open(fn) as f:
return f.read()
def make_stream(
self,
stream_name: str,
realm: Optional[Realm] = None,
invite_only: bool = False,
is_web_public: bool = False,
history_public_to_subscribers: Optional[bool] = None,
) -> Stream:
if realm is None:
realm = get_realm("zulip")
history_public_to_subscribers = get_default_value_for_history_public_to_subscribers(
realm, invite_only, history_public_to_subscribers
)
try:
stream = Stream.objects.create(
realm=realm,
name=stream_name,
invite_only=invite_only,
is_web_public=is_web_public,
history_public_to_subscribers=history_public_to_subscribers,
)
except IntegrityError: # nocoverage -- this is for bugs in the tests
raise Exception(
f"""
{stream_name} already exists
Please call make_stream with a stream name
that is not already in use."""
)
recipient = Recipient.objects.create(type_id=stream.id, type=Recipient.STREAM)
stream.recipient = recipient
stream.save(update_fields=["recipient"])
return stream
INVALID_STREAM_ID = 999999
def get_stream_id(self, name: str, realm: Optional[Realm] = None) -> int:
if not realm:
realm = get_realm("zulip")
try:
stream = get_realm_stream(name, realm.id)
except Stream.DoesNotExist:
return self.INVALID_STREAM_ID
return stream.id
# Subscribe to a stream directly
def subscribe(self, user_profile: UserProfile, stream_name: str) -> Stream:
realm = user_profile.realm
try:
stream = get_stream(stream_name, user_profile.realm)
except Stream.DoesNotExist:
stream, from_stream_creation = create_stream_if_needed(realm, stream_name)
bulk_add_subscriptions(realm, [stream], [user_profile], acting_user=None)
return stream
def unsubscribe(self, user_profile: UserProfile, stream_name: str) -> None:
client = get_client("website")
stream = get_stream(stream_name, user_profile.realm)
bulk_remove_subscriptions([user_profile], [stream], client, acting_user=None)
# Subscribe to a stream by making an API request
def common_subscribe_to_streams(
self,
user: UserProfile,
streams: Iterable[str],
extra_post_data: Dict[str, Any] = {},
invite_only: bool = False,
is_web_public: bool = False,
allow_fail: bool = False,
**kwargs: Any,
) -> HttpResponse:
post_data = {
"subscriptions": orjson.dumps([{"name": stream} for stream in streams]).decode(),
"is_web_public": orjson.dumps(is_web_public).decode(),
"invite_only": orjson.dumps(invite_only).decode(),
}
post_data.update(extra_post_data)
result = self.api_post(user, "/api/v1/users/me/subscriptions", post_data, **kwargs)
if not allow_fail:
self.assert_json_success(result)
return result
def check_user_subscribed_only_to_streams(self, user_name: str, streams: List[Stream]) -> None:
streams = sorted(streams, key=lambda x: x.name)
subscribed_streams = gather_subscriptions(self.nonreg_user(user_name))[0]
self.assert_length(subscribed_streams, len(streams))
for x, y in zip(subscribed_streams, streams):
self.assertEqual(x["name"], y.name)
def send_webhook_payload(
self,
user_profile: UserProfile,
url: str,
payload: Union[str, Dict[str, Any]],
**post_params: Any,
) -> Message:
"""
Send a webhook payload to the server, and verify that the
post is successful.
This is a pretty low-level function. For most use cases
see the helpers that call this function, which do additional
checks.
Occasionally tests will call this directly, for unique
situations like having multiple messages go to a stream,
where the other helper functions are a bit too rigid,
and you'll want the test itself do various assertions.
Even in those cases, you're often better to simply
call client_post and assert_json_success.
If the caller expects a message to be sent to a stream,
the caller should make sure the user is subscribed.
"""
prior_msg = self.get_last_message()
result = self.client_post(url, payload, **post_params)
self.assert_json_success(result)
# Check the correct message was sent
msg = self.get_last_message()
if msg.id == prior_msg.id:
raise Exception(
"""
Your test code called an endpoint that did
not write any new messages. It is probably
broken (but still returns 200 due to exception
handling).
One possible gotcha is that you forgot to
subscribe the test user to the stream that
the webhook sends to.
"""
) # nocoverage
self.assertEqual(msg.sender.email, user_profile.email)
return msg
def get_last_message(self) -> Message:
return Message.objects.latest("id")
def get_second_to_last_message(self) -> Message:
return Message.objects.all().order_by("-id")[1]
@contextmanager
def simulated_markdown_failure(self) -> Iterator[None]:
"""
This raises a failure inside of the try/except block of
markdown.__init__.do_convert.
"""
with self.settings(ERROR_BOT=None), mock.patch(
"zerver.lib.markdown.timeout", side_effect=subprocess.CalledProcessError(1, [])
), mock.patch("zerver.lib.markdown.markdown_logger"):
yield
def create_default_device(
self, user_profile: UserProfile, number: str = "+12125550100"
) -> None:
phone_device = PhoneDevice(
user=user_profile,
name="default",
confirmed=True,
number=number,
key="abcd",
method="sms",
)
phone_device.save()
def rm_tree(self, path: str) -> None:
if os.path.exists(path):
shutil.rmtree(path)
def make_import_output_dir(self, exported_from: str) -> str:
output_dir = tempfile.mkdtemp(
dir=settings.TEST_WORKER_DIR, prefix="test-" + exported_from + "-import-"
)
os.makedirs(output_dir, exist_ok=True)
return output_dir
def get_set(self, data: List[Dict[str, Any]], field: str) -> Set[str]:
values = {r[field] for r in data}
return values
def find_by_id(self, data: List[Dict[str, Any]], db_id: int) -> Dict[str, Any]:
return [r for r in data if r["id"] == db_id][0]
def init_default_ldap_database(self) -> None:
"""
Takes care of the mock_ldap setup, loads
a directory from zerver/tests/fixtures/ldap/directory.json with various entries
to be used by tests.
If a test wants to specify its own directory, it can just replace
self.mock_ldap.directory with its own content, but in most cases it should be
enough to use change_user_attr to make simple modifications to the pre-loaded
directory. If new user entries are needed to test for some additional unusual
scenario, it's most likely best to add that to directory.json.
"""
directory = orjson.loads(self.fixture_data("directory.json", type="ldap"))
for dn, attrs in directory.items():
if "uid" in attrs:
# Generate a password for the LDAP account:
attrs["userPassword"] = [self.ldap_password(attrs["uid"][0])]
# Load binary attributes. If in "directory", an attribute as its value
# has a string starting with "file:", the rest of the string is assumed
# to be a path to the file from which binary data should be loaded,
# as the actual value of the attribute in LDAP.
for attr, value in attrs.items():
if isinstance(value, str) and value.startswith("file:"):
with open(value[5:], "rb") as f:
attrs[attr] = [f.read()]
ldap_patcher = mock.patch("django_auth_ldap.config.ldap.initialize")
self.mock_initialize = ldap_patcher.start()
self.mock_ldap = MockLDAP(directory)
self.mock_initialize.return_value = self.mock_ldap
def change_ldap_user_attr(
self, username: str, attr_name: str, attr_value: Union[str, bytes], binary: bool = False
) -> None:
"""
Method for changing the value of an attribute of a user entry in the mock
directory. Use option binary=True if you want binary data to be loaded
into the attribute from a file specified at attr_value. This changes
the attribute only for the specific test function that calls this method,
and is isolated from other tests.
"""
dn = f"uid={username},ou=users,dc=zulip,dc=com"
if binary:
with open(attr_value, "rb") as f:
# attr_value should be a path to the file with the binary data
data: Union[str, bytes] = f.read()
else:
data = attr_value
self.mock_ldap.directory[dn][attr_name] = [data]
def remove_ldap_user_attr(self, username: str, attr_name: str) -> None:
"""
Method for removing the value of an attribute of a user entry in the mock
directory. This changes the attribute only for the specific test function
that calls this method, and is isolated from other tests.
"""
dn = f"uid={username},ou=users,dc=zulip,dc=com"
self.mock_ldap.directory[dn].pop(attr_name, None)
def ldap_username(self, username: str) -> str:
"""
Maps Zulip username to the name of the corresponding LDAP user
in our test directory at zerver/tests/fixtures/ldap/directory.json,
if the LDAP user exists.
"""
return self.example_user_ldap_username_map[username]
def ldap_password(self, uid: str) -> str:
return f"{uid}_ldap_password"
def email_display_from(self, email_message: EmailMessage) -> str:
"""
Returns the email address that will show in email clients as the
"From" field.
"""
# The extra_headers field may contain a "From" which is used
# for display in email clients, and appears in the RFC822
# header as `From`. The `.from_email` accessor is the
# "envelope from" address, used by mail transfer agents if
# the email bounces.
return email_message.extra_headers.get("From", email_message.from_email)
def email_envelope_from(self, email_message: EmailMessage) -> str:
"""
Returns the email address that will be used if the email bounces.
"""
# See email_display_from, above.
return email_message.from_email
def check_has_permission_policies(
self, policy: str, validation_func: Callable[[UserProfile], bool]
) -> None:
realm = get_realm("zulip")
admin_user = self.example_user("iago")
moderator_user = self.example_user("shiva")
member_user = self.example_user("hamlet")
new_member_user = self.example_user("othello")
guest_user = self.example_user("polonius")
do_set_realm_property(realm, "waiting_period_threshold", 1000, acting_user=None)
new_member_user.date_joined = timezone_now() - timedelta(
days=(realm.waiting_period_threshold - 1)
)
new_member_user.save()
member_user.date_joined = timezone_now() - timedelta(
days=(realm.waiting_period_threshold + 1)
)
member_user.save()
do_set_realm_property(realm, policy, Realm.POLICY_ADMINS_ONLY, acting_user=None)
self.assertTrue(validation_func(admin_user))
self.assertFalse(validation_func(moderator_user))
self.assertFalse(validation_func(member_user))
self.assertFalse(validation_func(new_member_user))
self.assertFalse(validation_func(guest_user))
do_set_realm_property(realm, policy, Realm.POLICY_MODERATORS_ONLY, acting_user=None)
self.assertTrue(validation_func(admin_user))
self.assertTrue(validation_func(moderator_user))
self.assertFalse(validation_func(member_user))
self.assertFalse(validation_func(new_member_user))
self.assertFalse(validation_func(guest_user))
do_set_realm_property(realm, policy, Realm.POLICY_FULL_MEMBERS_ONLY, acting_user=None)
self.assertTrue(validation_func(admin_user))
self.assertTrue(validation_func(moderator_user))
self.assertTrue(validation_func(member_user))
self.assertFalse(validation_func(new_member_user))
self.assertFalse(validation_func(guest_user))
do_set_realm_property(realm, policy, Realm.POLICY_MEMBERS_ONLY, acting_user=None)
self.assertTrue(validation_func(admin_user))
self.assertTrue(validation_func(moderator_user))
self.assertTrue(validation_func(member_user))
self.assertTrue(validation_func(new_member_user))
self.assertFalse(validation_func(guest_user))
def subscribe_realm_to_manual_license_management_plan(
self, realm: Realm, licenses: int, licenses_at_next_renewal: int, billing_schedule: int
) -> Tuple[CustomerPlan, LicenseLedger]:
customer, _ = Customer.objects.get_or_create(realm=realm)
plan = CustomerPlan.objects.create(
customer=customer,
automanage_licenses=False,
billing_cycle_anchor=timezone_now(),
billing_schedule=billing_schedule,
tier=CustomerPlan.STANDARD,
)
ledger = LicenseLedger.objects.create(
plan=plan,
is_renewal=True,
event_time=timezone_now(),
licenses=licenses,
licenses_at_next_renewal=licenses_at_next_renewal,
)
realm.plan_type = Realm.STANDARD
realm.save(update_fields=["plan_type"])
return plan, ledger
def subscribe_realm_to_monthly_plan_on_manual_license_management(
self, realm: Realm, licenses: int, licenses_at_next_renewal: int
) -> Tuple[CustomerPlan, LicenseLedger]:
return self.subscribe_realm_to_manual_license_management_plan(
realm, licenses, licenses_at_next_renewal, CustomerPlan.MONTHLY
)
@contextmanager
def tornado_redirected_to_list(
self, lst: List[Mapping[str, Any]], expected_num_events: int
) -> Iterator[None]:
lst.clear()
real_event_queue_process_notification = django_tornado_api.process_notification
# process_notification takes a single parameter called 'notice'.
# lst.append takes a single argument called 'object'.
# Some code might call process_notification using keyword arguments,
# so mypy doesn't allow assigning lst.append to process_notification
# So explicitly change parameter name to 'notice' to work around this problem
django_tornado_api.process_notification = lambda notice: lst.append(notice)
# Some `send_event` calls need to be executed only after the current transaction
# commits (using `on_commit` hooks). Because the transaction in Django tests never
# commits (rather, gets rolled back after the test completes), such events would
# never be sent in tests, and we would be unable to verify them. Hence, we use
# this helper to make sure the `send_event` calls actually run.
with self.captureOnCommitCallbacks(execute=True):
yield
django_tornado_api.process_notification = real_event_queue_process_notification
self.assert_length(lst, expected_num_events)
def create_user_notifications_data_object(
self, *, user_id: int, **kwargs: Any
) -> UserMessageNotificationsData:
return UserMessageNotificationsData(
user_id=user_id,
flags=kwargs.get("flags", []),
mentioned=kwargs.get("mentioned", False),
online_push_enabled=kwargs.get("online_push_enabled", False),
stream_email_notify=kwargs.get("stream_email_notify", False),
stream_push_notify=kwargs.get("stream_push_notify", False),
wildcard_mention_notify=kwargs.get("wildcard_mention_notify", False),
sender_is_muted=kwargs.get("sender_is_muted", False),
)
def get_maybe_enqueue_notifications_parameters(
self, *, message_id: int, user_id: int, acting_user_id: int, **kwargs: Any
) -> Dict[str, Any]:
"""
Returns a dictionary with the passed parameters, after filling up the
missing data with default values, for testing what was passed to the
`maybe_enqueue_notifications` method.
"""
user_notifications_data = self.create_user_notifications_data_object(
user_id=user_id, **kwargs
)
return dict(
user_notifications_data=user_notifications_data,
message_id=message_id,
acting_user_id=acting_user_id,
private_message=kwargs.get("private_message", False),
stream_name=kwargs.get("stream_name", None),
idle=kwargs.get("idle", True),
already_notified=kwargs.get(
"already_notified", {"email_notified": False, "push_notified": False}
),
)
class WebhookTestCase(ZulipTestCase):
"""
Common for all webhooks tests
Override below class attributes and run send_and_test_message
If you create your URL in uncommon way you can override build_webhook_url method
In case that you need modify body or create it without using fixture you can also override get_body method
"""
STREAM_NAME: Optional[str] = None
TEST_USER_EMAIL = "[email protected]"
URL_TEMPLATE: str
WEBHOOK_DIR_NAME: Optional[str] = None
@property
def test_user(self) -> UserProfile:
return get_user(self.TEST_USER_EMAIL, get_realm("zulip"))
def setUp(self) -> None:
super().setUp()
self.url = self.build_webhook_url()
def api_stream_message(self, user: UserProfile, *args: Any, **kwargs: Any) -> HttpResponse:
kwargs["HTTP_AUTHORIZATION"] = self.encode_user(user)
return self.check_webhook(*args, **kwargs)
def check_webhook(
self,
fixture_name: str,
expected_topic: str,
expected_message: str,
content_type: Optional[str] = "application/json",
**kwargs: Any,
) -> None:
"""
check_webhook is the main way to test "normal" webhooks that
work by receiving a payload from a third party and then writing
some message to a Zulip stream.
We use `fixture_name` to find the payload data in of our test
fixtures. Then we verify that a message gets sent to a stream:
self.STREAM_NAME: stream name
expected_topic: topic
expected_message: content
We simulate the delivery of the payload with `content_type`,
and you can pass other headers via `kwargs`.
For the rare cases of webhooks actually sending private messages,
see send_and_test_private_message.
"""
assert self.STREAM_NAME is not None
self.subscribe(self.test_user, self.STREAM_NAME)
payload = self.get_payload(fixture_name)
if content_type is not None:
kwargs["content_type"] = content_type
if self.WEBHOOK_DIR_NAME is not None:
headers = get_fixture_http_headers(self.WEBHOOK_DIR_NAME, fixture_name)
headers = standardize_headers(headers)
kwargs.update(headers)
msg = self.send_webhook_payload(
self.test_user,
self.url,
payload,
**kwargs,
)
self.assert_stream_message(
message=msg,
stream_name=self.STREAM_NAME,
topic_name=expected_topic,
content=expected_message,
)
def assert_stream_message(
self,
message: Message,
stream_name: str,
topic_name: str,
content: str,
) -> None:
self.assertEqual(get_display_recipient(message.recipient), stream_name)
self.assertEqual(message.topic_name(), topic_name)
self.assertEqual(message.content, content)
def send_and_test_private_message(
self,
fixture_name: str,
expected_message: str,
content_type: str = "application/json",
**kwargs: Any,
) -> Message:
"""
For the rare cases that you are testing a webhook that sends
private messages, use this function.
Most webhooks send to streams, and you will want to look at
check_webhook.
"""
payload = self.get_payload(fixture_name)
kwargs["content_type"] = content_type
if self.WEBHOOK_DIR_NAME is not None:
headers = get_fixture_http_headers(self.WEBHOOK_DIR_NAME, fixture_name)
headers = standardize_headers(headers)
kwargs.update(headers)
# The sender profile shouldn't be passed any further in kwargs, so we pop it.
sender = kwargs.pop("sender", self.test_user)
msg = self.send_webhook_payload(
sender,
self.url,
payload,
**kwargs,
)
self.assertEqual(msg.content, expected_message)
return msg
def build_webhook_url(self, *args: Any, **kwargs: Any) -> str:
url = self.URL_TEMPLATE
if url.find("api_key") >= 0:
api_key = get_api_key(self.test_user)
url = self.URL_TEMPLATE.format(api_key=api_key, stream=self.STREAM_NAME)
else:
url = self.URL_TEMPLATE.format(stream=self.STREAM_NAME)
has_arguments = kwargs or args
if has_arguments and url.find("?") == -1:
url = f"{url}?" # nocoverage
else:
url = f"{url}&"
for key, value in kwargs.items():
url = f"{url}{key}={value}&"
for arg in args:
url = f"{url}{arg}&"
return url[:-1] if has_arguments else url
def get_payload(self, fixture_name: str) -> Union[str, Dict[str, str]]:
"""
Generally webhooks that override this should return dicts."""
return self.get_body(fixture_name)
def get_body(self, fixture_name: str) -> str:
assert self.WEBHOOK_DIR_NAME is not None
body = self.webhook_fixture_data(self.WEBHOOK_DIR_NAME, fixture_name)
# fail fast if we don't have valid json
orjson.loads(body)
return body
class MigrationsTestCase(ZulipTestCase): # nocoverage
"""
Test class for database migrations inspired by this blog post:
https://www.caktusgroup.com/blog/2016/02/02/writing-unit-tests-django-migrations/
Documented at https://zulip.readthedocs.io/en/latest/subsystems/schema-migrations.html
"""
@property
def app(self) -> str:
return apps.get_containing_app_config(type(self).__module__).name
migrate_from: Optional[str] = None
migrate_to: Optional[str] = None
def setUp(self) -> None:
assert (
self.migrate_from and self.migrate_to
), f"TestCase '{type(self).__name__}' must define migrate_from and migrate_to properties"
migrate_from: List[Tuple[str, str]] = [(self.app, self.migrate_from)]
migrate_to: List[Tuple[str, str]] = [(self.app, self.migrate_to)]
executor = MigrationExecutor(connection)
old_apps = executor.loader.project_state(migrate_from).apps
# Reverse to the original migration
executor.migrate(migrate_from)
self.setUpBeforeMigration(old_apps)
# Run the migration to test
executor = MigrationExecutor(connection)
executor.loader.build_graph() # reload.
executor.migrate(migrate_to)
self.apps = executor.loader.project_state(migrate_to).apps
def setUpBeforeMigration(self, apps: StateApps) -> None:
pass # nocoverage
|
the-stack_106_26662 | import copy
from typing import Any, Dict, List
from pytest import lazy_fixture # type: ignore
from pytest import fixture, mark, param
from omegaconf import OmegaConf
from omegaconf._utils import ValueKind, _is_missing_literal, get_value_kind
def build_dict(
d: Dict[str, Any], depth: int, width: int, leaf_value: Any = 1
) -> Dict[str, Any]:
if depth == 0:
for i in range(width):
d[f"key_{i}"] = leaf_value
else:
for i in range(width):
c: Dict[str, Any] = {}
d[f"key_{i}"] = c
build_dict(c, depth - 1, width, leaf_value)
return d
def build_list(length: int, val: Any = 1) -> List[int]:
return [val] * length
@fixture(scope="module")
def large_dict() -> Any:
return build_dict({}, 11, 2)
@fixture(scope="module")
def small_dict() -> Any:
return build_dict({}, 5, 2)
@fixture(scope="module")
def dict_with_list_leaf() -> Any:
return build_dict({}, 5, 2, leaf_value=[1, 2])
@fixture(scope="module")
def small_dict_config(small_dict: Any) -> Any:
return OmegaConf.create(small_dict)
@fixture(scope="module")
def dict_config_with_list_leaf(dict_with_list_leaf: Any) -> Any:
return OmegaConf.create(dict_with_list_leaf)
@fixture(scope="module")
def large_dict_config(large_dict: Any) -> Any:
return OmegaConf.create(large_dict)
@fixture(scope="module")
def merge_data(small_dict: Any) -> Any:
return [OmegaConf.create(small_dict) for _ in range(5)]
@fixture(scope="module")
def small_list() -> Any:
return build_list(3, 1)
@fixture(scope="module")
def small_listconfig(small_list: Any) -> Any:
return OmegaConf.create(small_list)
@mark.parametrize(
"data",
[
lazy_fixture("small_dict"),
lazy_fixture("large_dict"),
lazy_fixture("small_dict_config"),
lazy_fixture("large_dict_config"),
lazy_fixture("dict_config_with_list_leaf"),
],
)
def test_omegaconf_create(data: Any, benchmark: Any) -> None:
benchmark(OmegaConf.create, data)
@mark.parametrize(
"merge_function",
[
param(OmegaConf.merge, id="merge"),
param(OmegaConf.unsafe_merge, id="unsafe_merge"),
],
)
def test_omegaconf_merge(merge_function: Any, merge_data: Any, benchmark: Any) -> None:
benchmark(merge_function, merge_data)
@mark.parametrize(
"lst",
[
lazy_fixture("small_list"),
lazy_fixture("small_listconfig"),
],
)
def test_list_in(lst: List[Any], benchmark: Any) -> None:
benchmark(lambda seq, val: val in seq, lst, 10)
@mark.parametrize(
"lst",
[
lazy_fixture("small_list"),
lazy_fixture("small_listconfig"),
],
)
def test_list_iter(lst: List[Any], benchmark: Any) -> None:
def iterate(seq: Any) -> None:
for _ in seq:
pass
benchmark(iterate, lst)
@mark.parametrize(
"strict_interpolation_validation",
[True, False],
)
@mark.parametrize(
("value", "expected"),
[
("simple", ValueKind.VALUE),
("${a}", ValueKind.INTERPOLATION),
("${a:b,c,d}", ValueKind.INTERPOLATION),
("${${b}}", ValueKind.INTERPOLATION),
("${a:${b}}", ValueKind.INTERPOLATION),
("${long_string1xxx}_${long_string2xxx:${key}}", ValueKind.INTERPOLATION),
(
"${a[1].a[1].a[1].a[1].a[1].a[1].a[1].a[1].a[1].a[1].a[1]}",
ValueKind.INTERPOLATION,
),
],
)
def test_get_value_kind(
strict_interpolation_validation: bool, value: Any, expected: Any, benchmark: Any
) -> None:
assert benchmark(get_value_kind, value, strict_interpolation_validation) == expected
def test_is_missing_literal(benchmark: Any) -> None:
assert benchmark(_is_missing_literal, "???")
@mark.parametrize("force_add", [False, True])
@mark.parametrize("key", ["a", "a.a.a.a.a.a.a.a.a.a.a"])
def test_update_force_add(
large_dict_config: Any, key: str, force_add: bool, benchmark: Any
) -> None:
cfg = copy.deepcopy(large_dict_config) # this test modifies the config
if force_add:
OmegaConf.set_struct(cfg, True)
def recursive_is_struct(node: Any) -> None:
if OmegaConf.is_config(node):
OmegaConf.is_struct(node)
for val in node.values():
recursive_is_struct(val)
recursive_is_struct(cfg)
benchmark(OmegaConf.update, cfg, key, 10, force_add=force_add)
|
the-stack_106_26663 | import pytest
import json
import time
import logging
import os
from tests.common.fixtures.ptfhost_utils import copy_ptftests_directory # lgtm[py/unused-import]
from tests.ptf_runner import ptf_runner
from tests.common.devices import AnsibleHostBase
from tests.common.fixtures.conn_graph_facts import conn_graph_facts
from tests.common.utilities import wait_until
from tests.common.helpers.assertions import pytest_assert
from tests.common.helpers.assertions import pytest_require
from tests.common.helpers.dut_ports import decode_dut_port_name
logger = logging.getLogger(__name__)
pytestmark = [
pytest.mark.topology('any')
]
@pytest.fixture(scope="module")
def common_setup_teardown(ptfhost):
logger.info("########### Setup for lag testing ###########")
# Copy PTF test into PTF-docker for test LACP DU
test_files = ['lag_test.py', 'acs_base_test.py', 'router_utils.py']
for test_file in test_files:
src = "../ansible/roles/test/files/acstests/%s" % test_file
dst = "/tmp/%s" % test_file
ptfhost.copy(src=src, dest=dst)
yield ptfhost
class LagTest:
def __init__(self, duthost, tbinfo, ptfhost, nbrhosts, fanouthosts, conn_graph_facts):
self.duthost = duthost
self.tbinfo = tbinfo
self.ptfhost = ptfhost
self.nbrhosts = nbrhosts
self.fanouthosts = fanouthosts
self.mg_facts = duthost.get_extended_minigraph_facts(tbinfo)
self.conn_graph_facts = conn_graph_facts
self.vm_neighbors = self.mg_facts['minigraph_neighbors']
self.fanout_neighbors = self.conn_graph_facts['device_conn'][duthost.hostname] if 'device_conn' in self.conn_graph_facts else {}
def __get_lag_facts(self):
return self.duthost.lag_facts(host = self.duthost.hostname)['ansible_facts']['lag_facts']
def __get_lag_intf_info(self, lag_facts, lag_name):
# Figure out interface informations
po_interfaces = lag_facts['lags'][lag_name]['po_config']['ports']
intf = lag_facts['lags'][lag_name]['po_config']['ports'].keys()[0]
return intf, po_interfaces
def __check_flap(self, lag_facts, lag_name):
po_intf_num = len(lag_facts['lags'][lag_name]['po_config']['ports'])
po_min_links = lag_facts['lags'][lag_name]['po_config']['runner']['min_ports']
return ((po_intf_num - 1) * 100 / po_min_links) < 75
def __check_shell_output(self, host, command):
out = host.shell(command)
return out['stdout'] == 'True'
def __check_intf_state(self, vm_host, intf, expect):
return vm_host.check_intf_link_state(vm_host, intf) == expect
def __verify_lag_lacp_timing(self, lacp_timer, exp_iface):
if exp_iface is None:
return
# Check LACP timing
params = {
'exp_iface': exp_iface,
'timeout': 35,
'packet_timing': lacp_timer,
'ether_type': 0x8809,
'interval_count': 3
}
ptf_runner(self.ptfhost, '/tmp', "lag_test.LacpTimingTest", '/root/ptftests', params=params)
def __verify_lag_minlink(
self,
host,
lag_name,
intf,
neighbor_intf, po_interfaces, po_flap, deselect_time, wait_timeout = 30):
delay = 5
try:
host.shutdown(neighbor_intf)
# Let PortalChannel react to neighbor interface shutdown
time.sleep(deselect_time)
# Verify PortChannel interfaces are up correctly
for po_intf in po_interfaces.keys():
if po_intf != intf:
command = 'bash -c "teamdctl %s state dump" | python -c "import sys, json; print json.load(sys.stdin)[\'ports\'][\'%s\'][\'runner\'][\'selected\']"' % (lag_name, po_intf)
wait_until(wait_timeout, delay, self.__check_shell_output, self.duthost, command)
# Refresh lag facts
lag_facts = self.__get_lag_facts()
# Verify lag member is marked deselected for the shutdown port and all other lag member interfaces are marked selected
for po_intf in po_interfaces.keys():
pytest_assert((po_intf != intf) == (lag_facts['lags'][lag_name]['po_stats']['ports'][po_intf]['runner']['selected']),
"Unexpected port channel {} member {} selected state: {}".format(lag_name, po_intf, (po_intf != intf)))
# Verify PortChannel's interface are marked down/up correctly if it should down/up
exp_state = 'Down' if po_flap else 'Up'
found_state = lag_facts['lags'][lag_name]['po_intf_stat']
pytest_assert(found_state == exp_state, "Expected lag {} state {} found {}.".format(lag_name, exp_state, found_state))
finally:
# Bring back port in case test error and left testbed in unknow stage
# Bring up neighbor interface
host.no_shutdown(neighbor_intf)
# Verify PortChannel interfaces are up correctly
for po_intf in po_interfaces.keys():
if po_intf != intf:
command = 'bash -c "teamdctl %s state dump" | python -c "import sys, json; print json.load(sys.stdin)[\'ports\'][\'%s\'][\'link\'][\'up\']"' % (lag_name, po_intf)
wait_until(wait_timeout, delay, self.__check_shell_output, self.duthost, command)
def run_single_lag_lacp_rate_test(self, lag_name):
logger.info("Start checking single lag lacp rate for: %s" % lag_name)
lag_facts = self.__get_lag_facts()
intf, po_interfaces = self.__get_lag_intf_info(lag_facts, lag_name)
peer_device = self.vm_neighbors[intf]['name']
# Prepare for the remote VM interfaces that using PTF docker to check if the LACP DU packet rate is correct
iface_behind_lag_member = []
for neighbor_intf in self.vm_neighbors.keys():
if peer_device == self.vm_neighbors[neighbor_intf]['name']:
iface_behind_lag_member.append(self.mg_facts['minigraph_ptf_indices'][neighbor_intf])
neighbor_lag_intfs = []
for po_intf in po_interfaces:
neighbor_lag_intfs.append(self.vm_neighbors[po_intf]['port'])
try:
lag_rate_current_setting = None
# Get the vm host(veos) by it host name
vm_host = self.nbrhosts[peer_device]['host']
# Make sure all lag members on VM are set to fast
for neighbor_lag_member in neighbor_lag_intfs:
logger.info("Changing lacp rate to fast for %s in %s" % (neighbor_lag_member, peer_device))
vm_host.set_interface_lacp_rate_mode(neighbor_lag_member, 'fast')
lag_rate_current_setting = 'fast'
time.sleep(5)
for iface_behind_lag in iface_behind_lag_member:
self.__verify_lag_lacp_timing(1, iface_behind_lag)
# Make sure all lag members on VM are set to slow
for neighbor_lag_member in neighbor_lag_intfs:
logger.info("Changing lacp rate to slow for %s in %s" % (neighbor_lag_member, peer_device))
vm_host.set_interface_lacp_rate_mode(neighbor_lag_member, 'normal')
lag_rate_current_setting = 'slow'
time.sleep(5)
for iface_behind_lag in iface_behind_lag_member:
self.__verify_lag_lacp_timing(30, iface_behind_lag)
finally:
# Restore lag rate setting on VM in case of failure
if lag_rate_current_setting == 'fast':
for neighbor_lag_member in neighbor_lag_intfs:
logger.info("Changing lacp rate to slow for %s in %s" % (neighbor_lag_member, peer_device))
vm_host.set_interface_lacp_rate_mode(neighbor_lag_member, 'normal')
def run_single_lag_test(self, lag_name):
logger.info("Start checking single lag for: %s" % lag_name)
lag_facts = self.__get_lag_facts()
intf, po_interfaces = self.__get_lag_intf_info(lag_facts, lag_name)
po_flap = self.__check_flap(lag_facts, lag_name)
# Figure out fanout switches info if exists for the lag member and run minlink test
if intf in self.fanout_neighbors.keys():
peer_device = self.fanout_neighbors[intf]['peerdevice']
neighbor_intf = self.fanout_neighbors[intf]['peerport']
self.__verify_lag_minlink(self.fanouthosts[peer_device], lag_name, intf, neighbor_intf, po_interfaces, po_flap, deselect_time=5)
# Figure out remote VM and interface info for the lag member and run minlink test
peer_device = self.vm_neighbors[intf]['name']
neighbor_intf = self.vm_neighbors[intf]['port']
self.__verify_lag_minlink(self.nbrhosts[peer_device]['host'], lag_name, intf, neighbor_intf, po_interfaces, po_flap, deselect_time=95)
def run_lag_fallback_test(self, lag_name):
logger.info("Start checking lag fall back for: %s" % lag_name)
lag_facts = self.__get_lag_facts()
intf, po_interfaces = self.__get_lag_intf_info(lag_facts, lag_name)
po_fallback = lag_facts['lags'][lag_name]['po_config']['runner']['fallback']
# Figure out remote VM and interface info for the lag member and run lag fallback test
peer_device = self.vm_neighbors[intf]['name']
neighbor_intf = self.vm_neighbors[intf]['port']
vm_host = self.nbrhosts[peer_device]['host']
wait_timeout = 120
delay = 5
try:
# Shut down neighbor interface
vm_host.shutdown(neighbor_intf)
wait_until(wait_timeout, delay, self.__check_intf_state, vm_host, neighbor_intf, False)
# Refresh lag facts
lag_facts = self.__get_lag_facts()
# Get teamshow result
teamshow_result = self.duthost.shell('teamshow')
logger.debug("Teamshow result: %s" % teamshow_result)
# Verify lag members
# 1. All other lag should keep selected state
# 2. Shutdown port should keep selected state if fallback enabled
# 3. Shutdown port should marded as deselected if fallback disabled
# is marked deselected for the shutdown port and all other lag member interfaces are marked selected
for po_intf in po_interfaces.keys():
pytest_assert((po_intf != intf or po_fallback) == (lag_facts['lags'][lag_name]['po_stats']['ports'][po_intf]['runner']['selected']),
"Unexpected port channel {} member {} selected state: {}".format(lag_name, po_intf, (po_intf != intf)))
# The portchannel should marked Up/Down correctly according to po fallback setting
exp_state = 'Up' if po_fallback else 'Down'
found_state = lag_facts['lags'][lag_name]['po_intf_stat']
pytest_assert(found_state == exp_state, "Expected lag {} state {} found {}.".format(lag_name, exp_state, found_state))
finally:
# Bring up neighbor interface
vm_host.no_shutdown(neighbor_intf)
wait_until(wait_timeout, delay, self.__check_intf_state, vm_host, neighbor_intf, True)
@pytest.mark.parametrize("testcase", ["single_lag",
"lacp_rate",
"fallback"])
def test_lag(common_setup_teardown, duthosts, tbinfo, nbrhosts, fanouthosts, conn_graph_facts, enum_dut_portchannel, testcase):
ptfhost = common_setup_teardown
dut_name, dut_lag = decode_dut_port_name(enum_dut_portchannel)
some_test_ran = False
for duthost in duthosts:
if dut_name in [ 'unknown', duthost.hostname ]:
lag_facts = duthost.lag_facts(host = duthost.hostname)['ansible_facts']['lag_facts']
test_instance = LagTest(duthost, tbinfo, ptfhost, nbrhosts, fanouthosts, conn_graph_facts)
# Test for each lag
if dut_lag == "unknown":
test_lags = lag_facts['names']
else:
pytest_require(dut_lag in lag_facts['names'], "No lag {} configuration found in {}".format(dut_lag, duthost.hostname))
test_lags = [ dut_lag ]
for lag_name in test_lags:
if testcase in [ "single_lag", "lacp_rate" ]:
try:
lag_facts['lags'][lag_name]['po_config']['runner']['min_ports']
except KeyError:
msg = "Skip {} for lag {} due to min_ports not exists".format(testcase, lag_name)
pytest_require(lag_name == "unknown", msg)
logger.info(msg)
continue
else:
some_test_ran = True
if testcase == "single_lag":
test_instance.run_single_lag_test(lag_name)
else:
test_instance.run_single_lag_lacp_rate_test(lag_name)
else: # fallback testcase
try:
lag_facts['lags'][lag_name]['po_config']['runner']['fallback']
except KeyError:
msg = "Skip {} for lag {} due to fallback was not set for it".format(testcase, lag_name)
pytest_require(lag_name == "unknown", msg)
continue
else:
some_test_ran = True
test_instance.run_lag_fallback_test(lag_name)
pytest_assert(some_test_ran, "Didn't run any test.")
|
the-stack_106_26664 | # Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from code import Code
from model import PropertyType
import any_helper
import cpp_util
class CppTypeGenerator(object):
"""Manages the types of properties and provides utilities for getting the
C++ type out of a model.Property
"""
def __init__(self, root_namespace, namespace=None, cpp_namespace=None):
"""Creates a cpp_type_generator. The given root_namespace should be of the
format extensions::api::sub. The generator will generate code suitable for
use in the given namespace.
"""
self._type_namespaces = {}
self._root_namespace = root_namespace.split('::')
self._cpp_namespaces = {}
if namespace and cpp_namespace:
self._namespace = namespace
self.AddNamespace(namespace, cpp_namespace)
def AddNamespace(self, namespace, cpp_namespace):
"""Maps a model.Namespace to its C++ namespace name. All mappings are
beneath the root namespace.
"""
for type_ in namespace.types:
qualified_name = self._QualifyName(namespace, type_)
if qualified_name in self._type_namespaces:
raise ValueError('Type %s is declared in both %s and %s' %
(qualified_name, namespace.name,
self._type_namespaces[qualified_name].name))
self._type_namespaces[qualified_name] = namespace
self._cpp_namespaces[namespace] = cpp_namespace
def GetExpandedChoicesInParams(self, params):
"""Returns the given parameters with PropertyType.CHOICES parameters
expanded so that each choice is a separate parameter and sets a unix_name
for each choice.
"""
expanded = []
for param in params:
if param.type_ == PropertyType.CHOICES:
for choice in param.choices.values():
choice.unix_name = (
param.unix_name + '_' + choice.type_.name.lower())
expanded.append(choice)
else:
expanded.append(param)
return expanded
def GetCppNamespaceName(self, namespace):
"""Gets the mapped C++ namespace name for the given namespace relative to
the root namespace.
"""
return self._cpp_namespaces[namespace]
def GetRootNamespaceStart(self):
"""Get opening root namespace declarations.
"""
c = Code()
for namespace in self._root_namespace:
c.Append('namespace %s {' % namespace)
return c
def GetRootNamespaceEnd(self):
"""Get closing root namespace declarations.
"""
c = Code()
for namespace in reversed(self._root_namespace):
c.Append('} // %s' % namespace)
return c
def GetNamespaceStart(self):
"""Get opening self._namespace namespace declaration.
"""
return Code().Append('namespace %s {' %
self.GetCppNamespaceName(self._namespace))
def GetNamespaceEnd(self):
"""Get closing self._namespace namespace declaration.
"""
return Code().Append('} // %s' %
self.GetCppNamespaceName(self._namespace))
def GetEnumNoneValue(self, prop):
"""Gets the enum value in the given model.Property indicating no value has
been set.
"""
return '%s_NONE' % prop.unix_name.upper()
def GetEnumValue(self, prop, enum_value):
"""Gets the enum value of the given model.Property of the given type.
e.g VAR_STRING
"""
return '%s_%s' % (
prop.unix_name.upper(), cpp_util.Classname(enum_value.upper()))
def GetChoicesEnumType(self, prop):
"""Gets the type of the enum for the given model.Property.
e.g VarType
"""
return cpp_util.Classname(prop.name) + 'Type'
def GetType(self, prop, pad_for_generics=False, wrap_optional=False):
"""Translates a model.Property into its C++ type.
If REF types from different namespaces are referenced, will resolve
using self._type_namespaces.
Use pad_for_generics when using as a generic to avoid operator ambiguity.
Use wrap_optional to wrap the type in a scoped_ptr<T> if the Property is
optional.
"""
cpp_type = None
if prop.type_ == PropertyType.REF:
dependency_namespace = self._ResolveTypeNamespace(prop.ref_type)
if not dependency_namespace:
raise KeyError('Cannot find referenced type: %s' % prop.ref_type)
if self._namespace != dependency_namespace:
cpp_type = '%s::%s' % (self._cpp_namespaces[dependency_namespace],
prop.ref_type)
else:
cpp_type = prop.ref_type
elif prop.type_ == PropertyType.BOOLEAN:
cpp_type = 'bool'
elif prop.type_ == PropertyType.INTEGER:
cpp_type = 'int'
elif prop.type_ == PropertyType.DOUBLE:
cpp_type = 'double'
elif prop.type_ == PropertyType.STRING:
cpp_type = 'std::string'
elif prop.type_ == PropertyType.ENUM:
cpp_type = cpp_util.Classname(prop.name)
elif prop.type_ == PropertyType.ADDITIONAL_PROPERTIES:
cpp_type = 'DictionaryValue'
elif prop.type_ == PropertyType.ANY:
cpp_type = any_helper.ANY_CLASS
elif prop.type_ == PropertyType.OBJECT:
cpp_type = cpp_util.Classname(prop.name)
elif prop.type_ == PropertyType.ARRAY:
if prop.item_type.type_ in (
PropertyType.REF, PropertyType.ANY, PropertyType.OBJECT):
cpp_type = 'std::vector<linked_ptr<%s> > '
else:
cpp_type = 'std::vector<%s> '
cpp_type = cpp_type % self.GetType(
prop.item_type, pad_for_generics=True)
else:
raise NotImplementedError(prop.type_)
# Enums aren't wrapped because C++ won't allow it. Optional enums have a
# NONE value generated instead.
if wrap_optional and prop.optional and prop.type_ != PropertyType.ENUM:
cpp_type = 'scoped_ptr<%s> ' % cpp_type
if pad_for_generics:
return cpp_type
return cpp_type.strip()
def GenerateForwardDeclarations(self):
"""Returns the forward declarations for self._namespace.
Use after GetRootNamespaceStart. Assumes all namespaces are relative to
self._root_namespace.
"""
c = Code()
for namespace, types in sorted(self._NamespaceTypeDependencies().items()):
c.Append('namespace %s {' % namespace.name)
for type_ in types:
c.Append('struct %s;' % type_)
c.Append('}')
c.Concat(self.GetNamespaceStart())
for (name, type_) in self._namespace.types.items():
if not type_.functions:
c.Append('struct %s;' % name)
c.Concat(self.GetNamespaceEnd())
return c
def GenerateIncludes(self):
"""Returns the #include lines for self._namespace.
"""
c = Code()
for dependency in sorted(self._NamespaceTypeDependencies().keys()):
c.Append('#include "%s/%s.h"' % (
dependency.source_file_dir,
self._cpp_namespaces[dependency]))
return c
def _QualifyName(self, namespace, name):
return '.'.join([namespace.name, name])
def _ResolveTypeNamespace(self, ref_type):
"""Resolves a type name to its enclosing namespace.
Searches for the ref_type first as an explicitly qualified name, then within
the enclosing namespace, then within other namespaces that the current
namespace depends upon.
"""
if ref_type in self._type_namespaces:
return self._type_namespaces[ref_type]
qualified_name = self._QualifyName(self._namespace, ref_type)
if qualified_name in self._type_namespaces:
return self._type_namespaces[qualified_name]
for (type_name, namespace) in self._type_namespaces.items():
if type_name == self._QualifyName(namespace, ref_type):
return namespace
return None
def _NamespaceTypeDependencies(self):
"""Returns a dict containing a mapping of model.Namespace to the C++ type
of type dependencies for self._namespace.
"""
dependencies = set()
for function in self._namespace.functions.values():
for param in function.params:
dependencies |= self._PropertyTypeDependencies(param)
if function.callback:
for param in function.callback.params:
dependencies |= self._PropertyTypeDependencies(param)
for type_ in self._namespace.types.values():
for prop in type_.properties.values():
dependencies |= self._PropertyTypeDependencies(prop)
dependency_namespaces = dict()
for dependency in dependencies:
namespace = self._ResolveTypeNamespace(dependency)
if namespace != self._namespace:
dependency_namespaces.setdefault(namespace, [])
dependency_namespaces[namespace].append(dependency)
return dependency_namespaces
def _PropertyTypeDependencies(self, prop):
"""Recursively gets all the type dependencies of a property.
"""
deps = set()
if prop:
if prop.type_ == PropertyType.REF:
deps.add(prop.ref_type)
elif prop.type_ == PropertyType.ARRAY:
deps = self._PropertyTypeDependencies(prop.item_type)
elif prop.type_ == PropertyType.OBJECT:
for p in prop.properties.values():
deps |= self._PropertyTypeDependencies(p)
return deps
|
the-stack_106_26665 | import typing as t
from collections import Counter
from weakref import WeakSet
class Metric:
def __init__(
self, name: str,
counter: t.MutableMapping[str, t.Union[float, int]],
default: t.Union[float, int] = 0,
):
self.name: str = name
self.counter = counter
self.counter[name] = default
def __get__(self) -> t.Union[float, int]:
return self.counter[self.name]
def __set__(self, value: t.Union[float, int]) -> None:
self.counter[self.name] = value
def __iadd__(self, value: t.Union[float, int]) -> "Metric":
self.counter[self.name] += value
return self
def __isub__(self, value: t.Union[float, int]) -> "Metric":
self.counter[self.name] -= value
return self
def __eq__(self, other: t.Any) -> bool:
return self.counter[self.name] == other
def __hash__(self) -> int:
return hash(self.counter[self.name])
class AbstractStatistic:
__metrics__: t.FrozenSet[str]
__instances__: t.MutableSet["AbstractStatistic"]
_counter: t.MutableMapping[str, t.Union[float, int]]
name: t.Optional[str]
CLASS_STORE: t.Set[t.Type[AbstractStatistic]] = set()
class MetaStatistic(type):
def __new__(
mcs, name: str,
bases: t.Tuple[type, ...],
dct: t.Dict[str, t.Any],
) -> t.Any:
# noinspection PyTypeChecker
klass: t.Type[AbstractStatistic] = super().__new__(
mcs, name, bases, dct,
) # type: ignore
metrics = set()
for base_class in bases:
if not issubclass(base_class, AbstractStatistic):
continue
if not hasattr(base_class, "__annotations__"):
continue
for prop, kind in base_class.__annotations__.items():
if kind not in (int, float):
continue
if prop.startswith("_"):
continue
metrics.add(prop)
for prop, kind in klass.__annotations__.items():
if kind not in (int, float):
continue
metrics.add(prop)
klass.__metrics__ = frozenset(metrics)
if klass.__metrics__:
klass.__instances__ = WeakSet()
CLASS_STORE.add(klass)
return klass
class Statistic(AbstractStatistic, metaclass=MetaStatistic):
def __init__(self, name: t.Optional[str] = None) -> None:
self._counter = Counter() # type: ignore
self.name = name
for prop in self.__metrics__:
setattr(self, prop, Metric(prop, self._counter))
self.__instances__.add(self)
class StatisticResult(t.NamedTuple):
kind: t.Type[AbstractStatistic]
name: t.Optional[str]
metric: str
value: t.Union[int, float]
# noinspection PyProtectedMember
def get_statistics(
*kind: t.Type[Statistic]
) -> t.Generator[t.Any, t.Tuple[Statistic, str, int], None]:
for klass in CLASS_STORE:
if kind and not issubclass(klass, kind):
continue
for instance in klass.__instances__:
for metric, value in instance._counter.items():
yield StatisticResult(
kind=klass,
name=instance.name,
metric=metric,
value=value,
)
|
the-stack_106_26666 | """Base option parser setup"""
# The following comment should be removed at some point in the future.
# mypy: disallow-untyped-defs=False
from __future__ import absolute_import
import logging
import optparse
import sys
import textwrap
from distutils.util import strtobool
from pip._vendor.six import string_types
from pip._internal.cli.status_codes import UNKNOWN_ERROR
from pip._internal.configuration import Configuration, ConfigurationError
from pip._internal.utils.compat import get_terminal_size
logger = logging.getLogger(__name__)
class PrettyHelpFormatter(optparse.IndentedHelpFormatter):
"""A prettier/less verbose help formatter for optparse."""
def __init__(self, *args, **kwargs):
# help position must be aligned with __init__.parseopts.description
kwargs['max_help_position'] = 30
kwargs['indent_increment'] = 1
kwargs['width'] = get_terminal_size()[0] - 2
optparse.IndentedHelpFormatter.__init__(self, *args, **kwargs)
def format_option_strings(self, option):
return self._format_option_strings(option)
def _format_option_strings(self, option, mvarfmt=' <{}>', optsep=', '):
"""
Return a comma-separated list of option strings and metavars.
:param option: tuple of (short opt, long opt), e.g: ('-f', '--format')
:param mvarfmt: metavar format string
:param optsep: separator
"""
opts = []
if option._short_opts:
opts.append(option._short_opts[0])
if option._long_opts:
opts.append(option._long_opts[0])
if len(opts) > 1:
opts.insert(1, optsep)
if option.takes_value():
metavar = option.metavar or option.dest.lower()
opts.append(mvarfmt.format(metavar.lower()))
return ''.join(opts)
def format_heading(self, heading):
if heading == 'Options':
return ''
return heading + ':\n'
def format_usage(self, usage):
"""
Ensure there is only one newline between usage and the first heading
if there is no description.
"""
msg = '\nUsage: {}\n'.format(
self.indent_lines(textwrap.dedent(usage), " "))
return msg
def format_description(self, description):
# leave full control over description to us
if description:
if hasattr(self.parser, 'main'):
label = 'Commands'
else:
label = 'Description'
# some doc strings have initial newlines, some don't
description = description.lstrip('\n')
# some doc strings have final newlines and spaces, some don't
description = description.rstrip()
# dedent, then reindent
description = self.indent_lines(textwrap.dedent(description), " ")
description = '{}:\n{}\n'.format(label, description)
return description
else:
return ''
def format_epilog(self, epilog):
# leave full control over epilog to us
if epilog:
return epilog
else:
return ''
def indent_lines(self, text, indent):
new_lines = [indent + line for line in text.split('\n')]
return "\n".join(new_lines)
class UpdatingDefaultsHelpFormatter(PrettyHelpFormatter):
"""Custom help formatter for use in ConfigOptionParser.
This is updates the defaults before expanding them, allowing
them to show up correctly in the help listing.
"""
def expand_default(self, option):
if self.parser is not None:
self.parser._update_defaults(self.parser.defaults)
return optparse.IndentedHelpFormatter.expand_default(self, option)
class CustomOptionParser(optparse.OptionParser):
def insert_option_group(self, idx, *args, **kwargs):
"""Insert an OptionGroup at a given position."""
group = self.add_option_group(*args, **kwargs)
self.option_groups.pop()
self.option_groups.insert(idx, group)
return group
@property
def option_list_all(self):
"""Get a list of all options, including those in option groups."""
res = self.option_list[:]
for i in self.option_groups:
res.extend(i.option_list)
return res
class ConfigOptionParser(CustomOptionParser):
"""Custom option parser which updates its defaults by checking the
configuration files and environmental variables"""
def __init__(self, *args, **kwargs):
self.name = kwargs.pop('name')
isolated = kwargs.pop("isolated", False)
self.config = Configuration(isolated)
assert self.name
optparse.OptionParser.__init__(self, *args, **kwargs)
def check_default(self, option, key, val):
try:
return option.check_value(key, val)
except optparse.OptionValueError as exc:
print("An error occurred during configuration: {}".format(exc))
sys.exit(3)
def _get_ordered_configuration_items(self):
# Configuration gives keys in an unordered manner. Order them.
override_order = ["global", self.name, ":env:"]
# Pool the options into different groups
section_items = {name: [] for name in override_order}
for section_key, val in self.config.items():
# ignore empty values
if not val:
logger.debug(
"Ignoring configuration key '%s' as it's value is empty.",
section_key
)
continue
section, key = section_key.split(".", 1)
if section in override_order:
section_items[section].append((key, val))
# Yield each group in their override order
for section in override_order:
for key, val in section_items[section]:
yield key, val
def _update_defaults(self, defaults):
"""Updates the given defaults with values from the config files and
the environ. Does a little special handling for certain types of
options (lists)."""
# Accumulate complex default state.
self.values = optparse.Values(self.defaults)
late_eval = set()
# Then set the options with those values
for key, val in self._get_ordered_configuration_items():
# '--' because configuration supports only long names
option = self.get_option('--' + key)
# Ignore options not present in this parser. E.g. non-globals put
# in [global] by users that want them to apply to all applicable
# commands.
if option is None:
continue
if option.action in ('store_true', 'store_false', 'count'):
try:
val = strtobool(val)
except ValueError:
error_msg = invalid_config_error_message(
option.action, key, val
)
self.error(error_msg)
elif option.action == 'append':
val = val.split()
val = [self.check_default(option, key, v) for v in val]
elif option.action == 'callback':
late_eval.add(option.dest)
opt_str = option.get_opt_string()
val = option.convert_value(opt_str, val)
# From take_action
args = option.callback_args or ()
kwargs = option.callback_kwargs or {}
option.callback(option, opt_str, val, self, *args, **kwargs)
else:
val = self.check_default(option, key, val)
defaults[option.dest] = val
for key in late_eval:
defaults[key] = getattr(self.values, key)
self.values = None
return defaults
def get_default_values(self):
"""Overriding to make updating the defaults after instantiation of
the option parser possible, _update_defaults() does the dirty work."""
if not self.process_default_values:
# Old, pre-Optik 1.5 behaviour.
return optparse.Values(self.defaults)
# Load the configuration, or error out in case of an error
try:
self.config.load()
except ConfigurationError as err:
self.exit(UNKNOWN_ERROR, str(err))
defaults = self._update_defaults(self.defaults.copy()) # ours
for option in self._get_all_options():
default = defaults.get(option.dest)
if isinstance(default, string_types):
opt_str = option.get_opt_string()
defaults[option.dest] = option.check_value(opt_str, default)
return optparse.Values(defaults)
def error(self, msg):
self.print_usage(sys.stderr)
self.exit(UNKNOWN_ERROR, "{}\n".format(msg))
def invalid_config_error_message(action, key, val):
"""Returns a better error message when invalid configuration option
is provided."""
if action in ('store_true', 'store_false'):
return ("{0} is not a valid value for {1} option, "
"please specify a boolean value like yes/no, "
"true/false or 1/0 instead.").format(val, key)
return ("{0} is not a valid value for {1} option, "
"please specify a numerical value like 1/0 "
"instead.").format(val, key)
|
the-stack_106_26670 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import os.path as osp
import numpy as np
# `pip install easydict` if you don't have it
from easydict import EasyDict as edict
__C = edict()
# Consumers can get config by:
# from fast_rcnn_config import cfg
cfg = __C
#
# Training options
#
__C.TRAIN = edict()
# Initial learning rate
__C.TRAIN.LEARNING_RATE = 0.001
# Optimizer Adam, Momentum, RMS
__C.TRAIN.OPTIMIZER = 'Adam'
# Momentum
__C.TRAIN.MOMENTUM = 0.9
# Weight decay, for regularization
__C.TRAIN.WEIGHT_DECAY = 0.0005
# Factor for reducing the learning rate
__C.TRAIN.GAMMA = 0.1
# Step size for reducing the learning rate, currently only support one step
__C.TRAIN.STEPSIZE = [50000]
# Iteration intervals for showing the loss during training, on command line interface
__C.TRAIN.DISPLAY = 10
# Whether to double the learning rate for bias
__C.TRAIN.DOUBLE_BIAS = True
# Whether to initialize the weights with truncated normal distribution
__C.TRAIN.TRUNCATED = False
# Whether to have weight decay on bias as well
__C.TRAIN.BIAS_DECAY = False
# Whether to add ground truth boxes to the pool when sampling regions
__C.TRAIN.USE_GT = False
# Whether to use aspect-ratio grouping of training images, introduced merely for saving
# GPU memory
__C.TRAIN.ASPECT_GROUPING = False
# The number of snapshots kept, older ones are deleted to save space
__C.TRAIN.SNAPSHOT_KEPT = 3
# The time interval for saving tensorflow summaries
__C.TRAIN.SUMMARY_INTERVAL = 30
# Scale to use during training (can list multiple scales)
# The scale is the pixel size of an image's shortest side
__C.TRAIN.SCALES = (600,)
# Max pixel size of the longest side of a scaled input image
__C.TRAIN.MAX_SIZE = 1200
# Images to use per minibatch
__C.TRAIN.IMS_PER_BATCH = 1
# Fraction of minibatch that is labeled foreground (i.e. class > 0)
__C.TRAIN.FG_FRACTION = 0.3
# Overlap threshold for a ROI to be considered foreground (if >= FG_THRESH)
__C.TRAIN.FG_THRESH = 0.5
# Overlap threshold for a ROI to be considered background (class = 0 if
# overlap in [LO, HI))
__C.TRAIN.BG_THRESH_HI = 0.5
__C.TRAIN.BG_THRESH_LO = 0.1
__C.TRAIN.USE_FLIPPED = True
# Train bounding-box regressors
__C.TRAIN.BBOX_REG = True
# Overlap required between a ROI and ground-truth box in order for that ROI to
# be used as a bounding-box regression training example
__C.TRAIN.BBOX_THRESH = 0.5
# Iterations between snapshots
__C.TRAIN.SNAPSHOT_ITERS = 5000
# solver.prototxt specifies the snapshot path prefix, this adds an optional
# infix to yield the path: <prefix>[_<infix>]_iters_XYZ.caffemodel
__C.TRAIN.SNAPSHOT_PREFIX = 'res101_faster_rcnn'
# Normalize the targets (subtract empirical mean, divide by empirical stddev)
__C.TRAIN.BBOX_NORMALIZE_TARGETS = True
# Deprecated (inside weights) useless in CTPN
__C.TRAIN.BBOX_INSIDE_WEIGHTS = (0.0, 1.0, 0.0, 1.0)
# Normalize the targets using "precomputed" (or made up) means and stdevs
# (BBOX_NORMALIZE_TARGETS must also be True)
__C.TRAIN.BBOX_NORMALIZE_TARGETS_PRECOMPUTED = True
__C.TRAIN.BBOX_NORMALIZE_MEANS = (0.0, 0.0, 0.0, 0.0)
__C.TRAIN.BBOX_NORMALIZE_STDS = (0.1, 0.1, 0.2, 0.2)
# Train using these proposals
__C.TRAIN.PROPOSAL_METHOD = 'gt'
# Make minibatches from images that have similar aspect ratios (i.e. both
# tall and thin or both short and wide) in order to avoid wasting computation
# on zero-padding.
# IOU >= thresh: positive example
__C.TRAIN.RPN_POSITIVE_OVERLAP = 0.7
# IOU < thresh: negative example
__C.TRAIN.RPN_NEGATIVE_OVERLAP = 0.5
# If an anchor satisfied by positive and negative conditions set to negative
__C.TRAIN.RPN_CLOBBER_POSITIVES = False
# Max number of foreground examples
__C.TRAIN.RPN_FG_FRACTION = 0.5
# Total number of examples
__C.TRAIN.RPN_BATCHSIZE = 128
# NMS threshold used on RPN proposals
__C.TRAIN.RPN_NMS_THRESH = 0.7
# Number of top scoring boxes to keep before apply NMS to RPN proposals
__C.TRAIN.RPN_PRE_NMS_TOP_N = 12000
# Number of top scoring boxes to keep after applying NMS to RPN proposals
__C.TRAIN.RPN_POST_NMS_TOP_N = 2000
# The order of weights see lib/model/bbox_transform.py bbox_transform()
# Weights for (x, y, w, h), for CTPN it should be (0.,1.,0.,1.)
__C.TRAIN.RPN_BBOX_INSIDE_WEIGHTS = (0.0, 1.0, 0.0, 1.0)
# Give the positive RPN examples weight of p * 1 / {num positives}
# and give negatives a weight of (1 - p)
# Set to -1.0 to use uniform example weighting
__C.TRAIN.RPN_POSITIVE_WEIGHT = -1.0
# Whether to use all ground truth bounding boxes for training,
# For COCO, setting USE_ALL_GT to False will exclude boxes that are flagged as ''iscrowd''
__C.TRAIN.USE_ALL_GT = True
#
# Testing options
#
__C.TEST = edict()
# Scale to use during testing (can NOT list multiple scales)
# The scale is the pixel size of an image's shortest side
__C.TEST.SCALES = (600,)
# Max pixel size of the longest side of a scaled input image
__C.TEST.MAX_SIZE = 1200
# Overlap threshold used for non-maximum suppression (suppress boxes with
# IoU >= this threshold)
__C.TEST.NMS = 0.3
# Test using bounding-box regressors
__C.TEST.BBOX_REG = True
# Test using these proposals
__C.TEST.PROPOSAL_METHOD = 'gt'
## NMS threshold used on RPN proposals
__C.TEST.RPN_NMS_THRESH = 0.7
# Number of top scoring boxes to keep before apply NMS to RPN proposals
__C.TEST.RPN_PRE_NMS_TOP_N = 12000
# Number of top scoring boxes to keep after applying NMS to RPN proposals
__C.TEST.RPN_POST_NMS_TOP_N = 1000
# Proposal height and width both need to be greater than RPN_MIN_SIZE (at orig image scale)
# __C.TEST.RPN_MIN_SIZE = 16
# Testing mode, default to be 'nms', 'top' is slower but better
# See report for details
__C.TEST.MODE = 'nms'
# Only useful when TEST.MODE is 'top', specifies the number of top proposals to select
__C.TEST.RPN_TOP_N = 5000
#
# ResNet options
#
__C.RESNET = edict()
# Number of fixed blocks during training, by default the first of all 4 blocks is fixed
# Range: 0 (none) to 3 (all)
__C.RESNET.FIXED_BLOCKS = 1
#
# MobileNet options
#
__C.MOBILENET = edict()
# Whether to regularize the depth-wise filters during training
__C.MOBILENET.REGU_DEPTH = False
# Number of fixed layers during training, by default the bottom 5 of 14 layers is fixed
# Range: 0 (none) to 12 (all)
__C.MOBILENET.FIXED_LAYERS = 5
# Weight decay for the mobilenet weights
__C.MOBILENET.WEIGHT_DECAY = 0.00004
# Depth multiplier
__C.MOBILENET.DEPTH_MULTIPLIER = 1.
#
# MISC
#
# Pixel mean values (BGR order) as a (1, 1, 3) array
# Means for VGG, from https://github.com/tensorflow/models/blob/master/research/slim/preprocessing/vgg_preprocessing.py
__C.PIXEL_MEANS = np.array([[[102.9801, 115.9465, 122.7717]]])
# __C.PIXEL_MEANS = np.array([[[103.94, 116.78, 123.68]]])
# For reproducibility
__C.RNG_SEED = 3
# Root directory of project
__C.ROOT_DIR = osp.abspath(osp.join(osp.dirname(__file__), '..', '..'))
# Data directory
__C.DATA_DIR = osp.abspath(osp.join(__C.ROOT_DIR, 'data'))
# Name (or path to) the matlab executable
__C.MATLAB = 'matlab'
# Place outputs under an experiments directory
__C.EXP_DIR = 'default'
# Use GPU implementation of non-maximum suppression
__C.USE_GPU_NMS = True
# Anchor scales for RPN
__C.ANCHOR_SCALES = [8, 16, 32]
# Anchor ratios for RPN
__C.ANCHOR_RATIOS = [0.5, 1, 2]
# Number of filters for the RPN layer
__C.RPN_CHANNELS = 512
#
# CTPN options
#
__C.CTPN = edict()
__C.CTPN.NUM_ANCHORS = 10
__C.CTPN.ANCHOR_WIDTH = 16
__C.CTPN.H_RADIO_STEP = 0.7
def get_output_dir(imdb, weights_filename):
"""Return the directory where experimental artifacts are placed.
If the directory does not exist, it is created.
A canonical path is built using the name from an imdb and a network
(if not None).
"""
outdir = osp.abspath(osp.join(__C.ROOT_DIR, 'output', __C.EXP_DIR, imdb.name))
if weights_filename is None:
weights_filename = 'default'
outdir = osp.join(outdir, weights_filename)
if not os.path.exists(outdir):
os.makedirs(outdir)
return outdir
def get_output_tb_dir(imdb, weights_filename):
"""Return the directory where tensorflow summaries are placed.
If the directory does not exist, it is created.
A canonical path is built using the name from an imdb and a network
(if not None).
"""
outdir = osp.abspath(osp.join(__C.ROOT_DIR, 'tensorboard', __C.EXP_DIR, imdb.name))
if weights_filename is None:
weights_filename = 'default'
outdir = osp.join(outdir, weights_filename)
if not os.path.exists(outdir):
os.makedirs(outdir)
return outdir
def _merge_a_into_b(a, b):
"""Merge config dictionary a into config dictionary b, clobbering the
options in b whenever they are also specified in a.
"""
if type(a) is not edict:
return
for k, v in a.items():
# a must specify keys that are in b
if k not in b:
raise KeyError('{} is not a valid config key'.format(k))
# the types must match, too
old_type = type(b[k])
if old_type is not type(v):
if isinstance(b[k], np.ndarray):
v = np.array(v, dtype=b[k].dtype)
else:
raise ValueError(('Type mismatch ({} vs. {}) '
'for config key: {}').format(type(b[k]),
type(v), k))
# recursively merge dicts
if type(v) is edict:
try:
_merge_a_into_b(a[k], b[k])
except:
print(('Error under config key: {}'.format(k)))
raise
else:
b[k] = v
def cfg_from_file(filename):
"""Load a config file and merge it into the default options."""
import yaml
with open(filename, 'r') as f:
yaml_cfg = edict(yaml.load(f))
_merge_a_into_b(yaml_cfg, __C)
def cfg_from_list(cfg_list):
"""Set config keys via list (e.g., from command line)."""
from ast import literal_eval
assert len(cfg_list) % 2 == 0
for k, v in zip(cfg_list[0::2], cfg_list[1::2]):
key_list = k.split('.')
d = __C
for subkey in key_list[:-1]:
assert subkey in d
d = d[subkey]
subkey = key_list[-1]
assert subkey in d
try:
value = literal_eval(v)
except:
# handle the case when v is a string literal
value = v
assert type(value) == type(d[subkey]), \
'type {} does not match original type {}'.format(
type(value), type(d[subkey]))
d[subkey] = value
|
the-stack_106_26671 | # -*- coding: utf-8 -*-
"""
Created on Wed Feb 3 14:33:25 2016
@author: hjalmar
"""
from ht_helper import get_input, FrameStepper, CountdownPrinter
import matplotlib.pyplot as plt
from datetime import datetime
from scipy.misc import imresize
from time import sleep
from glob import glob
import numpy as np
import warnings
import tensorflow as tf
warnings.simplefilter("ignore")
class LabelFrames:
"""
"""
def __init__(self, video_fname, log_fname=None):
"""
"""
# Supress the plt.ginput warning.
warnings.warn("deprecated", DeprecationWarning)
plt.ion()
self.start_t = datetime.now()
self.video_fname = video_fname
if log_fname is None:
self.log_fname = ('%s.txt' %
video_fname.split('/')[-1].split('.')[-2])
else:
self.log_fname = log_fname
# Open output log file.
self.f = open(self.log_fname, 'w')
self.figsize = [8.125, 6.125]
self.fst = FrameStepper(self.video_fname)
self.available_nf = self.fst.tot_n
self.frame = self.fst.frame
self.frame_num = self.fst.n
self.frame_time = self.fst.t
self.fig = plt.figure(figsize=self.figsize)
self.ax = self.fig.add_axes([0.01, 0.01, 0.97, 0.97])
self.num_labelled = 0
self.imwdt = self.frame.shape[1]
self.imhgt = self.frame.shape[0]
self.head_data = {'center_x': 0.0,
'center_y': 0.0,
'angle': 0.0,
'angle_visible': 0,
'box_width': 0.0,
'box_height': 0.0,
'forehead_pos_x': 0.0,
'forehead_pos_y': 0.0,
'tuft_pos_left_x': 0.0,
'tuft_pos_left_y': 0.0,
'tuft_pos_right_x': 0.0,
'tuft_pos_right_y': 0.0}
self._head_len_wdt_ratio = 1.0 # head a bit wider than long
self._head_backwrd_shift = 0.6
self._head_scaling = 3 # multiplied with inter_tuft_distance to get
# width of head including tufts
# Write the header to the log file.
self._write_log(write_header=True)
def run_spacedbatch(self, t0=0.2, batch_size=1000):
"""
"""
self.batch_size = batch_size
n_skip = self.fst.tot_n // batch_size
frame_num = int(t0 / self.fst.dt)
while frame_num <= self.fst.tot_n:
self.fst.read_frame(frame_num)
self.frame = self.fst.frame
self.frame_num = self.fst.n
self.frame_time = self.fst.t
self._annote(1, batch_type='spaced')
if self.head_position_ok:
self._write_log(write_header=False)
self.num_labelled += 1
frame_num = np.random.randint(3, 2*n_skip-1) + self.frame_num
print('Batch complete.\n%d frames labelled.' % self.num_labelled)
self.close()
def run_sequentialbatch(self, t0, seq_len=200, n_seqs=10):
"""
"""
self.max_skip = self.fst.duration - seq_len * (n_seqs - 1) * self.fst.dt - t0
self.max_skip /= (n_seqs - 1)
self.available_nf - seq_len * n_seqs
for i in range(n_seqs):
print('Starting sequence %d of %d at time %1.2fs.' %
(i+1, n_seqs, t0))
self.run_sequence(t0, seq_len=seq_len)
if i < n_seqs - 1:
if not get_input('Continue', bool, default=True):
print('Quitting without having finished the batch.')
break
# Start time for next sequence.
# Random drawn from the interval [1/fps, max_skip+1/fps) s.
t0 = self.frame_time + np.random.random() * self.max_skip + self.fst.dt
else:
print('Batch complete.\n%d frames labelled.' %
self.num_labelled)
self.close()
def run_sequence(self, t0, seq_len=200):
"""
"""
self._seq_len = seq_len
self.fst.read_t(t0)
self.frame = self.fst.frame
self.frame_num = self.fst.n
self.frame_num_start = self.fst.n
self.frame_num_end = self.fst.n + seq_len
self.frame_time = self.fst.t
self._annote(self.frame_num-self.frame_num_start+1)
self._write_log(write_header=False)
for i in range(1, seq_len + 1):
self.fst.next()
self.frame = self.fst.frame
self.frame_num = self.fst.n
self.frame_time = self.fst.t
self._annote(self.frame_num-self.frame_num_start + 1, batch_type='sequential')
if self.head_position_ok:
self._write_log(write_header=False)
self.num_labelled += 1
def _write_log(self, write_header=False):
"""
Writes a header or head data.
"""
if write_header:
s = ('date_time, video_fname, head_backwrd_shift, '
'head_len_wdt_ratio, head_scaling\n'
'%s, %s, %1.2f, %1.2f, %1.2f\n'
'frame_number, frame_time(s), center_x(px), center_y(px), '
'gaze_angle(rad), gaze_angle_visible(bool), box_width(px), box_height(px), '
'forehead_pos_x(px), forehead_pos_y(px), '
'tuft_pos_left_x(px), tuft_pos_left_y(px), '
'tuft_pos_right_x(px), tuft_pos_right_y(px)\n' %
(self.start_t.strftime("%Y-%m-%d %H:%M:%S"),
self.video_fname.split('/')[-1],
self._head_backwrd_shift,
self._head_len_wdt_ratio,
self._head_scaling))
else:
s = ('%d, %1.9f, %1.2f, %1.2f, %1.9f, %d, %1.2f, %1.2f, '
'%1.2f, %1.2f, %1.2f, %1.2f, %1.2f, %1.2f\n' %
(self.frame_num,
self.frame_time,
self.head_data['center_x'],
self.head_data['center_y'],
self.head_data['angle'],
self.head_data['angle_visible'],
self.head_data['box_width'],
self.head_data['box_height'],
self.head_data['forehead_pos_x'],
self.head_data['forehead_pos_y'],
self.head_data['tuft_pos_left_x'],
self.head_data['tuft_pos_left_y'],
self.head_data['tuft_pos_right_x'],
self.head_data['tuft_pos_right_y']))
self.f.write(s)
def _annote(self, frame_num_in_seq, batch_type='sequential'):
"""
"""
redo = True
while redo:
# plot
# Set image to be oriented with 0,0 in lower left corner
# and x_max, y_max in upper right corner
self.ax.cla()
self.ax.imshow(self.frame, origin='lower')
self.ax.set_xticks([])
self.ax.set_yticks([])
if batch_type == 'sequential':
s = ('start: %d, end: %d, current: %d, remaining: %d' %
(self.frame_num_start, self.frame_num_end,
self.frame_num_start + frame_num_in_seq,
self._seq_len - frame_num_in_seq))
elif batch_type == 'spaced':
s = ('time: %1.2fs, current: %d, remaining: ≈ %d' %
(self.frame_time, self.num_labelled,
self.batch_size - self.num_labelled))
else:
raise ValueError('Unknown batch_type specified: %s' % batch_type)
txt0 = self.ax.text(self.imwdt-5, 5, s, va='bottom',
ha='right', fontsize=12, color=[0.4, 0.8, 0.2])
s = 'LEFT to SELECT 1) forehead, 2) one tuft, 3) other tuft\n'
s += 'MIDDLE to SKIP'
txt1 = self.ax.text(self.imwdt//2, self.imhgt-10, s, va='top',
color='w', fontsize=14, ha='center')
plt.draw()
self._get_head_pos_and_rotation()
if self.head_position_ok:
draw_head_position_and_angle(self.ax,
self.imwdt,
self.imhgt,
self._head_backwrd_shift,
self.head_data)
txt1.set_visible(False)
s = 'Gaze direction visible?\nLEFT for Yes | MIDDLE for No'
txt2 = self.ax.text(self.imwdt//2, self.imhgt-10, s, va='top',
color='w', fontsize=14, ha='center')
plt.draw()
r = plt.ginput(n=1, mouse_add=1, mouse_stop=2,
mouse_pop=3, timeout=0)
if len(r) > 0:
self.head_data['angle_visible'] = 1
else:
self.head_data['angle_visible'] = 0
txt2.set_visible(False)
s = 'MIDDLE to REDO | LEFT to NEXT'
self.ax.text(self.imwdt//2, self.imhgt-10, s, va='top',
color='w', fontsize=14, ha='center')
plt.draw()
r = plt.ginput(n=1, mouse_add=1, mouse_stop=2,
mouse_pop=3, timeout=0)
if len(r) == 0:
redo = True
self.ax.cla()
else:
redo = False
txt0.set_visible(False)
def _get_head_pos_and_rotation(self):
"""
"""
# Get tuft and forehead positions from image.
pos = plt.ginput(3, timeout=0)
if len(pos) == 3:
self.head_position_ok = True
# Get the head rotation angle.
head_pos_x = pos[1][0] + (pos[2][0] - pos[1][0])/2
head_pos_y = pos[1][1] + (pos[2][1] - pos[1][1])/2
xdist = pos[0][0] - head_pos_x
ydist = pos[0][1] - head_pos_y # y-dim 0 is at top of image
# Angle from horizontal
#angle = np.angle(xdist+ydist*1j)
angle = np.arctan2(ydist, xdist)
# Positions of tufts relative to gaze/nose.
tuft_pos_left_x, tuft_pos_left_y = pos[1][0], pos[1][1]
tuft_pos_right_x, tuft_pos_right_y = pos[2][0], pos[2][1]
# Make sure that left tuft is left relative to gaze.
flip = False
if (angle == 0 or angle == 2*np.pi):
if tuft_pos_left_y < tuft_pos_right_y:
flip = True
elif angle < np.pi:
if tuft_pos_left_x > tuft_pos_right_x:
flip = True
elif angle == np.pi:
if tuft_pos_left_y > tuft_pos_right_y:
flip = True
else: # angle > pi
if tuft_pos_left_x < tuft_pos_right_x:
flip = True
if flip:
tmp_x, tmp_y = tuft_pos_right_x, tuft_pos_right_y
tuft_pos_right_x = tuft_pos_left_x
tuft_pos_right_y = tuft_pos_left_y
tuft_pos_left_x, tuft_pos_left_y = tmp_x, tmp_y
# Store head position and angle data in head_data.
# To be saved in the log file later.
self.head_data['center_x'] = head_pos_x
self.head_data['center_y'] = head_pos_y
self.head_data['angle'] = angle
inter_tuft_dist = np.sqrt((pos[1][0] - pos[2][0])**2 +
(pos[1][1] - pos[2][1])**2)
self.head_data['box_width'] = self._head_scaling * inter_tuft_dist
self.head_data['box_height'] = self.head_data['box_width'] * \
self._head_len_wdt_ratio
self.head_data['forehead_pos_x'] = pos[0][0]
self.head_data['forehead_pos_y'] = pos[0][1]
self.head_data['tuft_pos_left_x'] = tuft_pos_left_x
self.head_data['tuft_pos_left_y'] = tuft_pos_left_y
self.head_data['tuft_pos_right_x'] = tuft_pos_right_x
self.head_data['tuft_pos_right_y'] = tuft_pos_right_y
else:
self.head_position_ok = False
def close(self):
"""
"""
self.fst.vr.close()
self.f.close()
def draw_head_position_and_angle(ax, imwdt, imhgt, head_backwrd_shift, data):
"""
"""
# Forehead
x, y = data['forehead_pos_x'], data['forehead_pos_y']
ax.plot(x, y, 'o', ms=5, mec=[1, 0.6, 0.3], mfc='none', mew=1)
ax.plot(x, y, 'o', ms=20, mec=[1, 0.9, 0.5], mfc='none', mew=1)
# Left tuft
x, y = data['tuft_pos_left_x'], data['tuft_pos_left_y']
ax.plot(x, y, 'o', ms=20, mec=[1, 0.3, 0.1], mfc='none', mew=1)
ax.plot(x, y, '.r')
# Right tuft
x, y = data['tuft_pos_right_x'], data['tuft_pos_right_y']
ax.plot(x, y, 'o', ms=20, mec=[1, 0.3, 0.1], mfc='none', mew=1)
ax.plot(x, y, '.r')
# Head postion, center between the tufts.
hp_x, hp_y = data['center_x'], data['center_y']
ax.plot(hp_x, hp_y, 'o', ms=5, mec=[1, 0, 0], mfc='none', mew=1)
ax.plot(hp_x, hp_y, 'o', ms=20, mec=[1, 0.3, 0.1], mfc='none', mew=1)
# For plotting line of gaze.
angle = data['angle']
if angle < 0: # 3rd or 4th quadrant
ydist_lim = - hp_y + 10
else: # 1st or 2nd quadrant
ydist_lim = imhgt - hp_y - 10
if abs(angle) < np.pi/2: # 1st or 4th quadrant
xdist_lim = imwdt - hp_x - 10
else: # 2nd or 3rd quadrant
xdist_lim = - hp_x + 10
# y-dim 0 is at top of image
xdist, ydist = data['forehead_pos_x'] - hp_x, data['forehead_pos_y'] - hp_y
# TODO: try to replace with get_gaze_line
# or at least check that (ydist_lim / ydist) * ydist really is neccessary
gaze_pos_x = hp_x + (ydist_lim / ydist) * ydist / np.tan(angle)
gaze_pos_y = hp_y + (xdist_lim / xdist) * xdist * np.tan(angle)
# Fixing gaze line so that it doesn't end outside of image.
if gaze_pos_y > imhgt:
gaze_pos_y = hp_y + ydist_lim
gaze_pos_x = hp_x + ydist_lim / np.tan(angle)
elif gaze_pos_x > imwdt:
gaze_pos_x = hp_x + xdist_lim
gaze_pos_y = hp_y + xdist_lim * np.tan(angle)
elif gaze_pos_y < 0:
gaze_pos_y = hp_y + ydist_lim
gaze_pos_x = hp_x + ydist_lim / np.tan(angle)
elif gaze_pos_x < 0:
gaze_pos_x = hp_x + xdist_lim
gaze_pos_y = hp_y + xdist_lim * np.tan(angle)
# Plot gaze line
ax.plot([hp_x, gaze_pos_x], [hp_y, gaze_pos_y],
'-', color=[1, 0.6, 0.2], lw=3, alpha=0.5)
ax.set_xlim([0, imwdt])
ax.set_ylim([0, imhgt])
def read_log_data(log_fname):
"""
"""
dtype = [('frame_num', int),
('frame_time', np.float64),
('center_x', np.float64),
('center_y', np.float64),
('angle', np.float64),
('angle_ok', int),
('box_width', np.float64),
('box_height', np.float64),
('forehead_pos_x', np.float64),
('forehead_pos_y', np.float64),
('tuft_pos_left_x', np.float64),
('tuft_pos_left_y', np.float64),
('tuft_pos_right_x', np.float64),
('tuft_pos_right_y', np.float64)]
data = np.genfromtxt(log_fname, dtype=dtype, delimiter=',', skip_header=3)
f = open(log_fname, 'r')
H0 = f.readline().split(',')
H1 = f.readline().split(',')
header = {}
for h0, h1 in zip(H0, H1):
header[h0.strip().rstrip('\n')] = h1.strip().rstrip('\n')
f.close()
return data, header
def plot_head_data(log_fname, video_fname):
"""
Mainly for checking the manual annotation.
"""
head_backwrd_shift = 0.6
figsize = [8.125, 6.125]
fst = FrameStepper(video_fname)
frame = fst.frame
fig = plt.figure(figsize=figsize)
ax = fig.add_axes([0.01, 0.01, 0.97, 0.97])
imwdt = frame.shape[1]
imhgt = frame.shape[0]
log_data, log_header = read_log_data(log_fname)
for i, dat in enumerate(log_data):
fst.read_t(dat['frame_time'])
ax.cla()
ax.imshow(fst.frame, origin='lower')
ax.set_xticks([])
ax.set_yticks([])
draw_head_position_and_angle(ax, imwdt, imhgt, head_backwrd_shift, dat)
plt.draw()
fig.savefig('test_%d.png' % i)
sleep(5)
fst.close()
def convert_to_tfrecords(images, angles, angles_ok, positions, fname):
"""
"""
def _int64_feature(value):
return tf.train.Feature(int64_list=tf.train.Int64List(value=[value]))
def _bytes_feature(value):
return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))
if images.shape[0] != angles.shape[0]:
raise ValueError("Images size %d does not match label size %d." %
(images.shape[0], angles.shape[0]))
writer = tf.python_io.TFRecordWriter(fname)
for i in range(images.shape[0]):
image_raw = images[i].tostring()
example = tf.train.Example(features=tf.train.Features(feature={
'height': _int64_feature(images.shape[1]),
'width': _int64_feature(images.shape[2]),
'depth': _int64_feature(images.shape[3]),
'angle': _int64_feature(int(angles[i])),
'angle_ok': _int64_feature(int(angles_ok[i])),
'position_x': _int64_feature(int(positions[i]['x'])),
'position_y': _int64_feature(int(positions[i]['y'])),
'image_raw': _bytes_feature(image_raw)}))
writer.write(example.SerializeToString())
writer.close()
def labeledDataToStorage(log_dir, video_dir, data_dir, Ntrain=None, Ndev=3000):
"""
Trying to maximize resolution while minimizing the number of windows/patches
to classify per video fram using a Multi Resolution Pyramid.
Parameters
----------
log_dir
video_dir
data_dir
Ntrain
Ndev -- 3 000 should be fine for 1% acc differences.
"""
#head_size = 200 # pixels in 480 x 640 frame
#scale_factor = 32 / head_size # TODO improve this
scale_factor = 160/640.
log_fnames = glob(log_dir.rstrip('/') + '/HeadData*.txt')
Nlogs = len(log_fnames)
frames = []
angles_ok = []
angles = []
positions_x = []
positions_y = []
for i, log_fname in enumerate(log_fnames):
print('Processing file (%d of %d): %s' % (i+1, Nlogs, log_fname.split('/')[-1]))
log_data, log_header = read_log_data(log_fname)
video_fname = '%s/%s' % (video_dir.rstrip('/'), log_header['video_fname'])
video_fname = glob(video_fname)
if len(video_fname) != 1:
print('The video file matching to the log cannot be found in %s'
% video_dir)
print('Log file:', log_fname)
print('Found video files:', video_fname)
return 0
# To read the frames
fst = FrameStepper(video_fname[0])
# Scale head positions to fit rescaled frames.
log_data['center_x'] = log_data['center_x'] * scale_factor
log_data['center_y'] = log_data['center_y'] * scale_factor
# Head angles to degrees (-180 to 180)
log_data['angle'] = (180 * (log_data['angle'] / np.pi)).round()
# Counter printed on command line
cdp = CountdownPrinter(log_data.shape[0])
for j, dat in enumerate(log_data):
# Counter printed on the command line
cdp.print(j)
# Read the frame
fst.read_t(dat['frame_time'])
frame = imresize(fst.frame.mean(axis=2), scale_factor)
frames.append(frame.reshape(frame.shape[0], frame.shape[1], 1))
angles_ok.append(dat['angle_ok'])
angles.append(dat['angle'])
positions_x.append(dat['center_x'])
positions_y.append(dat['center_y'])
fst.close()
# assign to dev and train set, and write
print('\nSaving labeled data to tfrecords...')
Ntot = len(frames)
#im_h, im_w = frames[0].shape
if Ndev is None and Ntrain is None:
Ndev = 3000
Ntrain = Ntot - Ndev
elif Ndev is None and np.isscalar(Ntrain):
Ndev = Ntot - Ntrain
elif Ntrain is None and np.isscalar(Ndev):
Ntrain = Ntot - Ndev
elif np.isscalar(Ndev) and np.isscalar(Ntrain):
Ndev = Ntot - Ntrain
print('Ndev set to :', Ndev)
else:
import pdb
pdb.set_trace()
raise ValueError('What do you want?')
rnd_idx = np.random.permutation(Ntot)
dev_idx = rnd_idx[:Ndev]
train_idx = rnd_idx[Ndev:]
train_idx = train_idx[:Ntrain]
images = np.array(frames, dtype=np.uint8)
angles = np.array(angles, dtype=np.int64)
angles_ok = np.array(angles_ok, dtype=np.int64)
positions = np.recarray(Ntot, dtype=[('x', np.int64),('y', np.int64)])
positions.x = positions_x
positions.y = positions_y
dev_fname = '%s/dev_CAM_N%0000d.tfrecords' % (data_dir.rstrip('/'), Ndev)
convert_to_tfrecords(images[dev_idx], angles[dev_idx],
angles_ok[dev_idx], positions[dev_idx], dev_fname)
train_fname = '%s/train_CAM_N%000d.tfrecords' % (data_dir.rstrip('/'), Ntrain)
convert_to_tfrecords(images[train_idx], angles[train_idx],
angles_ok[train_idx], positions[train_idx], train_fname)
print('\nSaved data\n%s' % ( '-'*20))
print(' Total num:', Ntot)
print(' Num train:', train_idx.shape[0])
print(' Num dev:', dev_idx.shape[0]) |
the-stack_106_26673 | # -*- coding: utf-8 -*-
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
"""
test_limit
----------------------------------
Tests for `limit` module.
"""
import uuid
from oslotest import base
from oslo_limit import limit
class TestProjectClaim(base.BaseTestCase):
def test_required_parameters(self):
resource_name = uuid.uuid4().hex
project_id = uuid.uuid4().hex
claim = limit.ProjectClaim(resource_name, project_id)
self.assertEqual(resource_name, claim.resource_name)
self.assertEqual(project_id, claim.project_id)
self.assertIsNone(claim.quantity)
def test_optional_parameters(self):
resource_name = uuid.uuid4().hex
project_id = uuid.uuid4().hex
quantity = 10
claim = limit.ProjectClaim(
resource_name, project_id, quantity=quantity
)
self.assertEqual(resource_name, claim.resource_name)
self.assertEqual(project_id, claim.project_id)
self.assertEqual(quantity, claim.quantity)
def test_resource_name_must_be_a_string(self):
project_id = uuid.uuid4().hex
invalid_resource_name_types = [
True, False, [uuid.uuid4().hex], {'key': 'value'}, 1, 1.2
]
for invalid_resource_name in invalid_resource_name_types:
self.assertRaises(
ValueError,
limit.ProjectClaim,
invalid_resource_name,
project_id
)
def test_project_id_must_be_a_string(self):
resource_name = uuid.uuid4().hex
invalid_project_id_types = [
True, False, [uuid.uuid4().hex], {'key': 'value'}, 1, 1.2
]
for invalid_project_id in invalid_project_id_types:
self.assertRaises(
ValueError,
limit.ProjectClaim,
resource_name,
invalid_project_id
)
def test_quantity_must_be_an_integer(self):
resource_name = uuid.uuid4().hex
invalid_quantity_types = ['five', 5.5, [5], {5: 5}]
for invalid_quantity in invalid_quantity_types:
self.assertRaises(
ValueError,
limit.ProjectClaim,
resource_name,
invalid_quantity,
quantity=invalid_quantity
)
class TestEnforcer(base.BaseTestCase):
def setUp(self):
super(TestEnforcer, self).setUp()
self.resource_name = uuid.uuid4().hex
self.project_id = uuid.uuid4().hex
self.quantity = 10
self.claim = limit.ProjectClaim(
self.resource_name, self.project_id, quantity=self.quantity
)
def _get_usage_for_project(self, project_id):
return 8
def test_required_parameters(self):
enforcer = limit.Enforcer(self.claim)
self.assertEqual(self.claim, enforcer.claim)
self.assertIsNone(enforcer.callback)
self.assertTrue(enforcer.verify)
def test_optional_parameters(self):
callback = self._get_usage_for_project
enforcer = limit.Enforcer(self.claim, callback=callback, verify=True)
self.assertEqual(self.claim, enforcer.claim)
self.assertEqual(self._get_usage_for_project, enforcer.callback)
self.assertTrue(enforcer.verify)
def test_callback_must_be_callable(self):
invalid_callback_types = [uuid.uuid4().hex, 5, 5.1]
for invalid_callback in invalid_callback_types:
self.assertRaises(
ValueError,
limit.Enforcer,
self.claim,
callback=invalid_callback
)
def test_verify_must_be_boolean(self):
invalid_verify_types = [uuid.uuid4().hex, 5, 5.1]
for invalid_verify in invalid_verify_types:
self.assertRaises(
ValueError,
limit.Enforcer,
self.claim,
callback=self._get_usage_for_project,
verify=invalid_verify
)
def test_claim_must_be_an_instance_of_project_claim(self):
invalid_claim_types = [uuid.uuid4().hex, 5, 5.1, True, False, [], {}]
for invalid_claim in invalid_claim_types:
self.assertRaises(
ValueError,
limit.Enforcer,
invalid_claim,
)
|
the-stack_106_26675 | # -*- coding: utf-8 -*-
# Copyright 2013 Mirantis, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from nailgun.db import db
from nailgun.db.sqlalchemy.models import NovaNetworkConfig
from nailgun.network.manager import NetworkManager
class NovaNetworkManager(NetworkManager):
@classmethod
def create_nova_network_config(cls, cluster):
nova_net_config = NovaNetworkConfig(
cluster_id=cluster.id,
)
db().add(nova_net_config)
meta = cluster.release.networks_metadata["nova_network"]["config"]
for key, value in meta.iteritems():
if hasattr(nova_net_config, key):
setattr(nova_net_config, key, value)
db().flush()
@classmethod
def generate_vlan_ids_list(cls, data, cluster, ng):
if ng["name"] == "fixed":
netw_params = data.get("networking_parameters", {})
start = netw_params.get("fixed_networks_vlan_start")
amount = netw_params.get("fixed_networks_amount")
if start and amount:
return range(int(start), int(start) + int(amount))
if ng.get("vlan_start") is None:
return []
return [int(ng.get("vlan_start"))]
|
the-stack_106_26677 | # Copyright (c) 2009-2015 Tom Keffer <[email protected]>
# See the file LICENSE.txt for your rights.
"""Example of how to implement a low battery alarm in weewx.
*******************************************************************************
To use this alarm, add the following somewhere in your configuration file
weewx.conf:
[Alarm]
time_wait = 3600
count_threshold = 10
smtp_host = smtp.example.com
smtp_user = myusername
smtp_password = mypassword
from = [email protected]
mailto = [email protected], [email protected]
subject = "Time to change the battery!"
An email will be sent to each address in the comma separated list of recipients
The example assumes an SMTP email server at smtp.example.com that requires
login. If the SMTP server does not require login, leave out the lines for
smtp_user and smtp_password.
Setting an email "from" is optional. If not supplied, one will be filled in,
but your SMTP server may or may not accept it.
Setting an email "subject" is optional. If not supplied, one will be filled in.
To avoid a flood of emails, one will only be sent every 3600 seconds (one
hour).
It will also not send an email unless the low battery indicator has been on
greater than or equal to count_threshold times in an archive period. This
avoids sending out an alarm if the battery is only occasionally being signaled
as bad.
*******************************************************************************
To enable this service:
1) Copy this file to your user directory. See https://bit.ly/33YHsqX for where your user
directory is located.
2) Modify the weewx configuration file by adding this service to the option
"report_services", located in section [Engine][[Services]].
[Engine]
[[Services]]
...
report_services = weewx.engine.StdPrint, weewx.engine.StdReport, user.lowBattery.BatteryAlarm
*******************************************************************************
If you wish to use both this example and the alarm.py example, simply merge the
two configuration options together under [Alarm] and add both services to
report_services.
*******************************************************************************
"""
import time
import smtplib
from email.mime.text import MIMEText
import threading
import syslog
import weewx
from weewx.engine import StdService
from weeutil.weeutil import timestamp_to_string, option_as_list
# Inherit from the base class StdService:
class BatteryAlarm(StdService):
"""Service that sends email if one of the batteries is low"""
def __init__(self, engine, config_dict):
# Pass the initialization information on to my superclass:
super(BatteryAlarm, self).__init__(engine, config_dict)
# This will hold the time when the last alarm message went out:
self.last_msg_ts = 0
# This will hold the count of the number of times the VP2 has signaled
# a low battery alarm this archive period
self.alarm_count = 0
try:
# Dig the needed options out of the configuration dictionary.
# If a critical option is missing, an exception will be thrown and
# the alarm will not be set.
self.time_wait = int(config_dict['Alarm'].get('time_wait', 3600))
self.count_threshold = int(config_dict['Alarm'].get('count_threshold', 10))
self.smtp_host = config_dict['Alarm']['smtp_host']
self.smtp_user = config_dict['Alarm'].get('smtp_user')
self.smtp_password = config_dict['Alarm'].get('smtp_password')
self.SUBJECT = config_dict['Alarm'].get('subject', "Low battery alarm message from weewx")
self.FROM = config_dict['Alarm'].get('from', '[email protected]')
self.TO = option_as_list(config_dict['Alarm']['mailto'])
syslog.syslog(syslog.LOG_INFO, "lowBattery: LowBattery alarm enabled. Count threshold is %d" % self.count_threshold)
# If we got this far, it's ok to start intercepting events:
self.bind(weewx.NEW_LOOP_PACKET, self.newLoopPacket)
self.bind(weewx.NEW_ARCHIVE_RECORD, self.newArchiveRecord)
except KeyError as e:
syslog.syslog(syslog.LOG_INFO, "lowBattery: No alarm set. Missing parameter: %s" % e)
def newLoopPacket(self, event):
"""This function is called on each new LOOP packet."""
# If any battery status flag is non-zero, a battery is low
low_batteries = dict()
for flag in ['txBatteryStatus', 'windBatteryStatus',
'rainBatteryStatus', 'inTempBatteryStatus',
'outTempBatteryStatus']:
if flag in event.packet and event.packet[flag]:
low_batteries[flag] = event.packet[flag]
# If there are any low batteries, see if we need to send an alarm
if low_batteries:
self.alarm_count += 1
# Don't panic on the first occurrence. We must see the alarm at
# least count_threshold times before sounding the alarm.
if self.alarm_count >= self.count_threshold:
# We've hit the threshold. However, to avoid a flood of nearly
# identical emails, send a new one only if it's been a long
# time since we sent the last one:
if abs(time.time() - self.last_msg_ts) >= self.time_wait :
# Sound the alarm!
timestamp = event.packet['dateTime']
# Launch in a separate thread so it does not block the
# main LOOP thread:
t = threading.Thread(target=BatteryAlarm.soundTheAlarm,
args=(self, timestamp,
low_batteries,
self.alarm_count))
t.start()
# Record when the message went out:
self.last_msg_ts = time.time()
def newArchiveRecord(self, event): # @UnusedVariable
"""This function is called on each new archive record."""
# Reset the alarm counter
self.alarm_count = 0
def soundTheAlarm(self, timestamp, battery_flags, alarm_count):
"""This function is called when the alarm has been triggered."""
# Get the time and convert to a string:
t_str = timestamp_to_string(timestamp)
# Log it in the system log:
syslog.syslog(syslog.LOG_INFO, "lowBattery: Low battery status sounded at %s: %s" % (t_str, battery_flags))
# Form the message text:
indicator_strings = []
for bat in battery_flags:
indicator_strings.append("%s: %04x" % (bat, battery_flags[bat]))
msg_text = """
The low battery indicator has been seen %d times since the last archive period.
Alarm sounded at %s
Low battery indicators:
%s
""" % (alarm_count, t_str, '\n'.join(indicator_strings))
# Convert to MIME:
msg = MIMEText(msg_text)
# Fill in MIME headers:
msg['Subject'] = self.SUBJECT
msg['From'] = self.FROM
msg['To'] = ','.join(self.TO)
try:
# First try end-to-end encryption
s=smtplib.SMTP_SSL(self.smtp_host)
syslog.syslog(syslog.LOG_DEBUG, "lowBattery: using SMTP_SSL")
except AttributeError:
# If that doesn't work, try creating an insecure host, then upgrading
s = smtplib.SMTP(self.smtp_host)
try:
# Be prepared to catch an exception if the server
# does not support encrypted transport.
s.ehlo()
s.starttls()
s.ehlo()
syslog.syslog(syslog.LOG_DEBUG,
"lowBattery: using SMTP encrypted transport")
except smtplib.SMTPException:
syslog.syslog(syslog.LOG_DEBUG,
"lowBattery: using SMTP unencrypted transport")
try:
# If a username has been given, assume that login is required
# for this host:
if self.smtp_user:
s.login(self.smtp_user, self.smtp_password)
syslog.syslog(syslog.LOG_DEBUG,
"lowBattery: logged in as %s" % self.smtp_user)
# Send the email:
s.sendmail(msg['From'], self.TO, msg.as_string())
# Log out of the server:
s.quit()
except Exception as e:
syslog.syslog(syslog.LOG_ERR,
"lowBattery: send email failed: %s" % (e,))
raise
# Log sending the email:
syslog.syslog(syslog.LOG_INFO,
"lowBattery: email sent to: %s" % self.TO)
|
the-stack_106_26681 | from src.application.usecase.place_order import PlaceOrder
from src.infra.repository.memory.item_repository_memory import ItemRepositoryMemory
from src.infra.repository.memory.order_repository_memory import OrderRepositoryMemory
def test_place_order():
input = {
"cpf": "847.903.332-05",
"order_items": [
{"id": 1, "quantity": 1},
{"id": 2, "quantity": 1},
{"id": 3, "quantity": 3},
],
}
place_order = PlaceOrder(ItemRepositoryMemory(), OrderRepositoryMemory())
output = place_order.execute(input)
assert output.total == 1680.00
|
the-stack_106_26682 | import copy
def mat_shift(mat, way = 'down', inplace = False):
"""
Shifts a matrix's rows by one position
"""
assert mat.size != None
if inplace:
cmat = mat
else:
cmat = copy.deepcopy(mat)
temp_mat = copy.deepcopy(cmat)
if way.lower() == 'down':
for r in range(cmat.shape[0]):
cmat[r,:] = temp_mat[r+1,:] if r+1 != cmat.shape[0] else temp_mat[0,:]
elif way.lower() == 'up':
for r in range(cmat.shape[0]):
cmat[r,:] = temp_mat[r-1,:] if r-1 != -1 else temp_mat[-1,:]
elif way.lower() == 'right':
for c in range(cmat.shape[1]):
cmat[:,c] = temp_mat[:,c+1] if c+1 != cmat.shape[1] else temp_mat[:,0]
elif way.lower() == 'left':
for c in range(cmat.shape[1]):
cmat[:,c] = temp_mat[:,c-1] if c-1 != -1 else temp_mat[:,-1]
else:
raise ValueError("{!r} is not a valid value for `way`".format(way))
return cmat
|
the-stack_106_26683 | """Test FAST extractor."""
from os.path import dirname, join, realpath
from cd2h_repo_project.modules.terms.fast import FAST
class TestFAST(object):
"""Test FAST extractor."""
filename = 'fast_test_file.nt'
@classmethod
def filepath(cls):
return join(dirname(realpath(__file__)), cls.filename)
def test_load_topics(self):
topics = FAST.load(TestFAST.filepath())
assert topics == [
{
'prefLabel': 'Civil defense--Safety measures',
'identifier': 862474,
},
{
'prefLabel': 'Architecture, Regency',
'identifier': 813916,
},
{
'prefLabel': 'Broad beechfern',
'identifier': 1738210,
},
{
'prefLabel': 'Onions--Diseases and pests--Control',
'identifier': 1045901,
},
]
def test_load_zipped_topics(self):
tmp_filename = TestFAST.filename
FAST.filename = 'fast_test_file.nt.zip'
topics = FAST.load(TestFAST.filepath())
assert topics == [
{
'prefLabel': 'Civil defense--Safety measures',
'identifier': 862474,
},
{
'prefLabel': 'Architecture, Regency',
'identifier': 813916,
},
{
'prefLabel': 'Broad beechfern',
'identifier': 1738210,
},
{
'prefLabel': 'Onions--Diseases and pests--Control',
'identifier': 1045901,
},
]
FAST.filename = tmp_filename
|
the-stack_106_26684 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import re
import sys
import cv2
from face_track import tracker
request_run: bool = True
def main(args=None) -> int:
"""The main routine."""
if args is None:
args = sys.argv[1:]
print(f"OpenCV version: {cv2.__version__}")
cv_info = [
re.sub('\s+', ' ', ci.strip())
for ci in cv2.getBuildInformation().strip().split('\n')
if len(ci) > 0 and re.search(r'(nvidia*:?)|(cuda*:)|(cudnn*:)',
ci.lower()) is not None
]
if cv_info:
print(cv_info)
alpha = tracker.FaceTracker()
alpha.startVideoRecord()
while request_run:
img = alpha.readFrame()
img, info = alpha.findFace(img)
alpha.trackFace(info)
alpha.putPID(img)
alpha.putFPS(img)
alpha.putBattery(img)
alpha.putTemperature(img)
alpha.putFlight(img)
alpha.setAnnotatedImage(img)
cv2.imshow("Alpha Drone", img)
if cv2.waitKey(1) != -1:
break
cv2.destroyAllWindows()
alpha.end()
return 0
if __name__ == "__main__":
sys.exit(main())
|
the-stack_106_26685 | from django.conf import settings
from django.db import migrations
def update_site_forward(apps, schema_editor):
"""Set site domain and name."""
Site = apps.get_model("sites", "Site")
Site.objects.update_or_create(id=settings.SITE_ID, defaults={"domain": "pola.pl", "name": "pola"})
def update_site_backward(apps, schema_editor):
"""Revert site domain and name to default."""
Site = apps.get_model("sites", "Site")
Site.objects.update_or_create(id=settings.SITE_ID, defaults={"domain": "example.com", "name": "example.com"})
class Migration(migrations.Migration):
dependencies = [
('sites', '0001_initial'),
]
operations = [
migrations.RunPython(update_site_forward, update_site_backward),
]
|
the-stack_106_26686 | import io
import os
from operator import itemgetter
from os.path import join
import pytest
from dvc.fs import get_cloud_fs
from dvc.fs.local import LocalFileSystem
from dvc.path_info import PathInfo
from dvc.repo import Repo
from dvc.scm import SCM
from tests.basic_env import TestDir, TestGit, TestGitSubmodule
class TestLocalFileSystem(TestDir):
def setUp(self):
super().setUp()
self.fs = LocalFileSystem()
def test_open(self):
with self.fs.open(self.FOO) as fd:
self.assertEqual(fd.read(), self.FOO_CONTENTS)
with self.fs.open(self.UNICODE, encoding="utf-8") as fd:
self.assertEqual(fd.read(), self.UNICODE_CONTENTS)
def test_exists(self):
self.assertTrue(self.fs.exists(self.FOO))
self.assertTrue(self.fs.exists(self.UNICODE))
self.assertFalse(self.fs.exists("not-existing-file"))
def test_isdir(self):
self.assertTrue(self.fs.isdir(self.DATA_DIR))
self.assertFalse(self.fs.isdir(self.FOO))
self.assertFalse(self.fs.isdir("not-existing-file"))
def test_isfile(self):
self.assertTrue(self.fs.isfile(self.FOO))
self.assertFalse(self.fs.isfile(self.DATA_DIR))
self.assertFalse(self.fs.isfile("not-existing-file"))
class GitFileSystemTests:
# pylint: disable=no-member
def test_open(self):
self.scm.add([self.FOO, self.UNICODE, self.DATA_DIR])
self.scm.commit("add")
fs = self.scm.get_fs("master")
with fs.open(self.FOO) as fd:
self.assertEqual(fd.read(), self.FOO_CONTENTS)
with fs.open(self.UNICODE) as fd:
self.assertEqual(fd.read(), self.UNICODE_CONTENTS)
with self.assertRaises(IOError):
fs.open("not-existing-file")
with self.assertRaises(IOError):
fs.open(self.DATA_DIR)
def test_exists(self):
fs = self.scm.get_fs("master")
self.assertFalse(fs.exists(self.FOO))
self.assertFalse(fs.exists(self.UNICODE))
self.assertFalse(fs.exists(self.DATA_DIR))
self.scm.add([self.FOO, self.UNICODE, self.DATA])
self.scm.commit("add")
fs = self.scm.get_fs("master")
self.assertTrue(fs.exists(self.FOO))
self.assertTrue(fs.exists(self.UNICODE))
self.assertTrue(fs.exists(self.DATA_DIR))
self.assertFalse(fs.exists("non-existing-file"))
def test_isdir(self):
self.scm.add([self.FOO, self.DATA_DIR])
self.scm.commit("add")
fs = self.scm.get_fs("master")
self.assertTrue(fs.isdir(self.DATA_DIR))
self.assertFalse(fs.isdir(self.FOO))
self.assertFalse(fs.isdir("non-existing-file"))
def test_isfile(self):
self.scm.add([self.FOO, self.DATA_DIR])
self.scm.commit("add")
fs = self.scm.get_fs("master")
self.assertTrue(fs.isfile(self.FOO))
self.assertFalse(fs.isfile(self.DATA_DIR))
self.assertFalse(fs.isfile("not-existing-file"))
class TestGitFileSystem(TestGit, GitFileSystemTests):
def setUp(self):
super().setUp()
self.scm = SCM(self._root_dir)
class TestGitSubmoduleFileSystem(TestGitSubmodule, GitFileSystemTests):
def setUp(self):
super().setUp()
self.scm = SCM(self._root_dir)
self._pushd(self._root_dir)
class AssertWalkEqualMixin:
def assertWalkEqual(self, actual, expected, msg=None):
def convert_to_sets(walk_results):
return [
(root, set(dirs), set(nondirs))
for root, dirs, nondirs in walk_results
]
self.assertEqual(
convert_to_sets(actual), convert_to_sets(expected), msg=msg
)
class TestWalkInNoSCM(AssertWalkEqualMixin, TestDir):
def test(self):
fs = LocalFileSystem()
self.assertWalkEqual(
fs.walk(self._root_dir),
[
(
self._root_dir,
["data_dir"],
["code.py", "bar", "тест", "foo"],
),
(join(self._root_dir, "data_dir"), ["data_sub_dir"], ["data"]),
(
join(self._root_dir, "data_dir", "data_sub_dir"),
[],
["data_sub"],
),
],
)
def test_subdir(self):
fs = LocalFileSystem()
self.assertWalkEqual(
fs.walk(join("data_dir", "data_sub_dir")),
[(join("data_dir", "data_sub_dir"), [], ["data_sub"])],
)
class TestWalkInGit(AssertWalkEqualMixin, TestGit):
def test_nobranch(self):
fs = LocalFileSystem(url=self._root_dir)
walk_result = []
for root, dirs, files in fs.walk("."):
dirs[:] = [i for i in dirs if i != ".git"]
walk_result.append((root, dirs, files))
self.assertWalkEqual(
walk_result,
[
(".", ["data_dir"], ["bar", "тест", "code.py", "foo"]),
(join("data_dir"), ["data_sub_dir"], ["data"]),
(join("data_dir", "data_sub_dir"), [], ["data_sub"]),
],
)
self.assertWalkEqual(
fs.walk(join("data_dir", "data_sub_dir")),
[(join("data_dir", "data_sub_dir"), [], ["data_sub"])],
)
def test_branch(self):
scm = SCM(self._root_dir)
scm.add([self.DATA_SUB_DIR])
scm.commit("add data_dir/data_sub_dir/data_sub")
fs = scm.get_fs("master")
self.assertWalkEqual(
fs.walk("."),
[
(self._root_dir, ["data_dir"], ["code.py"]),
(join(self._root_dir, "data_dir"), ["data_sub_dir"], []),
(
join(self._root_dir, "data_dir", "data_sub_dir"),
[],
["data_sub"],
),
],
)
self.assertWalkEqual(
fs.walk(join("data_dir", "data_sub_dir")),
[
(
join(self._root_dir, "data_dir", "data_sub_dir"),
[],
["data_sub"],
)
],
)
def test_cleanfs_subrepo(tmp_dir, dvc, scm, monkeypatch):
tmp_dir.gen({"subdir": {}})
subrepo_dir = tmp_dir / "subdir"
with subrepo_dir.chdir():
subrepo = Repo.init(subdir=True)
subrepo_dir.gen({"foo": "foo", "dir": {"bar": "bar"}})
path = PathInfo(subrepo_dir)
assert dvc.fs.exists(path / "foo")
assert dvc.fs.isfile(path / "foo")
assert dvc.fs.exists(path / "dir")
assert dvc.fs.isdir(path / "dir")
assert subrepo.fs.exists(path / "foo")
assert subrepo.fs.isfile(path / "foo")
assert subrepo.fs.exists(path / "dir")
assert subrepo.fs.isdir(path / "dir")
def test_walk_dont_ignore_subrepos(tmp_dir, scm, dvc):
tmp_dir.dvc_gen({"foo": "foo"}, commit="add foo")
subrepo_dir = tmp_dir / "subdir"
subrepo_dir.mkdir()
with subrepo_dir.chdir():
Repo.init(subdir=True)
scm.add(["subdir"])
scm.commit("Add subrepo")
dvc_fs = dvc.fs
dvc._reset()
scm_fs = scm.get_fs("HEAD")
path = os.fspath(tmp_dir)
get_dirs = itemgetter(1)
assert set(get_dirs(next(dvc_fs.walk(path)))) == {".dvc", "subdir", ".git"}
assert set(get_dirs(next(scm_fs.walk(path)))) == {".dvc", "subdir"}
@pytest.mark.parametrize(
"cloud",
[
pytest.lazy_fixture("local_cloud"),
pytest.lazy_fixture("s3"),
pytest.param(
pytest.lazy_fixture("gs"), marks=pytest.mark.needs_internet
),
pytest.lazy_fixture("hdfs"),
pytest.lazy_fixture("http"),
],
)
def test_fs_getsize(dvc, cloud):
cloud.gen({"data": {"foo": "foo"}, "baz": "baz baz"})
cls, config, path_info = get_cloud_fs(dvc, **cloud.config)
fs = cls(**config)
assert fs.getsize(path_info / "baz") == 7
assert fs.getsize(path_info / "data" / "foo") == 3
@pytest.mark.needs_internet
@pytest.mark.parametrize(
"cloud",
[
pytest.lazy_fixture("azure"),
pytest.lazy_fixture("gs"),
pytest.lazy_fixture("gdrive"),
pytest.lazy_fixture("hdfs"),
pytest.lazy_fixture("local_cloud"),
pytest.lazy_fixture("oss"),
pytest.lazy_fixture("s3"),
pytest.lazy_fixture("ssh"),
pytest.lazy_fixture("webhdfs"),
],
)
def test_fs_upload_fobj(dvc, tmp_dir, cloud):
tmp_dir.gen("foo", "foo")
cls, config, path_info = get_cloud_fs(dvc, **cloud.config)
fs = cls(**config)
from_info = tmp_dir / "foo"
to_info = path_info / "foo"
with open(from_info, "rb") as stream:
fs.upload_fobj(stream, to_info)
assert fs.exists(to_info)
with fs.open(to_info, "rb") as stream:
assert stream.read() == b"foo"
@pytest.mark.needs_internet
@pytest.mark.parametrize("cloud", [pytest.lazy_fixture("gdrive")])
def test_fs_ls(dvc, cloud):
cloud.gen(
{
"directory": {
"foo": "foo",
"bar": "bar",
"baz": {"quux": "quux", "egg": {"foo": "foo"}},
"empty": {},
}
}
)
cls, config, path_info = get_cloud_fs(dvc, **cloud.config)
fs = cls(**config)
path_info /= "directory"
assert {
os.path.basename(file_key.rstrip("/")) for file_key in fs.ls(path_info)
} == {
"foo",
"bar",
"baz",
"empty",
}
assert set(fs.ls(path_info / "empty")) == set()
assert {
(detail["type"], os.path.basename(detail["name"].rstrip("/")))
for detail in fs.ls(path_info / "baz", detail=True)
} == {("file", "quux"), ("directory", "egg")}
@pytest.mark.needs_internet
@pytest.mark.parametrize(
"cloud",
[
pytest.lazy_fixture("s3"),
pytest.lazy_fixture("azure"),
pytest.lazy_fixture("gs"),
pytest.lazy_fixture("webdav"),
pytest.lazy_fixture("gdrive"),
],
)
def test_fs_find(dvc, cloud):
cloud.gen({"data": {"foo": "foo", "bar": {"baz": "baz"}, "quux": "quux"}})
cls, config, path_info = get_cloud_fs(dvc, **cloud.config)
fs = cls(**config)
assert {
os.path.basename(file_key) for file_key in fs.find(path_info / "data")
} == {"foo", "baz", "quux"}
assert {
os.path.basename(file_info["name"])
for file_info in fs.find(path_info / "data", detail=True)
} == {"foo", "baz", "quux"}
@pytest.mark.parametrize(
"cloud",
[
pytest.lazy_fixture("s3"),
pytest.lazy_fixture("azure"),
pytest.param(
pytest.lazy_fixture("gs"), marks=pytest.mark.needs_internet
),
pytest.lazy_fixture("webdav"),
],
)
def test_fs_find_with_etag(dvc, cloud):
cloud.gen({"data": {"foo": "foo", "bar": {"baz": "baz"}, "quux": "quux"}})
cls, config, path_info = get_cloud_fs(dvc, **cloud.config)
fs = cls(**config)
for details in fs.find(path_info / "data", detail=True):
assert (
fs.info(path_info.replace(path=details["name"]))["etag"]
== details["etag"]
)
@pytest.mark.parametrize(
"cloud",
[
pytest.lazy_fixture("azure"),
pytest.param(
pytest.lazy_fixture("gs"), marks=pytest.mark.needs_internet
),
],
)
def test_fs_fsspec_path_management(dvc, cloud):
cloud.gen({"foo": "foo", "data": {"bar": "bar", "baz": {"foo": "foo"}}})
cls, config, _ = get_cloud_fs(dvc, **cloud.config)
fs = cls(**config)
root = cloud.parents[len(cloud.parents) - 1]
bucket_details = fs.info(root)
# special conditions: name always points to the bucket name
assert bucket_details["name"] == root.bucket
assert bucket_details["type"] == "directory"
data = cloud / "data"
data_details = fs.info(data)
assert data_details["name"].rstrip("/") == data.path
assert data_details["type"] == "directory"
@pytest.mark.needs_internet
@pytest.mark.parametrize(
"cloud",
[
pytest.lazy_fixture("azure"),
pytest.lazy_fixture("gs"),
pytest.lazy_fixture("s3"),
pytest.lazy_fixture("webdav"),
],
)
def test_fs_makedirs_on_upload_and_copy(dvc, cloud):
cls, config, _ = get_cloud_fs(dvc, **cloud.config)
fs = cls(**config)
with io.BytesIO(b"foo") as stream:
fs.upload(stream, cloud / "dir" / "foo")
assert fs.isdir(cloud / "dir")
assert fs.exists(cloud / "dir" / "foo")
fs.copy(cloud / "dir" / "foo", cloud / "dir2" / "foo")
assert fs.isdir(cloud / "dir2")
assert fs.exists(cloud / "dir2" / "foo")
|
the-stack_106_26687 | """
Test Figure.grdimage.
"""
import numpy as np
import pytest
import xarray as xr
from pygmt import Figure
from pygmt.datasets import load_earth_relief
from pygmt.exceptions import GMTInvalidInput
from pygmt.helpers.testing import check_figures_equal
@pytest.fixture(scope="module", name="grid")
def fixture_grid():
"""
Load the grid data from the sample earth_relief file.
"""
return load_earth_relief(registration="gridline")
@pytest.fixture(scope="module", name="grid_360")
def fixture_grid_360(grid):
"""
Earth relief grid with longitude range from 0 to 360 (instead of -180 to
180).
"""
_grid = grid.copy() # get a copy of original earth_relief grid
_grid.encoding.pop("source") # unlink earth_relief NetCDF source
_grid["lon"] = np.arange(0, 361, 1) # convert longitude from -180:180 to 0:360
return _grid
@pytest.fixture(scope="module", name="xrgrid")
def fixture_xrgrid():
"""
Create a sample xarray.DataArray grid for testing.
"""
longitude = np.arange(0, 360, 1)
latitude = np.arange(-89, 90, 1)
x = np.sin(np.deg2rad(longitude))
y = np.linspace(start=0, stop=1, num=179)
data = y[:, np.newaxis] * x
return xr.DataArray(
data,
coords=[
("latitude", latitude, {"units": "degrees_north"}),
("longitude", longitude, {"units": "degrees_east"}),
],
attrs={"actual_range": [-1, 1]},
)
@pytest.mark.mpl_image_compare
def test_grdimage(grid):
"""
Plot an image using an xarray grid.
"""
fig = Figure()
fig.grdimage(grid, cmap="earth", projection="W0/6i")
return fig
@pytest.mark.mpl_image_compare
def test_grdimage_slice(grid):
"""
Plot an image using an xarray grid that has been sliced.
"""
grid_ = grid.sel(lat=slice(-30, 30))
fig = Figure()
fig.grdimage(grid_, cmap="earth", projection="M6i")
return fig
@pytest.mark.mpl_image_compare
def test_grdimage_file():
"""
Plot an image using file input.
"""
fig = Figure()
fig.grdimage(
"@earth_relief_01d_g",
cmap="ocean",
region=[-180, 180, -70, 70],
projection="W0/10i",
shading=True,
)
return fig
@check_figures_equal()
@pytest.mark.parametrize(
"shading",
[True, 0.5, "+a30+nt0.8", "@earth_relief_01d_g+d", "@earth_relief_01d_g+a60+nt0.8"],
)
def test_grdimage_shading_xarray(grid, shading):
"""
Test that shading works well for xarray.
The ``shading`` can be True, a constant intensity, some modifiers, or
a grid with modifiers.
See https://github.com/GenericMappingTools/pygmt/issues/364 and
https://github.com/GenericMappingTools/pygmt/issues/618.
"""
fig_ref, fig_test = Figure(), Figure()
kwargs = dict(
region=[-180, 180, -90, 90],
frame=True,
projection="Cyl_stere/6i",
cmap="geo",
shading=shading,
)
fig_ref.grdimage("@earth_relief_01d_g", **kwargs)
fig_test.grdimage(grid, **kwargs)
return fig_ref, fig_test
@pytest.mark.xfail(
reason="Incorrect scaling of geo CPT on xarray.DataArray grdimage plot."
"See https://github.com/GenericMappingTools/gmt/issues/5294",
)
@check_figures_equal()
def test_grdimage_grid_and_shading_with_xarray(grid, xrgrid):
"""
Test that shading works well when xarray.DataArray is input to both the
``grid`` and ``shading`` arguments.
"""
fig_ref, fig_test = Figure(), Figure()
fig_ref.grdimage(
grid="@earth_relief_01d_g", region="GL", cmap="geo", shading=xrgrid, verbose="i"
)
fig_ref.colorbar()
fig_test.grdimage(grid=grid, region="GL", cmap="geo", shading=xrgrid, verbose="i")
fig_test.colorbar()
return fig_ref, fig_test
def test_grdimage_fails():
"""
Should fail for unrecognized input.
"""
fig = Figure()
with pytest.raises(GMTInvalidInput):
fig.grdimage(np.arange(20).reshape((4, 5)))
@pytest.mark.mpl_image_compare
def test_grdimage_over_dateline(xrgrid):
"""
Ensure no gaps are plotted over the 180 degree international dateline.
Specifically checking that `xrgrid.gmt.gtype = 1` sets `GMT_GRID_IS_GEO`,
and that `xrgrid.gmt.registration = 0` sets `GMT_GRID_NODE_REG`. Note that
there would be a gap over the dateline if a pixel registered grid is used.
See also https://github.com/GenericMappingTools/pygmt/issues/375.
"""
fig = Figure()
assert xrgrid.gmt.registration == 0 # gridline registration
xrgrid.gmt.gtype = 1 # geographic coordinate system
fig.grdimage(grid=xrgrid, region="g", projection="A0/0/1c", V="i")
return fig
@pytest.mark.mpl_image_compare
def test_grdimage_global_subset(grid_360):
"""
Ensure subsets of grids are plotted correctly on a global map.
Specifically checking that xarray.DataArray grids can wrap around the left
and right sides on a Mollweide projection (W) plot correctly. Note that a
Cartesian grid is used here instead of a Geographic grid (i.e.
GMT_GRID_IS_CARTESIAN). This is a regression test for
https://github.com/GenericMappingTools/pygmt/issues/732.
"""
# Get a slice of South America and Africa only (lat=-90:31, lon=-180:41)
sliced_grid = grid_360[0:121, 0:221]
assert sliced_grid.gmt.registration == 0 # gridline registration
assert sliced_grid.gmt.gtype == 0 # Cartesian coordinate system
fig = Figure()
fig.grdimage(
grid=sliced_grid, cmap="vik", region="g", projection="W0/3.5c", frame=True
)
return fig
@check_figures_equal()
@pytest.mark.parametrize("lon0", [0, 123, 180])
@pytest.mark.parametrize("proj_type", ["H", "W"])
def test_grdimage_central_meridians(grid, proj_type, lon0):
"""
Test that plotting a grid with different central meridians (lon0) using
Hammer (H) and Mollweide (W) projection systems work.
"""
fig_ref, fig_test = Figure(), Figure()
fig_ref.grdimage(
"@earth_relief_01d_g", projection=f"{proj_type}{lon0}/15c", cmap="geo"
)
fig_test.grdimage(grid, projection=f"{proj_type}{lon0}/15c", cmap="geo")
return fig_ref, fig_test
# Cylindrical Equidistant (Q) projections plotted with xarray and NetCDF grids
# are still slightly different with an RMS error of 25, see issue at
# https://github.com/GenericMappingTools/pygmt/issues/390
# TO-DO remove tol=1.5 and pytest.mark.xfail once bug is solved in upstream GMT
@check_figures_equal(tol=1.5)
@pytest.mark.parametrize("lat0", [0, 30])
@pytest.mark.parametrize("lon0", [0, 123, 180])
@pytest.mark.parametrize("proj_type", [pytest.param("Q", marks=pytest.mark.xfail), "S"])
def test_grdimage_central_meridians_and_standard_parallels(grid, proj_type, lon0, lat0):
"""
Test that plotting a grid with different central meridians (lon0) and
standard_parallels (lat0) using Cylindrical Equidistant (Q) and General
Stereographic (S) projection systems work.
"""
fig_ref, fig_test = Figure(), Figure()
fig_ref.grdimage(
"@earth_relief_01d_g", projection=f"{proj_type}{lon0}/{lat0}/15c", cmap="geo"
)
fig_test.grdimage(grid, projection=f"{proj_type}{lon0}/{lat0}/15c", cmap="geo")
return fig_ref, fig_test
|
the-stack_106_26688 | from blackbot.core.utils import get_path_in_package
from blackbot.core.wss.atomic import Atomic
from terminaltables import SingleTable
import os
import json
class Atomic(Atomic):
def __init__(self):
self.name = 'Impact/T1489-2'
self.controller_type = ''
self.external_id = 'T1489'
self.blackbot_id = 'T1489-2'
self.version = ''
self.language = 'boo'
self.description = self.get_description()
self.last_updated_by = 'Blackbot, Inc. All Rights reserved'
self.references = ["System.Management.Automation"]
self.options = {}
def payload(self):
with open(get_path_in_package('core/wss/ttp/art/src/cmd_prompt.boo'), 'r') as ttp_src:
src = ttp_src.read()
cmd_script = get_path_in_package('core/wss/ttp/art/cmd_ttp/impact/T1489-2')
with open(cmd_script) as cmd:
src = src.replace("CMD_SCRIPT", cmd.read())
return src
def get_description(self):
path = get_path_in_package('core/wss/ttp/art/cmd_ttp/impact/T1489-2')
with open(path) as text:
head = [next(text) for l in range(4)]
technique_name = head[0].replace('#TechniqueName: ', '').strip('\n')
atomic_name = head[1].replace('#AtomicTestName: ', '').strip('\n')
description = head[2].replace('#Description: ', '').strip('\n')
language = head[3].replace('#Language: ', '').strip('\n')
aux = ''
count = 1
for char in description:
if char == '&':
continue
aux += char
if count % 126 == 0:
aux += '\n'
count += 1
out = '{}: {}\n{}\n\n{}\n'.format(technique_name, language, atomic_name, aux)
return out
|
the-stack_106_26689 | import torch
from torch.autograd import Variable
import torch.nn as nn
import torch.utils.model_zoo as model_zoo
import torch.nn.functional as F
import random
import numpy as np
import os
__all__ = [
'VGG', 'vgg11', 'vgg11_bn', 'vgg13', 'vgg13_bn', 'vgg16', 'vgg16_bn',
'vgg19_bn', 'vgg19', 'model'
]
model_urls = {
'vgg11': 'https://download.pytorch.org/models/vgg11-bbd30ac9.pth',
'vgg13': 'https://download.pytorch.org/models/vgg13-c768596a.pth',
'vgg16': 'https://download.pytorch.org/models/vgg16-397923af.pth',
'vgg19': 'https://download.pytorch.org/models/vgg19-dcbb9e9d.pth',
'vgg11_bn': 'https://download.pytorch.org/models/vgg11_bn-6002323d.pth',
'vgg13_bn': 'https://download.pytorch.org/models/vgg13_bn-abd245e5.pth',
'vgg16_bn': 'https://download.pytorch.org/models/vgg16_bn-6c64b313.pth',
'vgg19_bn': 'https://download.pytorch.org/models/vgg19_bn-c79401a0.pth',
}
class VGG(nn.Module):
def __init__(self, features, num_classes=1000, cnvs=(10,17,24), args=None):
super(VGG, self).__init__()
self.conv1_2 = nn.Sequential(*features[:cnvs[0]])
self.conv3 = nn.Sequential(*features[cnvs[0]:cnvs[1]])
self.conv4 = nn.Sequential(*features[cnvs[1]:cnvs[2]])
self.conv5 = nn.Sequential(*features[cnvs[2]:-1])
self.conv5_add = nn.Sequential(
nn.Conv2d(512, 512,3, padding=1),
nn.ReLU(inplace=True))
self.fmp = features[-1] # final max pooling
self.num_classes = num_classes
self.args = args
self.cls = nn.Sequential(
nn.Conv2d(512, 1024, kernel_size=3, padding=1, dilation=1), # fc6
nn.ReLU(True),
nn.Conv2d(1024, 1024, kernel_size=3, padding=1, dilation=1), # fc7
nn.ReLU(True),
nn.Conv2d(1024, self.num_classes, kernel_size=1, padding=0)
)
self._initialize_weights()
# loss function
self.loss_cross_entropy = F.cross_entropy
self.loss_bce = F.binary_cross_entropy_with_logits
self.nll_loss = F.nll_loss
def _initialize_weights(self):
for m in self.modules():
if isinstance(m, nn.Conv2d):
nn.init.xavier_uniform_(m.weight.data)
if m.bias is not None:
m.bias.data.zero_()
elif isinstance(m, nn.BatchNorm2d):
m.weight.data.fill_(1)
m.bias.data.zero_()
elif isinstance(m, nn.Linear):
m.weight.data.normal_(0, 0.01)
m.bias.data.zero_()
def forward(self, x, scg_flag=False):
x = self.conv1_2(x)
sc_2 = None
sc_2_so = None
if scg_flag and '2' in self.args.scg_blocks :
sc_2, sc_2_so = self.hsc(x, fo_th=self.args.scg_fosc_th,
so_th=self.args.scg_sosc_th,
order=self.args.scg_order)
feat_3 = self.conv3(x)
sc_3 = None
sc_3_so = None
if scg_flag and '3' in self.args.scg_blocks :
sc_3, sc_3_so = self.hsc(feat_3, fo_th=self.args.scg_fosc_th,
so_th=self.args.scg_sosc_th,
order=self.args.scg_order)
feat_4 = self.conv4(feat_3)
self.feat4= feat_4
sc_4 = None
sc_4_so = None
if scg_flag and '4' in self.args.scg_blocks:
sc_4, sc_4_so = self.hsc(feat_4, fo_th=self.args.scg_fosc_th,
so_th=self.args.scg_sosc_th,
order=self.args.scg_order)
feat_5 = self.conv5(feat_4)
self.feat5= feat_5
sc_5 = None
sc_5_so = None
if scg_flag and '5' in self.args.scg_blocks:
sc_5, sc_5_so = self.hsc(feat_5, fo_th=self.args.scg_fosc_th,
so_th=self.args.scg_sosc_th,
order=self.args.scg_order)
cls_map = self.cls(feat_5)
self.cls_map = cls_map
return cls_map, (sc_2, sc_3, sc_4, sc_5), (sc_2_so, sc_3_so, sc_4_so, sc_5_so)
def hsc(self, f_phi, fo_th=0.1, so_th=0.1, order=2):
"""
Calculate affinity matrix and update feature.
:param feat:
:param f_phi:
:param fo_th:
:param so_weight:
:return:
"""
n, c_nl, h, w = f_phi.size()
c_nl = f_phi.size(1)
f_phi = f_phi.permute(0, 2, 3, 1).contiguous().view(n, -1, c_nl)
f_phi_normed = f_phi/(torch.norm(f_phi, dim=2, keepdim=True)+1e-10)
# first order
non_local_cos = F.relu(torch.matmul(f_phi_normed, f_phi_normed.transpose(1,2)))
non_local_cos[non_local_cos<fo_th] = 0
non_local_cos_fo = non_local_cos.clone()
non_local_cos_fo = non_local_cos_fo / (torch.sum(non_local_cos_fo, dim=1, keepdim=True) + 1e-5)
# high order
base_th = 1./(h*w)
non_local_cos[:, torch.arange(h * w), torch.arange(w * h)] = 0
non_local_cos = non_local_cos/(torch.sum(non_local_cos,dim=1, keepdim=True) + 1e-5)
non_local_cos_ho = non_local_cos.clone()
so_th = base_th * so_th
for _ in range(order-1):
non_local_cos_ho = torch.matmul(non_local_cos_ho, non_local_cos)
# non_local_cos_ho[:, torch.arange(h * w), torch.arange(w * h)] = 0
non_local_cos_ho = non_local_cos_ho / (torch.sum(non_local_cos_ho, dim=1, keepdim=True) + 1e-10)
# non_local_cos_ho = non_local_cos_ho - torch.min(non_local_cos_ho, dim=1, keepdim=True)[0]
#non_local_cos_ho = non_local_cos_ho / (torch.max(non_local_cos_ho, dim=1, keepdim=True)[0] + 1e-10)
non_local_cos_ho[non_local_cos_ho < so_th] = 0
return non_local_cos_fo, non_local_cos_ho
def get_loss(self, logits, gt_child_label, epoch=0, ram_start=10):
cls_logits = torch.mean(torch.mean(logits, dim=2), dim=2)
loss = 0
loss += self.loss_cross_entropy(cls_logits, gt_child_label.long())
if self.args.ram and epoch >= ram_start:
ra_loss = self.get_ra_loss(logits, gt_child_label, self.args.ram_th_bg, self.args.ram_bg_fg_gap)
loss += self.args.ra_loss_weight * ra_loss
else:
ra_loss = torch.zeros_like(loss)
return loss, ra_loss,
def get_ra_loss(self, logits, label, th_bg=0.3, bg_fg_gap=0.0):
n, _, _, _ = logits.size()
cls_logits = F.softmax(logits, dim=1)
var_logits = torch.var(cls_logits, dim=1)
norm_var_logits = self.normalize_feat(var_logits)
bg_mask = (norm_var_logits < th_bg).float()
fg_mask = (norm_var_logits > (th_bg + bg_fg_gap)).float()
cls_map = logits[torch.arange(n), label.long(), ...]
cls_map = torch.sigmoid(cls_map)
ra_loss = torch.mean(cls_map * bg_mask + (1 - cls_map) * fg_mask)
return ra_loss
def normalize_feat(self,feat):
n, fh, fw = feat.size()
feat = feat.view(n, -1)
min_val, _ = torch.min(feat, dim=-1, keepdim=True)
max_val, _ = torch.max(feat, dim=-1, keepdim=True)
norm_feat = (feat - min_val) / (max_val - min_val + 1e-15)
norm_feat = norm_feat.view(n, fh, fw)
return norm_feat
def get_cls_maps(self):
return F.relu(self.cls_map)
def get_loc_maps(self):
return torch.sigmoid(self.loc_map)
def make_layers(cfg, dilation=None, batch_norm=False, instance_norm=False, inl=False):
layers = []
in_channels = 3
for v, d in zip(cfg, dilation):
if v == 'M':
layers += [nn.MaxPool2d(kernel_size=3, stride=2, padding=1)]
elif v == 'N':
layers += [nn.MaxPool2d(kernel_size=3, stride=1, padding=1)]
elif v == 'L':
layers += [nn.MaxPool2d(kernel_size=2, stride=2, padding=0)]
else:
conv2d = nn.Conv2d(in_channels, v, kernel_size=3, padding=d, dilation=d)
if batch_norm:
layers += [conv2d, nn.BatchNorm2d(v), nn.ReLU(inplace=True)]
elif instance_norm and v <256 and v>64:
layers += [conv2d, nn.InstanceNorm2d(v, affine=inl), nn.ReLU(inplace=True)]
else:
layers += [conv2d, nn.ReLU(inplace=True)]
in_channels = v
return layers
cfg = {
'A': [64, 'M', 128, 'M', 256, 256, 'M', 512, 512, 'M', 512, 512, 'M'],
'B': [64, 64, 'M', 128, 128, 'M', 256, 256, 'M', 512, 512, 'M', 512, 512, 'M'],
'D': [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 'M', 512, 512, 512, 'M', 512, 512, 512, 'M'],
'D1': [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 'M', 512, 512, 512, 'N', 512, 512, 512, 'N'],
# 'D_deeplab': [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 'M', 512, 512, 512, 'N', 512, 512, 512, 'N'],
'E': [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 256, 'M', 512, 512, 512, 512, 'M', 512, 512, 512, 512, 'M'],
'O': [64, 64, 'L', 128, 128, 'L', 256, 256, 256, 'L', 512, 512, 512, 'L', 512, 512, 512, 'L']
}
dilation = {
'D_deeplab': [1, 1, 'M', 1, 1, 'M', 1, 1, 1, 'M', 1, 1, 1, 'N', 2, 2, 2, 'N'],
'D1': [1, 1, 'M', 1, 1, 'M', 1, 1, 1, 'M', 1, 1, 1, 'N', 1, 1, 1, 'N']
}
cnvs= {'O': (10,7,7), 'OI':(12,7,7)}
def model(pretrained=False, **kwargs):
"""VGG 16-layer model (configuration "D")
Args:
pretrained (bool): If True, returns a model pre-trained on ImageNet
'D': [64, 64, 'M', 128, 128, 'M', 256, 256, 256, 'M', 512, 512, 512, 'M', 512, 512, 512, 'M'],
"""
layers = make_layers(cfg['O'], dilation=dilation['D1'])
cnv = np.cumsum(cnvs['O'])
model = VGG(layers, cnvs=cnv, **kwargs)
if pretrained:
pre2local_keymap = [('features.{}.weight'.format(i), 'conv1_2.{}.weight'.format(i)) for i in range(10)]
pre2local_keymap += [('features.{}.bias'.format(i), 'conv1_2.{}.bias'.format(i)) for i in range(10)]
pre2local_keymap += [('features.{}.weight'.format(i + 10), 'conv3.{}.weight'.format(i)) for i in range(7)]
pre2local_keymap += [('features.{}.bias'.format(i + 10), 'conv3.{}.bias'.format(i)) for i in range(7)]
pre2local_keymap += [('features.{}.weight'.format(i + 17), 'conv4.{}.weight'.format(i)) for i in range(7)]
pre2local_keymap += [('features.{}.bias'.format(i + 17), 'conv4.{}.bias'.format(i)) for i in range(7)]
pre2local_keymap += [('features.{}.weight'.format(i + 24), 'conv5.{}.weight'.format(i)) for i in range(7)]
pre2local_keymap += [('features.{}.bias'.format(i + 24), 'conv5.{}.bias'.format(i)) for i in range(7)]
pre2local_keymap = dict(pre2local_keymap)
model_dict = model.state_dict()
pretrained_file = os.path.join(kwargs['args'].pretrained_model_dir, kwargs['args'].pretrained_model)
if os.path.isfile(pretrained_file):
pretrained_dict = torch.load(pretrained_file)
print('load pretrained model from {}'.format(pretrained_file))
else:
pretrained_dict = model_zoo.load_url(model_urls['vgg16'])
print('load pretrained model from {}'.format(model_urls['vgg16']))
# 0. replace the key
pretrained_dict = {pre2local_keymap[k] if k in pre2local_keymap.keys() else k: v for k, v in
pretrained_dict.items()}
# *. show the loading information
for k in pretrained_dict.keys():
if k not in model_dict:
print('Key {} is removed from vgg16'.format(k))
print(' ')
for k in model_dict.keys():
if k not in pretrained_dict:
print('Key {} is new added for DA Net'.format(k))
# 1. filter out unnecessary keys
pretrained_dict = {k: v for k, v in pretrained_dict.items() if k in model_dict}
# 2. overwrite entries in the existing state dict
model_dict.update(pretrained_dict)
# 3. load the new state dict
model.load_state_dict(model_dict)
return model
if __name__ == '__main__':
model(True)
|
the-stack_106_26691 | # timing_t.cfg
# NON-REGRESSSION Unit test configuration file for MessageLogger service:
# This variant puts Timing into job report.
# Tester should run with FrameworkJobReport.fwk and timing_t.log for proper timing info.
import FWCore.ParameterSet.Config as cms
process = cms.Process("TEST")
import FWCore.Framework.test.cmsExceptionsFatal_cff
process.options = FWCore.Framework.test.cmsExceptionsFatal_cff.options
process.load("FWCore.MessageService.test.Services_cff")
process.Timing = cms.Service("Timing",
useJobReport = cms.untracked.bool(True)
)
process.MessageLogger = cms.Service("MessageLogger",
# produce file u16_job_report.mmxml
u16_job_report = cms.untracked.PSet(
extension = cms.untracked.string('mmxml')
),
default = cms.untracked.PSet(
FwkJob = cms.untracked.PSet(
limit = cms.untracked.int32(0)
)
),
timing_t = cms.untracked.PSet(
threshold = cms.untracked.string('ERROR'),
noTimeStamps = cms.untracked.bool(True)
),
debugModules = cms.untracked.vstring('*'),
categories = cms.untracked.vstring('preEventProcessing',
'FwkJob'),
destinations = cms.untracked.vstring('timing_t')
)
process.maxEvents = cms.untracked.PSet(
input = cms.untracked.int32(10)
)
process.source = cms.Source("EmptySource")
process.sendSomeMessages = cms.EDAnalyzer("UnitTestClient_A")
process.p = cms.Path(process.sendSomeMessages)
|
the-stack_106_26692 | import shutil
from dataclasses import dataclass
from pathlib import Path
from typing import Union
import requests
from fastapi.logger import logger
from mealie.core.config import app_dirs
from mealie.services.image import minify
@dataclass
class ImageOptions:
ORIGINAL_IMAGE: str = "original*"
MINIFIED_IMAGE: str = "min-original*"
TINY_IMAGE: str = "tiny-original*"
IMG_OPTIONS = ImageOptions()
def read_image(recipe_slug: str, image_type: str = "original") -> Path:
"""returns the path to the image file for the recipe base of image_type
Args:
recipe_slug (str): Recipe Slug
image_type (str, optional): Glob Style Matcher "original*" | "min-original* | "tiny-original*"
Returns:
Path: [description]
"""
recipe_slug = recipe_slug.split(".")[0] # Incase of File Name
recipe_image_dir = app_dirs.IMG_DIR.joinpath(recipe_slug)
for file in recipe_image_dir.glob(image_type):
return file
return None
def rename_image(original_slug, new_slug) -> Path:
current_path = app_dirs.IMG_DIR.joinpath(original_slug)
new_path = app_dirs.IMG_DIR.joinpath(new_slug)
try:
new_path = current_path.rename(new_path)
except FileNotFoundError:
logger.error(f"Image Directory {original_slug} Doesn't Exist")
return new_path
def write_image(recipe_slug: str, file_data: bytes, extension: str) -> Path.name:
try:
delete_image(recipe_slug)
except:
pass
image_dir = Path(app_dirs.IMG_DIR.joinpath(f"{recipe_slug}"))
image_dir.mkdir()
extension = extension.replace(".", "")
image_path = image_dir.joinpath(f"original.{extension}")
if isinstance(file_data, bytes):
with open(image_path, "ab") as f:
f.write(file_data)
else:
with open(image_path, "ab") as f:
shutil.copyfileobj(file_data, f)
minify.migrate_images()
return image_path
def delete_image(recipe_slug: str) -> str:
recipe_slug = recipe_slug.split(".")[0]
for file in app_dirs.IMG_DIR.glob(f"{recipe_slug}*"):
return shutil.rmtree(file)
def scrape_image(image_url: str, slug: str) -> Path:
if isinstance(image_url, str): # Handles String Types
image_url = image_url
if isinstance(image_url, list): # Handles List Types
image_url = image_url[0]
if isinstance(image_url, dict): # Handles Dictionary Types
for key in image_url:
if key == "url":
image_url = image_url.get("url")
filename = slug + "." + image_url.split(".")[-1]
filename = app_dirs.IMG_DIR.joinpath(filename)
try:
r = requests.get(image_url, stream=True)
except:
logger.exception("Fatal Image Request Exception")
return None
if r.status_code == 200:
r.raw.decode_content = True
write_image(slug, r.raw, filename.suffix)
filename.unlink()
return slug
return None
|
the-stack_106_26698 | # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
# Copyright 2015 and onwards Google, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from nemo_text_processing.text_normalization.graph_utils import GraphFst
from nemo_text_processing.text_normalization.verbalizers.cardinal import CardinalFst
from nemo_text_processing.text_normalization.verbalizers.date import DateFst
from nemo_text_processing.text_normalization.verbalizers.decimal import DecimalFst
from nemo_text_processing.text_normalization.verbalizers.electronic import ElectronicFst
from nemo_text_processing.text_normalization.verbalizers.measure import MeasureFst
from nemo_text_processing.text_normalization.verbalizers.money import MoneyFst
from nemo_text_processing.text_normalization.verbalizers.ordinal import OrdinalFst
from nemo_text_processing.text_normalization.verbalizers.telephone import TelephoneFst
from nemo_text_processing.text_normalization.verbalizers.time import TimeFst
from nemo_text_processing.text_normalization.verbalizers.whitelist import WhiteListFst
class VerbalizeFst(GraphFst):
"""
Composes other verbalizer grammars.
For deployment, this grammar will be compiled and exported to OpenFst Finate State Archiv (FAR) File.
More details to deployment at NeMo/tools/text_processing_deployment.
Args:
deterministic: if True will provide a single transduction option,
for False multiple options (used for audio-based normalization)
"""
def __init__(self, deterministic: bool = True):
super().__init__(name="verbalize", kind="verbalize", deterministic=deterministic)
cardinal = CardinalFst(deterministic=deterministic)
cardinal_graph = cardinal.fst
decimal = DecimalFst(cardinal=cardinal, deterministic=deterministic)
decimal_graph = decimal.fst
ordinal = OrdinalFst(deterministic=deterministic)
ordinal_graph = ordinal.fst
telephone_graph = TelephoneFst(deterministic=deterministic).fst
electronic_graph = ElectronicFst(deterministic=deterministic).fst
measure = MeasureFst(decimal=decimal, cardinal=cardinal, deterministic=deterministic)
measure_graph = measure.fst
time_graph = TimeFst(deterministic=deterministic).fst
date_graph = DateFst(ordinal=ordinal, deterministic=deterministic).fst
money_graph = MoneyFst(decimal=decimal, deterministic=deterministic).fst
whitelist_graph = WhiteListFst(deterministic=deterministic).fst
graph = (
time_graph
| date_graph
| money_graph
| measure_graph
| ordinal_graph
| decimal_graph
| cardinal_graph
| telephone_graph
| electronic_graph
| whitelist_graph
)
self.fst = graph
|
the-stack_106_26699 | from typing import List, Optional, Tuple, Dict
import numpy as np
from docknet.layer.abstract_layer import AbstractLayer
class AdamOptimizer(object):
def __init__(self, learning_rate: float = 0.01, beta1: float = 0.9, beta2: float = 0.999, epsilon: float = 1e-8):
"""
Builds a new Adam Optimizer storing the optimizer parameters and defining additional parameters to be used
during the optimization process
"""
self.learning_rate = learning_rate
self.beta1 = beta1
self.beta2 = beta2
self.epsilon = epsilon
self.network_params: Optional[List[Tuple]] = None
self.network_v: List[Dict[str, np.ndarray]] = []
self.network_s: List[Dict[str, np.ndarray]] = []
self.t = 0
def reset(self, layers: List[AbstractLayer]):
"""
Initializes Adam's v and s parameters as 0 for each network parameter, and Adam's counter t as 0
:param layers: the list of network layers
"""
self.network_v.clear()
self.network_s.clear()
for layer in layers:
layer_v = {name: np.zeros(value.shape) for name, value in layer.params.items()}
layer_s = {name: np.zeros(value.shape) for name, value in layer.params.items()}
self.network_v.append(layer_v)
self.network_s.append(layer_s)
self.t = 1
def optimize(self, network_layers: List[AbstractLayer], network_gradients: List[Dict[str, np.ndarray]]):
"""
Optimize the network parameters, given the gradients of the cost function wrt the network parameters for one
given batch during one training iteration
:param network_layers: the list of network layers
:param network_gradients: the network parameter gradients as a list of dictionaries, one dictionary per layer,
where each dictionary contains key/value pairs (k, v) with k the name of a layer parameter and v the
the corresponding gradient
"""
# For each layer except the input layer (since no gradients are computed for the input layer)
for p, dp, v, s in \
zip([layer.params for layer in network_layers], network_gradients, self.network_v, self.network_s):
# For each param in the layer
for k in p.keys():
# Compute moving average of the gradients
v[k] = self.beta1 * v[k] + (1 - self.beta1) * dp[k]
# Compute bias-corrected first moment estimate
v_corrected = v[k] / (1 - self.beta1 ** self.t)
# Compute moving average of the squared gradients
s[k] = self.beta2 * s[k] + (1 - self.beta2) * dp[k]**2
# Compute bias-corrected second raw moment estimate
s_corrected = s[k] / (1 - self.beta2 ** self.t)
# Update parameter
p[k] = p[k] - self.learning_rate * v_corrected / (np.sqrt(s_corrected + self.epsilon))
|
the-stack_106_26700 | # Copyright (c) 2010 Advanced Micro Devices, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met: redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer;
# redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution;
# neither the name of the copyright holders nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# Authors: Steve Reinhardt
from m5.params import *
from m5.objects import *
class Crossbar(Topology):
description='Crossbar'
def makeTopology(nodes, options, IntLink, ExtLink, Router):
# Create an individual router for each controller plus one more for the
# centralized crossbar. The large numbers of routers are needed because
# external links do not model outgoing bandwidth in the simple network, but
# internal links do.
cb = Crossbar()
cb.routers = [Router(router_id=i) for i in range(len(nodes)+1)]
cb.ext_links = [ExtLink(link_id=i, ext_node=n, int_node=cb.routers[i])
for (i, n) in enumerate(nodes)]
link_count = len(nodes)
xbar = cb.routers[len(nodes)] # the crossbar router is the last router created
cb.int_links = [IntLink(link_id=(link_count+i),
node_a=cb.routers[i], node_b=xbar)
for i in range(len(nodes))]
return cb
|
the-stack_106_26701 | # Copyright (c) 2018, The MITRE Corporation. All rights reserved.
# See LICENSE.txt for complete terms.
import unittest
from cybox.test import EntityTestCase, round_trip
from maec.bundle.bundle import Bundle
from maec.bundle.malware_action import MalwareAction
from cybox.core import Object
from maec.bundle.behavior import Behavior
from maec.bundle.candidate_indicator import CandidateIndicator
class TestBundle(EntityTestCase, unittest.TestCase):
klass = Bundle
_full_dict = {
'defined_subject':False
}
def test_id_autoset(self):
o = Bundle()
self.assertNotEqual(o.id_, None)
def test_round_trip(self):
o = Bundle()
o2 = round_trip(o, True)
self.assertEqual(o.to_dict(), o2.to_dict())
def test_add_collections(self):
o = Bundle()
o.add_named_action_collection("Actions")
ma = MalwareAction()
o.add_action(ma, "Actions")
self.assertTrue(o.collections.action_collections.has_collection("Actions"))
o.add_named_object_collection("Objects")
obj = Object()
o.add_object(obj, "Objects")
self.assertTrue(o.collections.object_collections.has_collection("Objects"))
o.add_named_behavior_collection("Behaviors")
b = Behavior()
o.add_behavior(b, "Behaviors")
self.assertTrue(o.collections.behavior_collections.has_collection("Behaviors"))
o.add_named_candidate_indicator_collection("Indicators")
ci = CandidateIndicator()
o.add_candidate_indicator(ci, "Indicators")
self.assertTrue(o.collections.candidate_indicator_collections.has_collection("Indicators"))
if __name__ == "__main__":
unittest.main()
|
the-stack_106_26703 | from typing import List, Tuple
import numpy as np
from collections import defaultdict
from gnes.indexer.base import BaseChunkIndexer as BCI
class KeywordIndexer(BCI):
def __init__(self, *args, **kwargs):
"""
Initialize an indexer that implements the AhoCorasick Algorithm
"""
super().__init__(*args, **kwargs)
import ahocorasick
self._automaton = ahocorasick.Automaton()
self.size = 0
def add(self, keys: List[Tuple[int, int]], vectors: np.ndarray, _, *args, **kwargs):
if vectors.dtype != np.uint8:
raise ValueError('vectors should be ndarray of uint8')
for key, vector in zip(keys, vectors):
self._automaton.add_word(self.decode_textbytes(vector), key)
self.size += 1
self.logger.error(list(self._automaton.keys()))
def query(self, keys: np.ndarray, top_k: int, *args, **kwargs) -> List[List[Tuple]]:
if keys.dtype != np.uint8:
raise ValueError('vectors should be ndarray of uint8')
elif not self.size > 0:
print('Warning: empty index queried')
return []
self._automaton.make_automaton()
ret = []
for key in keys:
ret_i = defaultdict(int)
for _, (doc_id, offset) in self._automaton.iter(self.decode_textbytes(key)):
ret_i[(doc_id, offset)] += 1
# _doc_id, _offset, _weight, _relevance
results = [(*k, 1.0, v) for k, v in ret_i.items()]
# topk by number of keyword matches
ret.append(sorted(results, reverse=True, key=lambda x: x[-1])[:top_k])
return ret
@staticmethod
def decode_textbytes(vector: np.ndarray):
return vector.tobytes().rstrip(b'\x00').decode()
|
the-stack_106_26705 | import os
import sqlite3
from functools import update_wrapper
from dagster import check
from .sql import run_migrations_offline as run_migrations_offline_
from .sql import run_migrations_online as run_migrations_online_
def run_migrations_offline(*args, **kwargs):
try:
run_migrations_offline_(*args, **kwargs)
except sqlite3.DatabaseError as exc:
# This is to deal with concurrent execution -- if this table already exists thanks to a
# race with another process, we are fine and can continue.
if not "table alembic_version already exists" in str(exc):
raise
def run_migrations_online(*args, **kwargs):
try:
run_migrations_online_(*args, **kwargs)
except (sqlite3.DatabaseError, sqlite3.OperationalError) as exc:
# This is to deal with concurrent execution -- if this table already exists thanks to a
# race with another process, we are fine and can continue.
if not "table alembic_version already exists" in str(exc):
raise
update_wrapper(run_migrations_offline, run_migrations_offline_)
update_wrapper(run_migrations_online, run_migrations_online_)
def create_db_conn_string(base_dir, db_name):
check.str_param(base_dir, "base_dir")
check.str_param(db_name, "db_name")
path_components = os.path.abspath(base_dir).split(os.sep)
db_file = "{}.db".format(db_name)
return "sqlite:///{}".format("/".join(path_components + [db_file]))
|
the-stack_106_26707 | # -*- coding: utf-8 -*-
"""
Cloudformation Template Generation.
"""
import json
from troposphere_mate import (
Template, Parameter, Ref, helper_fn_sub,
iam, awslambda, canned,
)
from ..devops.config_init import config
template = Template()
param_env_name = Parameter(
"EnvironmentName",
Type="String",
Default=config.ECS_EXAMPLE_ENVIRONMENT_NAME.get_value()
)
template.add_parameter(param_env_name)
iam_role_lambda_exec = iam.Role(
"IamForLambda",
RoleName=helper_fn_sub("{}-lambda-exec-role", param_env_name),
AssumeRolePolicyDocument=canned.iam.create_assume_role_policy_document([
canned.iam.AWSServiceName.aws_Lambda,
]),
ManagedPolicyArns=[
canned.iam.AWSManagedPolicyArn.awsLambdaBasicExecutionRole,
]
)
template.create_resource_type_label()
# give all aws resource common tags
common_tags = {
"EnvironmentName": Ref(param_env_name),
}
template.update_tags(common_tags)
|
the-stack_106_26708 | """
High level interface to PyTables for reading and writing pandas data structures
to disk
"""
import copy
from datetime import date, tzinfo
import itertools
import os
import re
from typing import (
TYPE_CHECKING,
Any,
Dict,
Hashable,
List,
Optional,
Tuple,
Type,
Union,
)
import warnings
import numpy as np
from pandas._config import config, get_option
from pandas._libs import lib, writers as libwriters
from pandas._libs.tslibs import timezones
from pandas.compat._optional import import_optional_dependency
from pandas.errors import PerformanceWarning
from pandas.util._decorators import cache_readonly
from pandas.core.dtypes.common import (
ensure_object,
is_categorical_dtype,
is_complex_dtype,
is_datetime64_dtype,
is_datetime64tz_dtype,
is_extension_array_dtype,
is_list_like,
is_string_dtype,
is_timedelta64_dtype,
)
from pandas.core.dtypes.generic import ABCExtensionArray
from pandas.core.dtypes.missing import array_equivalent
from pandas import (
DataFrame,
DatetimeIndex,
Index,
Int64Index,
MultiIndex,
PeriodIndex,
Series,
TimedeltaIndex,
concat,
isna,
)
from pandas._typing import ArrayLike, FrameOrSeries
from pandas.core.arrays.categorical import Categorical
import pandas.core.common as com
from pandas.core.computation.pytables import PyTablesExpr, maybe_expression
from pandas.core.index import ensure_index
from pandas.io.common import _stringify_path
from pandas.io.formats.printing import adjoin, pprint_thing
if TYPE_CHECKING:
from tables import File, Node, Col # noqa:F401
# versioning attribute
_version = "0.15.2"
# encoding
_default_encoding = "UTF-8"
def _ensure_decoded(s):
""" if we have bytes, decode them to unicode """
if isinstance(s, np.bytes_):
s = s.decode("UTF-8")
return s
def _ensure_encoding(encoding):
# set the encoding if we need
if encoding is None:
encoding = _default_encoding
return encoding
def _ensure_str(name):
"""
Ensure that an index / column name is a str (python 3); otherwise they
may be np.string dtype. Non-string dtypes are passed through unchanged.
https://github.com/pandas-dev/pandas/issues/13492
"""
if isinstance(name, str):
name = str(name)
return name
Term = PyTablesExpr
def _ensure_term(where, scope_level: int):
"""
ensure that the where is a Term or a list of Term
this makes sure that we are capturing the scope of variables
that are passed
create the terms here with a frame_level=2 (we are 2 levels down)
"""
# only consider list/tuple here as an ndarray is automatically a coordinate
# list
level = scope_level + 1
if isinstance(where, (list, tuple)):
wlist = []
for w in filter(lambda x: x is not None, where):
if not maybe_expression(w):
wlist.append(w)
else:
wlist.append(Term(w, scope_level=level))
where = wlist
elif maybe_expression(where):
where = Term(where, scope_level=level)
return where if where is None or len(where) else None
class PossibleDataLossError(Exception):
pass
class ClosedFileError(Exception):
pass
class IncompatibilityWarning(Warning):
pass
incompatibility_doc = """
where criteria is being ignored as this version [%s] is too old (or
not-defined), read the file in and write it out to a new file to upgrade (with
the copy_to method)
"""
class AttributeConflictWarning(Warning):
pass
attribute_conflict_doc = """
the [%s] attribute of the existing index is [%s] which conflicts with the new
[%s], resetting the attribute to None
"""
class DuplicateWarning(Warning):
pass
duplicate_doc = """
duplicate entries in table, taking most recently appended
"""
performance_doc = """
your performance may suffer as PyTables will pickle object types that it cannot
map directly to c-types [inferred_type->%s,key->%s] [items->%s]
"""
# formats
_FORMAT_MAP = {"f": "fixed", "fixed": "fixed", "t": "table", "table": "table"}
format_deprecate_doc = """
the table keyword has been deprecated
use the format='fixed(f)|table(t)' keyword instead
fixed(f) : specifies the Fixed format
and is the default for put operations
table(t) : specifies the Table format
and is the default for append operations
"""
# storer class map
_STORER_MAP = {
"series": "SeriesFixed",
"frame": "FrameFixed",
}
# table class map
_TABLE_MAP = {
"generic_table": "GenericTable",
"appendable_series": "AppendableSeriesTable",
"appendable_multiseries": "AppendableMultiSeriesTable",
"appendable_frame": "AppendableFrameTable",
"appendable_multiframe": "AppendableMultiFrameTable",
"worm": "WORMTable",
}
# axes map
_AXES_MAP = {DataFrame: [0]}
# register our configuration options
dropna_doc = """
: boolean
drop ALL nan rows when appending to a table
"""
format_doc = """
: format
default format writing format, if None, then
put will default to 'fixed' and append will default to 'table'
"""
with config.config_prefix("io.hdf"):
config.register_option("dropna_table", False, dropna_doc, validator=config.is_bool)
config.register_option(
"default_format",
None,
format_doc,
validator=config.is_one_of_factory(["fixed", "table", None]),
)
# oh the troubles to reduce import time
_table_mod = None
_table_file_open_policy_is_strict = False
def _tables():
global _table_mod
global _table_file_open_policy_is_strict
if _table_mod is None:
import tables
_table_mod = tables
# set the file open policy
# return the file open policy; this changes as of pytables 3.1
# depending on the HDF5 version
try:
_table_file_open_policy_is_strict = (
tables.file._FILE_OPEN_POLICY == "strict"
)
except AttributeError:
pass
return _table_mod
# interface to/from ###
def to_hdf(
path_or_buf,
key: str,
value: FrameOrSeries,
mode: str = "a",
complevel: Optional[int] = None,
complib: Optional[str] = None,
append: bool = False,
format: Optional[str] = None,
index: bool = True,
min_itemsize: Optional[Union[int, Dict[str, int]]] = None,
nan_rep=None,
dropna: Optional[bool] = None,
data_columns: Optional[List[str]] = None,
errors: str = "strict",
encoding: str = "UTF-8",
):
""" store this object, close it if we opened it """
if append:
f = lambda store: store.append(
key,
value,
format=format,
index=index,
min_itemsize=min_itemsize,
nan_rep=nan_rep,
dropna=dropna,
data_columns=data_columns,
errors=errors,
encoding=encoding,
)
else:
# NB: dropna is not passed to `put`
f = lambda store: store.put(
key,
value,
format=format,
index=index,
min_itemsize=min_itemsize,
nan_rep=nan_rep,
data_columns=data_columns,
errors=errors,
encoding=encoding,
)
path_or_buf = _stringify_path(path_or_buf)
if isinstance(path_or_buf, str):
with HDFStore(
path_or_buf, mode=mode, complevel=complevel, complib=complib
) as store:
f(store)
else:
f(path_or_buf)
def read_hdf(
path_or_buf,
key=None,
mode: str = "r",
errors: str = "strict",
where=None,
start: Optional[int] = None,
stop: Optional[int] = None,
columns=None,
iterator=False,
chunksize: Optional[int] = None,
**kwargs,
):
"""
Read from the store, close it if we opened it.
Retrieve pandas object stored in file, optionally based on where
criteria
Parameters
----------
path_or_buf : str, path object, pandas.HDFStore or file-like object
Any valid string path is acceptable. The string could be a URL. Valid
URL schemes include http, ftp, s3, and file. For file URLs, a host is
expected. A local file could be: ``file://localhost/path/to/table.h5``.
If you want to pass in a path object, pandas accepts any
``os.PathLike``.
Alternatively, pandas accepts an open :class:`pandas.HDFStore` object.
By file-like object, we refer to objects with a ``read()`` method,
such as a file handler (e.g. via builtin ``open`` function)
or ``StringIO``.
.. versionadded:: 0.21.0 support for __fspath__ protocol.
key : object, optional
The group identifier in the store. Can be omitted if the HDF file
contains a single pandas object.
mode : {'r', 'r+', 'a'}, default 'r'
Mode to use when opening the file. Ignored if path_or_buf is a
:class:`pandas.HDFStore`. Default is 'r'.
where : list, optional
A list of Term (or convertible) objects.
start : int, optional
Row number to start selection.
stop : int, optional
Row number to stop selection.
columns : list, optional
A list of columns names to return.
iterator : bool, optional
Return an iterator object.
chunksize : int, optional
Number of rows to include in an iteration when using an iterator.
errors : str, default 'strict'
Specifies how encoding and decoding errors are to be handled.
See the errors argument for :func:`open` for a full list
of options.
**kwargs
Additional keyword arguments passed to HDFStore.
Returns
-------
item : object
The selected object. Return type depends on the object stored.
See Also
--------
DataFrame.to_hdf : Write a HDF file from a DataFrame.
HDFStore : Low-level access to HDF files.
Examples
--------
>>> df = pd.DataFrame([[1, 1.0, 'a']], columns=['x', 'y', 'z'])
>>> df.to_hdf('./store.h5', 'data')
>>> reread = pd.read_hdf('./store.h5')
"""
if mode not in ["r", "r+", "a"]:
raise ValueError(
f"mode {mode} is not allowed while performing a read. "
f"Allowed modes are r, r+ and a."
)
# grab the scope
if where is not None:
where = _ensure_term(where, scope_level=1)
if isinstance(path_or_buf, HDFStore):
if not path_or_buf.is_open:
raise IOError("The HDFStore must be open for reading.")
store = path_or_buf
auto_close = False
else:
path_or_buf = _stringify_path(path_or_buf)
if not isinstance(path_or_buf, str):
raise NotImplementedError(
"Support for generic buffers has not been implemented."
)
try:
exists = os.path.exists(path_or_buf)
# if filepath is too long
except (TypeError, ValueError):
exists = False
if not exists:
raise FileNotFoundError(f"File {path_or_buf} does not exist")
store = HDFStore(path_or_buf, mode=mode, errors=errors, **kwargs)
# can't auto open/close if we are using an iterator
# so delegate to the iterator
auto_close = True
try:
if key is None:
groups = store.groups()
if len(groups) == 0:
raise ValueError("No dataset in HDF5 file.")
candidate_only_group = groups[0]
# For the HDF file to have only one dataset, all other groups
# should then be metadata groups for that candidate group. (This
# assumes that the groups() method enumerates parent groups
# before their children.)
for group_to_check in groups[1:]:
if not _is_metadata_of(group_to_check, candidate_only_group):
raise ValueError(
"key must be provided when HDF5 file "
"contains multiple datasets."
)
key = candidate_only_group._v_pathname
return store.select(
key,
where=where,
start=start,
stop=stop,
columns=columns,
iterator=iterator,
chunksize=chunksize,
auto_close=auto_close,
)
except (ValueError, TypeError, KeyError):
if not isinstance(path_or_buf, HDFStore):
# if there is an error, close the store if we opened it.
try:
store.close()
except AttributeError:
pass
raise
def _is_metadata_of(group: "Node", parent_group: "Node") -> bool:
"""Check if a given group is a metadata group for a given parent_group."""
if group._v_depth <= parent_group._v_depth:
return False
current = group
while current._v_depth > 1:
parent = current._v_parent
if parent == parent_group and current._v_name == "meta":
return True
current = current._v_parent
return False
class HDFStore:
"""
Dict-like IO interface for storing pandas objects in PyTables.
Either Fixed or Table format.
Parameters
----------
path : string
File path to HDF5 file
mode : {'a', 'w', 'r', 'r+'}, default 'a'
``'r'``
Read-only; no data can be modified.
``'w'``
Write; a new file is created (an existing file with the same
name would be deleted).
``'a'``
Append; an existing file is opened for reading and writing,
and if the file does not exist it is created.
``'r+'``
It is similar to ``'a'``, but the file must already exist.
complevel : int, 0-9, default None
Specifies a compression level for data.
A value of 0 or None disables compression.
complib : {'zlib', 'lzo', 'bzip2', 'blosc'}, default 'zlib'
Specifies the compression library to be used.
As of v0.20.2 these additional compressors for Blosc are supported
(default if no compressor specified: 'blosc:blosclz'):
{'blosc:blosclz', 'blosc:lz4', 'blosc:lz4hc', 'blosc:snappy',
'blosc:zlib', 'blosc:zstd'}.
Specifying a compression library which is not available issues
a ValueError.
fletcher32 : bool, default False
If applying compression use the fletcher32 checksum
Examples
--------
>>> bar = pd.DataFrame(np.random.randn(10, 4))
>>> store = pd.HDFStore('test.h5')
>>> store['foo'] = bar # write to HDF5
>>> bar = store['foo'] # retrieve
>>> store.close()
"""
_handle: Optional["File"]
_mode: str
_complevel: int
_fletcher32: bool
def __init__(
self,
path,
mode: str = "a",
complevel: Optional[int] = None,
complib=None,
fletcher32: bool = False,
**kwargs,
):
if "format" in kwargs:
raise ValueError("format is not a defined argument for HDFStore")
tables = import_optional_dependency("tables")
if complib is not None and complib not in tables.filters.all_complibs:
raise ValueError(
f"complib only supports {tables.filters.all_complibs} compression."
)
if complib is None and complevel is not None:
complib = tables.filters.default_complib
self._path = _stringify_path(path)
if mode is None:
mode = "a"
self._mode = mode
self._handle = None
self._complevel = complevel if complevel else 0
self._complib = complib
self._fletcher32 = fletcher32
self._filters = None
self.open(mode=mode, **kwargs)
def __fspath__(self):
return self._path
@property
def root(self):
""" return the root node """
self._check_if_open()
return self._handle.root
@property
def filename(self):
return self._path
def __getitem__(self, key: str):
return self.get(key)
def __setitem__(self, key: str, value):
self.put(key, value)
def __delitem__(self, key: str):
return self.remove(key)
def __getattr__(self, name: str):
""" allow attribute access to get stores """
try:
return self.get(name)
except (KeyError, ClosedFileError):
pass
raise AttributeError(
f"'{type(self).__name__}' object has no attribute '{name}'"
)
def __contains__(self, key: str) -> bool:
""" check for existence of this key
can match the exact pathname or the pathnm w/o the leading '/'
"""
node = self.get_node(key)
if node is not None:
name = node._v_pathname
if name == key or name[1:] == key:
return True
return False
def __len__(self) -> int:
return len(self.groups())
def __repr__(self) -> str:
pstr = pprint_thing(self._path)
return f"{type(self)}\nFile path: {pstr}\n"
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
self.close()
def keys(self) -> List[str]:
"""
Return a list of keys corresponding to objects stored in HDFStore.
Returns
-------
list
List of ABSOLUTE path-names (e.g. have the leading '/').
"""
return [n._v_pathname for n in self.groups()]
def __iter__(self):
return iter(self.keys())
def items(self):
"""
iterate on key->group
"""
for g in self.groups():
yield g._v_pathname, g
iteritems = items
def open(self, mode: str = "a", **kwargs):
"""
Open the file in the specified mode
Parameters
----------
mode : {'a', 'w', 'r', 'r+'}, default 'a'
See HDFStore docstring or tables.open_file for info about modes
"""
tables = _tables()
if self._mode != mode:
# if we are changing a write mode to read, ok
if self._mode in ["a", "w"] and mode in ["r", "r+"]:
pass
elif mode in ["w"]:
# this would truncate, raise here
if self.is_open:
raise PossibleDataLossError(
f"Re-opening the file [{self._path}] with mode [{self._mode}] "
"will delete the current file!"
)
self._mode = mode
# close and reopen the handle
if self.is_open:
self.close()
if self._complevel and self._complevel > 0:
self._filters = _tables().Filters(
self._complevel, self._complib, fletcher32=self._fletcher32
)
try:
self._handle = tables.open_file(self._path, self._mode, **kwargs)
except IOError as err: # pragma: no cover
if "can not be written" in str(err):
print(f"Opening {self._path} in read-only mode")
self._handle = tables.open_file(self._path, "r", **kwargs)
else:
raise
except ValueError as err:
# trap PyTables >= 3.1 FILE_OPEN_POLICY exception
# to provide an updated message
if "FILE_OPEN_POLICY" in str(err):
hdf_version = tables.get_hdf5_version()
err = ValueError(
f"PyTables [{tables.__version__}] no longer supports "
"opening multiple files\n"
"even in read-only mode on this HDF5 version "
f"[{hdf_version}]. You can accept this\n"
"and not open the same file multiple times at once,\n"
"upgrade the HDF5 version, or downgrade to PyTables 3.0.0 "
"which allows\n"
"files to be opened multiple times at once\n"
)
raise err
except Exception as err:
# trying to read from a non-existent file causes an error which
# is not part of IOError, make it one
if self._mode == "r" and "Unable to open/create file" in str(err):
raise IOError(str(err))
raise
def close(self):
"""
Close the PyTables file handle
"""
if self._handle is not None:
self._handle.close()
self._handle = None
@property
def is_open(self) -> bool:
"""
return a boolean indicating whether the file is open
"""
if self._handle is None:
return False
return bool(self._handle.isopen)
def flush(self, fsync: bool = False):
"""
Force all buffered modifications to be written to disk.
Parameters
----------
fsync : bool (default False)
call ``os.fsync()`` on the file handle to force writing to disk.
Notes
-----
Without ``fsync=True``, flushing may not guarantee that the OS writes
to disk. With fsync, the operation will block until the OS claims the
file has been written; however, other caching layers may still
interfere.
"""
if self._handle is not None:
self._handle.flush()
if fsync:
try:
os.fsync(self._handle.fileno())
except OSError:
pass
def get(self, key: str):
"""
Retrieve pandas object stored in file.
Parameters
----------
key : str
Returns
-------
object
Same type as object stored in file.
"""
group = self.get_node(key)
if group is None:
raise KeyError(f"No object named {key} in the file")
return self._read_group(group)
def select(
self,
key: str,
where=None,
start=None,
stop=None,
columns=None,
iterator=False,
chunksize=None,
auto_close: bool = False,
):
"""
Retrieve pandas object stored in file, optionally based on where criteria.
Parameters
----------
key : str
Object being retrieved from file.
where : list, default None
List of Term (or convertible) objects, optional.
start : int, default None
Row number to start selection.
stop : int, default None
Row number to stop selection.
columns : list, default None
A list of columns that if not None, will limit the return columns.
iterator : bool, default False
Returns an iterator.
chunksize : int, default None
Number or rows to include in iteration, return an iterator.
auto_close : bool, default False
Should automatically close the store when finished.
Returns
-------
object
Retrieved object from file.
"""
group = self.get_node(key)
if group is None:
raise KeyError(f"No object named {key} in the file")
# create the storer and axes
where = _ensure_term(where, scope_level=1)
s = self._create_storer(group)
s.infer_axes()
# function to call on iteration
def func(_start, _stop, _where):
return s.read(start=_start, stop=_stop, where=_where, columns=columns)
# create the iterator
it = TableIterator(
self,
s,
func,
where=where,
nrows=s.nrows,
start=start,
stop=stop,
iterator=iterator,
chunksize=chunksize,
auto_close=auto_close,
)
return it.get_result()
def select_as_coordinates(
self,
key: str,
where=None,
start: Optional[int] = None,
stop: Optional[int] = None,
):
"""
return the selection as an Index
Parameters
----------
key : str
where : list of Term (or convertible) objects, optional
start : integer (defaults to None), row number to start selection
stop : integer (defaults to None), row number to stop selection
"""
where = _ensure_term(where, scope_level=1)
tbl = self.get_storer(key)
if not isinstance(tbl, Table):
raise TypeError("can only read_coordinates with a table")
return tbl.read_coordinates(where=where, start=start, stop=stop)
def select_column(
self,
key: str,
column: str,
start: Optional[int] = None,
stop: Optional[int] = None,
):
"""
return a single column from the table. This is generally only useful to
select an indexable
Parameters
----------
key : str
column : str
The column of interest.
start : int or None, default None
stop : int or None, default None
Raises
------
raises KeyError if the column is not found (or key is not a valid
store)
raises ValueError if the column can not be extracted individually (it
is part of a data block)
"""
tbl = self.get_storer(key)
if not isinstance(tbl, Table):
raise TypeError("can only read_column with a table")
return tbl.read_column(column=column, start=start, stop=stop)
def select_as_multiple(
self,
keys,
where=None,
selector=None,
columns=None,
start=None,
stop=None,
iterator=False,
chunksize=None,
auto_close: bool = False,
):
"""
Retrieve pandas objects from multiple tables.
Parameters
----------
keys : a list of the tables
selector : the table to apply the where criteria (defaults to keys[0]
if not supplied)
columns : the columns I want back
start : integer (defaults to None), row number to start selection
stop : integer (defaults to None), row number to stop selection
iterator : boolean, return an iterator, default False
chunksize : nrows to include in iteration, return an iterator
auto_close : bool, default False
Should automatically close the store when finished.
Raises
------
raises KeyError if keys or selector is not found or keys is empty
raises TypeError if keys is not a list or tuple
raises ValueError if the tables are not ALL THE SAME DIMENSIONS
"""
# default to single select
where = _ensure_term(where, scope_level=1)
if isinstance(keys, (list, tuple)) and len(keys) == 1:
keys = keys[0]
if isinstance(keys, str):
return self.select(
key=keys,
where=where,
columns=columns,
start=start,
stop=stop,
iterator=iterator,
chunksize=chunksize,
auto_close=auto_close,
)
if not isinstance(keys, (list, tuple)):
raise TypeError("keys must be a list/tuple")
if not len(keys):
raise ValueError("keys must have a non-zero length")
if selector is None:
selector = keys[0]
# collect the tables
tbls = [self.get_storer(k) for k in keys]
s = self.get_storer(selector)
# validate rows
nrows = None
for t, k in itertools.chain([(s, selector)], zip(tbls, keys)):
if t is None:
raise KeyError(f"Invalid table [{k}]")
if not t.is_table:
raise TypeError(
f"object [{t.pathname}] is not a table, and cannot be used in all "
"select as multiple"
)
if nrows is None:
nrows = t.nrows
elif t.nrows != nrows:
raise ValueError("all tables must have exactly the same nrows!")
# The isinstance checks here are redundant with the check above,
# but necessary for mypy; see GH#29757
_tbls = [x for x in tbls if isinstance(x, Table)]
# axis is the concentration axes
axis = list({t.non_index_axes[0][0] for t in _tbls})[0]
def func(_start, _stop, _where):
# retrieve the objs, _where is always passed as a set of
# coordinates here
objs = [
t.read(where=_where, columns=columns, start=_start, stop=_stop)
for t in tbls
]
# concat and return
return concat(objs, axis=axis, verify_integrity=False)._consolidate()
# create the iterator
it = TableIterator(
self,
s,
func,
where=where,
nrows=nrows,
start=start,
stop=stop,
iterator=iterator,
chunksize=chunksize,
auto_close=auto_close,
)
return it.get_result(coordinates=True)
def put(
self,
key: str,
value: FrameOrSeries,
format=None,
index=True,
append=False,
complib=None,
complevel: Optional[int] = None,
min_itemsize: Optional[Union[int, Dict[str, int]]] = None,
nan_rep=None,
data_columns: Optional[List[str]] = None,
encoding=None,
errors: str = "strict",
):
"""
Store object in HDFStore.
Parameters
----------
key : str
value : {Series, DataFrame}
format : 'fixed(f)|table(t)', default is 'fixed'
fixed(f) : Fixed format
Fast writing/reading. Not-appendable, nor searchable.
table(t) : Table format
Write as a PyTables Table structure which may perform
worse but allow more flexible operations like searching
/ selecting subsets of the data.
append : bool, default False
This will force Table format, append the input data to the
existing.
data_columns : list, default None
List of columns to create as data columns, or True to
use all columns. See `here
<http://pandas.pydata.org/pandas-docs/stable/user_guide/io.html#query-via-data-columns>`__.
encoding : str, default None
Provide an encoding for strings.
dropna : bool, default False, do not write an ALL nan row to
The store settable by the option 'io.hdf.dropna_table'.
"""
if format is None:
format = get_option("io.hdf.default_format") or "fixed"
format = self._validate_format(format)
self._write_to_group(
key,
value,
format=format,
index=index,
append=append,
complib=complib,
complevel=complevel,
min_itemsize=min_itemsize,
nan_rep=nan_rep,
data_columns=data_columns,
encoding=encoding,
errors=errors,
)
def remove(self, key: str, where=None, start=None, stop=None):
"""
Remove pandas object partially by specifying the where condition
Parameters
----------
key : string
Node to remove or delete rows from
where : list of Term (or convertible) objects, optional
start : integer (defaults to None), row number to start selection
stop : integer (defaults to None), row number to stop selection
Returns
-------
number of rows removed (or None if not a Table)
Raises
------
raises KeyError if key is not a valid store
"""
where = _ensure_term(where, scope_level=1)
try:
s = self.get_storer(key)
except KeyError:
# the key is not a valid store, re-raising KeyError
raise
except AssertionError:
# surface any assertion errors for e.g. debugging
raise
except Exception:
# In tests we get here with ClosedFileError, TypeError, and
# _table_mod.NoSuchNodeError. TODO: Catch only these?
if where is not None:
raise ValueError(
"trying to remove a node with a non-None where clause!"
)
# we are actually trying to remove a node (with children)
node = self.get_node(key)
if node is not None:
node._f_remove(recursive=True)
return None
# remove the node
if com.all_none(where, start, stop):
s.group._f_remove(recursive=True)
# delete from the table
else:
if not s.is_table:
raise ValueError(
"can only remove with where on objects written as tables"
)
return s.delete(where=where, start=start, stop=stop)
def append(
self,
key: str,
value: FrameOrSeries,
format=None,
axes=None,
index=True,
append=True,
complib=None,
complevel: Optional[int] = None,
columns=None,
min_itemsize: Optional[Union[int, Dict[str, int]]] = None,
nan_rep=None,
chunksize=None,
expectedrows=None,
dropna: Optional[bool] = None,
data_columns: Optional[List[str]] = None,
encoding=None,
errors: str = "strict",
):
"""
Append to Table in file. Node must already exist and be Table
format.
Parameters
----------
key : str
value : {Series, DataFrame}
format : 'table' is the default
table(t) : table format
Write as a PyTables Table structure which may perform
worse but allow more flexible operations like searching
/ selecting subsets of the data.
append : bool, default True
Append the input data to the existing.
data_columns : list of columns, or True, default None
List of columns to create as indexed data columns for on-disk
queries, or True to use all columns. By default only the axes
of the object are indexed. See `here
<http://pandas.pydata.org/pandas-docs/stable/user_guide/io.html#query-via-data-columns>`__.
min_itemsize : dict of columns that specify minimum string sizes
nan_rep : string to use as string nan representation
chunksize : size to chunk the writing
expectedrows : expected TOTAL row size of this table
encoding : default None, provide an encoding for strings
dropna : bool, default False
Do not write an ALL nan row to the store settable
by the option 'io.hdf.dropna_table'.
Notes
-----
Does *not* check if data being appended overlaps with existing
data in the table, so be careful
"""
if columns is not None:
raise TypeError(
"columns is not a supported keyword in append, try data_columns"
)
if dropna is None:
dropna = get_option("io.hdf.dropna_table")
if format is None:
format = get_option("io.hdf.default_format") or "table"
format = self._validate_format(format)
self._write_to_group(
key,
value,
format=format,
axes=axes,
index=index,
append=append,
complib=complib,
complevel=complevel,
min_itemsize=min_itemsize,
nan_rep=nan_rep,
chunksize=chunksize,
expectedrows=expectedrows,
dropna=dropna,
data_columns=data_columns,
encoding=encoding,
errors=errors,
)
def append_to_multiple(
self,
d: Dict,
value,
selector,
data_columns=None,
axes=None,
dropna=False,
**kwargs,
):
"""
Append to multiple tables
Parameters
----------
d : a dict of table_name to table_columns, None is acceptable as the
values of one node (this will get all the remaining columns)
value : a pandas object
selector : a string that designates the indexable table; all of its
columns will be designed as data_columns, unless data_columns is
passed, in which case these are used
data_columns : list of columns to create as data columns, or True to
use all columns
dropna : if evaluates to True, drop rows from all tables if any single
row in each table has all NaN. Default False.
Notes
-----
axes parameter is currently not accepted
"""
if axes is not None:
raise TypeError(
"axes is currently not accepted as a parameter to"
" append_to_multiple; you can create the "
"tables independently instead"
)
if not isinstance(d, dict):
raise ValueError(
"append_to_multiple must have a dictionary specified as the "
"way to split the value"
)
if selector not in d:
raise ValueError(
"append_to_multiple requires a selector that is in passed dict"
)
# figure out the splitting axis (the non_index_axis)
axis = list(set(range(value.ndim)) - set(_AXES_MAP[type(value)]))[0]
# figure out how to split the value
remain_key = None
remain_values: List = []
for k, v in d.items():
if v is None:
if remain_key is not None:
raise ValueError(
"append_to_multiple can only have one value in d that "
"is None"
)
remain_key = k
else:
remain_values.extend(v)
if remain_key is not None:
ordered = value.axes[axis]
ordd = ordered.difference(Index(remain_values))
ordd = sorted(ordered.get_indexer(ordd))
d[remain_key] = ordered.take(ordd)
# data_columns
if data_columns is None:
data_columns = d[selector]
# ensure rows are synchronized across the tables
if dropna:
idxs = (value[cols].dropna(how="all").index for cols in d.values())
valid_index = next(idxs)
for index in idxs:
valid_index = valid_index.intersection(index)
value = value.loc[valid_index]
# append
for k, v in d.items():
dc = data_columns if k == selector else None
# compute the val
val = value.reindex(v, axis=axis)
self.append(k, val, data_columns=dc, **kwargs)
def create_table_index(
self,
key: str,
columns=None,
optlevel: Optional[int] = None,
kind: Optional[str] = None,
):
"""
Create a pytables index on the table.
Parameters
----------
key : str
columns : None, bool, or listlike[str]
Indicate which columns to create an index on.
* False : Do not create any indexes.
* True : Create indexes on all columns.
* None : Create indexes on all columns.
* listlike : Create indexes on the given columns.
optlevel : int or None, default None
Optimization level, if None, pytables defaults to 6.
kind : str or None, default None
Kind of index, if None, pytables defaults to "medium"
Raises
------
TypeError: raises if the node is not a table
"""
# version requirements
_tables()
s = self.get_storer(key)
if s is None:
return
if not isinstance(s, Table):
raise TypeError("cannot create table index on a Fixed format store")
s.create_index(columns=columns, optlevel=optlevel, kind=kind)
def groups(self):
"""
Return a list of all the top-level nodes.
Each node returned is not a pandas storage object.
Returns
-------
list
List of objects.
"""
_tables()
self._check_if_open()
return [
g
for g in self._handle.walk_groups()
if (
not isinstance(g, _table_mod.link.Link)
and (
getattr(g._v_attrs, "pandas_type", None)
or getattr(g, "table", None)
or (isinstance(g, _table_mod.table.Table) and g._v_name != "table")
)
)
]
def walk(self, where="/"):
"""
Walk the pytables group hierarchy for pandas objects.
This generator will yield the group path, subgroups and pandas object
names for each group.
Any non-pandas PyTables objects that are not a group will be ignored.
The `where` group itself is listed first (preorder), then each of its
child groups (following an alphanumerical order) is also traversed,
following the same procedure.
.. versionadded:: 0.24.0
Parameters
----------
where : str, default "/"
Group where to start walking.
Yields
------
path : str
Full path to a group (without trailing '/').
groups : list
Names (strings) of the groups contained in `path`.
leaves : list
Names (strings) of the pandas objects contained in `path`.
"""
_tables()
self._check_if_open()
for g in self._handle.walk_groups(where):
if getattr(g._v_attrs, "pandas_type", None) is not None:
continue
groups = []
leaves = []
for child in g._v_children.values():
pandas_type = getattr(child._v_attrs, "pandas_type", None)
if pandas_type is None:
if isinstance(child, _table_mod.group.Group):
groups.append(child._v_name)
else:
leaves.append(child._v_name)
yield (g._v_pathname.rstrip("/"), groups, leaves)
def get_node(self, key: str) -> Optional["Node"]:
""" return the node with the key or None if it does not exist """
self._check_if_open()
if not key.startswith("/"):
key = "/" + key
assert self._handle is not None
assert _table_mod is not None # for mypy
try:
node = self._handle.get_node(self.root, key)
except _table_mod.exceptions.NoSuchNodeError:
return None
assert isinstance(node, _table_mod.Node), type(node)
return node
def get_storer(self, key: str) -> Union["GenericFixed", "Table"]:
""" return the storer object for a key, raise if not in the file """
group = self.get_node(key)
if group is None:
raise KeyError(f"No object named {key} in the file")
s = self._create_storer(group)
s.infer_axes()
return s
def copy(
self,
file,
mode="w",
propindexes: bool = True,
keys=None,
complib=None,
complevel: Optional[int] = None,
fletcher32: bool = False,
overwrite=True,
):
"""
Copy the existing store to a new file, updating in place.
Parameters
----------
propindexes: bool, default True
Restore indexes in copied file.
keys : list of keys to include in the copy (defaults to all)
overwrite : overwrite (remove and replace) existing nodes in the
new store (default is True)
mode, complib, complevel, fletcher32 same as in HDFStore.__init__
Returns
-------
open file handle of the new store
"""
new_store = HDFStore(
file, mode=mode, complib=complib, complevel=complevel, fletcher32=fletcher32
)
if keys is None:
keys = list(self.keys())
if not isinstance(keys, (tuple, list)):
keys = [keys]
for k in keys:
s = self.get_storer(k)
if s is not None:
if k in new_store:
if overwrite:
new_store.remove(k)
data = self.select(k)
if isinstance(s, Table):
index: Union[bool, list] = False
if propindexes:
index = [a.name for a in s.axes if a.is_indexed]
new_store.append(
k,
data,
index=index,
data_columns=getattr(s, "data_columns", None),
encoding=s.encoding,
)
else:
new_store.put(k, data, encoding=s.encoding)
return new_store
def info(self) -> str:
"""
Print detailed information on the store.
.. versionadded:: 0.21.0
Returns
-------
str
"""
path = pprint_thing(self._path)
output = f"{type(self)}\nFile path: {path}\n"
if self.is_open:
lkeys = sorted(self.keys())
if len(lkeys):
keys = []
values = []
for k in lkeys:
try:
s = self.get_storer(k)
if s is not None:
keys.append(pprint_thing(s.pathname or k))
values.append(pprint_thing(s or "invalid_HDFStore node"))
except AssertionError:
# surface any assertion errors for e.g. debugging
raise
except Exception as detail:
keys.append(k)
dstr = pprint_thing(detail)
values.append(f"[invalid_HDFStore node: {dstr}]")
output += adjoin(12, keys, values)
else:
output += "Empty"
else:
output += "File is CLOSED"
return output
# ------------------------------------------------------------------------
# private methods
def _check_if_open(self):
if not self.is_open:
raise ClosedFileError(f"{self._path} file is not open!")
def _validate_format(self, format: str) -> str:
""" validate / deprecate formats """
# validate
try:
format = _FORMAT_MAP[format.lower()]
except KeyError:
raise TypeError(f"invalid HDFStore format specified [{format}]")
return format
def _create_storer(
self,
group,
format=None,
value=None,
encoding: str = "UTF-8",
errors: str = "strict",
) -> Union["GenericFixed", "Table"]:
""" return a suitable class to operate """
def error(t):
# return instead of raising so mypy can tell where we are raising
return TypeError(
f"cannot properly create the storer for: [{t}] [group->"
f"{group},value->{type(value)},format->{format}"
)
pt = _ensure_decoded(getattr(group._v_attrs, "pandas_type", None))
tt = _ensure_decoded(getattr(group._v_attrs, "table_type", None))
# infer the pt from the passed value
if pt is None:
if value is None:
_tables()
assert _table_mod is not None # for mypy
if getattr(group, "table", None) or isinstance(
group, _table_mod.table.Table
):
pt = "frame_table"
tt = "generic_table"
else:
raise TypeError(
"cannot create a storer if the object is not existing "
"nor a value are passed"
)
else:
_TYPE_MAP = {Series: "series", DataFrame: "frame"}
try:
pt = _TYPE_MAP[type(value)]
except KeyError:
raise error("_TYPE_MAP")
# we are actually a table
if format == "table":
pt += "_table"
# a storer node
if "table" not in pt:
try:
return globals()[_STORER_MAP[pt]](
self, group, encoding=encoding, errors=errors
)
except KeyError:
raise error("_STORER_MAP")
# existing node (and must be a table)
if tt is None:
# if we are a writer, determine the tt
if value is not None:
if pt == "series_table":
index = getattr(value, "index", None)
if index is not None:
if index.nlevels == 1:
tt = "appendable_series"
elif index.nlevels > 1:
tt = "appendable_multiseries"
elif pt == "frame_table":
index = getattr(value, "index", None)
if index is not None:
if index.nlevels == 1:
tt = "appendable_frame"
elif index.nlevels > 1:
tt = "appendable_multiframe"
elif pt == "wide_table":
tt = "appendable_panel"
elif pt == "ndim_table":
tt = "appendable_ndim"
else:
# distinguish between a frame/table
tt = "legacy_panel"
try:
fields = group.table._v_attrs.fields
if len(fields) == 1 and fields[0] == "value":
tt = "legacy_frame"
except IndexError:
pass
try:
return globals()[_TABLE_MAP[tt]](
self, group, encoding=encoding, errors=errors
)
except KeyError:
raise error("_TABLE_MAP")
def _write_to_group(
self,
key: str,
value: FrameOrSeries,
format,
axes=None,
index=True,
append=False,
complib=None,
complevel: Optional[int] = None,
fletcher32=None,
min_itemsize: Optional[Union[int, Dict[str, int]]] = None,
chunksize=None,
expectedrows=None,
dropna=False,
nan_rep=None,
data_columns=None,
encoding=None,
errors: str = "strict",
):
group = self.get_node(key)
# we make this assertion for mypy; the get_node call will already
# have raised if this is incorrect
assert self._handle is not None
# remove the node if we are not appending
if group is not None and not append:
self._handle.remove_node(group, recursive=True)
group = None
# we don't want to store a table node at all if our object is 0-len
# as there are not dtypes
if getattr(value, "empty", None) and (format == "table" or append):
return
if group is None:
paths = key.split("/")
# recursively create the groups
path = "/"
for p in paths:
if not len(p):
continue
new_path = path
if not path.endswith("/"):
new_path += "/"
new_path += p
group = self.get_node(new_path)
if group is None:
group = self._handle.create_group(path, p)
path = new_path
s = self._create_storer(group, format, value, encoding=encoding, errors=errors)
if append:
# raise if we are trying to append to a Fixed format,
# or a table that exists (and we are putting)
if not s.is_table or (s.is_table and format == "fixed" and s.is_exists):
raise ValueError("Can only append to Tables")
if not s.is_exists:
s.set_object_info()
else:
s.set_object_info()
if not s.is_table and complib:
raise ValueError("Compression not supported on Fixed format stores")
# write the object
s.write(
obj=value,
axes=axes,
append=append,
complib=complib,
complevel=complevel,
fletcher32=fletcher32,
min_itemsize=min_itemsize,
chunksize=chunksize,
expectedrows=expectedrows,
dropna=dropna,
nan_rep=nan_rep,
data_columns=data_columns,
)
if isinstance(s, Table) and index:
s.create_index(columns=index)
def _read_group(self, group: "Node"):
s = self._create_storer(group)
s.infer_axes()
return s.read()
class TableIterator:
""" define the iteration interface on a table
Parameters
----------
store : the reference store
s : the referred storer
func : the function to execute the query
where : the where of the query
nrows : the rows to iterate on
start : the passed start value (default is None)
stop : the passed stop value (default is None)
iterator : bool, default False
Whether to use the default iterator.
chunksize : the passed chunking value (default is 100000)
auto_close : boolean, automatically close the store at the end of
iteration, default is False
"""
chunksize: Optional[int]
store: HDFStore
s: Union["GenericFixed", "Table"]
def __init__(
self,
store: HDFStore,
s: Union["GenericFixed", "Table"],
func,
where,
nrows,
start=None,
stop=None,
iterator: bool = False,
chunksize: Optional[int] = None,
auto_close: bool = False,
):
self.store = store
self.s = s
self.func = func
self.where = where
# set start/stop if they are not set if we are a table
if self.s.is_table:
if nrows is None:
nrows = 0
if start is None:
start = 0
if stop is None:
stop = nrows
stop = min(nrows, stop)
self.nrows = nrows
self.start = start
self.stop = stop
self.coordinates = None
if iterator or chunksize is not None:
if chunksize is None:
chunksize = 100000
self.chunksize = int(chunksize)
else:
self.chunksize = None
self.auto_close = auto_close
def __iter__(self):
# iterate
current = self.start
while current < self.stop:
stop = min(current + self.chunksize, self.stop)
value = self.func(None, None, self.coordinates[current:stop])
current = stop
if value is None or not len(value):
continue
yield value
self.close()
def close(self):
if self.auto_close:
self.store.close()
def get_result(self, coordinates: bool = False):
# return the actual iterator
if self.chunksize is not None:
if not isinstance(self.s, Table):
raise TypeError("can only use an iterator or chunksize on a table")
self.coordinates = self.s.read_coordinates(where=self.where)
return self
# if specified read via coordinates (necessary for multiple selections
if coordinates:
if not isinstance(self.s, Table):
raise TypeError("can only read_coordinates on a table")
where = self.s.read_coordinates(
where=self.where, start=self.start, stop=self.stop
)
else:
where = self.where
# directly return the result
results = self.func(self.start, self.stop, where)
self.close()
return results
class IndexCol:
""" an index column description class
Parameters
----------
axis : axis which I reference
values : the ndarray like converted values
kind : a string description of this type
typ : the pytables type
pos : the position in the pytables
"""
is_an_indexable = True
is_data_indexable = True
_info_fields = ["freq", "tz", "index_name"]
name: str
cname: str
def __init__(
self,
name: str,
values=None,
kind=None,
typ=None,
cname: Optional[str] = None,
axis=None,
pos=None,
freq=None,
tz=None,
index_name=None,
):
if not isinstance(name, str):
raise ValueError("`name` must be a str.")
self.values = values
self.kind = kind
self.typ = typ
self.name = name
self.cname = cname or name
self.axis = axis
self.pos = pos
self.freq = freq
self.tz = tz
self.index_name = index_name
self.table = None
self.meta = None
self.metadata = None
if pos is not None:
self.set_pos(pos)
# These are ensured as long as the passed arguments match the
# constructor annotations.
assert isinstance(self.name, str)
assert isinstance(self.cname, str)
@property
def itemsize(self) -> int:
# Assumes self.typ has already been initialized
return self.typ.itemsize
@property
def kind_attr(self) -> str:
return f"{self.name}_kind"
def set_pos(self, pos: int):
""" set the position of this column in the Table """
self.pos = pos
if pos is not None and self.typ is not None:
self.typ._v_pos = pos
def __repr__(self) -> str:
temp = tuple(
map(pprint_thing, (self.name, self.cname, self.axis, self.pos, self.kind))
)
return ",".join(
(
f"{key}->{value}"
for key, value in zip(["name", "cname", "axis", "pos", "kind"], temp)
)
)
def __eq__(self, other: Any) -> bool:
""" compare 2 col items """
return all(
getattr(self, a, None) == getattr(other, a, None)
for a in ["name", "cname", "axis", "pos"]
)
def __ne__(self, other) -> bool:
return not self.__eq__(other)
@property
def is_indexed(self) -> bool:
""" return whether I am an indexed column """
if not hasattr(self.table, "cols"):
# e.g. if infer hasn't been called yet, self.table will be None.
return False
# GH#29692 mypy doesn't recognize self.table as having a "cols" attribute
# 'error: "None" has no attribute "cols"'
return getattr(self.table.cols, self.cname).is_indexed # type: ignore
def copy(self):
new_self = copy.copy(self)
return new_self
def infer(self, handler: "Table"):
"""infer this column from the table: create and return a new object"""
table = handler.table
new_self = self.copy()
new_self.table = table
new_self.get_attr()
new_self.read_metadata(handler)
return new_self
def convert(
self, values: np.ndarray, nan_rep, encoding, errors, start=None, stop=None
):
""" set the values from this selection: take = take ownership """
# values is a recarray
if values.dtype.fields is not None:
values = values[self.cname]
values = _maybe_convert(values, self.kind, encoding, errors)
kwargs = dict()
if self.freq is not None:
kwargs["freq"] = _ensure_decoded(self.freq)
if self.index_name is not None:
kwargs["name"] = _ensure_decoded(self.index_name)
# making an Index instance could throw a number of different errors
try:
self.values = Index(values, **kwargs)
except ValueError:
# if the output freq is different that what we recorded,
# it should be None (see also 'doc example part 2')
if "freq" in kwargs:
kwargs["freq"] = None
self.values = Index(values, **kwargs)
self.values = _set_tz(self.values, self.tz)
def take_data(self):
""" return the values & release the memory """
self.values, values = None, self.values
return values
@property
def attrs(self):
return self.table._v_attrs
@property
def description(self):
return self.table.description
@property
def col(self):
""" return my current col description """
return getattr(self.description, self.cname, None)
@property
def cvalues(self):
""" return my cython values """
return self.values
def __iter__(self):
return iter(self.values)
def maybe_set_size(self, min_itemsize=None):
""" maybe set a string col itemsize:
min_itemsize can be an integer or a dict with this columns name
with an integer size """
if _ensure_decoded(self.kind) == "string":
if isinstance(min_itemsize, dict):
min_itemsize = min_itemsize.get(self.name)
if min_itemsize is not None and self.typ.itemsize < min_itemsize:
self.typ = _tables().StringCol(itemsize=min_itemsize, pos=self.pos)
def validate(self, handler, append):
self.validate_names()
def validate_names(self):
pass
def validate_and_set(self, handler: "AppendableTable", append: bool):
self.table = handler.table
self.validate_col()
self.validate_attr(append)
self.validate_metadata(handler)
self.write_metadata(handler)
self.set_attr()
def validate_col(self, itemsize=None):
""" validate this column: return the compared against itemsize """
# validate this column for string truncation (or reset to the max size)
if _ensure_decoded(self.kind) == "string":
c = self.col
if c is not None:
if itemsize is None:
itemsize = self.itemsize
if c.itemsize < itemsize:
raise ValueError(
f"Trying to store a string with len [{itemsize}] in "
f"[{self.cname}] column but\nthis column has a limit of "
f"[{c.itemsize}]!\nConsider using min_itemsize to "
"preset the sizes on these columns"
)
return c.itemsize
return None
def validate_attr(self, append: bool):
# check for backwards incompatibility
if append:
existing_kind = getattr(self.attrs, self.kind_attr, None)
if existing_kind is not None and existing_kind != self.kind:
raise TypeError(
f"incompatible kind in col [{existing_kind} - {self.kind}]"
)
def update_info(self, info):
""" set/update the info for this indexable with the key/value
if there is a conflict raise/warn as needed """
for key in self._info_fields:
value = getattr(self, key, None)
idx = _get_info(info, self.name)
existing_value = idx.get(key)
if key in idx and value is not None and existing_value != value:
# frequency/name just warn
if key in ["freq", "index_name"]:
ws = attribute_conflict_doc % (key, existing_value, value)
warnings.warn(ws, AttributeConflictWarning, stacklevel=6)
# reset
idx[key] = None
setattr(self, key, None)
else:
raise ValueError(
f"invalid info for [{self.name}] for [{key}], "
f"existing_value [{existing_value}] conflicts with "
f"new value [{value}]"
)
else:
if value is not None or existing_value is not None:
idx[key] = value
def set_info(self, info):
""" set my state from the passed info """
idx = info.get(self.name)
if idx is not None:
self.__dict__.update(idx)
def get_attr(self):
""" set the kind for this column """
self.kind = getattr(self.attrs, self.kind_attr, None)
def set_attr(self):
""" set the kind for this column """
setattr(self.attrs, self.kind_attr, self.kind)
def read_metadata(self, handler):
""" retrieve the metadata for this columns """
self.metadata = handler.read_metadata(self.cname)
def validate_metadata(self, handler: "AppendableTable"):
""" validate that kind=category does not change the categories """
if self.meta == "category":
new_metadata = self.metadata
cur_metadata = handler.read_metadata(self.cname)
if (
new_metadata is not None
and cur_metadata is not None
and not array_equivalent(new_metadata, cur_metadata)
):
raise ValueError(
"cannot append a categorical with "
"different categories to the existing"
)
def write_metadata(self, handler: "AppendableTable"):
""" set the meta data """
if self.metadata is not None:
handler.write_metadata(self.cname, self.metadata)
class GenericIndexCol(IndexCol):
""" an index which is not represented in the data of the table """
@property
def is_indexed(self) -> bool:
return False
def convert(
self,
values,
nan_rep,
encoding,
errors,
start: Optional[int] = None,
stop: Optional[int] = None,
):
""" set the values from this selection: take = take ownership
Parameters
----------
values : np.ndarray
nan_rep : str
encoding : str
errors : str
start : int, optional
Table row number: the start of the sub-selection.
stop : int, optional
Table row number: the end of the sub-selection. Values larger than
the underlying table's row count are normalized to that.
"""
assert self.table is not None # for mypy
_start = start if start is not None else 0
_stop = min(stop, self.table.nrows) if stop is not None else self.table.nrows
self.values = Int64Index(np.arange(_stop - _start))
def get_attr(self):
pass
def set_attr(self):
pass
class DataCol(IndexCol):
""" a data holding column, by definition this is not indexable
Parameters
----------
data : the actual data
cname : the column name in the table to hold the data (typically
values)
meta : a string description of the metadata
metadata : the actual metadata
"""
is_an_indexable = False
is_data_indexable = False
_info_fields = ["tz", "ordered"]
@classmethod
def create_for_block(
cls, i: int, name=None, version=None, pos: Optional[int] = None
):
""" return a new datacol with the block i """
cname = name or f"values_block_{i}"
if name is None:
name = cname
# prior to 0.10.1, we named values blocks like: values_block_0 an the
# name values_0
try:
if version[0] == 0 and version[1] <= 10 and version[2] == 0:
m = re.search(r"values_block_(\d+)", name)
if m:
grp = m.groups()[0]
name = f"values_{grp}"
except IndexError:
pass
return cls(name=name, cname=cname, pos=pos)
def __init__(
self, name: str, values=None, kind=None, typ=None, cname=None, pos=None,
):
super().__init__(
name=name, values=values, kind=kind, typ=typ, pos=pos, cname=cname
)
self.dtype = None
self.data = None
@property
def dtype_attr(self) -> str:
return f"{self.name}_dtype"
@property
def meta_attr(self) -> str:
return f"{self.name}_meta"
def __repr__(self) -> str:
temp = tuple(
map(
pprint_thing, (self.name, self.cname, self.dtype, self.kind, self.shape)
)
)
return ",".join(
(
f"{key}->{value}"
for key, value in zip(["name", "cname", "dtype", "kind", "shape"], temp)
)
)
def __eq__(self, other: Any) -> bool:
""" compare 2 col items """
return all(
getattr(self, a, None) == getattr(other, a, None)
for a in ["name", "cname", "dtype", "pos"]
)
def set_data(self, data: Union[np.ndarray, ABCExtensionArray]):
assert data is not None
if is_categorical_dtype(data.dtype):
data = data.codes
# For datetime64tz we need to drop the TZ in tests TODO: why?
dtype_name = data.dtype.name.split("[")[0]
if data.dtype.kind in ["m", "M"]:
data = np.asarray(data.view("i8"))
# TODO: we used to reshape for the dt64tz case, but no longer
# doing that doesnt seem to break anything. why?
self.data = data
if self.dtype is None:
self.dtype = dtype_name
self.set_kind()
def take_data(self):
""" return the data & release the memory """
self.data, data = None, self.data
return data
def set_kind(self):
# set my kind if we can
if self.dtype is not None:
dtype = _ensure_decoded(self.dtype)
if dtype.startswith("string") or dtype.startswith("bytes"):
self.kind = "string"
elif dtype.startswith("float"):
self.kind = "float"
elif dtype.startswith("complex"):
self.kind = "complex"
elif dtype.startswith("int") or dtype.startswith("uint"):
self.kind = "integer"
elif dtype.startswith("date"):
# in tests this is always "datetime64"
self.kind = "datetime"
elif dtype.startswith("timedelta"):
self.kind = "timedelta"
elif dtype.startswith("bool"):
self.kind = "bool"
else:
raise AssertionError(f"cannot interpret dtype of [{dtype}] in [{self}]")
# set my typ if we need
if self.typ is None:
self.typ = getattr(self.description, self.cname, None)
def set_atom(self, block):
""" create and setup my atom from the block b """
# short-cut certain block types
if block.is_categorical:
self.set_atom_categorical(block)
elif block.is_datetimetz:
self.set_atom_datetime64tz(block)
@classmethod
def _get_atom(cls, values: Union[np.ndarray, ABCExtensionArray]) -> "Col":
"""
Get an appropriately typed and shaped pytables.Col object for values.
"""
dtype = values.dtype
itemsize = dtype.itemsize
shape = values.shape
if values.ndim == 1:
# EA, use block shape pretending it is 2D
shape = (1, values.size)
if is_categorical_dtype(dtype):
codes = values.codes
atom = cls.get_atom_data(shape, kind=codes.dtype.name)
elif is_datetime64_dtype(dtype) or is_datetime64tz_dtype(dtype):
atom = cls.get_atom_datetime64(shape)
elif is_timedelta64_dtype(dtype):
atom = cls.get_atom_timedelta64(shape)
elif is_complex_dtype(dtype):
atom = _tables().ComplexCol(itemsize=itemsize, shape=shape[0])
elif is_string_dtype(dtype):
atom = cls.get_atom_string(shape, itemsize)
else:
atom = cls.get_atom_data(shape, kind=dtype.name)
return atom
@classmethod
def get_atom_string(cls, shape, itemsize):
return _tables().StringCol(itemsize=itemsize, shape=shape[0])
@classmethod
def get_atom_coltype(cls, kind: str) -> Type["Col"]:
""" return the PyTables column class for this column """
if kind.startswith("uint"):
k4 = kind[4:]
col_name = f"UInt{k4}Col"
else:
kcap = kind.capitalize()
col_name = f"{kcap}Col"
return getattr(_tables(), col_name)
@classmethod
def get_atom_data(cls, shape, kind: str) -> "Col":
return cls.get_atom_coltype(kind=kind)(shape=shape[0])
def set_atom_categorical(self, block):
# currently only supports a 1-D categorical
# in a 1-D block
values = block.values
if values.ndim > 1:
raise NotImplementedError("only support 1-d categoricals")
# write the codes; must be in a block shape
self.ordered = values.ordered
# write the categories
self.meta = "category"
self.metadata = np.array(values.categories, copy=False).ravel()
@classmethod
def get_atom_datetime64(cls, shape):
return _tables().Int64Col(shape=shape[0])
def set_atom_datetime64tz(self, block):
# store a converted timezone
self.tz = _get_tz(block.values.tz)
@classmethod
def get_atom_timedelta64(cls, shape):
return _tables().Int64Col(shape=shape[0])
@property
def shape(self):
return getattr(self.data, "shape", None)
@property
def cvalues(self):
""" return my cython values """
return self.data
def validate_attr(self, append):
"""validate that we have the same order as the existing & same dtype"""
if append:
existing_fields = getattr(self.attrs, self.kind_attr, None)
if existing_fields is not None and existing_fields != list(self.values):
raise ValueError("appended items do not match existing items in table!")
existing_dtype = getattr(self.attrs, self.dtype_attr, None)
if existing_dtype is not None and existing_dtype != self.dtype:
raise ValueError(
"appended items dtype do not match existing "
"items dtype in table!"
)
def convert(self, values, nan_rep, encoding, errors, start=None, stop=None):
"""set the data from this selection (and convert to the correct dtype
if we can)
"""
# values is a recarray
if values.dtype.fields is not None:
values = values[self.cname]
# NB: unlike in the other calls to set_data, self.dtype may not be None here
self.set_data(values)
# use the meta if needed
meta = _ensure_decoded(self.meta)
# convert to the correct dtype
if self.dtype is not None:
dtype = _ensure_decoded(self.dtype)
# reverse converts
if dtype == "datetime64":
# recreate with tz if indicated
self.data = _set_tz(self.data, self.tz, coerce=True)
elif dtype == "timedelta64":
self.data = np.asarray(self.data, dtype="m8[ns]")
elif dtype == "date":
try:
self.data = np.asarray(
[date.fromordinal(v) for v in self.data], dtype=object
)
except ValueError:
self.data = np.asarray(
[date.fromtimestamp(v) for v in self.data], dtype=object
)
elif meta == "category":
# we have a categorical
categories = self.metadata
codes = self.data.ravel()
# if we have stored a NaN in the categories
# then strip it; in theory we could have BOTH
# -1s in the codes and nulls :<
if categories is None:
# Handle case of NaN-only categorical columns in which case
# the categories are an empty array; when this is stored,
# pytables cannot write a zero-len array, so on readback
# the categories would be None and `read_hdf()` would fail.
categories = Index([], dtype=np.float64)
else:
mask = isna(categories)
if mask.any():
categories = categories[~mask]
codes[codes != -1] -= mask.astype(int).cumsum().values
self.data = Categorical.from_codes(
codes, categories=categories, ordered=self.ordered
)
else:
try:
self.data = self.data.astype(dtype, copy=False)
except TypeError:
self.data = self.data.astype("O", copy=False)
# convert nans / decode
if _ensure_decoded(self.kind) == "string":
self.data = _unconvert_string_array(
self.data, nan_rep=nan_rep, encoding=encoding, errors=errors
)
def get_attr(self):
""" get the data for this column """
self.values = getattr(self.attrs, self.kind_attr, None)
self.dtype = getattr(self.attrs, self.dtype_attr, None)
self.meta = getattr(self.attrs, self.meta_attr, None)
self.set_kind()
def set_attr(self):
""" set the data for this column """
setattr(self.attrs, self.kind_attr, self.values)
setattr(self.attrs, self.meta_attr, self.meta)
if self.dtype is not None:
setattr(self.attrs, self.dtype_attr, self.dtype)
class DataIndexableCol(DataCol):
""" represent a data column that can be indexed """
is_data_indexable = True
def validate_names(self):
if not Index(self.values).is_object():
# TODO: should the message here be more specifically non-str?
raise ValueError("cannot have non-object label DataIndexableCol")
@classmethod
def get_atom_string(cls, shape, itemsize):
return _tables().StringCol(itemsize=itemsize)
@classmethod
def get_atom_data(cls, shape, kind: str) -> "Col":
return cls.get_atom_coltype(kind=kind)()
@classmethod
def get_atom_datetime64(cls, shape):
return _tables().Int64Col()
@classmethod
def get_atom_timedelta64(cls, shape):
return _tables().Int64Col()
class GenericDataIndexableCol(DataIndexableCol):
""" represent a generic pytables data column """
def get_attr(self):
pass
class Fixed:
""" represent an object in my store
facilitate read/write of various types of objects
this is an abstract base class
Parameters
----------
parent : HDFStore
group : Node
The group node where the table resides.
"""
pandas_kind: str
obj_type: Type[Union[DataFrame, Series]]
ndim: int
parent: HDFStore
group: "Node"
errors: str
is_table = False
def __init__(
self, parent: HDFStore, group: "Node", encoding=None, errors: str = "strict"
):
assert isinstance(parent, HDFStore), type(parent)
assert _table_mod is not None # needed for mypy
assert isinstance(group, _table_mod.Node), type(group)
self.parent = parent
self.group = group
self.encoding = _ensure_encoding(encoding)
self.errors = errors
@property
def is_old_version(self) -> bool:
return self.version[0] <= 0 and self.version[1] <= 10 and self.version[2] < 1
@property
def version(self) -> Tuple[int, int, int]:
""" compute and set our version """
version = _ensure_decoded(getattr(self.group._v_attrs, "pandas_version", None))
try:
version = tuple(int(x) for x in version.split("."))
if len(version) == 2:
version = version + (0,)
except AttributeError:
version = (0, 0, 0)
return version
@property
def pandas_type(self):
return _ensure_decoded(getattr(self.group._v_attrs, "pandas_type", None))
def __repr__(self) -> str:
""" return a pretty representation of myself """
self.infer_axes()
s = self.shape
if s is not None:
if isinstance(s, (list, tuple)):
jshape = ",".join(pprint_thing(x) for x in s)
s = f"[{jshape}]"
return f"{self.pandas_type:12.12} (shape->{s})"
return self.pandas_type
def set_object_info(self):
""" set my pandas type & version """
self.attrs.pandas_type = str(self.pandas_kind)
self.attrs.pandas_version = str(_version)
def copy(self):
new_self = copy.copy(self)
return new_self
@property
def storage_obj_type(self):
return self.obj_type
@property
def shape(self):
return self.nrows
@property
def pathname(self):
return self.group._v_pathname
@property
def _handle(self):
return self.parent._handle
@property
def _filters(self):
return self.parent._filters
@property
def _complevel(self) -> int:
return self.parent._complevel
@property
def _fletcher32(self) -> bool:
return self.parent._fletcher32
@property
def _complib(self):
return self.parent._complib
@property
def attrs(self):
return self.group._v_attrs
def set_attrs(self):
""" set our object attributes """
pass
def get_attrs(self):
""" get our object attributes """
pass
@property
def storable(self):
""" return my storable """
return self.group
@property
def is_exists(self) -> bool:
return False
@property
def nrows(self):
return getattr(self.storable, "nrows", None)
def validate(self, other):
""" validate against an existing storable """
if other is None:
return
return True
def validate_version(self, where=None):
""" are we trying to operate on an old version? """
return True
def infer_axes(self):
""" infer the axes of my storer
return a boolean indicating if we have a valid storer or not """
s = self.storable
if s is None:
return False
self.get_attrs()
return True
def read(
self,
where=None,
columns=None,
start: Optional[int] = None,
stop: Optional[int] = None,
):
raise NotImplementedError(
"cannot read on an abstract storer: subclasses should implement"
)
def write(self, **kwargs):
raise NotImplementedError(
"cannot write on an abstract storer: subclasses should implement"
)
def delete(
self, where=None, start: Optional[int] = None, stop: Optional[int] = None
):
"""
support fully deleting the node in its entirety (only) - where
specification must be None
"""
if com.all_none(where, start, stop):
self._handle.remove_node(self.group, recursive=True)
return None
raise TypeError("cannot delete on an abstract storer")
class GenericFixed(Fixed):
""" a generified fixed version """
_index_type_map = {DatetimeIndex: "datetime", PeriodIndex: "period"}
_reverse_index_map = {v: k for k, v in _index_type_map.items()}
attributes: List[str] = []
# indexer helpders
def _class_to_alias(self, cls) -> str:
return self._index_type_map.get(cls, "")
def _alias_to_class(self, alias):
if isinstance(alias, type): # pragma: no cover
# compat: for a short period of time master stored types
return alias
return self._reverse_index_map.get(alias, Index)
def _get_index_factory(self, klass):
if klass == DatetimeIndex:
def f(values, freq=None, tz=None):
# data are already in UTC, localize and convert if tz present
result = DatetimeIndex._simple_new(values.values, name=None, freq=freq)
if tz is not None:
result = result.tz_localize("UTC").tz_convert(tz)
return result
return f
elif klass == PeriodIndex:
def f(values, freq=None, tz=None):
return PeriodIndex._simple_new(values, name=None, freq=freq)
return f
return klass
def validate_read(self, columns, where):
"""
raise if any keywords are passed which are not-None
"""
if columns is not None:
raise TypeError(
"cannot pass a column specification when reading "
"a Fixed format store. this store must be "
"selected in its entirety"
)
if where is not None:
raise TypeError(
"cannot pass a where specification when reading "
"from a Fixed format store. this store must be "
"selected in its entirety"
)
@property
def is_exists(self) -> bool:
return True
def set_attrs(self):
""" set our object attributes """
self.attrs.encoding = self.encoding
self.attrs.errors = self.errors
def get_attrs(self):
""" retrieve our attributes """
self.encoding = _ensure_encoding(getattr(self.attrs, "encoding", None))
self.errors = _ensure_decoded(getattr(self.attrs, "errors", "strict"))
for n in self.attributes:
setattr(self, n, _ensure_decoded(getattr(self.attrs, n, None)))
def write(self, obj, **kwargs):
self.set_attrs()
def read_array(
self, key: str, start: Optional[int] = None, stop: Optional[int] = None
):
""" read an array for the specified node (off of group """
import tables
node = getattr(self.group, key)
attrs = node._v_attrs
transposed = getattr(attrs, "transposed", False)
if isinstance(node, tables.VLArray):
ret = node[0][start:stop]
else:
dtype = getattr(attrs, "value_type", None)
shape = getattr(attrs, "shape", None)
if shape is not None:
# length 0 axis
ret = np.empty(shape, dtype=dtype)
else:
ret = node[start:stop]
if dtype == "datetime64":
# reconstruct a timezone if indicated
tz = getattr(attrs, "tz", None)
ret = _set_tz(ret, tz, coerce=True)
elif dtype == "timedelta64":
ret = np.asarray(ret, dtype="m8[ns]")
if transposed:
return ret.T
else:
return ret
def read_index(
self, key: str, start: Optional[int] = None, stop: Optional[int] = None
) -> Index:
variety = _ensure_decoded(getattr(self.attrs, f"{key}_variety"))
if variety == "multi":
return self.read_multi_index(key, start=start, stop=stop)
elif variety == "regular":
node = getattr(self.group, key)
index = self.read_index_node(node, start=start, stop=stop)
return index
else: # pragma: no cover
raise TypeError(f"unrecognized index variety: {variety}")
def write_index(self, key: str, index: Index):
if isinstance(index, MultiIndex):
setattr(self.attrs, f"{key}_variety", "multi")
self.write_multi_index(key, index)
else:
setattr(self.attrs, f"{key}_variety", "regular")
converted = _convert_index("index", index, self.encoding, self.errors)
self.write_array(key, converted.values)
node = getattr(self.group, key)
node._v_attrs.kind = converted.kind
node._v_attrs.name = index.name
if isinstance(index, (DatetimeIndex, PeriodIndex)):
node._v_attrs.index_class = self._class_to_alias(type(index))
if isinstance(index, (DatetimeIndex, PeriodIndex, TimedeltaIndex)):
node._v_attrs.freq = index.freq
if isinstance(index, DatetimeIndex) and index.tz is not None:
node._v_attrs.tz = _get_tz(index.tz)
def write_multi_index(self, key: str, index: MultiIndex):
setattr(self.attrs, f"{key}_nlevels", index.nlevels)
for i, (lev, level_codes, name) in enumerate(
zip(index.levels, index.codes, index.names)
):
# write the level
if is_extension_array_dtype(lev):
raise NotImplementedError(
"Saving a MultiIndex with an extension dtype is not supported."
)
level_key = f"{key}_level{i}"
conv_level = _convert_index(level_key, lev, self.encoding, self.errors)
self.write_array(level_key, conv_level.values)
node = getattr(self.group, level_key)
node._v_attrs.kind = conv_level.kind
node._v_attrs.name = name
# write the name
setattr(node._v_attrs, f"{key}_name{name}", name)
# write the labels
label_key = f"{key}_label{i}"
self.write_array(label_key, level_codes)
def read_multi_index(
self, key: str, start: Optional[int] = None, stop: Optional[int] = None
) -> MultiIndex:
nlevels = getattr(self.attrs, f"{key}_nlevels")
levels = []
codes = []
names: List[Optional[Hashable]] = []
for i in range(nlevels):
level_key = f"{key}_level{i}"
node = getattr(self.group, level_key)
lev = self.read_index_node(node, start=start, stop=stop)
levels.append(lev)
names.append(lev.name)
label_key = f"{key}_label{i}"
level_codes = self.read_array(label_key, start=start, stop=stop)
codes.append(level_codes)
return MultiIndex(
levels=levels, codes=codes, names=names, verify_integrity=True
)
def read_index_node(
self, node: "Node", start: Optional[int] = None, stop: Optional[int] = None
) -> Index:
data = node[start:stop]
# If the index was an empty array write_array_empty() will
# have written a sentinel. Here we relace it with the original.
if "shape" in node._v_attrs and np.prod(node._v_attrs.shape) == 0:
data = np.empty(node._v_attrs.shape, dtype=node._v_attrs.value_type,)
kind = _ensure_decoded(node._v_attrs.kind)
name = None
if "name" in node._v_attrs:
name = _ensure_str(node._v_attrs.name)
name = _ensure_decoded(name)
index_class = self._alias_to_class(
_ensure_decoded(getattr(node._v_attrs, "index_class", ""))
)
factory = self._get_index_factory(index_class)
kwargs = {}
if "freq" in node._v_attrs:
kwargs["freq"] = node._v_attrs["freq"]
if "tz" in node._v_attrs:
if isinstance(node._v_attrs["tz"], bytes):
# created by python2
kwargs["tz"] = node._v_attrs["tz"].decode("utf-8")
else:
# created by python3
kwargs["tz"] = node._v_attrs["tz"]
if kind == "date":
index = factory(
_unconvert_index(
data, kind, encoding=self.encoding, errors=self.errors
),
dtype=object,
**kwargs,
)
else:
index = factory(
_unconvert_index(
data, kind, encoding=self.encoding, errors=self.errors
),
**kwargs,
)
index.name = name
return index
def write_array_empty(self, key: str, value: ArrayLike):
""" write a 0-len array """
# ugly hack for length 0 axes
arr = np.empty((1,) * value.ndim)
self._handle.create_array(self.group, key, arr)
node = getattr(self.group, key)
node._v_attrs.value_type = str(value.dtype)
node._v_attrs.shape = value.shape
def write_array(self, key: str, value: ArrayLike, items: Optional[Index] = None):
# TODO: we only have one test that gets here, the only EA
# that gets passed is DatetimeArray, and we never have
# both self._filters and EA
assert isinstance(value, (np.ndarray, ABCExtensionArray)), type(value)
if key in self.group:
self._handle.remove_node(self.group, key)
# Transform needed to interface with pytables row/col notation
empty_array = value.size == 0
transposed = False
if is_categorical_dtype(value):
raise NotImplementedError(
"Cannot store a category dtype in "
"a HDF5 dataset that uses format="
'"fixed". Use format="table".'
)
if not empty_array:
if hasattr(value, "T"):
# ExtensionArrays (1d) may not have transpose.
value = value.T
transposed = True
atom = None
if self._filters is not None:
try:
# get the atom for this datatype
atom = _tables().Atom.from_dtype(value.dtype)
except ValueError:
pass
if atom is not None:
# We only get here if self._filters is non-None and
# the Atom.from_dtype call succeeded
# create an empty chunked array and fill it from value
if not empty_array:
ca = self._handle.create_carray(
self.group, key, atom, value.shape, filters=self._filters
)
ca[:] = value
else:
self.write_array_empty(key, value)
elif value.dtype.type == np.object_:
# infer the type, warn if we have a non-string type here (for
# performance)
inferred_type = lib.infer_dtype(value.ravel(), skipna=False)
if empty_array:
pass
elif inferred_type == "string":
pass
else:
ws = performance_doc % (inferred_type, key, items)
warnings.warn(ws, PerformanceWarning, stacklevel=7)
vlarr = self._handle.create_vlarray(self.group, key, _tables().ObjectAtom())
vlarr.append(value)
elif empty_array:
self.write_array_empty(key, value)
elif is_datetime64_dtype(value.dtype):
self._handle.create_array(self.group, key, value.view("i8"))
getattr(self.group, key)._v_attrs.value_type = "datetime64"
elif is_datetime64tz_dtype(value.dtype):
# store as UTC
# with a zone
self._handle.create_array(self.group, key, value.asi8)
node = getattr(self.group, key)
node._v_attrs.tz = _get_tz(value.tz)
node._v_attrs.value_type = "datetime64"
elif is_timedelta64_dtype(value.dtype):
self._handle.create_array(self.group, key, value.view("i8"))
getattr(self.group, key)._v_attrs.value_type = "timedelta64"
else:
self._handle.create_array(self.group, key, value)
getattr(self.group, key)._v_attrs.transposed = transposed
class SeriesFixed(GenericFixed):
pandas_kind = "series"
attributes = ["name"]
name: Optional[Hashable]
@property
def shape(self):
try:
return (len(self.group.values),)
except (TypeError, AttributeError):
return None
def read(
self,
where=None,
columns=None,
start: Optional[int] = None,
stop: Optional[int] = None,
):
self.validate_read(columns, where)
index = self.read_index("index", start=start, stop=stop)
values = self.read_array("values", start=start, stop=stop)
return Series(values, index=index, name=self.name)
def write(self, obj, **kwargs):
super().write(obj, **kwargs)
self.write_index("index", obj.index)
self.write_array("values", obj.values)
self.attrs.name = obj.name
class BlockManagerFixed(GenericFixed):
attributes = ["ndim", "nblocks"]
nblocks: int
@property
def shape(self):
try:
ndim = self.ndim
# items
items = 0
for i in range(self.nblocks):
node = getattr(self.group, f"block{i}_items")
shape = getattr(node, "shape", None)
if shape is not None:
items += shape[0]
# data shape
node = self.group.block0_values
shape = getattr(node, "shape", None)
if shape is not None:
shape = list(shape[0 : (ndim - 1)])
else:
shape = []
shape.append(items)
return shape
except AttributeError:
return None
def read(
self,
where=None,
columns=None,
start: Optional[int] = None,
stop: Optional[int] = None,
):
# start, stop applied to rows, so 0th axis only
self.validate_read(columns, where)
select_axis = self.obj_type()._get_block_manager_axis(0)
axes = []
for i in range(self.ndim):
_start, _stop = (start, stop) if i == select_axis else (None, None)
ax = self.read_index(f"axis{i}", start=_start, stop=_stop)
axes.append(ax)
items = axes[0]
dfs = []
for i in range(self.nblocks):
blk_items = self.read_index(f"block{i}_items")
values = self.read_array(f"block{i}_values", start=_start, stop=_stop)
columns = items[items.get_indexer(blk_items)]
df = DataFrame(values.T, columns=columns, index=axes[1])
dfs.append(df)
if len(dfs) > 0:
out = concat(dfs, axis=1)
out = out.reindex(columns=items, copy=False)
return out
return DataFrame(columns=axes[0], index=axes[1])
def write(self, obj, **kwargs):
super().write(obj, **kwargs)
data = obj._data
if not data.is_consolidated():
data = data.consolidate()
self.attrs.ndim = data.ndim
for i, ax in enumerate(data.axes):
if i == 0:
if not ax.is_unique:
raise ValueError("Columns index has to be unique for fixed format")
self.write_index(f"axis{i}", ax)
# Supporting mixed-type DataFrame objects...nontrivial
self.attrs.nblocks = len(data.blocks)
for i, blk in enumerate(data.blocks):
# I have no idea why, but writing values before items fixed #2299
blk_items = data.items.take(blk.mgr_locs)
self.write_array(f"block{i}_values", blk.values, items=blk_items)
self.write_index(f"block{i}_items", blk_items)
class FrameFixed(BlockManagerFixed):
pandas_kind = "frame"
obj_type = DataFrame
class Table(Fixed):
""" represent a table:
facilitate read/write of various types of tables
Attrs in Table Node
-------------------
These are attributes that are store in the main table node, they are
necessary to recreate these tables when read back in.
index_axes : a list of tuples of the (original indexing axis and
index column)
non_index_axes: a list of tuples of the (original index axis and
columns on a non-indexing axis)
values_axes : a list of the columns which comprise the data of this
table
data_columns : a list of the columns that we are allowing indexing
(these become single columns in values_axes), or True to force all
columns
nan_rep : the string to use for nan representations for string
objects
levels : the names of levels
metadata : the names of the metadata columns
"""
pandas_kind = "wide_table"
table_type: str
levels = 1
is_table = True
index_axes: List[IndexCol]
non_index_axes: List[Tuple[int, Any]]
values_axes: List[DataCol]
data_columns: List
metadata: List
info: Dict
def __init__(
self, parent: HDFStore, group: "Node", encoding=None, errors: str = "strict"
):
super().__init__(parent, group, encoding=encoding, errors=errors)
self.index_axes = []
self.non_index_axes = []
self.values_axes = []
self.data_columns = []
self.metadata = []
self.info = dict()
self.nan_rep = None
@property
def table_type_short(self) -> str:
return self.table_type.split("_")[0]
def __repr__(self) -> str:
""" return a pretty representation of myself """
self.infer_axes()
jdc = ",".join(self.data_columns) if len(self.data_columns) else ""
dc = f",dc->[{jdc}]"
ver = ""
if self.is_old_version:
jver = ".".join(str(x) for x in self.version)
ver = f"[{jver}]"
jindex_axes = ",".join(a.name for a in self.index_axes)
return (
f"{self.pandas_type:12.12}{ver} "
f"(typ->{self.table_type_short},nrows->{self.nrows},"
f"ncols->{self.ncols},indexers->[{jindex_axes}]{dc})"
)
def __getitem__(self, c: str):
""" return the axis for c """
for a in self.axes:
if c == a.name:
return a
return None
def validate(self, other):
""" validate against an existing table """
if other is None:
return
if other.table_type != self.table_type:
raise TypeError(
"incompatible table_type with existing "
f"[{other.table_type} - {self.table_type}]"
)
for c in ["index_axes", "non_index_axes", "values_axes"]:
sv = getattr(self, c, None)
ov = getattr(other, c, None)
if sv != ov:
# show the error for the specific axes
for i, sax in enumerate(sv):
oax = ov[i]
if sax != oax:
raise ValueError(
f"invalid combinate of [{c}] on appending data "
f"[{sax}] vs current table [{oax}]"
)
# should never get here
raise Exception(
f"invalid combinate of [{c}] on appending data [{sv}] vs "
f"current table [{ov}]"
)
@property
def is_multi_index(self) -> bool:
"""the levels attribute is 1 or a list in the case of a multi-index"""
return isinstance(self.levels, list)
def validate_multiindex(self, obj):
"""validate that we can store the multi-index; reset and return the
new object
"""
levels = [
l if l is not None else f"level_{i}" for i, l in enumerate(obj.index.names)
]
try:
return obj.reset_index(), levels
except ValueError:
raise ValueError(
"duplicate names/columns in the multi-index when storing as a table"
)
@property
def nrows_expected(self) -> int:
""" based on our axes, compute the expected nrows """
return np.prod([i.cvalues.shape[0] for i in self.index_axes])
@property
def is_exists(self) -> bool:
""" has this table been created """
return "table" in self.group
@property
def storable(self):
return getattr(self.group, "table", None)
@property
def table(self):
""" return the table group (this is my storable) """
return self.storable
@property
def dtype(self):
return self.table.dtype
@property
def description(self):
return self.table.description
@property
def axes(self):
return itertools.chain(self.index_axes, self.values_axes)
@property
def ncols(self) -> int:
""" the number of total columns in the values axes """
return sum(len(a.values) for a in self.values_axes)
@property
def is_transposed(self) -> bool:
return False
@property
def data_orientation(self):
"""return a tuple of my permutated axes, non_indexable at the front"""
return tuple(
itertools.chain(
[int(a[0]) for a in self.non_index_axes],
[int(a.axis) for a in self.index_axes],
)
)
def queryables(self) -> Dict[str, Any]:
""" return a dict of the kinds allowable columns for this object """
# compute the values_axes queryables
d1 = [(a.cname, a) for a in self.index_axes]
d2 = [
(self.storage_obj_type._AXIS_NAMES[axis], None)
for axis, values in self.non_index_axes
]
d3 = [
(v.cname, v) for v in self.values_axes if v.name in set(self.data_columns)
]
return dict(d1 + d2 + d3) # type: ignore
# error: List comprehension has incompatible type
# List[Tuple[Any, None]]; expected List[Tuple[str, IndexCol]]
def index_cols(self):
""" return a list of my index cols """
# Note: each `i.cname` below is assured to be a str.
return [(i.axis, i.cname) for i in self.index_axes]
def values_cols(self) -> List[str]:
""" return a list of my values cols """
return [i.cname for i in self.values_axes]
def _get_metadata_path(self, key: str) -> str:
""" return the metadata pathname for this key """
group = self.group._v_pathname
return f"{group}/meta/{key}/meta"
def write_metadata(self, key: str, values):
"""
write out a meta data array to the key as a fixed-format Series
Parameters
----------
key : str
values : ndarray
"""
values = Series(values)
self.parent.put(
self._get_metadata_path(key),
values,
format="table",
encoding=self.encoding,
errors=self.errors,
nan_rep=self.nan_rep,
)
def read_metadata(self, key: str):
""" return the meta data array for this key """
if getattr(getattr(self.group, "meta", None), key, None) is not None:
return self.parent.select(self._get_metadata_path(key))
return None
def set_attrs(self):
""" set our table type & indexables """
self.attrs.table_type = str(self.table_type)
self.attrs.index_cols = self.index_cols()
self.attrs.values_cols = self.values_cols()
self.attrs.non_index_axes = self.non_index_axes
self.attrs.data_columns = self.data_columns
self.attrs.nan_rep = self.nan_rep
self.attrs.encoding = self.encoding
self.attrs.errors = self.errors
self.attrs.levels = self.levels
self.attrs.metadata = self.metadata
self.attrs.info = self.info
def get_attrs(self):
""" retrieve our attributes """
self.non_index_axes = getattr(self.attrs, "non_index_axes", None) or []
self.data_columns = getattr(self.attrs, "data_columns", None) or []
self.info = getattr(self.attrs, "info", None) or dict()
self.nan_rep = getattr(self.attrs, "nan_rep", None)
self.encoding = _ensure_encoding(getattr(self.attrs, "encoding", None))
self.errors = _ensure_decoded(getattr(self.attrs, "errors", "strict"))
self.levels = getattr(self.attrs, "levels", None) or []
self.index_axes = [a.infer(self) for a in self.indexables if a.is_an_indexable]
self.values_axes = [
a.infer(self) for a in self.indexables if not a.is_an_indexable
]
self.metadata = getattr(self.attrs, "metadata", None) or []
def validate_version(self, where=None):
""" are we trying to operate on an old version? """
if where is not None:
if self.version[0] <= 0 and self.version[1] <= 10 and self.version[2] < 1:
ws = incompatibility_doc % ".".join([str(x) for x in self.version])
warnings.warn(ws, IncompatibilityWarning)
def validate_min_itemsize(self, min_itemsize):
"""validate the min_itemsize doesn't contain items that are not in the
axes this needs data_columns to be defined
"""
if min_itemsize is None:
return
if not isinstance(min_itemsize, dict):
return
q = self.queryables()
for k, v in min_itemsize.items():
# ok, apply generally
if k == "values":
continue
if k not in q:
raise ValueError(
f"min_itemsize has the key [{k}] which is not an axis or "
"data_column"
)
@cache_readonly
def indexables(self):
""" create/cache the indexables if they don't exist """
_indexables = []
# Note: each of the `name` kwargs below are str, ensured
# by the definition in index_cols.
# index columns
_indexables.extend(
[
IndexCol(name=name, axis=axis, pos=i)
for i, (axis, name) in enumerate(self.attrs.index_cols)
]
)
# values columns
dc = set(self.data_columns)
base_pos = len(_indexables)
def f(i, c):
assert isinstance(c, str)
klass = DataCol
if c in dc:
klass = DataIndexableCol
return klass.create_for_block(
i=i, name=c, pos=base_pos + i, version=self.version
)
# Note: the definition of `values_cols` ensures that each
# `c` below is a str.
_indexables.extend([f(i, c) for i, c in enumerate(self.attrs.values_cols)])
return _indexables
def create_index(self, columns=None, optlevel=None, kind: Optional[str] = None):
"""
Create a pytables index on the specified columns
note: cannot index Time64Col() or ComplexCol currently;
PyTables must be >= 3.0
Parameters
----------
columns : None, bool, or listlike[str]
Indicate which columns to create an index on.
* False : Do not create any indexes.
* True : Create indexes on all columns.
* None : Create indexes on all columns.
* listlike : Create indexes on the given columns.
optlevel : int or None, default None
Optimization level, if None, pytables defaults to 6.
kind : str or None, default None
Kind of index, if None, pytables defaults to "medium"
Raises
------
raises if the node is not a table
"""
if not self.infer_axes():
return
if columns is False:
return
# index all indexables and data_columns
if columns is None or columns is True:
columns = [a.cname for a in self.axes if a.is_data_indexable]
if not isinstance(columns, (tuple, list)):
columns = [columns]
kw = dict()
if optlevel is not None:
kw["optlevel"] = optlevel
if kind is not None:
kw["kind"] = kind
table = self.table
for c in columns:
v = getattr(table.cols, c, None)
if v is not None:
# remove the index if the kind/optlevel have changed
if v.is_indexed:
index = v.index
cur_optlevel = index.optlevel
cur_kind = index.kind
if kind is not None and cur_kind != kind:
v.remove_index()
else:
kw["kind"] = cur_kind
if optlevel is not None and cur_optlevel != optlevel:
v.remove_index()
else:
kw["optlevel"] = cur_optlevel
# create the index
if not v.is_indexed:
if v.type.startswith("complex"):
raise TypeError(
"Columns containing complex values can be stored "
"but cannot"
" be indexed when using table format. Either use "
"fixed format, set index=False, or do not include "
"the columns containing complex values to "
"data_columns when initializing the table."
)
v.create_index(**kw)
def read_axes(
self, where, start: Optional[int] = None, stop: Optional[int] = None
) -> bool:
"""
Create the axes sniffed from the table.
Parameters
----------
where : ???
start : int or None, default None
stop : int or None, default None
Returns
-------
bool
Indicates success.
"""
# validate the version
self.validate_version(where)
# infer the data kind
if not self.infer_axes():
return False
# create the selection
selection = Selection(self, where=where, start=start, stop=stop)
values = selection.select()
# convert the data
for a in self.axes:
a.set_info(self.info)
a.convert(
values,
nan_rep=self.nan_rep,
encoding=self.encoding,
errors=self.errors,
start=start,
stop=stop,
)
return True
def get_object(self, obj, transposed: bool):
""" return the data for this obj """
return obj
def validate_data_columns(self, data_columns, min_itemsize, non_index_axes):
"""take the input data_columns and min_itemize and create a data
columns spec
"""
if not len(non_index_axes):
return []
axis, axis_labels = non_index_axes[0]
info = self.info.get(axis, dict())
if info.get("type") == "MultiIndex" and data_columns:
raise ValueError(
f"cannot use a multi-index on axis [{axis}] with "
f"data_columns {data_columns}"
)
# evaluate the passed data_columns, True == use all columns
# take only valide axis labels
if data_columns is True:
data_columns = list(axis_labels)
elif data_columns is None:
data_columns = []
# if min_itemsize is a dict, add the keys (exclude 'values')
if isinstance(min_itemsize, dict):
existing_data_columns = set(data_columns)
data_columns.extend(
[
k
for k in min_itemsize.keys()
if k != "values" and k not in existing_data_columns
]
)
# return valid columns in the order of our axis
return [c for c in data_columns if c in axis_labels]
def create_axes(
self,
axes,
obj,
validate: bool = True,
nan_rep=None,
data_columns=None,
min_itemsize=None,
):
""" create and return the axes
legacy tables create an indexable column, indexable index,
non-indexable fields
Parameters
----------
axes: a list of the axes in order to create (names or numbers of
the axes)
obj : the object to create axes on
validate: validate the obj against an existing object already
written
min_itemsize: a dict of the min size for a column in bytes
nan_rep : a values to use for string column nan_rep
encoding : the encoding for string values
data_columns : a list of columns that we want to create separate to
allow indexing (or True will force all columns)
"""
# set the default axes if needed
if axes is None:
try:
axes = _AXES_MAP[type(obj)]
except KeyError:
group = self.group._v_name
raise TypeError(
f"cannot properly create the storer for: [group->{group},"
f"value->{type(obj)}]"
)
# map axes to numbers
axes = [obj._get_axis_number(a) for a in axes]
# do we have an existing table (if so, use its axes & data_columns)
if self.infer_axes():
existing_table = self.copy()
existing_table.infer_axes()
axes = [a.axis for a in existing_table.index_axes]
data_columns = existing_table.data_columns
nan_rep = existing_table.nan_rep
self.encoding = existing_table.encoding
self.errors = existing_table.errors
self.info = copy.copy(existing_table.info)
else:
existing_table = None
assert self.ndim == 2 # with next check, we must have len(axes) == 1
# currently support on ndim-1 axes
if len(axes) != self.ndim - 1:
raise ValueError(
"currently only support ndim-1 indexers in an AppendableTable"
)
# create according to the new data
new_non_index_axes: List = []
new_data_columns: List[Optional[str]] = []
# nan_representation
if nan_rep is None:
nan_rep = "nan"
# We construct the non-index-axis first, since that alters self.info
idx = [x for x in [0, 1] if x not in axes][0]
a = obj.axes[idx]
# we might be able to change the axes on the appending data if necessary
append_axis = list(a)
if existing_table is not None:
indexer = len(new_non_index_axes) # i.e. 0
exist_axis = existing_table.non_index_axes[indexer][1]
if not array_equivalent(np.array(append_axis), np.array(exist_axis)):
# ahah! -> reindex
if array_equivalent(
np.array(sorted(append_axis)), np.array(sorted(exist_axis))
):
append_axis = exist_axis
# the non_index_axes info
info = self.info.setdefault(idx, {})
info["names"] = list(a.names)
info["type"] = type(a).__name__
new_non_index_axes.append((idx, append_axis))
# Now we can construct our new index axis
idx = axes[0]
a = obj.axes[idx]
name = obj._AXIS_NAMES[idx]
new_index = _convert_index(name, a, self.encoding, self.errors)
new_index.axis = idx
# Because we are always 2D, there is only one new_index, so
# we know it will have pos=0
new_index.set_pos(0)
new_index.update_info(self.info)
new_index.maybe_set_size(min_itemsize) # check for column conflicts
self.non_index_axes = new_non_index_axes
new_index_axes = [new_index]
j = len(new_index_axes) # i.e. 1
assert j == 1
# reindex by our non_index_axes & compute data_columns
assert len(new_non_index_axes) == 1
for a in new_non_index_axes:
obj = _reindex_axis(obj, a[0], a[1])
def get_blk_items(mgr, blocks):
return [mgr.items.take(blk.mgr_locs) for blk in blocks]
transposed = new_index.axis == 1
# figure out data_columns and get out blocks
block_obj = self.get_object(obj, transposed)._consolidate()
blocks = block_obj._data.blocks
blk_items = get_blk_items(block_obj._data, blocks)
if len(new_non_index_axes):
axis, axis_labels = new_non_index_axes[0]
data_columns = self.validate_data_columns(
data_columns, min_itemsize, new_non_index_axes
)
if len(data_columns):
mgr = block_obj.reindex(
Index(axis_labels).difference(Index(data_columns)), axis=axis
)._data
blocks = list(mgr.blocks)
blk_items = get_blk_items(mgr, blocks)
for c in data_columns:
mgr = block_obj.reindex([c], axis=axis)._data
blocks.extend(mgr.blocks)
blk_items.extend(get_blk_items(mgr, mgr.blocks))
# reorder the blocks in the same order as the existing_table if we can
if existing_table is not None:
by_items = {
tuple(b_items.tolist()): (b, b_items)
for b, b_items in zip(blocks, blk_items)
}
new_blocks = []
new_blk_items = []
for ea in existing_table.values_axes:
items = tuple(ea.values)
try:
b, b_items = by_items.pop(items)
new_blocks.append(b)
new_blk_items.append(b_items)
except (IndexError, KeyError):
jitems = ",".join(pprint_thing(item) for item in items)
raise ValueError(
f"cannot match existing table structure for [{jitems}] "
"on appending data"
)
blocks = new_blocks
blk_items = new_blk_items
# add my values
vaxes = []
for i, (b, b_items) in enumerate(zip(blocks, blk_items)):
# shape of the data column are the indexable axes
klass = DataCol
name = None
# we have a data_column
if data_columns and len(b_items) == 1 and b_items[0] in data_columns:
klass = DataIndexableCol
name = b_items[0]
if not (name is None or isinstance(name, str)):
# TODO: should the message here be more specifically non-str?
raise ValueError("cannot have non-object label DataIndexableCol")
new_data_columns.append(name)
# make sure that we match up the existing columns
# if we have an existing table
if existing_table is not None and validate:
try:
existing_col = existing_table.values_axes[i]
except (IndexError, KeyError):
raise ValueError(
f"Incompatible appended table [{blocks}]"
f"with existing table [{existing_table.values_axes}]"
)
else:
existing_col = None
new_name = name or f"values_block_{i}"
data_converted = _maybe_convert_for_string_atom(
new_name,
b,
existing_col=existing_col,
min_itemsize=min_itemsize,
nan_rep=nan_rep,
encoding=self.encoding,
errors=self.errors,
)
typ = klass._get_atom(data_converted)
col = klass.create_for_block(i=i, name=new_name, version=self.version)
col.values = list(b_items)
col.typ = typ
col.set_atom(block=b)
col.set_data(data_converted)
col.update_info(self.info)
col.set_pos(j)
vaxes.append(col)
j += 1
self.nan_rep = nan_rep
self.data_columns = new_data_columns
self.values_axes = vaxes
self.index_axes = new_index_axes
self.non_index_axes = new_non_index_axes
# validate our min_itemsize
self.validate_min_itemsize(min_itemsize)
# validate our metadata
self.metadata = [c.name for c in self.values_axes if c.metadata is not None]
# validate the axes if we have an existing table
if validate:
self.validate(existing_table)
def process_axes(self, obj, selection: "Selection", columns=None):
""" process axes filters """
# make a copy to avoid side effects
if columns is not None:
columns = list(columns)
# make sure to include levels if we have them
if columns is not None and self.is_multi_index:
assert isinstance(self.levels, list) # assured by is_multi_index
for n in self.levels:
if n not in columns:
columns.insert(0, n)
# reorder by any non_index_axes & limit to the select columns
for axis, labels in self.non_index_axes:
obj = _reindex_axis(obj, axis, labels, columns)
# apply the selection filters (but keep in the same order)
if selection.filter is not None:
for field, op, filt in selection.filter.format():
def process_filter(field, filt):
for axis_name in obj._AXIS_NAMES.values():
axis_number = obj._get_axis_number(axis_name)
axis_values = obj._get_axis(axis_name)
assert axis_number is not None
# see if the field is the name of an axis
if field == axis_name:
# if we have a multi-index, then need to include
# the levels
if self.is_multi_index:
filt = filt.union(Index(self.levels))
takers = op(axis_values, filt)
return obj.loc(axis=axis_number)[takers]
# this might be the name of a file IN an axis
elif field in axis_values:
# we need to filter on this dimension
values = ensure_index(getattr(obj, field).values)
filt = ensure_index(filt)
# hack until we support reversed dim flags
if isinstance(obj, DataFrame):
axis_number = 1 - axis_number
takers = op(values, filt)
return obj.loc(axis=axis_number)[takers]
raise ValueError(f"cannot find the field [{field}] for filtering!")
obj = process_filter(field, filt)
return obj
def create_description(
self,
complib=None,
complevel: Optional[int] = None,
fletcher32: bool = False,
expectedrows: Optional[int] = None,
) -> Dict[str, Any]:
""" create the description of the table from the axes & values """
# provided expected rows if its passed
if expectedrows is None:
expectedrows = max(self.nrows_expected, 10000)
d = dict(name="table", expectedrows=expectedrows)
# description from the axes & values
d["description"] = {a.cname: a.typ for a in self.axes}
if complib:
if complevel is None:
complevel = self._complevel or 9
filters = _tables().Filters(
complevel=complevel,
complib=complib,
fletcher32=fletcher32 or self._fletcher32,
)
d["filters"] = filters
elif self._filters is not None:
d["filters"] = self._filters
return d
def read_coordinates(
self, where=None, start: Optional[int] = None, stop: Optional[int] = None,
):
"""select coordinates (row numbers) from a table; return the
coordinates object
"""
# validate the version
self.validate_version(where)
# infer the data kind
if not self.infer_axes():
return False
# create the selection
selection = Selection(self, where=where, start=start, stop=stop)
coords = selection.select_coords()
if selection.filter is not None:
for field, op, filt in selection.filter.format():
data = self.read_column(
field, start=coords.min(), stop=coords.max() + 1
)
coords = coords[op(data.iloc[coords - coords.min()], filt).values]
return Index(coords)
def read_column(
self,
column: str,
where=None,
start: Optional[int] = None,
stop: Optional[int] = None,
):
"""return a single column from the table, generally only indexables
are interesting
"""
# validate the version
self.validate_version()
# infer the data kind
if not self.infer_axes():
return False
if where is not None:
raise TypeError("read_column does not currently accept a where clause")
# find the axes
for a in self.axes:
if column == a.name:
if not a.is_data_indexable:
raise ValueError(
f"column [{column}] can not be extracted individually; "
"it is not data indexable"
)
# column must be an indexable or a data column
c = getattr(self.table.cols, column)
a.set_info(self.info)
a.convert(
c[start:stop],
nan_rep=self.nan_rep,
encoding=self.encoding,
errors=self.errors,
)
return Series(_set_tz(a.take_data(), a.tz), name=column)
raise KeyError(f"column [{column}] not found in the table")
class WORMTable(Table):
""" a write-once read-many table: this format DOES NOT ALLOW appending to a
table. writing is a one-time operation the data are stored in a format
that allows for searching the data on disk
"""
table_type = "worm"
def read(
self,
where=None,
columns=None,
start: Optional[int] = None,
stop: Optional[int] = None,
):
""" read the indices and the indexing array, calculate offset rows and
return """
raise NotImplementedError("WORMTable needs to implement read")
def write(self, **kwargs):
""" write in a format that we can search later on (but cannot append
to): write out the indices and the values using _write_array
(e.g. a CArray) create an indexing table so that we can search
"""
raise NotImplementedError("WORMTable needs to implement write")
class AppendableTable(Table):
""" support the new appendable table formats """
table_type = "appendable"
def write(
self,
obj,
axes=None,
append=False,
complib=None,
complevel=None,
fletcher32=None,
min_itemsize=None,
chunksize=None,
expectedrows=None,
dropna=False,
nan_rep=None,
data_columns=None,
):
if not append and self.is_exists:
self._handle.remove_node(self.group, "table")
# create the axes
self.create_axes(
axes=axes,
obj=obj,
validate=append,
min_itemsize=min_itemsize,
nan_rep=nan_rep,
data_columns=data_columns,
)
for a in self.axes:
a.validate(self, append)
if not self.is_exists:
# create the table
options = self.create_description(
complib=complib,
complevel=complevel,
fletcher32=fletcher32,
expectedrows=expectedrows,
)
# set the table attributes
self.set_attrs()
# create the table
self._handle.create_table(self.group, **options)
# update my info
self.attrs.info = self.info
# validate the axes and set the kinds
for a in self.axes:
a.validate_and_set(self, append)
# add the rows
self.write_data(chunksize, dropna=dropna)
def write_data(self, chunksize: Optional[int], dropna: bool = False):
""" we form the data into a 2-d including indexes,values,mask
write chunk-by-chunk """
names = self.dtype.names
nrows = self.nrows_expected
# if dropna==True, then drop ALL nan rows
masks = []
if dropna:
for a in self.values_axes:
# figure the mask: only do if we can successfully process this
# column, otherwise ignore the mask
mask = isna(a.data).all(axis=0)
if isinstance(mask, np.ndarray):
masks.append(mask.astype("u1", copy=False))
# consolidate masks
if len(masks):
mask = masks[0]
for m in masks[1:]:
mask = mask & m
mask = mask.ravel()
else:
mask = None
# broadcast the indexes if needed
indexes = [a.cvalues for a in self.index_axes]
nindexes = len(indexes)
assert nindexes == 1, nindexes # ensures we dont need to broadcast
# transpose the values so first dimension is last
# reshape the values if needed
values = [a.take_data() for a in self.values_axes]
values = [v.transpose(np.roll(np.arange(v.ndim), v.ndim - 1)) for v in values]
bvalues = []
for i, v in enumerate(values):
new_shape = (nrows,) + self.dtype[names[nindexes + i]].shape
bvalues.append(values[i].reshape(new_shape))
# write the chunks
if chunksize is None:
chunksize = 100000
rows = np.empty(min(chunksize, nrows), dtype=self.dtype)
chunks = int(nrows / chunksize) + 1
for i in range(chunks):
start_i = i * chunksize
end_i = min((i + 1) * chunksize, nrows)
if start_i >= end_i:
break
self.write_data_chunk(
rows,
indexes=[a[start_i:end_i] for a in indexes],
mask=mask[start_i:end_i] if mask is not None else None,
values=[v[start_i:end_i] for v in bvalues],
)
def write_data_chunk(self, rows, indexes, mask, values):
"""
Parameters
----------
rows : an empty memory space where we are putting the chunk
indexes : an array of the indexes
mask : an array of the masks
values : an array of the values
"""
# 0 len
for v in values:
if not np.prod(v.shape):
return
nrows = indexes[0].shape[0]
if nrows != len(rows):
rows = np.empty(nrows, dtype=self.dtype)
names = self.dtype.names
nindexes = len(indexes)
# indexes
for i, idx in enumerate(indexes):
rows[names[i]] = idx
# values
for i, v in enumerate(values):
rows[names[i + nindexes]] = v
# mask
if mask is not None:
m = ~mask.ravel().astype(bool, copy=False)
if not m.all():
rows = rows[m]
if len(rows):
self.table.append(rows)
self.table.flush()
def delete(
self, where=None, start: Optional[int] = None, stop: Optional[int] = None,
):
# delete all rows (and return the nrows)
if where is None or not len(where):
if start is None and stop is None:
nrows = self.nrows
self._handle.remove_node(self.group, recursive=True)
else:
# pytables<3.0 would remove a single row with stop=None
if stop is None:
stop = self.nrows
nrows = self.table.remove_rows(start=start, stop=stop)
self.table.flush()
return nrows
# infer the data kind
if not self.infer_axes():
return None
# create the selection
table = self.table
selection = Selection(self, where, start=start, stop=stop)
values = selection.select_coords()
# delete the rows in reverse order
sorted_series = Series(values).sort_values()
ln = len(sorted_series)
if ln:
# construct groups of consecutive rows
diff = sorted_series.diff()
groups = list(diff[diff > 1].index)
# 1 group
if not len(groups):
groups = [0]
# final element
if groups[-1] != ln:
groups.append(ln)
# initial element
if groups[0] != 0:
groups.insert(0, 0)
# we must remove in reverse order!
pg = groups.pop()
for g in reversed(groups):
rows = sorted_series.take(range(g, pg))
table.remove_rows(
start=rows[rows.index[0]], stop=rows[rows.index[-1]] + 1
)
pg = g
self.table.flush()
# return the number of rows removed
return ln
class AppendableFrameTable(AppendableTable):
""" support the new appendable table formats """
pandas_kind = "frame_table"
table_type = "appendable_frame"
ndim = 2
obj_type: Type[Union[DataFrame, Series]] = DataFrame
@property
def is_transposed(self) -> bool:
return self.index_axes[0].axis == 1
def get_object(self, obj, transposed: bool):
""" these are written transposed """
if transposed:
obj = obj.T
return obj
def read(
self,
where=None,
columns=None,
start: Optional[int] = None,
stop: Optional[int] = None,
):
if not self.read_axes(where=where, start=start, stop=stop):
return None
info = (
self.info.get(self.non_index_axes[0][0], dict())
if len(self.non_index_axes)
else dict()
)
index = self.index_axes[0].values
frames = []
for a in self.values_axes:
# we could have a multi-index constructor here
# ensure_index doesn't recognized our list-of-tuples here
if info.get("type") == "MultiIndex":
cols = MultiIndex.from_tuples(a.values)
else:
cols = Index(a.values)
names = info.get("names")
if names is not None:
cols.set_names(names, inplace=True)
if self.is_transposed:
values = a.cvalues
index_ = cols
cols_ = Index(index, name=getattr(index, "name", None))
else:
values = a.cvalues.T
index_ = Index(index, name=getattr(index, "name", None))
cols_ = cols
# if we have a DataIndexableCol, its shape will only be 1 dim
if values.ndim == 1 and isinstance(values, np.ndarray):
values = values.reshape((1, values.shape[0]))
if isinstance(values, np.ndarray):
df = DataFrame(values.T, columns=cols_, index=index_)
elif isinstance(values, Index):
df = DataFrame(values, columns=cols_, index=index_)
else:
# Categorical
df = DataFrame([values], columns=cols_, index=index_)
assert (df.dtypes == values.dtype).all(), (df.dtypes, values.dtype)
frames.append(df)
if len(frames) == 1:
df = frames[0]
else:
df = concat(frames, axis=1)
selection = Selection(self, where=where, start=start, stop=stop)
# apply the selection filters & axis orderings
df = self.process_axes(df, selection=selection, columns=columns)
return df
class AppendableSeriesTable(AppendableFrameTable):
""" support the new appendable table formats """
pandas_kind = "series_table"
table_type = "appendable_series"
ndim = 2
obj_type = Series
storage_obj_type = DataFrame
@property
def is_transposed(self) -> bool:
return False
def get_object(self, obj, transposed: bool):
return obj
def write(self, obj, data_columns=None, **kwargs):
""" we are going to write this as a frame table """
if not isinstance(obj, DataFrame):
name = obj.name or "values"
obj = obj.to_frame(name)
return super().write(obj=obj, data_columns=obj.columns.tolist(), **kwargs)
def read(
self,
where=None,
columns=None,
start: Optional[int] = None,
stop: Optional[int] = None,
):
is_multi_index = self.is_multi_index
if columns is not None and is_multi_index:
assert isinstance(self.levels, list) # needed for mypy
for n in self.levels:
if n not in columns:
columns.insert(0, n)
s = super().read(where=where, columns=columns, start=start, stop=stop)
if is_multi_index:
s.set_index(self.levels, inplace=True)
s = s.iloc[:, 0]
# remove the default name
if s.name == "values":
s.name = None
return s
class AppendableMultiSeriesTable(AppendableSeriesTable):
""" support the new appendable table formats """
pandas_kind = "series_table"
table_type = "appendable_multiseries"
def write(self, obj, **kwargs):
""" we are going to write this as a frame table """
name = obj.name or "values"
obj, self.levels = self.validate_multiindex(obj)
cols = list(self.levels)
cols.append(name)
obj.columns = cols
return super().write(obj=obj, **kwargs)
class GenericTable(AppendableFrameTable):
""" a table that read/writes the generic pytables table format """
pandas_kind = "frame_table"
table_type = "generic_table"
ndim = 2
obj_type = DataFrame
@property
def pandas_type(self) -> str:
return self.pandas_kind
@property
def storable(self):
return getattr(self.group, "table", None) or self.group
def get_attrs(self):
""" retrieve our attributes """
self.non_index_axes = []
self.nan_rep = None
self.levels = []
self.index_axes = [a.infer(self) for a in self.indexables if a.is_an_indexable]
self.values_axes = [
a.infer(self) for a in self.indexables if not a.is_an_indexable
]
self.data_columns = [a.name for a in self.values_axes]
@cache_readonly
def indexables(self):
""" create the indexables from the table description """
d = self.description
# the index columns is just a simple index
_indexables = [GenericIndexCol(name="index", axis=0)]
for i, n in enumerate(d._v_names):
assert isinstance(n, str)
dc = GenericDataIndexableCol(name=n, pos=i, values=[n])
_indexables.append(dc)
return _indexables
def write(self, **kwargs):
raise NotImplementedError("cannot write on an generic table")
class AppendableMultiFrameTable(AppendableFrameTable):
""" a frame with a multi-index """
table_type = "appendable_multiframe"
obj_type = DataFrame
ndim = 2
_re_levels = re.compile(r"^level_\d+$")
@property
def table_type_short(self) -> str:
return "appendable_multi"
def write(self, obj, data_columns=None, **kwargs):
if data_columns is None:
data_columns = []
elif data_columns is True:
data_columns = obj.columns.tolist()
obj, self.levels = self.validate_multiindex(obj)
for n in self.levels:
if n not in data_columns:
data_columns.insert(0, n)
return super().write(obj=obj, data_columns=data_columns, **kwargs)
def read(
self,
where=None,
columns=None,
start: Optional[int] = None,
stop: Optional[int] = None,
):
df = super().read(where=where, columns=columns, start=start, stop=stop)
df = df.set_index(self.levels)
# remove names for 'level_%d'
df.index = df.index.set_names(
[None if self._re_levels.search(l) else l for l in df.index.names]
)
return df
def _reindex_axis(obj, axis: int, labels: Index, other=None):
ax = obj._get_axis(axis)
labels = ensure_index(labels)
# try not to reindex even if other is provided
# if it equals our current index
if other is not None:
other = ensure_index(other)
if (other is None or labels.equals(other)) and labels.equals(ax):
return obj
labels = ensure_index(labels.unique())
if other is not None:
labels = ensure_index(other.unique()).intersection(labels, sort=False)
if not labels.equals(ax):
slicer: List[Union[slice, Index]] = [slice(None, None)] * obj.ndim
slicer[axis] = labels
obj = obj.loc[tuple(slicer)]
return obj
def _get_info(info, name):
""" get/create the info for this name """
try:
idx = info[name]
except KeyError:
idx = info[name] = dict()
return idx
# tz to/from coercion
def _get_tz(tz: tzinfo) -> Union[str, tzinfo]:
""" for a tz-aware type, return an encoded zone """
zone = timezones.get_timezone(tz)
return zone
def _set_tz(
values: Union[np.ndarray, Index],
tz: Optional[Union[str, tzinfo]],
coerce: bool = False,
) -> Union[np.ndarray, DatetimeIndex]:
"""
coerce the values to a DatetimeIndex if tz is set
preserve the input shape if possible
Parameters
----------
values : ndarray or Index
tz : str or tzinfo
coerce : if we do not have a passed timezone, coerce to M8[ns] ndarray
"""
if isinstance(values, DatetimeIndex):
# If values is tzaware, the tz gets dropped in the values.ravel()
# call below (which returns an ndarray). So we are only non-lossy
# if `tz` matches `values.tz`.
assert values.tz is None or values.tz == tz
if tz is not None:
name = getattr(values, "name", None)
values = values.ravel()
tz = timezones.get_timezone(_ensure_decoded(tz))
values = DatetimeIndex(values, name=name)
values = values.tz_localize("UTC").tz_convert(tz)
elif coerce:
values = np.asarray(values, dtype="M8[ns]")
return values
def _convert_index(name: str, index: Index, encoding=None, errors="strict"):
assert isinstance(name, str)
index_name = index.name
if isinstance(index, DatetimeIndex):
converted = index.asi8
return IndexCol(
name,
converted,
"datetime64",
_tables().Int64Col(),
freq=index.freq,
tz=index.tz,
index_name=index_name,
)
elif isinstance(index, TimedeltaIndex):
converted = index.asi8
return IndexCol(
name,
converted,
"timedelta64",
_tables().Int64Col(),
freq=index.freq,
index_name=index_name,
)
elif isinstance(index, (Int64Index, PeriodIndex)):
atom = _tables().Int64Col()
# avoid to store ndarray of Period objects
return IndexCol(
name,
index._ndarray_values,
"integer",
atom,
freq=getattr(index, "freq", None),
index_name=index_name,
)
if isinstance(index, MultiIndex):
raise TypeError("MultiIndex not supported here!")
inferred_type = lib.infer_dtype(index, skipna=False)
# we wont get inferred_type of "datetime64" or "timedelta64" as these
# would go through the DatetimeIndex/TimedeltaIndex paths above
values = np.asarray(index)
if inferred_type == "date":
converted = np.asarray([v.toordinal() for v in values], dtype=np.int32)
return IndexCol(
name, converted, "date", _tables().Time32Col(), index_name=index_name,
)
elif inferred_type == "string":
# atom = _tables().ObjectAtom()
# return np.asarray(values, dtype='O'), 'object', atom
converted = _convert_string_array(values, encoding, errors)
itemsize = converted.dtype.itemsize
return IndexCol(
name,
converted,
"string",
_tables().StringCol(itemsize),
index_name=index_name,
)
elif inferred_type == "integer":
# take a guess for now, hope the values fit
atom = _tables().Int64Col()
return IndexCol(
name,
np.asarray(values, dtype=np.int64),
"integer",
atom,
index_name=index_name,
)
elif inferred_type == "floating":
atom = _tables().Float64Col()
return IndexCol(
name,
np.asarray(values, dtype=np.float64),
"float",
atom,
index_name=index_name,
)
else:
atom = _tables().ObjectAtom()
return IndexCol(
name, np.asarray(values, dtype="O"), "object", atom, index_name=index_name,
)
def _unconvert_index(data, kind: str, encoding=None, errors="strict"):
index: Union[Index, np.ndarray]
if kind == "datetime64":
index = DatetimeIndex(data)
elif kind == "timedelta64":
index = TimedeltaIndex(data)
elif kind == "date":
try:
index = np.asarray([date.fromordinal(v) for v in data], dtype=object)
except (ValueError):
index = np.asarray([date.fromtimestamp(v) for v in data], dtype=object)
elif kind in ("integer", "float"):
index = np.asarray(data)
elif kind in ("string"):
index = _unconvert_string_array(
data, nan_rep=None, encoding=encoding, errors=errors
)
elif kind == "object":
index = np.asarray(data[0])
else: # pragma: no cover
raise ValueError(f"unrecognized index type {kind}")
return index
def _maybe_convert_for_string_atom(
name: str, block, existing_col, min_itemsize, nan_rep, encoding, errors
):
if not block.is_object:
return block.values
dtype_name = block.dtype.name
inferred_type = lib.infer_dtype(block.values, skipna=False)
if inferred_type == "date":
raise TypeError("[date] is not implemented as a table column")
elif inferred_type == "datetime":
# after GH#8260
# this only would be hit for a multi-timezone dtype which is an error
raise TypeError(
"too many timezones in this block, create separate data columns"
)
elif not (inferred_type == "string" or dtype_name == "object"):
return block.values
block = block.fillna(nan_rep, downcast=False)
if isinstance(block, list):
# Note: because block is always object dtype, fillna goes
# through a path such that the result is always a 1-element list
block = block[0]
data = block.values
# see if we have a valid string type
inferred_type = lib.infer_dtype(data.ravel(), skipna=False)
if inferred_type != "string":
# we cannot serialize this data, so report an exception on a column
# by column basis
for i in range(len(block.shape[0])):
col = block.iget(i)
inferred_type = lib.infer_dtype(col.ravel(), skipna=False)
if inferred_type != "string":
iloc = block.mgr_locs.indexer[i]
raise TypeError(
f"Cannot serialize the column [{iloc}] because\n"
f"its data contents are [{inferred_type}] object dtype"
)
# itemsize is the maximum length of a string (along any dimension)
data_converted = _convert_string_array(data, encoding, errors).reshape(data.shape)
assert data_converted.shape == block.shape, (data_converted.shape, block.shape)
itemsize = data_converted.itemsize
# specified min_itemsize?
if isinstance(min_itemsize, dict):
min_itemsize = int(min_itemsize.get(name) or min_itemsize.get("values") or 0)
itemsize = max(min_itemsize or 0, itemsize)
# check for column in the values conflicts
if existing_col is not None:
eci = existing_col.validate_col(itemsize)
if eci > itemsize:
itemsize = eci
data_converted = data_converted.astype(f"|S{itemsize}", copy=False)
return data_converted
def _convert_string_array(data, encoding, errors, itemsize=None):
"""
we take a string-like that is object dtype and coerce to a fixed size
string type
Parameters
----------
data : a numpy array of object dtype
encoding : None or string-encoding
errors : handler for encoding errors
itemsize : integer, optional, defaults to the max length of the strings
Returns
-------
data in a fixed-length string dtype, encoded to bytes if needed
"""
# encode if needed
if encoding is not None and len(data):
data = (
Series(data.ravel()).str.encode(encoding, errors).values.reshape(data.shape)
)
# create the sized dtype
if itemsize is None:
ensured = ensure_object(data.ravel())
itemsize = max(1, libwriters.max_len_string_array(ensured))
data = np.asarray(data, dtype=f"S{itemsize}")
return data
def _unconvert_string_array(data, nan_rep=None, encoding=None, errors="strict"):
"""
inverse of _convert_string_array
Parameters
----------
data : fixed length string dtyped array
nan_rep : the storage repr of NaN, optional
encoding : the encoding of the data, optional
errors : handler for encoding errors, default 'strict'
Returns
-------
an object array of the decoded data
"""
shape = data.shape
data = np.asarray(data.ravel(), dtype=object)
# guard against a None encoding (because of a legacy
# where the passed encoding is actually None)
encoding = _ensure_encoding(encoding)
if encoding is not None and len(data):
itemsize = libwriters.max_len_string_array(ensure_object(data))
dtype = f"U{itemsize}"
if isinstance(data[0], bytes):
data = Series(data).str.decode(encoding, errors=errors).values
else:
data = data.astype(dtype, copy=False).astype(object, copy=False)
if nan_rep is None:
nan_rep = "nan"
data = libwriters.string_array_replace_from_nan_rep(data, nan_rep)
return data.reshape(shape)
def _maybe_convert(values: np.ndarray, val_kind, encoding, errors):
val_kind = _ensure_decoded(val_kind)
if _need_convert(val_kind):
conv = _get_converter(val_kind, encoding, errors)
# conv = np.frompyfunc(conv, 1, 1)
values = conv(values)
return values
def _get_converter(kind: str, encoding, errors):
if kind == "datetime64":
return lambda x: np.asarray(x, dtype="M8[ns]")
elif kind == "string":
return lambda x: _unconvert_string_array(x, encoding=encoding, errors=errors)
else: # pragma: no cover
raise ValueError(f"invalid kind {kind}")
def _need_convert(kind) -> bool:
if kind in ("datetime64", "string"):
return True
return False
class Selection:
"""
Carries out a selection operation on a tables.Table object.
Parameters
----------
table : a Table object
where : list of Terms (or convertible to)
start, stop: indices to start and/or stop selection
"""
def __init__(
self,
table: Table,
where=None,
start: Optional[int] = None,
stop: Optional[int] = None,
):
self.table = table
self.where = where
self.start = start
self.stop = stop
self.condition = None
self.filter = None
self.terms = None
self.coordinates = None
if is_list_like(where):
# see if we have a passed coordinate like
try:
inferred = lib.infer_dtype(where, skipna=False)
if inferred == "integer" or inferred == "boolean":
where = np.asarray(where)
if where.dtype == np.bool_:
start, stop = self.start, self.stop
if start is None:
start = 0
if stop is None:
stop = self.table.nrows
self.coordinates = np.arange(start, stop)[where]
elif issubclass(where.dtype.type, np.integer):
if (self.start is not None and (where < self.start).any()) or (
self.stop is not None and (where >= self.stop).any()
):
raise ValueError(
"where must have index locations >= start and < stop"
)
self.coordinates = where
except ValueError:
pass
if self.coordinates is None:
self.terms = self.generate(where)
# create the numexpr & the filter
if self.terms is not None:
self.condition, self.filter = self.terms.evaluate()
def generate(self, where):
""" where can be a : dict,list,tuple,string """
if where is None:
return None
q = self.table.queryables()
try:
return PyTablesExpr(where, queryables=q, encoding=self.table.encoding)
except NameError:
# raise a nice message, suggesting that the user should use
# data_columns
qkeys = ",".join(q.keys())
raise ValueError(
f"The passed where expression: {where}\n"
" contains an invalid variable reference\n"
" all of the variable references must be a "
"reference to\n"
" an axis (e.g. 'index' or 'columns'), or a "
"data_column\n"
f" The currently defined references are: {qkeys}\n"
)
def select(self):
"""
generate the selection
"""
if self.condition is not None:
return self.table.table.read_where(
self.condition.format(), start=self.start, stop=self.stop
)
elif self.coordinates is not None:
return self.table.table.read_coordinates(self.coordinates)
return self.table.table.read(start=self.start, stop=self.stop)
def select_coords(self):
"""
generate the selection
"""
start, stop = self.start, self.stop
nrows = self.table.nrows
if start is None:
start = 0
elif start < 0:
start += nrows
if self.stop is None:
stop = nrows
elif stop < 0:
stop += nrows
if self.condition is not None:
return self.table.table.get_where_list(
self.condition.format(), start=start, stop=stop, sort=True
)
elif self.coordinates is not None:
return self.coordinates
return np.arange(start, stop)
|
the-stack_106_26710 | prisonCell = ""
windows = int(input("Please enter the amount of windows in your home: "))
if windows < 0:
print("\nI'm pretty sure thats impossible")
elif windows == 0:
print("\nI'm beginning to suspect you live\nin some kind of military compound")
elif windows == 1:
prisonCell = (str(input("\nDo you live in a prison cell?: ")))
elif(windows >= 30):
print("\nYou must have one of\nthose new fangled\nglass houses")
else:
print("\nYou have over one window\nyou must be doing well in life")
if prisonCell == 'yes' or prisonCell == 'Yes':
print("\nOk")
elif prisonCell == 'maybe' or prisonCell == 'Maybe':
print("Hmmmmm\n\nInteresting")
elif prisonCell == "":
print()
else:
print('\n"Sure"')
|
the-stack_106_26711 | import logging
import threading
import time
import message
import shared
class Advertiser(threading.Thread):
def __init__(self):
super().__init__(name='Advertiser')
def run(self):
while True:
time.sleep(0.4)
if shared.shutting_down:
logging.debug('Shutting down Advertiser')
break
self._advertise_vectors()
self._advertise_addresses()
@staticmethod
def _advertise_vectors():
vectors_to_advertise = set()
while not shared.vector_advertise_queue.empty():
vectors_to_advertise.add(shared.vector_advertise_queue.get())
if len(vectors_to_advertise) > 0:
for c in shared.connections.copy():
if c.status == 'fully_established':
c.send_queue.put(message.Inv(vectors_to_advertise))
@staticmethod
def _advertise_addresses():
addresses_to_advertise = set()
while not shared.address_advertise_queue.empty():
addr = shared.address_advertise_queue.get()
if addr.port == 'i2p':
# We should not try to construct Addr messages with I2P destinations (yet)
continue
addresses_to_advertise.add(addr)
if len(addresses_to_advertise) > 0:
for c in shared.connections.copy():
if c.status == 'fully_established':
c.send_queue.put(message.Addr(addresses_to_advertise))
|
the-stack_106_26714 | #!/usr/bin/env python
# An example of building a state machine in ROS.
#
# state_machine.py
#
# Bill Smart
#
# This code is an example of how to put together a state machine in ROS using smach. The
# state machine is defined in code, rather than in some description format, which gives it
# more flexibility. Note that, although we're setting this up as a node, it doesn't really
# do anything particular to ROS.
import rospy
import sys
# Import the smach, the state machine handler.
import smach
# Import the ROS interface to smach, which includes the visualizer, and some other useful stuff.
import smach_ros
# Smach states are Python classes, which inherit from smach.State.
class PrintState(smach.State):
"""
Create state. This is a very simple example of a state that simply prints a string to the info log
channel.
"""
def __init__(self, text):
# This line calls the constructor on the base class, eumerating the possible outcomes of the state.
# If you don't include this line, then the state machine will not work.
smach.State.__init__(self, outcomes=['printed'])
# Initialize anything that's specific to your state here.
self.text = text
def execute(self, userdata):
"""
Function that is called when the state becomes active. The state ceases to be active when this
function returns. Control will pass to the next state in the FSM, according to the return value.
"""
rospy.loginfo(self.text)
# You have to return one of the strings that's enumerated in the outcomes parameter passed to the
# smach.State base class.
return 'printed'
if __name__ == '__main__':
# Initialize the node, as usual.
rospy.init_node('basic_state_machine', argv=sys.argv)
# Make a state machine, and enumerate all of the return values (outcomes) it can have.
state_machine = smach.StateMachine(outcomes=['done'])
# Open the state machine context with a with statement. Everything in the indent block below the with
# statement will apply to this state machine. it's possible to have more than one state machine in a
# single node, although only one can be active at a time.
with state_machine:
# Add a state to the state machine, giving a name, a State subclass instance, and a dictionary that
# specifies what happens on the possible transition values.
smach.StateMachine.add('State 1', PrintState('First state'), transitions={'printed':'State 2'})
# Since this State subclass transitions to done (a string passed as an outcome for the state machine),
# that will end the state machine execution.
smach.StateMachine.add('State 2', PrintState('Second state'), transitions={'printed':'done'})
# Start up an introspection server, so that we can look at the state machine in smach_viewer.
sis = smach_ros.IntrospectionServer('simple_state_machine', state_machine, '/STATE_MACHINE_ROOT')
sis.start()
# Start up the state machine.
final_outcome = state_machine.execute()
# We're going to put in a spin() just to keep the node alive, so we can look at the state machine structure.
rospy.spin()
|
the-stack_106_26715 | import argparse
import gensim
import json
import numpy as np
import os
import torch
from nltk.tokenize import word_tokenize
from tqdm import tqdm
from models import InferSent
def transform_sentences(_sentences, _model, _pretrained):
_model.cuda()
if _pretrained == 'ft':
W2V_PATH = 'fastText/crawl-300d-2M.vec'
elif _pretrained == 'glove':
W2V_PATH = 'GloVe/glove.840B.300d.txt'
_model.set_w2v_path(W2V_PATH)
_model.build_vocab(_sentences, tokenize=True)
embeddings = infersent.encode(sentences, tokenize=True, verbose=True)
_sent_tensors = [torch.from_numpy(j) for j in embeddings]
return torch.stack(_sent_tensors)
if __name__ == "__main__":
parser = argparse.ArgumentParser(prog="build_glove_space",
description="Builds sentence embeddings from the GloVe model")
parser.add_argument('-s', '--set', required=True, type=str,
help='The dataset name', dest='data')
parser.add_argument('-v', '--version', required=True, type=int,
help='The InferSent model version', dest='v')
parser.add_argument('-p', '--pretrained', required=True, type=str,
help='The pretrained vector set', dest='p')
args = parser.parse_args()
wd = os.path.normpath(os.getcwd() + os.sep + os.pardir + os.sep + os.pardir + os.sep + os.pardir)
if args.data == 'riedel':
sentence_path = os.path.join(wd, "data", "RESIDE", "riedel_data", "sentence_mapper.json")
with open(sentence_path, 'rb') as f:
sentences = json.load(f)
elif args.data == 'gids':
sentence_path = os.path.join(wd, "data", "GIDS", "gids_data", "sentence_mapper.json")
with open(sentence_path, 'rb') as f:
sentences = json.load(f)
print('Loading InferSent model...')
MODEL_PATH = 'encoder/infersent{n}.pkl'.format(n=args.v)
params_model = {'bsize': 256, 'word_emb_dim': 300, 'enc_lstm_dim': 2048,
'pool_type': 'max', 'dpout_model': 0.0, 'version': args.v}
infersent = InferSent(params_model)
infersent.load_state_dict(torch.load(MODEL_PATH))
print('Building sentence representations')
sent_space = transform_sentences(sentences, infersent, args.p)
torch.save(sent_space, '{d}_infersent{v}{p}_space.pt'.format(d=args.data,
v=args.v,
p=args.p))
print(sent_space.shape)
|
the-stack_106_26717 | import pytest
from tests.unit_tests.test_resources.mock_for_querybuilder_tests import all_query_builders
from sokannonser.repository.platsannonser import transform_platsannons_query_stats_result
from tests.test_resources.stats import region_stats, region_stats_result, municipality_stats, municipality_stats_result, \
country_stats, country_stats_result, occupation_field_stats, occupation_field_stats_result, occupation_group_stats, \
occupation_group_stats_result, occupation_name_stats, occupation_name_stats_result
pytestmark = pytest.mark.unit
@pytest.mark.parametrize("mock_query_builder", all_query_builders)
@pytest.mark.parametrize("args, query_result, stats_result", [
({'stats': ['occupation-name']}, occupation_name_stats, occupation_name_stats_result),
({'stats': ['occupation-group']}, occupation_group_stats, occupation_group_stats_result),
({'stats': ['occupation-field']}, occupation_field_stats, occupation_field_stats_result),
({'stats': ['country']}, country_stats, country_stats_result),
({'stats': ['municipality']}, municipality_stats, municipality_stats_result),
({'stats': ['region']}, region_stats, region_stats_result)])
def test_stats_transform_platsannons_query_result(args, query_result, stats_result, mock_query_builder):
result = transform_platsannons_query_stats_result(args, query_result, mock_query_builder, {})
print(stats_result)
assert result.get('stats', stats_result) == stats_result
|
the-stack_106_26719 | # This code is part of Qiskit.
#
# (C) Copyright IBM 2018, 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
# pylint: disable=no-name-in-module,import-error
""" Test Operator construction, including OpPrimitives and singletons. """
import unittest
from test.python.opflow import QiskitOpflowTestCase
from ddt import ddt, data
import numpy
from qiskit.circuit import QuantumCircuit, Parameter
from qiskit.utils import QuantumInstance
from qiskit.opflow import (
StateFn, Zero, One, H, X, I, Z, Plus, Minus, CircuitSampler, ListOp
)
@ddt
class TestStateOpMeasEvals(QiskitOpflowTestCase):
"""Tests of evals of Meas-Operator-StateFn combos."""
def test_statefn_overlaps(self):
""" state functions overlaps test """
wf = (4 * StateFn({'101010': .5, '111111': .3})) + ((3 + .1j) * (Zero ^ 6))
wf_vec = StateFn(wf.to_matrix())
self.assertAlmostEqual(wf.adjoint().eval(wf), 14.45)
self.assertAlmostEqual(wf_vec.adjoint().eval(wf_vec), 14.45)
self.assertAlmostEqual(wf_vec.adjoint().eval(wf), 14.45)
self.assertAlmostEqual(wf.adjoint().eval(wf_vec), 14.45)
def test_wf_evals_x(self):
""" wf evals x test """
qbits = 4
wf = ((Zero ^ qbits) + (One ^ qbits)) * (1 / 2 ** .5)
# Note: wf = Plus^qbits fails because TensoredOp can't handle it.
wf_vec = StateFn(wf.to_matrix())
op = X ^ qbits
# op = I^6
self.assertAlmostEqual(wf.adjoint().eval(op.eval(wf)), 1)
self.assertAlmostEqual(wf_vec.adjoint().eval(op.eval(wf)), 1)
self.assertAlmostEqual(wf.adjoint().eval(op.eval(wf_vec)), 1)
self.assertAlmostEqual(wf_vec.adjoint().eval(op.eval(wf_vec)), 1)
# op = (H^X^Y)^2
op = H ^ 6
wf = ((Zero ^ 6) + (One ^ 6)) * (1 / 2 ** .5)
wf_vec = StateFn(wf.to_matrix())
# print(wf.adjoint().to_matrix() @ op.to_matrix() @ wf.to_matrix())
self.assertAlmostEqual(wf.adjoint().eval(op.eval(wf)), .25)
self.assertAlmostEqual(wf_vec.adjoint().eval(op.eval(wf)), .25)
self.assertAlmostEqual(wf.adjoint().eval(op.eval(wf_vec)), .25)
self.assertAlmostEqual(wf_vec.adjoint().eval(op.eval(wf_vec)), .25)
def test_coefficients_correctly_propagated(self):
"""Test that the coefficients in SummedOp and states are correctly used."""
try:
from qiskit.providers.aer import Aer
except Exception as ex: # pylint: disable=broad-except
self.skipTest("Aer doesn't appear to be installed. Error: '{}'".format(str(ex)))
return
with self.subTest('zero coeff in SummedOp'):
op = 0 * (I + Z)
state = Plus
self.assertEqual((~StateFn(op) @ state).eval(), 0j)
backend = Aer.get_backend('qasm_simulator')
q_instance = QuantumInstance(backend, seed_simulator=97, seed_transpiler=97)
op = I
with self.subTest('zero coeff in summed StateFn and CircuitSampler'):
state = 0 * (Plus + Minus)
sampler = CircuitSampler(q_instance).convert(~StateFn(op) @ state)
self.assertEqual(sampler.eval(), 0j)
with self.subTest('coeff gets squared in CircuitSampler shot-based readout'):
state = (Plus + Minus) / numpy.sqrt(2)
sampler = CircuitSampler(q_instance).convert(~StateFn(op) @ state)
self.assertAlmostEqual(sampler.eval(), 1+0j)
def test_is_measurement_correctly_propagated(self):
"""Test if is_measurement property of StateFn is propagated to converted StateFn."""
try:
from qiskit.providers.aer import Aer
except Exception as ex: # pylint: disable=broad-except
self.skipTest("Aer doesn't appear to be installed. Error: '{}'".format(str(ex)))
return
backend = Aer.get_backend('qasm_simulator')
q_instance = QuantumInstance(backend) # no seeds needed since no values are compared
state = Plus
sampler = CircuitSampler(q_instance).convert(~state @ state)
self.assertTrue(sampler.oplist[0].is_measurement)
def test_parameter_binding_on_listop(self):
"""Test passing a ListOp with differing parameters works with the circuit sampler."""
try:
from qiskit.providers.aer import Aer
except Exception as ex: # pylint: disable=broad-except
self.skipTest("Aer doesn't appear to be installed. Error: '{}'".format(str(ex)))
return
x, y = Parameter('x'), Parameter('y')
circuit1 = QuantumCircuit(1)
circuit1.p(0.2, 0)
circuit2 = QuantumCircuit(1)
circuit2.p(x, 0)
circuit3 = QuantumCircuit(1)
circuit3.p(y, 0)
bindings = {x: -0.4, y: 0.4}
listop = ListOp([StateFn(circuit) for circuit in [circuit1, circuit2, circuit3]])
sampler = CircuitSampler(Aer.get_backend('qasm_simulator'))
sampled = sampler.convert(listop, params=bindings)
self.assertTrue(all(len(op.parameters) == 0 for op in sampled.oplist))
def test_list_op_eval_coeff_with_nonlinear_combofn(self):
"""Test evaluating a ListOp with non-linear combo function works with coefficients."""
state = One
op = ListOp(5 * [I], coeff=2, combo_fn=numpy.prod)
expr1 = ~StateFn(op) @ state
expr2 = ListOp(5 * [~state @ I @ state], coeff=2, combo_fn=numpy.prod)
self.assertEqual(expr1.eval(), 2) # if the coeff is propagated too far the result is 4
self.assertEqual(expr2.eval(), 2)
def test_single_parameter_binds(self):
"""Test passing parameter binds as a dictionary to the circuit sampler."""
try:
from qiskit.providers.aer import Aer
except Exception as ex: # pylint: disable=broad-except
self.skipTest("Aer doesn't appear to be installed. Error: '{}'".format(str(ex)))
return
x = Parameter('x')
circuit = QuantumCircuit(1)
circuit.ry(x, 0)
expr = ~StateFn(H) @ StateFn(circuit)
sampler = CircuitSampler(Aer.get_backend('statevector_simulator'))
res = sampler.convert(expr, params={x: 0}).eval()
self.assertIsInstance(res, complex)
@data('all', 'last')
def test_circuit_sampler_caching(self, caching):
"""Test caching all operators works."""
try:
from qiskit.providers.aer import Aer
except Exception as ex: # pylint: disable=broad-except
self.skipTest("Aer doesn't appear to be installed. Error: '{}'".format(str(ex)))
return
x = Parameter('x')
circuit = QuantumCircuit(1)
circuit.ry(x, 0)
expr1 = ~StateFn(H) @ StateFn(circuit)
expr2 = ~StateFn(X) @ StateFn(circuit)
sampler = CircuitSampler(Aer.get_backend('statevector_simulator'), caching=caching)
res1 = sampler.convert(expr1, params={x: 0}).eval()
res2 = sampler.convert(expr2, params={x: 0}).eval()
res3 = sampler.convert(expr1, params={x: 0}).eval()
res4 = sampler.convert(expr2, params={x: 0}).eval()
self.assertEqual(res1, res3)
self.assertEqual(res2, res4)
if caching == 'last':
self.assertEqual(len(sampler._cached_ops.keys()), 1)
else:
self.assertEqual(len(sampler._cached_ops.keys()), 2)
if __name__ == '__main__':
unittest.main()
|
the-stack_106_26721 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright (c) 2013 Boris Pavlovic ([email protected]).
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from migrate.changeset import UniqueConstraint
from sqlalchemy import MetaData, Table
from nova.db.sqlalchemy import utils
UC_NAME = "uniq_task_name_x_host_x_period_beginning_x_period_ending"
COLUMNS = ('task_name', 'host', 'period_beginning', 'period_ending')
TABLE_NAME = 'task_log'
def upgrade(migrate_engine):
meta = MetaData(bind=migrate_engine)
t = Table(TABLE_NAME, meta, autoload=True)
utils.drop_old_duplicate_entries_from_table(migrate_engine, TABLE_NAME,
False, *COLUMNS)
uc = UniqueConstraint(*COLUMNS, table=t, name=UC_NAME)
uc.create()
def downgrade(migrate_engine):
utils.drop_unique_constraint(migrate_engine, TABLE_NAME, UC_NAME, *COLUMNS)
|
the-stack_106_26723 | #!/bin/env python3
"""
This script creates a canonicalized version of KG2 stored in TSV files, ready for import into neo4j. The TSVs are
created in the current working directory.
Usage: python3 create_canonicalized_kg_tsvs.py [--test]
"""
import argparse
import ast
import csv
import os
import sys
import time
import traceback
from datetime import datetime
from typing import List, Dict, Tuple, Union
from neo4j import GraphDatabase
sys.path.append(os.path.dirname(os.path.abspath(__file__))+"/../../") # code directory
from RTXConfiguration import RTXConfiguration
sys.path.append(os.path.dirname(os.path.abspath(__file__))+"/../../ARAX/NodeSynonymizer/")
from node_synonymizer import NodeSynonymizer
def _run_cypher_query(cypher_query: str, kg="KG2") -> List[Dict[str, any]]:
# This function sends a cypher query to neo4j (either KG1 or KG2) and returns results
rtxc = RTXConfiguration()
if kg == "KG2":
rtxc.live = "KG2"
try:
driver = GraphDatabase.driver(rtxc.neo4j_bolt, auth=(rtxc.neo4j_username, rtxc.neo4j_password))
with driver.session() as session:
print(f" Sending cypher query to {kg} neo4j..")
query_results = session.run(cypher_query).data()
print(f" Got {len(query_results)} results back from neo4j")
driver.close()
except Exception:
tb = traceback.format_exc()
error_type, error, _ = sys.exc_info()
print(f"ERROR: Encountered a problem interacting with {kg} neo4j. {tb}")
return []
else:
return query_results
def _convert_list_to_neo4j_format(input_list: List[any]) -> str:
return str(input_list).strip("[").strip("]").replace("'", "")
def _merge_two_lists(list_a: List[any], list_b: List[any]) -> List[any]:
return list(set(list_a + list_b))
def _literal_eval_list(input_item: Union[str, List[any]]) -> List[any]:
try:
actual_list = ast.literal_eval(input_item)
except Exception:
return []
else:
return actual_list
def _convert_strange_provided_by_field_to_list(provided_by_field):
# Needed temporarily until kg2-2+ is rolled out to production
provided_by_list = []
for item in provided_by_field:
if "[" in item:
item = item.replace("[", "")
if "]" in item:
item = item.replace("]", "")
if "'" in item:
item = item.replace("'", "")
provided_by_list.append(item)
return provided_by_list
def _canonicalize_nodes(nodes: List[Dict[str, any]]) -> Tuple[List[Dict[str, any]], Dict[str, str]]:
synonymizer = NodeSynonymizer()
node_ids = [node.get('id') for node in nodes if node.get('id')]
print(f" Sending NodeSynonymizer.get_canonical_curies() a list of {len(node_ids)} curies..")
canonicalized_info = synonymizer.get_canonical_curies(curies=node_ids, return_all_types=True)
print(f" Creating canonicalized nodes..")
curie_map = dict()
canonicalized_nodes = dict()
for node in nodes:
canonical_info = canonicalized_info.get(node['id'])
canonicalized_curie = canonical_info.get('preferred_curie', node['id']) if canonical_info else node['id']
node['publications'] = _literal_eval_list(node['publications']) # Only need to do this until kg2.2+ is rolled out
if canonicalized_curie in canonicalized_nodes:
existing_canonical_node = canonicalized_nodes[canonicalized_curie]
existing_canonical_node['publications'] = _merge_two_lists(existing_canonical_node['publications'], node['publications'])
else:
if canonical_info:
canonicalized_node = {
'id': canonicalized_curie,
'name': canonical_info.get('preferred_name', node['name']),
'types': list(canonical_info.get('all_types')),
'preferred_type': canonical_info.get('preferred_type', node['category_label']),
'publications': node['publications']
}
else:
canonicalized_node = {
'id': canonicalized_curie,
'name': node['name'],
'types': [node['category_label']],
'preferred_type': node['category_label'],
'publications': node['publications']
}
canonicalized_nodes[canonicalized_node['id']] = canonicalized_node
curie_map[node['id']] = canonicalized_curie # Record this mapping for easy lookup later
# Create a node containing information about this KG2C build
new_build_node = {'id': 'RTX:KG2C',
'name': f"KG2C:Build created on {datetime.now().strftime('%Y-%m-%d %H:%M')}",
'types': ['data_file'],
'preferred_type': 'data_file',
'publications': []}
canonicalized_nodes[new_build_node['id']] = new_build_node
# Decorate nodes with equivalent curies
print(f" Sending NodeSynonymizer.get_equivalent_nodes() a list of {len(canonicalized_nodes)} curies..")
equivalent_curies_dict = synonymizer.get_equivalent_nodes(list(canonicalized_nodes.keys()))
for curie, canonical_node in canonicalized_nodes.items():
equivalent_curies = []
equivalent_curies_dict_for_curie = equivalent_curies_dict.get(curie)
if equivalent_curies_dict_for_curie is not None:
for equivalent_curie in equivalent_curies_dict_for_curie:
equivalent_curies.append(equivalent_curie)
canonical_node['equivalent_curies'] = equivalent_curies
# Convert array fields into the format neo4j wants and do final processing
for canonicalized_node in canonicalized_nodes.values():
canonicalized_node['types'] = _convert_list_to_neo4j_format(canonicalized_node['types'])
canonicalized_node['publications'] = _convert_list_to_neo4j_format(canonicalized_node['publications'])
canonicalized_node['equivalent_curies'] = _convert_list_to_neo4j_format(canonicalized_node['equivalent_curies'])
canonicalized_node['preferred_type_for_conversion'] = canonicalized_node['preferred_type']
return list(canonicalized_nodes.values()), curie_map
def _remap_edges(edges: List[Dict[str, any]], curie_map: Dict[str, str], is_test: bool) -> List[Dict[str, any]]:
allowed_self_edges = ['positively_regulates', 'interacts_with', 'increase']
merged_edges = dict()
for edge in edges:
original_source_id = edge['subject']
original_target_id = edge['object']
if not is_test: # Make sure we don't wind up with any orphan edges
assert original_source_id in curie_map
assert original_target_id in curie_map
canonicalized_source_id = curie_map.get(original_source_id, original_source_id)
canonicalized_target_id = curie_map.get(original_target_id, original_target_id)
edge_type = edge['simplified_edge_label']
# Convert fields that should be lists to lists (only need to do this until kg2.2+ is rolled out to production)
edge['provided_by'] = _convert_strange_provided_by_field_to_list(edge['provided_by'])
edge['publications'] = _literal_eval_list(edge['publications'])
if canonicalized_source_id != canonicalized_target_id or edge_type in allowed_self_edges:
remapped_edge_key = f"{canonicalized_source_id}--{edge_type}--{canonicalized_target_id}"
if remapped_edge_key in merged_edges:
merged_edge = merged_edges[remapped_edge_key]
merged_edge['provided_by'] = _merge_two_lists(merged_edge['provided_by'], edge['provided_by'])
merged_edge['publications'] = _merge_two_lists(merged_edge['publications'], edge['publications'])
else:
new_remapped_edge = dict()
new_remapped_edge['subject'] = canonicalized_source_id
new_remapped_edge['object'] = canonicalized_target_id
new_remapped_edge['simplified_edge_label'] = edge['simplified_edge_label']
new_remapped_edge['provided_by'] = edge['provided_by']
new_remapped_edge['publications'] = edge['publications']
merged_edges[remapped_edge_key] = new_remapped_edge
# Convert array fields into the format neo4j wants and do final processing
for final_edge in merged_edges.values():
final_edge['provided_by'] = _convert_list_to_neo4j_format(final_edge['provided_by'])
final_edge['publications'] = _convert_list_to_neo4j_format(final_edge['publications'])
final_edge['simplified_edge_label_for_conversion'] = final_edge['simplified_edge_label']
final_edge['subject_for_conversion'] = final_edge['subject']
final_edge['object_for_conversion'] = final_edge['object']
return list(merged_edges.values())
def _modify_column_headers_for_neo4j(plain_column_headers: List[str]) -> List[str]:
modified_headers = []
array_columns = ['provided_by', 'types', 'equivalent_curies', 'publications']
for header in plain_column_headers:
if header in array_columns:
header = f"{header}:string[]"
elif header == 'id':
header = f"{header}:ID"
elif header == 'preferred_type_for_conversion':
header = ":LABEL"
elif header == 'subject_for_conversion':
header = ":START_ID"
elif header == 'object_for_conversion':
header = ":END_ID"
elif header == 'simplified_edge_label_for_conversion':
header = ":TYPE"
modified_headers.append(header)
return modified_headers
def create_canonicalized_tsvs(is_test=False):
# Grab the node data from KG2 neo4j and load it into TSVs
print(f" Starting nodes..")
nodes_query = f"match (n) return n.id as id, n.name as name, n.category_label as category_label, " \
f"n.publications as publications{' limit 20000' if is_test else ''}"
nodes = _run_cypher_query(nodes_query)
if nodes:
print(f" Canonicalizing nodes..")
canonicalized_nodes, curie_map = _canonicalize_nodes(nodes)
print(f" Canonicalized KG contains {len(canonicalized_nodes)} nodes ({round((len(canonicalized_nodes) / len(nodes)) * 100)}%)")
print(f" Creating nodes header file..")
column_headers = list(canonicalized_nodes[0].keys())
modified_headers = _modify_column_headers_for_neo4j(column_headers)
with open(f"{'test_' if is_test else ''}nodes_c_header.tsv", "w+") as nodes_header_file:
dict_writer = csv.DictWriter(nodes_header_file, modified_headers, delimiter='\t')
dict_writer.writeheader()
print(f" Creating nodes file..")
with open(f"{'test_' if is_test else ''}nodes_c.tsv", "w+") as nodes_file:
dict_writer = csv.DictWriter(nodes_file, column_headers, delimiter='\t')
dict_writer.writerows(canonicalized_nodes)
else:
print(f"ERROR: Couldn't get node data from KG2 neo4j.")
return
# Grab the edge data from KG2 neo4j and load it into TSVs
print(f" Starting edges..")
edges_query = f"match (n)-[e]->(m) return n.id as subject, m.id as object, e.simplified_edge_label as " \
f"simplified_edge_label, e.provided_by as provided_by, e.publications as publications" \
f"{' limit 20000' if is_test else ''}"
edges = _run_cypher_query(edges_query)
if edges:
print(f" Remapping edges..")
remapped_edges = _remap_edges(edges, curie_map, is_test)
print(f" Canonicalized KG contains {len(remapped_edges)} edges ({round((len(remapped_edges) / len(edges)) * 100)}%)")
print(f" Creating edges header file..")
column_headers = list(remapped_edges[0].keys())
modified_headers = _modify_column_headers_for_neo4j(column_headers)
with open(f"{'test_' if is_test else ''}edges_c_header.tsv", "w+") as edges_header_file:
dict_writer = csv.DictWriter(edges_header_file, modified_headers, delimiter='\t')
dict_writer.writeheader()
print(f" Creating edges file..")
with open(f"{'test_' if is_test else ''}edges_c.tsv", "w+") as edges_file:
dict_writer = csv.DictWriter(edges_file, column_headers, delimiter='\t')
dict_writer.writerows(remapped_edges)
else:
print(f"ERROR: Couldn't get edge data from KG2 neo4j.")
return
def main():
arg_parser = argparse.ArgumentParser(description="Creates a canonicalized KG2, stored in TSV files")
arg_parser.add_argument('--test', dest='test', action='store_true', default=False)
args = arg_parser.parse_args()
print(f"Starting to create canonicalized KG TSV files..")
start = time.time()
create_canonicalized_tsvs(args.test)
print(f"Done! Took {round((time.time() - start) / 60, 2)} minutes.")
if __name__ == "__main__":
main()
|
the-stack_106_26724 | """Tool to get AWS credentials from AWS STS when MFA is required to AWS CLI."""
from configparser import ConfigParser
from typing import (
Dict,
Optional
)
from sys import (
exit,
stderr
)
import json
import os
import subprocess
def get_aws_credentials(
aws_profile: str,
aws_config_file: str,
mfa_credentials_file: str,
aws_mfa_token: Optional[str] = None
) -> Dict[str, str]:
"""Get AWS credentials for a given profile.
Parameters
----------
aws_profile : str
Profile name in the AWS config/mfa files.
aws_config_file : str
AWS config file with MFA serial for the profile.
mfa_credentials_file : str
MFA credentials file to access AWS STS for the profile.
aws_mfa_token : Optional[str], optional
MFA token for AWS STS, by default None (it will be asked).
Returns
-------
Dict[str, str]
AWS Session credentials for the profile.
"""
config = ConfigParser()
config.read(aws_config_file)
try:
profile = config[aws_profile]
except KeyError:
print(f"AWS profile {aws_profile} not found at {aws_config_file}.", file=stderr)
exit(-1)
try:
mfa_serial = profile["mfa_serial"]
except KeyError:
print(f"AWS profile {aws_profile} does not have mfa_serial configured at {aws_config_file}", file=stderr)
exit(-1)
mfa_token = input(f"MFA token for profile {aws_profile}: ") if aws_mfa_token is None else aws_mfa_token
# Delete any AWS environment variable in place
env_vars = os.environ.copy()
aws_keys = [key for key in env_vars.keys() if key.startswith("AWS_")]
for key in aws_keys:
del env_vars[key]
# AWS credentials file with access keys for the profile MFA
env_vars["AWS_SHARED_CREDENTIALS_FILE"] = mfa_credentials_file
# Get the session token
proc = subprocess.Popen(
[
"aws", "sts", "get-session-token",
"--profile", aws_profile,
"--serial-number", mfa_serial,
"--token-code", mfa_token
],
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
env=env_vars
)
data, _ = proc.communicate()
if proc.returncode != 0:
print(f"Get session token for profile {aws_profile} failed: {data.decode('utf-8')}.", file=stderr)
exit(-1)
# Get temporary credentials
credentials = json.loads(data.decode("utf-8"))["Credentials"]
return credentials
def save_credentials(aws_profile: str, aws_credentials: Dict[str, str], credentials_file: str) -> None:
"""Save the session credentials into the AWS credential file.
Parameters
----------
aws_profile : str
AWS profile name in the credentials file.
aws_credentials : Dict[str, str]
AWS Session credentials for the profile.
credentials_file : str
AWS credentials file location.
"""
aws_file = ConfigParser()
aws_file.read(credentials_file)
aws_file[aws_profile] = aws_credentials
with open(credentials_file, "w") as f:
aws_file.write(f)
print(f"AWS credentials file {credentials_file} for profile {aws_profile} updated.")
|
the-stack_106_26732 | #!/usr/bin/env python
# Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""git drover: A tool for merging changes to release branches."""
import argparse
import pickle
import functools
import logging
import os
import re
import shutil
import subprocess
import sys
import tempfile
import git_common
class Error(Exception):
pass
_PATCH_ERROR_MESSAGE = """Patch failed to apply.
A workdir for this cherry-pick has been created in
{0}
To continue, resolve the conflicts there and run
git drover --continue {0}
To abort this cherry-pick run
git drover --abort {0}
"""
class PatchError(Error):
"""An error indicating that the patch failed to apply."""
def __init__(self, workdir):
super(PatchError, self).__init__(_PATCH_ERROR_MESSAGE.format(workdir))
_DEV_NULL_FILE = open(os.devnull, 'w')
if os.name == 'nt':
# This is a just-good-enough emulation of os.symlink for drover to work on
# Windows. It uses junctioning of directories (most of the contents of
# the .git directory), but copies files. Note that we can't use
# CreateSymbolicLink or CreateHardLink here, as they both require elevation.
# Creating reparse points is what we want for the directories, but doing so
# is a relatively messy set of DeviceIoControl work at the API level, so we
# simply shell to `mklink /j` instead.
def emulate_symlink_windows(source, link_name):
if os.path.isdir(source):
subprocess.check_call(['mklink', '/j',
link_name.replace('/', '\\'),
source.replace('/', '\\')],
shell=True)
else:
shutil.copy(source, link_name)
mk_symlink = emulate_symlink_windows
else:
mk_symlink = os.symlink
class _Drover(object):
def __init__(self, branch, revision, parent_repo, dry_run, verbose):
self._branch = branch
self._branch_ref = 'refs/remotes/branch-heads/%s' % branch
self._revision = revision
self._parent_repo = os.path.abspath(parent_repo)
self._dry_run = dry_run
self._workdir = None
self._branch_name = None
self._needs_cleanup = True
self._verbose = verbose
self._process_options()
def _process_options(self):
if self._verbose:
logging.getLogger().setLevel(logging.DEBUG)
@classmethod
def resume(cls, workdir):
"""Continues a cherry-pick that required manual resolution.
Args:
workdir: A string containing the path to the workdir used by drover.
"""
drover = cls._restore_drover(workdir)
drover._continue()
@classmethod
def abort(cls, workdir):
"""Aborts a cherry-pick that required manual resolution.
Args:
workdir: A string containing the path to the workdir used by drover.
"""
drover = cls._restore_drover(workdir)
drover._cleanup()
@staticmethod
def _restore_drover(workdir):
"""Restores a saved drover state contained within a workdir.
Args:
workdir: A string containing the path to the workdir used by drover.
"""
try:
with open(os.path.join(workdir, '.git', 'drover'), 'rb') as f:
drover = pickle.load(f)
drover._process_options()
return drover
except (IOError, pickle.UnpicklingError):
raise Error('%r is not git drover workdir' % workdir)
def _continue(self):
if os.path.exists(os.path.join(self._workdir, '.git', 'CHERRY_PICK_HEAD')):
self._run_git_command(
['commit', '--no-edit'],
error_message='All conflicts must be resolved before continuing')
if self._upload_and_land():
# Only clean up the workdir on success. The manually resolved cherry-pick
# can be reused if the user cancels before landing.
self._cleanup()
def run(self):
"""Runs this Drover instance.
Raises:
Error: An error occurred while attempting to cherry-pick this change.
"""
try:
self._run_internal()
finally:
self._cleanup()
def _run_internal(self):
self._check_inputs()
if not self._confirm('Going to cherry-pick\n"""\n%s"""\nto %s.' % (
self._run_git_command(['show', '-s', self._revision]), self._branch)):
return
self._create_checkout()
self._perform_cherry_pick()
self._upload_and_land()
def _cleanup(self):
if not self._needs_cleanup:
return
if self._workdir:
logging.debug('Deleting %s', self._workdir)
if os.name == 'nt':
try:
# Use rmdir to properly handle the junctions we created.
subprocess.check_call(
['rmdir', '/s', '/q', self._workdir], shell=True)
except subprocess.CalledProcessError:
logging.error(
'Failed to delete workdir %r. Please remove it manually.',
self._workdir)
else:
shutil.rmtree(self._workdir)
self._workdir = None
if self._branch_name:
self._run_git_command(['branch', '-D', self._branch_name])
@staticmethod
def _confirm(message):
"""Show a confirmation prompt with the given message.
Returns:
A bool representing whether the user wishes to continue.
"""
result = ''
while result not in ('y', 'n'):
try:
result = input('%s Continue (y/n)? ' % message)
except EOFError:
result = 'n'
return result == 'y'
def _check_inputs(self):
"""Check the input arguments and ensure the parent repo is up to date."""
if not os.path.isdir(self._parent_repo):
raise Error('Invalid parent repo path %r' % self._parent_repo)
self._run_git_command(['--help'], error_message='Unable to run git')
self._run_git_command(['status'],
error_message='%r is not a valid git repo' %
os.path.abspath(self._parent_repo))
self._run_git_command(['fetch', 'origin'],
error_message='Failed to fetch origin')
self._run_git_command(
['rev-parse', '%s^{commit}' % self._branch_ref],
error_message='Branch %s not found' % self._branch_ref)
self._run_git_command(
['rev-parse', '%s^{commit}' % self._revision],
error_message='Revision "%s" not found' % self._revision)
FILES_TO_LINK = [
'refs',
'logs/refs',
'info/refs',
'info/exclude',
'objects',
'hooks',
'packed-refs',
'remotes',
'rr-cache',
]
FILES_TO_COPY = ['config', 'HEAD']
def _create_checkout(self):
"""Creates a checkout to use for cherry-picking.
This creates a checkout similarly to git-new-workdir. Most of the .git
directory is shared with the |self._parent_repo| using symlinks. This
differs from git-new-workdir in that the config is forked instead of shared.
This is so the new workdir can be a sparse checkout without affecting
|self._parent_repo|.
"""
parent_git_dir = os.path.join(self._parent_repo, self._run_git_command(
['rev-parse', '--git-dir']).strip())
self._workdir = tempfile.mkdtemp(prefix='drover_%s_' % self._branch)
logging.debug('Creating checkout in %s', self._workdir)
git_dir = os.path.join(self._workdir, '.git')
git_common.make_workdir_common(parent_git_dir, git_dir, self.FILES_TO_LINK,
self.FILES_TO_COPY, mk_symlink)
self._run_git_command(['config', 'core.sparsecheckout', 'true'])
with open(os.path.join(git_dir, 'info', 'sparse-checkout'), 'w') as f:
f.write('/codereview.settings')
branch_name = os.path.split(self._workdir)[-1]
self._run_git_command(['checkout', '-b', branch_name, self._branch_ref])
self._branch_name = branch_name
def _perform_cherry_pick(self):
try:
self._run_git_command(['cherry-pick', '-x', self._revision],
error_message='Patch failed to apply')
except Error:
self._prepare_manual_resolve()
self._save_state()
self._needs_cleanup = False
raise PatchError(self._workdir)
def _save_state(self):
"""Saves the state of this Drover instances to the workdir."""
with open(os.path.join(self._workdir, '.git', 'drover'), 'wb') as f:
pickle.dump(self, f)
def _prepare_manual_resolve(self):
"""Prepare the workdir for the user to manually resolve the cherry-pick."""
# Files that have been deleted between branch and cherry-pick will not have
# their skip-worktree bit set so set it manually for those files to avoid
# git status incorrectly listing them as unstaged deletes.
repo_status = self._run_git_command(
['-c', 'core.quotePath=false', 'status', '--porcelain']).splitlines()
extra_files = [f[3:] for f in repo_status if f[:2] == ' D']
if extra_files:
self._run_git_command_with_stdin(
['update-index', '--skip-worktree', '--stdin'],
stdin='\n'.join(extra_files) + '\n')
def _upload_and_land(self):
if self._dry_run:
logging.info('--dry_run enabled; not landing.')
return True
self._run_git_command(['reset', '--hard'])
author = self._run_git_command(['log', '-1', '--format=%ae']).strip()
self._run_git_command(['cl', 'upload', '--send-mail', '--tbrs', author],
error_message='Upload failed',
interactive=True)
if not self._confirm('About to land on %s.' % self._branch):
return False
self._run_git_command(['cl', 'land', '--bypass-hooks'], interactive=True)
return True
def _run_git_command(self, args, error_message=None, interactive=False):
"""Runs a git command.
Args:
args: A list of strings containing the args to pass to git.
error_message: A string containing the error message to report if the
command fails.
interactive: A bool containing whether the command requires user
interaction. If false, the command will be provided with no input and
the output is captured.
Returns:
stdout as a string, or stdout interleaved with stderr if self._verbose
Raises:
Error: The command failed to complete successfully.
"""
cwd = self._workdir if self._workdir else self._parent_repo
logging.debug('Running git %s (cwd %r)', ' '.join('%s' % arg
for arg in args), cwd)
run = subprocess.check_call if interactive else subprocess.check_output
# Discard stderr unless verbose is enabled.
stderr = None if self._verbose else _DEV_NULL_FILE
try:
return run(['git'] + args, shell=False, cwd=cwd, stderr=stderr)
except (OSError, subprocess.CalledProcessError) as e:
if error_message:
raise Error(error_message)
else:
raise Error('Command %r failed: %s' % (' '.join(args), e))
def _run_git_command_with_stdin(self, args, stdin):
"""Runs a git command with a provided stdin.
Args:
args: A list of strings containing the args to pass to git.
stdin: A string to provide on stdin.
Returns:
stdout as a string, or stdout interleaved with stderr if self._verbose
Raises:
Error: The command failed to complete successfully.
"""
cwd = self._workdir if self._workdir else self._parent_repo
logging.debug('Running git %s (cwd %r)', ' '.join('%s' % arg
for arg in args), cwd)
# Discard stderr unless verbose is enabled.
stderr = None if self._verbose else _DEV_NULL_FILE
try:
popen = subprocess.Popen(['git'] + args, shell=False, cwd=cwd,
stderr=stderr, stdin=subprocess.PIPE)
popen.communicate(stdin)
if popen.returncode != 0:
raise Error('Command %r failed' % ' '.join(args))
except OSError as e:
raise Error('Command %r failed: %s' % (' '.join(args), e))
def cherry_pick_change(branch, revision, parent_repo, dry_run, verbose=False):
"""Cherry-picks a change into a branch.
Args:
branch: A string containing the release branch number to which to
cherry-pick.
revision: A string containing the revision to cherry-pick. It can be any
string that git-rev-parse can identify as referring to a single
revision.
parent_repo: A string containing the path to the parent repo to use for this
cherry-pick.
dry_run: A bool containing whether to stop before uploading the
cherry-pick cl.
verbose: A bool containing whether to print verbose logging.
Raises:
Error: An error occurred while attempting to cherry-pick |cl| to |branch|.
"""
drover = _Drover(branch, revision, parent_repo, dry_run, verbose)
drover.run()
def continue_cherry_pick(workdir):
"""Continues a cherry-pick that required manual resolution.
Args:
workdir: A string containing the path to the workdir used by drover.
"""
_Drover.resume(workdir)
def abort_cherry_pick(workdir):
"""Aborts a cherry-pick that required manual resolution.
Args:
workdir: A string containing the path to the workdir used by drover.
"""
_Drover.abort(workdir)
def main():
parser = argparse.ArgumentParser(
description='Cherry-pick a change into a release branch.')
group = parser.add_mutually_exclusive_group(required=True)
parser.add_argument(
'--branch',
type=str,
metavar='<branch>',
help='the name of the branch to which to cherry-pick; e.g. 1234')
group.add_argument(
'--cherry-pick',
type=str,
metavar='<change>',
help=('the change to cherry-pick; this can be any string '
'that unambiguously refers to a revision not involving HEAD'))
group.add_argument(
'--continue',
type=str,
nargs='?',
dest='resume',
const=os.path.abspath('.'),
metavar='path_to_workdir',
help='Continue a drover cherry-pick after resolving conflicts')
group.add_argument('--abort',
type=str,
nargs='?',
const=os.path.abspath('.'),
metavar='path_to_workdir',
help='Abort a drover cherry-pick')
parser.add_argument(
'--parent_checkout',
type=str,
default=os.path.abspath('.'),
metavar='<path_to_parent_checkout>',
help=('the path to the chromium checkout to use as the source for a '
'creating git-new-workdir workdir to use for cherry-picking; '
'if unspecified, the current directory is used'))
parser.add_argument(
'--dry-run',
action='store_true',
default=False,
help=("don't actually upload and land; "
"just check that cherry-picking would succeed"))
parser.add_argument('-v',
'--verbose',
action='store_true',
default=False,
help='show verbose logging')
options = parser.parse_args()
try:
if options.resume:
_Drover.resume(options.resume)
elif options.abort:
_Drover.abort(options.abort)
else:
if not options.branch:
parser.error('argument --branch is required for --cherry-pick')
cherry_pick_change(options.branch, options.cherry_pick,
options.parent_checkout, options.dry_run,
options.verbose)
except Error as e:
print('Error:', e.message)
sys.exit(128)
if __name__ == '__main__':
main()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.