_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q21700
Apps.get_cdn_auth_token
train
def get_cdn_auth_token(self, app_id, hostname): """Get CDN authentication token :param app_id: app id :type app_id: :class:`int` :param hostname: cdn hostname :type hostname: :class:`str` :return: `CMsgClientGetCDNAuthTokenResponse <https://github.com/ValvePython/steam/blob/39627fe883feeed2206016bacd92cf0e4580ead6/protobufs/steammessages_clientserver_2.proto#L585-L589>`_ :rtype: proto message """ return self.send_job_and_wait(MsgProto(EMsg.ClientGetCDNAuthToken), { 'app_id': app_id, 'host_name': hostname, }, timeout=15 )
python
{ "resource": "" }
q21701
Apps.get_product_access_tokens
train
def get_product_access_tokens(self, app_ids=[], package_ids=[]): """Get access tokens :param app_ids: list of app ids :type app_ids: :class:`list` :param package_ids: list of package ids :type package_ids: :class:`list` :return: dict with ``apps`` and ``packages`` containing their access tokens, see example below :rtype: :class:`dict`, :class:`None` .. code:: python {'apps': {123: 'token', ...}, 'packages': {456: 'token', ...} } """ if not app_ids and not package_ids: return resp = self.send_job_and_wait(MsgProto(EMsg.ClientPICSAccessTokenRequest), { 'appids': map(int, app_ids), 'packageids': map(int, package_ids), }, timeout=15 ) if resp: return {'apps': dict(map(lambda app: (app.appid, app.access_token), resp.app_access_tokens)), 'packages': dict(map(lambda pkg: (pkg.appid, pkg.access_token), resp.package_access_tokens)), }
python
{ "resource": "" }
q21702
a2s_players
train
def a2s_players(server_addr, timeout=2, challenge=0): """Get list of players and their info :param server_addr: (ip, port) for the server :type server_addr: tuple :param timeout: (optional) timeout in seconds :type timeout: float :param challenge: (optional) challenge number :type challenge: int :raises: :class:`RuntimeError`, :class:`socket.timeout` :returns: a list of players :rtype: :class:`list` """ ss = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) ss.connect(server_addr) ss.settimeout(timeout) # request challenge number header = None if challenge in (-1, 0): ss.send(_pack('<lci', -1, b'U', challenge)) try: data = ss.recv(512) _, header, challenge = _unpack_from('<lcl', data) except: ss.close() raise if header not in b'AD': # work around for CSGO sending only max players raise RuntimeError("Unexpected challenge response - %s" % repr(header)) # request player info if header == b'D': # work around for CSGO sending only max players data = StructReader(data) else: ss.send(_pack('<lci', -1, b'U', challenge)) try: data = StructReader(_handle_a2s_response(ss)) finally: ss.close() header, num_players = data.unpack('<4xcB') if header != b'D': raise RuntimeError("Invalid reponse header - %s" % repr(header)) players = [] while len(players) < num_players: player = dict() player['index'] = data.unpack('<B')[0] player['name'] = data.read_cstring() player['score'], player['duration'] = data.unpack('<lf') players.append(player) if data.rlen() / 8 == num_players: # assume the ship server for player in players: player['deaths'], player['money'] = data.unpack('<ll') return players
python
{ "resource": "" }
q21703
a2s_rules
train
def a2s_rules(server_addr, timeout=2, challenge=0): """Get rules from server :param server_addr: (ip, port) for the server :type server_addr: tuple :param timeout: (optional) timeout in seconds :type timeout: float :param challenge: (optional) challenge number :type challenge: int :raises: :class:`RuntimeError`, :class:`socket.timeout` :returns: a list of players :rtype: :class:`list` """ ss = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) ss.connect(server_addr) ss.settimeout(timeout) # request challenge number if challenge in (-1, 0): ss.send(_pack('<lci', -1, b'V', challenge)) try: _, header, challenge = _unpack_from('<lcl', ss.recv(512)) except: ss.close() raise if header != b'A': raise RuntimeError("Unexpected challenge response") # request player info ss.send(_pack('<lci', -1, b'V', challenge)) try: data = StructReader(_handle_a2s_response(ss)) finally: ss.close() header, num_rules = data.unpack('<4xcH') if header != b'E': raise RuntimeError("Invalid reponse header - %s" % repr(header)) rules = {} while len(rules) != num_rules: name = data.read_cstring() value = data.read_cstring() if _re_match(r'^\-?[0-9]+$', value): value = int(value) elif _re_match(r'^\-?[0-9]+\.[0-9]+$', value): value = float(value) rules[name] = value return rules
python
{ "resource": "" }
q21704
a2s_ping
train
def a2s_ping(server_addr, timeout=2): """Ping a server .. warning:: This method for pinging is considered deprecated and may not work on certian servers. Use :func:`.a2s_info` instead. :param server_addr: (ip, port) for the server :type server_addr: tuple :param timeout: (optional) timeout in seconds :type timeout: float :raises: :class:`RuntimeError`, :class:`socket.timeout` :returns: ping response in milliseconds or `None` for timeout :rtype: :class:`float` """ ss = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) ss.connect(server_addr) ss.settimeout(timeout) ss.send(_pack('<lc', -1, b'i')) start = _time() try: data = _handle_a2s_response(ss) finally: ss.close() ping = max(0.0, _time() - start) * 1000 if data[4:5] == b'j': return ping
python
{ "resource": "" }
q21705
get_cmsg
train
def get_cmsg(emsg): """Get protobuf for a given EMsg :param emsg: EMsg :type emsg: :class:`steam.enums.emsg.EMsg`, :class:`int` :return: protobuf message """ if not isinstance(emsg, EMsg): emsg = EMsg(emsg) if emsg in cmsg_lookup_predefined: return cmsg_lookup_predefined[emsg] else: enum_name = emsg.name.lower() if enum_name.startswith("econ"): # special case for 'EconTrading_' enum_name = enum_name[4:] cmsg_name = "cmsg" + enum_name return cmsg_lookup.get(cmsg_name, None)
python
{ "resource": "" }
q21706
Web.get_web_session_cookies
train
def get_web_session_cookies(self): """Get web authentication cookies via WebAPI's ``AuthenticateUser`` .. note:: The cookies are valid only while :class:`.SteamClient` instance is logged on. :return: dict with authentication cookies :rtype: :class:`dict`, :class:`None` """ if not self.logged_on: return None resp = self.send_job_and_wait(MsgProto(EMsg.ClientRequestWebAPIAuthenticateUserNonce), timeout=7) if resp is None: return None skey, ekey = generate_session_key() data = { 'steamid': self.steam_id, 'sessionkey': ekey, 'encrypted_loginkey': symmetric_encrypt(resp.webapi_authenticate_user_nonce.encode('ascii'), skey), } try: resp = webapi.post('ISteamUserAuth', 'AuthenticateUser', 1, params=data) except Exception as exp: self._LOG.debug("get_web_session_cookies error: %s" % str(exp)) return None return { 'steamLogin': resp['authenticateuser']['token'], 'steamLoginSecure': resp['authenticateuser']['tokensecure'], }
python
{ "resource": "" }
q21707
User.change_status
train
def change_status(self, **kwargs): """ Set name, persona state, flags .. note:: Changing persona state will also change :attr:`persona_state` :param persona_state: persona state (Online/Offlane/Away/etc) :type persona_state: :class:`.EPersonaState` :param player_name: profile name :type player_name: :class:`str` :param persona_state_flags: persona state flags :type persona_state_flags: :class:`.EPersonaStateFlag` """ if not kwargs: return self.persona_state = kwargs.get('persona_state', self.persona_state) message = MsgProto(EMsg.ClientChangeStatus) proto_fill_from_dict(message.body, kwargs) self.send(message)
python
{ "resource": "" }
q21708
User.request_persona_state
train
def request_persona_state(self, steam_ids, state_flags=863): """Request persona state data :param steam_ids: list of steam ids :type steam_ids: :class:`list` :param state_flags: client state flags :type state_flags: :class:`.EClientPersonaStateFlag` """ m = MsgProto(EMsg.ClientRequestFriendData) m.body.persona_state_requested = state_flags m.body.friends.extend(steam_ids) self.send(m)
python
{ "resource": "" }
q21709
User.games_played
train
def games_played(self, app_ids): """ Set the apps being played by the user :param app_ids: a list of application ids :type app_ids: :class:`list` These app ids will be recorded in :attr:`current_games_played`. """ if not isinstance(app_ids, list): raise ValueError("Expected app_ids to be of type list") self.current_games_played = app_ids = list(map(int, app_ids)) self.send(MsgProto(EMsg.ClientGamesPlayed), {'games_played': [{'game_id': app_id} for app_id in app_ids]} )
python
{ "resource": "" }
q21710
GlobalID.new
train
def new(sequence_count, start_time, process_id, box_id): """Make new GlobalID :param sequence_count: sequence count :type sequence_count: :class:`int` :param start_time: start date time of server (must be after 2005-01-01) :type start_time: :class:`str`, :class:`datetime` :param process_id: process id :type process_id: :class:`int` :param box_id: box id :type box_id: :class:`int` :return: Global ID integer :rtype: :class:`int` """ if not isinstance(start_time, datetime): start_time = datetime.strptime(start_time, '%Y-%m-%d %H:%M:%S') start_time_seconds = int((start_time - datetime(2005, 1, 1)).total_seconds()) return (box_id << 54) | (process_id << 50) | (start_time_seconds << 20) | sequence_count
python
{ "resource": "" }
q21711
Service.get_shared_people
train
def get_shared_people(self): """Retrieves all people that share their location with this account""" people = [] output = self._get_data() self._logger.debug(output) shared_entries = output[0] or [] for info in shared_entries: try: people.append(Person(info)) except InvalidData: self._logger.debug('Missing location or other info, dropping person with info: %s', info) return people
python
{ "resource": "" }
q21712
Service.get_authenticated_person
train
def get_authenticated_person(self): """Retrieves the person associated with this account""" try: output = self._get_data() self._logger.debug(output) person = Person([ self.email, output[9][1], None, None, None, None, [ None, None, self.email, self.email ], None, None, None, None, None, None, None, ]) except (IndexError, TypeError, InvalidData): self._logger.debug('Missing essential info, cannot instantiate authenticated person') return None return person
python
{ "resource": "" }
q21713
Service.get_person_by_nickname
train
def get_person_by_nickname(self, nickname): """Retrieves a person by nickname""" return next((person for person in self.get_all_people() if person.nickname.lower() == nickname.lower()), None)
python
{ "resource": "" }
q21714
Service.get_person_by_full_name
train
def get_person_by_full_name(self, name): """Retrieves a person by full name""" return next((person for person in self.get_all_people() if person.full_name.lower() == name.lower()), None)
python
{ "resource": "" }
q21715
Service.get_coordinates_by_nickname
train
def get_coordinates_by_nickname(self, nickname): """Retrieves a person's coordinates by nickname""" person = self.get_person_by_nickname(nickname) if not person: return '', '' return person.latitude, person.longitude
python
{ "resource": "" }
q21716
Service.get_coordinates_by_full_name
train
def get_coordinates_by_full_name(self, name): """Retrieves a person's coordinates by full name""" person = self.get_person_by_full_name(name) if not person: return '', '' return person.latitude, person.longitude
python
{ "resource": "" }
q21717
Person.datetime
train
def datetime(self): """A datetime representation of the location retrieval""" return datetime.fromtimestamp(int(self.timestamp) / 1000, tz=pytz.utc)
python
{ "resource": "" }
q21718
xnormpath
train
def xnormpath(path): """ Cross-platform version of os.path.normpath """ # replace escapes and Windows slashes normalized = posixpath.normpath(path).replace(b'\\', b'/') # fold the result return posixpath.normpath(normalized)
python
{ "resource": "" }
q21719
xstrip
train
def xstrip(filename): """ Make relative path out of absolute by stripping prefixes used on Linux, OS X and Windows. This function is critical for security. """ while xisabs(filename): # strip windows drive with all slashes if re.match(b'\\w:[\\\\/]', filename): filename = re.sub(b'^\\w+:[\\\\/]+', b'', filename) # strip all slashes elif re.match(b'[\\\\/]', filename): filename = re.sub(b'^[\\\\/]+', b'', filename) return filename
python
{ "resource": "" }
q21720
pathstrip
train
def pathstrip(path, n): """ Strip n leading components from the given path """ pathlist = [path] while os.path.dirname(pathlist[0]) != b'': pathlist[0:1] = os.path.split(pathlist[0]) return b'/'.join(pathlist[n:])
python
{ "resource": "" }
q21721
PatchSet._detect_type
train
def _detect_type(self, p): """ detect and return type for the specified Patch object analyzes header and filenames info NOTE: must be run before filenames are normalized """ # check for SVN # - header starts with Index: # - next line is ===... delimiter # - filename is followed by revision number # TODO add SVN revision if (len(p.header) > 1 and p.header[-2].startswith(b"Index: ") and p.header[-1].startswith(b"="*67)): return SVN # common checks for both HG and GIT DVCS = ((p.source.startswith(b'a/') or p.source == b'/dev/null') and (p.target.startswith(b'b/') or p.target == b'/dev/null')) # GIT type check # - header[-2] is like "diff --git a/oldname b/newname" # - header[-1] is like "index <hash>..<hash> <mode>" # TODO add git rename diffs and add/remove diffs # add git diff with spaced filename # TODO http://www.kernel.org/pub/software/scm/git/docs/git-diff.html # Git patch header len is 2 min if len(p.header) > 1: # detect the start of diff header - there might be some comments before for idx in reversed(range(len(p.header))): if p.header[idx].startswith(b"diff --git"): break if p.header[idx].startswith(b'diff --git a/'): if (idx+1 < len(p.header) and re.match(b'index \\w{7}..\\w{7} \\d{6}', p.header[idx+1])): if DVCS: return GIT # HG check # # - for plain HG format header is like "diff -r b2d9961ff1f5 filename" # - for Git-style HG patches it is "diff --git a/oldname b/newname" # - filename starts with a/, b/ or is equal to /dev/null # - exported changesets also contain the header # # HG changeset patch # # User name@example.com # ... # TODO add MQ # TODO add revision info if len(p.header) > 0: if DVCS and re.match(b'diff -r \\w{12} .*', p.header[-1]): return HG if DVCS and p.header[-1].startswith(b'diff --git a/'): if len(p.header) == 1: # native Git patch header len is 2 return HG elif p.header[0].startswith(b'# HG changeset patch'): return HG return PLAIN
python
{ "resource": "" }
q21722
PatchSet.findfile
train
def findfile(self, old, new): """ return name of file to be patched or None """ if exists(old): return old elif exists(new): return new else: # [w] Google Code generates broken patches with its online editor debug("broken patch from Google Code, stripping prefixes..") if old.startswith(b'a/') and new.startswith(b'b/'): old, new = old[2:], new[2:] debug(" %s" % old) debug(" %s" % new) if exists(old): return old elif exists(new): return new return None
python
{ "resource": "" }
q21723
PatchSet.revert
train
def revert(self, strip=0, root=None): """ apply patch in reverse order """ reverted = copy.deepcopy(self) reverted._reverse() return reverted.apply(strip, root)
python
{ "resource": "" }
q21724
PatchSet.can_patch
train
def can_patch(self, filename): """ Check if specified filename can be patched. Returns None if file can not be found among source filenames. False if patch can not be applied clearly. True otherwise. :returns: True, False or None """ filename = abspath(filename) for p in self.items: if filename == abspath(p.source): return self._match_file_hunks(filename, p.hunks) return None
python
{ "resource": "" }
q21725
PatchSet.patch_stream
train
def patch_stream(self, instream, hunks): """ Generator that yields stream patched with hunks iterable Converts lineends in hunk lines to the best suitable format autodetected from input """ # todo: At the moment substituted lineends may not be the same # at the start and at the end of patching. Also issue a # warning/throw about mixed lineends (is it really needed?) hunks = iter(hunks) srclineno = 1 lineends = {b'\n':0, b'\r\n':0, b'\r':0} def get_line(): """ local utility function - return line from source stream collecting line end statistics on the way """ line = instream.readline() # 'U' mode works only with text files if line.endswith(b"\r\n"): lineends[b"\r\n"] += 1 elif line.endswith(b"\n"): lineends[b"\n"] += 1 elif line.endswith(b"\r"): lineends[b"\r"] += 1 return line for hno, h in enumerate(hunks): debug("hunk %d" % (hno+1)) # skip to line just before hunk starts while srclineno < h.startsrc: yield get_line() srclineno += 1 for hline in h.text: # todo: check \ No newline at the end of file if hline.startswith(b"-") or hline.startswith(b"\\"): get_line() srclineno += 1 continue else: if not hline.startswith(b"+"): get_line() srclineno += 1 line2write = hline[1:] # detect if line ends are consistent in source file if sum([bool(lineends[x]) for x in lineends]) == 1: newline = [x for x in lineends if lineends[x] != 0][0] yield line2write.rstrip(b"\r\n")+newline else: # newlines are mixed yield line2write for line in instream: yield line
python
{ "resource": "" }
q21726
cd
train
def cd(new_directory, clean_up=lambda: True): # pylint: disable=invalid-name """Changes into a given directory and cleans up after it is done Args: new_directory: The directory to change to clean_up: A method to clean up the working directory once done """ previous_directory = os.getcwd() os.chdir(os.path.expanduser(new_directory)) try: yield finally: os.chdir(previous_directory) clean_up()
python
{ "resource": "" }
q21727
tempdir
train
def tempdir(): """Creates a temporary directory""" directory_path = tempfile.mkdtemp() def clean_up(): # pylint: disable=missing-docstring shutil.rmtree(directory_path, onerror=on_error) with cd(directory_path, clean_up): yield directory_path
python
{ "resource": "" }
q21728
ScrolledListbox._grid_widgets
train
def _grid_widgets(self): """Puts the two whole widgets in the correct position depending on compound.""" scrollbar_column = 0 if self.__compound is tk.LEFT else 2 self.listbox.grid(row=0, column=1, sticky="nswe") self.scrollbar.grid(row=0, column=scrollbar_column, sticky="ns")
python
{ "resource": "" }
q21729
ItemsCanvas.left_press
train
def left_press(self, event): """ Callback for the press of the left mouse button. Selects a new item and sets its highlightcolor. :param event: Tkinter event """ self.current_coords = self.canvas.canvasx(event.x), self.canvas.canvasy(event.y) self.set_current() if self.current: self.canvas.itemconfigure(self.current, fill=self.item_colors[self.current][1]) self.current = None return results = self.canvas.find_withtag(tk.CURRENT) if len(results) is 0: return self.current = results[0] self.canvas.itemconfigure(self.current, fill=self.item_colors[self.current][2])
python
{ "resource": "" }
q21730
ItemsCanvas.left_release
train
def left_release(self, event): """ Callback for the release of the left button. :param event: Tkinter event """ self.config(cursor="") if len(self.canvas.find_withtag("current")) != 0 and self.current is not None: self.canvas.itemconfigure(tk.CURRENT, fill=self.item_colors[self.current][1])
python
{ "resource": "" }
q21731
ItemsCanvas.left_motion
train
def left_motion(self, event): """ Callback for the B1-Motion event, or the dragging of an item. Moves the item to the desired location, but limits its movement to a place on the actual Canvas. The item cannot be moved outside of the Canvas. :param event: Tkinter event """ self.set_current() results = self.canvas.find_withtag(tk.CURRENT) if len(results) is 0: return item = results[0] rectangle = self.items[item] self.config(cursor="exchange") self.canvas.itemconfigure(item, fill="blue") xc, yc = self.canvas.canvasx(event.x), self.canvas.canvasy(event.y) dx, dy = xc - self.current_coords[0], yc - self.current_coords[1] self.current_coords = xc, yc self.canvas.move(item, dx, dy) # check whether the new position of the item respects the boundaries x, y = self.canvas.coords(item) x, y = max(min(x, self._max_x), 0), max(min(y, self._max_y), 0) self.canvas.coords(item, x, y) self.canvas.coords(rectangle, self.canvas.bbox(item))
python
{ "resource": "" }
q21732
ItemsCanvas.del_item
train
def del_item(self): """Delete the current item on the Canvas.""" item = self.current rectangle = self.items[item] self.canvas.delete(item, rectangle) if callable(self._callback_del): self._callback_del(item, rectangle)
python
{ "resource": "" }
q21733
DebugWindow.save
train
def save(self): """Save widget content.""" file_name = fd.asksaveasfilename() if file_name is "" or file_name is None: return with open(file_name, "w") as f: f.write(self.text.get("1.0", tk.END))
python
{ "resource": "" }
q21734
LimitVar.get
train
def get(self): """ Convert the content to int between the limits of the variable. If the content is not an integer between the limits, the value is corrected and the corrected result is returned. """ val = tk.StringVar.get(self) try: val = int(val) if val < self._from: val = self._from self.set(val) elif val > self._to: val = self._to self.set(val) except ValueError: val = 0 self.set(0) return val
python
{ "resource": "" }
q21735
askcolor
train
def askcolor(color="red", parent=None, title=_("Color Chooser"), alpha=False): """ Open a ColorPicker dialog and return the chosen color. :return: the selected color in RGB(A) and hexadecimal #RRGGBB(AA) formats. (None, None) is returned if the color selection is cancelled. :param color: initially selected color (RGB(A), HEX or tkinter color name) :type color: sequence[int] or str :param parent: parent widget :type parent: widget :param title: dialog title :type title: str :param alpha: whether to display the alpha channel :type alpha: bool """ col = ColorPicker(parent, color, alpha, title) col.wait_window(col) res = col.get_color() if res: return res[0], res[2] else: return None, None
python
{ "resource": "" }
q21736
ColorPicker._unfocus
train
def _unfocus(self, event): """Unfocus palette items when click on bar or square.""" w = self.focus_get() if w != self and 'spinbox' not in str(w) and 'entry' not in str(w): self.focus_set()
python
{ "resource": "" }
q21737
ColorPicker._update_preview
train
def _update_preview(self): """Update color preview.""" color = self.hexa.get() if self.alpha_channel: prev = overlay(self._transparent_bg, hexa_to_rgb(color)) self._im_color = ImageTk.PhotoImage(prev, master=self) self.color_preview.configure(image=self._im_color) else: self.color_preview.configure(background=color)
python
{ "resource": "" }
q21738
ColorPicker._change_sel_color
train
def _change_sel_color(self, event): """Respond to motion of the color selection cross.""" (r, g, b), (h, s, v), color = self.square.get() self.red.set(r) self.green.set(g) self.blue.set(b) self.saturation.set(s) self.value.set(v) self.hexa.delete(0, "end") self.hexa.insert(0, color.upper()) if self.alpha_channel: self.alphabar.set_color((r, g, b)) self.hexa.insert('end', ("%2.2x" % self.alpha.get()).upper()) self._update_preview()
python
{ "resource": "" }
q21739
ColorPicker._change_color
train
def _change_color(self, event): """Respond to motion of the hsv cursor.""" h = self.bar.get() self.square.set_hue(h) (r, g, b), (h, s, v), sel_color = self.square.get() self.red.set(r) self.green.set(g) self.blue.set(b) self.hue.set(h) self.saturation.set(s) self.value.set(v) self.hexa.delete(0, "end") self.hexa.insert(0, sel_color.upper()) if self.alpha_channel: self.alphabar.set_color((r, g, b)) self.hexa.insert('end', ("%2.2x" % self.alpha.get()).upper()) self._update_preview()
python
{ "resource": "" }
q21740
ColorPicker._update_color_hexa
train
def _update_color_hexa(self, event=None): """Update display after a change in the HEX entry.""" color = self.hexa.get().upper() self.hexa.delete(0, 'end') self.hexa.insert(0, color) if re.match(r"^#[0-9A-F]{6}$", color): r, g, b = hexa_to_rgb(color) self.red.set(r) self.green.set(g) self.blue.set(b) h, s, v = rgb_to_hsv(r, g, b) self.hue.set(h) self.saturation.set(s) self.value.set(v) self.bar.set(h) self.square.set_hsv((h, s, v)) if self.alpha_channel: a = self.alpha.get() self.hexa.insert('end', ("%2.2x" % a).upper()) self.alphabar.set_color((r, g, b, a)) elif self.alpha_channel and re.match(r"^#[0-9A-F]{8}$", color): r, g, b, a = hexa_to_rgb(color) self.red.set(r) self.green.set(g) self.blue.set(b) self.alpha.set(a) self.alphabar.set_color((r, g, b, a)) h, s, v = rgb_to_hsv(r, g, b) self.hue.set(h) self.saturation.set(s) self.value.set(v) self.bar.set(h) self.square.set_hsv((h, s, v)) else: self._update_color_rgb() self._update_preview()
python
{ "resource": "" }
q21741
ColorPicker._update_alpha
train
def _update_alpha(self, event=None): """Update display after a change in the alpha spinbox.""" a = self.alpha.get() hexa = self.hexa.get() hexa = hexa[:7] + ("%2.2x" % a).upper() self.hexa.delete(0, 'end') self.hexa.insert(0, hexa) self.alphabar.set(a) self._update_preview()
python
{ "resource": "" }
q21742
ColorPicker._update_color_hsv
train
def _update_color_hsv(self, event=None): """Update display after a change in the HSV spinboxes.""" if event is None or event.widget.old_value != event.widget.get(): h = self.hue.get() s = self.saturation.get() v = self.value.get() sel_color = hsv_to_rgb(h, s, v) self.red.set(sel_color[0]) self.green.set(sel_color[1]) self.blue.set(sel_color[2]) if self.alpha_channel: sel_color += (self.alpha.get(),) self.alphabar.set_color(sel_color) hexa = rgb_to_hexa(*sel_color) self.hexa.delete(0, "end") self.hexa.insert(0, hexa) self.square.set_hsv((h, s, v)) self.bar.set(h) self._update_preview()
python
{ "resource": "" }
q21743
ColorPicker._update_color_rgb
train
def _update_color_rgb(self, event=None): """Update display after a change in the RGB spinboxes.""" if event is None or event.widget.old_value != event.widget.get(): r = self.red.get() g = self.green.get() b = self.blue.get() h, s, v = rgb_to_hsv(r, g, b) self.hue.set(h) self.saturation.set(s) self.value.set(v) args = (r, g, b) if self.alpha_channel: args += (self.alpha.get(),) self.alphabar.set_color(args) hexa = rgb_to_hexa(*args) self.hexa.delete(0, "end") self.hexa.insert(0, hexa) self.square.set_hsv((h, s, v)) self.bar.set(h) self._update_preview()
python
{ "resource": "" }
q21744
ColorPicker.ok
train
def ok(self): """Validate color selection and destroy dialog.""" rgb, hsv, hexa = self.square.get() if self.alpha_channel: hexa = self.hexa.get() rgb += (self.alpha.get(),) self.color = rgb, hsv, hexa self.destroy()
python
{ "resource": "" }
q21745
AlphaBar._draw_gradient
train
def _draw_gradient(self, alpha, color): """Draw the gradient and put the cursor on alpha.""" self.delete("gradient") self.delete("cursor") del self.gradient width = self.winfo_width() height = self.winfo_height() bg = create_checkered_image(width, height) r, g, b = color w = width - 1. gradient = Image.new("RGBA", (width, height)) for i in range(width): for j in range(height): gradient.putpixel((i, j), (r, g, b, round2(i / w * 255))) self.gradient = ImageTk.PhotoImage(Image.alpha_composite(bg, gradient), master=self) self.create_image(0, 0, anchor="nw", tags="gardient", image=self.gradient) self.lower("gradient") x = alpha / 255. * width h, s, v = rgb_to_hsv(r, g, b) if v < 50: fill = "gray80" else: fill = 'black' self.create_line(x, 0, x, height, width=2, tags='cursor', fill=fill)
python
{ "resource": "" }
q21746
AlphaBar.set
train
def set(self, alpha): """ Set cursor position on the color corresponding to the alpha value. :param alpha: new alpha value (between 0 and 255) :type alpha: int """ if alpha > 255: alpha = 255 elif alpha < 0: alpha = 0 x = alpha / 255. * self.winfo_width() self.coords('cursor', x, 0, x, self.winfo_height()) self._variable.set(alpha)
python
{ "resource": "" }
q21747
AlphaBar.set_color
train
def set_color(self, color): """ Change gradient color and change cursor position if an alpha value is supplied. :param color: new gradient color in RGB(A) format :type color: tuple[int] """ if len(color) == 3: alpha = self.get() else: alpha = color[3] self._draw_gradient(alpha, color[:3])
python
{ "resource": "" }
q21748
FontChooser._grid_widgets
train
def _grid_widgets(self): """Puts all the child widgets in the correct position.""" self._font_family_header.grid(row=0, column=1, sticky="nswe", padx=5, pady=5) self._font_label.grid(row=1, column=1, sticky="nswe", padx=5, pady=(0, 5)) self._font_family_list.grid(row=2, rowspan=3, column=1, sticky="nswe", padx=5, pady=(0, 5)) self._font_properties_header.grid(row=0, column=2, sticky="nswe", padx=5, pady=5) self._font_properties_frame.grid(row=1, rowspan=2, column=2, sticky="we", padx=5, pady=5) self._font_size_header.grid(row=3, column=2, sticky="we", padx=5, pady=5) self._size_dropdown.grid(row=4, column=2, sticky="we", padx=5, pady=5) self._example_label.grid(row=5, column=1, columnspan=2, sticky="nswe", padx=5, pady=5) self._ok_button.grid(row=6, column=2, sticky="nswe", padx=5, pady=5) self._cancel_button.grid(row=6, column=1, sticky="nswe", padx=5, pady=5)
python
{ "resource": "" }
q21749
FontChooser._on_change
train
def _on_change(self): """Callback if any of the values are changed.""" font = self.__generate_font_tuple() self._example_label.configure(font=font)
python
{ "resource": "" }
q21750
GradientBar._draw_gradient
train
def _draw_gradient(self, hue): """Draw the gradient and put the cursor on hue.""" self.delete("gradient") self.delete("cursor") del self.gradient width = self.winfo_width() height = self.winfo_height() self.gradient = tk.PhotoImage(master=self, width=width, height=height) line = [] for i in range(width): line.append(rgb_to_hexa(*hue2col(float(i) / width * 360))) line = "{" + " ".join(line) + "}" self.gradient.put(" ".join([line for j in range(height)])) self.create_image(0, 0, anchor="nw", tags="gardient", image=self.gradient) self.lower("gradient") x = hue / 360. * width self.create_line(x, 0, x, height, width=2, tags='cursor')
python
{ "resource": "" }
q21751
GradientBar._on_click
train
def _on_click(self, event): """Move selection cursor on click.""" x = event.x self.coords('cursor', x, 0, x, self.winfo_height()) self._variable.set(round2((360. * x) / self.winfo_width()))
python
{ "resource": "" }
q21752
GradientBar._on_move
train
def _on_move(self, event): """Make selection cursor follow the cursor.""" w = self.winfo_width() x = min(max(event.x, 0), w) self.coords('cursor', x, 0, x, self.winfo_height()) self._variable.set(round2((360. * x) / w))
python
{ "resource": "" }
q21753
FontSelectFrame._grid_widgets
train
def _grid_widgets(self): """ Puts all the widgets in the correct place. """ self._family_dropdown.grid(row=0, column=0, sticky="nswe") self._size_dropdown.grid(row=0, column=1, sticky="nswe") self._properties_frame.grid(row=0, column=2, sticky="nswe")
python
{ "resource": "" }
q21754
FontSelectFrame._on_change
train
def _on_change(self): """Call callback if any property is changed.""" if callable(self.__callback): self.__callback((self._family, self._size, self._bold, self._italic, self._underline, self._overstrike))
python
{ "resource": "" }
q21755
LinkLabel._on_enter
train
def _on_enter(self, *args): """Set the text color to the hover color.""" self.config(foreground=self._hover_color, cursor=self._cursor)
python
{ "resource": "" }
q21756
LinkLabel._on_leave
train
def _on_leave(self, *args): """Set the text color to either the normal color when not clicked or the clicked color when clicked.""" if self.__clicked: self.config(foreground=self._clicked_color) else: self.config(foreground=self._normal_color) self.config(cursor="")
python
{ "resource": "" }
q21757
LinkLabel.open_link
train
def open_link(self, *args): """Open the link in the web browser.""" if "disabled" not in self.state(): webbrowser.open(self._link) self.__clicked = True self._on_leave()
python
{ "resource": "" }
q21758
LinkLabel.keys
train
def keys(self): """Return a list of all resource names of this widget.""" keys = ttk.Label.keys(self) keys.extend(["link", "normal_color", "hover_color", "clicked_color"]) return keys
python
{ "resource": "" }
q21759
Table._move_dragged_row
train
def _move_dragged_row(self, item): """Insert dragged row at item's position.""" self.move(self._dragged_row, '', self.index(item)) self.see(self._dragged_row) bbox = self.bbox(self._dragged_row) self._dragged_row_y = bbox[1] self._dragged_row_height = bbox[3] self._visual_drag.see(self._dragged_row)
python
{ "resource": "" }
q21760
Table._start_drag_col
train
def _start_drag_col(self, event): """Start dragging a column""" # identify dragged column col = self.identify_column(event.x) self._dragged_col = ttk.Treeview.column(self, col, 'id') # get column width self._dragged_col_width = w = ttk.Treeview.column(self, col, 'width') # get x coordinate of the left side of the column x = event.x while self.identify_region(x, event.y) == 'heading': # decrease x until reaching the separator x -= 1 x_sep = x w_sep = 0 # determine separator width while self.identify_region(x_sep, event.y) == 'separator': w_sep += 1 x_sep -= 1 if event.x - x <= self._im_drag.width(): # start dragging if mouse click was on dragging icon x = x - w_sep // 2 - 1 self._dragged_col_x = x # get neighboring column widths displayed_cols = self._displayed_cols self._dragged_col_index = i1 = displayed_cols.index(self._dragged_col) if i1 > 0: left = ttk.Treeview.column(self, displayed_cols[i1 - 1], 'width') else: left = None if i1 < len(displayed_cols) - 1: right = ttk.Treeview.column(self, displayed_cols[i1 + 1], 'width') else: right = None self._dragged_col_neighbor_widths = (left, right) self._dx = x - event.x # distance between cursor and column left border # configure dragged column preview self._visual_drag.column(self._dragged_col, width=w) self._visual_drag.configure(displaycolumns=[self._dragged_col]) if 'headings' in tuple(str(p) for p in self['show']): self._visual_drag.configure(show='headings') else: self._visual_drag.configure(show='') self._visual_drag.place(in_=self, x=x, y=0, anchor='nw', width=w + 2, relheight=1) self._visual_drag.state(('active',)) self._visual_drag.update_idletasks() self._visual_drag.yview_moveto(self.yview()[0]) else: self._dragged_col = None
python
{ "resource": "" }
q21761
Table._start_drag_row
train
def _start_drag_row(self, event): """Start dragging a row""" self._dragged_row = self.identify_row(event.y) # identify dragged row bbox = self.bbox(self._dragged_row) self._dy = bbox[1] - event.y # distance between cursor and row upper border self._dragged_row_y = bbox[1] # y coordinate of dragged row upper border self._dragged_row_height = bbox[3] # configure dragged row preview self._visual_drag.configure(displaycolumns=self['displaycolumns'], height=1) for col in self['columns']: self._visual_drag.column(col, width=self.column(col, 'width')) if 'tree' in tuple(str(p) for p in self['show']): self._visual_drag.configure(show='tree') else: self._visual_drag.configure(show='') self._visual_drag.place(in_=self, x=0, y=bbox[1], height=self._visual_drag.winfo_reqheight() + 2, anchor='nw', relwidth=1) self._visual_drag.selection_add(self._dragged_row) self.selection_remove(self._dragged_row) self._visual_drag.update_idletasks() self._visual_drag.see(self._dragged_row) self._visual_drag.update_idletasks() self._visual_drag.xview_moveto(self.xview()[0])
python
{ "resource": "" }
q21762
Table._on_release
train
def _on_release(self, event): """Stop dragging.""" if self._drag_cols or self._drag_rows: self._visual_drag.place_forget() self._dragged_col = None self._dragged_row = None
python
{ "resource": "" }
q21763
Table._on_motion
train
def _on_motion(self, event): """Drag around label if visible.""" if not self._visual_drag.winfo_ismapped(): return if self._drag_cols and self._dragged_col is not None: self._drag_col(event) elif self._drag_rows and self._dragged_row is not None: self._drag_row(event)
python
{ "resource": "" }
q21764
Table._drag_col
train
def _drag_col(self, event): """Continue dragging a column""" x = self._dx + event.x # get dragged column new left x coordinate self._visual_drag.place_configure(x=x) # update column preview position # if one border of the dragged column is beyon the middle of the # neighboring column, swap them if (self._dragged_col_neighbor_widths[0] is not None and x < self._dragged_col_x - self._dragged_col_neighbor_widths[0] / 2): self._swap_columns('left') elif (self._dragged_col_neighbor_widths[1] is not None and x > self._dragged_col_x + self._dragged_col_neighbor_widths[1] / 2): self._swap_columns('right') # horizontal scrolling if the cursor reaches the side of the table if x < 0 and self.xview()[0] > 0: # scroll left and update dragged column x coordinate self.xview_scroll(-10, 'units') self._dragged_col_x += 10 elif x + self._dragged_col_width / 2 > self.winfo_width() and self.xview()[1] < 1: # scroll right and update dragged column x coordinate self.xview_scroll(10, 'units') self._dragged_col_x -= 10
python
{ "resource": "" }
q21765
Table._drag_row
train
def _drag_row(self, event): """Continue dragging a row""" y = self._dy + event.y # get dragged row new upper y coordinate self._visual_drag.place_configure(y=y) # update row preview position if y > self._dragged_row_y: # moving downward item = self.identify_row(y + self._dragged_row_height) if item != '': bbox = self.bbox(item) if not bbox: # the item is not visible so make it visible self.see(item) self.update_idletasks() bbox = self.bbox(item) if y > self._dragged_row_y + bbox[3] / 2: # the row is beyond half of item, so insert it below self._move_dragged_row(item) elif item != self.next(self._dragged_row): # item is not the lower neighbor of the dragged row so insert the row above self._move_dragged_row(self.prev(item)) elif y < self._dragged_row_y: # moving upward item = self.identify_row(y) if item != '': bbox = self.bbox(item) if not bbox: # the item is not visible so make it visible self.see(item) self.update_idletasks() bbox = self.bbox(item) if y < self._dragged_row_y - bbox[3] / 2: # the row is beyond half of item, so insert it above self._move_dragged_row(item) elif item != self.prev(self._dragged_row): # item is not the upper neighbor of the dragged row so insert the row below self._move_dragged_row(self.next(item)) self.selection_remove(self._dragged_row)
python
{ "resource": "" }
q21766
Table._sort_column
train
def _sort_column(self, column, reverse): """Sort a column by its values""" if tk.DISABLED in self.state(): return # get list of (value, item) tuple where value is the value in column for the item l = [(self.set(child, column), child) for child in self.get_children('')] # sort list using the column type l.sort(reverse=reverse, key=lambda x: self._column_types[column](x[0])) # reorder items for index, (val, child) in enumerate(l): self.move(child, "", index) # reverse sorting direction for the next time self.heading(column, command=lambda: self._sort_column(column, not reverse))
python
{ "resource": "" }
q21767
Table.column
train
def column(self, column, option=None, **kw): """ Query or modify the options for the specified column. If `kw` is not given, returns a dict of the column option values. If `option` is specified then the value for that option is returned. Otherwise, sets the options to the corresponding values. :param id: the column's identifier (read-only option) :param anchor: "n", "ne", "e", "se", "s", "sw", "w", "nw", or "center": alignment of the text in this column with respect to the cell :param minwidth: minimum width of the column in pixels :type minwidth: int :param stretch: whether the column's width should be adjusted when the widget is resized :type stretch: bool :param width: width of the column in pixels :type width: int :param type: column's content type (for sorting), default type is `str` :type type: type """ config = False if option == 'type': return self._column_types[column] elif 'type' in kw: config = True self._column_types[column] = kw.pop('type') if kw: self._visual_drag.column(ttk.Treeview.column(self, column, 'id'), option, **kw) if kw or option: return ttk.Treeview.column(self, column, option, **kw) elif not config: res = ttk.Treeview.column(self, column, option, **kw) res['type'] = self._column_types[column] return res
python
{ "resource": "" }
q21768
Table._config_options
train
def _config_options(self): """Apply options set in attributes to Treeview""" self._config_sortable(self._sortable) self._config_drag_cols(self._drag_cols)
python
{ "resource": "" }
q21769
Table._config_sortable
train
def _config_sortable(self, sortable): """Configure a new sortable state""" for col in self["columns"]: command = (lambda c=col: self._sort_column(c, True)) if sortable else "" self.heading(col, command=command) self._sortable = sortable
python
{ "resource": "" }
q21770
Table._config_drag_cols
train
def _config_drag_cols(self, drag_cols): """Configure a new drag_cols state""" self._drag_cols = drag_cols # remove/display drag icon if self._drag_cols: self._im_drag.paste(self._im_draggable) else: self._im_drag.paste(self._im_not_draggable) self.focus_set() self.update_idletasks()
python
{ "resource": "" }
q21771
Table.delete
train
def delete(self, *items): """ Delete all specified items and all their descendants. The root item may not be deleted. :param items: list of item identifiers :type items: sequence[str] """ self._visual_drag.delete(*items) ttk.Treeview.delete(self, *items)
python
{ "resource": "" }
q21772
Table.detach
train
def detach(self, *items): """ Unlinks all of the specified items from the tree. The items and all of their descendants are still present, and may be reinserted at another point in the tree, but will not be displayed. The root item may not be detached. :param items: list of item identifiers :type items: sequence[str] """ self._visual_drag.detach(*items) ttk.Treeview.detach(self, *items)
python
{ "resource": "" }
q21773
Table.heading
train
def heading(self, column, option=None, **kw): """ Query or modify the heading options for the specified column. If `kw` is not given, returns a dict of the heading option values. If `option` is specified then the value for that option is returned. Otherwise, sets the options to the corresponding values. :param text: text to display in the column heading :type text: str :param image: image to display to the right of the column heading :type image: PhotoImage :param anchor: "n", "ne", "e", "se", "s", "sw", "w", "nw", or "center": alignement of the heading text :type anchor: str :param command: callback to be invoked when the heading label is pressed. :type command: function """ if kw: # Set the default image of the heading to the drag icon kw.setdefault("image", self._im_drag) self._visual_drag.heading(ttk.Treeview.column(self, column, 'id'), option, **kw) return ttk.Treeview.heading(self, column, option, **kw)
python
{ "resource": "" }
q21774
Table.item
train
def item(self, item, option=None, **kw): """ Query or modify the options for the specified item. If no options are given, a dict with options/values for the item is returned. If option is specified then the value for that option is returned. Otherwise, sets the options to the corresponding values as given by `kw`. :param text: item's label :type text: str :param image: image to be displayed on the left of the item's label :type image: PhotoImage :param values: values to put in the columns :type values: sequence :param open: whether the item's children should be displayed :type open: bool :param tags: list of tags associated with this item :type tags: sequence[str] """ if kw: self._visual_drag.item(item, option, **kw) return ttk.Treeview.item(self, item, option, **kw)
python
{ "resource": "" }
q21775
Table.set
train
def set(self, item, column=None, value=None): """ Query or set the value of given item. With one argument, return a dictionary of column/value pairs for the specified item. With two arguments, return the current value of the specified column. With three arguments, set the value of given column in given item to the specified value. :param item: item's identifier :type item: str :param column: column's identifier :type column: str, int or None :param value: new value """ if value is not None: self._visual_drag.set(item, ttk.Treeview.column(self, column, 'id'), value) return ttk.Treeview.set(self, item, column, value)
python
{ "resource": "" }
q21776
ScaleEntry._on_scale
train
def _on_scale(self, event): """ Callback for the Scale widget, inserts an int value into the Entry. :param event: Tkinter event """ self._entry.delete(0, tk.END) self._entry.insert(0, str(self._variable.get()))
python
{ "resource": "" }
q21777
ScaleEntry.config_scale
train
def config_scale(self, cnf={}, **kwargs): """Configure resources of the Scale widget.""" self._scale.config(cnf, **kwargs) # Update self._variable limits in case the ones of the scale have changed self._variable.configure(high=self._scale['to'], low=self._scale['from']) if 'orient' in cnf or 'orient' in kwargs: self._grid_widgets()
python
{ "resource": "" }
q21778
Balloon._grid_widgets
train
def _grid_widgets(self): """Place the widgets in the Toplevel.""" self._canvas.grid(sticky="nswe") self.header_label.grid(row=1, column=1, sticky="nswe", pady=5, padx=5) self.text_label.grid(row=3, column=1, sticky="nswe", pady=6, padx=5)
python
{ "resource": "" }
q21779
Balloon.show
train
def show(self): """ Create the Toplevel widget and its child widgets to show in the spot of the cursor. This is the callback for the delayed :obj:`<Enter>` event (see :meth:`~Balloon._on_enter`). """ self._toplevel = tk.Toplevel(self.master) self._canvas = tk.Canvas(self._toplevel, background=self.__background) self.header_label = ttk.Label(self._canvas, text=self.__headertext, background=self.__background, image=self._photo_image, compound=tk.LEFT) self.text_label = ttk.Label(self._canvas, text=self.__text, wraplength=self.__width, background=self.__background) self._toplevel.attributes("-topmost", True) self._toplevel.overrideredirect(True) self._grid_widgets() x, y = self.master.winfo_pointerxy() self._canvas.update() # Update the Geometry of the Toplevel to update its position and size self._toplevel.geometry("{0}x{1}+{2}+{3}".format(self._canvas.winfo_width(), self._canvas.winfo_height(), x + 2, y + 2))
python
{ "resource": "" }
q21780
FontPropertiesFrame._on_click
train
def _on_click(self): """Handles clicks and calls callback.""" if callable(self.__callback): self.__callback((self.bold, self.italic, self.underline, self.overstrike))
python
{ "resource": "" }
q21781
rgb_to_hsv
train
def rgb_to_hsv(r, g, b): """Convert RGB color to HSV.""" h, s, v = colorsys.rgb_to_hsv(r / 255., g / 255., b / 255.) return round2(h * 360), round2(s * 100), round2(v * 100)
python
{ "resource": "" }
q21782
hexa_to_rgb
train
def hexa_to_rgb(color): """Convert hexadecimal color to RGB.""" r = int(color[1:3], 16) g = int(color[3:5], 16) b = int(color[5:7], 16) if len(color) == 7: return r, g, b elif len(color) == 9: return r, g, b, int(color[7:9], 16) else: raise ValueError("Invalid hexadecimal notation.")
python
{ "resource": "" }
q21783
col2hue
train
def col2hue(r, g, b): """Return hue value corresponding to given RGB color.""" return round2(180 / pi * atan2(sqrt(3) * (g - b), 2 * r - g - b) + 360) % 360
python
{ "resource": "" }
q21784
create_checkered_image
train
def create_checkered_image(width, height, c1=(154, 154, 154, 255), c2=(100, 100, 100, 255), s=6): """ Return a checkered image of size width x height. Arguments: * width: image width * height: image height * c1: first color (RGBA) * c2: second color (RGBA) * s: size of the squares """ im = Image.new("RGBA", (width, height), c1) draw = ImageDraw.Draw(im, "RGBA") for i in range(s, width, 2 * s): for j in range(0, height, 2 * s): draw.rectangle(((i, j), ((i + s - 1, j + s - 1))), fill=c2) for i in range(0, width, 2 * s): for j in range(s, height, 2 * s): draw.rectangle(((i, j), ((i + s - 1, j + s - 1))), fill=c2) return im
python
{ "resource": "" }
q21785
TimeLine.grid_widgets
train
def grid_widgets(self): """ Configure all widgets using the grid geometry manager Automatically called by the :meth:`__init__` method. Does not have to be called by the user except in extraordinary cases. """ # Categories for index, label in enumerate(self._category_labels.values()): label.grid(column=0, row=index, padx=5, sticky="nw", pady=(1, 0) if index == 0 else 0) # Canvas widgets self._canvas_scroll.grid(column=1, row=0, padx=(0, 5), pady=5, sticky="nswe") self._canvas_ticks.grid(column=1, row=1, padx=(0, 5), pady=(0, 5), sticky="nswe") self._scrollbar_timeline.grid(column=1, row=2, padx=(0, 5), pady=(0, 5), sticky="we") # Zoom widgets self._button_zoom_in.grid(row=0, column=0, pady=5, sticky="nswe") self._button_zoom_out.grid(row=1, column=0, pady=(0, 5), sticky="nswe") self._button_zoom_reset.grid(row=2, column=0, pady=(0, 5), sticky="nswe") # Frames self._canvas_categories.grid(column=0, row=0, padx=5, pady=5, sticky="nswe") self._scrollbar_vertical.grid(column=2, row=0, pady=5, padx=(0, 5), sticky="ns") self._frame_zoom.grid(column=3, row=0, rowspan=2, padx=(0, 5), pady=5, sticky="nswe")
python
{ "resource": "" }
q21786
TimeLine.draw_timeline
train
def draw_timeline(self): """Draw the contents of the whole TimeLine Canvas""" # Configure the canvas self.clear_timeline() self.create_scroll_region() self._timeline.config(width=self.pixel_width) self._canvas_scroll.config(width=self._width, height=self._height) # Generate the Y-coordinates for each of the rows and create the lines indicating the rows self.draw_separators() # Create the markers on the timeline self.draw_markers() # Create the ticks in the _canvas_ticks self.draw_ticks() self.draw_time_marker()
python
{ "resource": "" }
q21787
TimeLine.draw_time_marker
train
def draw_time_marker(self): """Draw the time marker on the TimeLine Canvas""" self._time_marker_image = self._canvas_ticks.create_image((2, 16), image=self._time_marker) self._time_marker_line = self._timeline.create_line( (2, 0, 2, self._timeline.winfo_height()), fill="#016dc9", width=2) self._timeline.lift(self._time_marker_line) self._timeline.tag_lower("marker")
python
{ "resource": "" }
q21788
TimeLine.draw_categories
train
def draw_categories(self): """Draw the category labels on the Canvas""" for label in self._category_labels.values(): label.destroy() self._category_labels.clear() canvas_width = 0 for category in (sorted(self._categories.keys() if isinstance(self._categories, dict) else self._categories) if not isinstance(self._categories, OrderedDict) else self._categories): kwargs = self._categories[category] if isinstance(self._categories, dict) else {"text": category} kwargs["background"] = kwargs.get("background", self._background) kwargs["justify"] = kwargs.get("justify", tk.LEFT) label = ttk.Label(self._frame_categories, **kwargs) width = label.winfo_reqwidth() canvas_width = width if width > canvas_width else canvas_width self._category_labels[category] = label self._canvas_categories.create_window(0, 0, window=self._frame_categories, anchor=tk.NW) self._canvas_categories.config(width=canvas_width + 5, height=self._height)
python
{ "resource": "" }
q21789
TimeLine.create_scroll_region
train
def create_scroll_region(self): """Setup the scroll region on the Canvas""" canvas_width = 0 canvas_height = 0 for label in self._category_labels.values(): width = label.winfo_reqwidth() canvas_height += label.winfo_reqheight() canvas_width = width if width > canvas_width else canvas_width self._canvas_categories.config(scrollregion="0 0 {0} {1}".format(canvas_width, canvas_height))
python
{ "resource": "" }
q21790
TimeLine.clear_timeline
train
def clear_timeline(self): """ Clear the contents of the TimeLine Canvas Does not modify the actual markers dictionary and thus after redrawing all markers are visible again. """ self._timeline.delete(tk.ALL) self._canvas_ticks.delete(tk.ALL)
python
{ "resource": "" }
q21791
TimeLine.draw_ticks
train
def draw_ticks(self): """Draw the time tick markers on the TimeLine Canvas""" self._canvas_ticks.create_line((0, 10, self.pixel_width, 10), fill="black") self._ticks = list(TimeLine.range(self._start, self._finish, self._tick_resolution / self._zoom_factor)) for tick in self._ticks: string = TimeLine.get_time_string(tick, self._unit) x = self.get_time_position(tick) x_tick = x + 1 if x == 0 else (x - 1 if x == self.pixel_width else x) x_text = x + 15 if x - 15 <= 0 else (x - 15 if x + 15 >= self.pixel_width else x) self._canvas_ticks.create_text((x_text, 20), text=string, fill="black", font=("default", 10)) self._canvas_ticks.create_line((x_tick, 5, x_tick, 15), fill="black") self._canvas_ticks.config(scrollregion="0 0 {0} {1}".format(self.pixel_width, 30))
python
{ "resource": "" }
q21792
TimeLine.draw_separators
train
def draw_separators(self): """Draw the lines separating the categories on the Canvas""" total = 1 self._timeline.create_line((0, 1, self.pixel_width, 1)) for index, (category, label) in enumerate(self._category_labels.items()): height = label.winfo_reqheight() self._rows[category] = (total, total + height) total += height self._timeline.create_line((0, total, self.pixel_width, total)) pixel_height = total self._timeline.config(height=pixel_height)
python
{ "resource": "" }
q21793
TimeLine.draw_markers
train
def draw_markers(self): """Draw all created markers on the TimeLine Canvas""" self._canvas_markers.clear() for marker in self._markers.values(): self.create_marker(marker["category"], marker["start"], marker["finish"], marker)
python
{ "resource": "" }
q21794
TimeLine.__configure_timeline
train
def __configure_timeline(self, *args): """Function from ScrolledFrame, adapted for the _timeline""" # Resize the canvas scrollregion to fit the entire frame (size_x, size_y) = (self._timeline.winfo_reqwidth(), self._timeline.winfo_reqheight()) self._canvas_scroll.config(scrollregion="0 0 {0} {1}".format(size_x, size_y - 5))
python
{ "resource": "" }
q21795
TimeLine.create_marker
train
def create_marker(self, category, start, finish, marker=None, **kwargs): """ Create a new marker in the TimeLine with the specified options :param category: Category identifier, key as given in categories dictionary upon initialization :type category: Any :param start: Start time for the marker :type start: float :param finish: Finish time for the marker :type finish: float :param marker: marker dictionary (replaces kwargs) :type marker: dict[str, Any] **Marker Options** Options can be given either in the marker dictionary argument, or as keyword arguments. Given keyword arguments take precedence over tag options, which take precedence over default options. :param text: Text to show in the marker. Text may not be displayed fully if the zoom level does not allow the marker to be wide enough. Updates when resizing the marker. :type text: str :param background: Background color for the marker :type background: str :param foreground: Foreground (text) color for the marker :type foreground: str :param outline: Outline color for the marker :type outline: str :param border: The width of the border (for which outline is the color) :type border: int :param font: Font tuple to set for the marker :type font: tuple :param iid: Unique marker identifier to use. A marker is generated if not given, and its value is returned. Use this option if keeping track of markers in a different manner than with auto-generated iid's is necessary. :type iid: str :param tags: Set of tags to apply to this marker, allowing callbacks to be set and other options to be configured. The option precedence is from the first to the last item, so the options of the last item overwrite those of the one before, and those of the one before that, and so on. :type tags: tuple[str] :param move: Whether the marker is allowed to be moved :type move: bool Additionally, all the options with the ``marker_`` prefix from :meth:`__init__`, but without the prefix, are supported. Active state options are also available, with the ``active_`` prefix for ``background``, ``foreground``, ``outline``, ``border``. These options are also available for the hover state with the ``hover_`` prefix. :return: identifier of the created marker :rtype: str :raise ValueError: One of the specified arguments is invalid """ kwargs = kwargs if marker is None else marker if category not in self._categories: raise ValueError("category argument not a valid category: {}".format(category)) if start < self._start or finish > self._finish: raise ValueError("time out of bounds") self.check_marker_kwargs(kwargs) # Update the options based on the tags. The last tag always takes precedence over the ones before it, and the # marker specific options take precedence over tag options tags = kwargs.get("tags", ()) options = kwargs.copy() # Check the tags for tag in tags: # Update the options kwargs.update(self._tags[tag]) # Update with the specific marker options kwargs.update(options) # Process the other options iid = kwargs.pop("iid", str(self._iid)) background = kwargs.get("background", "default") foreground = kwargs.get("foreground", "default") outline = kwargs.get("outline", "default") font = kwargs.get("font", "default") border = kwargs.get("border", "default") move = kwargs.get("move", "default") change_category = kwargs.get("change_category", "default") allow_overlap = kwargs.get("allow_overlap", "default") snap_to_ticks = kwargs.get("snap_to_ticks", "default") # Calculate pixel positions x1 = start / self._resolution * self._zoom_factor x2 = finish / self._resolution * self._zoom_factor y1, y2 = self._rows[category] # Create the rectangle rectangle_id = self._timeline.create_rectangle( (x1, y1, x2, y2), fill=background if background != "default" else self._marker_background, outline=outline if outline != "default" else self._marker_outline, tags=("marker",), width=border if border != "default" else self._marker_border ) # Create the text text = kwargs.get("text", None) text_id = self._draw_text((x1, y1, x2, y2), text, foreground, font) if text is not None else None # Save the marker locals_ = locals() self._markers[iid] = { key: ( locals_[key.replace("hover_", "").replace("active_", "")] if key in ( prefix + color for prefix in ["", "hover_", "active_"] for color in ["background", "foreground", "outline", "border"] ) and key not in kwargs else (locals_[key] if key in locals_ else kwargs[key]) ) for key in self.marker_options } # Save the marker's Canvas IDs self._canvas_markers[rectangle_id] = iid self._canvas_markers[text_id] = iid self._timeline.tag_lower("marker") # Attempt to prevent duplicate iids while str(self._iid) in self.markers: self._iid += 1 return iid
python
{ "resource": "" }
q21796
TimeLine._draw_text
train
def _draw_text(self, coords, text, foreground, font): """Draw the text and shorten it if required""" if text is None: return None x1_r, _, x2_r, _ = coords while True: text_id = self._timeline.create_text( (0, 0), text=text, fill=foreground if foreground != "default" else self._marker_foreground, font=font if font != "default" else self._marker_font, tags=("marker",) ) x1_t, _, x2_t, _ = self._timeline.bbox(text_id) if (x2_t - x1_t) < (x2_r - x1_r): break self._timeline.delete(text_id) text = text[:-4] + "..." x, y = TimeLine.calculate_text_coords(coords) self._timeline.coords(text_id, (x, y)) return text_id
python
{ "resource": "" }
q21797
TimeLine.update_marker
train
def update_marker(self, iid, **kwargs): """ Change the options for a certain marker and redraw the marker :param iid: identifier of the marker to change :type iid: str :param kwargs: Dictionary of options to update :type kwargs: dict :raises: ValueError """ if iid not in self._markers: raise ValueError("Unknown iid passed as argument: {}".format(iid)) self.check_kwargs(kwargs) marker = self._markers[iid] marker.update(kwargs) self.delete_marker(iid) return self.create_marker(marker["category"], marker["start"], marker["finish"], marker)
python
{ "resource": "" }
q21798
TimeLine.delete_marker
train
def delete_marker(self, iid): """ Delete a marker from the TimeLine :param iid: marker identifier :type iid: str """ if iid == tk.ALL: for iid in self.markers.keys(): self.delete_marker(iid) return options = self._markers[iid] rectangle_id, text_id = options["rectangle_id"], options["text_id"] del self._canvas_markers[rectangle_id] del self._canvas_markers[text_id] del self._markers[iid] self._timeline.delete(rectangle_id, text_id)
python
{ "resource": "" }
q21799
TimeLine.zoom_in
train
def zoom_in(self): """Increase zoom factor and redraw TimeLine""" index = self._zoom_factors.index(self._zoom_factor) if index + 1 == len(self._zoom_factors): # Already zoomed in all the way return self._zoom_factor = self._zoom_factors[index + 1] if self._zoom_factors.index(self.zoom_factor) + 1 == len(self._zoom_factors): self._button_zoom_in.config(state=tk.DISABLED) self._button_zoom_out.config(state=tk.NORMAL) self.draw_timeline()
python
{ "resource": "" }