code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
with self.notifications_lock:
if clear_if_dupl and message in self.message_widget_dict.keys():
logger.debug("notification %r is already displayed", message)
return
logger.debug("display notification %r", message)
widget = urwid.AttrMap... | def notify_message(self, message, level="info", clear_if_dupl=True,
clear_in=CLEAR_NOTIF_BAR_MESSAGE_IN) | :param message, str
:param level: str, {info, error}
:param clear_if_dupl: bool, if True, don't display the notification again
:param clear_in: seconds, remove the notificantion after some time
opens notification popup. | 3.855778 | 3.966267 | 0.972143 |
@log_traceback
def clear_notification(*args, **kwargs):
# the point here is the log_traceback
self.remove_widget(widget, message=message)
if not widget:
return
logger.debug("display notification widget %s", widget)
with self.notifi... | def notify_widget(self, widget, message=None, clear_in=CLEAR_NOTIF_BAR_MESSAGE_IN) | opens notification popup.
:param widget: instance of Widget, widget to display
:param message: str, message to remove from list of notifications
:param clear_in: int, time seconds when notification should be removed | 5.610969 | 5.822168 | 0.963725 |
logger.debug("refresh user interface")
try:
with self.refresh_lock:
self.draw_screen()
except AssertionError:
logger.warning("application is not running")
pass | def refresh(self) | explicitely refresh user interface; useful when changing widgets dynamically | 8.943417 | 6.861283 | 1.303461 |
max_cols_lengths = {}
for row in table:
col_index = 0
for idx, widget in enumerate(row.widgets):
l = widget.pack((size[0], ))[0]
max_cols_lengths[idx] = max(max_cols_lengths.get(idx, 0), l)
col_index += 1
max_cols_lengths.setdefault(0, 1) # in case... | def calculate_max_cols_length(table, size) | :param table: list of lists:
[["row 1 column 1", "row 1 column 2"],
["row 2 column 1", "row 2 column 2"]]
each item consists of instance of urwid.Text
:returns dict, {index: width} | 3.365085 | 3.292686 | 1.021988 |
rows = []
max_lengths = {}
ignore_columns = ignore_columns or []
# shitty performance, here we go
# it would be way better to do a single double loop and provide mutable variable
# FIXME: merge this code with calculate() from above
for row in data:
col_index = 0
for wid... | def assemble_rows(data, max_allowed_lengths=None, dividechars=1,
ignore_columns=None) | :param data: list of lists:
[["row 1 column 1", "row 1 column 2"],
["row 2 column 1", "row 2 column 2"]]
each item consists of instance of urwid.Text
:param max_allowed_lengths: dict:
{col_index: maximum_allowed_length}
:param ignore_columns: list of ints, indexes which should not be calcu... | 3.347738 | 3.284307 | 1.019313 |
now = datetime.datetime.now()
if t + datetime.timedelta(hours=3) > now:
return get_map("main_list_white")
if t + datetime.timedelta(days=3) > now:
return get_map("main_list_lg")
else:
return get_map("main_list_dg") | def get_time_attr_map(t) | now -> |
hour ago -> |
day ago -> |
|--------------|--------------------|---------------------| | 4.141431 | 4.214817 | 0.982589 |
# esc[ + values + control character
# h, l, p commands are complicated, let's ignore them
seq_regex = r"\x1b\[[0-9;]*[mKJusDCBAfH]"
regex = re.compile(seq_regex)
start = 0
response = ""
for match in regex.finditer(text):
end = match.start()
response += text[start:end]
... | def strip_from_ansi_esc_sequences(text) | find ANSI escape sequences in text and remove them
:param text: str
:return: list, should be passed to ListBox | 7.792358 | 8.572723 | 0.908971 |
# TODO: make this available for every buffer
logger.info("starting receiving events from docker")
it = self.d.realtime_updates()
while True:
try:
event = next(it)
except NotifyError as ex:
self.ui.notify_message("error when... | def realtime_updates(self) | fetch realtime events from docker and pass them to buffers
:return: None | 10.530281 | 9.172829 | 1.147986 |
try:
top_dir = os.path.abspath(os.path.expanduser(os.environ["XDG_CACHE_HOME"]))
except KeyError:
top_dir = os.path.abspath(os.path.expanduser("~/.cache"))
our_cache_dir = os.path.join(top_dir, PROJECT_NAME)
os.makedirs(our_cache_dir, mode=0o775, exist_ok=True)
return our_cache_... | def setup_dirs() | Make required directories to hold logfile.
:returns: str | 2.145495 | 2.333652 | 0.919372 |
abbrevs = (
(1 << 50, 'PB'),
(1 << 40, 'TB'),
(1 << 30, 'GB'),
(1 << 20, 'MB'),
(1 << 10, 'kB'),
(1, 'bytes')
)
if bytesize == 1:
return '1 byte'
for factor, suffix in abbrevs:
if bytesize >= factor:
break
if factor == ... | def humanize_bytes(bytesize, precision=2) | Humanize byte size figures
https://gist.github.com/moird/3684595 | 1.466892 | 1.504933 | 0.974722 |
args = args or ()
kwargs = kwargs or {}
t = 1.0
for x in range(retries):
try:
return call(*args, **kwargs)
except APIError as ex:
logger.error("query #%d: docker returned an error: %r", x, ex)
except Exception as ex:
# this may be pretty b... | def repeater(call, args=None, kwargs=None, retries=4) | repeat call x-times: docker API is just awesome
:param call: function
:param args: tuple, args for function
:param kwargs: dict, kwargs for function
:param retries: int, how many times we try?
:return: response of the call | 3.965621 | 4.05707 | 0.977459 |
try:
value = graceful_chain_get(self.inspect(cached=cached).response, *path)
except docker.errors.NotFound:
logger.warning("object %s is not available anymore", self)
raise NotAvailableAnymore()
return value | def metadata_get(self, path, cached=True) | get metadata from inspect, specified by path
:param path: list of str
:param cached: bool, use cached version of inspect if available | 10.149285 | 9.995164 | 1.01542 |
# sample output:
# {
# "Created": 1457116802,
# "Id": "sha256:507cb13a216097710f0d234668bf64a4c92949c573ba15eba13d05aad392fe04",
# "Size": 204692029,
# "Tags": [
# "docker.io/fedora:latest"
# ],
# "Comment":... | def layers(self) | similar as parent images, except that it uses /history API endpoint
:return: | 6.921929 | 6.497313 | 1.065353 |
self._virtual_size = self._virtual_size or \
graceful_chain_get(self.data, "VirtualSize", default=0)
try:
return self._virtual_size - self._shared_size
except TypeError:
return 0 | def unique_size(self) | Size of ONLY this particular layer
:return: int or None | 6.406429 | 6.882638 | 0.93081 |
try:
# docker >= 1.9
image_id = self.data["ImageID"]
except KeyError:
# docker <= 1.8
image_id = self.metadata_get(["Image"])
return image_id | def image_id(self) | this container is created from image with id... | 5.081625 | 4.247422 | 1.196402 |
try:
return NetData(self.inspect(cached=True).response)
except docker.errors.NotFound:
raise NotAvailableAnymore() | def net(self) | get ACTIVE port mappings of a container
:return: dict:
{
"host_port": "container_port"
} | 17.372025 | 16.088539 | 1.079776 |
# let's get resources from .stats()
ps_args = "-eo pid,ppid,wchan,args"
# returns {"Processes": [values], "Titles": [values]}
# it's easier to play with list of dicts: [{"pid": 1, "ppid": 0}]
try:
response = self.d.top(self.container_id, ps_args=ps_args)
... | def top(self) | list of processes in a running container
:return: None or list of dicts | 7.654895 | 6.566599 | 1.165732 |
content = []
containers_o = None
images_o = None
# return containers when containers=False and running=True
if containers or not stopped:
containers_o = self.get_containers(cached=cached, stopped=stopped)
content += containers_o.response
i... | def filter(self, containers=True, images=True, stopped=True, cached=False, sort_by_created=True) | since django is so awesome, let's use their ORM API
:return: | 3.492326 | 3.613465 | 0.966476 |
maxcol = size[0]
self._cache_maxcol = maxcol
widths = [width for i, (w, (t, width, b)) in enumerate(self.contents)]
self._cache_column_widths = widths
return widths | def column_widths(self, size, focus=False) | Return a list of column widths.
0 values in the list mean hide corresponding column completely | 8.011147 | 8.414714 | 0.95204 |
a4 = None
if network_name == "host":
a4 = "127.0.0.1"
n = {}
a4 = graceful_chain_get(network_data, "IPAddress") or a4
if a4:
n["ip_address4"] = a4
a6 = graceful_chain_get(network_data, "GlobalIPv6Address")
if a6:
n["ip_address4"] = a6
return n | def extract_data_from_inspect(network_name, network_data) | :param network_name: str
:param network_data: dict
:return: dict:
{
"ip_address4": "12.34.56.78"
"ip_address6": "ff:fa:..."
} | 4.040465 | 3.29396 | 1.226629 |
if self._ports is None:
self._ports = {}
if self.net_settings["Ports"]:
for key, value in self.net_settings["Ports"].items():
cleaned_port = key.split("/")[0]
self._ports[cleaned_port] = graceful_chain_get(value, 0, "HostP... | def ports(self) | :return: dict
{
# container -> host
"1234": "2345"
} | 4.588004 | 3.942307 | 1.163787 |
if self._ips is None:
self._ips = {}
default_net = extract_data_from_inspect("default", self.net_settings)
if default_net:
self._ips["default"] = default_net
# this can be None
networks = self.inspect_data["NetworkSettings"]["N... | def ips(self) | :return: dict:
{
"default": {
"ip_address4": "12.34.56.78"
"ip_address6": "ff:fa:..."
}
"other": {
...
}
} | 3.808851 | 3.305983 | 1.152108 |
logger.info("refresh listing")
focus_on_top = len(self.body) == 0 # focus if empty
with self.refresh_lock:
self.query(query_string=query)
if focus_on_top:
try:
self.set_focus(0)
except IndexError:
pass | def refresh(self, query=None) | refresh listing, also apply filters
:return: | 6.748354 | 6.541352 | 1.031645 |
def query_notify(operation):
w = get_operation_notify_widget(operation, display_always=False)
if w:
self.ui.notify_widget(w)
if query_string is not None:
self.filter_query = query_string.strip()
# FIXME: this could be part of filter... | def query(self, query_string="") | query and display, also apply filters
:param query_string: str
:return: None | 3.530866 | 3.495225 | 1.010197 |
arg_index = 0
for a in argument_list:
opt_and_val = a.split("=", 1)
opt_name = opt_and_val[0]
try:
# option
argument = self.options[opt_name]
except KeyError:
# argument
try:
... | def process(self, argument_list) | :param argument_list: list of str, input from user
:return: dict:
{"cleaned_arg_name": "value"} | 3.456715 | 3.404826 | 1.01524 |
logger.debug("get command for command input %r", command_input)
if not command_input:
# noop, don't do anything
return
if command_input[0] in ["/"]: # we could add here !, @, ...
command_name = command_input[0]
unparsed_command_args = s... | def get_command(self, command_input, docker_object=None, buffer=None, size=None) | return command instance which is the actual command to be executed
:param command_input: str, command name and its args: "command arg arg2=val opt"
:param docker_object:
:param buffer:
:param size: tuple, so we can call urwid.keypress(size, ...)
:return: instance of Command | 3.017115 | 2.998193 | 1.006311 |
if wav:
f = wave.open(wav, 'rb')
rate = f.getframerate()
channels = f.getnchannels()
width = f.getsampwidth()
def gen(w):
d = w.readframes(CHUNK_SIZE)
while d:
yield d
d ... | def play(self, wav=None, data=None, rate=16000, channels=1, width=2, block=True, spectrum=None) | play wav file or raw audio (string or generator)
Args:
wav: wav file path
data: raw audio data, str or iterator
rate: sample rate, only for raw audio
channels: channel number, only for raw data
width: raw audio data width, 16 bit is 2, only for raw dat... | 2.067215 | 2.111332 | 0.979105 |
if platform.machine() == 'mips':
command = 'madplay -o wave:- - | aplay -M'
else:
command = 'ffplay -autoexit -nodisp -'
if mp3:
def gen(m):
with open(m, 'rb') as f:
d = f.read(1024)
while d:
... | def play_mp3(self, mp3=None, data=None, block=True) | It supports GeneratorType mp3 stream or mp3 data string
Args:
mp3: mp3 file
data: mp3 generator or data
block: if true, block until audio is played. | 2.563278 | 2.487761 | 1.030355 |
val = self._fd.read()
self._fd.seek(0)
return int(val) | def read(self) | Read pin value
@rtype: int
@return: I{0} when LOW, I{1} when HIGH | 6.713024 | 7.172066 | 0.935996 |
# find all devices matching the vid/pid specified
dev = usb.core.find(idVendor=0x2886, idProduct=0x0007)
if not dev:
logging.debug("No device connected")
return []
interface_number = -1
# get active config
config = dev.get_active_config... | def getAllConnectedInterface() | returns all the connected devices which matches PyUSB.vid/PyUSB.pid.
returns an array of PyUSB (Interface) objects | 2.932176 | 2.728386 | 1.074692 |
# report_size = 64
# if self.ep_out:
# report_size = self.ep_out.wMaxPacketSize
#
# for _ in range(report_size - len(data)):
# data.append(0)
self.read_sem.release()
if not self.ep_out:
bmRequestType = 0x21 #Host to dev... | def write(self, data) | write data on the OUT endpoint associated to the HID interface | 7.221054 | 6.314714 | 1.143528 |
logging.debug("closing interface")
self.closed = True
self.read_sem.release()
self.thread.join()
usb.util.dispose_resources(self.dev) | def close(self) | close the interface | 5.437877 | 4.84621 | 1.122089 |
all_devices = hid.find_all_hid_devices()
# find devices with good vid/pid
all_mbed_devices = []
for d in all_devices:
if (d.product_name.find("MicArray") >= 0):
all_mbed_devices.append(d)
boards = []
for dev in all_mbed_devices:
... | def getAllConnectedInterface() | returns all the connected CMSIS-DAP devices | 3.040233 | 3.060113 | 0.993504 |
for _ in range(64 - len(data)):
data.append(0)
#logging.debug("send: %s", data)
self.report.send(bytearray([0]) + data)
return | def write(self, data) | write data on the OUT endpoint associated to the HID interface | 6.178428 | 5.407749 | 1.142514 |
start = time()
while len(self.rcv_data) == 0:
if time() - start > timeout:
# Read operations should typically take ~1-2ms.
# If this exception occurs, then it could indicate
# a problem in one of the following areas:
# ... | def read(self, timeout=1.0) | read data on the IN endpoint associated to the HID interface | 8.427095 | 8.427782 | 0.999919 |
devices = hid.enumerate()
if not devices:
logging.debug("No Mbed device connected")
return []
boards = []
for deviceInfo in devices:
product_name = deviceInfo['product_string']
if (product_name.find("MicArray") < 0):
... | def getAllConnectedInterface() | returns all the connected devices which matches HidApiUSB.vid/HidApiUSB.pid.
returns an array of HidApiUSB (Interface) objects | 3.181755 | 2.959294 | 1.075174 |
for _ in range(64 - len(data)):
data.append(0)
#logging.debug("send: %s", data)
self.device.write(bytearray([0]) + data)
return | def write(self, data) | write data on the OUT endpoint associated to the HID interface | 5.00316 | 4.607761 | 1.085811 |
return CDFepoch.encode_tt2000(epochs, iso_8601)
elif (isinstance(epochs, float) or isinstance(epochs, np.float64)):
return CDFepoch.encode_epoch(epochs, iso_8601)
elif (isinstance(epochs, complex) or isinstance(epochs, np.complex128)):
return CDFepoch.encode_epoch16(e... | def encode(epochs, iso_8601=True): # @NoSelf
if (isinstance(epochs, int) or isinstance(epochs, np.int64)) | Encodes the epoch(s) into UTC string(s).
For CDF_EPOCH:
The input should be either a float or list of floats
(in numpy, a np.float64 or a np.ndarray of np.float64)
Each epoch is encoded, by default to a ISO 8601 form:
2004-05-13T15:08:11.022
... | 1.634838 | 1.465975 | 1.115188 |
if len(cdf_time) == 1:
time_list = [time_list]
else:
time_list = [time_list]
unixtime = []
for t in time_list:
date = ['year', 'month', 'day', 'hour', 'minute', 'second', 'microsecond']
for i in range(0, len(t)):
if i... | def unixtime(cdf_time, to_np=False): # @NoSelf
import datetime
time_list = CDFepoch.breakdown(cdf_time, to_np=False)
#Check if only one time was input into unixtime.
#If so, turn the output of breakdown into a list for this function to work
if hasattr(cdf_time, '__len_... | Encodes the epoch(s) into seconds after 1970-01-01. Precision is only
kept to the nearest microsecond.
If to_np is True, then the values will be returned in a numpy array. | 2.199254 | 2.297651 | 0.957175 |
raise TypeError('datetime must be in list form')
if isinstance(datetimes[0], numbers.Number):
items = len(datetimes)
elif isinstance(datetimes[0], (list, tuple, np.ndarray)):
items = len(datetimes[0])
else:
print('Unknown input')
retur... | def compute(datetimes, to_np=None): # @NoSelf
if not isinstance(datetimes, (list, tuple, np.ndarray)) | Computes the provided date/time components into CDF epoch value(s).
For CDF_EPOCH:
For computing into CDF_EPOCH value, each date/time elements should
have exactly seven (7) components, as year, month, day, hour, minute,
second and millisecond, in a list. For exam... | 3.02936 | 2.189235 | 1.383753 |
return CDFepoch.epochrange_epoch(epochs, starttime, endtime)
elif (isinstance(epochs, int) or isinstance(epochs, np.int64)):
return CDFepoch.epochrange_tt2000(epochs, starttime, endtime)
elif isinstance(epochs, (complex, np.complex128)):
return CDFepoch.epochrange_epo... | def findepochrange(epochs, starttime=None, endtime=None): # @NoSelf
if (isinstance(epochs, float) or isinstance(epochs, np.float64)) | Finds the record range within the start and end time from values
of a CDF epoch data type. It returns a list of record numbers.
If the start time is not provided, then it is
assumed to be the minimum possible value. If the end time is not
provided, then the maximum possible value is assu... | 1.741809 | 1.690424 | 1.030398 |
print('Invalid value... should be a string or a list of string')
return None
elif ((not (isinstance(value, list))) and
(not (isinstance(value, tuple))) and
(not (isinstance(value, str)))):
print('Invalid value... should be a string or a list of str... | def parse(value, to_np=None): # @NoSelf
if ((isinstance(value, list) or isinstance(value, tuple)) and
not (isinstance(value[0], str))) | Parses the provided date/time string(s) into CDF epoch value(s).
For CDF_EPOCH:
The string has to be in the form of 'dd-mmm-yyyy hh:mm:ss.xxx' or
'yyyy-mm-ddThh:mm:ss.xxx' (in iso_8601). The string is the output
from encode function.
For CDF_EPOCH16:
... | 2.489784 | 2.223766 | 1.119625 |
def getVersion(): # @NoSelf
print('epochs version:', str(CDFepoch.version) + '.' +
str(CDFepoch.release) + '.'+str(CDFepoch.increment)) | Shows the code version. | null | null | null | |
def getLeapSecondLastUpdated(): # @NoSelf
print('Leap second last updated:', str(CDFepoch.LTS[-1][0]) + '-' +
str(CDFepoch.LTS[-1][1]) + '-' + str(CDFepoch.LTS[-1][2])) | Shows the latest date a leap second was added to the leap second table. | null | null | null | |
'''
Closes the CDF Class.
1. If compression was set, this is where the compressed file is
written.
2. If a checksum is needed, this will place the checksum at the end
of the file.
'''
if self.compressed_file is None:
wi... | def close(self) | Closes the CDF Class.
1. If compression was set, this is where the compressed file is
written.
2. If a checksum is needed, this will place the checksum at the end
of the file. | 4.362647 | 3.111916 | 1.401917 |
'''
Writes ADRs and AEDRs for variables
Parameters:
f : file
The open CDF file
varNum : int
The variable number for adding attributes
var_attrs : dict
A dictionary object full of variable attributes
... | def _write_var_attrs(self, f, varNum, var_attrs, zVar) | Writes ADRs and AEDRs for variables
Parameters:
f : file
The open CDF file
varNum : int
The variable number for adding attributes
var_attrs : dict
A dictionary object full of variable attributes
zVar : bool
... | 3.620916 | 3.111914 | 1.163566 |
'''
Writes a VVR and a VXR for this block of sparse data
Parameters:
f : file
The open CDF file
zVar : bool
True if this is for a z variable
var : int
The variable number
dataType : int
... | def _write_var_data_sparse(self, f, zVar, var, dataType, numElems, recVary,
oneblock) | Writes a VVR and a VXR for this block of sparse data
Parameters:
f : file
The open CDF file
zVar : bool
True if this is for a z variable
var : int
The variable number
dataType : int
The CDF data type... | 3.93887 | 2.867701 | 1.373529 |
'''
Create a VXR AND use a VXR
Parameters:
f : file
The open CDF file
recStart : int
The start record of this block
recEnd : int
The ending record of this block
currentVDR : int
The b... | def _create_vxr(self, f, recStart, recEnd, currentVDR, priorVXR, vvrOffset) | Create a VXR AND use a VXR
Parameters:
f : file
The open CDF file
recStart : int
The start record of this block
recEnd : int
The ending record of this block
currentVDR : int
The byte location of the ... | 3.847107 | 2.302433 | 1.670888 |
'''
Adds a VVR pointer to a VXR
'''
# Select the next unused entry in a VXR for a VVR/CVVR
f.seek(VXRoffset+20)
# num entries
numEntries = int.from_bytes(f.read(4), 'big', signed=True)
# used entries
usedEntries = int.from_bytes(f.read(4), 'big', s... | def _use_vxrentry(self, f, VXRoffset, recStart, recEnd, offset) | Adds a VVR pointer to a VXR | 3.364803 | 3.050399 | 1.10307 |
'''
Build a new level of VXRs... make VXRs more tree-like
From:
VXR1 -> VXR2 -> VXR3 -> VXR4 -> ... -> VXRn
To:
new VXR1
/ | \
VXR2 VXR3 VXR4
/ | \
... | def _add_vxr_levels_r(self, f, vxrhead, numVXRs) | Build a new level of VXRs... make VXRs more tree-like
From:
VXR1 -> VXR2 -> VXR3 -> VXR4 -> ... -> VXRn
To:
new VXR1
/ | \
VXR2 VXR3 VXR4
/ | \
...
... | 3.294071 | 2.126454 | 1.549091 |
'''
This sets a VXR to be the first and last VXR in the VDR
'''
# VDR's VXRhead
self._update_offset_value(f, vdr_offset+28, 8, VXRoffset)
# VDR's VXRtail
self._update_offset_value(f, vdr_offset+36, 8, VXRoffset) | def _update_vdr_vxrheadtail(self, f, vdr_offset, VXRoffset) | This sets a VXR to be the first and last VXR in the VDR | 4.047579 | 2.735396 | 1.479705 |
'''
Finds the first and last record numbers pointed by the VXR
Assumes the VXRs are in order
'''
f.seek(VXRoffset+20)
# Num entries
numEntries = int.from_bytes(f.read(4), 'big', signed=True)
# used entries
usedEntries = int.from_bytes(f.read(4), 'b... | def _get_recrange(self, f, VXRoffset) | Finds the first and last record numbers pointed by the VXR
Assumes the VXRs are in order | 3.148989 | 2.29282 | 1.373413 |
datatype : int
CDF variable data type
numElms : int
number of elements
Returns:
numBytes : int
The number of bytes for the data
'''
sizes = {1: 1,
2: 2,
4: 4,
8... | def _datatype_size(datatype, numElms): # @NoSelf
'''
Gets datatype size
Parameters | Gets datatype size
Parameters:
datatype : int
CDF variable data type
numElms : int
number of elements
Returns:
numBytes : int
The number of bytes for the data | 2.040994 | 1.912844 | 1.066994 |
'''
Writes and ADR to the end of the file.
Additionally, it will update the offset values to either the previous ADR
or the ADRhead field in the GDR.
Parameters:
f : file
The open CDF file
gORv : bool
True if a global attr... | def _write_adr(self, f, gORv, name) | Writes and ADR to the end of the file.
Additionally, it will update the offset values to either the previous ADR
or the ADRhead field in the GDR.
Parameters:
f : file
The open CDF file
gORv : bool
True if a global attribute, False if vari... | 3.198464 | 2.405978 | 1.329382 |
'''
Creates a VXR at the end of the file.
Returns byte location of the VXR
The First, Last, and Offset fields will need to be filled in later
'''
f.seek(0, 2)
byte_loc = f.tell()
section_type = CDF.VXR_
nextVXR = 0
if (numEntries == None):... | def _write_vxr(self, f, numEntries=None) | Creates a VXR at the end of the file.
Returns byte location of the VXR
The First, Last, and Offset fields will need to be filled in later | 2.731781 | 2.177579 | 1.254504 |
'''
Writes a vvr to the end of file "f" with the byte stream "data".
'''
f.seek(0, 2)
byte_loc = f.tell()
block_size = CDF.VVR_BASE_SIZE64 + len(data)
section_type = CDF.VVR_
vvr1 = bytearray(12)
vvr1[0:8] = struct.pack('>q', block_size)
v... | def _write_vvr(self, f, data) | Writes a vvr to the end of file "f" with the byte stream "data". | 4.28067 | 3.178108 | 1.346924 |
'''
Write compression info to the end of the file in a CPR.
'''
f.seek(0, 2)
byte_loc = f.tell()
block_size = CDF.CPR_BASE_SIZE64 + 4
section_type = CDF.CPR_
rfuA = 0
pCount = 1
cpr = bytearray(block_size)
cpr[0:8] = struct.pack('>... | def _write_cpr(self, f, cType, parameter) -> int | Write compression info to the end of the file in a CPR. | 3.271953 | 2.819006 | 1.160676 |
'''
Write compressed "data" variable to the end of the file in a CVVR
'''
f.seek(0, 2)
byte_loc = f.tell()
cSize = len(data)
block_size = CDF.CVVR_BASE_SIZE64 + cSize
section_type = CDF.CVVR_
rfuA = 0
cvvr1 = bytearray(24)
cvvr1[0:... | def _write_cvvr(self, f, data) | Write compressed "data" variable to the end of the file in a CVVR | 3.886512 | 3.267636 | 1.189396 |
'''
Write a CCR to file "g" from file "f" with level "level".
Currently, only handles gzip compression.
Parameters:
f : file
Uncompressed file to read from
g : file
File to read the compressed file into
level : int
... | def _write_ccr(self, f, g, level: int) | Write a CCR to file "g" from file "f" with level "level".
Currently, only handles gzip compression.
Parameters:
f : file
Uncompressed file to read from
g : file
File to read the compressed file into
level : int
The leve... | 4.001733 | 2.997882 | 1.334853 |
'''
Determines which symbol to use for numpy conversions
> : a little endian system to big endian ordering
< : a big endian system to little endian ordering
= : No conversion
'''
data_endian = 'little'
if (self._encoding == 1 or self._encoding == 2 or self... | def _convert_option(self) | Determines which symbol to use for numpy conversions
> : a little endian system to big endian ordering
< : a big endian system to little endian ordering
= : No conversion | 3.994522 | 2.228859 | 1.792183 |
dt_string = 'b'
elif data_type == 2:
dt_string = 'h'
elif data_type == 4:
dt_string = 'i'
elif data_type in (8, 33):
dt_string = 'q'
elif data_type == 11:
dt_string = 'B'
elif data_type == 12:
dt_string = 'H'... | def _convert_type(data_type): # @NoSelf
'''
Converts CDF data types into python types
'''
if data_type in (1, 41) | Converts CDF data types into python types | 1.781768 | 1.746619 | 1.020124 |
return np.int8(data).tobytes()
elif data_type == 2:
return np.int16(data).tobytes()
elif data_type == 4:
return np.int32(data).tobytes()
elif (data_type == 8) or (data_type == 33):
return np.int64(data).tobytes()
elif data_type == 11:
... | def _convert_nptype(data_type, data): # @NoSelf
'''
Converts "data" of CDF type "data_type" into a numpy array
'''
if data_type in (1, 41) | Converts "data" of CDF type "data_type" into a numpy array | 1.510528 | 1.48051 | 1.020275 |
'''
Determines the default pad data for a "data_type"
'''
order = self._convert_option()
if (data_type == 1) or (data_type == 41):
pad_value = struct.pack(order+'b', -127)
elif data_type == 2:
pad_value = struct.pack(order+'h', -32767)
elif... | def _default_pad(self, data_type, numElems) | Determines the default pad data for a "data_type" | 1.984705 | 1.885772 | 1.052463 |
'''
Determines the number of values in a record.
Set zVar=True if this is a zvariable.
'''
values = 1
if (zVar == True):
numDims = self.zvarsinfo[varNum][2]
dimSizes = self.zvarsinfo[varNum][3]
dimVary = self.zvarsinfo[varNum][4]
... | def _num_values(self, zVar, varNum) | Determines the number of values in a record.
Set zVar=True if this is a zvariable. | 2.575518 | 2.089302 | 1.232717 |
'''
Reads an integer value from file "f" at location "offset".
'''
f.seek(offset, 0)
if (size == 8):
return int.from_bytes(f.read(8), 'big', signed=True)
else:
return int.from_bytes(f.read(4), 'big', signed=True) | def _read_offset_value(self, f, offset, size) | Reads an integer value from file "f" at location "offset". | 2.809583 | 2.106357 | 1.333859 |
'''
Writes "value" into location "offset" in file "f".
'''
f.seek(offset, 0)
if (size == 8):
f.write(struct.pack('>q', value))
else:
f.write(struct.pack('>i', value)) | def _update_offset_value(self, f, offset, size, value) | Writes "value" into location "offset" in file "f". | 3.263273 | 2.210963 | 1.475951 |
'''
Computes the checksum of the file
'''
md5 = hashlib.md5()
block_size = 16384
f.seek(0, 2)
remaining = f.tell()
f.seek(0)
while (remaining > block_size):
data = f.read(block_size)
remaining = remaining - block_size
... | def _md5_compute(self, f) | Computes the checksum of the file | 2.365093 | 2.236064 | 1.057703 |
records: list
A list of records that there is data for
Returns:
sparse_blocks: list of list
A list of ranges we have physical values for.
Example:
Input: [1,2,3,4,10,11,12,13,50,51,52,53]
Output: [[1,4],[10,13],[50,53]]
... | def _make_blocks(records): # @NoSelf
'''
Organizes the physical records into blocks in a list by
placing consecutive physical records into a single block, so
lesser VXRs will be created.
[[start_rec1,end_rec1,data_1], [start_rec2,enc_rec2,data_2], ...]
Parameters | Organizes the physical records into blocks in a list by
placing consecutive physical records into a single block, so
lesser VXRs will be created.
[[start_rec1,end_rec1,data_1], [start_rec2,enc_rec2,data_2], ...]
Parameters:
records: list
A list of records t... | 3.407831 | 2.47679 | 1.375906 |
'''
Handles the data for the variable with sparse records.
Organizes the physical record numbers into blocks in a list:
[[start_rec1,end_rec1,data_1], [start_rec2,enc_rec2,data_2], ...]
Place consecutive physical records into a single block
Parameters:
vari... | def _make_sparse_blocks_with_virtual(self, variable, records, data) | Handles the data for the variable with sparse records.
Organizes the physical record numbers into blocks in a list:
[[start_rec1,end_rec1,data_1], [start_rec2,enc_rec2,data_2], ...]
Place consecutive physical records into a single block
Parameters:
variable: dict
... | 3.857735 | 2.117481 | 1.821851 |
mycdf_info = {}
mycdf_info['CDF'] = self.file
mycdf_info['Version'] = self._version
mycdf_info['Encoding'] = self._encoding
mycdf_info['Majority'] = self._majority
mycdf_info['rVariables'], mycdf_info['zVariables'] = self._get_varnames()
mycdf_info['Attri... | def cdf_info(self) | Returns a dictionary that shows the basic CDF information.
This information includes
+---------------+--------------------------------------------------------------------------------+
| ['CDF'] | the name of the CDF ... | 3.487556 | 1.974495 | 1.766302 |
vdr_info = self.varget(variable=variable, inq=True)
if vdr_info is None:
raise KeyError("Variable {} not found.".format(variable))
var = {}
var['Variable'] = vdr_info['name']
var['Num'] = vdr_info['variable_number']
var['Var_Type'] = CDF._variable_to... | def varinq(self, variable) | Returns a dictionary that shows the basic variable information.
This information includes
+-----------------+--------------------------------------------------------------------------------+
| ['Variable'] | the name of the variable ... | 2.795602 | 2.003342 | 1.395469 |
position = self._first_adr
if isinstance(attribute, str):
for _ in range(0, self._num_att):
name, next_adr = self._read_adr_fast(position)
if name.strip().lower() == attribute.strip().lower():
return self._read_adr(position)
... | def attinq(self, attribute=None) | Get attribute information.
Returns
-------
dict
Dictionary of attribution infromation. | 3.788441 | 3.92543 | 0.965102 |
return self.varget(variable=epoch, starttime=starttime,
endtime=endtime, record_range_only=True) | def epochrange(self, epoch=None, starttime=None, endtime=None) | Get epoch range.
Returns a list of the record numbers, representing the
corresponding starting and ending records within the time
range from the epoch data. A None is returned if there is no
data either written or found in the time range. | 10.747846 | 8.978678 | 1.197041 |
byte_loc = self._first_adr
return_dict = {}
for _ in range(0, self._num_att):
adr_info = self._read_adr(byte_loc)
if (adr_info['scope'] != 1):
byte_loc = adr_info['next_adr_location']
continue
if (adr_info['num_gr_entr... | def globalattsget(self, expand=False, to_np=True) | Gets all global attributes.
This function returns all of the global attribute entries,
in a dictionary (in the form of 'attribute': {entry: value}
pair) from a CDF. If there is no entry found, None is
returned. If expand is entered with non-False, then each
entry's data type is ... | 2.240016 | 2.125495 | 1.05388 |
if (isinstance(variable, int) and self._num_zvariable > 0 and self._num_rvariable > 0):
print('This CDF has both r and z variables. Use variable name')
return None
if isinstance(variable, str):
position = self._first_zvariable
num_variables = self... | def varattsget(self, variable=None, expand=False, to_np=True) | Gets all variable attributes.
Unlike attget, which returns a single attribute entry value,
this function returns all of the variable attribute entries,
in a dictionary (in the form of 'attribute': value pair) for
a variable. If there is no entry found, None is returned.
If no va... | 3.041607 | 2.995127 | 1.015519 |
'''
Writes the current file into a file in the temporary directory.
If that doesn't work, create a new file in the CDFs directory.
'''
with self.file.open('rb') as f:
if (self.cdfversion == 3):
data_start, data_size, cType, _ = self._read_ccr(8)
... | def _uncompress_file(self, path) | Writes the current file into a file in the temporary directory.
If that doesn't work, create a new file in the CDFs directory. | 4.120082 | 3.015412 | 1.366341 |
'''
Verifies the MD5 checksum.
Only used in the __init__() function
'''
fn = self.file if self.compressed_file is None else self.compressed_file
md5 = hashlib.md5()
block_size = 16384
with fn.open('rb') as f:
f.seek(-16, 2)
remaini... | def _md5_validation(self) -> bool | Verifies the MD5 checksum.
Only used in the __init__() function | 3.203528 | 2.593454 | 1.235236 |
'''
Determines how to convert CDF byte ordering to the system
byte ordering.
'''
if sys.byteorder == 'little' and self._endian() == 'big-endian':
# big->little
order = '>'
elif sys.byteorder == 'big' and self._endian() == 'little-endian':
... | def _convert_option(self) | Determines how to convert CDF byte ordering to the system
byte ordering. | 5.336882 | 3.026851 | 1.76318 |
'''
Determines endianess of the CDF file
Only used in __init__
'''
if (self._encoding == 1 or self._encoding == 2 or self._encoding == 5 or
self._encoding == 7 or self._encoding == 9 or self._encoding == 11 or
self._encoding == 12):
return ... | def _endian(self) -> str | Determines endianess of the CDF file
Only used in __init__ | 4.119227 | 2.60265 | 1.582705 |
'''
Returns the number of values in a record, using a given VDR
dictionary. Multiplies the dimension sizes of each dimension,
if it is varying.
'''
values = 1
for x in range(0, vdr_dict['num_dims']):
if (vdr_dict['dim_vary'][x] != 0):
v... | def _num_values(self, vdr_dict) | Returns the number of values in a record, using a given VDR
dictionary. Multiplies the dimension sizes of each dimension,
if it is varying. | 5.153208 | 2.217364 | 2.324024 |
'''
CDF data types to python struct data types
'''
if (data_type == 1) or (data_type == 41):
dt_string = 'b'
elif data_type == 2:
dt_string = 'h'
elif data_type == 4:
dt_string = 'i'
elif (data_type == 8) or (data_type == 33):
... | def _convert_type(self, data_type) | CDF data types to python struct data types | 1.866621 | 1.713274 | 1.089505 |
return str(' '*num_elms)
if (data_type == 1) or (data_type == 41):
pad_value = struct.pack(order+'b', -127)
dt_string = 'i1'
elif data_type == 2:
pad_value = struct.pack(order+'h', -32767)
dt_string = 'i2'
elif data_type == 4:
... | def _default_pad(self, data_type, num_elms): # @NoSelf
'''
The default pad values by CDF data type
'''
order = self._convert_option()
if (data_type == 51 or data_type == 52) | The default pad values by CDF data type | 1.711444 | 1.715233 | 0.997791 |
if (data == ''):
return ('\x00'*num_elems).encode()
else:
return data.ljust(num_elems, '\x00').encode('utf-8')
elif (data_type == 32):
data_stream = data.real.tobytes()
data_stream += data.imag.tobytes()
return data_stre... | def _convert_np_data(data, data_type, num_elems): # @NoSelf
'''
Converts a single np data into byte stream.
'''
if (data_type == 51 or data_type == 52) | Converts a single np data into byte stream. | 3.097059 | 2.925126 | 1.058778 |
'''
Returns a VVR or decompressed CVVR block
'''
with self.file.open('rb') as f:
f.seek(offset, 0)
block_size = int.from_bytes(f.read(8), 'big')
block = f.read(block_size-8)
section_type = int.from_bytes(block[0:4], 'big')
if section_t... | def _read_vvr_block(self, offset) | Returns a VVR or decompressed CVVR block | 2.913638 | 2.318245 | 1.256829 |
cur_block = 0
for x in range(cur_block, total):
if (starts[x] <= rec_num and ends[x] >= rec_num):
return x, x
if (starts[x] > rec_num):
break
return -1, x-1 | def _find_block(starts, ends, cur_block, rec_num): # @NoSelf
'''
Finds the block that rec_num is in if it is found. Otherwise it returns -1.
It also returns the block that has the physical data either at or
preceeding the rec_num.
It could be -1 if the preceeding block does not... | Finds the block that rec_num is in if it is found. Otherwise it returns -1.
It also returns the block that has the physical data either at or
preceeding the rec_num.
It could be -1 if the preceeding block does not exists. | 2.570799 | 2.72754 | 0.942534 |
'''
Converts data to the appropriate type using the struct.unpack method,
rather than using numpy.
'''
if (data_type == 51 or data_type == 52):
return [data[i:i+num_elems].decode('utf-8') for i in
range(0, num_recs*num_values*num_elems, num_elems)... | def _convert_data(self, data, data_type, num_recs, num_values, num_elems) | Converts data to the appropriate type using the struct.unpack method,
rather than using numpy. | 4.396858 | 3.54434 | 1.240529 |
def getVersion(): # @NoSelf
print('CDFread version:', str(CDF.version) + '.' + str(CDF.release) +
'.' + str(CDF.increment))
print('Date: 2018/01/11') | Shows the code version and last modified date. | null | null | null | |
'''
Returns an access token for the specified subscription.
This method uses a cache to limit the number of requests to the token service.
A fresh token can be re-used during its lifetime of 10 minutes. After a successful
request to the token service, this method caches the acce... | def get_access_token(self) | Returns an access token for the specified subscription.
This method uses a cache to limit the number of requests to the token service.
A fresh token can be re-used during its lifetime of 10 minutes. After a successful
request to the token service, this method caches the access token. Subsequent... | 3.881863 | 1.666245 | 2.329707 |
text = ' '.join(text)
kwargs = dict(from_lang=from_lang, to_lang=to_lang, provider=provider)
if provider != DEFAULT_PROVIDER:
kwargs['secret_access_key'] = secret_access_key
translator = Translator(**kwargs)
translation = translator.translate(text)
if sys.version_info.major == 2:
... | def main(from_lang, to_lang, provider, secret_access_key, output_only, text) | Python command line tool to make on line translations
\b
Example:
\b
\t $ translate-cli -t zh the book is on the table
\t 碗是在桌子上。
\b
Available languages:
\b
\t https://en.wikipedia.org/wiki/ISO_639-1
\t Examples: (e.g. en, ja, ko, pt, zh, zh-TW, ...) | 2.420907 | 2.737742 | 0.884271 |
server_configs = (
{'url': url, 'auth': ('admin', 'changeme'), 'verify': False}
for url
in ('https://sat1.example.com', 'https://sat2.example.com')
)
for server_config in server_configs:
response = requests.post(
server_config['url'] + '/api/v2/users',
... | def main() | Create an identical user account on a pair of satellites. | 3.494028 | 3.218478 | 1.085615 |
response = requests.get(
server_config['url'] + '/katello/api/v2/organizations',
data=json.dumps({'search': 'label={}'.format(label)}),
auth=server_config['auth'],
headers={'content-type': 'application/json'},
verify=server_config['verify'],
)
response.raise_for_... | def get_organization_id(server_config, label) | Return the ID of the organization with label ``label``.
:param server_config: A dict of information about the server being talked
to. The dict should include the keys "url", "auth" and "verify".
:param label: A string label that will be used when searching. Every
organization should have a uniq... | 2.738744 | 2.751678 | 0.995299 |
org = Organization(name='junk org').create()
pprint(org.get_values()) # e.g. {'name': 'junk org', …}
org.delete() | def main() | Create an organization, print out its attributes and delete it. | 10.756598 | 6.430594 | 1.672722 |
if poll_rate is None:
poll_rate = TASK_POLL_RATE
if timeout is None:
timeout = TASK_TIMEOUT
# Implement the timeout.
def raise_task_timeout(): # pragma: no cover
thread.interrupt_main()
timer = threading.Timer(timeout, raise_task_timeout)
# Poll until th... | def _poll_task(task_id, server_config, poll_rate=None, timeout=None) | Implement :meth:`nailgun.entities.ForemanTask.poll`.
See :meth:`nailgun.entities.ForemanTask.poll` for a full description of how
this method acts. Other methods may also call this method, such as
:meth:`nailgun.entity_mixins.EntityDeleteMixin.delete`.
Certain mixins benefit from being able to poll the... | 2.897755 | 2.950463 | 0.982136 |
if isinstance(entity_obj_or_id, entity_cls):
return entity_obj_or_id
return entity_cls(server_config, id=entity_obj_or_id) | def _make_entity_from_id(entity_cls, entity_obj_or_id, server_config) | Given an entity object or an ID, return an entity object.
If the value passed in is an object that is a subclass of :class:`Entity`,
return that value. Otherwise, create an object of the type that ``field``
references, give that object an ID of ``field_value``, and return that
object.
:param entit... | 2.050203 | 2.443733 | 0.838964 |
return [
_make_entity_from_id(entity_cls, entity_or_id, server_config)
for entity_or_id
in entity_objs_and_ids
] | def _make_entities_from_ids(entity_cls, entity_objs_and_ids, server_config) | Given an iterable of entities and/or IDs, return a list of entities.
:param entity_cls: An :class:`Entity` subclass.
:param entity_obj_or_id: An iterable of
:class:`nailgun.entity_mixins.Entity` objects and/or entity IDs. All of
the entities in this iterable should be of type ``entity_cls``.
... | 2.487909 | 3.359149 | 0.740637 |
for field_name, field in fields.items():
if field_name in values:
if isinstance(field, OneToOneField):
values[field_name + '_id'] = (
getattr(values.pop(field_name), 'id', None)
)
elif isinstance(field, OneToManyField):
... | def _payload(fields, values) | Implement the ``*_payload`` methods.
It's frequently useful to create a dict of values that can be encoded to
JSON and sent to the server. Unfortunately, there are mismatches between
the field names used by NailGun and the field names the server expects.
This method provides a default translation that ... | 2.664506 | 2.657631 | 1.002587 |
field_name_id = field_name + '_id'
if field_name in attrs:
if attrs[field_name] is None:
return None
elif 'id' in attrs[field_name]:
return attrs[field_name]['id']
if field_name_id in attrs:
return attrs[field_name_id]
else:
raise MissingValue... | def _get_entity_id(field_name, attrs) | Find the ID for a one to one relationship.
The server may return JSON data in the following forms for a
:class:`nailgun.entity_fields.OneToOneField`::
'user': None
'user': {'name': 'Alice Hayes', 'login': 'ahayes', 'id': 1}
'user_id': 1
'user_id': None
Search ``attrs`` for... | 2.908531 | 3.149478 | 0.923496 |
field_name_ids = field_name + '_ids'
plural_field_name = pluralize(field_name)
if field_name_ids in attrs:
return attrs[field_name_ids]
elif field_name in attrs:
return [entity['id'] for entity in attrs[field_name]]
elif plural_field_name in attrs:
return [entity['id'] f... | def _get_entity_ids(field_name, attrs) | Find the IDs for a one to many relationship.
The server may return JSON data in the following forms for a
:class:`nailgun.entity_fields.OneToManyField`::
'user': [{'id': 1, …}, {'id': 42, …}]
'users': [{'id': 1, …}, {'id': 42, …}]
'user_ids': [1, 42]
Search ``attrs`` for a one to ... | 2.609215 | 2.8092 | 0.928811 |
if isinstance(obj, Entity):
return obj.to_json_dict()
if isinstance(obj, dict):
return {k: to_json_serializable(v) for k, v in obj.items()}
elif isinstance(obj, (list, tuple)):
return [to_json_serializable(v) for v in obj]
elif isinstance(obj, datetime):
return obj.... | def to_json_serializable(obj) | Transforms obj into a json serializable object.
:param obj: entity or any json serializable object
:return: serializable object | 1.648701 | 1.722392 | 0.957216 |
# It is OK that member ``self._meta`` is not found. Subclasses are
# required to set that attribute if they wish to use this method.
#
# Beware of leading and trailing slashes:
#
# urljoin('example.com', 'foo') => 'foo'
# urljoin('example.com/', '... | def path(self, which=None) | Return the path to the current entity.
Return the path to base entities of this entity's type if:
* ``which`` is ``'base'``, or
* ``which`` is ``None`` and instance attribute ``id`` is unset.
Return the path to this exact entity if instance attribute ``id`` is
set and:
... | 4.152833 | 3.517249 | 1.180705 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.