_id
stringlengths 2
7
| title
stringlengths 1
88
| partition
stringclasses 3
values | text
stringlengths 75
19.8k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q21800
|
TimeLine.zoom_out
|
train
|
def zoom_out(self):
"""Decrease zoom factor and redraw TimeLine"""
index = self._zoom_factors.index(self._zoom_factor)
if index == 0:
# Already zoomed out all the way
return
self._zoom_factor = self._zoom_factors[index - 1]
if self._zoom_factors.index(self._zoom_factor) == 0:
self._button_zoom_out.config(state=tk.DISABLED)
self._button_zoom_in.config(state=tk.NORMAL)
self.draw_timeline()
|
python
|
{
"resource": ""
}
|
q21801
|
TimeLine.zoom_reset
|
train
|
def zoom_reset(self):
"""Reset the zoom factor to default and redraw TimeLine"""
self._zoom_factor = self._zoom_factors[0] if self._zoom_default == 0 else self._zoom_default
if self._zoom_factors.index(self._zoom_factor) == 0:
self._button_zoom_out.config(state=tk.DISABLED)
self._button_zoom_in.config(state=tk.NORMAL)
elif self._zoom_factors.index(self.zoom_factor) + 1 == len(self._zoom_factors):
self._button_zoom_out.config(state=tk.NORMAL)
self._button_zoom_in.config(state=tk.DISABLED)
self.draw_timeline()
|
python
|
{
"resource": ""
}
|
q21802
|
TimeLine.set_time
|
train
|
def set_time(self, time):
"""
Set the time marker to a specific time
:param time: Time to set for the time marker on the TimeLine
:type time: float
"""
x = self.get_time_position(time)
_, y = self._canvas_ticks.coords(self._time_marker_image)
self._canvas_ticks.coords(self._time_marker_image, x, y)
self._timeline.coords(self._time_marker_line, x, 0, x, self._timeline.winfo_height())
|
python
|
{
"resource": ""
}
|
q21803
|
TimeLine._time_show
|
train
|
def _time_show(self):
"""Show the time marker window"""
if not self._time_visible:
self._time_visible = True
self._time_window = tk.Toplevel(self)
self._time_window.attributes("-topmost", True)
self._time_window.overrideredirect(True)
self._time_label = ttk.Label(self._time_window)
self._time_label.grid()
self._time_window.lift()
x, y = self.master.winfo_pointerxy()
geometry = "{0}x{1}+{2}+{3}".format(
self._time_label.winfo_width(),
self._time_label.winfo_height(),
x - 15,
self._canvas_ticks.winfo_rooty() - 10)
self._time_window.wm_geometry(geometry)
self._time_label.config(text=TimeLine.get_time_string(self.time, self._unit))
|
python
|
{
"resource": ""
}
|
q21804
|
TimeLine.tag_configure
|
train
|
def tag_configure(self, tag_name, **kwargs):
"""
Create a marker tag
:param tag_name: Identifier for the tag
:param move_callback: Callback to be called upon moving a
marker. Arguments to callback:
``(iid: str, (old_start: float, old_finish: float),
(new_start: float, new_finish: float))``
:type move_callback: callable
:param left_callback: Callback to be called upon left clicking
a marker. Arguments to callback:
``(iid: str, x_coord: int, y_coord: int)``
:type left_callback: callable
:param right_callback: Callback to be called upon right clicking
a marker. Arguments to callback:
``(iid: str, x_coord: int, y_coord: int)``
:type right_callback: callable
:param menu: A Menu widget to show upon right click. Can be
used with the right_callback option simultaneously.
:type menu: tk.Menu
In addition, supports all options supported by markers. Note
that tag options are applied to markers upon marker creation,
and thus is a tag is updated, the markers are not automatically
updated as well.
"""
callbacks = [
kwargs.get("move_callback", None),
kwargs.get("left_callback", None),
kwargs.get("right_callback", None)
]
for callback in callbacks:
if callback is not None and not callable(callback):
raise ValueError("One or more callbacks is not a callable object")
self._tags[tag_name] = kwargs
|
python
|
{
"resource": ""
}
|
q21805
|
TimeLine.marker_tags
|
train
|
def marker_tags(self, iid):
"""Generator for all the tags of a certain marker"""
tags = self._markers[iid]["tags"]
for tag in tags:
yield tag
|
python
|
{
"resource": ""
}
|
q21806
|
TimeLine._set_scroll_v
|
train
|
def _set_scroll_v(self, *args):
"""Scroll both categories Canvas and scrolling container"""
self._canvas_categories.yview(*args)
self._canvas_scroll.yview(*args)
|
python
|
{
"resource": ""
}
|
q21807
|
TimeLine._set_scroll
|
train
|
def _set_scroll(self, *args):
"""Set horizontal scroll of scroll container and ticks Canvas"""
self._canvas_scroll.xview(*args)
self._canvas_ticks.xview(*args)
|
python
|
{
"resource": ""
}
|
q21808
|
TimeLine.get_time_position
|
train
|
def get_time_position(self, time):
"""
Get x-coordinate for given time
:param time: Time to determine x-coordinate on Canvas for
:type time: float
:return: X-coordinate for the given time
:rtype: int
:raises: ValueError
"""
if time < self._start or time > self._finish:
raise ValueError("time argument out of bounds")
return (time - self._start) / (self._resolution / self._zoom_factor)
|
python
|
{
"resource": ""
}
|
q21809
|
TimeLine.get_position_time
|
train
|
def get_position_time(self, position):
"""
Get time for x-coordinate
:param position: X-coordinate position to determine time for
:type position: int
:return: Time for the given x-coordinate
:rtype: float
"""
return self._start + position * (self._resolution / self._zoom_factor)
|
python
|
{
"resource": ""
}
|
q21810
|
TimeLine.get_time_string
|
train
|
def get_time_string(time, unit):
"""
Create a properly formatted string given a time and unit
:param time: Time to format
:type time: float
:param unit: Unit to apply format of. Only supports hours ('h')
and minutes ('m').
:type unit: str
:return: A string in format '{whole}:{part}'
:rtype: str
"""
supported_units = ["h", "m"]
if unit not in supported_units:
return "{}".format(round(time, 2))
hours, minutes = str(time).split(".")
hours = int(hours)
minutes = int(round(float("0.{}".format(minutes)) * 60))
return "{:02d}:{:02d}".format(hours, minutes)
|
python
|
{
"resource": ""
}
|
q21811
|
TimeLine._right_click
|
train
|
def _right_click(self, event):
"""Function bound to right click event for marker canvas"""
iid = self.current_iid
if iid is None:
if self._menu is not None:
self._menu.post(event.x, event.y)
return
args = (iid, (event.x_root, event.y_root))
self.call_callbacks(iid, "right_callback", args)
tags = list(self.marker_tags(iid))
if len(tags) == 0:
return
menu = self._tags[tags[-1]].get("menu", None)
if menu is None or not isinstance(menu, tk.Menu):
return
menu.post(event.x_root, event.y_root)
|
python
|
{
"resource": ""
}
|
q21812
|
TimeLine._left_click
|
train
|
def _left_click(self, event):
"""Function bound to left click event for marker canvas"""
self.update_active()
iid = self.current_iid
if iid is None:
return
args = (iid, event.x_root, event.y_root)
self.call_callbacks(iid, "left_callback", args)
|
python
|
{
"resource": ""
}
|
q21813
|
TimeLine.update_state
|
train
|
def update_state(self, iid, state):
"""
Set a custom state of the marker
:param iid: identifier of the marker to set the state of
:type iid: str
:param state: supports "active", "hover", "normal"
:type state: str
"""
if state not in ["normal", "hover", "active"]:
raise ValueError("Invalid state: {}".format(state))
marker = self._markers[iid]
rectangle_id, text_id = marker["rectangle_id"], marker["text_id"]
state = "" if state == "normal" else state + "_"
colors = {}
for color_type in ["background", "foreground", "outline", "border"]:
value = marker[state + color_type]
attribute = "_marker_{}".format(color_type)
colors[color_type] = getattr(self, attribute) if value == "default" else value
self._timeline.itemconfigure(rectangle_id, fill=colors["background"], width=colors["border"],
outline=colors["outline"])
self._timeline.itemconfigure(text_id, fill=colors["foreground"])
|
python
|
{
"resource": ""
}
|
q21814
|
TimeLine.update_active
|
train
|
def update_active(self):
"""Update the active marker on the marker Canvas"""
if self.active is not None:
self.update_state(self.active, "normal")
if self.current_iid == self.active:
self._active = None
return
self._active = self.current_iid
if self.active is not None:
self.update_state(self.active, "active")
|
python
|
{
"resource": ""
}
|
q21815
|
TimeLine.call_callbacks
|
train
|
def call_callbacks(self, iid, type, args):
"""
Call the available callbacks for a certain marker
:param iid: marker identifier
:type iid: str
:param type: type of callback (key in tag dictionary)
:type type: str
:param args: arguments for the callback
:type args: tuple
:return: amount of callbacks called
:rtype: int
"""
amount = 0
for tag in self.marker_tags(iid):
callback = self._tags[tag].get(type, None)
if callback is not None:
amount += 1
callback(*args)
return amount
|
python
|
{
"resource": ""
}
|
q21816
|
TimeLine.time
|
train
|
def time(self):
"""
Current value the time marker is pointing to
:rtype: float
"""
x, _, = self._canvas_ticks.coords(self._time_marker_image)
return self.get_position_time(x)
|
python
|
{
"resource": ""
}
|
q21817
|
TimeLine.current
|
train
|
def current(self):
"""
Currently active item on the _timeline Canvas
:rtype: str
"""
results = self._timeline.find_withtag(tk.CURRENT)
return results[0] if len(results) != 0 else None
|
python
|
{
"resource": ""
}
|
q21818
|
TimeLine.current_iid
|
train
|
def current_iid(self):
"""
Currently active item's iid
:rtype: str
"""
current = self.current
if current is None or current not in self._canvas_markers:
return None
return self._canvas_markers[current]
|
python
|
{
"resource": ""
}
|
q21819
|
TimeLine.pixel_width
|
train
|
def pixel_width(self):
"""
Width of the whole TimeLine in pixels
:rtype: int
"""
return self.zoom_factor * ((self._finish - self._start) / self._resolution)
|
python
|
{
"resource": ""
}
|
q21820
|
TimeLine.configure
|
train
|
def configure(self, cnf={}, **kwargs):
"""Update options of the TimeLine widget"""
kwargs.update(cnf)
TimeLine.check_kwargs(kwargs)
scrollbars = 'autohidescrollbars' in kwargs
for option in self.options:
attribute = "_" + option
setattr(self, attribute, kwargs.pop(option, getattr(self, attribute)))
if scrollbars:
self._scrollbar_timeline.destroy()
self._scrollbar_vertical.destroy()
if self._autohidescrollbars:
self._scrollbar_timeline = AutoHideScrollbar(self, command=self._set_scroll, orient=tk.HORIZONTAL)
self._scrollbar_vertical = AutoHideScrollbar(self, command=self._set_scroll_v, orient=tk.VERTICAL)
else:
self._scrollbar_timeline = ttk.Scrollbar(self, command=self._set_scroll, orient=tk.HORIZONTAL)
self._scrollbar_vertical = ttk.Scrollbar(self, command=self._set_scroll_v, orient=tk.VERTICAL)
self._canvas_scroll.config(xscrollcommand=self._scrollbar_timeline.set,
yscrollcommand=self._scrollbar_vertical.set)
self._canvas_categories.config(yscrollcommand=self._scrollbar_vertical.set)
self._scrollbar_timeline.grid(column=1, row=2, padx=(0, 5), pady=(0, 5), sticky="we")
self._scrollbar_vertical.grid(column=2, row=0, pady=5, padx=(0, 5), sticky="ns")
ttk.Frame.configure(self, **kwargs)
self.draw_timeline()
|
python
|
{
"resource": ""
}
|
q21821
|
TimeLine.cget
|
train
|
def cget(self, item):
"""Return the value of an option"""
return getattr(self, "_" + item) if item in self.options else ttk.Frame.cget(self, item)
|
python
|
{
"resource": ""
}
|
q21822
|
TimeLine.itemconfigure
|
train
|
def itemconfigure(self, iid, rectangle_options, text_options):
"""
Configure options of items drawn on the Canvas
Low-level access to the individual elements of markers and other
items drawn on the timeline Canvas. All modifications are
overwritten when the TimeLine is redrawn.
"""
rectangle_id, text_id = self._markers[iid]["rectangle_id"], self._markers[iid]["text_id"]
if len(rectangle_options) != 0:
self._timeline.itemconfigure(rectangle_id, **rectangle_options)
if len(text_options) != 0:
self._timeline.itemconfigure(text_id, **text_options)
|
python
|
{
"resource": ""
}
|
q21823
|
TimeLine.calculate_text_coords
|
train
|
def calculate_text_coords(rectangle_coords):
"""Calculate Canvas text coordinates based on rectangle coords"""
return (int(rectangle_coords[0] + (rectangle_coords[2] - rectangle_coords[0]) / 2),
int(rectangle_coords[1] + (rectangle_coords[3] - rectangle_coords[1]) / 2))
|
python
|
{
"resource": ""
}
|
q21824
|
TimeLine.check_marker_kwargs
|
train
|
def check_marker_kwargs(self, kwargs):
"""
Check the types of the keyword arguments for marker creation
:param kwargs: dictionary of options for marker creation
:type kwargs: dict
:raises: TypeError, ValueError
"""
text = kwargs.get("text", "")
if not isinstance(text, str) and text is not None:
raise TypeError("text argument is not of str type")
for color in (item for item in (prefix + color for prefix in ["active_", "hover_", ""]
for color in ["background", "foreground", "outline"])):
value = kwargs.get(color, "")
if value == "default":
continue
if not isinstance(value, str):
raise TypeError("{} argument not of str type".format(color))
font = kwargs.get("font", ("default", 10))
if (not isinstance(font, tuple) or not len(font) > 0 or not isinstance(font[0], str)) and font != "default":
raise ValueError("font argument is not a valid font tuple")
for border in (prefix + "border" for prefix in ["active_", "hover_", ""]):
border_v = kwargs.get(border, 0)
if border_v == "default":
continue
if not isinstance(border_v, int) or border_v < 0:
raise ValueError("{} argument is not of int type or smaller than zero".format(border))
iid = kwargs.get("iid", "-1")
if not isinstance(iid, str):
raise TypeError("iid argument not of str type")
if iid == "":
raise ValueError("iid argument empty string")
for boolean_arg in ["move", "category_change", "allow_overlap", "snap_to_ticks"]:
value = kwargs.get(boolean_arg, False)
if value == "default":
continue
if not isinstance(value, bool):
raise TypeError("{} argument is not of bool type".format(boolean_arg))
tags = kwargs.get("tags", ())
if not isinstance(tags, tuple):
raise TypeError("tags argument is not of tuple type")
for tag in tags:
if not isinstance(tag, str):
raise TypeError("one or more values in tags argument is not of str type")
if tag not in self._tags:
raise ValueError("unknown tag in tags argument")
|
python
|
{
"resource": ""
}
|
q21825
|
ScrolledFrame.__grid_widgets
|
train
|
def __grid_widgets(self):
"""Places all the child widgets in the appropriate positions."""
scrollbar_column = 0 if self.__compound is tk.LEFT else 2
self._canvas.grid(row=0, column=1, sticky="nswe")
self._scrollbar.grid(row=0, column=scrollbar_column, sticky="ns")
|
python
|
{
"resource": ""
}
|
q21826
|
AutoHideScrollbar._get_info
|
train
|
def _get_info(self, layout):
"""Alternative to pack_info and place_info in case of bug."""
info = str(self.tk.call(layout, 'info', self._w)).split("-")
dic = {}
for i in info:
if i:
key, val = i.strip().split()
dic[key] = val
return dic
|
python
|
{
"resource": ""
}
|
q21827
|
CheckboxTreeview.expand_all
|
train
|
def expand_all(self):
"""Expand all items."""
def aux(item):
self.item(item, open=True)
children = self.get_children(item)
for c in children:
aux(c)
children = self.get_children("")
for c in children:
aux(c)
|
python
|
{
"resource": ""
}
|
q21828
|
CheckboxTreeview.collapse_all
|
train
|
def collapse_all(self):
"""Collapse all items."""
def aux(item):
self.item(item, open=False)
children = self.get_children(item)
for c in children:
aux(c)
children = self.get_children("")
for c in children:
aux(c)
|
python
|
{
"resource": ""
}
|
q21829
|
CheckboxTreeview.change_state
|
train
|
def change_state(self, item, state):
"""
Replace the current state of the item.
i.e. replace the current state tag but keeps the other tags.
:param item: item id
:type item: str
:param state: "checked", "unchecked" or "tristate": new state of the item
:type state: str
"""
tags = self.item(item, "tags")
states = ("checked", "unchecked", "tristate")
new_tags = [t for t in tags if t not in states]
new_tags.append(state)
self.item(item, tags=tuple(new_tags))
|
python
|
{
"resource": ""
}
|
q21830
|
CheckboxTreeview.get_checked
|
train
|
def get_checked(self):
"""Return the list of checked items that do not have any child."""
checked = []
def get_checked_children(item):
if not self.tag_has("unchecked", item):
ch = self.get_children(item)
if not ch and self.tag_has("checked", item):
checked.append(item)
else:
for c in ch:
get_checked_children(c)
ch = self.get_children("")
for c in ch:
get_checked_children(c)
return checked
|
python
|
{
"resource": ""
}
|
q21831
|
CheckboxTreeview._check_descendant
|
train
|
def _check_descendant(self, item):
"""Check the boxes of item's descendants."""
children = self.get_children(item)
for iid in children:
self.change_state(iid, "checked")
self._check_descendant(iid)
|
python
|
{
"resource": ""
}
|
q21832
|
CheckboxTreeview._tristate_parent
|
train
|
def _tristate_parent(self, item):
"""
Put the box of item in tristate and change the state of the boxes of
item's ancestors accordingly.
"""
self.change_state(item, "tristate")
parent = self.parent(item)
if parent:
self._tristate_parent(parent)
|
python
|
{
"resource": ""
}
|
q21833
|
CheckboxTreeview._uncheck_descendant
|
train
|
def _uncheck_descendant(self, item):
"""Uncheck the boxes of item's descendant."""
children = self.get_children(item)
for iid in children:
self.change_state(iid, "unchecked")
self._uncheck_descendant(iid)
|
python
|
{
"resource": ""
}
|
q21834
|
CheckboxTreeview._uncheck_ancestor
|
train
|
def _uncheck_ancestor(self, item):
"""
Uncheck the box of item and change the state of the boxes of item's
ancestors accordingly.
"""
self.change_state(item, "unchecked")
parent = self.parent(item)
if parent:
children = self.get_children(parent)
b = ["unchecked" in self.item(c, "tags") for c in children]
if False in b:
# at least one box is checked and item's box is unchecked
self._tristate_parent(parent)
else:
# no box is checked
self._uncheck_ancestor(parent)
|
python
|
{
"resource": ""
}
|
q21835
|
CheckboxTreeview._box_click
|
train
|
def _box_click(self, event):
"""Check or uncheck box when clicked."""
x, y, widget = event.x, event.y, event.widget
elem = widget.identify("element", x, y)
if "image" in elem:
# a box was clicked
item = self.identify_row(y)
if self.tag_has("unchecked", item) or self.tag_has("tristate", item):
self._check_ancestor(item)
self._check_descendant(item)
else:
self._uncheck_descendant(item)
self._uncheck_ancestor(item)
|
python
|
{
"resource": ""
}
|
q21836
|
TickScale._apply_style
|
train
|
def _apply_style(self):
"""Apply the scale style to the frame and labels."""
ttk.Frame.configure(self, style=self._style_name + ".TFrame")
self.label.configure(style=self._style_name + ".TLabel")
bg = self.style.lookup('TFrame', 'background', default='light grey')
for label in self.ticklabels:
label.configure(style=self._style_name + ".TLabel")
self.style.configure(self._style_name + ".TFrame",
background=self.style.lookup(self._style_name,
'background',
default=bg))
self.style.map(self._style_name + ".TFrame",
background=self.style.map(self._style_name, 'background'))
self.style.configure(self._style_name + ".TLabel",
font=self.style.lookup(self._style_name, 'font', default='TkDefaultFont'),
background=self.style.lookup(self._style_name, 'background', default=bg),
foreground=self.style.lookup(self._style_name, 'foreground', default='black'))
self.style.map(self._style_name + ".TLabel",
font=self.style.map(self._style_name, 'font'),
background=self.style.map(self._style_name, 'background'),
foreground=self.style.map(self._style_name, 'foreground'))
|
python
|
{
"resource": ""
}
|
q21837
|
TickScale._init
|
train
|
def _init(self):
"""Create and grid the widgets."""
for label in self.ticklabels:
label.destroy()
self.label.place_forget()
self.ticks = []
self.ticklabels = []
if self._resolution > 0:
nb_steps = round((self.scale.cget('to') - self.scale.cget('from')) / self._resolution)
self.scale.configure(to=self.scale.cget('from') + nb_steps * self._resolution)
self._extent = self.scale.cget('to') - self.scale.cget('from')
if str(self.scale.cget('orient')) == "horizontal":
self.get_scale_length = self.scale.winfo_width
self.display_value = self._display_value_horizontal
self._update_slider_length = self._update_slider_length_horizontal
self.place_ticks = self._place_ticks_horizontal
self._init_horizontal()
else:
self.get_scale_length = self.scale.winfo_height
self.display_value = self._display_value_vertical
self._update_slider_length = self._update_slider_length_vertical
self.place_ticks = self._place_ticks_vertical
self._init_vertical()
self.scale.lift()
try:
self._var.trace_remove('write', self._trace)
self._trace = self._var.trace_add('write', self._increment)
except AttributeError:
# backward compatibility
self._var.trace_vdelete('w', self._trace)
self._trace = self._var.trace('w', self._increment)
self._update_slider_length()
|
python
|
{
"resource": ""
}
|
q21838
|
TickScale._place_ticks_horizontal
|
train
|
def _place_ticks_horizontal(self):
"""Display the ticks for a horizontal scale."""
# first tick
tick = self.ticks[0]
label = self.ticklabels[0]
x = self.convert_to_pixels(tick)
half_width = label.winfo_reqwidth() / 2
if x - half_width < 0:
x = half_width
label.place_configure(x=x)
# ticks in the middle
for tick, label in zip(self.ticks[1:-1], self.ticklabels[1:-1]):
x = self.convert_to_pixels(tick)
label.place_configure(x=x)
# last tick
tick = self.ticks[-1]
label = self.ticklabels[-1]
x = self.convert_to_pixels(tick)
half_width = label.winfo_reqwidth() / 2
if x + half_width > self.scale.winfo_reqwidth():
x = self.scale.winfo_width() - half_width
label.place_configure(x=x)
|
python
|
{
"resource": ""
}
|
q21839
|
TickScale._place_ticks_vertical
|
train
|
def _place_ticks_vertical(self):
"""Display the ticks for a vertical slider."""
for tick, label in zip(self.ticks, self.ticklabels):
y = self.convert_to_pixels(tick)
label.place_configure(y=y)
|
python
|
{
"resource": ""
}
|
q21840
|
TickScale._increment
|
train
|
def _increment(self, *args):
"""Move the slider only by increment given by resolution."""
value = self._var.get()
if self._resolution:
value = self._start + int(round((value - self._start) / self._resolution)) * self._resolution
self._var.set(value)
self.display_value(value)
|
python
|
{
"resource": ""
}
|
q21841
|
TickScale._update_display
|
train
|
def _update_display(self, event=None):
"""Redisplay the ticks and the label so that they adapt to the new size of the scale."""
try:
if self._showvalue:
self.display_value(self.scale.get())
if self._tickinterval:
self.place_ticks()
except IndexError:
# happens when configure is called during a orientation change
# because self.ticks is empty
pass
|
python
|
{
"resource": ""
}
|
q21842
|
ColorSquare._fill
|
train
|
def _fill(self):
"""Create the gradient."""
r, g, b = hue2col(self._hue)
width = self.winfo_width()
height = self.winfo_height()
h = float(height - 1)
w = float(width - 1)
if height:
c = [(r + i / h * (255 - r), g + i / h * (255 - g), b + i / h * (255 - b)) for i in range(height)]
data = []
for i in range(height):
line = []
for j in range(width):
rij = round2(j / w * c[i][0])
gij = round2(j / w * c[i][1])
bij = round2(j / w * c[i][2])
color = rgb_to_hexa(rij, gij, bij)
line.append(color)
data.append("{" + " ".join(line) + "}")
self.bg.put(" ".join(data))
|
python
|
{
"resource": ""
}
|
q21843
|
ColorSquare._draw
|
train
|
def _draw(self, color):
"""Draw the gradient and the selection cross on the canvas."""
width = self.winfo_width()
height = self.winfo_height()
self.delete("bg")
self.delete("cross_h")
self.delete("cross_v")
del self.bg
self.bg = tk.PhotoImage(width=width, height=height, master=self)
self._fill()
self.create_image(0, 0, image=self.bg, anchor="nw", tags="bg")
self.tag_lower("bg")
h, s, v = color
x = v / 100.
y = (1 - s / 100.)
self.create_line(0, y * height, width, y * height, tags="cross_h",
fill="#C2C2C2")
self.create_line(x * width, 0, x * width, height, tags="cross_v",
fill="#C2C2C2")
|
python
|
{
"resource": ""
}
|
q21844
|
ColorSquare.set_hue
|
train
|
def set_hue(self, value):
"""
Change hue.
:param value: new hue value (between 0 and 360)
:type value: int
"""
old = self._hue
self._hue = value
if value != old:
self._fill()
self.event_generate("<<ColorChanged>>")
|
python
|
{
"resource": ""
}
|
q21845
|
ColorSquare._on_click
|
train
|
def _on_click(self, event):
"""Move cross on click."""
x = event.x
y = event.y
self.coords('cross_h', 0, y, self.winfo_width(), y)
self.coords('cross_v', x, 0, x, self.winfo_height())
self.event_generate("<<ColorChanged>>")
|
python
|
{
"resource": ""
}
|
q21846
|
ColorSquare._on_move
|
train
|
def _on_move(self, event):
"""Make the cross follow the cursor."""
w = self.winfo_width()
h = self.winfo_height()
x = min(max(event.x, 0), w)
y = min(max(event.y, 0), h)
self.coords('cross_h', 0, y, w, y)
self.coords('cross_v', x, 0, x, h)
self.event_generate("<<ColorChanged>>")
|
python
|
{
"resource": ""
}
|
q21847
|
ColorSquare.get
|
train
|
def get(self):
"""
Get selected color.
:return: color under cursor as a (RGB, HSV, HEX) tuple
"""
x = self.coords('cross_v')[0]
y = self.coords('cross_h')[1]
xp = min(x, self.bg.width() - 1)
yp = min(y, self.bg.height() - 1)
try:
r, g, b = self.bg.get(round2(xp), round2(yp))
except ValueError:
r, g, b = self.bg.get(round2(xp), round2(yp)).split()
r, g, b = int(r), int(g), int(b)
hexa = rgb_to_hexa(r, g, b)
h = self.get_hue()
s = round2((1 - float(y) / self.winfo_height()) * 100)
v = round2(100 * float(x) / self.winfo_width())
return (r, g, b), (h, s, v), hexa
|
python
|
{
"resource": ""
}
|
q21848
|
ColorSquare.set_hsv
|
train
|
def set_hsv(self, sel_color):
"""
Put cursor on sel_color given in HSV.
:param sel_color: color in HSV format
:type sel_color: sequence(int)
"""
width = self.winfo_width()
height = self.winfo_height()
h, s, v = sel_color
self.set_hue(h)
x = v / 100.
y = (1 - s / 100.)
self.coords('cross_h', 0, y * height, width, y * height)
self.coords('cross_v', x * width, 0, x * width, height)
|
python
|
{
"resource": ""
}
|
q21849
|
AdyenClient._determine_hpp_url
|
train
|
def _determine_hpp_url(self, platform, action):
"""This returns the Adyen HPP endpoint based on the provided platform,
and action.
Args:
platform (str): Adyen platform, ie 'live' or 'test'.
action (str): the HPP action to perform.
possible actions: select, pay, skipDetails, directory
"""
base_uri = settings.BASE_HPP_URL.format(platform)
service = action + '.shtml'
result = '/'.join([base_uri, service])
return result
|
python
|
{
"resource": ""
}
|
q21850
|
HTTPClient._pycurl_post
|
train
|
def _pycurl_post(self,
url,
json=None,
data=None,
username="",
password="",
headers={},
timeout=30):
"""This function will POST to the url endpoint using pycurl. returning
an AdyenResult object on 200 HTTP responce. Either json or data has to
be provided. If username and password are provided, basic auth will be
used.
Args:
url (str): url to send the POST
json (dict, optional): Dict of the JSON to POST
data (dict, optional): Dict, presumed flat structure
of key/value of request to place
username (str, optional): Username for basic auth. Must be included
as part of password.
password (str, optional): Password for basic auth. Must be included
as part of username.
headers (dict, optional): Key/Value pairs of headers to include
timeout (int, optional): Default 30. Timeout for the request.
Returns:
str: Raw response received
str: Raw request placed
int: HTTP status code, eg 200,404,401
dict: Key/Value pairs of the headers received.
"""
response_headers = {}
curl = pycurl.Curl()
curl.setopt(curl.URL, url)
if sys.version_info[0] >= 3:
stringbuffer = BytesIO()
else:
stringbuffer = StringIO()
curl.setopt(curl.WRITEDATA, stringbuffer)
# Add User-Agent header to request so that the
# request can be identified as coming from the Adyen Python library.
headers['User-Agent'] = self.user_agent
# Convert the header dict to formatted array as pycurl needs.
if sys.version_info[0] >= 3:
header_list = ["%s:%s" % (k, v) for k, v in headers.items()]
else:
header_list = ["%s:%s" % (k, v) for k, v in headers.iteritems()]
# Ensure proper content-type when adding headers
if json:
header_list.append("Content-Type:application/json")
curl.setopt(pycurl.HTTPHEADER, header_list)
# Return regular dict instead of JSON encoded dict for request:
raw_store = json
# Set the request body.
raw_request = json_lib.dumps(json) if json else urlencode(data)
curl.setopt(curl.POSTFIELDS, raw_request)
if username and password:
curl.setopt(curl.USERPWD, '%s:%s' % (username, password))
curl.setopt(curl.TIMEOUT, timeout)
curl.perform()
# Grab the response content
result = stringbuffer.getvalue()
status_code = curl.getinfo(curl.RESPONSE_CODE)
curl.close()
# Return regular dict instead of JSON encoded dict for request:
raw_request = raw_store
return result, raw_request, status_code, response_headers
|
python
|
{
"resource": ""
}
|
q21851
|
HTTPClient._requests_post
|
train
|
def _requests_post(self, url,
json=None,
data=None,
username="",
password="",
xapikey="",
headers=None,
timeout=30):
"""This function will POST to the url endpoint using requests.
Returning an AdyenResult object on 200 HTTP response.
Either json or data has to be provided.
If username and password are provided, basic auth will be used.
Args:
url (str): url to send the POST
json (dict, optional): Dict of the JSON to POST
data (dict, optional): Dict, presumed flat structure of key/value
of request to place
username (str, optionl): Username for basic auth. Must be included
as part of password.
password (str, optional): Password for basic auth. Must be included
as part of username.
headers (dict, optional): Key/Value pairs of headers to include
timeout (int, optional): Default 30. Timeout for the request.
Returns:
str: Raw response received
str: Raw request placed
int: HTTP status code, eg 200,404,401
dict: Key/Value pairs of the headers received.
"""
if headers is None:
headers = {}
# Adding basic auth if username and password provided.
auth = None
if username and password:
auth = requests.auth.HTTPBasicAuth(username, password)
elif xapikey:
headers['x-api-key'] = xapikey
# Add User-Agent header to request so that the request
# can be identified as coming from the Adyen Python library.
headers['User-Agent'] = self.user_agent
request = requests.post(url, auth=auth, data=data, json=json,
headers=headers, timeout=timeout)
# Ensure either json or data is returned for raw request
# Updated: Only return regular dict,
# don't switch out formats if this is not important.
message = json
return request.text, message, request.status_code, request.headers
|
python
|
{
"resource": ""
}
|
q21852
|
HTTPClient._urllib_post
|
train
|
def _urllib_post(self, url,
json="",
data="",
username="",
password="",
headers=None,
timeout=30):
"""This function will POST to the url endpoint using urllib2. returning
an AdyenResult object on 200 HTTP responce. Either json or data has to
be provided. If username and password are provided, basic auth will be
used.
Args:
url (str): url to send the POST
json (dict, optional): Dict of the JSON to POST
data (dict, optional): Dict, presumed flat structure of
key/value of request to place as
www-form
username (str, optional): Username for basic auth. Must be
uncluded as part of password.
password (str, optional): Password for basic auth. Must be
included as part of username.
headers (dict, optional): Key/Value pairs of headers to include
timeout (int, optional): Default 30. Timeout for the request.
Returns:
str: Raw response received
str: Raw request placed
int: HTTP status code, eg 200,404,401
dict: Key/Value pairs of the headers received.
"""
if headers is None:
headers = {}
# Store regular dict to return later:
raw_store = json
raw_request = json_lib.dumps(json) if json else urlencode(data)
url_request = Request(url, data=raw_request.encode('utf8'))
if json:
url_request.add_header('Content-Type', 'application/json')
elif not data:
raise ValueError("Please provide either a json or a data field.")
# Add User-Agent header to request so that the
# request can be identified as coming from the Adyen Python library.
headers['User-Agent'] = self.user_agent
# Set regular dict to return as raw_request:
raw_request = raw_store
# Adding basic auth is username and password provided.
if username and password:
if sys.version_info[0] >= 3:
basic_authstring = base64.encodebytes(('%s:%s' %
(username, password))
.encode()).decode(). \
replace('\n', '')
else:
basic_authstring = base64.encodestring('%s:%s' % (username,
password)). \
replace('\n', '')
url_request.add_header("Authorization",
"Basic %s" % basic_authstring)
# Adding the headers to the request.
for key, value in headers.items():
url_request.add_header(key, str(value))
# URLlib raises all non 200 responses as en error.
try:
response = urlopen(url_request, timeout=timeout)
except HTTPError as e:
raw_response = e.read()
return raw_response, raw_request, e.getcode(), e.headers
else:
raw_response = response.read()
response.close()
# The dict(response.info()) is the headers of the response
# Raw response, raw request, status code and headers returned
return (raw_response, raw_request,
response.getcode(), dict(response.info()))
|
python
|
{
"resource": ""
}
|
q21853
|
check_in
|
train
|
def check_in(request, action):
"""This function checks for missing properties in the request dict
for the corresponding action."""
if not request:
req_str = ""
for idx, val in enumerate(actions[action]):
req_str += "\n" + val
erstr = "Provide a request dict with the following properties:" \
" %s" % req_str
raise ValueError(erstr)
required_fields = actions[action]
missing = []
for field in required_fields:
if not is_key_present(request, field):
missing.append(field)
if missing:
missing_string = ""
for idx, val in enumerate(missing):
missing_string += "\n" + val
erstr = "Provide the required request parameters to" \
" complete this request: %s" % missing_string
raise ValueError(erstr)
return True
|
python
|
{
"resource": ""
}
|
q21854
|
resolve_type_name
|
train
|
def resolve_type_name(ctx, param, value): # pylint: disable=unused-argument
"""Resolve CLI option type name"""
def _resolve(value):
"""Resolve single type name"""
value = [
type_id
for type_id, type_name in W1ThermSensor.TYPE_NAMES.items()
if type_name == value
][0]
return value
if not value:
return value
if isinstance(value, tuple):
return [_resolve(v) for v in value]
else:
return _resolve(value)
|
python
|
{
"resource": ""
}
|
q21855
|
ls
|
train
|
def ls(types, as_json): # pylint: disable=invalid-name
"""List all available sensors"""
sensors = W1ThermSensor.get_available_sensors(types)
if as_json:
data = [
{"id": i, "hwid": s.id, "type": s.type_name}
for i, s in enumerate(sensors, 1)
]
click.echo(json.dumps(data, indent=4, sort_keys=True))
else:
click.echo(
"Found {0} sensors:".format(click.style(str(len(sensors)), bold=True))
)
for i, sensor in enumerate(sensors, 1):
click.echo(
" {0}. HWID: {1} Type: {2}".format(
click.style(str(i), bold=True),
click.style(sensor.id, bold=True),
click.style(sensor.type_name, bold=True),
)
)
|
python
|
{
"resource": ""
}
|
q21856
|
all
|
train
|
def all(types, unit, precision, as_json): # pylint: disable=redefined-builtin
"""Get temperatures of all available sensors"""
sensors = W1ThermSensor.get_available_sensors(types)
temperatures = []
for sensor in sensors:
if precision:
sensor.set_precision(precision, persist=False)
temperatures.append(sensor.get_temperature(unit))
if as_json:
data = [
{"id": i, "hwid": s.id, "type": s.type_name, "temperature": t, "unit": unit}
for i, s, t in zip(count(start=1), sensors, temperatures)
]
click.echo(json.dumps(data, indent=4, sort_keys=True))
else:
click.echo(
"Got temperatures of {0} sensors:".format(
click.style(str(len(sensors)), bold=True)
)
)
for i, sensor, temperature in zip(count(start=1), sensors, temperatures):
click.echo(
" Sensor {0} ({1}) measured temperature: {2} {3}".format(
click.style(str(i), bold=True),
click.style(sensor.id, bold=True),
click.style(str(round(temperature, 2)), bold=True),
click.style(unit, bold=True),
)
)
|
python
|
{
"resource": ""
}
|
q21857
|
get
|
train
|
def get(id_, hwid, type_, unit, precision, as_json):
"""Get temperature of a specific sensor"""
if id_ and (hwid or type_):
raise click.BadOptionUsage(
"If --id is given --hwid and --type are not allowed."
)
if id_:
try:
sensor = W1ThermSensor.get_available_sensors()[id_ - 1]
except IndexError:
raise click.BadOptionUsage(
"No sensor with id {0} available. "
"Use the ls command to show all available sensors.".format(id_)
)
else:
sensor = W1ThermSensor(type_, hwid)
if precision:
sensor.set_precision(precision, persist=False)
temperature = sensor.get_temperature(unit)
if as_json:
data = {
"hwid": sensor.id,
"type": sensor.type_name,
"temperature": temperature,
"unit": unit,
}
click.echo(json.dumps(data, indent=4, sort_keys=True))
else:
click.echo(
"Sensor {0} measured temperature: {1} {2}".format(
click.style(sensor.id, bold=True),
click.style(str(temperature), bold=True),
click.style(unit, bold=True),
)
)
|
python
|
{
"resource": ""
}
|
q21858
|
precision
|
train
|
def precision(precision, id_, hwid, type_):
"""Change the precision for the sensor and persist it in the sensor's EEPROM"""
if id_ and (hwid or type_):
raise click.BadOptionUsage(
"If --id is given --hwid and --type are not allowed."
)
if id_:
try:
sensor = W1ThermSensor.get_available_sensors()[id_ - 1]
except IndexError:
raise click.BadOptionUsage(
"No sensor with id {0} available. "
"Use the ls command to show all available sensors.".format(id_)
)
else:
sensor = W1ThermSensor(type_, hwid)
sensor.set_precision(precision, persist=True)
|
python
|
{
"resource": ""
}
|
q21859
|
load_kernel_modules
|
train
|
def load_kernel_modules():
"""
Load kernel modules needed by the temperature sensor
if they are not already loaded.
If the base directory then does not exist an exception is raised an the kernel module loading
should be treated as failed.
:raises KernelModuleLoadError: if the kernel module could not be loaded properly
"""
if not os.path.isdir(W1ThermSensor.BASE_DIRECTORY):
os.system("modprobe w1-gpio >/dev/null 2>&1")
os.system("modprobe w1-therm >/dev/null 2>&1")
for _ in range(W1ThermSensor.RETRY_ATTEMPTS):
if os.path.isdir(
W1ThermSensor.BASE_DIRECTORY
): # w1 therm modules loaded correctly
break
time.sleep(W1ThermSensor.RETRY_DELAY_SECONDS)
else:
raise KernelModuleLoadError()
|
python
|
{
"resource": ""
}
|
q21860
|
W1ThermSensor.get_available_sensors
|
train
|
def get_available_sensors(cls, types=None):
"""
Return all available sensors.
:param list types: the type of the sensor to look for.
If types is None it will search for all available types.
:returns: a list of sensor instances.
:rtype: list
"""
if not types:
types = cls.TYPE_NAMES.keys()
is_sensor = lambda s: any(s.startswith(hex(x)[2:]) for x in types) # noqa
return [
cls(cls.RESOLVE_TYPE_STR[s[:2]], s[3:])
for s in os.listdir(cls.BASE_DIRECTORY)
if is_sensor(s)
]
|
python
|
{
"resource": ""
}
|
q21861
|
W1ThermSensor.raw_sensor_strings
|
train
|
def raw_sensor_strings(self):
"""
Reads the raw strings from the kernel module sysfs interface
:returns: raw strings containing all bytes from the sensor memory
:rtype: str
:raises NoSensorFoundError: if the sensor could not be found
:raises SensorNotReadyError: if the sensor is not ready yet
"""
try:
with open(self.sensorpath, "r") as f:
data = f.readlines()
except IOError:
raise NoSensorFoundError(self.type_name, self.id)
if data[0].strip()[-3:] != "YES":
raise SensorNotReadyError(self)
return data
|
python
|
{
"resource": ""
}
|
q21862
|
W1ThermSensor.raw_sensor_count
|
train
|
def raw_sensor_count(self):
"""
Returns the raw integer ADC count from the sensor
Note: Must be divided depending on the max. sensor resolution
to get floating point celsius
:returns: the raw value from the sensor ADC
:rtype: int
:raises NoSensorFoundError: if the sensor could not be found
:raises SensorNotReadyError: if the sensor is not ready yet
"""
# two complement bytes, MSB comes after LSB!
bytes = self.raw_sensor_strings[1].split()
# Convert from 16 bit hex string into int
int16 = int(bytes[1] + bytes[0], 16)
# check first signing bit
if int16 >> 15 == 0:
return int16 # positive values need no processing
else:
return int16 - (1 << 16)
|
python
|
{
"resource": ""
}
|
q21863
|
W1ThermSensor._get_unit_factor
|
train
|
def _get_unit_factor(cls, unit):
"""
Returns the unit factor depending on the unit constant
:param int unit: the unit of the factor requested
:returns: a function to convert the raw sensor value to the given unit
:rtype: lambda function
:raises UnsupportedUnitError: if the unit is not supported
"""
try:
if isinstance(unit, str):
unit = cls.UNIT_FACTOR_NAMES[unit]
return cls.UNIT_FACTORS[unit]
except KeyError:
raise UnsupportedUnitError()
|
python
|
{
"resource": ""
}
|
q21864
|
W1ThermSensor.get_temperature
|
train
|
def get_temperature(self, unit=DEGREES_C):
"""
Returns the temperature in the specified unit
:param int unit: the unit of the temperature requested
:returns: the temperature in the given unit
:rtype: float
:raises UnsupportedUnitError: if the unit is not supported
:raises NoSensorFoundError: if the sensor could not be found
:raises SensorNotReadyError: if the sensor is not ready yet
:raises ResetValueError: if the sensor has still the initial value and no measurment
"""
if self.type in self.TYPES_12BIT_STANDARD:
value = self.raw_sensor_count
# the int part is 8 bit wide, 4 bit are left on 12 bit
# so divide with 2^4 = 16 to get the celsius fractions
value /= 16.0
# check if the sensor value is the reset value
if value == 85.0:
raise ResetValueError(self)
factor = self._get_unit_factor(unit)
return factor(value)
# Fallback to precalculated value for other sensor types
factor = self._get_unit_factor(unit)
return factor(self.raw_sensor_temp * 0.001)
|
python
|
{
"resource": ""
}
|
q21865
|
W1ThermSensor.get_temperatures
|
train
|
def get_temperatures(self, units):
"""
Returns the temperatures in the specified units
:param list units: the units for the sensor temperature
:returns: the sensor temperature in the given units. The order of
the temperatures matches the order of the given units.
:rtype: list
:raises UnsupportedUnitError: if the unit is not supported
:raises NoSensorFoundError: if the sensor could not be found
:raises SensorNotReadyError: if the sensor is not ready yet
"""
sensor_value = self.get_temperature(self.DEGREES_C)
return [self._get_unit_factor(unit)(sensor_value) for unit in units]
|
python
|
{
"resource": ""
}
|
q21866
|
W1ThermSensor.get_precision
|
train
|
def get_precision(self):
"""
Get the current precision from the sensor.
:returns: sensor resolution from 9-12 bits
:rtype: int
"""
config_str = self.raw_sensor_strings[1].split()[4] # Byte 5 is the config register
bit_base = int(config_str, 16) >> 5 # Bit 5-6 contains the resolution, cut off the rest
return bit_base + 9
|
python
|
{
"resource": ""
}
|
q21867
|
W1ThermSensor.set_precision
|
train
|
def set_precision(self, precision, persist=False):
"""
Set the precision of the sensor for the next readings.
If the ``persist`` argument is set to ``False`` this value
is "only" stored in the volatile SRAM, so it is reset when
the sensor gets power-cycled.
If the ``persist`` argument is set to ``True`` the current set
precision is stored into the EEPROM. Since the EEPROM has a limited
amount of writes (>50k), this command should be used wisely.
Note: root permissions are required to change the sensors precision.
Note: This function is supported since kernel 4.7.
:param int precision: the sensor precision in bits.
Valid values are between 9 and 12
:param bool persist: if the sensor precision should be written
to the EEPROM.
:returns: if the sensor precision could be set or not.
:rtype: bool
"""
if not 9 <= precision <= 12:
raise ValueError(
"The given sensor precision '{0}' is out of range (9-12)".format(
precision
)
)
exitcode = subprocess.call(
"echo {0} > {1}".format(precision, self.sensorpath), shell=True
)
if exitcode != 0:
raise W1ThermSensorError(
"Failed to change resolution to {0} bit. "
"You might have to be root to change the precision".format(precision)
)
if persist:
exitcode = subprocess.call(
"echo 0 > {0}".format(self.sensorpath), shell=True
)
if exitcode != 0:
raise W1ThermSensorError(
"Failed to write precision configuration to sensor EEPROM"
)
return True
|
python
|
{
"resource": ""
}
|
q21868
|
round_to_n
|
train
|
def round_to_n(x, n):
"""
Round to sig figs
"""
return round(x, -int(np.floor(np.log10(x))) + (n - 1))
|
python
|
{
"resource": ""
}
|
q21869
|
sharey
|
train
|
def sharey(axes):
"""
Shared axes limits without shared locators, ticks, etc.
By Joe Kington
"""
linker = Linker(axes)
for ax in axes:
ax._linker = linker
|
python
|
{
"resource": ""
}
|
q21870
|
fix_ticks
|
train
|
def fix_ticks(ax):
"""
Center ticklabels and hide any outside axes limits.
By Joe Kington
"""
plt.setp(ax.get_yticklabels(), ha='center', x=0.5,
transform=ax._yaxis_transform)
# We'll still wind up with some tick labels beyond axes limits for reasons
# I don't fully understand...
limits = ax.get_ylim()
for label, loc in zip(ax.yaxis.get_ticklabels(), ax.yaxis.get_ticklocs()):
if loc < min(limits) or loc > max(limits):
label.set(visible=False)
else:
label.set(visible=True)
|
python
|
{
"resource": ""
}
|
q21871
|
list_and_add
|
train
|
def list_and_add(a, b):
"""
Concatenate anything into a list.
Args:
a: the first thing
b: the second thing
Returns:
list. All the things in a list.
"""
if not isinstance(b, list):
b = [b]
if not isinstance(a, list):
a = [a]
return a + b
|
python
|
{
"resource": ""
}
|
q21872
|
lasio_get
|
train
|
def lasio_get(l,
section,
item,
attrib='value',
default=None,
remap=None,
funcs=None):
"""
Grabs, renames and transforms stuff from a lasio object.
Args:
l (lasio): a lasio instance.
section (str): The LAS section to grab from, eg ``well``
item (str): The item in the LAS section to grab from, eg ``name``
attrib (str): The attribute of the item to grab, eg ``value``
default (str): What to return instead.
remap (dict): Optional. A dict of 'old': 'new' LAS field names.
funcs (dict): Optional. A dict of 'las field': function() for
implementing a transform before loading. Can be a lambda.
Returns:
The transformed item.
"""
remap = remap or {}
item_to_fetch = remap.get(item, item)
if item_to_fetch is None:
return None
try:
obj = getattr(l, section)
result = getattr(obj, item_to_fetch)[attrib]
except:
return default
if funcs is not None:
f = funcs.get(item, null)
result = f(result)
return result
|
python
|
{
"resource": ""
}
|
q21873
|
parabolic
|
train
|
def parabolic(f, x):
"""
Interpolation. From ageobot, from somewhere else.
"""
xv = 1/2. * (f[x-1] - f[x+1]) / (f[x-1] - 2 * f[x] + f[x+1]) + x
yv = f[x] - 1/4. * (f[x-1] - f[x+1]) * (xv - x)
return (xv, yv)
|
python
|
{
"resource": ""
}
|
q21874
|
find_nearest
|
train
|
def find_nearest(a, value, index=False):
"""
Find the array value, or index of the array value, closest to some given
value.
Args:
a (ndarray)
value (float)
index (bool): whether to return the index instead of the array value.
Returns:
float. The array value (or index, as int) nearest the specified value.
"""
i = np.abs(a - value).argmin()
if index:
return i
else:
return a[i]
|
python
|
{
"resource": ""
}
|
q21875
|
find_previous
|
train
|
def find_previous(a, value, index=False, return_distance=False):
"""
Find the nearest array value, or index of the array value, before some
given value. Optionally also return the fractional distance of the given
value from that previous value.
Args:
a (ndarray)
value (float)
index (bool): whether to return the index instead of the array value.
Default: False.
return_distance(bool): whether to return the fractional distance from
the nearest value to the specified value. Default: False.
Returns:
float. The array value (or index, as int) before the specified value.
If ``return_distance==True`` then a tuple is returned, where the
second value is the distance.
"""
b = a - value
i = np.where(b > 0)[0][0]
d = (value - a[i-1]) / (a[i] - a[i-1])
if index:
if return_distance:
return i - 1, d
else:
return i - 1
else:
if return_distance:
return a[i - 1], d
else:
return a[i - 1]
|
python
|
{
"resource": ""
}
|
q21876
|
dd2dms
|
train
|
def dd2dms(dd):
"""
Decimal degrees to DMS.
Args:
dd (float). Decimal degrees.
Return:
tuple. Degrees, minutes, and seconds.
"""
m, s = divmod(dd * 3600, 60)
d, m = divmod(m, 60)
return int(d), int(m), s
|
python
|
{
"resource": ""
}
|
q21877
|
ricker
|
train
|
def ricker(f, length, dt):
"""
A Ricker wavelet.
Args:
f (float): frequency in Haz, e.g. 25 Hz.
length (float): Length in s, e.g. 0.128.
dt (float): sample interval in s, e.g. 0.001.
Returns:
tuple. time basis, amplitude values.
"""
t = np.linspace(-int(length/2), int((length-dt)/2), int(length/dt))
y = (1. - 2.*(np.pi**2)*(f**2)*(t**2))*np.exp(-(np.pi**2)*(f**2)*(t**2))
return t, y
|
python
|
{
"resource": ""
}
|
q21878
|
hex_is_dark
|
train
|
def hex_is_dark(hexx, percent=50):
"""
Function to decide if a hex colour is dark.
Args:
hexx (str): A hexadecimal colour, starting with '#'.
Returns:
bool: The colour's brightness is less than the given percent.
"""
r, g, b = hex_to_rgb(hexx)
luma = (0.2126 * r + 0.7152 * g + 0.0722 * b) / 2.55 # per ITU-R BT.709
return (luma < percent)
|
python
|
{
"resource": ""
}
|
q21879
|
text_colour_for_hex
|
train
|
def text_colour_for_hex(hexx, percent=50, dark='#000000', light='#ffffff'):
"""
Function to decide what colour to use for a given hex colour.
Args:
hexx (str): A hexadecimal colour, starting with '#'.
Returns:
bool: The colour's brightness is less than the given percent.
"""
return light if hex_is_dark(hexx, percent=percent) else dark
|
python
|
{
"resource": ""
}
|
q21880
|
get_lines
|
train
|
def get_lines(handle, line):
"""
Get zero-indexed line from an open file-like.
"""
for i, l in enumerate(handle):
if i == line:
return l
|
python
|
{
"resource": ""
}
|
q21881
|
find_file
|
train
|
def find_file(pattern, path):
"""
A bit like grep. Finds a pattern, looking in path. Returns the filename.
"""
for fname in glob.iglob(path):
with open(fname) as f:
if re.search(pattern, f.read()):
return fname
return
|
python
|
{
"resource": ""
}
|
q21882
|
Location.from_lasio
|
train
|
def from_lasio(cls, l, remap=None, funcs=None):
"""
Make a Location object from a lasio object. Assumes we're starting
with a lasio object, l.
Args:
l (lasio).
remap (dict): Optional. A dict of 'old': 'new' LAS field names.
funcs (dict): Optional. A dict of 'las field': function() for
implementing a transform before loading. Can be a lambda.
Returns:
Location. An instance of this class.
"""
params = {}
funcs = funcs or {}
funcs['location'] = str
for field, (sect, code) in las_fields['location'].items():
params[field] = utils.lasio_get(l,
sect,
code,
remap=remap,
funcs=funcs)
return cls(params)
|
python
|
{
"resource": ""
}
|
q21883
|
Location.add_deviation
|
train
|
def add_deviation(self, dev, td=None):
"""
Add a deviation survey to this instance, and try to compute a position
log from it.
"""
self.deviation = dev
try:
self.compute_position_log(td=td)
except:
self.position = None
return
|
python
|
{
"resource": ""
}
|
q21884
|
Location.md2tvd
|
train
|
def md2tvd(self, kind='linear'):
"""
Provides an transformation and interpolation function that converts
MD to TVD.
Args:
kind (str): The kind of interpolation to do, e.g. 'linear',
'cubic', 'nearest'.
Returns:
function.
"""
if self.position is None:
return lambda x: x
return interp1d(self.md, self.tvd,
kind=kind,
assume_sorted=True,
fill_value="extrapolate",
bounds_error=False)
|
python
|
{
"resource": ""
}
|
q21885
|
Project.add_canstrat_striplogs
|
train
|
def add_canstrat_striplogs(self,
path, uwi_transform=None, name='canstrat'):
"""
This may be too specific a method... just move it to the workflow.
Requires striplog.
"""
from striplog import Striplog
uwi_transform = uwi_transform or utils.null
for w in self.__list:
try:
dat_file = utils.find_file(str(uwi_transform(w.uwi)), path)
except:
print("- Skipping {}: something went wrong".format(w.uwi))
continue
if dat_file is None:
print("- Omitting {}: no data".format(w.uwi))
continue
# If we got here, we're using it.
print("+ Adding {} from {}".format(w.uwi, dat_file))
w.data[name] = Striplog.from_canstrat(dat_file)
return
|
python
|
{
"resource": ""
}
|
q21886
|
Project.__all_curve_names
|
train
|
def __all_curve_names(self, uwis=None, unique=True, count=False, nodepth=True):
"""
Utility function to get all curve names from all wells, regardless
of data type or repetition.
"""
uwis = uwis or self.uwis
c = utils.flatten_list([list(w.data.keys()) for w in self if w.uwi in uwis])
if nodepth:
c = filter(lambda x: x not in ['DEPT', 'DEPTH'], c)
if unique:
if count:
return Counter(c).most_common()
else:
return [i[0] for i in Counter(c).most_common()]
return list(c)
|
python
|
{
"resource": ""
}
|
q21887
|
Project.get_mnemonics
|
train
|
def get_mnemonics(self, mnemonics, uwis=None, alias=None):
"""
Looks at all the wells in turn and returns the highest thing
in the alias table.
Args:
mnemonics (list)
alias (dict)
Returns:
list. A list of lists.
"""
# Let's not do the nested comprehension...
uwis = uwis or self.uwis
wells = [w for w in self.__list if w.uwi in uwis]
all_wells = []
for w in wells:
this_well = [w.get_mnemonic(m, alias=alias) for m in mnemonics]
all_wells.append(this_well)
return all_wells
|
python
|
{
"resource": ""
}
|
q21888
|
Project.count_mnemonic
|
train
|
def count_mnemonic(self, mnemonic, uwis=uwis, alias=None):
"""
Counts the wells that have a given curve, given the mnemonic and an
alias dict.
"""
all_mnemonics = self.get_mnemonics([mnemonic], uwis=uwis, alias=alias)
return len(list(filter(None, utils.flatten_list(all_mnemonics))))
|
python
|
{
"resource": ""
}
|
q21889
|
Project.plot_kdes
|
train
|
def plot_kdes(self, mnemonic, alias=None, uwi_regex=None, return_fig=False):
"""
Plot KDEs for all curves with the given name.
Args:
menmonic (str): the name of the curve to look for.
alias (dict): a welly alias dictionary.
uwi_regex (str): a regex pattern. Only this part of the UWI will be displayed
on the plot of KDEs.
return_fig (bool): whether to return the matplotlib figure object.
Returns:
None or figure.
"""
wells = self.find_wells_with_curve(mnemonic, alias=alias)
fig, axs = plt.subplots(len(self), 1, figsize=(10, 1.5*len(self)))
curves = [w.get_curve(mnemonic, alias=alias) for w in wells]
all_data = np.hstack(curves)
all_data = all_data[~np.isnan(all_data)]
# Find values for common axis to exclude outliers.
amax = np.percentile(all_data, 99)
amin = np.percentile(all_data, 1)
for i, w in enumerate(self):
c = w.get_curve(mnemonic, alias=alias)
if uwi_regex is not None:
label = re.sub(uwi_regex, r'\1', w.uwi)
else:
label = w.uwi
if c is not None:
axs[i] = c.plot_kde(ax=axs[i], amax=amax, amin=amin, label=label+'-'+str(c.mnemonic))
else:
continue
if return_fig:
return fig
else:
return
|
python
|
{
"resource": ""
}
|
q21890
|
Project.find_wells_with_curve
|
train
|
def find_wells_with_curve(self, mnemonic, alias=None):
"""
Returns a new Project with only the wells which have the named curve.
Args:
menmonic (str): the name of the curve to look for.
alias (dict): a welly alias dictionary.
Returns:
project.
"""
return Project([w for w in self if w.get_curve(mnemonic, alias=alias) is not None])
|
python
|
{
"resource": ""
}
|
q21891
|
Project.find_wells_without_curve
|
train
|
def find_wells_without_curve(self, mnemonic, alias=None):
"""
Returns a new Project with only the wells which DO NOT have the named curve.
Args:
menmonic (str): the name of the curve to look for.
alias (dict): a welly alias dictionary.
Returns:
project.
"""
return Project([w for w in self if w.get_curve(mnemonic, alias=alias) is None])
|
python
|
{
"resource": ""
}
|
q21892
|
Project.get_wells
|
train
|
def get_wells(self, uwis=None):
"""
Returns a new Project with only the wells named by UWI.
Args:
uwis (list): list or tuple of UWI strings.
Returns:
project.
"""
if uwis is None:
return Project(self.__list)
return Project([w for w in self if w.uwi in uwis])
|
python
|
{
"resource": ""
}
|
q21893
|
Project.omit_wells
|
train
|
def omit_wells(self, uwis=None):
"""
Returns a new project where wells with specified uwis have been omitted
Args:
uwis (list): list or tuple of UWI strings.
Returns:
project
"""
if uwis is None:
raise ValueError('Must specify at least one uwi')
return Project([w for w in self if w.uwi not in uwis])
|
python
|
{
"resource": ""
}
|
q21894
|
Project.get_well
|
train
|
def get_well(self, uwi):
"""
Returns a Well object identified by UWI
Args:
uwi (string): the UWI string for the well.
Returns:
well
"""
if uwi is None:
raise ValueError('a UWI must be provided')
matching_wells = [w for w in self if w.uwi == uwi]
return matching_wells[0] if len(matching_wells) >= 1 else None
|
python
|
{
"resource": ""
}
|
q21895
|
Project.merge_wells
|
train
|
def merge_wells(self, right, keys=None):
"""
Returns a new Project object containing wells from self where
curves from the wells on the right have been added. Matching between
wells in self and right is based on uwi match and ony wells in self
are considered
Args:
uwi (string): the UWI string for the well.
Returns:
project
"""
wells = []
for w in self:
rw = right.get_well(w.uwi)
if rw is not None:
if keys is None:
keys = list(rw.data.keys())
for k in keys:
try:
w.data[k] = rw.data[k]
except:
pass
wells.append(w)
return Project(wells)
|
python
|
{
"resource": ""
}
|
q21896
|
Project.df
|
train
|
def df(self):
"""
Makes a pandas DataFrame containing Curve data for all the wells
in the Project. The DataFrame has a dual index of well UWI and
curve Depths. Requires `pandas`.
Args:
No arguments.
Returns:
`pandas.DataFrame`.
"""
import pandas as pd
return pd.concat([w.df(uwi=True) for w in self])
|
python
|
{
"resource": ""
}
|
q21897
|
Curve.basis
|
train
|
def basis(self):
"""
The depth or time basis of the curve's points. Computed
on the fly from the start, stop and step.
Returns
ndarray. The array, the same length as the curve.
"""
return np.linspace(self.start, self.stop, self.shape[0], endpoint=True)
|
python
|
{
"resource": ""
}
|
q21898
|
Curve.describe
|
train
|
def describe(self):
"""
Return basic statistics about the curve.
"""
stats = {}
stats['samples'] = self.shape[0]
stats['nulls'] = self[np.isnan(self)].shape[0]
stats['mean'] = float(np.nanmean(self.real))
stats['min'] = float(np.nanmin(self.real))
stats['max'] = float(np.nanmax(self.real))
return stats
|
python
|
{
"resource": ""
}
|
q21899
|
Curve.from_lasio_curve
|
train
|
def from_lasio_curve(cls, curve,
depth=None,
basis=None,
start=None,
stop=None,
step=0.1524,
run=-1,
null=-999.25,
service_company=None,
date=None):
"""
Makes a curve object from a lasio curve object and either a depth
basis or start and step information.
Args:
curve (ndarray)
depth (ndarray)
basis (ndarray)
start (float)
stop (float)
step (float): default: 0.1524
run (int): default: -1
null (float): default: -999.25
service_company (str): Optional.
data (str): Optional.
Returns:
Curve. An instance of the class.
"""
data = curve.data
unit = curve.unit
# See if we have uneven sampling.
if depth is not None:
d = np.diff(depth)
if not np.allclose(d - np.mean(d), np.zeros_like(d)):
# Sampling is uneven.
m = "Irregular sampling in depth is not supported. "
m += "Interpolating to regular basis."
warnings.warn(m)
step = np.nanmedian(d)
start, stop = depth[0], depth[-1]+0.00001 # adjustment
basis = np.arange(start, stop, step)
data = np.interp(basis, depth, data)
else:
step = np.nanmedian(d)
start = depth[0]
# Carry on with easier situations.
if start is None:
if basis is not None:
start = basis[0]
step = basis[1] - basis[0]
else:
raise CurveError("You must provide a basis or a start depth.")
if step == 0:
if stop is None:
raise CurveError("You must provide a step or a stop depth.")
else:
step = (stop - start) / (curve.data.shape[0] - 1)
# Interpolate into this.
params = {}
params['mnemonic'] = curve.mnemonic
params['description'] = curve.descr
params['start'] = start
params['step'] = step
params['units'] = unit
params['run'] = run
params['null'] = null
params['service_company'] = service_company
params['date'] = date
params['code'] = curve.API_code
return cls(data, params=params)
|
python
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.