_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q227300 | CA.column_coordinates | train | def column_coordinates(self, X):
"""The column principal coordinates."""
utils.validation.check_is_fitted(self, 'V_')
_, _, _, col_names = util.make_labels_and_names(X)
if isinstance(X, pd.SparseDataFrame):
X = X.to_coo()
elif isinstance(X, pd.DataFrame):
... | python | {
"resource": ""
} |
q227301 | CA.plot_coordinates | train | def plot_coordinates(self, X, ax=None, figsize=(6, 6), x_component=0, y_component=1,
show_row_labels=True, show_col_labels=True, **kwargs):
"""Plot the principal coordinates."""
utils.validation.check_is_fitted(self, 's_')
if ax is None:
fig, ax =... | python | {
"resource": ""
} |
q227302 | MCA.plot_coordinates | train | def plot_coordinates(self, X, ax=None, figsize=(6, 6), x_component=0, y_component=1,
show_row_points=True, row_points_size=10, show_row_labels=False,
show_column_points=True, column_points_size=30,
show_column_label... | python | {
"resource": ""
} |
q227303 | compute_svd | train | def compute_svd(X, n_components, n_iter, random_state, engine):
"""Computes an SVD with k components."""
# Determine what SVD engine to use
if engine == 'auto':
engine = 'sklearn'
# Compute the SVD
if engine == 'fbpca':
if FBPCA_INSTALLED:
U, s, V = fbpca.pca(X, k=n_com... | python | {
"resource": ""
} |
q227304 | PCA.row_standard_coordinates | train | def row_standard_coordinates(self, X):
"""Returns the row standard coordinates.
The row standard coordinates are obtained by dividing each row principal coordinate by it's
associated eigenvalue.
"""
utils.validation.check_is_fitted(self, 's_')
return self.row_coordinates... | python | {
"resource": ""
} |
q227305 | PCA.row_cosine_similarities | train | def row_cosine_similarities(self, X):
"""Returns the cosine similarities between the rows and their principal components.
The row cosine similarities are obtained by calculating the cosine of the angle shaped by
the row principal coordinates and the row principal components. This is calculated ... | python | {
"resource": ""
} |
q227306 | PCA.column_correlations | train | def column_correlations(self, X):
"""Returns the column correlations with each principal component."""
utils.validation.check_is_fitted(self, 's_')
# Convert numpy array to pandas DataFrame
if isinstance(X, np.ndarray):
X = pd.DataFrame(X)
row_pc = self.row_coordina... | python | {
"resource": ""
} |
q227307 | build_ellipse | train | def build_ellipse(X, Y):
"""Construct ellipse coordinates from two arrays of numbers.
Args:
X (1D array_like)
Y (1D array_like)
Returns:
float: The mean of `X`.
float: The mean of `Y`.
float: The width of the ellipse.
float: The height of the ellipse.
... | python | {
"resource": ""
} |
q227308 | TimeInput.set_start_time | train | def set_start_time(self, start_time):
""" set the start time. when start time is set, drop down list
will start from start time and duration will be displayed in
brackets
"""
start_time = start_time or dt.time()
if isinstance(start_time, dt.time): # ensure that we... | python | {
"resource": ""
} |
q227309 | extract_time | train | def extract_time(match):
"""extract time from a time_re match."""
hour = int(match.group('hour'))
minute = int(match.group('minute'))
return dt.time(hour, minute) | python | {
"resource": ""
} |
q227310 | default_logger | train | def default_logger(name):
"""Return a toplevel logger.
This should be used only in the toplevel file.
Files deeper in the hierarchy should use
``logger = logging.getLogger(__name__)``,
in order to considered as children of the toplevel logger.
Beware that without a setLevel() somewhere,
th... | python | {
"resource": ""
} |
q227311 | Fact.serialized | train | def serialized(self, prepend_date=True):
"""Return a string fully representing the fact."""
name = self.serialized_name()
datetime = self.serialized_time(prepend_date)
return "%s %s" % (datetime, name) | python | {
"resource": ""
} |
q227312 | Widget._with_rotation | train | def _with_rotation(self, w, h):
"""calculate the actual dimensions after rotation"""
res_w = abs(w * math.cos(self.rotation) + h * math.sin(self.rotation))
res_h = abs(h * math.cos(self.rotation) + w * math.sin(self.rotation))
return res_w, res_h | python | {
"resource": ""
} |
q227313 | Widget.queue_resize | train | def queue_resize(self):
"""request the element to re-check it's child sprite sizes"""
self._children_resize_queued = True
parent = getattr(self, "parent", None)
if parent and isinstance(parent, graphics.Sprite) and hasattr(parent, "queue_resize"):
parent.queue_resize() | python | {
"resource": ""
} |
q227314 | Widget.get_min_size | train | def get_min_size(self):
"""returns size required by the widget"""
if self.visible == False:
return 0, 0
else:
return ((self.min_width or 0) + self.horizontal_padding + self.margin_left + self.margin_right,
(self.min_height or 0) + self.vertical_padding... | python | {
"resource": ""
} |
q227315 | Widget.insert | train | def insert(self, index = 0, *widgets):
"""insert widget in the sprites list at the given index.
by default will prepend."""
for widget in widgets:
self._add(widget, index)
index +=1 # as we are moving forwards
self._sort() | python | {
"resource": ""
} |
q227316 | Widget.insert_before | train | def insert_before(self, target):
"""insert this widget into the targets parent before the target"""
if not target.parent:
return
target.parent.insert(target.parent.sprites.index(target), self) | python | {
"resource": ""
} |
q227317 | Widget.insert_after | train | def insert_after(self, target):
"""insert this widget into the targets parent container after the target"""
if not target.parent:
return
target.parent.insert(target.parent.sprites.index(target) + 1, self) | python | {
"resource": ""
} |
q227318 | Widget.width | train | def width(self):
"""width in pixels"""
alloc_w = self.alloc_w
if self.parent and isinstance(self.parent, graphics.Scene):
alloc_w = self.parent.width
def res(scene, event):
if self.parent:
self.queue_resize()
else:
... | python | {
"resource": ""
} |
q227319 | Widget.height | train | def height(self):
"""height in pixels"""
alloc_h = self.alloc_h
if self.parent and isinstance(self.parent, graphics.Scene):
alloc_h = self.parent.height
min_height = (self.min_height or 0) + self.margin_top + self.margin_bottom
h = alloc_h if alloc_h is not None and... | python | {
"resource": ""
} |
q227320 | Widget.enabled | train | def enabled(self):
"""whether the user is allowed to interact with the
widget. Item is enabled only if all it's parent elements are"""
enabled = self._enabled
if not enabled:
return False
if self.parent and isinstance(self.parent, Widget):
if self.parent.... | python | {
"resource": ""
} |
q227321 | Container.resize_children | train | def resize_children(self):
"""default container alignment is to pile stuff just up, respecting only
padding, margin and element's alignment properties"""
width = self.width - self.horizontal_padding
height = self.height - self.vertical_padding
for sprite, props in (get_props(spr... | python | {
"resource": ""
} |
q227322 | DesktopIntegrations.check_hamster | train | def check_hamster(self):
"""refresh hamster every x secs - load today, check last activity etc."""
try:
# can't use the client because then we end up in a dbus loop
# as this is initiated in storage
todays_facts = self.storage._Storage__get_todays_facts()
... | python | {
"resource": ""
} |
q227323 | DesktopIntegrations.check_user | train | def check_user(self, todays_facts):
"""check if we need to notify user perhaps"""
interval = self.conf_notify_interval
if interval <= 0 or interval >= 121:
return
now = dt.datetime.now()
message = None
last_activity = todays_facts[-1] if todays_facts else No... | python | {
"resource": ""
} |
q227324 | Storage.stop_tracking | train | def stop_tracking(self, end_time):
"""Stops tracking the current activity"""
facts = self.__get_todays_facts()
if facts and not facts[-1]['end_time']:
self.__touch_fact(facts[-1], end_time)
self.facts_changed() | python | {
"resource": ""
} |
q227325 | Storage.remove_fact | train | def remove_fact(self, fact_id):
"""Remove fact from storage by it's ID"""
self.start_transaction()
fact = self.__get_fact(fact_id)
if fact:
self.__remove_fact(fact_id)
self.facts_changed()
self.end_transaction() | python | {
"resource": ""
} |
q227326 | load_ui_file | train | def load_ui_file(name):
"""loads interface from the glade file; sorts out the path business"""
ui = gtk.Builder()
ui.add_from_file(os.path.join(runtime.data_dir, name))
return ui | python | {
"resource": ""
} |
q227327 | GConfStore._fix_key | train | def _fix_key(self, key):
"""
Appends the GCONF_PREFIX to the key if needed
@param key: The key to check
@type key: C{string}
@returns: The fixed key
@rtype: C{string}
"""
if not key.startswith(self.GCONF_DIR):
return self.GCONF_DIR + key
... | python | {
"resource": ""
} |
q227328 | GConfStore._key_changed | train | def _key_changed(self, client, cnxn_id, entry, data=None):
"""
Callback when a gconf key changes
"""
key = self._fix_key(entry.key)[len(self.GCONF_DIR):]
value = self._get_value(entry.value, self.DEFAULTS[key])
self.emit('conf-changed', key, value) | python | {
"resource": ""
} |
q227329 | GConfStore._get_value | train | def _get_value(self, value, default):
"""calls appropriate gconf function by the default value"""
vtype = type(default)
if vtype is bool:
return value.get_bool()
elif vtype is str:
return value.get_string()
elif vtype is int:
return value.get_... | python | {
"resource": ""
} |
q227330 | GConfStore.get | train | def get(self, key, default=None):
"""
Returns the value of the key or the default value if the key is
not yet in gconf
"""
#function arguments override defaults
if default is None:
default = self.DEFAULTS.get(key, None)
vtype = type(default)
... | python | {
"resource": ""
} |
q227331 | GConfStore.set | train | def set(self, key, value):
"""
Sets the key value in gconf and connects adds a signal
which is fired if the key changes
"""
logger.debug("Settings %s -> %s" % (key, value))
if key in self.DEFAULTS:
vtype = type(self.DEFAULTS[key])
else:
vty... | python | {
"resource": ""
} |
q227332 | GConfStore.day_start | train | def day_start(self):
"""Start of the hamster day."""
day_start_minutes = self.get("day_start_minutes")
hours, minutes = divmod(day_start_minutes, 60)
return dt.time(hours, minutes) | python | {
"resource": ""
} |
q227333 | CustomFactController.localized_fact | train | def localized_fact(self):
"""Make sure fact has the correct start_time."""
fact = Fact(self.activity.get_text())
if fact.start_time:
fact.date = self.date
else:
fact.start_time = dt.datetime.now()
return fact | python | {
"resource": ""
} |
q227334 | CompleteTree.set_row_positions | train | def set_row_positions(self):
"""creates a list of row positions for simpler manipulation"""
self.row_positions = [i * self.row_height for i in range(len(self.rows))]
self.set_size_request(0, self.row_positions[-1] + self.row_height if self.row_positions else 0) | python | {
"resource": ""
} |
q227335 | from_dbus_fact | train | def from_dbus_fact(fact):
"""unpack the struct into a proper dict"""
return Fact(fact[4],
start_time = dt.datetime.utcfromtimestamp(fact[1]),
end_time = dt.datetime.utcfromtimestamp(fact[2]) if fact[2] else None,
description = fact[3],
activity_id... | python | {
"resource": ""
} |
q227336 | Storage.get_tags | train | def get_tags(self, only_autocomplete = False):
"""returns list of all tags. by default only those that have been set for autocomplete"""
return self._to_dict(('id', 'name', 'autocomplete'), self.conn.GetTags(only_autocomplete)) | python | {
"resource": ""
} |
q227337 | Storage.stop_tracking | train | def stop_tracking(self, end_time = None):
"""Stop tracking current activity. end_time can be passed in if the
activity should have other end time than the current moment"""
end_time = timegm((end_time or dt.datetime.now()).timetuple())
return self.conn.StopTracking(end_time) | python | {
"resource": ""
} |
q227338 | Storage.get_category_activities | train | def get_category_activities(self, category_id = None):
"""Return activities for category. If category is not specified, will
return activities that have no category"""
category_id = category_id or -1
return self._to_dict(('id', 'name', 'category_id', 'category'), self.conn.GetCategoryAct... | python | {
"resource": ""
} |
q227339 | Storage.get_activity_by_name | train | def get_activity_by_name(self, activity, category_id = None, resurrect = True):
"""returns activity dict by name and optionally filtering by category.
if activity is found but is marked as deleted, it will be resurrected
unless told otherwise in the resurrect param
"""
cate... | python | {
"resource": ""
} |
q227340 | DbusIdleListener.bus_inspector | train | def bus_inspector(self, bus, message):
"""
Inspect the bus for screensaver messages of interest
"""
# We only care about stuff on this interface. We did filter
# for it above, but even so we still hear from ourselves
# (hamster messages).
if message.get_interfac... | python | {
"resource": ""
} |
q227341 | C_ | train | def C_(ctx, s):
"""Provide qualified translatable strings via context.
Taken from gnome-games.
"""
translated = gettext.gettext('%s\x04%s' % (ctx, s))
if '\x04' in translated:
# no translation found, return input string
return s
return translated | python | {
"resource": ""
} |
q227342 | clean | train | def clean(bld):
'''removes the build files'''
try:
proj=Environment.Environment(Options.lockfile)
except IOError:
raise Utils.WafError('Nothing to clean (project not configured)')
bld.load_dirs(proj[SRCDIR],proj[BLDDIR])
bld.load_envs()
bld.is_install=0
bld.add_subdirs([os.path.split(Utils.g_module.root_path... | python | {
"resource": ""
} |
q227343 | install | train | def install(bld):
'''installs the build files'''
bld=check_configured(bld)
Options.commands['install']=True
Options.commands['uninstall']=False
Options.is_install=True
bld.is_install=INSTALL
build_impl(bld)
bld.install() | python | {
"resource": ""
} |
q227344 | uninstall | train | def uninstall(bld):
'''removes the installed files'''
Options.commands['install']=False
Options.commands['uninstall']=True
Options.is_install=True
bld.is_install=UNINSTALL
try:
def runnable_status(self):
return SKIP_ME
setattr(Task.Task,'runnable_status_back',Task.Task.runnable_status)
setattr(Task.Task,... | python | {
"resource": ""
} |
q227345 | distclean | train | def distclean(ctx=None):
'''removes the build directory'''
global commands
lst=os.listdir('.')
for f in lst:
if f==Options.lockfile:
try:
proj=Environment.Environment(f)
except:
Logs.warn('could not read %r'%f)
continue
try:
shutil.rmtree(proj[BLDDIR])
except IOError:
pass
excep... | python | {
"resource": ""
} |
q227346 | dist | train | def dist(appname='',version=''):
'''makes a tarball for redistributing the sources'''
import tarfile
if not appname:appname=Utils.g_module.APPNAME
if not version:version=Utils.g_module.VERSION
tmp_folder=appname+'-'+version
if g_gz in['gz','bz2']:
arch_name=tmp_folder+'.tar.'+g_gz
else:
arch_name=tmp_folder+... | python | {
"resource": ""
} |
q227347 | ReportChooserDialog.show | train | def show(self, start_date, end_date):
"""setting suggested name to something readable, replace backslashes
with dots so the name is valid in linux"""
# title in the report file name
vars = {"title": _("Time track"),
"start": start_date.strftime("%x").replace("/", ".")... | python | {
"resource": ""
} |
q227348 | Tweener.kill_tweens | train | def kill_tweens(self, obj = None):
"""Stop tweening an object, without completing the motion or firing the
on_complete"""
if obj is not None:
try:
del self.current_tweens[obj]
except:
pass
else:
self.current_tweens = col... | python | {
"resource": ""
} |
q227349 | Tweener.remove_tween | train | def remove_tween(self, tween):
""""remove given tween without completing the motion or firing the on_complete"""
if tween.target in self.current_tweens and tween in self.current_tweens[tween.target]:
self.current_tweens[tween.target].remove(tween)
if not self.current_tweens[tween... | python | {
"resource": ""
} |
q227350 | Tweener.finish | train | def finish(self):
"""jump the the last frame of all tweens"""
for obj in self.current_tweens:
for tween in self.current_tweens[obj]:
tween.finish()
self.current_tweens = {} | python | {
"resource": ""
} |
q227351 | Tweener.update | train | def update(self, delta_seconds):
"""update tweeners. delta_seconds is time in seconds since last frame"""
for obj in tuple(self.current_tweens):
for tween in tuple(self.current_tweens[obj]):
done = tween.update(delta_seconds)
if done:
self... | python | {
"resource": ""
} |
q227352 | Tween.update | train | def update(self, ptime):
"""Update tween with the time since the last frame"""
delta = self.delta + ptime
total_duration = self.delay + self.duration
if delta > total_duration:
delta = total_duration
if delta < self.delay:
pass
elif delta == tota... | python | {
"resource": ""
} |
q227353 | StackedBar.set_items | train | def set_items(self, items):
"""expects a list of key, value to work with"""
res = []
max_value = max(sum((rec[1] for rec in items)), 1)
for key, val in items:
res.append((key, val, val * 1.0 / max_value))
self._items = res | python | {
"resource": ""
} |
q227354 | HorizontalBarChart.set_values | train | def set_values(self, values):
"""expects a list of 2-tuples"""
self.values = values
self.height = len(self.values) * 14
self._max = max(rec[1] for rec in values) if values else dt.timedelta(0) | python | {
"resource": ""
} |
q227355 | datetime_to_hamsterday | train | def datetime_to_hamsterday(civil_date_time):
"""Return the hamster day corresponding to a given civil datetime.
The hamster day start is taken into account.
"""
# work around cyclic imports
from hamster.lib.configuration import conf
if civil_date_time.time() < conf.day_start:
# early ... | python | {
"resource": ""
} |
q227356 | hamsterday_time_to_datetime | train | def hamsterday_time_to_datetime(hamsterday, time):
"""Return the civil datetime corresponding to a given hamster day and time.
The hamster day start is taken into account.
"""
# work around cyclic imports
from hamster.lib.configuration import conf
if time < conf.day_start:
# early mor... | python | {
"resource": ""
} |
q227357 | format_duration | train | def format_duration(minutes, human = True):
"""formats duration in a human readable format.
accepts either minutes or timedelta"""
if isinstance(minutes, dt.timedelta):
minutes = duration_minutes(minutes)
if not minutes:
if human:
return ""
else:
return ... | python | {
"resource": ""
} |
q227358 | duration_minutes | train | def duration_minutes(duration):
"""returns minutes from duration, otherwise we keep bashing in same math"""
if isinstance(duration, list):
res = dt.timedelta()
for entry in duration:
res += entry
return duration_minutes(res)
elif isinstance(duration, dt.timedelta):
... | python | {
"resource": ""
} |
q227359 | locale_first_weekday | train | def locale_first_weekday():
"""figure if week starts on monday or sunday"""
first_weekday = 6 #by default settle on monday
try:
process = os.popen("locale first_weekday week-1stday")
week_offset, week_start = process.read().split('\n')[:2]
process.close()
week_start = dt.dat... | python | {
"resource": ""
} |
q227360 | totals | train | def totals(iter, keyfunc, sumfunc):
"""groups items by field described in keyfunc and counts totals using value
from sumfunc
"""
data = sorted(iter, key=keyfunc)
res = {}
for k, group in groupby(data, keyfunc):
res[k] = sum([sumfunc(entry) for entry in group])
return res | python | {
"resource": ""
} |
q227361 | dateDict | train | def dateDict(date, prefix = ""):
"""converts date into dictionary, having prefix for all the keys"""
res = {}
res[prefix+"a"] = date.strftime("%a")
res[prefix+"A"] = date.strftime("%A")
res[prefix+"b"] = date.strftime("%b")
res[prefix+"B"] = date.strftime("%B")
res[prefix+"c"] = date.strfti... | python | {
"resource": ""
} |
q227362 | Storage.__get_tag_ids | train | def __get_tag_ids(self, tags):
"""look up tags by their name. create if not found"""
db_tags = self.fetchall("select * from tags where name in (%s)"
% ",".join(["?"] * len(tags)), tags) # bit of magic here - using sqlites bind variables
changes = Fal... | python | {
"resource": ""
} |
q227363 | Storage.__get_activity_by_name | train | def __get_activity_by_name(self, name, category_id = None, resurrect = True):
"""get most recent, preferably not deleted activity by it's name"""
if category_id:
query = """
SELECT a.id, a.name, a.deleted, coalesce(b.name, ?) as category
FROM ... | python | {
"resource": ""
} |
q227364 | Storage.__get_category_id | train | def __get_category_id(self, name):
"""returns category by it's name"""
query = """
SELECT id from categories
WHERE lower(name) = lower(?)
ORDER BY id desc
LIMIT 1
"""
res = self.fetchone(query, (name, ))
... | python | {
"resource": ""
} |
q227365 | Storage.__group_tags | train | def __group_tags(self, facts):
"""put the fact back together and move all the unique tags to an array"""
if not facts: return facts #be it None or whatever
grouped_facts = []
for fact_id, fact_tags in itertools.groupby(facts, lambda f: f["id"]):
fact_tags = list(fact_tags)
... | python | {
"resource": ""
} |
q227366 | Storage.__squeeze_in | train | def __squeeze_in(self, start_time):
""" tries to put task in the given date
if there are conflicts, we will only truncate the ongoing task
and replace it's end part with our activity """
# we are checking if our start time is in the middle of anything
# or maybe there is... | python | {
"resource": ""
} |
q227367 | Storage.__get_activities | train | def __get_activities(self, search):
"""returns list of activities for autocomplete,
activity names converted to lowercase"""
query = """
SELECT a.name AS name, b.name AS category
FROM activities a
LEFT JOIN categories b ON coalesce(b.id... | python | {
"resource": ""
} |
q227368 | Storage.__remove_activity | train | def __remove_activity(self, id):
""" check if we have any facts with this activity and behave accordingly
if there are facts - sets activity to deleted = True
else, just remove it"""
query = "select count(*) as count from facts where activity_id = ?"
bound_facts = self.f... | python | {
"resource": ""
} |
q227369 | Storage.__remove_category | train | def __remove_category(self, id):
"""move all activities to unsorted and remove category"""
affected_query = """
SELECT id
FROM facts
WHERE activity_id in (SELECT id FROM activities where category_id=?)
"""
affected_ids = [res[0] for res in self.fet... | python | {
"resource": ""
} |
q227370 | Storage.__remove_index | train | def __remove_index(self, ids):
"""remove affected ids from the index"""
if not ids:
return
ids = ",".join((str(id) for id in ids))
self.execute("DELETE FROM fact_index where id in (%s)" % ids) | python | {
"resource": ""
} |
q227371 | Storage.execute | train | def execute(self, statement, params = ()):
"""
execute sql statement. optionally you can give multiple statements
to save on cursor creation and closure
"""
con = self.__con or self.connection
cur = self.__cur or con.cursor()
if isinstance(statement, list) == Fal... | python | {
"resource": ""
} |
q227372 | Storage.run_fixtures | train | def run_fixtures(self):
self.start_transaction()
"""upgrade DB to hamster version"""
version = self.fetchone("SELECT version FROM version")["version"]
current_version = 9
if version < 8:
# working around sqlite's utf-f case sensitivity (bug 624438)
# mor... | python | {
"resource": ""
} |
q227373 | FactTree.current_fact_index | train | def current_fact_index(self):
"""Current fact index in the self.facts list."""
facts_ids = [fact.id for fact in self.facts]
return facts_ids.index(self.current_fact.id) | python | {
"resource": ""
} |
q227374 | chain | train | def chain(*steps):
"""chains the given list of functions and object animations into a callback string.
Expects an interlaced list of object and params, something like:
object, {params},
callable, {params},
object, {},
object, {params}
Assumes that all cal... | python | {
"resource": ""
} |
q227375 | full_pixels | train | def full_pixels(space, data, gap_pixels=1):
"""returns the given data distributed in the space ensuring it's full pixels
and with the given gap.
this will result in minor sub-pixel inaccuracies.
XXX - figure out where to place these guys as they are quite useful
"""
available = space - (len(data... | python | {
"resource": ""
} |
q227376 | ColorUtils.gdk | train | def gdk(self, color):
"""returns gdk.Color object of the given color"""
c = self.parse(color)
return gdk.Color.from_floats(c) | python | {
"resource": ""
} |
q227377 | ColorUtils.contrast | train | def contrast(self, color, step):
"""if color is dark, will return a lighter one, otherwise darker"""
hls = colorsys.rgb_to_hls(*self.rgb(color))
if self.is_light(color):
return colorsys.hls_to_rgb(hls[0], hls[1] - step, hls[2])
else:
return colorsys.hls_to_rgb(hls... | python | {
"resource": ""
} |
q227378 | ColorUtils.mix | train | def mix(self, ca, cb, xb):
"""Mix colors.
Args:
ca (gdk.RGBA): first color
cb (gdk.RGBA): second color
xb (float): between 0.0 and 1.0
Return:
gdk.RGBA: linear interpolation between ca and cb,
0 or 1 return the unaltered 1st... | python | {
"resource": ""
} |
q227379 | Graphics.set_line_style | train | def set_line_style(self, width = None, dash = None, dash_offset = 0):
"""change width and dash of a line"""
if width is not None:
self._add_instruction("set_line_width", width)
if dash is not None:
self._add_instruction("set_dash", dash, dash_offset) | python | {
"resource": ""
} |
q227380 | Graphics._set_color | train | def _set_color(self, context, r, g, b, a):
"""the alpha has to changed based on the parent, so that happens at the
time of drawing"""
if a < 1:
context.set_source_rgba(r, g, b, a)
else:
context.set_source_rgb(r, g, b) | python | {
"resource": ""
} |
q227381 | Graphics.arc | train | def arc(self, x, y, radius, start_angle, end_angle):
"""draw arc going counter-clockwise from start_angle to end_angle"""
self._add_instruction("arc", x, y, radius, start_angle, end_angle) | python | {
"resource": ""
} |
q227382 | Graphics.ellipse | train | def ellipse(self, x, y, width, height, edges = None):
"""draw 'perfect' ellipse, opposed to squashed circle. works also for
equilateral polygons"""
# the automatic edge case is somewhat arbitrary
steps = edges or max((32, width, height)) / 2
angle = 0
step = math.pi *... | python | {
"resource": ""
} |
q227383 | Graphics.arc_negative | train | def arc_negative(self, x, y, radius, start_angle, end_angle):
"""draw arc going clockwise from start_angle to end_angle"""
self._add_instruction("arc_negative", x, y, radius, start_angle, end_angle) | python | {
"resource": ""
} |
q227384 | Graphics.rectangle | train | def rectangle(self, x, y, width, height, corner_radius = 0):
"""draw a rectangle. if corner_radius is specified, will draw
rounded corners. corner_radius can be either a number or a tuple of
four items to specify individually each corner, starting from top-left
and going clockwise"""
... | python | {
"resource": ""
} |
q227385 | Graphics.fill_area | train | def fill_area(self, x, y, width, height, color, opacity = 1):
"""fill rectangular area with specified color"""
self.save_context()
self.rectangle(x, y, width, height)
self._add_instruction("clip")
self.rectangle(x, y, width, height)
self.fill(color, opacity)
self.... | python | {
"resource": ""
} |
q227386 | Graphics.fill_stroke | train | def fill_stroke(self, fill = None, stroke = None, opacity = 1, line_width = None):
"""fill and stroke the drawn area in one go"""
if line_width: self.set_line_style(line_width)
if fill and stroke:
self.fill_preserve(fill, opacity)
elif fill:
self.fill(fill, opaci... | python | {
"resource": ""
} |
q227387 | Graphics.create_layout | train | def create_layout(self, size = None):
"""utility function to create layout with the default font. Size and
alignment parameters are shortcuts to according functions of the
pango.Layout"""
if not self.context:
# TODO - this is rather sloppy as far as exception goes
... | python | {
"resource": ""
} |
q227388 | Graphics.show_label | train | def show_label(self, text, size = None, color = None, font_desc = None):
"""display text. unless font_desc is provided, will use system's default font"""
font_desc = pango.FontDescription(font_desc or _font_desc)
if color: self.set_color(color)
if size: font_desc.set_absolute_size(size *... | python | {
"resource": ""
} |
q227389 | Graphics._draw | train | def _draw(self, context, opacity):
"""draw accumulated instructions in context"""
# if we have been moved around, we should update bounds
fresh_draw = len(self.__new_instructions or []) > 0
if fresh_draw: #new stuff!
self.paths = []
self.__instruction_cache = sel... | python | {
"resource": ""
} |
q227390 | Parent.find | train | def find(self, id):
"""breadth-first sprite search by ID"""
for sprite in self.sprites:
if sprite.id == id:
return sprite
for sprite in self.sprites:
found = sprite.find(id)
if found:
return found | python | {
"resource": ""
} |
q227391 | Parent.traverse | train | def traverse(self, attr_name = None, attr_value = None):
"""traverse the whole sprite tree and return child sprites which have the
attribute and it's set to the specified value.
If falue is None, will return all sprites that have the attribute
"""
for sprite in self.sprites:
... | python | {
"resource": ""
} |
q227392 | Parent.log | train | def log(self, *lines):
"""will print out the lines in console if debug is enabled for the
specific sprite"""
if getattr(self, "debug", False):
print(dt.datetime.now().time(), end=' ')
for line in lines:
print(line, end=' ')
print() | python | {
"resource": ""
} |
q227393 | Parent._add | train | def _add(self, sprite, index = None):
"""add one sprite at a time. used by add_child. split them up so that
it would be possible specify the index externally"""
if sprite == self:
raise Exception("trying to add sprite to itself")
if sprite.parent:
sprite.x, sprit... | python | {
"resource": ""
} |
q227394 | Parent._sort | train | def _sort(self):
"""sort sprites by z_order"""
self.__dict__['_z_ordered_sprites'] = sorted(self.sprites, key=lambda sprite:sprite.z_order) | python | {
"resource": ""
} |
q227395 | Parent.add_child | train | def add_child(self, *sprites):
"""Add child sprite. Child will be nested within parent"""
for sprite in sprites:
self._add(sprite)
self._sort()
self.redraw() | python | {
"resource": ""
} |
q227396 | Parent.all_child_sprites | train | def all_child_sprites(self):
"""returns all child and grandchild sprites in a flat list"""
for sprite in self.sprites:
for child_sprite in sprite.all_child_sprites():
yield child_sprite
yield sprite | python | {
"resource": ""
} |
q227397 | Parent.disconnect_child | train | def disconnect_child(self, sprite, *handlers):
"""disconnects from child event. if handler is not specified, will
disconnect from all the child sprite events"""
handlers = handlers or self._child_handlers.get(sprite, [])
for handler in list(handlers):
if sprite.handler_is_con... | python | {
"resource": ""
} |
q227398 | Sprite._get_mouse_cursor | train | def _get_mouse_cursor(self):
"""Determine mouse cursor.
By default look for self.mouse_cursor is defined and take that.
Otherwise use gdk.CursorType.FLEUR for draggable sprites and gdk.CursorType.HAND2 for
interactive sprites. Defaults to scenes cursor.
"""
if self.mouse_... | python | {
"resource": ""
} |
q227399 | Sprite.bring_to_front | train | def bring_to_front(self):
"""adjusts sprite's z-order so that the sprite is on top of it's
siblings"""
if not self.parent:
return
self.z_order = self.parent._z_ordered_sprites[-1].z_order + 1 | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.