text
stringlengths
81
112k
Loads analytics report from json file specified by path. Args: path (str): path to json file with analytics report. def load(path): """Loads analytics report from json file specified by path. Args: path (str): path to json file with analytics report. """ ...
Collect analytics report. def collect(self): """Collect analytics report.""" from dvc.scm import SCM from dvc.utils import is_binary from dvc.repo import Repo from dvc.exceptions import NotDvcRepoError self.info[self.PARAM_DVC_VERSION] = __version__ self.info[se...
Collect analytics info from a CLI command. def collect_cmd(self, args, ret): """Collect analytics info from a CLI command.""" from dvc.command.daemon import CmdDaemonAnalytics assert isinstance(ret, int) or ret is None if ret is not None: self.info[self.PARAM_CMD_RETURN_CO...
Save analytics report to a temporary file. Returns: str: path to the temporary file that contains the analytics report. def dump(self): """Save analytics report to a temporary file. Returns: str: path to the temporary file that contains the analytics report. ""...
Collect and send analytics for CLI command. Args: args (list): parsed args for the CLI command. ret (int): return value of the CLI command. def send_cmd(cmd, args, ret): """Collect and send analytics for CLI command. Args: args (list): parsed args for the C...
Collect and send analytics. def send(self): """Collect and send analytics.""" import requests if not self._is_enabled(): return self.collect() logger.debug("Sending analytics: {}".format(self.info)) try: requests.post(self.URL, json=self.info,...
Directory tree generator. See `os.walk` for the docs. Differences: - no support for symlinks - it could raise exceptions, there is no onerror argument def walk(self, top, topdown=True, ignore_file_handler=None): """Directory tree generator. See `os.walk` for the docs. Differen...
Push data items in a cloud-agnostic way. Args: targets (list): list of targets to push to the cloud. jobs (int): number of jobs that can be running simultaneously. remote (dvc.remote.base.RemoteBase): optional remote to push to. By default remote from core.re...
Check status of data items in a cloud-agnostic way. Args: targets (list): list of targets to check status for. jobs (int): number of jobs that can be running simultaneously. remote (dvc.remote.base.RemoteBase): optional remote to compare targets to. By defaul...
Generator that iterates over specified revisions. Args: branches (list): a list of branches to iterate over. all_branches (bool): iterate over all available branches. tags (list): a list of tags to iterate over. all_tags (bool): iterate over all available tags. Yields: ...
Check if file/directory has the expected md5. Args: path (str): path to the file/directory to check. md5 (str): expected md5. Returns: bool: True if path has the expected md5, False otherwise. def changed(self, path, md5): """Check if file/directory has the...
Loads state database. def load(self): """Loads state database.""" retries = 1 while True: assert self.database is None assert self.cursor is None assert self.inserts == 0 empty = not os.path.exists(self.state_file) self.database = sqli...
Saves state database. def dump(self): """Saves state database.""" assert self.database is not None cmd = "SELECT count from {} WHERE rowid={}" self._execute(cmd.format(self.STATE_INFO_TABLE, self.STATE_INFO_ROW)) ret = self._fetchall() assert len(ret) == 1 asser...
Save checksum for the specified path info. Args: path_info (dict): path_info to save checksum for. checksum (str): checksum to save. def save(self, path_info, checksum): """Save checksum for the specified path info. Args: path_info (dict): path_info to save...
Gets the checksum for the specified path info. Checksum will be retrieved from the state database if available. Args: path_info (dict): path info to get the checksum for. Returns: str or None: checksum for the specified path info or None if it doesn't exist ...
Adds the specified path to the list of links created by dvc. This list is later used on `dvc checkout` to cleanup old links. Args: path_info (dict): path info to add to the list of links. def save_link(self, path_info): """Adds the specified path to the list of links created by dvc...
Removes all saved links except the ones that are used. Args: used (list): list of used links that should not be removed. def remove_unused_links(self, used): """Removes all saved links except the ones that are used. Args: used (list): list of used links that should not...
Args: metrics (list): Where each element is either a `list` if an xpath was specified, otherwise a `str` def show_metrics(metrics, all_branches=False, all_tags=False): """ Args: metrics (list): Where each element is either a `list` if an xpath was specified, otherwise a ...
Acquire lock for dvc repo. def lock(self): """Acquire lock for dvc repo.""" try: self._do_lock() return except LockError: time.sleep(self.TIMEOUT) self._do_lock()
Reads late emails from IMAP server and displays them in the Window :param window: window to display emails in :return: def read_mail(window): """ Reads late emails from IMAP server and displays them in the Window :param window: window to display emails in :return: """ mail = imaplib.IMA...
run shell command @param cmd: command to execute @param timeout: timeout for command execution @return: (return code from command, command output) def runCommand(cmd, timeout=None): """ run shell command @param cmd: command to execute @param timeout: timeout for command execution @return: (return code fr...
Kill a process tree (including grandchildren) with signal "sig" and return a (gone, still_alive) tuple. "on_terminate", if specified, is a callabck function which is called as soon as a child terminates. def kill_proc_tree(pid, sig=signal.SIGTERM, include_parent=True, timeout=None, on_te...
Popup - Display a popup box with as many parms as you wish to include :param args: :param button_color: :param background_color: :param text_color: :param button_type: :param auto_close: :param auto_close_duration: :param non_blocking: :param icon: :param line_width: :param f...
Show a Popup but without any buttons :param args: :param button_color: :param background_color: :param text_color: :param auto_close: :param auto_close_duration: :param non_blocking: :param icon: :param line_width: :param font: :param no_titlebar: :param grab_anywhere: ...
Popup with colored button and 'Error' as button text :param args: :param button_color: :param background_color: :param text_color: :param auto_close: :param auto_close_duration: :param non_blocking: :param icon: :param line_width: :param font: :param no_titlebar: :param g...
Set the scroll region on the canvas def set_scrollregion(self, event=None): """ Set the scroll region on the canvas""" self.canvas.configure(scrollregion=self.canvas.bbox('all'))
Configure canvas for a new selection. def _show_selection(self, text, bbox): """Configure canvas for a new selection.""" x, y, width, height = bbox textw = self._font.measure(text) canvas = self._canvas canvas.configure(width=width, height=height) canvas.coords(canvas....
Clicked somewhere in the calendar. def _pressed(self, evt): """Clicked somewhere in the calendar.""" x, y, widget = evt.x, evt.y, evt.widget item = widget.identify_row(y) column = widget.identify_column(x) if not column or not item in self._items: # clicked in the w...
Updated calendar to show the previous month. def _prev_month(self): """Updated calendar to show the previous month.""" self._canvas.place_forget() self._date = self._date - self.timedelta(days=1) self._date = self.datetime(self._date.year, self._date.month, 1) self._build_calen...
Update calendar to show the next month. def _next_month(self): """Update calendar to show the next month.""" self._canvas.place_forget() year, month = self._date.year, self._date.month self._date = self._date + self.timedelta( days=calendar.monthrange(year, month)[1] + 1) ...
Return a datetime representing the current selected date. def selection(self): """Return a datetime representing the current selected date.""" if not self._selection: return None year, month = self._date.year, self._date.month return self.datetime(year, month, int(self._sel...
Parms are a variable number of Elements def AddRow(self, *args): ''' Parms are a variable number of Elements ''' NumRows = len(self.Rows) # number of existing rows is our row number CurrentRowNumber = NumRows # this row's number CurrentRow = [] # start with a blank row and build up ...
Change the window's transparency :param alpha: From 0 to 1 with 0 being completely transparent :return: def SetAlpha(self, alpha): ''' Change the window's transparency :param alpha: From 0 to 1 with 0 being completely transparent :return: ''' self._AlphaC...
Sets Card's color and escape code. def setColor(self, color): '''Sets Card's color and escape code.''' if color == 'blue': self.color = 'blue' self.colorCode = self.colors['blue'] self.colorCodeDark = self.colors['dblue'] elif color == 'red': self...
Generate image data using PIL def get_img_data(f, maxsize = (1200, 850), first = False): """Generate image data using PIL """ img = Image.open(f) img.thumbnail(maxsize) if first: # tkinter is inactive the first time bio = io.BytesIO() img.save(bio, format = "PNG"...
Returns either the delay (in ms) or None on timeout. def do_one(myStats, destIP, hostname, timeout, mySeqNumber, packet_size, quiet=False): """ Returns either the delay (in ms) or None on timeout. """ delay = None try: # One could use UDP here, but it's obscure mySocket = socket.socket(so...
Same as verbose_ping, but the results are returned as tuple def quiet_ping(hostname, timeout=WAIT_TIMEOUT, count=NUM_PACKETS, packet_size=PACKET_SIZE, path_finder=False): """ Same as verbose_ping, but the results are returned as tuple """ myStats = MyStats() # Reset the stats mySeqNu...
Return a PNG image for a document page number. def get_page(pno, zoom = False, max_size = None, first = False): """Return a PNG image for a document page number. """ dlist = dlist_tab[pno] # get display list of page number if not dlist: # create if not yet there dlist_tab[pno] = do...
Count the number of live neighbours around point (i, j). def live_neighbours(self, i, j): """ Count the number of live neighbours around point (i, j). """ s = 0 # The total number of live neighbours. # Loop over all the neighbours. for x in [i - 1, i, i + 1]: for y in [j - ...
Play Conway's Game of Life. def play(self): """ Play Conway's Game of Life. """ # Write the initial configuration to file. self.t = 1 # Current time level while self.t <= self.T: # Evolve! # print( "At time level %d" % t) # Loop over each cell of the grid an...
Returns a human readable string reprentation of bytes def human_size(bytes, units=[' bytes','KB','MB','GB','TB', 'PB', 'EB']): """ Returns a human readable string reprentation of bytes""" return str(bytes) + units[0] if bytes < 1024 else human_size(bytes>>10, units[1:])
Make and show a window (PySimpleGUI form) that takes user input and sends to the HowDoI web oracle Excellent example of 2 GUI concepts 1. Output Element that will show text in a scrolled window 2. Non-Window-Closing Buttons - These buttons will cause the form to return with the form's values, but do...
Kicks off a subprocess to send the 'Query' to HowDoI Prints the result, which in this program will route to a gooeyGUI window :param Query: text english question to ask the HowDoI web engine :return: nothing def QueryHowDoI(Query, num_answers, full_text, window:sg.Window): ''' Kicks off a subproces...
The selection event of the listView, returns a key of the clicked event. You can retrieve the item rapidly def list_view_on_selected(self, widget, selected_item_key): """ The selection event of the listView, returns a key of the clicked event. You can retrieve the item rapidly "...
============================================================= Demo of the histogram (hist) function with multiple data sets ============================================================= Plot histogram with multiple sample sets and demonstrate: * Use of legend with multiple sample sets * St...
========================================= Demo of artist customization in box plots ========================================= This example demonstrates how to use the various kwargs to fully customize box plots. The first figure demonstrates how to remove and add individual components (note that th...
========== Linestyles ========== This examples showcases different linestyles copying those of Tikz/PGF. def PyplotLineStyles(): """ ========== Linestyles ========== This examples showcases different linestyles copying those of Tikz/PGF. """ import numpy as np import matpl...
Converts size in characters to size in pixels :param size: size in characters, rows :return: size in pixels, pixels def convert_tkinter_size_to_Qt(size): """ Converts size in characters to size in pixels :param size: size in characters, rows :return: size in pixels, pixels """ qtsize ...
Convert from font string/tyuple into a Qt style sheet string :param font: "Arial 10 Bold" or ('Arial', 10, 'Bold) :return: style string that can be combined with other style strings def create_style_from_font(font): """ Convert from font string/tyuple into a Qt style sheet string :param font: "Aria...
Display popup with text entry field and browse button. Browse for folder :param message: :param default_path: :param no_window: :param size: :param button_color: :param background_color: :param text_color: :param icon: :param font: :param no_titlebar: :param grab_anywhere: ...
Display popup with text entry field and browse button. Browse for file :param message: :param default_path: :param default_extension: :param save_as: :param file_types: :param no_window: :param size: :param button_color: :param background_color: :param text_color: :param icon...
Display Popup with text entry field :param message: :param default_text: :param password_char: :param size: :param button_color: :param background_color: :param text_color: :param icon: :param font: :param no_titlebar: :param grab_anywhere: :param keep_on_top: :param ...
Reads the context menu :param timeout: Optional. Any value other than None indicates a non-blocking read :return: def Read(self, timeout=None): ''' Reads the context menu :param timeout: Optional. Any value other than None indicates a non-blocking read :return: ...
Shows a balloon above icon in system tray :param title: Title shown in balloon :param message: Message to be displayed :param filename: Optional icon filename :param data: Optional in-ram icon :param data_base64: Optional base64 icon :param time: How long to display mess...
Updates the menu, tooltip or icon :param menu: menu defintion :param tooltip: string representing tooltip :param filename: icon filename :param data: icon raw image :param data_base64: icon base 64 image :return: def Update(self, menu=None, tooltip=None,filename=None, ...
Change the window's transparency :param alpha: From 0 to 1 with 0 being completely transparent :return: def SetAlpha(self, alpha): ''' Change the window's transparency :param alpha: From 0 to 1 with 0 being completely transparent :return: ''' self._AlphaC...
Converts size in characters to size in pixels :param size: size in characters, rows :return: size in pixels, pixels def convert_tkinter_size_to_Wx(size): """ Converts size in characters to size in pixels :param size: size in characters, rows :return: size in pixels, pixels """ qtsize ...
Convert from font string/tyuple into a Qt style sheet string :param font: "Arial 10 Bold" or ('Arial', 10, 'Bold) :return: style string that can be combined with other style strings def font_to_wx_font(font): """ Convert from font string/tyuple into a Qt style sheet string :param font: "Arial 10 Bo...
Popup with colored button and 'Error' as button text :param args: :param button_color: :param background_color: :param text_color: :param auto_close: :param auto_close_duration: :param non_blocking: :param icon: :param line_width: :param font: :param no_titlebar: :param g...
Display popup with text entry field and browse button. Browse for folder :param message: :param default_path: :param no_window: :param size: :param button_color: :param background_color: :param text_color: :param icon: :param font: :param no_titlebar: :param grab_anywhere: ...
Display popup with text entry field and browse button. Browse for file :param message: :param default_path: :param default_extension: :param save_as: :param file_types: :param no_window: :param size: :param button_color: :param background_color: :param text_color: :param icon...
Reads the context menu :param timeout: Optional. Any value other than None indicates a non-blocking read :return: def Read(self, timeout=None): ''' Reads the context menu :param timeout: Optional. Any value other than None indicates a non-blocking read :return: ...
Shows a balloon above icon in system tray :param title: Title shown in balloon :param message: Message to be displayed :param filename: Optional icon filename :param data: Optional in-ram icon :param data_base64: Optional base64 icon :param time: How long to display mess...
Updates the menu, tooltip or icon :param menu: menu defintion :param tooltip: string representing tooltip :param filename: icon filename :param data: icon raw image :param data_base64: icon base 64 image :return: def Update(self, menu=None, tooltip=None,filename=None, ...
implement dragging def on_mouse(self, event): ''' implement dragging ''' # print('on_mouse') if not event.Dragging(): self._dragPos = None return # self.CaptureMouse() if not self._dragPos: self._dragPos = event.GetPosition() ...
Change the window's transparency :param alpha: From 0 to 1 with 0 being completely transparent :return: def SetAlpha(self, alpha): ''' Change the window's transparency :param alpha: From 0 to 1 with 0 being completely transparent :return: ''' self._AlphaC...
A worker thrread that communicates with the GUI These threads can call functions that block withouth affecting the GUI (a good thing) Note that this function is the code started as each thread. All threads are identical in this way :param thread_name: Text name used for displaying info :param run_freq:...
Starts and executes the GUI Reads data from a Queue and displays the data to the window Returns when the user exits / closes the window (that means it does NOT return until the user exits the window) :param gui_queue: Queue the GUI should read from :return: def the_gui(gui_queue): """ S...
Send one ping to the given >destIP<. def send_one_ping(mySocket, destIP, myID, mySeqNumber, packet_size): """ Send one ping to the given >destIP<. """ #destIP = socket.gethostbyname(destIP) # Header is type (8), code (8), checksum (16), id (16), sequence (16) # (packet_size - 8) - Remove hea...
Receive the ping from the socket. Timeout = in ms def receive_one_ping(mySocket, myID, timeout): """ Receive the ping from the socket. Timeout = in ms """ timeLeft = timeout/1000 while True: # Loop while waiting for packet or timeout startedSelect = default_timer() whatReady = sele...
run shell command @param cmd: command to execute @param timeout: timeout for command execution @param window: the PySimpleGUI window that the output is going to (needed to do refresh on) @return: (return code from command, command output) def runCommand(cmd, timeout=None, window=None): """ run shell command @...
Convert from font string/tyuple into a Qt style sheet string :param font: "Arial 10 Bold" or ('Arial', 10, 'Bold) :return: style string that can be combined with other style strings def font_parse_string(font): """ Convert from font string/tyuple into a Qt style sheet string :param font: "Arial 10 ...
Create and show a form on tbe caller's behalf. :param title: :param max_value: :param args: ANY number of arguments the caller wants to display :param orientation: :param bar_color: :param size: :param Style: :param StyleOffset: :return: ProgressBar object that is in the form def _P...
Update the progress meter for a form :param form: class ProgressBar :param value: int :return: True if not cancelled, OK....False if Error def _ProgressMeterUpdate(bar, value, text_elem, *args): ''' Update the progress meter for a form :param form: class ProgressBar :param value: int :r...
A ONE-LINE progress meter. Add to your code where ever you need a meter. No need for a second function call before your loop. You've got enough code to write! :param title: Title will be shown on the window :param current_value: Current count of your items :param max_value: Max value your count will eve...
Show Popup box and immediately return (does not block) :param args: :param button_type: :param button_color: :param background_color: :param text_color: :param auto_close: :param auto_close_duration: :param non_blocking: :param icon: :param line_width: :param font: :param...
Display popup with text entry field and browse button. Browse for folder :param message: :param default_path: :param no_window: :param size: :param button_color: :param background_color: :param text_color: :param icon: :param font: :param no_titlebar: :param grab_anywhere: ...
Display popup with text entry field and browse button. Browse for file :param message: :param default_path: :param default_extension: :param save_as: :param file_types: :param no_window: :param size: :param button_color: :param background_color: :param text_color: :param icon...
Display data in a table format def TableSimulation(): """ Display data in a table format """ sg.SetOptions(element_padding=(0,0)) menu_def = [['File', ['Open', 'Save', 'Exit']], ['Edit', ['Paste', ['Special', 'Normal',], 'Undo'],], ['Help', 'About...'],] columm...
Make and show a window (PySimpleGUI form) that takes user input and sends to the HowDoI web oracle Excellent example of 2 GUI concepts 1. Output Element that will show text in a scrolled window 2. Non-Window-Closing Buttons - These buttons will cause the form to return with the form's values, but do...
Kicks off a subprocess to send the 'Query' to HowDoI Prints the result, which in this program will route to a gooeyGUI window :param Query: text english question to ask the HowDoI web engine :return: nothing def QueryHowDoI(Query, num_answers, full_text): ''' Kicks off a subprocess to send the 'Que...
Exports a ModuleSpec with weights taken from a checkpoint. This is an helper to export modules directly from a ModuleSpec without having to create a session and set the variables to the intended values. Example usage: ```python spec = hub.create_module_spec(module_fn) spec.export("/path/t...
Returns the message attached to the module under the given key, or None. Module publishers can attach protocol messages to modules at creation time to provide module consumers with additional information, e.g., on module usage or provenance (see see hub.attach_message()). A typical use would be to stor...
Builds a list of training images from the file system. Analyzes the sub folders in the image directory, splits them into stable training, testing, and validation sets, and returns a data structure describing the lists of images for each label and their paths. Args: image_dir: String path to a folder conta...
Returns a path to an image for a label at the given index. Args: image_lists: OrderedDict of training images for each label. label_name: Label string we want to get an image for. index: Int offset of the image we want. This will be moduloed by the available number of images for the label, so it can b...
Returns a path to a bottleneck file for a label at the given index. Args: image_lists: OrderedDict of training images for each label. label_name: Label string we want to get an image for. index: Integer offset of the image we want. This will be moduloed by the available number of images for the label...
Creates a graph and loads Hub Module into it. Args: module_spec: the hub.ModuleSpec for the image module being used. Returns: graph: the tf.Graph that was created. bottleneck_tensor: the bottleneck values output by the module. resized_input_tensor: the input images, resized as expected by the modu...
Runs inference on an image to extract the 'bottleneck' summary layer. Args: sess: Current active TensorFlow Session. image_data: String of raw JPEG data. image_data_tensor: Input data layer in the graph. decoded_image_tensor: Output of initial image resizing and preprocessing. resized_input_tenso...
Create a single bottleneck file. def create_bottleneck_file(bottleneck_path, image_lists, label_name, index, image_dir, category, sess, jpeg_data_tensor, decoded_image_tensor, resized_input_tensor, bottleneck_tensor): """Create a single...
Retrieves or calculates bottleneck values for an image. If a cached version of the bottleneck data exists on-disk, return that, otherwise calculate the data and save it to disk for future use. Args: sess: The current active TensorFlow Session. image_lists: OrderedDict of training images for each label. ...
Ensures all the training, testing, and validation bottlenecks are cached. Because we're likely to read the same image multiple times (if there are no distortions applied during training) it can speed things up a lot if we calculate the bottleneck layer values once for each image during preprocessing, and then ...
Retrieves bottleneck values for cached images. If no distortions are being applied, this function can retrieve the cached bottleneck values directly from disk for images. It picks a random set of images from the specified category. Args: sess: Current TensorFlow Session. image_lists: OrderedDict of tr...
Retrieves bottleneck values for training images, after distortions. If we're training with distortions like crops, scales, or flips, we have to recalculate the full model for every image, and so we can't use cached bottleneck values. Instead we find random images for the requested category, run them through th...
Creates the operations to apply the specified distortions. During training it can help to improve the results if we run the images through simple distortions like crops, scales, and flips. These reflect the kind of variations we expect in the real world, and so can help train the model to cope with natural dat...
Attach a lot of summaries to a Tensor (for TensorBoard visualization). def variable_summaries(var): """Attach a lot of summaries to a Tensor (for TensorBoard visualization).""" with tf.name_scope('summaries'): mean = tf.reduce_mean(var) tf.summary.scalar('mean', mean) with tf.name_scope('stddev'): ...
Adds a new softmax and fully-connected layer for training and eval. We need to retrain the top layer to identify our new classes, so this function adds the right operations to the graph, along with some variables to hold the weights, and then sets up all the gradients for the backward pass. The set up for the...
Inserts the operations we need to evaluate the accuracy of our results. Args: result_tensor: The new final node that produces results. ground_truth_tensor: The node we feed ground truth data into. Returns: Tuple of (evaluation step, prediction). def add_evaluation_step(result_tensor, ground_truth...
Runs a final evaluation on an eval graph using the test data set. Args: train_session: Session for the train graph with the tensors below. module_spec: The hub.ModuleSpec for the image module being used. class_count: Number of classes image_lists: OrderedDict of training images for each label. jp...
Builds an restored eval session without train operations for exporting. Args: module_spec: The hub.ModuleSpec for the image module being used. class_count: Number of classes Returns: Eval session containing the restored eval graph. The bottleneck input, ground truth, eval step, and prediction tens...
Saves an graph to file, creating a valid quantized one if necessary. def save_graph_to_file(graph_file_name, module_spec, class_count): """Saves an graph to file, creating a valid quantized one if necessary.""" sess, _, _, _, _, _ = build_eval_session(module_spec, class_count) graph = sess.graph output_graph_...