code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
bitmask = libnuma.numa_get_membind()
nodemask = nodemask_t()
libnuma.copy_bitmask_to_nodemask(bitmask, byref(nodemask))
libnuma.numa_bitmask_free(bitmask)
return numa_nodemask_to_set(nodemask) | def get_membind() | Returns the mask of nodes from which memory can currently be allocated.
@return: node mask
@rtype: C{set} | 4.259539 | 4.253446 | 1.001432 |
mask = set_to_numa_nodemask(nodemask)
tmp = bitmask_t()
tmp.maskp = cast(byref(mask), POINTER(c_ulong))
tmp.size = sizeof(nodemask_t) * 8
if libnuma.numa_run_on_node_mask(byref(tmp)) < 0:
raise RuntimeError() | def set_run_on_node_mask(nodemask) | Runs the current thread and its children only on nodes specified in nodemask.
They will not migrate to CPUs of other nodes until the node affinity is
reset with a new call to L{set_run_on_node_mask}.
@param nodemask: node mask
@type nodemask: C{set} | 5.42361 | 7.124516 | 0.76126 |
bitmask = libnuma.numa_get_run_node_mask()
nodemask = nodemask_t()
libnuma.copy_bitmask_to_nodemask(bitmask, byref(nodemask))
libnuma.numa_bitmask_free(bitmask)
return numa_nodemask_to_set(nodemask) | def get_run_on_node_mask() | Returns the mask of nodes that the current thread is allowed to run on.
@return: node mask
@rtype: C{set} | 3.940737 | 4.685587 | 0.841034 |
if node1 < 0 or node1 > get_max_node():
raise ValueError(node1)
if node2 < 0 or node2 > get_max_node():
raise ValueError(node2)
return libnuma.numa_distance(node1, node2) | def get_distance(node1, node2) | Reports the distance in the machine topology between two nodes.
The factors are a multiple of 10. It returns 0 when the distance cannot be determined. A node has
distance 10 to itself. Reporting the distance requires a Linux kernel version of 2.6.10 or newer.
@param node1: node idx
@type node1: C{in... | 2.97653 | 3.056218 | 0.973926 |
cpuset = cpu_set_t()
result = set()
libnuma.sched_getaffinity(pid, sizeof(cpu_set_t), byref(cpuset))
for i in range(0, sizeof(cpu_set_t)*8):
if __CPU_ISSET(i, cpuset):
result.add(i)
return result | def get_affinity(pid) | Returns the affinity mask of the process whose ID is pid.
@param pid: process PID (0 == current process)
@type pid: C{int}
@return: set of CPU ids
@rtype: C{set} | 4.680503 | 4.661216 | 1.004138 |
_cpuset = cpu_set_t()
__CPU_ZERO(_cpuset)
for i in cpuset:
if i in range(0, sizeof(cpu_set_t) * 8):
__CPU_SET(i, _cpuset)
if libnuma.sched_setaffinity(pid, sizeof(cpu_set_t), byref(_cpuset)) < 0:
raise RuntimeError() | def set_affinity(pid, cpuset) | Sets the CPU affinity mask of the process whose ID is pid to the value specified by mask.
If pid is zero, then the calling process is used.
@param pid: process PID (0 == current process)
@type pid: C{int}
@param cpuset: set of CPU ids
@type cpuset: C{set} | 4.685462 | 5.19269 | 0.902319 |
'''Render template lines.
Note: we only need to parse the namespace if we used variables in
this part of the template.
'''
return self._text.format_map(namespace.dictionary) \
if self._need_format else self._text | def render(self, namespace) | Render template lines.
Note: we only need to parse the namespace if we used variables in
this part of the template. | 15.753633 | 4.716376 | 3.340198 |
if cancel_transition:
self._cancel_active_transition()
if color is not None:
self._assert_is_color(color)
self._color = color
super().set(is_on, brightness, cancel_transition=False) | def set(self, is_on=None, brightness=None, color=None,
cancel_transition=True) | Set properties of the led simultaneously before updating pwm values.
:param is_on: On-off state of the led.
:param brightness: Brightness of the led.
:param color: Color of the led.
:param cancel_transition: Cancel active transitions. | 3.251596 | 3.914209 | 0.830716 |
dest_state = super()._prepare_transition(is_on,
brightness=brightness,
color=color)
# Handle transitions from off to on and changing color
if is_on and not self.is_on and color is not None... | def _prepare_transition(self, is_on=None, brightness=None, color=None) | Perform pre-transition tasks and construct the destination state.
:param is_on: The on-off state to transition to.
:param brightness: The brightness to transition to (0.0-1.0).
:param color: The color to transition to.
:return: The destination state of the transition. | 4.652802 | 5.035986 | 0.923911 |
values = []
if brightness is not None:
self._assert_is_brightness(brightness)
values.append((self.brightness, brightness))
if color is not None:
self._assert_is_color(color)
values += [(self.color[i] / 255, color[i] / 255) for i in range(... | def _transition_steps(self, brightness=None, color=None) | Get the maximum number of steps needed for a transition.
:param brightness: The brightness to transition to (0.0-1.0).
:param color: The color to transition to.
:return: The maximum number of steps. | 2.897392 | 3.038379 | 0.953598 |
if brightness is not None:
self._assert_is_brightness(brightness)
brightness = self._interpolate(self.brightness, brightness,
step, total_steps)
if color is not None:
self._assert_is_color(color)
color =... | def _transition_stage(self, step, total_steps,
brightness=None, color=None) | Get a transition stage at a specific step.
:param step: The current step.
:param total_steps: The total number of steps.
:param brightness: The brightness to transition to (0.0-1.0).
:param color: The color to transition to.
:return: The stage at the specific step. | 2.369506 | 2.669608 | 0.887586 |
if not isinstance(value, tuple) or len(value) != 3:
raise ValueError("Color must be a RGB tuple.")
if not all(0 <= x <= 255 for x in value):
raise ValueError("RGB values of color must be between 0 and 255.") | def _assert_is_color(value) | Assert that the given value is a valid brightness.
:param value: The value to check. | 2.480271 | 2.647082 | 0.936983 |
lambda_function = []
with open(python_file, 'r') as f:
lambda_function.extend(f.read().splitlines())
return awslambda.Code(ZipFile=(Join('\n', lambda_function))) | def lambda_from_file(python_file) | Reads a python file and returns a awslambda.Code object
:param python_file:
:return: | 4.474338 | 3.875876 | 1.154407 |
'''Render a 'true' or (if available) 'false' block based on a
boolean.'''
if (self._isbool and
namespace[self._evaluate]) or \
(not self._isbool and
namespace[self._evaluate](*[namespace[arg]
for arg in self._args])):
... | def render(self, namespace) | Render a 'true' or (if available) 'false' block based on a
boolean. | 5.651217 | 3.269744 | 1.728336 |
'''Set the correct render method (boolean or function call)
and read variables from the current line.
'''
m = self.__class__.RE_IF.match(lines.current)
if m is None:
raise DefineBlockError(
'Incorrect block definition at line {}, {}\nShould be '
... | def _compile(self, lines) | Set the correct render method (boolean or function call)
and read variables from the current line. | 7.639591 | 5.007232 | 1.525711 |
api = Client.instance().api
api.index(id).delete() | def remove(cls, id) | Deletes an index with id
:param id string/document-handle | 27.291571 | 22.913906 | 1.191048 |
api = Client.instance().api
index_details = {
'type': self.index_type_obj.type_name
}
extra_index_attributes = self.index_type_obj.get_extra_attributes()
for extra_attribute_key in extra_index_attributes:
extra_attribute_value = extra_index_at... | def save(self) | Creates this index in the collection if it hasn't been already created | 3.251821 | 2.875154 | 1.131008 |
'''Return macro or block name from the current line.'''
m = cls.RE_PASTE.match(lines.current)
if m is None:
raise MacroBlockUsageError(
'Incorrect macro or block usage at line {}, {}\nShould be '
'something like: #my_macro'.format(lines.pos, lines.curr... | def _compile(cls, lines) | Return macro or block name from the current line. | 8.926435 | 5.783948 | 1.543312 |
from matplotlib.pyplot import axis, colorbar, figure, gca
img = asarray(img)
if (nans is True) and (img.dtype != bool):
img = nan_to_num(img)
if ax is None:
f = figure(figsize=(size, size))
ax = gca()
if img.ndim == 3:
if bar:
raise ValueError("Ca... | def image(img, cmap='gray', bar=False, nans=True, clim=None, size=7, ax=None) | Streamlined display of images using matplotlib.
Parameters
----------
img : ndarray, 2D or 3D
The image to display
cmap : str or Colormap, optional, default = 'gray'
A colormap to use, for non RGB images
bar : boolean, optional, default = False
Whether to append a colorbar... | 2.418247 | 2.528424 | 0.956425 |
api = Client.instance().api
endpoint_list = api.endpoint.get()
return endpoint_list | def all(cls) | Returns a list of all configured endpoints the server is listening on. For each endpoint,
the list of allowed databases is returned too if set.
The result is a JSON hash which has the endpoints as keys, and the list of
mapped database names as values for each endpoint.
... | 17.997606 | 8.750424 | 2.05677 |
api = Client.instance().api
result = api.endpoint.post(data={
'endpoint': url,
'databases': databases,
})
return result | def create(cls, url, databases) | If databases is an empty list, all databases present in the server will become accessible via the endpoint,
with the _system database being the default database.
If databases is non-empty, only the specified databases will become available via the endpoint.
The first database name i... | 8.40275 | 8.04064 | 1.045035 |
api = Client.instance().api
api.endpoint(url).delete() | def destroy(cls, url) | This operation deletes an existing endpoint from the list of all endpoints,
and makes the server stop listening on the endpoint.
*Note*: deleting and disconnecting an endpoint is allowed in the system database only.
Calling this action in any other database will make the server retu... | 20.710196 | 15.929504 | 1.300115 |
d = defer.Deferred()
if self._result is None:
self._waiters.append(d)
else:
self._fire_deferred(d)
return d | def wait(self) | Return a deferred that will be fired when the event is fired. | 3.640166 | 2.917251 | 1.247807 |
self._closing = True
self.do_close(reason)
self._closing = False | def close(self, reason) | Explicitly close a channel | 4.837221 | 5.465179 | 0.885098 |
if self.closed:
return
self.closed = True
self.reason = reason
self.incoming.close()
self.responses.close()
if not self._closing:
self.client.channel_failed(self, Failure(reason)) | def do_close(self, reason) | Called when channel_close() is received | 5.745323 | 5.452555 | 1.053694 |
if isinstance(reason, Message):
if reason.method.klass.name == "channel":
raise ChannelClosed(reason)
elif reason.method.klass.name == "connection":
raise ConnectionClosed(reason)
raise Closed(reason) | def _raise_closed(reason) | Raise the appropriate Closed-based error for the given reason. | 4.282488 | 3.676622 | 1.164789 |
if self.closed:
return
if reason is None:
reason = ConnectionDone()
if within > 0:
channel0 = yield self.channel(0)
deferred = channel0.connection_close()
call = self.clock.callLater(within, deferred.cancel)
try:
... | def close(self, reason=None, within=0) | Explicitely close the connection.
@param reason: Optional closing reason. If not given, ConnectionDone
will be used.
@param within: Shutdown the client within this amount of seconds. If
zero (the default), all channels and queues will be closed
immediately. If greate... | 4.063556 | 3.733952 | 1.088272 |
'''Returns a copy of this namespace.
Note: we truly create a copy of the dictionary but keep
_macros and _blocks.
'''
return Namespace(self.dictionary.copy(), self._macros, self._blocks) | def copy(self) | Returns a copy of this namespace.
Note: we truly create a copy of the dictionary but keep
_macros and _blocks. | 16.094643 | 2.676988 | 6.012221 |
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(1)
sock.connect((ip, self.conf['tcp_check_port']))
except:
# Any problem during the connection attempt? We won't diagnose it,
# we just indicate failure by a... | def _do_tcp_check(self, ip, results) | Attempt to establish a TCP connection.
If not successful, record the IP in the results dict.
Always closes the connection at the end. | 3.985741 | 4.148925 | 0.960668 |
threads = []
results = []
# Start the thread for each IP we wish to check.
for count, ip in enumerate(list_of_ips):
thread = threading.Thread(
target = self._do_tcp_check,
name = "%s:%s" % (self.threa... | def do_health_checks(self, list_of_ips) | Perform a health check on a list of IP addresses.
Each check (we use a TCP connection attempt) is run in its own thread.
Gather up the results and return the list of those addresses that
failed the test and the list of questionable IPs.
TODO: Currently, this starts a thread for every ... | 3.722945 | 3.487891 | 1.067391 |
logging.info("TCP health monitor plugin: Starting to watch "
"instances.")
self.monitor_thread = threading.Thread(target = self.start_monitoring,
name = self.thread_name)
self.monitor_thread.daemon = True
sel... | def start(self) | Start the monitoring thread of the plugin. | 6.460681 | 5.535283 | 1.167182 |
super(Tcp, self).stop()
self.monitor_thread.join()
logging.info("TCP health monitor plugin: Stopped") | def stop(self) | Stop the monitoring thread of the plugin.
The super-class will send the stop signal on the monitor-IP queue,
which prompts the loop to stop. | 13.053313 | 10.231114 | 1.275845 |
parser.add_argument('--tcp_check_interval',
dest='tcp_check_interval',
required=False, default=2, type=float,
help="TCP health-test interval in seconds, "
"default 2 "
... | def add_arguments(cls, parser, sys_arg_list=None) | Arguments for the TCP health monitor plugin. | 3.074054 | 2.569248 | 1.19648 |
# Checking the interval
if not conf['tcp_check_interval']:
raise ArgsError("A TCP health-test interval needs to be "
"specified (--tcp_check_interval).")
if not (1 <= conf['tcp_check_interval'] <= 3600):
raise ArgsError("Specified TCP... | def check_arguments(cls, conf) | Sanity check plugin options values.
As a side effect, it also converts the specified interval and port
to an integer. | 2.334969 | 2.196681 | 1.062953 |
"Raise warning for negative numbers."
negatives = filter(lambda x: x < 0, filter(None, numbers))
if any(negatives):
neg_values = ', '.join(map(str, negatives))
msg = 'Found negative value(s): {0!s}. '.format(neg_values)
msg += 'While not forbidden, the output will look unexpected.'
... | def _check_negatives(numbers) | Raise warning for negative numbers. | 5.58971 | 5.092258 | 1.097688 |
"Find index postions in list of numbers to be emphasized according to emph."
pat = '(\w+)\:(eq|gt|ge|lt|le)\:(.+)'
# find values to be highlighted
emphasized = {} # index: color
for (i, n) in enumerate(numbers):
if n is None:
continue
for em in emph:
color, o... | def _check_emphasis(numbers, emph) | Find index postions in list of numbers to be emphasized according to emph. | 3.02232 | 2.457481 | 1.229845 |
"Scale input numbers to appropriate range."
# find min/max values, ignoring Nones
filtered = [n for n in numbers if n is not None]
min_ = min(filtered) if minimum is None else minimum
max_ = max(filtered) if maximum is None else maximum
dv = max_ - min_
# clamp
numbers = [max(min(n, ma... | def scale_values(numbers, num_lines=1, minimum=None, maximum=None) | Scale input numbers to appropriate range. | 3.683557 | 3.593493 | 1.025063 |
assert num_lines > 0
if len(numbers) == 0:
return ['']
# raise warning for negative numbers
_check_negatives(numbers)
values = scale_values(numbers, num_lines=num_lines, minimum=minimum, maximum=maximum)
# find values to be highlighted
emphasized = _check_emphasis(numbers, ... | def sparklines(numbers=[], num_lines=1, emph=None, verbose=False,
minimum=None, maximum=None, wrap=None) | Return a list of 'sparkline' strings for a given list of input numbers.
The list of input numbers may contain None values, too, for which the
resulting sparkline will contain a blank character (a space).
Examples:
sparklines([3, 1, 4, 1, 5, 9, 2, 6])
-> ['▃▁▄▁▄█▂▅']
sparklines([3,... | 3.654536 | 3.768173 | 0.969843 |
"Batch items into groups of batch_size"
items = list(items)
if batch_size is None:
return [items]
MISSING = object()
padded_items = items + [MISSING] * (batch_size - 1)
groups = zip(*[padded_items[i::batch_size] for i in range(batch_size)])
return [[item for item in group if item != ... | def batch(batch_size, items) | Batch items into groups of batch_size | 2.868156 | 2.83515 | 1.011642 |
"Print a few usage examples on stdout."
nums = nums or [3, 1, 4, 1, 5, 9, 2, 6]
fmt = lambda num: '{0:g}'.format(num) if isinstance(num, (float, int)) else 'None'
nums1 = list(map(fmt, nums))
if __name__ == '__main__':
prog = sys.argv[0]
else:
prog = 'sparklines'
result = ... | def demo(nums=[]) | Print a few usage examples on stdout. | 2.304251 | 2.220976 | 1.037495 |
expire_time_stamp = time.time() - self.expire_time
self.timed_data = {d: t for d, t in self.timed_data.items()
if t > expire_time_stamp} | def _expire_data(self) | Remove all expired entries. | 4.816785 | 4.114605 | 1.170655 |
now = time.time()
for d in data_set:
self.timed_data[d] = now
self._expire_data() | def update(self, data_set) | Refresh the time of all specified elements in the supplied data set. | 7.536143 | 5.878359 | 1.282015 |
plugin_infos = {}
for pc in self.plugins:
plugin_infos.update(pc.get_info())
return {
self.get_plugin_name() : {
"version" : self.get_version(),
"sub-plugins" : plugin_infos,
"params" : {
"mu... | def get_info(self) | Return plugin information. | 4.695801 | 4.15511 | 1.130127 |
all_reported_ips = set()
for pname, q in plugin_queue_lookup.items():
# Get all the IPs of the specified type from all the plugins.
ips = utils.read_last_msg_from_queue(q)
if ips:
logging.debug("Sub-plugin '%s' reported %d "
... | def _accumulate_ips_from_plugins(self, ip_type_name, plugin_queue_lookup,
ip_accumulator) | Retrieve all IPs of a given type from all sub-plugins.
ip_type_name: A name of the type of IP we are working with.
Used for nice log messages. Example 'failed',
'questionable'.
plugin_queue_lookup: Dictionary to lookup the queues (of a gi... | 5.640608 | 5.070055 | 1.112534 |
logging.info("Multi-plugin health monitor: Started in thread.")
try:
while True:
# Get new IP addresses and pass them on to the sub-plugins
new_ips = self.get_new_working_set()
if new_ips:
logging.debug("Sending lis... | def start_monitoring(self) | Pass IP lists to monitor sub-plugins and get results from them.
Override the common definition of this function, since in the multi
plugin it's a little different: Instead of monitoring ourselves, we
just use a number of other plugins to gather results. The multi plugin
just serves as a... | 4.066704 | 3.690871 | 1.101828 |
super(Multi, self).stop()
self.monitor_thread.join()
logging.info("Multi-plugin health monitor: Stopping plugins")
for p in self.plugins:
p.stop()
logging.info("Multi-plugin health monitor: Stopped") | def stop(self) | Stop the monitoring thread of the plugin.
The super-class will send the stop signal on the monitor-IP queue,
which prompts the loop to stop. | 5.402842 | 5.030488 | 1.074019 |
plugin_classes = {}
if plugins_str:
for plugin_name in plugins_str.split(":"):
pc = load_plugin(plugin_name, MONITOR_DEFAULT_PLUGIN_MODULE)
plugin_classes[plugin_name] = pc
return plugin_classes | def load_sub_plugins_from_str(cls, plugins_str) | Load plugin classes based on column separated list of plugin names.
Returns dict with plugin name as key and class as value. | 3.86711 | 3.460294 | 1.117567 |
parser.add_argument('--multi_plugins',
dest='multi_plugins', required=True,
help="Column seperated list of health monitor "
"plugins (only for 'multi' health monitor "
"plugin)")
... | def add_arguments(cls, parser, sys_arg_list=None) | Arguments for the Multi health monitor plugin. | 5.759338 | 5.071253 | 1.135684 |
# Checking the specified list of basic health monitor plugins, which
# should be run by the multi plugin.
if not conf.get('multi_plugins'):
raise ArgsError("A specification of health monitor plugins "
"is required (--multi_plugins).")
# N... | def check_arguments(cls, conf) | Sanity check plugin options values. | 10.950475 | 10.5503 | 1.03793 |
try:
try:
f = open(fname, "r")
except IOError as e:
# Cannot open file? Doesn't exist?
raise ValueError("Cannot open file: " + str(e))
data = json.loads(f.read())
f.close()
# Sanity checking on the data object
data = common.par... | def read_route_spec_config(fname) | Read, parse and sanity check the route spec config file.
The config file needs to be in this format:
{
"<CIDR-1>" : [ "host-1-ip", "host-2-ip", "host-3-ip" ],
"<CIDR-2>" : [ "host-4-ip", "host-5-ip" ],
"<CIDR-3>" : [ "host-6-ip", "host-7-ip", "host-8-ip", "host-9-ip" ]
}
Retur... | 4.014533 | 4.127565 | 0.972615 |
fname = self.conf['file']
logging.info("Configfile watcher plugin: Starting to watch route spec "
"file '%s' for changes..." % fname)
# Initial content of file needs to be processed at least once, before
# we start watching for any changes to it. Therefore,... | def start(self) | Start the configfile change monitoring thread. | 4.927842 | 4.683798 | 1.052104 |
self.observer_thread.stop()
self.observer_thread.join()
logging.info("Configfile watcher plugin: Stopped") | def stop(self) | Stop the config change monitoring thread. | 10.440643 | 7.349593 | 1.420574 |
return {
self.get_plugin_name() : {
"version" : self.get_version(),
"params" : {
"file" : self.conf['file']
},
"stats" : {
"last_route_spec_update" :
self.last_rou... | def get_info(self) | Return plugin information. | 4.989472 | 4.404825 | 1.132729 |
parser.add_argument('-f', '--file', dest='file', required=True,
help="config file for routing groups "
"(only in configfile mode)")
return ["file"] | def add_arguments(cls, parser, sys_arg_list=None) | Arguments for the configfile mode. | 12.127131 | 8.21906 | 1.475489 |
try:
# Check we have access to the config file
f = open(conf['file'], "r")
f.close()
except IOError as e:
raise ArgsError("Cannot open config file '%s': %s" %
(conf['file'], e)) | def check_arguments(cls, conf) | Sanity checks for options needed for configfile mode. | 4.210787 | 3.838095 | 1.097104 |
try:
if "." in plugin_name:
# Assume external plugin, full path
plugin_mod_name = plugin_name
plugin_class_name = plugin_name.split(".")[-1].capitalize()
else:
# One of the built-in plugins
plugin_mod_name = "%s.%s" % (default_plug... | def load_plugin(plugin_name, default_plugin_module) | Load a plugin plugin.
Supports loading of plugins that are part of the vpcrouter, as well as
external plugins: If the plugin name has a dotted notation then it
assumes it's an external plugin and the dotted notation is the complete
import path. If it's just a single word then it looks for the plugin in... | 2.078256 | 2.118222 | 0.981132 |
if (signal in self._signal_names):
s = Signal(signal, callback_fn, user_arg)
self._signals[signal] = s
self._bus.add_signal_receiver(s.signal_handler,
signal,
dbus_interface=self._dbu... | def add_signal_receiver(self, callback_fn, signal, user_arg) | Add a signal receiver callback with user argument
See also :py:meth:`remove_signal_receiver`,
:py:exc:`.ConnSignalNameNotRecognisedException`
:param func callback_fn:
User-defined callback function to call when signal triggers
:param str signal:
Signal name e.g.... | 5.151673 | 4.264904 | 1.207922 |
if (signal in self._signal_names):
s = self._signals.get(signal)
if (s):
self._bus.remove_signal_receiver(s.signal_handler,
signal,
dbus_interface=self._dbus_addr) ... | def remove_signal_receiver(self, signal) | Remove an installed signal receiver by signal name.
See also :py:meth:`add_signal_receiver`
:py:exc:`exceptions.ConnSignalNameNotRecognisedException`
:param str signal:
Signal name to uninstall e.g., :py:attr:`SIGNAL_PROPERTY_CHANGED`
:return:
:raises ConnSignalName... | 5.920872 | 4.725649 | 1.252923 |
"Actually makes the HTTP request."
try:
response = request(url, stream=True, **kwargs)
except RequestException as e:
raise RequestError(e)
else:
if response.status_code >= 400:
raise ResponseError(response)
# Try to return the r... | def _do_request(self, request, url, **kwargs) | Actually makes the HTTP request. | 3.468707 | 3.296487 | 1.052243 |
"Handles retrying failed requests and error handling."
request = getattr(requests, method, None)
if not callable(request):
raise RequestError('Invalid method %s' % method)
# Find files, separate them out to correct kwarg for requests.
data = kwargs.get('data')
... | def _request(self, method, endpoint, id=None, **kwargs) | Handles retrying failed requests and error handling. | 3.397544 | 3.223449 | 1.054009 |
response = self.get(
'/path/data/', file_to_be_downloaded, raw=False)
if not perform_download:
# The caller can decide how to process the download of the data
return response
if not download_to_path:
download_to_path = file_to_be_downloade... | def download(self, file_to_be_downloaded, perform_download=True, download_to_path=None) | file_to_be_downloaded is a file-like object that has already
been uploaded, you cannot download folders | 5.01335 | 5.0244 | 0.997801 |
r = requests.post('http://{0}/api/notebook'.format(self.zeppelin_url),
json=data)
self.notebook_id = r.json()['body'] | def create_notebook(self, data) | Create notebook under notebook directory. | 4.934232 | 4.60464 | 1.071578 |
while True:
r = requests.get('http://{0}/api/notebook/job/{1}'.format(
self.zeppelin_url, self.notebook_id))
if r.status_code == 200:
try:
data = r.json()['body']
if all(paragraph['status'] in ... | def wait_for_notebook_to_execute(self) | Wait for notebook to finish executing before continuing. | 3.001346 | 2.936019 | 1.02225 |
r = requests.get('http://{0}/api/notebook/{1}'.format(
self.zeppelin_url, self.notebook_id))
if r.status_code == 200:
return r.json()['body']
else:
print('ERROR: Could not get executed notebook.', file=sys.stderr)
sys.exit(1) | def get_executed_notebook(self) | Return the executed notebook. | 3.214518 | 2.976747 | 1.079876 |
directory = os.path.dirname(self.output_path)
full_path = os.path.join(directory, self.notebook_name)
try:
with open(full_path, 'w') as fh:
fh.write(json.dumps(body, indent=2))
except ValueError:
print('ERROR: Could not save executed noteb... | def save_notebook(self, body) | Save notebook depending on user provided output path. | 3.50385 | 3.170636 | 1.105093 |
self.create_notebook(data)
self.run_notebook()
self.wait_for_notebook_to_execute()
body = self.get_executed_notebook()
err = False
output = []
for paragraph in body['paragraphs']:
if 'results' in paragraph and paragraph['results']['code'] == ... | def execute_notebook(self, data) | Execute input notebook and save it to file.
If no output path given, the output will be printed to stdout.
If any errors occur from executing the notebook's paragraphs, they will
be displayed in stderr. | 3.070447 | 2.882196 | 1.065315 |
parser = argparse.ArgumentParser(
description="VPC router: Manage routes in VPC route table")
# General arguments
parser.add_argument('--verbose', dest="verbose", action='store_true',
help="produces more output")
parser.add_argument('-l', '--logfile', des... | def _setup_arg_parser(args_list, watcher_plugin_class, health_plugin_class) | Configure and return the argument parser for the command line options.
If a watcher and/or health-monitor plugin_class is provided then call the
add_arguments() callback of the plugin class(es), in order to add plugin
specific options.
Some parameters are required (vpc and region, for example), but we... | 3.296525 | 3.138817 | 1.050245 |
conf = {}
# Setting up the command line argument parser. Note that we pass the
# complete list of all plugins, so that their parameter can be added to the
# official parameter handling, the help screen, etc. Some plugins may even
# add further plugins themselves, but will handle this themselve... | def _parse_args(args_list, watcher_plugin_class, health_plugin_class) | Parse command line arguments and return relevant values in a dict.
Also perform basic sanity checking on some arguments.
If plugin classes have been provided then a callback into those classes is
used to extend the arguments with plugin-specific options.
Likewise, the sanity checking will then also i... | 5.071501 | 5.099707 | 0.994469 |
if conf['verbose']:
level = logging.DEBUG
else:
level = logging.INFO
fname = conf['logfile'] if conf['logfile'] != "-" else None
logging.basicConfig(filename=fname, level=level,
format='%(asctime)s - %(levelname)-8s - '
'%(thr... | def _setup_logging(conf) | Configure the logging framework.
If run in CLI mode then all log output is simply written to stdout. | 3.262407 | 3.36476 | 0.969581 |
try:
# A bit of a hack: We want to load the plugins (specified via the mode
# and health parameter) in order to add their arguments to the argument
# parser. But this means we first need to look into the CLI arguments
# to find them ... before looking at the arguments. So we fir... | def main() | Starting point of the executable. | 4.437465 | 4.420894 | 1.003748 |
#database = parse_uri(self.uri).get("database")
if self.ioloop:
if only_db == False:
client = AsyncIOMotorClient("/".join(self.uri.split("/")[:-1]), io_loop=self.ioloop)
else:
client = AsyncIOMotorClient(self.uri, io_loop=self.ioloop)
... | def create_client(self,only_db=False) | 返回连接的客户端 | 2.341522 | 2.326691 | 1.006375 |
if app.config.GRIDFS_SETTINGS and isinstance(app.config.GRIDFS_SETTINGS, dict):
self.GRIDFS_SETTINGS = app.config.GRIDFS_SETTINGS
self.app = app
else:
raise ValueError(
"nonstandard sanic config GRIDFS_URIS,GRIDFS_URIS must be a Dict[Bucket_n... | def init_app(self, app) | 绑定app | 4.097044 | 4.124684 | 0.993299 |
self.plugin_by_name[plugin.get_plugin_name()] = plugin
self.plugins.append(plugin) | def add_plugin(self, plugin) | Every plugin (watcher and health) is added so we can later get live
info from each plugin. | 3.622012 | 3.118123 | 1.1616 |
d = {}
for p in self.plugins:
d.update(p.get_info())
return d | def get_plugins_info(self) | Collect the current live info from all the registered plugins.
Return a dictionary, keyed on the plugin name. | 3.875693 | 3.38376 | 1.145381 |
if path == "ips":
return {
"failed_ips" : self.failed_ips,
"questionable_ips" : self.questionable_ips,
"working_set" : self.working_set,
}
if path == "route_info":
return {
"route_spe... | def get_state_repr(self, path) | Returns the current state, or sub-state, depending on the path. | 3.375362 | 3.330275 | 1.013539 |
if path not in self.top_level_links:
raise StateError("Unknown path")
return json.dumps(self.get_state_repr(path),
indent=4 if with_indent else None) | def as_json(self, path="", with_indent=False) | Return a rendering of the current state in JSON. | 7.014776 | 5.47348 | 1.281593 |
if path not in self.top_level_links:
raise StateError("Unknown path")
header =
footer =
rep = self.get_state_repr(path)
def make_links(rep):
# Recursively create clickable links for _href elements
for e, v in rep.items():
... | def as_html(self, path="") | Return a rendering of the current state in HTML. | 3.694316 | 3.519517 | 1.049666 |
result = x // y
if (x % y):
result += 1
return result | def intdivceil(x, y) | Returns the exact value of ceil(x // y).
No floating point calculations are used.
Requires positive integer types. The result
is undefined if at least one of the inputs
is floating point. | 3.579262 | 4.722338 | 0.757943 |
objs = iter(objs)
try:
while (1):
chunk = []
while len(chunk) < n:
chunk.append(six.next(objs))
yield chunk
except StopIteration:
pass
if len(chunk):
yield chunk | def chunkiter(objs, n=100) | Chunk an iterator of unknown size. The optional
keyword 'n' sets the chunk size (default 100). | 3.117343 | 3.236457 | 0.963196 |
if app.config.MONGO_URIS and isinstance(app.config.MONGO_URIS, dict):
self.MONGO_URIS = app.config.MONGO_URIS
self.app = app
else:
raise ValueError(
"nonstandard sanic config MONGO_URIS,MONGO_URIS must be a Dict[dbname,dburl]")
@app... | def init_app(self, app) | 绑定app | 3.538805 | 3.553805 | 0.995779 |
# Normally, we should start a thread or process here, pass the message
# queue self.q_route_spec to that thread and let it send route
# configurations through that queue. But since we're just sending a
# single, fixed configuration, we can just do that right here.
# Note... | def start(self) | Start the config watch thread or process. | 8.229116 | 8.019283 | 1.026166 |
parser.add_argument('--fixed_cidr', dest="fixed_cidr", required=True,
help="specify the route CIDR "
"(only in fixedconf mode)")
parser.add_argument('--fixed_hosts', dest="fixed_hosts", required=True,
help=... | def add_arguments(cls, parser, sys_arg_list=None) | Callback to add command line options for this plugin to the argparse
parser. | 5.435865 | 5.42855 | 1.001348 |
# Perform sanity checking on CIDR
utils.ip_check(conf['fixed_cidr'], netmask_expected=True)
# Perform sanity checking on host list
for host in conf['fixed_hosts'].split(":"):
utils.ip_check(host) | def check_arguments(cls, conf) | Callback to perform sanity checking for the plugin's specific
parameters. | 9.820453 | 9.743664 | 1.007881 |
new_list_of_ips = None
while True:
try:
new_list_of_ips = self.q_monitor_ips.get_nowait()
self.q_monitor_ips.task_done()
if type(new_list_of_ips) is MonitorPluginStopSignal:
raise StopReceived()
except Q... | def get_new_working_set(self) | Get a new list of IPs to work with from the queue.
This returns None if there is no update.
Read all the messages from the queue on which we get the IP addresses
that we have to monitor. We will ignore all of them, except the last
one, since maybe we received two updates in a row, but ... | 5.029262 | 3.657082 | 1.375212 |
time.sleep(1)
# This is our working set. This list may be updated occasionally when
# we receive messages on the q_monitor_ips queue. But irrespective of
# any received updates, the list of IPs in here is regularly checked.
list_of_ips = []
curre... | def start_monitoring(self) | Monitor IP addresses and send notifications if one of them has failed.
This function will continuously monitor q_monitor_ips for new lists of
IP addresses to monitor. Each message received there is the full state
(the complete lists of addresses to monitor).
Push out (return) any faile... | 4.119737 | 3.996938 | 1.030723 |
# Sanity checking on the data object
if type(data) is not dict:
raise ValueError("Expected dictionary at top level")
try:
for k, v in data.items():
utils.ip_check(k, netmask_expected=True)
if type(v) is not list:
raise ValueError("Expect list of I... | def parse_route_spec_config(data) | Parse and sanity check the route spec config.
The config data is a blob of JSON that needs to be in this format:
{
"<CIDR-1>" : [ "host-1-ip", "host-2-ip", "host-3-ip" ],
"<CIDR-2>" : [ "host-4-ip", "host-5-ip" ],
"<CIDR-3>" : [ "host-6-ip", "host-7-ip", "host-8-ip", "host-9-ip" ]
... | 4.47491 | 4.291135 | 1.042827 |
# Extract all the IP addresses from the route spec, unique and sorted.
new_all_ips = \
sorted(set(itertools.chain.from_iterable(route_spec.values())))
if new_all_ips != all_ips:
logging.debug("New route spec detected. Updating "
"health-monitor with: %s" %
... | def _update_health_monitor_with_new_ips(route_spec, all_ips,
q_monitor_ips) | Take the current route spec and compare to the current list of known IP
addresses. If the route spec mentiones a different set of IPs, update the
monitoring thread with that new list.
Return the current set of IPs mentioned in the route spec. | 3.678338 | 3.52829 | 1.042527 |
# No matter what the chosen plugin to watch for config updates: We get a
# plugin-handle back. This gives us a start(), stop() and
# get_route_spec_queue() function. All watcher plugins provide the same
# interface.
watcher_plugin = watcher_plugin_class(conf)
watcher_plugin.start()
# S... | def start_plugins(conf, watcher_plugin_class, health_plugin_class,
sleep_time) | Start the working threads:
- Health monitor (the health plugin)
- Config change monitor (the watcher plugin) | 8.541662 | 8.830675 | 0.967272 |
logging.debug("Stopping health-check monitor...")
health_plugin.stop()
logging.debug("Stopping config change observer...")
watcher_plugin.stop() | def stop_plugins(watcher_plugin, health_plugin) | Stops all plugins. | 5.818325 | 6.37892 | 0.912118 |
if CURRENT_STATE._stop_all:
logging.debug("Not starting plugins: Global stop")
return
# Start the working threads (health monitor, config event monitor, etc.)
# and return the thread handles and message queues in a thread-info dict.
watcher_plugin, health_plugin = \
sta... | def start_watcher(conf, watcher_plugin_class, health_plugin_class,
iterations=None, sleep_time=1) | Start watcher loop, listening for config changes or failed hosts.
Also starts the various service threads.
VPC router watches for any changes in the config and updates/adds/deletes
routes as necessary. If failed hosts are reported, routes are also updated
as needed.
This function starts a few wor... | 8.554006 | 7.389847 | 1.157535 |
header = ['---',
'title: ' + title,
'author(s): ' + self.user,
'tags: ',
'created_at: ' + str(self.date_created),
'updated_at: ' + str(self.date_updated),
'tldr: ',
'thumbnail: ... | def build_header(self, title) | Generate the header for the Markdown file. | 3.818978 | 3.425223 | 1.114957 |
self.out.append("```" + lang)
self.build_markdown(lang, body)
self.out.append("```") | def build_code(self, lang, body) | Wrap text with markdown specific flavour. | 5.596551 | 4.347545 | 1.28729 |
try:
lang, body = paragraph.split(None, 1)
except ValueError:
lang, body = paragraph, None
if not lang.strip().startswith('%'):
lang = 'scala'
body = paragraph.strip()
else:
lang = lang.strip()[1:]
if lang ==... | def process_input(self, paragraph) | Parse paragraph for the language of the code and the code itself. | 4.040417 | 3.521296 | 1.147423 |
if not row:
return
cols = row.split('\t')
if len(cols) == 1:
self.out.append(cols[0])
else:
col_md = '|'
underline_md = '|'
if cols:
for col in cols:
col_md += col + '|'
... | def create_md_row(self, row, header=False) | Translate row into markdown format. | 2.763595 | 2.554564 | 1.081826 |
date = parse(text)
if self.date_created == 'N/A':
self.date_created = date
if date < self.date_created:
self.date_created = date | def process_date_created(self, text) | Set date_created to the oldest date (date created). | 2.937752 | 2.61142 | 1.124963 |
date = parse(text)
if self.date_updated == 'N/A':
self.date_updated = date
if date > self.date_updated:
self.date_updated = date | def process_date_updated(self, text) | Set date_updated to the most recent date (updated date). | 2.901327 | 2.686329 | 1.080034 |
fout.write('\n'.join([s for s in self.out])) | def build_output(self, fout) | Squash self.out into string.
Join every line in self.out with a new line and write the
result to the output file. | 8.988168 | 7.537826 | 1.192409 |
self.build_markdown_body(json) # create the body
self.build_header(json['name']) # create the md header
self.build_output(fout) | def convert(self, json, fout) | Convert json to markdown.
Takes in a .json file as input and convert it to Markdown format,
saving the generated .png images into ./images. | 8.848557 | 8.419903 | 1.05091 |
key_options = {
'dateCreated': self.process_date_created,
'dateUpdated': self.process_date_updated,
'title': self.process_title,
'text': self.process_input
}
for paragraph in text['paragraphs']:
if 'user' in paragraph:
... | def build_markdown_body(self, text) | Generate the body for the Markdown file.
- processes each json block one by one
- for each block, process:
- the creator of the notebook (user)
- the date the notebook was created
- the date the notebook was last updated
- the input by detecting the edito... | 3.749412 | 3.456627 | 1.084702 |
rows = msg.split('\n')
if rows:
header_row, *body_rows = rows
self.create_md_row(header_row, True)
for row in body_rows:
self.create_md_row(row) | def build_table(self, msg) | Format each row of the table. | 3.53209 | 3.346035 | 1.055605 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.