code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
edgepaths = super(Graph, self).edgepaths
edgepaths.crs = self.crs
return edgepaths | def edgepaths(self) | Returns the fixed EdgePaths or computes direct connections
between supplied nodes. | 7.074056 | 5.901814 | 1.198624 |
edgepaths = super(TriMesh, self).edgepaths
edgepaths.crs = self.crs
return edgepaths | def edgepaths(self) | Returns the fixed EdgePaths or computes direct connections
between supplied nodes. | 7.514316 | 6.962255 | 1.079293 |
reader = Reader(shapefile)
return cls.from_records(reader.records(), *args, **kwargs) | def from_shapefile(cls, shapefile, *args, **kwargs) | Loads a shapefile from disk and optionally merges
it with a dataset. See ``from_records`` for full
signature.
Parameters
----------
records: list of cartopy.io.shapereader.Record
Iterator containing Records.
dataset: holoviews.Dataset
Any HoloViews ... | 3.894839 | 10.101747 | 0.385561 |
if dataset is not None and not on:
raise ValueError('To merge dataset with shapes mapping '
'must define attribute(s) to merge on.')
if util.pd and isinstance(dataset, util.pd.DataFrame):
dataset = Dataset(dataset)
if not isinstance... | def from_records(cls, records, dataset=None, on=None, value=None,
index=[], drop_missing=False, element=None, **kwargs) | Load data from a collection of `cartopy.io.shapereader.Record`
objects and optionally merge it with a dataset to assign
values to each polygon and form a chloropleth. Supplying just
records will return an NdOverlayof Shape Elements with a
numeric index. If a dataset is supplied, a mappin... | 3.119084 | 2.898668 | 1.07604 |
plot = plot or cb.plot
if isinstance(plot, GeoOverlayPlot):
plots = [get_cb_plot(cb, p) for p in plot.subplots.values()]
plots = [p for p in plots if any(s in cb.streams and getattr(s, '_triggering', False)
for s in p.streams)]
if plots:
... | def get_cb_plot(cb, plot=None) | Finds the subplot with the corresponding stream. | 4.201634 | 3.676056 | 1.142973 |
if not all(a in msg for a in attributes):
return True
plot = get_cb_plot(cb)
return (not getattr(plot, 'geographic', False) or
not hasattr(plot.current_frame, 'crs')) | def skip(cb, msg, attributes) | Skips applying transforms if data is not geographic. | 6.916313 | 5.864422 | 1.179368 |
if skip(cb, msg, attributes):
return msg
plot = get_cb_plot(cb)
x0, x1 = msg.get('x_range', (0, 1000))
y0, y1 = msg.get('y_range', (0, 1000))
extents = x0, y0, x1, y1
x0, y0, x1, y1 = project_extents(extents, plot.projection,
plot.current_frame.... | def project_ranges(cb, msg, attributes) | Projects ranges supplied by a callback. | 2.981854 | 3.033801 | 0.982877 |
if skip(cb, msg, attributes): return msg
plot = get_cb_plot(cb)
x, y = msg.get('x', 0), msg.get('y', 0)
crs = plot.current_frame.crs
coordinates = crs.transform_points(plot.projection, np.array([x]), np.array([y]))
msg['x'], msg['y'] = coordinates[0, :2]
return {k: v for k, v in msg.ite... | def project_point(cb, msg, attributes=('x', 'y')) | Projects a single point supplied by a callback | 3.237332 | 3.303154 | 0.980073 |
stream = cb.streams[0]
old_data = stream.data
stream.update(data=msg['data'])
element = stream.element
stream.update(data=old_data)
proj = cb.plot.projection
if not isinstance(element, _Element) or element.crs == proj:
return None
crs = element.crs
element.crs = proj
... | def project_drawn(cb, msg) | Projects a drawn element to the declared coordinate system | 6.116119 | 5.991758 | 1.020755 |
deleted = []
for f in cls._files:
try:
os.remove(f)
deleted.append(f)
except FileNotFoundError:
pass
print('Deleted %d weight files' % len(deleted))
cls._files = [] | def clean_weight_files(cls) | Cleans existing weight files. | 2.940858 | 2.810874 | 1.046243 |
result = None
if hasattr(el, 'crs'):
result = (int(el._auxiliary_component), el.crs)
return result | def _get_projection(el) | Get coordinate reference system from non-auxiliary elements.
Return value is a tuple of a precedence integer and the projection,
to allow non-auxiliary components to take precedence. | 10.23632 | 5.38085 | 1.902361 |
proj = self.projection
if self.global_extent and range_type in ('combined', 'data'):
(x0, x1), (y0, y1) = proj.x_limits, proj.y_limits
return (x0, y0, x1, y1)
extents = super(ProjectionPlot, self).get_extents(element, ranges, range_type)
if not getattr(el... | def get_extents(self, element, ranges, range_type='combined') | Subclasses the get_extents method using the GeoAxes
set_extent method to project the extents to the
Elements coordinate reference system. | 3.044012 | 2.922024 | 1.041748 |
lons = lons.astype(np.float64)
return ((lons - base + period * 2) % period) + base | def wrap_lons(lons, base, period) | Wrap longitude values into the range between base and base+period. | 4.113277 | 3.933217 | 1.045779 |
x, y = coord_names
geom = geom_dict['geometry']
new_dict = {k: v for k, v in geom_dict.items() if k != 'geometry'}
array = geom_to_array(geom)
new_dict[x] = array[:, 0]
new_dict[y] = array[:, 1]
if geom.geom_type == 'Polygon':
holes = []
for interior in geom.interiors:
... | def geom_dict_to_array_dict(geom_dict, coord_names=['Longitude', 'Latitude']) | Converts a dictionary containing an geometry key to a dictionary
of x- and y-coordinate arrays and if present a list-of-lists of
hole array. | 1.925053 | 1.805533 | 1.066196 |
interface = polygons.interface.datatype
if interface == 'geodataframe':
return [row.to_dict() for _, row in polygons.data.iterrows()]
elif interface == 'geom_dictionary':
return polygons.data
polys = []
xdim, ydim = polygons.kdims
has_holes = polygons.has_holes
holes = ... | def polygons_to_geom_dicts(polygons, skip_invalid=True) | Converts a Polygons element into a list of geometry dictionaries,
preserving all value dimensions.
For array conversion the following conventions are applied:
* Any nan separated array are converted into a MultiPolygon
* Any array without nans is converted to a Polygon
* If there are holes associa... | 2.965796 | 2.970835 | 0.998304 |
interface = path.interface.datatype
if interface == 'geodataframe':
return [row.to_dict() for _, row in path.data.iterrows()]
elif interface == 'geom_dictionary':
return path.data
geoms = []
invalid = False
xdim, ydim = path.kdims
for i, path in enumerate(path.split(dat... | def path_to_geom_dicts(path, skip_invalid=True) | Converts a Path element into a list of geometry dictionaries,
preserving all value dimensions. | 3.302156 | 3.268219 | 1.010384 |
if isinstance(geom, sgeom.Polygon) and not geom.exterior.is_ccw:
geom = sgeom.polygon.orient(geom)
return geom | def to_ccw(geom) | Reorients polygon to be wound counter-clockwise. | 3.614331 | 3.499156 | 1.032915 |
if geom.geom_type == 'Point':
return 1
if hasattr(geom, 'exterior'):
geom = geom.exterior
if not geom.geom_type.startswith('Multi') and hasattr(geom, 'array_interface_base'):
return len(geom.array_interface_base['data'])//2
else:
length = 0
for g in geom:
... | def geom_length(geom) | Calculates the length of coordinates in a shapely geometry. | 3.086004 | 3.054782 | 1.010221 |
if len(element.vdims) > 1:
xs, ys = (element.dimension_values(i, False, False)
for i in range(2))
zs = np.dstack([element.dimension_values(i, False, False)
for i in range(2, 2+len(element.vdims))])
else:
xs, ys, zs = (element.dimension_value... | def geo_mesh(element) | Get mesh data from a 2D Element ensuring that if the data is
on a cylindrical coordinate system and wraps globally that data
actually wraps around. | 2.664939 | 2.613713 | 1.019599 |
import pyproj
if isinstance(crs, pyproj.Proj):
out = crs
elif isinstance(crs, dict) or isinstance(crs, basestring):
try:
out = pyproj.Proj(crs)
except RuntimeError:
try:
out = pyproj.Proj(init=crs)
except RuntimeError:
... | def check_crs(crs) | Checks if the crs represents a valid grid, projection or ESPG string.
(Code copied from https://github.com/fmaussion/salem)
Examples
--------
>>> p = check_crs('+units=m +init=epsg:26915')
>>> p.srs
'+units=m +init=epsg:26915 '
>>> p = check_crs('wrong')
>>> p is None
True
Retu... | 2.308523 | 2.54701 | 0.906366 |
import cartopy.crs as ccrs
try:
from osgeo import osr
has_gdal = True
except ImportError:
has_gdal = False
proj = check_crs(proj)
if proj.is_latlong():
return ccrs.PlateCarree()
srs = proj.srs
if has_gdal:
# this is more robust, as srs could b... | def proj_to_cartopy(proj) | Converts a pyproj.Proj to a cartopy.crs.Projection
(Code copied from https://github.com/fmaussion/salem)
Parameters
----------
proj: pyproj.Proj
the projection to convert
Returns
-------
a cartopy.crs.Projection object | 1.998262 | 1.989196 | 1.004558 |
try:
import cartopy.crs as ccrs
import geoviews as gv # noqa
import pyproj
except:
raise ImportError('Geographic projection support requires GeoViews and cartopy.')
if crs is None:
return ccrs.PlateCarree()
if isinstance(crs, basestring) and crs.lower().sta... | def process_crs(crs) | Parses cartopy CRS definitions defined in one of a few formats:
1. EPSG codes: Defined as string of the form "EPSG: {code}" or an integer
2. proj.4 string: Defined as string of the form "{proj.4 string}"
3. cartopy.crs.CRS instance
4. None defaults to crs.PlateCaree | 2.856904 | 2.610278 | 1.094483 |
try:
import xarray as xr
except:
raise ImportError('Loading tiffs requires xarray to be installed')
with warnings.catch_warnings():
warnings.filterwarnings('ignore')
da = xr.open_rasterio(filename)
return from_xarray(da, crs, apply_transform, nan_nodata, **kwargs) | def load_tiff(filename, crs=None, apply_transform=False, nan_nodata=False, **kwargs) | Returns an RGB or Image element loaded from a geotiff file.
The data is loaded using xarray and rasterio. If a crs attribute
is present on the loaded data it will attempt to decode it into
a cartopy projection otherwise it will default to a non-geographic
HoloViews element.
Parameters
--------... | 2.629839 | 2.938559 | 0.894942 |
if crs:
kwargs['crs'] = crs
elif hasattr(da, 'crs'):
try:
kwargs['crs'] = process_crs(da.crs)
except:
param.main.warning('Could not decode projection from crs string %r, '
'defaulting to non-geographic element.' % da.crs)
c... | def from_xarray(da, crs=None, apply_transform=False, nan_nodata=False, **kwargs) | Returns an RGB or Image element given an xarray DataArray
loaded using xr.open_rasterio.
If a crs attribute is present on the loaded data it will
attempt to decode it into a cartopy projection otherwise it
will default to a non-geographic HoloViews element.
Parameters
----------
da: xarray... | 2.630765 | 2.527446 | 1.040879 |
if not isinstance(self.handles.get('artist'), GoogleTiles):
self.handles['artist'].remove() | def teardown_handles(self) | If no custom update_handles method is supplied this method
is called to tear down any previous handles before replacing
them. | 16.722113 | 17.011747 | 0.982974 |
for i, g in enumerate(geoms):
if g is geom:
return i | def find_geom(geom, geoms) | Returns the index of a geometry in a list of geometries avoiding
expensive equality checks of `in` operator. | 3.656793 | 3.433084 | 1.065163 |
area_fraction = min(bounds.area/domain.area, 1)
return int(min(round(np.log2(1/area_fraction)), levels)) | def compute_zoom_level(bounds, domain, levels) | Computes a zoom level given a bounds polygon, a polygon of the
overall domain and the number of zoom levels to divide the data
into.
Parameters
----------
bounds: shapely.geometry.Polygon
Polygon representing the area of the current viewport
domain: shapely.geometry.Polygon
Poly... | 5.280281 | 6.114902 | 0.86351 |
x0, y0, x1, y1 = bounds
return Polygon([(x0, y0), (x1, y0), (x1, y1), (x0, y1)]) | def bounds_to_poly(bounds) | Constructs a shapely Polygon from the provided bounds tuple.
Parameters
----------
bounds: tuple
Tuple representing the (left, bottom, right, top) coordinates
Returns
-------
polygon: shapely.geometry.Polygon
Shapely Polygon geometry of the bounds | 1.788991 | 2.874707 | 0.622321 |
tile_source = mapping['tile_source']
level = properties.pop('level', 'underlay')
renderer = plot.add_tile(tile_source, level=level)
renderer.alpha = properties.get('alpha', 1)
# Remove save tool
plot.tools = [t for t in plot.tools if not isinstance(t, SaveTool)]... | def _init_glyph(self, plot, mapping, properties) | Returns a Bokeh glyph object. | 4.419827 | 4.147783 | 1.065588 |
try:
plan = json.loads(open(self.args.plan_file_path).read())
return plan_to_assignment(plan)
except IOError:
self.log.exception(
'Given json file {file} not found.'
.format(file=self.args.plan_file_path),
)
... | def get_assignment(self) | Parse the given json plan in dict format. | 2.514736 | 2.199722 | 1.143206 |
# encoders / decoders do not maintain ordering currently
# so we need to keep this so we can rebuild order before returning
original_ordering = [(p.topic, p.partition) for p in payloads]
retries = 0
broker = None
while not broker:
try:
... | def _send_consumer_aware_request(self, group, payloads, encoder_fn, decoder_fn) | Send a list of requests to the consumer coordinator for the group
specified using the supplied encode/decode functions. As the payloads
that use consumer-aware requests do not contain the group (e.g.
OffsetFetchRequest), all payloads must be for a single group.
Arguments:
group: ... | 4.352613 | 4.348905 | 1.000853 |
with ZK(cluster_config) as zk:
brokers = sorted(list(zk.get_brokers().items()), key=itemgetter(0))
return [(id, data['host']) for id, data in brokers] | def get_broker_list(cluster_config) | Returns a list of brokers in the form [(id: host)]
:param cluster_config: the configuration of the cluster
:type cluster_config: map | 4.512273 | 4.712114 | 0.95759 |
filter_by_set = set(filter_by)
return [(id, host) for id, host in brokers if id in filter_by_set] | def filter_broker_list(brokers, filter_by) | Returns sorted list, a subset of elements from brokers in the form [(id, host)].
Passing empty list for filter_by will return empty list.
:param brokers: list of brokers to filter, assumes the data is in so`rted order
:type brokers: list of (id, host)
:param filter_by: the list of ids of brokers to kee... | 3.561453 | 2.98993 | 1.191149 |
session = FuturesSession()
for host in hosts:
url = "http://{host}:{port}/{prefix}/read/{key}".format(
host=host,
port=jolokia_port,
prefix=jolokia_prefix,
key=UNDER_REPL_KEY,
)
yield host, session.get(url) | def generate_requests(hosts, jolokia_port, jolokia_prefix) | Return a generator of requests to fetch the under replicated
partition number from the specified hosts.
:param hosts: list of brokers ip addresses
:type hosts: list of strings
:param jolokia_port: HTTP port for Jolokia
:type jolokia_port: integer
:param jolokia_prefix: HTTP prefix on the server... | 3.51214 | 3.398395 | 1.03347 |
under_replicated = 0
missing_brokers = 0
for host, request in generate_requests(hosts, jolokia_port, jolokia_prefix):
try:
response = request.result()
if 400 <= response.status_code <= 599:
print("Got status code {0}. Exiting.".format(response.status_code... | def read_cluster_status(hosts, jolokia_port, jolokia_prefix) | Read and return the number of under replicated partitions and
missing brokers from the specified hosts.
:param hosts: list of brokers ip addresses
:type hosts: list of strings
:param jolokia_port: HTTP port for Jolokia
:type jolokia_port: integer
:param jolokia_prefix: HTTP prefix on the server... | 3.200999 | 3.067932 | 1.043374 |
print("Will restart the following brokers in {0}:".format(cluster_config.name))
for id, host in brokers:
print(" {0}: {1}".format(id, host)) | def print_brokers(cluster_config, brokers) | Print the list of brokers that will be restarted.
:param cluster_config: the cluster configuration
:type cluster_config: map
:param brokers: the brokers that will be restarted
:type brokers: map of broker ids and host names | 3.995519 | 3.492829 | 1.143921 |
while True:
print("Do you want to restart these brokers? ", end="")
choice = input().lower()
if choice in ['yes', 'y']:
return True
elif choice in ['no', 'n']:
return False
else:
print("Please respond with 'yes' or 'no'") | def ask_confirmation() | Ask for confirmation to the user. Return true if the user confirmed
the execution, false otherwise.
:returns: bool | 2.833099 | 3.049378 | 0.929074 |
_, stdout, stderr = connection.sudo_command(start_command)
if verbose:
report_stdout(host, stdout)
report_stderr(host, stderr) | def start_broker(host, connection, start_command, verbose) | Execute the start | 3.987805 | 4.842483 | 0.823504 |
_, stdout, stderr = connection.sudo_command(stop_command)
if verbose:
report_stdout(host, stdout)
report_stderr(host, stderr) | def stop_broker(host, connection, stop_command, verbose) | Execute the stop | 3.874691 | 4.6792 | 0.828067 |
stable_counter = 0
max_checks = int(math.ceil(unhealthy_time_limit / check_interval))
for i in itertools.count():
partitions, brokers = read_cluster_status(
hosts,
jolokia_port,
jolokia_prefix,
)
if partitions or brokers:
stable_co... | def wait_for_stable_cluster(
hosts,
jolokia_port,
jolokia_prefix,
check_interval,
check_count,
unhealthy_time_limit,
) | Block the caller until the cluster can be considered stable.
:param hosts: list of brokers ip addresses
:type hosts: list of strings
:param jolokia_port: HTTP port for Jolokia
:type jolokia_port: integer
:param jolokia_prefix: HTTP prefix on the server for the Jolokia queries
:type jolokia_pref... | 2.835737 | 3.03534 | 0.93424 |
all_hosts = [b[1] for b in brokers]
for n, host in enumerate(all_hosts[skip:]):
with ssh(host=host, forward_agent=True, sudoable=True, max_attempts=3, max_timeout=2,
ssh_password=ssh_password) as connection:
execute_task(pre_stop_task, host)
wait_for_stable_... | def execute_rolling_restart(
brokers,
jolokia_port,
jolokia_prefix,
check_interval,
check_count,
unhealthy_time_limit,
skip,
verbose,
pre_stop_task,
post_stop_task,
start_command,
stop_command,
ssh_password=None
) | Execute the rolling restart on the specified brokers. It checks the
number of under replicated partitions on each broker, using Jolokia.
The check is performed at constant intervals, and a broker will be restarted
when all the brokers are answering and are reporting zero under replicated
partitions.
... | 2.526661 | 2.540288 | 0.994636 |
if opts.skip < 0 or opts.skip >= brokers_num:
print("Error: --skip must be >= 0 and < #brokers")
return True
if opts.check_count < 0:
print("Error: --check-count must be >= 0")
return True
if opts.unhealthy_time_limit < 0:
print("Error: --unhealthy-time-limit mus... | def validate_opts(opts, brokers_num) | Basic option validation. Returns True if the options are not valid,
False otherwise.
:param opts: the command line options
:type opts: map
:param brokers_num: the number of brokers
:type brokers_num: integer
:returns: bool | 2.179513 | 2.254951 | 0.966546 |
all_ids = set(broker_ids)
valid = True
for subset_id in subset_ids:
valid = valid and subset_id in all_ids
if subset_id not in all_ids:
print("Error: user specified broker id {0} does not exist in cluster.".format(subset_id))
return valid | def validate_broker_ids_subset(broker_ids, subset_ids) | Validate that user specified broker ids to restart exist in the broker ids retrieved
from cluster config.
:param broker_ids: all broker IDs in a cluster
:type broker_ids: list of integers
:param subset_ids: broker IDs specified by user
:type subset_ids: list of integers
:returns: bool | 3.057297 | 2.704661 | 1.130381 |
pre_stop_tasks = []
post_stop_tasks = []
task_to_task_args = dict(list(zip(tasks, task_args)))
tasks_classes = [PreStopTask, PostStopTask]
for func, task_args in task_to_task_args.items():
for task_class in tasks_classes:
imported_class = dynamic_import(func, task_class)
... | def get_task_class(tasks, task_args) | Reads in a list of tasks provided by the user,
loads the appropiate task, and returns two lists,
pre_stop_tasks and post_stop_tasks
:param tasks: list of strings locating tasks to load
:type tasks: list
:param task_args: list of strings to be used as args
:type task_args: list | 2.465314 | 2.389665 | 1.031656 |
self.cluster_config = cluster_config
self.args = args
with ZK(self.cluster_config) as self.zk:
self.log.debug(
'Starting %s for cluster: %s and zookeeper: %s',
self.__class__.__name__,
self.cluster_config.name,
... | def run(
self,
cluster_config,
rg_parser,
partition_measurer,
cluster_balancer,
args,
) | Initialize cluster_config, args, and zk then call run_command. | 3.462014 | 3.218931 | 1.075517 |
if self.should_execute():
result = self.zk.execute_plan(plan, allow_rf_change=allow_rf_change)
if not result:
self.log.error('Plan execution unsuccessful.')
sys.exit(1)
else:
self.log.info(
'Plan sen... | def execute_plan(self, plan, allow_rf_change=False) | Save proposed-plan and execute the same if requested. | 5.889122 | 5.320135 | 1.10695 |
return self.args.apply and (self.args.no_confirm or self.confirm_execution()) | def should_execute(self) | Confirm if proposed-plan should be executed. | 13.566002 | 8.516402 | 1.592926 |
in_progress_plan = self.zk.get_pending_plan()
if in_progress_plan:
in_progress_partitions = in_progress_plan['partitions']
self.log.info(
'Previous re-assignment in progress for {count} partitions.'
' Current partitions in re-assignment qu... | def is_reassignment_pending(self) | Return True if there are reassignment tasks pending. | 3.820988 | 3.765322 | 1.014784 |
new_assignment = cluster_topology.assignment
if (not original_assignment or not new_assignment or
max_partition_movements < 0 or max_leader_only_changes < 0 or
max_movement_size < 0):
return {}
# The replica set stays the same for leaders onl... | def get_reduced_assignment(
self,
original_assignment,
cluster_topology,
max_partition_movements,
max_leader_only_changes,
max_movement_size=DEFAULT_MAX_MOVEMENT_SIZE,
force_progress=False,
) | Reduce the assignment based on the total actions.
Actions represent actual partition movements
and/or changes in preferred leader.
Get the difference of original and proposed assignment
and take the subset of this plan for given limit.
Argument(s):
original_assignment: ... | 2.929633 | 2.889758 | 1.013799 |
# Group actions by topic
topic_actions = defaultdict(list)
for t_p, replica_change_cnt in movement_counts:
topic_actions[t_p[0]].append((t_p, replica_change_cnt))
# Create reduced assignment minimizing duplication of topics
extracted_actions = []
cur... | def _extract_actions_unique_topics(self, movement_counts, max_movements, cluster_topology, max_movement_size) | Extract actions limiting to given max value such that
the resultant has the minimum possible number of duplicate topics.
Algorithm:
1. Group actions by by topic-name: {topic: action-list}
2. Iterate through the dictionary in circular fashion and keep
extracting... | 3.216105 | 2.80882 | 1.145002 |
permit = ''
while permit.lower() not in ('yes', 'no'):
permit = input('Execute Proposed Plan? [yes/no] ')
if permit.lower() == 'yes':
return True
else:
return False | def confirm_execution(self) | Confirm from your if proposed-plan be executed. | 4.381073 | 3.063052 | 1.430296 |
with open(proposed_plan_file, 'w') as output:
json.dump(proposed_layout, output) | def write_json_plan(self, proposed_layout, proposed_plan_file) | Dump proposed json plan to given output file for future usage. | 2.379903 | 2.247459 | 1.05893 |
# Replica set cannot be changed
assert(new_leader in self._replicas)
curr_leader = self.leader
idx = self._replicas.index(new_leader)
self._replicas[0], self._replicas[idx] = \
self._replicas[idx], self._replicas[0]
return curr_leader | def swap_leader(self, new_leader) | Change the preferred leader with one of
given replicas.
Note: Leaders for all the replicas of current
partition needs to be changed. | 3.627405 | 3.540813 | 1.024455 |
for i, broker in enumerate(self.replicas):
if broker == source:
self.replicas[i] = dest
return | def replace(self, source, dest) | Replace source broker with destination broker in replica set if found. | 5.553222 | 3.157984 | 1.758471 |
count = sum(
int(self.topic == partition.topic)
for partition in partitions
)
return count | def count_siblings(self, partitions) | Count siblings of partition in given partition-list.
:key-term:
sibling: partitions with same topic | 7.453388 | 7.331223 | 1.016664 |
kafka_client = KafkaToolClient(hosts, timeout=10)
kafka_client.load_metadata_for_topics()
topic_partitions = kafka_client.topic_partitions
resp = kafka_client.send_metadata_request()
for _, topic, partitions in resp.topics:
for partition_error, partition, leader, replicas, isr in parti... | def get_topic_partition_metadata(hosts) | Returns topic-partition metadata from Kafka broker.
kafka-python 1.3+ doesn't include partition metadata information in
topic_partitions so we extract it from metadata ourselves. | 3.013548 | 2.989979 | 1.007883 |
topic_data = zk.get_topics(partition_metadata.topic)
topic = partition_metadata.topic
partition = partition_metadata.partition
expected_replicas = set(topic_data[topic]['partitions'][str(partition)]['replicas'])
available_replicas = set(partition_metadata.replicas)
return expected_replicas ... | def get_unavailable_brokers(zk, partition_metadata) | Returns the set of unavailable brokers from the difference of replica
set of given partition to the set of available replicas. | 3.027192 | 2.482895 | 1.219218 |
metadata = get_topic_partition_metadata(cluster_config.broker_list)
affected_partitions = set()
if fetch_unavailable_brokers:
unavailable_brokers = set()
with ZK(cluster_config) as zk:
for partitions in metadata.values():
for partition_metadata in partitions.values():
... | def get_topic_partition_with_error(cluster_config, error, fetch_unavailable_brokers=False) | Fetches the metadata from the cluster and returns the set of
(topic, partition) tuples containing all the topic-partitions
currently affected by the specified error. It also fetches unavailable-broker list
if required. | 2.301897 | 2.181348 | 1.055264 |
topics = _verify_topics_and_partitions(kafka_client, topics, raise_on_error)
group_offset_reqs = [
OffsetFetchRequestPayload(topic, partition)
for topic, partitions in six.iteritems(topics)
for partition in partitions
]
group_offsets = {}
send_api = kafka_client.send... | def get_current_consumer_offsets(
kafka_client,
group,
topics,
raise_on_error=True,
) | Get current consumer offsets.
NOTE: This method does not refresh client metadata. It is up to the caller
to avoid using stale metadata.
If any partition leader is not available, the request fails for all the
other topics. This is the tradeoff of sending all topic requests in batch
and save both in... | 4.058604 | 3.933102 | 1.031909 |
topics = _verify_topics_and_partitions(
kafka_client,
topics,
raise_on_error,
)
highmark_offset_reqs = []
lowmark_offset_reqs = []
for topic, partitions in six.iteritems(topics):
# Batch watermark requests
for partition in partitions:
# Reque... | def get_topics_watermarks(kafka_client, topics, raise_on_error=True) | Get current topic watermarks.
NOTE: This method does not refresh client metadata. It is up to the caller
to use avoid using stale metadata.
If any partition leader is not available, the request fails for all the
other topics. This is the tradeoff of sending all topic requests in batch
and save bot... | 2.3188 | 2.372273 | 0.977459 |
kafka_client.load_metadata_for_topics()
return _commit_offsets_to_watermark(
kafka_client, group, topics,
HIGH_WATERMARK, raise_on_error,
) | def advance_consumer_offsets(
kafka_client,
group,
topics,
raise_on_error=True,
) | Advance consumer offsets to the latest message in the topic
partition (the high watermark).
This method shall refresh the client metadata prior to updating
the offsets.
If any partition leader is not available, the request fails for all the
other topics. This is the tradeoff of sending all topic r... | 6.217515 | 8.195325 | 0.758666 |
kafka_client.load_metadata_for_topics()
return _commit_offsets_to_watermark(
kafka_client, group, topics,
LOW_WATERMARK, raise_on_error,
) | def rewind_consumer_offsets(
kafka_client,
group,
topics,
raise_on_error=True,
) | Rewind consumer offsets to the earliest message in the topic
partition (the low watermark).
This method shall refresh the client metadata prior to updating
the offsets.
If any partition leader is not available, the request fails for all the
other topics. This is the tradeoff of sending all topic r... | 5.952087 | 7.559995 | 0.787314 |
valid_new_offsets = _verify_commit_offsets_requests(
kafka_client,
new_offsets,
raise_on_error
)
group_offset_reqs = [
OffsetCommitRequestPayload(
topic,
partition,
offset,
metadata='',
)
for topic, new_par... | def set_consumer_offsets(
kafka_client,
group,
new_offsets,
raise_on_error=True,
) | Set consumer offsets to the specified offsets.
This method does not validate the specified offsets, it is up to
the caller to specify valid offsets within a topic partition.
If any partition leader is not available, the request fails for all the
other topics. This is the tradeoff of sending all topic ... | 3.865835 | 3.920346 | 0.986095 |
result = {}
for topic, partition_offsets in six.iteritems(offsets):
result[topic] = _nullify_partition_offsets(partition_offsets)
return result | def nullify_offsets(offsets) | Modify offsets metadata so that the partition offsets
have null payloads.
:param offsets: dict {<topic>: {<partition>: <offset>}}
:returns: a dict topic: partition: offset | 3.510843 | 3.582564 | 0.979981 |
assert all(len(row) == len(headers) for row in table)
str_headers = [str(header) for header in headers]
str_table = [[str(cell) for cell in row] for row in table]
column_lengths = [
max(len(header), *(len(row[i]) for row in str_table))
for i, header in enumerate(str_headers)
]
... | def display_table(headers, table) | Print a formatted table.
:param headers: A list of header objects that are displayed in the first
row of the table.
:param table: A list of lists where each sublist is a row of the table.
The number of elements in each row should be equal to the number of
headers. | 1.775557 | 1.834997 | 0.967608 |
assert cluster_topologies
rg_ids = list(next(six.itervalues(cluster_topologies)).rgs.keys())
assert all(
set(rg_ids) == set(cluster_topology.rgs.keys())
for cluster_topology in six.itervalues(cluster_topologies)
)
rg_imbalances = [
stats.get_replication_group_imbalance... | def display_replica_imbalance(cluster_topologies) | Display replica replication-group distribution imbalance statistics.
:param cluster_topologies: A dictionary mapping a string name to a
ClusterTopology object. | 3.202173 | 3.140258 | 1.019717 |
broker_ids = list(next(six.itervalues(cluster_topologies)).brokers.keys())
assert all(
set(broker_ids) == set(cluster_topology.brokers.keys())
for cluster_topology in six.itervalues(cluster_topologies)
)
broker_partition_counts = [
stats.get_broker_partition_counts(
... | def display_partition_imbalance(cluster_topologies) | Display partition count and weight imbalance statistics.
:param cluster_topologies: A dictionary mapping a string name to a
ClusterTopology object. | 2.332075 | 2.277802 | 1.023827 |
broker_ids = list(next(six.itervalues(cluster_topologies)).brokers.keys())
assert all(
set(broker_ids) == set(cluster_topology.brokers.keys())
for cluster_topology in six.itervalues(cluster_topologies)
)
broker_leader_counts = [
stats.get_broker_leader_counts(
c... | def display_leader_imbalance(cluster_topologies) | Display leader count and weight imbalance statistics.
:param cluster_topologies: A dictionary mapping a string name to a
ClusterTopology object. | 2.271545 | 2.241678 | 1.013323 |
broker_ids = list(next(six.itervalues(cluster_topologies)).brokers.keys())
assert all(
set(broker_ids) == set(cluster_topology.brokers.keys())
for cluster_topology in six.itervalues(cluster_topologies)
)
topic_names = list(next(six.itervalues(cluster_topologies)).topics.keys())
... | def display_topic_broker_imbalance(cluster_topologies) | Display topic broker imbalance statistics.
:param cluster_topologies: A dictionary mapping a string name to a
ClusterTopology object. | 1.954299 | 1.982065 | 0.985991 |
movement_count, movement_size, leader_changes = \
stats.get_partition_movement_stats(ct, base_assignment)
print(
'Total partition movements: {movement_count}\n'
'Total partition movement size: {movement_size}\n'
'Total leader changes: {leader_changes}'
.format(
... | def display_movements_stats(ct, base_assignment) | Display how the amount of movement between two assignments.
:param ct: The cluster's ClusterTopology.
:param base_assignment: The cluster assignment to compare against. | 2.717394 | 2.971293 | 0.914549 |
curr_plan_list, new_plan_list, total_changes = plan_details
action_cnt = '\n[INFO] Total actions required {0}'.format(total_changes)
_log_or_display(to_log, action_cnt)
action_cnt = (
'[INFO] Total actions that will be executed {0}'
.format(len(new_plan_list))
)
_log_or_disp... | def display_assignment_changes(plan_details, to_log=True) | Display current and proposed changes in
topic-partition to replica layout over brokers. | 2.583836 | 2.431566 | 1.062622 |
data_mean = data_mean or mean(data)
return sum((x - data_mean) ** 2 for x in data) / len(data) | def variance(data, data_mean=None) | Return variance of a sequence of numbers.
:param data_mean: Precomputed mean of the sequence. | 2.176145 | 2.732102 | 0.796509 |
data_variance = data_variance or variance(data, data_mean)
return sqrt(data_variance) | def stdevp(data, data_mean=None, data_variance=None) | Return standard deviation of a sequence of numbers.
:param data_mean: Precomputed mean of the sequence.
:param data_variance: Precomputed variance of the sequence. | 3.231037 | 5.055966 | 0.639054 |
data_mean = data_mean or mean(data)
data_stdev = data_stdev or stdevp(data, data_mean)
if data_mean == 0:
return float("inf") if data_stdev != 0 else 0
else:
return data_stdev / data_mean | def coefficient_of_variation(data, data_mean=None, data_stdev=None) | Return the coefficient of variation (CV) of a sequence of numbers.
:param data_mean: Precomputed mean of the sequence.
:param data_stdevp: Precomputed stdevp of the
sequence. | 2.48282 | 2.443472 | 1.016103 |
net_imbalance = 0
opt_count, extra_allowed = \
compute_optimum(len(count_per_broker), sum(count_per_broker))
for count in count_per_broker:
extra_cnt, extra_allowed = \
get_extra_element_count(count, opt_count, extra_allowed)
net_imbalance += extra_cnt
return net... | def get_net_imbalance(count_per_broker) | Calculate and return net imbalance based on given count of
partitions or leaders per broker.
Net-imbalance in case of partitions implies total number of
extra partitions from optimal count over all brokers.
This is also implies, the minimum number of partition movements
required for overall balanci... | 4.019559 | 4.259558 | 0.943656 |
if curr_count > opt_count:
# We still can allow 1 extra count
if extra_allowed_cnt > 0:
extra_allowed_cnt -= 1
extra_cnt = curr_count - opt_count - 1
else:
extra_cnt = curr_count - opt_count
else:
extra_cnt = 0
return extra_cnt, extra_... | def get_extra_element_count(curr_count, opt_count, extra_allowed_cnt) | Evaluate and return extra same element count based on given values.
:key-term:
group: In here group can be any base where elements are place
i.e. replication-group while placing replicas (elements)
or brokers while placing partitions (elements).
element: Generic term for units wh... | 2.671592 | 2.995541 | 0.891856 |
tot_rgs = len(rgs)
extra_replica_cnt_per_rg = defaultdict(int)
for partition in partitions:
# Get optimal replica-count for each partition
opt_replica_cnt, extra_replicas_allowed = \
compute_optimum(tot_rgs, partition.replication_factor)
# Extra replica count for ea... | def get_replication_group_imbalance_stats(rgs, partitions) | Calculate extra replica count replica count over each replication-group
and net extra-same-replica count. | 3.513666 | 3.206758 | 1.095707 |
extra_partition_cnt_per_broker = defaultdict(int)
tot_brokers = len(brokers)
# Sort the brokers so that the iteration order is deterministic.
sorted_brokers = sorted(brokers, key=lambda b: b.id)
for topic in topics:
# Optimal partition-count per topic per broker
total_partition_... | def get_topic_imbalance_stats(brokers, topics) | Return count of topics and partitions on each broker having multiple
partitions of same topic.
:rtype dict(broker_id: same-topic-partition count)
Example:
Total-brokers (b1, b2): 2
Total-partitions of topic t1: 5
(b1 has 4 partitions), (b2 has 1 partition)
opt-count: 5/2 = 2
extra-count... | 3.390456 | 3.350086 | 1.012051 |
total_movements = 0
movements = {}
for prev_partition, prev_replicas in six.iteritems(prev_assignment):
curr_replicas = curr_assignment[prev_partition]
diff = len(set(curr_replicas) - set(prev_replicas))
if diff:
total_movements += diff
movements[prev_par... | def calculate_partition_movement(prev_assignment, curr_assignment) | Calculate the partition movements from initial to current assignment.
Algorithm:
For each partition in initial assignment
# If replica set different in current assignment:
# Get Difference in sets
:rtype: tuple
dict((partition, (from_broker_set, to_broker_set)), total_mo... | 2.359195 | 1.985886 | 1.187981 |
try:
with open(meta_properties_path, 'r') as f:
broker_id = _parse_meta_properties_file(f)
except IOError:
raise IOError(
"Cannot open meta.properties file: {path}"
.format(path=meta_properties_path),
)
except ValueError:
raise ValueEr... | def _read_generated_broker_id(meta_properties_path) | reads broker_id from meta.properties file.
:param string meta_properties_path: path for meta.properties file
:returns int: broker_id from meta_properties_path | 3.372839 | 3.401485 | 0.991578 |
# Path to the meta.properties file. This is used to read the automatic broker id
# if the given broker id is -1
META_FILE_PATH = "{data_path}/meta.properties"
if not data_path:
raise ValueError("You need to specify the data_path if broker_id == -1")
meta_properties_path = META_FILE_PA... | def get_broker_id(data_path) | This function will look into the data folder to get the automatically created
broker_id.
:param string data_path: the path to the kafka data folder
:returns int: the real broker_id | 5.013473 | 5.00839 | 1.001015 |
# Refresh client metadata. We do not use the topic list, because we
# don't want to accidentally create the topic if it does not exist.
# If Kafka is unavailable, let's retry loading client metadata
try:
kafka_client.load_metadata_for_topics()
except KafkaUnavailableError:
kafka... | def get_consumer_offsets_metadata(
kafka_client,
group,
topics,
raise_on_error=True,
) | This method:
* refreshes metadata for the kafka client
* fetches group offsets
* fetches watermarks
:param kafka_client: KafkaToolClient instance
:param group: group id
:param topics: list of topics
:param raise_on_error: if False the method ignores missing topics and
miss... | 3.206435 | 2.865121 | 1.119127 |
# Refresh client metadata. We do not use the topic list, because we
# don't want to accidentally create the topic if it does not exist.
# If Kafka is unavailable, let's retry loading client metadata
try:
kafka_client.load_metadata_for_topics()
except KafkaUnavailableError:
kafka... | def get_watermark_for_regex(
kafka_client,
topic_regex,
) | This method:
* refreshes metadata for the kafka client
* fetches watermarks
:param kafka_client: KafkaToolClient instance
:param topic: the topic regex
:returns: dict <topic>: [ConsumerPartitionOffsets] | 3.791303 | 3.708359 | 1.022367 |
# Refresh client metadata. We do not use the topic list, because we
# don't want to accidentally create the topic if it does not exist.
# If Kafka is unavailable, let's retry loading client metadata
try:
kafka_client.load_metadata_for_topics()
except KafkaUnavailableError:
kafka... | def get_watermark_for_topic(
kafka_client,
topic,
) | This method:
* refreshes metadata for the kafka client
* fetches watermarks
:param kafka_client: KafkaToolClient instance
:param topic: the topic
:returns: dict <topic>: [ConsumerPartitionOffsets] | 5.662444 | 5.430851 | 1.042644 |
result = dict()
for topic in topics:
partition_offsets = [
response[topic]
for response in offsets_responses
if topic in response
]
result[topic] = merge_partition_offsets(*partition_offsets)
return result | def merge_offsets_metadata(topics, *offsets_responses) | Merge the offset metadata dictionaries from multiple responses.
:param topics: list of topics
:param offsets_responses: list of dict topic: partition: offset
:returns: dict topic: partition: offset | 2.80848 | 2.822342 | 0.995088 |
output = dict()
for partition_offset in partition_offsets:
for partition, offset in six.iteritems(partition_offset):
prev_offset = output.get(partition, 0)
output[partition] = max(prev_offset, offset)
return output | def merge_partition_offsets(*partition_offsets) | Merge the partition offsets of a single topic from multiple responses.
:param partition_offsets: list of dict partition: offset
:returns: dict partition: offset | 2.328483 | 2.700565 | 0.862221 |
movement_count = 0
movement_size = 0
for partition in six.itervalues(self.cluster_topology.partitions):
count, size = self._rebalance_partition_replicas(
partition,
None if not max_movement_count
else max_movement_count - movem... | def rebalance_replicas(
self,
max_movement_count=None,
max_movement_size=None,
) | Balance replicas across replication-groups.
:param max_movement_count: The maximum number of partitions to move.
:param max_movement_size: The maximum total size of the partitions to move.
:returns: A 2-tuple whose first element is the number of partitions moved
and whose second el... | 2.231464 | 2.511375 | 0.888543 |
# Separate replication-groups into under and over replicated
total = partition.replication_factor
over_replicated_rgs, under_replicated_rgs = separate_groups(
list(self.cluster_topology.rgs.values()),
lambda g: g.count_replica(partition),
total,
... | def _rebalance_partition_replicas(
self,
partition,
max_movement_count=None,
max_movement_size=None,
) | Rebalance replication groups for given partition. | 2.525425 | 2.52126 | 1.001652 |
return max(
over_replicated_rgs,
key=lambda rg: rg.count_replica(partition),
) | def _elect_source_replication_group(
self,
over_replicated_rgs,
partition,
) | Decide source replication-group based as group with highest replica
count. | 5.229637 | 3.788797 | 1.38029 |
min_replicated_rg = min(
under_replicated_rgs,
key=lambda rg: rg.count_replica(partition),
)
# Locate under-replicated replication-group with lesser
# replica count than source replication-group
if min_replicated_rg.count_replica(partition) < repl... | def _elect_dest_replication_group(
self,
replica_count_source,
under_replicated_rgs,
partition,
) | Decide destination replication-group based on replica-count. | 3.289628 | 2.955546 | 1.113036 |
with open(json_file, 'r') as consumer_offsets_json:
try:
parsed_offsets = {}
parsed_offsets_data = json.load(consumer_offsets_json)
# Create new dict with partition-keys as integers
parsed_offsets['groupid'] = parsed_offsets_da... | def parse_consumer_offsets(cls, json_file) | Parse current offsets from json-file. | 2.921399 | 2.806733 | 1.040854 |
new_offsets = defaultdict(dict)
try:
for topic, partitions in six.iteritems(topic_partitions):
# Validate current offsets in range of low and highmarks
# Currently we only validate for positive offsets and warn
# if out of range of low... | def build_new_offsets(cls, client, topics_offset_data, topic_partitions, current_offsets) | Build complete consumer offsets from parsed current consumer-offsets
and lowmarks and highmarks from current-offsets for. | 2.522419 | 2.422934 | 1.04106 |
# Fetch current offsets
try:
consumer_group = parsed_consumer_offsets['groupid']
topics_offset_data = parsed_consumer_offsets['offsets']
topic_partitions = dict(
(topic, [partition for partition in offset_data.keys()])
for topi... | def restore_offsets(cls, client, parsed_consumer_offsets) | Fetch current offsets from kafka, validate them against given
consumer-offsets data and commit the new offsets.
:param client: Kafka-client
:param parsed_consumer_offsets: Parsed consumer offset data from json file
:type parsed_consumer_offsets: dict(group: dict(topic: partition-offsets... | 2.982885 | 2.907596 | 1.025894 |
tuple_list = list(tup)
for index, value in pairs:
tuple_list[index] = value
return tuple(tuple_list) | def tuple_replace(tup, *pairs) | Return a copy of a tuple with some elements replaced.
:param tup: The tuple to be copied.
:param pairs: Any number of (index, value) tuples where index is the index
of the item to replace and value is the new value of the item. | 2.676144 | 3.287306 | 0.814084 |
# timeit says that this is faster than a similar
tuple_list = list(tup)
for i, f in pairs:
tuple_list[i] = f(tuple_list[i])
return tuple(tuple_list) | def tuple_alter(tup, *pairs) | Return a copy of a tuple with some elements altered.
:param tup: The tuple to be copied.
:param pairs: Any number of (index, func) tuples where index is the index
of the item to alter and the new value is func(tup[index]). | 5.294024 | 5.300419 | 0.998793 |
tuple_list = list(tup)
for item in items:
tuple_list.remove(item)
return tuple(tuple_list) | def tuple_remove(tup, *items) | Return a copy of a tuple with some items removed.
:param tup: The tuple to be copied.
:param items: Any number of items. The first instance of each item will
be removed from the tuple. | 2.300543 | 3.386401 | 0.679347 |
error_msg = 'Positive integer required, {string} given.'.format(string=string)
try:
value = int(string)
except ValueError:
raise ArgumentTypeError(error_msg)
if value < 0:
raise ArgumentTypeError(error_msg)
return value | def positive_int(string) | Convert string to positive integer. | 2.292733 | 2.216361 | 1.034459 |
error_msg = 'Positive non-zero integer required, {string} given.'.format(string=string)
try:
value = int(string)
except ValueError:
raise ArgumentTypeError(error_msg)
if value <= 0:
raise ArgumentTypeError(error_msg)
return value | def positive_nonzero_int(string) | Convert string to positive integer greater than zero. | 2.427009 | 2.34596 | 1.034548 |
error_msg = 'Positive float required, {string} given.'.format(string=string)
try:
value = float(string)
except ValueError:
raise ArgumentTypeError(error_msg)
if value < 0:
raise ArgumentTypeError(error_msg)
return value | def positive_float(string) | Convert string to positive float. | 2.420738 | 2.331923 | 1.038086 |
return dict(list(set1.items()) + list(set2.items())) | def dict_merge(set1, set2) | Joins two dictionaries. | 2.749715 | 2.617035 | 1.050699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.